Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(scheduler): invoke rate schedules at their first occurrence (#5610)

vamsiak16293b609b6c
diff --git a/docs/services/scheduler.md b/docs/services/scheduler.md
index 5f6d006cde..277f982f63 100644
--- a/docs/services/scheduler.md
+++ b/docs/services/scheduler.md
@@ -27,7 +27,10 @@ background dispatcher fires schedule targets on time. Supported expressions:
- `at(YYYY-MM-DDTHH:mm:ss)`: one-time fire; honors `ScheduleExpressionTimezone`
(default UTC) and `ActionAfterCompletion=DELETE`.
-- `rate(N unit)`: repeating fire (`minutes`, `hours`, `days`).
+- `rate(N unit)`: repeating fire (`minutes`, `hours`, `days`). The first
+ occurrence uses `StartDate`, or creation time when `StartDate` is omitted,
+ and is delivered on the first eligible dispatcher tick. Later occurrences
+ retain the interval from the previous actual dispatch time.
- `cron(minute hour day-of-month month day-of-week year)`: AWS 6-field cron;
honors `ScheduleExpressionTimezone`. Day-of-week is `1-7` or `SUN-SAT`, so
`2` is Monday and `cron(30 2 ? * 2#1 *)` is the first Monday of the month.
@@ -40,6 +43,12 @@ background dispatcher fires schedule targets on time. Supported expressions:
window are skipped. The dispatcher ticks every
`floci.services.scheduler.tick-interval-seconds` (default `10`).
+Rate schedules use the same dispatcher whether created or updated directly or
+through Step Functions. A changed future `StartDate` takes effect before the
+first dispatch. The dispatcher keeps its last-fire state in memory; past dates,
+restart, post-dispatch updates and re-enable timing have not been verified
+against live AWS. Fixed-anchor recurrence is not implemented.
+
Supported target types: SQS, Lambda, SNS, ECS `RunTask`, EventBridge
`PutEvents`, and unqualified Step Functions state machine ARNs. Templated
targets receive the schedule target's `Input`. When `Input` is absent, Floci
diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java
index e5967b1f2d..db3795290c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java
+++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java
@@ -225,10 +225,12 @@ public class ScheduleDispatcher implements Resettable {
}
case RATE -> {
long intervalMs = SchedulerExpressionParser.parseRateMillis(expr);
- Instant base = lastFireByArn.getOrDefault(arn, schedule.getCreationDate() != null
- ? schedule.getCreationDate()
- : now);
- yield base.plusMillis(intervalMs);
+ Instant lastFire = lastFireByArn.get(arn);
+ if (lastFire != null) {
+ yield lastFire.plusMillis(intervalMs);
+ }
+ yield schedule.getStartDate() != null ? schedule.getStartDate()
+ : schedule.getCreationDate() != null ? schedule.getCreationDate() : now;
}
case CRON -> {
Instant base = lastFireByArn.getOrDefault(arn, schedule.getCreationDate() != null
diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java
index 4dfb7e391b..9f7bc30837 100644
--- a/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java
@@ -189,13 +189,74 @@ class ScheduleDispatcherTest {
}
@Test
- void ratesFireOnceIntervalHasPassed() {
+ void rateWithoutStartDateFiresAtCreationThenWaitsAnInterval() {
+ Schedule schedule = newSchedule("immediate-rate", "rate(5 minutes)", "ENABLED");
+ Instant firstFire = schedule.getCreationDate();
+ when(schedulerService.listAllSchedules()).thenReturn(List.of(schedule));
+
+ dispatcher.tick(firstFire.minusSeconds(1));
+ verifyNoInteractions(invoker);
+ dispatcher.tick(firstFire);
+ dispatcher.tick(firstFire.plusSeconds(299));
+ verify(invoker).invoke(eq(schedule), eq(firstFire), any(), anyInt());
+ dispatcher.tick(firstFire.plusSeconds(300));
+ verify(invoker).invoke(eq(schedule), eq(firstFire.plusSeconds(300)), any(), anyInt());
+ verify(invoker, times(2)).invoke(eq(schedule), any(), any(), anyInt());
+ }
+
+ @Test
+ void rateWithFutureStartDateFiresAtStartDate() {
+ Schedule schedule = newSchedule("future-rate", "rate(10 minutes)", "ENABLED");
+ Instant start = schedule.getCreationDate().plusSeconds(60);
+ schedule.setStartDate(start);
+ when(schedulerService.listAllSchedules()).thenReturn(List.of(schedule));
+
+ dispatcher.tick(start.minusSeconds(1));
+ verifyNoInteractions(invoker);
+ dispatcher.tick(start.plusSeconds(5));
+ verify(invoker).invoke(eq(schedule), eq(start), any(), anyInt());
+ dispatcher.tick(start.plusSeconds(604));
+ verify(invoker, times(1)).invoke(eq(schedule), any(), any(), anyInt());
+ dispatcher.tick(start.plusSeconds(605));
+ verify(invoker).invoke(eq(schedule), eq(start.plusSeconds(605)), any(), anyInt());
+ }
+
+ @Test
+ void rateUsesUpdatedStartDateBeforeFirstFire() {
+ Schedule schedule = newSchedule("updated-rate", "rate(10 minutes)", "ENABLED");
+ Instant start = schedule.getCreationDate().plusSeconds(60);
+ schedule.setStartDate(start);
+ when(schedulerService.listAllSchedules()).thenReturn(List.of(schedule));
+ dispatcher.tick(start.minusSeconds(1));
+ schedule.setStartDate(start.plusSeconds(60));
+
+ dispatcher.tick(start);
+ verifyNoInteractions(invoker);
+ dispatcher.tick(start.plusSeconds(60));
+ verify(invoker).invoke(eq(schedule), eq(start.plusSeconds(60)), any(), anyInt());
+ }
+
+ @Test
+ void rateWithoutCreationDateFiresOnlyOnceAtFirstTick() {
+ Schedule schedule = newSchedule("missing-creation", "rate(5 minutes)", "ENABLED");
+ schedule.setCreationDate(null);
+ Instant now = Instant.parse("2026-04-21T09:00:00Z");
+ when(schedulerService.listAllSchedules()).thenReturn(List.of(schedule));
+
+ dispatcher.tick(now);
+ dispatcher.tick(now.plusSeconds(1));
+ verify(invoker).invoke(eq(schedule), eq(now), any(), anyInt());
+ verify(invoker, times(1)).invoke(eq(schedule), any(), any(), anyInt());
+ }
+
+ @Test
+ void ratesKeepIntervalFromActualDispatchTime() {
Schedule s = newSchedule("rate1", "rate(5 minutes)", "ENABLED");
s.setCreationDate(Instant.parse("2026-04-21T09:00:00Z"));
when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
dispatcher.tick(Instant.parse("2026-04-21T09:04:00Z"));
- verify(invoker, never()).invoke(any(), any(), any(), anyInt());
+ verify(invoker).invoke(eq(s), eq(s.getCreationDate()), any(), anyInt());
dispatcher.tick(Instant.parse("2026-04-21T09:06:00Z"));
verify(invoker, times(1)).invoke(eq(s), any(), any(), anyInt());
@@ -209,6 +270,9 @@ class ScheduleDispatcherTest {
Schedule schedule = newSchedule("legacy-weekly", "rate(1 week)", "ENABLED");
when(schedulerService.listAllSchedules()).thenReturn(List.of(schedule));
+ dispatcher.tick(schedule.getCreationDate());
+ verify(invoker).invoke(eq(schedule), eq(schedule.getCreationDate()), any(), anyInt());
+ clearInvocations(invoker);
dispatcher.tick(Instant.parse("2026-04-28T08:59:59Z"));
verify(invoker, never()).invoke(any(), any(), any(), anyInt());
@@ -228,6 +292,9 @@ class ScheduleDispatcherTest {
s.setCreationDate(Instant.parse("2026-03-07T10:30:00Z"));
when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
+ dispatcher.tick(s.getCreationDate());
+ verify(invoker).invoke(eq(s), eq(s.getCreationDate()), any(), anyInt());
+ clearInvocations(invoker);
dispatcher.tick(Instant.parse("2026-03-08T09:30:00Z"));
verify(invoker, never()).invoke(any(), any(), any(), anyInt());
dispatcher.tick(Instant.parse("2026-03-08T10:30:00Z"));
@@ -471,7 +538,7 @@ class ScheduleDispatcherTest {
verify(invoker, times(4)).invoke(eq(s), any(), any(), anyInt());
List<Map<String, MessageAttributeValue>> deadLetters = deadLetters(2);
- assertEquals("2026-04-21T09:05:00Z", attribute(deadLetters.get(0), "SCHEDULED_TIME"));
+ assertEquals("2026-04-21T09:00:00Z", attribute(deadLetters.get(0), "SCHEDULED_TIME"));
assertEquals("2026-04-21T09:10:00Z", attribute(deadLetters.get(1), "SCHEDULED_TIME"));
assertNotEquals(attribute(deadLetters.get(0), "EXECUTION_ID"), attribute(deadLetters.get(1), "EXECUTION_ID"));
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerContextAttributesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerContextAttributesIntegrationTest.java
index e2d21a8840..68376af8df 100644
--- a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerContextAttributesIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerContextAttributesIntegrationTest.java
@@ -99,7 +99,7 @@ class SchedulerContextAttributesIntegrationTest {
String scheduleName = uniqueName("ctx-rate");
harness.createSchedule(scheduleName, "rate(1 minute)", "ENABLED", queueArn(queueName), CONTEXT_INPUT);
Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION);
- Instant firstFire = schedule.getCreationDate().plus(1, ChronoUnit.MINUTES);
+ Instant firstFire = schedule.getCreationDate();
ScheduleDispatcher dispatcher = harness.dispatcherFor(scheduleName);
dispatcher.tick(firstFire.plusSeconds(1));
@@ -190,7 +190,7 @@ class SchedulerContextAttributesIntegrationTest {
String scheduleName = uniqueName("ctx-ids");
harness.createSchedule(scheduleName, "rate(1 minute)", "ENABLED", queueArn(queueName), CONTEXT_INPUT);
Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION);
- Instant firstFire = schedule.getCreationDate().plus(1, ChronoUnit.MINUTES);
+ Instant firstFire = schedule.getCreationDate();
ScheduleDispatcher dispatcher = harness.dispatcherFor(scheduleName);
dispatcher.tick(firstFire.plusSeconds(1));
diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerRateFirstOccurrenceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerRateFirstOccurrenceIntegrationTest.java
new file mode 100644
index 0000000000..4c5be659f6
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerRateFirstOccurrenceIntegrationTest.java
@@ -0,0 +1,139 @@
+package io.github.hectorvent.floci.services.scheduler;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.scheduler.model.Schedule;
+import io.github.hectorvent.floci.services.sqs.SqsService;
+import io.github.hectorvent.floci.services.sqs.model.Message;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.QuarkusTestProfile;
+import io.quarkus.test.junit.TestProfile;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import static io.github.hectorvent.floci.services.scheduler.SchedulerTestHarness.REGION;
+import static io.github.hectorvent.floci.services.scheduler.SchedulerTestHarness.ROLE_ARN;
+import static io.github.hectorvent.floci.services.scheduler.SchedulerTestHarness.uniqueName;
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+@QuarkusTest
+@TestProfile(SchedulerRateFirstOccurrenceIntegrationTest.ManualDispatch.class)
+class SchedulerRateFirstOccurrenceIntegrationTest {
+
+ public static class ManualDispatch implements QuarkusTestProfile {
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ return Map.of("floci.services.scheduler.invocation-enabled", "false");
+ }
+ }
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ @Inject
+ SchedulerService schedulerService;
+ @Inject
+ ScheduleInvoker scheduleInvoker;
+ @Inject
+ SqsService sqsService;
+ @Inject
+ EmulatorConfig config;
+
+ private SchedulerTestHarness harness;
+ private final List<String> queues = new ArrayList<>();
+
+ @BeforeEach
+ void setUp() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ harness = new SchedulerTestHarness(schedulerService, scheduleInvoker, sqsService, config);
+ }
+
+ @AfterEach
+ void cleanUp() {
+ harness.cleanUp();
+ for (String queue : queues) {
+ sqsService.deleteQueue(queue, REGION);
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"false,omitted", "false,future", "false,updated",
+ "true,omitted", "true,future", "true,updated"})
+ void firstOccurrenceUsesStoredStartThroughDirectAndSdkTasks(boolean sdkTask, String mode) throws Exception {
+ String name = uniqueName("rate-first");
+ String queueName = uniqueName("rate-first-q");
+ String queueUrl = sqsService.createQueue(queueName, Map.of(), REGION).getQueueUrl();
+ queues.add(queueUrl);
+ String queueArn = sqsService.getQueueAttributes(queueUrl, List.of("QueueArn"), REGION).get("QueueArn");
+ Instant start = Instant.now().plusSeconds(86400);
+ ObjectNode request = MAPPER.createObjectNode();
+ request.put("Name", name);
+ request.put("ScheduleExpression", "rate(10 minutes)");
+ request.put("State", "ENABLED");
+ request.putObject("FlexibleTimeWindow").put("Mode", "OFF");
+ ObjectNode target = request.putObject("Target");
+ target.put("Arn", queueArn);
+ target.put("RoleArn", ROLE_ARN);
+ target.put("Input", "<aws.scheduler.scheduled-time>");
+ if (!"omitted".equals(mode)) {
+ request.put("StartDate", start.toEpochMilli() / 1000.0);
+ }
+ harness.trackSchedule(name);
+ applySchedule(request, sdkTask, false);
+ if ("updated".equals(mode)) {
+ request.put("StartDate", start.plusSeconds(120).toEpochMilli() / 1000.0);
+ applySchedule(request, sdkTask, true);
+ }
+ Schedule schedule = schedulerService.getSchedule(name, null, REGION);
+ Instant firstFire = schedule.getStartDate() != null ? schedule.getStartDate() : schedule.getCreationDate();
+ ScheduleDispatcher dispatcher = harness.dispatcherFor(name);
+ dispatcher.tick(firstFire.minusMillis(1));
+ assertTrue(sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION).isEmpty());
+
+ dispatcher.tick(firstFire.plusSeconds(5));
+ List<Message> messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
+ assertEquals(1, messages.size());
+ assertEquals(firstFire.truncatedTo(ChronoUnit.SECONDS).toString(), messages.get(0).getBody());
+ dispatcher.tick(firstFire.plusSeconds(604));
+ assertTrue(sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION).isEmpty());
+ dispatcher.tick(firstFire.plusSeconds(605));
+ messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
+ assertEquals(1, messages.size());
+ assertEquals(firstFire.plusSeconds(605).truncatedTo(ChronoUnit.SECONDS).toString(), messages.get(0).getBody());
+ }
+
+ private void applySchedule(ObjectNode request, boolean sdkTask, boolean update) {
+ if (!sdkTask) {
+ if (update) {
+ given().contentType("application/json").body(request.toString())
+ .when().put("/schedules/" + request.path("Name").asText()).then().statusCode(200);
+ } else {
+ given().contentType("application/json").body(request.toString())
+ .when().post("/schedules/" + request.path("Name").asText()).then().statusCode(200);
+ }
+ return;
+ }
+ ObjectNode definition = MAPPER.createObjectNode();
+ definition.put("StartAt", "Schedule");
+ ObjectNode task = definition.putObject("States").putObject("Schedule");
+ task.put("Type", "Task");
+ task.put("Resource", "arn:aws:states:::aws-sdk:scheduler:" + (update ? "updateSchedule" : "createSchedule"));
+ task.set("Parameters", request);
+ task.put("End", true);
+ String machine = harness.createStateMachine(uniqueName("rate-first-task"), definition.toString());
+ String execution = harness.startExecution(machine);
+ assertEquals("SUCCEEDED", harness.waitForTerminalExecution(execution).jsonPath().getString("status"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerStepFunctionsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerStepFunctionsIntegrationTest.java
index 831d3b19b1..f45b3d3393 100644
--- a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerStepFunctionsIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerStepFunctionsIntegrationTest.java
@@ -1,11 +1,8 @@
package io.github.hectorvent.floci.services.scheduler;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.scheduler.model.Schedule;
import io.github.hectorvent.floci.services.sqs.SqsService;
-import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsService;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
@@ -15,10 +12,8 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
-import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -26,32 +21,23 @@ import static io.github.hectorvent.floci.services.scheduler.SchedulerTestHarness
import static io.github.hectorvent.floci.services.scheduler.SchedulerTestHarness.ROLE_ARN;
import static io.github.hectorvent.floci.services.scheduler.SchedulerTestHarness.atExpression;
import static io.github.hectorvent.floci.services.scheduler.SchedulerTestHarness.uniqueName;
-import static io.restassured.RestAssured.given;
-import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class SchedulerStepFunctionsIntegrationTest {
- private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
- private static final ObjectMapper MAPPER = new ObjectMapper();
-
@Inject
ScheduleInvoker scheduleInvoker;
@Inject
SchedulerService schedulerService;
- @Inject
- StepFunctionsService stepFunctionsService;
-
@Inject
SqsService sqsService;
@Inject
EmulatorConfig config;
- private final List<String> stateMachineArns = new ArrayList<>();
private SchedulerTestHarness harness;
@BeforeAll
@@ -67,9 +53,6 @@ class SchedulerStepFunctionsIntegrationTest {
@AfterEach
void cleanUp() {
harness.cleanUp();
- for (String stateMachineArn : stateMachineArns) {
- stepFunctionsService.deleteStateMachine(stateMachineArn);
- }
}
@Test
@@ -82,9 +65,9 @@ class SchedulerStepFunctionsIntegrationTest {
harness.dispatcherFor(scheduleName).tick(fireAt);
- List<Map<String, Object>> executions = listExecutions(stateMachineArn);
+ List<Map<String, Object>> executions = harness.listExecutions(stateMachineArn);
assertEquals(1, executions.size());
- Response execution = waitForTerminalExecution((String) executions.get(0).get("executionArn"));
+ Response execution = harness.waitForTerminalExecution((String) executions.get(0).get("executionArn"));
assertEquals("SUCCEEDED", execution.jsonPath().getString("status"));
assertEquals(input, execution.jsonPath().getString("input"));
assertEquals(input, execution.jsonPath().getString("output"));
@@ -102,7 +85,7 @@ class SchedulerStepFunctionsIntegrationTest {
dispatcher.tick(firstFire);
dispatcher.tick(firstFire.plus(61, ChronoUnit.SECONDS));
- assertEquals(2, listExecutions(stateMachineArn).size());
+ assertEquals(2, harness.listExecutions(stateMachineArn).size());
}
@Test
@@ -114,7 +97,7 @@ class SchedulerStepFunctionsIntegrationTest {
harness.dispatcherFor(scheduleName).tick(fireAt);
- assertEquals(0, listExecutions(stateMachineArn).size());
+ assertEquals(0, harness.listExecutions(stateMachineArn).size());
}
@Test
@@ -125,7 +108,7 @@ class SchedulerStepFunctionsIntegrationTest {
targetStateMachineArn, "{\"deleted\":false}");
Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION);
Instant fireAt = schedule.getCreationDate().plus(61, ChronoUnit.SECONDS);
- String deleterStateMachineArn = createStateMachine(uniqueName("schedule-deleter"), """
+ String deleterStateMachineArn = harness.createStateMachine(uniqueName("schedule-deleter"), """
{
"QueryLanguage": "JSONata",
"StartAt": "Delete",
@@ -140,12 +123,12 @@ class SchedulerStepFunctionsIntegrationTest {
}
""".replace("SCHEDULE_NAME", scheduleName));
- Response deletion = waitForTerminalExecution(startExecution(deleterStateMachineArn));
+ Response deletion = harness.waitForTerminalExecution(harness.startExecution(deleterStateMachineArn));
assertEquals("SUCCEEDED", deletion.jsonPath().getString("status"));
harness.unscopedDispatcher().tick(fireAt);
- assertEquals(0, listExecutions(targetStateMachineArn).size());
+ assertEquals(0, harness.listExecutions(targetStateMachineArn).size());
}
@Test
@@ -154,7 +137,7 @@ class SchedulerStepFunctionsIntegrationTest {
String scheduleName = uniqueName("sfn-sdk-input");
String expectedInput = "{\"scheduleId\":\"schedule-123\",\"nested\":{\"quote\":\"a\\\"b\"}}";
Instant fireAt = Instant.now().plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.SECONDS);
- String creatorStateMachineArn = createStateMachine(uniqueName("schedule-creator"), """
+ String creatorStateMachineArn = harness.createStateMachine(uniqueName("schedule-creator"), """
{
"QueryLanguage": "JSONata",
"StartAt": "Create",
@@ -185,7 +168,7 @@ class SchedulerStepFunctionsIntegrationTest {
.replace("TARGET_ARN", targetStateMachineArn)
.replace("ROLE", ROLE_ARN));
- Response creation = waitForTerminalExecution(startExecution(creatorStateMachineArn));
+ Response creation = harness.waitForTerminalExecution(harness.startExecution(creatorStateMachineArn));
assertEquals("SUCCEEDED", creation.jsonPath().getString("status"));
harness.trackSchedule(scheduleName);
Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION);
@@ -193,9 +176,9 @@ class SchedulerStepFunctionsIntegrationTest {
harness.dispatcherFor(scheduleName).tick(fireAt);
- List<Map<String, Object>> executions = listExecutions(targetStateMachineArn);
+ List<Map<String, Object>> executions = harness.listExecutions(targetStateMachineArn);
assertEquals(1, executions.size());
- Response targetExecution = waitForTerminalExecution((String) executions.get(0).get("executionArn"));
+ Response targetExecution = harness.waitForTerminalExecution((String) executions.get(0).get("executionArn"));
assertEquals("SUCCEEDED", targetExecution.jsonPath().getString("status"));
assertEquals(expectedInput, targetExecution.jsonPath().getString("input"));
assertEquals(expectedInput, targetExecution.jsonPath().getString("output"));
@@ -204,72 +187,7 @@ class SchedulerStepFunctionsIntegrationTest {
private String createPassStateMachine() {
String name = uniqueName("scheduled-workflow");
String definition = "{\"StartAt\":\"Pass\",\"States\":{\"Pass\":{\"Type\":\"Pass\",\"End\":true}}}";
- return createStateMachine(name, definition);
+ return harness.createStateMachine(name, definition);
}
- private String createStateMachine(String name, String definition) {
- ObjectNode request = MAPPER.createObjectNode();
- request.put("name", name);
- request.put("definition", definition);
- request.put("roleArn", ROLE_ARN);
-
- Response response = given()
- .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
- .contentType(SFN_CONTENT_TYPE)
- .body(request.toString())
- .when()
- .post("/");
- response.then().statusCode(200);
- String stateMachineArn = response.jsonPath().getString("stateMachineArn");
- stateMachineArns.add(stateMachineArn);
- return stateMachineArn;
- }
-
- private String startExecution(String stateMachineArn) {
- ObjectNode request = MAPPER.createObjectNode();
- request.put("stateMachineArn", stateMachineArn);
- request.put("input", "{}");
- Response response = given()
- .header("X-Amz-Target", "AWSStepFunctions.StartExecution")
- .contentType(SFN_CONTENT_TYPE)
- .body(request.toString())
- .when()
- .post("/");
- response.then().statusCode(200);
- return response.jsonPath().getString("executionArn");
- }
-
- private List<Map<String, Object>> listExecutions(String stateMachineArn) {
- ObjectNode request = MAPPER.createObjectNode();
- request.put("stateMachineArn", stateMachineArn);
- Response response = given()
- .header("X-Amz-Target", "AWSStepFunctions.ListExecutions")
- .contentType(SFN_CONTENT_TYPE)
- .body(request.toString())
- .when()
- .post("/");
- response.then().statusCode(200);
- return response.jsonPath().getList("executions");
- }
-
- private Response waitForTerminalExecution(String executionArn) {
- await()
- .atMost(Duration.ofSeconds(5))
- .pollInterval(Duration.ofMillis(100))
- .until(() -> !"RUNNING".equals(describeExecution(executionArn).jsonPath().getString("status")));
- return describeExecution(executionArn);
- }
-
- private Response describeExecution(String executionArn) {
- ObjectNode request = MAPPER.createObjectNode();
- request.put("executionArn", executionArn);
- Response response = given()
- .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
- .contentType(SFN_CONTENT_TYPE)
- .body(request.toString())
- .when()
- .post("/");
- response.then().statusCode(200);
- return response;
- }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerTestHarness.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerTestHarness.java
index 46c5b77a8b..2ea86d419c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerTestHarness.java
+++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerTestHarness.java
@@ -6,15 +6,19 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.scheduler.model.Schedule;
import io.github.hectorvent.floci.services.sqs.SqsService;
+import io.restassured.response.Response;
+import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
+import static org.awaitility.Awaitility.await;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -28,6 +32,7 @@ final class SchedulerTestHarness {
static final String REGION = "us-east-1";
static final String ROLE_ARN = "arn:aws:iam::000000000000:role/scheduler-role";
+ private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final DateTimeFormatter SCHEDULE_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss").withZone(ZoneOffset.UTC);
@@ -38,6 +43,7 @@ final class SchedulerTestHarness {
private final EmulatorConfig config;
private final List<String> scheduleNames = new ArrayList<>();
private final List<ScheduleDispatcher> dispatchers = new ArrayList<>();
+ private final List<String> stateMachineArns = new ArrayList<>();
SchedulerTestHarness(SchedulerService schedulerService, ScheduleInvoker scheduleInvoker,
SqsService sqsService, EmulatorConfig config) {
@@ -94,6 +100,72 @@ final class SchedulerTestHarness {
return track(new ScheduleDispatcher(schedulerService, scheduleInvoker, sqsService, config));
}
+ String createStateMachine(String name, String definition) {
+ ObjectNode request = MAPPER.createObjectNode();
+ request.put("name", name);
+ request.put("definition", definition);
+ request.put("roleArn", ROLE_ARN);
+
+ Response response = given()
+ .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
+ .contentType(SFN_CONTENT_TYPE)
+ .body(request.toString())
+ .when()
+ .post("/");
+ response.then().statusCode(200);
+ String stateMachineArn = response.jsonPath().getString("stateMachineArn");
+ stateMachineArns.add(stateMachineArn);
+ return stateMachineArn;
+ }
+
+ String startExecution(String stateMachineArn) {
+ ObjectNode request = MAPPER.createObjectNode();
+ request.put("stateMachineArn", stateMachineArn);
+ request.put("input", "{}");
+ Response response = given()
+ .header("X-Amz-Target", "AWSStepFunctions.StartExecution")
+ .contentType(SFN_CONTENT_TYPE)
+ .body(request.toString())
+ .when()
+ .post("/");
+ response.then().statusCode(200);
+ return response.jsonPath().getString("executionArn");
+ }
+
+ List<Map<String, Object>> listExecutions(String stateMachineArn) {
+ ObjectNode request = MAPPER.createObjectNode();
+ request.put("stateMachineArn", stateMachineArn);
+ Response response = given()
+ .header("X-Amz-Target", "AWSStepFunctions.ListExecutions")
+ .contentType(SFN_CONTENT_TYPE)
+ .body(request.toString())
+ .when()
+ .post("/");
+ response.then().statusCode(200);
+ return response.jsonPath().getList("executions");
+ }
+
+ Response waitForTerminalExecution(String executionArn) {
+ await()
+ .atMost(Duration.ofSeconds(10))
+ .pollInterval(Duration.ofMillis(100))
+ .until(() -> !"RUNNING".equals(describeExecution(executionArn).jsonPath().getString("status")));
+ return describeExecution(executionArn);
+ }
+
+ private Response describeExecution(String executionArn) {
+ ObjectNode request = MAPPER.createObjectNode();
+ request.put("executionArn", executionArn);
+ Response response = given()
+ .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
+ .contentType(SFN_CONTENT_TYPE)
+ .body(request.toString())
+ .when()
+ .post("/");
+ response.then().statusCode(200);
+ return response;
+ }
+
void cleanUp() {
for (String scheduleName : scheduleNames) {
try {
@@ -105,6 +177,11 @@ final class SchedulerTestHarness {
for (ScheduleDispatcher dispatcher : dispatchers) {
dispatcher.onStop(null);
}
+ for (String stateMachineArn : stateMachineArns) {
+ given().header("X-Amz-Target", "AWSStepFunctions.DeleteStateMachine")
+ .contentType(SFN_CONTENT_TYPE).body(Map.of("stateMachineArn", stateMachineArn))
+ .when().post("/").then().statusCode(200);
+ }
}
private ScheduleDispatcher track(ScheduleDispatcher dispatcher) {