feat(ses): add v2 export jobs (#4327)

* feat(ses): add v2 export jobs

CreateExportJob, GetExportJob, ListExportJobs and CancelExportJob render the
per-recipient timelines already stored at send time as CSV or JSON, through
the same aggregation BatchGetMetricData serves, so an export and a query of
one window cannot disagree.

Real SES writes the file into a bucket it owns and refuses a caller-chosen
S3Url, so Floci does the same and writes into its own S3 emulation, which is
what the presigned URL on a finished job resolves against.

The VDM gate answers BadRequestException here where message insights and
metric data answer NotFoundException, so SesAccountService takes the caller's
error shape and keeps one copy of the probed sentence.

* fix(ses): use the published concurrent-export quota and prove the reset test parks

* fix(ses): scope the export bucket per account and fix two row-count bugs

* fix(ses): make the reset drain test deterministic and document the presigner limit

* test(ses): assert the reset thread finished, since join returns on timeout too
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-09-24 22:54:36 -04:00
1 parent 88a992757e
commit 08c6ce0768
15 files changed
+3030 -4

No files matched your search

@@ -0,0 +1,101 @@
package io.github.hectorvent.floci.services.ses;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SesExportFiltersTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static SesExportPayloads.InsightsRow row(String destination, String tenantName) {
Map<String, String> columns = new LinkedHashMap<>();
columns.put("destination", destination);
columns.put("isp", "UNKNOWN_ISP");
columns.put("last_delivery_event", "DELIVERY");
columns.put("last_engagement_event", null);
return new SesExportPayloads.InsightsRow(columns, tenantName);
}
private static JsonNode source(String json) {
try {
return MAPPER.readTree(json);
} catch (Exception e) {
throw new AssertionError("bad test json", e);
}
}
private static List<String> destinations(List<SesExportPayloads.InsightsRow> rows) {
return rows.stream().map(row -> row.columns().get("destination")).toList();
}
private static final List<SesExportPayloads.InsightsRow> ROWS = List.of(
row("one@example.com", "blue"),
row("two@example.com", "green"),
row("three@example.com", null));
@Test
void includeOnTenantNameKeepsOnlyThatTenant() {
List<SesExportPayloads.InsightsRow> kept = SesExportFilters.apply(ROWS,
source("{\"Include\": {\"TenantName\": [\"blue\"]}}"));
assertEquals(List.of("one@example.com"), destinations(kept));
}
@Test
void includeOnTenantNameAcceptsSeveralValues() {
List<SesExportPayloads.InsightsRow> kept = SesExportFilters.apply(ROWS,
source("{\"Include\": {\"TenantName\": [\"blue\", \"green\"]}}"));
assertEquals(List.of("one@example.com", "two@example.com"), destinations(kept));
}
@Test
void excludeOnTenantNameDropsThatTenantAndKeepsTheTenantlessSend() {
List<SesExportPayloads.InsightsRow> kept = SesExportFilters.apply(ROWS,
source("{\"Exclude\": {\"TenantName\": [\"blue\"]}}"));
assertEquals(List.of("two@example.com", "three@example.com"), destinations(kept));
}
@Test
void membersWithinOneIncludeAllHaveToMatch() {
List<SesExportPayloads.InsightsRow> kept = SesExportFilters.apply(ROWS,
source("{\"Include\": {\"TenantName\": [\"blue\"], \"Isp\": [\"GMAIL\"]}}"));
assertTrue(kept.isEmpty(), "the ISP member excludes the row the tenant member keeps");
}
@Test
void anIncludeOnLastEngagementEventSelectsNothing() {
// Floci derives no opens or clicks, so the column is always null and cannot match.
List<SesExportPayloads.InsightsRow> kept = SesExportFilters.apply(ROWS,
source("{\"Include\": {\"LastEngagementEvent\": [\"OPEN\"]}}"));
assertTrue(kept.isEmpty());
}
@Test
void anExcludeCarryingNoValuesKeepsEveryRow() {
// Every member is absent, so the block constrains nothing. Read as a match it would empty
// the file, which is the one direction where "no constraint" is not harmless.
assertEquals(3, SesExportFilters.apply(ROWS, source("{\"Exclude\": {}}")).size());
assertEquals(3, SesExportFilters.apply(ROWS,
source("{\"Exclude\": {\"TenantName\": []}}")).size());
}
@Test
void maxResultsTruncatesAfterFiltering() {
List<SesExportPayloads.InsightsRow> kept = SesExportFilters.apply(ROWS,
source("{\"Exclude\": {\"TenantName\": [\"blue\"]}, \"MaxResults\": 1}"));
assertEquals(List.of("two@example.com"), destinations(kept));
}
}
@@ -0,0 +1,361 @@
package io.github.hectorvent.floci.services.ses;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.s3.PreSignedUrlGenerator;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ses.model.EmailInsights;
import io.github.hectorvent.floci.services.ses.model.ExportJob;
import io.github.hectorvent.floci.services.ses.model.InsightsEvent;
import io.github.hectorvent.floci.services.ses.model.SentEmail;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
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.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
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.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The parts of {@link SesExportJobService} the integration test cannot pin down: what happens when
* a cancel lands in the window between the object being written and the job being marked complete.
* The worker runs on a captured task here, so that window is reachable.
*/
class SesExportJobServiceTest {
private static final String REGION = "eu-north-1";
private static final String ACCOUNT = "000000000000";
private final S3Service s3Service = mock(S3Service.class);
private final PreSignedUrlGenerator presigner = mock(PreSignedUrlGenerator.class);
private final SesSentEmailService sentEmailService =
new SesSentEmailService(new InMemoryStorage<>());
private final ObjectMapper objectMapper = new ObjectMapper();
private final List<Runnable> tasks = new ArrayList<>();
private SesExportJobService service;
@BeforeEach
void setUp() {
when(s3Service.bucketExists(anyString())).thenReturn(true);
service = new SesExportJobService(new InMemoryStorage<>(), sentEmailService, s3Service,
presigner, objectMapper, Clock.fixed(Instant.parse("2026-09-23T00:00:00Z"),
ZoneOffset.UTC),
tasks::add, "http://localhost:4566");
}
private JsonNode insightsSource() {
try {
return objectMapper.readTree("""
{"MessageInsightsDataSource": {"StartDate": 1758499200, "EndDate": 1758672000}}
""");
} catch (JsonProcessingException e) {
throw new AssertionError(e);
}
}
private ExportJob createJob() {
return service.createExportJob(REGION, ACCOUNT, insightsSource(), destination(), () -> { });
}
private JsonNode destination() {
return objectMapper.createObjectNode().put("DataFormat", ExportJob.FORMAT_CSV);
}
@Test
void aCancelDuringTheWriteLeavesNoObjectBehind() {
ExportJob job = createJob();
// The cancel lands while the worker is inside putObject, which is the only window in which
// an object can be written for a job that will never point at it.
when(s3Service.putObject(anyString(), anyString(), any(), anyString(), any()))
.thenAnswer(invocation -> {
service.cancelExportJob(REGION, job.getJobId());
return null;
});
tasks.forEach(Runnable::run);
ExportJob stored = service.getExportJob(REGION, job.getJobId());
assertEquals(ExportJob.STATUS_CANCELLED, stored.getJobStatus());
assertNull(stored.getObjectKey(), "a cancelled job points at nothing");
verify(s3Service).deleteObject(eq(SesExportJobService.exportBucket(ACCOUNT, REGION)), anyString());
}
@Test
void anUninterruptedJobKeepsItsObject() {
ExportJob job = createJob();
tasks.forEach(Runnable::run);
ExportJob stored = service.getExportJob(REGION, job.getJobId());
assertEquals(ExportJob.STATUS_COMPLETED, stored.getJobStatus());
verify(s3Service, never()).deleteObject(anyString(), anyString());
}
@Test
void cancellingBeforeTheWorkerRunsSkipsTheWriteEntirely() {
ExportJob job = createJob();
service.cancelExportJob(REGION, job.getJobId());
tasks.forEach(Runnable::run);
assertEquals(ExportJob.STATUS_CANCELLED,
service.getExportJob(REGION, job.getJobId()).getJobStatus());
verify(s3Service, never()).putObject(anyString(), anyString(), any(), anyString(),
any(Map.class));
}
@Test
void aResetAbandonsAJobThatHasNotStartedWriting() {
ExportJob job = createJob();
service.beforeReset();
tasks.forEach(Runnable::run);
verify(s3Service, never()).putObject(anyString(), anyString(), any(), anyString(),
any(Map.class));
assertEquals(ExportJob.STATUS_PROCESSING,
service.getExportJob(REGION, job.getJobId()).getJobStatus());
}
@Test
void aResetWaitsForAWorkerAlreadyInsideItsWrite() throws Exception {
CountDownLatch writing = new CountDownLatch(1);
CountDownLatch releaseWrite = new CountDownLatch(1);
AtomicBoolean workerFinishedTheWrite = new AtomicBoolean();
SesExportJobService threaded = new SesExportJobService(new InMemoryStorage<>(),
sentEmailService, s3Service, presigner, objectMapper,
Clock.fixed(Instant.parse("2026-09-23T00:00:00Z"), ZoneOffset.UTC),
task -> new Thread(task).start(), "http://localhost:4566");
when(s3Service.putObject(anyString(), anyString(), any(), anyString(), any()))
.thenAnswer(invocation -> {
writing.countDown();
releaseWrite.await(5, TimeUnit.SECONDS);
workerFinishedTheWrite.set(true);
return null;
});
threaded.createExportJob(REGION, ACCOUNT, insightsSource(), destination(), () -> { });
assertTrue(writing.await(5, TimeUnit.SECONDS), "the worker never reached its write");
Thread reset = new Thread(threaded::beforeReset);
reset.start();
awaitParked(reset, "the reset waiting on the in-flight write");
releaseWrite.countDown();
reset.join(5_000);
// join returns on timeout too, so without this the assertion below would hold even if
// beforeReset never came back.
assertFalse(reset.isAlive(), "the reset did not finish after the in-flight write");
assertTrue(workerFinishedTheWrite.get(),
"the reset returned before the in-flight write finished");
}
private void recordSend(Instant sentAt, String source) {
SentEmail email = new SentEmail();
email.setMessageId("m-" + sentAt.toEpochMilli() + "-" + source);
email.setSource(source);
email.setSentAt(sentAt);
email.setInsights(List.of(new EmailInsights("to@example.com", "UNKNOWN_ISP",
List.of(InsightsEvent.of(sentAt, "SEND")))));
sentEmailService.record(REGION, email.getMessageId(), email);
}
private String runMetricsExport(String dimensions, Instant start, Instant end) throws Exception {
JsonNode source = objectMapper.readTree("""
{"MetricsDataSource": {"Dimensions": %s, "Namespace": "VDM",
"Metrics": [{"Name": "SEND", "Aggregation": "VOLUME"}],
"StartDate": %d, "EndDate": %d}}
""".formatted(dimensions, start.getEpochSecond(), end.getEpochSecond()));
service.createExportJob(REGION, ACCOUNT, source, destination(), () -> { });
tasks.forEach(Runnable::run);
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(anyString(), anyString(), payload.capture(), anyString(), any());
return new String(payload.getValue(), StandardCharsets.UTF_8);
}
@Test
void anIdentityRowIsKeyedByTheBareAddressAndCountsItsSend() throws Exception {
recordSend(Instant.parse("2026-09-23T10:00:00Z"), "\"Doe, Jane\" <jane@example.com>");
String csv = runMetricsExport("{\"EMAIL_IDENTITY\": [\"*\"]}",
Instant.parse("2026-09-23T00:00:00Z"), Instant.parse("2026-09-24T00:00:00Z"));
// Keyed by the stored Source, the row is one the identity matching behind the counts then
// refuses, so it comes back at zero, and a comma in the display name splits the CSV row.
assertEquals("EMAIL_IDENTITY,SEND_VOLUME\njane@example.com,1.0000\n", csv);
}
@Test
void aDimensionValueSeenOnlyOutsideTheWindowProducesNoRow() throws Exception {
recordSend(Instant.parse("2026-09-23T10:00:00Z"), "inside@example.com");
recordSend(Instant.parse("2026-09-20T10:00:00Z"), "outside@example.com");
String csv = runMetricsExport("{\"EMAIL_IDENTITY\": [\"*\"]}",
Instant.parse("2026-09-23T00:00:00Z"), Instant.parse("2026-09-24T00:00:00Z"));
assertTrue(csv.contains("inside@example.com,1.0000"), csv);
assertFalse(csv.contains("outside@example.com"), csv);
}
@Test
void anInsightsWindowIncludesASendOnItsEndInstant() throws Exception {
// The model calls MessageInsightsDataSource.EndDate inclusive, unlike the daily metrics
// buckets, whose exclusive end the BatchGetMetricData probe confirmed.
Instant sentAt = Instant.parse("2026-09-23T12:00:00Z");
recordSend(sentAt, "edge@example.com");
JsonNode source = objectMapper.readTree("""
{"MessageInsightsDataSource": {"StartDate": %d, "EndDate": %d}}
""".formatted(sentAt.minusSeconds(3600).getEpochSecond(), sentAt.getEpochSecond()));
ExportJob job = service.createExportJob(REGION, ACCOUNT, source, destination(), () -> { });
tasks.forEach(Runnable::run);
assertEquals(1L, service.getExportJob(REGION, job.getJobId()).getProcessedRecordsCount());
}
@Test
void aBucketCreatedByAConcurrentJobDoesNotFailTheExport() {
when(s3Service.bucketExists(anyString())).thenReturn(false);
when(s3Service.createBucket(anyString(), anyString())).thenThrow(new AwsException(
"BucketAlreadyOwnedByYou",
"Your previous request to create the named bucket succeeded and you already own it.",
409));
ExportJob job = createJob();
tasks.forEach(Runnable::run);
assertEquals(ExportJob.STATUS_COMPLETED,
service.getExportJob(REGION, job.getJobId()).getJobStatus());
}
@Test
void aCreateArrivingDuringAResetWaitsForItToFinish() throws Exception {
service.beforeReset();
AtomicBoolean admitted = new AtomicBoolean();
Thread creator = new Thread(() -> {
createJob();
admitted.set(true);
});
creator.start();
// Waiting for the thread to actually park proves the reset blocked it. A plain sleep would
// pass while the thread was merely unscheduled, and stay green with the blocking removed.
awaitParked(creator, "the create waiting on the reset");
assertFalse(admitted.get(), "a create must not be admitted while the reset is in progress");
service.afterReset();
creator.join(5_000);
assertTrue(admitted.get(), "afterReset must release the waiting create");
}
@Test
void theExportBucketIsScopedToTheJobsAccount() {
// An object write resolves its bucket across accounts under global-bucket-namespace, so a
// shared name would put this account's export in whichever account created the bucket.
createJob();
tasks.forEach(Runnable::run);
ArgumentCaptor<String> bucket = ArgumentCaptor.forClass(String.class);
verify(s3Service).putObject(bucket.capture(), anyString(), any(), anyString(), any());
assertEquals("floci-" + ACCOUNT + "-" + REGION + "-ses-export-files", bucket.getValue());
}
@Test
void identitiesDifferingOnlyInCaseShareOneRow() throws Exception {
// The aggregator matches identities without regard to case, so two rows would each count
// both sends and the export would disagree with a BatchGetMetricData query.
recordSend(Instant.parse("2026-09-23T10:00:00Z"), "a@example.com");
recordSend(Instant.parse("2026-09-23T11:00:00Z"), "A@example.com");
String csv = runMetricsExport("{\"EMAIL_IDENTITY\": [\"*\"]}",
Instant.parse("2026-09-23T00:00:00Z"), Instant.parse("2026-09-24T00:00:00Z"));
assertEquals("EMAIL_IDENTITY,SEND_VOLUME\na@example.com,2.0000\n", csv);
}
@Test
void theConcurrentJobCeilingIsThePublishedQuota() {
// SES documents 20 concurrent export jobs, the same figure it gives import jobs. The
// workers are captured here, so every job stays PROCESSING and occupies a slot.
for (int i = 0; i < SesExportJobService.MAX_CONCURRENT_JOBS; i++) {
createJob();
}
AwsException thrown = assertThrows(AwsException.class, this::createJob);
assertEquals("LimitExceededException", thrown.getErrorCode());
assertEquals(20, SesExportJobService.MAX_CONCURRENT_JOBS);
}
/** Both waits here park in {@code Object.wait(timeout)}, so the state is timed, not WAITING. */
private static void awaitParked(Thread thread, String what) {
long deadline = System.currentTimeMillis() + 5_000;
while (System.currentTimeMillis() < deadline) {
Thread.State state = thread.getState();
if (state == Thread.State.TIMED_WAITING || state == Thread.State.WAITING) {
return;
}
Thread.onSpinWait();
}
throw new AssertionError(what + " never parked, it was " + thread.getState());
}
@Test
void recoverInterruptedJobsFailsAJobOfEveryAccount() {
String otherAccount = "111122223333";
AccountAwareStorageBackend<ExportJob> persisted =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, ACCOUNT);
ExportJob stuck = new ExportJob();
stuck.setJobId("stuck");
stuck.setRegion(REGION);
stuck.setJobStatus(ExportJob.STATUS_PROCESSING);
stuck.setCreatedTimestamp(Instant.parse("2026-09-23T00:00:00Z"));
String key = "export-job::" + REGION + "::stuck";
persisted.putForAccount(otherAccount, key, stuck);
new SesExportJobService(persisted, sentEmailService, s3Service, presigner, objectMapper,
Clock.fixed(Instant.parse("2026-09-23T00:00:00Z"), ZoneOffset.UTC), tasks::add,
"http://localhost:4566");
ExportJob recovered = persisted.getForAccount(otherAccount, key).orElseThrow();
assertEquals(ExportJob.STATUS_FAILED, recovered.getJobStatus());
assertEquals(SesExportJobService.RESTART_FAILURE_MESSAGE, recovered.getErrorMessage());
}
@Test
void cancellingAFinishedJobIsRefused() {
ExportJob job = createJob();
tasks.forEach(Runnable::run);
AwsException thrown = assertThrows(AwsException.class,
() -> service.cancelExportJob(REGION, job.getJobId()));
assertEquals("Cannot cancel an export job that has a <COMPLETED> status.",
thrown.getMessage());
}
}
@@ -0,0 +1,549 @@
package io.github.hectorvent.floci.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Integration tests for the four SES v2 export-job operations.
*
* <p>Probe-confirmed against real SES (2026-09-23): a request naming its own {@code S3Url} is
* refused, exactly one data source is required, the metrics source insists on whole UTC days, an
* unknown job is a 400 rather than a 404, and a finished job cannot be cancelled. Uses an isolated
* signing region so no other test's sends reach the exported rows.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesExportJobV2IntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/eu-west-2/ses/aws4_request";
private static final String SENDER = "export-sender@example.com";
private static long midnightToday() {
return Instant.now().truncatedTo(ChronoUnit.DAYS).getEpochSecond();
}
private static Response create(String body) {
return given().contentType("application/json").header("Authorization", AUTH)
.body(body)
.when().post("/v2/email/export-jobs");
}
private static String insightsSource() {
return """
{"ExportDataSource": {"MessageInsightsDataSource":
{"StartDate": %d, "EndDate": %d}},
"ExportDestination": {"DataFormat": "CSV"}}
""".formatted(Instant.now().minus(Duration.ofDays(1)).getEpochSecond(),
Instant.now().plus(Duration.ofDays(1)).getEpochSecond());
}
private static String awaitTerminal(String jobId) {
for (int attempt = 0; attempt < 100; attempt++) {
String status = given().header("Authorization", AUTH)
.when().get("/v2/email/export-jobs/" + jobId).then().statusCode(200)
.extract().path("JobStatus");
if (!"PROCESSING".equals(status) && !"CREATED".equals(status)) {
return status;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AssertionError("interrupted while waiting for the job", e);
}
}
throw new AssertionError("export job " + jobId + " never reached a terminal state");
}
@Test
@Order(0)
void createExportJob_vdmDisabled_isABadRequestNotANotFound() {
// The same sentence message insights and metric data use, but 400 here, not 404.
create(insightsSource()).then().statusCode(400)
.body("message", containsString(
"To use this feature you must enable Virtual Deliverability Manager"));
}
@Test
@Order(1)
void enableVdmAndVerifyTheSender() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"VdmAttributes\":{\"VdmEnabled\":\"ENABLED\"}}")
.when().put("/v2/email/account/vdm").then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"EmailIdentity\":\"" + SENDER + "\"}")
.when().post("/v2/email/identities").then().statusCode(200);
}
@Test
@Order(2)
void createExportJob_refusesACallerChosenDestination() {
create("""
{"ExportDataSource": {"MessageInsightsDataSource":
{"StartDate": %d, "EndDate": %d}},
"ExportDestination": {"DataFormat": "CSV", "S3Url": "s3://mine/prefix/"}}
""".formatted(midnightToday() - 86400, midnightToday()))
.then().statusCode(400)
.body("message", equalTo("Providing a custom S3 URL is not supported"));
}
@Test
@Order(3)
void createExportJob_checksTheDestinationInTheProbedOrder() {
// Probed: the data source outranks the destination's own constraints, which outrank the
// refusal of a caller-chosen S3Url, which outranks the VDM gate.
create("""
{"ExportDataSource": {"MessageInsightsDataSource":
{"StartDate": %d, "EndDate": %d}}}
""".formatted(midnightToday() - 86400, midnightToday()))
.then().statusCode(400).body("message", equalTo(
"1 validation error detected: Value at 'exportDestination' failed to satisfy "
+ "constraint: Member must not be null"));
create("""
{"ExportDataSource": {"MessageInsightsDataSource":
{"StartDate": %d, "EndDate": %d}},
"ExportDestination": {"S3Url": "s3://mine/prefix/"}}
""".formatted(midnightToday() - 86400, midnightToday()))
.then().statusCode(400).body("message", equalTo(
"1 validation error detected: Value at 'exportDestination.dataFormat' failed to "
+ "satisfy constraint: Member must not be null"));
create("""
{"ExportDataSource": {"MessageInsightsDataSource":
{"StartDate": %d, "EndDate": %d}},
"ExportDestination": {"DataFormat": "PARQUET"}}
""".formatted(midnightToday() - 86400, midnightToday()))
.then().statusCode(400).body("message", containsString(
"Member must satisfy enum value set: [CSV, JSON]"));
// A missing data source beats even a caller-chosen destination.
create("""
{"ExportDataSource": {},
"ExportDestination": {"DataFormat": "CSV", "S3Url": "s3://mine/prefix/"}}
""")
.then().statusCode(400).body("message", equalTo("One data source must be provided"));
}
@Test
@Order(4)
void createExportJob_requiresExactlyOneDataSource() {
String both = """
{"ExportDataSource": {"MessageInsightsDataSource": {"StartDate": %d, "EndDate": %d},
"MetricsDataSource": {"Dimensions": {"ISP": ["*"]},
"Namespace": "VDM",
"Metrics": [{"Name": "SEND"}],
"StartDate": %d, "EndDate": %d}},
"ExportDestination": {"DataFormat": "CSV"}}
""".formatted(midnightToday() - 86400, midnightToday(),
midnightToday() - 86400, midnightToday());
create(both).then().statusCode(400)
.body("message", equalTo("One data source must be provided"));
create("{\"ExportDataSource\": {}, \"ExportDestination\": {\"DataFormat\": \"CSV\"}}")
.then().statusCode(400).body("message", equalTo("One data source must be provided"));
}
@Test
@Order(5)
void createExportJob_checksTheDates() {
create("""
{"ExportDataSource": {"MessageInsightsDataSource":
{"StartDate": %d, "EndDate": %d}},
"ExportDestination": {"DataFormat": "CSV"}}
""".formatted(midnightToday(), midnightToday() - 86400))
.then().statusCode(400).body("message", equalTo("Invalid date range"));
// Only the metrics source insists on whole days.
create("""
{"ExportDataSource": {"MetricsDataSource": {"Dimensions": {"ISP": ["*"]},
"Namespace": "VDM",
"Metrics": [{"Name": "SEND"}],
"StartDate": %d, "EndDate": %d}},
"ExportDestination": {"DataFormat": "CSV"}}
""".formatted(midnightToday() - 86400 + 3600, midnightToday()))
.then().statusCode(400).body("message", containsString("midnight to midnight UTC"));
}
@Test
@Order(6)
void exportJob_writesTheInsightsFileAndServesItBehindAPresignedUrl() {
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["reader@example.com"]},
"Content": {"Simple": {"Subject": {"Data": "exported"},
"Body": {"Text": {"Data": "hi"}}}}}
""".formatted(SENDER))
.when().post("/v2/email/outbound-emails").then().statusCode(200);
String jobId = create(insightsSource()).then().statusCode(200)
.extract().path("JobId");
assertEquals("COMPLETED", awaitTerminal(jobId));
Response job = given().header("Authorization", AUTH)
.when().get("/v2/email/export-jobs/" + jobId);
job.then().statusCode(200)
.body("ExportSourceType", equalTo("MESSAGE_INSIGHTS"))
.body("ExportDestination.DataFormat", equalTo("CSV"))
.body("ExportDestination.S3Url", notNullValue())
.body("ExportDataSource.MessageInsightsDataSource", notNullValue())
.body("CompletedTimestamp", notNullValue())
// Probed: AWS reports the rows examined and never ExportedRecordsCount.
.body("Statistics.ProcessedRecordsCount", equalTo(1))
.body("Statistics", not(hasKey("ExportedRecordsCount")));
// The URL is Floci's own S3 emulation, so the object is fetched back through it.
String url = job.path("ExportDestination.S3Url");
String path = url.substring(url.indexOf('/', url.indexOf("//") + 2));
String body = given().when().get(path).then().statusCode(200).extract().asString();
assertTrue(body.startsWith("\"messageid\",\"sendtimestamp\""), body.substring(0, 60));
assertTrue(body.contains("reader@example.com"), "the send should be in the export");
}
@Test
@Order(7)
void exportJob_metricsSourceCountsTheSameSends() {
String jobId = create("""
{"ExportDataSource": {"MetricsDataSource": {"Dimensions": {"ISP": ["*"]},
"Namespace": "VDM",
"Metrics": [{"Name": "SEND",
"Aggregation": "VOLUME"}],
"StartDate": %d, "EndDate": %d}},
"ExportDestination": {"DataFormat": "CSV"}}
""".formatted(midnightToday(), midnightToday() + 86400))
.then().statusCode(200).extract().path("JobId");
assertEquals("COMPLETED", awaitTerminal(jobId));
String url = given().header("Authorization", AUTH)
.when().get("/v2/email/export-jobs/" + jobId).then().statusCode(200)
.extract().path("ExportDestination.S3Url");
String path = url.substring(url.indexOf('/', url.indexOf("//") + 2));
String body = given().when().get(path).then().statusCode(200).extract().asString();
assertTrue(body.startsWith("ISP,SEND_VOLUME\n"), body);
assertTrue(body.contains("UNKNOWN_ISP,1.0000"), body);
}
@Test
@Order(8)
void cancelExportJob_refusesAFinishedJob() {
// Only the refusal is reachable here: a Floci export finishes in milliseconds, so a job is
// already COMPLETED by the time a second request arrives. The accepted-cancel path is
// covered deterministically in SesExportJobServiceTest.
String finished = create(insightsSource()).then().statusCode(200).extract().path("JobId");
assertEquals("COMPLETED", awaitTerminal(finished));
given().contentType("application/json").header("Authorization", AUTH)
.when().put("/v2/email/export-jobs/" + finished + "/cancel").then().statusCode(400)
.body("message", equalTo(
"Cannot cancel an export job that has a <COMPLETED> status."));
}
@Test
@Order(9)
void getExportJob_unknownJobIsABadRequest() {
given().header("Authorization", AUTH)
.when().get("/v2/email/export-jobs/no-such-job").then().statusCode(400)
.body("message", equalTo("Invalid JobId"));
}
@Test
@Order(10)
void listExportJobs_filtersAndPaginates() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.when().post("/v2/email/list-export-jobs").then().statusCode(200)
.body("ExportJobs.JobStatus", everyItem(equalTo("COMPLETED")));
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"ExportSourceType\": \"METRICS_DATA\"}")
.when().post("/v2/email/list-export-jobs").then().statusCode(200)
.body("ExportJobs", hasSize(1));
String nextToken = given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": 1}")
.when().post("/v2/email/list-export-jobs").then().statusCode(200)
.body("ExportJobs", hasSize(1))
.extract().path("NextToken");
assertNotNull(nextToken, "a truncated page carries a NextToken");
}
@Test
@Order(11)
void insightsExport_filtersOnTheTenantTheSendNamed() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"TenantName\": \"export-tenant\"}")
.when().post("/v2/email/tenants").then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{"TenantName": "export-tenant",
"ResourceArn": "arn:aws:ses:eu-west-2:000000000000:identity/%s"}
""".formatted(SENDER))
.when().post("/v2/email/tenants/resources").then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{"FromEmailAddress": "%s", "TenantName": "export-tenant",
"Destination": {"ToAddresses": ["in-tenant@example.com"]},
"Content": {"Simple": {"Subject": {"Data": "t"},
"Body": {"Text": {"Data": "hi"}}}}}
""".formatted(SENDER))
.when().post("/v2/email/outbound-emails").then().statusCode(200);
// reader@example.com was sent at order 6 without a tenant, so it is the row the filter
// has to drop. An Include that matched everything would keep it.
assertTrue(insightsExport("\"Include\": {\"TenantName\": [\"export-tenant\"]},")
.contains("in-tenant@example.com"));
assertFalse(insightsExport("\"Include\": {\"TenantName\": [\"export-tenant\"]},")
.contains("reader@example.com"));
String excluded = insightsExport("\"Exclude\": {\"TenantName\": [\"export-tenant\"]},");
assertTrue(excluded.contains("reader@example.com"), excluded);
assertFalse(excluded.contains("in-tenant@example.com"), excluded);
}
/** Runs a message-insights export carrying the given filter members and returns the file. */
private static String insightsExport(String filters) {
String jobId = create("""
{"ExportDataSource": {"MessageInsightsDataSource":
{%s "StartDate": %d, "EndDate": %d}},
"ExportDestination": {"DataFormat": "CSV"}}
""".formatted(filters, Instant.now().minus(Duration.ofDays(1)).getEpochSecond(),
Instant.now().plus(Duration.ofDays(1)).getEpochSecond()))
.then().statusCode(200).extract().path("JobId");
assertEquals("COMPLETED", awaitTerminal(jobId));
String url = given().header("Authorization", AUTH)
.when().get("/v2/email/export-jobs/" + jobId).then().statusCode(200)
.extract().path("ExportDestination.S3Url");
String path = url.substring(url.indexOf('/', url.indexOf("//") + 2));
return given().when().get(path).then().statusCode(200).extract().asString();
}
@Test
@Order(12)
void createExportJob_validatesTheMetricsSourceMembers() {
// Without these an unknown dimension was dropped, an unknown metric aggregated to zero and
// an unrecognised aggregation was read as VOLUME, so the job completed with a meaningless
// file. The wording follows BatchGetMetricData; AWS's own was not observed.
metricsSource("{\"NOT_A_DIMENSION\": [\"*\"]}", "\"VDM\"", "[{\"Name\": \"SEND\"}]")
.then().statusCode(400).body("message", containsString(
"Value at 'exportDataSource.metricsDataSource.dimensions' failed to satisfy "
+ "constraint: Member must satisfy enum value set: "
+ "[EMAIL_IDENTITY, CONFIGURATION_SET, ISP, TENANT_NAME]"));
metricsSource("{\"ISP\": [\"*\"]}", "\"VDM\"", "[{\"Name\": \"NOT_A_METRIC\"}]")
.then().statusCode(400).body("message", containsString(
"'exportDataSource.metricsDataSource.metrics.1.member.name'"));
metricsSource("{\"ISP\": [\"*\"]}", "\"VDM\"",
"[{\"Name\": \"SEND\", \"Aggregation\": \"AVERAGE\"}]")
.then().statusCode(400).body("message", containsString(
"'exportDataSource.metricsDataSource.metrics.1.member.aggregation'"));
metricsSource("{}", "\"SES\"", "[]")
.then().statusCode(400).body("message", containsString("3 validation errors"));
metricsSource("{\"ISP\": []}", "\"VDM\"", "[{\"Name\": \"SEND\"}]")
.then().statusCode(400).body("message", containsString(
"'exportDataSource.metricsDataSource.dimensions.ISP'"));
}
@Test
@Order(13)
void metricsExport_matchesAnIdentityDomainTheWayTheBatchQueryDoes() {
// The sender is an address; a domain names the same identity, so it has to select the row.
String jobId = metricsSource("{\"EMAIL_IDENTITY\": [\"example.com\"]}", "\"VDM\"",
"[{\"Name\": \"SEND\", \"Aggregation\": \"VOLUME\"}]")
.then().statusCode(200).extract().path("JobId");
assertEquals("COMPLETED", awaitTerminal(jobId));
String url = given().header("Authorization", AUTH)
.when().get("/v2/email/export-jobs/" + jobId).then().statusCode(200)
.extract().path("ExportDestination.S3Url");
String path = url.substring(url.indexOf('/', url.indexOf("//") + 2));
String body = given().when().get(path).then().statusCode(200).extract().asString();
assertTrue(body.startsWith("EMAIL_IDENTITY,SEND_VOLUME\n"), body);
assertTrue(body.contains(SENDER), "a domain filter has to match the addresses inside it");
}
@Test
@Order(14)
void malformedPagingAndResultLimitsAreRefused() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": \"ten\"}")
.when().post("/v2/email/list-export-jobs").then().statusCode(400);
create("""
{"ExportDataSource": {"MessageInsightsDataSource":
{"MaxResults": -1, "StartDate": %d, "EndDate": %d}},
"ExportDestination": {"DataFormat": "CSV"}}
""".formatted(midnightToday(), midnightToday() + 86400))
.then().statusCode(400).body("message", containsString("Member must be between 1 and 10000"));
}
/** A metrics export request with the three members the service validates. */
private static Response metricsSource(String dimensions, String namespace, String metrics) {
return create("""
{"ExportDataSource": {"MetricsDataSource": {"Dimensions": %s,
"Namespace": %s,
"Metrics": %s,
"StartDate": %d, "EndDate": %d}},
"ExportDestination": {"DataFormat": "CSV"}}
""".formatted(dimensions, namespace, metrics, midnightToday(),
midnightToday() + 86400));
}
@Test
@Order(15)
void exportJob_runsUnderTheCallersAccount() {
// The worker runs on its own thread, where account-aware storage falls back to the default
// account unless the caller's is carried over: the job would then never be found again.
String otherAccount = "AWS4-HMAC-SHA256 Credential=111122223333/20260101/eu-west-2/ses/"
+ "aws4_request";
given().contentType("application/json").header("Authorization", otherAccount)
.body("{\"VdmAttributes\":{\"VdmEnabled\":\"ENABLED\"}}")
.when().put("/v2/email/account/vdm").then().statusCode(200);
String jobId = given().contentType("application/json").header("Authorization", otherAccount)
.body(insightsSource())
.when().post("/v2/email/export-jobs").then().statusCode(200).extract().path("JobId");
String status = null;
for (int attempt = 0; attempt < 100 && !"COMPLETED".equals(status); attempt++) {
status = given().header("Authorization", otherAccount)
.when().get("/v2/email/export-jobs/" + jobId).then().statusCode(200)
.extract().path("JobStatus");
if ("PROCESSING".equals(status) || "CREATED".equals(status)) {
status = null;
}
}
assertEquals("COMPLETED", status, "the job never finished under its own account");
// The default account cannot see it.
given().header("Authorization", AUTH)
.when().get("/v2/email/export-jobs/" + jobId).then().statusCode(400);
given().contentType("application/json").header("Authorization", otherAccount)
.body("{\"VdmAttributes\":{\"VdmEnabled\":\"DISABLED\"}}")
.when().put("/v2/email/account/vdm");
}
@Test
@Order(16)
void listExportJobs_acceptsAPageSizeAboveTheDefault() {
// PageSize carries no bound in the model, so a large page is a normal request.
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": 250}")
.when().post("/v2/email/list-export-jobs").then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": 0}")
.when().post("/v2/email/list-export-jobs").then().statusCode(400);
// A page size at the int ceiling is clamped, not refused, and must not report a further
// page: the paginator adds the page size to the offset as an int.
String token = given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": 1}")
.when().post("/v2/email/list-export-jobs").then().statusCode(200)
.extract().path("NextToken");
assertNotNull(token, "the fixture needs more than one job for this to mean anything");
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": 2147483647, \"NextToken\": \"%s\"}".formatted(token))
.when().post("/v2/email/list-export-jobs").then().statusCode(200)
.body("$", not(hasKey("NextToken")));
}
@Test
@Order(17)
void createExportJob_rejectsMembersOfTheWrongType() {
// Each of these was read as absent or coerced, so the job was created and produced a
// successful but meaningless file. They are deserialization errors, like every other
// typed SES v2 member.
create("""
{"ExportDataSource": {"MessageInsightsDataSource": {"StartDate": %d, "EndDate": %d},
"MetricsDataSource": []},
"ExportDestination": {"DataFormat": "CSV"}}
""".formatted(midnightToday(), midnightToday() + 86400))
.then().statusCode(400).body("__type", equalTo("SerializationException"));
create("""
{"ExportDataSource": {"MessageInsightsDataSource":
{"Include": {"TenantName": "blue"}, "StartDate": %d, "EndDate": %d}},
"ExportDestination": {"DataFormat": "CSV"}}
""".formatted(midnightToday(), midnightToday() + 86400))
.then().statusCode(400).body("__type", equalTo("SerializationException"));
metricsSource("{\"ISP\": [1]}", "\"VDM\"", "[{\"Name\": \"SEND\"}]")
.then().statusCode(400).body("__type", equalTo("SerializationException"));
metricsSource("{\"ISP\": [\"*\"]}", "\"VDM\"", "[\"SEND\"]")
.then().statusCode(400).body("__type", equalTo("SerializationException"));
// A MaxResults of the wrong type is a deserialization error, not a value out of range.
insightsWith("\"MaxResults\": \"100\",")
.then().statusCode(400).body("__type", equalTo("SerializationException"));
}
@Test
@Order(18)
void createExportJob_holdsEachFilterMemberToItsLength() {
// The model allows one Subject and two LastEngagementEvent values.
insightsWith("\"Include\": {\"Subject\": [\"one\", \"two\"]},")
.then().statusCode(400).body("message", equalTo(
"1 validation error detected: Value at 'exportDataSource."
+ "messageInsightsDataSource.include.subject' failed to satisfy "
+ "constraint: Member must have length less than or equal to 1"));
insightsWith("\"Exclude\": {\"LastEngagementEvent\": [\"OPEN\", \"CLICK\", \"OPEN\"]},")
.then().statusCode(400).body("message", containsString(
"exclude.lastEngagementEvent' failed to satisfy constraint: Member must "
+ "have length less than or equal to 2"));
insightsWith("\"Include\": {\"Isp\": [\"a\", \"b\", \"c\", \"d\", \"e\"]},")
.then().statusCode(200);
}
/** A message-insights export request carrying the given extra members. */
private static Response insightsWith(String members) {
return create("""
{"ExportDataSource": {"MessageInsightsDataSource":
{%s "StartDate": %d, "EndDate": %d}},
"ExportDestination": {"DataFormat": "CSV"}}
""".formatted(members, midnightToday(), midnightToday() + 86400));
}
@Test
@Order(19)
void cleanUpVdmAndIdentity() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"VdmAttributes\":{\"VdmEnabled\":\"DISABLED\"}}")
.when().put("/v2/email/account/vdm");
given().header("Authorization", AUTH)
.when().delete("/v2/email/identities/" + SENDER);
}
}
@@ -0,0 +1,136 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.services.ses.model.EmailInsights;
import io.github.hectorvent.floci.services.ses.model.InsightsBounce;
import io.github.hectorvent.floci.services.ses.model.InsightsEvent;
import io.github.hectorvent.floci.services.ses.model.InsightsEventDetails;
import io.github.hectorvent.floci.services.ses.model.SentEmail;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The export payloads. Every column name, the quoting, the timestamp pattern and the trailing
* comma are probe-confirmed against real SES, so this test pins the wire format rather than
* Floci's preference.
*/
class SesExportPayloadsTest {
private static final Instant SENT = Instant.parse("2026-09-21T01:02:03.123Z");
private static final String HEADER =
"\"messageid\",\"sendtimestamp\",\"isp\",\"fromaddress\",\"destination\",\"subject\","
+ "\"last_delivery_event\",\"last_engagement_event\","
+ "\"last_delivery_event_timestamp\",\"last_engagement_event_timestamp\","
+ "\"bounce_sub_type\",\"diagnostic_code\",";
private static SentEmail email(String subject, EmailInsights... recipients) {
SentEmail email = new SentEmail();
email.setMessageId("message-1");
email.setSource("sender@example.com");
email.setSubject(subject);
email.setSentAt(SENT);
email.setInsights(List.of(recipients));
return email;
}
private static EmailInsights delivered(String destination) {
return new EmailInsights(destination, "UNKNOWN_ISP", List.of(
InsightsEvent.of(SENT, "SEND"), InsightsEvent.of(SENT, "DELIVERY")));
}
private static EmailInsights bounced(String destination) {
return new EmailInsights(destination, "UNKNOWN_ISP", List.of(
InsightsEvent.of(SENT, "SEND"),
new InsightsEvent(SENT, "BOUNCE", new InsightsEventDetails(
new InsightsBounce("PERMANENT", "General", "smtp; 550 user unknown"), null))));
}
private static String csv(List<SentEmail> emails) {
return new String(SesExportPayloads.insightsCsv(SesExportPayloads.insightsRows(emails)),
StandardCharsets.UTF_8);
}
@Test
void insightsCsvCarriesTheProbedHeaderIncludingItsTrailingComma() {
String[] lines = csv(List.of(email("hello", delivered("user@example.com")))).split("\n");
assertEquals(HEADER, lines[0]);
assertEquals("\"message-1\",\"2026-09-21 01:02:03.123 UTC\",\"UNKNOWN_ISP\","
+ "\"sender@example.com\",\"user@example.com\",\"hello\",\"DELIVERY\",\"\","
+ "\"2026-09-21 01:02:03.123 UTC\",\"\",\"\",\"\",", lines[1]);
}
@Test
void oneRowPerRecipientNotPerMessage() {
String[] lines = csv(List.of(email("hello",
delivered("a@example.com"), delivered("b@example.com")))).split("\n");
assertEquals(3, lines.length);
}
@Test
void aBounceReportsItsTypeAndCarriesTheDetails() {
String[] lines = csv(List.of(email("hello", bounced("user@example.com")))).split("\n");
assertTrue(lines[1].contains("\"PERMANENT_BOUNCE\""), lines[1]);
assertTrue(lines[1].contains("\"General\""), lines[1]);
assertTrue(lines[1].contains("\"smtp; 550 user unknown\""), lines[1]);
}
@Test
void quotesInsideAValueAreDoubled() {
String row = csv(List.of(email("say \"hi\"", delivered("user@example.com")))).split("\n")[1];
assertTrue(row.contains("\"say \"\"hi\"\"\""), row);
}
@Test
void insightsJsonIsOneArrayWithTheCommaLeadingEachRowAfterTheFirst() {
String json = new String(SesExportPayloads.insightsJson(SesExportPayloads.insightsRows(
List.of(email("hello", delivered("a@example.com"), delivered("b@example.com"))))),
StandardCharsets.UTF_8);
String[] lines = json.split("\n");
assertEquals("[", lines[0]);
assertTrue(lines[1].startsWith("{\"messageid\":\"message-1\""), lines[1]);
assertTrue(lines[2].startsWith(",{"), lines[2]);
assertEquals("]", lines[3]);
}
@Test
void metricsCsvNamesTheDimensionThenEachMetricAndAggregation() {
String csv = new String(SesExportPayloads.metricsCsv(List.of("ISP"),
List.of("SEND_VOLUME", "DELIVERY_VOLUME"),
List.of(new SesExportPayloads.MetricRow(List.of("UNKNOWN_ISP"), List.of(3.0, 2.0)))),
StandardCharsets.UTF_8);
assertEquals("ISP,SEND_VOLUME,DELIVERY_VOLUME\nUNKNOWN_ISP,3.0000,2.0000\n", csv);
}
@Test
void metricsCsvQuotesOnlyTheValuesThatNeedIt() {
// The probed file leaves values bare, but an unquoted comma would shift every later column.
String csv = new String(SesExportPayloads.metricsCsv(List.of("EMAIL_IDENTITY"),
List.of("SEND_VOLUME"),
List.of(new SesExportPayloads.MetricRow(List.of("a,b@example.com"), List.of(1.0)))),
StandardCharsets.UTF_8);
assertEquals("EMAIL_IDENTITY,SEND_VOLUME\n\"a,b@example.com\",1.0000\n", csv);
}
@Test
void metricsJsonKeysTheDimensionInLowerCaseAndNestsTheMetrics() {
String json = new String(SesExportPayloads.metricsJson(List.of("ISP"),
List.of("DELIVERY_RATE"),
List.of(new SesExportPayloads.MetricRow(List.of("UNKNOWN_ISP"), List.of(0.5)))),
StandardCharsets.UTF_8);
assertEquals("[{\"isp\":\"UNKNOWN_ISP\",\"metrics\":{\"DELIVERY_RATE\":0.5000}}]\n", json);
}
}