Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [4.0.0] - 2026-04-06

### Added — Phase 4: Production Hardening & Distributed Transactions

#### Cross-Shard Saga Orchestration (sharding-saga — new module)
- `ShardSagaStep<T>` — interface defining `execute(T)` + `compensate(T)` for one saga step
- `ShardSagaDefinition<T>` — immutable ordered list of steps; built via fluent `builder()` API
- `ShardSagaOrchestrator` — executes steps in order; on failure compensates completed steps in reverse; continues even if individual compensation steps throw
- `ShardSagaLog` — immutable audit record (sagaId, stepName, Phase, Status, timestamp, errorMsg)
- `ShardSagaException` — carries sagaId + full audit log; thrown after compensation completes
- `ShardingSagaAutoConfiguration` — enabled via `sharding.saga.enabled=true`
- Registered in `sharding-spring-boot-starter` auto-configuration imports

#### Virtual Thread Executor (sharding-core)
- `VirtualThreadShardExecutor` — factory producing an `ExecutorService` optimised per JVM:
- JDK 21+: `Executors.newVirtualThreadPerTaskExecutor()` via reflection (stays source-compatible with JDK 17)
- JDK 17–20: fallback to a cached daemon thread pool
- `VirtualThreadShardExecutor.isVirtualThreadsAvailable()` — runtime JVM version check

#### Test Coverage (filling Phase 2 & 3 gaps)
- `ShardKeyExtractorTest` (sharding-aop) — all three extraction modes: first-long-param, named-param, entity-field; error paths for missing param/field
- `MeteredShardRouterTest` (sharding-metrics) — counter increment, timer recording, multi-call accumulation, and delegation to underlying router
- `ReadWriteRoutingDataSourceTest` (sharding-readwrite) — primary routing for writes, replica routing for reads, round-robin replica selection, no-replica fallback
- `ShardMigrationServiceTest` (sharding-migration) — state machine transitions, key-range matching, invalid-input validation, getPlan/listPlans/getProgress queries
- `ShardSagaOrchestratorTest` (sharding-saga) — all-steps-success, partial failure + compensation, first-step failure, full audit log assertions

## [3.0.0] - 2026-04-04

### Added — Phase 3
Expand Down
74 changes: 74 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
| **Cross-shard paged queries** | ✅ v3.0 | `sharding-jdbc` |
| **Online shard migration** (double-write + backfill) | ✅ v3.0 | `sharding-migration` |
| **CDC integration** (Debezium / Kafka) | ✅ v3.0 | `sharding-cdc` |
| **Cross-shard Saga transactions** (auto-compensation) | ✅ v4.0 | `sharding-saga` |
| **Virtual thread executor** (JDK 21 Project Loom) | ✅ v4.0 | `sharding-core` |

---

Expand Down Expand Up @@ -81,6 +83,13 @@ Các module optional — thêm vào khi cần:
<artifactId>sharding-cdc</artifactId>
<version>2.0.0</version>
</dependency>

<!-- Cross-shard Saga transactions (v4.0) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>sharding-saga</artifactId>
<version>4.0.0</version>
</dependency>
```

### 2. Cấu hình shards
Expand Down Expand Up @@ -515,6 +524,71 @@ public class MyCacheInvalidator extends ShardCacheInvalidator {

---

## Phase 4 — v4.0

### Cross-Shard Saga Transactions

Enable with `sharding.saga.enabled=true`. A Saga breaks a cross-shard operation into
ordered steps; if any step fails the orchestrator calls each previously-completed step's
compensate method in reverse order.

```java
// 1. Define steps (typically Spring beans)
ShardSagaDefinition<TransferContext> transferSaga =
ShardSagaDefinition.<TransferContext>builder()
.step(new DebitSourceStep(jdbcTemplate))
.step(new CreditTargetStep(jdbcTemplate))
.step(new RecordLedgerStep(jdbcTemplate))
.build();

// 2. Execute (inject ShardSagaOrchestrator as a Spring bean)
try {
orchestrator.execute(UUID.randomUUID().toString(), transferSaga, ctx);
} catch (ShardSagaException ex) {
log.error("Transfer failed: {}", ex.getSagaId());
ex.getAuditLog().forEach(e -> log.error(" {} {} {}", e.phase(), e.stepName(), e.status()));
}
```

Each step implements `ShardSagaStep<T>`:

```java
public class DebitSourceStep implements ShardSagaStep<TransferContext> {
@Override public String name() { return "debit-source"; }

@Override
public void execute(TransferContext ctx) {
// deduct from source shard — must be idempotent
jdbcTemplate.update(ctx.sourceShard(),
"UPDATE accounts SET balance = balance - ? WHERE id = ?",
ctx.amount(), ctx.sourceAccountId());
ctx.markDebited();
}

@Override
public void compensate(TransferContext ctx) {
// reverse the debit
jdbcTemplate.update(ctx.sourceShard(),
"UPDATE accounts SET balance = balance + ? WHERE id = ?",
ctx.amount(), ctx.sourceAccountId());
}
}
```

### Virtual Thread Executor (JDK 21)

```java
// Create a virtual-thread executor for scatter-gather queries
ExecutorService executor = VirtualThreadShardExecutor.create("shard-query");

// Check at runtime whether virtual threads are available
if (VirtualThreadShardExecutor.isVirtualThreadsAvailable()) {
log.info("Running on JDK 21+ with virtual threads");
}
```

---

## Cấu hình đầy đủ

```yaml
Expand Down
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
<module>sharding-migration</module>
<module>sharding-cdc</module>
<module>sharding-spring-boot-starter</module>
<module>sharding-saga</module>
</modules>

<dependencyManagement>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package org.springframework.boot.starter.sharding.aop;

