From b9957dfdbe2355a17d320ef7d1b2066ed8a03b86 Mon Sep 17 00:00:00 2001 From: Victor Sanchez Velasco Date: Wed, 22 Apr 2026 02:42:01 +0200 Subject: [PATCH] feat(scheduler): invoke targets when schedules fire (#551) Adds a background dispatcher that reads persisted schedules and invokes their targets on time, closing the CRUD-only gap called out in PR #260 and documented under "Not Yet Supported". - SchedulerExpressionParser parses at(), rate(), and 6-field cron() with optional ScheduleExpressionTimezone (default UTC). - ScheduleInvoker delivers to SQS, Lambda, SNS, and EventBridge PutEvents, mirroring the EventBridgeInvoker pattern but adapted to Scheduler's Target model (raw Input string, no JSONPath/template). - ScheduleDispatcher is a single-threaded ticker that scans every schedule, gates on State/StartDate/EndDate, fires due schedules, and honours ActionAfterCompletion=DELETE for one-time at() schedules. - FlexibleTimeWindow, RetryPolicy and DeadLetterConfig are stored but not yet honoured; those can be layered on incrementally. Config (floci.services.scheduler): - invocation-enabled (default true) - tick-interval-seconds (default 10) Unit tests cover the parser (at/rate/cron, timezone, validation) and the dispatcher (firing, once-semantics, delete-after-completion, state gating, start/end windows, unsupported expression handling). Closes #550 --- docs/services/scheduler.md | 20 +- .../floci/config/EmulatorConfig.java | 15 ++ .../scheduler/ScheduleDispatcher.java | 197 ++++++++++++++++++ .../services/scheduler/ScheduleInvoker.java | 111 ++++++++++ .../scheduler/SchedulerExpressionParser.java | 146 +++++++++++++ .../services/scheduler/SchedulerService.java | 9 + .../scheduler/ScheduleDispatcherTest.java | 179 ++++++++++++++++ .../SchedulerExpressionParserTest.java | 99 +++++++++ 8 files changed, 775 insertions(+), 1 deletion(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerExpressionParser.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerExpressionParserTest.java diff --git a/docs/services/scheduler.md b/docs/services/scheduler.md index 2ee0dab2a3..784fdf3d4c 100644 --- a/docs/services/scheduler.md +++ b/docs/services/scheduler.md @@ -17,10 +17,28 @@ | `DeleteSchedule` | `DELETE` | `/schedules/{Name}` | Delete a schedule | | `ListSchedules` | `GET` | `/schedules` | List schedules | +## Schedule Invocation + +When `floci.services.scheduler.invocation-enabled` is `true` (the default), a +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`, `weeks`). +- `cron(minute hour day-of-month month day-of-week year)` — AWS 6-field cron; + honors `ScheduleExpressionTimezone`. + +`State=DISABLED` schedules and schedules outside their `StartDate`/`EndDate` +window are skipped. The dispatcher ticks every +`floci.services.scheduler.tick-interval-seconds` (default `10`). + +Supported target types: SQS, Lambda, SNS, EventBridge `PutEvents`. + ## Not Yet Supported - `TagResource` / `UntagResource` / `ListTagsForResource` -- Schedule invocation (triggering targets on schedule) +- `RetryPolicy` and `DeadLetterConfig` on failed invocations (stored but not honored) +- `FlexibleTimeWindow` jitter (fires deterministically at the scheduled time) - `NextToken`-based pagination for List operations ## Examples diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 251498faad..7bb6370a62 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -352,6 +352,21 @@ public interface EmulatorConfig { interface SchedulerServiceConfig { @WithDefault("true") boolean enabled(); + + /** + * Run the background dispatcher that fires schedule targets. Setting this + * to {@code false} keeps the scheduler API CRUD-only (the pre-invocation + * behavior). Invocation is only attempted when the service itself is enabled. + */ + @WithDefault("true") + boolean invocationEnabled(); + + /** + * How often the dispatcher scans for due schedules. Must be >= 1s; + * default 10s is a reasonable trade-off between latency and load for local use. + */ + @WithDefault("10") + long tickIntervalSeconds(); } interface CloudWatchLogsServiceConfig { 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 new file mode 100644 index 0000000000..85c8212d04 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java @@ -0,0 +1,197 @@ +package io.github.hectorvent.floci.services.scheduler; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.scheduler.SchedulerExpressionParser.Kind; +import io.github.hectorvent.floci.services.scheduler.model.Schedule; +import io.quarkus.runtime.ShutdownEvent; +import io.quarkus.runtime.StartupEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * Fires EventBridge Scheduler targets when schedules are due. + * + * A single background thread ticks on a fixed interval, scans all persisted + * schedules, and invokes the target of any schedule whose next fire time has + * passed. Per-schedule "last fire" state is kept in memory (by schedule ARN); + * restarts reset it, matching the emulator's loose durability expectations. + * + * Scope of the initial implementation: + * + */ +@ApplicationScoped +public class ScheduleDispatcher { + + private static final Logger LOG = Logger.getLogger(ScheduleDispatcher.class); + + private final SchedulerService schedulerService; + private final ScheduleInvoker invoker; + private final long tickIntervalSeconds; + private final boolean enabled; + private final ScheduledExecutorService executor; + private final ConcurrentHashMap lastFireByArn = new ConcurrentHashMap<>(); + private final ConcurrentHashMap firedOnceByArn = new ConcurrentHashMap<>(); + + @Inject + public ScheduleDispatcher(SchedulerService schedulerService, + ScheduleInvoker invoker, + EmulatorConfig config) { + this.schedulerService = schedulerService; + this.invoker = invoker; + this.tickIntervalSeconds = config.services().scheduler().tickIntervalSeconds(); + this.enabled = config.services().scheduler().enabled() + && config.services().scheduler().invocationEnabled(); + this.executor = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "scheduler-dispatcher"); + t.setDaemon(true); + return t; + }); + } + + void onStart(@Observes StartupEvent ignored) { + if (!enabled) { + LOG.info("Scheduler dispatcher disabled by configuration"); + return; + } + executor.scheduleAtFixedRate(this::tickSafely, tickIntervalSeconds, tickIntervalSeconds, TimeUnit.SECONDS); + LOG.infov("Scheduler dispatcher started (tick every {0}s)", tickIntervalSeconds); + } + + void onStop(@Observes ShutdownEvent ignored) { + executor.shutdownNow(); + } + + void tickSafely() { + try { + tick(Instant.now()); + } catch (Throwable t) { + LOG.warnv("Scheduler dispatcher tick failed: {0}", t.getMessage()); + } + } + + void tick(Instant now) { + List schedules = schedulerService.listAllSchedules(); + for (Schedule schedule : schedules) { + try { + evaluate(schedule, now); + } catch (Exception e) { + LOG.warnv("Failed to evaluate schedule {0}: {1}", schedule.getArn(), e.getMessage()); + } + } + } + + private void evaluate(Schedule schedule, Instant now) { + if (!"ENABLED".equalsIgnoreCase(schedule.getState())) { + return; + } + if (schedule.getStartDate() != null && now.isBefore(schedule.getStartDate())) { + return; + } + if (schedule.getEndDate() != null && now.isAfter(schedule.getEndDate())) { + return; + } + if (schedule.getScheduleExpression() == null || schedule.getTarget() == null) { + return; + } + + Kind kind; + try { + kind = SchedulerExpressionParser.classify(schedule.getScheduleExpression()); + } catch (IllegalArgumentException e) { + LOG.warnv("Unsupported expression on schedule {0}: {1}", + schedule.getArn(), schedule.getScheduleExpression()); + return; + } + + Instant nextFire = computeNextFire(schedule, kind, now); + if (nextFire == null || now.isBefore(nextFire)) { + return; + } + + fire(schedule); + recordFire(schedule, now); + + if (kind == Kind.AT && isDeleteAfterCompletion(schedule)) { + try { + schedulerService.deleteSchedule(schedule.getName(), schedule.getGroupName(), regionOf(schedule)); + lastFireByArn.remove(schedule.getArn()); + firedOnceByArn.remove(schedule.getArn()); + } catch (Exception e) { + LOG.warnv("Post-completion delete failed for {0}: {1}", schedule.getArn(), e.getMessage()); + } + } + } + + private Instant computeNextFire(Schedule schedule, Kind kind, Instant now) { + String expr = schedule.getScheduleExpression(); + String tz = schedule.getScheduleExpressionTimezone(); + String arn = schedule.getArn(); + + return switch (kind) { + case AT -> { + if (firedOnceByArn.containsKey(arn)) { + yield null; + } + yield SchedulerExpressionParser.parseAt(expr, tz); + } + case RATE -> { + long intervalMs = SchedulerExpressionParser.parseRateMillis(expr); + Instant base = lastFireByArn.getOrDefault(arn, schedule.getCreationDate() != null + ? schedule.getCreationDate() + : now); + yield base.plusMillis(intervalMs); + } + case CRON -> { + Instant base = lastFireByArn.getOrDefault(arn, schedule.getCreationDate() != null + ? schedule.getCreationDate() + : now.minusSeconds(1)); + yield SchedulerExpressionParser.nextCronFire(expr, base, tz); + } + }; + } + + private void fire(Schedule schedule) { + String region = regionOf(schedule); + try { + invoker.invoke(schedule.getTarget(), region); + LOG.infov("Fired schedule {0} in group {1}", schedule.getName(), schedule.getGroupName()); + } catch (Exception e) { + LOG.warnv("Schedule {0} invocation failed: {1}", schedule.getArn(), e.getMessage()); + } + } + + private void recordFire(Schedule schedule, Instant now) { + lastFireByArn.put(schedule.getArn(), now); + firedOnceByArn.put(schedule.getArn(), Boolean.TRUE); + } + + private static boolean isDeleteAfterCompletion(Schedule schedule) { + return "DELETE".equalsIgnoreCase(schedule.getActionAfterCompletion()); + } + + private static String regionOf(Schedule schedule) { + String arn = schedule.getArn(); + if (arn == null) return "us-east-1"; + String[] parts = arn.split(":"); + return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : "us-east-1"; + } +} 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 new file mode 100644 index 0000000000..273c0e3d83 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java @@ -0,0 +1,111 @@ +package io.github.hectorvent.floci.services.scheduler; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.InvocationType; +import io.github.hectorvent.floci.services.scheduler.model.Target; +import io.github.hectorvent.floci.services.sns.SnsService; +import io.github.hectorvent.floci.services.sqs.SqsService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Delivers an EventBridge Scheduler target invocation to the underlying service. + * Supports SQS, Lambda, SNS, and EventBridge PutEvents targets — mirrors the + * subset handled by {@code EventBridgeInvoker} but using Scheduler's + * {@link Target} model (raw {@code input} string, no JSONPath/template). + */ +@ApplicationScoped +public class ScheduleInvoker { + + private static final Logger LOG = Logger.getLogger(ScheduleInvoker.class); + + private final SqsService sqsService; + private final LambdaService lambdaService; + private final SnsService snsService; + private final EventBridgeService eventBridgeService; + private final ObjectMapper objectMapper; + private final String baseUrl; + + @Inject + public ScheduleInvoker(SqsService sqsService, + LambdaService lambdaService, + SnsService snsService, + EventBridgeService eventBridgeService, + ObjectMapper objectMapper, + EmulatorConfig config) { + this.sqsService = sqsService; + this.lambdaService = lambdaService; + this.snsService = snsService; + this.eventBridgeService = eventBridgeService; + this.objectMapper = objectMapper; + this.baseUrl = config.baseUrl(); + } + + public void invoke(Target target, String region) { + if (target == null || target.getArn() == null) { + return; + } + String arn = target.getArn(); + String payload = target.getInput() != null ? target.getInput() : "{}"; + String targetRegion = extractRegion(arn, region); + + if (arn.contains(":sqs:")) { + String queueUrl = AwsArnUtils.arnToQueueUrl(arn, baseUrl); + sqsService.sendMessage(queueUrl, payload, 0); + LOG.debugv("Scheduler delivered to SQS: {0}", arn); + } else if (arn.contains(":lambda:") || arn.contains(":function:")) { + String fnName = arn.substring(arn.lastIndexOf(':') + 1); + lambdaService.invoke(targetRegion, fnName, payload.getBytes(), InvocationType.Event); + LOG.debugv("Scheduler delivered to Lambda: {0}", arn); + } else if (arn.contains(":sns:")) { + snsService.publish(arn, null, payload, "Scheduler", targetRegion); + LOG.debugv("Scheduler delivered to SNS: {0}", arn); + } else if (isEventBridgePutEventsArn(arn)) { + deliverToEventBridge(arn, payload, targetRegion); + LOG.debugv("Scheduler delivered to EventBridge: {0}", arn); + } else { + LOG.warnv("Scheduler: unsupported target ARN type: {0}", arn); + } + } + + private boolean isEventBridgePutEventsArn(String arn) { + return arn.contains(":events:") && arn.contains(":event-bus/"); + } + + private void deliverToEventBridge(String busArn, String payload, String region) { + String busName = busArn.substring(busArn.indexOf(":event-bus/") + ":event-bus/".length()); + Map entry = new HashMap<>(); + entry.put("EventBusName", busName); + entry.put("Source", "aws.scheduler"); + entry.put("DetailType", "Scheduled Event"); + entry.put("Detail", asDetail(payload)); + eventBridgeService.putEvents(List.of(entry), region); + } + + private String asDetail(String payload) { + try { + objectMapper.readTree(payload); + return payload; + } catch (Exception e) { + try { + return objectMapper.writeValueAsString(Map.of("payload", payload)); + } catch (Exception inner) { + return "{}"; + } + } + } + + private static String extractRegion(String arn, String defaultRegion) { + String[] parts = arn.split(":"); + return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : defaultRegion; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerExpressionParser.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerExpressionParser.java new file mode 100644 index 0000000000..46b1404adf --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerExpressionParser.java @@ -0,0 +1,146 @@ +package io.github.hectorvent.floci.services.scheduler; + +import com.cronutils.model.Cron; +import com.cronutils.model.definition.CronDefinition; +import com.cronutils.model.definition.CronDefinitionBuilder; +import com.cronutils.model.time.ExecutionTime; +import com.cronutils.parser.CronParser; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Parses AWS EventBridge Scheduler schedule expressions and computes next fire times. + * + * Supported forms (matches the AWS API): + *
    + *
  • {@code at(YYYY-MM-DDTHH:mm:ss)} — one-time fire at the given instant + * (interpreted in {@code scheduleExpressionTimezone}, default UTC).
  • + *
  • {@code rate(N unit)} — repeating fire every N minutes/hours/days/weeks.
  • + *
  • {@code cron(fields)} — six-field AWS EventBridge cron (minute hour DOM month DOW year).
  • + *
+ */ +public final class SchedulerExpressionParser { + + private static final Pattern AT_PATTERN = Pattern.compile( + "^at\\(\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2})\\s*\\)$", + Pattern.CASE_INSENSITIVE); + + private static final Pattern RATE_PATTERN = Pattern.compile( + "^rate\\(\\s*(\\d+)\\s+(minutes?|hours?|days?|weeks?)\\s*\\)$", + Pattern.CASE_INSENSITIVE); + + private static final Pattern CRON_PATTERN = Pattern.compile( + "^cron\\((.+)\\)$", + Pattern.CASE_INSENSITIVE); + + private static final DateTimeFormatter AT_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); + + private static final CronParser CRON_PARSER; + + static { + CronDefinition definition = CronDefinitionBuilder.defineCron() + .withSeconds().and() + .withMinutes().and() + .withHours().and() + .withDayOfMonth().supportsHash().supportsL().supportsW().supportsQuestionMark().and() + .withMonth().and() + .withDayOfWeek().supportsHash().supportsL().supportsW().supportsQuestionMark().and() + .withYear().optional().and() + .instance(); + CRON_PARSER = new CronParser(definition); + } + + public enum Kind { AT, RATE, CRON } + + private SchedulerExpressionParser() {} + + public static Kind classify(String expression) { + if (expression == null) { + throw new IllegalArgumentException("Schedule expression is null"); + } + String trimmed = expression.trim(); + if (AT_PATTERN.matcher(trimmed).matches()) return Kind.AT; + if (RATE_PATTERN.matcher(trimmed).matches()) return Kind.RATE; + if (CRON_PATTERN.matcher(trimmed).matches()) return Kind.CRON; + throw new IllegalArgumentException("Unsupported schedule expression: " + expression); + } + + /** + * Parses an {@code at(...)} expression and returns the fire instant. + * The timestamp is interpreted in {@code timezone} (default UTC). + */ + public static Instant parseAt(String expression, String timezone) { + Matcher m = AT_PATTERN.matcher(expression.trim()); + if (!m.matches()) { + throw new IllegalArgumentException("Not a valid at() expression: " + expression); + } + LocalDateTime local = LocalDateTime.parse(m.group(1), AT_FORMATTER); + ZoneId zone = resolveZone(timezone); + return local.atZone(zone).toInstant(); + } + + /** + * Parses a {@code rate(...)} expression and returns the interval in milliseconds. + */ + public static long parseRateMillis(String expression) { + Matcher m = RATE_PATTERN.matcher(expression.trim()); + if (!m.matches()) { + throw new IllegalArgumentException("Not a valid rate() expression: " + expression); + } + int value = Integer.parseInt(m.group(1)); + if (value < 1) { + throw new IllegalArgumentException("Rate value must be >= 1, got: " + value); + } + String unit = m.group(2).toLowerCase(); + return switch (unit) { + case "minute", "minutes" -> value * 60_000L; + case "hour", "hours" -> value * 3_600_000L; + case "day", "days" -> value * 86_400_000L; + case "week", "weeks" -> value * 604_800_000L; + default -> throw new IllegalArgumentException("Unknown rate unit: " + unit); + }; + } + + /** + * Returns the next fire instant at or after {@code from} for a cron expression + * evaluated in {@code timezone} (default UTC). + */ + public static Instant nextCronFire(String expression, Instant from, String timezone) { + Matcher m = CRON_PATTERN.matcher(expression.trim()); + if (!m.matches()) { + throw new IllegalArgumentException("Not a valid cron() expression: " + expression); + } + String cronFields = m.group(1).trim(); + String[] fields = cronFields.split("\\s+"); + if (fields.length != 6) { + throw new IllegalArgumentException( + "AWS EventBridge cron expressions require 6 fields (minute hour day-of-month month day-of-week year), got " + + fields.length + ": " + cronFields); + } + Cron cron = CRON_PARSER.parse("0 " + cronFields); + cron.validate(); + ExecutionTime exec = ExecutionTime.forCron(cron); + + ZoneId zone = resolveZone(timezone); + ZonedDateTime zdt = from.atZone(zone); + return exec.nextExecution(zdt) + .map(ZonedDateTime::toInstant) + .orElseThrow(() -> new IllegalStateException( + "No next fire time for cron expression: " + expression)); + } + + private static ZoneId resolveZone(String timezone) { + if (timezone == null || timezone.isBlank()) { + return ZoneOffset.UTC; + } + return ZoneId.of(timezone); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java index 3b9607570f..f78bf25b9c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java @@ -231,6 +231,15 @@ public class SchedulerService { LOG.infov("Deleted schedule: {0} in group {1}", name, effectiveGroup); } + /** + * Return every persisted schedule across all regions and groups. Used by + * {@link ScheduleDispatcher} to evaluate due schedules; other callers should + * prefer {@link #listSchedules}. + */ + public List listAllSchedules() { + return scheduleStore.scan(k -> k.startsWith("schedule:")); + } + public List listSchedules(String groupName, String namePrefix, String state, String region) { String storagePrefix; if (groupName != null && !groupName.isBlank()) { 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 new file mode 100644 index 0000000000..e38df056bd --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java @@ -0,0 +1,179 @@ +package io.github.hectorvent.floci.services.scheduler; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.scheduler.model.Schedule; +import io.github.hectorvent.floci.services.scheduler.model.Target; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +class ScheduleDispatcherTest { + + private static final String ARN_PREFIX = "arn:aws:scheduler:eu-central-1:000000000000:schedule/default/"; + private static final String SQS_TARGET_ARN = "arn:aws:sqs:eu-central-1:000000000000:test-queue"; + + private SchedulerService schedulerService; + private ScheduleInvoker invoker; + private ScheduleDispatcher dispatcher; + + @BeforeEach + void setUp() { + schedulerService = mock(SchedulerService.class); + invoker = mock(ScheduleInvoker.class); + + EmulatorConfig.SchedulerServiceConfig schedulerCfg = mock(EmulatorConfig.SchedulerServiceConfig.class); + when(schedulerCfg.enabled()).thenReturn(true); + when(schedulerCfg.invocationEnabled()).thenReturn(true); + when(schedulerCfg.tickIntervalSeconds()).thenReturn(10L); + EmulatorConfig.ServicesConfig servicesCfg = mock(EmulatorConfig.ServicesConfig.class); + when(servicesCfg.scheduler()).thenReturn(schedulerCfg); + EmulatorConfig config = mock(EmulatorConfig.class); + when(config.services()).thenReturn(servicesCfg); + + dispatcher = new ScheduleDispatcher(schedulerService, invoker, config); + } + + private Schedule newSchedule(String name, String expression, String state) { + Schedule s = new Schedule(); + s.setName(name); + s.setGroupName("default"); + s.setArn(ARN_PREFIX + name); + s.setState(state); + s.setScheduleExpression(expression); + Target target = new Target(); + target.setArn(SQS_TARGET_ARN); + target.setRoleArn("arn:aws:iam::000000000000:role/test"); + target.setInput("{\"hello\":\"world\"}"); + s.setTarget(target); + s.setCreationDate(Instant.parse("2026-04-21T09:00:00Z")); + return s; + } + + @Test + void firesAtScheduleWhenDue() { + Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED"); + when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); + + dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); + + verify(invoker, times(1)).invoke(s.getTarget(), "eu-central-1"); + } + + @Test + void skipsAtScheduleBeforeFireTime() { + Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED"); + when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); + + dispatcher.tick(Instant.parse("2026-04-21T09:17:00Z")); + + verify(invoker, never()).invoke(any(), anyString()); + } + + @Test + void firesAtOnlyOncePerSchedule() { + Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED"); + when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); + + 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:20:00Z")); + + verify(invoker, times(1)).invoke(eq(s.getTarget()), anyString()); + } + + @Test + void deletesAtScheduleWhenActionAfterCompletionIsDelete() { + Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED"); + s.setActionAfterCompletion("DELETE"); + when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); + + dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); + + verify(schedulerService, times(1)).deleteSchedule("at1", "default", "eu-central-1"); + } + + @Test + void leavesAtScheduleInPlaceWhenActionAfterCompletionIsNotDelete() { + Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED"); + s.setActionAfterCompletion("NONE"); + when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); + + dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); + + verify(schedulerService, never()).deleteSchedule(anyString(), anyString(), anyString()); + } + + @Test + void skipsDisabledSchedules() { + Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "DISABLED"); + when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); + + dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); + + verify(invoker, never()).invoke(any(), anyString()); + } + + @Test + void skipsBeforeStartDate() { + Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED"); + s.setStartDate(Instant.parse("2026-04-22T00:00:00Z")); + when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); + + dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); + + verify(invoker, never()).invoke(any(), anyString()); + } + + @Test + void skipsAfterEndDate() { + Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED"); + s.setEndDate(Instant.parse("2026-04-21T09:17:00Z")); + when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); + + dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); + + verify(invoker, never()).invoke(any(), anyString()); + } + + @Test + void ratesFireOnceIntervalHasPassed() { + 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(), anyString()); + + dispatcher.tick(Instant.parse("2026-04-21T09:06:00Z")); + verify(invoker, times(1)).invoke(eq(s.getTarget()), anyString()); + + dispatcher.tick(Instant.parse("2026-04-21T09:11:01Z")); + verify(invoker, times(2)).invoke(eq(s.getTarget()), anyString()); + } + + @Test + void unsupportedExpressionIsSkippedNotThrown() { + Schedule s = newSchedule("weird", "every 5 minutes", "ENABLED"); + when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); + + assertDoesNotThrow(() -> dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z"))); + verify(invoker, never()).invoke(any(), anyString()); + } + + @Test + void missingTargetIsSkipped() { + Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED"); + s.setTarget(null); + when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); + + dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); + + verify(invoker, never()).invoke(any(), anyString()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerExpressionParserTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerExpressionParserTest.java new file mode 100644 index 0000000000..8439fa29a8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerExpressionParserTest.java @@ -0,0 +1,99 @@ +package io.github.hectorvent.floci.services.scheduler; + +import io.github.hectorvent.floci.services.scheduler.SchedulerExpressionParser.Kind; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; + +import static org.junit.jupiter.api.Assertions.*; + +class SchedulerExpressionParserTest { + + @Test + void classifyAtExpression() { + assertEquals(Kind.AT, SchedulerExpressionParser.classify("at(2026-04-21T09:17:54)")); + assertEquals(Kind.AT, SchedulerExpressionParser.classify("AT(2026-04-21T09:17:54)")); + } + + @Test + void classifyRateExpression() { + assertEquals(Kind.RATE, SchedulerExpressionParser.classify("rate(5 minutes)")); + assertEquals(Kind.RATE, SchedulerExpressionParser.classify("rate(1 hour)")); + } + + @Test + void classifyCronExpression() { + assertEquals(Kind.CRON, SchedulerExpressionParser.classify("cron(0 10 * * ? *)")); + } + + @Test + void classifyRejectsUnknown() { + assertThrows(IllegalArgumentException.class, + () -> SchedulerExpressionParser.classify("every 5 minutes")); + assertThrows(IllegalArgumentException.class, + () -> SchedulerExpressionParser.classify(null)); + } + + @Test + void parseAtInUtc() { + Instant expected = ZonedDateTime.of(2026, 4, 21, 9, 17, 54, 0, ZoneOffset.UTC).toInstant(); + assertEquals(expected, SchedulerExpressionParser.parseAt("at(2026-04-21T09:17:54)", null)); + assertEquals(expected, SchedulerExpressionParser.parseAt("at(2026-04-21T09:17:54)", "UTC")); + } + + @Test + void parseAtInTimezoneShiftsInstant() { + Instant utc = SchedulerExpressionParser.parseAt("at(2026-04-21T09:17:54)", "UTC"); + Instant berlin = SchedulerExpressionParser.parseAt("at(2026-04-21T09:17:54)", "Europe/Berlin"); + assertTrue(berlin.isBefore(utc), + "09:17 Europe/Berlin should be an earlier instant than 09:17 UTC"); + } + + @Test + void parseAtRejectsMalformed() { + assertThrows(IllegalArgumentException.class, + () -> SchedulerExpressionParser.parseAt("at(not-a-date)", null)); + } + + @Test + void parseRateMillis() { + assertEquals(300_000L, SchedulerExpressionParser.parseRateMillis("rate(5 minutes)")); + assertEquals(3_600_000L, SchedulerExpressionParser.parseRateMillis("rate(1 hour)")); + assertEquals(86_400_000L, SchedulerExpressionParser.parseRateMillis("rate(1 day)")); + assertEquals(604_800_000L, SchedulerExpressionParser.parseRateMillis("rate(1 week)")); + } + + @Test + void parseRateRejectsZero() { + assertThrows(IllegalArgumentException.class, + () -> SchedulerExpressionParser.parseRateMillis("rate(0 minutes)")); + } + + @Test + void nextCronFireComputesFutureInstant() { + Instant from = ZonedDateTime.of(2026, 4, 21, 9, 0, 0, 0, ZoneOffset.UTC).toInstant(); + Instant next = SchedulerExpressionParser.nextCronFire("cron(30 10 * * ? *)", from, null); + ZonedDateTime asUtc = next.atZone(ZoneOffset.UTC); + assertEquals(10, asUtc.getHour()); + assertEquals(30, asUtc.getMinute()); + assertTrue(next.isAfter(from)); + } + + @Test + void nextCronFireRespectsTimezone() { + Instant from = ZonedDateTime.of(2026, 4, 21, 0, 0, 0, 0, ZoneOffset.UTC).toInstant(); + Instant nextUtc = SchedulerExpressionParser.nextCronFire("cron(0 10 * * ? *)", from, "UTC"); + Instant nextBerlin = SchedulerExpressionParser.nextCronFire("cron(0 10 * * ? *)", from, "Europe/Berlin"); + assertNotEquals(nextUtc, nextBerlin, + "10:00 UTC and 10:00 Europe/Berlin are different absolute instants"); + } + + @Test + void nextCronFireRejectsWrongFieldCount() { + Instant from = Instant.now(); + assertThrows(IllegalArgumentException.class, + () -> SchedulerExpressionParser.nextCronFire("cron(0 10 * * *)", from, null)); + } +}