diff --git a/axon-event-sourcing/README.md b/axon-event-sourcing/README.md new file mode 100644 index 0000000..c0a3ae6 --- /dev/null +++ b/axon-event-sourcing/README.md @@ -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. diff --git a/axon-event-sourcing/output/01-command-flow.txt b/axon-event-sourcing/output/01-command-flow.txt new file mode 100644 index 0000000..e3c1d69 --- /dev/null +++ b/axon-event-sourcing/output/01-command-flow.txt @@ -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} diff --git a/axon-event-sourcing/output/02-rejections.txt b/axon-event-sourcing/output/02-rejections.txt new file mode 100644 index 0000000..2c14ad2 --- /dev/null +++ b/axon-event-sourcing/output/02-rejections.txt @@ -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) diff --git a/axon-event-sourcing/output/03-no-entity-table.txt b/axon-event-sourcing/output/03-no-entity-table.txt new file mode 100644 index 0000000..39934bf --- /dev/null +++ b/axon-event-sourcing/output/03-no-entity-table.txt @@ -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 diff --git a/axon-event-sourcing/output/04-replay.txt b/axon-event-sourcing/output/04-replay.txt new file mode 100644 index 0000000..03687bd --- /dev/null +++ b/axon-event-sourcing/output/04-replay.txt @@ -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) diff --git a/axon-event-sourcing/output/05-variant-tag-key-mismatch.txt b/axon-event-sourcing/output/05-variant-tag-key-mismatch.txt new file mode 100644 index 0000000..abe3e5f --- /dev/null +++ b/axon-event-sourcing/output/05-variant-tag-key-mismatch.txt @@ -0,0 +1,4 @@ +# Broken variant: tag-key-mismatch + +OpenAccount[accountId=v-1, owner=Asha] -> OK +Deposit[accountId=v-1, amount=10] -> OK diff --git a/axon-event-sourcing/output/06-variant-id-only-creator.txt b/axon-event-sourcing/output/06-variant-id-only-creator.txt new file mode 100644 index 0000000..60a6f5e --- /dev/null +++ b/axon-event-sourcing/output/06-variant-id-only-creator.txt @@ -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] diff --git a/axon-event-sourcing/output/07-variant-two-tags.txt b/axon-event-sourcing/output/07-variant-two-tags.txt new file mode 100644 index 0000000..2fa9661 --- /dev/null +++ b/axon-event-sourcing/output/07-variant-two-tags.txt @@ -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 diff --git a/axon-event-sourcing/pom.xml b/axon-event-sourcing/pom.xml new file mode 100644 index 0000000..0f8ec81 --- /dev/null +++ b/axon-event-sourcing/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + + com.ankurm + spring-modulith-demo + 1.0.0 + + + axon-event-sourcing + jar + axon-event-sourcing + 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. + + + 25 + 5.4.2 + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + org.axonframework.extensions.spring + axon-spring-boot-starter + ${axon.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + runtime + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.axonframework + axon-test + ${axon.version} + test + + + + + axon-event-sourcing + + + org.apache.maven.plugins + maven-compiler-plugin + + true + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/axon-event-sourcing/scripts/broken-variants.sh b/axon-event-sourcing/scripts/broken-variants.sh new file mode 100755 index 0000000..d9ea901 --- /dev/null +++ b/axon-event-sourcing/scripts/broken-variants.sh @@ -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 diff --git a/axon-event-sourcing/scripts/run-all.sh b/axon-event-sourcing/scripts/run-all.sh new file mode 100755 index 0000000..3282fdf --- /dev/null +++ b/axon-event-sourcing/scripts/run-all.sh @@ -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 diff --git a/axon-event-sourcing/scripts/run.sh b/axon-event-sourcing/scripts/run.sh new file mode 100755 index 0000000..2d246f7 --- /dev/null +++ b/axon-event-sourcing/scripts/run.sh @@ -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 diff --git a/axon-event-sourcing/src/broken/id-only-creator/BankAccount.java b/axon-event-sourcing/src/broken/id-only-creator/BankAccount.java new file mode 100644 index 0000000..7778af6 --- /dev/null +++ b/axon-event-sourcing/src/broken/id-only-creator/BankAccount.java @@ -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(); + } +} diff --git a/axon-event-sourcing/src/broken/tag-key-mismatch/BankAccount.java b/axon-event-sourcing/src/broken/tag-key-mismatch/BankAccount.java new file mode 100644 index 0000000..7eb7e90 --- /dev/null +++ b/axon-event-sourcing/src/broken/tag-key-mismatch/BankAccount.java @@ -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. + *

+ * Three kinds of method, three jobs: + *

