fix(ses): align export job lookup and cancel with SES (#8385)

Probed against SES on 2026-11-14:

- GetExportJob and CancelExportJob answer 404 NotFoundException
  "Job ID: <id> not found" for an unknown id shaped like a UUID, and keep
  400 "Invalid JobId" for any other id.
- CancelExportJob on an already cancelled job succeeds instead of being
  refused. A completed job is still refused.
- A cancelled job no longer gains a CompletedTimestamp.
- GetExportJob always returns the Statistics structure, empty until a
  record count exists.

The probe used one random UUID and one plain word, so the canonical UUID
form is Floci's reading of where SES separates the two errors.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-11-14 19:50:33 -04:00
1 parent 6de963848b
commit 4373e83af1
6 files changed
+136 -15

No files matched your search

@@ -30,6 +30,7 @@ import software.amazon.awssdk.services.sesv2.model.ListExportJobsRequest;
import software.amazon.awssdk.services.sesv2.model.ListExportJobsResponse;
import software.amazon.awssdk.services.sesv2.model.Message;
import software.amazon.awssdk.services.sesv2.model.MessageInsightsDataSource;
import software.amazon.awssdk.services.sesv2.model.NotFoundException;
import software.amazon.awssdk.services.sesv2.model.PutAccountVdmAttributesRequest;
import software.amazon.awssdk.services.sesv2.model.SendEmailRequest;
import software.amazon.awssdk.services.sesv2.model.VdmAttributes;
@@ -149,8 +150,13 @@ class SesExportJobTest {
@Test
@Order(6)
@DisplayName("an unknown job id is a BadRequest rather than a NotFound")
void unknownJobIsABadRequest() {
@DisplayName("an unknown job id is a NotFound when shaped like an id, a BadRequest otherwise")
void unknownJobIsNotFoundOrBadRequest() {
String unknown = "7b9563a7-12fc-4129-ab8c-bd4783006c08";
assertThatThrownBy(() -> sesV2.getExportJob(
GetExportJobRequest.builder().jobId(unknown).build()))
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("Job ID: <" + unknown + "> not found");
assertThatThrownBy(() -> sesV2.getExportJob(
GetExportJobRequest.builder().jobId("no-such-job").build()))
.isInstanceOf(BadRequestException.class)
@@ -87,11 +87,11 @@ public class SesExportJobController {
putTimestamp(result, "CreatedTimestamp", job.getCreatedTimestamp());
putTimestamp(result, "CompletedTimestamp", job.getCompletedTimestamp());
// AWS returns the structure even before a count exists. It never fills
// ExportedRecordsCount, so Floci leaves that out although the model carries it.
ObjectNode statistics = result.putObject("Statistics");
if (job.getProcessedRecordsCount() != null) {
// AWS returns only ProcessedRecordsCount, never ExportedRecordsCount, so neither does
// Floci even though the model carries both.
result.putObject("Statistics")
.put("ProcessedRecordsCount", job.getProcessedRecordsCount());
statistics.put("ProcessedRecordsCount", job.getProcessedRecordsCount());
}
if (job.getErrorMessage() != null) {
result.putObject("FailureInfo").put("ErrorMessage", job.getErrorMessage());
@@ -38,6 +38,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import static io.floci.aws.services.ses.SesV2Json.intMemberOrAbsent;
@@ -81,6 +82,8 @@ public class SesExportJobService implements Resettable {
private static final DateTimeFormatter OBJECT_STAMP =
DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss", Locale.ROOT).withZone(ZoneOffset.UTC);
private static final int PRESIGNED_URL_EXPIRY_SECONDS = 3600;
private static final Pattern JOB_ID_SHAPE = Pattern.compile(
"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
private final StorageBackend<String, ExportJob> exportJobStore;
private final SesSentEmailService sentEmailService;
@@ -362,9 +365,20 @@ public class SesExportJobService implements Resettable {
return kept;
}
/**
* Probed 2026-11-14: an id shaped like a UUID that names no job is a 404, anything else a 400.
* The probe used one random UUID and one plain word, so the canonical UUID form is Floci's
* reading of where SES draws that line.
*/
public ExportJob getExportJob(String region, String jobId) {
return exportJobStore.get(key(region, jobId))
.orElseThrow(() -> new AwsException("BadRequestException", "Invalid JobId", 400));
return exportJobStore.get(key(region, jobId)).orElseThrow(() -> unknownJob(jobId));
}
private static AwsException unknownJob(String jobId) {
if (JOB_ID_SHAPE.matcher(jobId).matches()) {
return new AwsException("NotFoundException", "Job ID: <" + jobId + "> not found", 404);
}
return new AwsException("BadRequestException", "Invalid JobId", 400);
}
/**
@@ -412,16 +426,22 @@ public class SesExportJobService implements Resettable {
return SesListPaging.newestFirst(job.getCreatedTimestamp(), job.getJobId());
}
/**
* Probed 2026-11-14: cancelling a cancelled job again succeeds, and a cancelled job never gains
* a CompletedTimestamp.
*/
public void cancelExportJob(String region, String jobId) {
synchronized (createLock) {
ExportJob job = getExportJob(region, jobId);
if (ExportJob.STATUS_CANCELLED.equals(job.getJobStatus())) {
return;
}
if (job.isTerminal()) {
throw new AwsException("BadRequestException",
"Cannot cancel an export job that has a <" + job.getJobStatus()
+ "> status.", 400);
}
job.setJobStatus(ExportJob.STATUS_CANCELLED);
job.setCompletedTimestamp(Instant.now(clock));
exportJobStore.put(key(region, jobId), job);
}
}
@@ -0,0 +1,54 @@
package io.floci.aws.services.ses;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.ses.model.ExportJob;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The response shape of a job that has no record count yet, which the integration test cannot
* reach: a Floci export finishes in milliseconds, so every job it reads back is already counted.
*/
class SesExportJobControllerTest {
private static final String REGION = "eu-north-1";
private static final String JOB_ID = "7b9563a7-12fc-4129-ab8c-bd4783006c08";
private final SesExportJobService exportJobService = mock(SesExportJobService.class);
private final RegionResolver regionResolver = mock(RegionResolver.class);
private final SesExportJobController controller = new SesExportJobController(
exportJobService, mock(SesAccountService.class), regionResolver, new ObjectMapper());
@Test
void aCancelledJobCarriesAnEmptyStatisticsAndNoCompletedTimestamp() {
ExportJob job = new ExportJob();
job.setJobId(JOB_ID);
job.setExportSourceType(ExportJob.SOURCE_METRICS);
job.setJobStatus(ExportJob.STATUS_CANCELLED);
job.setDataFormat(ExportJob.FORMAT_CSV);
job.setDataSource("{}");
job.setCreatedTimestamp(Instant.parse("2026-11-14T00:00:00Z"));
when(regionResolver.resolveRegion(any())).thenReturn(REGION);
when(exportJobService.getExportJob(REGION, JOB_ID)).thenReturn(job);
Response response = controller.getExportJob(null, JOB_ID);
ObjectNode body = (ObjectNode) response.getEntity();
// Probed 2026-11-14: SES answers with the structure present and both counts null.
assertTrue(body.has("Statistics"), body.toString());
assertEquals(0, body.get("Statistics").size(), body.toString());
assertFalse(body.has("CompletedTimestamp"), body.toString());
assertFalse(body.get("ExportDestination").has("S3Url"), body.toString());
}
}
@@ -126,8 +126,9 @@ class SesExportJobServiceTest {
tasks.forEach(Runnable::run);
assertEquals(ExportJob.STATUS_CANCELLED,
service.getExportJob(REGION, job.getJobId()).getJobStatus());
ExportJob stored = service.getExportJob(REGION, job.getJobId());
assertEquals(ExportJob.STATUS_CANCELLED, stored.getJobStatus());
assertNull(stored.getCompletedTimestamp(), "SES leaves a cancelled job without one");
verify(s3Service, never()).putObject(anyString(), anyString(), any(), anyString(),
any(Map.class));
}
@@ -354,4 +355,31 @@ class SesExportJobServiceTest {
assertEquals("Cannot cancel an export job that has a <COMPLETED> status.",
thrown.getMessage());
}
@Test
void cancellingACancelledJobAgainSucceeds() {
ExportJob job = createJob();
service.cancelExportJob(REGION, job.getJobId());
service.cancelExportJob(REGION, job.getJobId());
assertEquals(ExportJob.STATUS_CANCELLED,
service.getExportJob(REGION, job.getJobId()).getJobStatus());
}
@Test
void anUnknownJobIsNotFoundOnlyWhenItsIdIsShapedLikeOne() {
String unknown = "7b9563a7-12fc-4129-ab8c-bd4783006c08";
AwsException notFound = assertThrows(AwsException.class,
() -> service.cancelExportJob(REGION, unknown));
assertEquals("NotFoundException", notFound.getErrorCode());
assertEquals(404, notFound.getHttpStatus());
assertEquals("Job ID: <" + unknown + "> not found", notFound.getMessage());
AwsException malformed = assertThrows(AwsException.class,
() -> service.getExportJob(REGION, unknown + "0"));
assertEquals("BadRequestException", malformed.getErrorCode());
assertEquals("Invalid JobId", malformed.getMessage());
}
}
@@ -30,8 +30,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
* Integration tests for the four SES v2 export-job operations.
*
* <p>Probe-confirmed against real SES (2026-09-23): a request naming its own {@code S3Url} is
* refused, exactly one data source is required, the metrics source insists on whole UTC days, an
* unknown job is a 400 rather than a 404, and a finished job cannot be cancelled. Uses an isolated
* refused, exactly one data source is required, the metrics source insists on whole UTC days, and
* a finished job cannot be cancelled. Probed again 2026-11-14: an unknown job is a 404 when its id
* is shaped like a UUID and a 400 otherwise, on the read and on the cancel alike. Uses an isolated
* signing region so no other test's sends reach the exported rows.
*/
@QuarkusTest
@@ -273,10 +274,22 @@ class SesExportJobV2IntegrationTest {
@Test
@Order(9)
void getExportJob_unknownJobIsABadRequest() {
void unknownJob_isNotFoundWhenTheIdIsShapedLikeOne() {
String unknown = "7b9563a7-12fc-4129-ab8c-bd4783006c08";
given().header("Authorization", AUTH)
.when().get("/v2/email/export-jobs/" + unknown).then().statusCode(404)
.header("x-amzn-ErrorType", equalTo("NotFoundException"))
.body("message", equalTo("Job ID: <" + unknown + "> not found"));
given().contentType("application/json").header("Authorization", AUTH)
.when().put("/v2/email/export-jobs/" + unknown + "/cancel").then().statusCode(404)
.body("message", equalTo("Job ID: <" + unknown + "> not found"));
given().header("Authorization", AUTH)
.when().get("/v2/email/export-jobs/no-such-job").then().statusCode(400)
.body("message", equalTo("Invalid JobId"));
given().contentType("application/json").header("Authorization", AUTH)
.when().put("/v2/email/export-jobs/no-such-job/cancel").then().statusCode(400)
.body("message", equalTo("Invalid JobId"));
}
@Test
@@ -463,7 +476,7 @@ class SesExportJobV2IntegrationTest {
// The default account cannot see it.
given().header("Authorization", AUTH)
.when().get("/v2/email/export-jobs/" + jobId).then().statusCode(400);
.when().get("/v2/email/export-jobs/" + jobId).then().statusCode(404);
given().contentType("application/json").header("Authorization", otherAccount)
.body("{\"VdmAttributes\":{\"VdmEnabled\":\"DISABLED\"}}")