Skip to content

refactor: extract datasource unwrapping into an ordered SPI - #804

Closed
Pika-Yalei wants to merge 2 commits into
baomidou:devfrom
Pika-Yalei:feat/datasource-unwrapper-spi
Closed

Pika-Yalei wants to merge 2 commits into
baomidou:devfrom
Pika-Yalei:feat/datasource-unwrapper-spi

Conversation

@Pika-Yalei

@Pika-Yalei Pika-Yalei commented Oct 15, 2026 •

Copy link
Copy Markdown

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style (formatting, no behaviour change)
  • Refactor
  • Build / CI
  • Doc
  • Other

Description

Fixes #792.

DynamicRoutingDataSource.closeDataSource currently owns optional P6Spy and Seata proxy knowledge. Extract that knowledge into a DataSourceUnwrapper SPI and an ordered chain so another proxy integration can register a Java service provider without editing the routing datasource.

  • Discover extensions through META-INF/services/com.baomidou.dynamic.datasource.unwrapper.DataSourceUnwrapper and order them through Ordered
  • Move P6Spy and Seata unwrapping into optional-aware built-in implementations
  • Keep the existing integration opt-in flags and ItemDataSource real-pool shortcut
  • Preserve one-layer behavior for nested proxies, immediate/graceful destruction, and per-datasource failure logging
  • Add SPI contract tests and shared real-pool lifecycle regressions for Boot 2/3/4
  • Cache the chain lazily per routing datasource and invalidate it when integration flags change
  • Document and test an explicit TCCL-first Spring classloader policy with null-TCCL fallback
  • Add narrow conditional Hikari reflection registrations for native graceful destruction

The chain deliberately stops at the first successfully unwrapped target rather than recursively stripping proxies, preserving existing lifecycle behavior. Endpoint reporting can reuse the SPI separately; this PR does not change the endpoint.

Impact on the core contracts

  • @DS resolution / DynamicDataSourceContextHolder switching and stack semantics
  • Datasource creation and connection-pool parameters
  • Transaction semantics (@DSTransactional, savepoints, XA/Atomikos, Seata)
  • Grouping and load balancing
  • ENC(...) encryption / configuration properties
  • Published artifacts (module layout, POM scopes, JDK baseline)
  • None of the listed contracts change

This is a datasource destruction refactor. It does not change datasource creation, transaction behavior, routing, configuration names, or production dependency scopes. Existing P6Spy/Seata dependencies are reused in test scope only. The new core bytecode was verified as class-file major version 52 (Java 8).

Checklist

  • Fresh clean test build under JDK 17, with Boot 2/library compilation and tests using JDK 8 toolchains
  • All modules and three starter test suites build successfully
  • Regression tests added
  • New Java files include the project Apache 2.0 license header
  • No new third-party libraries introduced
  • Boot 3 and Boot 4 nativeTest passed locally; existing native skips disclosed below
  • Conventional commit message, one logical change

Validation and remaining checks

The review follow-up was tested on the exact tree published as b160b12451f3292fb46e59721fbb453ff35764ec.

A fresh clean test build under JDK 17, with Java 8/17 module toolchains and the build cache disabled, passed 241 tests with zero failures, errors, or skips:

  • creator: 35
  • spring: 100
  • Boot 2 starter: 34
  • Boot 3 starter: 38
  • Boot 4 starter: 34

Both native test tasks passed with the CI-specified GraalVM Community 25.3.4.1:

  • Boot 3 nativeTest: 38 discovered, 33 executed and passed, 5 existing SpEL-related native skips
  • Boot 4 nativeTest: 34 discovered, 33 executed and passed, 1 existing SpEL-related native skip
  • Combined: 66 native tests executed and passed, zero failures/errors. No new skips were added, and no lifecycle regression test is skipped

The original published head reproduced a real native issue: image construction succeeded and immediate custom-SPI lifecycle tests passed, but four newly added graceful remove/replace cases failed because HikariDataSourceActiveDetector lacked reflection invocation metadata. The follow-up adds only conditional registrations for HikariDataSource.getHikariPoolMXBean() and HikariPool.getActiveConnections() in the shared native metadata module. Both affected native suites now pass. Standard ServiceLoader discovery is retained; no unsupported services metadata section was added.

The PR adds 45 regression cases: 15 SPI contract/lifecycle/classloader cases and 10 shared real-pool lifecycle cases on each starter line. Follow-up coverage verifies lazy chain reuse, changed/unchanged integration flags, null-TCCL fallback and child-only service-descriptor discovery. The chain uses an explicit TCCL-first Spring classloader policy, preserving application-provider visibility. Core SPI bytecode remains class-file major version 52 (Java 8).

The isolated environment used external validation-only init scripts for explicit Mockito startup-agent instrumentation and conservative worker/JVM limits. Native compilation used a 4 GiB heap and two compiler threads. No repository build settings or test exclusions were changed for those environment constraints.

