mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(lambda): durable function chained invokes (#5164)
* feat(lambda): durable function chained invokes
A CHAINED_INVOKE operation runs another function. A durable target
needs a version or alias and runs as its own durable execution with a
random name; its close completes the operation as SUCCEEDED, FAILED,
TIMED_OUT ("CHAINED_INVOKE timed out after N seconds.") or STOPPED. Any
other function is invoked once, and an output over 1 MB fails the
operation. A missing function or an unqualified durable one fails the
operation at once. Stopping the parent leaves the child running.
A plain chained invoke lost with the process runs again after a restart,
and a durable child that closed before its report reaches the parent
reports then.
* fix(lambda): close the gaps in durable chained invokes
A durable child that closes during a restart reports to its parent
under its own lock, and recovery triggers an execution once. A durable
target invoked without Payload starts its child with no input, while a
plain target gets {}. A target started in the batch that closes the
execution still runs and its result is ignored, as on AWS.
* fix(lambda): reject a chained invoke of another account or region
AWS rejects the checkpoint with InvalidParameterValueException "Cannot
start a CHAINED_INVOKE on a function in another account." or "... in
another region." Cross-account chained invocations are not supported.
* fix(lambda): keep durable chained invokes across a crash
The parent is saved before the child it starts, so a crash in between
leaves no child the parent does not know. On restart a child the parent
recorded but the store lost is started again under the same ARN, and a
plain target started by the checkpoint that closed the execution runs
again until its result is recorded. A child reports only to the
operation that started it.
* fix(lambda): recreate a lost durable child on the version its ARN names
An alias the chained invoke named may point to another version after a
restart, and a child recreated there would not match the ARN the parent
saved.
This commit is contained in:
1 parent
be668acefd
commit
6e6ce61eea
13 files changed
+921
-37
No files matched your search
+37
-9
@@ -33,10 +33,10 @@ class DurableCheckpointApplierTest {
|
||||
void anExecutionCloseCarriesOnlyItsOwnResultKind() {
|
||||
DurableErrorObject error = DurableErrorObject.of("m", "T");
|
||||
assertRejected(List.of(new DurableOperationUpdate("result", null, null, DurableOperationType.EXECUTION, null,
|
||||
DurableOperationAction.SUCCEED, "\"p\"", error, null, null, null, null, null)),
|
||||
DurableOperationAction.SUCCEED, "\"p\"", error, null, null, null, null, null, null, null)),
|
||||
"Cannot provide an Error for SUCCEED action.");
|
||||
assertRejected(List.of(new DurableOperationUpdate("result", null, null, DurableOperationType.EXECUTION, null,
|
||||
DurableOperationAction.FAIL, "\"p\"", error, null, null, null, null, null)),
|
||||
DurableOperationAction.FAIL, "\"p\"", error, null, null, null, null, null, null, null)),
|
||||
"Cannot provide a Payload for FAIL action.");
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ class DurableCheckpointApplierTest {
|
||||
void anExecutionErrorHasTheSameSizeLimitAsAnOperationError() {
|
||||
DurableErrorObject large = DurableErrorObject.of("x".repeat(DurableCheckpointApplier.MAX_ERROR_BYTES), "T");
|
||||
assertRejected(List.of(new DurableOperationUpdate("result", null, null, DurableOperationType.EXECUTION, null,
|
||||
DurableOperationAction.FAIL, null, large, null, null, null, null, null)),
|
||||
DurableOperationAction.FAIL, null, large, null, null, null, null, null, null, null)),
|
||||
"Error object size must be less than 32768 bytes.");
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ class DurableCheckpointApplierTest {
|
||||
assertEquals("Invalid current STEP state to start.", reject(execution, List.of(stepStart("s1", null))));
|
||||
assertEquals("Cannot provide an Error for SUCCEED action.", reject(execution, List.of(
|
||||
new DurableOperationUpdate("s1", null, null, DurableOperationType.STEP, null,
|
||||
DurableOperationAction.SUCCEED, null, DurableErrorObject.of("x", "y"), null, null, null, null, null))));
|
||||
DurableOperationAction.SUCCEED, null, DurableErrorObject.of("x", "y"), null, null, null, null, null, null, null))));
|
||||
assertEquals("Invalid StepOptions for the given action.", reject(execution, List.of(
|
||||
update("s1", null, DurableOperationType.STEP, DurableOperationAction.RETRY, null))));
|
||||
DurableCheckpointApplier.apply(execution, List.of(update("s1", null, DurableOperationType.STEP,
|
||||
@@ -118,9 +118,26 @@ class DurableCheckpointApplierTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void chainedInvokesAreNotSupportedYet() {
|
||||
void aChainedInvokeNeedsItsOptionsAndAnInputOfAtMostOneMegabyte() {
|
||||
assertRejected(List.of(update("i1", null, DurableOperationType.CHAINED_INVOKE, DurableOperationAction.START,
|
||||
null)), "CHAINED_INVOKE operations are not supported yet");
|
||||
null)), "Update for CHAINED_INVOKE operation requires ChainedInvokeOptions.");
|
||||
assertRejected(List.of(chainedStart("i1", "\"" + "x".repeat(1024 * 1024) + "\"")),
|
||||
"CHAINED_INVOKE input payload size must be less than or equal to 1048576 bytes.");
|
||||
assertRejected(List.of(chainedStart("i1", "arn:aws:lambda:us-east-1:111111111111:function:fn", null)),
|
||||
"Cannot start a CHAINED_INVOKE on a function in another account.");
|
||||
assertRejected(List.of(chainedStart("i1", "arn:aws:lambda:eu-west-1:000000000000:function:fn", null)),
|
||||
"Cannot start a CHAINED_INVOKE on a function in another region.");
|
||||
|
||||
DurableExecution execution = execution();
|
||||
DurableCheckpointApplier.Outcome outcome = DurableCheckpointApplier.apply(execution,
|
||||
List.of(chainedStart("i1", "arn:aws:lambda:us-east-1:000000000000:function:target-fn",
|
||||
"\"" + "x".repeat(300 * 1024) + "\"")), NOW);
|
||||
assertEquals(List.of("i1"), outcome.chainedInvokes(), "the service runs what the batch started");
|
||||
DurableOperation invoke = execution.getOperations().get("i1");
|
||||
assertEquals(DurableOperationStatus.STARTED, invoke.getStatus());
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:target-fn", invoke.getChainedFunctionName());
|
||||
assertEquals("Invalid action for the given operation type.", reject(execution, List.of(
|
||||
update("i1", null, DurableOperationType.CHAINED_INVOKE, DurableOperationAction.SUCCEED, "1"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -190,6 +207,8 @@ class DurableCheckpointApplierTest {
|
||||
DurableExecution execution = new DurableExecution();
|
||||
execution.setExecutionId("exec-id");
|
||||
execution.setExecutionArn(EXECUTION_ARN);
|
||||
execution.setAccountId("000000000000");
|
||||
execution.setRegion("us-east-1");
|
||||
execution.setName("exec");
|
||||
execution.setMaxResultBytes(DurableExecutionService.ASYNC_PAYLOAD_LIMIT);
|
||||
DurableOperation root = new DurableOperation();
|
||||
@@ -208,12 +227,21 @@ class DurableCheckpointApplierTest {
|
||||
|
||||
private static DurableOperationUpdate waitStart(String id) {
|
||||
return new DurableOperationUpdate(id, null, null, DurableOperationType.WAIT, null, DurableOperationAction.START,
|
||||
null, null, null, 5, null, null, null);
|
||||
null, null, null, 5, null, null, null, null, null);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate callbackStart(String id, int timeoutSeconds, int heartbeatSeconds) {
|
||||
return new DurableOperationUpdate(id, null, null, DurableOperationType.CALLBACK, "Callback",
|
||||
DurableOperationAction.START, null, null, null, null, null, timeoutSeconds, heartbeatSeconds);
|
||||
DurableOperationAction.START, null, null, null, null, null, timeoutSeconds, heartbeatSeconds, null, null);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate chainedStart(String id, String payload) {
|
||||
return chainedStart(id, "target-fn", payload);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate chainedStart(String id, String functionName, String payload) {
|
||||
return new DurableOperationUpdate(id, null, null, DurableOperationType.CHAINED_INVOKE, "ChainedInvoke",
|
||||
DurableOperationAction.START, payload, null, null, null, null, null, null, functionName, null);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate executionSucceed() {
|
||||
@@ -223,6 +251,6 @@ class DurableCheckpointApplierTest {
|
||||
private static DurableOperationUpdate update(String id, String parentId, DurableOperationType type,
|
||||
DurableOperationAction action, String payload) {
|
||||
return new DurableOperationUpdate(id, parentId, null, type, null, action, payload, null, null, null, null, null,
|
||||
null);
|
||||
null, null, null);
|
||||
}
|
||||
}
|
||||
+196
-4
@@ -31,6 +31,7 @@ import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -130,8 +131,182 @@ class DurableExecutionServicePersistenceTest {
|
||||
assertEquals(3, after.events.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlainChainedInvokeLostWithTheProcessRunsAgainAfterARestart() {
|
||||
ScriptedInvoker before = new ScriptedInvoker();
|
||||
PersistentStorageFactory firstStorage = new PersistentStorageFactory(directory);
|
||||
// Runs the parent's invocation and drops the chained invoke it starts, as a crash would.
|
||||
int[] launched = {0};
|
||||
DurableExecutionService first = newService(firstStorage, before, task -> {
|
||||
if (launched[0]++ == 0) {
|
||||
task.run();
|
||||
}
|
||||
});
|
||||
before.script((service, event) -> {
|
||||
service.checkpoint(arn(event), token(event), null, List.of(new DurableOperationUpdate("i1", null, null,
|
||||
DurableOperationType.CHAINED_INVOKE, "ChainedInvoke", DurableOperationAction.START, "{\"n\":1}",
|
||||
null, null, null, null, null, null, "plain-fn", null)));
|
||||
return "{\"Status\":\"PENDING\"}";
|
||||
});
|
||||
String executionArn = first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}",
|
||||
false)).getExecutionArn();
|
||||
assertEquals("STARTED", first.get(executionArn).getOperations().get("i1").getStatus().name());
|
||||
firstStorage.flushAll();
|
||||
|
||||
ScriptedInvoker after = new ScriptedInvoker();
|
||||
after.plainOutput = "{\"ran\":true}";
|
||||
DurableExecutionService restarted = newService(new PersistentStorageFactory(directory), after);
|
||||
after.script((service, event) -> {
|
||||
assertEquals("{\"ran\":true}", operation(event, "i1").at("/ChainedInvokeDetails/Result").asText());
|
||||
return "{\"Status\":\"SUCCEEDED\",\"Result\":\"\\\"done\\\"\"}";
|
||||
});
|
||||
restarted.recoverAfterRestart();
|
||||
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, restarted.get(executionArn).getStatus());
|
||||
assertEquals(List.of("{\"n\":1}"), after.plainPayloads);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDurableChildThatClosedBeforeItsReportCompletesTheParentAfterARestart() {
|
||||
ScriptedInvoker before = new ScriptedInvoker();
|
||||
PersistentStorageFactory firstStorage = new PersistentStorageFactory(directory);
|
||||
// Runs the parent's invocation and drops the child's, so the child stays RUNNING on disk.
|
||||
int[] launched = {0};
|
||||
DurableExecutionService first = newService(firstStorage, before, task -> {
|
||||
if (launched[0]++ == 0) {
|
||||
task.run();
|
||||
}
|
||||
});
|
||||
before.script((service, event) -> {
|
||||
service.checkpoint(arn(event), token(event), null, List.of(new DurableOperationUpdate("i1", null, null,
|
||||
DurableOperationType.CHAINED_INVOKE, "ChainedInvoke", DurableOperationAction.START, null,
|
||||
null, null, null, null, null, null, "child-fn:1", null)));
|
||||
return "{\"Status\":\"PENDING\"}";
|
||||
});
|
||||
String executionArn = first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}",
|
||||
false)).getExecutionArn();
|
||||
String childArn = first.get(executionArn).getOperations().get("i1").getChildExecutionArn();
|
||||
firstStorage.flushAll();
|
||||
|
||||
// The child closed, and the process stopped before its parent heard of it.
|
||||
PersistentStorageFactory crashedStorage = new PersistentStorageFactory(directory);
|
||||
AccountAwareStorageBackend<DurableExecution> store = crashedStorage.create("lambda",
|
||||
"lambda-durable-executions.json", new TypeReference<Map<String, DurableExecution>>() {});
|
||||
String childKey = DurableExecutionService.parseArn(childArn).storeKey();
|
||||
DurableExecution child = store.getForAccount(ACCOUNT, childKey).orElseThrow();
|
||||
child.setStatus(DurableExecutionStatus.SUCCEEDED);
|
||||
child.setResult("\"child done\"");
|
||||
store.putForAccount(ACCOUNT, childKey, child);
|
||||
crashedStorage.flushAll();
|
||||
|
||||
ScriptedInvoker after = new ScriptedInvoker();
|
||||
DurableExecutionService restarted = newService(new PersistentStorageFactory(directory), after);
|
||||
Script parent = (service, event) -> {
|
||||
JsonNode invoke = operation(event, "i1");
|
||||
if ("STARTED".equals(invoke.get("Status").asText())) {
|
||||
return "{\"Status\":\"PENDING\"}";
|
||||
}
|
||||
assertEquals("\"child done\"", invoke.at("/ChainedInvokeDetails/Result").asText());
|
||||
return "{\"Status\":\"SUCCEEDED\",\"Result\":\"\\\"done\\\"\"}";
|
||||
};
|
||||
after.script(parent);
|
||||
after.script(parent);
|
||||
restarted.recoverAfterRestart();
|
||||
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, restarted.get(executionArn).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDurableChildTheStoreLostIsStartedAgainUnderItsArnEvenIfItsAliasMoved() {
|
||||
ScriptedInvoker before = new ScriptedInvoker();
|
||||
PersistentStorageFactory firstStorage = new PersistentStorageFactory(directory);
|
||||
DurableExecutionService first = newService(firstStorage, before, firstTaskOnly());
|
||||
before.script((service, event) -> {
|
||||
service.checkpoint(arn(event), token(event), null, List.of(chainedStart("i1", "child-fn:live", "{\"n\":1}")));
|
||||
return "{\"Status\":\"PENDING\"}";
|
||||
});
|
||||
String parentArn = first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}",
|
||||
false)).getExecutionArn();
|
||||
String childArn = first.get(parentArn).getOperations().get("i1").getChildExecutionArn();
|
||||
executions(firstStorage).deleteForAccount(ACCOUNT,
|
||||
"us-east-1/" + DurableExecutionService.parseArn(childArn).executionId());
|
||||
firstStorage.flushAll();
|
||||
|
||||
ScriptedInvoker after = new ScriptedInvoker();
|
||||
after.liveVersion = "2";
|
||||
DurableExecutionService restarted = newService(new PersistentStorageFactory(directory), after);
|
||||
Script dispatch = (service, event) -> {
|
||||
if (arn(event).equals(childArn)) {
|
||||
assertEquals("{\"n\":1}", event.at("/InitialExecutionState/Operations/0/ExecutionDetails/InputPayload")
|
||||
.asText());
|
||||
return "{\"Status\":\"SUCCEEDED\",\"Result\":\"\\\"child\\\"\"}";
|
||||
}
|
||||
if ("SUCCEEDED".equals(operation(event, "i1").get("Status").asText())) {
|
||||
return "{\"Status\":\"SUCCEEDED\",\"Result\":\"\\\"parent\\\"\"}";
|
||||
}
|
||||
return "{\"Status\":\"PENDING\"}";
|
||||
};
|
||||
after.script(dispatch);
|
||||
after.script(dispatch);
|
||||
restarted.recoverAfterRestart();
|
||||
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, restarted.get(childArn).getStatus());
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, restarted.get(parentArn).getStatus());
|
||||
assertEquals("\"child\"", restarted.get(parentArn).getOperations().get("i1").getResult());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTargetStartedByTheClosingCheckpointRunsOnceAfterARestart() {
|
||||
ScriptedInvoker before = new ScriptedInvoker();
|
||||
PersistentStorageFactory firstStorage = new PersistentStorageFactory(directory);
|
||||
DurableExecutionService first = newService(firstStorage, before, firstTaskOnly());
|
||||
before.script((service, event) -> {
|
||||
service.checkpoint(arn(event), token(event), null, List.of(chainedStart("i1", "plain-fn", "{\"n\":1}"),
|
||||
new DurableOperationUpdate("result", null, null, DurableOperationType.EXECUTION, null,
|
||||
DurableOperationAction.SUCCEED, "\"closed\"", null, null, null, null, null, null, null,
|
||||
null)));
|
||||
return "{\"Status\":\"SUCCEEDED\",\"Result\":\"\"}";
|
||||
});
|
||||
first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}", false));
|
||||
firstStorage.flushAll();
|
||||
|
||||
ScriptedInvoker second = new ScriptedInvoker();
|
||||
PersistentStorageFactory secondStorage = new PersistentStorageFactory(directory);
|
||||
newService(secondStorage, second).recoverAfterRestart();
|
||||
secondStorage.flushAll();
|
||||
ScriptedInvoker third = new ScriptedInvoker();
|
||||
newService(new PersistentStorageFactory(directory), third).recoverAfterRestart();
|
||||
|
||||
assertEquals(List.of("{\"n\":1}"), second.plainPayloads);
|
||||
assertEquals(List.of(), third.plainPayloads, "a completed target does not run again");
|
||||
}
|
||||
|
||||
/** Runs the first launch, the parent's invocation, and drops what it starts, as a crash would. */
|
||||
private static Executor firstTaskOnly() {
|
||||
int[] launched = {0};
|
||||
return task -> {
|
||||
if (launched[0]++ == 0) {
|
||||
task.run();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static AccountAwareStorageBackend<DurableExecution> executions(StorageFactory storage) {
|
||||
return storage.create("lambda", "lambda-durable-executions.json",
|
||||
new TypeReference<Map<String, DurableExecution>>() {});
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate chainedStart(String id, String functionName, String payload) {
|
||||
return new DurableOperationUpdate(id, null, null, DurableOperationType.CHAINED_INVOKE, "ChainedInvoke",
|
||||
DurableOperationAction.START, payload, null, null, null, null, null, null, functionName, null);
|
||||
}
|
||||
|
||||
private DurableExecutionService newService(StorageFactory storage, ScriptedInvoker invoker) {
|
||||
DurableExecutionService service = new DurableExecutionService(storage, MAPPER, clock, invoker, Runnable::run,
|
||||
return newService(storage, invoker, Runnable::run);
|
||||
}
|
||||
|
||||
private DurableExecutionService newService(StorageFactory storage, ScriptedInvoker invoker, Executor executor) {
|
||||
DurableExecutionService service = new DurableExecutionService(storage, MAPPER, clock, invoker, executor,
|
||||
Duration.ZERO);
|
||||
invoker.service = service;
|
||||
return service;
|
||||
@@ -139,12 +314,12 @@ class DurableExecutionServicePersistenceTest {
|
||||
|
||||
private static DurableOperationUpdate update(String id, DurableOperationType type, DurableOperationAction action,
|
||||
String payload, Integer waitSeconds) {
|
||||
return new DurableOperationUpdate(id, null, null, type, null, action, payload, null, null, waitSeconds, null, null, null);
|
||||
return new DurableOperationUpdate(id, null, null, type, null, action, payload, null, null, waitSeconds, null, null, null, null, null);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate callbackStart(String id, int timeoutSeconds) {
|
||||
return new DurableOperationUpdate(id, null, null, DurableOperationType.CALLBACK, "Callback",
|
||||
DurableOperationAction.START, null, null, null, null, null, timeoutSeconds, null);
|
||||
DurableOperationAction.START, null, null, null, null, null, timeoutSeconds, null, null, null);
|
||||
}
|
||||
|
||||
private static String arn(JsonNode event) {
|
||||
@@ -172,6 +347,10 @@ class DurableExecutionServicePersistenceTest {
|
||||
|
||||
final Deque<Script> scripts = new ArrayDeque<>();
|
||||
final List<JsonNode> events = new ArrayList<>();
|
||||
final List<String> plainPayloads = new ArrayList<>();
|
||||
String plainOutput = "null";
|
||||
/** The version the alias {@code live} points to. */
|
||||
String liveVersion = "1";
|
||||
DurableExecutionService service;
|
||||
|
||||
void script(Script script) {
|
||||
@@ -180,12 +359,25 @@ class DurableExecutionServicePersistenceTest {
|
||||
|
||||
@Override
|
||||
public ResolvedDurableTarget resolve(String accountId, String region, String functionName, String qualifier) {
|
||||
if ("plain-fn".equals(functionName)) {
|
||||
return new ResolvedDurableTarget(accountId, region, functionName,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:plain-fn", "$LATEST", false, 0, 0);
|
||||
}
|
||||
String version = "live".equals(qualifier) ? liveVersion : "1";
|
||||
if (qualifier != null && !"live".equals(qualifier)) {
|
||||
version = qualifier;
|
||||
}
|
||||
return new ResolvedDurableTarget(accountId, region, functionName,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:" + functionName + ":1", "1", true, 3600, 7);
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:" + functionName + ":" + version, version, true,
|
||||
3600, 7);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload) {
|
||||
if (!target.durable()) {
|
||||
plainPayloads.add(new String(payload, StandardCharsets.UTF_8));
|
||||
return new DurableInvocationResult("req", plainOutput.getBytes(StandardCharsets.UTF_8), null);
|
||||
}
|
||||
JsonNode event;
|
||||
try {
|
||||
event = MAPPER.readTree(payload);
|
||||
|
||||
+235
-9
@@ -28,7 +28,9 @@ import java.time.Duration;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
@@ -629,8 +631,205 @@ class DurableExecutionServiceTest {
|
||||
assertCallbackClosed(() -> service.completeCallback(callbackId, ACCOUNT, REGION, true, "\"late\"", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChainedInvokeOfAPlainFunctionHandsItsResultToTheNextInvocation() {
|
||||
invoker.plainFunctions.put("plain-fn", event -> handlerResponse("{\"echo\":" + event + "}"));
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(chainedStart("i1", "plain-fn", "{\"a\":1}")));
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> {
|
||||
JsonNode invoke = operation(event, "i1");
|
||||
assertEquals("SUCCEEDED", invoke.get("Status").asText());
|
||||
assertEquals("{\"echo\":{\"a\":1}}", invoke.at("/ChainedInvokeDetails/Result").asText());
|
||||
return succeeded("\"done\"");
|
||||
});
|
||||
|
||||
DurableExecution execution = service.get(start("exec-1", "{}", false).getExecutionArn());
|
||||
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, execution.getStatus());
|
||||
DurableHistoryEvent started = event(execution, "ChainedInvokeStarted");
|
||||
assertEquals(Map.of("FunctionName", "plain-fn", "Input", Map.of("Payload", "{\"a\":1}", "Truncated", false),
|
||||
"ExecutedVersion", "$LATEST"), started.getDetails().get("ChainedInvokeStartedDetails"));
|
||||
assertTrue(eventTypes(execution).contains("ChainedInvokeSucceeded"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChainedInvokeOfAPlainFunctionFailsWithItsErrorOrAnOversizedOutput() {
|
||||
invoker.plainFunctions.put("raising-fn",
|
||||
event -> functionError("{\"errorMessage\":\"child exploded\",\"errorType\":\"ValueError\"}"));
|
||||
invoker.plainFunctions.put("chatty-fn", event -> handlerResponse("\"" + "x".repeat(1024 * 1024) + "\""));
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(chainedStart("raise", "raising-fn", null),
|
||||
chainedStart("chatty", "chatty-fn", null)));
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> {
|
||||
assertEquals("ValueError", operation(event, "raise").at("/ChainedInvokeDetails/Error/ErrorType").asText());
|
||||
JsonNode chatty = operation(event, "chatty");
|
||||
assertEquals("FAILED", chatty.get("Status").asText());
|
||||
assertEquals("CHAINED_INVOKE output payload size must be less than or equal to 1048576 bytes.",
|
||||
chatty.at("/ChainedInvokeDetails/Error/ErrorMessage").asText());
|
||||
return succeeded("\"handled\"");
|
||||
});
|
||||
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, service.get(start("exec-1", "{}", false).getExecutionArn())
|
||||
.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChainedInvokeThatCannotStartFailsAtOnce() {
|
||||
invoker.childScript("child-fn", event -> succeeded("\"never\""));
|
||||
invoker.script(event -> {
|
||||
CheckpointResult result = checkpoint(event, token(event), List.of(chainedStart("missing", "missing-fn", null),
|
||||
chainedStart("unqualified", "child-fn", null)));
|
||||
assertEquals(List.of(DurableOperationStatus.FAILED, DurableOperationStatus.FAILED),
|
||||
result.newExecutionState().stream().map(DurableOperation::getStatus).toList());
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> succeeded("\"handled\""));
|
||||
|
||||
DurableExecution execution = service.get(start("exec-1", "{}", false).getExecutionArn());
|
||||
|
||||
DurableOperation missing = execution.getOperations().get("missing");
|
||||
assertEquals("ResourceNotFoundException", missing.getError().getErrorType());
|
||||
assertEquals("Function not found: arn:aws:lambda:us-east-1:000000000000:function:missing-fn:$LATEST",
|
||||
missing.getError().getErrorMessage());
|
||||
assertEquals("You cannot invoke a durable function using an unqualified ARN.",
|
||||
execution.getOperations().get("unqualified").getError().getErrorMessage());
|
||||
assertEquals(Map.of("FunctionName", "missing-fn"),
|
||||
event(execution, "ChainedInvokeStarted").getDetails().get("ChainedInvokeStartedDetails"));
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, execution.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDurableChildReportsHowItClosedToTheParentOperation() {
|
||||
invoker.childScript("child-fn", event -> succeeded("\"child result\""));
|
||||
invoker.childScript("child-fn", event -> handlerResponse(
|
||||
"{\"Status\":\"FAILED\",\"Error\":{\"ErrorMessage\":\"child failed\",\"ErrorType\":\"ChildError\"}}"));
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(chainedStart("ok", "child-fn:1", "{\"x\":1}"),
|
||||
chainedStart("bad", "child-fn:1", null)));
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> {
|
||||
assertEquals("\"child result\"", operation(event, "ok").at("/ChainedInvokeDetails/Result").asText());
|
||||
assertEquals("ChildError", operation(event, "bad").at("/ChainedInvokeDetails/Error/ErrorType").asText());
|
||||
return succeeded("\"done\"");
|
||||
});
|
||||
|
||||
DurableExecution parent = service.get(start("exec-1", "{}", false).getExecutionArn());
|
||||
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, parent.getStatus());
|
||||
String childArn = parent.getOperations().get("ok").getChildExecutionArn();
|
||||
DurableExecution child = service.get(childArn);
|
||||
assertEquals("{\"x\":1}", child.getInputPayload());
|
||||
assertNull(service.get(parent.getOperations().get("bad").getChildExecutionArn()).getInputPayload(),
|
||||
"a missing Payload starts the child with no input");
|
||||
assertEquals(parent.getExecutionArn(), child.getParentExecutionArn());
|
||||
assertEquals(childArn, ((Map<?, ?>) event(parent, "ChainedInvokeStarted").getDetails()
|
||||
.get("ChainedInvokeStartedDetails")).get("DurableExecutionArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDurableChildThatTimesOutOrIsStoppedClosesTheParentOperationTheSameWay() {
|
||||
invoker.childExecutionTimeoutSeconds = 60;
|
||||
invoker.childScript("child-fn", event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w1", 600)));
|
||||
return pending();
|
||||
});
|
||||
invoker.childScript("child-fn", event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w1", 600)));
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(chainedStart("slow", "child-fn:1", null),
|
||||
chainedStart("stopped", "child-fn:1", null)));
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> {
|
||||
assertEquals("STOPPED", operation(event, "stopped").get("Status").asText());
|
||||
assertEquals("stopped by test", operation(event, "stopped").at("/ChainedInvokeDetails/Error/ErrorMessage")
|
||||
.asText());
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> {
|
||||
JsonNode slow = operation(event, "slow");
|
||||
assertEquals("TIMED_OUT", slow.get("Status").asText());
|
||||
assertEquals("CHAINED_INVOKE timed out after 60 seconds.",
|
||||
slow.at("/ChainedInvokeDetails/Error/ErrorMessage").asText());
|
||||
assertEquals("ChainedInvoke.Timeout", slow.at("/ChainedInvokeDetails/Error/ErrorType").asText());
|
||||
return succeeded("\"done\"");
|
||||
});
|
||||
String parentArn = start("exec-1", "{}", false).getExecutionArn();
|
||||
|
||||
service.stop(service.get(parentArn).getOperations().get("stopped").getChildExecutionArn(),
|
||||
DurableErrorObject.of("stopped by test", "Test"));
|
||||
assertEquals(2, invoker.events.size(), "the stopped child woke the parent");
|
||||
|
||||
clock.advance(Duration.ofSeconds(59));
|
||||
service.sweep();
|
||||
assertEquals(2, invoker.events.size(), "the child has not timed out yet");
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
service.sweep();
|
||||
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, service.get(parentArn).getStatus());
|
||||
assertEquals(3, invoker.events.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChainedInvokeInTheBatchThatClosesTheExecutionStillRuns() {
|
||||
List<String> received = new ArrayList<>();
|
||||
invoker.plainFunctions.put("plain-fn", event -> {
|
||||
received.add(event.toString());
|
||||
return handlerResponse("\"ignored\"");
|
||||
});
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(chainedStart("i1", "plain-fn", "{\"n\":1}"),
|
||||
executionSucceed("\"closed\"")));
|
||||
return succeeded("");
|
||||
});
|
||||
|
||||
DurableExecution execution = service.get(start("exec-1", "{}", false).getExecutionArn());
|
||||
|
||||
assertEquals(List.of("{\"n\":1}"), received);
|
||||
assertEquals("\"closed\"", execution.getResult());
|
||||
assertTrue(eventTypes(execution).contains("ChainedInvokeStarted"));
|
||||
assertFalse(eventTypes(execution).contains("ChainedInvokeSucceeded"));
|
||||
assertEquals(1, invoker.events.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppingTheParentLeavesADurableChildRunning() {
|
||||
invoker.childScript("child-fn", event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w1", 600)));
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(chainedStart("i1", "child-fn:1", null)));
|
||||
return pending();
|
||||
});
|
||||
String parentArn = start("exec-1", "{}", false).getExecutionArn();
|
||||
String childArn = service.get(parentArn).getOperations().get("i1").getChildExecutionArn();
|
||||
|
||||
service.stop(parentArn, null);
|
||||
|
||||
assertEquals(DurableExecutionStatus.RUNNING, service.get(childArn).getStatus());
|
||||
assertFalse(eventTypes(service.get(parentArn)).contains("ChainedInvokeStopped"));
|
||||
}
|
||||
|
||||
// ──────────────────────────── helpers ────────────────────────────
|
||||
|
||||
private static DurableHistoryEvent event(DurableExecution execution, String eventType) {
|
||||
return execution.getHistory().stream().filter(event -> eventType.equals(event.getEventType())).findFirst()
|
||||
.orElseThrow(() -> new AssertionError("no " + eventType + " in " + eventTypes(execution)));
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate chainedStart(String id, String functionName, String payload) {
|
||||
return new DurableOperationUpdate(id, null, null, DurableOperationType.CHAINED_INVOKE, "ChainedInvoke",
|
||||
DurableOperationAction.START, payload, null, null, null, null, null, null, functionName, null);
|
||||
}
|
||||
|
||||
private static void assertCallbackClosed(Executable call) {
|
||||
AwsException rejected = assertThrows(AwsException.class, call);
|
||||
assertEquals("CallbackTimeoutException", rejected.getErrorCode());
|
||||
@@ -676,27 +875,27 @@ class DurableExecutionServiceTest {
|
||||
private static DurableOperationUpdate step(String id, DurableOperationAction action, String payload,
|
||||
DurableErrorObject error) {
|
||||
return new DurableOperationUpdate(id, null, null, DurableOperationType.STEP, "Step", action, payload, error,
|
||||
null, null, null, null, null);
|
||||
null, null, null, null, null, null, null);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate stepRetry(String id, int delaySeconds, DurableErrorObject error) {
|
||||
return new DurableOperationUpdate(id, null, null, DurableOperationType.STEP, "Step",
|
||||
DurableOperationAction.RETRY, null, error, delaySeconds, null, null, null, null);
|
||||
DurableOperationAction.RETRY, null, error, delaySeconds, null, null, null, null, null, null);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate callbackStart(String id, int timeoutSeconds, int heartbeatSeconds) {
|
||||
return new DurableOperationUpdate(id, null, null, DurableOperationType.CALLBACK, "Callback",
|
||||
DurableOperationAction.START, null, null, null, null, null, timeoutSeconds, heartbeatSeconds);
|
||||
DurableOperationAction.START, null, null, null, null, null, timeoutSeconds, heartbeatSeconds, null, null);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate waitStart(String id, int seconds) {
|
||||
return new DurableOperationUpdate(id, null, null, DurableOperationType.WAIT, "Wait",
|
||||
DurableOperationAction.START, null, null, null, seconds, null, null, null);
|
||||
DurableOperationAction.START, null, null, null, seconds, null, null, null, null, null);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate executionSucceed(String payload) {
|
||||
return new DurableOperationUpdate("execution-result", null, null, DurableOperationType.EXECUTION, null,
|
||||
DurableOperationAction.SUCCEED, payload, null, null, null, null, null, null);
|
||||
DurableOperationAction.SUCCEED, payload, null, null, null, null, null, null, null, null);
|
||||
}
|
||||
|
||||
private static DurableFunctionInvoker.DurableInvocationResult succeeded(String result) {
|
||||
@@ -721,7 +920,12 @@ class DurableExecutionServiceTest {
|
||||
|
||||
final Deque<Function<JsonNode, DurableInvocationResult>> scripts = new ArrayDeque<>();
|
||||
final List<JsonNode> events = new ArrayList<>();
|
||||
/** Durable functions other than the one under test, each with its own scripts. */
|
||||
final Map<String, Deque<Function<JsonNode, DurableInvocationResult>>> childScripts = new HashMap<>();
|
||||
/** Plain functions a chained invoke may call, answering the raw payload. */
|
||||
final Map<String, Function<JsonNode, DurableInvocationResult>> plainFunctions = new HashMap<>();
|
||||
int executionTimeoutSeconds = 3600;
|
||||
int childExecutionTimeoutSeconds = 3600;
|
||||
String functionName = FUNCTION;
|
||||
int retentionPeriodInDays = 7;
|
||||
|
||||
@@ -729,12 +933,26 @@ class DurableExecutionServiceTest {
|
||||
scripts.add(script);
|
||||
}
|
||||
|
||||
void childScript(String function, Function<JsonNode, DurableInvocationResult> script) {
|
||||
childScripts.computeIfAbsent(function, ignored -> new ArrayDeque<>()).add(script);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResolvedDurableTarget resolve(String accountId, String region, String functionName, String qualifier) {
|
||||
String version = qualifier == null ? "1" : qualifier;
|
||||
return new ResolvedDurableTarget(accountId, region, this.functionName,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:" + this.functionName + ":" + version, version, true,
|
||||
executionTimeoutSeconds, retentionPeriodInDays);
|
||||
String version = qualifier == null ? "$LATEST" : qualifier;
|
||||
if (plainFunctions.containsKey(functionName)) {
|
||||
return new ResolvedDurableTarget(accountId, region, functionName,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:" + functionName, version, false, 0, 0);
|
||||
}
|
||||
String name = FUNCTION.equals(functionName) ? this.functionName : functionName;
|
||||
if (!name.equals(this.functionName) && !childScripts.containsKey(name)) {
|
||||
throw new AwsException("ResourceNotFoundException", "Function not found: " + name, 404);
|
||||
}
|
||||
String durableVersion = qualifier == null ? "1" : qualifier;
|
||||
return new ResolvedDurableTarget(accountId, region, name,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:" + name + ":" + durableVersion, durableVersion,
|
||||
true, name.equals(this.functionName) ? executionTimeoutSeconds : childExecutionTimeoutSeconds,
|
||||
retentionPeriodInDays);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -745,6 +963,14 @@ class DurableExecutionServiceTest {
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
if (!target.durable()) {
|
||||
return plainFunctions.get(target.functionName()).apply(event);
|
||||
}
|
||||
Deque<Function<JsonNode, DurableInvocationResult>> queue = childScripts.get(target.functionName());
|
||||
if (queue != null) {
|
||||
Function<JsonNode, DurableInvocationResult> script = queue.poll();
|
||||
return script != null ? script.apply(event) : pending();
|
||||
}
|
||||
events.add(event);
|
||||
Function<JsonNode, DurableInvocationResult> script = scripts.poll();
|
||||
if (script == null) {
|
||||
|
||||
+47
@@ -441,6 +441,53 @@ class LambdaDurableProtocolIntegrationTest {
|
||||
.body("Events[3].CallbackSucceededDetails.Result.Payload", equalTo("{\"approved\":true}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChainedInvokeOfAnUnqualifiedDurableFunctionFailsInTheCheckpointResponse() throws Exception {
|
||||
Response accepted = given()
|
||||
.header("X-Amz-Invocation-Type", "Event")
|
||||
.header("X-Amz-Durable-Execution-Name", "chained-1")
|
||||
.body("{}")
|
||||
.post(LAMBDA + "/functions/" + FUNCTION + ":$LATEST/invocations");
|
||||
String arn = accepted.getHeader("X-Amz-Durable-Execution-Arn");
|
||||
|
||||
Invocation first = invoker.awaitInvocation(Duration.ofSeconds(30));
|
||||
JsonNode event = MAPPER.readTree(first.payload());
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"CheckpointToken": "%s",
|
||||
"Updates": [{"Id": "i1", "Name": "greet", "Type": "CHAINED_INVOKE", "SubType": "ChainedInvoke",
|
||||
"Action": "START", "ChainedInvokeOptions": {"FunctionName": "%s"}}]
|
||||
}
|
||||
""".formatted(event.get("CheckpointToken").asText(), FUNCTION))
|
||||
.when()
|
||||
.post(DURABLE + "/durable-executions/" + arn + "/checkpoint")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("NewExecutionState.Operations[0].Type", equalTo("CHAINED_INVOKE"))
|
||||
.body("NewExecutionState.Operations[0].Status", equalTo("FAILED"))
|
||||
.body("NewExecutionState.Operations[0].ChainedInvokeDetails.Error.ErrorType",
|
||||
equalTo("InvalidParameterValueException"))
|
||||
.body("NewExecutionState.Operations[0].ChainedInvokeDetails.Error.ErrorMessage",
|
||||
equalTo("You cannot invoke a durable function using an unqualified ARN."));
|
||||
first.response().complete(handlerResponse("{\"Status\": \"PENDING\"}"));
|
||||
|
||||
Invocation second = invoker.awaitInvocation(Duration.ofSeconds(30));
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(DURABLE + "/durable-executions/" + arn + "/history")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Events.EventType", equalTo(List.of("ExecutionStarted", "ChainedInvokeStarted",
|
||||
"ChainedInvokeFailed", "InvocationCompleted")))
|
||||
.body("Events[1].ChainedInvokeStartedDetails.FunctionName", equalTo(FUNCTION))
|
||||
.body("Events[2].ChainedInvokeFailedDetails.Error.Truncated", equalTo(true));
|
||||
second.response().complete(handlerResponse("{\"Status\": \"SUCCEEDED\", \"Result\": \"\\\"ok\\\"\"}"));
|
||||
}
|
||||
|
||||
private static DurableInvocationResult handlerResponse(String json) {
|
||||
return new DurableInvocationResult("req-" + System.nanoTime(), json.getBytes(StandardCharsets.UTF_8), null);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user