mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(swf): invoke real Lambda functions for ScheduleLambdaFunction
The decision was recorded as ScheduleLambdaFunctionFailed with cause
LAMBDA_SERVICE_NOT_AVAILABLE_IN_REGION rather than invoking anything. SWF is
otherwise a pure coordination service — deciders and activity workers are the
user's own processes, so there is no user code for the emulator to run — but
ScheduleLambdaFunction is the one decision where SWF itself executes something,
and Floci already runs Lambda functions in containers. A decider that fans work
out to Lambda could not be exercised locally at all.
Floci now invokes the function through its own Lambda service, the same way the
EventBridge and Scheduler invokers do, and records the outcome. Verified against
the live service:
5 LambdaFunctionScheduled {control, id, input, name, startToCloseTimeout}
6 LambdaFunctionStarted {scheduledEventId: 5}
7 LambdaFunctionCompleted {result, scheduledEventId: 5, startedEventId: 6}
8 DecisionTaskScheduled
Four behaviours came from that capture and are easy to get wrong:
- A function that cannot be resolved is LambdaFunctionFailed with Lambda's own
error code as reason (ResourceNotFoundException) — not
ScheduleLambdaFunctionFailed — and it still reports Started first.
- An execution with no lambdaRole never starts the function at all: Scheduled is
followed by StartLambdaFunctionFailed with cause ASSUME_ROLE_FAILED and the
message "No IAM role is attached to the current workflow execution."
- lambdaRole resolves from StartWorkflowExecution's lambdaRole, falling back to
the workflow type's defaultLambdaRole, and is echoed in the started event.
- An absent input reaches the handler as {}, and reusing an id is accepted —
there is no ID_ALREADY_IN_USE for Lambda the way there is for activity ids.
SwfService takes a LambdaInvoker seam rather than LambdaService directly, so the
unit tests keep running without a Docker daemon while SwfLambdaInvoker wires the
real thing at runtime. The invocation is RequestResponse because the response
body is what gets recorded as result; the fire-and-forget invokers use Event for
the opposite reason.
The Lambda region comes from the execution's domain ARN, so a workflow in one
region does not invoke a function in another.
Tests: SwfServiceTest covers all four paths against a recording invoker and
fails on the previous behaviour with "the function must actually be invoked
==> expected: <1> but was: <0>". SwfLambdaIntegrationTest and the SDK
compatibility SwfLambdaTest deploy a real function and assert the recorded
result is what the container returned, so neither passes against a synthesised
event. Docker-backed cases live in their own class so a Docker-less run loses
only them rather than the whole SWF wire suite.
Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
9 files changed
+820
-14
No files matched your search
@@ -253,7 +253,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
|
||||
| Kinesis | In-process | Streams, shards, enhanced fan-out, split and merge |
|
||||
| Secrets Manager | In-process | Versioning, resource policies, tagging |
|
||||
| Step Functions | In-process | ASL execution, task tokens, execution history |
|
||||
| SWF | In-process | Decision and activity tasks, timers, child workflows, timeouts |
|
||||
| SWF | In-process | Decision and activity tasks, timers, child workflows, timeouts, real Lambda invocation |
|
||||
| CloudFormation | In-process | Stacks, change sets, resource provisioning, StackSets (cross-account instances) |
|
||||
| EventBridge | In-process | Custom buses, rules, SQS, SNS and Lambda targets |
|
||||
| EventBridge Pipes | In-process | Poller-based integration connecting SQS, Kinesis, DynamoDB, and MSK sources to targets with optional filtering |
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.lambda.LambdaClient;
|
||||
import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest;
|
||||
import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest;
|
||||
import software.amazon.awssdk.services.lambda.model.FunctionCode;
|
||||
import software.amazon.awssdk.services.lambda.model.Runtime;
|
||||
import software.amazon.awssdk.services.swf.SwfClient;
|
||||
import software.amazon.awssdk.services.swf.model.ChildPolicy;
|
||||
import software.amazon.awssdk.services.swf.model.Decision;
|
||||
import software.amazon.awssdk.services.swf.model.DecisionType;
|
||||
import software.amazon.awssdk.services.swf.model.EventType;
|
||||
import software.amazon.awssdk.services.swf.model.GetWorkflowExecutionHistoryRequest;
|
||||
import software.amazon.awssdk.services.swf.model.HistoryEvent;
|
||||
import software.amazon.awssdk.services.swf.model.LambdaFunctionCompletedEventAttributes;
|
||||
import software.amazon.awssdk.services.swf.model.LambdaFunctionScheduledEventAttributes;
|
||||
import software.amazon.awssdk.services.swf.model.PollForDecisionTaskRequest;
|
||||
import software.amazon.awssdk.services.swf.model.PollForDecisionTaskResponse;
|
||||
import software.amazon.awssdk.services.swf.model.RegisterDomainRequest;
|
||||
import software.amazon.awssdk.services.swf.model.RegisterWorkflowTypeRequest;
|
||||
import software.amazon.awssdk.services.swf.model.RespondDecisionTaskCompletedRequest;
|
||||
import software.amazon.awssdk.services.swf.model.ScheduleLambdaFunctionDecisionAttributes;
|
||||
import software.amazon.awssdk.services.swf.model.StartWorkflowExecutionRequest;
|
||||
import software.amazon.awssdk.services.swf.model.TaskList;
|
||||
import software.amazon.awssdk.services.swf.model.WorkflowExecution;
|
||||
import software.amazon.awssdk.services.swf.model.WorkflowType;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Drives SWF's ScheduleLambdaFunction decision through the AWS SDK against a real Lambda
|
||||
* function that Floci runs in a container.
|
||||
*
|
||||
* <p>The point of doing this at the SDK layer is that the generated model has to accept what
|
||||
* the emulator returns: the Lambda history events must deserialize into
|
||||
* {@code LambdaFunctionScheduled/Started/Completed} with their typed
|
||||
* {@code *EventAttributes} members populated, which a hand-rolled HTTP assertion cannot
|
||||
* verify.
|
||||
*/
|
||||
@DisplayName("SWF Lambda decisions via the AWS SDK")
|
||||
class SwfLambdaTest {
|
||||
|
||||
private static final String SUFFIX = String.valueOf(System.nanoTime());
|
||||
private static final String DOMAIN = "sdk-swf-lambda-" + SUFFIX;
|
||||
private static final String FUNCTION = "sdk-swf-fn-" + SUFFIX;
|
||||
private static final String TASK_LIST = "sdk-lam-tl-" + SUFFIX;
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/swf-lambda-role";
|
||||
|
||||
private static SwfClient swf;
|
||||
private static LambdaClient lambda;
|
||||
|
||||
@BeforeAll
|
||||
static void setUp() throws Exception {
|
||||
swf = TestFixtures.swfClient();
|
||||
lambda = TestFixtures.lambdaClient();
|
||||
|
||||
lambda.createFunction(CreateFunctionRequest.builder()
|
||||
.functionName(FUNCTION)
|
||||
.runtime(Runtime.PYTHON3_12)
|
||||
.role(ROLE)
|
||||
.handler("handler.handler")
|
||||
.timeout(30)
|
||||
.code(FunctionCode.builder().zipFile(SdkBytes.fromByteArray(handlerZip())).build())
|
||||
.build());
|
||||
|
||||
swf.registerDomain(RegisterDomainRequest.builder()
|
||||
.name(DOMAIN)
|
||||
.workflowExecutionRetentionPeriodInDays("1")
|
||||
.build());
|
||||
|
||||
swf.registerWorkflowType(RegisterWorkflowTypeRequest.builder()
|
||||
.domain(DOMAIN)
|
||||
.name("LambdaWf")
|
||||
.version("1.0")
|
||||
.defaultTaskList(TaskList.builder().name(TASK_LIST).build())
|
||||
.defaultTaskStartToCloseTimeout("300")
|
||||
.defaultExecutionStartToCloseTimeout("900")
|
||||
.defaultChildPolicy(ChildPolicy.TERMINATE)
|
||||
// SWF needs a role to invoke Lambda with; without one the invocation never starts.
|
||||
.defaultLambdaRole(ROLE)
|
||||
.build());
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDown() {
|
||||
try {
|
||||
lambda.deleteFunction(DeleteFunctionRequest.builder().functionName(FUNCTION).build());
|
||||
} catch (RuntimeException ignored) {
|
||||
// Best effort: leaving the function behind must not fail the suite.
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] handlerZip() throws Exception {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(baos)) {
|
||||
zip.putNextEntry(new ZipEntry("handler.py"));
|
||||
zip.write(("def handler(event, context):\n"
|
||||
+ " return {'doubled': [n * 2 for n in event.get('numbers', [])]}\n").getBytes());
|
||||
zip.closeEntry();
|
||||
}
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("ScheduleLambdaFunction runs the function and the SDK reads back its result")
|
||||
void scheduleLambdaFunction() {
|
||||
String runId = swf.startWorkflowExecution(StartWorkflowExecutionRequest.builder()
|
||||
.domain(DOMAIN)
|
||||
.workflowId("sdk-wf-lambda")
|
||||
.workflowType(WorkflowType.builder().name("LambdaWf").version("1.0").build())
|
||||
.build())
|
||||
.runId();
|
||||
assertNotNull(runId);
|
||||
|
||||
PollForDecisionTaskResponse task = null;
|
||||
for (int attempt = 0; attempt < 20 && task == null; attempt++) {
|
||||
PollForDecisionTaskResponse candidate = swf.pollForDecisionTask(
|
||||
PollForDecisionTaskRequest.builder()
|
||||
.domain(DOMAIN)
|
||||
.taskList(TaskList.builder().name(TASK_LIST).build())
|
||||
.identity("sdk-decider")
|
||||
.build());
|
||||
if (candidate.taskToken() != null && !candidate.taskToken().isEmpty()) {
|
||||
task = candidate;
|
||||
}
|
||||
}
|
||||
assertNotNull(task, "no decision task became available");
|
||||
|
||||
swf.respondDecisionTaskCompleted(RespondDecisionTaskCompletedRequest.builder()
|
||||
.taskToken(task.taskToken())
|
||||
.decisions(Decision.builder()
|
||||
.decisionType(DecisionType.SCHEDULE_LAMBDA_FUNCTION)
|
||||
.scheduleLambdaFunctionDecisionAttributes(
|
||||
ScheduleLambdaFunctionDecisionAttributes.builder()
|
||||
.id("sdk-lam-1")
|
||||
.name(FUNCTION)
|
||||
.control("sdk-ctl")
|
||||
.input("{\"numbers\": [1, 2, 3]}")
|
||||
.startToCloseTimeout("30")
|
||||
.build())
|
||||
.build())
|
||||
.build());
|
||||
|
||||
List<HistoryEvent> events = swf.getWorkflowExecutionHistory(
|
||||
GetWorkflowExecutionHistoryRequest.builder()
|
||||
.domain(DOMAIN)
|
||||
.execution(WorkflowExecution.builder()
|
||||
.workflowId("sdk-wf-lambda").runId(runId).build())
|
||||
.build())
|
||||
.events();
|
||||
|
||||
HistoryEvent scheduled = eventOf(events, EventType.LAMBDA_FUNCTION_SCHEDULED);
|
||||
HistoryEvent started = eventOf(events, EventType.LAMBDA_FUNCTION_STARTED);
|
||||
HistoryEvent completed = eventOf(events, EventType.LAMBDA_FUNCTION_COMPLETED);
|
||||
|
||||
// The generated model must populate the typed attribute members.
|
||||
LambdaFunctionScheduledEventAttributes scheduledAttrs =
|
||||
scheduled.lambdaFunctionScheduledEventAttributes();
|
||||
assertEquals("sdk-lam-1", scheduledAttrs.id());
|
||||
assertEquals(FUNCTION, scheduledAttrs.name());
|
||||
assertEquals("sdk-ctl", scheduledAttrs.control());
|
||||
assertEquals("30", scheduledAttrs.startToCloseTimeout());
|
||||
assertEquals(scheduled.eventId(),
|
||||
started.lambdaFunctionStartedEventAttributes().scheduledEventId());
|
||||
|
||||
LambdaFunctionCompletedEventAttributes completedAttrs =
|
||||
completed.lambdaFunctionCompletedEventAttributes();
|
||||
assertEquals(scheduled.eventId(), completedAttrs.scheduledEventId());
|
||||
assertEquals(started.eventId(), completedAttrs.startedEventId());
|
||||
|
||||
// Proof the container actually executed: the handler doubled the decider's input.
|
||||
assertTrue(completedAttrs.result().contains("2")
|
||||
&& completedAttrs.result().contains("4")
|
||||
&& completedAttrs.result().contains("6"),
|
||||
"expected the handler to double [1,2,3], got: " + completedAttrs.result());
|
||||
|
||||
assertEquals(EventType.DECISION_TASK_SCHEDULED, events.get(events.size() - 1).eventType());
|
||||
}
|
||||
|
||||
private static HistoryEvent eventOf(List<HistoryEvent> events, EventType type) {
|
||||
return events.stream()
|
||||
.filter(e -> type.equals(e.eventType()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AssertionError("no " + type + " in "
|
||||
+ events.stream().map(HistoryEvent::eventType).toList()));
|
||||
}
|
||||
}
|
||||
+23
-4
@@ -71,7 +71,7 @@ All 39 modeled operations are implemented.
|
||||
| `SignalExternalWorkflowExecution` | Delivers a signal to another execution in the same domain |
|
||||
| `RequestCancelExternalWorkflowExecution` | Requests cancellation of another execution |
|
||||
| `StartChildWorkflowExecution` | Starts a child execution and reports its outcome back to the parent |
|
||||
| `ScheduleLambdaFunction` | Recorded as `ScheduleLambdaFunctionFailed` with cause `LAMBDA_SERVICE_NOT_AVAILABLE_IN_REGION` (see [Limitations](#limitations)) |
|
||||
| `ScheduleLambdaFunction` | Invokes the function through Floci's Lambda service and records its result (see [Lambda functions](#lambda-functions)) |
|
||||
|
||||
A decision that cannot be applied appends its `*Failed` event with the AWS cause
|
||||
(`ACTIVITY_TYPE_DOES_NOT_EXIST`, `ACTIVITY_ID_ALREADY_IN_USE`, `TIMER_ID_UNKNOWN`,
|
||||
@@ -102,6 +102,28 @@ When an execution closes, its `childPolicy` is applied to still-open children:
|
||||
`TERMINATE` terminates them with cause `CHILD_POLICY_APPLIED`, `REQUEST_CANCEL` requests
|
||||
cancellation, and `ABANDON` leaves them running.
|
||||
|
||||
## Lambda functions
|
||||
|
||||
`ScheduleLambdaFunction` runs a real function: Floci invokes it through its own Lambda
|
||||
service, which executes it in a container exactly as an `Invoke` API call would, and records
|
||||
the outcome in history. Deploy the function with the Lambda API first — SWF resolves it by
|
||||
name in the region its domain was registered in.
|
||||
|
||||
The execution needs a `lambdaRole`, taken from `StartWorkflowExecution`'s `lambdaRole` or,
|
||||
when absent, the workflow type's `defaultLambdaRole`. The role is not evaluated as a policy;
|
||||
its presence is what SWF requires in order to invoke.
|
||||
|
||||
| Outcome | History |
|
||||
|---|---|
|
||||
| Success | `LambdaFunctionScheduled` → `LambdaFunctionStarted` → `LambdaFunctionCompleted` with the response as `result` |
|
||||
| Handler raised | `…Scheduled` → `…Started` → `LambdaFunctionFailed` with `reason` `Handled`/`Unhandled` and the error payload as `details` |
|
||||
| Function not found | `…Scheduled` → `…Started` → `LambdaFunctionFailed` with `reason` `ResourceNotFoundException` |
|
||||
| No `lambdaRole` | `…Scheduled` → `StartLambdaFunctionFailed` with cause `ASSUME_ROLE_FAILED`; the function is never started |
|
||||
|
||||
A decision with no `input` delivers `{}` to the handler, and reusing an `id` is accepted —
|
||||
SWF does not report `ID_ALREADY_IN_USE` for Lambda invocations the way it does for activity
|
||||
ids. Every outcome schedules a fresh decision task so the decider can react.
|
||||
|
||||
## Configuration
|
||||
|
||||
```yaml
|
||||
@@ -211,9 +233,6 @@ Faults use the AWS codes and messages, so SDK error handling works unchanged:
|
||||
- **Long polling.** `PollForDecisionTask` and `PollForActivityTask` return immediately
|
||||
instead of holding the connection for up to 60 seconds. Workers that loop on an empty
|
||||
poll behave the same; workers that rely on the call blocking will spin.
|
||||
- **`ScheduleLambdaFunction`.** Lambda-backed activities are recorded as
|
||||
`ScheduleLambdaFunctionFailed` rather than invoking a function, so a decider that uses
|
||||
them keeps making progress instead of waiting for an event that never arrives.
|
||||
- **Task tokens are in-memory.** Tokens do not survive a restart even under persistent
|
||||
storage modes, matching the fact that SWF tokens are not durable handles.
|
||||
- **Retention.** `workflowExecutionRetentionPeriodInDays` is stored and returned but
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package io.github.hectorvent.floci.services.swf;
|
||||
|
||||
/**
|
||||
* A Lambda invocation's outcome, reduced to what SWF records in history.
|
||||
*
|
||||
* @param payload the function's response body, recorded as the LambdaFunctionCompleted
|
||||
* {@code result} or, on a handler error, the Failed {@code details}
|
||||
* @param functionError the Lambda {@code FunctionError} header ({@code Handled}/{@code Unhandled}),
|
||||
* or {@code null} when the invocation succeeded
|
||||
*/
|
||||
record LambdaInvocationResult(String payload, String functionError) {
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package io.github.hectorvent.floci.services.swf;
|
||||
|
||||
/**
|
||||
* The slice of Lambda invocation SWF needs, so {@link SwfService} depends on a two-method
|
||||
* seam rather than on {@code LambdaService} itself.
|
||||
*
|
||||
* <p>This keeps the service unit-testable without a Docker daemon or the Lambda container
|
||||
* stack: {@code SwfServiceTest} supplies a stub, while at runtime {@link SwfLambdaInvoker}
|
||||
* delegates to the real Lambda service and its containers.
|
||||
*/
|
||||
interface LambdaInvoker {
|
||||
|
||||
/**
|
||||
* Invokes {@code functionName} synchronously and returns its response.
|
||||
*
|
||||
* @throws io.github.hectorvent.floci.core.common.AwsException if the function cannot be
|
||||
* resolved or invoked, so the caller can record the AWS error code as the
|
||||
* LambdaFunctionFailed {@code reason}
|
||||
*/
|
||||
LambdaInvocationResult invoke(String region, String functionName, byte[] payload);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package io.github.hectorvent.floci.services.swf;
|
||||
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* Runtime {@link LambdaInvoker}: runs the function through Floci's own Lambda service, which
|
||||
* executes it in a container exactly as an {@code Invoke} API call would.
|
||||
*
|
||||
* <p>Uses {@link InvocationType#RequestResponse} because SWF needs the response body to record
|
||||
* as the LambdaFunctionCompleted {@code result} — an {@code Event} invocation would return
|
||||
* immediately with nothing to record, the same reason the EventBridge and Scheduler invokers
|
||||
* pick {@code Event} for their fire-and-forget targets and this one does not.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SwfLambdaInvoker implements LambdaInvoker {
|
||||
|
||||
private final LambdaService lambdaService;
|
||||
|
||||
@Inject
|
||||
public SwfLambdaInvoker(LambdaService lambdaService) {
|
||||
this.lambdaService = lambdaService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LambdaInvocationResult invoke(String region, String functionName, byte[] payload) {
|
||||
InvokeResult result = lambdaService.invoke(region, functionName, payload,
|
||||
InvocationType.RequestResponse);
|
||||
byte[] body = result.getPayload();
|
||||
return new LambdaInvocationResult(
|
||||
body == null ? "" : new String(body, StandardCharsets.UTF_8),
|
||||
result.getFunctionError());
|
||||
}
|
||||
}
|
||||
@@ -77,9 +77,11 @@ public class SwfService implements Resettable {
|
||||
|
||||
private final RegionResolver regionResolver;
|
||||
private final Clock clock;
|
||||
private final LambdaInvoker lambdaInvoker;
|
||||
|
||||
@Inject
|
||||
public SwfService(StorageFactory storageFactory, RegionResolver regionResolver, Clock clock) {
|
||||
public SwfService(StorageFactory storageFactory, RegionResolver regionResolver, Clock clock,
|
||||
LambdaInvoker lambdaInvoker) {
|
||||
this.domainStore = storageFactory.create("swf", "swf-domains.json",
|
||||
new TypeReference<Map<String, SwfDomain>>() {});
|
||||
this.workflowTypeStore = storageFactory.create("swf", "swf-workflow-types.json",
|
||||
@@ -90,6 +92,7 @@ public class SwfService implements Resettable {
|
||||
new TypeReference<Map<String, SwfWorkflowExecution>>() {});
|
||||
this.regionResolver = regionResolver;
|
||||
this.clock = clock;
|
||||
this.lambdaInvoker = lambdaInvoker;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1082,19 +1085,104 @@ public class SwfService implements Resettable {
|
||||
}
|
||||
|
||||
/**
|
||||
* Lambda-backed activities are recorded but not invoked. Emitting Scheduled followed by
|
||||
* ScheduleLambdaFunctionFailed keeps a decider that uses them unblocked with a cause it
|
||||
* models, instead of stalling on an event that never arrives.
|
||||
* Invokes the Lambda function the decider asked for, through Floci's own Lambda service,
|
||||
* and records the outcome as the live service does.
|
||||
*
|
||||
* <p>Verified against the live service: a successful call appends Scheduled, Started, then
|
||||
* Completed with the function's response as {@code result}; a function that cannot be
|
||||
* resolved still gets Scheduled and Started, then Failed with the SDK's error code as
|
||||
* {@code reason}; and an execution with no {@code lambdaRole} never reaches Started at all,
|
||||
* appending StartLambdaFunctionFailed with cause ASSUME_ROLE_FAILED instead. Reusing an
|
||||
* {@code id} is accepted — SWF does not report ID_ALREADY_IN_USE for Lambda invocations the
|
||||
* way it does for activity ids.
|
||||
*
|
||||
* <p>The invocation is synchronous here rather than dispatched to the sweeper: floci's
|
||||
* Lambda service runs the function in a container it manages and returns the payload, so
|
||||
* the natural place to record Completed/Failed is the same decision that scheduled it.
|
||||
*/
|
||||
private void scheduleLambdaFunction(SwfWorkflowExecution execution, Decision decision, long decisionEventId) {
|
||||
appendEvent(execution, "ScheduleLambdaFunctionFailed")
|
||||
.attr("id", nullToEmpty(decision.string("id")))
|
||||
.attr("name", nullToEmpty(decision.string("name")))
|
||||
.attr("cause", "LAMBDA_SERVICE_NOT_AVAILABLE_IN_REGION")
|
||||
String id = nullToEmpty(decision.string("id"));
|
||||
String name = decision.string("name");
|
||||
|
||||
SwfHistoryEvent scheduled = appendEvent(execution, "LambdaFunctionScheduled");
|
||||
scheduled.attr("id", id)
|
||||
.attr("name", nullToEmpty(name))
|
||||
.attr("control", decision.string("control"))
|
||||
.attr("input", decision.string("input"))
|
||||
.attr("startToCloseTimeout", decision.string("startToCloseTimeout"))
|
||||
.attr("decisionTaskCompletedEventId", decisionEventId);
|
||||
|
||||
// No role means SWF cannot assume anything to invoke with, so the function is never
|
||||
// started. This is the one path that skips LambdaFunctionStarted entirely.
|
||||
if (execution.getLambdaRole() == null || execution.getLambdaRole().isEmpty()) {
|
||||
appendEvent(execution, "StartLambdaFunctionFailed")
|
||||
.attr("scheduledEventId", scheduled.getEventId())
|
||||
.attr("cause", "ASSUME_ROLE_FAILED")
|
||||
.attr("message", "No IAM role is attached to the current workflow execution.");
|
||||
execution.setDecisionNeeded(true);
|
||||
return;
|
||||
}
|
||||
|
||||
SwfHistoryEvent started = appendEvent(execution, "LambdaFunctionStarted");
|
||||
started.attr("scheduledEventId", scheduled.getEventId());
|
||||
|
||||
// An empty input is delivered to the handler as {}, matching the live service.
|
||||
String input = decision.string("input");
|
||||
byte[] payload = (input == null || input.isEmpty() ? "{}" : input)
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
try {
|
||||
LambdaInvocationResult result = lambdaInvoker.invoke(
|
||||
lambdaRegion(execution), name, payload);
|
||||
if (result.functionError() != null && !result.functionError().isEmpty()) {
|
||||
appendEvent(execution, "LambdaFunctionFailed")
|
||||
.attr("scheduledEventId", scheduled.getEventId())
|
||||
.attr("startedEventId", started.getEventId())
|
||||
.attr("reason", result.functionError())
|
||||
.attr("details", result.payload());
|
||||
} else {
|
||||
appendEvent(execution, "LambdaFunctionCompleted")
|
||||
.attr("scheduledEventId", scheduled.getEventId())
|
||||
.attr("startedEventId", started.getEventId())
|
||||
.attr("result", result.payload());
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
// The live service surfaces the Lambda SDK's own error code and message here, so a
|
||||
// decider sees ResourceNotFoundException for a function that does not exist.
|
||||
appendEvent(execution, "LambdaFunctionFailed")
|
||||
.attr("scheduledEventId", scheduled.getEventId())
|
||||
.attr("startedEventId", started.getEventId())
|
||||
.attr("reason", e.getErrorCode())
|
||||
.attr("details", e.getMessage());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("SWF Lambda invocation {0} ({1}) failed: {2}", id, name, e.getMessage());
|
||||
appendEvent(execution, "LambdaFunctionFailed")
|
||||
.attr("scheduledEventId", scheduled.getEventId())
|
||||
.attr("startedEventId", started.getEventId())
|
||||
.attr("reason", e.getClass().getSimpleName())
|
||||
.attr("details", nullToEmpty(e.getMessage()));
|
||||
}
|
||||
execution.setDecisionNeeded(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* The region to invoke Lambda in: taken from the execution's domain ARN, which was built
|
||||
* from the region the domain was registered in, so a Lambda scheduled by a workflow in
|
||||
* one region is not invoked in another. Falls back to the configured default when the ARN
|
||||
* is not in the expected shape.
|
||||
*/
|
||||
private String lambdaRegion(SwfWorkflowExecution execution) {
|
||||
SwfDomain domain = domainStore.get(execution.getDomain()).orElse(null);
|
||||
if (domain != null && domain.getArn() != null) {
|
||||
// arn:aws:swf:<region>:<account>:/domain/<name>
|
||||
String[] parts = domain.getArn().split(":", 5);
|
||||
if (parts.length >= 4 && !parts[3].isEmpty()) {
|
||||
return parts[3];
|
||||
}
|
||||
}
|
||||
return regionResolver.getDefaultRegion();
|
||||
}
|
||||
|
||||
// ────────────────────────────── Activity tasks ───────────────────────────
|
||||
|
||||
public Optional<SwfActivityTask> pollForActivityTask(String domainName, String taskList, String identity) {
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
package io.github.hectorvent.floci.services.swf;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.Base64;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Drives {@code ScheduleLambdaFunction} against a <em>real</em> Lambda function — deployed
|
||||
* through Floci's own Lambda API and executed in the container Floci starts for it — rather
|
||||
* than a stub, so the whole path is exercised: decision to Lambda service to container to
|
||||
* history event.
|
||||
*
|
||||
* <p>Separate from {@link SwfIntegrationTest} because these cases are the only SWF tests that
|
||||
* need a Docker daemon; keeping them apart means a Docker-less run loses exactly this class
|
||||
* instead of the whole SWF wire suite.
|
||||
*
|
||||
* <p>The expected event sequence and field shapes were captured from the live service:
|
||||
* LambdaFunctionScheduled, LambdaFunctionStarted, then Completed carrying the function's
|
||||
* response as {@code result}, followed by a fresh DecisionTaskScheduled.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class SwfLambdaIntegrationTest {
|
||||
|
||||
private static final String LAMBDA_PATH = "/2015-03-31/functions";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/swf-lambda-role";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private static Response swf(String action, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", "SimpleWorkflowService." + action)
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body(body)
|
||||
.when().post("/");
|
||||
}
|
||||
|
||||
/** A python handler that echoes its event, so the response proves the input reached it. */
|
||||
private static String echoFunctionZip() throws Exception {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(baos)) {
|
||||
zip.putNextEntry(new ZipEntry("handler.py"));
|
||||
zip.write(("import json\n"
|
||||
+ "def handler(event, context):\n"
|
||||
+ " return {'echoed': event, 'ok': True}\n").getBytes());
|
||||
zip.closeEntry();
|
||||
}
|
||||
return Base64.getEncoder().encodeToString(baos.toByteArray());
|
||||
}
|
||||
|
||||
private static void createEchoFunction(String name) throws Exception {
|
||||
given().contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"FunctionName": "%s",
|
||||
"Runtime": "python3.12",
|
||||
"Role": "%s",
|
||||
"Handler": "handler.handler",
|
||||
"Timeout": 30,
|
||||
"Code": {"ZipFile": "%s"}
|
||||
}
|
||||
""".formatted(name, ROLE, echoFunctionZip()))
|
||||
.when().post(LAMBDA_PATH)
|
||||
.then().statusCode(201)
|
||||
.body("State", equalTo("Active"));
|
||||
}
|
||||
|
||||
/** Registers a domain plus a workflow type carrying {@code defaultLambdaRole}. */
|
||||
private static void setUpDomain(String domain, String taskList, String lambdaRole) {
|
||||
swf("RegisterDomain", """
|
||||
{"name": "%s", "workflowExecutionRetentionPeriodInDays": "1"}
|
||||
""".formatted(domain)).then().statusCode(200);
|
||||
|
||||
String role = lambdaRole == null ? "" : "\"defaultLambdaRole\": \"%s\",".formatted(lambdaRole);
|
||||
swf("RegisterWorkflowType", """
|
||||
{"domain": "%s", "name": "LambdaWf", "version": "1.0",
|
||||
%s
|
||||
"defaultTaskList": {"name": "%s"},
|
||||
"defaultTaskStartToCloseTimeout": "300",
|
||||
"defaultExecutionStartToCloseTimeout": "900",
|
||||
"defaultChildPolicy": "TERMINATE"}
|
||||
""".formatted(domain, role, taskList)).then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String startAndPoll(String domain, String workflowId, String taskList) {
|
||||
swf("StartWorkflowExecution", """
|
||||
{"domain": "%s", "workflowId": "%s",
|
||||
"workflowType": {"name": "LambdaWf", "version": "1.0"}}
|
||||
""".formatted(domain, workflowId)).then().statusCode(200);
|
||||
|
||||
return swf("PollForDecisionTask", """
|
||||
{"domain": "%s", "taskList": {"name": "%s"}, "identity": "decider"}
|
||||
""".formatted(domain, taskList))
|
||||
.then().statusCode(200)
|
||||
.extract().path("taskToken");
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduleLambdaFunction_runsTheRealFunctionAndRecordsItsResponse() throws Exception {
|
||||
String suffix = String.valueOf(System.nanoTime());
|
||||
String fn = "swf-echo-" + suffix;
|
||||
String domain = "swf-lambda-" + suffix;
|
||||
String taskList = "lam-tl-" + suffix;
|
||||
|
||||
createEchoFunction(fn);
|
||||
setUpDomain(domain, taskList, ROLE);
|
||||
String token = startAndPoll(domain, "wf-lambda", taskList);
|
||||
|
||||
swf("RespondDecisionTaskCompleted", """
|
||||
{"taskToken": "%s", "decisions": [
|
||||
{"decisionType": "ScheduleLambdaFunction",
|
||||
"scheduleLambdaFunctionDecisionAttributes": {
|
||||
"id": "lam-1",
|
||||
"name": "%s",
|
||||
"control": "ctl-1",
|
||||
"input": "{\\"hello\\": \\"swf\\"}",
|
||||
"startToCloseTimeout": "30"
|
||||
}}]}
|
||||
""".formatted(token, fn)).then().statusCode(200);
|
||||
|
||||
Response history = swf("GetWorkflowExecutionHistory", """
|
||||
{"domain": "%s", "execution": {"workflowId": "wf-lambda"}}
|
||||
""".formatted(domain));
|
||||
|
||||
history.then()
|
||||
.statusCode(200)
|
||||
.body("events.eventType", org.hamcrest.Matchers.hasItems(
|
||||
"LambdaFunctionScheduled", "LambdaFunctionStarted", "LambdaFunctionCompleted"))
|
||||
.body("events.find { it.eventType == 'LambdaFunctionScheduled' }"
|
||||
+ ".lambdaFunctionScheduledEventAttributes.id", equalTo("lam-1"))
|
||||
.body("events.find { it.eventType == 'LambdaFunctionScheduled' }"
|
||||
+ ".lambdaFunctionScheduledEventAttributes.name", equalTo(fn))
|
||||
.body("events.find { it.eventType == 'LambdaFunctionScheduled' }"
|
||||
+ ".lambdaFunctionScheduledEventAttributes.control", equalTo("ctl-1"))
|
||||
.body("events.find { it.eventType == 'LambdaFunctionScheduled' }"
|
||||
+ ".lambdaFunctionScheduledEventAttributes.startToCloseTimeout", equalTo("30"))
|
||||
.body("events[-1].eventType", equalTo("DecisionTaskScheduled"));
|
||||
|
||||
// The recorded result must be the function's actual output, which proves the container
|
||||
// ran and received the decider's input rather than the event being synthesised.
|
||||
String result = history.path(
|
||||
"events.find { it.eventType == 'LambdaFunctionCompleted' }"
|
||||
+ ".lambdaFunctionCompletedEventAttributes.result");
|
||||
assertTrue(result != null && result.contains("\"ok\""),
|
||||
"expected the echo handler's response, got: " + result);
|
||||
assertTrue(result.contains("swf"),
|
||||
"expected the decider's input echoed back, got: " + result);
|
||||
|
||||
// initiated/started correlation ids must name the events they refer to.
|
||||
int scheduledId = history.path(
|
||||
"events.find { it.eventType == 'LambdaFunctionScheduled' }.eventId");
|
||||
int startedId = history.path(
|
||||
"events.find { it.eventType == 'LambdaFunctionStarted' }.eventId");
|
||||
assertEquals(scheduledId, (int) history.path(
|
||||
"events.find { it.eventType == 'LambdaFunctionStarted' }"
|
||||
+ ".lambdaFunctionStartedEventAttributes.scheduledEventId"));
|
||||
assertEquals(scheduledId, (int) history.path(
|
||||
"events.find { it.eventType == 'LambdaFunctionCompleted' }"
|
||||
+ ".lambdaFunctionCompletedEventAttributes.scheduledEventId"));
|
||||
assertEquals(startedId, (int) history.path(
|
||||
"events.find { it.eventType == 'LambdaFunctionCompleted' }"
|
||||
+ ".lambdaFunctionCompletedEventAttributes.startedEventId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduleLambdaFunction_forAMissingFunction_recordsFailedWithTheAwsErrorCode() {
|
||||
String suffix = String.valueOf(System.nanoTime());
|
||||
String domain = "swf-lambda-missing-" + suffix;
|
||||
String taskList = "lam-tl-" + suffix;
|
||||
|
||||
setUpDomain(domain, taskList, ROLE);
|
||||
String token = startAndPoll(domain, "wf-missing", taskList);
|
||||
|
||||
swf("RespondDecisionTaskCompleted", """
|
||||
{"taskToken": "%s", "decisions": [
|
||||
{"decisionType": "ScheduleLambdaFunction",
|
||||
"scheduleLambdaFunctionDecisionAttributes": {
|
||||
"id": "lam-missing", "name": "swf-no-such-function-%s"
|
||||
}}]}
|
||||
""".formatted(token, suffix)).then().statusCode(200);
|
||||
|
||||
// The live service still records Started before Failed for an unresolvable function,
|
||||
// and surfaces Lambda's own error code as the reason.
|
||||
swf("GetWorkflowExecutionHistory", """
|
||||
{"domain": "%s", "execution": {"workflowId": "wf-missing"}}
|
||||
""".formatted(domain))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("events.eventType", org.hamcrest.Matchers.hasItems(
|
||||
"LambdaFunctionScheduled", "LambdaFunctionStarted", "LambdaFunctionFailed"))
|
||||
.body("events.find { it.eventType == 'LambdaFunctionFailed' }"
|
||||
+ ".lambdaFunctionFailedEventAttributes.reason",
|
||||
equalTo("ResourceNotFoundException"))
|
||||
.body("events.find { it.eventType == 'LambdaFunctionFailed' }"
|
||||
+ ".lambdaFunctionFailedEventAttributes.details", notNullValue())
|
||||
.body("events[-1].eventType", equalTo("DecisionTaskScheduled"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduleLambdaFunction_withNoLambdaRole_reportsAssumeRoleFailedAndNeverStarts() {
|
||||
String suffix = String.valueOf(System.nanoTime());
|
||||
String domain = "swf-lambda-norole-" + suffix;
|
||||
String taskList = "lam-tl-" + suffix;
|
||||
|
||||
setUpDomain(domain, taskList, null);
|
||||
String token = startAndPoll(domain, "wf-norole", taskList);
|
||||
|
||||
swf("RespondDecisionTaskCompleted", """
|
||||
{"taskToken": "%s", "decisions": [
|
||||
{"decisionType": "ScheduleLambdaFunction",
|
||||
"scheduleLambdaFunctionDecisionAttributes": {"id": "x", "name": "whatever"}}]}
|
||||
""".formatted(token)).then().statusCode(200);
|
||||
|
||||
swf("GetWorkflowExecutionHistory", """
|
||||
{"domain": "%s", "execution": {"workflowId": "wf-norole"}}
|
||||
""".formatted(domain))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("events.eventType", org.hamcrest.Matchers.hasItem("StartLambdaFunctionFailed"))
|
||||
// This is the one Lambda path that never reaches Started.
|
||||
.body("events.eventType",
|
||||
org.hamcrest.Matchers.not(org.hamcrest.Matchers.hasItem("LambdaFunctionStarted")))
|
||||
.body("events.find { it.eventType == 'StartLambdaFunctionFailed' }"
|
||||
+ ".startLambdaFunctionFailedEventAttributes.cause", equalTo("ASSUME_ROLE_FAILED"))
|
||||
.body("events.find { it.eventType == 'StartLambdaFunctionFailed' }"
|
||||
+ ".startLambdaFunctionFailedEventAttributes.message",
|
||||
equalTo("No IAM role is attached to the current workflow execution."))
|
||||
.body("events[-1].eventType", equalTo("DecisionTaskScheduled"));
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,10 @@ import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -52,18 +54,40 @@ class SwfServiceTest {
|
||||
|
||||
private MutableClock clock;
|
||||
private SwfService service;
|
||||
private List<String> lambdaInvocations;
|
||||
private LambdaInvocationResult lambdaResponse;
|
||||
private RuntimeException lambdaFailure;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
clock = new MutableClock();
|
||||
lambdaInvocations = new ArrayList<>();
|
||||
lambdaResponse = new LambdaInvocationResult("{\"ok\":true}", null);
|
||||
lambdaFailure = null;
|
||||
service = new SwfService(new InMemoryStorageFactory(),
|
||||
new RegionResolver("us-east-1", "000000000000"), clock);
|
||||
new RegionResolver("us-east-1", "000000000000"), clock, recordingLambdaInvoker());
|
||||
|
||||
service.registerDomain(DOMAIN, "unit test domain", "7", Map.of(), "us-east-1");
|
||||
service.registerWorkflowType(DOMAIN, workflowType("W", "1"));
|
||||
service.registerActivityType(DOMAIN, activityType("A", "1"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stands in for the real Lambda service so these tests need no Docker daemon: records the
|
||||
* region and function it was asked for, then returns {@link #lambdaResponse} or throws
|
||||
* {@link #lambdaFailure}.
|
||||
*/
|
||||
private LambdaInvoker recordingLambdaInvoker() {
|
||||
return (region, functionName, payload) -> {
|
||||
lambdaInvocations.add(region + "|" + functionName + "|"
|
||||
+ new String(payload, StandardCharsets.UTF_8));
|
||||
if (lambdaFailure != null) {
|
||||
throw lambdaFailure;
|
||||
}
|
||||
return lambdaResponse;
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
void startWorkflowExecution_seedsStartedAndDecisionTaskScheduledEvents() {
|
||||
String runId = start("wf-1");
|
||||
@@ -432,6 +456,128 @@ class SwfServiceTest {
|
||||
assertEquals(1L, count, childId + " reported " + count + " times"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduleLambdaFunction_invokesTheFunctionAndRecordsCompletion() {
|
||||
// A lambdaRole is required for SWF to invoke at all.
|
||||
service.registerWorkflowType(DOMAIN, lambdaWorkflowType("LW", "1",
|
||||
"arn:aws:iam::000000000000:role/swf-lambda"));
|
||||
String runId = startLambdaWf("wf-lam", "LW");
|
||||
|
||||
SwfDecisionTask task = service.pollForDecisionTask(DOMAIN, "tl", "d").orElseThrow();
|
||||
lambdaResponse = new LambdaInvocationResult("{\"echoed\":{\"hello\":\"swf\"}}", null);
|
||||
service.respondDecisionTaskCompleted(task.getTaskToken(), List.of(
|
||||
scheduleLambda("lam-1", "my-fn", "{\"hello\":\"swf\"}", "ctl", "30")), null);
|
||||
|
||||
assertEquals(1, lambdaInvocations.size(), "the function must actually be invoked");
|
||||
assertEquals("us-east-1|my-fn|{\"hello\":\"swf\"}", lambdaInvocations.get(0));
|
||||
|
||||
List<SwfHistoryEvent> events = service.getWorkflowExecutionHistory(DOMAIN, "wf-lam", runId, false);
|
||||
SwfHistoryEvent scheduled = eventOfType(events, "LambdaFunctionScheduled");
|
||||
SwfHistoryEvent started = eventOfType(events, "LambdaFunctionStarted");
|
||||
SwfHistoryEvent completed = eventOfType(events, "LambdaFunctionCompleted");
|
||||
|
||||
assertEquals("lam-1", scheduled.getAttributes().get("id"));
|
||||
assertEquals("my-fn", scheduled.getAttributes().get("name"));
|
||||
assertEquals("ctl", scheduled.getAttributes().get("control"));
|
||||
assertEquals("30", scheduled.getAttributes().get("startToCloseTimeout"));
|
||||
assertEquals(scheduled.getEventId(), started.getAttributes().get("scheduledEventId"));
|
||||
assertEquals(scheduled.getEventId(), completed.getAttributes().get("scheduledEventId"));
|
||||
assertEquals(started.getEventId(), completed.getAttributes().get("startedEventId"));
|
||||
assertEquals("{\"echoed\":{\"hello\":\"swf\"}}", completed.getAttributes().get("result"));
|
||||
|
||||
// The outcome gives the decider a fresh task to react to.
|
||||
assertEquals("DecisionTaskScheduled", events.get(events.size() - 1).getEventType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduleLambdaFunction_withNoInput_passesAnEmptyJsonObject() {
|
||||
service.registerWorkflowType(DOMAIN, lambdaWorkflowType("LW", "1",
|
||||
"arn:aws:iam::000000000000:role/swf-lambda"));
|
||||
startLambdaWf("wf-lam-empty", "LW");
|
||||
SwfDecisionTask task = service.pollForDecisionTask(DOMAIN, "tl", "d").orElseThrow();
|
||||
|
||||
service.respondDecisionTaskCompleted(task.getTaskToken(), List.of(
|
||||
scheduleLambda("lam-1", "my-fn", null, null, null)), null);
|
||||
|
||||
assertEquals("us-east-1|my-fn|{}", lambdaInvocations.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduleLambdaFunction_whenTheFunctionIsMissing_recordsFailedWithTheAwsErrorCode() {
|
||||
service.registerWorkflowType(DOMAIN, lambdaWorkflowType("LW", "1",
|
||||
"arn:aws:iam::000000000000:role/swf-lambda"));
|
||||
String runId = startLambdaWf("wf-lam-missing", "LW");
|
||||
SwfDecisionTask task = service.pollForDecisionTask(DOMAIN, "tl", "d").orElseThrow();
|
||||
|
||||
lambdaFailure = new AwsException("ResourceNotFoundException",
|
||||
"Function not found: arn:aws:lambda:us-east-1:000000000000:function:gone", 404);
|
||||
service.respondDecisionTaskCompleted(task.getTaskToken(), List.of(
|
||||
scheduleLambda("lam-1", "gone", null, null, null)), null);
|
||||
|
||||
List<SwfHistoryEvent> events = service.getWorkflowExecutionHistory(DOMAIN, "wf-lam-missing", runId, false);
|
||||
// The live service still reports Started before Failed for an unresolvable function.
|
||||
SwfHistoryEvent started = eventOfType(events, "LambdaFunctionStarted");
|
||||
SwfHistoryEvent failed = eventOfType(events, "LambdaFunctionFailed");
|
||||
assertEquals("ResourceNotFoundException", failed.getAttributes().get("reason"));
|
||||
assertEquals(started.getEventId(), failed.getAttributes().get("startedEventId"));
|
||||
assertEquals("DecisionTaskScheduled", events.get(events.size() - 1).getEventType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduleLambdaFunction_whenTheHandlerErrors_recordsFailedWithTheFunctionError() {
|
||||
service.registerWorkflowType(DOMAIN, lambdaWorkflowType("LW", "1",
|
||||
"arn:aws:iam::000000000000:role/swf-lambda"));
|
||||
String runId = startLambdaWf("wf-lam-err", "LW");
|
||||
SwfDecisionTask task = service.pollForDecisionTask(DOMAIN, "tl", "d").orElseThrow();
|
||||
|
||||
lambdaResponse = new LambdaInvocationResult("{\"errorMessage\":\"boom\"}", "Unhandled");
|
||||
service.respondDecisionTaskCompleted(task.getTaskToken(), List.of(
|
||||
scheduleLambda("lam-1", "my-fn", null, null, null)), null);
|
||||
|
||||
SwfHistoryEvent failed = eventOfType(
|
||||
service.getWorkflowExecutionHistory(DOMAIN, "wf-lam-err", runId, false), "LambdaFunctionFailed");
|
||||
assertEquals("Unhandled", failed.getAttributes().get("reason"));
|
||||
assertEquals("{\"errorMessage\":\"boom\"}", failed.getAttributes().get("details"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduleLambdaFunction_withoutALambdaRole_neverStartsAndReportsAssumeRoleFailed() {
|
||||
// The workflow type registered in setUp() has no defaultLambdaRole.
|
||||
String runId = start("wf-lam-norole");
|
||||
SwfDecisionTask task = service.pollForDecisionTask(DOMAIN, "tl", "d").orElseThrow();
|
||||
|
||||
service.respondDecisionTaskCompleted(task.getTaskToken(), List.of(
|
||||
scheduleLambda("lam-1", "my-fn", null, null, null)), null);
|
||||
|
||||
assertTrue(lambdaInvocations.isEmpty(), "no role means the function is never invoked");
|
||||
|
||||
List<SwfHistoryEvent> events = service.getWorkflowExecutionHistory(DOMAIN, "wf-lam-norole", runId, false);
|
||||
SwfHistoryEvent scheduled = eventOfType(events, "LambdaFunctionScheduled");
|
||||
SwfHistoryEvent failed = eventOfType(events, "StartLambdaFunctionFailed");
|
||||
assertEquals("ASSUME_ROLE_FAILED", failed.getAttributes().get("cause"));
|
||||
assertEquals("No IAM role is attached to the current workflow execution.",
|
||||
failed.getAttributes().get("message"));
|
||||
assertEquals(scheduled.getEventId(), failed.getAttributes().get("scheduledEventId"));
|
||||
// This is the one Lambda path that skips Started entirely.
|
||||
assertTrue(events.stream().noneMatch(e -> "LambdaFunctionStarted".equals(e.getEventType())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void startWorkflowExecution_resolvesLambdaRoleFromTheTypeDefaultAndAcceptsAnOverride() {
|
||||
service.registerWorkflowType(DOMAIN, lambdaWorkflowType("LW", "1",
|
||||
"arn:aws:iam::000000000000:role/type-default"));
|
||||
|
||||
String inherited = startLambdaWf("wf-inherit", "LW");
|
||||
assertEquals("arn:aws:iam::000000000000:role/type-default",
|
||||
service.describeWorkflowExecution(DOMAIN, "wf-inherit", inherited).getLambdaRole());
|
||||
|
||||
String overridden = service.startWorkflowExecution(new StartWorkflowExecutionRequest(
|
||||
DOMAIN, "wf-override", "LW", "1", null, null, null, null, null, null, null,
|
||||
"arn:aws:iam::000000000000:role/per-execution"));
|
||||
assertEquals("arn:aws:iam::000000000000:role/per-execution",
|
||||
service.describeWorkflowExecution(DOMAIN, "wf-override", overridden).getLambdaRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listExecutions_separatesOpenFromClosed() {
|
||||
start("wf-open");
|
||||
@@ -750,6 +896,43 @@ class SwfServiceTest {
|
||||
return type;
|
||||
}
|
||||
|
||||
/** A workflow type carrying a {@code defaultLambdaRole}, which SWF requires to invoke Lambda. */
|
||||
private static SwfWorkflowType lambdaWorkflowType(String name, String version, String role) {
|
||||
SwfWorkflowType type = workflowType(name, version);
|
||||
type.setDefaultLambdaRole(role);
|
||||
return type;
|
||||
}
|
||||
|
||||
private String startLambdaWf(String workflowId, String typeName) {
|
||||
return service.startWorkflowExecution(new StartWorkflowExecutionRequest(
|
||||
DOMAIN, workflowId, typeName, "1", null, null, null, null, null, null, null, null));
|
||||
}
|
||||
|
||||
private static Decision scheduleLambda(String id, String name, String input,
|
||||
String control, String startToCloseTimeout) {
|
||||
Map<String, Object> attrs = new LinkedHashMap<>();
|
||||
attrs.put("id", id);
|
||||
attrs.put("name", name);
|
||||
if (input != null) {
|
||||
attrs.put("input", input);
|
||||
}
|
||||
if (control != null) {
|
||||
attrs.put("control", control);
|
||||
}
|
||||
if (startToCloseTimeout != null) {
|
||||
attrs.put("startToCloseTimeout", startToCloseTimeout);
|
||||
}
|
||||
return new Decision("ScheduleLambdaFunction", attrs);
|
||||
}
|
||||
|
||||
private static SwfHistoryEvent eventOfType(List<SwfHistoryEvent> events, String eventType) {
|
||||
return events.stream()
|
||||
.filter(e -> eventType.equals(e.getEventType()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AssertionError("no " + eventType + " in "
|
||||
+ events.stream().map(SwfHistoryEvent::getEventType).toList()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal in-memory {@link StorageFactory} so the service under test needs no Quarkus
|
||||
* container. Only {@link StorageFactory#create} is exercised by SwfService.
|
||||
|
||||
Reference in new issue
Block a user