Local verification does not replace the complete hosted JDK 17/21/25/27 matrix. On this exact head, GitHub CI and CodeQL are awaiting maintainer workflow approval (action_required), rather than reporting test failures.

Implementation and test preparation were AI-assisted, followed by independent code review and the local validation above. This PR is open and ready for review; merge remains subject to maintainer review and required hosted checks.

@github-actions github-actions Bot added core dynamic-datasource core modules tests Test suites and fixtures labels Oct 15, 2026
@huayanYu

Copy link
Copy Markdown
Member

Thanks — the direction here is right, and the equivalence work looks solid. I traced the old closeDataSource against the new chain and could not find a behavioural gap: order 0/1 reproduces the previous "seata then p6spy" precedence, one-layer-only unwrapping matches the original pair of independent ifs (both stripped from the original object), a null target still falls back to the input, exceptions still surface into the same catch, and the ItemDataSource shortcut / graceDestroy / per-datasource failure isolation are preserved. The fixtures are genuinely load-bearing too — LifecycleProxyDataSource has no close() and no JDBC unwrap, so without the SPI those cases fail instead of passing silently.

Before this lands, though, I think there is one blocker and a few things worth tightening.

1. This introduces the first runtime ServiceLoader in the codebase (blocker)

git grep ServiceLoader -- '*.java' on dev returns zero hits. The sibling SPI your #792 points at, DataSourceActiveDetector, is not discovered either — DefaultDataSourceDestroyer just hardcodes its three implementations in the constructor.

That matters because dynamic-datasource-native-metadata's reachability-metadata.json currently has exactly one top-level key, reflection — there is no services section. GraalVM fails at image build time, not runtime, when a provider is on the class path but unregistered. That is precisely the nativeTest situation: your fixture registers LifecycleDataSourceUnwrapper through testFixtures/resources/META-INF/services/..., so both test-graalvm-ce-ci legs in ci.yml (boot3 and boot4) will try to build an image containing an unregistered provider. The "native verification is incomplete" note is therefore not a nice-to-have — those two legs are the ones most likely to trip on exactly this change.

