Add temporal module: workflows, activities, retries, saga, signals, versioning, Spring Boot starter
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b5uEyg58znuchZ8C8i
This commit is contained in:
@@ -0,0 +1 @@
|
||||
target/
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,49 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.ankurm.workflows</groupId>
|
||||
<artifactId>workflow-engines-demo</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
<artifactId>temporal</artifactId>
|
||||
<name>temporal</name>
|
||||
<properties>
|
||||
<temporal.version>1.41.1</temporal.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webmvc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.temporal</groupId>
|
||||
<artifactId>temporal-spring-boot-starter</artifactId>
|
||||
<version>${temporal.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.temporal</groupId>
|
||||
<artifactId>temporal-testing</artifactId>
|
||||
<version>${temporal.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webmvc-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Executable
+38
@@ -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"
|
||||
Executable
+4
@@ -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
|
||||
Executable
+15
@@ -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
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.ankurm.workflows.temporal.hello;
|
||||
|
||||
public class GreetingActivitiesImpl implements GreetingActivities {
|
||||
|
||||
@Override
|
||||
public String composeGreeting(String name) {
|
||||
return "Hello, " + name + "!";
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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";
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<String, String> payments = new ConcurrentHashMap<>();
|
||||
public final Map<String, Integer> reservations = new ConcurrentHashMap<>();
|
||||
public final Map<String, String> orders = new ConcurrentHashMap<>();
|
||||
public final Map<String, Integer> 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<String> crashAfterChargeOnce = ConcurrentHashMap.newKeySet();
|
||||
private final List<String> journal = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
public void log(String line) {
|
||||
journal.add(line);
|
||||
}
|
||||
|
||||
public List<String> journal() {
|
||||
synchronized (journal) {
|
||||
return new ArrayList<>(journal);
|
||||
}
|
||||
}
|
||||
|
||||
public void clearJournal() {
|
||||
journal.clear();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.ankurm.workflows.temporal.saga;
|
||||
|
||||
public record OrderRequest(String orderId, String sku, int quantity, long amount, String shipTo) {
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+13
@@ -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);
|
||||
}
|
||||
+19
@@ -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;
|
||||
}
|
||||
}
|
||||
+20
@@ -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;
|
||||
}
|
||||
}
|
||||
+22
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+12
@@ -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);
|
||||
}
|
||||
@@ -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<String, String> 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<String, String> 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<String, String> status(@PathVariable String id) {
|
||||
return Map.of("status", client.newWorkflowStub(ApprovalWorkflow.class, "approval-" + id).status());
|
||||
}
|
||||
}
|
||||
@@ -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<Map<String, String>> 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
spring:
|
||||
temporal:
|
||||
test-server:
|
||||
enabled: false
|
||||
connection:
|
||||
target: 127.0.0.1:7233
|
||||
namespace: default
|
||||
@@ -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
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<? extends FulfilmentWorkflow> 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("");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user