Repository navigation
Close and replace every MongoDB client across a CRaC checkpoint, and route GORM calls to the connection a block opens - #16369
Conversation
MongoDatastore.stop() closed only the default connection's client, and start() replaced only that one, in the datastore's own field. The clients of the connections under grails.mongodb.connections, and of any added at runtime, stayed open through the checkpoint. Anything that read a client from its connection source rather than from the datastore went on using the one stop() had closed: SCHEMA multi-tenancy listing its tenants, MongoConnectionSources recording a connection added at runtime, and the Spring Data MongoDatabaseFactory, which kept the client it was created with. stop() now closes the client of every connection GORM created, and start() replaces each from the same settings. MongoConnectionSourceFactory creates a MongoConnectionSource, whose client can be replaced, so the replacement is handed out wherever the original was, and close() after a restore closes the replacements. The Spring Data factory asks the datastore for its client on every use. A datastore built from a MongoClientSettings.Builder builds its replacement default client with those options as well; it had been built from the configuration alone. Fixes apache#16366
The guide shows Book.withConnection('moreBooks') { Book.list() } and says
that everything in the closure uses the alternate connection. Only the
calls that did not name the class did: the closure's delegate is that
connection's static API, but Book.list(), a dynamic finder or
book.save() look their API up in the registry, which returned the
default connection's. A save meant for the named connection was written
to the default one.
GormRegistry.withConnectionScope routes an entity's unqualified static,
instance and validation API lookups to a connection while a closure
runs, and MongoEntity.withConnection runs its closure in one. A lookup
that names its connection, such as Book.moreBooks, is unaffected;
scopes nest, and are undone when the closure throws.
…ections A named connection's driver options are built with the default connection's Config as their fallback, and every value of it was passed on, the driver's own defaults included. Some of those are sentinels the builder's setters reject: eventLoopThreads() is 0 until set, and withEventLoopThreads(0) throws, so a datastore with any named connection failed to start. Only the values the default connection customized are inherited now.
Neo4jGormApiFactory built every static API without its qualifier, so Book.other reported the default connection. It read through the named connection's datastore, but the operations it hands to the instance API, save and delete among them, went to the default connection's instead: a write reached the default server, or failed with NoTransactionException inside the named connection's own transaction. The factory now passes the qualifier, resolver and registry through, as MongoDB's does.
Neo4jEntity.withConnection had the same gap as MongoDB's: only the calls that did not name the class used the named connection, and the guide told applications not to write Book.list() inside the block for that reason. It now runs its closure in GormRegistry.withConnectionScope, so static calls on the class and instance calls such as save() use the block's connection too. An operation that names its connection, such as Book.'default'.list(), keeps it.
The release notes gain an 8.0.x section for the two named-connection fixes, and the configuration guide says which driver options a named connection inherits: the ones the default connection sets.
…n or transaction opens
Book.moreBooks.withTransaction { } opens the moreBooks session and
transaction, but Book.list() and book.save() inside it resolved the
default connection's API. On MongoDB the save was written to the default
database, on Neo4j it went to the default server or failed with
NoTransactionException, and on Hibernate 5 and 7 it failed with
"No Session found for current thread".
withSession, withNewSession, withStatelessSession, withTransaction and
withNewTransaction on a named connection's API now run their closure in
GormRegistry.withConnectionScope for that connection, as withConnection
does. The default connection's API undoes an enclosing scope for its
block, so Book.'default'.withSession { } nested in one reaches the
default connection. A qualifier that names no connection, such as a
DISCRIMINATOR tenant id from withTenant, is left alone.
The refresh-lock specs relied on the old routing to reach the default
connection from inside a secondary block, and now name it.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## 8.0.x #16369 +/- ##
==================================================
+ Coverage 56.3406% 56.4363% +0.0957%
- Complexity 21863 22012 +149
==================================================
Files 2127 2130 +3
Lines 103460 103724 +264
Branches 18536 18606 +70
==================================================
+ Hits 58290 58538 +248
+ Misses 36887 36880 -7
- Partials 8283 8306 +23
🚀 New features to boost your workflow:
|
Review FindingsHead What I ran on the head, all green (build cache off,
The change is correct and I found nothing that blocks it. The design decision, that a session or transaction opened through [P3] The upgrade note says the old save always threw; in an application it usually did notReferences:
That is the standalone case. In a Grails web request the open-session-in-view interceptor keeps a default-connection session open, and in a service an outer Book.legacy.withTransaction {
Book.legacy.list().each { new Book(name: it.name).save() } // meant for the default database
}worked before and now writes back into [P3]
|
The scoped lookups went straight to the scope's connection API, ahead
of the multi-tenant resolution. For a scope on the default connection
and a DATABASE or SCHEMA mode entity that is not what Book.'default'
does: naming the default connection resolves the current tenant's API,
while the scope returned the default connection's own. Inside
Book.withConnection('default') { } the delegated list() and Book.list()
then read different stores.
A lookup that names no connection now takes the scope as its qualifier
and goes through the ordinary resolution, so a scope is what naming the
connection would be by construction. The javadoc says that for a
multi-tenant entity the scope's connection takes precedence over the
current tenant, as a named connection does, and that it belongs to the
calling thread.
Both withConnection pages say the routing applies on the calling thread and takes precedence over the current tenant for a multi-tenant class. The Neo4j release notes quote the two errors the named-connection fixes remove, so they can be searched for, and a MongoDatastore comment gets its missing word.
The upgrade note said a save inside a named connection's block used to throw. It did only with nothing else open: with a default-connection session further out, from open-session-in-view or an outer @transactional, it wrote to the default database silently, and a copy between connections written that way now writes back into the source. The guides say other domain classes are not affected, and that @transactional(connection = ...) opens the transaction without the routing. withSession and withStatelessSession on a named connection get tests of their own.
…ified-session-connection-scope # Conflicts: # grails-data-mongodb/docs/src/docs/asciidoc/multipleDataSources/mongoClientSwitching.adoc # grails-data-neo4j/docs/src/docs/asciidoc/multipleDataSources/boltDriverSwitching.adoc # grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/GormRegistry.groovy
|
@matrei thanks. Addressed in 2d8770e:
The branch also has #16368's review changes merged in (9e0312e). With a scope now resolving as the named connection does, the tweak this branch made so that |
…ction A method annotated @transactional(connection = 'books') opens the same transaction as Book.books.withTransaction { }, but book.save() inside it still went to the entity's default connection. The annotation names no class, so the routing covers every domain class mapped to the connection, and only those: GormRegistry gains a scope for every entity on a connection, which skips a class that has no mapping for it rather than send it somewhere it cannot be stored. The transform passes the annotation's connection to GrailsTransactionTemplate, whose execute and executeAndRollback run in that scope, and the TransactionService of a named connection's datastore does the same. The scopes are kept as a stack, so blocks for one class and for a whole connection nest in the order they were opened.
|
@matrei #16368 is closed, and this PR now carries all of it; the description covers everything. Your The transform passes the annotation's connection to Run on the six affected modules and the Hibernate 5 and 7 multi-datasource example apps: 7,458 tests, 0 failures. |
The configuration metadata said decimalType defaults to false, where the settings have it true, and named localhost as the host the driver connects to without configuration, where the settings take the driver's own 127.0.0.1, and with it the url. A spec now compares the metadata's defaults with the settings.
Review Findings, round 2Head What I ran on the head, all green (build cache off,
Every finding from the previous rounds is addressed the way the replies describe, the resolution change in [P3]
|
An index declared with a name that another index on different keys already holds is an IndexKeySpecsConflict, which the reconciliation did not handle: recreateOnConflict passed it by, and the build only reported the driver's message. The conflicting index is now found by the declared name, recreated where that is declared, and otherwise reported as the name being taken, by an error that says which name and what to do.
With MongoDB's properties present but no MongoClient bean, the auto-configuration built the client itself and handed it to the datastore as one the application supplied. GORM then left it alone for a checkpoint, which CRaC refuses while it holds its sockets, and the auto-configuration closed it on shutdown. A datastore can now be built around a Supplier<MongoClient>: it owns what the supplier builds, closes it for the checkpoint and builds the replacement the restore needs the same way. The client cannot be rebuilt from grails.mongodb settings, which is why the supplier rather than the configuration is what it keeps. The auto-configuration hands one over and no longer closes anything itself.
GormStaticApi.withNewSession(tenantId) opened a session on the tenant's datastore without binding the tenant, so the calls the closure made on the class were routed by whatever the tenant resolver reported: with another tenant current, they read that one's data through the session opened for this one. The tenant is now bound for the duration, as it is inside withTenant.
Inside Book.secondary.withConnection { }, a save of another class mapped
only to named connections went to secondary as well: with no connection
of its own named, the resolver picked the datastore that had a session
bound, which was the one the block opened. A class mapped to the default
connection was never affected, so which classes leaked depended on their
mappings.
The session a block opens belongs to the class the block names, so while
one is running the bound-session heuristic no longer applies to other
classes; each keeps the connection it is mapped to. Outside every block
the heuristic is unchanged, which is what routes the calls made inside a
session opened on the datastore itself.
|
Five more bugs fixed here, each in its own commit, rather than in follow-ups:
RxGORM's Run on the eight affected modules and the seven Hibernate 5 and 7 multi-datasource example apps: 7,490 tests, 0 failures. |
Only the connection source the factory creates can be given the client built for a restore. A custom factory's own kind cannot, so anything reading the client from it, rather than from the datastore, goes on using the one that was closed, silently. The restore now says which connection that is and what a factory should return, and the factory documents it.
Review Findings, round 3Head What I ran on the head, all green (build cache off,
And one thing that is not green, which CI found first. [P1]
|
…ction A transaction opened for a connection routed every class mapped to it, multi-tenant classes included, so inside @Rollback('moreBooks') a count resolved that tenant's data instead of asking the tenant resolver, and a spec that expects TenantNotFoundException with no tenant bound got a result. Which tenant an operation belongs to is what the tenant context says, and a transaction opened for a connection, or for a tenant's own schema or database, does not answer that. The scope for every class on a connection now passes over a multi-tenant class. Naming the connection on the class routes it as it always did, and the schema-per-tenant and database-per-tenant applications are back to throwing where they expect to.
|
The Hibernate 7 functional shards were failing on my
The scope for every class on a connection now passes over a multi-tenant class. Naming the connection on the class routes it as it always did, and Also here: 65b6851, which makes the one CRaC limitation audible. Only the Run for this: the eight affected modules and thirteen Hibernate 5 and 7 example applications, including schema-per-tenant and database-per-tenant on both: 7,521 tests, 0 failures, plus |
The transaction service took its datastore's connection name for every datastore, and for the root one that is the default connection, which the scope treats as an undo: a service injected anywhere, and every GraphQL fetch, reset the routing of the block it was called from. An unqualified @transactional in the same place does not, because the transform passes a connection only where the annotation names one. Only a named connection is passed now, so the root datastore's service behaves as that @transactional does, and the nested form is pinned by a test alongside the two that ran outside any block.
withNewSession(tenantId) bound the tenant through Tenants.withId, which in the modes that give a tenant its own connection opens a session for it, leaving the session this method then opens as the one the closure receives and the other one unused. The tenant is bound directly now, which is what the method needs.
The default-connection assertion ran outside every block, where the scope is skipped, so it asserted the plain count under another name; it now nests the block inside one for another connection, through the public form as well as the registry. The branch that leaves a qualifier which names no connection alone, a DISCRIMINATOR tenant id, had no test at all: a transaction and a session opened for one now assert that the calls inside stay with the current tenant.
…there Both guides promised that a method annotated @transactional with a connection routes the classes mapped to it, with no test on either: a service now saves and counts through one, against a container and against the second embedded server. "Mapped" is the connections a class declares. On MongoDB and Neo4j the child datastores share the parent's mapping context, so a class that declares none is still reachable through Book.moreBooks while the annotation leaves it alone, which the pages now say. Two sentences that still gave localhost as the host the driver connects to without configuration now give 127.0.0.1, as the metadata does.
|
@matrei round 2 arrived while I was pushing the five fixes and I only read it alongside round 3, so it went unanswered for a round. Both are addressed now. [P1] [P3] [P3] what "mapped" means — 44d95a6, also your first option. Both pages now say the class has to declare the connection in its Nit, two sessions in DATABASE mode — 9265c8e. Bound through Nit, the Nit, the "left alone" branch — 1103ddd, in Nit, the two The limitation line — it went from the description with fdd67c9; the description no longer lists it. You were right about the run. Mine covered seven multi-datasource applications and not the tenant ones, which is exactly where this broke. It is now the eight modules plus thirteen example applications, schema-per-tenant, database-per-tenant and partitioned included on both Hibernate versions. Run for these: 7,525 tests, 0 failures, plus |
This comment has been minimized.
This comment has been minimized.
matrei
left a comment
There was a problem hiding this comment.
Review Findings, round 4
Head 44d95a6427, base 8.0.x at 1fadd5c812; the branch still merges clean against the current 8.0.x (d4aa4effe0). This round covers the six commits since c82dd69b25: 65b6851931, 62c7b4a139, dd92b4502f, 9265c8e1b5, 1103ddd72c and 44d95a6427. CI on the head: 77 checks pass, 1 fails, and the failure is not this PR's (below).
What I ran on the head, all green (build cache off, cleanTest first, result XML timestamps from this run):
:grails-datamapping-core-test:testand:grails-datamapping-core:test, both whole modules: 627 + 1 082 tests, 0 failures.:grails-data-hibernate5-core:testand:grails-data-hibernate7-core:testforMultipleDataSourceConnectionsSpecand the refresh-lock specs: 110 + 109 tests, 0 failures.:grails-data-mongodb-core:testforMultipleConnectionsSpec, every*Tenan*spec,CheckpointRestoreConnectionsSpec,MongoDatastoreLifecycleSpec,MongoDatastoreExternalClientSpecandMongoConnectionSourceFactorySpec: 58 tests, 0 failures, against a real container.:grails-data-neo4j-core:test --tests NamedConnectionsSpec: 4 tests, 0 failures.:grails-test-examples-hibernate5-grails-schema-per-tenant:testand the Hibernate 7 twin, the two that failed onc82dd69b25: 2 + 2 tests, 0 failures.codeStyleongrails-datamapping-coreandgrails-data-mongodb-core: no violations.
Everything from rounds 2 and 3 is addressed, each the way I suggested or better, and I have nothing new to raise. From my side this is ready to merge once the end-to-end job is sorted out on 8.0.x.
The one red check is 8.0.x's, not this PR's
End to End Tests (end-to-end build only) fails in :taglib-index-incremental:test, all six features at TagLibraryIndexIncrementalSpec.groovy:158, which is assert status == 0 : "building the application failed". The captured build output in the uploaded report says why:
> Could not resolve all artifacts for configuration 'classpath'.
> Could not find org.apache.grails.gradle:grails-publish:1.0.0-RC1.
- file:/home/runner/work/grails-core/grails-core/build/local-maven/org/apache/grails/gradle/grails-publish/1.0.0-RC1/grails-publish-1.0.0-RC1.pom
buildscript of root project 'taglib-index-incremental-app' > ...grails-gsp.gradle.plugin:8.0.0-SNAPSHOT > grails-gradle-plugins:8.0.0-SNAPSHOT > grails-gradle-bom:8.0.0-SNAPSHOT
The sample application's buildscript asks for grails-publish:1.0.0-RC1, which is d4aa4effe0 ("bump publish plugin to 1.0.0-RC1"), merged to 8.0.x after this PR's base and pulled in through the PR's merge ref; the local Maven repository the job publishes to does not have that version. The same workflow passed on the four 8.0.x commits before d4aa4effe0, and d4aa4effe0's own run was cancelled, so it has never been seen green. Nothing in this PR touches the tag-library index, the publish plugin or the end-to-end build.
Confirmed
62c7b4a139(the round-3 P1):isMappedToConnectionnow returns false for a multi-tenant entity, looked up through the entity's default datastore's mapping context, so a connection-wide scope never covers one; the class-levelinConnectionScopeis untouched, soBook.moreBooks.withTransaction { }still routes as documented. Both schema-per-tenant examples pass again unchanged,ConnectionScopeMultiTenancySpecpins@Transactional('bar') { ScopedTenantBook.count() }to the current tenant withScopedTenantBook.bar.count()still reachingbar, and the guide, both Hibernate guides, section 72 and theTransactional.connection()javadoc all say a multi-tenant class is left to its tenant.dd92b4502f(round-2 P3):newTemplatesets the template's connection only when it is notDEFAULT, and the newMultipleDataSourceSpecfeature checks the nested case,Player.one.withTransaction { rootTransactionService.withTransaction { Player.count() } } == 2, next to the two outside-any-block cases.9265c8e1b5(round-3 nit):withNewSession(tenantId)binds throughCurrentTenantHolder.withTenant(defaultDatastore, tenantId, inNewSession), which callscallable.call(tenantId), so the closure's newSerializableparameter is right, and only the one session the static API opens is opened.1103ddd72c(the two test nits): thedefault-scope assertion is now nested inside abarblock, in both the public form and the registry form, andPartitionMultiTenancySpeccovers the "left alone" branch withBook.withTenant('901').withTransaction { Book.count() }and.withNewSession { }reading the current tenant whileBook.withTenant('901').count()reads901, which is the DISCRIMINATOR probe from round 2 made into a test.44d95a6427(round-2 P3): the MongoDB and Neo4jwithConnectionpages now say "every domain class that declaresmoreBooksin itsconnectionsmapping,ALLincluded", and that an undeclared class "is reachable throughBook.moreBooksbut is not routed by the annotation"; the upgrade notes say "for a class that declares that connection".ScopedCompanyServicein the MongoDBMultipleConnectionsSpecandRoutedCompanyServicein the Neo4jNamedConnectionsSpecsave and count through@Transactional(connection = ...)on both implementations.testing.adocand the MongoDB upgrade note now say127.0.0.1.65b6851931: a restore that meets a connection source that is not aMongoConnectionSourcelogs a warning naming the connection, the class it found and the class to return instead,MongoDatastoreLifecycleSpecasserts one per connection throughCapturedLog, and the factory'screatejavadoc tells a subclass what to return. The PR description's "Limitations" still lists the Boot-built client case thatfdd67c9244removed; only that line is stale now.
Verification
./gradlew --no-build-cache --continue :grails-datamapping-core-test:cleanTest :grails-datamapping-core-test:test :grails-datamapping-core:cleanTest :grails-datamapping-core:test :grails-data-hibernate5-core:cleanTest :grails-data-hibernate5-core:test --tests MultipleDataSourceConnectionsSpec --tests Hibernate5RefreshLockSpec :grails-data-hibernate7-core:cleanTest :grails-data-hibernate7-core:test --tests MultipleDataSourceConnectionsSpec --tests Hibernate7RefreshLockSpec :grails-data-mongodb-core:cleanTest :grails-data-mongodb-core:test --tests MultipleConnectionsSpec --tests '*Tenan*' --tests CheckpointRestoreConnectionsSpec --tests MongoDatastoreLifecycleSpec --tests MongoDatastoreExternalClientSpec --tests MongoConnectionSourceFactorySpec :grails-data-neo4j-core:cleanTest :grails-data-neo4j-core:test --tests NamedConnectionsSpec :grails-test-examples-hibernate7-grails-schema-per-tenant:cleanTest :grails-test-examples-hibernate7-grails-schema-per-tenant:test :grails-test-examples-hibernate5-grails-schema-per-tenant:cleanTest :grails-test-examples-hibernate5-grails-schema-per-tenant:test :grails-datamapping-core:codeStyle :grails-data-mongodb-core:codeStyleon44d95a6427: BUILD SUCCESSFUL; 627 + 1 082 + 110 + 109 + 58 + 4 + 2 + 2 tests, 0 failures, 0 errors; result XML written 07:01-07:06 today.- CI job
106887398381(End to End Tests): steps show only🧪 Run the end-to-end testsfailed; theend-to-end-test-reportsartifact'sTagLibraryIndexIncrementalSpecpages carry the resolution failure quoted above.gh api .../workflows/<id>/runs?branch=8.0.x:848d29e0ce,de903ae36a,bb372c3603,73e7a31bf7success with the End to End job passing on each;d4aa4effe0cancelled. - The worktree is back on the original branch with no tracked changes.
Section 72 says the calls on a class inside a named connection's session or transaction now use that connection, but not what that leaves for a method annotated @transactional without a connection and called from inside one. Its transaction is the default connection's while its calls on the class still follow the block, so the writes join the transaction the block opened rather than the one the method began, and a REQUIRES_NEW transaction covers none of them. Verified on an H2-backed Hibernate 7 datastore with a ProbeScribe mapped ALL: inside ProbeScribe.books.withTransaction the row written by a REQUIRES_NEW method that then throws survives in books, where the same call outside any block discards it.
MongoConnectionSource shadows DefaultConnectionSource's source with the client it hands out, and its close() closed that client whatever closeable said. Only the three-argument constructor was reachable, so closeable was always true and ownsClient() agreed with it; but MongoConnectionSourceFactory.create now documents this type as what a factory should return, and one that wraps a client the application supplied would have had it closed. close() leaves a client it does not own open, and a four-argument constructor says so. A replacement is still handed out either way, so a factory's own client stays replaceable across a restore.
jdaugherty
left a comment
There was a problem hiding this comment.
I've gone ahead and fixed the 2 issues I've pointed out below.
| `withConnection`, and the example above reads and saves through `secondary`. Other domain classes are not | ||
| affected, and an operation that names a connection keeps it. The same holds inside a method annotated | ||
| `@Transactional(connection = 'secondary')`, for every domain class mapped to `secondary`; a class that is not | ||
| mapped to it keeps its own connection, and a multi-tenant class is left to its tenant, as it was before. Code that relied on the old routing changes |
There was a problem hiding this comment.
An unqualified @Transactional method called from inside one of these blocks is worth a sentence here. It opens a transaction on the default transaction manager, but the calls it makes on a domain class still follow the enclosing block, so the writes land in the outer transaction rather than in the one the method just began.
That is the deliberate choice, since the transform passes a connection only when the annotation names one, and the routing half is already pinned (Player.one.withTransaction { plainService.countPlayers() } reads one). The consequence does not appear here, on the multiple-datasources page, or in the MongoDB and Neo4j notes: with propagation = REQUIRES_NEW the independent commit the method asked for no longer covers the write at all.
| } | ||
|
|
||
| @Override | ||
| void close() throws IOException { |
There was a problem hiding this comment.
close() closes the client whatever closeable says, and the class shadows DefaultConnectionSource.source with its own client field while inheriting isCloseable(), which is always true because only the three-argument super constructor is reachable.
That is consistent today: createDefaultConnectionSources builds one only on the closeable branch, and ownsClient() gets the right answer for it. But the new javadoc on MongoConnectionSourceFactory.create invites a custom factory to return this type, and one that wraps a client the application supplied would have it closed here. A closeable guard (if (!closeable) { closed = true; return }) and a four-argument constructor would keep the inherited contract.
|
@matrei @sbglasius if you can re-approve, I'll merge and get the RC1 released. |
matrei
left a comment
There was a problem hiding this comment.
Review Findings, round 5
Head 81b5b189df, base 8.0.x at 1fadd5c812; the branch still merges clean against the current 8.0.x (96e0e72f68). This round covers the two commits since 44d95a6427, both from @jdaugherty's review comments: d82c24e611 (section 72 says what a plain @Transactional inside a connection block covers) and 81b5b189df (MongoConnectionSource honours closeable). CI on the head is still running (20 passed, 51 pending, none failed).
What I ran on the head, all green (build cache off, cleanTest first, result XML timestamps from this run):
:grails-data-mongodb-core:testforMongoConnectionSourceSpec,MongoDatastoreLifecycleSpec,MongoDatastoreExternalClientSpec,CheckpointRestoreConnectionsSpecandMongoConnectionSourceFactorySpec: 27 tests, 0 failures, against a real container.:grails-data-mongodb-core:codeStyle: no violations.- A throwaway Hibernate 7 spec, H2-backed, checking the new upgrade-note paragraph: a
@Transactional(propagation = REQUIRES_NEW)service method that saves anALL-mapped class and then throws discards the row when called outside any block, and leaves it committed inbookswhen called insideProbeScribe.books.withTransaction { }; a plain@Transactionalmethod inside the same block writes tobookstoo. 3 tests, 0 failures. Not part of the PR, removed afterwards.
Both changes do what the comments asked, and I still approve. Two nits, neither blocking.
Nits
grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/connections/MongoConnectionSource.groovy:55-57: the four-argument constructor's javadoc says "The client is still replaceable, so a datastore that reads it from here after a restore gets the one in use". The datastore never replaces a client it does not own:stop()closes only the datastores whose default connection source reportscloseable, so withcloseable = falsenothing is closed,clientStoppedstays false, andstart()skips it (MongoDatastore.java:1843,1989-1991), exactly as thestop()javadoc says for a supplied client.replaceSourceis still there for whoever owns the client to use. Suggest "The client is still replaceable throughreplaceSource, but a datastore leaves a client it does not own alone across a checkpoint and restore, andcloseable = falseleaves closing it to whoever created it."- The review comment named three places for the
REQUIRES_NEWconsequence: section 72, the multiple-datasources page, and the MongoDB and Neo4j notes. Only section 72 got it. That is the right home for a behaviour change, but a reader of the guide who never reads the upgrade guide will not see it, and the sentence atgrails-doc/src/en/guide/conf/dataSource/multipleDatasources.adoc:212(and its twin in both Hibernate guides'dataSourceNamespaces.adoc:57) is where the connection routing of@Transactional(connection = ...)is explained. The MongoDB and Neo4j notes can stay as they are:springDataInterop.adoc:69already saysREQUIRES_NEWis not supported by GORM's transaction manager there, so the consequence has nowhere to bite.
Confirmed
81b5b189df:close()now returns after marking the source closed whencloseableis false, mirroringDefaultConnectionSource.close(); the three-argument constructor delegates withtrue, so the factory'screateandcreateDefaultConnectionSourcesare unchanged in behaviour, andownsClient()readsisCloseable()from the same field. The datastore's ownclose()builds itsinUselist from owning datastores only, so a non-owned client is closed neither by the connection sources nor by that loop. The three newMongoConnectionSourceSpecfeatures cover the constructor,close()with a non-owned client, and a replacement on a non-owned source being handed out and not closed.d82c24e611: the paragraph matches what runs. The transform passes a connection only when the annotation names one, so a plain@Transactionalopens its transaction on the default manager and leaves the enclosing scope in place; the class's calls inside it follow the block, join the block's session and transaction, and aREQUIRES_NEWtransaction on the default manager suspends only the default resources. The probe above pinned all three cases.
Verification
./gradlew --no-build-cache --continue :grails-data-mongodb-core:cleanTest :grails-data-mongodb-core:test --tests MongoConnectionSourceSpec --tests MongoDatastoreLifecycleSpec --tests MongoDatastoreExternalClientSpec --tests CheckpointRestoreConnectionsSpec --tests MongoConnectionSourceFactorySpec :grails-data-mongodb-core:codeStyleon81b5b189df: BUILD SUCCESSFUL; 27 tests, 0 failures, 0 errors; result XML written 17:39 today../gradlew --no-build-cache :grails-data-hibernate7-core:cleanTest :grails-data-hibernate7-core:test --tests RequiresNewProbeSpecwith the throwaway spec: BUILD SUCCESSFUL; 3 tests, 0 failures; result XML written 17:41 today.git merge-treeof the head againstorigin/8.0.x(96e0e72f68): no conflicts.- The worktree is back on the original branch with no tracked changes; the probe spec is deleted.
Fixes #16366.
MongoDatastoretakes part in the Spring lifecycle so an application can be checkpointed with CRaC and restored (#16095). Until now only the default connection'sMongoClientwas covered. This makes checkpoint and restore cover every client GORM creates. The later commits fix the named-connection bugs found along the way:withConnectionrouting in MongoDB and Neo4j, Neo4j named connections, which could not start, and the class's own calls inside a named connection's session or transaction, in every GORM implementation.Checkpoint and restore cover every connection
stop()closes the client of the default connection, of each connection undergrails.mongodb.connections, and of any added at runtime.start()builds a replacement for each from the same settings.MongoConnectionSourceFactorynow creates aMongoConnectionSource, aDefaultConnectionSourcewhose client can be replaced. Code that reads the client from the datastore's connection sources gets the new one. This fixes SCHEMA multi-tenancy, whereeachTenantlisted databases through the closed client, andMongoConnectionSources, which recorded a connection added after a restore through the closed client.close()after a restore closes the replacements, on every connection.MongoDatabaseFactoryasks the datastore for its client on every use, soMongoTemplateand repositories keep working after a restore.MongoClientSettings.Builderbuilds its replacement default client with those options. Before, the replacement was built from the configuration alone and lost them.The guide gains a "Checkpoint and Restore (CRaC)" section under Advanced Configuration, plus a release-notes entry and a line on the Spring Data interop page.
withConnectionroutes the class's own callsThe guide shows
Book.withConnection('moreBooks') { Book.list() }, but only the calls made without naming the class, such aslist(), used the named connection.Book.list(), dynamic finders,wherequeries andbook.save()went to the default connection, so a save inside the block was written to the wrong database. They now use the block's connection:An operation that names its own connection, such as
Book.moreBooks.count(), keeps it, and the default connection applies again after the block, including when it throws. The routing lives inGormRegistry.withConnectionScope, whichMongoEntity.withConnectionandNeo4jEntity.withConnectionuse. Both guides' pages forwithConnectionnow say exactly what the block covers. The Neo4j guide had documented the old behaviour ("should not be prefixed withBook."), so its upgrade notes cover the change.Neo4j named connections work
Config, and every value was copied, the driver's own defaults included.eventLoopThreads()is0until set, andwithEventLoopThreads(0)throws, so any datastore with a connection undergrails.neo4j.connectionsfailed to start. Only options the default connection customizes are inherited now.Neo4jGormApiFactorybuilt static APIs without their qualifier, soBook.moreBooks.save(book)handed the save to the default connection's instance API: it reached the default server, or failed withNoTransactionExceptioninsideBook.moreBooks.withTransaction { }. The factory now passes the qualifier through, as MongoDB's does.Calls inside a named connection's session or transaction use it
Book.moreBooks.withTransaction { }opens themoreBookssession and transaction, but the calls onBookinside it used the default connection:book.save()insideBook.moreBooks.withTransaction { }NoTransactionExceptionHibernateException: No Session found for current threadThey now use the connection the block opened:
withSession,withNewSession,withStatelessSession,withTransactionandwithNewTransactionon a named connection's API run their closure in the same connection scopewithConnectionuses. An operation inside the block that names a connection keeps it, and a qualifier that is not a connection name, such as a DISCRIMINATOR tenant id fromwithTenant, is left alone.A method annotated
@Transactional(connection = 'books')opens the same transaction, and now routes the same way. The annotation names no class, so it covers every domain class mapped to that connection, and only those; a class with no mapping for it keeps its own connection rather than being sent somewhere it cannot be stored. TheTransactionServiceof a named connection's datastore does the same.This changes behaviour for code that reached the default connection from inside such a block by calling the class directly. The refresh-lock specs in both Hibernate modules did, and now name the default connection instead:
A session or transaction opened through the default connection's API undoes the enclosing block for its duration, so the calls on the class inside it reach the default connection again.
The Grails guide's multiple datasources section and the Hibernate 5, Hibernate 7, MongoDB and Neo4j guides describe it. The Grails 8 upgrade guide (section 72), the MongoDB and Neo4j upgrade notes, and the MongoDB and Neo4j release notes cover the change.
Other bugs fixed along the way
MongoClientbean, the auto-configuration builds the client itself and used to hand it to GORM as if the application had supplied it, so a checkpoint kept its sockets. A datastore can now be built around aSupplier<MongoClient>, owning what the supplier builds, and the auto-configuration hands one over.recreateOnConflictignored a taken index name. An index declared with a name another index on different keys already holds is anIndexKeySpecsConflict, which the reconciliation did not handle. It is now recreated where that is declared, and otherwise reported as the name being taken, rather than as the driver's message.grails.mongodb.decimalTypeshowedfalsewhere the settings havetrue, and the host and url showedlocalhostwhere the driver's own127.0.0.1applies. A spec now compares the metadata with the settings.withNewSession(tenantId)on a static API routed the calls inside by whatever the tenant resolver reported, so with another tenant current they read that one's data through the session opened for this one.Book.secondary.withConnection { }, a save of a class mapped only to named connections went tosecondarytoo, because the resolver picked the datastore whose session the block had opened. Each class now keeps the connection it is mapped to; outside a block the behaviour is unchanged.Limitations
MongoConnectionSourceFactorywhosecreatereturns a plainDefaultConnectionSourcehas its clients closed and replaced in the datastore, but that connection source keeps handing out the closed one: only theMongoConnectionSourcethe stock factory creates can be given the replacement. The restore now warns, naming the connection and what a factory should return, and the factory documents it.MongoClientthat application code obtained before the checkpoint is closed; code keeping one has to obtain it again after the restore. A checkpoint cannot proceed while a client holds its sockets, so this is inherent.