Add axon-event-sourcing module: Axon 5.4.2 entity, projection, replay

Event-sourced bank account on Axon Framework 5.4.2 + Spring Boot 4.1.1,
with transcripts generated by tests and three reproduced JPA-store variants.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b69H5rTewUKPyhGS8r
This commit is contained in:
Ankur
2026-12-02 00:02:00 +05:30
parent b4a623b889
commit 5439c041d0
35 changed files with 998 additions and 0 deletions
+48
View File
@@ -0,0 +1,48 @@
# axon-event-sourcing
Companion project for the article **[Event Sourcing with Axon Framework 5 and Spring Boot: Entities, Projections and Replays](https://ankurm.com/event-sourcing-axon-framework-5-spring-boot-entities-projections-replays/)** on **[ankurm.com](https://ankurm.com)**.
There is deliberately **no `docs/` folder**: the deeper material lives in collapsible "going
deeper" sections inside the article itself.
## Versions
| | |
|---|---|
| Axon Framework | 5.4.2 (`org.axonframework.extensions.spring:axon-spring-boot-starter`) |
| Spring Boot | 4.1.1 |
| JDK | 25 (Temurin 25.0.5.1) |
| H2 | 2.4.240 |
| Hibernate ORM | 7.4.5.Final |
## Quickstart
```
./scripts/run-all.sh # tests (writes output/01-04) + broken variants (output/05-07)
./scripts/run.sh # start the app on :8080
```
## Endpoints
| | |
|---|---|
| `POST /accounts/{id}?owner=` | open an account |
| `POST /accounts/{id}/deposit?amount=` | deposit |
| `POST /accounts/{id}/withdraw?amount=` | withdraw |
| `GET /accounts/{id}` | read model |
| `GET /accounts/{id}/events` | raw stored events (diagnostic; delete before shipping) |
| `POST /admin/replay` | rebuild the read model |
## Output index
| File | Shows |
|---|---|
| `output/01-command-flow.txt` | commands, stored events, read model |
| `output/02-rejections.txt` | refused commands leave no events |
| `output/03-no-entity-table.txt` | the entity has no table |
| `output/04-replay.txt` | read model lost and rebuilt |
| `output/05-variant-tag-key-mismatch.txt` | JPA store ignores the tag key |
| `output/06-variant-id-only-creator.txt` | id-only `@EntityCreator` yields no entity |
| `output/07-variant-two-tags.txt` | JPA store rejects a second tag |
`src/broken/` holds the deliberately broken sources for 05-07; they are outside the build.
@@ -0,0 +1,17 @@
# Open, deposit, withdraw: commands in, events stored, read model updated
$ POST /accounts/acc-1?owner=Asha
HTTP 201 {"accountId":"acc-1","status":"opened"}
$ POST /accounts/acc-1/deposit?amount=500
HTTP 200 {"accountId":"acc-1","deposited":500}
$ POST /accounts/acc-1/withdraw?amount=120
HTTP 200 {"accountId":"acc-1","withdrawn":120}
# Stored events (aggregate_event_entry), the only thing the write side persists
seq=0 aggregate_type=accountId com.ankurm.axondemo.domain.AccountOpened {"accountId":"acc-1","owner":"Asha"}
seq=1 aggregate_type=accountId com.ankurm.axondemo.domain.MoneyDeposited {"accountId":"acc-1","amount":500}
seq=2 aggregate_type=accountId com.ankurm.axondemo.domain.MoneyWithdrawn {"accountId":"acc-1","amount":120}
# Read model, filled by the event handlers
$ GET /accounts/acc-1
HTTP 200 {"accountId":"acc-1","owner":"Asha","balance":380,"eventsApplied":3}
@@ -0,0 +1,10 @@
# Rejected commands append no events
$ POST /accounts/acc-1/withdraw?amount=9999
HTTP 409 {"error":"Insufficient funds: balance 380, requested 9999"}
$ POST /accounts/acc-1?owner=Again
HTTP 409 {"error":"Account already exists"}
$ POST /accounts/nobody/deposit?amount=5
HTTP 404 {"error":"No such account"}
events in the store after three rejected commands: 3 (still the 3 from the first scenario)
@@ -0,0 +1,7 @@
# The entity has no table: only events and read-model rows exist
table: account_balance
table: aggregate_event_entry
table: token_entry
no table named bank_account: BankAccount.balance exists only while a command runs
+16
View File
@@ -0,0 +1,16 @@
# Lose the read model, replay the events, get it back
# Simulate a lost or corrupted read model: DELETE FROM account_balance (2 rows)
$ GET /accounts/acc-1
HTTP 404
events still in the store: 5
$ POST /admin/replay
HTTP 200 {"status":"replay started"}
# After the replay
$ GET /accounts/acc-1
HTTP 200 {"accountId":"acc-1","owner":"Asha","balance":380,"eventsApplied":3}
$ GET /accounts/acc-2
HTTP 200 {"accountId":"acc-2","owner":"Ravi","balance":40,"eventsApplied":2}
events in the store after the replay: 5 (a replay reads events, it never writes them)
@@ -0,0 +1,4 @@
# Broken variant: tag-key-mismatch
OpenAccount[accountId=v-1, owner=Asha] -> OK
Deposit[accountId=v-1, amount=10] -> OK
@@ -0,0 +1,4 @@
# Broken variant: id-only-creator
OpenAccount[accountId=v-1, owner=Asha] -> org.axonframework.modelling.entity.EntityMissingForInstanceCommandHandlerException: Entity was missing for instance command handler for command [com.ankurm.axondemo.domain.OpenAccount#0.0.1]
Deposit[accountId=v-1, amount=10] -> org.axonframework.modelling.entity.EntityMissingForInstanceCommandHandlerException: Entity was missing for instance command handler for command [com.ankurm.axondemo.domain.Deposit#0.0.1]
@@ -0,0 +1,4 @@
# Broken variant: two-tags
OpenAccount[accountId=v-1, owner=Asha] -> OK
Deposit[accountId=v-1, amount=10] -> org.axonframework.eventsourcing.eventstore.TooManyTagsOnEventMessageException: An Event Storage engine in Aggregate mode does not support multiple tags per event
+87
View File
@@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.ankurm</groupId>
<artifactId>spring-modulith-demo</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>axon-event-sourcing</artifactId>
<packaging>jar</packaging>
<name>axon-event-sourcing</name>
<description>Event sourcing with Axon Framework 5 and Spring Boot: an event-sourced entity,
command handlers that append events, an event-handler projection, and a replay that
rebuilds the read model from the stored events.</description>
<properties>
<java.version>25</java.version>
<axon.version>5.4.2</axon.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.axonframework.extensions.spring</groupId>
<artifactId>axon-spring-boot-starter</artifactId>
<version>${axon.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-test</artifactId>
<version>${axon.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>axon-event-sourcing</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<parameters>true</parameters>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env bash
# Reproduces three real behaviours by compiling a deliberately broken BankAccount from src/broken/
# in a throwaway copy of this module, and captures the exception text into output/.
set -euo pipefail
cd "$(dirname "$0")/.."
MODULE_DIR="$(pwd)"
run_variant () {
local name="$1" out="$2"
local tmp; tmp="$(mktemp -d)"
cp ../pom.xml "$tmp/pom.xml"
mkdir "$tmp/axon-event-sourcing"
cp -r pom.xml src "$tmp/axon-event-sourcing/"
cp src/broken/"$name"/*.java "$tmp/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/"
(cd "$tmp/axon-event-sourcing" && mvn -B -q test -Dtest=VariantProbeTest \
-Dvariant="$name" -Dvariant.file="$out" -Dtranscript.dir="$MODULE_DIR/output" >/dev/null 2>&1 || true)
rm -rf "$tmp"
echo "wrote output/$out"
}
run_variant tag-key-mismatch 05-variant-tag-key-mismatch.txt
run_variant id-only-creator 06-variant-id-only-creator.txt
run_variant two-tags 07-variant-two-tags.txt
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Regenerates every file in output/: the scenario transcripts (01-04) come from the normal test
# suite, the broken-variant transcripts (05-07) from broken-variants.sh.
set -euo pipefail
cd "$(dirname "$0")/.."
rm -f output/*.txt
mvn -B -q test
./scripts/broken-variants.sh
ls output
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Starts the application on port 8080 (Ctrl-C to stop). Try:
# curl -X POST 'localhost:8080/accounts/acc-1?owner=Asha'
# curl -X POST 'localhost:8080/accounts/acc-1/deposit?amount=500'
# curl localhost:8080/accounts/acc-1
# curl localhost:8080/accounts/acc-1/events
# curl -X POST localhost:8080/admin/replay
cd "$(dirname "$0")/.."
exec mvn -B -q spring-boot:run
@@ -0,0 +1,46 @@
package com.ankurm.axondemo.domain;
import org.axonframework.eventsourcing.annotation.EventSourcingHandler;
import org.axonframework.eventsourcing.annotation.reflection.EntityCreator;
import org.axonframework.eventsourcing.annotation.reflection.InjectEntityId;
import org.axonframework.extension.spring.stereotype.EventSourced;
import org.axonframework.messaging.commandhandling.annotation.CommandHandler;
import org.axonframework.messaging.eventhandling.gateway.EventAppender;
/**
* BROKEN on purpose. The Javadoc of @EntityCreator says an id-only constructor "will always
* initialize the entity, even if no events are found". In Axon 5.4.2 it does not: with no events
* the entity is null, so an INSTANCE command handler (non-static) has nothing to run on.
*/
@EventSourced(tagKey = "accountId")
public class BankAccount {
private final String accountId;
private boolean opened;
private long balance;
@EntityCreator
public BankAccount(@InjectEntityId String accountId) {
this.accountId = accountId;
}
@CommandHandler
public void handle(OpenAccount command, EventAppender appender) {
appender.append(new AccountOpened(command.accountId(), command.owner()));
}
@CommandHandler
public void handle(Deposit command, EventAppender appender) {
appender.append(new MoneyDeposited(accountId, command.amount()));
}
@EventSourcingHandler
void on(AccountOpened event) {
this.opened = true;
}
@EventSourcingHandler
void on(MoneyDeposited event) {
this.balance += event.amount();
}
}
@@ -0,0 +1,68 @@
package com.ankurm.axondemo.domain;
import org.axonframework.eventsourcing.annotation.EventSourcingHandler;
import org.axonframework.eventsourcing.annotation.reflection.EntityCreator;
import org.axonframework.extension.spring.stereotype.EventSourced;
import org.axonframework.messaging.commandhandling.annotation.CommandHandler;
import org.axonframework.messaging.eventhandling.gateway.EventAppender;
/**
* The event-sourced entity. Its fields are never stored. They are rebuilt on every command by
* replaying this account's events.
* <p>
* Three kinds of method, three jobs:
* <ul>
* <li>{@code @EntityCreator} constructor - builds the object from the account's <em>first</em>
* event. If the account has no events, the entity does not exist at all.</li>
* <li>{@code @CommandHandler} - checks the current state and appends events. It never changes
* fields itself. A <em>static</em> one is a creational handler: it runs when the entity
* does not exist yet.</li>
* <li>{@code @EventSourcingHandler} - changes fields only. No checks, no side effects, because
* it also runs for events written years ago.</li>
* </ul>
*/
@EventSourced(tagKey = "account") // WRONG KEY on purpose: the events are tagged "accountId"
public class BankAccount {
private final String accountId;
private long balance;
/** Called with the first AccountOpened event when an existing account is loaded. */
@EntityCreator
public BankAccount(AccountOpened first) {
this.accountId = first.accountId();
}
/** Static = creational: runs only when no entity exists for this id. */
@CommandHandler
public static void handle(OpenAccount command, EventAppender appender) {
appender.append(new AccountOpened(command.accountId(), command.owner()));
}
@CommandHandler
public void handle(Deposit command, EventAppender appender) {
if (command.amount() <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
appender.append(new MoneyDeposited(accountId, command.amount()));
}
@CommandHandler
public void handle(Withdraw command, EventAppender appender) {
if (command.amount() > balance) {
throw new IllegalStateException(
"Insufficient funds: balance " + balance + ", requested " + command.amount());
}
appender.append(new MoneyWithdrawn(accountId, command.amount()));
}
@EventSourcingHandler
void on(MoneyDeposited event) {
this.balance += event.amount();
}
@EventSourcingHandler
void on(MoneyWithdrawn event) {
this.balance -= event.amount();
}
}
@@ -0,0 +1,10 @@
package com.ankurm.axondemo.domain;
import org.axonframework.eventsourcing.annotation.EventTag;
/**
* BROKEN on purpose: a second tag on the same event. Fine for a store that supports Dynamic
* Consistency Boundaries, rejected by the JPA store, which works in "aggregate mode".
*/
public record MoneyDeposited(@EventTag(key = "accountId") @EventTag(key = "ledger") String accountId, long amount) {
}
@@ -0,0 +1,20 @@
package com.ankurm.axondemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Event sourcing with Axon Framework 5 and Spring Boot.
* <p>
* There is no Axon-specific bootstrap code here. The axon-spring-boot-starter finds
* {@code @EventSourced} entities and {@code @EventHandler} beans by component scanning, and
* (because no Axon Server connector is on the classpath) stores events in the application's own
* database through JPA.
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,11 @@
package com.ankurm.axondemo.domain;
import org.axonframework.eventsourcing.annotation.EventTag;
/**
* Event: an account was opened. The {@code @EventTag} puts the tag {@code accountId=<id>} on the
* stored event. When the entity is loaded, Axon asks the store for "all events tagged with this
* entity's tag" - so the tag key here must equal the {@code tagKey} on the entity.
*/
public record AccountOpened(@EventTag(key = "accountId") String accountId, String owner) {
}
@@ -0,0 +1,68 @@
package com.ankurm.axondemo.domain;
import org.axonframework.eventsourcing.annotation.EventSourcingHandler;
import org.axonframework.eventsourcing.annotation.reflection.EntityCreator;
import org.axonframework.extension.spring.stereotype.EventSourced;
import org.axonframework.messaging.commandhandling.annotation.CommandHandler;
import org.axonframework.messaging.eventhandling.gateway.EventAppender;
/**
* The event-sourced entity. Its fields are never stored. They are rebuilt on every command by
* replaying this account's events.
* <p>
* Three kinds of method, three jobs:
* <ul>
* <li>{@code @EntityCreator} constructor - builds the object from the account's <em>first</em>
* event. If the account has no events, the entity does not exist at all.</li>
* <li>{@code @CommandHandler} - checks the current state and appends events. It never changes
* fields itself. A <em>static</em> one is a creational handler: it runs when the entity
* does not exist yet.</li>
* <li>{@code @EventSourcingHandler} - changes fields only. No checks, no side effects, because
* it also runs for events written years ago.</li>
* </ul>
*/
@EventSourced(tagKey = "accountId")
public class BankAccount {
private final String accountId;
private long balance;
/** Called with the first AccountOpened event when an existing account is loaded. */
@EntityCreator
public BankAccount(AccountOpened first) {
this.accountId = first.accountId();
}
/** Static = creational: runs only when no entity exists for this id. */
@CommandHandler
public static void handle(OpenAccount command, EventAppender appender) {
appender.append(new AccountOpened(command.accountId(), command.owner()));
}
@CommandHandler
public void handle(Deposit command, EventAppender appender) {
if (command.amount() <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
appender.append(new MoneyDeposited(accountId, command.amount()));
}
@CommandHandler
public void handle(Withdraw command, EventAppender appender) {
if (command.amount() > balance) {
throw new IllegalStateException(
"Insufficient funds: balance " + balance + ", requested " + command.amount());
}
appender.append(new MoneyWithdrawn(accountId, command.amount()));
}
@EventSourcingHandler
void on(MoneyDeposited event) {
this.balance += event.amount();
}
@EventSourcingHandler
void on(MoneyWithdrawn event) {
this.balance -= event.amount();
}
}
@@ -0,0 +1,7 @@
package com.ankurm.axondemo.domain;
import org.axonframework.modelling.annotation.TargetEntityId;
/** Command: put money into an account. */
public record Deposit(@TargetEntityId String accountId, long amount) {
}
@@ -0,0 +1,7 @@
package com.ankurm.axondemo.domain;
import org.axonframework.eventsourcing.annotation.EventTag;
/** Event: money went in. */
public record MoneyDeposited(@EventTag(key = "accountId") String accountId, long amount) {
}
@@ -0,0 +1,7 @@
package com.ankurm.axondemo.domain;
import org.axonframework.eventsourcing.annotation.EventTag;
/** Event: money went out. */
public record MoneyWithdrawn(@EventTag(key = "accountId") String accountId, long amount) {
}
@@ -0,0 +1,7 @@
package com.ankurm.axondemo.domain;
import org.axonframework.modelling.annotation.TargetEntityId;
/** Command: open an account. {@code @TargetEntityId} tells Axon which entity instance this command is for. */
public record OpenAccount(@TargetEntityId String accountId, String owner) {
}
@@ -0,0 +1,7 @@
package com.ankurm.axondemo.domain;
import org.axonframework.modelling.annotation.TargetEntityId;
/** Command: take money out of an account. Rejected when the balance is too low. */
public record Withdraw(@TargetEntityId String accountId, long amount) {
}
@@ -0,0 +1,61 @@
package com.ankurm.axondemo.projection;
import com.ankurm.axondemo.domain.AccountOpened;
import com.ankurm.axondemo.domain.MoneyDeposited;
import com.ankurm.axondemo.domain.MoneyWithdrawn;
import org.axonframework.messaging.eventhandling.annotation.EventHandler;
import org.axonframework.messaging.eventhandling.replay.annotation.ResetHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Component;
/**
* The read model: one row per account in {@code account_balance}, kept up to date by event
* handlers. It is a disposable copy. Dropping the table and replaying the events brings it back.
* <p>
* Events reach these methods through a <em>streaming event processor</em> that remembers how far
* it has read (its tracking token) - see {@link ProjectionConfig}.
*/
@Component
public class AccountBalanceProjection {
private static final Logger log = LoggerFactory.getLogger(AccountBalanceProjection.class);
private final JdbcClient jdbc;
public AccountBalanceProjection(JdbcClient jdbc) {
this.jdbc = jdbc;
}
@EventHandler
void on(AccountOpened event) {
log.info("projection: AccountOpened {}", event.accountId());
jdbc.sql("INSERT INTO account_balance (account_id, owner, balance, events_applied) VALUES (?, ?, 0, 1)")
.params(event.accountId(), event.owner())
.update();
}
@EventHandler
void on(MoneyDeposited event) {
log.info("projection: MoneyDeposited {} +{}", event.accountId(), event.amount());
jdbc.sql("UPDATE account_balance SET balance = balance + ?, events_applied = events_applied + 1 WHERE account_id = ?")
.params(event.amount(), event.accountId())
.update();
}
@EventHandler
void on(MoneyWithdrawn event) {
log.info("projection: MoneyWithdrawn {} -{}", event.accountId(), event.amount());
jdbc.sql("UPDATE account_balance SET balance = balance - ?, events_applied = events_applied + 1 WHERE account_id = ?")
.params(event.amount(), event.accountId())
.update();
}
/** Called once when the processor is reset for a replay, before the first old event arrives. */
@ResetHandler
void reset() {
int rows = jdbc.sql("DELETE FROM account_balance").update();
log.info("projection: reset, cleared {} rows", rows);
}
}
@@ -0,0 +1,5 @@
package com.ankurm.axondemo.projection;
/** One row of the read model. */
public record AccountBalanceView(String accountId, String owner, long balance, int eventsApplied) {
}
@@ -0,0 +1,23 @@
package com.ankurm.axondemo.projection;
import org.axonframework.extension.spring.config.EventProcessorDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Gives the projection its own named streaming processor. Without this bean Axon would still
* create one, named after the handler's package; naming it explicitly makes the replay endpoint
* and the log lines easier to read.
*/
@Configuration
public class ProjectionConfig {
public static final String PROCESSOR = "account-balance";
@Bean
EventProcessorDefinition accountBalanceProcessor() {
return EventProcessorDefinition.pooledStreaming(PROCESSOR)
.assigningHandlers(d -> AccountBalanceProjection.class.equals(d.beanType()))
.notCustomized();
}
}
@@ -0,0 +1,37 @@
package com.ankurm.axondemo.projection;
import org.axonframework.common.configuration.AxonConfiguration;
import org.axonframework.messaging.eventhandling.processing.streaming.StreamingEventProcessor;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* Rebuilds the read model: stop the processor, rewind its tracking token to the start of the
* event stream (which also runs the {@code @ResetHandler}), start it again.
*/
@Service
public class ReplayService {
private final AxonConfiguration configuration;
public ReplayService(AxonConfiguration configuration) {
this.configuration = configuration;
}
public void replay() throws Exception {
StreamingEventProcessor processor = configuration.getComponents(StreamingEventProcessor.class)
.entrySet().stream()
.filter(e -> e.getKey().contains(ProjectionConfig.PROCESSOR))
.map(java.util.Map.Entry::getValue)
.findFirst()
.orElseThrow(() -> new IllegalStateException(
"No streaming processor named " + ProjectionConfig.PROCESSOR));
if (!processor.supportsReset()) {
throw new IllegalStateException("Processor does not support reset");
}
processor.shutdown().get(10, TimeUnit.SECONDS);
processor.resetTokens().get(10, TimeUnit.SECONDS);
processor.start().get(10, TimeUnit.SECONDS);
}
}
@@ -0,0 +1,98 @@
package com.ankurm.axondemo.web;
import com.ankurm.axondemo.domain.Deposit;
import com.ankurm.axondemo.domain.OpenAccount;
import com.ankurm.axondemo.domain.Withdraw;
import com.ankurm.axondemo.projection.AccountBalanceView;
import org.axonframework.messaging.commandhandling.gateway.CommandGateway;
import org.axonframework.modelling.entity.EntityAlreadyExistsForCreationalCommandHandlerException;
import org.axonframework.modelling.entity.EntityMissingForInstanceCommandHandlerException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.web.bind.annotation.*;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* HTTP edge. Commands go through the {@link CommandGateway}; reads go straight to the read model
* table and never touch the event store.
*/
@RestController
@RequestMapping("/accounts")
public class AccountController {
private final CommandGateway commands;
private final JdbcClient jdbc;
public AccountController(CommandGateway commands, JdbcClient jdbc) {
this.commands = commands;
this.jdbc = jdbc;
}
@PostMapping("/{id}")
ResponseEntity<Map<String, Object>> open(@PathVariable String id, @RequestParam String owner) {
commands.sendAndWait(new OpenAccount(id, owner));
return ResponseEntity.status(HttpStatus.CREATED).body(ack("accountId", id, "status", "opened"));
}
@PostMapping("/{id}/deposit")
Map<String, Object> deposit(@PathVariable String id, @RequestParam long amount) {
commands.sendAndWait(new Deposit(id, amount));
return ack("accountId", id, "deposited", amount);
}
@PostMapping("/{id}/withdraw")
Map<String, Object> withdraw(@PathVariable String id, @RequestParam long amount) {
commands.sendAndWait(new Withdraw(id, amount));
return ack("accountId", id, "withdrawn", amount);
}
@GetMapping("/{id}")
ResponseEntity<AccountBalanceView> view(@PathVariable String id) {
return jdbc.sql("SELECT account_id, owner, balance, events_applied FROM account_balance WHERE account_id = ?")
.param(id)
.query((rs, n) -> new AccountBalanceView(rs.getString(1), rs.getString(2), rs.getLong(3), rs.getInt(4)))
.optional()
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
/** Diagnostic: the raw stored events. Delete this endpoint before shipping. */
@GetMapping("/{id}/events")
List<Map<String, Object>> events(@PathVariable String id) {
return jdbc.sql("SELECT aggregate_sequence_number AS seq, aggregate_type, type AS event_type, "
+ "UTF8TOSTRING(payload) AS payload FROM aggregate_event_entry "
+ "WHERE aggregate_identifier = ? ORDER BY aggregate_sequence_number")
.param(id)
.query().listOfRows();
}
@ExceptionHandler({IllegalStateException.class, IllegalArgumentException.class})
ResponseEntity<Map<String, String>> rejected(RuntimeException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("error", e.getMessage()));
}
/** OpenAccount for an id that already has events: the creational handler refuses to run. */
@ExceptionHandler(EntityAlreadyExistsForCreationalCommandHandlerException.class)
ResponseEntity<Map<String, String>> alreadyExists(RuntimeException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("error", "Account already exists"));
}
/** Deposit or Withdraw for an id with no events: there is no entity to run the handler on. */
@ExceptionHandler(EntityMissingForInstanceCommandHandlerException.class)
ResponseEntity<Map<String, String>> missing(RuntimeException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "No such account"));
}
/** Small ordered map so the JSON field order is the same on every run. */
private static Map<String, Object> ack(Object... keysAndValues) {
Map<String, Object> map = new LinkedHashMap<>();
for (int i = 0; i < keysAndValues.length; i += 2) {
map.put((String) keysAndValues[i], keysAndValues[i + 1]);
}
return map;
}
}
@@ -0,0 +1,26 @@
package com.ankurm.axondemo.web;
import com.ankurm.axondemo.projection.ReplayService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/** Admin trigger for a replay. Protect or remove this in a real service. */
@RestController
@RequestMapping("/admin")
public class ReplayController {
private final ReplayService replay;
public ReplayController(ReplayService replay) {
this.replay = replay;
}
@PostMapping("/replay")
Map<String, String> replay() throws Exception {
replay.replay();
return Map.of("status", "replay started");
}
}
@@ -0,0 +1,9 @@
spring.application.name=axon-event-sourcing
spring.datasource.url=jdbc:h2:mem:axondemo;DB_CLOSE_DELAY=-1
# Axon's JPA event store entities (aggregate_event_entry, token_entry, ...) are created by Hibernate.
spring.jpa.hibernate.ddl-auto=update
spring.sql.init.mode=always
spring.jpa.open-in-view=false
# No Axon Server connector on the classpath, so JPA event storage is used.
# Wake the streaming processor quickly so the demo output is not dominated by polling delay.
axon.eventstore.jpa.polling-interval=0
@@ -0,0 +1,6 @@
CREATE TABLE IF NOT EXISTS account_balance (
account_id VARCHAR(64) PRIMARY KEY,
owner VARCHAR(128) NOT NULL,
balance BIGINT NOT NULL,
events_applied INT NOT NULL
);
@@ -0,0 +1,154 @@
package com.ankurm.axondemo;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.jdbc.core.simple.JdbcClient;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import java.util.Map;
import java.util.function.BooleanSupplier;
import static org.assertj.core.api.Assertions.assertThat;
/**
* One test per scenario in the blog post. Each writes a transcript to {@code output/}.
* The tests run in order and share one application (and one in-memory event store).
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class EventSourcingTranscriptTest {
@LocalServerPort int port;
@Autowired JdbcClient jdbc;
private final HttpClient client = HttpClient.newHttpClient();
private HttpResponse<String> call(String method, String path) throws Exception {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + path))
.method(method, BodyPublishers.noBody()).build();
return client.send(request, BodyHandlers.ofString());
}
private void awaitTrue(BooleanSupplier condition) throws Exception {
for (int i = 0; i < 100 && !condition.getAsBoolean(); i++) {
Thread.sleep(100);
}
assertThat(condition.getAsBoolean()).as("condition within 10s").isTrue();
}
private long eventsApplied(String id) {
return jdbc.sql("SELECT COALESCE(MAX(events_applied), 0) FROM account_balance WHERE account_id = ?")
.param(id).query(Long.class).single();
}
@Test
@Order(1)
void commandFlow() throws Exception {
Transcript t = new Transcript("01-command-flow.txt", "Open, deposit, withdraw: commands in, events stored, read model updated");
t.http("POST", "/accounts/acc-1?owner=Asha", call("POST", "/accounts/acc-1?owner=Asha"));
t.http("POST", "/accounts/acc-1/deposit?amount=500", call("POST", "/accounts/acc-1/deposit?amount=500"));
t.http("POST", "/accounts/acc-1/withdraw?amount=120", call("POST", "/accounts/acc-1/withdraw?amount=120"));
t.line("");
t.line("# Stored events (aggregate_event_entry), the only thing the write side persists");
List<Map<String, Object>> events = jdbc.sql(
"SELECT aggregate_sequence_number AS seq, aggregate_type, type, UTF8TOSTRING(payload) AS payload "
+ "FROM aggregate_event_entry WHERE aggregate_identifier = 'acc-1' ORDER BY seq").query().listOfRows();
for (Map<String, Object> e : events) {
t.line("seq=%s aggregate_type=%s %s %s", e.get("SEQ"), e.get("AGGREGATE_TYPE"), e.get("TYPE"), e.get("PAYLOAD"));
}
assertThat(events).hasSize(3);
awaitTrue(() -> eventsApplied("acc-1") == 3);
t.line("");
t.line("# Read model, filled by the event handlers");
HttpResponse<String> view = call("GET", "/accounts/acc-1");
t.http("GET", "/accounts/acc-1", view);
assertThat(view.body()).contains("\"balance\":380").contains("\"eventsApplied\":3");
t.save();
}
@Test
@Order(2)
void rejectedCommandsAppendNothing() throws Exception {
Transcript t = new Transcript("02-rejections.txt", "Rejected commands append no events");
HttpResponse<String> overdraft = call("POST", "/accounts/acc-1/withdraw?amount=9999");
HttpResponse<String> reopen = call("POST", "/accounts/acc-1?owner=Again");
HttpResponse<String> unknown = call("POST", "/accounts/nobody/deposit?amount=5");
t.http("POST", "/accounts/acc-1/withdraw?amount=9999", overdraft);
t.http("POST", "/accounts/acc-1?owner=Again", reopen);
t.http("POST", "/accounts/nobody/deposit?amount=5", unknown);
assertThat(overdraft.statusCode()).isEqualTo(409);
assertThat(overdraft.body()).contains("Insufficient funds: balance 380, requested 9999");
assertThat(reopen.statusCode()).isEqualTo(409);
assertThat(unknown.statusCode()).isEqualTo(404);
long count = jdbc.sql("SELECT COUNT(*) FROM aggregate_event_entry").query(Long.class).single();
t.line("");
t.line("events in the store after three rejected commands: %d (still the 3 from the first scenario)", count);
assertThat(count).isEqualTo(3);
t.save();
}
@Test
@Order(3)
void entityStateIsNotStored() {
Transcript t = new Transcript("03-no-entity-table.txt", "The entity has no table: only events and read-model rows exist");
List<String> tables = jdbc.sql("SELECT table_name FROM information_schema.tables "
+ "WHERE table_schema = 'PUBLIC' ORDER BY table_name")
.query(String.class).list();
tables.forEach(name -> t.line("table: %s", name.toLowerCase()));
assertThat(tables).contains("AGGREGATE_EVENT_ENTRY", "ACCOUNT_BALANCE", "TOKEN_ENTRY");
assertThat(tables).doesNotContain("BANK_ACCOUNT");
t.line("");
t.line("no table named bank_account: BankAccount.balance exists only while a command runs");
t.save();
}
@Test
@Order(4)
void replayRebuildsTheReadModel() throws Exception {
Transcript t = new Transcript("04-replay.txt", "Lose the read model, replay the events, get it back");
call("POST", "/accounts/acc-2?owner=Ravi");
call("POST", "/accounts/acc-2/deposit?amount=40");
awaitTrue(() -> eventsApplied("acc-2") == 2);
int removed = jdbc.sql("DELETE FROM account_balance").update();
t.line("# Simulate a lost or corrupted read model: DELETE FROM account_balance (%d rows)", removed);
HttpResponse<String> gone = call("GET", "/accounts/acc-1");
t.http("GET", "/accounts/acc-1", gone);
assertThat(gone.statusCode()).isEqualTo(404);
long events = jdbc.sql("SELECT COUNT(*) FROM aggregate_event_entry").query(Long.class).single();
t.line("events still in the store: %d", events);
t.line("");
HttpResponse<String> replay = call("POST", "/admin/replay");
t.http("POST", "/admin/replay", replay);
assertThat(replay.statusCode()).isEqualTo(200);
awaitTrue(() -> eventsApplied("acc-1") == 3 && eventsApplied("acc-2") == 2);
t.line("");
t.line("# After the replay");
HttpResponse<String> a1 = call("GET", "/accounts/acc-1");
HttpResponse<String> a2 = call("GET", "/accounts/acc-2");
t.http("GET", "/accounts/acc-1", a1);
t.http("GET", "/accounts/acc-2", a2);
assertThat(a1.body()).contains("\"balance\":380");
assertThat(a2.body()).contains("\"balance\":40");
long after = jdbc.sql("SELECT COUNT(*) FROM aggregate_event_entry").query(Long.class).single();
t.line("events in the store after the replay: %d (a replay reads events, it never writes them)", after);
assertThat(after).isEqualTo(events);
t.save();
}
}
@@ -0,0 +1,42 @@
package com.ankurm.axondemo;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Collects the lines a test prints and writes them to {@code output/NN-name.txt}. The same test
* asserts the numbers it prints, so every figure in a transcript (and in the blog post) is an
* assertion that fails the build the day it stops being true.
*/
final class Transcript {
private final Path file;
private final StringBuilder text = new StringBuilder();
Transcript(String fileName, String title) {
this.file = Path.of(System.getProperty("transcript.dir", "output")).resolve(fileName);
line("# " + title);
line("");
}
void line(String format, Object... args) {
text.append(args.length == 0 ? format : format.formatted(args)).append('\n');
}
void http(String method, String path, HttpResponse<String> response) {
line("$ %s %s", method, path);
line("HTTP %d %s", response.statusCode(), response.body());
}
void save() {
try {
Files.createDirectories(file.getParent());
Files.writeString(file, text.toString());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -0,0 +1,42 @@
package com.ankurm.axondemo;
import com.ankurm.axondemo.domain.Deposit;
import com.ankurm.axondemo.domain.OpenAccount;
import org.axonframework.messaging.commandhandling.gateway.CommandGateway;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* Skipped in the normal build. scripts/broken-variants.sh copies the module to a temp directory,
* swaps in a deliberately broken BankAccount from src/broken/, and runs only this test with
* -Dvariant=NAME so the real exception text is captured into output/.
*/
@SpringBootTest
class VariantProbeTest {
@Autowired CommandGateway commands;
@Test
void probe() {
String variant = System.getProperty("variant");
org.junit.jupiter.api.Assumptions.assumeTrue(variant != null, "only runs under scripts/broken-variants.sh");
Transcript t = new Transcript(System.getProperty("variant.file"), "Broken variant: " + variant);
send(t, new OpenAccount("v-1", "Asha"));
send(t, new Deposit("v-1", 10));
t.save();
}
private void send(Transcript t, Object command) {
try {
commands.sendAndWait(command);
t.line("%s -> OK", command);
} catch (Throwable e) {
Throwable root = e;
while (root.getCause() != null && root.getCause() != root) {
root = root.getCause();
}
t.line("%s -> %s: %s", command, root.getClass().getName(), root.getMessage().replaceAll("@[0-9a-f]+", "@<hash>"));
}
}
}
+1
View File
@@ -29,5 +29,6 @@
<module>order-fulfillment</module>
<module>outbox</module>
<module>cqrs</module>
<module>axon-event-sourcing</module>
</modules>
</project>