import org.junit.jupiter.api.Test;
import org.springframework.boot.starter.sharding.jpa.ShardBy;

import java.lang.reflect.Method;

import static org.assertj.core.api.Assertions.*;

/**
* Unit tests for {@link ShardKeyExtractor} covering all three extraction modes.
*/
class ShardKeyExtractorTest {

// -------------------------------------------------------------------------
// Mode 1: first long parameter (no value on @ShardBy)
// -------------------------------------------------------------------------

@Test
void firstLongParam_extractsCorrectly() throws Exception {
Method method = Fixture.class.getMethod("byFirstLong", long.class, String.class);
ShardBy annotation = method.getAnnotation(ShardBy.class);
long key = ShardKeyExtractor.extract(method, new Object[]{42L, "ignored"}, annotation);
assertThat(key).isEqualTo(42L);
}

@Test
void firstLongParam_noLongParameter_throws() throws Exception {
Method method = Fixture.class.getMethod("noLong", String.class);
ShardBy annotation = method.getAnnotation(ShardBy.class);
assertThatThrownBy(() -> ShardKeyExtractor.extract(method, new Object[]{"x"}, annotation))
.isInstanceOf(ShardKeyExtractionException.class);
}

// -------------------------------------------------------------------------
// Mode 2: named parameter
// -------------------------------------------------------------------------

@Test
void namedParam_extractsCorrectly() throws Exception {
Method method = Fixture.class.getMethod("byName", String.class, long.class);
ShardBy annotation = method.getAnnotation(ShardBy.class);
long key = ShardKeyExtractor.extract(method, new Object[]{"unused", 99L}, annotation);
assertThat(key).isEqualTo(99L);
}

// -------------------------------------------------------------------------
// Mode 3: entity field
// -------------------------------------------------------------------------

@Test
void fromEntity_extractsFieldValue() throws Exception {
Method method = Fixture.class.getMethod("byEntityField", Fixture.Payment.class);
ShardBy annotation = method.getAnnotation(ShardBy.class);
Fixture.Payment payment = new Fixture.Payment(777L);
long key = ShardKeyExtractor.extract(method, new Object[]{payment}, annotation);
assertThat(key).isEqualTo(777L);
}

@Test
void fromEntity_missingField_throws() throws Exception {
Method method = Fixture.class.getMethod("byMissingField", Fixture.Payment.class);
ShardBy annotation = method.getAnnotation(ShardBy.class);
assertThatThrownBy(() ->
ShardKeyExtractor.extract(method, new Object[]{new Fixture.Payment(1L)}, annotation))
.isInstanceOf(ShardKeyExtractionException.class);
}

// -------------------------------------------------------------------------
// Fixture class (compiled with -parameters via Spring Boot default)
// -------------------------------------------------------------------------

static class Fixture {

@ShardBy
public void byFirstLong(long accountId, String name) {}

@ShardBy
public void noLong(String name) {}

@ShardBy("accountId")
public void byName(String ignored, long accountId) {}

@ShardBy(value = "accountId", fromEntity = true)
public void byEntityField(Payment payment) {}

@ShardBy(value = "nonExistentField", fromEntity = true)
public void byMissingField(Payment payment) {}

static class Payment {
public final long accountId;
Payment(long accountId) { this.accountId = accountId; }
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package org.springframework.boot.starter.sharding.core;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* Factory for an {@link ExecutorService} used by scatter-gather and other parallel
* shard operations.
*
* <p>On <b>JDK&nbsp;21+</b> the executor uses <em>virtual threads</em> (Project Loom),
* giving near-zero per-thread overhead and making it safe to issue one virtual thread
* per shard regardless of shard count.
*
* <p>On <b>JDK&nbsp;17/18/19/20</b> (where virtual threads are either unavailable or
* only in preview) the executor falls back to a standard cached thread pool.
*
* <h2>Usage</h2>
* <pre>{@code
* // Inject as a bean or create locally:
* ExecutorService executor = VirtualThreadShardExecutor.create("shard-scatter");
*
* // Hand off to ShardScatterGatherTemplate:
* new ShardScatterGatherTemplate(shardRouter, executor);
* }</pre>
*
* <h2>Lifecycle</h2>
* The returned {@link ExecutorService} must be shut down by the caller when no longer
* needed. For Spring-managed beans use {@code @PreDestroy} or {@code DisposableBean}.
*/
public final class VirtualThreadShardExecutor {

private VirtualThreadShardExecutor() {}

/**
* Create an executor optimised for the current JVM.
*
* @param threadNamePrefix prefix used when naming threads (informational)
* @return a new {@link ExecutorService}; caller is responsible for shutdown
*/
public static ExecutorService create(String threadNamePrefix) {
if (isVirtualThreadsAvailable()) {
return newVirtualThreadExecutor(threadNamePrefix);
}
return Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r);
t.setName(threadNamePrefix + "-" + t.getId());
t.setDaemon(true);
return t;
});
}

/**
* Returns {@code true} if the JVM supports virtual threads (JDK 21+).
*/
public static boolean isVirtualThreadsAvailable() {
return Runtime.version().feature() >= 21;
}

/**
* Called only when JDK 21+ is confirmed; uses reflection to avoid compile-time
* dependency on preview/newer APIs, keeping the module source-compatible with JDK 17.
*/
private static ExecutorService newVirtualThreadExecutor(String prefix) {
try {
// Executors.newVirtualThreadPerTaskExecutor() — JDK 21 API
var method = Executors.class.getMethod("newVirtualThreadPerTaskExecutor");
return (ExecutorService) method.invoke(null);
} catch (Exception e) {
// Should never happen when isVirtualThreadsAvailable() is true
return Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r);
t.setName(prefix + "-fallback-" + t.getId());
t.setDaemon(true);
return t;
});
}
}
}
Loading
Loading