feat: add scheduled rules support for EventBridge Rules (#217)

This commit is contained in:
Mahamed-Belkheir authored and GitHub committed 2026-04-05 20:08:52 -05:00
1 parent b973b7060d
commit e8c6440489
10 files changed
+911 -95

No files matched your search

@@ -0,0 +1,65 @@
package io.github.hectorvent.floci.services.eventbridge;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
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;
@ApplicationScoped
public class EventBridgeInvoker {
private static final Logger LOG = Logger.getLogger(EventBridgeInvoker.class);
private final LambdaService lambdaService;
private final SqsService sqsService;
private final SnsService snsService;
private final String baseUrl;
@Inject
public EventBridgeInvoker(LambdaService lambdaService,
SqsService sqsService,
SnsService snsService,
EmulatorConfig config) {
this.lambdaService = lambdaService;
this.sqsService = sqsService;
this.snsService = snsService;
this.baseUrl = config.baseUrl();
}
public void invokeTarget(Target target, String eventJson, String region) {
String arn = target.getArn();
String payload = target.getInput() != null ? target.getInput() : eventJson;
try {
if (arn.contains(":lambda:") || arn.contains(":function:")) {
String fnName = arn.substring(arn.lastIndexOf(':') + 1);
String fnRegion = extractRegionFromArn(arn, region);
lambdaService.invoke(fnRegion, fnName, payload.getBytes(), InvocationType.Event);
LOG.debugv("EventBridge delivered to Lambda: {0}", arn);
} else if (arn.contains(":sqs:")) {
String queueUrl = AwsArnUtils.arnToQueueUrl(arn, baseUrl);
sqsService.sendMessage(queueUrl, payload, 0);
LOG.debugv("EventBridge delivered to SQS: {0}", arn);
} else if (arn.contains(":sns:")) {
String topicRegion = extractRegionFromArn(arn, region);
snsService.publish(arn, null, payload, "EventBridge", topicRegion);
LOG.debugv("EventBridge delivered to SNS: {0}", arn);
} else {
LOG.warnv("EventBridge: unsupported target ARN type: {0}", arn);
}
} catch (Exception e) {
LOG.warnv("EventBridge failed to deliver to target {0}: {1}", arn, e.getMessage());
}
}
private static String extractRegionFromArn(String arn, String defaultRegion) {
String[] parts = arn.split(":");
return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : defaultRegion;
}
}
@@ -2,7 +2,6 @@ package io.github.hectorvent.floci.services.eventbridge;
import com.fasterxml.jackson.databind.node.ArrayNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -11,14 +10,11 @@ import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
import io.github.hectorvent.floci.services.eventbridge.model.Rule;
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -39,20 +35,17 @@ public class EventBridgeService {
private final StorageBackend<String, Rule> ruleStore;
private final StorageBackend<String, List<Target>> targetStore;
private final RegionResolver regionResolver;
private final LambdaService lambdaService;
private final SqsService sqsService;
private final SnsService snsService;
private final ObjectMapper objectMapper;
private final String baseUrl;
private final RuleScheduler ruleScheduler;
private final EventBridgeInvoker invoker;
@Inject
public EventBridgeService(StorageFactory storageFactory,
EmulatorConfig config,
RegionResolver regionResolver,
LambdaService lambdaService,
SqsService sqsService,
SnsService snsService,
ObjectMapper objectMapper) {
ObjectMapper objectMapper,
RuleScheduler ruleScheduler,
EventBridgeInvoker invoker) {
this(
storageFactory.create("eventbridge", "eventbridge-buses.json",
new TypeReference<Map<String, EventBus>>() {}),
@@ -60,7 +53,7 @@ public class EventBridgeService {
new TypeReference<Map<String, Rule>>() {}),
storageFactory.create("eventbridge", "eventbridge-targets.json",
new TypeReference<Map<String, List<Target>>>() {}),
regionResolver, lambdaService, sqsService, snsService, objectMapper, config.effectiveBaseUrl()
regionResolver, objectMapper, ruleScheduler, invoker
);
}
@@ -68,31 +61,26 @@ public class EventBridgeService {
StorageBackend<String, Rule> ruleStore,
StorageBackend<String, List<Target>> targetStore,
RegionResolver regionResolver,
LambdaService lambdaService,
SqsService sqsService,
SnsService snsService,
ObjectMapper objectMapper) {
this(busStore, ruleStore, targetStore, regionResolver, lambdaService, sqsService, snsService, objectMapper, "http://localhost:4566");
}
EventBridgeService(StorageBackend<String, EventBus> busStore,
StorageBackend<String, Rule> ruleStore,
StorageBackend<String, List<Target>> targetStore,
RegionResolver regionResolver,
LambdaService lambdaService,
SqsService sqsService,
SnsService snsService,
ObjectMapper objectMapper,
String baseUrl) {
RuleScheduler ruleScheduler,
EventBridgeInvoker invoker) {
this.busStore = busStore;
this.ruleStore = ruleStore;
this.targetStore = targetStore;
this.regionResolver = regionResolver;
this.lambdaService = lambdaService;
this.sqsService = sqsService;
this.snsService = snsService;
this.objectMapper = objectMapper;
this.baseUrl = baseUrl;
this.ruleScheduler = ruleScheduler;
this.invoker = invoker;
}
@PostConstruct
void init() {
if (ruleScheduler != null) {
ruleStore.keys().forEach(key -> {
ruleStore.get(key).ifPresent(this::startSchedulerIfNeeded);
});
LOG.infov("EventBridge initialized, {0} scheduler(s) restored", ruleScheduler.getActiveSchedulerCount());
}
}
// ──────────────────────────── Event Buses ────────────────────────────
@@ -186,7 +174,7 @@ public class EventBridgeService {
String key = ruleKey(region, effectiveBus, name);
Rule rule = ruleStore.get(key).orElse(new Rule());
rule.setName(name);
rule.setArn(regionResolver.buildArn("events", region, "rule/" + effectiveBus + "/" + name));
rule.setArn(buildRuleArn(region, effectiveBus, name));
rule.setEventBusName(effectiveBus);
rule.setEventPattern(eventPattern);
rule.setScheduleExpression(scheduleExpression);
@@ -200,6 +188,12 @@ public class EventBridgeService {
rule.setCreatedAt(Instant.now());
}
ruleStore.put(key, rule);
if (ruleScheduler != null) {
ruleScheduler.stopScheduler(rule.getArn());
startSchedulerIfNeeded(rule);
}
LOG.infov("Put rule: {0} on bus {1}", name, effectiveBus);
return rule;
}
@@ -207,7 +201,7 @@ public class EventBridgeService {
public void deleteRule(String name, String busName, String region) {
String effectiveBus = resolvedBusName(busName);
String key = ruleKey(region, effectiveBus, name);
ruleStore.get(key)
Rule rule = ruleStore.get(key)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Rule not found: " + name, 404));
List<Target> targets = targetStore.get(key).orElse(List.of());
@@ -215,6 +209,11 @@ public class EventBridgeService {
throw new AwsException("ValidationException",
"Rule still has targets. Remove targets before deleting the rule.", 400);
}
if (ruleScheduler != null) {
ruleScheduler.stopScheduler(rule.getArn());
}
ruleStore.delete(key);
LOG.infov("Deleted rule: {0}", name);
}
@@ -245,6 +244,7 @@ public class EventBridgeService {
"Rule not found: " + name, 404));
rule.setState(RuleState.ENABLED);
ruleStore.put(key, rule);
startSchedulerIfNeeded(rule);
}
public void disableRule(String name, String busName, String region) {
@@ -255,6 +255,10 @@ public class EventBridgeService {
"Rule not found: " + name, 404));
rule.setState(RuleState.DISABLED);
ruleStore.put(key, rule);
if (ruleScheduler != null) {
ruleScheduler.stopScheduler(rule.getArn());
}
}
// ──────────────────────────── Targets ────────────────────────────
@@ -336,7 +340,7 @@ public class EventBridgeService {
List<Target> targets = targetStore.get(ruleKey).orElse(List.of());
String eventJson = buildEventEnvelope(entry, effectiveBus, eventId);
for (Target target : targets) {
invokeTarget(target, eventJson, region);
invoker.invokeTarget(target, eventJson, region);
}
}
}
@@ -420,31 +424,6 @@ public class EventBridgeService {
// ──────────────────────────── Target Routing ────────────────────────────
private void invokeTarget(Target target, String eventJson, String region) {
String arn = target.getArn();
String payload = target.getInput() != null ? target.getInput() : eventJson;
try {
if (arn.contains(":lambda:") || arn.contains(":function:")) {
String fnName = arn.substring(arn.lastIndexOf(':') + 1);
String fnRegion = extractRegionFromArn(arn, region);
lambdaService.invoke(fnRegion, fnName, payload.getBytes(), InvocationType.Event);
LOG.debugv("EventBridge delivered to Lambda: {0}", arn);
} else if (arn.contains(":sqs:")) {
String queueUrl = sqsArnToUrl(arn);
sqsService.sendMessage(queueUrl, payload, 0);
LOG.debugv("EventBridge delivered to SQS: {0}", arn);
} else if (arn.contains(":sns:")) {
String topicRegion = extractRegionFromArn(arn, region);
snsService.publish(arn, null, payload, "EventBridge", topicRegion);
LOG.debugv("EventBridge delivered to SNS: {0}", arn);
} else {
LOG.warnv("EventBridge: unsupported target ARN type: {0}", arn);
}
} catch (Exception e) {
LOG.warnv("EventBridge failed to deliver to target {0}: {1}", arn, e.getMessage());
}
}
private String buildEventEnvelope(Map<String, Object> entry, String busName, String eventId) {
try {
String source = (String) entry.getOrDefault("Source", "");
@@ -502,17 +481,30 @@ public class EventBridgeService {
return ruleKeyPrefix(region, busName) + ruleName;
}
private static String extractRegionFromArn(String arn, String defaultRegion) {
String[] parts = arn.split(":");
return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : defaultRegion;
private String buildRuleArn(String region, String busName, String ruleName) {
if ("default".equals(busName)) {
return regionResolver.buildArn("events", region, "rule/" + ruleName);
}
return regionResolver.buildArn("events", region, "rule/" + busName + "/" + ruleName);
}
private String sqsArnToUrl(String arn) {
String[] parts = arn.split(":");
if (parts.length < 6) {
throw new IllegalArgumentException("Invalid SQS ARN: " + arn);
private void startSchedulerIfNeeded(Rule rule) {
if (ruleScheduler != null
&& rule.getState() == RuleState.ENABLED
&& rule.getScheduleExpression() != null
&& !rule.getScheduleExpression().isBlank()) {
String region = rule.getRegion() != null ? rule.getRegion() : "us-east-1";
String key = ruleKey(region, rule.getEventBusName(), rule.getName());
ruleScheduler.startScheduler(
rule.getArn(),
rule.getScheduleExpression(),
() -> {
Rule r = ruleStore.get(key).orElse(null);
List<Target> t = targetStore.get(key).orElse(List.of());
return new RuleScheduler.ScheduleData(r, t);
}
);
}
return AwsArnUtils.arnToQueueUrl(arn, baseUrl);
}
}
@@ -0,0 +1,176 @@
package io.github.hectorvent.floci.services.eventbridge;
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.eventbridge.model.Rule;
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.vertx.core.Vertx;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
@ApplicationScoped
public class RuleScheduler {
private static final Logger LOG = Logger.getLogger(RuleScheduler.class);
private final Vertx vertx;
private final ObjectMapper objectMapper;
private final String accountId;
private final EventBridgeInvoker invoker;
private final ConcurrentHashMap<String, ScheduleContext> scheduleContexts = new ConcurrentHashMap<>();
@Inject
public RuleScheduler(Vertx vertx,
EmulatorConfig config,
ObjectMapper objectMapper,
EventBridgeInvoker invoker) {
this.vertx = vertx;
this.objectMapper = objectMapper;
this.accountId = config.defaultAccountId();
this.invoker = invoker;
}
@PreDestroy
void shutdown() {
scheduleContexts.values().forEach(ctx -> vertx.cancelTimer(ctx.timerId));
scheduleContexts.clear();
LOG.info("RuleScheduler shut down, all timers cancelled");
}
public void startScheduler(String ruleArn, String scheduleExpr,
Supplier<ScheduleData> dataSupplier) {
if (scheduleContexts.containsKey(ruleArn)) {
return;
}
if (scheduleExpr == null || scheduleExpr.isBlank()) {
LOG.warnv("Cannot start scheduler for rule {0}: no schedule expression", ruleArn);
return;
}
try {
if (ScheduleExpressionParser.isRateExpression(scheduleExpr)) {
startRateScheduler(ruleArn, scheduleExpr, dataSupplier);
} else if (ScheduleExpressionParser.isCronExpression(scheduleExpr)) {
scheduleCronFire(ruleArn, scheduleExpr, dataSupplier);
} else {
LOG.warnv("Unknown schedule expression format for rule {0}: {1}", ruleArn, scheduleExpr);
}
} catch (Exception e) {
LOG.warnv("Failed to parse schedule expression for rule {0}: {1}", ruleArn, e.getMessage());
}
}
private void startRateScheduler(String ruleArn, String scheduleExpr,
Supplier<ScheduleData> dataSupplier) {
long intervalMs = ScheduleExpressionParser.parseRateToMillis(scheduleExpr);
tick(dataSupplier);
long timerId = vertx.setPeriodic(intervalMs, id -> tick(dataSupplier));
scheduleContexts.put(ruleArn, new ScheduleContext(timerId, scheduleExpr));
LOG.debugv("Started rate scheduler for rule {0} with interval {1}ms", ruleArn, intervalMs);
}
private void scheduleCronFire(String ruleArn, String scheduleExpr,
Supplier<ScheduleData> dataSupplier) {
long delayMs;
try {
delayMs = ScheduleExpressionParser.millisUntilNextFire(scheduleExpr, ZonedDateTime.now());
} catch (Exception e) {
LOG.warnv("Failed to compute next fire time for rule {0}: {1}", ruleArn, e.getMessage());
return;
}
long timerId = vertx.setTimer(delayMs, id -> {
tick(dataSupplier);
scheduleContexts.remove(ruleArn);
scheduleCronFire(ruleArn, scheduleExpr, dataSupplier);
});
scheduleContexts.put(ruleArn, new ScheduleContext(timerId, scheduleExpr));
LOG.debugv("Scheduled cron fire for rule {0} in {1}ms", ruleArn, delayMs);
}
public void stopScheduler(String ruleArn) {
ScheduleContext ctx = scheduleContexts.remove(ruleArn);
if (ctx != null) {
vertx.cancelTimer(ctx.timerId);
LOG.debugv("Stopped scheduler for rule {0}", ruleArn);
}
}
private void tick(Supplier<ScheduleData> dataSupplier) {
ScheduleData data = dataSupplier.get();
if (data == null || data.rule == null) {
LOG.debugv("Rule no longer exists, stopping scheduler");
stopScheduler(data != null && data.rule != null ? data.rule.getArn() : null);
return;
}
if (data.rule.getState() != RuleState.ENABLED) {
LOG.debugv("Rule {0} is disabled, skipping tick", data.rule.getName());
return;
}
if (data.targets.isEmpty()) {
LOG.debugv("Rule {0} has no targets, skipping tick", data.rule.getName());
return;
}
String region = data.rule.getRegion() != null ? data.rule.getRegion() : "us-east-1";
String eventJson = buildScheduledEvent(data.rule, region);
LOG.debugv("Rule {0} firing scheduled event", data.rule.getName());
for (Target target : data.targets) {
try {
invoker.invokeTarget(target, eventJson, region);
} catch (Exception e) {
LOG.warnv("Failed to invoke target {0} for rule {1}: {2}",
target.getId(), data.rule.getName(), e.getMessage());
}
}
}
private String buildScheduledEvent(Rule rule, String region) {
try {
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
ObjectNode node = objectMapper.createObjectNode();
node.put("version", "0");
node.put("id", UUID.randomUUID().toString());
node.put("source", "aws.events");
node.put("detail-type", "Scheduled Event");
node.put("account", accountId);
node.put("time", now.toInstant().toString());
node.put("region", region);
node.putArray("resources").add(rule.getArn());
node.putObject("detail");
return objectMapper.writeValueAsString(node);
} catch (Exception e) {
LOG.warnv("Failed to build scheduled event: {0}", e.getMessage());
return "{\"version\":\"0\",\"source\":\"aws.events\",\"detail-type\":\"Scheduled Event\",\"detail\":{}}";
}
}
public boolean isRunning(String ruleArn) {
return scheduleContexts.containsKey(ruleArn);
}
public int getActiveSchedulerCount() {
return scheduleContexts.size();
}
public record ScheduleData(Rule rule, List<Target> targets) {}
private record ScheduleContext(long timerId, String scheduleExpr) {}
}
@@ -0,0 +1,109 @@
package io.github.hectorvent.floci.services.eventbridge;
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.ZonedDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class ScheduleExpressionParser {
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 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);
}
private ScheduleExpressionParser() {}
public static boolean isRateExpression(String expression) {
return expression != null && RATE_PATTERN.matcher(expression.trim()).matches();
}
public static boolean isCronExpression(String expression) {
return expression != null && CRON_PATTERN.matcher(expression.trim()).matches();
}
public static long parseRateToMillis(String expression) {
if (expression == null || expression.isBlank()) {
throw new IllegalArgumentException("Schedule expression cannot be null or blank");
}
Matcher rateMatcher = RATE_PATTERN.matcher(expression.trim());
if (!rateMatcher.matches()) {
throw new IllegalArgumentException("Not a valid rate expression: " + expression);
}
int value = Integer.parseInt(rateMatcher.group(1));
if (value < 1) {
throw new IllegalArgumentException("Rate value must be >= 1, got: " + value);
}
String unit = rateMatcher.group(2).toLowerCase();
return switch (unit) {
case "minute", "minutes" -> value * 60 * 1000L;
case "hour", "hours" -> value * 60 * 60 * 1000L;
case "day", "days" -> value * 24 * 60 * 60 * 1000L;
case "week", "weeks" -> value * 7 * 24 * 60 * 60 * 1000L;
default -> throw new IllegalArgumentException("Unknown rate unit: " + unit);
};
}
public static ZonedDateTime getNextFireTime(String expression, ZonedDateTime from) {
if (expression == null || expression.isBlank()) {
throw new IllegalArgumentException("Schedule expression cannot be null or blank");
}
Matcher cronMatcher = CRON_PATTERN.matcher(expression.trim());
if (!cronMatcher.matches()) {
throw new IllegalArgumentException("Expected cron expression but got: " + expression);
}
String cronExpression = cronMatcher.group(1);
String normalized = normalizeCronExpression(cronExpression);
Cron cron = CRON_PARSER.parse(normalized);
cron.validate();
ExecutionTime executionTime = ExecutionTime.forCron(cron);
return executionTime.nextExecution(from).orElse(null);
}
public static long millisUntilNextFire(String expression, ZonedDateTime from) {
ZonedDateTime next = getNextFireTime(expression, from);
if (next == null) {
throw new IllegalStateException("No next fire time found for cron expression: " + expression);
}
long millis = java.time.temporal.ChronoUnit.MILLIS.between(from, next);
return Math.max(millis, 1000);
}
private static String normalizeCronExpression(String cronExpression) {
String[] fields = cronExpression.trim().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 + ": " + cronExpression);
}
return "0 " + cronExpression;
}
}
@@ -51,4 +51,10 @@ public class Rule {
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
public String getRegion() {
if (arn == null) return null;
String[] parts = arn.split(":");
return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : null;
}
}