Light, fluffy, and always free - The AWS Local Emulator alternative
feat(glue): create, run and chain triggers (#4436)
David0d813adf9547
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/GlueTriggerTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/GlueTriggerTest.javanew file mode 100644index 0000000000..56cc5f5b7a--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/GlueTriggerTest.java@@ -0,0 +1,111 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.glue.GlueClient;+import software.amazon.awssdk.services.glue.model.BatchGetTriggersResponse;+import software.amazon.awssdk.services.glue.model.JobRun;+import software.amazon.awssdk.services.glue.model.JobRunState;+import software.amazon.awssdk.services.glue.model.LogicalOperator;+import software.amazon.awssdk.services.glue.model.Trigger;+import software.amazon.awssdk.services.glue.model.TriggerState;+import software.amazon.awssdk.services.glue.model.TriggerType;++import java.util.List;+import java.util.Map;++import static org.assertj.core.api.Assertions.assertThat;++@DisplayName("Glue triggers")+class GlueTriggerTest {++ private static final String EXTRACT = TestFixtures.uniqueName("trigger_extract");+ private static final String LOAD = TestFixtures.uniqueName("trigger_load");+ private static final String MANUAL = TestFixtures.uniqueName("trigger_manual");+ private static final String CHAIN = TestFixtures.uniqueName("trigger_chain");+ private static final String ROLE = "arn:aws:iam::000000000000:role/glue";++ private static GlueClient glue;++ @BeforeAll+ static void setup() {+ glue = TestFixtures.glueClient();+ for (String job : List.of(EXTRACT, LOAD)) {+ glue.createJob(r -> r.name(job).role(ROLE).command(c -> c.name("glueetl"))+ .executionProperty(p -> p.maxConcurrentRuns(5)));+ }+ glue.createTrigger(r -> r.name(MANUAL).type(TriggerType.ON_DEMAND)+ .actions(a -> a.jobName(EXTRACT)).tags(Map.of("team", "data")));+ glue.createTrigger(r -> r.name(CHAIN).type(TriggerType.CONDITIONAL).startOnCreation(true)+ .actions(a -> a.jobName(LOAD))+ .predicate(p -> p.conditions(c -> c.logicalOperator(LogicalOperator.EQUALS)+ .jobName(EXTRACT).state(JobRunState.SUCCEEDED))));+ }++ @AfterAll+ static void cleanup() {+ if (glue == null) {+ return;+ }+ for (String trigger : List.of(MANUAL, CHAIN)) {+ try {+ glue.deleteTrigger(r -> r.name(trigger));+ }+ catch (Exception ignored) {+ // Cleanup is best effort: the names are unique to this run and the emulator is disposable.+ }+ }+ for (String job : List.of(EXTRACT, LOAD)) {+ try {+ glue.deleteJob(r -> r.jobName(job));+ }+ catch (Exception ignored) {+ // Cleanup is best effort, as above.+ }+ }+ glue.close();+ }++ @Test+ @DisplayName("StartTrigger runs an ON_DEMAND trigger and a CONDITIONAL trigger follows it")+ void onDemandThenConditional() {+ glue.startTrigger(r -> r.name(MANUAL));++ JobRun extractRun = glue.getJobRuns(r -> r.jobName(EXTRACT)).jobRuns().get(0);+ assertThat(extractRun.triggerName()).isEqualTo(MANUAL);+ JobRun loadRun = glue.getJobRuns(r -> r.jobName(LOAD)).jobRuns().get(0);+ assertThat(loadRun.triggerName()).isEqualTo(CHAIN);+ assertThat(loadRun.jobRunState()).isEqualTo(JobRunState.SUCCEEDED);+ }++ @Test+ @DisplayName("GetTrigger, BatchGetTriggers and ListTriggers parse with the SDK")+ void readTriggers() {+ Trigger chain = glue.getTrigger(r -> r.name(CHAIN)).trigger();+ assertThat(chain.type()).isEqualTo(TriggerType.CONDITIONAL);+ assertThat(chain.state()).isEqualTo(TriggerState.ACTIVATED);+ assertThat(chain.predicate().conditions().get(0).jobName()).isEqualTo(EXTRACT);++ BatchGetTriggersResponse batch = glue.batchGetTriggers(r -> r.triggerNames(MANUAL, "absent_trigger"));+ assertThat(batch.triggers()).extracting(Trigger::name).containsExactly(MANUAL);+ assertThat(batch.triggersNotFound()).containsExactly("absent_trigger");++ assertThat(glue.listTriggers(r -> r.tags(Map.of("team", "data"))).triggerNames()).contains(MANUAL);+ }++ @Test+ @DisplayName("StopTrigger and UpdateTrigger round trip")+ void stopAndUpdate() {+ glue.stopTrigger(r -> r.name(CHAIN));+ assertThat(glue.getTrigger(r -> r.name(CHAIN)).trigger().state()).isEqualTo(TriggerState.DEACTIVATED);++ Trigger updated = glue.updateTrigger(r -> r.name(CHAIN).triggerUpdate(u -> u.description("load after extract")))+ .trigger();+ assertThat(updated.description()).isEqualTo("load after extract");++ glue.startTrigger(r -> r.name(CHAIN));+ assertThat(glue.getTrigger(r -> r.name(CHAIN)).trigger().state()).isEqualTo(TriggerState.ACTIVATED);+ }+}diff --git a/docs/services/glue.md b/docs/services/glue.mdindex 9716181c07..b3eea476b0 100644--- a/docs/services/glue.md+++ b/docs/services/glue.md@@ -183,6 +183,33 @@ of `SUCCEEDED` (or `CANCELLED` after `StopCrawler`). With the default `crawler-r`GetCrawlerMetrics` reports zero tables created, updated and deleted. Schedules are stored and theirstate can be switched, but a schedule never starts a crawl on its own.+#### Triggers++| Action | Description |+|--------|-------------|+| CreateTrigger | Creates an `ON_DEMAND`, `SCHEDULED` or `CONDITIONAL` trigger whose actions start jobs or crawlers. |+| GetTrigger | Retrieves a trigger. |+| GetTriggers | Retrieves triggers; with `DependentJobName`, those that start the job, or all when none do. |+| ListTriggers | Lists trigger names, with the same `DependentJobName` rule and an optional tag filter. |+| BatchGetTriggers | Retrieves several triggers by name and reports the names not found. |+| UpdateTrigger | Applies the members a `TriggerUpdate` sets and returns the trigger. |+| DeleteTrigger | Deletes a trigger; deleting one that does not exist succeeds. |+| StartTrigger | Runs an `ON_DEMAND` trigger's actions now, or activates a `SCHEDULED` or `CONDITIONAL` one. |+| StopTrigger | Deactivates a `SCHEDULED` or `CONDITIONAL` trigger. |++An activated `CONDITIONAL` trigger fires for each job run or crawl its predicate watches that finishes+in the named state (`ANY` on each matching completion, `AND` on a matching completion once every+condition's latest outcome matches). Runs finished before the trigger was activated do not count.+Floci evaluates conditional triggers after each request that starts, stops or reads job runs or crawls,+so with the default run durations of 0 a whole chain of triggers completes within the request that+starts it; with a positive duration the trigger fires on the first such request after the watched run+finishes. One request runs at most 25 firing rounds; a longer chain continues on the next such request.+As an emulator safeguard (AWS has no such limit), triggers start at most 100 runs on behalf of the run+that set off a chain, the one no trigger started, so a loop of triggers of any shape stops there.+A run a trigger starts carries its `TriggerName`. `SCHEDULED` triggers are stored and can+be activated, but no timer fires them. `EVENT` triggers and `WorkflowName` need workflows, which are+not emulated yet.+#### Classifiers| Action | Description |diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/GlueCrawlerRunService.java b/src/main/java/io/github/hectorvent/floci/services/glue/GlueCrawlerRunService.javaindex 47743793fe..b24d8a7352 100644--- a/src/main/java/io/github/hectorvent/floci/services/glue/GlueCrawlerRunService.java+++ b/src/main/java/io/github/hectorvent/floci/services/glue/GlueCrawlerRunService.java@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.glue.model.Crawler;import io.github.hectorvent.floci.services.glue.model.CrawlerRunRecord;+import io.github.hectorvent.floci.services.glue.model.FinishedCrawl;import io.github.hectorvent.floci.services.glue.model.LastCrawlInfo;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;@@ -43,6 +44,7 @@ public class GlueCrawlerRunService {static final String STATUS_CANCELLED = "CANCELLED";private static final String LOG_GROUP = "/aws-glue/crawlers";+ static final String CRAWL_ID_PREFIX = "crawl:";// Enough history for a stable median without letting a long-lived crawler grow without bound.private static final int MAX_RUNTIME_HISTORY = 100;@@ -69,17 +71,30 @@ public class GlueCrawlerRunService {this.clock = clock;}- public synchronized void startCrawler(String name) {+ public synchronized String startCrawler(String name) {+ return startCrawler(name, null);+ }++ /**+ * Starts a crawl and returns its crawl id ({@code crawl:} and a UUID, so ids never repeat, even for+ * a crawler deleted and created again). A trigger passes the origin of its chain; a null origin+ * makes the crawl its own origin.+ */+ public synchronized String startCrawler(String name, String originRunId) {glueService.getCrawler(name);CrawlerRunRecord record = settledRecord(name);if (record.getCurrentStart() != null) {throw new AwsException("CrawlerRunningException", "Crawler with name " + name + " has already started", 400);}+ String crawlId = CRAWL_ID_PREFIX + UUID.randomUUID();record.setCurrentStart(clock.instant());record.setCurrentMessagePrefix(UUID.randomUUID().toString());+ record.setCurrentCrawlId(crawlId);+ record.setCurrentOriginRunId(originRunId != null ? originRunId : crawlId);recordStore.put(name, record);LOG.infov("Started Glue crawler {0}", name);settle(record);+ return crawlId;}public synchronized void stopCrawler(String name) {@@ -149,6 +164,43 @@ public class GlueCrawlerRunService {return glueService.paginate(metrics, maxResults, nextToken);}+ /**+ * The crawler's finished crawls after {@code afterPosition} (all kept history when null or empty), oldest+ * first; what a conditional trigger on the crawler processes. Positions are crawl sequence numbers.+ */+ public synchronized List<GlueRunCompletion> completionsAfter(String name, String afterPosition) {+ CrawlerRunRecord record = settledRecord(name);+ long after = afterPosition == null || afterPosition.isEmpty() ? 0 : Long.parseLong(afterPosition);+ List<GlueRunCompletion> completions = new ArrayList<>();+ for (FinishedCrawl crawl : record.getRecentCrawls()) {+ if (crawl.getSequence() > after) {+ completions.add(new GlueRunCompletion(Long.toString(crawl.getSequence()), crawl.getFinishedAt(),+ crawl.getStatus(), crawl.getOriginRunId()));+ }+ }+ return completions;+ }++ /**+ * Records that triggers are about to start {@code runs} more runs on behalf of the origin crawl, if+ * that keeps it within {@code limit}. False when the crawl is no longer in its crawler's history.+ */+ public synchronized boolean claimTriggeredRuns(String originCrawlId, int runs, int limit) {+ for (CrawlerRunRecord record : recordStore.scan(key -> true)) {+ for (FinishedCrawl crawl : record.getRecentCrawls()) {+ if (originCrawlId.equals(crawl.getCrawlId())) {+ if (crawl.getTriggeredRuns() + runs > limit) {+ return false;+ }+ crawl.setTriggeredRuns(crawl.getTriggeredRuns() + runs);+ recordStore.put(record.getCrawlerName(), record);+ return true;+ }+ }+ }+ return false;+ }+public synchronized void updateCrawler(Crawler update) {requireNotRunning(update.getName());glueService.updateCrawler(update);@@ -235,11 +287,27 @@ public class GlueCrawlerRunService {runtimes.removeFirst();}record.setRuntimeSeconds(runtimes);+ FinishedCrawl finished = new FinishedCrawl();+ finished.setSequence(record.getFinishedCount() + 1);+ finished.setStartedAt(record.getCurrentStart());+ finished.setFinishedAt(finishedAt);+ finished.setStatus(status);+ finished.setCrawlId(record.getCurrentCrawlId());+ finished.setOriginRunId(record.getCurrentOriginRunId());+ List<FinishedCrawl> recent = new ArrayList<>(record.getRecentCrawls());+ recent.add(finished);+ if (recent.size() > MAX_RUNTIME_HISTORY) {+ recent.removeFirst();+ }+ record.setRecentCrawls(recent);+ record.setFinishedCount(finished.getSequence());record.setLastStart(record.getCurrentStart());record.setLastStatus(status);record.setLastMessagePrefix(record.getCurrentMessagePrefix());record.setCurrentStart(null);record.setCurrentMessagePrefix(null);+ record.setCurrentCrawlId(null);+ record.setCurrentOriginRunId(null);recordStore.put(record.getCrawlerName(), record);}}diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/GlueJobRunService.java b/src/main/java/io/github/hectorvent/floci/services/glue/GlueJobRunService.javaindex f08df58860..8d1f138d70 100644--- a/src/main/java/io/github/hectorvent/floci/services/glue/GlueJobRunService.java+++ b/src/main/java/io/github/hectorvent/floci/services/glue/GlueJobRunService.java@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.glue.model.ExecutionProperty;import io.github.hectorvent.floci.services.glue.model.Job;import io.github.hectorvent.floci.services.glue.model.JobRun;+import io.github.hectorvent.floci.services.glue.model.JobRunBookkeeping;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import org.jboss.logging.Logger;@@ -18,6 +19,7 @@ import java.time.Instant;import java.util.ArrayList;import java.util.Comparator;import java.util.List;+import java.util.Optional;import java.util.Set;import java.util.UUID;@@ -50,6 +52,10 @@ public class GlueJobRunService {private static final String LOG_GROUP_NAME = "/aws-glue/jobs";private final StorageBackend<String, JobRun> runStore;+ // Per run: the order in which Floci saw it finish (a conditional trigger's position; unlike+ // CompletedOn it never ties), its trigger chain origin, and that origin's triggered run count.+ private final StorageBackend<String, JobRunBookkeeping> bookkeepingStore;+ private long nextCompletionOrder;private final GlueService glueService;private final int runDurationSeconds;private final Clock clock;@@ -57,16 +63,18 @@ public class GlueJobRunService {@Injectpublic GlueJobRunService(StorageFactory storageFactory, GlueService glueService, EmulatorConfig config) {this(storageFactory.create("glue", "job_runs.json", new TypeReference<>() {}),+ storageFactory.create("glue", "job_run_bookkeeping.json", new TypeReference<>() {}),glueService, config.services().glue().jobRunDurationSeconds(), Clock.systemUTC());}- GlueJobRunService(StorageBackend<String, JobRun> runStore, GlueService glueService,- int runDurationSeconds, Clock clock) {+ GlueJobRunService(StorageBackend<String, JobRun> runStore, StorageBackend<String, JobRunBookkeeping> bookkeepingStore,+ GlueService glueService, int runDurationSeconds, Clock clock) {if (runDurationSeconds < 0) {throw new IllegalArgumentException("floci.services.glue.job-run-duration-seconds must not be negative: " + runDurationSeconds);}this.runStore = runStore;+ this.bookkeepingStore = bookkeepingStore;this.glueService = glueService;this.runDurationSeconds = runDurationSeconds;this.clock = clock;@@ -79,6 +87,15 @@ public class GlueJobRunService {* unset field falls back to the job definition.*/public synchronized JobRun startJobRun(String jobName, String previousRunId, JobRun overrides) {+ return startJobRun(jobName, previousRunId, overrides, null);+ }++ /**+ * As {@link #startJobRun(String, String, JobRun)}, for a run a trigger starts on behalf of+ * {@code originRunId}; a null origin makes the run its own origin.+ */+ public synchronized JobRun startJobRun(String jobName, String previousRunId, JobRun overrides,+ String originRunId) {Job job = glueService.getJob(jobName);// The job's own Timeout is stored as given by CreateJob/UpdateJob, so check what the run inherits.Integer timeout = firstNonNull(overrides.getTimeout(), job.getTimeout());@@ -102,6 +119,7 @@ public class GlueJobRunService {run.setId(newRunId());run.setAttempt(0);run.setPreviousRunId(previousRunId);+ run.setTriggerName(overrides.getTriggerName());run.setJobName(job.getName());run.setJobMode(job.getJobMode());run.setJobRunQueuingEnabled(queuingEnabled);@@ -123,6 +141,9 @@ public class GlueJobRunService {run.setLogGroupName(LOG_GROUP_NAME);run.setExecutionTime(0);runStore.put(run.getId(), run);+ JobRunBookkeeping bookkeeping = new JobRunBookkeeping();+ bookkeeping.setOriginRunId(originRunId != null ? originRunId : run.getId());+ bookkeepingStore.put(run.getId(), bookkeeping);LOG.infov("Started Glue job run {0} for job {1}", run.getId(), jobName);return settle(run);}@@ -180,10 +201,37 @@ public class GlueJobRunService {return new StopResult(stopped, errors);}+ /**+ * The job's finished runs after {@code afterPosition} (all when null or empty), in the order Floci saw+ * them finish; what a conditional trigger on the job processes. Every run that has finished by now+ * is settled first, so a run settled later always comes after the last position a trigger has seen.+ */+ public synchronized List<GlueRunCompletion> completionsAfter(String jobName, String afterPosition) {+ List<GlueRunCompletion> completions = new ArrayList<>();+ for (JobRun run : runsOf(jobName)) {+ settle(run);+ if (isTerminal(run)) {+ String position = positionOf(run);+ if (afterPosition == null || afterPosition.isEmpty() || position.compareTo(afterPosition) > 0) {+ completions.add(new GlueRunCompletion(position, run.getCompletedOn(), run.getJobRunState(),+ bookkeepingOf(run.getId()).getOriginRunId()));+ }+ }+ }+ completions.sort(Comparator.comparing(GlueRunCompletion::position));+ return completions;+ }++ // Zero padded so that comparing positions as strings follows the completion order.+ private String positionOf(JobRun run) {+ return String.format("%020d", bookkeepingOf(run.getId()).getCompletionOrder());+ }+/** Runs belong to their job: deleting the job removes them, as it does on AWS. */public synchronized void deleteRuns(String jobName) {for (JobRun run : runsOf(jobName)) {runStore.delete(run.getId());+ bookkeepingStore.delete(run.getId());}}@@ -215,6 +263,42 @@ public class GlueJobRunService {run.setExecutionTime((int) Duration.between(run.getStartedOn(), completedOn).toSeconds());run.setErrorMessage(errorMessage);runStore.put(run.getId(), run);+ JobRunBookkeeping bookkeeping = bookkeepingOf(run.getId());+ bookkeeping.setCompletionOrder(nextCompletionOrder());+ bookkeepingStore.put(run.getId(), bookkeeping);+ }++ private long nextCompletionOrder() {+ if (nextCompletionOrder == 0) {+ long highest = 0;+ for (JobRunBookkeeping bookkeeping : bookkeepingStore.scan(key -> true)) {+ highest = Math.max(highest, bookkeeping.getCompletionOrder());+ }+ nextCompletionOrder = highest + 1;+ }+ return nextCompletionOrder++;+ }++ private JobRunBookkeeping bookkeepingOf(String runId) {+ return bookkeepingStore.get(runId).orElseGet(() -> {+ JobRunBookkeeping fresh = new JobRunBookkeeping();+ fresh.setOriginRunId(runId);+ return fresh;+ });+ }++ /**+ * Records that triggers are about to start {@code runs} more runs on behalf of the origin job run,+ * if that keeps the origin within {@code limit}. False when the origin run no longer exists.+ */+ public synchronized boolean claimTriggeredRuns(String originRunId, int runs, int limit) {+ Optional<JobRunBookkeeping> origin = bookkeepingStore.get(originRunId);+ if (origin.isEmpty() || origin.get().getTriggeredRuns() + runs > limit) {+ return false;+ }+ origin.get().setTriggeredRuns(origin.get().getTriggeredRuns() + runs);+ bookkeepingStore.put(originRunId, origin.get());+ return true;}private JobRun findRun(String jobName, String runId) {diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.javaindex 5dce251376..3a940f2577 100644--- a/src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java@@ -21,6 +21,7 @@ import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Objects;+import java.util.Set;@ApplicationScopedpublic class GlueJsonHandler {@@ -29,10 +30,17 @@ public class GlueJsonHandler {private static final TypeReference<Map<String, String>> STRING_MAP = new TypeReference<>() {};private static final TypeReference<List<Map<String, Object>>> MAP_LIST = new TypeReference<>() {};private static final TypeReference<List<Partition>> PARTITION_LIST = new TypeReference<>() {};+ private static final TypeReference<List<TriggerAction>> TRIGGER_ACTIONS = new TypeReference<>() {};+ private static final Set<String> RUN_ACTIONS = Set.of(+ "StartJobRun", "GetJobRun", "GetJobRuns", "BatchStopJobRun",+ "StartCrawler", "StopCrawler", "GetCrawler", "GetCrawlers", "BatchGetCrawlers", "GetCrawlerMetrics",+ "UpdateCrawler",+ "StartTrigger");private final GlueService glueService;private final GlueJobRunService jobRunService;private final GlueCrawlerRunService crawlerRunService;+ private final GlueTriggerService triggerService;private final GlueSchemaRegistryService schemaRegistryService;private final ObjectMapper mapper;@@ -40,16 +48,29 @@ public class GlueJsonHandler {public GlueJsonHandler(GlueService glueService,GlueJobRunService jobRunService,GlueCrawlerRunService crawlerRunService,+ GlueTriggerService triggerService,GlueSchemaRegistryService schemaRegistryService,ObjectMapper mapper) {this.glueService = glueService;this.jobRunService = jobRunService;this.crawlerRunService = crawlerRunService;+ this.triggerService = triggerService;this.schemaRegistryService = schemaRegistryService;this.mapper = mapper;}public Response handle(String action, JsonNode request, String region) throws Exception {+ Response response = dispatch(action, request, region);+ // Runs and crawls finish when they are started, stopped or read (they settle on read), so+ // after those requests an activated CONDITIONAL trigger watching them gets to fire. Catalog+ // and definition requests cannot finish a run and skip the evaluation.+ if (RUN_ACTIONS.contains(action)) {+ triggerService.fireConditionalTriggers();+ }+ return response;+ }++ private Response dispatch(String action, JsonNode request, String region) throws Exception {return switch (action) {case "CreateDatabase" -> {Database db = mapper.treeToValue(request.get("DatabaseInput"), Database.class);@@ -438,10 +459,84 @@ public class GlueJsonHandler {case "ListDataQualityRulesets" -> Response.ok(Map.of("Rulesets", List.of())).build();case "GetSecurityConfigurations" -> Response.ok(Map.of("SecurityConfigurations", glueService.getSecurityConfigurations(region))).build();+ case "CreateTrigger" -> {+ Trigger trigger = toTrigger(request);+ trigger.setName(request.path("Name").asText(null));+ trigger.setWorkflowName(request.path("WorkflowName").asText(null));+ trigger.setType(request.path("Type").asText(null));+ Map<String, String> tags = request.hasNonNull("Tags")+ ? mapper.convertValue(request.get("Tags"), STRING_MAP)+ : null;+ triggerService.createTrigger(trigger, request.path("StartOnCreation").asBoolean(false), tags, region);+ yield Response.ok(Map.of("Name", trigger.getName())).build();+ }+ case "GetTrigger" -> Response.ok(Map.of(+ "Trigger", glueService.getTrigger(request.path("Name").asText(null)))).build();+ case "GetTriggers" -> {+ GlueService.Page<Trigger> page = glueService.getTriggers(+ request.path("DependentJobName").asText(null), readMaxResults(request), readNextToken(request));+ yield Response.ok(pageResponse("Triggers", page.items(), page.nextToken())).build();+ }+ case "ListTriggers" -> {+ Map<String, String> tags = request.hasNonNull("Tags")+ ? mapper.convertValue(request.get("Tags"), STRING_MAP)+ : null;+ GlueService.Page<String> page = glueService.listTriggers(request.path("DependentJobName").asText(null),+ readMaxResults(request), readNextToken(request), tags, region);+ yield Response.ok(pageResponse("TriggerNames", page.items(), page.nextToken())).build();+ }+ case "BatchGetTriggers" -> {+ List<String> names = request.hasNonNull("TriggerNames")+ ? mapper.convertValue(request.get("TriggerNames"), STRING_LIST)+ : null;+ GlueService.BatchGetTriggersResult result = glueService.batchGetTriggers(names);+ Map<String, Object> response = new LinkedHashMap<>();+ response.put("Triggers", result.triggers());+ response.put("TriggersNotFound", result.triggersNotFound());+ yield Response.ok(response).build();+ }+ case "UpdateTrigger" -> {+ Trigger update = request.hasNonNull("TriggerUpdate") ? toTrigger(request.get("TriggerUpdate")) : null;+ yield Response.ok(Map.of("Trigger",+ triggerService.updateTrigger(request.path("Name").asText(null), update))).build();+ }+ case "DeleteTrigger" -> {+ String name = request.path("Name").asText(null);+ triggerService.deleteTrigger(name, region);+ yield Response.ok(Map.of("Name", name)).build();+ }+ case "StartTrigger" -> {+ String name = request.path("Name").asText(null);+ triggerService.startTrigger(name);+ yield Response.ok(Map.of("Name", name)).build();+ }+ case "StopTrigger" -> {+ String name = request.path("Name").asText(null);+ triggerService.stopTrigger(name);+ yield Response.ok(Map.of("Name", name)).build();+ }default -> throw new AwsException("InvalidAction", "Action " + action + " is not supported", 400);};}+ /** The definition members CreateTrigger and TriggerUpdate share. */+ private Trigger toTrigger(JsonNode node) throws Exception {+ Trigger trigger = new Trigger();+ trigger.setDescription(node.path("Description").asText(null));+ trigger.setSchedule(node.path("Schedule").asText(null));+ if (node.hasNonNull("Actions")) {+ trigger.setActions(mapper.convertValue(node.get("Actions"), TRIGGER_ACTIONS));+ }+ if (node.hasNonNull("Predicate")) {+ trigger.setPredicate(mapper.treeToValue(node.get("Predicate"), Predicate.class));+ }+ if (node.hasNonNull("EventBatchingCondition")) {+ trigger.setEventBatchingCondition(+ mapper.treeToValue(node.get("EventBatchingCondition"), EventBatchingCondition.class));+ }+ return trigger;+ }+private Response handleUpdateColumnStatisticsForTable(JsonNode request) {String dbName = request.get("DatabaseName").asText();String tableName = request.get("TableName").asText();diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/GlueRunCompletion.java b/src/main/java/io/github/hectorvent/floci/services/glue/GlueRunCompletion.javanew file mode 100644index 0000000000..137353de6b--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/glue/GlueRunCompletion.java@@ -0,0 +1,11 @@+package io.github.hectorvent.floci.services.glue;++import java.time.Instant;++/**+ * One finished job run or crawl, as a conditional trigger sees it. {@code position} orders the+ * completions of one job or crawler; a trigger remembers the last position it has processed.+ * {@code originRunId} is the run that set off the trigger chain this run belongs to (the run itself+ * when no trigger started it): a job run id, or a crawl id beginning {@code crawl:}.+ */+public record GlueRunCompletion(String position, Instant finishedAt, String state, String originRunId) {}diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java b/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.javaindex c751c56316..72ca799c75 100644--- a/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java+++ b/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java@@ -14,23 +14,27 @@ import io.github.hectorvent.floci.services.glue.model.Column;import io.github.hectorvent.floci.services.glue.model.Connection;import io.github.hectorvent.floci.services.glue.model.ConnectionInput;import io.github.hectorvent.floci.services.glue.model.ConnectionPasswordEncryption;-import io.github.hectorvent.floci.services.glue.model.DataCatalogEncryptionSettings;-import io.github.hectorvent.floci.services.glue.model.EncryptionAtRest;-import io.github.hectorvent.floci.services.glue.model.GluePolicy;import io.github.hectorvent.floci.services.glue.model.Crawler;import io.github.hectorvent.floci.services.glue.model.CrawlerTargets;+import io.github.hectorvent.floci.services.glue.model.DataCatalogEncryptionSettings;import io.github.hectorvent.floci.services.glue.model.Database;+import io.github.hectorvent.floci.services.glue.model.EncryptionAtRest;+import io.github.hectorvent.floci.services.glue.model.GluePolicy;import io.github.hectorvent.floci.services.glue.model.Job;import io.github.hectorvent.floci.services.glue.model.JobUpdate;import io.github.hectorvent.floci.services.glue.model.KeySchemaElement;import io.github.hectorvent.floci.services.glue.model.Partition;import io.github.hectorvent.floci.services.glue.model.PartitionIndex;import io.github.hectorvent.floci.services.glue.model.PartitionIndexDescriptor;+import io.github.hectorvent.floci.services.glue.model.Predicate;import io.github.hectorvent.floci.services.glue.model.Schedule;import io.github.hectorvent.floci.services.glue.model.SchemaReference;import io.github.hectorvent.floci.services.glue.model.SecurityConfiguration;import io.github.hectorvent.floci.services.glue.model.StorageDescriptor;import io.github.hectorvent.floci.services.glue.model.Table;+import io.github.hectorvent.floci.services.glue.model.Trigger;+import io.github.hectorvent.floci.services.glue.model.TriggerAction;+import io.github.hectorvent.floci.services.glue.model.TriggerCondition;import io.github.hectorvent.floci.services.glue.model.UserDefinedFunction;import io.github.hectorvent.floci.services.glue.schemaregistry.GlueSchemaRegistryService;import io.github.hectorvent.floci.services.glue.schemaregistry.SchemaToColumnsConverter;@@ -153,6 +157,12 @@ public class GlueService {private static final String SCHEDULE_SCHEDULED = "SCHEDULED";private static final String SCHEDULE_NOT_SCHEDULED = "NOT_SCHEDULED";private static final Pattern CRON_FIELD = Pattern.compile("[0-9A-Za-z*?/,#-]+");+ private static final Set<String> TRIGGER_TYPES = Set.of("SCHEDULED", "CONDITIONAL", "ON_DEMAND", "EVENT");+ // The job run and crawl states a trigger condition may name (JobRunState / CrawlState in the model+ // allow more, but only final states are meaningful as conditions).+ private static final Set<String> CONDITION_JOB_STATES = Set.of("SUCCEEDED", "STOPPED", "FAILED", "TIMEOUT");+ private static final Set<String> CONDITION_CRAWL_STATES = Set.of("SUCCEEDED", "CANCELLED", "FAILED");+ private static final int MAX_TRIGGERS_PAGE_SIZE = 200;// BatchGetCrawlers takes a CrawlerNameList, which the API model caps at 100 names.private static final int MAX_BATCH_GET_CRAWLERS = 100;@@ -171,6 +181,7 @@ public class GlueService {private final StorageBackend<String, GluePolicy> resourcePolicyStore;private final StorageBackend<String, DataCatalogEncryptionSettings> encryptionSettingsStore;private final StorageBackend<String, SecurityConfiguration> securityConfigurationStore;+ private final StorageBackend<String, Trigger> triggerStore;private final GlueSchemaRegistryService schemaRegistryService;private final RegionResolver regionResolver;private final ResourceGroupsTaggingService resourceGroupsTaggingService;@@ -201,6 +212,7 @@ public class GlueService {"glue", "catalog_encryption_settings.json", new TypeReference<>() {});this.securityConfigurationStore = storageFactory.create("glue", "security_configurations.json", new TypeReference<>() {});+ this.triggerStore = storageFactory.create("glue", "triggers.json", new TypeReference<>() {});this.schemaRegistryService = schemaRegistryService;this.regionResolver = regionResolver;this.resourceGroupsTaggingService = resourceGroupsTaggingService;@@ -222,6 +234,7 @@ public class GlueService {StorageBackend<String, GluePolicy> resourcePolicyStore,StorageBackend<String, DataCatalogEncryptionSettings> encryptionSettingsStore,StorageBackend<String, SecurityConfiguration> securityConfigurationStore,+ StorageBackend<String, Trigger> triggerStore,GlueSchemaRegistryService schemaRegistryService,RegionResolver regionResolver,ResourceGroupsTaggingService resourceGroupsTaggingService,@@ -241,6 +254,7 @@ public class GlueService {this.resourcePolicyStore = resourcePolicyStore;this.encryptionSettingsStore = encryptionSettingsStore;this.securityConfigurationStore = securityConfigurationStore;+ this.triggerStore = triggerStore;this.schemaRegistryService = schemaRegistryService;this.regionResolver = regionResolver;this.resourceGroupsTaggingService = resourceGroupsTaggingService;@@ -1501,6 +1515,10 @@ public class GlueService {return regionResolver.buildArn("glue", region, "crawler/" + crawlerName);}+ private String triggerArn(String region, String triggerName) {+ return regionResolver.buildArn("glue", region, "trigger/" + triggerName);+ }+private static Pattern compileFunctionPattern(String pattern) {if (pattern == null) {return Pattern.compile(".*");@@ -2148,6 +2166,212 @@ public class GlueService {crawlerStore.put(name, crawler);}+ // ---- Triggers ---------------------------------------------------------------------------++ public void createTrigger(Trigger trigger, Map<String, String> tags, String region) {+ validateRequired(trigger.getName(), "Name");+ validateRequired(trigger.getType(), "Type");+ if (!TRIGGER_TYPES.contains(trigger.getType())) {+ throw new AwsException("InvalidInputException", "Invalid trigger type: " + trigger.getType(), 400);+ }+ if (trigger.getWorkflowName() != null) {+ throw new AwsException("EntityNotFoundException",+ "Workflow " + trigger.getWorkflowName() + " not found.", 400);+ }+ if ("EVENT".equals(trigger.getType())) {+ throw new AwsException("InvalidInputException", "An EVENT trigger must belong to a workflow.", 400);+ }+ validateTriggerDefinition(trigger);+ String name = trigger.getName();+ if (triggerStore.get(name).isPresent()) {+ throw new AwsException("AlreadyExistsException", "Trigger " + name + " already exists.", 400);+ }+ triggerStore.put(name, trigger);+ if (tags != null && !tags.isEmpty()) {+ resourceGroupsTaggingService.tagResources(List.of(triggerArn(region, name)), tags, region);+ }+ LOG.infov("Created Glue trigger {0}", name);+ }++ public Trigger getTrigger(String name) {+ validateRequired(name, "Name");+ return triggerStore.get(name)+ .orElseThrow(() -> new AwsException("EntityNotFoundException", "Trigger " + name + " not found.", 400));+ }++ public List<Trigger> allTriggers() {+ List<Trigger> triggers = triggerStore.scan(k -> true);+ triggers.sort(Comparator.comparing(Trigger::getName));+ return triggers;+ }++ public void putTrigger(Trigger trigger) {+ triggerStore.put(trigger.getName(), trigger);+ }++ /**+ * GetTriggers. With DependentJobName, the triggers that can start that job; AWS documents that+ * all triggers are returned when none can.+ */+ public Page<Trigger> getTriggers(String dependentJobName, Integer maxResults, String nextToken) {+ if (maxResults != null && (maxResults < 1 || maxResults > MAX_TRIGGERS_PAGE_SIZE)) {+ throw new AwsException("InvalidInputException",+ "MaxResults must be between 1 and " + MAX_TRIGGERS_PAGE_SIZE, 400);+ }+ return paginate(triggersStarting(dependentJobName), maxResults, nextToken);+ }++ public Page<String> listTriggers(String dependentJobName, Integer maxResults, String nextToken,+ Map<String, String> tags, String region) {+ List<String> names = new ArrayList<>();+ for (Trigger trigger : triggersStarting(dependentJobName)) {+ if (tags == null || tags.isEmpty() || hasTags(triggerArn(region, trigger.getName()), tags, region)) {+ names.add(trigger.getName());+ }+ }+ return paginate(names, maxResults, nextToken);+ }++ public BatchGetTriggersResult batchGetTriggers(List<String> names) {+ if (names == null || names.isEmpty()) {+ throw new AwsException("InvalidInputException", "TriggerNames is required.", 400);+ }+ List<Trigger> triggers = new ArrayList<>();+ List<String> notFound = new ArrayList<>();+ for (String name : names) {+ Optional<Trigger> trigger = name == null ? Optional.empty() : triggerStore.get(name);+ if (trigger.isPresent()) {+ triggers.add(trigger.get());+ } else {+ notFound.add(name);+ }+ }+ return new BatchGetTriggersResult(triggers, notFound);+ }++ public record BatchGetTriggersResult(List<Trigger> triggers, List<String> triggersNotFound) {}++ /**+ * Applies the members a TriggerUpdate sets; the rest of the trigger is kept. The update is built+ * and validated on a copy, so a rejected update leaves the stored trigger as it was.+ */+ public Trigger updateTrigger(String name, Trigger update) {+ validateRequired(update, "TriggerUpdate");+ Trigger stored = getTrigger(name);+ Trigger trigger = new Trigger();+ trigger.setName(stored.getName());+ trigger.setWorkflowName(stored.getWorkflowName());+ trigger.setType(stored.getType());+ trigger.setState(stored.getState());+ trigger.setDescription(stored.getDescription());+ trigger.setSchedule(stored.getSchedule());+ trigger.setActions(stored.getActions());+ trigger.setPredicate(stored.getPredicate());+ trigger.setEventBatchingCondition(stored.getEventBatchingCondition());+ if (update.getDescription() != null) {+ trigger.setDescription(update.getDescription());+ }+ if (update.getSchedule() != null) {+ trigger.setSchedule(update.getSchedule());+ }+ if (update.getActions() != null) {+ trigger.setActions(update.getActions());+ }+ if (update.getPredicate() != null) {+ trigger.setPredicate(update.getPredicate());+ }+ if (update.getEventBatchingCondition() != null) {+ trigger.setEventBatchingCondition(update.getEventBatchingCondition());+ }+ validateTriggerDefinition(trigger);+ triggerStore.put(name, trigger);+ return trigger;+ }++ /** DeleteTrigger declares no EntityNotFoundException: deleting a missing trigger succeeds. */+ public void deleteTrigger(String name, String region) {+ validateRequired(name, "Name");+ triggerStore.delete(name);+ resourceGroupsTaggingService.deleteResources(List.of(triggerArn(region, name)), region);+ }++ private List<Trigger> triggersStarting(String dependentJobName) {+ List<Trigger> all = allTriggers();+ if (dependentJobName == null) {+ return all;+ }+ getJob(dependentJobName);+ List<Trigger> starting = new ArrayList<>();+ for (Trigger trigger : all) {+ for (TriggerAction action : trigger.getActions()) {+ if (dependentJobName.equals(action.getJobName())) {+ starting.add(trigger);+ break;+ }+ }+ }+ return starting.isEmpty() ? all : starting;+ }++ private void validateTriggerDefinition(Trigger trigger) {+ List<TriggerAction> actions = trigger.getActions();+ if (actions == null || actions.isEmpty()) {+ throw new AwsException("InvalidInputException", "Actions must contain at least one action.", 400);+ }+ for (TriggerAction action : actions) {+ boolean hasJob = action.getJobName() != null;+ boolean hasCrawler = action.getCrawlerName() != null;+ if (hasJob == hasCrawler) {+ throw new AwsException("InvalidInputException",+ "Each action must name exactly one of JobName and CrawlerName.", 400);+ }+ if (hasJob) {+ getJob(action.getJobName());+ } else {+ getCrawler(action.getCrawlerName());+ }+ if (action.getTimeout() != null && action.getTimeout() < 1) {+ throw new AwsException("InvalidInputException", "Timeout must be at least 1 minute.", 400);+ }+ }+ if ("SCHEDULED".equals(trigger.getType())) {+ validateCronExpression(trigger.getSchedule());+ }+ if ("CONDITIONAL".equals(trigger.getType())) {+ validatePredicate(trigger.getPredicate());+ }+ }++ private void validatePredicate(Predicate predicate) {+ if (predicate == null || predicate.getConditions() == null || predicate.getConditions().isEmpty()) {+ throw new AwsException("InvalidInputException", "A CONDITIONAL trigger needs a predicate.", 400);+ }+ if (predicate.getLogical() != null && !Set.of("AND", "ANY").contains(predicate.getLogical())) {+ throw new AwsException("InvalidInputException", "Logical must be AND or ANY.", 400);+ }+ for (TriggerCondition condition : predicate.getConditions()) {+ if (condition.getLogicalOperator() != null && !"EQUALS".equals(condition.getLogicalOperator())) {+ throw new AwsException("InvalidInputException", "LogicalOperator must be EQUALS.", 400);+ }+ if (condition.getJobName() != null) {+ if (condition.getState() == null || !CONDITION_JOB_STATES.contains(condition.getState())) {+ throw new AwsException("InvalidInputException",+ "A job condition's State must be one of " + CONDITION_JOB_STATES, 400);+ }+ getJob(condition.getJobName());+ } else if (condition.getCrawlerName() != null) {+ if (condition.getCrawlState() == null || !CONDITION_CRAWL_STATES.contains(condition.getCrawlState())) {+ throw new AwsException("InvalidInputException",+ "A crawler condition's CrawlState must be one of " + CONDITION_CRAWL_STATES, 400);+ }+ getCrawler(condition.getCrawlerName());+ } else {+ throw new AwsException("InvalidInputException",+ "Each condition must name a JobName or a CrawlerName.", 400);+ }+ }+ }+public void updateCrawler(Crawler update) {validateRequired(update.getName(), "Name");// Jobs and crawlers skip normalizeName because AWS preserves their case@@ -2603,6 +2827,9 @@ public class GlueService {} else if (resource.startsWith("crawler/")) {getCrawler(resource.substring(8));return;+ } else if (resource.startsWith("trigger/")) {+ getTrigger(resource.substring(8));+ return;} else if (resource.startsWith("connection/")) {getConnection(resource.substring(11), false);return;diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/GlueTriggerService.java b/src/main/java/io/github/hectorvent/floci/services/glue/GlueTriggerService.javanew file mode 100644index 0000000000..ad99472ef2--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/glue/GlueTriggerService.java@@ -0,0 +1,300 @@+package io.github.hectorvent.floci.services.glue;++import com.fasterxml.jackson.core.type.TypeReference;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.glue.model.JobRun;+import io.github.hectorvent.floci.services.glue.model.Trigger;+import io.github.hectorvent.floci.services.glue.model.TriggerAction;+import io.github.hectorvent.floci.services.glue.model.TriggerCondition;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.util.ArrayList;+import java.util.Comparator;+import java.util.HashMap;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;++/**+ * Glue trigger lifecycle and firing. An ON_DEMAND trigger fires when started. A CONDITIONAL trigger,+ * once ACTIVATED, fires when a job run or crawl its predicate watches finishes in the named state:+ * after each Glue request that starts, stops or reads job runs or crawls,+ * {@link #fireConditionalTriggers()} processes every completion of a watched job or crawler this+ * trigger has not seen yet, in finishing order. A SCHEDULED trigger is stored and can be activated,+ * but no timer fires it.+ *+ * <p>Every public method is synchronized. This service calls the job run and crawler run services+ * and they never call back, so the lock order is always this service first.+ */+@ApplicationScoped+public class GlueTriggerService {++ private static final Logger LOG = Logger.getLogger(GlueTriggerService.class);++ static final String TYPE_ON_DEMAND = "ON_DEMAND";+ static final String TYPE_CONDITIONAL = "CONDITIONAL";+ static final String STATE_CREATED = "CREATED";+ static final String STATE_ACTIVATED = "ACTIVATED";+ static final String STATE_DEACTIVATED = "DEACTIVATED";++ // Work done within one request; a longer chain continues on the next run-related request.+ private static final int MAX_FIRING_ROUNDS = 25;+ // Emulator safeguard, not an AWS limit: triggers start at most this many runs on behalf of one run+ // that no trigger started (the origin of a chain). Here every run succeeds, so without it a trigger+ // loop of any shape, branching or not, would never stop.+ static final int MAX_TRIGGERED_RUNS_PER_ORIGIN = 100;+ private static final String JOB_KEY = "job:";+ private static final String CRAWLER_KEY = "crawler:";+ // Per watched job or crawler, the seen map holds the last processed position and that outcome's state.+ private static final String POSITION = "position:";+ private static final String STATE = "state:";++ private final StorageBackend<String, Map<String, String>> seenStore;+ private final GlueService glueService;+ private final GlueJobRunService jobRunService;+ private final GlueCrawlerRunService crawlerRunService;++ @Inject+ public GlueTriggerService(StorageFactory storageFactory, GlueService glueService,+ GlueJobRunService jobRunService, GlueCrawlerRunService crawlerRunService) {+ this(storageFactory.create("glue", "trigger_seen_runs.json", new TypeReference<>() {}),+ glueService, jobRunService, crawlerRunService);+ }++ GlueTriggerService(StorageBackend<String, Map<String, String>> seenStore, GlueService glueService,+ GlueJobRunService jobRunService, GlueCrawlerRunService crawlerRunService) {+ this.seenStore = seenStore;+ this.glueService = glueService;+ this.jobRunService = jobRunService;+ this.crawlerRunService = crawlerRunService;+ }++ public synchronized void createTrigger(Trigger trigger, boolean startOnCreation, Map<String, String> tags,+ String region) {+ if (startOnCreation && TYPE_ON_DEMAND.equals(trigger.getType())) {+ throw new AwsException("InvalidInputException",+ "StartOnCreation is not supported for ON_DEMAND triggers.", 400);+ }+ trigger.setState(startOnCreation ? STATE_ACTIVATED : STATE_CREATED);+ glueService.createTrigger(trigger, tags, region);+ if (isActiveConditional(trigger)) {+ markAlreadyFinishedAsSeen(trigger, false);+ }+ }++ public synchronized Trigger updateTrigger(String name, Trigger update) {+ Trigger trigger = glueService.updateTrigger(name, update);+ if (isActiveConditional(trigger)) {+ // Completions not yet evaluated for what the trigger already watched must still fire it;+ // only a newly watched job or crawler starts from what has finished so far.+ markAlreadyFinishedAsSeen(trigger, true);+ }+ return trigger;+ }++ public synchronized void deleteTrigger(String name, String region) {+ glueService.deleteTrigger(name, region);+ seenStore.delete(name);+ }++ /** ON_DEMAND: runs the actions now. SCHEDULED and CONDITIONAL: activates the trigger. */+ public synchronized void startTrigger(String name) {+ Trigger trigger = glueService.getTrigger(name);+ if (TYPE_ON_DEMAND.equals(trigger.getType())) {+ fire(trigger, null, true);+ return;+ }+ boolean wasActive = STATE_ACTIVATED.equals(trigger.getState());+ trigger.setState(STATE_ACTIVATED);+ glueService.putTrigger(trigger);+ if (isActiveConditional(trigger)) {+ markAlreadyFinishedAsSeen(trigger, wasActive);+ }+ }++ public synchronized void stopTrigger(String name) {+ Trigger trigger = glueService.getTrigger(name);+ if (TYPE_ON_DEMAND.equals(trigger.getType())) {+ throw new AwsException("InvalidInputException", "An ON_DEMAND trigger cannot be stopped.", 400);+ }+ trigger.setState(STATE_DEACTIVATED);+ glueService.putTrigger(trigger);+ }++ /**+ * Fires every activated CONDITIONAL trigger for each new job run or crawl completion that meets+ * its predicate, repeating while firing finishes more runs (a chain of triggers with the default+ * run duration of 0 completes within one request, up to {@link #MAX_FIRING_ROUNDS} rounds; the rest+ * continues on the next run-related request). A trigger loop of any shape stops once triggers have+ * started {@link #MAX_TRIGGERED_RUNS_PER_ORIGIN} runs on behalf of the run that set it off.+ */+ public synchronized void fireConditionalTriggers() {+ for (int round = 0; round < MAX_FIRING_ROUNDS; round++) {+ boolean anyFired = false;+ for (Trigger trigger : glueService.allTriggers()) {+ if (!isActiveConditional(trigger)) {+ continue;+ }+ for (GlueRunCompletion cause : newFirings(trigger)) {+ String origin = cause.originRunId();+ if (!claimTriggeredRuns(origin, trigger.getActions().size())) {+ LOG.warnv("Glue trigger {0} not fired: triggers already started {1} runs on behalf of {2}, "+ + "so they probably form a loop", trigger.getName(), MAX_TRIGGERED_RUNS_PER_ORIGIN, origin);+ continue;+ }+ fire(trigger, origin, false);+ anyFired = true;+ }+ }+ if (!anyFired) {+ return;+ }+ }+ }++ /**+ * Processes the completions this trigger has not seen yet, in finishing order, and returns the+ * completions that fire it. ANY fires on+ * each completion that matches one of its conditions; AND fires on a matching completion once+ * every condition's latest outcome matches.+ */+ private List<GlueRunCompletion> newFirings(Trigger trigger) {+ Map<String, String> before = seenStore.get(trigger.getName()).orElse(Map.of());+ Map<String, String> seen = new HashMap<>(before);+ List<KeyedCompletion> fresh = new ArrayList<>();+ for (String key : watchedKeys(trigger)) {+ for (GlueRunCompletion completion : completionsAfter(key, seen.get(POSITION + key))) {+ fresh.add(new KeyedCompletion(key, completion));+ }+ }+ fresh.sort(Comparator.comparing((KeyedCompletion k) -> k.completion().finishedAt())+ .thenComparing(k -> k.completion().position()));+ boolean any = "ANY".equals(trigger.getPredicate().getLogical());+ List<GlueRunCompletion> firings = new ArrayList<>();+ for (KeyedCompletion event : fresh) {+ // Events run in finishing order, which need not be completion order (a run can be stopped+ // before an earlier started one is seen succeeding), so keep the highest position processed.+ String processed = seen.get(POSITION + event.key());+ if (processed == null || event.completion().position().compareTo(processed) > 0) {+ seen.put(POSITION + event.key(), event.completion().position());+ }+ seen.put(STATE + event.key(), event.completion().state());+ boolean eventMatches = false;+ boolean allMatch = true;+ for (TriggerCondition condition : trigger.getPredicate().getConditions()) {+ boolean matches = expectedState(condition).equals(seen.get(STATE + keyOf(condition)));+ allMatch &= matches;+ eventMatches |= matches && keyOf(condition).equals(event.key())+ && expectedState(condition).equals(event.completion().state());+ }+ if (eventMatches && (any || allMatch)) {+ firings.add(event.completion());+ }+ }+ if (!seen.equals(before)) {+ seenStore.put(trigger.getName(), seen);+ }+ return firings;+ }++ /**+ * Marks what has already finished as seen, so that only later completions count. With+ * {@code keepProcessed}, a watched job or crawler the trigger already tracks keeps its position, so+ * its unevaluated completions still fire the trigger; only newly watched ones are marked.+ */+ private void markAlreadyFinishedAsSeen(Trigger trigger, boolean keepProcessed) {+ Map<String, String> seen = new HashMap<>();+ Map<String, String> previous = keepProcessed ? seenStore.get(trigger.getName()).orElse(Map.of()) : Map.of();+ for (String key : watchedKeys(trigger)) {+ if (previous.containsKey(POSITION + key)) {+ seen.put(POSITION + key, previous.get(POSITION + key));+ if (previous.containsKey(STATE + key)) {+ seen.put(STATE + key, previous.get(STATE + key));+ }+ continue;+ }+ List<GlueRunCompletion> completions = completionsAfter(key, null);+ if (completions.isEmpty()) {+ // Tracked from the start: an empty position means every completion is still unseen.+ seen.put(POSITION + key, "");+ } else {+ GlueRunCompletion last = completions.getLast();+ seen.put(POSITION + key, last.position());+ seen.put(STATE + key, last.state());+ }+ }+ seenStore.put(trigger.getName(), seen);+ }++ private static Set<String> watchedKeys(Trigger trigger) {+ Set<String> keys = new LinkedHashSet<>();+ for (TriggerCondition condition : trigger.getPredicate().getConditions()) {+ keys.add(keyOf(condition));+ }+ return keys;+ }++ private List<GlueRunCompletion> completionsAfter(String key, String position) {+ if (key.startsWith(JOB_KEY)) {+ return jobRunService.completionsAfter(key.substring(JOB_KEY.length()), position);+ }+ return crawlerRunService.completionsAfter(key.substring(CRAWLER_KEY.length()), position);+ }++ private boolean claimTriggeredRuns(String originRunId, int runs) {+ if (originRunId == null) {+ return false;+ }+ return originRunId.startsWith(GlueCrawlerRunService.CRAWL_ID_PREFIX)+ ? crawlerRunService.claimTriggeredRuns(originRunId, runs, MAX_TRIGGERED_RUNS_PER_ORIGIN)+ : jobRunService.claimTriggeredRuns(originRunId, runs, MAX_TRIGGERED_RUNS_PER_ORIGIN);+ }++ /**+ * Starts the trigger's actions on behalf of {@code originRunId}; with a null origin (StartTrigger on+ * an ON_DEMAND trigger) each run or crawl started is its own origin.+ */+ private void fire(Trigger trigger, String originRunId, boolean propagateFailures) {+ LOG.infov("Firing Glue trigger {0}", trigger.getName());+ for (TriggerAction action : trigger.getActions()) {+ try {+ if (action.getJobName() != null) {+ JobRun overrides = new JobRun();+ overrides.setArguments(action.getArguments());+ overrides.setTimeout(action.getTimeout());+ overrides.setSecurityConfiguration(action.getSecurityConfiguration());+ overrides.setNotificationProperty(action.getNotificationProperty());+ overrides.setTriggerName(trigger.getName());+ jobRunService.startJobRun(action.getJobName(), null, overrides, originRunId);+ } else {+ crawlerRunService.startCrawler(action.getCrawlerName(), originRunId);+ }+ } catch (AwsException e) {+ if (propagateFailures) {+ throw e;+ }+ LOG.warnv("Glue trigger {0} could not start {1}: {2}", trigger.getName(),+ action.getJobName() != null ? action.getJobName() : action.getCrawlerName(), e.getMessage());+ }+ }+ }++ private static String expectedState(TriggerCondition condition) {+ return condition.getJobName() != null ? condition.getState() : condition.getCrawlState();+ }++ private static String keyOf(TriggerCondition condition) {+ return condition.getJobName() != null ? JOB_KEY + condition.getJobName() : CRAWLER_KEY + condition.getCrawlerName();+ }++ private static boolean isActiveConditional(Trigger trigger) {+ return TYPE_CONDITIONAL.equals(trigger.getType()) && STATE_ACTIVATED.equals(trigger.getState());+ }++ private record KeyedCompletion(String key, GlueRunCompletion completion) {}+}diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/CrawlerRunRecord.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/CrawlerRunRecord.javaindex 8fc5e96c68..9a3ee679ab 100644--- a/src/main/java/io/github/hectorvent/floci/services/glue/model/CrawlerRunRecord.java+++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/CrawlerRunRecord.java@@ -15,10 +15,14 @@ public class CrawlerRunRecord {private String crawlerName;private Instant currentStart;private String currentMessagePrefix;+ private String currentCrawlId;+ private String currentOriginRunId;private Instant lastStart;private String lastStatus;private String lastMessagePrefix;private List<Double> runtimeSeconds = new ArrayList<>();+ private long finishedCount;+ private List<FinishedCrawl> recentCrawls = new ArrayList<>();public CrawlerRunRecord() {}@@ -34,6 +38,12 @@ public class CrawlerRunRecord {public Instant getLastStart() { return lastStart; }public void setLastStart(Instant lastStart) { this.lastStart = lastStart; }+ public String getCurrentCrawlId() { return currentCrawlId; }+ public void setCurrentCrawlId(String currentCrawlId) { this.currentCrawlId = currentCrawlId; }++ public String getCurrentOriginRunId() { return currentOriginRunId; }+ public void setCurrentOriginRunId(String currentOriginRunId) { this.currentOriginRunId = currentOriginRunId; }+public String getLastStatus() { return lastStatus; }public void setLastStatus(String lastStatus) { this.lastStatus = lastStatus; }@@ -42,4 +52,10 @@ public class CrawlerRunRecord {public List<Double> getRuntimeSeconds() { return runtimeSeconds; }public void setRuntimeSeconds(List<Double> runtimeSeconds) { this.runtimeSeconds = runtimeSeconds; }++ public long getFinishedCount() { return finishedCount; }+ public void setFinishedCount(long finishedCount) { this.finishedCount = finishedCount; }++ public List<FinishedCrawl> getRecentCrawls() { return recentCrawls; }+ public void setRecentCrawls(List<FinishedCrawl> recentCrawls) { this.recentCrawls = recentCrawls; }}diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/EventBatchingCondition.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/EventBatchingCondition.javanew file mode 100644index 0000000000..ca014a6cf0--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/EventBatchingCondition.java@@ -0,0 +1,23 @@+package io.github.hectorvent.floci.services.glue.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public class EventBatchingCondition {+ @JsonProperty("BatchSize")+ private Integer batchSize;++ @JsonProperty("BatchWindow")+ private Integer batchWindow;++ public EventBatchingCondition() {}++ public Integer getBatchSize() { return batchSize; }+ public void setBatchSize(Integer batchSize) { this.batchSize = batchSize; }++ public Integer getBatchWindow() { return batchWindow; }+ public void setBatchWindow(Integer batchWindow) { this.batchWindow = batchWindow; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/FinishedCrawl.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/FinishedCrawl.javanew file mode 100644index 0000000000..9327e55c22--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/FinishedCrawl.java@@ -0,0 +1,40 @@+package io.github.hectorvent.floci.services.glue.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;++/** One finished crawl in a crawler's recent history; Floci bookkeeping, never sent on the wire. */+@RegisterForReflection+public class FinishedCrawl {+ private long sequence;+ private Instant startedAt;+ private Instant finishedAt;+ private String status;+ private String crawlId;+ private String originRunId;+ private int triggeredRuns;++ public FinishedCrawl() {}++ public long getSequence() { return sequence; }+ public void setSequence(long sequence) { this.sequence = sequence; }++ public Instant getStartedAt() { return startedAt; }+ public void setStartedAt(Instant startedAt) { this.startedAt = startedAt; }++ public Instant getFinishedAt() { return finishedAt; }+ public void setFinishedAt(Instant finishedAt) { this.finishedAt = finishedAt; }++ public String getStatus() { return status; }+ public void setStatus(String status) { this.status = status; }++ public String getCrawlId() { return crawlId; }+ public void setCrawlId(String crawlId) { this.crawlId = crawlId; }++ public String getOriginRunId() { return originRunId; }+ public void setOriginRunId(String originRunId) { this.originRunId = originRunId; }++ public int getTriggeredRuns() { return triggeredRuns; }+ public void setTriggeredRuns(int triggeredRuns) { this.triggeredRuns = triggeredRuns; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/JobRun.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/JobRun.javaindex 2a8affdc25..a5008d0e98 100644--- a/src/main/java/io/github/hectorvent/floci/services/glue/model/JobRun.java+++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/JobRun.java@@ -20,6 +20,9 @@ public class JobRun {@JsonProperty("PreviousRunId")private String previousRunId;+ @JsonProperty("TriggerName")+ private String triggerName;+@JsonProperty("JobName")private String jobName;@@ -94,6 +97,9 @@ public class JobRun {public String getPreviousRunId() { return previousRunId; }public void setPreviousRunId(String previousRunId) { this.previousRunId = previousRunId; }+ public String getTriggerName() { return triggerName; }+ public void setTriggerName(String triggerName) { this.triggerName = triggerName; }+public String getJobName() { return jobName; }public void setJobName(String jobName) { this.jobName = jobName; }diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/JobRunBookkeeping.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/JobRunBookkeeping.javanew file mode 100644index 0000000000..769db54b3f--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/JobRunBookkeeping.java@@ -0,0 +1,26 @@+package io.github.hectorvent.floci.services.glue.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * Floci's own bookkeeping for one job run, never sent on the wire, and deleted with the run: the order+ * in which Floci saw it finish, the run that set off its trigger chain, and, when the run is itself+ * such an origin, how many runs triggers have started on its behalf.+ */+@RegisterForReflection+public class JobRunBookkeeping {+ private long completionOrder;+ private String originRunId;+ private int triggeredRuns;++ public JobRunBookkeeping() {}++ public long getCompletionOrder() { return completionOrder; }+ public void setCompletionOrder(long completionOrder) { this.completionOrder = completionOrder; }++ public String getOriginRunId() { return originRunId; }+ public void setOriginRunId(String originRunId) { this.originRunId = originRunId; }++ public int getTriggeredRuns() { return triggeredRuns; }+ public void setTriggeredRuns(int triggeredRuns) { this.triggeredRuns = triggeredRuns; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/Predicate.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/Predicate.javanew file mode 100644index 0000000000..368534995c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/Predicate.java@@ -0,0 +1,25 @@+package io.github.hectorvent.floci.services.glue.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.List;++@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public class Predicate {+ @JsonProperty("Logical")+ private String logical;++ @JsonProperty("Conditions")+ private List<TriggerCondition> conditions;++ public Predicate() {}++ public String getLogical() { return logical; }+ public void setLogical(String logical) { this.logical = logical; }++ public List<TriggerCondition> getConditions() { return conditions; }+ public void setConditions(List<TriggerCondition> conditions) { this.conditions = conditions; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/Trigger.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/Trigger.javanew file mode 100644index 0000000000..f3631c0799--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/Trigger.java@@ -0,0 +1,67 @@+package io.github.hectorvent.floci.services.glue.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.List;++@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public class Trigger {+ @JsonProperty("Name")+ private String name;++ @JsonProperty("WorkflowName")+ private String workflowName;++ @JsonProperty("Type")+ private String type;++ @JsonProperty("State")+ private String state;++ @JsonProperty("Description")+ private String description;++ @JsonProperty("Schedule")+ private String schedule;++ @JsonProperty("Actions")+ private List<TriggerAction> actions;++ @JsonProperty("Predicate")+ private Predicate predicate;++ @JsonProperty("EventBatchingCondition")+ private EventBatchingCondition eventBatchingCondition;++ public Trigger() {}++ public String getName() { return name; }+ public void setName(String name) { this.name = name; }++ public String getWorkflowName() { return workflowName; }+ public void setWorkflowName(String workflowName) { this.workflowName = workflowName; }++ public String getType() { return type; }+ public void setType(String type) { this.type = type; }++ public String getState() { return state; }+ public void setState(String state) { this.state = state; }++ public String getDescription() { return description; }+ public void setDescription(String description) { this.description = description; }++ public String getSchedule() { return schedule; }+ public void setSchedule(String schedule) { this.schedule = schedule; }++ public List<TriggerAction> getActions() { return actions; }+ public void setActions(List<TriggerAction> actions) { this.actions = actions; }++ public Predicate getPredicate() { return predicate; }+ public void setPredicate(Predicate predicate) { this.predicate = predicate; }++ public EventBatchingCondition getEventBatchingCondition() { return eventBatchingCondition; }+ public void setEventBatchingCondition(EventBatchingCondition eventBatchingCondition) { this.eventBatchingCondition = eventBatchingCondition; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/TriggerAction.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/TriggerAction.javanew file mode 100644index 0000000000..389730d76d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/TriggerAction.java@@ -0,0 +1,50 @@+package io.github.hectorvent.floci.services.glue.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.Map;++/** One action of a trigger: start a job run or a crawl. */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public class TriggerAction {+ @JsonProperty("JobName")+ private String jobName;++ @JsonProperty("Arguments")+ private Map<String, String> arguments;++ @JsonProperty("Timeout")+ private Integer timeout;++ @JsonProperty("SecurityConfiguration")+ private String securityConfiguration;++ @JsonProperty("NotificationProperty")+ private NotificationProperty notificationProperty;++ @JsonProperty("CrawlerName")+ private String crawlerName;++ public TriggerAction() {}++ public String getJobName() { return jobName; }+ public void setJobName(String jobName) { this.jobName = jobName; }++ public Map<String, String> getArguments() { return arguments; }+ public void setArguments(Map<String, String> arguments) { this.arguments = arguments; }++ public Integer getTimeout() { return timeout; }+ public void setTimeout(Integer timeout) { this.timeout = timeout; }++ public String getSecurityConfiguration() { return securityConfiguration; }+ public void setSecurityConfiguration(String securityConfiguration) { this.securityConfiguration = securityConfiguration; }++ public NotificationProperty getNotificationProperty() { return notificationProperty; }+ public void setNotificationProperty(NotificationProperty notificationProperty) { this.notificationProperty = notificationProperty; }++ public String getCrawlerName() { return crawlerName; }+ public void setCrawlerName(String crawlerName) { this.crawlerName = crawlerName; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/TriggerCondition.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/TriggerCondition.javanew file mode 100644index 0000000000..764e4ca8e3--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/TriggerCondition.java@@ -0,0 +1,42 @@+package io.github.hectorvent.floci.services.glue.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++/** One condition of a trigger predicate: a job run state or a crawl state. */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public class TriggerCondition {+ @JsonProperty("LogicalOperator")+ private String logicalOperator;++ @JsonProperty("JobName")+ private String jobName;++ @JsonProperty("State")+ private String state;++ @JsonProperty("CrawlerName")+ private String crawlerName;++ @JsonProperty("CrawlState")+ private String crawlState;++ public TriggerCondition() {}++ public String getLogicalOperator() { return logicalOperator; }+ public void setLogicalOperator(String logicalOperator) { this.logicalOperator = logicalOperator; }++ public String getJobName() { return jobName; }+ public void setJobName(String jobName) { this.jobName = jobName; }++ public String getState() { return state; }+ public void setState(String state) { this.state = state; }++ public String getCrawlerName() { return crawlerName; }+ public void setCrawlerName(String crawlerName) { this.crawlerName = crawlerName; }++ public String getCrawlState() { return crawlState; }+ public void setCrawlState(String crawlState) { this.crawlState = crawlState; }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueJobRunServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueJobRunServiceTest.javaindex d7e8f048bf..e75c9e14e0 100644--- a/src/test/java/io/github/hectorvent/floci/services/glue/GlueJobRunServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueJobRunServiceTest.java@@ -61,7 +61,7 @@ class GlueJobRunServiceTest {}private GlueJobRunService service(int runDurationSeconds) {- return new GlueJobRunService(runStore, glueService, runDurationSeconds, clock);+ return new GlueJobRunService(runStore, new InMemoryStorage<>(), glueService, runDurationSeconds, clock);}private Job createJob(String name, Integer maxConcurrentRuns, Integer timeoutMinutes) {@@ -309,7 +309,7 @@ class GlueJobRunServiceTest {void startRacingDeleteNeverLeavesARunBehind() throws Exception {createJob("etl", null, null);PausingStore store = new PausingStore(runStore);- GlueJobRunService service = new GlueJobRunService(store, glueService, 60, clock);+ GlueJobRunService service = new GlueJobRunService(store, new InMemoryStorage<>(), glueService, 60, clock);ExecutorService pool = Executors.newFixedThreadPool(2);try {Future<?> start = pool.submit(() -> service.startJobRun("etl", null, new JobRun()));diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerEmptyListTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerEmptyListTest.javaindex 462d94d4d1..ac519dd348 100644--- a/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerEmptyListTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerEmptyListTest.java@@ -45,9 +45,13 @@ class GlueJsonHandlerEmptyListTest {GlueService glueService = new GlueService(storageFactory, schemaRegistryService, regionResolver,new ResourceGroupsTaggingService(storageFactory), new KmsService(storageFactory, regionResolver));- handler = new GlueJsonHandler(glueService,- new GlueJobRunService(new InMemoryStorage<>(), glueService, 0, Clock.systemUTC()),- new GlueCrawlerRunService(new InMemoryStorage<>(), glueService, 0, Clock.systemUTC()),+ GlueJobRunService jobRunService =+ new GlueJobRunService(new InMemoryStorage<>(), new InMemoryStorage<>(), glueService, 0, Clock.systemUTC());+ GlueCrawlerRunService crawlerRunService =+ new GlueCrawlerRunService(new InMemoryStorage<>(), glueService, 0, Clock.systemUTC());+ handler = new GlueJsonHandler(glueService, jobRunService, crawlerRunService,+ new GlueTriggerService(new InMemoryStorage<>(), glueService,+ jobRunService, crawlerRunService),schemaRegistryService, mapper);}diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerTest.javaindex 9c93db2d33..0f574d5d73 100644--- a/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerTest.java@@ -46,9 +46,13 @@ class GlueJsonHandlerTest {GlueService glueService = new GlueService(storageFactory, schemaRegistryService, regionResolver, new ResourceGroupsTaggingService(storageFactory),new KmsService(storageFactory, regionResolver));- handler = new GlueJsonHandler(glueService,- new GlueJobRunService(new InMemoryStorage<>(), glueService, 0, Clock.systemUTC()),- new GlueCrawlerRunService(new InMemoryStorage<>(), glueService, 0, Clock.systemUTC()),+ GlueJobRunService jobRunService =+ new GlueJobRunService(new InMemoryStorage<>(), new InMemoryStorage<>(), glueService, 0, Clock.systemUTC());+ GlueCrawlerRunService crawlerRunService =+ new GlueCrawlerRunService(new InMemoryStorage<>(), glueService, 0, Clock.systemUTC());+ handler = new GlueJsonHandler(glueService, jobRunService, crawlerRunService,+ new GlueTriggerService(new InMemoryStorage<>(), glueService,+ jobRunService, crawlerRunService),schemaRegistryService, mapper);}@@ -947,4 +951,74 @@ class GlueJsonHandlerTest {assertEquals("READY", got.get("Crawlers").get(0).get("State").asText());assertEquals("absent", got.get("CrawlersNotFound").get(0).asText());}++ /**+ * Trigger CRUD on the wire: Create, Start, Stop and Delete answer with the name, Get and+ * UpdateTrigger with the trigger, and the definition round trips with its predicate.+ */+ @Test+ void triggerOperationsAnswerWithTheDocumentedBodies() throws Exception {+ createJobWithTags("extract", Map.of());+ createJobWithTags("load", Map.of());+ ObjectNode create = mapper.createObjectNode();+ create.put("Name", "after-extract");+ create.put("Type", "CONDITIONAL");+ create.put("StartOnCreation", true);+ create.putArray("Actions").addObject().put("JobName", "load");+ ObjectNode predicate = create.putObject("Predicate");+ predicate.put("Logical", "AND");+ predicate.putArray("Conditions").addObject()+ .put("LogicalOperator", "EQUALS").put("JobName", "extract").put("State", "SUCCEEDED");+ create.putObject("Tags").put("team", "data");++ JsonNode created = mapper.valueToTree(handler.handle("CreateTrigger", create, REGION).getEntity());+ assertEquals("after-extract", created.get("Name").asText());++ ObjectNode byName = mapper.createObjectNode().put("Name", "after-extract");+ JsonNode trigger = mapper.valueToTree(handler.handle("GetTrigger", byName, REGION).getEntity()).get("Trigger");+ assertEquals("CONDITIONAL", trigger.get("Type").asText());+ assertEquals("ACTIVATED", trigger.get("State").asText());+ assertEquals("load", trigger.get("Actions").get(0).get("JobName").asText());+ assertEquals("SUCCEEDED", trigger.get("Predicate").get("Conditions").get(0).get("State").asText());+ assertFalse(trigger.has("Schedule"));++ ObjectNode tags = mapper.createObjectNode();+ tags.put("ResourceArn", "arn:aws:glue:" + REGION + ":" + ACCOUNT_ID + ":trigger/after-extract");+ assertEquals("data", mapper.valueToTree(handler.handle("GetTags", tags, REGION).getEntity())+ .get("Tags").get("team").asText());++ ObjectNode update = mapper.createObjectNode().put("Name", "after-extract");+ update.putObject("TriggerUpdate").put("Description", "load after extract");+ JsonNode updated = mapper.valueToTree(handler.handle("UpdateTrigger", update, REGION).getEntity());+ assertEquals("load after extract", updated.get("Trigger").get("Description").asText());++ assertEquals("after-extract", mapper.valueToTree(+ handler.handle("StopTrigger", byName, REGION).getEntity()).get("Name").asText());+ assertEquals("after-extract", mapper.valueToTree(+ handler.handle("DeleteTrigger", byName, REGION).getEntity()).get("Name").asText());+ JsonNode names = mapper.valueToTree(handler.handle("ListTriggers", mapper.createObjectNode(), REGION).getEntity());+ assertEquals(0, names.get("TriggerNames").size());+ }++ /** A conditional trigger fires within the request that finishes the run it watches. */+ @Test+ void conditionalTriggerFiresAfterTheRequestThatFinishesTheWatchedRun() throws Exception {+ createJobWithTags("extract", Map.of());+ createJobWithTags("load", Map.of());+ ObjectNode create = mapper.createObjectNode();+ create.put("Name", "after-extract");+ create.put("Type", "CONDITIONAL");+ create.put("StartOnCreation", true);+ create.putArray("Actions").addObject().put("JobName", "load");+ create.putObject("Predicate").putArray("Conditions").addObject()+ .put("LogicalOperator", "EQUALS").put("JobName", "extract").put("State", "SUCCEEDED");+ handler.handle("CreateTrigger", create, REGION);++ handler.handle("StartJobRun", mapper.createObjectNode().put("JobName", "extract"), REGION);++ JsonNode runs = mapper.valueToTree(handler.handle(+ "GetJobRuns", mapper.createObjectNode().put("JobName", "load"), REGION).getEntity()).get("JobRuns");+ assertEquals(1, runs.size());+ assertEquals("after-extract", runs.get(0).get("TriggerName").asText());+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.javaindex 41e6277c68..484165bdb2 100644--- a/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java@@ -31,6 +31,7 @@ import io.github.hectorvent.floci.services.glue.model.PartitionIndexDescriptor;import io.github.hectorvent.floci.services.glue.model.S3Target;import io.github.hectorvent.floci.services.glue.model.SchemaReference;import io.github.hectorvent.floci.services.glue.model.SecurityConfiguration;+import io.github.hectorvent.floci.services.glue.model.Trigger;import io.github.hectorvent.floci.services.glue.model.StorageDescriptor;import io.github.hectorvent.floci.services.glue.model.Table;import io.github.hectorvent.floci.services.glue.model.UserDefinedFunction;@@ -110,6 +111,7 @@ class GlueServiceTest {new InMemoryStorage<String, GluePolicy>(),new InMemoryStorage<String, DataCatalogEncryptionSettings>(),new InMemoryStorage<String, SecurityConfiguration>(),+ new InMemoryStorage<String, Trigger>(),schemaRegistryService, regionResolver, new ResourceGroupsTaggingService(null), kmsService);glueService.createDatabase(new Database("db1"));}diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueTriggerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueTriggerIntegrationTest.javanew file mode 100644index 0000000000..7a4051b5d0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueTriggerIntegrationTest.java@@ -0,0 +1,73 @@+package io.github.hectorvent.floci.services.glue;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.ValidatableResponse;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.util.UUID;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasSize;++@QuarkusTest+class GlueTriggerIntegrationTest {++ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";+ private static final String ROLE = "arn:aws:iam::000000000000:role/my-role";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ private static ValidatableResponse call(String action, String body) {+ return given().contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AWSGlue." + action)+ .body(body)+ .when().post("/")+ .then();+ }++ @Test+ void onDemandAndConditionalTriggersStartTheirJobs() {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String extract = "extract-" + suffix;+ String load = "load-" + suffix;+ for (String job : new String[] {extract, load}) {+ call("CreateJob", """+ { "Name": "%s", "Role": "%s", "Command": { "Name": "glueetl" },+ "ExecutionProperty": { "MaxConcurrentRuns": 5 } }+ """.formatted(job, ROLE)).statusCode(200);+ }+ call("CreateTrigger", """+ { "Name": "manual-%s", "Type": "ON_DEMAND", "Actions": [ { "JobName": "%s" } ] }+ """.formatted(suffix, extract)).statusCode(200);+ call("CreateTrigger", """+ { "Name": "chain-%s", "Type": "CONDITIONAL", "StartOnCreation": true,+ "Actions": [ { "JobName": "%s" } ],+ "Predicate": { "Conditions": [+ { "LogicalOperator": "EQUALS", "JobName": "%s", "State": "SUCCEEDED" } ] } }+ """.formatted(suffix, load, extract)).statusCode(200);++ call("StartTrigger", "{ \"Name\": \"manual-" + suffix + "\" }")+ .statusCode(200)+ .body("Name", equalTo("manual-" + suffix));++ call("GetJobRuns", "{ \"JobName\": \"" + extract + "\" }")+ .statusCode(200)+ .body("JobRuns", hasSize(1))+ .body("JobRuns[0].TriggerName", equalTo("manual-" + suffix));+ call("GetJobRuns", "{ \"JobName\": \"" + load + "\" }")+ .statusCode(200)+ .body("JobRuns", hasSize(1))+ .body("JobRuns[0].TriggerName", equalTo("chain-" + suffix));++ call("DeleteTrigger", "{ \"Name\": \"chain-" + suffix + "\" }").statusCode(200);+ call("GetTrigger", "{ \"Name\": \"chain-" + suffix + "\" }")+ .statusCode(400)+ .body("__type", equalTo("EntityNotFoundException"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueTriggerServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueTriggerServiceTest.javanew file mode 100644index 0000000000..71ccb2b855--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueTriggerServiceTest.java@@ -0,0 +1,630 @@+package io.github.hectorvent.floci.services.glue;++import com.fasterxml.jackson.core.type.TypeReference;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.glue.model.Crawler;+import io.github.hectorvent.floci.services.glue.model.CrawlerTargets;+import io.github.hectorvent.floci.services.glue.model.ExecutionProperty;+import io.github.hectorvent.floci.services.glue.model.Job;+import io.github.hectorvent.floci.services.glue.model.JobCommand;+import io.github.hectorvent.floci.services.glue.model.JobRun;+import io.github.hectorvent.floci.services.glue.model.Predicate;+import io.github.hectorvent.floci.services.glue.model.S3Target;+import io.github.hectorvent.floci.services.glue.model.Trigger;+import io.github.hectorvent.floci.services.glue.model.TriggerAction;+import io.github.hectorvent.floci.services.glue.model.TriggerCondition;+import io.github.hectorvent.floci.services.glue.schemaregistry.GlueSchemaRegistryService;+import io.github.hectorvent.floci.services.kms.KmsService;+import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingService;+import io.github.hectorvent.floci.testing.MutableClock;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.time.Clock;+import java.time.Duration;+import java.time.Instant;+import java.time.ZoneOffset;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++class GlueTriggerServiceTest {++ private static final String REGION = "us-east-1";+ private static final String ACCOUNT_ID = "000000000000";+ private static final String ROLE = "arn:aws:iam::000000000000:role/glue";++ private GlueService glueService;+ private GlueJobRunService jobRuns;+ private GlueCrawlerRunService crawls;+ private GlueTriggerService triggers;++ @BeforeEach+ void setUp() {+ RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT_ID);+ StorageFactory storageFactory = new InMemoryStorageFactory();+ glueService = new GlueService(storageFactory, new GlueSchemaRegistryService(storageFactory, regionResolver),+ regionResolver, new ResourceGroupsTaggingService(storageFactory),+ new KmsService(storageFactory, regionResolver));+ jobRuns = new GlueJobRunService(new InMemoryStorage<>(), new InMemoryStorage<>(), glueService, 0, Clock.systemUTC());+ crawls = new GlueCrawlerRunService(new InMemoryStorage<>(), glueService, 0, Clock.systemUTC());+ triggers = new GlueTriggerService(new InMemoryStorage<>(), glueService, jobRuns, crawls);+ for (String job : List.of("extract", "load", "report")) {+ createJob(job);+ }+ Crawler crawler = new Crawler();+ crawler.setName("raw");+ crawler.setRole(ROLE);+ S3Target target = new S3Target();+ target.setPath("s3://raw/data");+ CrawlerTargets targets = new CrawlerTargets();+ targets.setS3Targets(List.of(target));+ crawler.setTargets(targets);+ glueService.createCrawler(crawler, null, REGION);+ }++ private void createJob(String name) {+ Job job = new Job();+ job.setName(name);+ job.setRole(ROLE);+ job.setCommand(new JobCommand());+ ExecutionProperty property = new ExecutionProperty();+ property.setMaxConcurrentRuns(100);+ job.setExecutionProperty(property);+ glueService.createJob(job, null, REGION);+ }++ private static TriggerAction startJob(String job) {+ TriggerAction action = new TriggerAction();+ action.setJobName(job);+ return action;+ }++ private static TriggerCondition jobIs(String job, String state) {+ TriggerCondition condition = new TriggerCondition();+ condition.setLogicalOperator("EQUALS");+ condition.setJobName(job);+ condition.setState(state);+ return condition;+ }++ private static TriggerCondition crawlIs(String crawler, String state) {+ TriggerCondition condition = new TriggerCondition();+ condition.setLogicalOperator("EQUALS");+ condition.setCrawlerName(crawler);+ condition.setCrawlState(state);+ return condition;+ }++ private static Trigger trigger(String name, String type, List<TriggerAction> actions) {+ Trigger trigger = new Trigger();+ trigger.setName(name);+ trigger.setType(type);+ trigger.setActions(actions);+ return trigger;+ }++ private static Trigger conditional(String name, String logical, List<TriggerCondition> conditions,+ String startsJob) {+ Trigger trigger = trigger(name, "CONDITIONAL", List.of(startJob(startsJob)));+ Predicate predicate = new Predicate();+ predicate.setLogical(logical);+ predicate.setConditions(conditions);+ trigger.setPredicate(predicate);+ return trigger;+ }++ private List<JobRun> runsOf(String job) {+ return jobRuns.getJobRuns(job, 200, null).items();+ }++ /** Keeps evaluating, as later run-related requests would, until nothing more fires. */+ private void settleEverything() {+ for (int request = 0; request < 20; request++) {+ triggers.fireConditionalTriggers();+ }+ }++ private String startAndSettle(String job) {+ String runId = jobRuns.startJobRun(job, null, new JobRun()).getId();+ triggers.fireConditionalTriggers();+ return runId;+ }++ @Test+ void definitionsAreValidatedAgainstTheApiRules() {+ assertEquals("InvalidInputException", assertThrows(AwsException.class, () ->+ triggers.createTrigger(trigger("t", "ON_DEMAND", List.of()), false, null, REGION)).getErrorCode());+ assertEquals("EntityNotFoundException", assertThrows(AwsException.class, () -> triggers.createTrigger(+ trigger("t", "ON_DEMAND", List.of(startJob("missing"))), false, null, REGION)).getErrorCode());+ TriggerAction both = startJob("load");+ both.setCrawlerName("raw");+ assertEquals("InvalidInputException", assertThrows(AwsException.class, () ->+ triggers.createTrigger(trigger("t", "ON_DEMAND", List.of(both)), false, null, REGION)).getErrorCode());+ assertEquals("InvalidInputException", assertThrows(AwsException.class, () -> triggers.createTrigger(+ trigger("t", "SCHEDULED", List.of(startJob("load"))), false, null, REGION)).getErrorCode());+ assertEquals("InvalidInputException", assertThrows(AwsException.class, () -> triggers.createTrigger(+ trigger("t", "CONDITIONAL", List.of(startJob("load"))), false, null, REGION)).getErrorCode());+ assertEquals("InvalidInputException", assertThrows(AwsException.class, () -> triggers.createTrigger(+ conditional("t", null, List.of(jobIs("extract", "RUNNING")), "load"), false, null, REGION))+ .getErrorCode());+ assertEquals("InvalidInputException", assertThrows(AwsException.class, () -> triggers.createTrigger(+ trigger("t", "ON_DEMAND", List.of(startJob("load"))), true, null, REGION)).getErrorCode());+ Trigger inWorkflow = trigger("t", "ON_DEMAND", List.of(startJob("load")));+ inWorkflow.setWorkflowName("pipeline");+ assertEquals("EntityNotFoundException", assertThrows(AwsException.class, () ->+ triggers.createTrigger(inWorkflow, false, null, REGION)).getErrorCode());++ triggers.createTrigger(trigger("t", "ON_DEMAND", List.of(startJob("load"))), false, null, REGION);+ assertEquals("AlreadyExistsException", assertThrows(AwsException.class, () -> triggers.createTrigger(+ trigger("t", "ON_DEMAND", List.of(startJob("load"))), false, null, REGION)).getErrorCode());+ }++ @Test+ void stateFollowsCreationStartAndStop() {+ Trigger nightly = trigger("nightly", "SCHEDULED", List.of(startJob("load")));+ nightly.setSchedule("cron(0 2 * * ? *)");+ triggers.createTrigger(nightly, false, null, REGION);+ assertEquals("CREATED", glueService.getTrigger("nightly").getState());++ triggers.startTrigger("nightly");+ assertEquals("ACTIVATED", glueService.getTrigger("nightly").getState());+ triggers.stopTrigger("nightly");+ assertEquals("DEACTIVATED", glueService.getTrigger("nightly").getState());++ triggers.createTrigger(conditional("after", null, List.of(jobIs("extract", "SUCCEEDED")), "load"),+ true, null, REGION);+ assertEquals("ACTIVATED", glueService.getTrigger("after").getState());++ triggers.createTrigger(trigger("manual", "ON_DEMAND", List.of(startJob("load"))), false, null, REGION);+ assertEquals("InvalidInputException",+ assertThrows(AwsException.class, () -> triggers.stopTrigger("manual")).getErrorCode());+ }++ @Test+ void startingAnOnDemandTriggerRunsItsActions() {+ TriggerAction load = startJob("load");+ load.setArguments(Map.of("--mode", "full"));+ TriggerAction crawl = new TriggerAction();+ crawl.setCrawlerName("raw");+ triggers.createTrigger(trigger("manual", "ON_DEMAND", List.of(load, crawl)), false, null, REGION);++ triggers.startTrigger("manual");++ JobRun run = runsOf("load").getFirst();+ assertEquals("manual", run.getTriggerName());+ assertEquals(Map.of("--mode", "full"), run.getArguments());+ assertEquals("SUCCEEDED", crawls.completionsAfter("raw", null).getLast().state());+ assertEquals("CREATED", glueService.getTrigger("manual").getState());+ }++ @Test+ void conditionalTriggerFiresOnceWhenTheWatchedJobSucceeds() {+ triggers.createTrigger(conditional("after", null, List.of(jobIs("extract", "SUCCEEDED")), "load"),+ true, null, REGION);++ startAndSettle("extract");+ triggers.fireConditionalTriggers();++ assertEquals(1, runsOf("load").size());+ assertEquals("after", runsOf("load").getFirst().getTriggerName());+ }++ @Test+ void runsFinishedBeforeActivationDoNotFire() {+ startAndSettle("extract");+ triggers.createTrigger(conditional("after", null, List.of(jobIs("extract", "SUCCEEDED")), "load"),+ false, null, REGION);++ triggers.startTrigger("after");+ triggers.fireConditionalTriggers();++ assertTrue(runsOf("load").isEmpty());+ }++ @Test+ void conditionOnAnotherStateDoesNotFire() {+ triggers.createTrigger(conditional("onFailure", null, List.of(jobIs("extract", "FAILED")), "report"),+ true, null, REGION);++ startAndSettle("extract");++ assertTrue(runsOf("report").isEmpty());+ }++ @Test+ void andWaitsForEveryConditionWhileAnyFiresOnTheFirst() {+ List<TriggerCondition> conditions = List.of(jobIs("extract", "SUCCEEDED"), crawlIs("raw", "SUCCEEDED"));+ triggers.createTrigger(conditional("both", "AND", conditions, "load"), true, null, REGION);+ triggers.createTrigger(conditional("either", "ANY", conditions, "report"), true, null, REGION);++ startAndSettle("extract");+ assertTrue(runsOf("load").isEmpty());+ assertEquals(1, runsOf("report").size());++ crawls.startCrawler("raw");+ triggers.fireConditionalTriggers();+ assertEquals(1, runsOf("load").size());+ assertEquals(2, runsOf("report").size());+ }++ @Test+ void chainedTriggersRunTheWholePipelineInOneRequest() {+ triggers.createTrigger(conditional("step1", null, List.of(jobIs("extract", "SUCCEEDED")), "load"),+ true, null, REGION);+ triggers.createTrigger(conditional("step2", null, List.of(jobIs("load", "SUCCEEDED")), "report"),+ true, null, REGION);++ startAndSettle("extract");++ assertEquals(1, runsOf("load").size());+ assertEquals(1, runsOf("report").size());+ assertEquals("step2", runsOf("report").getFirst().getTriggerName());+ }++ @Test+ void aTriggerThatRestartsItsOwnJobStopsAtTheRunBudget() {+ triggers.createTrigger(conditional("loop", null, List.of(jobIs("extract", "SUCCEEDED")), "extract"),+ true, null, REGION);++ startAndSettle("extract");+ assertEquals(26, runsOf("extract").size());+ settleEverything();++ assertEquals(1 + GlueTriggerService.MAX_TRIGGERED_RUNS_PER_ORIGIN, runsOf("extract").size());+ assertEquals("ACTIVATED", glueService.getTrigger("loop").getState());+ }++ @Test+ void aTwoTriggerCycleStopsAtTheRunBudget() {+ triggers.createTrigger(conditional("forth", null, List.of(jobIs("extract", "SUCCEEDED")), "load"),+ true, null, REGION);+ triggers.createTrigger(conditional("back", null, List.of(jobIs("load", "SUCCEEDED")), "extract"),+ true, null, REGION);++ startAndSettle("extract");+ settleEverything();++ assertEquals(1 + GlueTriggerService.MAX_TRIGGERED_RUNS_PER_ORIGIN, runsOf("extract").size() + runsOf("load").size());+ assertEquals("ACTIVATED", glueService.getTrigger("forth").getState());+ assertEquals("ACTIVATED", glueService.getTrigger("back").getState());+ }++ /** Two actions restarting the watched job double the runs each hop; the budget bounds runs, not hops. */+ @Test+ void aBranchingLoopStopsAtTheRunBudget() {+ Trigger branching = conditional("branch", null, List.of(jobIs("extract", "SUCCEEDED")), "extract");+ branching.setActions(List.of(startJob("extract"), startJob("extract")));+ triggers.createTrigger(branching, true, null, REGION);++ startAndSettle("extract");+ settleEverything();++ assertEquals(1 + GlueTriggerService.MAX_TRIGGERED_RUNS_PER_ORIGIN, runsOf("extract").size());+ }++ /** Every crawl has its own id, so a crawler deleted and created again never inherits old bookkeeping. */+ @Test+ void aRecreatedCrawlerStartsANewChainWithItsOwnBudget() {+ triggers.createTrigger(conditional("each", "ANY", List.of(crawlIs("raw", "SUCCEEDED")), "load"),+ true, null, REGION);+ String first = crawls.startCrawler("raw");+ triggers.fireConditionalTriggers();++ triggers.deleteTrigger("each", REGION);+ crawls.deleteCrawler("raw", REGION);+ Crawler again = new Crawler();+ again.setName("raw");+ again.setRole(ROLE);+ S3Target target = new S3Target();+ target.setPath("s3://raw/data");+ CrawlerTargets targets = new CrawlerTargets();+ targets.setS3Targets(List.of(target));+ again.setTargets(targets);+ glueService.createCrawler(again, null, REGION);+ triggers.createTrigger(conditional("each", "ANY", List.of(crawlIs("raw", "SUCCEEDED")), "load"),+ true, null, REGION);+ String second = crawls.startCrawler("raw");+ triggers.fireConditionalTriggers();++ assertTrue(!first.equals(second), first + " was reused");+ assertEquals(2, runsOf("load").size());+ }++ /**+ * A ring longer than the rounds one request runs: names sort against the ring order so each round+ * advances one link, and the loop still has to stop across requests.+ */+ @Test+ void aTriggerRingLongerThanOneRequestStopsAtTheRunBudget() {+ int size = 26;+ for (int i = 0; i < size; i++) {+ createJob("ring" + i);+ }+ for (int i = 0; i < size; i++) {+ triggers.createTrigger(conditional("hop" + (100 - i), null, List.of(jobIs("ring" + i, "SUCCEEDED")),+ "ring" + ((i + 1) % size)), true, null, REGION);+ }++ startAndSettle("ring0");+ settleEverything();++ int total = 0;+ for (int i = 0; i < size; i++) {+ total += runsOf("ring" + i).size();+ }+ assertEquals(1 + GlueTriggerService.MAX_TRIGGERED_RUNS_PER_ORIGIN, total);+ }++ /**+ * Trigger names sorting against the chain order make every round advance one link only; a chain+ * longer than the round limit must keep its triggers and finish on the next evaluation.+ */+ @Test+ void aChainLongerThanTheRoundLimitIsNotDeactivated() {+ int links = 30;+ for (int i = 1; i <= links; i++) {+ createJob("step" + i);+ }+ for (int i = 0; i < links; i++) {+ String watched = i == 0 ? "extract" : "step" + i;+ triggers.createTrigger(conditional("link" + (100 - i), null, List.of(jobIs(watched, "SUCCEEDED")),+ "step" + (i + 1)), true, null, REGION);+ }++ startAndSettle("extract");+ assertTrue(runsOf("step" + links).isEmpty());+ triggers.fireConditionalTriggers();++ assertEquals(1, runsOf("step" + links).size());+ for (Trigger trigger : glueService.allTriggers()) {+ assertEquals("ACTIVATED", trigger.getState(), trigger.getName());+ }+ }++ /** A trigger fed by two branches fires in two rounds without being part of any cycle. */+ @Test+ void aFanInTriggerFiringInSeveralRoundsOfALongPipelineStaysActive() {+ int links = 30;+ for (int i = 1; i <= links; i++) {+ createJob("step" + i);+ }+ for (int i = 0; i < links; i++) {+ String watched = i == 0 ? "extract" : "step" + i;+ triggers.createTrigger(conditional("link" + (100 - i), null, List.of(jobIs(watched, "SUCCEEDED")),+ "step" + (i + 1)), true, null, REGION);+ }+ triggers.createTrigger(conditional("sink", "ANY",+ List.of(jobIs("step2", "SUCCEEDED"), jobIs("step20", "SUCCEEDED")), "report"), true, null, REGION);++ startAndSettle("extract");+ triggers.fireConditionalTriggers();++ assertEquals("ACTIVATED", glueService.getTrigger("sink").getState());+ assertEquals(2, runsOf("report").size());+ assertEquals(1, runsOf("step" + links).size());+ }++ /**+ * forward watches step5 succeed and starts phase; back watches phase fail and starts step5. The+ * definitions form a loop, but phase runs succeed, so back never fires and nothing repeats: forward+ * must stay active even when a long pipeline reaches the round limit.+ */+ @Test+ void aCycleThatNeverRunsDeactivatesNothing() {+ int links = 30;+ for (int i = 1; i <= links; i++) {+ createJob("step" + i);+ }+ createJob("phase");+ for (int i = 0; i < links; i++) {+ String watched = i == 0 ? "extract" : "step" + i;+ triggers.createTrigger(conditional("link" + (100 - i), null, List.of(jobIs(watched, "SUCCEEDED")),+ "step" + (i + 1)), true, null, REGION);+ }+ triggers.createTrigger(conditional("forward", null, List.of(jobIs("step5", "SUCCEEDED")), "phase"),+ true, null, REGION);+ triggers.createTrigger(conditional("back", null, List.of(jobIs("phase", "FAILED")), "step5"),+ true, null, REGION);++ startAndSettle("extract");+ triggers.fireConditionalTriggers();++ assertEquals(1, runsOf("step" + links).size());+ assertEquals(1, runsOf("phase").size());+ assertEquals("ACTIVATED", glueService.getTrigger("forward").getState());+ assertEquals("ACTIVATED", glueService.getTrigger("back").getState());+ }++ @Test+ void updatingOrRestartingAnActiveTriggerKeepsCompletionsItHasNotEvaluated() {+ triggers.createTrigger(conditional("after", "ANY", List.of(crawlIs("raw", "SUCCEEDED")), "load"),+ true, null, REGION);+ crawls.startCrawler("raw");+ Trigger update = new Trigger();+ update.setDescription("changed");+ triggers.updateTrigger("after", update);+ triggers.fireConditionalTriggers();+ assertEquals(1, runsOf("load").size());++ crawls.startCrawler("raw");+ triggers.startTrigger("after");+ triggers.fireConditionalTriggers();+ assertEquals(2, runsOf("load").size());+ }++ @Test+ void aRejectedUpdateLeavesTheStoredTriggerUnchanged() {+ triggers.createTrigger(trigger("manual", "ON_DEMAND", List.of(startJob("load"))), false, null, REGION);+ Trigger update = new Trigger();+ update.setDescription("changed");+ update.setActions(List.of(startJob("missing")));++ assertThrows(AwsException.class, () -> triggers.updateTrigger("manual", update));++ Trigger stored = glueService.getTrigger("manual");+ assertNull(stored.getDescription());+ assertEquals("load", stored.getActions().getFirst().getJobName());+ }++ @Test+ void conditionWithoutAStateIsAnInputError() {+ TriggerCondition noState = jobIs("extract", null);+ TriggerCondition noCrawlState = crawlIs("raw", null);++ for (TriggerCondition condition : List.of(noState, noCrawlState)) {+ assertEquals("InvalidInputException", assertThrows(AwsException.class, () -> triggers.createTrigger(+ conditional("t", null, List.of(condition), "load"), false, null, REGION)).getErrorCode());+ }+ }++ @Test+ void aSuccessIsNotLostWhenALaterRunOfTheSameJobIsStoppedFirst() {+ MutableClock clock = new MutableClock();+ GlueJobRunService slowRuns = new GlueJobRunService(new InMemoryStorage<>(), new InMemoryStorage<>(), glueService, 60, clock);+ GlueTriggerService slowTriggers = new GlueTriggerService(new InMemoryStorage<>(), glueService, slowRuns, crawls);+ slowTriggers.createTrigger(conditional("after", null, List.of(jobIs("extract", "SUCCEEDED")), "load"),+ true, null, REGION);+ slowRuns.startJobRun("extract", null, new JobRun());+ clock.advance(Duration.ofSeconds(10));+ String second = slowRuns.startJobRun("extract", null, new JobRun()).getId();++ clock.advance(Duration.ofSeconds(55));+ slowRuns.batchStopJobRun("extract", List.of(second));+ slowTriggers.fireConditionalTriggers();++ assertEquals(1, slowRuns.getJobRuns("load", null, null).items().size());+ }++ @Test+ void jobRunsFinishingInTheSameClockTickEachCount() {+ Clock frozen = Clock.fixed(Instant.parse("2026-09-25T12:00:00Z"), ZoneOffset.UTC);+ GlueJobRunService frozenRuns =+ new GlueJobRunService(new InMemoryStorage<>(), new InMemoryStorage<>(), glueService, 0, frozen);+ GlueTriggerService frozenTriggers = new GlueTriggerService(new InMemoryStorage<>(), glueService, frozenRuns, crawls);+ frozenTriggers.createTrigger(conditional("each", "ANY", List.of(jobIs("extract", "SUCCEEDED")), "load"),+ true, null, REGION);++ for (int i = 0; i < 5; i++) {+ frozenRuns.startJobRun("extract", null, new JobRun());+ frozenTriggers.fireConditionalTriggers();+ }++ assertEquals(5, frozenRuns.getJobRuns("load", null, null).items().size());+ }++ @Test+ void crawlsFinishingInTheSameClockTickEachCount() {+ Clock frozen = Clock.fixed(Instant.parse("2026-09-25T12:00:00Z"), ZoneOffset.UTC);+ GlueCrawlerRunService frozenCrawls = new GlueCrawlerRunService(new InMemoryStorage<>(), glueService, 0, frozen);+ GlueTriggerService frozenTriggers =+ new GlueTriggerService(new InMemoryStorage<>(), glueService, jobRuns, frozenCrawls);+ frozenTriggers.createTrigger(conditional("each", "ANY", List.of(crawlIs("raw", "SUCCEEDED")), "load"),+ true, null, REGION);++ frozenCrawls.startCrawler("raw");+ frozenCrawls.startCrawler("raw");+ frozenTriggers.fireConditionalTriggers();++ assertEquals(2, runsOf("load").size());+ }++ @Test+ void deactivatedTriggersDoNotFire() {+ triggers.createTrigger(conditional("after", null, List.of(jobIs("extract", "SUCCEEDED")), "load"),+ true, null, REGION);+ triggers.stopTrigger("after");++ startAndSettle("extract");++ assertTrue(runsOf("load").isEmpty());+ }++ @Test+ void updateMergesTheGivenMembersAndDeleteIsIdempotent() {+ triggers.createTrigger(conditional("after", null, List.of(jobIs("extract", "SUCCEEDED")), "load"),+ true, null, REGION);+ Trigger update = new Trigger();+ update.setDescription("nightly load");+ update.setActions(List.of(startJob("report")));++ Trigger updated = triggers.updateTrigger("after", update);++ assertEquals("nightly load", updated.getDescription());+ assertEquals("report", updated.getActions().getFirst().getJobName());+ assertEquals("ACTIVATED", updated.getState());+ assertEquals("extract", updated.getPredicate().getConditions().getFirst().getJobName());++ triggers.deleteTrigger("after", REGION);+ triggers.deleteTrigger("after", REGION);+ assertEquals("EntityNotFoundException",+ assertThrows(AwsException.class, () -> glueService.getTrigger("after")).getErrorCode());+ }++ @Test+ void dependentJobNameReturnsTheTriggersThatStartTheJobOrElseAll() {+ triggers.createTrigger(trigger("loads", "ON_DEMAND", List.of(startJob("load"))), false, null, REGION);+ triggers.createTrigger(trigger("reports", "ON_DEMAND", List.of(startJob("report"))), false, null, REGION);++ assertEquals(List.of("loads"), glueService.getTriggers("load", null, null).items().stream()+ .map(Trigger::getName).toList());+ assertEquals(2, glueService.getTriggers("extract", null, null).items().size());+ assertEquals("EntityNotFoundException", assertThrows(AwsException.class,+ () -> glueService.getTriggers("missing", null, null)).getErrorCode());+ }++ @Test+ void concurrentEvaluationsFireATriggerOncePerCompletion() throws Exception {+ triggers.createTrigger(conditional("after", null, List.of(jobIs("extract", "SUCCEEDED")), "load"),+ true, null, REGION);+ jobRuns.startJobRun("extract", null, new JobRun());+ int threads = 8;+ CountDownLatch go = new CountDownLatch(1);+ ExecutorService pool = Executors.newFixedThreadPool(threads);+ try {+ List<Future<?>> futures = new ArrayList<>();+ for (int i = 0; i < threads; i++) {+ futures.add(pool.submit(() -> {+ go.await();+ triggers.fireConditionalTriggers();+ return null;+ }));+ }+ go.countDown();+ for (Future<?> future : futures) {+ future.get(10, TimeUnit.SECONDS);+ }+ } finally {+ pool.shutdownNow();+ }++ assertEquals(1, runsOf("load").size());+ }++ private static final class InMemoryStorageFactory extends StorageFactory {+ private InMemoryStorageFactory() {+ super(null, null);+ }++ @Override+ public <V> AccountAwareStorageBackend<V> create(String serviceName,+ String fileName,+ TypeReference<Map<String, V>> typeReference) {+ return AccountAwareStorageBackend.inMemory(ACCOUNT_ID);+ }+ }+}