Options: add a services entry to the native metadata, switch to SpringFactoriesLoader (which Boot handles natively and also sidesteps #3 below), or follow DataSourceActiveDetector's explicit-list style. Whichever way, this needs green nativeTest on both legs first.

2. The chain is rebuilt — and META-INF/services rescanned — on every close

The chain is constructed inside closeDataSource (DataSourceUnwrapperChain L37-58), so ServiceLoader.load performs a full config-file scan per call. removeDataSource is a single call, but destroy() loops over every datasource (DynamicRoutingDataSource L284-295), so shutting down N datasources means N rescans. Both flags are fixed at startup, so this could be built lazily once and cached. The neighbouring new DefaultDataSourceDestroyer() is already per-call, so this is not a new class of problem — but a service scan is considerably heavier than a constructor.

3. Undefined classloader semantics

ServiceLoader.load(X) resolves against the TCCL. Under java -jar (Spring Boot Loader) or devtools the TCCL is not the application loader, so third-party providers risk not being found — or being found against a different loader. There is no precedent in this repo to lean on here, so worth pinning down explicitly (e.g. passing DataSourceUnwrapper.class.getClassLoader()).

4. Minor

  • DataSourceUnwrapper extends org.springframework.core.Ordered binds a pure-JDBC concept to Spring. Harmless today since spring-core is already api, but it caps reuse outside Spring.
  • Neighbouring interfaces carry @author / @since javadoc (DataSourceActiveDetector does); the new ones do not. Worth matching for consistency.
  • One-layer unwrapping stops at ItemDataSource. This does not actually break anything — I checked ItemDataSource.close(), which forwards to the real pool — but the graceful path in DefaultDataSourceDestroyer matches detectors by exact class name, so it silently degrades to the 10s timeout instead of detecting Hikari activity. The tests avoid this today by wrapping the pool rather than the ItemDataSource. Not introduced by this PR, but adjacent enough that this refactor is a reasonable place to settle it.

CI status note

Heads-up on the current state: isDraft is true and the check rollup only shows welcome (fail), remind (skipping) and label (pass). CI and CodeQL have not reported at all yet — consistent with a first-time fork contributor whose workflow runs are still awaiting approval — and zizmor correctly does not trigger since no workflow file is touched. So per AGENTS.md §7 there is no Test CI signal to point at yet, and the JDK 17/21/25/27 matrix plus both native legs still need to run before merge.

Happy to help with the native services metadata if you want to go that route.

@Pika-Yalei
Pika-Yalei marked this pull request as ready for review October 15, 2026 10:05
@Pika-Yalei
Pika-Yalei requested a review from huayanYu as a code owner October 15, 2026 10:05
@huayanYu

Copy link
Copy Markdown
Member

Correction to my earlier comment — point 1 was wrong, please disregard it.

I claimed Native Image would fail at image build time because reachability-metadata.json has no services section, and suggested adding one. That was wrong twice over:

  1. There is no services metadata type. The documented types are reflection / JNI / resources / resource bundles / serialization / predefined classes (Reachability Metadata). So "add a services entry" was never actionable.
  2. Native Image registers ServiceLoader providers found on the build-time classpath automatically. The fixture provider sits on the nativeTest classpath, so it is registered without any metadata.

Your description already states the conclusion more concisely than I did — "no unsupported services metadata section was added" — and you found the real native problem instead: HikariDataSourceActiveDetector calls getHikariPoolMXBean() / getActiveConnections() reflectively, which had no invocation metadata, and that is exactly what the four graceful remove/replace cases hit. The conditional registrations in com.zaxxer/HikariCP/6.3.3 look correct to me: getHikariPoolMXBean on the runtime class HikariDataSource, and getActiveConnections on HikariPool (the MXBean's actual runtime class), both guarded by typeReached. Sorry for the noise on that one.

The remaining points look addressed to me:

  • Caching — lazy getDataSourceUnwrapperChain() with invalidation on flag change, and changingP6spyFlagAfterFirstCloseRebuildsTheCachedChain / changingSeataFlagAfterFirstCloseRebuildsTheCachedChain demonstrate both the reuse and the rebuild. Side note: I checked all three autoconfigurations call setP6spy / setSeata directly, so replacing the Lombok @Setter with the explicit synchronized versions keeps property binding intact.
  • Classloader — ClassUtils.getDefaultClassLoader() (TCCL first, Spring fallback), with providerDescriptorsVisibleOnlyThroughTheContextClassLoaderRemainDiscoverable covering the child-only descriptor case.
  • @author / @since — added.

Two small things I would still flag, both non-blocking:

  • The HikariPool entry is conditioned on HikariDataSourceActiveDetector, which DefaultDataSourceDestroyer instantiates on every close. The condition is therefore always satisfied and the entry behaves as unconditional. Harmless, just not the size win the conditional form normally buys.
  • The chain is now captured once, using whatever TCCL was current at first close. That is documented in the interface javadoc, and a restart builds a fresh routing datasource anyway, so I think it is fine — but "providers are discovered once" is now a real behavioural commitment for anyone registering providers lazily, worth keeping explicit.

For the record on CI: CI and CodeQL still report nothing (only label pass and remind skipping), consistent with action_required awaiting maintainer approval — so the hosted JDK 17/21/25/27 matrix has not validated any of this yet.

@huayanYu

Copy link
Copy Markdown
Member

CI is fully green here (Test CI JDK 17/21/25/27, both NativeTest legs, CodeQL, Dependency review) — the only thing blocking merge is that dev moved ahead since abab01e, and your fork does not have Allow edits by maintainers enabled (maintainerCanModify: false), so I cannot push the fix-up to this branch.

The conflict is a single file, DynamicRoutingDataSource.java, and it is purely an adjacent-insertion conflict:

  • dev (via aed8872) changed getPrimary() from protected to public and added a javadoc block.
  • This PR inserts setP6spy / setSeata / getDataSourceUnwrapperChain immediately above it.

The two are independent, so the resolution is simply keeping both.

To avoid losing your work while waiting on that, I opened #808, which merges your two commits onto the current dev tip with the conflict resolved as the union. Your commits are kept byte-identical with you as the author (c872248, b160b12), and the resulting diff against dev is still exactly 19 files / +1078 / -18.

Up to you how to proceed:

Both routes land the same code, so only one should stay open. Thanks for the work on this — the caching follow-up and the Hikari native metadata were the right calls.

@huayanYu

Copy link
Copy Markdown
Member

Merged — thank you for the work on this.

Your two commits are now on dev, rebased, with you as the author:

  • a4fe679 — refactor: extract datasource unwrapping into an ordered SPI
  • dada706 — fix: cache datasource unwrappers and register native pool access

They landed via #808. To explain why it went through a second PR rather than this one: dev moved ahead after your branch was cut (aed8872 changed DynamicRoutingDataSource.getPrimary() from protected to public), which put this branch into conflict, and your fork does not have Allow edits by maintainers enabled — so there was no way for me to push the fix-up here. #808 replays your two commits onto the current dev with that conflict resolved, keeps you as the author, and leaves the history linear so any merge strategy works.

Everything you validated held up on the hosted matrix: JDK 17/21/25/27, both nativeTest legs, CodeQL, Dependency review — all green.

Two things worth carrying forward from the review, both of which you already got right:

  • The caching follow-up was the correct call: the chain is now built once per routing datasource instead of rescanning META-INF/services on every close.
  • The Hikari reflection metadata (getHikariPoolMXBean / HikariPool.getActiveConnections) was the real native gap — the four graceful remove/replace cases were failing there, not on anything ServiceLoader related.

Closing this one as superseded by #808. Apologies again for my incorrect first comment about needing a services section in the native metadata — there is no such metadata type, and Native Image registers build-time classpath providers automatically.

@huayanYu huayanYu closed this Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core dynamic-datasource core modules tests Test suites and fixtures

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants