From 07ebc33d28b366dab2d9b9b2470d91c9a2b26434 Mon Sep 17 00:00:00 2001 From: Salil Chincholikar <31334826+salilchincholikar@users.noreply.github.com> Date: Fri, 9 Oct 2026 21:38:34 +0530 Subject: [PATCH] feat(scheduler): substitute schedule context attributes in target Input (#5194) * feat(scheduler): substitute schedule context attributes in target Input Replace , , and in the target Input for templated and universal targets, using the occurrence's scheduled time and the retry attempt the dispatcher tracks. * test(scheduler): share one harness between the scheduler integration tests SchedulerContextAttributesIntegrationTest copied its schedule creation, scoped dispatcher, unique names and cleanup from SchedulerStepFunctionsIntegrationTest. Both now use SchedulerTestHarness, which also builds the at() expression they each formatted by hand. * fix(scheduler): keep dead-letter context aligned with the last attempt Materialize the target request before every invocation so an exhausted occurrence's dead-letter body carries the same execution id and attempt number as its last attempted delivery. Preserve that request when the occurrence expires before another retry. Share scheduled-time formatting across context attributes, default events and dead-letter attributes. Cover retry-count and event-age exhaustion and remove the documented first-attempt body limitation. * style(scheduler): fix shared harness static import order Place ROLE_ARN before atExpression to satisfy the ImportOrder rule used by the PR's merged Checkstyle configuration. --- docs/services/scheduler.md | 11 + .../scheduler/ScheduleDispatcher.java | 33 ++- .../services/scheduler/ScheduleInvoker.java | 77 +++++- .../scheduler/ScheduleDispatcherTest.java | 116 +++++---- .../scheduler/ScheduleInvokerTest.java | 79 +++++++ ...dulerContextAttributesIntegrationTest.java | 223 ++++++++++++++++++ ...SchedulerStepFunctionsIntegrationTest.java | 96 ++------ .../scheduler/SchedulerTestHarness.java | 114 +++++++++ 8 files changed, 606 insertions(+), 143 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerContextAttributesIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerTestHarness.java diff --git a/docs/services/scheduler.md b/docs/services/scheduler.md index d6c3db30b4..fdc815eef1 100644 --- a/docs/services/scheduler.md +++ b/docs/services/scheduler.md @@ -52,6 +52,17 @@ an asynchronous execution with that payload as its input. Scheduler delivery succeeds when `StartExecution` is accepted; a later workflow failure does not trigger Scheduler retries. +When `Input` is present, Floci replaces the Scheduler context attributes in it +on every invocation, for templated and universal (`aws-sdk`) targets alike: +`` with the schedule ARN, +`` with the occurrence's scheduled time in UTC +to the second (for example `2026-04-21T09:17:54Z`), `` +with a 16-character hex id, and `` with the +1-based attempt number. Each attempted invocation, retries included, gets its +own execution id and increments the attempt number; a dead-letter message +reports the last attempt's id as `EXECUTION_ID`. The dead-letter body carries +the last attempt's request, with matching context attributes. + `CreateSchedule` and `UpdateSchedule` reject a non-JSON `Input` for Lambda, Step Functions, and EventBridge targets with a `ValidationException`, as AWS does. A blank `Input`, or one with text after the JSON value such as 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 25bc10bbb0..e5967b1f2d 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 @@ -19,14 +19,12 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.time.Instant; -import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -208,9 +206,9 @@ public class ScheduleDispatcher implements Resettable { // Record the fire before delivering so a failing occurrence never holds back the next one. recordFire(schedule, now); - String requestBody = invoker.materializeRequest(schedule, nextFire); + String executionId = ScheduleInvoker.newExecutionId(); attempt(schedule, new Occurrence(schedule.getArn(), nextFire), - Delivery.first(kind, schedule, requestBody), now); + Delivery.first(kind, schedule, executionId), now); } private Instant computeNextFire(Schedule schedule, Kind kind, Instant now) { @@ -242,8 +240,11 @@ public class ScheduleDispatcher implements Resettable { } private void attempt(Schedule schedule, Occurrence occurrence, Delivery delivery, Instant now) { + String requestBody = invoker.materializeRequest(schedule, occurrence.scheduledAt(), + delivery.executionId(), delivery.attemptNumber()); + delivery = delivery.withRequestBody(requestBody); try { - invoker.invoke(schedule, occurrence.scheduledAt()); + invoker.invoke(schedule, occurrence.scheduledAt(), delivery.executionId(), delivery.attemptNumber()); } catch (Exception e) { LOG.warnv("Schedule {0} invocation failed: {1}", schedule.getArn(), e.getMessage()); Delivery failed = delivery.failedWith(e, now); @@ -304,7 +305,7 @@ public class ScheduleDispatcher implements Resettable { attributes.put("IS_PAYLOAD_TRUNCATED", stringAttribute("false")); attributes.put("RETRY_ATTEMPTS", stringAttribute(String.valueOf(delivery.retryAttempts()))); attributes.put("SCHEDULED_TIME", stringAttribute( - occurrence.scheduledAt().truncatedTo(ChronoUnit.SECONDS).toString())); + ScheduleInvoker.formatScheduledTime(occurrence.scheduledAt()))); attributes.put("SCHEDULE_ARN", stringAttribute(schedule.getArn())); attributes.put("TARGET_ARN", stringAttribute(target.getArn())); @@ -377,15 +378,25 @@ public class ScheduleDispatcher implements Resettable { int retryAttempts, String errorCode, String errorMessage, String requestBody, Instant nextAttemptAt) { - static Delivery first(Kind kind, Schedule schedule, String requestBody) { - String executionId = UUID.randomUUID().toString().replace("-", "").substring(0, 16); + static Delivery first(Kind kind, Schedule schedule, String executionId) { return new Delivery(kind, schedule.getLastModificationDate(), executionId, 0, null, null, - requestBody, null); + null, null); } + Delivery withRequestBody(String body) { + return new Delivery(kind, lastModificationDate, executionId, retryAttempts, errorCode, errorMessage, + body, nextAttemptAt); + } + + /** The 1-based number of the attempt this delivery makes: the first attempt plus its retries. */ + int attemptNumber() { + return retryAttempts + 1; + } + + /** Each attempted invocation gets its own execution id, as AWS documents for the context attribute. */ Delivery nextRetry() { - return new Delivery(kind, lastModificationDate, executionId, retryAttempts + 1, errorCode, errorMessage, - requestBody, null); + return new Delivery(kind, lastModificationDate, ScheduleInvoker.newExecutionId(), retryAttempts + 1, + errorCode, errorMessage, requestBody, null); } Delivery failedWith(Exception e, Instant now) { diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java index 6f22c78347..95209dbf37 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java @@ -48,6 +48,11 @@ public class ScheduleInvoker { private static final Logger LOG = Logger.getLogger(ScheduleInvoker.class); + static final String CONTEXT_SCHEDULE_ARN = ""; + static final String CONTEXT_SCHEDULED_TIME = ""; + static final String CONTEXT_EXECUTION_ID = ""; + static final String CONTEXT_ATTEMPT_NUMBER = ""; + private final SqsService sqsService; private final LambdaService lambdaService; private final SnsService snsService; @@ -79,24 +84,35 @@ public class ScheduleInvoker { } /** - * Delivers one occurrence of {@code schedule}, scheduled at {@code scheduledAt}, to its target - * and returns the JSON request that was sent (see {@link #materializeRequest}). + * Delivers the first attempt of one occurrence of {@code schedule}, under a fresh execution id. + * See {@link #invoke(Schedule, Instant, String, int)}. */ public String invoke(Schedule schedule, Instant scheduledAt) { + return invoke(schedule, scheduledAt, newExecutionId(), 1); + } + + /** + * Delivers one attempt of the occurrence of {@code schedule} scheduled at {@code scheduledAt} + * to its target and returns the JSON request that was sent (see {@link #materializeRequest}). + * {@code executionId} and the 1-based {@code attemptNumber} fill the context attributes of + * the target's {@code Input}. + */ + public String invoke(Schedule schedule, Instant scheduledAt, String executionId, int attemptNumber) { Target target = schedule.getTarget(); if (target == null || target.getArn() == null) { return "{}"; } String arn = target.getArn(); String region = regionOf(schedule, defaultRegion); + String input = contextualInput(schedule, scheduledAt, executionId, attemptNumber); if (isUniversalTarget(arn)) { invokeUniversalTarget(arn.substring(arn.indexOf(":aws-sdk:") + ":aws-sdk:".length()), - target.getInput(), region); - return universalTargetRequest(target); + input, region); + return universalTargetRequest(input); } TargetKind kind = TargetKind.of(target); - String payload = templatedPayload(schedule, scheduledAt); + String payload = templatedPayload(schedule, input, scheduledAt); String targetRegion = extractRegion(arn, region); switch (kind) { case SQS -> { @@ -141,14 +157,52 @@ public class ScheduleInvoker { * in the dead-letter queue example of the Scheduler user guide. */ public String materializeRequest(Schedule schedule, Instant scheduledAt) { + return materializeRequest(schedule, scheduledAt, newExecutionId(), 1); + } + + /** The request {@link #invoke(Schedule, Instant, String, int)} sends for the same attempt. */ + public String materializeRequest(Schedule schedule, Instant scheduledAt, String executionId, + int attemptNumber) { Target target = schedule.getTarget(); if (target == null || target.getArn() == null) { return "{}"; } + String input = contextualInput(schedule, scheduledAt, executionId, attemptNumber); if (isUniversalTarget(target.getArn())) { - return universalTargetRequest(target); + return universalTargetRequest(input); } - return templatedTargetRequest(target, TargetKind.of(target), templatedPayload(schedule, scheduledAt)); + return templatedTargetRequest(target, TargetKind.of(target), + templatedPayload(schedule, input, scheduledAt)); + } + + static String formatScheduledTime(Instant scheduledAt) { + return scheduledAt.truncatedTo(ChronoUnit.SECONDS).toString(); + } + + /** A Scheduler-style execution id: 16 lowercase hex characters. */ + public static String newExecutionId() { + return UUID.randomUUID().toString().replace("-", "").substring(0, 16); + } + + /** + * The target's {@code Input} with the Scheduler context attributes replaced: the schedule ARN, + * the scheduled time as UTC seconds with a {@code Z} suffix, the execution id and the 1-based + * attempt number. Null when the target has no {@code Input}, so the default event is untouched. + */ + static String contextualInput(Schedule schedule, Instant scheduledAt, String executionId, + int attemptNumber) { + String input = schedule.getTarget().getInput(); + if (input == null || input.indexOf('<') < 0) { + return input; + } + String scheduledTime = scheduledAt == null + ? "" + : formatScheduledTime(scheduledAt); + return input + .replace(CONTEXT_SCHEDULE_ARN, schedule.getArn() == null ? "" : schedule.getArn()) + .replace(CONTEXT_SCHEDULED_TIME, scheduledTime) + .replace(CONTEXT_EXECUTION_ID, executionId == null ? "" : executionId) + .replace(CONTEXT_ATTEMPT_NUMBER, String.valueOf(attemptNumber)); } /** The templated target types Floci delivers to, in the order their ARNs are recognised. */ @@ -189,8 +243,8 @@ public class ScheduleInvoker { return arn.contains(":aws-sdk:"); } - private String universalTargetRequest(Target target) { - return validJsonOrString(target.getInput() != null ? target.getInput() : "{}"); + private String universalTargetRequest(String input) { + return validJsonOrString(input != null ? input : "{}"); } private String templatedTargetRequest(Target target, TargetKind kind, String payload) { @@ -256,8 +310,7 @@ public class ScheduleInvoker { * The payload a templated target receives: the target's {@code Input}, or Scheduler's default * notification when no {@code Input} was configured (API reference, {@code Target.Input}). */ - private String templatedPayload(Schedule schedule, Instant scheduledAt) { - String input = schedule.getTarget().getInput(); + private String templatedPayload(Schedule schedule, String input, Instant scheduledAt) { return input != null ? input : defaultScheduledEvent(schedule, scheduledAt); } @@ -275,7 +328,7 @@ public class ScheduleInvoker { event.put("detail-type", "Scheduled Event"); event.put("source", "aws.scheduler"); event.put("account", scheduleArn.accountId()); - event.put("time", scheduledAt.truncatedTo(ChronoUnit.SECONDS).toString()); + event.put("time", formatScheduledTime(scheduledAt)); event.put("region", scheduleArn.region()); event.put("resources", List.of(schedule.getArn())); event.put("detail", "{}"); 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 5ee05d9164..4dfb7e391b 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 @@ -75,8 +75,8 @@ class ScheduleDispatcherTest { s.getTarget().setDeadLetterConfig(new DeadLetterConfig(DLQ_TARGET_ARN)); when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); doThrow(new RuntimeException("target unavailable")).when(invoker) - .invoke(eq(s), any()); - when(invoker.materializeRequest(eq(s), any())).thenReturn(TARGET_REQUEST); + .invoke(eq(s), any(), any(), anyInt()); + when(invoker.materializeRequest(eq(s), any(), any(), anyInt())).thenReturn(TARGET_REQUEST); return s; } @@ -108,7 +108,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); - verify(invoker, times(1)).invoke(eq(s), eq(Instant.parse("2026-04-21T09:17:54Z"))); + verify(invoker, times(1)).invoke(eq(s), eq(Instant.parse("2026-04-21T09:17:54Z")), any(), anyInt()); } @Test @@ -118,7 +118,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:17:00Z")); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); } @Test @@ -130,7 +130,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:20:00Z")); - verify(invoker, times(1)).invoke(eq(s), any()); + verify(invoker, times(1)).invoke(eq(s), any(), any(), anyInt()); } @Test @@ -163,7 +163,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); } @Test @@ -174,7 +174,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); } @Test @@ -185,7 +185,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); } @Test @@ -195,13 +195,13 @@ class ScheduleDispatcherTest { when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); dispatcher.tick(Instant.parse("2026-04-21T09:04:00Z")); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); dispatcher.tick(Instant.parse("2026-04-21T09:06:00Z")); - verify(invoker, times(1)).invoke(eq(s), any()); + verify(invoker, times(1)).invoke(eq(s), any(), any(), anyInt()); dispatcher.tick(Instant.parse("2026-04-21T09:11:01Z")); - verify(invoker, times(2)).invoke(eq(s), any()); + verify(invoker, times(2)).invoke(eq(s), any(), any(), anyInt()); } @Test @@ -210,15 +210,15 @@ class ScheduleDispatcherTest { when(schedulerService.listAllSchedules()).thenReturn(List.of(schedule)); dispatcher.tick(Instant.parse("2026-04-28T08:59:59Z")); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); Instant firstFire = Instant.parse("2026-04-28T09:00:00Z"); dispatcher.tick(firstFire); - verify(invoker).invoke(schedule, firstFire); + verify(invoker).invoke(eq(schedule), eq(firstFire), any(), anyInt()); Instant secondFire = firstFire.plusSeconds(7 * 24 * 60 * 60); dispatcher.tick(secondFire); - verify(invoker).invoke(schedule, secondFire); + verify(invoker).invoke(eq(schedule), eq(secondFire), any(), anyInt()); } @Test @@ -229,9 +229,9 @@ class ScheduleDispatcherTest { when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); dispatcher.tick(Instant.parse("2026-03-08T09:30:00Z")); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); dispatcher.tick(Instant.parse("2026-03-08T10:30:00Z")); - verify(invoker).invoke(s, Instant.parse("2026-03-08T10:30:00Z")); + verify(invoker).invoke(eq(s), eq(Instant.parse("2026-03-08T10:30:00Z")), any(), anyInt()); } @Test @@ -241,9 +241,9 @@ class ScheduleDispatcherTest { when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); dispatcher.tick(Instant.parse("2026-04-21T15:29:00Z")); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); dispatcher.tick(Instant.parse("2026-04-21T15:30:00Z")); - verify(invoker).invoke(s, Instant.parse("2026-04-21T15:30:00Z")); + verify(invoker).invoke(eq(s), eq(Instant.parse("2026-04-21T15:30:00Z")), any(), anyInt()); } @Test @@ -252,9 +252,9 @@ class ScheduleDispatcherTest { when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); dispatcher.tick(Instant.parse("2026-04-21T10:29:00Z")); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); dispatcher.tick(Instant.parse("2026-04-21T10:30:00Z")); - verify(invoker).invoke(s, Instant.parse("2026-04-21T10:30:00Z")); + verify(invoker).invoke(eq(s), eq(Instant.parse("2026-04-21T10:30:00Z")), any(), anyInt()); } @Test @@ -265,13 +265,13 @@ class ScheduleDispatcherTest { when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); dispatcher.tick(Instant.parse("2026-04-21T09:59:59Z")); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); dispatcher.tick(Instant.parse("2026-04-21T10:00:00Z")); dispatcher.tick(Instant.parse("2026-04-22T10:00:00Z")); dispatcher.tick(Instant.parse("2026-04-23T10:00:00Z")); - verify(invoker).invoke(s, Instant.parse("2026-04-21T10:00:00Z")); - verify(invoker).invoke(s, Instant.parse("2026-04-22T10:00:00Z")); - verify(invoker, times(2)).invoke(eq(s), any()); + verify(invoker).invoke(eq(s), eq(Instant.parse("2026-04-21T10:00:00Z")), any(), anyInt()); + verify(invoker).invoke(eq(s), eq(Instant.parse("2026-04-22T10:00:00Z")), any(), anyInt()); + verify(invoker, times(2)).invoke(eq(s), any(), any(), anyInt()); } @Test @@ -281,7 +281,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T10:00:00Z")); dispatcher.tick(Instant.parse("2026-04-22T10:00:00Z")); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); } @Test @@ -290,7 +290,7 @@ class ScheduleDispatcherTest { when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); assertDoesNotThrow(() -> dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z"))); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); } @Test @@ -301,7 +301,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); } @Test @@ -312,7 +312,7 @@ class ScheduleDispatcherTest { tickEveryTenSeconds("2026-04-21T09:18:00Z", 3); - verify(invoker, times(1)).invoke(eq(s), eq(Instant.parse("2026-04-21T09:17:54Z"))); + verify(invoker, times(1)).invoke(eq(s), eq(Instant.parse("2026-04-21T09:17:54Z")), any(), anyInt()); verifyNoInteractions(sqsService); } @@ -323,7 +323,7 @@ class ScheduleDispatcherTest { tickEveryTenSeconds("2026-04-21T09:18:00Z", 3); - verify(invoker, never()).invoke(any(), any()); + verify(invoker, never()).invoke(any(), any(), any(), anyInt()); verifyNoInteractions(sqsService); } @@ -333,13 +333,35 @@ class ScheduleDispatcherTest { s.getTarget().setRetryPolicy(new RetryPolicy(3600, 1)); when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); doThrow(new RuntimeException("target unavailable")).when(invoker) - .invoke(eq(s), any()); + .invoke(eq(s), any(), any(), anyInt()); dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:21:00Z")); - verify(invoker, times(2)).invoke(eq(s), any()); + verify(invoker, times(2)).invoke(eq(s), any(), any(), anyInt()); + } + + @Test + void eachRetryGetsItsOwnExecutionIdAndAnIncrementingAttemptNumber() { + Schedule s = failingSchedule("attempts", "at(2026-04-21T09:17:54)", new RetryPolicy(3600, 1)); + Instant scheduledAt = Instant.parse("2026-04-21T09:17:54Z"); + + dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); + dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); + + ArgumentCaptor executionIds = ArgumentCaptor.captor(); + ArgumentCaptor attempts = ArgumentCaptor.captor(); + verify(invoker, times(2)).invoke(eq(s), eq(scheduledAt), executionIds.capture(), attempts.capture()); + assertEquals(List.of(1, 2), attempts.getAllValues()); + String firstExecutionId = executionIds.getAllValues().get(0); + String retryExecutionId = executionIds.getAllValues().get(1); + assertTrue(firstExecutionId.matches("[0-9a-f]{16}"), firstExecutionId); + assertTrue(retryExecutionId.matches("[0-9a-f]{16}"), retryExecutionId); + assertNotEquals(firstExecutionId, retryExecutionId); + verify(invoker).materializeRequest(s, scheduledAt, firstExecutionId, 1); + verify(invoker).materializeRequest(s, scheduledAt, retryExecutionId, 2); + assertEquals(retryExecutionId, attribute(deadLetters(1).get(0), "EXECUTION_ID")); } @Test @@ -348,15 +370,15 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:18:59Z")); - verify(invoker, times(1)).invoke(eq(s), any()); + verify(invoker, times(1)).invoke(eq(s), any(), any(), anyInt()); dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); - verify(invoker, times(2)).invoke(eq(s), any()); + verify(invoker, times(2)).invoke(eq(s), any(), any(), anyInt()); dispatcher.tick(Instant.parse("2026-04-21T09:20:59Z")); - verify(invoker, times(2)).invoke(eq(s), any()); + verify(invoker, times(2)).invoke(eq(s), any(), any(), anyInt()); dispatcher.tick(Instant.parse("2026-04-21T09:21:00Z")); - verify(invoker, times(3)).invoke(eq(s), any()); + verify(invoker, times(3)).invoke(eq(s), any(), any(), anyInt()); } @Test @@ -366,7 +388,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); - verify(invoker, times(2)).invoke(eq(s), any()); + verify(invoker, times(2)).invoke(eq(s), any(), any(), anyInt()); verifyNoInteractions(sqsService); } @@ -377,7 +399,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); dispatcher.tick(Instant.parse("2026-04-21T11:18:00Z")); - verify(invoker, times(2)).invoke(eq(s), any()); + verify(invoker, times(2)).invoke(eq(s), any(), any(), anyInt()); Map attributes = deadLetters(1).get(0); assertEquals("MaximumRetryAttempts", attribute(attributes, "EXHAUSTED_RETRY_CONDITION")); assertEquals("1", attribute(attributes, "RETRY_ATTEMPTS")); @@ -391,7 +413,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:21:00Z")); - verify(invoker, times(1)).invoke(eq(s), any()); + verify(invoker, times(1)).invoke(eq(s), any(), any(), anyInt()); Map attributes = deadLetters(1).get(0); assertEquals("MaximumEventAgeInSeconds", attribute(attributes, "EXHAUSTED_RETRY_CONDITION")); assertEquals("0", attribute(attributes, "RETRY_ATTEMPTS")); @@ -401,13 +423,13 @@ class ScheduleDispatcherTest { void sendsExhaustedOccurrenceToDeadLetterQueueWithSchedulerAttributes() { Schedule s = failingSchedule("dead-letter", "at(2026-04-21T09:17:54)", new RetryPolicy(3600, 2)); doThrow(new AwsException("AWS.SimpleQueueService.NonExistentQueue", - "The specified queue does not exist.", 400)).when(invoker).invoke(eq(s), any()); + "The specified queue does not exist.", 400)).when(invoker).invoke(eq(s), any(), any(), anyInt()); dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:21:00Z")); - verify(invoker, times(3)).invoke(eq(s), any()); + verify(invoker, times(3)).invoke(eq(s), any(), any(), anyInt()); Map attributes = deadLetters(1).get(0); assertEquals(9, attributes.size()); assertEquals("AWS.SimpleQueueService.NonExistentQueue", attribute(attributes, "ERROR_CODE")); @@ -431,11 +453,11 @@ class ScheduleDispatcherTest { topic.getTarget().setRetryPolicy(new RetryPolicy(3600, 0)); topic.getTarget().setDeadLetterConfig(new DeadLetterConfig("arn:aws:sns:eu-central-1:000000000000:dead-letter")); when(schedulerService.listAllSchedules()).thenReturn(List.of(fifo, topic)); - doThrow(new RuntimeException("target unavailable")).when(invoker).invoke(any(), any()); + doThrow(new RuntimeException("target unavailable")).when(invoker).invoke(any(), any(), any(), anyInt()); tickEveryTenSeconds("2026-04-21T09:18:00Z", 2); - verify(invoker, times(2)).invoke(any(), any()); + verify(invoker, times(2)).invoke(any(), any(), any(), anyInt()); verifyNoInteractions(sqsService); } @@ -447,7 +469,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:10:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:12:00Z")); - verify(invoker, times(4)).invoke(eq(s), any()); + verify(invoker, times(4)).invoke(eq(s), any(), any(), anyInt()); List> deadLetters = deadLetters(2); assertEquals("2026-04-21T09:05:00Z", attribute(deadLetters.get(0), "SCHEDULED_TIME")); assertEquals("2026-04-21T09:10:00Z", attribute(deadLetters.get(1), "SCHEDULED_TIME")); @@ -459,7 +481,7 @@ class ScheduleDispatcherTest { Schedule s = failingSchedule("at-delete", "at(2026-04-21T09:17:54)", new RetryPolicy(3600, 1)); s.setActionAfterCompletion("DELETE"); s.setAccountId("000000000000"); - when(invoker.invoke(eq(s), any())) + when(invoker.invoke(eq(s), any(), any(), anyInt())) .thenThrow(new RuntimeException("target unavailable")) .thenReturn(TARGET_REQUEST); @@ -495,7 +517,7 @@ class ScheduleDispatcherTest { s.setState("ENABLED"); dispatcher.tick(Instant.parse("2026-04-21T09:18:20Z")); - verify(invoker, times(1)).invoke(eq(s), any()); + verify(invoker, times(1)).invoke(eq(s), any(), any(), anyInt()); verifyNoInteractions(sqsService); } @@ -506,7 +528,7 @@ class ScheduleDispatcherTest { tickEveryTenSeconds("2026-04-21T09:18:00Z", 3); - verify(invoker, times(1)).invoke(eq(s), any()); + verify(invoker, times(1)).invoke(eq(s), any(), any(), anyInt()); verifyNoInteractions(sqsService); } @@ -519,7 +541,7 @@ class ScheduleDispatcherTest { s.setLastModificationDate(Instant.parse("2026-04-21T09:18:05Z")); dispatcher.tick(Instant.parse("2026-04-21T09:18:10Z")); - verify(invoker, times(1)).invoke(eq(s), any()); + verify(invoker, times(1)).invoke(eq(s), any(), any(), anyInt()); verifyNoInteractions(sqsService); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvokerTest.java index a3489e0467..dcf723e0b4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvokerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvokerTest.java @@ -31,9 +31,11 @@ import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertArrayEquals; 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; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; @@ -601,4 +603,81 @@ class ScheduleInvokerTest { verifyNoInteractions(sqsService, lambdaService, snsService, eventBridgeService, ecsService); } + + private static final String CONTEXT_INPUT = "{\"arn\":\"\"," + + "\"time\":\"\",\"id\":\"\"," + + "\"attempt\":}"; + private static final String SCHEDULE_ARN = + "arn:aws:scheduler:us-east-1:000000000000:schedule/default/test-schedule"; + + @Test + void templatedTargetInputHasContextAttributesReplaced() { + Target target = new Target(); + target.setArn("arn:aws:sqs:us-east-1:000000000000:test-queue"); + target.setInput(CONTEXT_INPUT); + + String request = invoker.invoke(scheduleIn("us-east-1", target), + Instant.parse("2026-04-21T09:17:54.678Z"), "d32c5kddcf5bb8c3", 3); + + String expected = "{\"arn\":\"" + SCHEDULE_ARN + "\",\"time\":\"2026-04-21T09:17:54Z\"," + + "\"id\":\"d32c5kddcf5bb8c3\",\"attempt\":3}"; + verify(sqsService).sendMessage(anyString(), eq(expected), eq(0), isNull(), isNull(), eq("us-east-1")); + assertTrue(request.contains("2026-04-21T09:17:54Z"), request); + } + + @Test + void materializedRequestUsesTheSameContextAttributes() { + Target target = new Target(); + target.setArn("arn:aws:lambda:us-east-1:000000000000:function:fn"); + target.setInput(CONTEXT_INPUT); + + String request = invoker.materializeRequest(scheduleIn("us-east-1", target), SCHEDULED_AT, + "abcdef0123456789", 1); + + assertTrue(request.contains("abcdef0123456789"), request); + assertTrue(request.contains("2026-04-21T09:17:54Z"), request); + assertTrue(request.contains("\\\"attempt\\\":1"), request); + assertFalse(request.contains("||" + + "|\"}"); + + invoker.invoke(scheduleIn("us-east-1", target), SCHEDULED_AT, "0123456789abcdef", 2); + + verify(sqsService).sendMessage(eq("http://localhost:4566/000000000000/q"), + eq(SCHEDULE_ARN + "|2026-04-21T09:17:54Z|0123456789abcdef|2"), eq(0), isNull(), isNull(), + argThat(attrs -> attrs == null || attrs.isEmpty()), eq("us-east-1")); + } + + @Test + void inputWithoutContextAttributesIsDeliveredUnchanged() { + Target target = new Target(); + target.setArn("arn:aws:sqs:us-east-1:000000000000:test-queue"); + target.setInput("{\"plain\":\"not a keyword\"}"); + + invoker.invoke(scheduleIn("us-east-1", target), SCHEDULED_AT, "0123456789abcdef", 4); + + verify(sqsService).sendMessage(anyString(), eq("{\"plain\":\"not a keyword\"}"), eq(0), + isNull(), isNull(), eq("us-east-1")); + } + + @Test + void twoArgumentInvokeIsTheFirstAttemptUnderAFreshExecutionId() { + Target target = new Target(); + target.setArn("arn:aws:sqs:us-east-1:000000000000:test-queue"); + target.setInput("/"); + + invoke(target, "us-east-1"); + + ArgumentCaptor body = ArgumentCaptor.forClass(String.class); + verify(sqsService).sendMessage(anyString(), body.capture(), eq(0), isNull(), isNull(), eq("us-east-1")); + assertTrue(body.getValue().matches("[0-9a-f]{16}/1"), body.getValue()); + } } 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 new file mode 100644 index 0000000000..e2d21a8840 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerContextAttributesIntegrationTest.java @@ -0,0 +1,223 @@ +package io.github.hectorvent.floci.services.scheduler; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.scheduler.model.DeadLetterConfig; +import io.github.hectorvent.floci.services.scheduler.model.RetryPolicy; +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.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +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.atExpression; +import static io.github.hectorvent.floci.services.scheduler.SchedulerTestHarness.uniqueName; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The Scheduler context attributes in a target's {@code Input} are replaced on delivery with the + * schedule ARN, the scheduled time, the execution id and the attempt number. + */ +@QuarkusTest +class SchedulerContextAttributesIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String CONTEXT_INPUT = "{\"arn\":\"\"," + + "\"time\":\"\"," + + "\"executionId\":\"\"," + + "\"attempt\":}"; + + @Inject + ScheduleInvoker scheduleInvoker; + + @Inject + SchedulerService schedulerService; + + @Inject + SqsService sqsService; + + @Inject + EmulatorConfig config; + + private final List queueUrls = new ArrayList<>(); + private SchedulerTestHarness harness; + + @BeforeEach + void createHarness() { + harness = new SchedulerTestHarness(schedulerService, scheduleInvoker, sqsService, config); + } + + @AfterEach + void cleanUp() { + harness.cleanUp(); + for (String queueUrl : queueUrls) { + sqsService.deleteQueue(queueUrl, REGION); + } + } + + @Test + void atScheduleDeliversInputWithContextAttributesReplaced() throws Exception { + String queueName = uniqueName("ctx-at-q"); + String queueUrl = createQueue(queueName); + String scheduleName = uniqueName("ctx-at"); + Instant fireAt = Instant.now().plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.SECONDS); + harness.createSchedule(scheduleName, atExpression(fireAt), "ENABLED", queueArn(queueName), CONTEXT_INPUT); + Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION); + + harness.dispatcherFor(scheduleName).tick(fireAt.plusSeconds(5)); + + JsonNode body = singleBody(queueUrl); + assertEquals(schedule.getArn(), body.path("arn").asText()); + assertEquals(fireAt.toString(), body.path("time").asText()); + assertTrue(body.path("time").asText().matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z"), + body.toString()); + assertTrue(body.path("executionId").asText().matches("[0-9a-f]{16}"), body.toString()); + assertEquals(1, body.path("attempt").asInt()); + assertTrue(body.path("attempt").isInt(), body.toString()); + } + + @Test + void rateScheduleDeliversEachOccurrenceWithItsScheduledTime() throws Exception { + String queueName = uniqueName("ctx-rate-q"); + String queueUrl = createQueue(queueName); + 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); + ScheduleDispatcher dispatcher = harness.dispatcherFor(scheduleName); + + dispatcher.tick(firstFire.plusSeconds(1)); + + JsonNode body = singleBody(queueUrl); + assertEquals(schedule.getArn(), body.path("arn").asText()); + assertEquals(firstFire.truncatedTo(ChronoUnit.SECONDS).toString(), body.path("time").asText()); + assertTrue(body.path("executionId").asText().matches("[0-9a-f]{16}"), body.toString()); + assertEquals(1, body.path("attempt").asInt()); + } + + @Test + void retriedDeliveryCarriesTheNextAttemptNumber() throws Exception { + String queueName = uniqueName("ctx-retry-q"); + String scheduleName = uniqueName("ctx-retry"); + Instant fireAt = Instant.now().plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.SECONDS); + // The queue does not exist yet, so the first attempt fails and is retried on a later tick. + harness.createSchedule(scheduleName, atExpression(fireAt), "ENABLED", queueArn(queueName), CONTEXT_INPUT); + ScheduleDispatcher dispatcher = harness.dispatcherFor(scheduleName); + + dispatcher.tick(fireAt.plusSeconds(1)); + String queueUrl = createQueue(queueName); + dispatcher.tick(fireAt.plusSeconds(120)); + + JsonNode body = singleBody(queueUrl); + assertEquals(2, body.path("attempt").asInt()); + assertEquals(fireAt.toString(), body.path("time").asText()); + assertTrue(body.path("executionId").asText().matches("[0-9a-f]{16}"), body.toString()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void deadLetterBodyMatchesLastAttemptContext(boolean expiresByAge) throws Exception { + String queueName = uniqueName("ctx-missing-q"); + String dlqName = uniqueName("ctx-dlq"); + String dlqUrl = createQueue(dlqName); + String scheduleName = uniqueName("ctx-dlq-schedule"); + Instant fireAt = Instant.now().plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.SECONDS); + harness.createSchedule(scheduleName, atExpression(fireAt), "ENABLED", queueArn(queueName), CONTEXT_INPUT); + Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION); + schedule.getTarget().setDeadLetterConfig(new DeadLetterConfig(queueArn(dlqName))); + schedule.getTarget().setRetryPolicy(expiresByAge ? new RetryPolicy(180, 10) : new RetryPolicy(3600, 1)); + ScheduleDispatcher dispatcher = harness.dispatcherFor(scheduleName); + + dispatcher.tick(fireAt.plusSeconds(1)); + dispatcher.tick(fireAt.plusSeconds(61)); + if (expiresByAge) { + dispatcher.tick(fireAt.plusSeconds(181)); + } + + List messages = sqsService.receiveMessage(dlqUrl, 10, 30, 0, REGION); + assertEquals(1, messages.size()); + Message message = messages.get(0); + JsonNode request = MAPPER.readTree(message.getBody()); + JsonNode input = MAPPER.readTree(request.path("MessageBody").asText()); + assertEquals(2, input.path("attempt").asInt()); + assertEquals(schedule.getArn(), input.path("arn").asText()); + assertEquals(fireAt.toString(), input.path("time").asText()); + assertEquals(input.path("executionId").asText(), + message.getMessageAttributes().get("EXECUTION_ID").getStringValue()); + assertEquals(input.path("time").asText(), + message.getMessageAttributes().get("SCHEDULED_TIME").getStringValue()); + assertEquals("1", message.getMessageAttributes().get("RETRY_ATTEMPTS").getStringValue()); + assertEquals(expiresByAge ? "MaximumEventAgeInSeconds" : "MaximumRetryAttempts", + message.getMessageAttributes().get("EXHAUSTED_RETRY_CONDITION").getStringValue()); + } + + @Test + void inputWithoutContextAttributesIsDeliveredUnchanged() { + String queueName = uniqueName("ctx-plain-q"); + String queueUrl = createQueue(queueName); + String scheduleName = uniqueName("ctx-plain"); + Instant fireAt = Instant.now().plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.SECONDS); + String input = "{\"hello\":\"\",\"n\":1}"; + harness.createSchedule(scheduleName, atExpression(fireAt), "ENABLED", queueArn(queueName), input); + + harness.dispatcherFor(scheduleName).tick(fireAt.plusSeconds(1)); + + List messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION); + assertEquals(1, messages.size()); + assertEquals(input, messages.get(0).getBody()); + } + + @Test + void executionIdsDifferBetweenOccurrences() throws Exception { + String queueName = uniqueName("ctx-ids-q"); + String queueUrl = createQueue(queueName); + 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); + ScheduleDispatcher dispatcher = harness.dispatcherFor(scheduleName); + + dispatcher.tick(firstFire.plusSeconds(1)); + dispatcher.tick(firstFire.plusSeconds(62)); + + List messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION); + assertEquals(2, messages.size()); + String first = MAPPER.readTree(messages.get(0).getBody()).path("executionId").asText(); + String second = MAPPER.readTree(messages.get(1).getBody()).path("executionId").asText(); + assertNotEquals(first, second); + } + + private JsonNode singleBody(String queueUrl) throws Exception { + List messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION); + assertEquals(1, messages.size()); + String body = messages.get(0).getBody(); + assertTrue(!body.contains(" scheduleNames = new ArrayList<>(); private final List stateMachineArns = new ArrayList<>(); - private final List testDispatchers = new ArrayList<>(); + private SchedulerTestHarness harness; @BeforeAll static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); } + @BeforeEach + void createHarness() { + harness = new SchedulerTestHarness(schedulerService, scheduleInvoker, sqsService, config); + } + @AfterEach void cleanUp() { - for (String scheduleName : scheduleNames) { - try { - schedulerService.deleteSchedule(scheduleName, null, REGION); - } catch (AwsException expected) { - // A schedule with ActionAfterCompletion=DELETE may already be gone. - } - } + harness.cleanUp(); for (String stateMachineArn : stateMachineArns) { stepFunctionsService.deleteStateMachine(stateMachineArn); } - for (ScheduleDispatcher dispatcher : testDispatchers) { - dispatcher.onStop(null); - } } @Test @@ -88,10 +78,9 @@ class SchedulerStepFunctionsIntegrationTest { String scheduleName = uniqueName("sfn-at"); String input = "{\"order\":{\"id\":42},\"items\":[\"a\",\"b\"]}"; Instant fireAt = Instant.now().plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.SECONDS); - createSchedule(scheduleName, "at(" + SCHEDULE_TIME.format(fireAt) + ")", "ENABLED", - stateMachineArn, input); + harness.createSchedule(scheduleName, atExpression(fireAt), "ENABLED", stateMachineArn, input); - dispatcherFor(scheduleName).tick(fireAt); + harness.dispatcherFor(scheduleName).tick(fireAt); List> executions = listExecutions(stateMachineArn); assertEquals(1, executions.size()); @@ -105,10 +94,10 @@ class SchedulerStepFunctionsIntegrationTest { void recurringScheduleStartsOneExecutionPerOccurrence() { String stateMachineArn = createPassStateMachine(); String scheduleName = uniqueName("sfn-rate"); - createSchedule(scheduleName, "rate(1 minute)", "ENABLED", stateMachineArn, "{\"kind\":\"recurring\"}"); + harness.createSchedule(scheduleName, "rate(1 minute)", "ENABLED", stateMachineArn, "{\"kind\":\"recurring\"}"); Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION); Instant firstFire = schedule.getCreationDate().plus(61, ChronoUnit.SECONDS); - ScheduleDispatcher dispatcher = dispatcherFor(scheduleName); + ScheduleDispatcher dispatcher = harness.dispatcherFor(scheduleName); dispatcher.tick(firstFire); dispatcher.tick(firstFire.plus(61, ChronoUnit.SECONDS)); @@ -121,10 +110,9 @@ class SchedulerStepFunctionsIntegrationTest { String stateMachineArn = createPassStateMachine(); String scheduleName = uniqueName("sfn-disabled"); Instant fireAt = Instant.now().plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.SECONDS); - createSchedule(scheduleName, "at(" + SCHEDULE_TIME.format(fireAt) + ")", "DISABLED", - stateMachineArn, "{\"disabled\":true}"); + harness.createSchedule(scheduleName, atExpression(fireAt), "DISABLED", stateMachineArn, "{\"disabled\":true}"); - dispatcherFor(scheduleName).tick(fireAt); + harness.dispatcherFor(scheduleName).tick(fireAt); assertEquals(0, listExecutions(stateMachineArn).size()); } @@ -133,7 +121,7 @@ class SchedulerStepFunctionsIntegrationTest { void stepFunctionsDeleteScheduleStopsFutureOccurrence() { String targetStateMachineArn = createPassStateMachine(); String scheduleName = uniqueName("sfn-delete"); - createSchedule(scheduleName, "rate(1 minute)", "ENABLED", + harness.createSchedule(scheduleName, "rate(1 minute)", "ENABLED", targetStateMachineArn, "{\"deleted\":false}"); Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION); Instant fireAt = schedule.getCreationDate().plus(61, ChronoUnit.SECONDS); @@ -155,10 +143,7 @@ class SchedulerStepFunctionsIntegrationTest { Response deletion = waitForTerminalExecution(startExecution(deleterStateMachineArn)); assertEquals("SUCCEEDED", deletion.jsonPath().getString("status")); - ScheduleDispatcher dispatcher = new ScheduleDispatcher( - schedulerService, scheduleInvoker, sqsService, config); - testDispatchers.add(dispatcher); - dispatcher.tick(fireAt); + harness.unscopedDispatcher().tick(fireAt); assertEquals(0, listExecutions(targetStateMachineArn).size()); } @@ -196,17 +181,17 @@ class SchedulerStepFunctionsIntegrationTest { } """ .replace("SCHEDULE_NAME", scheduleName) - .replace("SCHEDULE_EXPRESSION", "at(" + SCHEDULE_TIME.format(fireAt) + ")") + .replace("SCHEDULE_EXPRESSION", atExpression(fireAt)) .replace("TARGET_ARN", targetStateMachineArn) .replace("ROLE", ROLE_ARN)); Response creation = waitForTerminalExecution(startExecution(creatorStateMachineArn)); assertEquals("SUCCEEDED", creation.jsonPath().getString("status")); - scheduleNames.add(scheduleName); + harness.trackSchedule(scheduleName); Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION); assertEquals(expectedInput, schedule.getTarget().getInput()); - dispatcherFor(scheduleName).tick(fireAt); + harness.dispatcherFor(scheduleName).tick(fireAt); List> executions = listExecutions(targetStateMachineArn); assertEquals(1, executions.size()); @@ -254,37 +239,6 @@ class SchedulerStepFunctionsIntegrationTest { return response.jsonPath().getString("executionArn"); } - private void createSchedule(String name, String expression, String state, - String targetArn, String input) { - ObjectNode request = MAPPER.createObjectNode(); - request.put("ScheduleExpression", expression); - request.putObject("FlexibleTimeWindow").put("Mode", "OFF"); - request.put("State", state); - ObjectNode target = request.putObject("Target"); - target.put("Arn", targetArn); - target.put("RoleArn", ROLE_ARN); - target.put("Input", input); - - given() - .contentType("application/json") - .body(request.toString()) - .when() - .post("/schedules/" + name) - .then() - .statusCode(200); - scheduleNames.add(name); - } - - private ScheduleDispatcher dispatcherFor(String scheduleName) { - Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION); - SchedulerService scopedSchedulerService = mock(SchedulerService.class); - when(scopedSchedulerService.listAllSchedules()).thenReturn(List.of(schedule)); - ScheduleDispatcher dispatcher = new ScheduleDispatcher( - scopedSchedulerService, scheduleInvoker, sqsService, config); - testDispatchers.add(dispatcher); - return dispatcher; - } - private List> listExecutions(String stateMachineArn) { ObjectNode request = MAPPER.createObjectNode(); request.put("stateMachineArn", stateMachineArn); @@ -318,8 +272,4 @@ class SchedulerStepFunctionsIntegrationTest { response.then().statusCode(200); return response; } - - private static String uniqueName(String prefix) { - return prefix + "-" + UUID.randomUUID().toString().substring(0, 8); - } } 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 new file mode 100644 index 0000000000..46c5b77a8b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerTestHarness.java @@ -0,0 +1,114 @@ +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.core.common.AwsException; +import io.github.hectorvent.floci.services.scheduler.model.Schedule; +import io.github.hectorvent.floci.services.sqs.SqsService; + +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Creates schedules through the REST API and drives them with a dispatcher scoped to one schedule, + * then deletes and stops what it created. An integration test builds one per test and calls + * {@link #cleanUp()} after it. + */ +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 ObjectMapper MAPPER = new ObjectMapper(); + private static final DateTimeFormatter SCHEDULE_TIME = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss").withZone(ZoneOffset.UTC); + + private final SchedulerService schedulerService; + private final ScheduleInvoker scheduleInvoker; + private final SqsService sqsService; + private final EmulatorConfig config; + private final List scheduleNames = new ArrayList<>(); + private final List dispatchers = new ArrayList<>(); + + SchedulerTestHarness(SchedulerService schedulerService, ScheduleInvoker scheduleInvoker, + SqsService sqsService, EmulatorConfig config) { + this.schedulerService = schedulerService; + this.scheduleInvoker = scheduleInvoker; + this.sqsService = sqsService; + this.config = config; + } + + static String uniqueName(String prefix) { + return prefix + "-" + UUID.randomUUID().toString().substring(0, 8); + } + + /** The one-time expression that fires at {@code time}, to the second. */ + static String atExpression(Instant time) { + return "at(" + SCHEDULE_TIME.format(time) + ")"; + } + + void createSchedule(String name, String expression, String state, String targetArn, String input) { + ObjectNode request = MAPPER.createObjectNode(); + request.put("ScheduleExpression", expression); + request.putObject("FlexibleTimeWindow").put("Mode", "OFF"); + request.put("State", state); + ObjectNode target = request.putObject("Target"); + target.put("Arn", targetArn); + target.put("RoleArn", ROLE_ARN); + target.put("Input", input); + + given() + .contentType("application/json") + .body(request.toString()) + .when() + .post("/schedules/" + name) + .then() + .statusCode(200); + scheduleNames.add(name); + } + + /** Registers a schedule created another way, so {@link #cleanUp()} deletes it too. */ + void trackSchedule(String name) { + scheduleNames.add(name); + } + + /** A dispatcher that sees only the named schedule, so other tests' schedules never fire. */ + ScheduleDispatcher dispatcherFor(String scheduleName) { + Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION); + SchedulerService scopedSchedulerService = mock(SchedulerService.class); + when(scopedSchedulerService.listAllSchedules()).thenReturn(List.of(schedule)); + return track(new ScheduleDispatcher(scopedSchedulerService, scheduleInvoker, sqsService, config)); + } + + /** A dispatcher over every schedule the service holds. */ + ScheduleDispatcher unscopedDispatcher() { + return track(new ScheduleDispatcher(schedulerService, scheduleInvoker, sqsService, config)); + } + + void cleanUp() { + for (String scheduleName : scheduleNames) { + try { + schedulerService.deleteSchedule(scheduleName, null, REGION); + } catch (AwsException expected) { + // The test, or ActionAfterCompletion=DELETE, may have deleted it already. + } + } + for (ScheduleDispatcher dispatcher : dispatchers) { + dispatcher.onStop(null); + } + } + + private ScheduleDispatcher track(ScheduleDispatcher dispatcher) { + dispatchers.add(dispatcher); + return dispatcher; + } +}