fix(stepfunctions): honor Wait Timestamp and TimestampPath (#4099)

This commit is contained in:
Daniël van Ziel authored and GitHub committed 2026-09-22 13:42:52 -04:00
1 parent 8e6faffcaf
commit 00cfcef8f9
11 files changed
+390 -24

No files matched your search

+14 -2
View File
@@ -205,8 +205,19 @@ workflows converge: the `framework-isComplete-task` throws on every not-yet-comp
`JitterStrategy` supports `NONE` (the default) and `FULL`. `FULL` draws the delay
uniformly between zero and the computed delay, as on AWS. One deviation. The delay
between attempts is capped at 30 seconds, the same cap Floci applies to `Wait` states,
so emulated runs stay fast.
between attempts is capped at `floci.services.stepfunctions.max-wait-seconds`
(default 30), the same ceiling Floci applies to `Wait` states, so emulated runs stay fast.
## Wait states
A `Wait` state honors `Seconds`, `SecondsPath`, `Timestamp`, and `TimestampPath`. The two
`Seconds` forms pause for the given number of seconds. The two `Timestamp` forms parse an
ISO-8601 instant and pause until it, or return promptly when it has already passed. An
unparseable timestamp fails the execution with `States.Runtime`. In a JSONata state machine,
`Seconds` and `Timestamp` each accept a literal or a JSONata expression that produces the value.
One deviation. Every pause is capped at `floci.services.stepfunctions.max-wait-seconds`
(default 30) so emulated runs stay fast, where AWS sleeps the full duration.
## Timeouts
@@ -629,6 +640,7 @@ no additional event is written.
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_STEPFUNCTIONS_ENABLED` | `true` | Enable or disable the service |
| `FLOCI_SERVICES_STEPFUNCTIONS_MAX_WAIT_SECONDS` | `30` | Ceiling in seconds on a `Wait` state pause and a `Retry` backoff |
| `SFN_MOCK_CONFIG` | unset | Path to a Step Functions Local compatible mock configuration file (alias: `FLOCI_SERVICES_STEPFUNCTIONS_MOCK_CONFIG_FILE`) |
## Examples
@@ -1765,6 +1765,13 @@ public interface EmulatorConfig {
* compatibility with Step Functions Local.
*/
Optional<String> mockConfigFile();
/**
* Ceiling, in seconds, on a Wait state pause and a Retry backoff. AWS allows waits far longer
* than this, but the emulator caps them to keep runs fast. Raise it to exercise longer waits.
*/
@WithDefault("30")
int maxWaitSeconds();
}
interface SwfServiceConfig {
@@ -81,6 +81,8 @@ import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -145,7 +147,6 @@ public class AslExecutor {
}
private static final Logger LOG = Logger.getLogger(AslExecutor.class);
private static final int MAX_WAIT_SECONDS = 30;
// How long a Task waits for its token when the state declares no TimeoutSeconds. AWS lets it
// run for a year; the emulator would rather free the worker thread.
private static final int DEFAULT_TASK_TOKEN_TIMEOUT_SECONDS = 300;
@@ -249,6 +250,10 @@ public class AslExecutor {
private final WebClient webClient;
private final EmulatorConfig config;
private final CustomResourceLiveness customResourceLiveness;
private final Clock clock;
private final Sleeper sleeper;
// Null in production, where the ceiling comes from the Step Functions config. Tests pin it.
private final Integer maxWaitSecondsOverride;
private final Map<String, ActiveMockExecution> activeMocks = new ConcurrentHashMap<>();
private final ExecutorService executor = Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r, "sfn-executor");
@@ -268,6 +273,26 @@ public class AslExecutor {
ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,
Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,
CustomResourceLiveness customResourceLiveness) {
this(lambdaExecutor, functionStore, dynamoDbService, dynamoDbJsonHandler,
sqsJsonHandler, snsJsonHandler, cloudFormationHandler,
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null);
}
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore,
DynamoDbService dynamoDbService, DynamoDbJsonHandler dynamoDbJsonHandler,
SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler,
CloudFormationQueryHandler cloudFormationHandler,
Ec2Service ec2Service, S3Service s3Service,
EcsService ecsService, EcsJsonHandler ecsJsonHandler,
EventBridgeHandler eventBridgeHandler, SchedulerService schedulerService,
SchedulerController schedulerController,
ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,
Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,
CustomResourceLiveness customResourceLiveness,
Clock clock, Sleeper sleeper, Integer maxWaitSecondsOverride) {
this.customResourceLiveness = customResourceLiveness;
this.lambdaExecutor = lambdaExecutor;
this.functionStore = functionStore;
@@ -293,6 +318,9 @@ public class AslExecutor {
this.jsonataEvaluator = jsonataEvaluator;
this.sfnService = sfnService;
this.config = config;
this.clock = clock;
this.sleeper = sleeper;
this.maxWaitSecondsOverride = maxWaitSecondsOverride;
if (vertx != null) {
// This can be optimized further
// TODO Set WebclientOptions useragent to Amazon|StepFunctions|HttpInvoke|{{{{region}}}}
@@ -302,6 +330,12 @@ public class AslExecutor {
}
}
/** Test seam: lets Wait states be exercised without real time passing. */
@FunctionalInterface
interface Sleeper {
void sleep(long nanos) throws InterruptedException;
}
@PreDestroy
void stop() {
executor.shutdownNow();
@@ -627,7 +661,8 @@ public class AslExecutor {
*/
private void sleepBeforeRetry(JsonNode retrier, int attemptsUsed, long executionDeadlineNanos)
throws InterruptedException {
var delaySeconds = retryDelaySeconds(retrier, attemptsUsed, ThreadLocalRandom.current().nextDouble());
double delaySeconds = retryDelaySeconds(retrier, attemptsUsed, ThreadLocalRandom.current().nextDouble(),
maxWaitSeconds());
sleepOrTimeOutExecution((long) (delaySeconds * 1_000_000_000L), executionDeadlineNanos);
}
@@ -636,13 +671,13 @@ public class AslExecutor {
* the retrier declares {@code JitterStrategy: FULL}, which draws the delay uniformly between
* zero and the computed delay. Jitter applies after the caps, matching AWS.
*/
static double retryDelaySeconds(JsonNode retrier, int attemptsUsed, double random) {
static double retryDelaySeconds(JsonNode retrier, int attemptsUsed, double random, int maxWaitSeconds) {
var interval = retrier.path("IntervalSeconds").asDouble(1.0);
var backoffRate = retrier.path("BackoffRate").asDouble(2.0);
var delaySeconds = interval * Math.pow(backoffRate, attemptsUsed - 1.0);
var maxDelay = retrier.path("MaxDelaySeconds").asDouble(MAX_WAIT_SECONDS);
// Like the Wait state, cap the delay at MAX_WAIT_SECONDS to keep emulated runs fast.
delaySeconds = Math.min(delaySeconds, Math.min(maxDelay, MAX_WAIT_SECONDS));
double maxDelay = retrier.path("MaxDelaySeconds").asDouble(maxWaitSeconds);
// Like the Wait state, cap the delay at the configured ceiling to keep emulated runs fast.
delaySeconds = Math.min(delaySeconds, Math.min(maxDelay, maxWaitSeconds));
if ("FULL".equals(retrier.path("JitterStrategy").asText(null))) {
delaySeconds *= random;
}
@@ -2151,7 +2186,7 @@ public class AslExecutor {
private StateResult executeWaitState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,
ObjectNode variables, long executionDeadlineNanos)
throws InterruptedException {
int seconds = 0;
long waitNanos = 0;
JsonNode effectiveInput = input;
if (jsonata) {
if (stateDef.has("Seconds")) {
@@ -2160,23 +2195,37 @@ public class AslExecutor {
JsonNode statesVar = buildStatesVar(input, null, context);
JsonNode result = jsonataEvaluator.evaluateField(
secondsNode.asText(), "Seconds", statesVar, variables);
seconds = Math.min(result.asInt(), MAX_WAIT_SECONDS);
waitNanos = secondsToNanos(result.asLong());
} else {
seconds = Math.min(secondsNode.asInt(), MAX_WAIT_SECONDS);
waitNanos = secondsToNanos(secondsNode.asLong());
}
} else if (stateDef.has("Timestamp")) {
JsonNode timestampNode = stateDef.get("Timestamp");
if (timestampNode.isTextual() && JsonataEvaluator.isExpression(timestampNode.asText())) {
JsonNode statesVar = buildStatesVar(input, null, context);
JsonNode result = jsonataEvaluator.evaluateField(
timestampNode.asText(), "Timestamp", statesVar, variables);
waitNanos = nanosUntil(result.asText());
} else {
waitNanos = nanosUntil(timestampNode.asText());
}
}
} else {
effectiveInput = applyInputPath(stateDef, input);
if (stateDef.has("Seconds")) {
seconds = Math.min(stateDef.get("Seconds").asInt(), MAX_WAIT_SECONDS);
waitNanos = secondsToNanos(stateDef.get("Seconds").asLong());
} else if (stateDef.has("SecondsPath")) {
JsonNode val = resolvePath(stateDef.get("SecondsPath").asText(), effectiveInput);
seconds = Math.min(val.asInt(), MAX_WAIT_SECONDS);
waitNanos = secondsToNanos(val.asLong());
} else if (stateDef.has("Timestamp")) {
waitNanos = nanosUntil(stateDef.get("Timestamp").asText());
} else if (stateDef.has("TimestampPath")) {
JsonNode val = resolvePath(stateDef.get("TimestampPath").asText(), effectiveInput);
waitNanos = nanosUntil(val.asText());
}
}
// Timestamp and TimestampPath: wait until that time or now, whichever is sooner
if (seconds > 0) {
sleepOrTimeOutExecution(TimeUnit.SECONDS.toNanos(seconds), executionDeadlineNanos);
if (waitNanos > 0) {
sleepOrTimeOutExecution(waitNanos, executionDeadlineNanos);
}
if (jsonata) {
JsonNode output = applyJsonataOutput(stateDef, input, null, context, variables);
@@ -2186,6 +2235,39 @@ public class AslExecutor {
return new StateResult(output, stateDef.path("Next").asText(null));
}
private int maxWaitSeconds() {
return maxWaitSecondsOverride != null
? maxWaitSecondsOverride
: config.services().stepfunctions().maxWaitSeconds();
}
private long secondsToNanos(long seconds) {
if (seconds <= 0) {
return 0;
}
return TimeUnit.SECONDS.toNanos(Math.min(seconds, maxWaitSeconds()));
}
/**
* Remaining pause for an absolute ASL {@code Timestamp}, floored at zero. The standard says to
* sleep until that instant; the emulator caps the pause at the configured wait ceiling so a
* future date cannot hold a worker for days. Tests raise that cap or inject a {@link Sleeper} to
* exercise longer waits without real time passing.
*/
private long nanosUntil(String timestamp) {
Instant target;
try {
target = Instant.parse(timestamp);
} catch (DateTimeParseException e) {
throw new FailStateException("States.Runtime", "Invalid Timestamp: " + timestamp);
}
long remainingNanos = Duration.between(clock.instant(), target).toNanos();
if (remainingNanos <= 0) {
return 0;
}
return Math.min(remainingNanos, TimeUnit.SECONDS.toNanos(maxWaitSeconds()));
}
/**
* Sleeps out a pause the definition asked for, ending the execution instead when the state
* machine's {@code TimeoutSeconds} budget runs out first. The two pauses long enough to
@@ -2196,10 +2278,10 @@ public class AslExecutor {
throws InterruptedException {
long remainingNanos = executionDeadlineNanos - System.nanoTime();
if (pauseNanos < remainingNanos) {
TimeUnit.NANOSECONDS.sleep(pauseNanos);
sleeper.sleep(pauseNanos);
return;
}
TimeUnit.NANOSECONDS.sleep(Math.max(remainingNanos, 0));
sleeper.sleep(Math.max(remainingNanos, 0));
throw new ExecutionTimedOutException();
}
+1
View File
@@ -461,6 +461,7 @@ floci:
enabled: true
allow-plaintext-http: false
mock-config-file: ${SFN_MOCK_CONFIG:}
max-wait-seconds: 30
swf:
enabled: true
timeout-sweep-enabled: true
@@ -31,6 +31,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -61,6 +62,8 @@ class AslExecutorBranchHistoryEventsTest {
void setUp() {
Instance<StepFunctionsService> sfnService = mock(Instance.class);
when(sfnService.get()).thenReturn(mock(StepFunctionsService.class));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().stepfunctions().maxWaitSeconds()).thenReturn(30);
executor = new AslExecutor(
mock(LambdaExecutorService.class),
mock(LambdaFunctionStore.class),
@@ -77,7 +80,7 @@ class AslExecutorBranchHistoryEventsTest {
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
sfnService, mock(EmulatorConfig.class), vertx,
sfnService, config, vertx,
mock(io.github.hectorvent.floci.core.common.CustomResourceLiveness.class));
}
@@ -28,8 +28,10 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@QuarkusTest
class AslExecutorMockedResponsesTest {
@@ -48,6 +50,8 @@ class AslExecutorMockedResponsesTest {
@BeforeEach
void setUp() {
lambdaExecutor = mock(LambdaExecutorService.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().stepfunctions().maxWaitSeconds()).thenReturn(30);
executor = new AslExecutor(
lambdaExecutor,
@@ -65,7 +69,7 @@ class AslExecutorMockedResponsesTest {
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class), mock(EmulatorConfig.class), vertx, null);
mock(Instance.class), config, vertx, null);
}
@Test
@@ -30,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -65,6 +66,9 @@ class AslExecutorNestedStartExecutionTest {
childExec.setStartDate(1.0);
when(childSfn.startExecution(any(), any(), any(), any())).thenReturn(childExec);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().stepfunctions().maxWaitSeconds()).thenReturn(30);
executor = new AslExecutor(
mock(LambdaExecutorService.class),
mock(LambdaFunctionStore.class),
@@ -82,7 +86,7 @@ class AslExecutorNestedStartExecutionTest {
mapper,
new JsonataEvaluator(mapper),
sfnInstance,
mock(EmulatorConfig.class),
config,
null, null);
}
@@ -66,6 +66,14 @@ class AslExecutorRetryTest {
flakyFunction.setFunctionArn(FLAKY_FUNCTION_ARN);
when(functionStore.get(REGION, FLAKY_FUNCTION_NAME)).thenReturn(Optional.of(flakyFunction));
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.StepFunctionsServiceConfig stepFunctionsConfig =
mock(EmulatorConfig.StepFunctionsServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.stepfunctions()).thenReturn(stepFunctionsConfig);
when(stepFunctionsConfig.maxWaitSeconds()).thenReturn(30);
executor = new AslExecutor(
lambdaExecutor,
functionStore,
@@ -82,7 +90,7 @@ class AslExecutorRetryTest {
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class), mock(EmulatorConfig.class), vertx, null);
mock(Instance.class), config, vertx, null);
}
@Test
@@ -399,8 +407,19 @@ class AslExecutorRetryTest {
assertEquals(10.0, delay("{\"IntervalSeconds\": 10, \"BackoffRate\": 1.0, \"JitterStrategy\": \"NONE\"}", 1, 0.5));
}
@Test
void theDelayCapIsTheConfiguredWaitCeiling() throws Exception {
String retrier = "{\"IntervalSeconds\": 100, \"BackoffRate\": 2.0}";
assertEquals(30.0, delay(retrier, 2, 0.5));
assertEquals(120.0, delay(retrier, 2, 0.5, 120));
}
private double delay(String retrierJson, int attemptsUsed, double random) throws Exception {
return AslExecutor.retryDelaySeconds(objectMapper.readTree(retrierJson), attemptsUsed, random);
return delay(retrierJson, attemptsUsed, random, 30);
}
private double delay(String retrierJson, int attemptsUsed, double random, int maxWaitSeconds) throws Exception {
return AslExecutor.retryDelaySeconds(objectMapper.readTree(retrierJson), attemptsUsed, random, maxWaitSeconds);
}
private void failOnceThenSucceed() {
@@ -35,6 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -62,6 +63,8 @@ class AslExecutorTaskHistoryEventsTest {
void setUp() {
lambdaExecutor = mock(LambdaExecutorService.class);
functionStore = mock(LambdaFunctionStore.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().stepfunctions().maxWaitSeconds()).thenReturn(30);
executor = new AslExecutor(
lambdaExecutor,
@@ -79,7 +82,7 @@ class AslExecutorTaskHistoryEventsTest {
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class), mock(EmulatorConfig.class), vertx,
mock(Instance.class), config, vertx,
mock(io.github.hectorvent.floci.core.common.CustomResourceLiveness.class));
}
@@ -0,0 +1,230 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.CustomResourceLiveness;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler;
import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;
import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.scheduler.SchedulerController;
import io.github.hectorvent.floci.services.scheduler.SchedulerService;
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
/**
* Wait states must honor {@code Seconds}, {@code SecondsPath}, {@code Timestamp}, and
* {@code TimestampPath}. Timestamp support was missing: the state fell through with no pause and
* ran early. With no {@code TimeoutSeconds}, the execution deadline is unbounded, so the injected
* {@link AslExecutor.Sleeper} is the only thing that records the requested pause.
*/
class AslExecutorWaitStateTest {
private static final Instant NOW = Instant.parse("2026-01-01T00:00:00Z");
@Test
void secondsAboveThirtyAreHonoredWhenTheCapIsRaised() {
RecordingSleeper sleeper = new RecordingSleeper();
AslExecutor executor = newExecutor(sleeper, 120);
Execution execution = run(executor, """
{"StartAt":"W","States":{"W":{"Type":"Wait","Seconds":45,"End":true}}}
""", "{}");
assertEquals("SUCCEEDED", execution.getStatus());
assertEquals(TimeUnit.SECONDS.toNanos(45), sleeper.singleSleep());
}
@Test
void secondsAreCappedAtTheConfiguredMaximum() {
RecordingSleeper sleeper = new RecordingSleeper();
AslExecutor executor = newExecutor(sleeper, 10);
run(executor, """
{"StartAt":"W","States":{"W":{"Type":"Wait","Seconds":100,"End":true}}}
""", "{}");
assertEquals(TimeUnit.SECONDS.toNanos(10), sleeper.singleSleep());
}
@Test
void absoluteTimestampWaitsUntilThatInstant() {
RecordingSleeper sleeper = new RecordingSleeper();
AslExecutor executor = newExecutor(sleeper, 120);
Instant wake = NOW.plusSeconds(45);
run(executor, """
{"StartAt":"W","States":{"W":{"Type":"Wait","Timestamp":"%s","End":true}}}
""".formatted(wake), "{}");
assertEquals(TimeUnit.SECONDS.toNanos(45), sleeper.singleSleep());
}
@Test
void timestampPathResolvesTheWakeInstant() {
RecordingSleeper sleeper = new RecordingSleeper();
AslExecutor executor = newExecutor(sleeper, 120);
Instant wake = NOW.plusSeconds(20);
run(executor, """
{"StartAt":"W","States":{"W":{"Type":"Wait","TimestampPath":"$.wake","End":true}}}
""", "{\"wake\":\"" + wake + "\"}");
assertEquals(TimeUnit.SECONDS.toNanos(20), sleeper.singleSleep());
}
@Test
void jsonataLiteralTimestampWaitsUntilThatInstant() {
RecordingSleeper sleeper = new RecordingSleeper();
AslExecutor executor = newExecutor(sleeper, 120);
Instant wake = NOW.plusSeconds(45);
run(executor, """
{"QueryLanguage":"JSONata","StartAt":"W","States":{"W":{"Type":"Wait","Timestamp":"%s","End":true}}}
""".formatted(wake), "{}");
assertEquals(TimeUnit.SECONDS.toNanos(45), sleeper.singleSleep());
}
@Test
void jsonataTimestampExpressionResolvesTheWakeInstant() {
RecordingSleeper sleeper = new RecordingSleeper();
AslExecutor executor = newExecutor(sleeper, 120);
Instant wake = NOW.plusSeconds(20);
run(executor, """
{"QueryLanguage":"JSONata","StartAt":"W","States":{"W":{"Type":"Wait","Timestamp":"{% $states.input.wake %}","End":true}}}
""", "{\"wake\":\"" + wake + "\"}");
assertEquals(TimeUnit.SECONDS.toNanos(20), sleeper.singleSleep());
}
@Test
void timestampInThePastDoesNotSleep() {
RecordingSleeper sleeper = new RecordingSleeper();
AslExecutor executor = newExecutor(sleeper, 120);
Instant past = NOW.minusSeconds(10);
Execution execution = run(executor, """
{"StartAt":"W","States":{"W":{"Type":"Wait","Timestamp":"%s","End":true}}}
""".formatted(past), "{}");
assertEquals("SUCCEEDED", execution.getStatus());
assertTrue(sleeper.sleeps().isEmpty());
}
@Test
void timestampExactlyNowDoesNotSleep() {
RecordingSleeper sleeper = new RecordingSleeper();
AslExecutor executor = newExecutor(sleeper, 120);
run(executor, """
{"StartAt":"W","States":{"W":{"Type":"Wait","Timestamp":"%s","End":true}}}
""".formatted(NOW), "{}");
assertTrue(sleeper.sleeps().isEmpty());
}
@Test
void invalidTimestampFailsTheExecution() {
RecordingSleeper sleeper = new RecordingSleeper();
AslExecutor executor = newExecutor(sleeper, 120);
Execution execution = run(executor, """
{"StartAt":"W","States":{"W":{"Type":"Wait","Timestamp":"not-a-timestamp","End":true}}}
""", "{}");
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Runtime", execution.getError());
assertTrue(sleeper.sleeps().isEmpty());
}
private static AslExecutor newExecutor(RecordingSleeper sleeper, int maxWaitSeconds) {
ObjectMapper objectMapper = new ObjectMapper();
return new AslExecutor(
mock(LambdaExecutorService.class),
mock(LambdaFunctionStore.class),
mock(DynamoDbService.class),
mock(DynamoDbJsonHandler.class),
mock(SqsJsonHandler.class),
mock(SnsJsonHandler.class),
mock(CloudFormationQueryHandler.class),
mock(Ec2Service.class),
mock(S3Service.class),
mock(EcsService.class),
mock(EcsJsonHandler.class),
mock(EventBridgeHandler.class),
mock(SchedulerService.class),
mock(SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class),
mock(EmulatorConfig.class),
null,
mock(CustomResourceLiveness.class),
Clock.fixed(NOW, ZoneOffset.UTC),
sleeper,
maxWaitSeconds);
}
private static Execution run(AslExecutor executor, String definition, String input) {
StateMachine stateMachine = new StateMachine();
stateMachine.setName("wait-state-test");
stateMachine.setStateMachineArn(
"arn:aws:states:us-east-1:000000000000:stateMachine:wait-state-test");
stateMachine.setDefinition(definition);
Execution execution = new Execution();
execution.setName("wait-exec");
execution.setExecutionArn(
"arn:aws:states:us-east-1:000000000000:execution:wait-state-test:wait-exec");
execution.setStateMachineArn(stateMachine.getStateMachineArn());
execution.setInput(input);
List<HistoryEvent> history = new ArrayList<>();
executor.executeSync(stateMachine, execution, history, (updated, events) -> {
});
return execution;
}
private static final class RecordingSleeper implements AslExecutor.Sleeper {
private final List<Long> sleeps = new ArrayList<>();
@Override
public void sleep(long nanos) {
sleeps.add(nanos);
}
List<Long> sleeps() {
return sleeps;
}
long singleSleep() {
assertEquals(1, sleeps.size(), "expected exactly one recorded sleep");
return sleeps.getFirst();
}
}
}
+1
View File
@@ -249,6 +249,7 @@ floci:
enabled: true
allow-plaintext-http: true
mock-config-file: ${SFN_MOCK_CONFIG:src/test/resources/fixtures/sfn-mock-config.json}
max-wait-seconds: 30
swf:
enabled: true
timeout-sweep-enabled: true