Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(emr): publish aws.emr cluster and step events to EventBridge (#6403)

Priamo Germosen1174922522d5
diff --git a/docs/services/emr.md b/docs/services/emr.md
index 2b697d7ee0..8790784736 100644
--- a/docs/services/emr.md
+++ b/docs/services/emr.md
@@ -55,8 +55,9 @@ Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job
## Cluster lifecycle
-Steps complete immediately in this metadata-only emulator. A cluster created with
-`Instances.KeepJobFlowAliveWhenNoSteps` set to `false` terminates after its initial steps or
+Steps complete immediately in this metadata-only emulator, in the order the Management Guide gives:
+a request's steps are all created `PENDING`, then each completes before the next starts. A cluster
+created with `Instances.KeepJobFlowAliveWhenNoSteps` set to `false` terminates after its initial steps or
steps added later complete, reporting `ALL_STEPS_COMPLETED`. A cluster with no steps remains
`WAITING` until steps are added. Set `KeepJobFlowAliveWhenNoSteps` to `true` to keep the cluster
`WAITING` after its steps complete. Automatic step-completion termination also applies when
@@ -84,6 +85,39 @@ still accepted.
A state machine drives clusters and steps through the `elasticmapreduce:` integrations, `.sync`
included; see [Step Functions: Amazon EMR tasks](step-functions.md#amazon-emr-tasks).
+## EventBridge events
+
+Every state a cluster or a step enters is sent to the default EventBridge bus of its Region, in the
+account that made the call, as AWS sends it: source `aws.emr`, detail type `EMR Cluster State Change`
+or `EMR Step Status Change`, an empty `resources`, and the detail of the EMR Management Guide's
+examples. A cluster's detail holds `severity`, `stateChangeReason`, `name`, `clusterId`, `state` and
+`message`; a step's holds `severity`, `actionOnFailure`, `stepId`, `name`, `clusterId`, `state` and
+`message`. The severity and message are the ones the guide's "Monitoring Amazon EMR events" tables
+give each state, with times to the minute (`2026-10-24 09:41 UTC`).
+
+Since steps complete at once, each call sends:
+
+| Call | Events, in order |
+|---|---|
+| `RunJobFlow` | the cluster `STARTING`; each step `PENDING`, then each `COMPLETED`; then the cluster `WAITING`, or `TERMINATED` with `ALL_STEPS_COMPLETED` when it ends after its steps |
+| `AddJobFlowSteps` | each step `PENDING`, then each `COMPLETED`; then the cluster `TERMINATED` with `ALL_STEPS_COMPLETED` when it ends after them |
+| `TerminateJobFlows` | `TERMINATED` with `USER_REQUEST` for each cluster it ends, also when a protected cluster fails the call |
+| `CancelSteps` | `CANCELLED` for each step it cancels, none while steps complete at once |
+
+A `STARTING` or `WAITING` cluster's `stateChangeReason` is `{"code":""}`, as in the guide's example,
+and a `TERMINATED` one's carries the reason's code and message, such as
+`{"code":"USER_REQUEST","message":"Terminated by user request"}`. `TERMINATED` is `INFO` for
+`USER_REQUEST` and `ALL_STEPS_COMPLETED` and `CRITICAL` for any other reason; a cancelled step is
+`WARN`. The tables have no row for a cluster's `BOOTSTRAPPING`, `RUNNING` or `TERMINATING`, which
+send nothing. A step is never seen `RUNNING`, and a `WAITING` cluster that runs added steps stays
+`WAITING`, so neither sends an event for it. The guide gives two `WAITING` messages without saying
+when each applies: a cluster that ran steps reports it "finished running all pending steps", one that
+did not that it "was created ... and is ready for use".
+
+Events go out in the order their changes were made, once the call that made them no longer holds the
+cluster. A rule's target that calls EMR while an event is delivered, such as one ending the cluster on
+its `STARTING` event, has its events sent after the rest of that call's.
+
## Release catalogue
`ListReleaseLabels`, `DescribeReleaseLabel` and `ListSupportedInstanceTypes` read a curated catalogue,
diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/EmrEventPublisher.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrEventPublisher.java
new file mode 100644
index 0000000000..7902a1642e
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrEventPublisher.java
@@ -0,0 +1,166 @@
+package io.github.hectorvent.floci.services.emr;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.RequestScopes;
+import io.github.hectorvent.floci.services.emr.model.EmrCluster;
+import io.github.hectorvent.floci.services.emr.model.EmrStep;
+import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.Queue;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * The {@code aws.emr} events AWS sends to the default EventBridge bus as a cluster or a step changes
+ * state, "EMR Cluster State Change" and "EMR Step Status Change": the detail of the Management Guide's
+ * examples, with the severity and message its "Monitoring Amazon EMR events" tables give each state.
+ * {@link EmrService} queues an event while it holds the cluster and publishes the queue once it does
+ * not, so a rule's target that calls EMR never waits on the call that made the change, and events go
+ * out in the order their changes were made.
+ */
+@ApplicationScoped
+public class EmrEventPublisher {
+
+ static final String SOURCE = "aws.emr";
+ static final String CLUSTER_STATE_CHANGE = "EMR Cluster State Change";
+ static final String STEP_STATUS_CHANGE = "EMR Step Status Change";
+ // The guide's examples, and an event recorded from AWS, write times to the minute: "at 2016-12-16 21:00 UTC".
+ private static final DateTimeFormatter TIME =
+ DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'").withZone(ZoneOffset.UTC);
+ // The termination reasons the table reports as INFO; it reports every other one as CRITICAL.
+ private static final Set<String> ROUTINE_TERMINATIONS = Set.of("USER_REQUEST", "ALL_STEPS_COMPLETED");
+
+ /** One event, its detail written while the cluster was held. */
+ public record Event(String detailType, String detail) {}
+
+ /** A queued event, with the Region and account of the call that made the change. */
+ private record Queued(Event event, String region, String accountId) {}
+
+ private final EventBridgeService eventBridgeService;
+ private final ObjectMapper objectMapper;
+ private final RegionResolver regionResolver;
+ private final Queue<Queued> queued = new ConcurrentLinkedQueue<>();
+ private final AtomicBoolean publishing = new AtomicBoolean();
+
+ @Inject
+ public EmrEventPublisher(EventBridgeService eventBridgeService, ObjectMapper objectMapper,
+ RegionResolver regionResolver) {
+ this.eventBridgeService = eventBridgeService;
+ this.objectMapper = objectMapper;
+ this.regionResolver = regionResolver;
+ }
+
+ /** {@code cluster} entering {@code state}: STARTING, WAITING or TERMINATED. */
+ Event clusterStateChange(EmrCluster cluster, String state) {
+ boolean terminated = "TERMINATED".equals(state);
+ String code = cluster.getStateChangeReasonCode();
+ // The examples' reason is a JSON string: {"code":""} for a WAITING cluster, and the reason's code
+ // and message for a TERMINATED one.
+ ObjectNode reason = objectMapper.createObjectNode().put("code", terminated && code != null ? code : "");
+ if (terminated && cluster.getStateChangeMessage() != null) {
+ reason.put("message", cluster.getStateChangeMessage());
+ }
+ ObjectNode detail = objectMapper.createObjectNode();
+ boolean routine = code != null && ROUTINE_TERMINATIONS.contains(code);
+ detail.put("severity", terminated && !routine ? "CRITICAL" : "INFO");
+ detail.put("stateChangeReason", reason.toString());
+ detail.put("name", cluster.getName());
+ detail.put("clusterId", cluster.getId());
+ detail.put("state", state);
+ detail.put("message", clusterMessage(cluster, state));
+ return new Event(CLUSTER_STATE_CHANGE, detail.toString());
+ }
+
+ /** {@code step} of {@code cluster} entering {@code state}: PENDING, COMPLETED or CANCELLED. */
+ Event stepStatusChange(EmrCluster cluster, EmrStep step, String state) {
+ ObjectNode detail = objectMapper.createObjectNode();
+ detail.put("severity", "CANCELLED".equals(state) ? "WARN" : "INFO");
+ detail.put("actionOnFailure", step.getActionOnFailure());
+ detail.put("stepId", step.getId());
+ detail.put("name", step.getName());
+ detail.put("clusterId", cluster.getId());
+ detail.put("state", state);
+ detail.put("message", stepMessage(cluster, step, state));
+ return new Event(STEP_STATUS_CHANGE, detail.toString());
+ }
+
+ /**
+ * Queues {@code event} for {@code region}'s default bus in the calling account. {@link EmrService}
+ * queues while it holds the cluster, so the queue keeps the order the changes were made in.
+ */
+ void queue(Event event, String region) {
+ queued.add(new Queued(event, region, regionResolver.getAccountId()));
+ }
+
+ /**
+ * Publishes the queued events in order, naming no resources, as the examples do; called once the
+ * caller no longer holds the cluster. One call publishes at a time: a call made while an event is
+ * delivered, such as a rule's target calling EMR back, on this thread or another, leaves its events
+ * queued behind the rest and returns, and the call already publishing sends them after.
+ */
+ void publishQueued() {
+ while (!queued.isEmpty() && publishing.compareAndSet(false, true)) {
+ try {
+ Queued next;
+ while ((next = queued.poll()) != null) {
+ publish(next);
+ }
+ } finally {
+ publishing.set(false);
+ }
+ }
+ }
+
+ private void publish(Queued queued) {
+ // In the account and Region of the call that queued it, whichever call's thread publishes it.
+ RequestScopes.runAs(queued.accountId(), queued.region(), () -> eventBridgeService.publishServiceEvent(
+ SOURCE, queued.event().detailType(), queued.event().detail(), null, queued.region()));
+ }
+
+ private static String clusterMessage(EmrCluster cluster, String state) {
+ String named = cluster.getId() + " (" + cluster.getName() + ")";
+ return switch (state) {
+ case "STARTING" -> "Amazon EMR cluster " + named + " was requested at "
+ + time(cluster.getCreationDateTime()) + " and is being created.";
+ case "WAITING" -> cluster.getSteps().isEmpty()
+ ? "Amazon EMR cluster " + named + " was created at " + time(cluster.getReadyDateTime())
+ + " and is ready for use."
+ : "Amazon EMR cluster " + named + " finished running all pending steps at "
+ + time(cluster.getReadyDateTime()) + ".";
+ case "TERMINATED" -> "Amazon EMR Cluster " + named + " has terminated at " + time(cluster.getEndDateTime())
+ + " with a reason of " + cluster.getStateChangeReasonCode() + ".";
+ default -> throw new IllegalArgumentException("No cluster event for state " + state);
+ };
+ }
+
+ private static String stepMessage(EmrCluster cluster, EmrStep step, String state) {
+ String stepNamed = step.getId() + " (" + step.getName() + ")";
+ String clusterNamed = cluster.getId() + " (" + cluster.getName() + ")";
+ return switch (state) {
+ case "PENDING" -> "Step " + stepNamed + " was added to Amazon EMR cluster " + clusterNamed + " at "
+ + time(step.getCreationDateTime()) + " and is pending execution.";
+ case "COMPLETED" -> "Step " + stepNamed + " in Amazon EMR cluster " + clusterNamed
+ + " completed execution at " + time(step.getEndDateTime()) + ". The step started running at "
+ + time(step.getStartDateTime())
+ + " and took " + Duration.between(step.getStartDateTime(), step.getEndDateTime()).toMinutes()
+ + " minutes to complete.";
+ case "CANCELLED" -> "Cancellation request has succeeded for cluster step " + stepNamed
+ + " in Amazon EMR cluster " + clusterNamed + " at " + time(step.getEndDateTime())
+ + ", and the step is now cancelled.";
+ default -> throw new IllegalArgumentException("No step event for state " + state);
+ };
+ }
+
+ private static String time(Instant instant) {
+ return TIME.format(instant);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java
index 7c0b2eb1f8..5b4caf1844 100644
--- a/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java
@@ -39,6 +39,8 @@ import java.util.function.Function;
* leaving persistent clusters WAITING and transient clusters with steps TERMINATED.
* The {@code clusterStartupDelaySeconds} config exists for
* future deferred transitions; Phase 1 advances synchronously for deterministic tests.
+ * Every state a cluster or step enters is published as an {@code aws.emr} event, once the call that
+ * made the change no longer holds the service.
*/
@ApplicationScoped
public class EmrService {
@@ -54,6 +56,7 @@ public class EmrService {
// Block public access is an account setting per Region, so this store is keyed by Region.
private final StorageBackend<String, EmrBlockPublicAccess> blockPublicAccessStore;
private final RegionResolver regionResolver;
+ private final EmrEventPublisher eventPublisher;
private static final Set<String> COMPUTE_LIMITS_UNIT_TYPES = Set.of("InstanceFleetUnits", "Instances", "VCPU");
private static final Set<String> SCALING_STRATEGIES = Set.of("DEFAULT", "ADVANCED");
@@ -67,7 +70,8 @@ public class EmrService {
private final String defaultReleaseLabel;
@Inject
- public EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) {
+ public EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
+ EmrEventPublisher eventPublisher) {
this.clusterStore = storageFactory.create("emr", "emr-clusters.json",
new TypeReference<Map<String, EmrCluster>>() {});
this.secConfigStore = storageFactory.create("emr", "emr-security-configs.json",
@@ -75,12 +79,21 @@ public class EmrService {
this.blockPublicAccessStore = storageFactory.create("emr", "emr-block-public-access.json",
new TypeReference<Map<String, EmrBlockPublicAccess>>() {});
this.regionResolver = regionResolver;
+ this.eventPublisher = eventPublisher;
this.defaultReleaseLabel = config.services().emr().defaultReleaseLabel();
}
// ──────────────────────────── Cluster lifecycle ────────────────────────────
- public synchronized EmrCluster runJobFlow(EmrCluster cluster, String region) {
+ public EmrCluster runJobFlow(EmrCluster cluster, String region) {
+ try {
+ return runJobFlowLocked(cluster, region);
+ } finally {
+ eventPublisher.publishQueued();
+ }
+ }
+
+ private synchronized EmrCluster runJobFlowLocked(EmrCluster cluster, String region) {
// Only a missing Name fails AWS's framework validation: the member is REQUIRED but its
// constraint is len=[0..256], so an explicit empty string is accepted by real EMR.
if (cluster.getName() == null) {
@@ -109,13 +122,13 @@ public class EmrService {
f.setProvisionedSpotCapacity(f.getTargetSpotCapacity());
f.setState("RUNNING");
}
- for (EmrStep step : cluster.getSteps()) {
- initStep(step);
- completeStep(step);
- }
+ eventPublisher.queue(eventPublisher.clusterStateChange(cluster, "STARTING"), region);
+ runSteps(cluster, cluster.getSteps(), region);
advanceToWaiting(cluster);
terminateAfterCompletedSteps(cluster);
clusterStore.put(id, cluster);
+ // The WAITING a transient cluster passes through here is never seen, so it has no event.
+ eventPublisher.queue(eventPublisher.clusterStateChange(cluster, cluster.getState()), region);
return cluster;
}
@@ -153,7 +166,16 @@ public class EmrService {
return result;
}
- public synchronized void terminateJobFlows(List<String> ids) {
+ public void terminateJobFlows(List<String> ids) {
+ try {
+ terminateJobFlowsLocked(ids);
+ } finally {
+ // A request naming a protected cluster still terminates the others before it fails.
+ eventPublisher.publishQueued();
+ }
+ }
+
+ private synchronized void terminateJobFlowsLocked(List<String> ids) {
// AWS terminates the unprotected clusters in the request and then fails it with a
// ValidationException if any were termination protected.
boolean anyProtected = false;
@@ -175,6 +197,8 @@ public class EmrService {
cluster.setStateChangeMessage("Terminated by user request");
cluster.setEndDateTime(Instant.now());
clusterStore.put(id, cluster);
+ eventPublisher.queue(eventPublisher.clusterStateChange(cluster, "TERMINATED"),
+ regionResolver.getRegion());
}
if (anyProtected) {
throw new AwsException("ValidationException",
@@ -212,7 +236,15 @@ public class EmrService {
// ──────────────────────────── Steps ────────────────────────────
- public synchronized List<String> addJobFlowSteps(String clusterId, List<EmrStep> steps) {
+ public List<String> addJobFlowSteps(String clusterId, List<EmrStep> steps) {
+ try {
+ return addJobFlowStepsLocked(clusterId, steps);
+ } finally {
+ eventPublisher.publishQueued();
+ }
+ }
+
+ private synchronized List<String> addJobFlowStepsLocked(String clusterId, List<EmrStep> steps) {
// AWS's own wording for an unknown job flow here, not DescribeCluster's: a botocore ClientError
// (raster-foundry/raster-foundry#352) and a CloudTrail record on AWS re:Post both show it.
EmrCluster cluster = clusterId == null ? requireCluster(null) : findCluster(clusterId).orElseThrow(
@@ -220,17 +252,17 @@ public class EmrService {
if ("TERMINATED".equals(cluster.getState())) {
throw new AwsException("ValidationException", JOB_FLOW_SHUT_DOWN, 400);
}
- List<String> ids = new ArrayList<>();
- for (EmrStep step : steps) {
- initStep(step);
- completeStep(step);
- cluster.getSteps().add(step);
- ids.add(step.getId());
- }
+ String region = regionResolver.getRegion();
+ runSteps(cluster, steps, region);
+ cluster.getSteps().addAll(steps);
+ List<String> ids = steps.stream().map(EmrStep::getId).toList();
if (!steps.isEmpty()) {
terminateAfterCompletedSteps(cluster);
}
clusterStore.put(clusterId, cluster);
+ if ("TERMINATED".equals(cluster.getState())) {
+ eventPublisher.queue(eventPublisher.clusterStateChange(cluster, "TERMINATED"), region);
+ }
return ids;
}
@@ -263,7 +295,15 @@ public class EmrService {
public record CancelStepInfo(String stepId, String status, String reason) {}
- public synchronized List<CancelStepInfo> cancelSteps(String clusterId, List<String> stepIds) {
+ public List<CancelStepInfo> cancelSteps(String clusterId, List<String> stepIds) {
+ try {
+ return cancelStepsLocked(clusterId, stepIds);
+ } finally {
+ eventPublisher.publishQueued();
+ }
+ }
+
+ private synchronized List<CancelStepInfo> cancelStepsLocked(String clusterId, List<String> stepIds) {
EmrCluster cluster = requireCluster(clusterId);
List<CancelStepInfo> result = new ArrayList<>();
for (String stepId : stepIds) {
@@ -275,6 +315,8 @@ public class EmrService {
step.setState("CANCELLED");
step.setEndDateTime(Instant.now());
result.add(new CancelStepInfo(stepId, "SUBMITTED", null));
+ eventPublisher.queue(eventPublisher.stepStatusChange(cluster, step, "CANCELLED"),
+ regionResolver.getRegion());
} else {
result.add(new CancelStepInfo(stepId, "FAILED",
"Step is not in a cancellable state: " + step.getState()));
@@ -825,6 +867,22 @@ public class EmrService {
cluster.setReadyDateTime(Instant.now());
}
+ /**
+ * Runs a request's steps as the Management Guide describes ("Running steps to process data"): all
+ * are set PENDING, then each completes before the next starts. Here they complete at once. Each
+ * change queues its event as it is made, so the events follow the steps' recorded times.
+ */
+ private void runSteps(EmrCluster cluster, List<EmrStep> steps, String region) {
+ for (EmrStep step : steps) {
+ initStep(step);
+ eventPublisher.queue(eventPublisher.stepStatusChange(cluster, step, "PENDING"), region);
+ }
+ for (EmrStep step : steps) {
+ completeStep(step);
+ eventPublisher.queue(eventPublisher.stepStatusChange(cluster, step, "COMPLETED"), region);
+ }
+ }
+
private void terminateAfterCompletedSteps(EmrCluster cluster) {
if (cluster.getSteps().isEmpty() || !cluster.isAutoTerminate()
|| "TERMINATED".equals(cluster.getState())) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java
index c9fdba71fc..7f7ce8a7bc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java
@@ -838,6 +838,26 @@ public class EventBridgeService implements ResourceProvider {
return entry;
}
+ /**
+ * Publishes one event an AWS service sends on its own behalf to {@code region}'s default bus, in the
+ * caller's account. Best effort, as the change it reports has already happened and its caller must
+ * not see it fail: an entry the bus rejects, or any failure publishing it, is logged and goes no
+ * further.
+ */
+ public void publishServiceEvent(String source, String detailType, String detail, String resourceArn,
+ String region) {
+ try {
+ PutEventsResult result = putEvents(List.of(serviceEventEntry(source, detailType, detail, resourceArn)),
+ region);
+ if (result.failedCount() > 0) {
+ LOG.warnv("EventBridge rejected the {0} {1} event in {2}: {3}", source, detailType, region,
+ result.entries());
+ }
+ } catch (RuntimeException e) {
+ LOG.warnv(e, "EventBridge could not publish the {0} {1} event in {2}", source, detailType, region);
+ }
+ }
+
public PutEventsResult putEvents(List<Map<String, Object>> entries, String region) {
return putEvents(entries, region, null);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrEventPublisherTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrEventPublisherTest.java
new file mode 100644
index 0000000000..6e0f2c4e48
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrEventPublisherTest.java
@@ -0,0 +1,311 @@
+package io.github.hectorvent.floci.services.emr;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.emr.model.EmrCluster;
+import io.github.hectorvent.floci.services.emr.model.EmrStep;
+import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
+import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * The {@code aws.emr} events {@link EmrService} publishes, in the order it publishes them, each one
+ * checked against the Management Guide's detail and its tables' severity and message.
+ */
+class EmrEventPublisherTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String ACCOUNT = "000000000000";
+ private static final DateTimeFormatter MINUTE =
+ DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'").withZone(ZoneOffset.UTC);
+
+ private final ObjectMapper objectMapper = new ObjectMapper();
+ private final List<JsonNode> published = new ArrayList<>();
+ private Target target = event -> { };
+ private EmrEventPublisher publisher;
+ private EmrService service;
+
+ /** A rule's target, given each event as it is published, as EventBridge's first delivery is. */
+ @FunctionalInterface
+ private interface Target {
+ void deliver(JsonNode event) throws Exception;
+ }
+
+ @BeforeEach
+ void setUp() {
+ EventBridgeService eventBridge = mock(EventBridgeService.class);
+ doAnswer(invocation -> {
+ // The call that made the change has let go of the service by now.
+ assertFalse(Thread.holdsLock(service), "published while EmrService was held");
+ JsonNode event = objectMapper.createObjectNode()
+ .put("detail-type", invocation.<String>getArgument(1))
+ .set("detail", objectMapper.readTree(invocation.<String>getArgument(2)));
+ published.add(event);
+ target.deliver(event);
+ return null;
+ }).when(eventBridge).publishServiceEvent(eq("aws.emr"), anyString(), anyString(), isNull(), eq(REGION));
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.services().emr().defaultReleaseLabel()).thenReturn("emr-7.5.0");
+ publisher = new EmrEventPublisher(eventBridge, objectMapper, new RegionResolver(REGION, ACCOUNT));
+ service = new EmrService(new InMemoryStorageFactory(ACCOUNT), config, new RegionResolver(REGION, ACCOUNT),
+ publisher);
+ }
+
+ @Test
+ void aClusterThatRunsItsStepsAndWaitsIsStartedAddsAndCompletesThemAndWaits() {
+ EmrCluster cluster = service.runJobFlow(cluster("nightly", true, step("load"), step("report")), REGION);
+
+ EmrStep load = cluster.getSteps().get(0);
+ EmrStep report = cluster.getSteps().get(1);
+ assertEquals(List.of("STARTING", "PENDING load", "PENDING report", "COMPLETED load", "COMPLETED report",
+ "WAITING"), states());
+ // As the events tell it: every step was added before the first one ran.
+ assertFalse(report.getCreationDateTime().isAfter(load.getStartDateTime()));
+ assertCluster(published.get(0), cluster, "STARTING", "INFO", "{\"code\":\"\"}",
+ "Amazon EMR cluster " + cluster.getId() + " (nightly) was requested at "
+ + minute(cluster.getCreationDateTime()) + " and is being created.");
+ assertStep(published.get(1), cluster, load, "PENDING", "INFO",
+ "Step " + load.getId() + " (load) was added to Amazon EMR cluster " + cluster.getId()
+ + " (nightly) at " + minute(load.getCreationDateTime()) + " and is pending execution.");
+ assertStep(published.get(3), cluster, load, "COMPLETED", "INFO",
+ "Step " + load.getId() + " (load) in Amazon EMR cluster " + cluster.getId()
+ + " (nightly) completed execution at " + minute(load.getEndDateTime())
+ + ". The step started running at " + minute(load.getStartDateTime())
+ + " and took 0 minutes to complete.");
+ assertEquals(report.getId(), published.get(4).at("/detail/stepId").asText());
+ assertCluster(published.get(5), cluster, "WAITING", "INFO", "{\"code\":\"\"}",
+ "Amazon EMR cluster " + cluster.getId() + " (nightly) finished running all pending steps at "
+ + minute(cluster.getReadyDateTime()) + ".");
+ }
+
+ @Test
+ void aClusterWithoutStepsIsReadyForUse() {
+ EmrCluster cluster = service.runJobFlow(cluster("idle", true), REGION);
+
+ assertEquals(List.of("STARTING", "WAITING"), states());
+ assertEquals("Amazon EMR cluster " + cluster.getId() + " (idle) was created at "
+ + minute(cluster.getReadyDateTime()) + " and is ready for use.",
+ published.get(1).at("/detail/message").asText());
+ }
+
+ @Test
+ void aTransientClusterTerminatesAfterItsStepsWithoutWaiting() {
+ EmrCluster cluster = service.runJobFlow(cluster("transient", false, step("only")), REGION);
+
+ assertEquals(List.of("STARTING", "PENDING only", "COMPLETED only", "TERMINATED"), states());
+ assertCluster(published.get(3), cluster, "TERMINATED", "INFO",
+ "{\"code\":\"ALL_STEPS_COMPLETED\",\"message\":\"All steps completed.\"}",
+ "Amazon EMR Cluster " + cluster.getId() + " (transient) has terminated at "
+ + minute(cluster.getEndDateTime()) + " with a reason of ALL_STEPS_COMPLETED.");
+ }
+
+ @Test
+ void stepsAddedToAWaitingClusterLeaveItWaiting() {
+ EmrCluster cluster = service.runJobFlow(cluster("kept", true), REGION);
+ published.clear();
+
+ service.addJobFlowSteps(cluster.getId(), List.of(step("late")));
+
+ assertEquals(List.of("PENDING late", "COMPLETED late"), states());
+ }
+
+ @Test
+ void stepsAddedToATransientClusterThatWaitedEndIt() {
+ EmrCluster cluster = service.runJobFlow(cluster("no-steps-yet", false), REGION);
+ published.clear();
+
+ service.addJobFlowSteps(cluster.getId(), List.of(step("late")));
+
+ assertEquals(List.of("PENDING late", "COMPLETED late", "TERMINATED"), states());
+ assertEquals("{\"code\":\"ALL_STEPS_COMPLETED\",\"message\":\"All steps completed.\"}",
+ published.get(2).at("/detail/stateChangeReason").asText());
+ }
+
+ @Test
+ void terminatingPublishesForEveryClusterItEndsEvenWhenAProtectedOneFailsTheCall() {
+ EmrCluster ended = service.runJobFlow(cluster("ended", true), REGION);
+ EmrCluster gone = service.runJobFlow(cluster("gone", true), REGION);
+ EmrCluster kept = cluster("kept", true);
+ kept.setTerminationProtected(true);
+ kept = service.runJobFlow(kept, REGION);
+ service.terminateJobFlows(List.of(gone.getId()));
+ published.clear();
+
+ List<String> ids = List.of(ended.getId(), gone.getId(), kept.getId());
+ assertThrows(AwsException.class, () -> service.terminateJobFlows(ids));
+
+ assertEquals(List.of("TERMINATED"), states());
+ assertCluster(published.get(0), service.describeCluster(ended.getId()), "TERMINATED", "INFO",
+ "{\"code\":\"USER_REQUEST\",\"message\":\"Terminated by user request\"}",
+ "Amazon EMR Cluster " + ended.getId() + " (ended) has terminated at "
+ + minute(service.describeCluster(ended.getId()).getEndDateTime())
+ + " with a reason of USER_REQUEST.");
+ }
+
+ @Test
+ void aRefusedCallPublishesNothing() {
+ EmrCluster cluster = service.runJobFlow(cluster("refusing", true), REGION);
+ service.terminateJobFlows(List.of(cluster.getId()));
+ published.clear();
+
+ assertThrows(AwsException.class, () -> service.addJobFlowSteps(cluster.getId(), List.of(step("late"))));
+ assertThrows(AwsException.class, () -> service.runJobFlow(new EmrCluster(), REGION));
+
+ assertEquals(List.of(), states());
+ }
+
+ @Test
+ void aTargetThatEndsTheClusterOnItsStartingEventHearsOfItAfterTheRestOfTheCall() {
+ target = event -> {
+ if ("STARTING".equals(event.at("/detail/state").asText())) {
+ service.terminateJobFlows(List.of(event.at("/detail/clusterId").asText()));
+ }
+ };
+
+ service.runJobFlow(cluster("answered", true), REGION);
+
+ assertEquals(List.of("STARTING", "WAITING", "TERMINATED"), states());
+ }
+
+ @Test
+ void aTargetCallingBackFromAnotherThreadHearsOfItAfterTheRestOfTheCall() {
+ AtomicReference<Throwable> failure = new AtomicReference<>();
+ target = event -> {
+ if ("STARTING".equals(event.at("/detail/state").asText())) {
+ // As an API destination would, from the thread serving its request, while this one waits.
+ String clusterId = event.at("/detail/clusterId").asText();
+ Thread other = new Thread(() -> {
+ try {
+ service.terminateJobFlows(List.of(clusterId));
+ } catch (Throwable e) {
+ failure.set(e);
+ }
+ });
+ other.start();
+ other.join();
+ }
+ };
+
+ service.runJobFlow(cluster("answered", true), REGION);
+
+ assertNull(failure.get());
+ assertEquals(List.of("STARTING", "WAITING", "TERMINATED"), states());
+ }
+
+ @Test
+ void aTerminationForAFailureIsCritical() throws Exception {
+ EmrCluster cluster = service.runJobFlow(cluster("failing", true), REGION);
+ cluster.setStateChangeReasonCode("STEP_FAILURE");
+ cluster.setStateChangeMessage("Shut down as step failed");
+ cluster.setEndDateTime(Instant.parse("2026-10-24T09:41:30Z"));
+
+ JsonNode detail = objectMapper.readTree(publisher.clusterStateChange(cluster, "TERMINATED").detail());
+
+ assertEquals("CRITICAL", detail.path("severity").asText());
+ assertEquals("Amazon EMR Cluster " + cluster.getId() + " (failing) has terminated at 2026-10-24 09:41 UTC"
+ + " with a reason of STEP_FAILURE.", detail.path("message").asText());
+ }
+
+ @Test
+ void aCancelledStepIsAWarning() throws Exception {
+ EmrCluster cluster = service.runJobFlow(cluster("cancelling", true, step("doomed")), REGION);
+ EmrStep step = cluster.getSteps().get(0);
+ step.setEndDateTime(Instant.parse("2026-10-24T09:41:30Z"));
+
+ EmrEventPublisher.Event event = publisher.stepStatusChange(cluster, step, "CANCELLED");
+
+ assertEquals("EMR Step Status Change", event.detailType());
+ JsonNode detail = objectMapper.readTree(event.detail());
+ assertEquals("WARN", detail.path("severity").asText());
+ assertEquals("Cancellation request has succeeded for cluster step " + step.getId() + " (doomed) in Amazon EMR"
+ + " cluster " + cluster.getId() + " (cancelling) at 2026-10-24 09:41 UTC, and the step is now"
+ + " cancelled.", detail.path("message").asText());
+ }
+
+ private void assertCluster(JsonNode event, EmrCluster cluster, String state, String severity, String reason,
+ String message) {
+ assertEquals("EMR Cluster State Change", event.path("detail-type").asText());
+ JsonNode detail = event.path("detail");
+ assertEquals(List.of("severity", "stateChangeReason", "name", "clusterId", "state", "message"),
+ fieldNames(detail));
+ assertEquals(severity, detail.path("severity").asText());
+ assertEquals(reason, detail.path("stateChangeReason").asText());
+ assertEquals(cluster.getName(), detail.path("name").asText());
+ assertEquals(cluster.getId(), detail.path("clusterId").asText());
+ assertEquals(state, detail.path("state").asText());
+ assertEquals(message, detail.path("message").asText());
+ }
+
+ private void assertStep(JsonNode event, EmrCluster cluster, EmrStep step, String state, String severity,
+ String message) {
+ assertEquals("EMR Step Status Change", event.path("detail-type").asText());
+ JsonNode detail = event.path("detail");
+ assertEquals(List.of("severity", "actionOnFailure", "stepId", "name", "clusterId", "state", "message"),
+ fieldNames(detail));
+ assertEquals(severity, detail.path("severity").asText());
+ assertEquals("CONTINUE", detail.path("actionOnFailure").asText());
+ assertEquals(step.getId(), detail.path("stepId").asText());
+ assertEquals(step.getName(), detail.path("name").asText());
+ assertEquals(cluster.getId(), detail.path("clusterId").asText());
+ assertEquals(state, detail.path("state").asText());
+ assertEquals(message, detail.path("message").asText());
+ }
+
+ /** Each event's state, a step's followed by its name. */
+ private List<String> states() {
+ return published.stream().map(event -> {
+ JsonNode detail = event.path("detail");
+ return detail.has("stepId")
+ ? detail.path("state").asText() + " " + detail.path("name").asText()
+ : detail.path("state").asText();
+ }).toList();
+ }
+
+ private static List<String> fieldNames(JsonNode node) {
+ List<String> names = new ArrayList<>();
+ node.fieldNames().forEachRemaining(names::add);
+ return names;
+ }
+
+ private static String minute(Instant instant) {
+ return MINUTE.format(instant);
+ }
+
+ private static EmrCluster cluster(String name, boolean keepAlive, EmrStep... steps) {
+ EmrCluster cluster = new EmrCluster();
+ cluster.setName(name);
+ cluster.setKeepJobFlowAliveWhenNoSteps(keepAlive);
+ cluster.setSteps(new ArrayList<>(List.of(steps)));
+ return cluster;
+ }
+
+ private static EmrStep step(String name) {
+ EmrStep step = new EmrStep();
+ step.setName(name);
+ step.setActionOnFailure("CONTINUE");
+ return step;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrEventsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrEventsIntegrationTest.java
new file mode 100644
index 0000000000..21db3427e6
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrEventsIntegrationTest.java
@@ -0,0 +1,135 @@
+package io.github.hectorvent.floci.services.emr;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.testing.EventRuleQueue;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.path.json.config.JsonPathConfig;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.math.BigDecimal;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static io.github.hectorvent.floci.testing.EmrRequests.emr;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The {@code aws.emr} events reach an EventBridge rule's target, as the AWS calls that change a
+ * cluster or a step make them. Each test runs its clusters in a Region no other EMR test uses, so its
+ * rule sees only its own.
+ */
+@QuarkusTest
+class EmrEventsIntegrationTest {
+
+ private static final String ACCOUNT = "000000000000";
+ private static final String EMR_EVENTS = "{\"source\":[\"aws.emr\"]}";
+ private static final DateTimeFormatter MINUTE =
+ DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'").withZone(ZoneOffset.UTC);
+ private static final JsonPathConfig DECIMAL_NUMBERS =
+ JsonPathConfig.jsonPathConfig().numberReturnType(JsonPathConfig.NumberReturnType.BIG_DECIMAL);
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void aClusterKeptAliveReportsEachStepAndItsTermination() throws Exception {
+ String region = "ap-northeast-3";
+ try (EventRuleQueue queue = EventRuleQueue.route(region, "emr-events-kept", EMR_EVENTS)) {
+ String clusterId = emr(region, "RunJobFlow", "{\"Name\":\"kept\","
+ + "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true},"
+ + "\"Steps\":[{\"Name\":\"load\",\"ActionOnFailure\":\"CONTINUE\","
+ + "\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}}]}")
+ .then().statusCode(200).extract().path("JobFlowId");
+ emr(region, "AddJobFlowSteps", "{\"JobFlowId\":\"" + clusterId + "\",\"Steps\":[{\"Name\":\"report\","
+ + "\"ActionOnFailure\":\"CONTINUE\",\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}}]}")
+ .then().statusCode(200);
+ emr(region, "TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200);
+
+ Map<String, JsonNode> events = byState(queue.drain(), region, clusterId);
+ assertThat(events.keySet(), containsInAnyOrder("STARTING", "PENDING load", "COMPLETED load", "WAITING",
+ "PENDING report", "COMPLETED report", "TERMINATED"));
+ JsonNode waiting = events.get("WAITING").path("detail");
+ assertEquals("{\"code\":\"\"}", waiting.path("stateChangeReason").asText());
+ assertEquals("Amazon EMR cluster " + clusterId + " (kept) finished running all pending steps at "
+ + minute(timeline(region, clusterId, "ReadyDateTime")) + ".", waiting.path("message").asText());
+ JsonNode completed = events.get("COMPLETED report").path("detail");
+ assertEquals("INFO", completed.path("severity").asText());
+ assertEquals("CONTINUE", completed.path("actionOnFailure").asText());
+ assertTrue(completed.path("message").asText().endsWith(" and took 0 minutes to complete."),
+ completed.path("message").asText());
+ JsonNode terminated = events.get("TERMINATED").path("detail");
+ assertEquals("INFO", terminated.path("severity").asText());
+ assertEquals("{\"code\":\"USER_REQUEST\",\"message\":\"Terminated by user request\"}",
+ terminated.path("stateChangeReason").asText());
+ assertEquals("Amazon EMR Cluster " + clusterId + " (kept) has terminated at "
+ + minute(timeline(region, clusterId, "EndDateTime")) + " with a reason of USER_REQUEST.",
+ terminated.path("message").asText());
+ }
+ }
+
+ @Test
+ void aTransientClusterEndsAfterItsStepsWithoutWaiting() throws Exception {
+ String region = "ap-southeast-3";
+ try (EventRuleQueue queue = EventRuleQueue.route(region, "emr-events-transient", EMR_EVENTS)) {
+ String clusterId = emr(region, "RunJobFlow", "{\"Name\":\"transient\",\"Instances\":{},"
+ + "\"Steps\":[{\"Name\":\"only\",\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}}]}")
+ .then().statusCode(200).extract().path("JobFlowId");
+
+ Map<String, JsonNode> events = byState(queue.drain(), region, clusterId);
+ assertThat(events.keySet(),
+ containsInAnyOrder("STARTING", "PENDING only", "COMPLETED only", "TERMINATED"));
+ JsonNode terminated = events.get("TERMINATED").path("detail");
+ assertEquals("INFO", terminated.path("severity").asText());
+ assertEquals("{\"code\":\"ALL_STEPS_COMPLETED\",\"message\":\"All steps completed.\"}",
+ terminated.path("stateChangeReason").asText());
+ assertEquals("TERMINATE_CLUSTER",
+ events.get("PENDING only").path("detail").path("actionOnFailure").asText());
+ }
+ }
+
+ /**
+ * The events by state, a step's followed by its name, once each is checked to be one of
+ * {@code clusterId}'s, sent by EMR to {@code region}'s default bus with no resources. A state seen
+ * twice fails, so the keys are every event.
+ */
+ private static Map<String, JsonNode> byState(List<JsonNode> events, String region, String clusterId) {
+ for (JsonNode event : events) {
+ assertEquals("aws.emr", event.path("source").asText());
+ assertEquals(ACCOUNT, event.path("account").asText());
+ assertEquals(region, event.path("region").asText());
+ assertEquals(0, event.path("resources").size());
+ assertEquals(clusterId, event.path("detail").path("clusterId").asText());
+ assertEquals(event.path("detail").has("stepId") ? "EMR Step Status Change" : "EMR Cluster State Change",
+ event.path("detail-type").asText());
+ }
+ return events.stream().collect(Collectors.toMap(event -> {
+ JsonNode detail = event.path("detail");
+ return detail.has("stepId")
+ ? detail.path("state").asText() + " " + detail.path("name").asText()
+ : detail.path("state").asText();
+ }, Function.identity()));
+ }
+
+ private static Instant timeline(String region, String clusterId, String field) {
+ BigDecimal seconds = emr(region, "DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}").then()
+ .statusCode(200).extract().response().jsonPath(DECIMAL_NUMBERS)
+ .get("Cluster.Status.Timeline." + field);
+ return Instant.ofEpochMilli(seconds.movePointRight(3).longValue());
+ }
+
+ private static String minute(Instant instant) {
+ return MINUTE.format(instant);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java
index 4cf935dd6c..59b0d38268 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java
@@ -39,8 +39,10 @@ import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -859,6 +861,57 @@ class EventBridgeServiceTest {
verify(dispatcherMock).dispatch(eq(rule.getArn()), eq(target), anyString(), eq(REGION), any());
}
+ @Test
+ void publishServiceEventSendsTheEventToTheRegionsDefaultBus() throws Exception {
+ Rule rule = service.putRule("emr", null, "{\"source\":[\"aws.emr\"]}", null, RuleState.ENABLED,
+ null, null, null, REGION);
+ Target target = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue-1", null, null);
+ service.putTargets("emr", null, List.of(target), REGION);
+
+ service.publishServiceEvent("aws.emr", "EMR Cluster State Change", "{\"state\":\"WAITING\"}", null, REGION);
+
+ ArgumentCaptor<String> eventJson = ArgumentCaptor.forClass(String.class);
+ verify(dispatcherMock).dispatch(eq(rule.getArn()), eq(target), eventJson.capture(), eq(REGION), any());
+ JsonNode event = OBJECT_MAPPER.readTree(eventJson.getValue());
+ assertEquals("aws.emr", event.path("source").asText());
+ assertEquals("EMR Cluster State Change", event.path("detail-type").asText());
+ assertEquals(REGION, event.path("region").asText());
+ assertEquals(0, event.path("resources").size());
+ assertEquals("WAITING", event.path("detail").path("state").asText());
+ }
+
+ @Test
+ void publishServiceEventLeavesAnEntryTheBusRejectsUndelivered() {
+ service.putRule("emr", null, "{\"source\":[\"aws.emr\"]}", null, RuleState.ENABLED,
+ null, null, null, REGION);
+ service.putTargets("emr", null,
+ List.of(new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue-1", null, null)), REGION);
+
+ assertDoesNotThrow(() -> service.publishServiceEvent("aws.emr", "EMR Cluster State Change", "not json",
+ null, REGION));
+
+ verify(dispatcherMock, never()).dispatch(anyString(), any(), anyString(), anyString(), any());
+ }
+
+ @Test
+ void publishServiceEventPassesOverACallEventBridgeRefuses() {
+ EventBridgeService refusing = spy(service);
+ doThrow(new AwsException("InternalException", "unavailable", 500))
+ .when(refusing).putEvents(anyList(), eq(REGION));
+
+ assertDoesNotThrow(() -> refusing.publishServiceEvent("aws.emr", "EMR Cluster State Change", "{}", null,
+ REGION));
+ }
+
+ @Test
+ void publishServiceEventPassesOverAnyOtherFailure() {
+ EventBridgeService faulty = spy(service);
+ doThrow(new IllegalStateException("broken")).when(faulty).putEvents(anyList(), eq(REGION));
+
+ assertDoesNotThrow(() -> faulty.publishServiceEvent("aws.emr", "EMR Cluster State Change", "{}", null,
+ REGION));
+ }
+
private void assertPutTargetsValidation(String expectedMessage, Target... targets) {
AwsException error = assertThrows(AwsException.class, () ->
service.putTargets("missing-rule", null, List.of(targets), REGION));
diff --git a/src/test/java/io/github/hectorvent/floci/testing/EventRuleQueue.java b/src/test/java/io/github/hectorvent/floci/testing/EventRuleQueue.java
new file mode 100644
index 0000000000..10042991ed
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/testing/EventRuleQueue.java
@@ -0,0 +1,99 @@
+package io.github.hectorvent.floci.testing;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.restassured.response.Response;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static io.restassured.RestAssured.given;
+
+/**
+ * An SQS queue that an EventBridge rule on a Region's default bus sends its matching events to, set
+ * up over the AWS wire, so a test can read back the events a service published. Give the rule a
+ * pattern, or a Region, of the test's own, so no other test's events reach the queue, and close it,
+ * which removes the rule and the queue. The calls send AWS JSON, so the test class runs
+ * {@link RestAssuredJsonUtils#configureAwsContentTypes()} first.
+ */
+public final class EventRuleQueue implements AutoCloseable {
+
+ private static final String SQS_CONTENT_TYPE = "application/x-amz-json-1.0";
+ private static final String EVENTS_CONTENT_TYPE = "application/x-amz-json-1.1";
+ private static final String TARGET_ID = "1";
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private final String region;
+ private final String name;
+ private final String url;
+
+ private EventRuleQueue(String region, String name, String url) {
+ this.region = region;
+ this.name = name;
+ this.url = url;
+ }
+
+ /** A queue named {@code name}, and a rule of the same name sending it the events {@code pattern} matches. */
+ public static EventRuleQueue route(String region, String name, String pattern) {
+ String url = call(region, "sqs", "AmazonSQS.CreateQueue", SQS_CONTENT_TYPE,
+ MAPPER.createObjectNode().put("QueueName", name)).jsonPath().getString("QueueUrl");
+ ObjectNode attributes = MAPPER.createObjectNode().put("QueueUrl", url);
+ attributes.putArray("AttributeNames").add("QueueArn");
+ String arn = call(region, "sqs", "AmazonSQS.GetQueueAttributes", SQS_CONTENT_TYPE, attributes)
+ .jsonPath().getString("Attributes.QueueArn");
+ call(region, "events", "AWSEvents.PutRule", EVENTS_CONTENT_TYPE,
+ MAPPER.createObjectNode().put("Name", name).put("EventPattern", pattern));
+ ObjectNode targets = MAPPER.createObjectNode().put("Rule", name);
+ targets.putArray("Targets").addObject().put("Id", TARGET_ID).put("Arn", arn);
+ call(region, "events", "AWSEvents.PutTargets", EVENTS_CONTENT_TYPE, targets);
+ return new EventRuleQueue(region, name, url);
+ }
+
+ /**
+ * The events on the queue, as they arrived (a standard queue does not promise their order), each
+ * deleted once read. EventBridge delivers to an SQS target before the call that published the event
+ * returns, so they are all there once the calls under test have returned.
+ */
+ public List<JsonNode> drain() throws Exception {
+ List<JsonNode> events = new ArrayList<>();
+ ObjectNode receive = MAPPER.createObjectNode().put("QueueUrl", url).put("MaxNumberOfMessages", 10)
+ .put("WaitTimeSeconds", 0);
+ while (true) {
+ Response response = call(region, "sqs", "AmazonSQS.ReceiveMessage", SQS_CONTENT_TYPE, receive);
+ JsonNode messages = MAPPER.readTree(response.asString()).path("Messages");
+ if (messages.isEmpty()) {
+ return events;
+ }
+ for (JsonNode message : messages) {
+ events.add(MAPPER.readTree(message.path("Body").asText()));
+ call(region, "sqs", "AmazonSQS.DeleteMessage", SQS_CONTENT_TYPE, MAPPER.createObjectNode()
+ .put("QueueUrl", url).put("ReceiptHandle", message.path("ReceiptHandle").asText()));
+ }
+ }
+ }
+
+ /** Removes the rule's target, the rule and the queue. */
+ @Override
+ public void close() {
+ ObjectNode targets = MAPPER.createObjectNode().put("Rule", name);
+ targets.putArray("Ids").add(TARGET_ID);
+ call(region, "events", "AWSEvents.RemoveTargets", EVENTS_CONTENT_TYPE, targets);
+ call(region, "events", "AWSEvents.DeleteRule", EVENTS_CONTENT_TYPE,
+ MAPPER.createObjectNode().put("Name", name));
+ call(region, "sqs", "AmazonSQS.DeleteQueue", SQS_CONTENT_TYPE,
+ MAPPER.createObjectNode().put("QueueUrl", url));
+ }
+
+ private static Response call(String region, String service, String target, String contentType, JsonNode body) {
+ Response response = given()
+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260215/" + region + "/" + service
+ + "/aws4_request, SignedHeaders=host, Signature=abc")
+ .header("X-Amz-Target", target)
+ .contentType(contentType)
+ .body(body.toString())
+ .when().post("/");
+ response.then().statusCode(200);
+ return response;
+ }
+}