mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
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:
1 parent
fb9deb1e89
commit
8ca748355d
17 files changed
+2775
-1
No files matched your search
@@ -39,6 +39,7 @@ import io.github.hectorvent.floci.services.ses.SesContactController;
|
||||
import io.github.hectorvent.floci.services.ses.SesCvetController;
|
||||
import io.github.hectorvent.floci.services.ses.SesDedicatedIpController;
|
||||
import io.github.hectorvent.floci.services.ses.SesIdentityController;
|
||||
import io.github.hectorvent.floci.services.ses.SesImportJobController;
|
||||
import io.github.hectorvent.floci.services.ses.SesSendController;
|
||||
import io.github.hectorvent.floci.services.ses.SesSuppressionController;
|
||||
import io.github.hectorvent.floci.services.ses.SesTagController;
|
||||
@@ -301,7 +302,7 @@ public class ResolvedServiceCatalog {
|
||||
SesDedicatedIpController.class, SesIdentityController.class,
|
||||
SesSendController.class, SesSuppressionController.class,
|
||||
SesTagController.class, SesTemplateController.class,
|
||||
SesTenantController.class)),
|
||||
SesImportJobController.class, SesTenantController.class)),
|
||||
descriptor("es", "opensearch", config.services().opensearch().enabled(), true,
|
||||
"opensearch", storageMode(config.storage().services().opensearch().mode(), config.storage().mode()),
|
||||
config.storage().services().opensearch().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
|
||||
|
||||
@@ -386,6 +386,32 @@ public class SesContactService {
|
||||
return existing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces a contact outright, as a contact-list import job's {@code PUT} action does. Probed
|
||||
* against real AWS: an imported record is the whole contact, so preferences, attributes, and
|
||||
* the unsubscribe flag it omits are cleared rather than merged, unlike
|
||||
* {@link #updateContact}, whose topic preferences merge by name.
|
||||
*/
|
||||
public Contact replaceContact(String listName, String emailAddress, List<TopicPreference> topicPreferences,
|
||||
Boolean unsubscribeAll, String attributesData, String region) {
|
||||
validateContactInput(listName, emailAddress, topicPreferences, region);
|
||||
String key = contactKey(region, listName, emailAddress);
|
||||
Contact existing;
|
||||
// Same lock as create/update: a concurrent deleteContactList must not slip between the
|
||||
// validation and the write.
|
||||
synchronized (contactMutationLock) {
|
||||
getContactList(listName, region);
|
||||
existing = contactStore.get(key).orElseThrow(() -> contactNotFound(emailAddress));
|
||||
existing.setTopicPreferences(topicPreferences);
|
||||
existing.setUnsubscribeAll(unsubscribeAll != null && unsubscribeAll);
|
||||
existing.setAttributesData(attributesData);
|
||||
existing.setLastUpdatedTimestamp(Instant.now(clock));
|
||||
contactStore.put(key, existing);
|
||||
}
|
||||
LOG.infov("Replaced SES contact {0} in list {1}", emailAddress, listName);
|
||||
return existing;
|
||||
}
|
||||
|
||||
public void deleteContact(String listName, String emailAddress, String region) {
|
||||
validateEmailAddress(emailAddress);
|
||||
String key = contactKey(region, listName, emailAddress);
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectReader;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.ses.model.ImportJob;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.github.hectorvent.floci.services.ses.SesV2Json.intMemberOrAbsent;
|
||||
import static io.github.hectorvent.floci.services.ses.SesV2Json.readRequiredStringField;
|
||||
import static io.github.hectorvent.floci.services.ses.SesV2Json.remapV1Exception;
|
||||
import static io.github.hectorvent.floci.services.ses.SesV2Json.requireJsonObject;
|
||||
import static io.github.hectorvent.floci.services.ses.SesV2Json.requireObjectOrAbsent;
|
||||
import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMemberOrAbsent;
|
||||
|
||||
/**
|
||||
* SES V2 import job endpoints ({@code /v2/email/import-jobs}). Every operation is a single-domain
|
||||
* call on {@link SesImportJobService}; the JSON shape of {@code ImportDestination} /
|
||||
* {@code ImportDataSource} is parsed and rendered here.
|
||||
*/
|
||||
@Path("/v2/email")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class SesImportJobController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesImportJobController.class);
|
||||
|
||||
private final SesImportJobService importJobService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
// FAIL_ON_TRAILING_TOKENS so "{...} garbage" is rejected instead of creating a job from the
|
||||
// leading object, as the JSON protocol controllers do.
|
||||
private final ObjectReader strictReader;
|
||||
|
||||
@Inject
|
||||
public SesImportJobController(SesImportJobService importJobService, RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper) {
|
||||
this.importJobService = importJobService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
this.strictReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/import-jobs")
|
||||
public Response createImportJob(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
if (body == null || body.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "Request body is required.", 400);
|
||||
}
|
||||
JsonNode request = strictReader.readTree(body);
|
||||
requireJsonObject(request);
|
||||
JsonNode source = requireObjectOrAbsent(request, "ImportDataSource");
|
||||
if (!source.isObject()) {
|
||||
throw new AwsException("BadRequestException", "ImportDataSource is required.", 400);
|
||||
}
|
||||
String s3Url = readRequiredStringField(source, "S3Url");
|
||||
String dataFormat = readRequiredStringField(source, "DataFormat");
|
||||
JsonNode destination = requireObjectOrAbsent(request, "ImportDestination");
|
||||
if (!destination.isObject()) {
|
||||
throw new AwsException("BadRequestException", "ImportDestination is required.", 400);
|
||||
}
|
||||
JsonNode suppression = requireObjectOrAbsent(destination, "SuppressionListDestination");
|
||||
JsonNode contactList = requireObjectOrAbsent(destination, "ContactListDestination");
|
||||
if (suppression.isObject() == contactList.isObject()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"ImportDestination must contain exactly one of SuppressionListDestination "
|
||||
+ "or ContactListDestination.", 400);
|
||||
}
|
||||
String accountId = regionResolver.getAccountId();
|
||||
ImportJob job;
|
||||
if (suppression.isObject()) {
|
||||
String action = readRequiredStringField(suppression, "SuppressionListImportAction");
|
||||
job = importJobService.createSuppressionListImportJob(region, accountId, s3Url, dataFormat, action);
|
||||
} else {
|
||||
String listName = readRequiredStringField(contactList, "ContactListName");
|
||||
String action = readRequiredStringField(contactList, "ContactListImportAction");
|
||||
job = importJobService.createContactListImportJob(region, accountId, s3Url, dataFormat,
|
||||
listName, action);
|
||||
}
|
||||
LOG.infov("SES V2 CreateImportJob: {0}", job.getJobId());
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.put("JobId", job.getJobId());
|
||||
return Response.ok(result).build();
|
||||
} catch (AwsException e) {
|
||||
throw remapV1Exception(e);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/import-jobs/{jobId}")
|
||||
public Response getImportJob(@Context HttpHeaders headers, @PathParam("jobId") String jobId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
ImportJob job = importJobService.getImportJob(region, jobId);
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
writeSummary(result, job);
|
||||
ObjectNode source = result.putObject("ImportDataSource");
|
||||
source.put("S3Url", job.getS3Url());
|
||||
source.put("DataFormat", job.getDataFormat());
|
||||
if (job.getCompletedTimestamp() != null) {
|
||||
result.put("CompletedTimestamp", job.getCompletedTimestamp().toEpochMilli() / 1000.0);
|
||||
}
|
||||
if (job.getErrorMessage() != null) {
|
||||
result.putObject("FailureInfo").put("ErrorMessage", job.getErrorMessage());
|
||||
}
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/import-jobs/list")
|
||||
public Response listImportJobs(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
JsonNode request = (body == null || body.isBlank())
|
||||
? objectMapper.createObjectNode()
|
||||
: strictReader.readTree(body);
|
||||
requireJsonObject(request);
|
||||
String destinationType = stringMemberOrAbsent(request, "ImportDestinationType");
|
||||
Integer pageSize = intMemberOrAbsent(request, "PageSize");
|
||||
String nextToken = stringMemberOrAbsent(request, "NextToken");
|
||||
List<ImportJob> jobs = importJobService.listImportJobs(region, destinationType, pageSize, nextToken);
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
ArrayNode items = result.putArray("ImportJobs");
|
||||
for (ImportJob job : jobs) {
|
||||
writeSummary(items.addObject(), job);
|
||||
}
|
||||
// AWS renders NextToken as an explicit null on the last (here: only) page.
|
||||
result.putNull("NextToken");
|
||||
return Response.ok(result).build();
|
||||
} catch (AwsException e) {
|
||||
throw remapV1Exception(e);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
// The ImportJobSummary members, shared by GetImportJob (which adds the source, completion time
|
||||
// and failure info on top).
|
||||
private static void writeSummary(ObjectNode node, ImportJob job) {
|
||||
node.put("JobId", job.getJobId());
|
||||
ObjectNode destination = node.putObject("ImportDestination");
|
||||
if (ImportJob.DESTINATION_SUPPRESSION_LIST.equals(job.getDestinationType())) {
|
||||
destination.putObject("SuppressionListDestination")
|
||||
.put("SuppressionListImportAction", job.getImportAction());
|
||||
} else {
|
||||
ObjectNode contactList = destination.putObject("ContactListDestination");
|
||||
contactList.put("ContactListName", job.getContactListName());
|
||||
contactList.put("ContactListImportAction", job.getImportAction());
|
||||
}
|
||||
node.put("JobStatus", job.getJobStatus());
|
||||
node.put("CreatedTimestamp", job.getCreatedTimestamp().toEpochMilli() / 1000.0);
|
||||
node.put("ProcessedRecordsCount", job.getProcessedRecordsCount());
|
||||
node.put("FailedRecordsCount", job.getFailedRecordsCount());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.ses.imports.ImportRecord;
|
||||
import io.github.hectorvent.floci.services.ses.imports.RecordReader;
|
||||
import io.github.hectorvent.floci.services.ses.imports.RecordReaderFactory;
|
||||
import io.github.hectorvent.floci.services.ses.model.ImportJob;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* SES V2 import jobs: bulk-loads a CSV or newline-delimited JSON object from S3 into the account
|
||||
* suppression list or a contact list. A job is stored as CREATED and returned immediately; a
|
||||
* worker then flips it to PROCESSING and applies the records one by one through
|
||||
* {@link SesSuppressionService} / {@link SesContactService}, so the imported data lives in those
|
||||
* services' stores and only the job record lives here. A record that fails validation is counted
|
||||
* in {@code FailedRecordsCount} and the job still completes; the job itself fails when the source
|
||||
* cannot be read or the contact list is gone.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SesImportJobService implements Resettable {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesImportJobService.class);
|
||||
|
||||
static final int MAX_CONCURRENT_JOBS = 20;
|
||||
// AWS reports an import's counters as it runs, so the worker republishes them as it goes.
|
||||
// Every record would mean serializing the job per row, so progress lands in batches.
|
||||
static final int PROGRESS_RECORD_INTERVAL = 100;
|
||||
static final String RESTART_FAILURE_MESSAGE = "The emulator restarted before the import finished";
|
||||
private static final long RESET_ADMISSION_WAIT_MILLIS = 30_000L;
|
||||
// The drain only ever waits for the record being applied right now plus the read of the next
|
||||
// one, which is a store get/put and a line off a local file, so this deadline is a safety net
|
||||
// that a healthy import never reaches. 5s is what every other worker wait in Floci uses
|
||||
// (WalStorage, HybridStorage, CloudWatchLogsMetricFilterService, CodePipelineService). Raising
|
||||
// it is the wrong direction: a reset walks every Resettable service in turn, so per-service
|
||||
// deadlines add up.
|
||||
static final long RESET_DRAIN_TIMEOUT_MILLIS = 5_000L;
|
||||
|
||||
private static final Pattern S3_URL = Pattern.compile("^s3://([^/]+)/(.*?([^/]+)/?)$");
|
||||
private static final Set<String> DATA_FORMATS = Set.of(ImportJob.FORMAT_CSV, ImportJob.FORMAT_JSON);
|
||||
private static final Set<String> IMPORT_ACTIONS = Set.of(ImportJob.ACTION_PUT, ImportJob.ACTION_DELETE);
|
||||
private static final Set<String> DESTINATION_TYPES =
|
||||
Set.of(ImportJob.DESTINATION_SUPPRESSION_LIST, ImportJob.DESTINATION_CONTACT_LIST);
|
||||
|
||||
private final StorageBackend<String, ImportJob> importJobStore;
|
||||
private final S3Service s3Service;
|
||||
private final SesSuppressionService suppressionService;
|
||||
private final SesContactService contactService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RecordReaderFactory readerFactory;
|
||||
private final Clock clock;
|
||||
private final Executor workers;
|
||||
private final long resetDrainTimeoutMillis;
|
||||
// Admission lock: serializes the concurrent-job count against the store write (so two creates
|
||||
// cannot both pass the limit check) and against reset, which flips {@code resetting} under it.
|
||||
private final Object createLock = new Object();
|
||||
private boolean resetting;
|
||||
// Reset support: beforeReset bumps the generation so every running worker stops before its
|
||||
// next write, then waits on workerMonitor for the workers still inside one. That wait is
|
||||
// bounded (see RESET_DRAIN_TIMEOUT_MILLIS), so a worker wedged past the deadline can still
|
||||
// land the record it is applying right now; it is logged when that happens.
|
||||
private final AtomicInteger generation = new AtomicInteger();
|
||||
private final Object workerMonitor = new Object();
|
||||
private int activeWorkers;
|
||||
|
||||
@Inject
|
||||
public SesImportJobService(StorageFactory storageFactory, S3Service s3Service,
|
||||
SesSuppressionService suppressionService, SesContactService contactService,
|
||||
ObjectMapper objectMapper, Clock clock) {
|
||||
this(storageFactory.create("ses", "ses-import-jobs.json",
|
||||
new TypeReference<Map<String, ImportJob>>() {}),
|
||||
s3Service, suppressionService, contactService, objectMapper, clock,
|
||||
task -> Thread.ofVirtual().start(task));
|
||||
}
|
||||
|
||||
SesImportJobService(StorageBackend<String, ImportJob> importJobStore, S3Service s3Service,
|
||||
SesSuppressionService suppressionService, SesContactService contactService,
|
||||
ObjectMapper objectMapper, Clock clock, Executor workers) {
|
||||
this(importJobStore, s3Service, suppressionService, contactService, objectMapper, clock, workers,
|
||||
RESET_DRAIN_TIMEOUT_MILLIS);
|
||||
}
|
||||
|
||||
SesImportJobService(StorageBackend<String, ImportJob> importJobStore, S3Service s3Service,
|
||||
SesSuppressionService suppressionService, SesContactService contactService,
|
||||
ObjectMapper objectMapper, Clock clock, Executor workers,
|
||||
long resetDrainTimeoutMillis) {
|
||||
this.resetDrainTimeoutMillis = resetDrainTimeoutMillis;
|
||||
this.importJobStore = importJobStore;
|
||||
this.s3Service = s3Service;
|
||||
this.suppressionService = suppressionService;
|
||||
this.contactService = contactService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.readerFactory = new RecordReaderFactory(objectMapper);
|
||||
this.clock = clock;
|
||||
this.workers = workers;
|
||||
recoverInterruptedJobs();
|
||||
}
|
||||
|
||||
public ImportJob createSuppressionListImportJob(String region, String accountId, String s3Url,
|
||||
String dataFormat, String importAction) {
|
||||
ImportJob job = newJob(region, s3Url, dataFormat, importAction);
|
||||
job.setDestinationType(ImportJob.DESTINATION_SUPPRESSION_LIST);
|
||||
return start(job, accountId);
|
||||
}
|
||||
|
||||
public ImportJob createContactListImportJob(String region, String accountId, String s3Url,
|
||||
String dataFormat, String contactListName,
|
||||
String importAction) {
|
||||
ImportJob job = newJob(region, s3Url, dataFormat, importAction);
|
||||
job.setDestinationType(ImportJob.DESTINATION_CONTACT_LIST);
|
||||
job.setContactListName(contactListName);
|
||||
requireContactList(job);
|
||||
return start(job, accountId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Probed against real AWS: an import job checks the contact list when it is created, answering
|
||||
* NotFoundException even though the model lists only BadRequest / LimitExceeded /
|
||||
* TooManyRequests for CreateImportJob. This path also words it differently from the contact-list
|
||||
* APIs ("ContactList <name> doesn't exist" rather than "List with name: <name> doesn't exist."),
|
||||
* so the message is rewritten here and the contact service keeps its own.
|
||||
*/
|
||||
private void requireContactList(ImportJob job) {
|
||||
try {
|
||||
contactService.getContactList(job.getContactListName(), job.getRegion());
|
||||
} catch (AwsException e) {
|
||||
if (!"NotFoundException".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
throw new AwsException("NotFoundException",
|
||||
"ContactList <" + job.getContactListName() + "> doesn't exist", 404);
|
||||
}
|
||||
}
|
||||
|
||||
private ImportJob newJob(String region, String s3Url, String dataFormat, String importAction) {
|
||||
if (s3Url == null || !S3_URL.matcher(s3Url).matches()) {
|
||||
throw validationError("importDataSource.s3Url",
|
||||
"Member must satisfy regular expression pattern: " + S3_URL.pattern());
|
||||
}
|
||||
if (dataFormat == null || !DATA_FORMATS.contains(dataFormat)) {
|
||||
throw validationError("importDataSource.dataFormat",
|
||||
"Member must satisfy enum value set: [CSV, JSON]");
|
||||
}
|
||||
if (importAction == null || !IMPORT_ACTIONS.contains(importAction)) {
|
||||
throw validationError("importDestination", "Member must satisfy enum value set: [DELETE, PUT]");
|
||||
}
|
||||
ImportJob job = new ImportJob();
|
||||
job.setJobId(UUID.randomUUID().toString());
|
||||
job.setRegion(region);
|
||||
job.setS3Url(s3Url);
|
||||
job.setDataFormat(dataFormat);
|
||||
job.setImportAction(importAction);
|
||||
job.setJobStatus(ImportJob.STATUS_CREATED);
|
||||
job.setCreatedTimestamp(Instant.now(clock));
|
||||
return job;
|
||||
}
|
||||
|
||||
private ImportJob start(ImportJob job, String accountId) {
|
||||
// The worker gets its own copy so the record serialized into the Create response never
|
||||
// changes underneath the handler, and runs as the request account so its store writes
|
||||
// land in that account's partition.
|
||||
ImportJob worker = objectMapper.convertValue(job, ImportJob.class);
|
||||
synchronized (createLock) {
|
||||
awaitResetFinished();
|
||||
long active = importJobStore.scan(k -> k.startsWith(keyPrefix(job.getRegion()))).stream()
|
||||
.filter(j -> !j.isTerminal())
|
||||
.count();
|
||||
if (active >= MAX_CONCURRENT_JOBS) {
|
||||
throw new AwsException("LimitExceededException",
|
||||
"The maximum number of concurrent import jobs (" + MAX_CONCURRENT_JOBS
|
||||
+ ") has been reached.", 400);
|
||||
}
|
||||
publish(key(job.getRegion(), job.getJobId()), job);
|
||||
// Persist, capture the generation and dispatch under the same lock beforeReset takes,
|
||||
// so a job is either fully admitted before a reset (and then abandoned by its stale
|
||||
// generation) or admitted only after the reset has finished.
|
||||
int startedIn = generation.get();
|
||||
workers.execute(() -> RequestScopes.runAs(accountId, () -> runImport(worker, startedIn)));
|
||||
}
|
||||
LOG.infov("Created SES import job {0} in region {1}: {2} {3} from {4}", job.getJobId(),
|
||||
job.getRegion(), job.getImportAction(), job.getDestinationType(), job.getS3Url());
|
||||
return job;
|
||||
}
|
||||
|
||||
// Holds createLock. A create that arrives while a reset is in progress waits for afterReset
|
||||
// rather than persisting a job that the wipe would then race.
|
||||
private void awaitResetFinished() {
|
||||
long deadline = System.currentTimeMillis() + RESET_ADMISSION_WAIT_MILLIS;
|
||||
while (resetting) {
|
||||
long remaining = deadline - System.currentTimeMillis();
|
||||
if (remaining <= 0) {
|
||||
throw new AwsException("TooManyRequestsException",
|
||||
"Import jobs are not accepted while the emulator is resetting.", 429);
|
||||
}
|
||||
try {
|
||||
createLock.wait(remaining);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AwsException("TooManyRequestsException",
|
||||
"Import jobs are not accepted while the emulator is resetting.", 429);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void runImport(ImportJob job, int startedIn) {
|
||||
synchronized (workerMonitor) {
|
||||
activeWorkers++;
|
||||
}
|
||||
try {
|
||||
runImportInGeneration(job, startedIn);
|
||||
} finally {
|
||||
synchronized (workerMonitor) {
|
||||
activeWorkers--;
|
||||
workerMonitor.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void runImportInGeneration(ImportJob job, int startedIn) {
|
||||
String storeKey = key(job.getRegion(), job.getJobId());
|
||||
if (generation.get() != startedIn) {
|
||||
return;
|
||||
}
|
||||
job.setJobStatus(ImportJob.STATUS_PROCESSING);
|
||||
publish(storeKey, job);
|
||||
try {
|
||||
Matcher url = S3_URL.matcher(job.getS3Url());
|
||||
if (!url.matches()) {
|
||||
throw new AwsException("BadRequestException", "Invalid S3 URL: " + job.getS3Url(), 400);
|
||||
}
|
||||
if (ImportJob.DESTINATION_CONTACT_LIST.equals(job.getDestinationType())) {
|
||||
requireContactList(job);
|
||||
}
|
||||
// Streamed and applied one record at a time, so an import never holds more than the
|
||||
// current record in memory whatever the object's size.
|
||||
try (InputStream raw = s3Service.openObjectStream(url.group(1), url.group(2), null);
|
||||
BufferedReader source = new BufferedReader(new InputStreamReader(raw, StandardCharsets.UTF_8))) {
|
||||
applyRecords(job, storeKey, startedIn, readerFactory.forJob(job, source));
|
||||
}
|
||||
job.setJobStatus(ImportJob.STATUS_COMPLETED);
|
||||
} catch (AwsException e) {
|
||||
job.setJobStatus(ImportJob.STATUS_FAILED);
|
||||
job.setErrorMessage(e.getMessage());
|
||||
} catch (IOException | RuntimeException e) {
|
||||
LOG.errorv(e, "SES import job {0} failed", job.getJobId());
|
||||
job.setJobStatus(ImportJob.STATUS_FAILED);
|
||||
job.setErrorMessage(e.getMessage());
|
||||
}
|
||||
job.setCompletedTimestamp(Instant.now(clock));
|
||||
if (generation.get() != startedIn) {
|
||||
LOG.infov("SES import job {0} abandoned by an emulator reset", job.getJobId());
|
||||
return;
|
||||
}
|
||||
publish(storeKey, job);
|
||||
LOG.infov("SES import job {0} {1}: processed={2}, failed={3}", job.getJobId(), job.getJobStatus(),
|
||||
job.getProcessedRecordsCount(), job.getFailedRecordsCount());
|
||||
}
|
||||
|
||||
// The worker goes on mutating its own ImportJob after each write, so every store write publishes
|
||||
// a copy: a backend that hands back the stored instance must never let a poll observe a
|
||||
// half-applied transition, such as COMPLETED before the completion timestamp is set.
|
||||
private void publish(String storeKey, ImportJob job) {
|
||||
importJobStore.put(storeKey, objectMapper.convertValue(job, ImportJob.class));
|
||||
}
|
||||
|
||||
private void applyRecords(ImportJob job, String storeKey, int startedIn,
|
||||
RecordReader reader)
|
||||
throws IOException {
|
||||
for (ImportRecord record = reader.next(); record != null; record = reader.next()) {
|
||||
if (generation.get() != startedIn) {
|
||||
LOG.infov("SES import job {0} abandoned by an emulator reset", job.getJobId());
|
||||
return;
|
||||
}
|
||||
job.setProcessedRecordsCount(job.getProcessedRecordsCount() + 1);
|
||||
applyRecord(job, record);
|
||||
if (job.getProcessedRecordsCount() % PROGRESS_RECORD_INTERVAL == 0) {
|
||||
publish(storeKey, job);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void applyRecord(ImportJob job, ImportRecord record) {
|
||||
if (record.error() != null) {
|
||||
failRecord(job, record.line(), record.error());
|
||||
return;
|
||||
}
|
||||
try {
|
||||
apply(job, record);
|
||||
} catch (AwsException e) {
|
||||
// A NotFound for a contact-list job is a missing contact (a failed record) unless the
|
||||
// list itself has gone, which fails the whole job like the pre-run check.
|
||||
if (ImportJob.DESTINATION_CONTACT_LIST.equals(job.getDestinationType())
|
||||
&& "NotFoundException".equals(e.getErrorCode())) {
|
||||
requireContactList(job);
|
||||
}
|
||||
failRecord(job, record.line(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void failRecord(ImportJob job, int line, String reason) {
|
||||
job.setFailedRecordsCount(job.getFailedRecordsCount() + 1);
|
||||
LOG.debugv("SES import job {0} skipped record at line {1}: {2}", job.getJobId(), line, reason);
|
||||
}
|
||||
|
||||
private void apply(ImportJob job, ImportRecord record) {
|
||||
boolean put = ImportJob.ACTION_PUT.equals(job.getImportAction());
|
||||
if (ImportJob.DESTINATION_SUPPRESSION_LIST.equals(job.getDestinationType())) {
|
||||
if (put) {
|
||||
suppressionService.putSuppressedDestination(job.getRegion(), record.emailAddress(), record.reason());
|
||||
} else {
|
||||
suppressionService.deleteSuppressedDestination(job.getRegion(), record.emailAddress());
|
||||
}
|
||||
return;
|
||||
}
|
||||
String list = job.getContactListName();
|
||||
if (!put) {
|
||||
contactService.deleteContact(list, record.emailAddress(), job.getRegion());
|
||||
return;
|
||||
}
|
||||
// PUT over an existing contact replaces it outright rather than merging: probed against real
|
||||
// AWS, an import record that omits a topic, the attributes, or the unsubscribe flag clears
|
||||
// them. That is not UpdateContact's contract, so it has its own service path.
|
||||
try {
|
||||
contactService.createContact(list, record.emailAddress(), record.topicPreferences(),
|
||||
record.unsubscribeAll(), record.attributesData(), job.getRegion());
|
||||
} catch (AwsException e) {
|
||||
if (!"AlreadyExistsException".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
contactService.replaceContact(list, record.emailAddress(), record.topicPreferences(),
|
||||
record.unsubscribeAll(), record.attributesData(), job.getRegion());
|
||||
}
|
||||
}
|
||||
|
||||
public ImportJob getImportJob(String region, String jobId) {
|
||||
return importJobStore.get(key(region, jobId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException",
|
||||
"Import job " + jobId + " does not exist.", 404));
|
||||
}
|
||||
|
||||
public List<ImportJob> listImportJobs(String region, String destinationType, Integer pageSize,
|
||||
String nextToken) {
|
||||
if (destinationType != null && !DESTINATION_TYPES.contains(destinationType)) {
|
||||
throw validationError("importDestinationType",
|
||||
"Member must satisfy enum value set: [SUPPRESSION_LIST, CONTACT_LIST]");
|
||||
}
|
||||
SesTenantService.validateListPaging(pageSize, nextToken);
|
||||
return importJobStore.scan(k -> k.startsWith(keyPrefix(region))).stream()
|
||||
.filter(j -> destinationType == null || destinationType.equals(j.getDestinationType()))
|
||||
.sorted(Comparator.comparing(ImportJob::getCreatedTimestamp)
|
||||
.thenComparing(ImportJob::getJobId))
|
||||
.toList();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Lifecycle ────────────────────────────
|
||||
|
||||
// Recovery happens in the constructor, and a normal-scoped bean is only built on first use, so
|
||||
// without this the jobs left non-terminal by a restart would not be failed until an import
|
||||
// endpoint was called. Observing startup makes "marked FAILED on the next start" true of the
|
||||
// boot itself, which is what the docs promise.
|
||||
void onStart(@Observes StartupEvent ignored) {
|
||||
LOG.debugv("SES import job service ready");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeReset() {
|
||||
synchronized (createLock) {
|
||||
resetting = true;
|
||||
generation.incrementAndGet();
|
||||
}
|
||||
// Drain, but bounded: a reset has to return even when a worker is wedged in a slow read.
|
||||
// Every worker re-checks the generation before its next write, so the wait normally covers
|
||||
// only the record being applied right now. If the deadline passes anyway that one record
|
||||
// can still land after the wipe, which the warning below is there to explain.
|
||||
boolean interrupted = false;
|
||||
long deadline = System.currentTimeMillis() + resetDrainTimeoutMillis;
|
||||
synchronized (workerMonitor) {
|
||||
while (activeWorkers > 0) {
|
||||
long remaining = deadline - System.currentTimeMillis();
|
||||
if (remaining <= 0) {
|
||||
LOG.warnv("{0} SES import worker(s) still running after {1}ms; a record in flight may "
|
||||
+ "write after the reset", activeWorkers, resetDrainTimeoutMillis);
|
||||
break;
|
||||
}
|
||||
try {
|
||||
workerMonitor.wait(remaining);
|
||||
} catch (InterruptedException e) {
|
||||
// Keep draining to the deadline; the interrupt is re-asserted on the way out.
|
||||
interrupted = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterReset() {
|
||||
synchronized (createLock) {
|
||||
resetting = false;
|
||||
createLock.notifyAll();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
// The job store is wiped by StorageFactory; the imported rows belong to the suppression and
|
||||
// contact services, which clear their own stores.
|
||||
}
|
||||
|
||||
|
||||
// A job interrupted by a restart would otherwise stay CREATED/PROCESSING forever, since no
|
||||
// worker survives the process.
|
||||
private void recoverInterruptedJobs() {
|
||||
if (!(importJobStore instanceof AccountAwareStorageBackend<ImportJob> jobs)) {
|
||||
return;
|
||||
}
|
||||
Instant now = Instant.now(clock);
|
||||
for (AccountAwareStorageBackend.AccountEntry<ImportJob> entry : jobs.scanAllAccountEntries(k -> true)) {
|
||||
ImportJob job = entry.value();
|
||||
if (job.isTerminal()) {
|
||||
continue;
|
||||
}
|
||||
job.setJobStatus(ImportJob.STATUS_FAILED);
|
||||
job.setErrorMessage(RESTART_FAILURE_MESSAGE);
|
||||
job.setCompletedTimestamp(now);
|
||||
jobs.putForAccount(entry.accountId(), entry.key(), job);
|
||||
LOG.warnv("SES import job {0} was interrupted by a restart and is now FAILED", job.getJobId());
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException validationError(String path, String constraint) {
|
||||
return new AwsException("BadRequestException",
|
||||
"1 validation error detected: Value at '" + path + "' failed to satisfy constraint: "
|
||||
+ constraint, 400);
|
||||
}
|
||||
|
||||
static String key(String region, String jobId) {
|
||||
return keyPrefix(region) + jobId;
|
||||
}
|
||||
|
||||
private static String keyPrefix(String region) {
|
||||
return "importJob::" + region + "::";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package io.github.hectorvent.floci.services.ses.imports;
|
||||
|
||||
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 java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Reads RFC 4180 records one at a time: a record ends at an unquoted line break (a quoted
|
||||
* attributesData may span lines), the first record of a contact-list file is the header, and
|
||||
* a row whose width or quoting is wrong is a failed record. Records are numbered by position.
|
||||
*
|
||||
* <p>Deliberately not {@link io.github.hectorvent.floci.core.common.CsvParser}, which parses a
|
||||
* whole document held as a {@code String} and is permissive by design (a quote inside an
|
||||
* unquoted field is literal, an unterminated quoted field simply ends at EOF, and
|
||||
* {@code parseAll} applies the backslash escapes S3 Select, Athena, and the Step Functions
|
||||
* ItemReader expect). An import reads its source straight off an S3 stream so a large file is
|
||||
* never materialized, and it has to report malformed quoting rather than absorb it, since a bad
|
||||
* row has to land in {@code FailedRecordsCount} or fail the job. Nothing else in Floci streams
|
||||
* CSV out of S3 yet: DynamoDB's {@code ImportTable} sidesteps it by rejecting the CSV
|
||||
* {@code InputFormat} outright, so this is the first of its kind, and the place to grow a
|
||||
* shared streaming reader from if that changes.
|
||||
*/
|
||||
final class CsvRecordReader implements RecordReader {
|
||||
|
||||
private static final String TOPIC_PREFERENCE_COLUMN_PREFIX = "topicPreferences.";
|
||||
private final Reader source;
|
||||
private final ImportJob job;
|
||||
private final boolean contactList;
|
||||
private int pending = -1;
|
||||
private boolean bomChecked;
|
||||
private int recordNumber;
|
||||
private Map<String, Integer> columns;
|
||||
|
||||
CsvRecordReader(Reader source, ImportJob job) {
|
||||
this.source = source;
|
||||
this.job = job;
|
||||
this.contactList = ImportJob.DESTINATION_CONTACT_LIST.equals(job.getDestinationType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ImportRecord next() throws IOException {
|
||||
String raw;
|
||||
while ((raw = nextRawRecord()) != null) {
|
||||
recordNumber++;
|
||||
if (raw.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
List<String> fields;
|
||||
try {
|
||||
fields = splitCsvLine(raw);
|
||||
} catch (InvalidRecordException e) {
|
||||
if (contactList && columns == null) {
|
||||
throw new AwsException("BadRequestException", "Malformed CSV header: " + e.getMessage(), 400);
|
||||
}
|
||||
return ImportRecord.invalid(recordNumber, e.getMessage());
|
||||
}
|
||||
if (contactList && columns == null) {
|
||||
columns = readContactHeader(fields);
|
||||
continue;
|
||||
}
|
||||
if (!contactList) {
|
||||
// The documented formats are exactly "email,reason" for PUT and "email" for DELETE.
|
||||
int expected = ImportJob.ACTION_PUT.equals(job.getImportAction()) ? 2 : 1;
|
||||
if (fields.size() != expected) {
|
||||
return ImportRecord.invalid(recordNumber,
|
||||
"Expected " + expected + " column(s) but found " + fields.size() + ".");
|
||||
}
|
||||
return new ImportRecord(recordNumber, fields.get(0), expected == 2 ? fields.get(1) : null,
|
||||
null, null, null, null);
|
||||
}
|
||||
if (fields.size() != columns.size()) {
|
||||
return ImportRecord.invalid(recordNumber,
|
||||
"Expected " + columns.size() + " column(s) but found " + fields.size() + ".");
|
||||
}
|
||||
return contactRecordFromCsv(recordNumber, fields, columns);
|
||||
}
|
||||
if (contactList && columns == null) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"The CSV file must start with a header line naming the emailAddress column.", 400);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Only a quote at the start of a field opens a quoted section (a bare quote elsewhere is
|
||||
// left for splitCsvLine to reject as a malformed row), so one bad row cannot swallow the
|
||||
// rest of the file; a doubled quote inside a quoted field stays inside it.
|
||||
private String nextRawRecord() throws IOException {
|
||||
int start = read();
|
||||
if (start < 0) {
|
||||
return null;
|
||||
}
|
||||
pushBack(start);
|
||||
StringBuilder current = new StringBuilder();
|
||||
boolean quoted = false;
|
||||
boolean fieldStart = true;
|
||||
int next;
|
||||
while ((next = read()) >= 0) {
|
||||
char c = (char) next;
|
||||
if (quoted) {
|
||||
if (c == '"') {
|
||||
int peek = read();
|
||||
if (peek == '"') {
|
||||
current.append(c);
|
||||
} else {
|
||||
quoted = false;
|
||||
pushBack(peek);
|
||||
}
|
||||
}
|
||||
current.append(c);
|
||||
} else if (c == '\n' || c == '\r') {
|
||||
if (c == '\r') {
|
||||
int peek = read();
|
||||
if (peek != '\n') {
|
||||
pushBack(peek);
|
||||
}
|
||||
}
|
||||
return current.toString();
|
||||
} else {
|
||||
if (c == '"' && fieldStart) {
|
||||
quoted = true;
|
||||
}
|
||||
fieldStart = c == ',';
|
||||
current.append(c);
|
||||
}
|
||||
}
|
||||
if (quoted) {
|
||||
throw new AwsException("BadRequestException", "Malformed CSV: unterminated quoted field.", 400);
|
||||
}
|
||||
return current.toString();
|
||||
}
|
||||
|
||||
private int read() throws IOException {
|
||||
int c;
|
||||
if (pending >= 0) {
|
||||
c = pending;
|
||||
pending = -1;
|
||||
} else {
|
||||
c = source.read();
|
||||
}
|
||||
if (!bomChecked) {
|
||||
bomChecked = true;
|
||||
if (c == '\uFEFF') {
|
||||
return read();
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
private void pushBack(int c) {
|
||||
if (c >= 0) {
|
||||
pending = c;
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, Integer> readContactHeader(List<String> header) {
|
||||
Map<String, Integer> columns = new LinkedHashMap<>();
|
||||
for (int i = 0; i < header.size(); i++) {
|
||||
columns.put(header.get(i).trim(), i);
|
||||
}
|
||||
if (!columns.containsKey("emailAddress")) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"The CSV header line must contain an emailAddress column.", 400);
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
private static ImportRecord contactRecordFromCsv(int line, List<String> fields, Map<String, Integer> columns) {
|
||||
String email = column(fields, columns, "emailAddress");
|
||||
Boolean unsubscribeAll = null;
|
||||
String unsubscribeText = column(fields, columns, "unsubscribeAll");
|
||||
if (unsubscribeText != null && !unsubscribeText.isEmpty()) {
|
||||
if (unsubscribeText.equalsIgnoreCase("true")) {
|
||||
unsubscribeAll = true;
|
||||
} else if (unsubscribeText.equalsIgnoreCase("false")) {
|
||||
unsubscribeAll = false;
|
||||
} else {
|
||||
return ImportRecord.invalid(line, "unsubscribeAll must be true or false.");
|
||||
}
|
||||
}
|
||||
String attributesData = column(fields, columns, "attributesData");
|
||||
if (attributesData != null && attributesData.isEmpty()) {
|
||||
attributesData = null;
|
||||
}
|
||||
List<TopicPreference> prefs = null;
|
||||
for (Map.Entry<String, Integer> entry : columns.entrySet()) {
|
||||
if (!entry.getKey().startsWith(TOPIC_PREFERENCE_COLUMN_PREFIX)) {
|
||||
continue;
|
||||
}
|
||||
String status = fields.get(entry.getValue()).trim();
|
||||
if (status.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (prefs == null) {
|
||||
prefs = new ArrayList<>();
|
||||
}
|
||||
prefs.add(new TopicPreference(entry.getKey().substring(TOPIC_PREFERENCE_COLUMN_PREFIX.length()),
|
||||
status));
|
||||
}
|
||||
return new ImportRecord(line, email, null, unsubscribeAll, attributesData, prefs, null);
|
||||
}
|
||||
|
||||
private static String column(List<String> fields, Map<String, Integer> columns, String name) {
|
||||
Integer index = columns.get(name);
|
||||
return index == null ? null : fields.get(index);
|
||||
}
|
||||
|
||||
// RFC 4180 field splitting: a quoted field may contain commas and line breaks, and a doubled
|
||||
// quote inside a quoted field is a literal quote. A quote that does not open a field is data,
|
||||
// not an error: the developer guide's own contact row writes attributesData unquoted as
|
||||
// {"Name": "John"}, and core/common/CsvParser keeps such a quote literal as well. Anything but
|
||||
// a delimiter after a closing quote is still malformed, since that row cannot be read back.
|
||||
static List<String> splitCsvLine(String line) {
|
||||
List<String> fields = new ArrayList<>();
|
||||
StringBuilder current = new StringBuilder();
|
||||
boolean quoted = false;
|
||||
boolean afterClosingQuote = false;
|
||||
for (int i = 0; i < line.length(); i++) {
|
||||
char c = line.charAt(i);
|
||||
if (quoted) {
|
||||
if (c == '"') {
|
||||
if (i + 1 < line.length() && line.charAt(i + 1) == '"') {
|
||||
current.append('"');
|
||||
i++;
|
||||
} else {
|
||||
quoted = false;
|
||||
afterClosingQuote = true;
|
||||
}
|
||||
} else {
|
||||
current.append(c);
|
||||
}
|
||||
} else if (afterClosingQuote) {
|
||||
if (c != ',') {
|
||||
throw new InvalidRecordException("Malformed CSV: unexpected character after a closing quote.");
|
||||
}
|
||||
fields.add(current.toString());
|
||||
current.setLength(0);
|
||||
afterClosingQuote = false;
|
||||
} else if (c == '"' && current.isEmpty()) {
|
||||
quoted = true;
|
||||
} else if (c == ',') {
|
||||
fields.add(current.toString());
|
||||
current.setLength(0);
|
||||
} else {
|
||||
current.append(c);
|
||||
}
|
||||
}
|
||||
if (quoted) {
|
||||
throw new InvalidRecordException("Malformed CSV: unterminated quoted field.");
|
||||
}
|
||||
fields.add(current.toString());
|
||||
return fields;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package io.github.hectorvent.floci.services.ses.imports;
|
||||
|
||||
import io.github.hectorvent.floci.services.ses.model.TopicPreference;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* One parsed source record. {@code error} is set when the record could not be turned into an
|
||||
* import (it still counts as processed and failed, and the job carries on), mirroring how AWS
|
||||
* reports a partially failed import as COMPLETED with a FailedRecordsCount.
|
||||
*/
|
||||
public record ImportRecord(int line, String emailAddress, String reason, Boolean unsubscribeAll,
|
||||
String attributesData, List<TopicPreference> topicPreferences, String error) {
|
||||
|
||||
public static ImportRecord invalid(int line, String error) {
|
||||
return new ImportRecord(line, null, null, null, null, null, error);
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package io.github.hectorvent.floci.services.ses.imports;
|
||||
|
||||
|
||||
/**
|
||||
* A source record that cannot be turned into an import. Caught by the reader that raised it and
|
||||
* reported as a failed record, so one bad row never fails the whole job.
|
||||
*/
|
||||
final class InvalidRecordException extends RuntimeException {
|
||||
|
||||
InvalidRecordException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package io.github.hectorvent.floci.services.ses.imports;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectReader;
|
||||
import io.github.hectorvent.floci.services.ses.model.ImportJob;
|
||||
import io.github.hectorvent.floci.services.ses.model.TopicPreference;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Reads newline-delimited JSON: one complete object per line. */
|
||||
final class JsonLineReader implements RecordReader {
|
||||
|
||||
private static final String BOM = "\uFEFF";
|
||||
private final BufferedReader source;
|
||||
private final ImportJob job;
|
||||
private final ObjectReader lineReader;
|
||||
private int lineNumber;
|
||||
|
||||
JsonLineReader(BufferedReader source, ImportJob job, ObjectReader lineReader) {
|
||||
this.source = source;
|
||||
this.job = job;
|
||||
this.lineReader = lineReader;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ImportRecord next() throws IOException {
|
||||
String read;
|
||||
while ((read = source.readLine()) != null) {
|
||||
lineNumber++;
|
||||
String line = (lineNumber == 1 ? stripBom(read) : read).trim();
|
||||
if (line.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
JsonNode node;
|
||||
try {
|
||||
node = lineReader.readTree(line);
|
||||
} catch (JsonProcessingException e) {
|
||||
return ImportRecord.invalid(lineNumber, "Malformed JSON: " + e.getOriginalMessage());
|
||||
}
|
||||
try {
|
||||
return jsonRecord(lineNumber, node, job);
|
||||
} catch (InvalidRecordException e) {
|
||||
return ImportRecord.invalid(lineNumber, e.getMessage());
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static ImportRecord jsonRecord(int line, JsonNode node, ImportJob job) {
|
||||
if (!node.isObject()) {
|
||||
throw new InvalidRecordException("Each line must be a JSON object.");
|
||||
}
|
||||
String email = textMember(node, "emailAddress");
|
||||
if (ImportJob.DESTINATION_SUPPRESSION_LIST.equals(job.getDestinationType())) {
|
||||
return new ImportRecord(line, email, textMember(node, "reason"), null, null, null, null);
|
||||
}
|
||||
Boolean unsubscribeAll = null;
|
||||
JsonNode unsubscribeNode = node.get("unsubscribeAll");
|
||||
if (unsubscribeNode != null && !unsubscribeNode.isNull()) {
|
||||
if (!unsubscribeNode.isBoolean()) {
|
||||
throw new InvalidRecordException("unsubscribeAll must be a boolean.");
|
||||
}
|
||||
unsubscribeAll = unsubscribeNode.booleanValue();
|
||||
}
|
||||
List<TopicPreference> prefs = null;
|
||||
JsonNode prefsNode = node.get("topicPreferences");
|
||||
if (prefsNode != null && !prefsNode.isNull()) {
|
||||
if (!prefsNode.isArray()) {
|
||||
throw new InvalidRecordException("topicPreferences must be an array.");
|
||||
}
|
||||
prefs = new ArrayList<>();
|
||||
for (JsonNode p : prefsNode) {
|
||||
if (!p.isObject()) {
|
||||
throw new InvalidRecordException("Each topicPreferences element must be a JSON object.");
|
||||
}
|
||||
prefs.add(new TopicPreference(textMember(p, "topicName"), textMember(p, "subscriptionStatus")));
|
||||
}
|
||||
}
|
||||
return new ImportRecord(line, email, null, unsubscribeAll, textMember(node, "attributesData"), prefs, null);
|
||||
}
|
||||
|
||||
// A present member of the wrong JSON type is an invalid record, not coerced text, matching the
|
||||
// SerializationException the CreateContact / PutSuppressedDestination bodies get.
|
||||
private static String textMember(JsonNode node, String field) {
|
||||
JsonNode member = node.get(field);
|
||||
if (member == null || member.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!member.isTextual()) {
|
||||
throw new InvalidRecordException(field + " must be a JSON string.");
|
||||
}
|
||||
return member.textValue();
|
||||
}
|
||||
|
||||
private static String stripBom(String text) {
|
||||
return text.startsWith(BOM) ? text.substring(BOM.length()) : text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package io.github.hectorvent.floci.services.ses.imports;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Yields an import job's source records lazily, one at a time, so a large object is never held in
|
||||
* memory. {@code null} ends the source; a problem with the file as a whole rather than with one
|
||||
* record is an {@code AwsException} that fails the job.
|
||||
*/
|
||||
public interface RecordReader {
|
||||
|
||||
ImportRecord next() throws IOException;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package io.github.hectorvent.floci.services.ses.imports;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectReader;
|
||||
|
||||
import io.github.hectorvent.floci.services.ses.model.ImportJob;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
|
||||
/**
|
||||
* Builds the reader for an import job's DataFormat. Takes the mapper rather than a ready-made
|
||||
* {@link ObjectReader} on purpose: reading a JSON line strictly is a requirement of the format, not
|
||||
* a caller's preference, so the setting lives here instead of leaking to whoever wires this up,
|
||||
* where a plain reader would compile and quietly accept malformed lines.
|
||||
*/
|
||||
public final class RecordReaderFactory {
|
||||
|
||||
/**
|
||||
* FAIL_ON_TRAILING_TOKENS so a line like {@code {"emailAddress":"x"} garbage} is a malformed
|
||||
* record rather than a silently accepted object, as the JSON protocol controllers read their
|
||||
* bodies. Built once: an import reads thousands of lines through it.
|
||||
*/
|
||||
private final ObjectReader lineReader;
|
||||
|
||||
public RecordReaderFactory(ObjectMapper objectMapper) {
|
||||
this.lineReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
|
||||
}
|
||||
|
||||
/** CSV is parsed without Jackson, so only the JSON reader is handed the line reader. */
|
||||
public RecordReader forJob(ImportJob job, BufferedReader source) {
|
||||
return ImportJob.FORMAT_JSON.equals(job.getDataFormat())
|
||||
? new JsonLineReader(source, job, lineReader)
|
||||
: new CsvRecordReader(source, job);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package io.github.hectorvent.floci.services.ses.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* A SES V2 import job: the S3 source, the suppression-list or contact-list destination, and the
|
||||
* job's progress. The destination is flattened (type + action + optional contact list name) since
|
||||
* a job has exactly one; the controller rebuilds the AWS {@code ImportDestination} shape from it.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class ImportJob {
|
||||
|
||||
public static final String DESTINATION_SUPPRESSION_LIST = "SUPPRESSION_LIST";
|
||||
public static final String DESTINATION_CONTACT_LIST = "CONTACT_LIST";
|
||||
public static final String ACTION_PUT = "PUT";
|
||||
public static final String ACTION_DELETE = "DELETE";
|
||||
public static final String FORMAT_CSV = "CSV";
|
||||
public static final String FORMAT_JSON = "JSON";
|
||||
public static final String STATUS_CREATED = "CREATED";
|
||||
public static final String STATUS_PROCESSING = "PROCESSING";
|
||||
public static final String STATUS_COMPLETED = "COMPLETED";
|
||||
public static final String STATUS_FAILED = "FAILED";
|
||||
|
||||
private String jobId;
|
||||
private String region;
|
||||
private String destinationType;
|
||||
private String importAction;
|
||||
private String contactListName;
|
||||
private String s3Url;
|
||||
private String dataFormat;
|
||||
private String jobStatus;
|
||||
private Instant createdTimestamp;
|
||||
private Instant completedTimestamp;
|
||||
private long processedRecordsCount;
|
||||
private long failedRecordsCount;
|
||||
private String errorMessage;
|
||||
|
||||
public ImportJob() {}
|
||||
|
||||
public String getJobId() { return jobId; }
|
||||
public void setJobId(String jobId) { this.jobId = jobId; }
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
|
||||
public String getDestinationType() { return destinationType; }
|
||||
public void setDestinationType(String destinationType) { this.destinationType = destinationType; }
|
||||
|
||||
public String getImportAction() { return importAction; }
|
||||
public void setImportAction(String importAction) { this.importAction = importAction; }
|
||||
|
||||
public String getContactListName() { return contactListName; }
|
||||
public void setContactListName(String contactListName) { this.contactListName = contactListName; }
|
||||
|
||||
public String getS3Url() { return s3Url; }
|
||||
public void setS3Url(String s3Url) { this.s3Url = s3Url; }
|
||||
|
||||
public String getDataFormat() { return dataFormat; }
|
||||
public void setDataFormat(String dataFormat) { this.dataFormat = dataFormat; }
|
||||
|
||||
public String getJobStatus() { return jobStatus; }
|
||||
public void setJobStatus(String jobStatus) { this.jobStatus = jobStatus; }
|
||||
|
||||
public Instant getCreatedTimestamp() { return createdTimestamp; }
|
||||
public void setCreatedTimestamp(Instant createdTimestamp) { this.createdTimestamp = createdTimestamp; }
|
||||
|
||||
public Instant getCompletedTimestamp() { return completedTimestamp; }
|
||||
public void setCompletedTimestamp(Instant completedTimestamp) { this.completedTimestamp = completedTimestamp; }
|
||||
|
||||
public long getProcessedRecordsCount() { return processedRecordsCount; }
|
||||
public void setProcessedRecordsCount(long processedRecordsCount) {
|
||||
this.processedRecordsCount = processedRecordsCount;
|
||||
}
|
||||
|
||||
public long getFailedRecordsCount() { return failedRecordsCount; }
|
||||
public void setFailedRecordsCount(long failedRecordsCount) { this.failedRecordsCount = failedRecordsCount; }
|
||||
|
||||
public String getErrorMessage() { return errorMessage; }
|
||||
public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
|
||||
|
||||
@JsonIgnore
|
||||
public boolean isTerminal() {
|
||||
return STATUS_COMPLETED.equals(jobStatus) || STATUS_FAILED.equals(jobStatus);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user