mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(lambda): run durable functions with checkpoints, waits and step retries (#5047)
* feat(lambda): run durable functions with checkpoints, waits and step retries
Invoking a durable function starts a durable execution, through Invoke or through an ARN (EventBridge, Scheduler, function URLs, destinations). The function checkpoints through CheckpointDurableExecution and GetDurableExecutionState, and Floci re-invokes it when a wait or a step retry comes due. GetDurableExecution, GetDurableExecutionHistory, ListDurableExecutionsByFunction and StopDurableExecution read and stop executions. Timers are persisted deadlines fired by a background sweep, so an execution survives a restart. Callbacks and chained invokes are rejected at checkpoint time.
* fix(iam): authorize durable execution actions against the owning function
A durable execution route has no /functions/ segment, so its resource fell back to *. The function name now comes from the execution ARN in the path.
* fix(lambda): keep durable executions inside their account
The execution APIs took the account from the ARN in the path, so another account could read or stop an execution. An ARN of another account is now ResourceNotFoundException.
* fix(lambda): limit the error size of an EXECUTION checkpoint too
* fix(lambda): reject an EXECUTION close that carries the other result kind
AWS rejects SUCCEED with an Error and FAIL with a Payload on the EXECUTION operation, as it does for steps.
* fix(lambda): spend a durable wake-up when a failed invocation schedules its retry
* fix(lambda): keep a durable crash retry's backoff across a restart
* fix(lambda): bound the durable execution locks
A lock per execution ARN was kept forever, even for an ARN that did not exist. A fixed set of striped locks replaces it. Locks are never nested, so a shared stripe cannot deadlock.
* fix(lambda): accept PAUSED, PAUSING and DELETING as durable status filters
AWS accepts them and answers an empty list, since Floci never puts an execution in those states.
* fix(lambda): reject a non-finite durable list timestamp
* test(lambda): resume a durable execution from its JSON file after a restart
* fix(lambda): keep durable executions inside their region
An execution ARN of another region now answers ResourceNotFoundException "Function not found", as AWS does, instead of reaching the execution past the IAM check of the request region.
* fix(lambda): validate durable list parameters before an empty status filter answers
Statuses of only PAUSED, PAUSING or DELETING still checks MaxItems and Marker, as AWS does. The bad Marker message is "Invalid Marker".
* perf(lambda): skip the execution scan for a status filter that matches nothing
Statuses of only PAUSED, PAUSING or DELETING now checks MaxItems and Marker without listing the account's executions.
* test(lambda): drop durable tests that repeat other coverage
The in-memory restart test repeats the persistence test, and the Docker success case repeats the compat suite's checkpoint loop. The Docker test keeps the failure case.
* fix(lambda): re-attach a durable execution name only on the same version
AWS keeps execution names unique per function across versions. A sync Invoke of another version with the same name and payload is DurableExecutionAlreadyStartedException, not the existing execution.
* chore(lambda): simplify the durable execution engine
Drop stored fields nothing reads, share the unseen-operations and
page-cursor helpers, skip the name scan for a generated name, and save
an execution once per invocation instead of twice.
* fix(lambda): reject a non-integer durable MaxItems as AWS does
AWS answers MaxItems=x on the durable execution APIs with
SerializationException "'x' can not be converted to Integer".
* docs(lambda): list the durable execution size limits as not emulated
* fix(iam): authorize durable execution actions against the execution ARN
The durable execution actions take the durable execution resource,
function:name:version/durable-execution/name/id. A role allowed on
function:name:* may checkpoint, one allowed only on the unqualified
function ARN is denied.
* fix(lambda): answer an unknown durable execution on checkpoint as a bad token
CheckpointDurableExecution and GetDurableExecutionState do not model
ResourceNotFoundException. AWS answers InvalidParameterValueException:
"Checkpoint token is not valid for the durable execution ARN" for a
token minted for another execution, "Invalid checkpoint token" otherwise.
* fix(lambda): replay a durable checkpoint retried with the same ClientToken
AWS answers a retry of the last checkpoint with the same ClientToken
with the same state and a usable next token, even though the request
token is spent. A different ClientToken, a retry after the next
checkpoint, or a retry of the checkpoint that closed the execution is
still an invalid checkpoint token.
* fix(lambda): validate durable list filters as AWS does
ListDurableExecutionsByFunction takes one status at most and answers
more with InvalidParameterValueException "Cannot filter by more than one
status". An unreadable StartedAfter or StartedBefore is
SerializationException "'<value>' can not be converted to Date", and a
plain date is accepted. Type errors come first, then MaxItems and status
values, then the single-status rule, then the function lookup.
* docs(lambda): note the history IncludeExecutionData default
* fix(lambda): report durable MaxItems and Statuses errors as AWS does
AWS puts an invalid MaxItems and an invalid Statuses into one
ValidationException ("2 validation errors detected: ...; ..."), MaxItems
first. A negative MaxItems must be greater than or equal to 0. MaxItems
is checked before the execution or function is looked up.
* refactor(lambda): share one durable execution ARN pattern with IAM
IAM and the durable execution service now recognize an execution ARN
with the same pattern, the one AWS validates it with.
* fix(lambda): replay a durable checkpoint answer as it was sent
On AWS a retry with the same ClientToken returns the operations as the
first answer had them: a WAIT stays STARTED in the retry even after it
has elapsed, while a fresh checkpoint reports it SUCCEEDED.
This commit is contained in:
1 parent
383c32443d
commit
6a3bc12769
49 files changed
+5007
-10
No files matched your search
@@ -24,6 +24,7 @@ import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.lambda.DynamoDbStreamsEventSourcePoller;
|
||||
import io.github.hectorvent.floci.services.lambda.KinesisEventSourcePoller;
|
||||
import io.github.hectorvent.floci.services.lambda.SqsEventSourcePoller;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableExecutionService;
|
||||
import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerManager;
|
||||
import io.github.hectorvent.floci.services.neptune.proxy.NeptuneProxyManager;
|
||||
import io.github.hectorvent.floci.services.pipes.PipesService;
|
||||
@@ -73,6 +74,7 @@ class EmulatorLifecycleTest {
|
||||
@Mock private EmulatorConfig config;
|
||||
@Mock private EmulatorConfig.StorageConfig storageConfig;
|
||||
@Mock private EmulatorConfig.ServicesConfig servicesConfig;
|
||||
@Mock private EmulatorConfig.LambdaServiceConfig lambdaServiceConfig;
|
||||
@Mock private EmulatorConfig.Ec2ServiceConfig ec2ServiceConfig;
|
||||
@Mock private EmulatorConfig.EcsServiceConfig ecsServiceConfig;
|
||||
@Mock private EmulatorConfig.EcsTaskRoleCredentialsConfig ecsTaskRoleCredentialsConfig;
|
||||
@@ -116,6 +118,7 @@ class EmulatorLifecycleTest {
|
||||
@Mock private EmulatorConfig.IamServiceConfig iamServiceConfig;
|
||||
@Mock private SchemaCreationWorker schemaCreationWorker;
|
||||
@Mock private StepFunctionsService stepFunctionsService;
|
||||
@Mock private DurableExecutionService durableExecutionService;
|
||||
@Mock private Instance<ContainerTeardown> containerTeardowns;
|
||||
@Mock private DynamoDbRuntime dynamoDbRuntime;
|
||||
@Mock private RedshiftDynamoDbZeroEtlConsumer redshiftZeroEtlConsumer;
|
||||
@@ -137,6 +140,8 @@ class EmulatorLifecycleTest {
|
||||
Mockito.lenient().when(elastiCacheServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(servicesConfig.elb()).thenReturn(elbServiceConfig);
|
||||
Mockito.lenient().when(elbServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(servicesConfig.lambda()).thenReturn(lambdaServiceConfig);
|
||||
Mockito.lenient().when(lambdaServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(servicesConfig.eks()).thenReturn(eksServiceConfig);
|
||||
Mockito.lenient().when(eksServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(servicesConfig.timestreamInfluxdb()).thenReturn(timestreamInfluxDbServiceConfig);
|
||||
@@ -158,7 +163,8 @@ class EmulatorLifecycleTest {
|
||||
elbV2Service, elbClassicService, ecsService,
|
||||
initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller,
|
||||
pipesService, ec2MetadataServer, ecsTaskRoleCredentialsServer, ecrRegistryManager, flociUiManager, initLifecycleState,
|
||||
schemaCreationWorker, stepFunctionsService, containerTeardowns, persistentPathValidator,
|
||||
schemaCreationWorker, stepFunctionsService, durableExecutionService, containerTeardowns,
|
||||
persistentPathValidator,
|
||||
dynamoDbRuntime, redshiftZeroEtlConsumer);
|
||||
Mockito.lenient().when(containerTeardowns.iterator())
|
||||
.thenReturn(java.util.Collections.emptyIterator());
|
||||
|
||||
@@ -210,6 +210,25 @@ class IamActionRegistryTest {
|
||||
assertEquals("lambda:InvokeFunction", registry.resolveRoute("lambda", invoke));
|
||||
}
|
||||
|
||||
@Test
|
||||
void durableExecutionRoutesResolveToTheirActions() {
|
||||
String arn = "arn%3Aaws%3Alambda%3Aus-east-1%3A000000000000%3Afunction%3Af%3A%24LATEST"
|
||||
+ "%2Fdurable-execution%2Fname%2Fid";
|
||||
String base = "/2025-12-01/durable-executions/" + arn;
|
||||
assertEquals("lambda:CheckpointDurableExecution", lambdaAction("POST", base + "/checkpoint"));
|
||||
assertEquals("lambda:GetDurableExecutionState", lambdaAction("GET", base + "/state"));
|
||||
assertEquals("lambda:GetDurableExecutionHistory", lambdaAction("GET", base + "/history"));
|
||||
assertEquals("lambda:StopDurableExecution", lambdaAction("POST", base + "/stop"));
|
||||
assertEquals("lambda:GetDurableExecution", lambdaAction("GET", base));
|
||||
assertEquals("lambda:ListDurableExecutionsByFunction",
|
||||
lambdaAction("GET", "/2025-12-01/functions/f/durable-executions"));
|
||||
}
|
||||
|
||||
private String lambdaAction(String method, String path) {
|
||||
return registry.resolveRoute("lambda",
|
||||
mockCtx(method, path, new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEncodedSlashStaysInsideItsPathParameter() {
|
||||
assertEquals("ses:GetSuppressedDestination", registry.resolveRoute("ses",
|
||||
|
||||
@@ -595,4 +595,21 @@ class ResourceArnBuilderTest {
|
||||
String arn = builder.build("lambda", ctx, "us-east-1", "000000000000");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function", arn);
|
||||
}
|
||||
|
||||
@Test
|
||||
void lambdaDurableExecutionRoutesNameTheExecution() {
|
||||
when(uriInfo.getPath()).thenReturn("/2025-12-01/durable-executions/arn:aws:lambda:us-east-1:000000000000:"
|
||||
+ "function:my-function:$LATEST/durable-execution/run-1/0b1c/stop");
|
||||
String arn = builder.build("lambda", ctx, "us-east-1", "000000000000");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function:$LATEST/durable-execution/run-1/0b1c",
|
||||
arn);
|
||||
}
|
||||
|
||||
@Test
|
||||
void lambdaDurableExecutionGetNamesTheExecution() {
|
||||
when(uriInfo.getPath()).thenReturn("/2025-12-01/durable-executions/arn:aws:lambda:us-east-1:000000000000:"
|
||||
+ "function:my-function:1/durable-execution/run-1/0b1c");
|
||||
String arn = builder.build("lambda", ctx, "us-east-1", "000000000000");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function:1/durable-execution/run-1/0b1c", arn);
|
||||
}
|
||||
}
|
||||
+3
@@ -77,6 +77,7 @@ class LambdaArnInvocationAccountTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
new ObjectMapper());
|
||||
|
||||
InvokeResult result = service.invokeArn(functionArn, "{}".getBytes(), InvocationType.Event);
|
||||
@@ -140,6 +141,7 @@ class LambdaArnInvocationAccountTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
new ObjectMapper());
|
||||
|
||||
InvokeResult versionResult = service.invokeArn(
|
||||
@@ -313,6 +315,7 @@ class LambdaArnInvocationAccountTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
new ObjectMapper());
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -31,7 +31,7 @@ class LambdaInvokeClientContextIntegrationTest {
|
||||
}
|
||||
|
||||
private void stubInvoke() {
|
||||
when(lambdaService.invoke(any(), any(), any(), any(), any(), any()))
|
||||
when(lambdaService.invoke(any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(new InvokeResult(200, null, "{}".getBytes(), null, "req"));
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ class LambdaInvokeClientContextIntegrationTest {
|
||||
.then().statusCode(200);
|
||||
|
||||
verify(lambdaService).invoke(any(), eq("ctx-fn"), any(), any(),
|
||||
eq(InvocationType.RequestResponse), eq(CONTEXT_JSON));
|
||||
eq(InvocationType.RequestResponse), eq(CONTEXT_JSON), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -63,7 +63,7 @@ class LambdaInvokeClientContextIntegrationTest {
|
||||
.then().statusCode(200);
|
||||
|
||||
verify(lambdaService).invoke(any(), eq("ctx-fn-event"), any(), any(),
|
||||
eq(InvocationType.Event), isNull());
|
||||
eq(InvocationType.Event), isNull(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -80,6 +80,6 @@ class LambdaInvokeClientContextIntegrationTest {
|
||||
.then().statusCode(200);
|
||||
|
||||
verify(lambdaService).invoke(any(), eq("ctx-fn-utf"), any(), any(),
|
||||
eq(InvocationType.RequestResponse), eq("{\"custom\":{\"name\":\"caf\\u00E9\"}}"));
|
||||
eq(InvocationType.RequestResponse), eq("{\"custom\":{\"name\":\"caf\\u00E9\"}}"), isNull());
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package io.github.hectorvent.floci.services.lambda.durable;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableErrorObject;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableExecution;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperation;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperationAction;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperationStatus;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperationType;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperationUpdate;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/** The batch rules of CheckpointDurableExecution, and that a rejected batch changes nothing. */
|
||||
class DurableCheckpointApplierTest {
|
||||
|
||||
private static final long NOW = 1_700_000_000_000L;
|
||||
|
||||
@Test
|
||||
void executionUpdateMustBeTheOnlyOneAndTheLast() {
|
||||
assertRejected(List.of(executionSucceed(), executionSucceed()), "Cannot checkpoint multiple EXECUTION updates.");
|
||||
assertRejected(List.of(executionSucceed(), stepStart("s1", null)), "EXECUTION checkpoint must be the last update.");
|
||||
}
|
||||
|
||||
@Test
|
||||
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)),
|
||||
"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)),
|
||||
"Cannot provide a Payload for FAIL action.");
|
||||
}
|
||||
|
||||
@Test
|
||||
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)),
|
||||
"Error object size must be less than 32768 bytes.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateIdsAreRejectedUnlessAStartIsClosedInTheSameBatch() {
|
||||
assertRejected(List.of(stepStart("s1", null), stepStart("s1", null)),
|
||||
"Cannot checkpoint multiple operations with the same ID.");
|
||||
assertRejected(List.of(waitStart("w1"), waitStart("w1")), "Cannot checkpoint multiple operations with the same ID.");
|
||||
DurableExecution execution = execution();
|
||||
DurableCheckpointApplier.apply(execution, List.of(stepStart("s1", null), update("s1", null,
|
||||
DurableOperationType.STEP, DurableOperationAction.SUCCEED, "1")), NOW);
|
||||
assertEquals(DurableOperationStatus.SUCCEEDED, execution.getOperations().get("s1").getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parentMustBeAContextAndMetadataMustStayConsistent() {
|
||||
assertRejected(List.of(stepStart("s1", "missing")), "Invalid parent operation id.");
|
||||
DurableExecution execution = execution();
|
||||
DurableCheckpointApplier.apply(execution, List.of(stepStart("s1", null)), NOW);
|
||||
assertEquals("Inconsistent operation type.", reject(execution, List.of(waitStart("s1"))));
|
||||
assertEquals("Inconsistent parent operation id.", reject(execution, List.of(stepStart("ctx", null),
|
||||
update("s1", "ctx", DurableOperationType.STEP, DurableOperationAction.SUCCEED, "1"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stepTransitionsAreGuarded() {
|
||||
DurableExecution execution = execution();
|
||||
DurableCheckpointApplier.apply(execution, List.of(stepStart("s1", null)), NOW);
|
||||
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))));
|
||||
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,
|
||||
DurableOperationAction.FAIL, null)), NOW);
|
||||
assertEquals("Invalid current STEP state to close.", reject(execution, List.of(
|
||||
update("s1", null, DurableOperationType.STEP, DurableOperationAction.SUCCEED, "1"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitsNeedOptionsAndCancelOnlyWhileStarted() {
|
||||
assertRejected(List.of(update("w1", null, DurableOperationType.WAIT, DurableOperationAction.START, null)),
|
||||
"Update for WAIT operation requires WaitOptions.");
|
||||
assertRejected(List.of(update("w1", null, DurableOperationType.WAIT, DurableOperationAction.CANCEL, null)),
|
||||
"Cannot cancel a WAIT that does not exist or has already completed.");
|
||||
DurableExecution execution = execution();
|
||||
DurableCheckpointApplier.apply(execution, List.of(waitStart("w1")), NOW);
|
||||
assertEquals("Cannot start a WAIT that already exist.", reject(execution, List.of(waitStart("w1"))));
|
||||
DurableCheckpointApplier.apply(execution, List.of(update("w1", null, DurableOperationType.WAIT,
|
||||
DurableOperationAction.CANCEL, null)), NOW);
|
||||
assertEquals(DurableOperationStatus.CANCELLED, execution.getOperations().get("w1").getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delaysOutsideTheirRangeAreValidationErrors() {
|
||||
AwsException rejected = assertThrows(AwsException.class, () -> DurableWire.parseUpdates(
|
||||
List.of(Map.of("Id", "w1", "Type", "WAIT", "Action", "START", "WaitOptions", Map.of("WaitSeconds", 0)))));
|
||||
assertEquals("ValidationException", rejected.getErrorCode());
|
||||
assertEquals("1 validation error detected: Value '0' at 'waitOptions.waitSeconds' failed to satisfy "
|
||||
+ "constraint: Member must have value greater than or equal to 1", rejected.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void callbacksAndChainedInvokesAreNotSupportedYet() {
|
||||
assertRejected(List.of(update("c1", null, DurableOperationType.CALLBACK, DurableOperationAction.START, null)),
|
||||
"CALLBACK operations are not supported yet");
|
||||
assertRejected(List.of(update("i1", null, DurableOperationType.CHAINED_INVOKE, DurableOperationAction.START,
|
||||
null)), "CHAINED_INVOKE operations are not supported yet");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRejectedBatchLeavesTheExecutionUntouched() {
|
||||
DurableExecution execution = execution();
|
||||
long sequence = execution.getChangeSequence();
|
||||
int events = execution.getHistory().size();
|
||||
reject(execution, List.of(stepStart("s1", null), waitStart("w1"), waitStart("w1")));
|
||||
assertEquals(1, execution.getOperations().size());
|
||||
assertEquals(sequence, execution.getChangeSequence());
|
||||
assertEquals(events, execution.getHistory().size());
|
||||
}
|
||||
|
||||
private static void assertRejected(List<DurableOperationUpdate> updates, String message) {
|
||||
assertEquals(message, reject(execution(), updates));
|
||||
}
|
||||
|
||||
private static String reject(DurableExecution execution, List<DurableOperationUpdate> updates) {
|
||||
AwsException rejected = assertThrows(AwsException.class,
|
||||
() -> DurableCheckpointApplier.apply(execution, updates, NOW));
|
||||
assertEquals(400, rejected.getHttpStatus());
|
||||
assertEquals("InvalidParameterValueException", rejected.getErrorCode());
|
||||
return rejected.getMessage();
|
||||
}
|
||||
|
||||
private static DurableExecution execution() {
|
||||
DurableExecution execution = new DurableExecution();
|
||||
execution.setExecutionId("exec-id");
|
||||
execution.setName("exec");
|
||||
execution.setMaxResultBytes(DurableExecutionService.ASYNC_PAYLOAD_LIMIT);
|
||||
DurableOperation root = new DurableOperation();
|
||||
root.setId("exec-id");
|
||||
root.setType(DurableOperationType.EXECUTION);
|
||||
root.setStatus(DurableOperationStatus.STARTED);
|
||||
root.setStartTimestamp(NOW);
|
||||
root.setChangeSequence(execution.nextChangeSequence());
|
||||
execution.getOperations().put("exec-id", root);
|
||||
return execution;
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate stepStart(String id, String parentId) {
|
||||
return update(id, parentId, DurableOperationType.STEP, DurableOperationAction.START, null);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate waitStart(String id) {
|
||||
return new DurableOperationUpdate(id, null, null, DurableOperationType.WAIT, null, DurableOperationAction.START,
|
||||
null, null, null, 5, null);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate executionSucceed() {
|
||||
return update("result", null, DurableOperationType.EXECUTION, DurableOperationAction.SUCCEED, "{}");
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
package io.github.hectorvent.floci.services.lambda.durable;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.PersistentStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.core.storage.WriteProfile;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableExecutionService.StartRequest;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableExecution;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableExecutionStatus;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableHistoryEvent;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperationAction;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperationType;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperationUpdate;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
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 static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* A restart reloads executions from the JSON file, not from shared objects, so this proves that
|
||||
* operations, history, deadlines and the invocation lane survive serialization.
|
||||
*/
|
||||
class DurableExecutionServicePersistenceTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
private final MutableClock clock = new MutableClock();
|
||||
|
||||
@Test
|
||||
void aRunningExecutionResumesFromDiskAfterARestart() {
|
||||
ScriptedInvoker before = new ScriptedInvoker();
|
||||
PersistentStorageFactory firstStorage = new PersistentStorageFactory(directory);
|
||||
DurableExecutionService first = newService(firstStorage, before);
|
||||
before.script((service, event) -> {
|
||||
service.checkpoint(arn(event), token(event), null, List.of(
|
||||
update("s1", DurableOperationType.STEP, DurableOperationAction.START, null, null),
|
||||
update("s1", DurableOperationType.STEP, DurableOperationAction.SUCCEED, "\"saved\"", null),
|
||||
update("w1", DurableOperationType.WAIT, DurableOperationAction.START, null, 5)));
|
||||
return "{\"Status\":\"PENDING\"}";
|
||||
});
|
||||
String executionArn = first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{\"a\":1}",
|
||||
false)).getExecutionArn();
|
||||
String oldToken = token(before.events.get(0));
|
||||
firstStorage.flushAll();
|
||||
|
||||
ScriptedInvoker after = new ScriptedInvoker();
|
||||
DurableExecutionService restarted = newService(new PersistentStorageFactory(directory), after);
|
||||
after.script((service, event) -> {
|
||||
assertEquals("SUCCEEDED", operation(event, "s1").get("Status").asText());
|
||||
assertEquals("\"saved\"", operation(event, "s1").at("/StepDetails/Result").asText());
|
||||
assertEquals("STARTED", operation(event, "w1").get("Status").asText());
|
||||
return "{\"Status\":\"PENDING\"}";
|
||||
});
|
||||
after.script((service, event) -> {
|
||||
assertEquals("SUCCEEDED", operation(event, "w1").get("Status").asText());
|
||||
return "{\"Status\":\"SUCCEEDED\",\"Result\":\"\\\"done\\\"\"}";
|
||||
});
|
||||
restarted.recoverAfterRestart();
|
||||
|
||||
assertThrows(AwsException.class, () -> restarted.checkpoint(executionArn, oldToken, null, List.of()));
|
||||
clock.advance(Duration.ofSeconds(5));
|
||||
restarted.sweep();
|
||||
|
||||
DurableExecution execution = restarted.get(executionArn);
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, execution.getStatus());
|
||||
assertEquals("\"done\"", execution.getResult());
|
||||
assertEquals("{\"a\":1}", execution.getInputPayload());
|
||||
assertEquals(List.of("ExecutionStarted", "StepStarted", "StepSucceeded", "WaitStarted", "InvocationCompleted",
|
||||
"InvocationCompleted", "WaitSucceeded", "InvocationCompleted", "ExecutionSucceeded"),
|
||||
execution.getHistory().stream().map(DurableHistoryEvent::getEventType).toList());
|
||||
}
|
||||
|
||||
private DurableExecutionService newService(StorageFactory storage, ScriptedInvoker invoker) {
|
||||
DurableExecutionService service = new DurableExecutionService(storage, MAPPER, clock, invoker, Runnable::run,
|
||||
Duration.ZERO);
|
||||
invoker.service = service;
|
||||
return service;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private static String arn(JsonNode event) {
|
||||
return event.get("DurableExecutionArn").asText();
|
||||
}
|
||||
|
||||
private static String token(JsonNode event) {
|
||||
return event.get("CheckpointToken").asText();
|
||||
}
|
||||
|
||||
private static JsonNode operation(JsonNode event, String id) {
|
||||
for (JsonNode operation : event.at("/InitialExecutionState/Operations")) {
|
||||
if (id.equals(operation.get("Id").asText())) {
|
||||
return operation;
|
||||
}
|
||||
}
|
||||
throw new AssertionError("no operation " + id);
|
||||
}
|
||||
|
||||
private interface Script {
|
||||
String run(DurableExecutionService service, JsonNode event);
|
||||
}
|
||||
|
||||
private static final class ScriptedInvoker implements DurableFunctionInvoker {
|
||||
|
||||
final Deque<Script> scripts = new ArrayDeque<>();
|
||||
final List<JsonNode> events = new ArrayList<>();
|
||||
DurableExecutionService service;
|
||||
|
||||
void script(Script script) {
|
||||
scripts.add(script);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResolvedDurableTarget resolve(String accountId, String region, String functionName, String qualifier) {
|
||||
return new ResolvedDurableTarget(accountId, region, functionName,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:" + functionName + ":1", "1", true, 3600, 7);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload) {
|
||||
JsonNode event;
|
||||
try {
|
||||
event = MAPPER.readTree(payload);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
events.add(event);
|
||||
Script script = scripts.poll();
|
||||
String body = script == null ? "{\"Status\":\"FAILED\",\"Error\":{\"ErrorMessage\":\"no script\"}}"
|
||||
: script.run(service, event);
|
||||
return new DurableInvocationResult("req", body.getBytes(StandardCharsets.UTF_8), null);
|
||||
}
|
||||
}
|
||||
|
||||
/** Each instance reads the JSON file from disk, as a restarted Floci does. */
|
||||
private static final class PersistentStorageFactory extends StorageFactory {
|
||||
|
||||
private final Path directory;
|
||||
private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
|
||||
|
||||
PersistentStorageFactory(Path directory) {
|
||||
super(null, null);
|
||||
this.directory = directory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return create(serviceName, fileName, typeReference, WriteProfile.DEFAULT);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference,
|
||||
WriteProfile profile) {
|
||||
return (AccountAwareStorageBackend<V>) stores.computeIfAbsent(fileName, ignored -> {
|
||||
PersistentStorage<String, V> storage = new PersistentStorage<>(directory.resolve(fileName),
|
||||
typeReference);
|
||||
storage.load();
|
||||
return new AccountAwareStorageBackend<>(storage, null, ACCOUNT);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flushAll() {
|
||||
stores.values().forEach(StorageBackend::flush);
|
||||
}
|
||||
}
|
||||
}
|
||||
+629
@@ -0,0 +1,629 @@
|
||||
package io.github.hectorvent.floci.services.lambda.durable;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableExecutionService.CheckpointResult;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableExecutionService.ListRequest;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableExecutionService.StartRequest;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableErrorObject;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableExecution;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableExecutionStatus;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableHistoryEvent;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperation;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperationAction;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperationStatus;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperationType;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.model.DurableOperationUpdate;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Drives the engine with a scripted stand-in for the function. The script receives the invocation
|
||||
* event, checkpoints through the service like the SDK would, and returns the handler response.
|
||||
* An inline executor and a zero retry delay make every invocation chain run on the test thread.
|
||||
*/
|
||||
class DurableExecutionServiceTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String FUNCTION = "durable-fn";
|
||||
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:durable-fn:1";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private final MutableClock clock = new MutableClock();
|
||||
private InMemoryStorageFactory storage;
|
||||
private ScriptedInvoker invoker;
|
||||
private DurableExecutionService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
storage = new InMemoryStorageFactory(ACCOUNT);
|
||||
invoker = new ScriptedInvoker();
|
||||
service = newService(storage, invoker, clock);
|
||||
}
|
||||
|
||||
@Test
|
||||
void startInvokesTheFunctionWithTheExecutionOperationAndAToken() {
|
||||
invoker.script(event -> succeeded("\"done\""));
|
||||
|
||||
DurableExecution execution = start("exec-1", "{\"a\":1}", true);
|
||||
|
||||
JsonNode event = invoker.events.get(0);
|
||||
assertEquals(execution.getExecutionArn(), event.get("DurableExecutionArn").asText());
|
||||
assertTrue(execution.getExecutionArn().startsWith(FUNCTION_ARN + "/durable-execution/exec-1/"));
|
||||
assertFalse(event.get("CheckpointToken").asText().isEmpty());
|
||||
assertEquals(execution.getExecutionId(), event.get("UpdatedOperationIds").get(0).asText());
|
||||
JsonNode root = event.get("InitialExecutionState").get("Operations").get(0);
|
||||
assertEquals(execution.getExecutionId(), root.get("Id").asText());
|
||||
assertEquals("EXECUTION", root.get("Type").asText());
|
||||
assertEquals("STARTED", root.get("Status").asText());
|
||||
assertEquals("{\"a\":1}", root.get("ExecutionDetails").get("InputPayload").asText());
|
||||
assertEquals("", event.get("InitialExecutionState").get("NextMarker").asText());
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, service.get(execution.getExecutionArn()).getStatus());
|
||||
assertEquals("\"done\"", service.get(execution.getExecutionArn()).getResult());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stepCheckpointIsReturnedAsNewStateAndTheResultClosesTheExecution() {
|
||||
invoker.script(event -> {
|
||||
CheckpointResult first = checkpoint(event, token(event),
|
||||
List.of(step("s1", DurableOperationAction.START, null, null), step("s1",
|
||||
DurableOperationAction.SUCCEED, "42", null)));
|
||||
assertEquals(1, first.newExecutionState().size());
|
||||
assertEquals(DurableOperationStatus.SUCCEEDED, first.newExecutionState().get(0).getStatus());
|
||||
assertEquals(1, first.newExecutionState().get(0).getAttempt());
|
||||
assertNotNull(first.checkpointToken());
|
||||
CheckpointResult poll = checkpoint(event, first.checkpointToken(), List.of());
|
||||
assertTrue(poll.newExecutionState().isEmpty(), "nothing changed since the last response");
|
||||
return succeeded("\"ok\"");
|
||||
});
|
||||
|
||||
DurableExecution execution = service.get(start("exec-1", "{}", true).getExecutionArn());
|
||||
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, execution.getStatus());
|
||||
assertEquals("\"ok\"", execution.getResult());
|
||||
assertEquals(List.of("ExecutionStarted", "StepStarted", "StepSucceeded", "InvocationCompleted",
|
||||
"ExecutionSucceeded"), eventTypes(execution));
|
||||
assertNull(execution.getCurrentInvocationId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitCompletesWhenTheSweepReachesItsDeadlineAndTheFunctionIsReinvoked() {
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w1", 5)));
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> {
|
||||
JsonNode wait = operation(event, "w1");
|
||||
assertEquals("SUCCEEDED", wait.get("Status").asText());
|
||||
assertEquals("w1", event.get("UpdatedOperationIds").get(0).asText());
|
||||
assertEquals(1, event.get("UpdatedOperationIds").size());
|
||||
return succeeded("\"after wait\"");
|
||||
});
|
||||
|
||||
String arn = start("exec-1", "{}", false).getExecutionArn();
|
||||
assertEquals(DurableExecutionStatus.RUNNING, service.get(arn).getStatus());
|
||||
service.sweep();
|
||||
assertEquals(1, invoker.events.size(), "the wait is not due yet");
|
||||
|
||||
clock.advance(Duration.ofSeconds(5));
|
||||
service.sweep();
|
||||
|
||||
assertEquals(2, invoker.events.size());
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, service.get(arn).getStatus());
|
||||
assertTrue(eventTypes(service.get(arn)).containsAll(List.of("WaitStarted", "WaitSucceeded")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stepRetryBecomesReadyAfterItsDelay() {
|
||||
invoker.script(event -> {
|
||||
CheckpointResult result = checkpoint(event, token(event), List.of(
|
||||
step("s1", DurableOperationAction.START, null, null),
|
||||
stepRetry("s1", 3, DurableErrorObject.of("boom", "Error"))));
|
||||
assertEquals(DurableOperationStatus.PENDING, result.newExecutionState().get(0).getStatus());
|
||||
assertNotNull(result.newExecutionState().get(0).getNextAttemptTimestamp());
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> {
|
||||
assertEquals("READY", operation(event, "s1").get("Status").asText());
|
||||
assertFalse(operation(event, "s1").get("StepDetails").has("NextAttemptTimestamp"));
|
||||
checkpoint(event, token(event), List.of(step("s1", DurableOperationAction.START, null, null),
|
||||
step("s1", DurableOperationAction.SUCCEED, "ok", null)));
|
||||
return succeeded("\"done\"");
|
||||
});
|
||||
|
||||
String arn = start("exec-1", "{}", false).getExecutionArn();
|
||||
clock.advance(Duration.ofSeconds(3));
|
||||
service.sweep();
|
||||
|
||||
DurableExecution execution = service.get(arn);
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, execution.getStatus());
|
||||
assertEquals(2, execution.getOperations().get("s1").getAttempt());
|
||||
assertTrue(eventTypes(execution).contains("StepFailed"), "a RETRY with an error records StepFailed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyCheckpointCompletesADueWaitInsideTheInvocation() {
|
||||
invoker.script(event -> {
|
||||
String token = checkpoint(event, token(event), List.of(waitStart("w1", 1))).checkpointToken();
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
CheckpointResult poll = checkpoint(event, token, List.of());
|
||||
assertEquals(1, poll.newExecutionState().size());
|
||||
assertEquals(DurableOperationStatus.SUCCEEDED, poll.newExecutionState().get(0).getStatus());
|
||||
return succeeded("\"x\"");
|
||||
});
|
||||
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, service.get(start("exec-1", "{}", true).getExecutionArn())
|
||||
.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void staleTokensAndTokensOfClosedExecutionsAreRejected() {
|
||||
invoker.script(event -> {
|
||||
String first = token(event);
|
||||
String second = checkpoint(event, first, List.of()).checkpointToken();
|
||||
AwsException stale = assertThrows(AwsException.class, () -> checkpoint(event, first, List.of()));
|
||||
assertEquals("Invalid checkpoint token", stale.getMessage());
|
||||
assertEquals(400, stale.getHttpStatus());
|
||||
assertThrows(AwsException.class, () -> checkpoint(event, "QUJDRA==", List.of()));
|
||||
String arn = event.get("DurableExecutionArn").asText();
|
||||
String otherArn = arn.substring(0, arn.lastIndexOf('/') + 1) + "other-id";
|
||||
AwsException other = assertThrows(AwsException.class,
|
||||
() -> service.checkpoint(otherArn, second, null, List.of()));
|
||||
assertEquals("Checkpoint token is not valid for the durable execution ARN", other.getMessage());
|
||||
CheckpointResult closing = checkpoint(event, second, List.of(executionSucceed("\"r\"")));
|
||||
assertNull(closing.checkpointToken(), "the closing checkpoint carries no token");
|
||||
assertThrows(AwsException.class, () -> checkpoint(event, second, List.of()));
|
||||
return succeeded("");
|
||||
});
|
||||
|
||||
DurableExecution execution = service.get(start("exec-1", "{}", true).getExecutionArn());
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, execution.getStatus());
|
||||
assertEquals("\"r\"", execution.getResult(), "the checkpointed result wins over the handler return");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRetriedCheckpointWithTheSameClientTokenGetsTheSameAnswer() {
|
||||
invoker.script(event -> {
|
||||
String arn = event.get("DurableExecutionArn").asText();
|
||||
String first = token(event);
|
||||
List<DurableOperationUpdate> updates = List.of(waitStart("w1", 1));
|
||||
CheckpointResult accepted = service.checkpoint(arn, first, "ct-1", updates);
|
||||
clock.advance(Duration.ofSeconds(2));
|
||||
service.sweep();
|
||||
CheckpointResult retried = service.checkpoint(arn, first, "ct-1", List.of());
|
||||
assertEquals(accepted.checkpointToken(), retried.checkpointToken());
|
||||
assertEquals(DurableOperationStatus.STARTED, retried.newExecutionState().get(0).getStatus(),
|
||||
"the retry gets the answer as it was sent, not the fired wait");
|
||||
assertThrows(AwsException.class, () -> service.checkpoint(arn, first, "ct-2", updates));
|
||||
CheckpointResult next = service.checkpoint(arn, accepted.checkpointToken(), "ct-3", List.of());
|
||||
assertEquals(DurableOperationStatus.SUCCEEDED, next.newExecutionState().get(0).getStatus());
|
||||
assertThrows(AwsException.class, () -> service.checkpoint(arn, first, "ct-1", updates));
|
||||
return succeeded("");
|
||||
});
|
||||
|
||||
DurableExecution execution = service.get(start("exec-1", "{}", true).getExecutionArn());
|
||||
assertEquals(List.of("ExecutionStarted", "WaitStarted", "WaitSucceeded", "InvocationCompleted",
|
||||
"ExecutionSucceeded"), eventTypes(execution));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameNameIsIdempotentForTheSamePayloadAndRejectedForAnotherPayload() {
|
||||
invoker.script(event -> succeeded("\"one\""));
|
||||
|
||||
DurableExecution first = start("same", "{\"a\":1}", true);
|
||||
DurableExecution again = start("same", "{\"a\":1}", true);
|
||||
assertEquals(first.getExecutionArn(), again.getExecutionArn());
|
||||
assertEquals(1, invoker.events.size());
|
||||
|
||||
AwsException conflict = assertThrows(AwsException.class, () -> start("same", "{\"a\":2}", true));
|
||||
assertEquals("DurableExecutionAlreadyStartedException", conflict.getErrorCode());
|
||||
assertEquals("Execution already started: " + first.getExecutionArn(), conflict.getMessage());
|
||||
assertEquals(409, conflict.getHttpStatus());
|
||||
|
||||
AwsException otherVersion = assertThrows(AwsException.class, () -> service.start(
|
||||
new StartRequest(ACCOUNT, REGION, FUNCTION, "2", "same", "{\"a\":1}", true)));
|
||||
assertEquals("Execution already started: " + first.getExecutionArn(), otherVersion.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlerResponsesThatBreakTheProtocolFailTheExecution() {
|
||||
invoker.script(event -> handlerResponse("{\"foo\":1}"));
|
||||
DurableExecution invalid = service.get(start("invalid", "{}", true).getExecutionArn());
|
||||
assertEquals(DurableExecutionStatus.FAILED, invalid.getStatus());
|
||||
assertEquals("Invalid Status in invocation output.", invalid.getError().getErrorMessage());
|
||||
assertEquals("InvalidParameterValueException", invalid.getError().getErrorType());
|
||||
assertEquals(List.of("ExecutionStarted", "InvocationCompleted", "ExecutionFailed"), eventTypes(invalid));
|
||||
|
||||
invoker.script(event -> pending());
|
||||
DurableExecution idle = service.get(start("idle", "{}", true).getExecutionArn());
|
||||
assertEquals(DurableExecutionStatus.FAILED, idle.getStatus());
|
||||
assertEquals("Cannot return PENDING status with no pending operations.", idle.getError().getErrorMessage());
|
||||
|
||||
invoker.script(event -> handlerResponse("{\"Status\":\"FAILED\",\"Error\":{\"ErrorMessage\":\"bad\","
|
||||
+ "\"ErrorType\":\"MyError\"}}"));
|
||||
DurableExecution failed = service.get(start("failed", "{}", true).getExecutionArn());
|
||||
assertEquals(DurableExecutionStatus.FAILED, failed.getStatus());
|
||||
assertEquals("MyError", failed.getError().getErrorType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFunctionErrorIsRetriedAndFailsTheExecutionAfterTheLastAttempt() {
|
||||
for (int i = 0; i < DurableExecutionService.INVOCATION_RETRY_MAX_ATTEMPTS; i++) {
|
||||
invoker.script(event -> functionError("{\"errorMessage\":\"crash\",\"errorType\":\"RuntimeError\"}"));
|
||||
}
|
||||
|
||||
String arn = start("exec-1", "{}", false).getExecutionArn();
|
||||
for (int i = 1; i < DurableExecutionService.INVOCATION_RETRY_MAX_ATTEMPTS; i++) {
|
||||
assertEquals(DurableExecutionStatus.RUNNING, service.get(arn).getStatus());
|
||||
service.sweep();
|
||||
}
|
||||
|
||||
DurableExecution execution = service.get(arn);
|
||||
assertEquals(DurableExecutionStatus.FAILED, execution.getStatus());
|
||||
assertEquals("crash", execution.getError().getErrorMessage());
|
||||
assertEquals("RuntimeError", execution.getError().getErrorType());
|
||||
assertEquals(DurableExecutionService.INVOCATION_RETRY_MAX_ATTEMPTS,
|
||||
eventTypes(execution).stream().filter("InvocationCompleted"::equals).count());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopClosesTheExecutionAndIsIdempotent() {
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w1", 60)));
|
||||
return pending();
|
||||
});
|
||||
String arn = start("exec-1", "{}", false).getExecutionArn();
|
||||
String token = token(invoker.events.get(0));
|
||||
|
||||
DurableExecution stopped = service.stop(arn, null);
|
||||
assertEquals(DurableExecutionStatus.STOPPED, stopped.getStatus());
|
||||
assertNotNull(stopped.getError(), "a stop without a body records an empty error object");
|
||||
assertNull(stopped.getError().getErrorMessage());
|
||||
assertEquals(stopped.getEndTimestamp(), service.stop(arn, DurableErrorObject.of("x", "y")).getEndTimestamp());
|
||||
assertNull(service.get(arn).getError().getErrorType(), "a second stop does not overwrite the first");
|
||||
assertThrows(AwsException.class, () -> service.checkpoint(arn, token, null, List.of()));
|
||||
assertEquals("ExecutionStopped", eventTypes(service.get(arn)).getLast());
|
||||
|
||||
clock.advance(Duration.ofSeconds(60));
|
||||
service.sweep();
|
||||
assertEquals(1, invoker.events.size(), "a stopped execution is never re-invoked");
|
||||
}
|
||||
|
||||
@Test
|
||||
void executionTimeoutMarksTheExecutionTimedOut() {
|
||||
invoker.executionTimeoutSeconds = 10;
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w1", 60)));
|
||||
return pending();
|
||||
});
|
||||
String arn = start("exec-1", "{}", false).getExecutionArn();
|
||||
|
||||
clock.advance(Duration.ofSeconds(10));
|
||||
service.sweep();
|
||||
|
||||
DurableExecution execution = service.get(arn);
|
||||
assertEquals(DurableExecutionStatus.TIMED_OUT, execution.getStatus());
|
||||
assertEquals("Execution timed out after 10 seconds.", execution.getError().getErrorMessage());
|
||||
assertEquals("ExecutionTimedOut", eventTypes(execution).getLast());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listFiltersAndPagesNewestFirst() {
|
||||
invoker.script(event -> succeeded("1"));
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w1", 60)));
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> succeeded("3"));
|
||||
String first = start("a", "{}", true).getExecutionArn();
|
||||
String second = start("b", "{}", false).getExecutionArn();
|
||||
String third = start("c", "{}", true).getExecutionArn();
|
||||
|
||||
PaginatedResult<DurableExecution> all = service.list(listRequest(null, null, null, null));
|
||||
assertEquals(List.of(third, second, first), all.items().stream().map(DurableExecution::getExecutionArn).toList());
|
||||
assertNull(all.nextToken());
|
||||
|
||||
PaginatedResult<DurableExecution> running = service.list(listRequest(Set.of(DurableExecutionStatus.RUNNING),
|
||||
null, null, null));
|
||||
assertEquals(List.of(second), running.items().stream().map(DurableExecution::getExecutionArn).toList());
|
||||
|
||||
PaginatedResult<DurableExecution> byName = service.list(listRequest(null, "c", null, null));
|
||||
assertEquals(List.of(third), byName.items().stream().map(DurableExecution::getExecutionArn).toList());
|
||||
|
||||
PaginatedResult<DurableExecution> page = service.list(listRequest(null, null, 2, null));
|
||||
assertEquals(2, page.items().size());
|
||||
assertNotNull(page.nextToken());
|
||||
PaginatedResult<DurableExecution> rest = service.list(listRequest(null, null, 2, page.nextToken()));
|
||||
assertEquals(List.of(first), rest.items().stream().map(DurableExecution::getExecutionArn).toList());
|
||||
assertNull(rest.nextToken());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyStatusFilterMatchesNothingButStillChecksTheMarker() {
|
||||
invoker.script(event -> succeeded("1"));
|
||||
start("a", "{}", true);
|
||||
|
||||
assertTrue(service.list(listRequest(Set.of(), null, null, null)).items().isEmpty());
|
||||
assertThrows(AwsException.class, () -> service.list(listRequest(Set.of(), null, null, "bogus")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyPagesInBothDirections() {
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(step("s1", DurableOperationAction.START, null, null),
|
||||
step("s1", DurableOperationAction.SUCCEED, "1", null)));
|
||||
return succeeded("\"x\"");
|
||||
});
|
||||
String arn = start("exec-1", "{}", true).getExecutionArn();
|
||||
|
||||
PaginatedResult<DurableHistoryEvent> firstPage = service.history(arn, 2, null, false);
|
||||
assertEquals(List.of(1L, 2L), firstPage.items().stream().map(DurableHistoryEvent::getEventId).toList());
|
||||
PaginatedResult<DurableHistoryEvent> secondPage = service.history(arn, 2, firstPage.nextToken(), false);
|
||||
assertEquals(List.of(3L, 4L), secondPage.items().stream().map(DurableHistoryEvent::getEventId).toList());
|
||||
PaginatedResult<DurableHistoryEvent> newestFirst = service.history(arn, 1, null, true);
|
||||
assertEquals("ExecutionSucceeded", newestFirst.items().get(0).getEventType());
|
||||
assertThrows(AwsException.class, () -> service.history(arn, 2, "bogus", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClosedExecutionIsDeletedWhenItsRetentionExpires() {
|
||||
invoker.retentionPeriodInDays = 1;
|
||||
invoker.script(event -> succeeded("1"));
|
||||
String arn = start("exec-1", "{}", true).getExecutionArn();
|
||||
|
||||
clock.advance(Duration.ofHours(23));
|
||||
service.sweep();
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, service.get(arn).getStatus());
|
||||
|
||||
clock.advance(Duration.ofHours(2));
|
||||
service.sweep();
|
||||
AwsException gone = assertThrows(AwsException.class, () -> service.get(arn));
|
||||
assertEquals(404, gone.getHttpStatus());
|
||||
assertEquals("Durable Execution does not exist", gone.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void awaitCompletionResolvesWhenTheExecutionCloses() throws Exception {
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w1", 2)));
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> succeeded("\"late\""));
|
||||
String arn = start("exec-1", "{}", true).getExecutionArn();
|
||||
assertFalse(service.awaitCompletion(arn).isDone());
|
||||
|
||||
clock.advance(Duration.ofSeconds(2));
|
||||
service.sweep();
|
||||
|
||||
assertEquals("\"late\"", service.awaitCompletion(arn).get(5, TimeUnit.SECONDS).getResult());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWaitThatFiresWhileTheHandlerRunsResumesInsteadOfFailing() {
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w1", 1)));
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> {
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
service.sweep();
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> {
|
||||
assertEquals("SUCCEEDED", operation(event, "w1").get("Status").asText());
|
||||
return succeeded("\"resumed\"");
|
||||
});
|
||||
|
||||
String arn = start("exec-1", "{}", false).getExecutionArn();
|
||||
service.recoverAfterRestart();
|
||||
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, service.get(arn).getStatus());
|
||||
assertEquals(3, invoker.events.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void executionNamesAreScopedToTheFunction() {
|
||||
invoker.script(event -> succeeded("\"a\""));
|
||||
invoker.script(event -> succeeded("\"b\""));
|
||||
DurableExecution first = start("shared", "{}", true);
|
||||
|
||||
invoker.functionName = "other-fn";
|
||||
DurableExecution second = service.start(new StartRequest(ACCOUNT, REGION, "other-fn", "1", "shared", "{\"x\":1}",
|
||||
true));
|
||||
|
||||
assertFalse(first.getExecutionArn().equals(second.getExecutionArn()));
|
||||
assertEquals("\"b\"", service.get(second.getExecutionArn()).getResult());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWakeUpDuringAFailedInvocationDoesNotAddAnInvocationAfterTheRetry() {
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w1", 1)));
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> {
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
service.sweep();
|
||||
return functionError("{\"errorMessage\":\"crash\",\"errorType\":\"E\"}");
|
||||
});
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w2", 60)));
|
||||
return pending();
|
||||
});
|
||||
String arn = start("exec-1", "{}", false).getExecutionArn();
|
||||
service.recoverAfterRestart();
|
||||
|
||||
service.sweep();
|
||||
|
||||
assertEquals(3, invoker.events.size(), "the retry is the only invocation after the crash");
|
||||
assertEquals(DurableExecutionStatus.RUNNING, service.get(arn).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestartKeepsTheBackoffOfAPendingRetry() {
|
||||
invoker.script(event -> functionError("{\"errorMessage\":\"crash\",\"errorType\":\"E\"}"));
|
||||
invoker.script(event -> succeeded("\"ok\""));
|
||||
String arn = start("exec-1", "{}", false).getExecutionArn();
|
||||
|
||||
newService(storage, invoker, clock).recoverAfterRestart();
|
||||
assertEquals(1, invoker.events.size(), "the retry waits for its backoff");
|
||||
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
service.sweep();
|
||||
assertEquals(DurableExecutionStatus.SUCCEEDED, service.get(arn).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewInvocationClearsAPendingRetry() {
|
||||
invoker.script(event -> functionError("{\"errorMessage\":\"crash\",\"errorType\":\"E\"}"));
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w1", 60)));
|
||||
return pending();
|
||||
});
|
||||
String arn = start("exec-1", "{}", false).getExecutionArn();
|
||||
assertNotNull(service.get(arn).getNextInvocationAttemptAt());
|
||||
|
||||
service.sweep();
|
||||
|
||||
assertNull(service.get(arn).getNextInvocationAttemptAt());
|
||||
service.sweep();
|
||||
assertEquals(2, invoker.events.size(), "no extra invocation after the retry ran");
|
||||
}
|
||||
|
||||
// ──────────────────────────── helpers ────────────────────────────
|
||||
|
||||
private static DurableExecutionService newService(InMemoryStorageFactory storage, ScriptedInvoker invoker,
|
||||
MutableClock clock) {
|
||||
return new DurableExecutionService(storage, MAPPER, clock, invoker, Runnable::run, Duration.ZERO);
|
||||
}
|
||||
|
||||
private DurableExecution start(String name, String payload, boolean synchronous) {
|
||||
return service.start(new StartRequest(ACCOUNT, REGION, FUNCTION, "1", name, payload, synchronous));
|
||||
}
|
||||
|
||||
private CheckpointResult checkpoint(JsonNode event, String token, List<DurableOperationUpdate> updates) {
|
||||
return service.checkpoint(event.get("DurableExecutionArn").asText(), token, null, updates);
|
||||
}
|
||||
|
||||
private static ListRequest listRequest(Set<DurableExecutionStatus> statuses, String name, Integer maxItems,
|
||||
String marker) {
|
||||
return new ListRequest(ACCOUNT, REGION, FUNCTION, null, name, statuses, null, null, false, maxItems, marker);
|
||||
}
|
||||
|
||||
private static String token(JsonNode event) {
|
||||
return event.get("CheckpointToken").asText();
|
||||
}
|
||||
|
||||
private static JsonNode operation(JsonNode event, String id) {
|
||||
for (JsonNode operation : event.get("InitialExecutionState").get("Operations")) {
|
||||
if (id.equals(operation.get("Id").asText())) {
|
||||
return operation;
|
||||
}
|
||||
}
|
||||
throw new AssertionError("no operation " + id + " in " + event);
|
||||
}
|
||||
|
||||
private static List<String> eventTypes(DurableExecution execution) {
|
||||
return execution.getHistory().stream().map(DurableHistoryEvent::getEventType).toList();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate waitStart(String id, int seconds) {
|
||||
return new DurableOperationUpdate(id, null, null, DurableOperationType.WAIT, "Wait",
|
||||
DurableOperationAction.START, null, null, null, seconds, null);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate executionSucceed(String payload) {
|
||||
return new DurableOperationUpdate("execution-result", null, null, DurableOperationType.EXECUTION, null,
|
||||
DurableOperationAction.SUCCEED, payload, null, null, null, null);
|
||||
}
|
||||
|
||||
private static DurableFunctionInvoker.DurableInvocationResult succeeded(String result) {
|
||||
return handlerResponse("{\"Status\":\"SUCCEEDED\",\"Result\":" + MAPPER.valueToTree(result) + "}");
|
||||
}
|
||||
|
||||
private static DurableFunctionInvoker.DurableInvocationResult pending() {
|
||||
return handlerResponse("{\"Status\":\"PENDING\"}");
|
||||
}
|
||||
|
||||
private static DurableFunctionInvoker.DurableInvocationResult handlerResponse(String json) {
|
||||
return new DurableFunctionInvoker.DurableInvocationResult("req", json.getBytes(StandardCharsets.UTF_8), null);
|
||||
}
|
||||
|
||||
private static DurableFunctionInvoker.DurableInvocationResult functionError(String json) {
|
||||
return new DurableFunctionInvoker.DurableInvocationResult("req", json.getBytes(StandardCharsets.UTF_8),
|
||||
"Unhandled");
|
||||
}
|
||||
|
||||
/** Plays one script per invocation; a missing script fails the execution so the test shows it. */
|
||||
private static final class ScriptedInvoker implements DurableFunctionInvoker {
|
||||
|
||||
final Deque<Function<JsonNode, DurableInvocationResult>> scripts = new ArrayDeque<>();
|
||||
final List<JsonNode> events = new ArrayList<>();
|
||||
int executionTimeoutSeconds = 3600;
|
||||
String functionName = FUNCTION;
|
||||
int retentionPeriodInDays = 7;
|
||||
|
||||
void script(Function<JsonNode, DurableInvocationResult> script) {
|
||||
scripts.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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload) {
|
||||
JsonNode event;
|
||||
try {
|
||||
event = MAPPER.readTree(payload);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
events.add(event);
|
||||
Function<JsonNode, DurableInvocationResult> script = scripts.poll();
|
||||
if (script == null) {
|
||||
return handlerResponse("{\"Status\":\"FAILED\",\"Error\":{\"ErrorMessage\":\"no script for "
|
||||
+ "invocation " + events.size() + "\",\"ErrorType\":\"TestError\"}}");
|
||||
}
|
||||
return script.apply(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package io.github.hectorvent.floci.services.lambda.durable;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig.LambdaServiceConfig;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig.ServicesConfig;
|
||||
import io.quarkus.runtime.ShutdownEvent;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/** A non-positive interval must not reach scheduleWithFixedDelay, which would abort startup. */
|
||||
class DurableExecutionSweeperTest {
|
||||
|
||||
@Test
|
||||
void nonPositiveConfiguredIntervalDoesNotPreventStartup() {
|
||||
for (long interval : new long[] {0L, -1L, Long.MIN_VALUE}) {
|
||||
DurableExecutionSweeper sweeper = new DurableExecutionSweeper(null, configWithInterval(interval));
|
||||
assertDoesNotThrow(() -> sweeper.onStart(new StartupEvent()), "interval " + interval + " must not abort startup");
|
||||
sweeper.onStop(new ShutdownEvent());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void positiveConfiguredIntervalStartsNormally() {
|
||||
DurableExecutionSweeper sweeper = new DurableExecutionSweeper(null, configWithInterval(30L));
|
||||
assertDoesNotThrow(() -> sweeper.onStart(new StartupEvent()));
|
||||
sweeper.onStop(new ShutdownEvent());
|
||||
}
|
||||
|
||||
private static EmulatorConfig configWithInterval(long intervalSeconds) {
|
||||
EmulatorConfig config = configView(EmulatorConfig.class);
|
||||
ServicesConfig services = configView(ServicesConfig.class);
|
||||
LambdaServiceConfig lambda = configView(LambdaServiceConfig.class);
|
||||
doReturn(services).when(config).services();
|
||||
doReturn(lambda).when(services).lambda();
|
||||
doReturn(true).when(lambda).enabled();
|
||||
doReturn(true).when(lambda).durableSweepEnabled();
|
||||
doReturn(intervalSeconds).when(lambda).durableSweepIntervalSeconds();
|
||||
return config;
|
||||
}
|
||||
|
||||
private static <T> T configView(Class<T> configType) {
|
||||
return mock(configType, invocation -> {
|
||||
throw new AssertionError("Unexpected configuration access: " + invocation.getMethod());
|
||||
});
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package io.github.hectorvent.floci.services.lambda.durable;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.core.storage.WriteProfile;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** In-memory stores shared by every service built on the same factory, so a second service sees a "restart". */
|
||||
final class InMemoryStorageFactory extends StorageFactory {
|
||||
|
||||
private final String accountId;
|
||||
private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
|
||||
|
||||
InMemoryStorageFactory(String accountId) {
|
||||
super(null, null);
|
||||
this.accountId = accountId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return create(serviceName, fileName, typeReference, WriteProfile.DEFAULT);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference,
|
||||
WriteProfile profile) {
|
||||
return (AccountAwareStorageBackend<V>) stores.computeIfAbsent(fileName,
|
||||
ignored -> AccountAwareStorageBackend.inMemory(accountId));
|
||||
}
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
package io.github.hectorvent.floci.services.lambda.durable;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.empty;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* The durable execution routes and the Invoke rules that need no running function: routing of
|
||||
* raw and percent-encoded ARNs, request validation, and the errors AWS returns for them.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class LambdaDurableExecutionApiIntegrationTest {
|
||||
|
||||
@Inject
|
||||
LambdaService lambdaService;
|
||||
|
||||
private static final String LAMBDA = "/2015-03-31";
|
||||
private static final String DURABLE = "/2025-12-01";
|
||||
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:api-durable-fn";
|
||||
private static final String UNKNOWN_EXECUTION = FUNCTION_ARN
|
||||
+ ":1/durable-execution/missing/00000000-0000-0000-0000-000000000000";
|
||||
private static final String ENCODED_UNKNOWN_EXECUTION = "arn%3Aaws%3Alambda%3Aus-east-1%3A000000000000%3A"
|
||||
+ "function%3Aapi-durable-fn%3A%24LATEST%2Fdurable-execution%2Fmissing%2F"
|
||||
+ "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
@BeforeEach
|
||||
void createFunctions() {
|
||||
createFunction("api-durable-fn", ", \"DurableConfig\": {\"ExecutionTimeout\": 3600}");
|
||||
createFunction("api-long-durable-fn", ", \"DurableConfig\": {\"ExecutionTimeout\": 901}");
|
||||
createFunction("api-plain-fn", "");
|
||||
}
|
||||
|
||||
/** Idempotent: the functions stay for the whole class, so a repeat create answers 409. */
|
||||
private static void createFunction(String name, String members) {
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"FunctionName": "%s",
|
||||
"Runtime": "nodejs20.x",
|
||||
"Role": "arn:aws:iam::000000000000:role/lambda-role",
|
||||
"Handler": "index.handler"%s
|
||||
}
|
||||
""".formatted(name, members))
|
||||
.when()
|
||||
.post(LAMBDA + "/functions")
|
||||
.then()
|
||||
.statusCode(anyOf(is(201), is(409)));
|
||||
}
|
||||
|
||||
/** RestAssured must not re-encode the path: both the raw and the SDK's percent-encoded form go on the wire as is. */
|
||||
private static RequestSpecification raw() {
|
||||
return given().urlEncodingEnabled(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rawAndEncodedExecutionArnsReachTheSameRoute() {
|
||||
raw().get(DURABLE + "/durable-executions/" + UNKNOWN_EXECUTION)
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"))
|
||||
.body("message", equalTo("Durable Execution does not exist"));
|
||||
|
||||
raw().get(DURABLE + "/durable-executions/" + ENCODED_UNKNOWN_EXECUTION)
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
|
||||
raw().get(DURABLE + "/durable-executions/" + ENCODED_UNKNOWN_EXECUTION + "/history")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
|
||||
raw().get(DURABLE + "/durable-executions/" + ENCODED_UNKNOWN_EXECUTION + "/history?MaxItems=-1")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("1 validation error detected: Value '-1' at 'maxItems' failed to satisfy "
|
||||
+ "constraint: Member must have value greater than or equal to 0"));
|
||||
|
||||
raw().contentType("application/json").body("{\"CheckpointToken\": \"QUJD\", \"Updates\": []}")
|
||||
.post(DURABLE + "/durable-executions/" + UNKNOWN_EXECUTION + "/checkpoint")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"))
|
||||
.body("message", equalTo("Invalid checkpoint token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMalformedExecutionArnIsAValidationError() {
|
||||
raw().get(DURABLE + "/durable-executions/" + FUNCTION_ARN)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", startsWith("1 validation error detected: Value '" + FUNCTION_ARN
|
||||
+ "' at 'durableExecutionArn' failed to satisfy constraint: Member must satisfy regular "
|
||||
+ "expression pattern: arn:([a-zA-Z0-9-]+):lambda:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDurableFunctionNeedsAQualifiedReference() {
|
||||
for (String invocationType : new String[] {"RequestResponse", "DryRun"}) {
|
||||
given()
|
||||
.header("X-Amz-Invocation-Type", invocationType)
|
||||
.body("{}")
|
||||
.when()
|
||||
.post(LAMBDA + "/functions/api-durable-fn/invocations")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"))
|
||||
.body("message", equalTo("You cannot invoke a durable function using an unqualified ARN."));
|
||||
}
|
||||
|
||||
given()
|
||||
.header("X-Amz-Invocation-Type", "DryRun")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post(LAMBDA + "/functions/api-durable-fn/invocations?Qualifier=$LATEST")
|
||||
.then()
|
||||
.statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anArnInvocationOfADurableFunctionNeedsAQualifierToo() {
|
||||
AwsException rejected = assertThrows(AwsException.class, () -> lambdaService.invokeArn(
|
||||
FUNCTION_ARN, "{}".getBytes(StandardCharsets.UTF_8), InvocationType.Event));
|
||||
assertEquals("InvalidParameterValueException", rejected.getErrorCode());
|
||||
assertEquals("You cannot invoke a durable function using an unqualified ARN.", rejected.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSynchronousInvokeNeedsAnExecutionTimeoutWithinTheInvocationLimit() {
|
||||
given()
|
||||
.body("{}")
|
||||
.when()
|
||||
.post(LAMBDA + "/functions/api-long-durable-fn:$LATEST/invocations")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"))
|
||||
.body("message", equalTo("You cannot synchronously invoke a durable function with an executionTimeout "
|
||||
+ "greater than 15 minutes."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInvalidExecutionNameIsRejected() {
|
||||
given()
|
||||
.header("X-Amz-Invocation-Type", "Event")
|
||||
.header("X-Amz-Durable-Execution-Name", "has space")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post(LAMBDA + "/functions/api-durable-fn:$LATEST/invocations")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", containsString("'durableExecutionName'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listValidatesItsParametersAndTheFunction() {
|
||||
given()
|
||||
.when()
|
||||
.get(DURABLE + "/functions/api-durable-fn/durable-executions")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DurableExecutions", empty());
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get(DURABLE + "/functions/api-durable-fn/durable-executions?Statuses=PAUSED")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DurableExecutions", empty());
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get(DURABLE + "/functions/api-durable-fn/durable-executions?Statuses=PAUSED&Marker=bogus")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"))
|
||||
.body("message", equalTo("Invalid Marker"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get(DURABLE + "/functions/api-plain-fn/durable-executions?Statuses=BOGUS")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", startsWith("1 validation error detected: Value '[BOGUS]' at 'statuses'"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get(DURABLE + "/functions/api-durable-fn/durable-executions?StartedAfter=NaN")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"))
|
||||
.body("message", equalTo("'NaN' can not be converted to Date"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get(DURABLE + "/functions/no-such-durable-fn/durable-executions?Statuses=RUNNING&Statuses=FAILED")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"))
|
||||
.body("message", equalTo("Cannot filter by more than one status"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get(DURABLE + "/functions/no-such-durable-fn/durable-executions?Statuses=BOGUS&MaxItems=-1")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", startsWith("2 validation errors detected: Value '-1' at 'maxItems' failed to satisfy "
|
||||
+ "constraint: Member must have value greater than or equal to 0; Value '[BOGUS]' at 'statuses'"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get(DURABLE + "/functions/api-durable-fn/durable-executions?MaxItems=x")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"))
|
||||
.body("message", equalTo("'x' can not be converted to Integer"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get(DURABLE + "/functions/no-such-durable-fn/durable-executions")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package io.github.hectorvent.floci.services.lambda.durable;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
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.anyOf;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Runs a real Python function in a container. Its FAILED envelope closes the execution and the
|
||||
* sync Invoke reports it as a function error. The compat suite covers the full checkpoint loop.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class LambdaDurableFunctionsDockerIntegrationTest {
|
||||
|
||||
private static final String LAMBDA = "/2015-03-31";
|
||||
private static final String DURABLE = "/2025-12-01";
|
||||
private static final String FUNCTION = "durable-docker-fn";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/lambda-role";
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@BeforeEach
|
||||
void requireDockerAndFunction() throws Exception {
|
||||
Assumptions.assumeTrue(isDockerAvailable(),
|
||||
"Docker daemon must be available for Lambda durable function integration tests");
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"FunctionName": "%s",
|
||||
"Runtime": "python3.14",
|
||||
"Role": "%s",
|
||||
"Handler": "lambda_function.handler",
|
||||
"Timeout": 30,
|
||||
"Publish": true,
|
||||
"DurableConfig": {"ExecutionTimeout": 120, "RetentionPeriodInDays": 1},
|
||||
"Code": {"ZipFile": "%s"}
|
||||
}
|
||||
""".formatted(FUNCTION, ROLE, handlerZipBase64()))
|
||||
.when()
|
||||
.post(LAMBDA + "/functions")
|
||||
.then()
|
||||
.statusCode(anyOf(is(201), is(409)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedExecutionIsReportedAsAFunctionError() {
|
||||
Response response = given()
|
||||
.header("X-Amz-Durable-Execution-Name", "docker-fail")
|
||||
.body("{\"fail\": true}")
|
||||
.post(LAMBDA + "/functions/" + FUNCTION + ":1/invocations");
|
||||
|
||||
assertEquals(200, response.statusCode(), response.asString());
|
||||
assertEquals("Unhandled", response.getHeader("X-Amz-Function-Error"));
|
||||
assertEquals("asked to fail", response.jsonPath().getString("errorMessage"));
|
||||
assertEquals("TestFailure", response.jsonPath().getString("errorType"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get(DURABLE + "/functions/" + FUNCTION + "/durable-executions?Qualifier=1&DurableExecutionName=docker-fail")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DurableExecutions", hasSize(1))
|
||||
.body("DurableExecutions[0].Status", equalTo("FAILED"));
|
||||
}
|
||||
|
||||
static String handlerSource() {
|
||||
return """
|
||||
def handler(event, context):
|
||||
return {"Status": "FAILED",
|
||||
"Error": {"ErrorMessage": "asked to fail", "ErrorType": "TestFailure"}}
|
||||
""";
|
||||
}
|
||||
|
||||
private static String handlerZipBase64() throws Exception {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
|
||||
zip.putNextEntry(new ZipEntry("lambda_function.py"));
|
||||
zip.write(handlerSource().getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
}
|
||||
return Base64.getEncoder().encodeToString(bytes.toByteArray());
|
||||
}
|
||||
|
||||
private boolean isDockerAvailable() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
return true;
|
||||
} catch (Exception expected) {
|
||||
// Docker is unreachable, so requireDockerAndFunction() skips the test rather than failing it.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
package io.github.hectorvent.floci.services.lambda.durable;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableFunctionInvoker.DurableInvocationResult;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.ScriptedDurableFunctionInvoker.Invocation;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Plays the Durable Execution SDK over the REST API while a scripted stand-in holds the function
|
||||
* invocation open, so the checkpoint protocol is exercised end to end without a container.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(LambdaDurableScriptedProfile.class)
|
||||
class LambdaDurableProtocolIntegrationTest {
|
||||
|
||||
private static final String LAMBDA = "/2015-03-31";
|
||||
private static final String DURABLE = "/2025-12-01";
|
||||
private static final String FUNCTION = "protocol-durable-fn";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@Inject
|
||||
ScriptedDurableFunctionInvoker invoker;
|
||||
|
||||
@BeforeEach
|
||||
void createFunctionAndDrainInvocations() {
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"FunctionName": "%s",
|
||||
"Runtime": "nodejs20.x",
|
||||
"Role": "arn:aws:iam::000000000000:role/lambda-role",
|
||||
"Handler": "index.handler",
|
||||
"DurableConfig": {"ExecutionTimeout": 300, "RetentionPeriodInDays": 1}
|
||||
}
|
||||
""".formatted(FUNCTION))
|
||||
.when()
|
||||
.post(LAMBDA + "/functions")
|
||||
.then()
|
||||
.statusCode(anyOf(is(201), is(409)));
|
||||
invoker.drain();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSynchronousInvokeReturnsTheResultOfACheckpointedExecution() throws Exception {
|
||||
CompletableFuture<Response> invoke = CompletableFuture.supplyAsync(() -> given()
|
||||
.header("X-Amz-Durable-Execution-Name", "sync-1")
|
||||
.body("{\"order\": 1}")
|
||||
.post(LAMBDA + "/functions/" + FUNCTION + ":$LATEST/invocations"));
|
||||
|
||||
Invocation invocation = invoker.awaitInvocation(Duration.ofSeconds(30));
|
||||
JsonNode event = MAPPER.readTree(invocation.payload());
|
||||
String arn = event.get("DurableExecutionArn").asText();
|
||||
String token = event.get("CheckpointToken").asText();
|
||||
assertEquals("{\"order\": 1}", event.at("/InitialExecutionState/Operations/0/ExecutionDetails/InputPayload")
|
||||
.asText());
|
||||
|
||||
Response checkpoint = given()
|
||||
.urlEncodingEnabled(false)
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"CheckpointToken": "%s",
|
||||
"Updates": [
|
||||
{"Id": "s1", "Name": "validate", "Type": "STEP", "SubType": "Step", "Action": "START"},
|
||||
{"Id": "s1", "Name": "validate", "Type": "STEP", "SubType": "Step", "Action": "SUCCEED",
|
||||
"Payload": "{\\"ok\\":true}"}
|
||||
]
|
||||
}
|
||||
""".formatted(token))
|
||||
.post(DURABLE + "/durable-executions/" + arn + "/checkpoint");
|
||||
checkpoint.then()
|
||||
.statusCode(200)
|
||||
.body("CheckpointToken", notNullValue())
|
||||
.body("NewExecutionState.Operations", hasSize(1))
|
||||
.body("NewExecutionState.Operations[0].Id", equalTo("s1"))
|
||||
.body("NewExecutionState.Operations[0].Status", equalTo("SUCCEEDED"))
|
||||
.body("NewExecutionState.Operations[0].StepDetails.Result", equalTo("{\"ok\":true}"))
|
||||
.body("NewExecutionState.Operations[0].StepDetails.Attempt", equalTo(1));
|
||||
String nextToken = checkpoint.jsonPath().getString("CheckpointToken");
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(DURABLE + "/durable-executions/" + arn + "/state?CheckpointToken=" + nextToken)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Operations", hasSize(2))
|
||||
.body("Operations[0].Type", equalTo("EXECUTION"))
|
||||
.body("Operations[1].Id", equalTo("s1"))
|
||||
.body("NextMarker", equalTo(""));
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.contentType("application/json")
|
||||
.body("{\"CheckpointToken\": \"" + token + "\", \"Updates\": []}")
|
||||
.when()
|
||||
.post(DURABLE + "/durable-executions/" + arn + "/checkpoint")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"))
|
||||
.body("message", equalTo("Invalid checkpoint token"));
|
||||
|
||||
invocation.response().complete(handlerResponse("{\"Status\": \"SUCCEEDED\", \"Result\": \"{\\\"total\\\":3}\"}"));
|
||||
|
||||
Response response = invoke.get(30, TimeUnit.SECONDS);
|
||||
assertEquals(200, response.statusCode());
|
||||
assertEquals(arn, response.getHeader("X-Amz-Durable-Execution-Arn"));
|
||||
assertEquals("$LATEST", response.getHeader("X-Amz-Executed-Version"));
|
||||
assertEquals("{\"total\":3}", response.asString());
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(DURABLE + "/durable-executions/" + arn)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Status", equalTo("SUCCEEDED"))
|
||||
.body("DurableExecutionName", equalTo("sync-1"))
|
||||
.body("Version", equalTo("$LATEST"))
|
||||
.body("InputPayload", equalTo("{\"order\": 1}"))
|
||||
.body("Result", equalTo("{\"total\":3}"))
|
||||
.body("ExecutionDataIncluded", equalTo(true))
|
||||
.body("DurableConfig.ExecutionTimeout", equalTo(300))
|
||||
.body("EndTimestamp", notNullValue());
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(DURABLE + "/durable-executions/" + arn + "?IncludeExecutionData=false")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ExecutionDataIncluded", equalTo(false))
|
||||
.body("$", not(hasKey("InputPayload")))
|
||||
.body("$", not(hasKey("Result")));
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(DURABLE + "/durable-executions/" + arn + "/history")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Events.EventType", equalTo(List.of("ExecutionStarted", "StepStarted", "StepSucceeded",
|
||||
"InvocationCompleted", "ExecutionSucceeded")))
|
||||
.body("Events[0].Id", notNullValue())
|
||||
.body("Events[0].Name", equalTo("sync-1"))
|
||||
.body("Events[0].ExecutionStartedDetails.Input.Truncated", equalTo(true))
|
||||
.body("Events[0].ExecutionStartedDetails.Input", not(hasKey("Payload")))
|
||||
.body("Events[2].Id", equalTo("s1"))
|
||||
.body("Events[2].Name", equalTo("validate"))
|
||||
.body("Events[2].SubType", equalTo("Step"))
|
||||
.body("Events[3].InvocationCompletedDetails.RequestId", notNullValue());
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(DURABLE + "/durable-executions/" + arn + "/history?IncludeExecutionData=true&ReverseOrder=true&MaxItems=2")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Events.EventType", equalTo(List.of("ExecutionSucceeded", "InvocationCompleted")))
|
||||
.body("Events[0].ExecutionSucceededDetails.Result.Payload", equalTo("{\"total\":3}"))
|
||||
.body("Events[0].ExecutionSucceededDetails.Result.Truncated", equalTo(false))
|
||||
.body("NextMarker", notNullValue());
|
||||
|
||||
String encoded = arn.replace(":", "%3A").replace("/", "%2F").replace("$", "%24");
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(DURABLE + "/durable-executions/" + encoded)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DurableExecutionArn", equalTo(arn));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAsynchronousInvokeIsIdempotentByNameAndCanBeStopped() throws Exception {
|
||||
Response accepted = given()
|
||||
.header("X-Amz-Invocation-Type", "Event")
|
||||
.header("X-Amz-Durable-Execution-Name", "async-1")
|
||||
.body("{\"job\": 1}")
|
||||
.post(LAMBDA + "/functions/" + FUNCTION + ":$LATEST/invocations");
|
||||
assertEquals(202, accepted.statusCode());
|
||||
String arn = accepted.getHeader("X-Amz-Durable-Execution-Arn");
|
||||
assertTrue(arn.contains("/durable-execution/async-1/"), arn);
|
||||
|
||||
Invocation invocation = invoker.awaitInvocation(Duration.ofSeconds(30));
|
||||
JsonNode event = MAPPER.readTree(invocation.payload());
|
||||
assertEquals(arn, event.get("DurableExecutionArn").asText());
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"CheckpointToken": "%s",
|
||||
"Updates": [{"Id": "w1", "Type": "WAIT", "SubType": "Wait", "Action": "START",
|
||||
"WaitOptions": {"WaitSeconds": 600}}]
|
||||
}
|
||||
""".formatted(event.get("CheckpointToken").asText()))
|
||||
.when()
|
||||
.post(DURABLE + "/durable-executions/" + arn + "/checkpoint")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("NewExecutionState.Operations[0].Status", equalTo("STARTED"))
|
||||
.body("NewExecutionState.Operations[0].WaitDetails.ScheduledEndTimestamp", notNullValue());
|
||||
invocation.response().complete(handlerResponse("{\"Status\": \"PENDING\"}"));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Invocation-Type", "Event")
|
||||
.header("X-Amz-Durable-Execution-Name", "async-1")
|
||||
.body("{\"job\": 1}")
|
||||
.when()
|
||||
.post(LAMBDA + "/functions/" + FUNCTION + ":$LATEST/invocations")
|
||||
.then()
|
||||
.statusCode(202)
|
||||
.header("X-Amz-Durable-Execution-Arn", equalTo(arn));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Invocation-Type", "Event")
|
||||
.header("X-Amz-Durable-Execution-Name", "async-1")
|
||||
.body("{\"job\": 2}")
|
||||
.when()
|
||||
.post(LAMBDA + "/functions/" + FUNCTION + ":$LATEST/invocations")
|
||||
.then()
|
||||
.statusCode(409)
|
||||
.body("__type", equalTo("DurableExecutionAlreadyStartedException"))
|
||||
.body("message", equalTo("Execution already started: " + arn));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get(DURABLE + "/functions/" + FUNCTION + "/durable-executions?Statuses=RUNNING&DurableExecutionName=async-1")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DurableExecutions", hasSize(1))
|
||||
.body("DurableExecutions[0].DurableExecutionArn", equalTo(arn))
|
||||
.body("DurableExecutions[0].Status", equalTo("RUNNING"))
|
||||
.body("DurableExecutions[0]", not(hasKey("EndTimestamp")));
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=000000000000/20260101/us-west-2/lambda/"
|
||||
+ "aws4_request, SignedHeaders=host, Signature=abc")
|
||||
.contentType("application/json")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post(DURABLE + "/durable-executions/" + arn + "/stop")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"))
|
||||
.body("message", equalTo("Function not found"));
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=111111111111/20260101/us-east-1/lambda/"
|
||||
+ "aws4_request, SignedHeaders=host, Signature=abc")
|
||||
.contentType("application/json")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post(DURABLE + "/durable-executions/" + arn + "/stop")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.contentType("application/json")
|
||||
.body("{\"ErrorType\": \"Cancelled\", \"ErrorMessage\": \"by test\"}")
|
||||
.when()
|
||||
.post(DURABLE + "/durable-executions/" + arn + "/stop")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("StopTimestamp", notNullValue());
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(DURABLE + "/durable-executions/" + arn)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Status", equalTo("STOPPED"))
|
||||
.body("Error.ErrorType", equalTo("Cancelled"))
|
||||
.body("Error.ErrorMessage", equalTo("by test"));
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(DURABLE + "/durable-executions/" + arn + "/history?ReverseOrder=true&MaxItems=1")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Events[0].EventType", equalTo("ExecutionStopped"));
|
||||
}
|
||||
|
||||
private static DurableInvocationResult handlerResponse(String json) {
|
||||
return new DurableInvocationResult("req-" + System.nanoTime(), json.getBytes(StandardCharsets.UTF_8), null);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package io.github.hectorvent.floci.services.lambda.durable;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/** Swaps the Lambda container stack for {@link ScriptedDurableFunctionInvoker}. */
|
||||
public class LambdaDurableScriptedProfile implements QuarkusTestProfile {
|
||||
|
||||
@Override
|
||||
public Set<Class<?>> getEnabledAlternatives() {
|
||||
return Set.of(ScriptedDurableFunctionInvoker.class);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package io.github.hectorvent.floci.services.lambda.durable;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Alternative;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
/**
|
||||
* Stands in for the Lambda container in protocol tests: functions resolve for real, but each
|
||||
* invocation is handed to the test, which plays the SDK over the REST API and then answers.
|
||||
* Enabled per test class through {@link LambdaDurableScriptedProfile}.
|
||||
*/
|
||||
@Alternative
|
||||
@ApplicationScoped
|
||||
public class ScriptedDurableFunctionInvoker implements DurableFunctionInvoker {
|
||||
|
||||
public record Invocation(ResolvedDurableTarget target, byte[] payload,
|
||||
CompletableFuture<DurableInvocationResult> response) {
|
||||
}
|
||||
|
||||
private final LambdaDurableFunctionInvoker real;
|
||||
private final BlockingQueue<Invocation> invocations = new LinkedBlockingQueue<>();
|
||||
|
||||
@Inject
|
||||
public ScriptedDurableFunctionInvoker(LambdaDurableFunctionInvoker real) {
|
||||
this.real = real;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResolvedDurableTarget resolve(String accountId, String region, String functionName, String qualifier) {
|
||||
return real.resolve(accountId, region, functionName, qualifier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload) {
|
||||
Invocation invocation = new Invocation(target, payload, new CompletableFuture<>());
|
||||
invocations.add(invocation);
|
||||
try {
|
||||
return invocation.response().get(30, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("interrupted while waiting for the scripted response", e);
|
||||
} catch (ExecutionException | TimeoutException e) {
|
||||
throw new IllegalStateException("no scripted response for the invocation", e);
|
||||
}
|
||||
}
|
||||
|
||||
public Invocation awaitInvocation(Duration timeout) throws InterruptedException {
|
||||
Invocation invocation = invocations.poll(timeout.toMillis(), TimeUnit.MILLISECONDS);
|
||||
if (invocation == null) {
|
||||
throw new AssertionError("no durable invocation within " + timeout);
|
||||
}
|
||||
return invocation;
|
||||
}
|
||||
|
||||
public void drain() {
|
||||
invocations.clear();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user