From e2e69f65f55be1fc81f891c797008931a788a4f9 Mon Sep 17 00:00:00 2001 From: Ahmed khaled <125749397+ahmedk20@users.noreply.github.com> Date: Sun, 30 Aug 2026 22:44:12 +0300 Subject: [PATCH] feat(core): add configurable mock responses for stub AI services (#2765) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(core): add configurable mock responses for stub AI services Adds AiMockConfigLoader, a shared mock-response config file (path via AI_MOCK_CONFIG env var or floci.ai-mock-config-file) that lets callers override Textract/Comprehend/Rekognition's fixed stub responses on a per-call basis, so application logic that branches on detection results (e.g. "escalate if sentiment is NEGATIVE") can be exercised end-to-end against floci. Mirrors Step Functions' SFN_MOCK_CONFIG mechanism (same mtime-cached reload without restart), but is shared across three services and never throws: a missing file, unset env var, or no matching entry all fall back to the existing default stub, since mocking here is opt-in on top of an always-available default, not the only way to invoke an action. Lookup keys: Comprehend keys on the exact Text value; Textract and Rekognition key on "/" from S3Object (a Bytes-backed image/document has no such key, so mocking only applies to S3Object-based calls). CompareFaces keys off SourceImage only. The Textract async Start*/Get* job flow does not support mocking. Closes #2764 * fix(core): catch unchecked exceptions when loading AI mock config Path.of(path) throws InvalidPathException (unchecked) for a malformed path string, and filesystem access can raise other unchecked exceptions IOException alone doesn't cover. load() only caught IOException, so a bad AI_MOCK_CONFIG value would propagate past the loader and turn a normal Comprehend/Textract/Rekognition request into a 500 — the exact opposite of this loader's contract (mocking is optional; it must never break the default stub). Wrapped the load logic in an outer catch (RuntimeException) that falls back the same way the existing IOException cases already do. Addresses review feedback on #2765. --- docs/services/comprehend.md | 22 ++++ docs/services/rekognition.md | 27 ++++ docs/services/textract.md | 28 ++++ .../floci/config/EmulatorConfig.java | 10 ++ .../floci/core/common/AiMockConfigLoader.java | 122 ++++++++++++++++++ .../comprehend/ComprehendService.java | 37 +++++- .../rekognition/RekognitionJsonHandler.java | 43 +++--- .../rekognition/RekognitionService.java | 45 ++++++- .../textract/TextractJsonHandler.java | 31 ++++- .../services/textract/TextractService.java | 29 ++++- src/main/resources/application.yml | 2 + .../core/common/AiMockConfigLoaderTest.java | 120 +++++++++++++++++ .../comprehend/ComprehendIntegrationTest.java | 15 +++ .../EventBridgeSchedulerIntegrationTest.java | 2 + .../RekognitionIntegrationTest.java | 15 +++ .../textract/TextractIntegrationTest.java | 15 +++ src/test/resources/application.yml | 1 + .../resources/fixtures/ai-mock-config.json | 42 ++++++ 18 files changed, 569 insertions(+), 37 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/core/common/AiMockConfigLoader.java create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/AiMockConfigLoaderTest.java create mode 100644 src/test/resources/fixtures/ai-mock-config.json diff --git a/docs/services/comprehend.md b/docs/services/comprehend.md index 0778b2b9e0..f4214049eb 100644 --- a/docs/services/comprehend.md +++ b/docs/services/comprehend.md @@ -40,6 +40,28 @@ | Variable | Default | Description | |---|---|---| | `FLOCI_SERVICES_COMPREHEND_ENABLED` | `true` | Enable or disable the service | +| `AI_MOCK_CONFIG` | unset | Path to a shared mock-response config file — see "Mock Responses" below | + +## Mock Responses + +The default stub responses above are the same for every call. To exercise application +logic that branches on detection results (e.g. "escalate if sentiment is NEGATIVE"), point +`AI_MOCK_CONFIG` at a JSON file shared across Comprehend, Textract, and Rekognition: + +```json +{ + "comprehend": { + "I am furious about this outage": { + "DetectSentiment": { "Sentiment": "NEGATIVE", "SentimentScore": { "Positive": 0.0, "Negative": 0.95, "Neutral": 0.05, "Mixed": 0.0 } } + } + } +} +``` + +The lookup key is the **exact `Text` value** sent in the request. The file is re-read when +its modification time changes, so it can be edited without restarting the emulator. A +missing file, an unset `AI_MOCK_CONFIG`, or no matching entry all fall back to the default +stub — mocking is opt-in and never breaks a call that isn't using it. ## Examples diff --git a/docs/services/rekognition.md b/docs/services/rekognition.md index 560c96508b..047e80af9b 100644 --- a/docs/services/rekognition.md +++ b/docs/services/rekognition.md @@ -52,6 +52,33 @@ | Variable | Default | Description | |---|---|---| | `FLOCI_SERVICES_REKOGNITION_ENABLED` | `true` | Enable or disable the service | +| `AI_MOCK_CONFIG` | unset | Path to a shared mock-response config file — see "Mock Responses" below | + +## Mock Responses + +The default stub responses above are the same for every call. To exercise application +logic that branches on detection results, point `AI_MOCK_CONFIG` at a JSON file shared +across Rekognition, Textract, and Comprehend: + +```json +{ + "rekognition": { + "my-bucket/cat.jpg": { + "DetectLabels": { + "Labels": [{ "Name": "Cat", "Confidence": 97.2 }, { "Name": "Animal", "Confidence": 98.1 }], + "LabelModelVersion": "1.0" + } + } + } +} +``` + +The lookup key is **`"/"`** from `Image.S3Object` (or `SourceImage.S3Object` +for `CompareFaces` — `TargetImage` has no independent key in this scheme). A `Bytes`-backed +image has no such key, so mocking only applies to S3Object-based calls. The file is re-read +when its modification time changes, so it can be edited without restarting the emulator. A +missing file, an unset `AI_MOCK_CONFIG`, or no matching entry all fall back to the default +stub. ## Examples diff --git a/docs/services/textract.md b/docs/services/textract.md index 9dca335c85..440307796b 100644 --- a/docs/services/textract.md +++ b/docs/services/textract.md @@ -39,6 +39,34 @@ Every block includes: `Id` (UUID), `Confidence` (99.9), `Page` (1), and a `Geome | Variable | Default | Description | |---|---|---| | `FLOCI_SERVICES_TEXTRACT_ENABLED` | `true` | Enable or disable the service | +| `AI_MOCK_CONFIG` | unset | Path to a shared mock-response config file — see "Mock Responses" below | + +## Mock Responses + +`DetectDocumentText` and `AnalyzeDocument` return the same stub `Block` list for every +call by default. To exercise application logic that reads the detected text, point +`AI_MOCK_CONFIG` at a JSON file shared across Textract, Comprehend, and Rekognition: + +```json +{ + "textract": { + "my-bucket/invoice.pdf": { + "DetectDocumentText": { + "DocumentMetadata": { "Pages": 1 }, + "Blocks": [{ "BlockType": "LINE", "Id": "line-1", "Confidence": 99.5, "Text": "Invoice Total: $42.00" }], + "DetectDocumentTextModelVersion": "1.0" + } + } + } +} +``` + +The lookup key is **`"/"`** from `Document.S3Object`. A `Bytes`-backed +`Document` has no such key, so mocking only applies to S3Object-based calls — a +`Bytes`-backed request always gets the default stub. The file is re-read when its +modification time changes, so it can be edited without restarting the emulator. A missing +file, an unset `AI_MOCK_CONFIG`, or no matching entry all fall back to the default stub. +The async `Start*`/`Get*` job flow does not support mocking. ## Examples diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index fe11bc4e34..49134d8440 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -57,6 +57,16 @@ public interface EmulatorConfig { @WithDefault("public.ecr.aws") String ecrBaseUri(); + /** + * Path to a shared mock-response configuration file used by the fixed-stub AI services + * (Textract, Comprehend, Rekognition) to return a caller-configured response instead of + * their default canned stub. See {@link io.github.hectorvent.floci.core.common.AiMockConfigLoader}. + * Equivalent to Step Functions' {@code SFN_MOCK_CONFIG}, but shared across services since + * mocking here is opt-in on top of an always-available default, not the only way to invoke + * an action. + */ + Optional aiMockConfigFile(); + StorageConfig storage(); DnsConfig dns(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AiMockConfigLoader.java b/src/main/java/io/github/hectorvent/floci/core/common/AiMockConfigLoader.java new file mode 100644 index 0000000000..d26084b562 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/AiMockConfigLoader.java @@ -0,0 +1,122 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; + +/** + * Loads the shared mock-response configuration file referenced by {@code AI_MOCK_CONFIG} + * or {@code floci.ai-mock-config-file}, used by the fixed-stub AI services (Textract, + * Comprehend, Rekognition) to return a caller-configured response instead of their default + * canned stub. The file is re-read when its modification time changes, so it can be edited + * without restarting the emulator — same mechanism as {@code SfnMockLoader}. + *

+ * Unlike {@code SfnMockLoader} (where the mock configuration is the only way to run a + * {@code StartExecution} test case, so a missing file or entry is a client error), mocking + * here is an opt-in layer on top of every service's always-available default stub. This + * loader therefore never throws: no file configured, a missing/unreadable file, or no + * matching entry all resolve to {@link Optional#empty()}, and callers fall back to their + * default response. + *

+ * Config file shape: {@code {"": {"": {"": }}}}. + * See {@code docs/services/textract.md} / {@code comprehend.md} / {@code rekognition.md} + * "Mock Responses" sections for each service's lookup-key convention. + */ +@ApplicationScoped +public class AiMockConfigLoader { + + private static final Logger LOG = Logger.getLogger(AiMockConfigLoader.class); + + private final Optional configuredPath; + private final ObjectMapper objectMapper; + private volatile CachedMockFile cache; + private volatile boolean warnedMissingFile; + + private record CachedMockFile(String path, long lastModified, JsonNode root) { + } + + @Inject + public AiMockConfigLoader(EmulatorConfig config, ObjectMapper objectMapper) { + this(config.aiMockConfigFile(), objectMapper); + } + + AiMockConfigLoader(Optional configuredPath, ObjectMapper objectMapper) { + this.configuredPath = configuredPath.filter(path -> !path.isBlank()); + this.objectMapper = objectMapper; + } + + /** + * Looks up a configured mock response for the given service, lookup key, and action. + * Returns empty whenever a default-stub fallback is appropriate — this method never + * throws. + */ + public Optional lookup(String serviceKey, String lookupKey, String action) { + if (configuredPath.isEmpty() || lookupKey == null) { + return Optional.empty(); + } + JsonNode root = load(configuredPath.get()); + if (root == null) { + return Optional.empty(); + } + JsonNode response = root.path(serviceKey).path(lookupKey).path(action); + if (response.isObject()) { + LOG.debugv("AI mock hit: {0}/{1}/{2}", serviceKey, lookupKey, action); + return Optional.of(response); + } + return Optional.empty(); + } + + private JsonNode load(String path) { + try { + return loadOrThrow(path); + } catch (RuntimeException e) { + // Path.of(path) throws InvalidPathException (unchecked) for a malformed path + // string (e.g. an embedded NUL character), and filesystem access can throw + // other unchecked exceptions (e.g. SecurityException) that IOException alone + // does not cover. None of that may ever break a real request: mocking is + // optional, so any failure to load the config falls back to the default stub, + // exactly like the IOException cases below. + LOG.warnv("AI mock configuration at {0} could not be loaded ({1}); using default stub responses.", + path, e); + return null; + } + } + private JsonNode loadOrThrow(String path) { + var file = Path.of(path); + long lastModified; + try { + lastModified = Files.getLastModifiedTime(file).toMillis(); + } catch (IOException e) { + if (!warnedMissingFile) { + warnedMissingFile = true; + LOG.warnv("AI mock configuration file not found: {0}; using default stub responses.", path); + } + return null; + } + var cached = cache; + if (cached != null && cached.path().equals(path) && cached.lastModified() == lastModified) { + return cached.root(); + } + JsonNode root; + try { + root = objectMapper.readTree(Files.readAllBytes(file)); + } catch (IOException e) { + LOG.warnv("Failed to read AI mock configuration file {0}: {1}", path, e.getMessage()); + return null; + } + if (root == null || !root.isObject()) { + LOG.warnv("AI mock configuration file {0} must contain a JSON object; ignoring.", path); + return null; + } + cache = new CachedMockFile(path, lastModified, root); + return root; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/comprehend/ComprehendService.java b/src/main/java/io/github/hectorvent/floci/services/comprehend/ComprehendService.java index 8b34a67f47..ee04050309 100644 --- a/src/main/java/io/github/hectorvent/floci/services/comprehend/ComprehendService.java +++ b/src/main/java/io/github/hectorvent/floci/services/comprehend/ComprehendService.java @@ -1,19 +1,27 @@ package io.github.hectorvent.floci.services.comprehend; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AiMockConfigLoader; import io.github.hectorvent.floci.core.common.AwsException; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; +import java.util.Optional; import java.util.Set; /** * Dummy response builder for Amazon Comprehend. Stateless — every sync Detect* * action ignores the actual Text content and returns a fixed but AWS-shaped - * response. Input validation (Text/LanguageCode required, supported language - * codes) still follows real Comprehend behavior, since that is protocol + * response by default. Input validation (Text/LanguageCode required, supported + * language codes) still follows real Comprehend behavior, since that is protocol * compatibility rather than NLP logic. *

+ * Callers can override the default stub per exact {@code Text} value via + * {@link AiMockConfigLoader} — see {@code docs/services/comprehend.md} + * "Mock Responses". Lookup happens after input validation, so a malformed + * request still gets a real validation error rather than a silently-matched mock. + *

* Real detection logic (lexicon/regex based) is a planned follow-up; see the * tracking issue for scope. * @@ -21,6 +29,7 @@ import java.util.Set; */ @ApplicationScoped public class ComprehendService { + private static final String SERVICE_KEY = "comprehend"; /** Languages accepted by DetectSentiment/DetectKeyPhrases. */ private static final Set SUPPORTED_LANGUAGE_CODES = Set.of( "en", "es", "fr", "de", "it", "pt", "ar", "hi", "ja", "ko", "zh", "zh-TW"); @@ -31,9 +40,11 @@ public class ComprehendService { */ private static final Set PII_SUPPORTED_LANGUAGE_CODES = Set.of("en", "es"); private final ObjectMapper objectMapper; + private final AiMockConfigLoader mockConfigLoader; @Inject - public ComprehendService(ObjectMapper objectMapper) { + public ComprehendService(ObjectMapper objectMapper, AiMockConfigLoader mockConfigLoader) { this.objectMapper = objectMapper; + this.mockConfigLoader = mockConfigLoader; } /** * DetectSentiment — always returns NEUTRAL with flat confidence scores. @@ -42,6 +53,10 @@ public class ComprehendService { public Response detectSentiment(String text, String languageCode) { requireText(text); requireLanguageCode(languageCode, SUPPORTED_LANGUAGE_CODES); + Optional mock = mockConfigLoader.lookup(SERVICE_KEY, text, "DetectSentiment"); + if (mock.isPresent()) { + return Response.ok(mock.get()).build(); + } ObjectNode root = objectMapper.createObjectNode(); root.put("Sentiment", "NEUTRAL"); ObjectNode score = root.putObject("SentimentScore"); @@ -58,6 +73,10 @@ public class ComprehendService { public Response detectKeyPhrases(String text, String languageCode) { requireText(text); requireLanguageCode(languageCode, SUPPORTED_LANGUAGE_CODES); + Optional mock = mockConfigLoader.lookup(SERVICE_KEY, text, "DetectKeyPhrases"); + if (mock.isPresent()) { + return Response.ok(mock.get()).build(); + } ObjectNode root = objectMapper.createObjectNode(); ArrayNode keyPhrases = root.putArray("KeyPhrases"); ObjectNode phrase = keyPhrases.addObject(); @@ -73,6 +92,10 @@ public class ComprehendService { */ public Response detectDominantLanguage(String text) { requireText(text); + Optional mock = mockConfigLoader.lookup(SERVICE_KEY, text, "DetectDominantLanguage"); + if (mock.isPresent()) { + return Response.ok(mock.get()).build(); + } ObjectNode root = objectMapper.createObjectNode(); ArrayNode languages = root.putArray("Languages"); ObjectNode language = languages.addObject(); @@ -88,6 +111,10 @@ public class ComprehendService { public Response detectPiiEntities(String text, String languageCode) { requireText(text); requireLanguageCode(languageCode, PII_SUPPORTED_LANGUAGE_CODES); + Optional mock = mockConfigLoader.lookup(SERVICE_KEY, text, "DetectPiiEntities"); + if (mock.isPresent()) { + return Response.ok(mock.get()).build(); + } ObjectNode root = objectMapper.createObjectNode(); root.putArray("Entities"); return Response.ok(root).build(); @@ -99,6 +126,10 @@ public class ComprehendService { public Response containsPiiEntities(String text, String languageCode) { requireText(text); requireLanguageCode(languageCode, PII_SUPPORTED_LANGUAGE_CODES); + Optional mock = mockConfigLoader.lookup(SERVICE_KEY, text, "ContainsPiiEntities"); + if (mock.isPresent()) { + return Response.ok(mock.get()).build(); + } ObjectNode root = objectMapper.createObjectNode(); root.putArray("Labels"); return Response.ok(root).build(); diff --git a/src/main/java/io/github/hectorvent/floci/services/rekognition/RekognitionJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/rekognition/RekognitionJsonHandler.java index 7ff085a655..ace18cffb6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rekognition/RekognitionJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/rekognition/RekognitionJsonHandler.java @@ -32,27 +32,15 @@ public class RekognitionJsonHandler { public Response handle(String action, JsonNode request, String region) { LOG.debugv("Rekognition action: {0}", action); return switch (action) { - case "DetectLabels" -> { - requireImage(request, "Image"); - yield rekognitionService.detectLabels(); - } - case "DetectFaces" -> { - requireImage(request, "Image"); - yield rekognitionService.detectFaces(); - } - case "DetectText" -> { - requireImage(request, "Image"); - yield rekognitionService.detectText(); - } + case "DetectLabels" -> rekognitionService.detectLabels(requireImage(request, "Image")); + case "DetectFaces" -> rekognitionService.detectFaces(requireImage(request, "Image")); + case "DetectText" -> rekognitionService.detectText(requireImage(request, "Image")); case "CompareFaces" -> { - requireImage(request, "SourceImage"); + String sourceKey = requireImage(request, "SourceImage"); requireImage(request, "TargetImage"); - yield rekognitionService.compareFaces(); - } - case "DetectModerationLabels" -> { - requireImage(request, "Image"); - yield rekognitionService.detectModerationLabels(); + yield rekognitionService.compareFaces(sourceKey); } + case "DetectModerationLabels" -> rekognitionService.detectModerationLabels(requireImage(request, "Image")); default -> Response.status(400) .entity(new AwsErrorResponse("UnknownOperationException", "Unknown operation: RekognitionService." + action)) @@ -62,9 +50,12 @@ public class RekognitionJsonHandler { /** * The Image shape (real content ignored — the response is a fixed stub) is still * required and must carry Bytes or S3Object, matching AWS's own required-member - * and one-of-Bytes-or-S3Object modeling for Image/SourceImage/TargetImage. + * and one-of-Bytes-or-S3Object modeling for Image/SourceImage/TargetImage. Returns + * an optional "Bucket/Name" mock-response lookup key when S3Object is present (null + * for a Bytes-backed image, which has no such key — mock lookup then simply doesn't + * apply, same as always). */ - private void requireImage(JsonNode request, String field) { + private String requireImage(JsonNode request, String field) { JsonNode image = request == null ? null : request.get(field); if (image == null || image.isNull()) { throw new AwsException("InvalidParameterException", field + " is a required field.", 400); @@ -79,6 +70,18 @@ public class RekognitionJsonHandler { throw new AwsException("InvalidParameterException", field + " must specify Bytes or S3Object.", 400); } + return extractS3Key(image.get("S3Object")); + } + private String extractS3Key(JsonNode s3Object) { + if (s3Object == null || !s3Object.isObject()) { + return null; + } + JsonNode bucket = s3Object.get("Bucket"); + JsonNode name = s3Object.get("Name"); + if (bucket == null || !bucket.isTextual() || name == null || !name.isTextual()) { + return null; + } + return bucket.asText() + "/" + name.asText(); } /** * Bytes (a blob shape, base64-encoded string on the wire) and S3Object (a structure) diff --git a/src/main/java/io/github/hectorvent/floci/services/rekognition/RekognitionService.java b/src/main/java/io/github/hectorvent/floci/services/rekognition/RekognitionService.java index 50fd5f6a63..ae3e0e3169 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rekognition/RekognitionService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rekognition/RekognitionService.java @@ -1,13 +1,16 @@ package io.github.hectorvent.floci.services.rekognition; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AiMockConfigLoader; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; +import java.util.Optional; /** * Dummy response builder for Amazon Rekognition. Stateless — every action ignores - * the actual image content and returns a fixed but AWS-shaped response. + * the actual image content and returns a fixed but AWS-shaped response by default. *

* Content-listing operations (DetectLabels, DetectText) always return one canned * entry, matching the TextractService stub precedent. Face/moderation operations @@ -16,6 +19,11 @@ import jakarta.ws.rs.core.Response; * biometric attributes or a moderation flag for content that was never analyzed, * matching the ComprehendService PII-detection precedent. *

+ * Callers can override the default stub per exact "Bucket/Name" S3Object key via + * {@link AiMockConfigLoader} — see {@code docs/services/rekognition.md} + * "Mock Responses". CompareFaces keys off SourceImage only (TargetImage has no + * independent key in this scheme). + *

* Real detection logic is a planned follow-up; see the tracking issue for scope. * * @see Rekognition API Reference @@ -23,16 +31,23 @@ import jakarta.ws.rs.core.Response; @ApplicationScoped public class RekognitionService { static final String MODEL_VERSION = "1.0"; + private static final String SERVICE_KEY = "rekognition"; private final ObjectMapper objectMapper; + private final AiMockConfigLoader mockConfigLoader; @Inject - public RekognitionService(ObjectMapper objectMapper) { + public RekognitionService(ObjectMapper objectMapper, AiMockConfigLoader mockConfigLoader) { this.objectMapper = objectMapper; + this.mockConfigLoader = mockConfigLoader; } /** * DetectLabels — always returns a single stub label. * Response shape: https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectLabels.html */ - public Response detectLabels() { + public Response detectLabels(String mockKey) { + Optional mock = mockConfigLoader.lookup(SERVICE_KEY, mockKey, "DetectLabels"); + if (mock.isPresent()) { + return Response.ok(mock.get()).build(); + } ObjectNode root = objectMapper.createObjectNode(); ArrayNode labels = root.putArray("Labels"); ObjectNode label = labels.addObject(); @@ -45,7 +60,11 @@ public class RekognitionService { * DetectFaces — always reports no faces found. * Response shape: https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectFaces.html */ - public Response detectFaces() { + public Response detectFaces(String mockKey) { + Optional mock = mockConfigLoader.lookup(SERVICE_KEY, mockKey, "DetectFaces"); + if (mock.isPresent()) { + return Response.ok(mock.get()).build(); + } ObjectNode root = objectMapper.createObjectNode(); root.putArray("FaceDetails"); return Response.ok(root).build(); @@ -55,7 +74,11 @@ public class RekognitionService { * Textract's PAGE/LINE/WORD block-hierarchy convention. * Response shape: https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectText.html */ - public Response detectText() { + public Response detectText(String mockKey) { + Optional mock = mockConfigLoader.lookup(SERVICE_KEY, mockKey, "DetectText"); + if (mock.isPresent()) { + return Response.ok(mock.get()).build(); + } ObjectNode root = objectMapper.createObjectNode(); ArrayNode detections = root.putArray("TextDetections"); ObjectNode line = detections.addObject(); @@ -79,7 +102,11 @@ public class RekognitionService { * legitimately omitted when no face is found in the source image). * Response shape: https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CompareFaces.html */ - public Response compareFaces() { + public Response compareFaces(String mockKey) { + Optional mock = mockConfigLoader.lookup(SERVICE_KEY, mockKey, "CompareFaces"); + if (mock.isPresent()) { + return Response.ok(mock.get()).build(); + } ObjectNode root = objectMapper.createObjectNode(); root.putArray("FaceMatches"); root.putArray("UnmatchedFaces"); @@ -89,7 +116,11 @@ public class RekognitionService { * DetectModerationLabels — always reports no moderation labels found. * Response shape: https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectModerationLabels.html */ - public Response detectModerationLabels() { + public Response detectModerationLabels(String mockKey) { + Optional mock = mockConfigLoader.lookup(SERVICE_KEY, mockKey, "DetectModerationLabels"); + if (mock.isPresent()) { + return Response.ok(mock.get()).build(); + } ObjectNode root = objectMapper.createObjectNode(); root.putArray("ModerationLabels"); root.put("ModerationModelVersion", MODEL_VERSION); diff --git a/src/main/java/io/github/hectorvent/floci/services/textract/TextractJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/textract/TextractJsonHandler.java index a982c0de61..97a0ac4c8f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/textract/TextractJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/textract/TextractJsonHandler.java @@ -21,13 +21,18 @@ public class TextractJsonHandler { } /** * Dispatches Textract actions received via the AwsJson11Controller. - * The request body is accepted but not parsed — stub ignores document input. + * The request body's Document content is not decoded — stub ignores it beyond + * extracting Document.S3Object as an optional mock-response lookup key (see + * {@link TextractService}); a Bytes-based Document has no such key, so mock + * lookup is simply skipped and the default stub applies, same as always. */ public Response handle(String action, JsonNode request, String region) { LOG.debugv("Textract action: {0}", action); return switch (action) { - case "DetectDocumentText" -> textractService.detectDocumentText(); - case "AnalyzeDocument" -> textractService.analyzeDocument(); + case "DetectDocumentText" -> textractService.detectDocumentText( + extractS3Key(request, "Document")); + case "AnalyzeDocument" -> textractService.analyzeDocument( + extractS3Key(request, "Document")); case "StartDocumentTextDetection" -> textractService.startDocumentTextDetection(); case "GetDocumentTextDetection" -> textractService.getDocumentTextDetection( getStringField(request, "JobId")); @@ -44,4 +49,24 @@ public class TextractJsonHandler { JsonNode value = node == null ? null : node.get(field); return (value != null && !value.isNull()) ? value.asText() : null; } + /** + * Extracts an optional "Bucket/Name" mock-response lookup key from an S3Object-backed + * document field. Returns null when the field is absent, not an object, or Bytes-backed + * (no S3Object) — every caller treats a null key as "mock lookup does not apply". + */ + private String extractS3Key(JsonNode request, String field) { + if (request == null) { + return null; + } + JsonNode s3Object = request.path(field).path("S3Object"); + if (!s3Object.isObject()) { + return null; + } + JsonNode bucket = s3Object.get("Bucket"); + JsonNode name = s3Object.get("Name"); + if (bucket == null || !bucket.isTextual() || name == null || !name.isTextual()) { + return null; + } + return bucket.asText() + "/" + name.asText(); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/textract/TextractService.java b/src/main/java/io/github/hectorvent/floci/services/textract/TextractService.java index e01571746e..44013d4f0c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/textract/TextractService.java +++ b/src/main/java/io/github/hectorvent/floci/services/textract/TextractService.java @@ -1,31 +1,44 @@ package io.github.hectorvent.floci.services.textract; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AiMockConfigLoader; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.Resettable; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** * Dummy response builder for Amazon Textract. Stateless for sync operations. * Async operations (Start* and Get*) use an in-memory job store. * No real OCR or document analysis is performed: every call returns a fixed - * stub Block list matching the AWS Textract wire format. + * stub Block list matching the AWS Textract wire format by default. + *

+ * Callers can override the sync-action default per exact "Bucket/Name" S3Object + * key via {@link AiMockConfigLoader} — see {@code docs/services/textract.md} + * "Mock Responses". A Bytes-backed Document has no such key, so mock lookup is + * simply skipped for it. The async Start and Get action pairs do not support + * mocking (the mock key would need to be persisted alongside the job id) — out + * of scope. * * @see Textract API Reference */ @ApplicationScoped public class TextractService implements Resettable { static final String MODEL_VERSION = "1.0"; + private static final String SERVICE_KEY = "textract"; private final ObjectMapper objectMapper; + private final AiMockConfigLoader mockConfigLoader; /** In-memory async job store: jobId to jobType ("TEXT_DETECTION" or "DOCUMENT_ANALYSIS"). */ private final ConcurrentHashMap asyncJobs = new ConcurrentHashMap<>(); @Inject - public TextractService(ObjectMapper objectMapper) { + public TextractService(ObjectMapper objectMapper, AiMockConfigLoader mockConfigLoader) { this.objectMapper = objectMapper; + this.mockConfigLoader = mockConfigLoader; } public void clear() { asyncJobs.clear(); @@ -34,7 +47,11 @@ public class TextractService implements Resettable { * DetectDocumentText — returns a stub PAGE + LINE + WORD block hierarchy. * Response shape: https://docs.aws.amazon.com/textract/latest/dg/API_DetectDocumentText.html */ - public Response detectDocumentText() { + public Response detectDocumentText(String mockKey) { + Optional mock = mockConfigLoader.lookup(SERVICE_KEY, mockKey, "DetectDocumentText"); + if (mock.isPresent()) { + return Response.ok(mock.get()).build(); + } ObjectNode root = objectMapper.createObjectNode(); root.set("DocumentMetadata", buildDocumentMetadata(1)); root.set("Blocks", buildStubBlocks()); @@ -45,7 +62,11 @@ public class TextractService implements Resettable { * AnalyzeDocument — returns the same stub blocks; FeatureTypes are accepted but ignored. * Response shape: https://docs.aws.amazon.com/textract/latest/dg/API_AnalyzeDocument.html */ - public Response analyzeDocument() { + public Response analyzeDocument(String mockKey) { + Optional mock = mockConfigLoader.lookup(SERVICE_KEY, mockKey, "AnalyzeDocument"); + if (mock.isPresent()) { + return Response.ok(mock.get()).build(); + } ObjectNode root = objectMapper.createObjectNode(); root.set("DocumentMetadata", buildDocumentMetadata(1)); root.set("Blocks", buildStubBlocks()); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 51c9dab365..eb55c06fa1 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -83,6 +83,8 @@ floci: # Needed for multi-container Docker setups. Example: FLOCI_HOSTNAME=floci default-region: us-east-1 default-account-id: "000000000000" + # Shared mock-response config for Textract/Comprehend/Rekognition. See AiMockConfigLoader. + ai-mock-config-file: ${AI_MOCK_CONFIG:} storage: # Supported modes: memory, persistent, hybrid, wal mode: memory diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AiMockConfigLoaderTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AiMockConfigLoaderTest.java new file mode 100644 index 0000000000..a984299ca9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/AiMockConfigLoaderTest.java @@ -0,0 +1,120 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AiMockConfigLoaderTest { + + private static final String CONFIG = """ + { + "comprehend": { + "I love this": { "DetectSentiment": { "Sentiment": "POSITIVE" } } + } + } + """; + + @TempDir + Path tempDir; + + private AiMockConfigLoader loader(String content) throws IOException { + var file = tempDir.resolve("ai-mock-config.json"); + Files.writeString(file, content); + return new AiMockConfigLoader(Optional.of(file.toString()), new ObjectMapper()); + } + + @Test + void resolvesMatchingEntry() throws IOException { + var loader = loader(CONFIG); + var result = loader.lookup("comprehend", "I love this", "DetectSentiment"); + assertTrue(result.isPresent()); + assertEquals("POSITIVE", result.get().path("Sentiment").asText()); + } + + @Test + void fallsBackWhenServiceKeyUnmatched() throws IOException { + var loader = loader(CONFIG); + assertTrue(loader.lookup("rekognition", "I love this", "DetectSentiment").isEmpty()); + } + + @Test + void fallsBackWhenLookupKeyUnmatched() throws IOException { + var loader = loader(CONFIG); + assertTrue(loader.lookup("comprehend", "I hate this", "DetectSentiment").isEmpty()); + } + + @Test + void fallsBackWhenActionUnmatched() throws IOException { + var loader = loader(CONFIG); + assertTrue(loader.lookup("comprehend", "I love this", "DetectKeyPhrases").isEmpty()); + } + + @Test + void fallsBackWhenLookupKeyIsNull() throws IOException { + // Bytes-backed images/documents have no natural lookup key. + var loader = loader(CONFIG); + assertTrue(loader.lookup("comprehend", null, "DetectSentiment").isEmpty()); + } + + @Test + void fallsBackWhenNoConfigConfigured() { + var loader = new AiMockConfigLoader(Optional.empty(), new ObjectMapper()); + assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty()); + } + + @Test + void fallsBackWhenFileMissing() { + var loader = new AiMockConfigLoader( + Optional.of(tempDir.resolve("absent.json").toString()), new ObjectMapper()); + assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty()); + } + + @Test + void fallsBackWhenConfiguredPathIsUnparseable() { + // An embedded NUL byte makes Path.of() throw InvalidPathException, an unchecked + // exception that a plain "catch (IOException)" does not cover. + var loader = new AiMockConfigLoader(Optional.of("bad\0path.json"), new ObjectMapper()); + assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty()); + } + + @Test + void fallsBackWhenFileIsNotAJsonObject() throws IOException { + var loader = loader("[1, 2, 3]"); + assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty()); + } + + @Test + void fallsBackWhenFileIsMalformedJson() throws IOException { + var loader = loader("{not valid json"); + assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty()); + } + + @Test + void treatsBlankConfiguredPathAsUnconfigured() { + var loader = new AiMockConfigLoader(Optional.of(" "), new ObjectMapper()); + assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty()); + } + + @Test + void reloadsFileWhenModified() throws IOException, InterruptedException { + var file = tempDir.resolve("ai-mock-config.json"); + Files.writeString(file, CONFIG); + var loader = new AiMockConfigLoader(Optional.of(file.toString()), new ObjectMapper()); + assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isPresent()); + assertFalse(loader.lookup("comprehend", "I hate this", "DetectSentiment").isPresent()); + + Thread.sleep(1100); + Files.writeString(file, CONFIG.replace("I love this", "I hate this")); + assertTrue(loader.lookup("comprehend", "I hate this", "DetectSentiment").isPresent()); + assertFalse(loader.lookup("comprehend", "I love this", "DetectSentiment").isPresent()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/comprehend/ComprehendIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/comprehend/ComprehendIntegrationTest.java index ee68cc0d5b..60e96a0ba9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/comprehend/ComprehendIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/comprehend/ComprehendIntegrationTest.java @@ -37,6 +37,21 @@ class ComprehendIntegrationTest { .body("SentimentScore.Mixed", notNullValue()); } @Test + void detectSentiment_matchingMockConfig_returnsConfiguredResponse() { + // src/test/resources/fixtures/ai-mock-config.json maps this exact Text to POSITIVE. + given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "Comprehend_20171127.DetectSentiment") + .header("Authorization", AUTH_HEADER) + .body("{\"Text\":\"I absolutely love this product!\",\"LanguageCode\":\"en\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body("Sentiment", equalTo("POSITIVE")) + .body("SentimentScore.Positive", equalTo(0.98f)); + } + @Test void detectSentiment_missingText_returns400() { given() .contentType(CONTENT_TYPE) diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java index 82026fb421..1826bab731 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java @@ -300,6 +300,8 @@ class EventBridgeSchedulerIntegrationTest { @Override public String ecrBaseUri() { return ""; } @Override + public Optional aiMockConfigFile() { return Optional.empty(); } + @Override public StorageConfig storage() { return null; } @Override public DnsConfig dns() { diff --git a/src/test/java/io/github/hectorvent/floci/services/rekognition/RekognitionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/rekognition/RekognitionIntegrationTest.java index 1de699d23a..e27f4df597 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rekognition/RekognitionIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rekognition/RekognitionIntegrationTest.java @@ -38,6 +38,21 @@ class RekognitionIntegrationTest { .body("LabelModelVersion", equalTo("1.0")); } @Test + void detectLabels_matchingMockConfig_returnsConfiguredResponse() { + // src/test/resources/fixtures/ai-mock-config.json maps mock-bucket/cat.jpg. + given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "RekognitionService.DetectLabels") + .header("Authorization", AUTH_HEADER) + .body("{\"Image\":{\"S3Object\":{\"Bucket\":\"mock-bucket\",\"Name\":\"cat.jpg\"}}}") + .when() + .post("/") + .then() + .statusCode(200) + .body("Labels", hasSize(2)) + .body("Labels.Name", hasItems("Cat", "Animal")); + } + @Test void detectLabels_missingImage_returns400() { given() .contentType(CONTENT_TYPE) diff --git a/src/test/java/io/github/hectorvent/floci/services/textract/TextractIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/textract/TextractIntegrationTest.java index a506d5fbfa..76d5d524ab 100644 --- a/src/test/java/io/github/hectorvent/floci/services/textract/TextractIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/textract/TextractIntegrationTest.java @@ -37,6 +37,21 @@ class TextractIntegrationTest { .body("Blocks.BlockType", hasItems("PAGE", "LINE", "WORD")); } @Test + void detectDocumentText_matchingMockConfig_returnsConfiguredResponse() { + // src/test/resources/fixtures/ai-mock-config.json maps mock-bucket/invoice.pdf. + given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "Textract.DetectDocumentText") + .header("Authorization", AUTH_HEADER) + .body("{\"Document\":{\"S3Object\":{\"Bucket\":\"mock-bucket\",\"Name\":\"invoice.pdf\"}}}") + .when() + .post("/") + .then() + .statusCode(200) + .body("Blocks", hasSize(1)) + .body("Blocks[0].Text", equalTo("Invoice Total: $42.00")); + } + @Test void detectDocumentText_blockShapesAreAwsCompatible() { given() .contentType(CONTENT_TYPE) diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index fe0fbb1e0e..efffba7e3e 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -19,6 +19,7 @@ floci: base-url: "http://localhost:4566" default-region: us-east-1 default-account-id: "000000000000" + ai-mock-config-file: ${AI_MOCK_CONFIG:src/test/resources/fixtures/ai-mock-config.json} storage: mode: memory persistent-path: ./target/test-data diff --git a/src/test/resources/fixtures/ai-mock-config.json b/src/test/resources/fixtures/ai-mock-config.json new file mode 100644 index 0000000000..f4ae76e4b9 --- /dev/null +++ b/src/test/resources/fixtures/ai-mock-config.json @@ -0,0 +1,42 @@ +{ + "comprehend": { + "I absolutely love this product!": { + "DetectSentiment": { + "Sentiment": "POSITIVE", + "SentimentScore": { + "Positive": 0.98, + "Negative": 0.01, + "Neutral": 0.01, + "Mixed": 0.0 + } + } + } + }, + "textract": { + "mock-bucket/invoice.pdf": { + "DetectDocumentText": { + "DocumentMetadata": { "Pages": 1 }, + "Blocks": [ + { + "BlockType": "LINE", + "Id": "mock-line-1", + "Confidence": 99.5, + "Text": "Invoice Total: $42.00" + } + ], + "DetectDocumentTextModelVersion": "1.0" + } + } + }, + "rekognition": { + "mock-bucket/cat.jpg": { + "DetectLabels": { + "Labels": [ + { "Name": "Cat", "Confidence": 97.2 }, + { "Name": "Animal", "Confidence": 98.1 } + ], + "LabelModelVersion": "1.0" + } + } + } +}