+ */ +@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(); + } +} diff --git a/axon-event-sourcing/src/broken/two-tags/MoneyDeposited.java b/axon-event-sourcing/src/broken/two-tags/MoneyDeposited.java new file mode 100644 index 0000000..588de7c --- /dev/null +++ b/axon-event-sourcing/src/broken/two-tags/MoneyDeposited.java @@ -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) { +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/Application.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/Application.java new file mode 100644 index 0000000..319da8c --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/Application.java @@ -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. + *

+ * 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); + } +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/AccountOpened.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/AccountOpened.java new file mode 100644 index 0000000..c47fb0a --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/AccountOpened.java @@ -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=} 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) { +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/BankAccount.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/BankAccount.java new file mode 100644 index 0000000..0ea7fea --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/BankAccount.java @@ -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. + *

+ * Three kinds of method, three jobs: + *

+ */ +@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(); + } +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/Deposit.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/Deposit.java new file mode 100644 index 0000000..a7cdbb1 --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/Deposit.java @@ -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) { +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/MoneyDeposited.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/MoneyDeposited.java new file mode 100644 index 0000000..a8570ab --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/MoneyDeposited.java @@ -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) { +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/MoneyWithdrawn.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/MoneyWithdrawn.java new file mode 100644 index 0000000..826c2c0 --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/MoneyWithdrawn.java @@ -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) { +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/OpenAccount.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/OpenAccount.java new file mode 100644 index 0000000..a1d25ae --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/OpenAccount.java @@ -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) { +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/Withdraw.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/Withdraw.java new file mode 100644 index 0000000..e29b80c --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/domain/Withdraw.java @@ -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) { +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/projection/AccountBalanceProjection.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/projection/AccountBalanceProjection.java new file mode 100644 index 0000000..104ad14 --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/projection/AccountBalanceProjection.java @@ -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. + *

+ * Events reach these methods through a streaming event processor 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); + } +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/projection/AccountBalanceView.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/projection/AccountBalanceView.java new file mode 100644 index 0000000..52e050e --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/projection/AccountBalanceView.java @@ -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) { +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/projection/ProjectionConfig.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/projection/ProjectionConfig.java new file mode 100644 index 0000000..469874a --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/projection/ProjectionConfig.java @@ -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(); + } +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/projection/ReplayService.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/projection/ReplayService.java new file mode 100644 index 0000000..b17da51 --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/projection/ReplayService.java @@ -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); + } +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/web/AccountController.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/web/AccountController.java new file mode 100644 index 0000000..f589203 --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/web/AccountController.java @@ -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> 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 deposit(@PathVariable String id, @RequestParam long amount) { + commands.sendAndWait(new Deposit(id, amount)); + return ack("accountId", id, "deposited", amount); + } + + @PostMapping("/{id}/withdraw") + Map withdraw(@PathVariable String id, @RequestParam long amount) { + commands.sendAndWait(new Withdraw(id, amount)); + return ack("accountId", id, "withdrawn", amount); + } + + @GetMapping("/{id}") + ResponseEntity 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> 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> 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> 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> 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 ack(Object... keysAndValues) { + Map map = new LinkedHashMap<>(); + for (int i = 0; i < keysAndValues.length; i += 2) { + map.put((String) keysAndValues[i], keysAndValues[i + 1]); + } + return map; + } +} diff --git a/axon-event-sourcing/src/main/java/com/ankurm/axondemo/web/ReplayController.java b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/web/ReplayController.java new file mode 100644 index 0000000..9b6ecb6 --- /dev/null +++ b/axon-event-sourcing/src/main/java/com/ankurm/axondemo/web/ReplayController.java @@ -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 replay() throws Exception { + replay.replay(); + return Map.of("status", "replay started"); + } +} diff --git a/axon-event-sourcing/src/main/resources/application.properties b/axon-event-sourcing/src/main/resources/application.properties new file mode 100644 index 0000000..20bf3d1 --- /dev/null +++ b/axon-event-sourcing/src/main/resources/application.properties @@ -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 diff --git a/axon-event-sourcing/src/main/resources/schema.sql b/axon-event-sourcing/src/main/resources/schema.sql new file mode 100644 index 0000000..c184c5a --- /dev/null +++ b/axon-event-sourcing/src/main/resources/schema.sql @@ -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 +); diff --git a/axon-event-sourcing/src/test/java/com/ankurm/axondemo/EventSourcingTranscriptTest.java b/axon-event-sourcing/src/test/java/com/ankurm/axondemo/EventSourcingTranscriptTest.java new file mode 100644 index 0000000..364df9f --- /dev/null +++ b/axon-event-sourcing/src/test/java/com/ankurm/axondemo/EventSourcingTranscriptTest.java @@ -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 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> 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 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 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 overdraft = call("POST", "/accounts/acc-1/withdraw?amount=9999"); + HttpResponse reopen = call("POST", "/accounts/acc-1?owner=Again"); + HttpResponse 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 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 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 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 a1 = call("GET", "/accounts/acc-1"); + HttpResponse 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(); + } +} diff --git a/axon-event-sourcing/src/test/java/com/ankurm/axondemo/Transcript.java b/axon-event-sourcing/src/test/java/com/ankurm/axondemo/Transcript.java new file mode 100644 index 0000000..951fc74 --- /dev/null +++ b/axon-event-sourcing/src/test/java/com/ankurm/axondemo/Transcript.java @@ -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 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); + } + } +} diff --git a/axon-event-sourcing/src/test/java/com/ankurm/axondemo/VariantProbeTest.java b/axon-event-sourcing/src/test/java/com/ankurm/axondemo/VariantProbeTest.java new file mode 100644 index 0000000..acf18a0 --- /dev/null +++ b/axon-event-sourcing/src/test/java/com/ankurm/axondemo/VariantProbeTest.java @@ -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]+", "@")); + } + } +} diff --git a/pom.xml b/pom.xml index 775893b..f77e34c 100644 --- a/pom.xml +++ b/pom.xml @@ -29,5 +29,6 @@ order-fulfillment outbox cqrs + axon-event-sourcing