From dada6361ff3b0bd8ad26b4bb04f063eec81fda27 Mon Sep 17 00:00:00 2001 From: Ankur Date: Sun, 29 Nov 2026 12:53:54 +0530 Subject: [PATCH] Add temporal module: workflows, activities, retries, saga, signals, versioning, Spring Boot starter Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017ic4b5uEyg58znuchZ8C8i --- .gitignore | 1 + README.md | 7 + pom.xml | 22 +++ temporal/.gitignore | 1 + temporal/README.md | 52 ++++++ temporal/output/01-hello-history.txt | 13 ++ temporal/output/02-retries.txt | 19 +++ temporal/output/03-saga-happy-path.txt | 18 ++ temporal/output/04-saga-out-of-stock.txt | 18 ++ temporal/output/05-saga-late-failure.txt | 8 + temporal/output/06-saga-idempotent-retry.txt | 6 + temporal/output/07-saga-no-worker-yet.txt | 6 + temporal/output/08-signals-queries-timers.txt | 17 ++ temporal/output/09-versioning-replay.txt | 40 +++++ temporal/output/10-spring-boot-rest.txt | 15 ++ temporal/output/11-workflow-id-reuse.txt | 9 + temporal/output/12-crash-recovery.txt | 21 +++ temporal/pom.xml | 49 ++++++ temporal/scripts/crash-recovery.sh | 38 +++++ temporal/scripts/dev-server.sh | 4 + temporal/scripts/run-all.sh | 15 ++ .../temporal/TemporalDemoApplication.java | 12 ++ .../temporal/hello/GreetingActivities.java | 10 ++ .../hello/GreetingActivitiesImpl.java | 9 + .../temporal/hello/GreetingWorkflow.java | 12 ++ .../temporal/hello/GreetingWorkflowImpl.java | 18 ++ .../temporal/retry/FlakyRateActivities.java | 33 ++++ .../temporal/retry/RateActivities.java | 10 ++ .../temporal/retry/RateWorkflow.java | 11 ++ .../temporal/retry/RateWorkflowImpl.java | 25 +++ .../workflows/temporal/saga/Ledger.java | 40 +++++ .../temporal/saga/OrderActivities.java | 18 ++ .../temporal/saga/OrderActivitiesImpl.java | 85 ++++++++++ .../workflows/temporal/saga/OrderRequest.java | 4 + .../workflows/temporal/saga/OrderResult.java | 12 ++ .../temporal/saga/OrderSagaWorkflow.java | 11 ++ .../temporal/saga/OrderSagaWorkflowImpl.java | 48 ++++++ .../temporal/signal/ApprovalWorkflow.java | 23 +++ .../temporal/signal/ApprovalWorkflowImpl.java | 40 +++++ .../versioning/FulfilmentActivities.java | 13 ++ .../versioning/FulfilmentActivitiesImpl.java | 19 +++ .../versioning/FulfilmentNaiveV2.java | 20 +++ .../versioning/FulfilmentPatchedV2.java | 22 +++ .../temporal/versioning/FulfilmentV1.java | 19 +++ .../versioning/FulfilmentWorkflow.java | 12 ++ .../temporal/web/ApprovalController.java | 41 +++++ .../temporal/web/OrderController.java | 54 ++++++ .../src/main/resources/application-server.yml | 7 + temporal/src/main/resources/application.yml | 11 ++ .../temporal/ApprovalWorkflowTest.java | 70 ++++++++ .../temporal/GreetingWorkflowTest.java | 41 +++++ .../workflows/temporal/OrderApiTest.java | 55 ++++++ .../workflows/temporal/OrderSagaTest.java | 157 ++++++++++++++++++ .../ankurm/workflows/temporal/RetryTest.java | 82 +++++++++ .../ankurm/workflows/temporal/Transcript.java | 59 +++++++ .../workflows/temporal/VersioningTest.java | 74 +++++++++ 56 files changed, 1556 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 pom.xml create mode 100644 temporal/.gitignore create mode 100644 temporal/README.md create mode 100644 temporal/output/01-hello-history.txt create mode 100644 temporal/output/02-retries.txt create mode 100644 temporal/output/03-saga-happy-path.txt create mode 100644 temporal/output/04-saga-out-of-stock.txt create mode 100644 temporal/output/05-saga-late-failure.txt create mode 100644 temporal/output/06-saga-idempotent-retry.txt create mode 100644 temporal/output/07-saga-no-worker-yet.txt create mode 100644 temporal/output/08-signals-queries-timers.txt create mode 100644 temporal/output/09-versioning-replay.txt create mode 100644 temporal/output/10-spring-boot-rest.txt create mode 100644 temporal/output/11-workflow-id-reuse.txt create mode 100644 temporal/output/12-crash-recovery.txt create mode 100644 temporal/pom.xml create mode 100755 temporal/scripts/crash-recovery.sh create mode 100755 temporal/scripts/dev-server.sh create mode 100755 temporal/scripts/run-all.sh create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/TemporalDemoApplication.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingActivities.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingActivitiesImpl.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingWorkflow.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingWorkflowImpl.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/retry/FlakyRateActivities.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/retry/RateActivities.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/retry/RateWorkflow.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/retry/RateWorkflowImpl.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/saga/Ledger.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderActivities.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderActivitiesImpl.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderRequest.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderResult.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderSagaWorkflow.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderSagaWorkflowImpl.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/signal/ApprovalWorkflow.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/signal/ApprovalWorkflowImpl.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentActivities.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentActivitiesImpl.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentNaiveV2.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentPatchedV2.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentV1.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentWorkflow.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/web/ApprovalController.java create mode 100644 temporal/src/main/java/com/ankurm/workflows/temporal/web/OrderController.java create mode 100644 temporal/src/main/resources/application-server.yml create mode 100644 temporal/src/main/resources/application.yml create mode 100644 temporal/src/test/java/com/ankurm/workflows/temporal/ApprovalWorkflowTest.java create mode 100644 temporal/src/test/java/com/ankurm/workflows/temporal/GreetingWorkflowTest.java create mode 100644 temporal/src/test/java/com/ankurm/workflows/temporal/OrderApiTest.java create mode 100644 temporal/src/test/java/com/ankurm/workflows/temporal/OrderSagaTest.java create mode 100644 temporal/src/test/java/com/ankurm/workflows/temporal/RetryTest.java create mode 100644 temporal/src/test/java/com/ankurm/workflows/temporal/Transcript.java create mode 100644 temporal/src/test/java/com/ankurm/workflows/temporal/VersioningTest.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..bdc7cd9 --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ +# workflow-engines-demo + +Companion code for ankurm.com posts about workflow engines on the JVM. One module per post, one commit per module. + +| Module | Post | What it shows | +|---|---|---| +| [temporal](temporal/) | [Temporal Workflows in Java with Spring Boot](https://ankurm.com/temporal-workflows-java-spring-boot-durable-sagas/) | Workflows, activities, retries, signals, versioning and a saga, tested without a server | diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..4e98c79 --- /dev/null +++ b/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.2.0 + + + com.ankurm.workflows + workflow-engines-demo + 1.0.0 + pom + workflow-engines-demo + + temporal + + + 25 + + diff --git a/temporal/.gitignore b/temporal/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/temporal/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/temporal/README.md b/temporal/README.md new file mode 100644 index 0000000..32dc464 --- /dev/null +++ b/temporal/README.md @@ -0,0 +1,52 @@ +# temporal + +Temporal Java SDK with Spring Boot: a durable order saga, retries, signals/queries/timers, workflow versioning with replay, and a REST layer. Everything runs in-memory via `TestWorkflowEnvironment`; no Temporal server, no Docker. + +| Component | Version (verified on Maven Central, 29 Nov 2026) | +|---|---| +| Temporal Java SDK (`temporal-sdk`, `temporal-testing`, `temporal-spring-boot-starter`) | 1.41.1 | +| Spring Boot | 4.2.0 | +| JDK | Temurin 25.0.5.1 | +| Temporal CLI / dev server (optional) | 1.10.1 (server 1.32.2) | + +## Run + +```bash +export JAVA_HOME=/path/to/jdk-25 +mvn test # regenerates output/01..11 +scripts/run-all.sh # also output/12 when the temporal CLI is on PATH +mvn spring-boot:run # app with the in-memory test server: POST /orders, GET /orders/{id} +``` + +Against a real server: `scripts/dev-server.sh` in one shell, then `mvn spring-boot:run -Dspring-boot.run.profiles=server`. + +## Layout + +| Path | What | +|---|---| +| `hello/` | smallest workflow + activity | +| `retry/` | retry policy, non-retryable failures | +| `saga/` | order saga with compensations, idempotent activities, in-memory `Ledger` | +| `signal/` | signal, query and a 24h timer | +| `versioning/` | V1, a naive V2, a `getVersion`-guarded V2 | +| `web/` | REST controllers using the Spring Boot starter | +| `output/` | captured real output, one file per scenario | + +## Output index + +| File | Scenario | +|---|---| +| `01-hello-history.txt` | event history of the smallest workflow | +| `02-retries.txt` | transient failure, exhausted retries, non-retryable failure | +| `03-saga-happy-path.txt` | saga success and its history | +| `04-saga-out-of-stock.txt` | compensation after the second step fails | +| `05-saga-late-failure.txt` | reverse-order compensation after the third step fails | +| `06-saga-idempotent-retry.txt` | activity retried after its effect already happened | +| `07-saga-no-worker-yet.txt` | workflow started before any worker existed | +| `08-signals-queries-timers.txt` | signal, query, 24h timer skipped by the test server | +| `09-versioning-replay.txt` | replay breaks on a naive change, passes with `getVersion` | +| `10-spring-boot-rest.txt` | REST calls through the Spring Boot starter | +| `11-workflow-id-reuse.txt` | what a second start under the same workflow id does | +| `12-crash-recovery.txt` | `kill -9` the JVM mid-workflow, new JVM finishes it (real dev server) | + +Run ids and the random workflow id in `12` differ between runs. diff --git a/temporal/output/01-hello-history.txt b/temporal/output/01-hello-history.txt new file mode 100644 index 0000000..b2f2753 --- /dev/null +++ b/temporal/output/01-hello-history.txt @@ -0,0 +1,13 @@ +result: Hello, Ankur! +event history of workflow hello-1: + 1 WORKFLOW_EXECUTION_STARTED + 2 WORKFLOW_TASK_SCHEDULED + 3 WORKFLOW_TASK_STARTED + 4 WORKFLOW_TASK_COMPLETED + 5 ACTIVITY_TASK_SCHEDULED ComposeGreeting + 6 ACTIVITY_TASK_STARTED + 7 ACTIVITY_TASK_COMPLETED + 8 WORKFLOW_TASK_SCHEDULED + 9 WORKFLOW_TASK_STARTED + 10 WORKFLOW_TASK_COMPLETED + 11 WORKFLOW_EXECUTION_COMPLETED diff --git a/temporal/output/02-retries.txt b/temporal/output/02-retries.txt new file mode 100644 index 0000000..88b1be9 --- /dev/null +++ b/temporal/output/02-retries.txt @@ -0,0 +1,19 @@ +retry policy: initial 1s, coefficient 2.0, maximum attempts 4 + +== two transient failures, then success == +fetchRate(USD/INR) attempt 1 +fetchRate(USD/INR) attempt 2 +fetchRate(USD/INR) attempt 3 +result: USD/INR=83.21 +workflow history spans 3 s (1 s + 2 s of backoff); wall clock under 5 s: true + +== always failing: attempts exhausted == +fetchRate(USD/INR) attempt 1 +fetchRate(USD/INR) attempt 2 +fetchRate(USD/INR) attempt 3 +fetchRate(USD/INR) attempt 4 +workflow failed: ActivityFailure -> ApplicationFailure: message='503 from rate service', type='java.lang.IllegalStateException', nonRetryable=false + +== non-retryable ApplicationFailure == +fetchRate(USD/INR) attempt 1 +workflow failed: type=UnknownPair nonRetryable=true message=unknown currency pair USD/INR diff --git a/temporal/output/03-saga-happy-path.txt b/temporal/output/03-saga-happy-path.txt new file mode 100644 index 0000000..d0db3b9 --- /dev/null +++ b/temporal/output/03-saga-happy-path.txt @@ -0,0 +1,18 @@ +result: OrderResult[orderId=o-1, status=CONFIRMED, reason=null] +chargePayment o-1 attempt 1: charged 500 +reserveStock o-1 attempt 1: reserved 2 x BOOK-1 +confirmOrder o-1 attempt 1: confirmed, shipping to Mumbai +stock BOOK-1 after: 3 + +event history (workflow tasks hidden): + 1 WORKFLOW_EXECUTION_STARTED + 5 ACTIVITY_TASK_SCHEDULED ChargePayment + 6 ACTIVITY_TASK_STARTED + 7 ACTIVITY_TASK_COMPLETED + 11 ACTIVITY_TASK_SCHEDULED ReserveStock + 12 ACTIVITY_TASK_STARTED + 13 ACTIVITY_TASK_COMPLETED + 17 ACTIVITY_TASK_SCHEDULED ConfirmOrder + 18 ACTIVITY_TASK_STARTED + 19 ACTIVITY_TASK_COMPLETED + 23 WORKFLOW_EXECUTION_COMPLETED diff --git a/temporal/output/04-saga-out-of-stock.txt b/temporal/output/04-saga-out-of-stock.txt new file mode 100644 index 0000000..df3b52c --- /dev/null +++ b/temporal/output/04-saga-out-of-stock.txt @@ -0,0 +1,18 @@ +result: OrderResult[orderId=o-2, status=CANCELLED, reason=OutOfStock] +chargePayment o-2 attempt 1: charged 900 +reserveStock o-2 attempt 1: OUT OF STOCK (1 of LAPTOP-9) +refundPayment o-2 attempt 1: refunded +payment state: REFUNDED + +event history (workflow tasks hidden): + 1 WORKFLOW_EXECUTION_STARTED + 5 ACTIVITY_TASK_SCHEDULED ChargePayment + 6 ACTIVITY_TASK_STARTED + 7 ACTIVITY_TASK_COMPLETED + 11 ACTIVITY_TASK_SCHEDULED ReserveStock + 12 ACTIVITY_TASK_STARTED + 13 ACTIVITY_TASK_FAILED + 17 ACTIVITY_TASK_SCHEDULED RefundPayment + 18 ACTIVITY_TASK_STARTED + 19 ACTIVITY_TASK_COMPLETED + 23 WORKFLOW_EXECUTION_COMPLETED diff --git a/temporal/output/05-saga-late-failure.txt b/temporal/output/05-saga-late-failure.txt new file mode 100644 index 0000000..453717a --- /dev/null +++ b/temporal/output/05-saga-late-failure.txt @@ -0,0 +1,8 @@ +result: OrderResult[orderId=o-3, status=CANCELLED, reason=Unshippable] +chargePayment o-3 attempt 1: charged 100 +reserveStock o-3 attempt 1: reserved 1 x BOOK-1 +confirmOrder o-3 attempt 1: FAILED (cannot ship to NOWHERE) +releaseStock o-3 attempt 1: released 1 +refundPayment o-3 attempt 1: refunded +payment state: REFUNDED +stock BOOK-1 after: 5 diff --git a/temporal/output/06-saga-idempotent-retry.txt b/temporal/output/06-saga-idempotent-retry.txt new file mode 100644 index 0000000..fabf964 --- /dev/null +++ b/temporal/output/06-saga-idempotent-retry.txt @@ -0,0 +1,6 @@ +result: OrderResult[orderId=o-4, status=CONFIRMED, reason=null] +chargePayment o-4 attempt 1: charged 100 +chargePayment o-4 attempt 2: already charged, skipped +reserveStock o-4 attempt 1: reserved 1 x BOOK-1 +confirmOrder o-4 attempt 1: confirmed, shipping to Pune +payments recorded for o-4: CHARGED diff --git a/temporal/output/07-saga-no-worker-yet.txt b/temporal/output/07-saga-no-worker-yet.txt new file mode 100644 index 0000000..5d3985e --- /dev/null +++ b/temporal/output/07-saga-no-worker-yet.txt @@ -0,0 +1,6 @@ +events recorded while no worker was running: [WORKFLOW_EXECUTION_STARTED, WORKFLOW_TASK_SCHEDULED] +journal while no worker was running: [] +after a worker started polling: OrderResult[orderId=o-5, status=CONFIRMED, reason=null] +chargePayment o-5 attempt 1: charged 100 +reserveStock o-5 attempt 1: reserved 1 x BOOK-1 +confirmOrder o-5 attempt 1: confirmed, shipping to Delhi diff --git a/temporal/output/08-signals-queries-timers.txt b/temporal/output/08-signals-queries-timers.txt new file mode 100644 index 0000000..b54affe --- /dev/null +++ b/temporal/output/08-signals-queries-timers.txt @@ -0,0 +1,17 @@ +== signal arrives after 5 minutes == +query while waiting: WAITING +result: req-1: APPROVED by priya +query after: APPROVED by priya + +== nobody answers == +result: req-2: EXPIRED after 24h +workflow clock advanced about 24 hours; wall clock under 5 s: true +query after: EXPIRED + +== rejected with a reason == +result: req-3: REJECTED by rahul (over budget) + +event history of req-3: + 1 WORKFLOW_EXECUTION_STARTED + 3 WORKFLOW_EXECUTION_SIGNALED reject + 6 WORKFLOW_EXECUTION_COMPLETED diff --git a/temporal/output/09-versioning-replay.txt b/temporal/output/09-versioning-replay.txt new file mode 100644 index 0000000..3daa112 --- /dev/null +++ b/temporal/output/09-versioning-replay.txt @@ -0,0 +1,40 @@ +V1 run: result: picked o-9, shipped o-9 +V1 history: + 1 WORKFLOW_EXECUTION_STARTED + 5 ACTIVITY_TASK_SCHEDULED Pick + 6 ACTIVITY_TASK_STARTED + 7 ACTIVITY_TASK_COMPLETED + 11 ACTIVITY_TASK_SCHEDULED Ship + 12 ACTIVITY_TASK_STARTED + 13 ACTIVITY_TASK_COMPLETED + 17 WORKFLOW_EXECUTION_COMPLETED + +== replay the V1 history against V1 code == +OK + +== replay the V1 history against NaiveV2 (new step inserted, no guard) == +java.lang.RuntimeException: query failure for workflow_id: "ful-1" +run_id: "run_id_in_replay" +, queryType=__replay_only, args=Optional.empty, error=io.temporal.worker.NonDeterministicException: [TMPRL1100] Failure handling event 11 of type 'EVENT_TYPE_ACTIVITY_TASK_SCHEDULED' during replay. [TMPRL1100] Command COMMAND_TYPE_SCHEDULE_ACTIVITY_TASK doesn't match event EVENT_TYPE_ACTIVITY_TASK_SCHEDULED with EventId=11 on check activityType with an expected value 'name: "FraudCheck" +' and an actual value 'name: "Ship" +'. {WorkflowTaskStartedEventId=9223372036854775807, CurrentStartedEventId=9} + +== replay the V1 history against PatchedV2 (getVersion guard) == +OK + +== a NEW execution on PatchedV2 == +PatchedV2 run: result: picked o-9, fraud-checked o-9, shipped o-9 +PatchedV2 history: + 1 WORKFLOW_EXECUTION_STARTED + 5 ACTIVITY_TASK_SCHEDULED Pick + 6 ACTIVITY_TASK_STARTED + 7 ACTIVITY_TASK_COMPLETED + 11 MARKER_RECORDED Version + 12 ACTIVITY_TASK_SCHEDULED FraudCheck + 13 ACTIVITY_TASK_STARTED + 14 ACTIVITY_TASK_COMPLETED + 18 ACTIVITY_TASK_SCHEDULED Ship + 19 ACTIVITY_TASK_STARTED + 20 ACTIVITY_TASK_COMPLETED + 24 WORKFLOW_EXECUTION_COMPLETED +replay of its own history: OK diff --git a/temporal/output/10-spring-boot-rest.txt b/temporal/output/10-spring-boot-rest.txt new file mode 100644 index 0000000..a468404 --- /dev/null +++ b/temporal/output/10-spring-boot-rest.txt @@ -0,0 +1,15 @@ +POST /orders {"orderId":"api-1","sku":"BOOK-1","quantity":1,"amount":250,"shipTo":"Navi Mumbai"} +-> {"workflowId":"order-api-1"} +GET /orders/api-1 -> {"orderId":"api-1","status":"CONFIRMED","reason":null} + +POST /orders {"orderId":"api-2","sku":"BOOK-1","quantity":1,"amount":5000,"shipTo":"Navi Mumbai"} +-> {"workflowId":"order-api-2"} +GET /orders/api-2 -> {"orderId":"api-2","status":"CANCELLED","reason":"PaymentDeclined"} + +POST the same order again -> HTTP 409 + +ledger journal: +chargePayment api-1 attempt 1: charged 250 +reserveStock api-1 attempt 1: reserved 1 x BOOK-1 +confirmOrder api-1 attempt 1: confirmed, shipping to Navi Mumbai +chargePayment api-2 attempt 1: DECLINED (amount 5000) diff --git a/temporal/output/11-workflow-id-reuse.txt b/temporal/output/11-workflow-id-reuse.txt new file mode 100644 index 0000000..9db7729 --- /dev/null +++ b/temporal/output/11-workflow-id-reuse.txt @@ -0,0 +1,9 @@ +default policy (ALLOW_DUPLICATE), second start after the first closed: new run id = true +REJECT_DUPLICATE, synchronous call: no exception, returned OrderResult[orderId=o-6, status=CONFIRMED, reason=null]; attached to the latest run = true +REJECT_DUPLICATE, WorkflowClient.start: WorkflowExecutionAlreadyStarted +chargePayment o-6 attempt 1: charged 100 +reserveStock o-6 attempt 1: reserved 1 x BOOK-1 +confirmOrder o-6 attempt 1: confirmed, shipping to Pune +chargePayment o-6 attempt 1: already charged, skipped +reserveStock o-6 attempt 1: already reserved, skipped +confirmOrder o-6 attempt 1: confirmed, shipping to Pune diff --git a/temporal/output/12-crash-recovery.txt b/temporal/output/12-crash-recovery.txt new file mode 100644 index 0000000..bcb2478 --- /dev/null +++ b/temporal/output/12-crash-recovery.txt @@ -0,0 +1,21 @@ +== JVM #1: start the approval workflow == +{"workflowId":"approval-req-29700"} +status query: {"status":"WAITING"} +== kill -9 the JVM (no graceful shutdown) == +app listening on 8099 after kill: 000 +== JVM #2: a brand-new process == +status query: {"status":"WAITING"} +{"signalled":"approve"} +status query: {"status":"APPROVED by priya"} +== temporal workflow show == +1 EVENT_TYPE_WORKFLOW_EXECUTION_STARTED +2 EVENT_TYPE_WORKFLOW_TASK_SCHEDULED +3 EVENT_TYPE_WORKFLOW_TASK_STARTED +4 EVENT_TYPE_WORKFLOW_TASK_COMPLETED +5 EVENT_TYPE_TIMER_STARTED +6 EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED +7 EVENT_TYPE_WORKFLOW_TASK_SCHEDULED +8 EVENT_TYPE_WORKFLOW_TASK_STARTED +9 EVENT_TYPE_WORKFLOW_TASK_COMPLETED +10 EVENT_TYPE_TIMER_CANCELED +11 EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED diff --git a/temporal/pom.xml b/temporal/pom.xml new file mode 100644 index 0000000..d1a2530 --- /dev/null +++ b/temporal/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + com.ankurm.workflows + workflow-engines-demo + 1.0.0 + + temporal + temporal + + 1.41.1 + + + + org.springframework.boot + spring-boot-starter-webmvc + + + io.temporal + temporal-spring-boot-starter + ${temporal.version} + + + io.temporal + temporal-testing + ${temporal.version} + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/temporal/scripts/crash-recovery.sh b/temporal/scripts/crash-recovery.sh new file mode 100755 index 0000000..20dc6a7 --- /dev/null +++ b/temporal/scripts/crash-recovery.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Kill the whole JVM while a workflow is waiting, start a new one, and finish the workflow. +# Needs: a Temporal dev server on 127.0.0.1:7233 (scripts/dev-server.sh), JDK 25, Maven. +set -euo pipefail +cd "$(dirname "$0")/.." +mkdir -p output +OUT=output/12-crash-recovery.txt +JAR=target/temporal-1.0.0.jar +[ -f "$JAR" ] || mvn -B -q -DskipTests package +ID="req-$RANDOM" +start_app() { + java -jar "$JAR" --spring.profiles.active=server --server.port=8099 > "/tmp/app-$1.log" 2>&1 & + echo $! > /tmp/app.pid + for i in $(seq 1 60); do curl -s -o /dev/null localhost:8099/ && break || sleep 1; done +} +{ + echo "== JVM #1: start the approval workflow ==" + start_app 1 + curl -s -X POST localhost:8099/approvals/$ID; echo + echo "status query: $(curl -s localhost:8099/approvals/$ID)" + echo "== kill -9 the JVM (no graceful shutdown) ==" + kill -9 "$(cat /tmp/app.pid)"; wait "$(cat /tmp/app.pid)" 2>/dev/null || true + echo "app listening on 8099 after kill: $(curl -s -o /dev/null -w '%{http_code}' localhost:8099/approvals/$ID || true)" + echo "== JVM #2: a brand-new process ==" + start_app 2 + echo "status query: $(curl -s localhost:8099/approvals/$ID)" + curl -s -X POST "localhost:8099/approvals/$ID/approve?by=priya"; echo + sleep 1 + echo "status query: $(curl -s localhost:8099/approvals/$ID)" + kill "$(cat /tmp/app.pid)"; wait "$(cat /tmp/app.pid)" 2>/dev/null || true + if command -v temporal >/dev/null; then + echo "== temporal workflow show ==" + temporal workflow show --workflow-id "approval-$ID" --output json | python3 -c ' +import json,sys +for e in json.load(sys.stdin)["events"]: + print(e["eventId"], e["eventType"])' + fi +} 2>&1 | tee "$OUT" diff --git a/temporal/scripts/dev-server.sh b/temporal/scripts/dev-server.sh new file mode 100755 index 0000000..15daa30 --- /dev/null +++ b/temporal/scripts/dev-server.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# Optional: run the same app against a real Temporal dev server (needs the temporal CLI on PATH). +set -euo pipefail +temporal server start-dev --headless --port 7233 --db-filename /tmp/temporal-dev.db diff --git a/temporal/scripts/run-all.sh b/temporal/scripts/run-all.sh new file mode 100755 index 0000000..bc964c9 --- /dev/null +++ b/temporal/scripts/run-all.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Regenerates every file in output/. Needs JDK 25 and Maven. Step 2 is optional (real Temporal dev server). +set -euo pipefail +cd "$(dirname "$0")/.." +echo "1/2 tests against the in-memory test server -> output/01..11" +mvn -B -q verify +if command -v temporal >/dev/null; then + echo "2/2 crash recovery against a real dev server -> output/12" + (temporal server start-dev --headless --port 7233 --db-filename /tmp/temporal-dev.db >/tmp/temporal-dev.log 2>&1 &) + sleep 8 + bash scripts/crash-recovery.sh + pkill -x temporal || true +else + echo "2/2 skipped: temporal CLI not on PATH" +fi diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/TemporalDemoApplication.java b/temporal/src/main/java/com/ankurm/workflows/temporal/TemporalDemoApplication.java new file mode 100644 index 0000000..26085a8 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/TemporalDemoApplication.java @@ -0,0 +1,12 @@ +package com.ankurm.workflows.temporal; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TemporalDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(TemporalDemoApplication.class, args); + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingActivities.java b/temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingActivities.java new file mode 100644 index 0000000..4411a15 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingActivities.java @@ -0,0 +1,10 @@ +package com.ankurm.workflows.temporal.hello; + +import io.temporal.activity.ActivityInterface; + +/** Activities are where side effects live: HTTP calls, database writes, anything non-deterministic. */ +@ActivityInterface +public interface GreetingActivities { + + String composeGreeting(String name); +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingActivitiesImpl.java b/temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingActivitiesImpl.java new file mode 100644 index 0000000..1c83227 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingActivitiesImpl.java @@ -0,0 +1,9 @@ +package com.ankurm.workflows.temporal.hello; + +public class GreetingActivitiesImpl implements GreetingActivities { + + @Override + public String composeGreeting(String name) { + return "Hello, " + name + "!"; + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingWorkflow.java b/temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingWorkflow.java new file mode 100644 index 0000000..7207bf9 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingWorkflow.java @@ -0,0 +1,12 @@ +package com.ankurm.workflows.temporal.hello; + +import io.temporal.workflow.WorkflowInterface; +import io.temporal.workflow.WorkflowMethod; + +/** The smallest possible workflow: one method, one activity call. */ +@WorkflowInterface +public interface GreetingWorkflow { + + @WorkflowMethod + String greet(String name); +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingWorkflowImpl.java b/temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingWorkflowImpl.java new file mode 100644 index 0000000..3566e10 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/hello/GreetingWorkflowImpl.java @@ -0,0 +1,18 @@ +package com.ankurm.workflows.temporal.hello; + +import io.temporal.activity.ActivityOptions; +import io.temporal.workflow.Workflow; +import java.time.Duration; + +public class GreetingWorkflowImpl implements GreetingWorkflow { + + // A stub: calling a method on it does not run the code here, it schedules an activity task. + private final GreetingActivities activities = Workflow.newActivityStub( + GreetingActivities.class, + ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(5)).build()); + + @Override + public String greet(String name) { + return activities.composeGreeting(name); + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/retry/FlakyRateActivities.java b/temporal/src/main/java/com/ankurm/workflows/temporal/retry/FlakyRateActivities.java new file mode 100644 index 0000000..6a6d4ef --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/retry/FlakyRateActivities.java @@ -0,0 +1,33 @@ +package com.ankurm.workflows.temporal.retry; + +import io.temporal.activity.Activity; +import io.temporal.failure.ApplicationFailure; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** Fails with a transient error for the first {@code failFirst} attempts, then succeeds. */ +public class FlakyRateActivities implements RateActivities { + + private final int failFirst; + private final boolean permanent; + public final List attempts = new CopyOnWriteArrayList<>(); + + public FlakyRateActivities(int failFirst, boolean permanent) { + this.failFirst = failFirst; + this.permanent = permanent; + } + + @Override + public String fetchRate(String pair) { + int attempt = Activity.getExecutionContext().getInfo().getAttempt(); + attempts.add("fetchRate(" + pair + ") attempt " + attempt); + if (permanent) { + // A business error: retrying will never help, so tell Temporal not to. + throw ApplicationFailure.newNonRetryableFailure("unknown currency pair " + pair, "UnknownPair"); + } + if (attempt <= failFirst) { + throw new IllegalStateException("503 from rate service"); + } + return pair + "=83.21"; + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/retry/RateActivities.java b/temporal/src/main/java/com/ankurm/workflows/temporal/retry/RateActivities.java new file mode 100644 index 0000000..7808cc1 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/retry/RateActivities.java @@ -0,0 +1,10 @@ +package com.ankurm.workflows.temporal.retry; + +import io.temporal.activity.ActivityInterface; + +@ActivityInterface +public interface RateActivities { + + /** Fetch an exchange rate from a (simulated) remote service. */ + String fetchRate(String pair); +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/retry/RateWorkflow.java b/temporal/src/main/java/com/ankurm/workflows/temporal/retry/RateWorkflow.java new file mode 100644 index 0000000..50974a2 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/retry/RateWorkflow.java @@ -0,0 +1,11 @@ +package com.ankurm.workflows.temporal.retry; + +import io.temporal.workflow.WorkflowInterface; +import io.temporal.workflow.WorkflowMethod; + +@WorkflowInterface +public interface RateWorkflow { + + @WorkflowMethod + String lookup(String pair); +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/retry/RateWorkflowImpl.java b/temporal/src/main/java/com/ankurm/workflows/temporal/retry/RateWorkflowImpl.java new file mode 100644 index 0000000..ab1aea8 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/retry/RateWorkflowImpl.java @@ -0,0 +1,25 @@ +package com.ankurm.workflows.temporal.retry; + +import io.temporal.activity.ActivityOptions; +import io.temporal.common.RetryOptions; +import io.temporal.workflow.Workflow; +import java.time.Duration; + +public class RateWorkflowImpl implements RateWorkflow { + + private final RateActivities activities = Workflow.newActivityStub( + RateActivities.class, + ActivityOptions.newBuilder() + .setStartToCloseTimeout(Duration.ofSeconds(5)) + .setRetryOptions(RetryOptions.newBuilder() + .setInitialInterval(Duration.ofSeconds(1)) + .setBackoffCoefficient(2.0) + .setMaximumAttempts(4) + .build()) + .build()); + + @Override + public String lookup(String pair) { + return activities.fetchRate(pair); + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/saga/Ledger.java b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/Ledger.java new file mode 100644 index 0000000..5535313 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/Ledger.java @@ -0,0 +1,40 @@ +package com.ankurm.workflows.temporal.saga; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import org.springframework.stereotype.Component; + +/** + * The "database" behind the activities: payments, stock and an ordered journal of everything + * that actually happened. It is in memory so the demo runs anywhere; the journal is what the + * captured transcripts print. + */ +@Component +public class Ledger { + + public final Map payments = new ConcurrentHashMap<>(); + public final Map reservations = new ConcurrentHashMap<>(); + public final Map orders = new ConcurrentHashMap<>(); + public final Map stock = new ConcurrentHashMap<>(Map.of("BOOK-1", 5, "LAPTOP-9", 1)); + /** Orders whose first charge attempt records the payment and then "loses the connection". */ + public final Set crashAfterChargeOnce = ConcurrentHashMap.newKeySet(); + private final List journal = Collections.synchronizedList(new ArrayList<>()); + + public void log(String line) { + journal.add(line); + } + + public List journal() { + synchronized (journal) { + return new ArrayList<>(journal); + } + } + + public void clearJournal() { + journal.clear(); + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderActivities.java b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderActivities.java new file mode 100644 index 0000000..2107e54 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderActivities.java @@ -0,0 +1,18 @@ +package com.ankurm.workflows.temporal.saga; + +import io.temporal.activity.ActivityInterface; + +/** One local transaction per method, plus the compensation that undoes it. */ +@ActivityInterface +public interface OrderActivities { + + void chargePayment(String orderId, long amount); + + void refundPayment(String orderId); + + void reserveStock(String orderId, String sku, int quantity); + + void releaseStock(String orderId); + + void confirmOrder(String orderId, String shipTo); +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderActivitiesImpl.java b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderActivitiesImpl.java new file mode 100644 index 0000000..1d8d4dd --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderActivitiesImpl.java @@ -0,0 +1,85 @@ +package com.ankurm.workflows.temporal.saga; + +import io.temporal.activity.Activity; +import io.temporal.failure.ApplicationFailure; +import io.temporal.spring.boot.ActivityImpl; +import org.springframework.stereotype.Component; + +/** + * Every method is idempotent on orderId. Temporal guarantees activities run at least once, not + * exactly once, so a retry after "the work happened but the ack was lost" must be harmless. + */ +@Component +@ActivityImpl(taskQueues = OrderActivitiesImpl.TASK_QUEUE) +public class OrderActivitiesImpl implements OrderActivities { + + public static final String TASK_QUEUE = "orders"; + + private final Ledger ledger; + + public OrderActivitiesImpl(Ledger ledger) { + this.ledger = ledger; + } + + private static int attempt() { + return Activity.getExecutionContext().getInfo().getAttempt(); + } + + @Override + public void chargePayment(String orderId, long amount) { + int attempt = attempt(); + if (amount > 1000) { + ledger.log("chargePayment " + orderId + " attempt " + attempt + ": DECLINED (amount " + amount + ")"); + throw ApplicationFailure.newNonRetryableFailure("card declined for " + orderId, "PaymentDeclined"); + } + if (ledger.payments.putIfAbsent(orderId, "CHARGED") == null) { + ledger.log("chargePayment " + orderId + " attempt " + attempt + ": charged " + amount); + } else { + ledger.log("chargePayment " + orderId + " attempt " + attempt + ": already charged, skipped"); + } + if (attempt == 1 && ledger.crashAfterChargeOnce.contains(orderId)) { + throw new IllegalStateException("connection reset after the charge went through"); + } + } + + @Override + public void refundPayment(String orderId) { + ledger.payments.computeIfPresent(orderId, (k, v) -> "REFUNDED"); + ledger.log("refundPayment " + orderId + " attempt " + attempt() + ": refunded"); + } + + @Override + public void reserveStock(String orderId, String sku, int quantity) { + int available = ledger.stock.getOrDefault(sku, 0); + if (ledger.reservations.containsKey(orderId)) { + ledger.log("reserveStock " + orderId + " attempt " + attempt() + ": already reserved, skipped"); + return; + } + if (available < quantity) { + ledger.log("reserveStock " + orderId + " attempt " + attempt() + ": OUT OF STOCK (" + available + " of " + sku + ")"); + throw ApplicationFailure.newNonRetryableFailure("not enough " + sku, "OutOfStock"); + } + ledger.stock.merge(sku, -quantity, Integer::sum); + ledger.reservations.put(orderId, quantity); + ledger.log("reserveStock " + orderId + " attempt " + attempt() + ": reserved " + quantity + " x " + sku); + } + + @Override + public void releaseStock(String orderId) { + Integer qty = ledger.reservations.remove(orderId); + if (qty != null) { + ledger.stock.merge("BOOK-1", qty, Integer::sum); + } + ledger.log("releaseStock " + orderId + " attempt " + attempt() + ": released " + (qty == null ? 0 : qty)); + } + + @Override + public void confirmOrder(String orderId, String shipTo) { + if ("NOWHERE".equals(shipTo)) { + ledger.log("confirmOrder " + orderId + " attempt " + attempt() + ": FAILED (cannot ship to " + shipTo + ")"); + throw ApplicationFailure.newNonRetryableFailure("cannot ship to " + shipTo, "Unshippable"); + } + ledger.orders.put(orderId, "CONFIRMED"); + ledger.log("confirmOrder " + orderId + " attempt " + attempt() + ": confirmed, shipping to " + shipTo); + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderRequest.java b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderRequest.java new file mode 100644 index 0000000..dd28379 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderRequest.java @@ -0,0 +1,4 @@ +package com.ankurm.workflows.temporal.saga; + +public record OrderRequest(String orderId, String sku, int quantity, long amount, String shipTo) { +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderResult.java b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderResult.java new file mode 100644 index 0000000..0ca8467 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderResult.java @@ -0,0 +1,12 @@ +package com.ankurm.workflows.temporal.saga; + +public record OrderResult(String orderId, String status, String reason) { + + public static OrderResult confirmed(String orderId) { + return new OrderResult(orderId, "CONFIRMED", null); + } + + public static OrderResult cancelled(String orderId, String reason) { + return new OrderResult(orderId, "CANCELLED", reason); + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderSagaWorkflow.java b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderSagaWorkflow.java new file mode 100644 index 0000000..6f136f8 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderSagaWorkflow.java @@ -0,0 +1,11 @@ +package com.ankurm.workflows.temporal.saga; + +import io.temporal.workflow.WorkflowInterface; +import io.temporal.workflow.WorkflowMethod; + +@WorkflowInterface +public interface OrderSagaWorkflow { + + @WorkflowMethod + OrderResult placeOrder(OrderRequest request); +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderSagaWorkflowImpl.java b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderSagaWorkflowImpl.java new file mode 100644 index 0000000..f31d67c --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/saga/OrderSagaWorkflowImpl.java @@ -0,0 +1,48 @@ +package com.ankurm.workflows.temporal.saga; + +import io.temporal.activity.ActivityOptions; +import io.temporal.common.RetryOptions; +import io.temporal.failure.ActivityFailure; +import io.temporal.failure.ApplicationFailure; +import io.temporal.spring.boot.WorkflowImpl; +import io.temporal.workflow.Saga; +import io.temporal.workflow.Workflow; +import java.time.Duration; + +/** + * The whole saga is this one method. The "state machine" is the program counter, and Temporal + * persists it by recording each activity result in the workflow's event history. + */ +@WorkflowImpl(taskQueues = OrderActivitiesImpl.TASK_QUEUE) +public class OrderSagaWorkflowImpl implements OrderSagaWorkflow { + + private final OrderActivities activities = Workflow.newActivityStub( + OrderActivities.class, + ActivityOptions.newBuilder() + .setStartToCloseTimeout(Duration.ofSeconds(5)) + .setRetryOptions(RetryOptions.newBuilder() + .setInitialInterval(Duration.ofSeconds(1)) + .setMaximumAttempts(3) + .build()) + .build()); + + @Override + public OrderResult placeOrder(OrderRequest r) { + Saga saga = new Saga(new Saga.Options.Builder().setParallelCompensation(false).build()); + try { + activities.chargePayment(r.orderId(), r.amount()); + saga.addCompensation(activities::refundPayment, r.orderId()); + + activities.reserveStock(r.orderId(), r.sku(), r.quantity()); + saga.addCompensation(activities::releaseStock, r.orderId()); + + activities.confirmOrder(r.orderId(), r.shipTo()); + return OrderResult.confirmed(r.orderId()); + } catch (ActivityFailure failure) { + // Compensations run in reverse order of registration. + saga.compensate(); + String type = failure.getCause() instanceof ApplicationFailure af ? af.getType() : "Unknown"; + return OrderResult.cancelled(r.orderId(), type); + } + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/signal/ApprovalWorkflow.java b/temporal/src/main/java/com/ankurm/workflows/temporal/signal/ApprovalWorkflow.java new file mode 100644 index 0000000..410be5e --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/signal/ApprovalWorkflow.java @@ -0,0 +1,23 @@ +package com.ankurm.workflows.temporal.signal; + +import io.temporal.workflow.QueryMethod; +import io.temporal.workflow.SignalMethod; +import io.temporal.workflow.WorkflowInterface; +import io.temporal.workflow.WorkflowMethod; + +/** A long-lived workflow that waits for a human. Signals write state; queries read it. */ +@WorkflowInterface +public interface ApprovalWorkflow { + + @WorkflowMethod + String awaitDecision(String requestId); + + @SignalMethod + void approve(String by); + + @SignalMethod + void reject(String by, String reason); + + @QueryMethod + String status(); +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/signal/ApprovalWorkflowImpl.java b/temporal/src/main/java/com/ankurm/workflows/temporal/signal/ApprovalWorkflowImpl.java new file mode 100644 index 0000000..fb114c9 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/signal/ApprovalWorkflowImpl.java @@ -0,0 +1,40 @@ +package com.ankurm.workflows.temporal.signal; + +import io.temporal.spring.boot.WorkflowImpl; +import io.temporal.workflow.Workflow; +import java.time.Duration; + +@WorkflowImpl(taskQueues = "orders") +public class ApprovalWorkflowImpl implements ApprovalWorkflow { + + private String decision; // set by a signal + private String status = "WAITING"; + + @Override + public String awaitDecision(String requestId) { + // Blocks for up to 24 hours of *workflow* time. No thread is held and no worker needs to stay up: + // the wait is a durable timer on the server. + boolean decided = Workflow.await(Duration.ofHours(24), () -> decision != null); + if (!decided) { + status = "EXPIRED"; + return requestId + ": EXPIRED after 24h"; + } + status = decision; + return requestId + ": " + decision; + } + + @Override + public void approve(String by) { + decision = "APPROVED by " + by; + } + + @Override + public void reject(String by, String reason) { + decision = "REJECTED by " + by + " (" + reason + ")"; + } + + @Override + public String status() { + return status; + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentActivities.java b/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentActivities.java new file mode 100644 index 0000000..415ed4b --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentActivities.java @@ -0,0 +1,13 @@ +package com.ankurm.workflows.temporal.versioning; + +import io.temporal.activity.ActivityInterface; + +@ActivityInterface +public interface FulfilmentActivities { + + String pick(String orderId); + + String fraudCheck(String orderId); + + String ship(String orderId); +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentActivitiesImpl.java b/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentActivitiesImpl.java new file mode 100644 index 0000000..4ffdad1 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentActivitiesImpl.java @@ -0,0 +1,19 @@ +package com.ankurm.workflows.temporal.versioning; + +public class FulfilmentActivitiesImpl implements FulfilmentActivities { + + @Override + public String pick(String orderId) { + return "picked " + orderId; + } + + @Override + public String fraudCheck(String orderId) { + return "fraud-checked " + orderId; + } + + @Override + public String ship(String orderId) { + return "shipped " + orderId; + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentNaiveV2.java b/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentNaiveV2.java new file mode 100644 index 0000000..00dc90a --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentNaiveV2.java @@ -0,0 +1,20 @@ +package com.ankurm.workflows.temporal.versioning; + +import io.temporal.activity.ActivityOptions; +import io.temporal.workflow.Workflow; +import java.time.Duration; + +/** Generation 2, done the tempting way: just insert the new step. Breaks every execution already in flight. */ +public class FulfilmentNaiveV2 implements FulfilmentWorkflow { + + private final FulfilmentActivities act = Workflow.newActivityStub(FulfilmentActivities.class, + ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(5)).build()); + + @Override + public String fulfil(String orderId) { + String a = act.pick(orderId); + String f = act.fraudCheck(orderId); + String b = act.ship(orderId); + return a + ", " + f + ", " + b; + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentPatchedV2.java b/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentPatchedV2.java new file mode 100644 index 0000000..ada2d91 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentPatchedV2.java @@ -0,0 +1,22 @@ +package com.ankurm.workflows.temporal.versioning; + +import io.temporal.activity.ActivityOptions; +import io.temporal.workflow.Workflow; +import java.time.Duration; + +/** Generation 2, done safely: the new step is guarded by Workflow.getVersion. */ +public class FulfilmentPatchedV2 implements FulfilmentWorkflow { + + private final FulfilmentActivities act = Workflow.newActivityStub(FulfilmentActivities.class, + ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(5)).build()); + + @Override + public String fulfil(String orderId) { + String a = act.pick(orderId); + // DEFAULT_VERSION (-1) is what histories recorded before this line existed will see. + int version = Workflow.getVersion("add-fraud-check", Workflow.DEFAULT_VERSION, 1); + String f = version == 1 ? act.fraudCheck(orderId) : "no fraud check"; + String b = act.ship(orderId); + return version == 1 ? a + ", " + f + ", " + b : a + ", " + b; + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentV1.java b/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentV1.java new file mode 100644 index 0000000..bdf69f8 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentV1.java @@ -0,0 +1,19 @@ +package com.ankurm.workflows.temporal.versioning; + +import io.temporal.activity.ActivityOptions; +import io.temporal.workflow.Workflow; +import java.time.Duration; + +/** Generation 1: what is deployed when the orders in flight are started. */ +public class FulfilmentV1 implements FulfilmentWorkflow { + + private final FulfilmentActivities act = Workflow.newActivityStub(FulfilmentActivities.class, + ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(5)).build()); + + @Override + public String fulfil(String orderId) { + String a = act.pick(orderId); + String b = act.ship(orderId); + return a + ", " + b; + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentWorkflow.java b/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentWorkflow.java new file mode 100644 index 0000000..974294a --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/versioning/FulfilmentWorkflow.java @@ -0,0 +1,12 @@ +package com.ankurm.workflows.temporal.versioning; + +import io.temporal.workflow.WorkflowInterface; +import io.temporal.workflow.WorkflowMethod; + +/** One workflow type name, three generations of implementation. */ +@WorkflowInterface +public interface FulfilmentWorkflow { + + @WorkflowMethod(name = "Fulfilment") + String fulfil(String orderId); +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/web/ApprovalController.java b/temporal/src/main/java/com/ankurm/workflows/temporal/web/ApprovalController.java new file mode 100644 index 0000000..17534db --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/web/ApprovalController.java @@ -0,0 +1,41 @@ +package com.ankurm.workflows.temporal.web; + +import com.ankurm.workflows.temporal.signal.ApprovalWorkflow; +import io.temporal.client.WorkflowClient; +import io.temporal.client.WorkflowOptions; +import java.util.Map; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** Starts a long-lived approval workflow, signals it, and queries it. */ +@RestController +public class ApprovalController { + + private final WorkflowClient client; + + public ApprovalController(WorkflowClient client) { + this.client = client; + } + + @PostMapping("/approvals/{id}") + public Map start(@PathVariable String id) { + ApprovalWorkflow wf = client.newWorkflowStub(ApprovalWorkflow.class, + WorkflowOptions.newBuilder().setTaskQueue("orders").setWorkflowId("approval-" + id).build()); + WorkflowClient.start(wf::awaitDecision, id); + return Map.of("workflowId", "approval-" + id); + } + + @PostMapping("/approvals/{id}/approve") + public Map approve(@PathVariable String id, @RequestParam String by) { + client.newWorkflowStub(ApprovalWorkflow.class, "approval-" + id).approve(by); + return Map.of("signalled", "approve"); + } + + @GetMapping("/approvals/{id}") + public Map status(@PathVariable String id) { + return Map.of("status", client.newWorkflowStub(ApprovalWorkflow.class, "approval-" + id).status()); + } +} diff --git a/temporal/src/main/java/com/ankurm/workflows/temporal/web/OrderController.java b/temporal/src/main/java/com/ankurm/workflows/temporal/web/OrderController.java new file mode 100644 index 0000000..ba6e377 --- /dev/null +++ b/temporal/src/main/java/com/ankurm/workflows/temporal/web/OrderController.java @@ -0,0 +1,54 @@ +package com.ankurm.workflows.temporal.web; + +import com.ankurm.workflows.temporal.saga.OrderActivitiesImpl; +import com.ankurm.workflows.temporal.saga.OrderRequest; +import com.ankurm.workflows.temporal.saga.OrderResult; +import com.ankurm.workflows.temporal.saga.OrderSagaWorkflow; +import io.temporal.client.WorkflowClient; +import io.temporal.client.WorkflowOptions; +import io.temporal.client.WorkflowExecutionAlreadyStarted; +import io.temporal.client.WorkflowStub; +import io.temporal.api.enums.v1.WorkflowIdReusePolicy; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class OrderController { + + private final WorkflowClient client; + + public OrderController(WorkflowClient client) { + this.client = client; + } + + /** Starts the saga and returns immediately; the workflow id is the order id, so a retried POST cannot start twice. */ + @PostMapping("/orders") + public ResponseEntity> place(@RequestBody OrderRequest request) { + OrderSagaWorkflow workflow = client.newWorkflowStub(OrderSagaWorkflow.class, + WorkflowOptions.newBuilder() + .setTaskQueue(OrderActivitiesImpl.TASK_QUEUE) + .setWorkflowId("order-" + request.orderId()) + // The default policy would allow a second run once the first has closed. + .setWorkflowIdReusePolicy(WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE) + .build()); + try { + WorkflowClient.start(workflow::placeOrder, request); + } catch (WorkflowExecutionAlreadyStarted e) { + return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("error", "order already submitted")); + } + return ResponseEntity.ok(Map.of("workflowId", "order-" + request.orderId())); + } + + @GetMapping("/orders/{orderId}") + public OrderResult result(@PathVariable String orderId) throws Exception { + WorkflowStub stub = client.newUntypedWorkflowStub("order-" + orderId); + return stub.getResult(30, TimeUnit.SECONDS, OrderResult.class); + } +} diff --git a/temporal/src/main/resources/application-server.yml b/temporal/src/main/resources/application-server.yml new file mode 100644 index 0000000..a1740f8 --- /dev/null +++ b/temporal/src/main/resources/application-server.yml @@ -0,0 +1,7 @@ +spring: + temporal: + test-server: + enabled: false + connection: + target: 127.0.0.1:7233 + namespace: default diff --git a/temporal/src/main/resources/application.yml b/temporal/src/main/resources/application.yml new file mode 100644 index 0000000..814705b --- /dev/null +++ b/temporal/src/main/resources/application.yml @@ -0,0 +1,11 @@ +spring: + application: + name: temporal-demo + temporal: + # In-memory Temporal test server: no Docker, no temporal CLI. Switch to the "server" profile for a real one. + test-server: + enabled: true + workers-auto-discovery: + packages: + - com.ankurm.workflows.temporal.saga + - com.ankurm.workflows.temporal.signal diff --git a/temporal/src/test/java/com/ankurm/workflows/temporal/ApprovalWorkflowTest.java b/temporal/src/test/java/com/ankurm/workflows/temporal/ApprovalWorkflowTest.java new file mode 100644 index 0000000..6916453 --- /dev/null +++ b/temporal/src/test/java/com/ankurm/workflows/temporal/ApprovalWorkflowTest.java @@ -0,0 +1,70 @@ +package com.ankurm.workflows.temporal; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.ankurm.workflows.temporal.signal.ApprovalWorkflow; +import com.ankurm.workflows.temporal.signal.ApprovalWorkflowImpl; +import io.temporal.client.WorkflowClient; +import io.temporal.client.WorkflowOptions; +import io.temporal.testing.TestWorkflowEnvironment; +import io.temporal.worker.Worker; +import java.time.Duration; +import org.junit.jupiter.api.Test; + +class ApprovalWorkflowTest { + + @Test + void signalsQueriesAndADayLongTimer() { + TestWorkflowEnvironment env = TestWorkflowEnvironment.newInstance(); + try { + Worker worker = env.newWorker("approvals"); + worker.registerWorkflowImplementationTypes(ApprovalWorkflowImpl.class); + env.start(); + WorkflowClient client = env.getWorkflowClient(); + Transcript t = new Transcript("08-signals-queries-timers.txt"); + + // 1. approved by signal + ApprovalWorkflow a = client.newWorkflowStub(ApprovalWorkflow.class, + WorkflowOptions.newBuilder().setTaskQueue("approvals").setWorkflowId("req-1").build()); + WorkflowClient.start(a::awaitDecision, "req-1"); + env.sleep(Duration.ofMinutes(5)); + String before = a.status(); + a.approve("priya"); + String result = client.newUntypedWorkflowStub("req-1").getResult(String.class); + t.line("== signal arrives after 5 minutes =="); + t.line("query while waiting: " + before); + t.line("result: " + result); + t.line("query after: " + a.status()); + assertEquals("WAITING", before); + + // 2. nobody answers: the 24h timer fires + ApprovalWorkflow b = client.newWorkflowStub(ApprovalWorkflow.class, + WorkflowOptions.newBuilder().setTaskQueue("approvals").setWorkflowId("req-2").build()); + long wfStart = env.currentTimeMillis(); + long wall = System.nanoTime(); + String expired = b.awaitDecision("req-2"); + long workflowHours = (env.currentTimeMillis() - wfStart) / 3_600_000; + long wallMs = (System.nanoTime() - wall) / 1_000_000; + t.line("").line("== nobody answers =="); + t.line("result: " + expired); + t.line("workflow clock advanced about " + workflowHours + " hours; wall clock under 5 s: " + (wallMs < 5000)); + t.line("query after: " + b.status()); + + // 3. reject carries two arguments + ApprovalWorkflow c = client.newWorkflowStub(ApprovalWorkflow.class, + WorkflowOptions.newBuilder().setTaskQueue("approvals").setWorkflowId("req-3").build()); + WorkflowClient.start(c::awaitDecision, "req-3"); + c.reject("rahul", "over budget"); + String rejected = client.newUntypedWorkflowStub("req-3").getResult(String.class); + t.line("").line("== rejected with a reason ==").line("result: " + rejected); + t.line("").line("event history of req-3:").history(client.fetchHistory("req-3"), true); + t.write(); + + assertEquals("req-1: APPROVED by priya", result); + assertEquals("req-2: EXPIRED after 24h", expired); + assertEquals(24, workflowHours); + } finally { + env.close(); + } + } +} diff --git a/temporal/src/test/java/com/ankurm/workflows/temporal/GreetingWorkflowTest.java b/temporal/src/test/java/com/ankurm/workflows/temporal/GreetingWorkflowTest.java new file mode 100644 index 0000000..a0c9629 --- /dev/null +++ b/temporal/src/test/java/com/ankurm/workflows/temporal/GreetingWorkflowTest.java @@ -0,0 +1,41 @@ +package com.ankurm.workflows.temporal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.ankurm.workflows.temporal.hello.GreetingActivitiesImpl; +import com.ankurm.workflows.temporal.hello.GreetingWorkflow; +import com.ankurm.workflows.temporal.hello.GreetingWorkflowImpl; +import io.temporal.client.WorkflowClient; +import io.temporal.common.WorkflowExecutionHistory; +import io.temporal.client.WorkflowOptions; +import io.temporal.testing.TestWorkflowEnvironment; +import io.temporal.worker.Worker; +import org.junit.jupiter.api.Test; + +class GreetingWorkflowTest { + + @Test + void helloWorkflowAndItsHistory() { + TestWorkflowEnvironment env = TestWorkflowEnvironment.newInstance(); + try { + Worker worker = env.newWorker("hello"); + worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class); + worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); + env.start(); + + WorkflowClient client = env.getWorkflowClient(); + GreetingWorkflow wf = client.newWorkflowStub(GreetingWorkflow.class, + WorkflowOptions.newBuilder().setTaskQueue("hello").setWorkflowId("hello-1").build()); + String result = wf.greet("Ankur"); + assertEquals("Hello, Ankur!", result); + + WorkflowExecutionHistory history = client.fetchHistory("hello-1"); + Transcript t = new Transcript("01-hello-history.txt"); + t.line("result: " + result).line("event history of workflow hello-1:").history(history, false).write(); + assertTrue(history.getEvents().stream().anyMatch(e -> e.hasActivityTaskCompletedEventAttributes())); + } finally { + env.close(); + } + } +} diff --git a/temporal/src/test/java/com/ankurm/workflows/temporal/OrderApiTest.java b/temporal/src/test/java/com/ankurm/workflows/temporal/OrderApiTest.java new file mode 100644 index 0000000..4b50c8c --- /dev/null +++ b/temporal/src/test/java/com/ankurm/workflows/temporal/OrderApiTest.java @@ -0,0 +1,55 @@ +package com.ankurm.workflows.temporal; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.ankurm.workflows.temporal.saga.Ledger; +import io.temporal.client.WorkflowClient; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +/** The Temporal Spring Boot starter in test-server mode: workers, client and REST layer in one context. */ +@SpringBootTest +@AutoConfigureMockMvc +class OrderApiTest { + + @Autowired MockMvc mvc; + @Autowired Ledger ledger; + @Autowired WorkflowClient client; + + @Test + void restCallStartsTheSagaAndPollsItsResult() throws Exception { + Transcript t = new Transcript("10-spring-boot-rest.txt"); + String ok = "{\"orderId\":\"api-1\",\"sku\":\"BOOK-1\",\"quantity\":1,\"amount\":250,\"shipTo\":\"Navi Mumbai\"}"; + String bad = "{\"orderId\":\"api-2\",\"sku\":\"BOOK-1\",\"quantity\":1,\"amount\":5000,\"shipTo\":\"Navi Mumbai\"}"; + + t.line("POST /orders " + ok); + String body1 = mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content(ok)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + t.line("-> " + body1); + String r1 = mvc.perform(get("/orders/api-1")).andExpect(status().isOk()) + .andExpect(jsonPath("$.status").value("CONFIRMED")).andReturn().getResponse().getContentAsString(); + t.line("GET /orders/api-1 -> " + r1); + + t.line("").line("POST /orders " + bad); + String body2 = mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content(bad)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + t.line("-> " + body2); + String r2 = mvc.perform(get("/orders/api-2")).andExpect(status().isOk()) + .andExpect(jsonPath("$.reason").value("PaymentDeclined")).andReturn().getResponse().getContentAsString(); + t.line("GET /orders/api-2 -> " + r2); + + // The workflow id is the order id: starting it again while it exists is rejected by the server. + String dup = mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content(ok)) + .andReturn().getResponse().getStatus() + ""; + t.line("").line("POST the same order again -> HTTP " + dup); + t.line("").line("ledger journal:").lines(ledger.journal()); + t.write(); + } +} diff --git a/temporal/src/test/java/com/ankurm/workflows/temporal/OrderSagaTest.java b/temporal/src/test/java/com/ankurm/workflows/temporal/OrderSagaTest.java new file mode 100644 index 0000000..760d01f --- /dev/null +++ b/temporal/src/test/java/com/ankurm/workflows/temporal/OrderSagaTest.java @@ -0,0 +1,157 @@ +package com.ankurm.workflows.temporal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.ankurm.workflows.temporal.saga.Ledger; +import com.ankurm.workflows.temporal.saga.OrderActivitiesImpl; +import com.ankurm.workflows.temporal.saga.OrderRequest; +import com.ankurm.workflows.temporal.saga.OrderResult; +import com.ankurm.workflows.temporal.saga.OrderSagaWorkflow; +import com.ankurm.workflows.temporal.saga.OrderSagaWorkflowImpl; +import io.temporal.client.WorkflowClient; +import io.temporal.client.WorkflowOptions; +import io.temporal.client.WorkflowStub; +import io.temporal.testing.TestWorkflowEnvironment; +import io.temporal.worker.Worker; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class OrderSagaTest { + + private TestWorkflowEnvironment env; + private Worker worker; + private Ledger ledger; + private WorkflowClient client; + + @BeforeEach + void setUp() { + env = TestWorkflowEnvironment.newInstance(); + ledger = new Ledger(); + worker = env.newWorker("orders"); + worker.registerWorkflowImplementationTypes(OrderSagaWorkflowImpl.class); + worker.registerActivitiesImplementations(new OrderActivitiesImpl(ledger)); + client = env.getWorkflowClient(); + } + + @AfterEach + void tearDown() { + env.close(); + } + + private OrderSagaWorkflow stub(String orderId) { + return client.newWorkflowStub(OrderSagaWorkflow.class, + WorkflowOptions.newBuilder().setTaskQueue("orders").setWorkflowId("order-" + orderId).build()); + } + + @Test + void happyPath() { + env.start(); + OrderResult r = stub("o-1").placeOrder(new OrderRequest("o-1", "BOOK-1", 2, 500, "Mumbai")); + new Transcript("03-saga-happy-path.txt") + .line("result: " + r).lines(ledger.journal()) + .line("stock BOOK-1 after: " + ledger.stock.get("BOOK-1")) + .line("").line("event history (workflow tasks hidden):") + .history(client.fetchHistory("order-o-1"), true).write(); + assertEquals("CONFIRMED", r.status()); + assertEquals(3, ledger.stock.get("BOOK-1")); + } + + @Test + void outOfStockRefundsThePayment() { + env.start(); + OrderResult r = stub("o-2").placeOrder(new OrderRequest("o-2", "LAPTOP-9", 3, 900, "Mumbai")); + new Transcript("04-saga-out-of-stock.txt") + .line("result: " + r).lines(ledger.journal()) + .line("payment state: " + ledger.payments.get("o-2")) + .line("").line("event history (workflow tasks hidden):") + .history(client.fetchHistory("order-o-2"), true).write(); + assertEquals("CANCELLED", r.status()); + assertEquals("OutOfStock", r.reason()); + assertEquals("REFUNDED", ledger.payments.get("o-2")); + } + + @Test + void lateFailureCompensatesInReverseOrder() { + env.start(); + OrderResult r = stub("o-3").placeOrder(new OrderRequest("o-3", "BOOK-1", 1, 100, "NOWHERE")); + new Transcript("05-saga-late-failure.txt") + .line("result: " + r).lines(ledger.journal()) + .line("payment state: " + ledger.payments.get("o-3")) + .line("stock BOOK-1 after: " + ledger.stock.get("BOOK-1")).write(); + assertEquals("Unshippable", r.reason()); + assertEquals(5, ledger.stock.get("BOOK-1")); + assertTrue(ledger.journal().indexOf("releaseStock o-3 attempt 1: released 1") + < ledger.journal().indexOf("refundPayment o-3 attempt 1: refunded")); + } + + @Test + void retriedActivityDoesNotChargeTwice() { + ledger.crashAfterChargeOnce.add("o-4"); + env.start(); + OrderResult r = stub("o-4").placeOrder(new OrderRequest("o-4", "BOOK-1", 1, 100, "Pune")); + new Transcript("06-saga-idempotent-retry.txt") + .line("result: " + r).lines(ledger.journal()) + .line("payments recorded for o-4: " + ledger.payments.get("o-4")).write(); + assertEquals("CONFIRMED", r.status()); + assertEquals(2, ledger.journal().stream().filter(l -> l.startsWith("chargePayment")).count()); + assertEquals(1, ledger.journal().stream().filter(l -> l.contains("charged 100")).count()); + } + + @Test + void workflowStartedBeforeAnyWorkerExistsStillCompletes() throws Exception { + // env.start() has NOT been called: the workflow is accepted by the server, but nobody polls the task queue. + OrderSagaWorkflow wf = stub("o-5"); + WorkflowClient.start(wf::placeOrder, new OrderRequest("o-5", "BOOK-1", 1, 100, "Delhi")); + Thread.sleep(500); + var before = client.fetchHistory("order-o-5").getEvents().stream().map(e -> e.getEventType().name().replace("EVENT_TYPE_", "")).toList(); + assertNull(ledger.payments.get("o-5")); + String journalBefore = ledger.journal().toString(); + + env.start(); // a worker appears + OrderResult r = WorkflowStub.fromTyped(wf).getResult(10, TimeUnit.SECONDS, OrderResult.class); + new Transcript("07-saga-no-worker-yet.txt") + .line("events recorded while no worker was running: " + before) + .line("journal while no worker was running: " + journalBefore) + .line("after a worker started polling: " + r) + .lines(ledger.journal()).write(); + assertEquals("CONFIRMED", r.status()); + } + + @Test + void workflowIdReusePolicyDecidesWhatASecondStartDoes() { + env.start(); + OrderRequest req = new OrderRequest("o-6", "BOOK-1", 1, 100, "Pune"); + OrderSagaWorkflow first = stub("o-6"); + first.placeOrder(req); + String firstRun = WorkflowStub.fromTyped(first).getExecution().getRunId(); + + OrderSagaWorkflow second = stub("o-6"); // default policy: ALLOW_DUPLICATE + second.placeOrder(req); + String secondRun = WorkflowStub.fromTyped(second).getExecution().getRunId(); + + OrderSagaWorkflow third = client.newWorkflowStub(OrderSagaWorkflow.class, WorkflowOptions.newBuilder() + .setTaskQueue("orders").setWorkflowId("order-o-6") + .setWorkflowIdReusePolicy(io.temporal.api.enums.v1.WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE) + .build()); + // A synchronous call with REJECT_DUPLICATE does not throw: the stub attaches to the existing run instead. + OrderResult attached = third.placeOrder(req); + String attachedRun = WorkflowStub.fromTyped(third).getExecution().getRunId(); + // Starting asynchronously is what surfaces the rejection. + OrderSagaWorkflow fourth = client.newWorkflowStub(OrderSagaWorkflow.class, WorkflowOptions.newBuilder() + .setTaskQueue("orders").setWorkflowId("order-o-6") + .setWorkflowIdReusePolicy(io.temporal.api.enums.v1.WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE) + .build()); + var ex = org.junit.jupiter.api.Assertions.assertThrows(io.temporal.client.WorkflowExecutionAlreadyStarted.class, + () -> WorkflowClient.start(fourth::placeOrder, req)); + new Transcript("11-workflow-id-reuse.txt") + .line("default policy (ALLOW_DUPLICATE), second start after the first closed: new run id = " + !firstRun.equals(secondRun)) + .line("REJECT_DUPLICATE, synchronous call: no exception, returned " + attached + "; attached to the latest run = " + attachedRun.equals(secondRun)) + .line("REJECT_DUPLICATE, WorkflowClient.start: " + ex.getClass().getSimpleName()) + .lines(ledger.journal()).write(); + assertTrue(!firstRun.equals(secondRun)); + } +} diff --git a/temporal/src/test/java/com/ankurm/workflows/temporal/RetryTest.java b/temporal/src/test/java/com/ankurm/workflows/temporal/RetryTest.java new file mode 100644 index 0000000..2368f52 --- /dev/null +++ b/temporal/src/test/java/com/ankurm/workflows/temporal/RetryTest.java @@ -0,0 +1,82 @@ +package com.ankurm.workflows.temporal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.ankurm.workflows.temporal.retry.FlakyRateActivities; +import com.ankurm.workflows.temporal.retry.RateWorkflow; +import com.ankurm.workflows.temporal.retry.RateWorkflowImpl; +import io.temporal.client.WorkflowFailedException; +import io.temporal.client.WorkflowOptions; +import io.temporal.failure.ActivityFailure; +import io.temporal.failure.ApplicationFailure; +import io.temporal.testing.TestWorkflowEnvironment; +import io.temporal.worker.Worker; +import org.junit.jupiter.api.Test; + +class RetryTest { + + private record Run(String result, Throwable failure, FlakyRateActivities acts, long workflowMs, long wallMs) { } + + private Run run(String id, int failFirst, boolean permanent) { + TestWorkflowEnvironment env = TestWorkflowEnvironment.newInstance(); + try { + FlakyRateActivities acts = new FlakyRateActivities(failFirst, permanent); + Worker worker = env.newWorker("rates"); + worker.registerWorkflowImplementationTypes(RateWorkflowImpl.class); + worker.registerActivitiesImplementations(acts); + env.start(); + RateWorkflow wf = env.getWorkflowClient().newWorkflowStub(RateWorkflow.class, + WorkflowOptions.newBuilder().setTaskQueue("rates").setWorkflowId(id).build()); + long wall = System.nanoTime(); + String result = null; + Throwable failure = null; + try { + result = wf.lookup("USD/INR"); + } catch (WorkflowFailedException e) { + failure = e; + } + var events = env.getWorkflowClient().fetchHistory(id).getEvents(); + var t0 = events.get(0).getEventTime(); + var t1 = events.get(events.size() - 1).getEventTime(); + return new Run(result, failure, acts, (t1.getSeconds() - t0.getSeconds()) * 1000 + (t1.getNanos() - t0.getNanos()) / 1_000_000, (System.nanoTime() - wall) / 1_000_000); + } finally { + env.close(); + } + } + + @Test + void retriesAndGivesUpAccordingToPolicy() { + Run transient2 = run("rates-1", 2, false); + Run exhausted = run("rates-2", 100, false); + Run permanent = run("rates-3", 0, true); + + Transcript t = new Transcript("02-retries.txt"); + t.line("retry policy: initial 1s, coefficient 2.0, maximum attempts 4"); + t.line("").line("== two transient failures, then success =="); + t.lines(transient2.acts().attempts); + t.line("result: " + transient2.result()); + t.line("workflow history spans " + Math.round(transient2.workflowMs() / 1000.0) + " s (1 s + 2 s of backoff); wall clock under 5 s: " + (transient2.wallMs() < 5000)); + + t.line("").line("== always failing: attempts exhausted =="); + t.lines(exhausted.acts().attempts); + WorkflowFailedException wfe = (WorkflowFailedException) exhausted.failure(); + ActivityFailure af = assertInstanceOf(ActivityFailure.class, wfe.getCause()); + t.line("workflow failed: " + wfe.getCause().getClass().getSimpleName() + " -> " + + af.getCause().getClass().getSimpleName() + ": " + af.getCause().getMessage()); + + t.line("").line("== non-retryable ApplicationFailure =="); + t.lines(permanent.acts().attempts); + ActivityFailure pf = assertInstanceOf(ActivityFailure.class, permanent.failure().getCause()); + ApplicationFailure app = assertInstanceOf(ApplicationFailure.class, pf.getCause()); + t.line("workflow failed: type=" + app.getType() + " nonRetryable=" + app.isNonRetryable() + " message=" + app.getOriginalMessage()); + t.write(); + + assertEquals(3, transient2.acts().attempts.size()); + assertTrue(Math.abs(transient2.workflowMs() - 3000) < 500, "history spans " + transient2.workflowMs()); + assertEquals("USD/INR=83.21", transient2.result()); + assertEquals(4, exhausted.acts().attempts.size()); + assertEquals(1, permanent.acts().attempts.size()); + } +} diff --git a/temporal/src/test/java/com/ankurm/workflows/temporal/Transcript.java b/temporal/src/test/java/com/ankurm/workflows/temporal/Transcript.java new file mode 100644 index 0000000..483fe66 --- /dev/null +++ b/temporal/src/test/java/com/ankurm/workflows/temporal/Transcript.java @@ -0,0 +1,59 @@ +package com.ankurm.workflows.temporal; + +import io.temporal.api.history.v1.HistoryEvent; +import io.temporal.common.WorkflowExecutionHistory; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** Writes captured output to output/NN-name.txt; tests assert the same facts, so a stale transcript fails the build. */ +public final class Transcript { + + private final List lines = new ArrayList<>(); + private final String file; + + public Transcript(String file) { + this.file = file; + } + + public Transcript line(String s) { + lines.add(s); + return this; + } + + public Transcript lines(List ls) { + lines.addAll(ls); + return this; + } + + public Transcript history(WorkflowExecutionHistory h, boolean hideWorkflowTasks) { + for (HistoryEvent e : h.getEvents()) { + String type = e.getEventType().name().replace("EVENT_TYPE_", ""); + if (hideWorkflowTasks && type.startsWith("WORKFLOW_TASK")) { + continue; + } + String extra = switch (e.getEventType()) { + case EVENT_TYPE_ACTIVITY_TASK_SCHEDULED -> + " " + e.getActivityTaskScheduledEventAttributes().getActivityType().getName(); + case EVENT_TYPE_MARKER_RECORDED -> " " + e.getMarkerRecordedEventAttributes().getMarkerName(); + case EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED -> + " " + e.getWorkflowExecutionSignaledEventAttributes().getSignalName(); + default -> ""; + }; + lines.add(String.format("%3d %s%s", e.getEventId(), type, extra)); + } + return this; + } + + public void write() { + try { + Path dir = Path.of("output"); + Files.createDirectories(dir); + Files.writeString(dir.resolve(file), String.join("\n", lines) + "\n"); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/temporal/src/test/java/com/ankurm/workflows/temporal/VersioningTest.java b/temporal/src/test/java/com/ankurm/workflows/temporal/VersioningTest.java new file mode 100644 index 0000000..34126fa --- /dev/null +++ b/temporal/src/test/java/com/ankurm/workflows/temporal/VersioningTest.java @@ -0,0 +1,74 @@ +package com.ankurm.workflows.temporal; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.ankurm.workflows.temporal.versioning.FulfilmentActivitiesImpl; +import com.ankurm.workflows.temporal.versioning.FulfilmentNaiveV2; +import com.ankurm.workflows.temporal.versioning.FulfilmentPatchedV2; +import com.ankurm.workflows.temporal.versioning.FulfilmentV1; +import com.ankurm.workflows.temporal.versioning.FulfilmentWorkflow; +import io.temporal.common.WorkflowExecutionHistory; +import io.temporal.client.WorkflowOptions; +import io.temporal.testing.TestWorkflowEnvironment; +import io.temporal.testing.WorkflowReplayer; +import io.temporal.worker.Worker; +import org.junit.jupiter.api.Test; + +class VersioningTest { + + private WorkflowExecutionHistory runAndFetch(Class impl, String id, Transcript t, String label) { + TestWorkflowEnvironment env = TestWorkflowEnvironment.newInstance(); + try { + Worker w = env.newWorker("fulfilment"); + w.registerWorkflowImplementationTypes(impl); + w.registerActivitiesImplementations(new FulfilmentActivitiesImpl()); + env.start(); + FulfilmentWorkflow wf = env.getWorkflowClient().newWorkflowStub(FulfilmentWorkflow.class, + WorkflowOptions.newBuilder().setTaskQueue("fulfilment").setWorkflowId(id).build()); + String result = wf.fulfil("o-9"); + t.line(label + " result: " + result); + return env.getWorkflowClient().fetchHistory(id); + } finally { + env.close(); + } + } + + @Test + void replayCatchesBreakingChangesAndGetVersionFixesThem() throws Exception { + Transcript t = new Transcript("09-versioning-replay.txt"); + WorkflowExecutionHistory v1History = runAndFetch(FulfilmentV1.class, "ful-1", t, "V1 run:"); + t.line("V1 history:").history(v1History, true); + + t.line("").line("== replay the V1 history against V1 code =="); + assertDoesNotThrow(() -> WorkflowReplayer.replayWorkflowExecution(v1History, FulfilmentV1.class)); + t.line("OK"); + + t.line("").line("== replay the V1 history against NaiveV2 (new step inserted, no guard) =="); + Exception naive = assertThrows(Exception.class, + () -> WorkflowReplayer.replayWorkflowExecution(v1History, FulfilmentNaiveV2.class)); + for (Throwable c = naive; c != null; c = c.getCause()) { + String msg = c.getMessage() == null ? "" : c.getMessage().lines().filter(l -> !l.startsWith("\tat ")).collect(java.util.stream.Collectors.joining("\n")); + t.line(c.getClass().getName() + ": " + msg); + } + + t.line("").line("== replay the V1 history against PatchedV2 (getVersion guard) =="); + assertDoesNotThrow(() -> WorkflowReplayer.replayWorkflowExecution(v1History, FulfilmentPatchedV2.class)); + t.line("OK"); + + t.line("").line("== a NEW execution on PatchedV2 =="); + WorkflowExecutionHistory v2History = runAndFetch(FulfilmentPatchedV2.class, "ful-2", t, "PatchedV2 run:"); + t.line("PatchedV2 history:").history(v2History, true); + assertDoesNotThrow(() -> WorkflowReplayer.replayWorkflowExecution(v2History, FulfilmentPatchedV2.class)); + t.line("replay of its own history: OK"); + t.write(); + + assertTrue(v2History.getEvents().stream().anyMatch(e -> e.hasMarkerRecordedEventAttributes())); + assertTrue(v1History.getEvents().stream().noneMatch(e -> e.hasMarkerRecordedEventAttributes())); + } + + private static String firstLine(String s) { + return s == null ? "null" : s.lines().findFirst().orElse(""); + } +}