feat(ses): publish events to Firehose, EventBridge, CloudWatch (#1188)

* feat(ses): publish events to Firehose, EventBridge, and CloudWatch destinations

Extend SES V2 configuration set event publishing so destinations beyond
SnsDestination actually deliver. Previously KinesisFirehoseDestination,
EventBridgeDestination, and CloudWatchDestination were stored but the
publisher logged a warning and skipped. PinpointDestination still skips.

- KinesisFirehoseDestination → single Firehose PutRecord per event;
  S3-backed streams flush accumulated records as NDJSON once the default
  count threshold is reached.
- EventBridgeDestination → PutEvents entry with Source=aws.ses,
  DetailType="Email <EventTypeLabel>", payload as Detail. Region is
  stamped on the entry (so matchesPattern + envelope agree on a
  non-default region) and Resources is always present (empty when
  sourceArn is null — matchesPattern's resources-filter branch casts
  entry.get("Resources") unconditionally).
- CloudWatchDestination → MetricDatum to AWS/SES with Unit=Count.
  Dimensions resolved from DimensionConfigurations against EmailTags
  (MESSAGE_TAG / messageTag), email headers (EMAIL_HEADER / emailHeader),
  or ses:configuration-set, falling back to DefaultDimensionValue.
  Timestamp left to putMetricData's epoch-seconds default.

Tests
- SesEventPublishingV2IntegrationTest @Order 14-28: per-destination
  setup → send → assert, plus a cross-region (eu-west-1) EventBridge
  case pinning region propagation end-to-end.
- SesEventPublisherTest (Mockito ArgumentCaptor): the EB PutEvents
  entry always carries Resources as an ArrayNode — integration tests
  cannot pin this because EventBridgeService.buildEventEnvelope
  defaults a missing key via getOrDefault.

Docs
- docs/services/ses.md: replace the SNS-only claim with the four
  supported destination types.

* fix(ses): use AWS past-tense detail-type for EventBridge SES events

The EventBridge publisher was emitting "Email Send", "Email Delivery",
etc — derived from the SNS notification eventType vocabulary by
prepending "Email ". AWS uses a separate past-tense vocabulary on
EventBridge: "Email Sent", "Email Delivered", "Email Bounced", "Email
Complaint Received", "Email Rejected", "Email Opened", "Email Clicked",
"Email Rendering Failed", "Email Delivery Delayed", "Email Subscribed"
(see https://docs.aws.amazon.com/eventbridge/latest/ref/events-ref-ses.html).

A customer rule pattern keyed on the AWS value
({"source":["aws.ses"],"detail-type":["Email Delivered"]}) would
silently fail to match Floci events.

Changes:
- Add SesEventPayload.eventBridgeDetailType returning the past-tense
  EventBridge vocabulary. Kept separate from eventTypeLabel (which
  remains correct for SNS notifications and CloudWatch metric names).
- SesEventPublisher.publishEventBridge uses the new mapping.

Tests
- SesEventPayloadTest.eventBridgeDetailType_matchesAwsPastTenseVocabulary:
  pins all 10 mappings against AWS docs.
- SesEventPublishingV2IntegrationTest @Order 29
  (eventBridge_detailTypePattern_keyedOnAwsSentValue_matches):
  structural pin — creates a rule with EventPattern
  {"source":["aws.ses"],"detail-type":["Email Sent"]} and asserts the
  SQS target receives the SEND envelope. A regression to "Email Send"
  would cause the rule to silently drop the event, failing the test
  without relying on any hard-coded assertion string.
- Existing tests updated to assert the AWS values:
  SesEventPublishingV2IntegrationTest 4 assertions; sdk-test-java
  SesEventPublishingTest 3 assertions.

* fix(ses): emit CloudWatch metric name "RenderingFailure" without space

AWS CloudWatch metric publishing for SES uses "RenderingFailure" (no
space) for the RENDERING_FAILURE event type — verified against real
AWS by configuring a CW event destination on a configuration set,
sending a templated email with a missing TemplateData key to trigger
the rendering failure path, and capturing the new metric name from
`aws cloudwatch list-metrics --namespace AWS/SES`.

Floci's publisher was previously sourcing the CW MetricName from
SesEventPayload.eventTypeLabel, which returns "Rendering Failure" (with
space). That spelling is correct for the SNS notification's eventType
field but wrong for CloudWatch — customer dashboards / alarms keyed on
the AWS-correct "RenderingFailure" never see Floci's metric.

Changes:
- Add SesEventPayload.cloudWatchMetricName returning the CW spelling.
  Mirrors eventTypeLabel for every other case so the two stay aligned
  in shape; only RENDERING_FAILURE differs.
- SesEventPublisher.publishCloudWatch uses the new mapping.
- SesEventPayloadTest.cloudWatchMetricName_matchesAwsCwSpelling pins
  all 10 mappings; RENDERING_FAILURE expectation comes from the live
  AWS capture rather than an AWS docs guess.

DELIVERY_DELAY remains as "DeliveryDelay" in this commit — it could
not be triggered conveniently from the SES sandbox (needs genuine SES
backoff), so leaving the existing value rather than guessing. Flagged
in code comments as needing future verification.

The other simple metric names (Send, Delivery, Bounce, Complaint) were
also verified against the same AWS capture and match Floci's existing
spelling byte-for-byte — no change needed for those.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-06-09 00:36:28 -05:00
1 parent 3065774e80
commit 35f597addd
7 files changed
+1893 -31

No files matched your search

@@ -308,4 +308,51 @@ class SesEventPayloadTest {
assertEquals("Reject", node.get("eventType").asText());
assertNotNull(node.get("reject").get("reason"));
}
/**
* AWS CloudWatch metric names for SES events are mostly the same as the SNS
* {@code eventType} value, except {@code RENDERING_FAILURE} is emitted as
* {@code RenderingFailure} (no space) on CW but {@code Rendering Failure}
* (with space) on SNS — verified directly against real AWS by sending a
* templated email with a missing {@code TemplateData} key through a CS with a
* CloudWatch event destination, then capturing the new metric name from
* {@code aws cloudwatch list-metrics --namespace AWS/SES}. Pin both spellings
* so a future cleanup of either accessor cannot silently regress the other.
*/
@Test
void cloudWatchMetricName_matchesAwsCwSpelling() {
assertEquals("Send", SesEventPayload.cloudWatchMetricName("SEND"));
assertEquals("Reject", SesEventPayload.cloudWatchMetricName("REJECT"));
assertEquals("Bounce", SesEventPayload.cloudWatchMetricName("BOUNCE"));
assertEquals("Complaint", SesEventPayload.cloudWatchMetricName("COMPLAINT"));
assertEquals("Delivery", SesEventPayload.cloudWatchMetricName("DELIVERY"));
assertEquals("Open", SesEventPayload.cloudWatchMetricName("OPEN"));
assertEquals("Click", SesEventPayload.cloudWatchMetricName("CLICK"));
// Verified against real AWS — no space, unlike the SNS spelling.
assertEquals("RenderingFailure", SesEventPayload.cloudWatchMetricName("RENDERING_FAILURE"));
assertEquals("DeliveryDelay", SesEventPayload.cloudWatchMetricName("DELIVERY_DELAY"));
assertEquals("Subscription", SesEventPayload.cloudWatchMetricName("SUBSCRIPTION"));
}
/**
* EventBridge uses a separate past-tense vocabulary for {@code detail-type}, distinct
* from the SNS notification {@code eventType} value. Pin every mapping against
* https://docs.aws.amazon.com/eventbridge/latest/ref/events-ref-ses.html so a
* future cleanup of {@link SesEventPayload#eventTypeLabel} cannot accidentally
* regress the EventBridge value (which would silently break customer rules
* keyed on the AWS detail-type names).
*/
@Test
void eventBridgeDetailType_matchesAwsPastTenseVocabulary() {
assertEquals("Email Sent", SesEventPayload.eventBridgeDetailType("SEND"));
assertEquals("Email Rejected", SesEventPayload.eventBridgeDetailType("REJECT"));
assertEquals("Email Bounced", SesEventPayload.eventBridgeDetailType("BOUNCE"));
assertEquals("Email Complaint Received", SesEventPayload.eventBridgeDetailType("COMPLAINT"));
assertEquals("Email Delivered", SesEventPayload.eventBridgeDetailType("DELIVERY"));
assertEquals("Email Opened", SesEventPayload.eventBridgeDetailType("OPEN"));
assertEquals("Email Clicked", SesEventPayload.eventBridgeDetailType("CLICK"));
assertEquals("Email Rendering Failed", SesEventPayload.eventBridgeDetailType("RENDERING_FAILURE"));
assertEquals("Email Delivery Delayed", SesEventPayload.eventBridgeDetailType("DELIVERY_DELAY"));
assertEquals("Email Subscribed", SesEventPayload.eventBridgeDetailType("SUBSCRIPTION"));
}
}
@@ -0,0 +1,133 @@
package io.github.hectorvent.floci.services.ses;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
import io.github.hectorvent.floci.services.ses.model.EventBridgeDestination;
import io.github.hectorvent.floci.services.ses.model.EventDestination;
import io.github.hectorvent.floci.services.sns.SnsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link SesEventPublisher}'s PutEvents entry construction.
*
* <p>The integration suite ({@link SesEventPublishingV2IntegrationTest}) cannot
* distinguish the with-fix and without-fix shapes of the EventBridge entry, because
* {@code EventBridgeService.buildEventEnvelope} defensively defaults
* a missing {@code Resources} entry to an empty {@code ArrayNode} when assembling
* the delivered envelope. These mock-based tests inspect the entry handed to
* {@code eventBridgeService.putEvents} directly so we can pin the publisher's
* contract regardless of downstream defaulting.
*/
@ExtendWith(MockitoExtension.class)
class SesEventPublisherTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String DEFAULT_BUS_ARN =
"arn:aws:events:us-east-1:000000000000:event-bus/default";
@Mock private SnsService snsService;
@Mock private FirehoseService firehoseService;
@Mock private EventBridgeService eventBridgeService;
@Mock private CloudWatchMetricsService cloudWatchMetricsService;
private SesEventPublisher publisher;
@BeforeEach
void setUp() {
publisher = new SesEventPublisher(snsService, firehoseService, eventBridgeService,
cloudWatchMetricsService, MAPPER);
}
@Test
void publishEventBridge_withNullSourceArn_emitsEmptyResourcesArrayNotAbsent() {
// Regression pin: SesEventPublisher.publishEventBridge must always set the
// "Resources" key on the PutEvents entry, even when sourceArn is null. Omitting
// the key causes EventBridgeService.matchesPattern to NPE on
// `((ArrayNode) entry.get("Resources")).elements()` for any rule with a
// "resources" pattern filter — the exception is caught and the rule silently
// turns into a no-match plus log noise. An empty ArrayNode matches AWS's
// behavior (the resources field is always present, sometimes empty).
when(eventBridgeService.putEvents(any(), anyString()))
.thenReturn(new EventBridgeService.PutEventsResult(0, List.of()));
publisher.publish(configurationSetWithEventBridgeDestination(DEFAULT_BUS_ARN),
"SEND", "msg-1", null, null, "000000000000", "subj",
List.of("to@example.com"), null, null, List.of("to@example.com"),
null, null, null, null, Instant.now(), "us-east-1");
Map<String, Object> entry = captureSingleEntry();
assertTrue(entry.containsKey("Resources"),
"Resources key must be present on the entry even when sourceArn is null");
Object resources = entry.get("Resources");
assertInstanceOf(ArrayNode.class, resources,
"Resources must be an ArrayNode (EventBridgeService.matchesPattern "
+ "casts entry.get(\"Resources\") unconditionally)");
assertEquals(0, ((ArrayNode) resources).size(),
"Resources must be an empty array when sourceArn is null, not absent");
}
@Test
void publishEventBridge_withSourceArn_emitsResourcesContainingArn() {
String arn = "arn:aws:ses:us-east-1:000000000000:identity/sender@example.com";
when(eventBridgeService.putEvents(any(), anyString()))
.thenReturn(new EventBridgeService.PutEventsResult(0, List.of()));
publisher.publish(configurationSetWithEventBridgeDestination(DEFAULT_BUS_ARN),
"SEND", "msg-1", "sender@example.com", arn, "000000000000", "subj",
List.of("to@example.com"), null, null, List.of("to@example.com"),
null, null, null, null, Instant.now(), "us-east-1");
Map<String, Object> entry = captureSingleEntry();
Object resources = entry.get("Resources");
assertNotNull(resources);
assertInstanceOf(ArrayNode.class, resources);
ArrayNode arr = (ArrayNode) resources;
assertEquals(1, arr.size());
assertEquals(arn, arr.get(0).asText());
}
@SuppressWarnings("unchecked")
private Map<String, Object> captureSingleEntry() {
ArgumentCaptor<List<Map<String, Object>>> captor =
ArgumentCaptor.forClass(List.class);
verify(eventBridgeService).putEvents(captor.capture(), anyString());
List<Map<String, Object>> entries = captor.getValue();
assertEquals(1, entries.size(), "publisher must emit exactly one entry per send");
return entries.get(0);
}
private ConfigurationSet configurationSetWithEventBridgeDestination(String busArn) {
EventBridgeDestination ebd = new EventBridgeDestination();
ebd.setEventBusArn(busArn);
EventDestination ed = new EventDestination();
ed.setName("ed-eb");
ed.setEnabled(true);
ed.setMatchingEventTypes(List.of("SEND"));
ed.setEventBridgeDestination(ebd);
ConfigurationSet cs = new ConfigurationSet("cs-test");
cs.setEventDestinations(List.of(ed));
return cs;
}
}