borinquenkid commented on code in PR #15779: URL: https://github.com/apache/grails-core/pull/15779#discussion_r3565727674
########## grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/core/ThreadLocalSessionResolver.groovy: ########## @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.grails.datastore.mapping.core + +import groovy.transform.CompileStatic + +/** + * A default thread-bound SessionResolver + * + * @author borinquenkid + * @since 8.0 + */ +@CompileStatic +class ThreadLocalSessionResolver<S extends Session> implements SessionResolver<S> { + + private final ThreadLocal<S> currentSession = new ThreadLocal<>() + private final ThreadLocal<Map<String, S>> qualifiedSessions = ThreadLocal.<Map<String, S>> withInitial { new HashMap<String, S>() } + + @Override + S resolve() { + return currentSession.get() + } + + @Override + S resolve(String qualifier) { + return qualifiedSessions.get().get(qualifier) + } + + @Override + void bind(S session) { + currentSession.set(session) + // Note: In a production scenario, we'd need to link the session's datastore qualifier here. Review Comment: Replied on the current-line thread you split this into — see the comment on `ThreadLocalSessionResolver.groovy` re: `bind()`/`unbind()`. Fixed in 48c9c49a34. ########## grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/core/AbstractDatastore.java: ########## @@ -122,6 +174,36 @@ public void destroy() { public void setApplicationContext(ApplicationContext ctx) { applicationContext = ctx; + if (ctx instanceof ApplicationEventPublisher) { + this.applicationEventPublisher = (ApplicationEventPublisher) ctx; + } + else if (ctx == null && !(this.applicationEventPublisher instanceof DefaultApplicationEventPublisher)) { + this.applicationEventPublisher = new DefaultApplicationEventPublisher(); + } + } + + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { + this.applicationEventPublisher = applicationEventPublisher; + } + + /** + * Adds an application listener to the datastore + * @param listener The listener + */ + public void addApplicationListener(ApplicationListener<?> listener) { + if (applicationEventPublisher instanceof ConfigurableApplicationContext) { + ((ConfigurableApplicationContext) applicationEventPublisher).addApplicationListener(listener); + } else if (applicationEventPublisher instanceof DefaultApplicationEventPublisher) { + ((DefaultApplicationEventPublisher) applicationEventPublisher).addApplicationListener(listener); + } + else { + try { + Method method = applicationEventPublisher.getClass().getMethod("addApplicationListener", ApplicationListener.class); Review Comment: Replied on the current-line thread you split this into — see the comment on `AbstractDatastore.java` line 218 re: the silent-drop path. Fixed in 48c9c49a34. ########## grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/core/ThreadLocalSessionResolver.groovy: ########## @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.grails.datastore.mapping.core + +import groovy.transform.CompileStatic + +import org.springframework.transaction.support.TransactionSynchronizationManager + +import org.grails.datastore.mapping.transactions.SessionHolder + +/** + * The default {@link SessionResolver}, backed by the same {@link SessionHolder}/ + * {@link TransactionSynchronizationManager} state as {@link DatastoreUtils}'s session binding - + * a thin, stateless view over the one authoritative session stack for its owning datastore, rather + * than an independent thread-local store that could disagree with it. Nested bindings are supported + * because {@link SessionHolder} itself is a stack: {@link #bind(Session)} pushes, {@link #resolve()} + * returns the top, and {@link #unbind()} clears the whole binding for the current thread. + * + * @author borinquenkid + * @since 8.0 + */ +@CompileStatic +class ThreadLocalSessionResolver<S extends Session> implements SessionResolver<S> { + + private final Datastore datastore + + ThreadLocalSessionResolver(Datastore datastore) { + this.datastore = datastore + } + + @Override + S resolve() { + SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(datastore) + return holder != null ? (S) holder.getSession() : null + } + + @Override + void bind(S session) { + DatastoreUtils.bindNewSession(session) + } + + @Override + void unbind() { + TransactionSynchronizationManager.unbindResourceIfPossible(datastore) Review Comment: Fixed in 48c9c49a34. `unbind()` no longer calls `unbindResourceIfPossible()` unconditionally — it now pops and closes only the top session: ```groovy void unbind() { SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(datastore) if (holder == null) { return } Session session = holder.getSession() if (session != null) { holder.removeSession(session) } if (holder.isEmpty()) { TransactionSynchronizationManager.unbindResourceIfPossible(datastore) } if (session != null) { DatastoreUtils.closeSessionOrRegisterDeferredClose(session, datastore) } } ``` Same `removeSession()`/`isEmpty()`/`closeSessionOrRegisterDeferredClose()` sequence `DatastoreUtils.executeWithNewSession` already used, so it's consistent with the rest of the session-binding code rather than a new pattern. The nested test now asserts restoration instead of the destructive behavior: ```groovy when: resolver.bind(first) resolver.bind(second) then: "resolve() returns the most recently bound (top-of-stack) session" resolver.resolve() == second when: resolver.unbind() then: "unbind() closes and pops only the top session, restoring the outer binding" 1 * second.disconnect() 0 * first.disconnect() resolver.resolve() == first when: resolver.unbind() then: "unbinding the last remaining session closes it and clears the binding entirely" 1 * first.disconnect() resolver.resolve() == null ``` `bind(A); bind(B); unbind()` now leaves `resolve() == A`, with only B closed — verified this actually passes locally, not just trusting the commit message. ########## grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/core/AbstractDatastore.java: ########## @@ -171,7 +276,7 @@ public Session getCurrentSession() throws ConnectionNotFoundException { } public boolean hasCurrentSession() { - return TransactionSynchronizationManager.hasResource(this); + return sessionResolver.resolve() != null; Review Comment: Fixed in 48c9c49a34. `sessionResolver` is now `final`, set once in the constructor to `new ThreadLocalSessionResolver<>(this)` — the alternate-resolver contract/setter you flagged (`setSessionResolver()`) is gone entirely; confirmed zero remaining references to it anywhere in the repo. `ThreadLocalSessionResolver` no longer maintains independent state — its `resolve()` reads the exact same `TransactionSynchronizationManager.getResource(datastore)`/`SessionHolder` state that `DatastoreUtils.doGetSession()` (which `getCurrentSession()` delegates to) also reads. So `hasCurrentSession()` and `getCurrentSession()` are now guaranteed to agree — there's no longer a second source of truth for either of them, or for `DatastoreUtils.execute()`'s branch, to disagree over. ########## grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/core/AbstractDatastore.java: ########## @@ -122,6 +189,44 @@ public void destroy() { public void setApplicationContext(ApplicationContext ctx) { applicationContext = ctx; + if (ctx instanceof ApplicationEventPublisher) { + this.applicationEventPublisher = (ApplicationEventPublisher) ctx; + } + else if (ctx == null && !applicationEventPublisherExplicitlySet) { + this.applicationEventPublisher = new MulticasterApplicationEventPublisher(); + } + } + + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { + this.applicationEventPublisher = applicationEventPublisher; + this.applicationEventPublisherExplicitlySet = true; + } + + /** + * Adds an application listener to the datastore. Registers against {@link #getApplicationEventPublisher()} + * rather than the raw field, so the listener reaches whatever publisher this datastore (or a subclass + * overriding {@link #getApplicationEventPublisher()} with its own field) actually publishes events through. + * + * @param listener The listener + */ + public void addApplicationListener(ApplicationListener<?> listener) { + ApplicationEventPublisher publisher = getApplicationEventPublisher(); + if (publisher instanceof ConfigurableApplicationContext) { + ((ConfigurableApplicationContext) publisher).addApplicationListener(listener); + } + else if (publisher instanceof MulticasterApplicationEventPublisher) { + ((MulticasterApplicationEventPublisher) publisher).addApplicationListener(listener); + } + else if (publisher != null) { Review Comment: Fixed in 48c9c49a34, along the second option you suggested (narrow what can silently succeed, rather than retain-and-delegate): the reflective fallback now throws `IllegalStateException` instead of logging and swallowing when the publisher exposes no `addApplicationListener(ApplicationListener)` method, so a caller can no longer register a listener that will never fire without finding out immediately. ```java else if (publisher != null) { try { Method method = publisher.getClass().getMethod("addApplicationListener", ApplicationListener.class); method.invoke(publisher, listener); } catch (Exception e) { throw new IllegalStateException("Could not register application listener [" + listener + "] with publisher [" + publisher + "]: it does not expose an addApplicationListener(ApplicationListener) method", e); } } ``` The test was rewritten to match — it no longer accepts the drop with `noExceptionThrown()`; it now asserts the throw: ```groovy void "addApplicationListener fails loudly rather than silently dropping the listener when the publisher exposes no addApplicationListener method"() { ... when: datastore.addApplicationListener(listener) then: "the caller finds out immediately that the listener will never receive events, instead of it being silently dropped" thrown(IllegalStateException) } ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
