feat(ses): add v2 import jobs for the suppression list and contact lists (#3892)

* feat(ses): add v2 import jobs for the suppression list and contact lists

Implements CreateImportJob, GetImportJob and ListImportJobs. A job reads a
CSV or newline-delimited JSON object from the local S3 emulation and applies
each record through the existing suppression-list and contact services, so
the imported rows land in their stores and only the job record is new.

The job is returned as CREATED and runs on a virtual thread under the request
account, moving to PROCESSING and then COMPLETED or FAILED, as on AWS. Records
that fail validation are counted in FailedRecordsCount while the job still
completes; a missing bucket or object, a contact-list CSV without an
emailAddress header, or a contact list deleted before the worker runs fail
the job with FailureInfo.ErrorMessage. At most 20 jobs per region may be in
progress, and jobs interrupted by a restart are marked FAILED on startup.

* fix(ses): accept the guide's unquoted contact row and match AWS's import not-found message

A quote that does not open a CSV field is data rather than an error: the SES
list-management guide writes attributesData unquoted as {"Name": "John"}, so
rejecting it refused the documented format. Garbage after a closing quote is
still a failed record, since that row cannot be read back unambiguously.

An import job for an unknown contact list answers NotFoundException with its
own wording, "ContactList <name> doesn't exist", which differs from the
contact-list APIs. Probed against real SES: the check is synchronous and the
error is NotFoundException, even though the service model lists only
BadRequestException, LimitExceededException and TooManyRequestsException for
CreateImportJob. The contact service keeps its own message.

Also drops five unused imports and a dead stripBom that held the only literal
BOM character in the reader sources.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-09-19 10:05:42 -04:00
1 parent fb9deb1e89
commit 8ca748355d
17 files changed
+2775 -1

No files matched your search

@@ -0,0 +1,656 @@
package io.github.hectorvent.floci.services.ses;
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.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ses.model.Contact;
import io.github.hectorvent.floci.services.ses.model.ImportJob;
import io.github.hectorvent.floci.services.ses.model.Topic;
import io.github.hectorvent.floci.services.ses.model.TopicPreference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
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.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
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.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.when;
/**
* Unit test for the import-job domain: request validation, the CSV / newline-delimited JSON record
* formats, per-record failure counting versus whole-job failure, and the concurrency limit. The
* worker executor runs inline so a job is terminal by the time create returns; S3 is a mock, the
* suppression and contact services are real ones over in-memory stores so the imported rows can be
* read back.
*/
class SesImportJobServiceTest {
private static final String REGION = "eu-west-3";
private static final String ACCOUNT = "000000000000";
private static final String BUCKET = "imports";
private static final String LIST = "newsletter";
private S3Service s3Service;
private SesSuppressionService suppressionService;
private SesContactService contactService;
private InMemoryStorage<String, ImportJob> jobStore;
private SesImportJobService service;
@BeforeEach
void setUp() {
s3Service = mock(S3Service.class);
Clock clock = Clock.fixed(Instant.parse("2026-09-18T00:00:00Z"), ZoneOffset.UTC);
suppressionService = new SesSuppressionService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>());
contactService = new SesContactService(new InMemoryStorage<>(), new InMemoryStorage<>(), clock);
contactService.createContactList(LIST, null,
List.of(new Topic("Sports", "Sports", "OPT_OUT", null),
new Topic("Cycling", "Cycling", "OPT_IN", null)),
null, REGION);
jobStore = new InMemoryStorage<>();
service = newService(Runnable::run);
}
private SesImportJobService newService(Executor workers) {
return new SesImportJobService(jobStore, s3Service, suppressionService, contactService,
new ObjectMapper().findAndRegisterModules(), Clock.systemUTC(), workers);
}
private void stubObject(String key, String content) {
when(s3Service.openObjectStream(BUCKET, key, null)).thenAnswer(
invocation -> new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
}
private static String url(String key) {
return "s3://" + BUCKET + "/" + key;
}
// ──────────────────────────── Suppression list ────────────────────────────
@Test
void suppressionCsvPut_addsEveryRowAndCompletes() {
stubObject("add.csv", "alice@example.com,BOUNCE\nbob@example.com,COMPLAINT\n");
ImportJob job = service.createSuppressionListImportJob(REGION, ACCOUNT, url("add.csv"), "CSV", "PUT");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_COMPLETED, stored.getJobStatus());
assertEquals(2, stored.getProcessedRecordsCount());
assertEquals(0, stored.getFailedRecordsCount());
assertNotNull(stored.getCompletedTimestamp());
assertNull(stored.getErrorMessage());
assertEquals("BOUNCE", suppressionService.getSuppressedDestination(REGION, "alice@example.com").getReason());
assertEquals("COMPLAINT", suppressionService.getSuppressedDestination(REGION, "bob@example.com").getReason());
}
@Test
void suppressionJsonPut_countsInvalidRowsAsFailedButCompletes() {
stubObject("add.json", """
{"emailAddress":"alice@example.com","reason":"BOUNCE"}
{"emailAddress":"bob@example.com","reason":"SPAM"}
not json at all
{"emailAddress":"carol@example.com","reason":"COMPLAINT"}
""");
ImportJob job = service.createSuppressionListImportJob(REGION, ACCOUNT, url("add.json"), "JSON", "PUT");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_COMPLETED, stored.getJobStatus());
assertEquals(4, stored.getProcessedRecordsCount());
assertEquals(2, stored.getFailedRecordsCount());
assertEquals(2, suppressionService.listSuppressedDestinations(REGION, null).size());
}
@Test
void suppressionCsvDelete_removesListedAddresses_missingOnesFail() {
suppressionService.putSuppressedDestination(REGION, "alice@example.com", "BOUNCE");
stubObject("remove.csv", "alice@example.com\nnobody@example.com\n");
ImportJob job = service.createSuppressionListImportJob(REGION, ACCOUNT, url("remove.csv"), "CSV", "DELETE");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_COMPLETED, stored.getJobStatus());
assertEquals(2, stored.getProcessedRecordsCount());
assertEquals(1, stored.getFailedRecordsCount());
assertTrue(suppressionService.listSuppressedDestinations(REGION, null).isEmpty());
}
// ──────────────────────────── Contact list ────────────────────────────
@Test
void contactCsvPut_readsHeaderTopicColumnsAndQuotedAttributes() {
stubObject("contacts.csv", """
emailAddress,unsubscribeAll,attributesData,topicPreferences.Sports,topicPreferences.Cycling
alice@example.com,false,"{""Name"":""Alice"",""City"":""Paris""}",OPT_IN,OPT_OUT
bob@example.com,true,,OPT_OUT,
""");
ImportJob job = service.createContactListImportJob(REGION, ACCOUNT, url("contacts.csv"), "CSV", LIST, "PUT");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_COMPLETED, stored.getJobStatus());
assertEquals(2, stored.getProcessedRecordsCount());
assertEquals(0, stored.getFailedRecordsCount());
Contact alice = contactService.getContact(LIST, "alice@example.com", REGION).contact();
assertEquals("{\"Name\":\"Alice\",\"City\":\"Paris\"}", alice.getAttributesData());
assertEquals(Map.of("Sports", "OPT_IN", "Cycling", "OPT_OUT"), preferences(alice));
Contact bob = contactService.getContact(LIST, "bob@example.com", REGION).contact();
assertTrue(bob.isUnsubscribeAll());
assertNull(bob.getAttributesData());
assertEquals(Map.of("Sports", "OPT_OUT"), preferences(bob));
}
@Test
void contactJsonPut_overridesExistingContact() {
contactService.createContact(LIST, "alice@example.com",
List.of(new TopicPreference("Sports", "OPT_OUT")), false, "{\"old\":true}", REGION);
stubObject("contacts.json", """
{"emailAddress":"alice@example.com","unsubscribeAll":true,"attributesData":"{\\"new\\":true}",
"topicPreferences":[{"topicName":"Cycling","subscriptionStatus":"OPT_IN"}]}
""".replace("\n", ""));
ImportJob job = service.createContactListImportJob(REGION, ACCOUNT, url("contacts.json"), "JSON", LIST, "PUT");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_COMPLETED, stored.getJobStatus());
assertEquals(0, stored.getFailedRecordsCount());
Contact alice = contactService.getContact(LIST, "alice@example.com", REGION).contact();
assertTrue(alice.isUnsubscribeAll());
assertEquals("{\"new\":true}", alice.getAttributesData());
// Probed against real AWS: a PUT import replaces the contact outright, so the Sports
// preference this record omits is cleared rather than merged.
assertEquals(Map.of("Cycling", "OPT_IN"), preferences(alice));
// A record carrying only the address clears the rest for the same reason.
stubObject("bare.json", "{\"emailAddress\":\"alice@example.com\"}\n");
service.createContactListImportJob(REGION, ACCOUNT, url("bare.json"), "JSON", LIST, "PUT");
Contact cleared = contactService.getContact(LIST, "alice@example.com", REGION).contact();
assertEquals(Map.of(), preferences(cleared));
assertFalse(cleared.isUnsubscribeAll());
assertNull(cleared.getAttributesData());
}
@Test
void contactCsv_unknownTopicAndBadBooleanAreFailedRecords() {
stubObject("contacts.csv", """
emailAddress,unsubscribeAll,topicPreferences.Chess
alice@example.com,false,OPT_IN
bob@example.com,maybe,
carol@example.com,,
""");
ImportJob job = service.createContactListImportJob(REGION, ACCOUNT, url("contacts.csv"), "CSV", LIST, "PUT");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_COMPLETED, stored.getJobStatus());
assertEquals(3, stored.getProcessedRecordsCount());
assertEquals(2, stored.getFailedRecordsCount());
assertEquals(1, contactService.listContacts(LIST, REGION).contacts().size());
}
@Test
void contactJsonDelete_removesContacts() {
contactService.createContact(LIST, "alice@example.com", null, false, null, REGION);
stubObject("remove.json", "{\"emailAddress\":\"alice@example.com\"}\n{\"emailAddress\":\"ghost@example.com\"}\n");
ImportJob job = service.createContactListImportJob(REGION, ACCOUNT, url("remove.json"), "JSON", LIST, "DELETE");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_COMPLETED, stored.getJobStatus());
assertEquals(1, stored.getFailedRecordsCount());
assertTrue(contactService.listContacts(LIST, REGION).contacts().isEmpty());
}
@Test
void contactCsv_withoutEmailAddressHeader_failsTheJob() {
stubObject("contacts.csv", "email,unsubscribeAll\nalice@example.com,false\n");
ImportJob job = service.createContactListImportJob(REGION, ACCOUNT, url("contacts.csv"), "CSV", LIST, "PUT");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_FAILED, stored.getJobStatus());
assertTrue(stored.getErrorMessage().contains("emailAddress"));
assertNotNull(stored.getCompletedTimestamp());
}
// ──────────────────────────── Whole-job failure ────────────────────────────
@Test
void missingObject_failsTheJobWithTheS3Message() {
when(s3Service.openObjectStream(eq(BUCKET), anyString(), eq(null))).thenThrow(
new AwsException("NoSuchKey", "The specified key does not exist.", 404));
ImportJob job = service.createSuppressionListImportJob(REGION, ACCOUNT, url("missing.csv"), "CSV", "PUT");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_FAILED, stored.getJobStatus());
assertEquals("The specified key does not exist.", stored.getErrorMessage());
assertEquals(0, stored.getProcessedRecordsCount());
}
@Test
void contactListDeletedBeforeTheWorkerRuns_failsTheJob() {
stubObject("contacts.csv", "emailAddress\nalice@example.com\n");
// Hold the worker so the list can be deleted between create and run.
List<Runnable> queued = new ArrayList<>();
SesImportJobService deferred = newService(queued::add);
ImportJob job = deferred.createContactListImportJob(REGION, ACCOUNT, url("contacts.csv"), "CSV", LIST, "PUT");
assertEquals(ImportJob.STATUS_CREATED, deferred.getImportJob(REGION, job.getJobId()).getJobStatus());
contactService.deleteContactList(LIST, REGION);
queued.forEach(Runnable::run);
ImportJob stored = deferred.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_FAILED, stored.getJobStatus());
assertNotNull(stored.getErrorMessage());
}
// ──────────────────────────── Validation ────────────────────────────
@Test
void create_rejectsBadUrlFormatAndAction() {
assertBadRequest(() -> service.createSuppressionListImportJob(REGION, ACCOUNT, "https://x/y", "CSV", "PUT"));
assertBadRequest(() -> service.createSuppressionListImportJob(REGION, ACCOUNT, "s3://bucket", "CSV", "PUT"));
assertBadRequest(() -> service.createSuppressionListImportJob(REGION, ACCOUNT, url("a.csv"), "XML", "PUT"));
assertBadRequest(() -> service.createSuppressionListImportJob(REGION, ACCOUNT, url("a.csv"), "CSV", "UPSERT"));
assertTrue(service.listImportJobs(REGION, null, null, null).isEmpty());
}
@Test
void create_unknownContactList_isNotFound() {
AwsException e = assertThrows(AwsException.class,
() -> service.createContactListImportJob(REGION, ACCOUNT, url("a.csv"), "CSV", "missing", "PUT"));
assertEquals("NotFoundException", e.getErrorCode());
// Probed against real AWS: this path words it differently from the contact-list APIs.
assertEquals("ContactList <missing> doesn't exist", e.getMessage());
assertTrue(service.listImportJobs(REGION, null, null, null).isEmpty());
}
@Test
void create_rejectsMoreThanTwentyInProgressJobs() {
stubObject("a.csv", "alice@example.com,BOUNCE\n");
SesImportJobService parked = newService(task -> { });
for (int i = 0; i < SesImportJobService.MAX_CONCURRENT_JOBS; i++) {
parked.createSuppressionListImportJob(REGION, ACCOUNT, url("a.csv"), "CSV", "PUT");
}
AwsException e = assertThrows(AwsException.class,
() -> parked.createSuppressionListImportJob(REGION, ACCOUNT, url("a.csv"), "CSV", "PUT"));
assertEquals("LimitExceededException", e.getErrorCode());
// Jobs in another region do not count against this region's limit.
assertEquals(ImportJob.STATUS_CREATED,
parked.createSuppressionListImportJob("us-east-1", ACCOUNT, url("a.csv"), "CSV", "PUT").getJobStatus());
}
@Test
void getImportJob_unknownId_isNotFound() {
AwsException e = assertThrows(AwsException.class, () -> service.getImportJob(REGION, "nope"));
assertEquals("NotFoundException", e.getErrorCode());
assertEquals(404, e.getHttpStatus());
}
@Test
void listImportJobs_filtersByDestinationTypeAndRejectsBadPaging() {
stubObject("a.csv", "alice@example.com,BOUNCE\n");
stubObject("c.csv", "emailAddress\ncarol@example.com\n");
service.createSuppressionListImportJob(REGION, ACCOUNT, url("a.csv"), "CSV", "PUT");
service.createContactListImportJob(REGION, ACCOUNT, url("c.csv"), "CSV", LIST, "PUT");
assertEquals(2, service.listImportJobs(REGION, null, null, null).size());
assertEquals(1, service.listImportJobs(REGION, "CONTACT_LIST", 10, null).size());
assertEquals(1, service.listImportJobs(REGION, "SUPPRESSION_LIST", null, null).size());
assertTrue(service.listImportJobs("us-east-1", null, null, null).isEmpty());
assertBadRequest(() -> service.listImportJobs(REGION, "EXPORT", null, null));
assertBadRequest(() -> service.listImportJobs(REGION, null, 0, null));
assertBadRequest(() -> service.listImportJobs(REGION, null, null, "token"));
}
@Test
void jsonLine_withTrailingTokensOrWrongMemberTypes_isAFailedRecord() {
stubObject("contacts.json", """
{"emailAddress":"alice@example.com"} garbage
{"emailAddress":"bob@example.com","attributesData":123}
{"emailAddress":"carol@example.com","topicPreferences":[{"topicName":"Sports","subscriptionStatus":true}]}
{"emailAddress":"dave@example.com","topicPreferences":["Sports"]}
{"emailAddress":"erin@example.com"}
""");
ImportJob job = service.createContactListImportJob(REGION, ACCOUNT, url("contacts.json"), "JSON", LIST, "PUT");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_COMPLETED, stored.getJobStatus());
assertEquals(5, stored.getProcessedRecordsCount());
assertEquals(4, stored.getFailedRecordsCount());
assertEquals(1, contactService.listContacts(LIST, REGION).contacts().size());
}
@Test
void contactCsv_quotedFieldMayContainLineBreaks() {
stubObject("contacts.csv", "emailAddress,attributesData\r\n"
+ "alice@example.com,\"{\r\n \"\"Name\"\": \"\"Alice\"\"\r\n}\"\r\n"
+ "bob@example.com,\r\n");
ImportJob job = service.createContactListImportJob(REGION, ACCOUNT, url("contacts.csv"), "CSV", LIST, "PUT");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_COMPLETED, stored.getJobStatus());
assertEquals(2, stored.getProcessedRecordsCount());
assertEquals(0, stored.getFailedRecordsCount());
assertEquals("{\r\n \"Name\": \"Alice\"\r\n}",
contactService.getContact(LIST, "alice@example.com", REGION).contact().getAttributesData());
}
@Test
void create_isSerializedAgainstTheConcurrencyLimit() throws InterruptedException {
stubObject("a.csv", "alice@example.com,BOUNCE\n");
SesImportJobService parked = newService(task -> { });
int attempts = SesImportJobService.MAX_CONCURRENT_JOBS * 2;
CountDownLatch start = new CountDownLatch(1);
AtomicInteger rejected = new AtomicInteger();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < attempts; i++) {
Thread t = new Thread(() -> {
try {
start.await();
parked.createSuppressionListImportJob(REGION, ACCOUNT, url("a.csv"), "CSV", "PUT");
} catch (AwsException e) {
rejected.incrementAndGet();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
threads.add(t);
t.start();
}
start.countDown();
for (Thread t : threads) {
t.join();
}
assertEquals(SesImportJobService.MAX_CONCURRENT_JOBS, rejected.get());
assertEquals(SesImportJobService.MAX_CONCURRENT_JOBS, parked.listImportJobs(REGION, null, null, null).size());
}
@Test
void beforeReset_stopsAQueuedWorkerBeforeItWrites() {
stubObject("a.csv", "alice@example.com,BOUNCE\n");
List<Runnable> queued = new ArrayList<>();
SesImportJobService deferred = newService(queued::add);
ImportJob job = deferred.createSuppressionListImportJob(REGION, ACCOUNT, url("a.csv"), "CSV", "PUT");
deferred.beforeReset();
queued.forEach(Runnable::run);
deferred.afterReset();
assertEquals(ImportJob.STATUS_CREATED, deferred.getImportJob(REGION, job.getJobId()).getJobStatus());
assertTrue(suppressionService.listSuppressedDestinations(REGION, null).isEmpty());
}
@Test
void beforeReset_waitsForARunningWorkerAndBlocksCreatesUntilAfterReset() throws Exception {
CountDownLatch s3Blocked = new CountDownLatch(1);
CountDownLatch releaseS3 = new CountDownLatch(1);
when(s3Service.openObjectStream(BUCKET, "slow.csv", null)).thenAnswer(invocation -> {
s3Blocked.countDown();
releaseS3.await();
return new ByteArrayInputStream("alice@example.com,BOUNCE\n".getBytes(StandardCharsets.UTF_8));
});
stubObject("a.csv", "bob@example.com,BOUNCE\n");
SesImportJobService threaded = newService(task -> new Thread(task).start());
ImportJob slow = threaded.createSuppressionListImportJob(REGION, ACCOUNT, url("slow.csv"), "CSV", "PUT");
assertTrue(s3Blocked.await(5, TimeUnit.SECONDS));
Thread reset = new Thread(threaded::beforeReset);
reset.start();
reset.join(300);
assertTrue(reset.isAlive(), "beforeReset must wait for the running worker");
// The create has to race the drain, not follow it: a job admitted between beforeReset and
// the storage wipe is exactly what the admission gate exists to stop.
AtomicInteger created = new AtomicInteger();
Thread create = new Thread(() -> {
threaded.createSuppressionListImportJob(REGION, ACCOUNT, url("a.csv"), "CSV", "PUT");
created.incrementAndGet();
});
create.start();
create.join(300);
assertEquals(0, created.get(), "a create arriving while the drain runs waits");
releaseS3.countDown();
reset.join(5_000);
assertFalse(reset.isAlive(), "beforeReset returns once the worker has left");
create.join(300);
assertEquals(0, created.get(), "and keeps waiting until the reset finishes");
threaded.afterReset();
create.join(5_000);
assertEquals(1, created.get());
// The slow worker was abandoned: no write after the reset started.
assertEquals(ImportJob.STATUS_PROCESSING, threaded.getImportJob(REGION, slow.getJobId()).getJobStatus());
assertTrue(suppressionService.findSuppressedDestination(REGION, "alice@example.com").isEmpty());
}
@Test
void beforeReset_givesUpOnAWedgedWorkerInsteadOfHangingTheReset() throws Exception {
CountDownLatch blocked = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
when(s3Service.openObjectStream(BUCKET, "wedged.csv", null)).thenAnswer(invocation -> {
blocked.countDown();
release.await();
return new ByteArrayInputStream("alice@example.com,BOUNCE\n".getBytes(StandardCharsets.UTF_8));
});
SesImportJobService threaded = new SesImportJobService(jobStore, s3Service, suppressionService,
contactService, new ObjectMapper().findAndRegisterModules(), Clock.systemUTC(),
task -> new Thread(task).start(), 200);
threaded.createSuppressionListImportJob(REGION, ACCOUNT, url("wedged.csv"), "CSV", "PUT");
assertTrue(blocked.await(5, TimeUnit.SECONDS));
// The worker never finishes, so the drain has to time out rather than block the reset.
long started = System.currentTimeMillis();
threaded.beforeReset();
long waited = System.currentTimeMillis() - started;
assertTrue(waited >= 200, "the drain should wait for its deadline, waited " + waited + "ms");
assertTrue(waited < 5_000, "beforeReset must return on the deadline, waited " + waited + "ms");
release.countDown();
threaded.afterReset();
}
@Test
void storedJobIsASnapshot_soAnEarlierPollIsNeverMutatedUnderTheReader() throws Exception {
CountDownLatch blocked = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
when(s3Service.openObjectStream(BUCKET, "slow.csv", null)).thenAnswer(invocation -> {
blocked.countDown();
release.await();
return new ByteArrayInputStream("alice@example.com,BOUNCE\n".getBytes(StandardCharsets.UTF_8));
});
SesImportJobService threaded = newService(task -> new Thread(task).start());
ImportJob job = threaded.createSuppressionListImportJob(REGION, ACCOUNT, url("slow.csv"), "CSV", "PUT");
assertTrue(blocked.await(5, TimeUnit.SECONDS));
ImportJob midRun = threaded.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_PROCESSING, midRun.getJobStatus());
release.countDown();
ImportJob finished = awaitTerminal(threaded, job.getJobId());
assertEquals(ImportJob.STATUS_COMPLETED, finished.getJobStatus());
assertNotNull(finished.getCompletedTimestamp());
assertEquals(1, finished.getProcessedRecordsCount());
// The worker keeps mutating its own copy, so the record the earlier poll returned is frozen:
// a poll can never catch a transition half applied (COMPLETED with no CompletedTimestamp).
assertEquals(ImportJob.STATUS_PROCESSING, midRun.getJobStatus());
assertEquals(0, midRun.getProcessedRecordsCount());
assertNull(midRun.getCompletedTimestamp());
}
private static ImportJob awaitTerminal(SesImportJobService service, String jobId) throws InterruptedException {
for (int i = 0; i < 250; i++) {
ImportJob job = service.getImportJob(REGION, jobId);
if (job.isTerminal()) {
return job;
}
Thread.sleep(20);
}
throw new AssertionError("import job " + jobId + " never reached a terminal status");
}
@Test
void longImportRepublishesItsCountersAsItRuns() {
int records = SesImportJobService.PROGRESS_RECORD_INTERVAL * 2 + 5;
StringBuilder csv = new StringBuilder();
for (int i = 0; i < records; i++) {
csv.append("user").append(i).append("@example.com,BOUNCE\n");
}
stubObject("bulk.csv", csv.toString());
List<Long> publishedCounts = new ArrayList<>();
StorageBackend<String, ImportJob> recording = new InMemoryStorage<>() {
@Override
public void put(String key, ImportJob value) {
publishedCounts.add(value.getProcessedRecordsCount());
super.put(key, value);
}
};
SesImportJobService service = new SesImportJobService(recording, s3Service, suppressionService,
contactService, new ObjectMapper().findAndRegisterModules(), Clock.systemUTC(), Runnable::run);
ImportJob job = service.createSuppressionListImportJob(REGION, ACCOUNT, url("bulk.csv"), "CSV", "PUT");
assertEquals(records, service.getImportJob(REGION, job.getJobId()).getProcessedRecordsCount());
// A poll partway through sees real progress rather than 0 until the job ends.
assertEquals(List.of(0L, 0L, 100L, 200L, (long) records), publishedCounts);
}
@Test
void suppressionCsv_wrongColumnCountIsAFailedRecord() {
stubObject("mixed.csv", "alice@example.com,BOUNCE,extra\nbob@example.com\ncarol@example.com,COMPLAINT\n");
ImportJob job = service.createSuppressionListImportJob(REGION, ACCOUNT, url("mixed.csv"), "CSV", "PUT");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(3, stored.getProcessedRecordsCount());
assertEquals(2, stored.getFailedRecordsCount());
assertEquals(1, suppressionService.listSuppressedDestinations(REGION, null).size());
}
@Test
void csv_unterminatedQuote_failsTheJob() {
stubObject("broken.csv", "emailAddress,attributesData\nalice@example.com,\"{unterminated\n");
ImportJob job = service.createContactListImportJob(REGION, ACCOUNT, url("broken.csv"), "CSV", LIST, "PUT");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_FAILED, stored.getJobStatus());
assertTrue(stored.getErrorMessage().contains("unterminated"));
assertTrue(contactService.listContacts(LIST, REGION).contacts().isEmpty());
}
@Test
void contactListDeletedDuringTheRun_failsTheJob() {
stubObject("contacts.csv", "emailAddress\nalice@example.com\nbob@example.com\n");
SesContactService deletingService = mock(SesContactService.class);
when(deletingService.getContactList(LIST, REGION)).thenReturn(contactService.getContactList(LIST, REGION));
when(deletingService.createContact(eq(LIST), anyString(), any(),
any(), any(), eq(REGION)))
.thenAnswer(invocation -> {
when(deletingService.getContactList(LIST, REGION))
.thenThrow(new AwsException("NotFoundException", "List " + LIST + " not found.", 404));
throw new AwsException("NotFoundException", "List " + LIST + " not found.", 404);
});
SesImportJobService racing = new SesImportJobService(jobStore, s3Service, suppressionService,
deletingService, new ObjectMapper().findAndRegisterModules(), Clock.systemUTC(), Runnable::run);
ImportJob job = racing.createContactListImportJob(REGION, ACCOUNT, url("contacts.csv"), "CSV", LIST, "PUT");
ImportJob stored = racing.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_FAILED, stored.getJobStatus());
assertEquals("ContactList <" + LIST + "> doesn't exist", stored.getErrorMessage());
assertEquals(1, stored.getProcessedRecordsCount());
}
@Test
void contactCsv_wrongRowWidthOrBadQuotingIsAFailedRecord() {
stubObject("contacts.csv", """
emailAddress,attributesData
alice@example.com,"{}",extra
bob@example.com,"x"junk
carol@example.com,ab"c
dave@example.com,
""");
ImportJob job = service.createContactListImportJob(REGION, ACCOUNT, url("contacts.csv"), "CSV", LIST, "PUT");
ImportJob stored = service.getImportJob(REGION, job.getJobId());
assertEquals(ImportJob.STATUS_COMPLETED, stored.getJobStatus());
assertEquals(4, stored.getProcessedRecordsCount());
// The wrong-width row and the one with data after a closing quote fail; carol's bare quote
// is data, as the developer guide's own unquoted attributesData shows.
assertEquals(2, stored.getFailedRecordsCount());
assertEquals(2, contactService.listContacts(LIST, REGION).contacts().size());
}
@Test
void recoverInterruptedJobs_failsNonTerminalJobsLeftInAnAccountAwareStore() {
AccountAwareStorageBackend<ImportJob> persisted =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, ACCOUNT);
ImportJob stuck = new ImportJob();
stuck.setJobId("stuck");
stuck.setRegion(REGION);
stuck.setDestinationType(ImportJob.DESTINATION_SUPPRESSION_LIST);
stuck.setImportAction("PUT");
stuck.setJobStatus(ImportJob.STATUS_PROCESSING);
stuck.setCreatedTimestamp(Instant.now());
persisted.putForAccount(ACCOUNT, SesImportJobService.key(REGION, "stuck"), stuck);
ImportJob done = new ImportJob();
done.setJobId("done");
done.setRegion(REGION);
done.setDestinationType(ImportJob.DESTINATION_SUPPRESSION_LIST);
done.setImportAction("PUT");
done.setJobStatus(ImportJob.STATUS_COMPLETED);
done.setCreatedTimestamp(Instant.now());
persisted.putForAccount(ACCOUNT, SesImportJobService.key(REGION, "done"), done);
SesImportJobService restarted = new SesImportJobService(persisted, s3Service, suppressionService,
contactService, new ObjectMapper().findAndRegisterModules(), Clock.systemUTC(), Runnable::run);
ImportJob recovered = restarted.getImportJob(REGION, "stuck");
assertEquals(ImportJob.STATUS_FAILED, recovered.getJobStatus());
assertEquals(SesImportJobService.RESTART_FAILURE_MESSAGE, recovered.getErrorMessage());
assertNotNull(recovered.getCompletedTimestamp());
assertEquals(ImportJob.STATUS_COMPLETED, restarted.getImportJob(REGION, "done").getJobStatus());
}
private static void assertBadRequest(Runnable call) {
AwsException e = assertThrows(AwsException.class, call::run);
assertEquals("BadRequestException", e.getErrorCode());
}
private static Map<String, String> preferences(Contact contact) {
return contact.getTopicPreferences().stream()
.collect(Collectors.toMap(TopicPreference::getTopicName, TopicPreference::getSubscriptionStatus));
}
}
@@ -0,0 +1,309 @@
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.util.function.Supplier;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Integration tests for the SES V2 import-job endpoints: {@code POST /v2/email/import-jobs}
* (CreateImportJob), {@code GET /v2/email/import-jobs/{JobId}} (GetImportJob) and
* {@code POST /v2/email/import-jobs/list} (ListImportJobs), end to end through the local S3
* emulation into the suppression list and a contact list. The job runs on a background worker as
* on AWS, so the tests poll GetImportJob until it is terminal. Uses its own region so the
* suppression list and the one-per-region contact list do not collide with other SES tests.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesImportJobV2IntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/eu-west-3/ses/aws4_request";
private static final String BUCKET = "ses-import-job-it";
private static final String LIST = "import-job-list";
private static String suppressionJobId;
private static String contactJobId;
@Test
@Order(0)
void setupBucketAndContactList() {
given().when().put("/" + BUCKET).then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{"ContactListName":"%s","Topics":[
{"TopicName":"Sports","DisplayName":"Sports","DefaultSubscriptionStatus":"OPT_OUT"},
{"TopicName":"Cycling","DisplayName":"Cycling","DefaultSubscriptionStatus":"OPT_IN"}]}
""".formatted(LIST))
.when().post("/v2/email/contact-lists").then().statusCode(200);
}
@Test
@Order(1)
void createImportJob_suppressionCsv_runsToCompletedAndFillsTheList() {
putObject("suppress.csv", "alice@example.com,BOUNCE\nbob@example.com,COMPLAINT\ncarol@example.com,SPAM\n");
suppressionJobId = given().contentType("application/json").header("Authorization", AUTH)
.body("""
{"ImportDataSource":{"S3Url":"s3://%s/suppress.csv","DataFormat":"CSV"},
"ImportDestination":{"SuppressionListDestination":{"SuppressionListImportAction":"PUT"}}}
""".formatted(BUCKET))
.when().post("/v2/email/import-jobs").then().statusCode(200)
.body("JobId", notNullValue())
.extract().jsonPath().getString("JobId");
assertEquals("COMPLETED", pollUntilTerminal(suppressionJobId));
given().header("Authorization", AUTH)
.when().get("/v2/email/import-jobs/" + suppressionJobId).then().statusCode(200)
.body("JobId", equalTo(suppressionJobId))
.body("JobStatus", equalTo("COMPLETED"))
.body("ImportDataSource.S3Url", equalTo("s3://" + BUCKET + "/suppress.csv"))
.body("ImportDataSource.DataFormat", equalTo("CSV"))
.body("ImportDestination.SuppressionListDestination.SuppressionListImportAction", equalTo("PUT"))
.body("ImportDestination.ContactListDestination", nullValue())
.body("ProcessedRecordsCount", equalTo(3))
.body("FailedRecordsCount", equalTo(1))
.body("CreatedTimestamp", notNullValue())
.body("CompletedTimestamp", notNullValue())
.body("FailureInfo", nullValue());
given().header("Authorization", AUTH)
.when().get("/v2/email/suppression/addresses").then().statusCode(200)
.body("SuppressedDestinationSummaries.EmailAddress",
hasItems("alice@example.com", "bob@example.com"))
.body("SuppressedDestinationSummaries", hasSize(2));
}
@Test
@Order(2)
void createImportJob_contactJson_addsContactsWithPreferences() {
putObject("contacts.json", """
{"emailAddress":"carol@example.com","unsubscribeAll":false,"attributesData":"{\\"Name\\":\\"Carol\\"}","topicPreferences":[{"topicName":"Sports","subscriptionStatus":"OPT_IN"}]}
{"emailAddress":"dave@example.com","unsubscribeAll":true}
""");
contactJobId = given().contentType("application/json").header("Authorization", AUTH)
.body("""
{"ImportDataSource":{"S3Url":"s3://%s/contacts.json","DataFormat":"JSON"},
"ImportDestination":{"ContactListDestination":{"ContactListName":"%s","ContactListImportAction":"PUT"}}}
""".formatted(BUCKET, LIST))
.when().post("/v2/email/import-jobs").then().statusCode(200)
.extract().jsonPath().getString("JobId");
assertEquals("COMPLETED", pollUntilTerminal(contactJobId));
given().header("Authorization", AUTH)
.when().get("/v2/email/import-jobs/" + contactJobId).then().statusCode(200)
.body("ImportDestination.ContactListDestination.ContactListName", equalTo(LIST))
.body("ImportDestination.ContactListDestination.ContactListImportAction", equalTo("PUT"))
.body("ProcessedRecordsCount", equalTo(2))
.body("FailedRecordsCount", equalTo(0));
given().header("Authorization", AUTH)
.when().get("/v2/email/contact-lists/" + LIST + "/contacts/carol@example.com").then().statusCode(200)
.body("AttributesData", equalTo("{\"Name\":\"Carol\"}"))
.body("TopicPreferences[0].TopicName", equalTo("Sports"))
.body("TopicPreferences[0].SubscriptionStatus", equalTo("OPT_IN"));
given().header("Authorization", AUTH)
.when().get("/v2/email/contact-lists/" + LIST + "/contacts/dave@example.com").then().statusCode(200)
.body("UnsubscribeAll", equalTo(true));
}
@Test
@Order(3)
void listImportJobs_returnsSummariesAndFiltersByDestinationType() {
given().contentType("application/json").header("Authorization", AUTH)
.when().post("/v2/email/import-jobs/list").then().statusCode(200)
.body("ImportJobs.JobId", hasItems(suppressionJobId, contactJobId))
.body("ImportJobs.find { it.JobId == '" + contactJobId + "' }.JobStatus", equalTo("COMPLETED"))
.body("ImportJobs.find { it.JobId == '" + contactJobId + "' }.ImportDataSource", nullValue())
.body("NextToken", nullValue());
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"ImportDestinationType\":\"SUPPRESSION_LIST\",\"PageSize\":10}")
.when().post("/v2/email/import-jobs/list").then().statusCode(200)
.body("ImportJobs.JobId", hasItems(suppressionJobId))
.body("ImportJobs.JobId", not(hasItems(contactJobId)));
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"ImportDestinationType\":\"EXPORT\"}")
.when().post("/v2/email/import-jobs/list").then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
}
@Test
@Order(4)
void createImportJob_missingObject_failsTheJob() {
String jobId = given().contentType("application/json").header("Authorization", AUTH)
.body("""
{"ImportDataSource":{"S3Url":"s3://%s/does-not-exist.csv","DataFormat":"CSV"},
"ImportDestination":{"SuppressionListDestination":{"SuppressionListImportAction":"DELETE"}}}
""".formatted(BUCKET))
.when().post("/v2/email/import-jobs").then().statusCode(200)
.extract().jsonPath().getString("JobId");
assertEquals("FAILED", pollUntilTerminal(jobId));
given().header("Authorization", AUTH)
.when().get("/v2/email/import-jobs/" + jobId).then().statusCode(200)
.body("FailureInfo.ErrorMessage", containsString("does not exist"))
.body("ProcessedRecordsCount", equalTo(0));
}
@Test
@Order(5)
void createImportJob_validationErrors() {
String badFormat = """
{"ImportDataSource":{"S3Url":"s3://%s/x.csv","DataFormat":"XML"},
"ImportDestination":{"SuppressionListDestination":{"SuppressionListImportAction":"PUT"}}}
""".formatted(BUCKET);
String bothDestinations = """
{"ImportDataSource":{"S3Url":"s3://%s/x.csv","DataFormat":"CSV"},
"ImportDestination":{"SuppressionListDestination":{"SuppressionListImportAction":"PUT"},
"ContactListDestination":{"ContactListName":"%s","ContactListImportAction":"PUT"}}}
""".formatted(BUCKET, LIST);
String noDataSource = """
{"ImportDestination":{"SuppressionListDestination":{"SuppressionListImportAction":"PUT"}}}
""";
String unknownList = """
{"ImportDataSource":{"S3Url":"s3://%s/x.csv","DataFormat":"CSV"},
"ImportDestination":{"ContactListDestination":{"ContactListName":"nope","ContactListImportAction":"PUT"}}}
""".formatted(BUCKET);
String trailingTokens = """
{"ImportDataSource":{"S3Url":"s3://%s/x.csv","DataFormat":"CSV"},
"ImportDestination":{"SuppressionListDestination":{"SuppressionListImportAction":"PUT"}}} garbage
""".formatted(BUCKET);
for (String body : new String[] {badFormat, bothDestinations, noDataSource, trailingTokens}) {
given().contentType("application/json").header("Authorization", AUTH).body(body)
.when().post("/v2/email/import-jobs").then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
}
given().contentType("application/json").header("Authorization", AUTH)
.when().post("/v2/email/import-jobs").then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
given().contentType("application/json").header("Authorization", AUTH).body(unknownList)
.when().post("/v2/email/import-jobs").then().statusCode(404)
.body("__type", equalTo("NotFoundException"));
}
@Test
@Order(6)
void getImportJob_unknownId_isNotFound() {
given().header("Authorization", AUTH)
.when().get("/v2/email/import-jobs/00000000-0000-0000-0000-000000000000").then().statusCode(404)
.body("__type", equalTo("NotFoundException"));
}
@Test
@Order(7)
void importJobsAndTheirRecordsAreScopedToTheCallingAccount() {
// A 12-digit access key id in the credential becomes the account (AccountContextFilter), so
// these two headers are two accounts hitting the same region, neither of them the default
// account the rest of this class runs as.
String authA = accountAuth("111111111111", "ses");
String authB = accountAuth("222222222222", "ses");
// The credential's service scope routes the request, so the S3 calls need an s3-scoped one.
String s3AuthA = accountAuth("111111111111", "s3");
String bucketA = BUCKET + "-a";
given().header("Authorization", s3AuthA).when().put("/" + bucketA).then().statusCode(200);
given().header("Authorization", s3AuthA).contentType("text/plain").body("account-a@example.com,BOUNCE\n")
.when().put("/" + bucketA + "/suppress.csv").then().statusCode(200);
String jobA = given().contentType("application/json").header("Authorization", authA)
.body("""
{"ImportDataSource":{"S3Url":"s3://%s/suppress.csv","DataFormat":"CSV"},
"ImportDestination":{"SuppressionListDestination":{"SuppressionListImportAction":"PUT"}}}
""".formatted(bucketA))
.when().post("/v2/email/import-jobs").then().statusCode(200)
.extract().jsonPath().getString("JobId");
// Reaching COMPLETED under account A also proves the worker's terminal write landed in A's
// partition: RequestScopes.runAs carries the account onto the worker thread, and without it
// the write would go to the default account and this poll would never leave PROCESSING.
assertEquals("COMPLETED", pollUntilTerminal(jobA, authA));
given().header("Authorization", authB)
.when().get("/v2/email/import-jobs/" + jobA).then().statusCode(404)
.body("__type", equalTo("NotFoundException"));
given().contentType("application/json").header("Authorization", authB)
.when().post("/v2/email/import-jobs/list").then().statusCode(200)
.body("ImportJobs.JobId", not(hasItems(jobA)));
given().contentType("application/json").header("Authorization", authA)
.when().post("/v2/email/import-jobs/list").then().statusCode(200)
.body("ImportJobs.JobId", hasItems(jobA));
// The imported rows are account-scoped too, not just the job record.
given().header("Authorization", authA)
.when().get("/v2/email/suppression/addresses").then().statusCode(200)
.body("SuppressedDestinationSummaries.EmailAddress", hasItems("account-a@example.com"));
given().header("Authorization", authB)
.when().get("/v2/email/suppression/addresses").then().statusCode(200)
.body("SuppressedDestinationSummaries.EmailAddress", not(hasItems("account-a@example.com")));
given().header("Authorization", authA)
.when().delete("/v2/email/suppression/addresses/account-a@example.com").then().statusCode(200);
given().header("Authorization", s3AuthA).when().delete("/" + bucketA + "/suppress.csv").then().statusCode(204);
given().header("Authorization", s3AuthA).when().delete("/" + bucketA).then().statusCode(204);
}
private static String accountAuth(String accountId, String service) {
return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260101/eu-west-3/" + service + "/aws4_request";
}
@Test
@Order(8)
void cleanup() {
given().header("Authorization", AUTH)
.when().delete("/v2/email/contact-lists/" + LIST).then().statusCode(200);
for (String address : new String[] {"alice@example.com", "bob@example.com"}) {
given().header("Authorization", AUTH)
.when().delete("/v2/email/suppression/addresses/" + address).then().statusCode(200);
}
}
private static void putObject(String key, String content) {
given().contentType("text/plain").body(content)
.when().put("/" + BUCKET + "/" + key).then().statusCode(200);
}
private static String pollUntilTerminal(String jobId) {
return pollUntilTerminal(jobId, AUTH);
}
private static String pollUntilTerminal(String jobId, String auth) {
Supplier<Response> call = () -> given().header("Authorization", auth)
.when().get("/v2/email/import-jobs/" + jobId);
long deadline = System.currentTimeMillis() + 10_000;
while (System.currentTimeMillis() < deadline) {
String status = call.get().then().statusCode(200).extract().jsonPath().getString("JobStatus");
if ("COMPLETED".equals(status) || "FAILED".equals(status)) {
return status;
}
sleep(100);
}
return "TIMEOUT";
}
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@@ -0,0 +1,196 @@
package io.github.hectorvent.floci.services.ses.imports;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.ses.model.ImportJob;
import io.github.hectorvent.floci.services.ses.model.TopicPreference;
import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit test for the CSV reader: where a record ends, how a field is split, and which malformed
* input fails one record versus the whole file. Reading is driven through the factory, the way the
* import worker reaches it.
*/
class CsvRecordReaderTest {
private static ImportJob job(String destinationType, String action, String contactList) {
ImportJob job = new ImportJob();
job.setDataFormat(ImportJob.FORMAT_CSV);
job.setDestinationType(destinationType);
job.setImportAction(action);
job.setContactListName(contactList);
return job;
}
private static ImportJob suppression(String action) {
return job(ImportJob.DESTINATION_SUPPRESSION_LIST, action, null);
}
private static ImportJob contacts() {
return job(ImportJob.DESTINATION_CONTACT_LIST, ImportJob.ACTION_PUT, "newsletter");
}
private static RecordReader reader(ImportJob job, String content) {
return new RecordReaderFactory(new ObjectMapper())
.forJob(job, new BufferedReader(new StringReader(content)));
}
private static List<ImportRecord> readAll(ImportJob job, String content) throws IOException {
RecordReader reader = reader(job, content);
List<ImportRecord> records = new ArrayList<>();
for (ImportRecord record = reader.next(); record != null; record = reader.next()) {
records.add(record);
}
return records;
}
private static Map<String, String> preferences(ImportRecord record) {
return record.topicPreferences().stream()
.collect(Collectors.toMap(TopicPreference::getTopicName, TopicPreference::getSubscriptionStatus));
}
@Test
void suppressionRows_carryTheAddressReasonAndLineNumber() throws IOException {
List<ImportRecord> records = readAll(suppression(ImportJob.ACTION_PUT),
"alice@example.com,BOUNCE\nbob@example.com,COMPLAINT\n");
assertEquals(2, records.size());
assertEquals("alice@example.com", records.get(0).emailAddress());
assertEquals("BOUNCE", records.get(0).reason());
assertEquals(1, records.get(0).line());
assertEquals(2, records.get(1).line());
}
@Test
void deleteRowsCarryNoReason_andAnExtraColumnFailsTheRecord() throws IOException {
List<ImportRecord> records = readAll(suppression(ImportJob.ACTION_DELETE),
"alice@example.com\nbob@example.com,BOUNCE\n");
assertNull(records.get(0).reason());
assertNull(records.get(0).error());
assertTrue(records.get(1).error().contains("1 column(s) but found 2"));
}
@Test
void quotedFieldMaySpanLines_andTheNextRecordKeepsCounting() throws IOException {
List<ImportRecord> records = readAll(contacts(), "emailAddress,attributesData\r\n"
+ "alice@example.com,\"{\r\n \"\"Name\"\": \"\"Alice\"\"\r\n}\"\r\n"
+ "bob@example.com,\r\n");
assertEquals(2, records.size());
assertEquals("{\r\n \"Name\": \"Alice\"\r\n}", records.get(0).attributesData());
// The header is record 1 and the multi-line row is record 2, so the row after it is 3:
// records are numbered by position, not by physical line.
assertEquals(2, records.get(0).line());
assertEquals(3, records.get(1).line());
assertEquals("bob@example.com", records.get(1).emailAddress());
}
@Test
void headerTopicColumnsBecomePreferences_andBlankCellsAreLeftOut() throws IOException {
List<ImportRecord> records = readAll(contacts(),
"emailAddress,unsubscribeAll,topicPreferences.Sports,topicPreferences.Cycling\n"
+ "alice@example.com,true,OPT_IN,\n");
ImportRecord alice = records.get(0);
assertEquals(Boolean.TRUE, alice.unsubscribeAll());
assertEquals(Map.of("Sports", "OPT_IN"), preferences(alice));
}
@Test
void aBomAndBlankLinesDoNotBecomeRecords() throws IOException {
List<ImportRecord> records = readAll(suppression(ImportJob.ACTION_DELETE),
"alice@example.com\n\n\nbob@example.com\n");
assertEquals(2, records.size());
assertEquals("alice@example.com", records.get(0).emailAddress());
// Blank lines are skipped but still counted, so the reported line matches the file.
assertEquals(4, records.get(1).line());
}
@Test
void theDeveloperGuidesOwnContactRowIsAccepted() throws IOException {
// Straight out of the SES list-management guide: attributesData is written unquoted, so the
// quotes inside it are data. Rejecting them would refuse the documented format.
List<ImportRecord> records = readAll(contacts(),
"emailAddress,unsubscribeAll,attributesData,topicPreferences.Sports,topicPreferences.Cycling\n"
+ "example1@amazon.com,false,{\"Name\": \"John\"},OPT_IN,OPT_OUT\n"
+ "example2@amazon.com,true,,OPT_OUT,OPT_OUT\n");
assertEquals(2, records.size());
assertNull(records.get(0).error());
assertEquals("{\"Name\": \"John\"}", records.get(0).attributesData());
assertEquals(Map.of("Sports", "OPT_IN", "Cycling", "OPT_OUT"), preferences(records.get(0)));
assertEquals(Boolean.TRUE, records.get(1).unsubscribeAll());
}
@Test
void garbageAfterAClosingQuoteFailsOneRecordAndTheReaderCarriesOn() throws IOException {
List<ImportRecord> records = readAll(contacts(), "emailAddress,attributesData\n"
+ "alice@example.com,\"x\"junk\n"
+ "bob@example.com,ab\"c\n"
+ "carol@example.com,fine\n");
// A field that opened a quoted run has to end at the delimiter; anything else cannot be
// read back unambiguously.
assertTrue(records.get(0).error().contains("closing quote"));
// A quote that never opened a run is data, so this row is fine.
assertNull(records.get(1).error());
assertEquals("ab\"c", records.get(1).attributesData());
assertEquals("carol@example.com", records.get(2).emailAddress());
assertNull(records.get(2).error());
}
@Test
void anUnterminatedQuoteFailsTheWholeFile() {
RecordReader reader = reader(contacts(), "emailAddress,attributesData\nalice@example.com,\"{oops\n");
AwsException e = assertThrows(AwsException.class, () -> {
for (ImportRecord record = reader.next(); record != null; record = reader.next()) {
// drain until the scanner reaches the end of the unterminated field
}
});
assertEquals("BadRequestException", e.getErrorCode());
assertTrue(e.getMessage().contains("unterminated"));
}
@Test
void aContactFileWithoutAnEmailAddressHeaderFailsTheWholeFile() {
RecordReader reader = reader(contacts(), "email,unsubscribeAll\nalice@example.com,false\n");
AwsException e = assertThrows(AwsException.class, reader::next);
assertEquals("BadRequestException", e.getErrorCode());
assertTrue(e.getMessage().contains("emailAddress"));
}
@Test
void anEmptyContactFileFailsForTheMissingHeader() {
AwsException e = assertThrows(AwsException.class, () -> reader(contacts(), "").next());
assertTrue(e.getMessage().contains("header line"));
}
@Test
void anEmptySuppressionFileYieldsNoRecords() throws IOException {
assertTrue(readAll(suppression(ImportJob.ACTION_PUT), "").isEmpty());
}
@Test
void splitCsvLine_handlesQuotesCommasAndEscapedQuotes() {
assertEquals(List.of("a", "b,c", "say \"hi\"", ""),
CsvRecordReader.splitCsvLine("a,\"b,c\",\"say \"\"hi\"\"\","));
assertEquals(List.of(""), CsvRecordReader.splitCsvLine(""));
}
}
@@ -0,0 +1,126 @@
package io.github.hectorvent.floci.services.ses.imports;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.ses.model.ImportJob;
import io.github.hectorvent.floci.services.ses.model.TopicPreference;
import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit test for the newline-delimited JSON reader: one object per line, and which malformed lines
* become failed records. Reading is driven through the factory, the way the import worker reaches
* it, so the strict parse the factory configures is exercised too.
*/
class JsonLineReaderTest {
private static ImportJob job(String destinationType) {
ImportJob job = new ImportJob();
job.setDataFormat(ImportJob.FORMAT_JSON);
job.setDestinationType(destinationType);
job.setImportAction(ImportJob.ACTION_PUT);
job.setContactListName("newsletter");
return job;
}
private static List<ImportRecord> readAll(ImportJob job, String content) throws IOException {
RecordReader reader = new RecordReaderFactory(new ObjectMapper())
.forJob(job, new BufferedReader(new StringReader(content)));
List<ImportRecord> records = new ArrayList<>();
for (ImportRecord record = reader.next(); record != null; record = reader.next()) {
records.add(record);
}
return records;
}
private static Map<String, String> preferences(ImportRecord record) {
return record.topicPreferences().stream()
.collect(Collectors.toMap(TopicPreference::getTopicName, TopicPreference::getSubscriptionStatus));
}
@Test
void suppressionLinesCarryTheAddressAndReason() throws IOException {
List<ImportRecord> records = readAll(job(ImportJob.DESTINATION_SUPPRESSION_LIST), """
{"emailAddress":"alice@example.com","reason":"BOUNCE"}
{"emailAddress":"bob@example.com"}
""");
assertEquals(2, records.size());
assertEquals("alice@example.com", records.get(0).emailAddress());
assertEquals("BOUNCE", records.get(0).reason());
assertNull(records.get(1).reason());
}
@Test
void contactLinesCarryPreferencesAttributesAndTheUnsubscribeFlag() throws IOException {
List<ImportRecord> records = readAll(job(ImportJob.DESTINATION_CONTACT_LIST), """
{"emailAddress":"alice@example.com","unsubscribeAll":false,"attributesData":"{\\"Name\\":\\"Alice\\"}",\
"topicPreferences":[{"topicName":"Sports","subscriptionStatus":"OPT_IN"},\
{"topicName":"Cycling","subscriptionStatus":"OPT_OUT"}]}
""");
ImportRecord alice = records.get(0);
assertEquals(Boolean.FALSE, alice.unsubscribeAll());
assertEquals("{\"Name\":\"Alice\"}", alice.attributesData());
assertEquals(Map.of("Sports", "OPT_IN", "Cycling", "OPT_OUT"), preferences(alice));
}
@Test
void aBomAndBlankLinesDoNotBecomeRecords() throws IOException {
List<ImportRecord> records = readAll(job(ImportJob.DESTINATION_SUPPRESSION_LIST),
"{\"emailAddress\":\"alice@example.com\"}\n\n \n{\"emailAddress\":\"bob@example.com\"}\n");
assertEquals(2, records.size());
assertEquals("alice@example.com", records.get(0).emailAddress());
// Blank lines are skipped but still counted, so the reported line matches the file.
assertEquals(4, records.get(1).line());
}
@Test
void malformedJsonAndTrailingTokensAreFailedRecords() throws IOException {
List<ImportRecord> records = readAll(job(ImportJob.DESTINATION_SUPPRESSION_LIST), """
not json at all
{"emailAddress":"alice@example.com"} garbage
["emailAddress"]
{"emailAddress":"bob@example.com"}
""");
assertTrue(records.get(0).error().contains("Malformed JSON"));
// The factory configures FAIL_ON_TRAILING_TOKENS, so the leading object is not accepted.
assertTrue(records.get(1).error().contains("Malformed JSON"));
assertTrue(records.get(2).error().contains("JSON object"));
assertNull(records.get(3).error());
}
@Test
void membersOfTheWrongTypeAreFailedRecordsRatherThanCoerced() throws IOException {
List<ImportRecord> records = readAll(job(ImportJob.DESTINATION_CONTACT_LIST), """
{"emailAddress":"alice@example.com","attributesData":123}
{"emailAddress":"bob@example.com","unsubscribeAll":"yes"}
{"emailAddress":"carol@example.com","topicPreferences":"Sports"}
{"emailAddress":"dave@example.com","topicPreferences":["Sports"]}
{"emailAddress":"erin@example.com","topicPreferences":[{"topicName":"Sports","subscriptionStatus":true}]}
""");
assertTrue(records.get(0).error().contains("attributesData"));
assertTrue(records.get(1).error().contains("unsubscribeAll"));
assertTrue(records.get(2).error().contains("topicPreferences"));
assertTrue(records.get(3).error().contains("JSON object"));
assertTrue(records.get(4).error().contains("subscriptionStatus"));
}
@Test
void anEmptySourceYieldsNoRecords() throws IOException {
assertTrue(readAll(job(ImportJob.DESTINATION_SUPPRESSION_LIST), "").isEmpty());
}
}