Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(appsync): execute APPSYNC_JS resolvers via a Node sidecar (#3422)

Anders Wasen27633bf94d94
diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh
index 9e08201970..83ab3fd364 100755
--- a/.github/ci/prefetch-images.sh
+++ b/.github/ci/prefetch-images.sh
@@ -28,6 +28,11 @@ grep -q '/verifiedpermissions/' "$SHARD_FILE" && [ -n "$CEDAR_IMAGE" ] && pull "
# services/cloudformation/, so it needs its own token alongside the /appsync/ path match.
GRAPHQL_IMAGE="$(grep -oE 'graphql-image: *"[^"]+"' src/main/resources/application.yml | grep -oE '"[^"]+"' | tr -d '"')"
grep -qE '/appsync/|AppSyncCfnIntegrationTest' "$SHARD_FILE" && [ -n "$GRAPHQL_IMAGE" ] && pull "$GRAPHQL_IMAGE"
+# The Node sidecar that evaluates APPSYNC_JS resolver code; the pin lives in application.yml too.
+# Matched on the one class that starts it rather than on /appsync/, since every other test in that
+# package is a unit test: a path match would have all four shards pull an image one of them uses.
+JS_RUNTIME_IMAGE="$(grep -oE 'image: *"node:[^"]+"' src/main/resources/application.yml | grep -oE '"[^"]+"' | tr -d '"')"
+grep -q 'AppSyncJsResolverDockerIntegrationTest' "$SHARD_FILE" && [ -n "$JS_RUNTIME_IMAGE" ] && pull "$JS_RUNTIME_IMAGE"
# RdsAwsIntegrationTest is the one class that starts SQL Server (about 1.5 GB); the pin lives in
# application.yml. The other services/rds classes mock the container layer.
SQLSERVER_IMAGE="$(grep -oE 'default-sql-server-image: *"[^"]+"' src/main/resources/application.yml | grep -oE '"[^"]+"' | tr -d '"')"
diff --git a/docs/services/appsync.md b/docs/services/appsync.md
index 8c38c1fc7d..b2c1c99650 100644
--- a/docs/services/appsync.md
+++ b/docs/services/appsync.md
@@ -230,7 +230,7 @@ Responses are `application/json` with AWS AppSync wire shapes (`data` / `errors[
| Case | HTTP | Notes |
|---|---|---|
-| Query / introspection / validation / syntax (incl. blank `query`) | 200 | Nullable fields may be `null` until DataFetchers (Phase 8) |
+| Query / introspection / validation / syntax (incl. blank `query`) | 200 | Fields with an `APPSYNC_JS` resolver are resolved (see [Resolver execution](#resolver-execution)). A field with no resolver is `null`; one with a VTL mapping template fails with an error saying so, rather than resolving to `null` |
| HTTP subscription operation | 200 | `OperationNotSupported` (realtime WebSocket is a later phase) |
| Empty body / `{}` / `[]` / unparseable JSON / bad Content-Type | 400 | `MalformedHttpRequestException` |
| Missing `operationName` with multiple operations | 400 | `BadRequestException` — `Missing operation name.` |
@@ -270,6 +270,133 @@ SDL field auth: unmarked fields require the API **default** mode. Additional mod
Duplicate `API_KEY` / `AWS_IAM` / `AWS_LAMBDA` (and the same Cognito pool or OIDC issuer) between default and additional providers is rejected on create/update with management 400 `BadRequestException`: `Authentication type {TYPE} for additional authentication provider {N} already specified on the API. It can only be specified once.` (`N` is 1-based in `additionalAuthenticationProviders`).
+## Resolver execution
+
+A field with an `APPSYNC_JS` resolver is executed, not stubbed: the resolver's own code runs, its
+data source is called, and the field gets the value the code returned.
+
+`VTL` mapping templates are **not** executed. A resolver declaring the VTL runtime fails its field
+with a message saying so, rather than resolving to `null`: a null that means "not implemented" is
+indistinguishable from a null that means "no rows".
+
+### How a resolver gets called
+
+The GraphQL engine runs in the `floci-sidecar-graphql` container, so the sidecar walks the query and
+Floci owns the resolvers. `POST /v1/execute` carries a `resolve` block naming every coordinate the
+query touches that has a resolver, plus a callback URL and a token minted for that one operation.
+The sidecar then batches each execution level into a single `POST /_floci/appsync/resolve`, Floci runs each
+field's resolver and answers with a value or an error, and a value becomes the `source` of that
+field's own children. The contract is [`graphql/API.md`](https://github.com/floci-io/floci-sidecars/blob/main/graphql/API.md)
+in floci-io/floci-sidecars.
+
+Field authorization is applied before any of this: a denied coordinate is never listed in `resolve`,
+so it cannot reach a resolver. The token stops working the moment the operation returns.
+
+One AppSync behaviour does not fit the callback response, which carries a value or an error per
+field and never both: `util.appendError` means "report this **and** keep the data". Those errors
+come back to Floci on the operation's session instead and are merged into the response envelope, so
+a resolver that appends errors still returns its data alongside them.
+
+### How the code runs
+
+Resolver JavaScript runs in a **Node sidecar container**, started lazily on the first JS resolver
+and reused for every evaluation after it. Floci's published image is a Mandrel native executable,
+which carries no Truffle languages, so there is no in-process JavaScript to embed; running real Node
+also means a bundle executes as written, ES modules and all.
+
+Node is the engine, but **the APPSYNC_JS subset is enforced before evaluation**. AWS runs resolvers
+on a restricted runtime, not Node, so code using Node-only capabilities would run locally and be
+rejected on deploy. Accepting it here would mean local runs green-light resolvers that cannot ship,
+which is the one failure an emulator must not have.
+
+`@aws-appsync/utils` and `@aws-appsync/utils/rds` resolve to a shim the sidecar writes at boot, not
+the published package, so a resolver call never depends on npm being reachable. Covered:
+`util.error` / `appendError` / `unauthorized`, `util.autoId`, `util.time.*`, `util.dynamodb.*`,
+`util.parseJson` / `toJson` and the type predicates, `runtime.earlyReturn`, `extensions.*` (accepted,
+no-ops), and from `/rds`: `toJsonObject`, `sql`, `select`, `insert`, `update`, `remove`,
+`createPgStatement` and `typeHint`. Anything outside that set throws by name rather than answering
+`undefined`, so a gap is visible instead of silent. `@aws-appsync/utils/dynamodb` covers `get`,
+`put` and `remove`; `update`, `scan`, `query`, `sync` and `operations` compile a condition or update
+expression and are not implemented, so they throw by name.
+
+### What is rejected
+
+| Construct | Why |
+|---|---|
+| `async` functions, `await`, promises | AWS's runtime has no async support at all |
+| `import` of anything but `@aws-appsync/utils[/rds\|/dynamodb]` | resolvers have no filesystem or network access |
+| `class`, `while`, `do...while`, generators, `yield` | not available in APPSYNC_JS |
+| `try` / `catch` / `finally`, `throw` | not available; use `util.error` |
+| `this`, `with`, `eval`, `debugger`, `require` | not available |
+
+An `async` handler is caught before it runs, a handler returning a promise is caught after, and
+imports are blocked by a module resolve hook, so a dynamic `import()` cannot slip past the source
+scan. The scan blanks comments, strings and template text first, so the same keywords inside them
+are not flagged. Recursion is also unavailable on AWS and is not detected, since that cannot be
+determined lexically.
+
+A rejected resolver fails its field with `errorType: UnsupportedFeature` and the line number, rather
+than running.
+
+| Setting | Env | Default |
+|---|---|---|
+| `floci.services.appsync.js-runtime.enabled` | `FLOCI_SERVICES_APPSYNC_JS_RUNTIME_ENABLED` | `true` |
+| `floci.services.appsync.js-runtime.enforce-appsync-subset` | … `_ENFORCE_APPSYNC_SUBSET` | `true` |
+| `floci.services.appsync.js-runtime.url` | `FLOCI_SERVICES_APPSYNC_JS_RUNTIME_URL` | unset |
+| `floci.services.appsync.js-runtime.image` | `FLOCI_SERVICES_APPSYNC_JS_RUNTIME_IMAGE` | `node:22-alpine` |
+| `floci.services.appsync.js-runtime.container-name` | `FLOCI_SERVICES_APPSYNC_JS_RUNTIME_CONTAINER_NAME` | `appsync-js-runtime` |
+| `floci.services.appsync.js-runtime.port` | `FLOCI_SERVICES_APPSYNC_JS_RUNTIME_PORT` | `0` (Docker picks) |
+| `floci.services.appsync.js-runtime.start-timeout-seconds` | … `_START_TIMEOUT_SECONDS` | `60` |
+| `floci.services.appsync.js-runtime.evaluation-timeout-seconds` | … `_EVALUATION_TIMEOUT_SECONDS` | `30` |
+| `floci.services.appsync.js-runtime.keep-running-on-shutdown` | … `_KEEP_RUNNING_ON_SHUTDOWN` | `false` |
+
+Set `url` to point at a Node server someone is already running, in which case Floci skips container
+management entirely and never starts, adopts or stops anything. That is the same contract as
+`floci.services.duck.url`, and it is the way to work on the sidecar itself or to run somewhere with
+no Docker socket to reach.
+
+Otherwise resolver execution needs Docker. Without it, a JS resolver fails its field with a message
+naming the sidecar; the management API is unaffected. The container is stopped through
+`ContainerTeardown` along with the other process-bound containers.
+
+### Pipelines
+
+A UNIT resolver is `request()` → data source → `response()`. A PIPELINE resolver runs its own
+`request()` as the before step, then each function in `pipelineConfig.functions` in order as its own
+request / data source / response, then its `response()` as the after step.
+
+- `ctx.stash` is threaded through every stage, so the before step can hand work to the functions.
+- Each stage sees the previous one's return value as `ctx.prev.result`.
+- A function that exports no `response()` passes its data source result straight through.
+- `runtime.earlyReturn(value)` makes `value` the field's result immediately, skipping every
+ remaining stage including the after step.
+- `util.error(...)` fails the field, carrying the resolver's own `errorType`, `errorInfo` and `data`
+ onto the GraphQL error.
+- `util.appendError(...)` stops nothing: the errors are returned **beside** the data.
+- A **data source failure** does not fail the field by itself. The stage's `response()` handler is
+ called with `ctx.error` set to `{message, type}` and no `ctx.result`, and it decides: re-raise
+ with `util.error` / collect with `util.appendError`, or return a value and **suppress** the error.
+ Suppression is AWS behaviour, and it is why resolvers carry an explicit `if (ctx.error)` branch:
+ without one a failed query silently returns whatever the handler returned. A stage that exports
+ no `response()` has nothing to make that decision, so there the error fails the field.
+
+`ctx` carries `arguments` / `args`, `source`, `stash`, `prev`, `identity`, `request.authType`,
+`info` (`fieldName`, `parentTypeName`, `variables`, `selectionSetList`) and `env` (the API's
+environment variables). `ctx.request.headers` is empty: the GraphQL context does not carry them.
+
+### Data sources
+
+| Type | Behaviour |
+|---|---|
+| `NONE` | The request is the result; a `payload` member is unwrapped, as on AWS. |
+| `AWS_LAMBDA` | `Invoke` and `BatchInvoke`. Only `payload` reaches the function. A function error fails the field rather than resolving to the error object. |
+| `RELATIONAL_DATABASE` | Statements run over the RDS Data API against `rdsHttpEndpointConfig`. Accepts `{statements, variableMap}`, the `{statement, parameters}` the `/rds` helpers build, a list of either, or a bare SQL string. `variableTypeHintMap` is honoured, without it a bound date binds as text and PostgreSQL refuses the comparison (`operator does not exist: timestamp with time zone >= character varying`), so a resolver's date filters need it. The result is wrapped as `{sqlStatementResults: […]}`, which is what `toJsonObject()` reads. |
+| `AMAZON_DYNAMODB` | `GetItem`, `PutItem`, `UpdateItem`, `DeleteItem`, `Query`, `Scan`, through the native DynamoDB path so expressions, conditions and indexes all apply. Items come back as **plain JSON**, not attribute values, as AppSync returns them. `nextToken` is an opaque encoding of `LastEvaluatedKey`. `BatchGetItem`, `TransactWriteItems` and `Sync` are not implemented and say so. |
+| `HTTP`, `AMAZON_EVENTBRIDGE`, `AMAZON_OPENSEARCH_SERVICE`, `AMAZON_BEDROCK_RUNTIME` | Not implemented; a resolver using one fails its field naming the type. |
+
+A field with no resolver falls back to reading its value off the parent object, which is how the
+fields of an object a resolver returned are populated.
+
## Pagination
All `List` operations support cursor-based pagination via query parameters:
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 d2c43a87d9..ad3f3e438c 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -2156,6 +2156,79 @@ public interface EmulatorConfig {
@WithDefault("floci/floci-sidecar-graphql:0.2.0")
String graphqlImage();
+
+ JsRuntimeConfig jsRuntime();
+ }
+
+ /**
+ * The Node sidecar that evaluates {@code APPSYNC_JS} resolver code.
+ *
+ * <p>A sidecar rather than an embedded engine because Floci's published image is a Mandrel
+ * native executable, and Mandrel carries no Truffle languages: there is no in-process
+ * JavaScript to embed. Running real Node also means a resolver bundle executes as written,
+ * ES modules included, instead of through a rewrite that only approximates AppSync.
+ *
+ * <p>Started lazily, on the first resolver that needs it, so an API with no JS resolvers, or
+ * a Floci with no Docker, costs nothing.
+ */
+ interface JsRuntimeConfig {
+ /**
+ * Env: {@code FLOCI_SERVICES_APPSYNC_JS_RUNTIME_ENABLED}. Turned off, a JS resolver fails
+ * with an explanatory error instead of silently resolving to null.
+ */
+ @WithDefault("true")
+ boolean enabled();
+
+ /**
+ * When set, Floci evaluates resolver code against this already-running server and skips
+ * container management entirely. Same contract as {@code floci.services.duck.url}: useful
+ * for running the sidecar by hand while working on it, and for an environment with no
+ * Docker socket to reach.
+ * Env: {@code FLOCI_SERVICES_APPSYNC_JS_RUNTIME_URL}
+ */
+ Optional<String> url();
+
+ /** Env: {@code FLOCI_SERVICES_APPSYNC_JS_RUNTIME_IMAGE} */
+ @WithDefault("node:22-alpine")
+ String image();
+
+ /** Env: {@code FLOCI_SERVICES_APPSYNC_JS_RUNTIME_CONTAINER_NAME} */
+ @WithDefault("appsync-js-runtime")
+ String containerName();
+
+ /** Host port to publish, or 0 to let Docker choose one. */
+ @WithDefault("0")
+ int port();
+
+ /** Seconds to wait for the sidecar to answer its health probe. */
+ @WithDefault("60")
+ int startTimeoutSeconds();
+
+ /** Seconds a single resolver evaluation may take. */
+ @WithDefault("30")
+ int evaluationTimeoutSeconds();
+
+ /**
+ * Rejects resolver code that uses JavaScript the APPSYNC_JS runtime does not have, before
+ * evaluating it. Env: {@code FLOCI_SERVICES_APPSYNC_JS_RUNTIME_ENFORCE_APPSYNC_SUBSET}
+ *
+ * <p>On by default, because the sidecar is real Node and would otherwise accept async
+ * functions, promises, classes, try/catch, while loops and Node builtin imports, none of
+ * which AWS accepts. Running code locally that cannot deploy is the one failure an emulator
+ * must not have. Turn it off only if Floci rejects something AWS accepts, and please report
+ * it.
+ */
+ @WithDefault("true")
+ boolean enforceAppsyncSubset();
+
+ /**
+ * Keeps the sidecar running when Floci stops, so the next start reuses it and skips the
+ * Node boot. Off by default: a stopped Floci leaving containers behind is surprising.
+ */
+ @WithDefault("false")
+ boolean keepRunningOnShutdown();
+
+ Optional<String> dockerNetwork();
}
interface OamServiceConfig {
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClient.java b/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClient.java
index a51333c8a1..72c2cb9d85 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClient.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClient.java
@@ -102,6 +102,18 @@ public class GraphqlSidecarClient {
public record DenyField(String typeName, String fieldName, String errorType, String message) {
}
+ /** One coordinate the sidecar should answer by calling back rather than by its own fetcher. */
+ public record ResolveField(String typeName, String fieldName) {
+ }
+
+ /**
+ * Wires the sidecar's resolver callback: {@code fields} are answered by {@code POST url} with
+ * {@code Authorization: Bearer token}, batched per execution level into chunks of at most
+ * {@code maxBatch}. A coordinate that is also in {@code denyFields} never reaches the callback.
+ */
+ public record ResolveSpec(String url, String token, List<ResolveField> fields, int maxBatch) {
+ }
+
/**
* {@code operationType} is {@code QUERY}/{@code MUTATION}/{@code SUBSCRIPTION}, or {@code
* null} when the query didn't parse or named an operation that doesn't exist, in which case
@@ -154,6 +166,13 @@ public class GraphqlSidecarClient {
public Map<String, Object> execute(String sdl, Map<String, String> scalars, String query,
Map<String, Object> variables, String operationName,
List<DenyField> denyFields) {
+ return execute(sdl, scalars, query, variables, operationName, denyFields, null);
+ }
+
+ /** As above, with {@code resolve} wiring the sidecar's callback for the fields that have resolvers. */
+ public Map<String, Object> execute(String sdl, Map<String, String> scalars, String query,
+ Map<String, Object> variables, String operationName,
+ List<DenyField> denyFields, ResolveSpec resolve) {
ObjectNode body = mapper.createObjectNode();
body.put("sdl", sdl);
body.set("scalars", mapper.valueToTree(scalars));
@@ -172,6 +191,18 @@ public class GraphqlSidecarClient {
node.put("message", deny.message());
}
}
+ if (resolve != null && !resolve.fields().isEmpty()) {
+ ObjectNode resolveNode = body.putObject("resolve");
+ resolveNode.put("url", resolve.url());
+ resolveNode.put("token", resolve.token());
+ resolveNode.put("maxBatch", resolve.maxBatch());
+ ArrayNode fields = resolveNode.putArray("fields");
+ for (ResolveField field : resolve.fields()) {
+ ObjectNode node = fields.addObject();
+ node.put("typeName", field.typeName());
+ node.put("fieldName", field.fieldName());
+ }
+ }
JsonNode response = requireSuccess(call("/v1/execute", body, "query execution"), "query execution");
return mapper.convertValue(response, Map.class);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarManager.java b/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarManager.java
index 07445c863d..56ee1ef03d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarManager.java
@@ -133,6 +133,9 @@ public class GraphqlSidecarManager {
.withDynamicPort(GRAPHQL_PORT)
.withDockerNetwork(config.services().dockerNetwork())
.withEmbeddedDns()
+ // The sidecar calls Floci back for every field that has a resolver, so it needs a
+ // route to the host even when the embedded DNS server is not the one answering.
+ .withHostDockerInternalOnLinux()
.withLogRotation()
.build();
ContainerInfo info = lifecycleManager.createAndStart(spec);
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatter.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatter.java
index 9bd59fda96..3445fd5cc9 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatter.java
@@ -69,14 +69,23 @@ public class AppSyncErrorFormatter {
if (path != null) {
map.put("path", path);
}
- String classification = null;
- Object extensions = error.get("extensions");
- if (extensions instanceof Map<?, ?> extensionsMap) {
- Object raw = extensionsMap.get("classification");
- classification = raw == null ? null : String.valueOf(raw);
+ // A resolver that called util.error chose its own errorType, errorInfo and data, and AppSync
+ // reports all three on the error itself. The sidecar's resolver callback copies them onto
+ // the error's extensions as type/data/info; anything else keeps the classification-derived
+ // type and the null errorInfo that a server-side failure has.
+ Map<?, ?> extensions = error.get("extensions") instanceof Map<?, ?> map1 ? map1 : null;
+ Object suppliedType = extensions == null ? null : extensions.get("type");
+ if (suppliedType instanceof String type && !type.isBlank()) {
+ map.put("errorType", type);
+ } else {
+ Object raw = extensions == null ? null : extensions.get("classification");
+ map.put("errorType", toAppSyncErrorType(raw == null ? null : String.valueOf(raw)));
+ }
+ map.put("errorInfo", extensions == null ? null : extensions.get("info"));
+ Object suppliedData = extensions == null ? null : extensions.get("data");
+ if (suppliedData != null) {
+ map.put("data", suppliedData);
}
- map.put("errorType", toAppSyncErrorType(classification));
- map.put("errorInfo", null);
return map;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java
index 27832c2266..09c3b7d965 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java
@@ -5,14 +5,21 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestContext;
+import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.DenyField;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlanResult;
+import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlannedField;
+import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.ResolveField;
+import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.ResolveSpec;
import io.github.hectorvent.floci.services.appsync.graphql.auth.AppSyncAuthContext;
import io.github.hectorvent.floci.services.appsync.graphql.auth.AuthMiddleware;
import io.github.hectorvent.floci.services.appsync.graphql.auth.AuthRequestInfo;
import io.github.hectorvent.floci.services.appsync.graphql.auth.SidecarFieldAuthorizationPlanner;
+import io.github.hectorvent.floci.services.appsync.graphql.resolver.AppSyncResolverError;
+import io.github.hectorvent.floci.services.appsync.graphql.resolver.AppSyncResolverExecutor;
+import io.github.hectorvent.floci.services.appsync.graphql.resolver.ResolverCallbackSessions;
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
import jakarta.inject.Inject;
import jakarta.ws.rs.POST;
@@ -27,10 +34,13 @@ import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.UUID;
/**
@@ -43,6 +53,8 @@ public class AppSyncExecutionController {
private static final Logger LOG = Logger.getLogger(AppSyncExecutionController.class);
private static final String HEADER_ERROR_TYPE = "x-amzn-errortype";
+ /** Matches the sidecar's own default; one execution level rarely has more fields than this. */
+ private static final int RESOLVE_MAX_BATCH = 100;
private final AppSyncService appSyncService;
private final SchemaRegistry schemaRegistry;
@@ -53,6 +65,9 @@ public class AppSyncExecutionController {
private final ObjectMapper objectMapper;
private final AuthMiddleware authMiddleware;
private final RequestContext requestContext;
+ private final AppSyncResolverExecutor resolverExecutor;
+ private final ResolverCallbackSessions callbackSessions;
+ private final ContainerReachableEndpoint reachableEndpoint;
@Inject
public AppSyncExecutionController(AppSyncService appSyncService,
@@ -63,7 +78,10 @@ public class AppSyncExecutionController {
AppSyncErrorFormatter errorFormatter,
ObjectMapper objectMapper,
AuthMiddleware authMiddleware,
- RequestContext requestContext) {
+ RequestContext requestContext,
+ AppSyncResolverExecutor resolverExecutor,
+ ResolverCallbackSessions callbackSessions,
+ ContainerReachableEndpoint reachableEndpoint) {
this.appSyncService = appSyncService;
this.schemaRegistry = schemaRegistry;
this.schemaCompiler = schemaCompiler;
@@ -73,6 +91,9 @@ public class AppSyncExecutionController {
this.objectMapper = objectMapper;
this.authMiddleware = authMiddleware;
this.requestContext = requestContext;
+ this.resolverExecutor = resolverExecutor;
+ this.callbackSessions = callbackSessions;
+ this.reachableEndpoint = reachableEndpoint;
}
@POST
@@ -130,8 +151,8 @@ public class AppSyncExecutionController {
return Response.ok(errorFormatter.format(operationNotSupported())).type(MediaType.APPLICATION_JSON).build();
}
List<DenyField> denyFields = fieldAuthorizationPlanner.planDenyFields(plan, authContext);
- Map<String, Object> rawResult = sidecarClient.execute(
- preparedSdl, scalars, parsed.query(), parsed.variables(), parsed.operationName(), denyFields);
+ Map<String, Object> rawResult = executeQuery(apiId, preparedSdl, scalars, parsed,
+ denyFields, plan, authContext);
return Response.ok(errorFormatter.format(rawResult)).type(MediaType.APPLICATION_JSON).build();
} catch (AppSyncTransportException e) {
return graphqlError(e.getHttpStatus(), e.getErrorType(), e.getMessage());
@@ -142,6 +163,101 @@ public class AppSyncExecutionController {
}
}
+ /**
+ * Runs the query on the sidecar, wiring the resolver callback when any field the query touches
+ * actually has a resolver. Without one, the sidecar resolves every field over a null root value
+ * exactly as before, so an API with no resolvers costs no session and no callback.
+ */
+ private Map<String, Object> executeQuery(String apiId, String preparedSdl, Map<String, String> scalars,
+ ParsedRequest parsed, List<DenyField> denyFields,
+ PlanResult plan, AppSyncAuthContext authContext) {
+ List<ResolveField> resolveFields = resolverBackedFields(apiId, plan, denyFields);
+ if (resolveFields.isEmpty()) {
+ return sidecarClient.execute(preparedSdl, scalars, parsed.query(), parsed.variables(),
+ parsed.operationName(), denyFields);
+ }
+ try (ResolverCallbackSessions.Session session =
+ callbackSessions.open(apiId, authContext.identity(), authContext.authType())) {
+ ResolveSpec resolve = new ResolveSpec(reachableEndpoint.baseUrl() + "/_floci/appsync/resolve",
+ session.token(), resolveFields, RESOLVE_MAX_BATCH);
+ Map<String, Object> result = sidecarClient.execute(preparedSdl, scalars, parsed.query(),
+ parsed.variables(), parsed.operationName(), denyFields, resolve);
+ return withAppendedErrors(result, session.appendedErrors());
+ }
+ }
+
+ /**
+ * The coordinates the sidecar should call back for: every planned field that has a resolver and
+ * is not already denied, since {@code denyFields} wins and a denied field must never reach one.
+ */
+ private List<ResolveField> resolverBackedFields(String apiId, PlanResult plan, List<DenyField> denyFields) {
+ Set<String> denied = new HashSet<>();
+ for (DenyField deny : denyFields) {
+ denied.add(deny.typeName() + "." + deny.fieldName());
+ }
+ Map<String, ResolveField> wired = new LinkedHashMap<>();
+ for (PlannedField field : plan.fields()) {
+ String key = field.typeName() + "." + field.fieldName();
+ if (denied.contains(key) || wired.containsKey(key)) {
+ continue;
+ }
+ if (hasResolver(apiId, field)) {
+ wired.put(key, new ResolveField(field.typeName(), field.fieldName()));
+ }
+ }
+ return List.copyOf(wired.values());
+ }
+
+ private boolean hasResolver(String apiId, PlannedField field) {
+ try {
+ return resolverExecutor.findResolver(apiId, field.typeName(), field.fieldName()) != null;
+ } catch (AwsException e) {
+ // A control-plane failure here (a schema mid-recreation answers 409) must not take down
+ // the whole operation: wire the field anyway and let the callback report it on that
+ // field alone, which is where a resolver failure belongs.
+ LOG.debugv("Could not tell whether {0}.{1} has a resolver: {2}",
+ field.typeName(), field.fieldName(), e.getMessage());
+ return true;
+ }
+ }
+
+ /**
+ * {@code util.appendError} reports errors <em>and</em> keeps the data, which the sidecar's
+ * per-field callback response cannot say (it carries a value or an error, never both). They
+ * come back on the session instead and join the envelope here.
+ */
+ private static Map<String, Object> withAppendedErrors(Map<String, Object> result,
+ List<AppSyncResolverError> appended) {
+ if (appended.isEmpty()) {
+ return result;
+ }
+ Map<String, Object> merged = new LinkedHashMap<>(result);
+ List<Object> errors = new ArrayList<>();
+ if (merged.get("errors") instanceof List<?> existing) {
+ errors.addAll(existing);
+ }
+ for (AppSyncResolverError error : appended) {
+ errors.add(envelopeError(error));
+ }
+ merged.put("errors", errors);
+ return merged;
+ }
+
+ /** The sidecar's own error shape, so {@link AppSyncErrorFormatter} reads both kinds the same way. */
+ private static Map<String, Object> envelopeError(AppSyncResolverError error) {
+ Map<String, Object> extensions = new LinkedHashMap<>();
+ extensions.put("type", error.errorType());
+ extensions.put("data", error.data());
+ extensions.put("info", error.errorInfo());
+ Map<String, Object> entry = new LinkedHashMap<>();
+ entry.put("message", error.message());
+ if (error.path() != null && !error.path().isEmpty()) {
+ entry.put("path", error.path());
+ }
+ entry.put("extensions", extensions);
+ return entry;
+ }
+
private boolean isAcceptedContentType(HttpHeaders headers) {
String contentType = headers.getHeaderString(HttpHeaders.CONTENT_TYPE);
if (contentType == null || contentType.isBlank()) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvoker.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvoker.java
new file mode 100644
index 0000000000..b6b478b333
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvoker.java
@@ -0,0 +1,29 @@
+package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+
+/**
+ * Carries out the request a resolver's {@code request()} handler returned, against one kind of data
+ * source, and hands back what the {@code response()} handler will see as {@code ctx.result}.
+ *
+ * <p>One implementation per {@link DataSourceType}, discovered by CDI through
+ * {@link AppSyncDataSourceInvokers}, the same shape as the CloudFormation provisioner registry, so
+ * a new data source type is a new class rather than another arm of a switch.
+ *
+ * <p>Both ends speak plain JSON-compatible data. That is not incidental: AppSync's JS resolvers
+ * build their request as a plain object and read the result as one, so a DynamoDB invoker has to
+ * unmarshal attribute values rather than pass them through.
+ */
+public interface AppSyncDataSourceInvoker {
+
+ DataSourceType type();
+
+ /**
+ * @param dataSource the resolved data source, for its config (table name, cluster, function)
+ * @param request whatever the {@code request()} handler returned
+ * @param region the region the API lives in
+ * @return the value to expose as {@code ctx.result}
+ */
+ Object invoke(DataSource dataSource, Object request, String region);
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokers.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokers.java
new file mode 100644
index 0000000000..aa4026c4b5
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokers.java
@@ -0,0 +1,57 @@
+package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Instance;
+import jakarta.inject.Inject;
+
+import java.util.EnumMap;
+import java.util.Map;
+
+/** Maps a data source type to the invoker that serves it. */
+@ApplicationScoped
+public class AppSyncDataSourceInvokers {
+
+ private final Map<DataSourceType, AppSyncDataSourceInvoker> byType = new EnumMap<>(DataSourceType.class);
+
+ @Inject
+ public AppSyncDataSourceInvokers(Instance<AppSyncDataSourceInvoker> invokers) {
+ invokers.forEach(invoker -> {
+ AppSyncDataSourceInvoker existing = byType.put(invoker.type(), invoker);
+ if (existing != null) {
+ throw new IllegalStateException("Two AppSync data source invokers for " + invoker.type()
+ + ": " + existing.getClass().getSimpleName() + " and "
+ + invoker.getClass().getSimpleName());
+ }
+ });
+ }
+
+ /** Test constructor: an explicit set, bypassing CDI. */
+ public AppSyncDataSourceInvokers(Iterable<AppSyncDataSourceInvoker> invokers) {
+ invokers.forEach(invoker -> byType.put(invoker.type(), invoker));
+ }
+
+ /**
+ * Runs the request against its data source.
+ *
+ * <p>A resolver whose data source type Floci cannot drive fails the field with that fact.
+ * Returning null instead would be indistinguishable from an empty result, which is the failure
+ * mode this whole layer exists to remove.
+ */
+ public Object invoke(DataSource dataSource, Object request, String region) {
+ DataSourceType type = dataSource.getType();
+ AppSyncDataSourceInvoker invoker = byType.get(type);
+ if (invoker == null) {
+ throw new AwsException("InternalFailureException",
+ "Floci cannot invoke AppSync data sources of type " + type
+ + " (data source " + dataSource.getName() + ")", 500);
+ }
+ return invoker.invoke(dataSource, request, region);
+ }
+
+ public boolean supports(DataSourceType type) {
+ return byType.containsKey(type);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/DynamoDbDataSourceInvoker.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/DynamoDbDataSourceInvoker.java
new file mode 100644
index 0000000000..870ea39ed3
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/DynamoDbDataSourceInvoker.java
@@ -0,0 +1,359 @@
+package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+
+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.AwsException;
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Response;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The {@code AMAZON_DYNAMODB} data source.
+ *
+ * <p>Translates AppSync's request objects, {@code {operation: "GetItem", key: …}} and friends,
+ * into the native DynamoDB API and back, going through {@link DynamoDbJsonHandler} so the whole of
+ * Floci's DynamoDB behaviour applies: expressions, conditions, indexes, pagination.
+ *
+ * <p>The translation that matters is on the way out. A resolver's request carries DynamoDB
+ * attribute values, because {@code util.dynamodb.toMapValues} put them there, but the result AppSync
+ * hands back is <em>plain JSON</em>, {@code {"id": "7"}}, never {@code {"id": {"S": "7"}}}. A
+ * resolver returning the raw response would give every field the wrong shape, so items are
+ * unmarshalled here.
+ *
+ * <p>{@code nextToken} is likewise AppSync's own: an opaque string, made here by base64-encoding
+ * the {@code LastEvaluatedKey} and decoded again on the way in.
+ */
+@ApplicationScoped
+public class DynamoDbDataSourceInvoker implements AppSyncDataSourceInvoker {
+
+ private final DynamoDbJsonHandler dynamoDbJsonHandler;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public DynamoDbDataSourceInvoker(DynamoDbJsonHandler dynamoDbJsonHandler, ObjectMapper objectMapper) {
+ this.dynamoDbJsonHandler = dynamoDbJsonHandler;
+ this.objectMapper = objectMapper;
+ }
+
+ @Override
+ public DataSourceType type() {
+ return DataSourceType.AMAZON_DYNAMODB;
+ }
+
+ @Override
+ public Object invoke(DataSource dataSource, Object request, String region) {
+ JsonNode appSyncRequest = objectMapper.valueToTree(request == null ? Map.of() : request);
+ String tableName = tableName(dataSource, appSyncRequest);
+ String operation = appSyncRequest.path("operation").asText("");
+ return switch (operation) {
+ case "GetItem" -> getItem(tableName, appSyncRequest, region);
+ case "PutItem" -> putItem(tableName, appSyncRequest, region);
+ case "UpdateItem" -> updateItem(tableName, appSyncRequest, region);
+ case "DeleteItem" -> deleteItem(tableName, appSyncRequest, region);
+ case "Query" -> queryOrScan("Query", tableName, appSyncRequest, region);
+ case "Scan" -> queryOrScan("Scan", tableName, appSyncRequest, region);
+ case "" -> throw new AwsException("InternalFailureException",
+ "The resolver's DynamoDB request has no \"operation\"", 500);
+ default -> throw new AwsException("InternalFailureException",
+ "Floci's AppSync DynamoDB data source does not implement the " + operation
+ + " operation yet", 500);
+ };
+ }
+
+ // ── Operations ───────────────────────────────────────────────────────────
+
+ private Object getItem(String tableName, JsonNode request, String region) {
+ ObjectNode native0 = base(tableName);
+ native0.set("Key", request.path("key"));
+ if (request.path("consistentRead").asBoolean(false)) {
+ native0.put("ConsistentRead", true);
+ }
+ applyProjection(native0, request.path("projection"));
+ JsonNode response = call("GetItem", native0, region);
+ // A miss is a null field, not an error: AppSync resolves the field to null.
+ return unmarshalItem(response.get("Item"));
+ }
+
+ private Object putItem(String tableName, JsonNode request, String region) {
+ ObjectNode item = objectMapper.createObjectNode();
+ item.setAll((ObjectNode) objectMapper.valueToTree(fields(request.path("attributeValues"))));
+ item.setAll((ObjectNode) objectMapper.valueToTree(fields(request.path("key"))));
+ ObjectNode native0 = base(tableName);
+ native0.set("Item", item);
+ applyCondition(native0, request.path("condition"));
+ call("PutItem", native0, region);
+ // AppSync answers with the item as written, which is the merged key and attributes.
+ return unmarshalItem(item);
+ }
+
+ private Object updateItem(String tableName, JsonNode request, String region) {
+ JsonNode update = request.path("update");
+ if (!update.hasNonNull("expression")) {
+ throw new AwsException("InternalFailureException",
+ "An UpdateItem request needs update.expression", 500);
+ }
+ ObjectNode native0 = base(tableName);
+ native0.set("Key", request.path("key"));
+ native0.put("UpdateExpression", update.path("expression").asText());
+ applyExpressionMaps(native0, update);
+ applyCondition(native0, request.path("condition"));
+ native0.put("ReturnValues", "ALL_NEW");
+ JsonNode response = call("UpdateItem", native0, region);
+ return unmarshalItem(response.get("Attributes"));
+ }
+
+ private Object deleteItem(String tableName, JsonNode request, String region) {
+ ObjectNode native0 = base(tableName);
+ native0.set("Key", request.path("key"));
+ applyCondition(native0, request.path("condition"));
+ native0.put("ReturnValues", "ALL_OLD");
+ JsonNode response = call("DeleteItem", native0, region);
+ // The deleted item, as AppSync reports it, so a mutation can return what it removed.
+ return unmarshalItem(response.get("Attributes"));
+ }
+
+ private Object queryOrScan(String action, String tableName, JsonNode request, String region) {
+ ObjectNode native0 = base(tableName);
+ if ("Query".equals(action)) {
+ JsonNode query = request.path("query");
+ if (!query.hasNonNull("expression")) {
+ throw new AwsException("InternalFailureException",
+ "A Query request needs query.expression", 500);
+ }
+ native0.put("KeyConditionExpression", query.path("expression").asText());
+ applyExpressionMaps(native0, query);
+ }
+ applyFilter(native0, request.path("filter"));
+ if (request.hasNonNull("index")) {
+ native0.put("IndexName", request.path("index").asText());
+ }
+ if (request.hasNonNull("limit")) {
+ native0.put("Limit", request.path("limit").asInt());
+ }
+ if (request.has("scanIndexForward")) {
+ native0.put("ScanIndexForward", request.path("scanIndexForward").asBoolean(true));
+ }
+ if (request.path("consistentRead").asBoolean(false)) {
+ native0.put("ConsistentRead", true);
+ }
+ if (request.hasNonNull("nextToken")) {
+ native0.set("ExclusiveStartKey", decodeNextToken(request.path("nextToken").asText()));
+ }
+ applyProjection(native0, request.path("projection"));
+
+ JsonNode response = call(action, native0, region);
+ List<Object> items = new ArrayList<>();
+ for (JsonNode item : response.path("Items")) {
+ items.add(unmarshalItem(item));
+ }
+ Map<String, Object> result = new LinkedHashMap<>();
+ result.put("items", items);
+ result.put("scannedCount", response.path("ScannedCount").asInt(items.size()));
+ result.put("nextToken", encodeNextToken(response.get("LastEvaluatedKey")));
+ return result;
+ }
+
+ // ── Request assembly ─────────────────────────────────────────────────────
+
+ private ObjectNode base(String tableName) {
+ ObjectNode request = objectMapper.createObjectNode();
+ request.put("TableName", tableName);
+ return request;
+ }
+
+ /**
+ * The table a resolver's request runs against. AppSync takes it from the data source's
+ * {@code dynamodbConfig}, and a request may not override it, so this is the one place the
+ * mapping between the two spellings of that config member matters.
+ */
+ private String tableName(DataSource dataSource, JsonNode request) {
+ Map<String, Object> config = dataSource.getDynamodbConfig();
+ Object tableName = config == null ? null : config.get("tableName");
+ if (tableName == null || String.valueOf(tableName).isBlank()) {
+ throw new AwsException("InternalFailureException",
+ "Data source " + dataSource.getName() + " has no dynamodbConfig.tableName", 500);
+ }
+ return String.valueOf(tableName);
+ }
+
+ private void applyProjection(ObjectNode target, JsonNode projection) {
+ if (projection == null || !projection.isObject()) {
+ return;
+ }
+ if (projection.hasNonNull("expression")) {
+ target.put("ProjectionExpression", projection.path("expression").asText());
+ }
+ applyExpressionMaps(target, projection);
+ }
+
+ private void applyFilter(ObjectNode target, JsonNode filter) {
+ if (filter == null || !filter.isObject() || !filter.hasNonNull("expression")) {
+ return;
+ }
+ target.put("FilterExpression", filter.path("expression").asText());
+ applyExpressionMaps(target, filter);
+ }
+
+ private void applyCondition(ObjectNode target, JsonNode condition) {
+ if (condition == null || !condition.isObject() || !condition.hasNonNull("expression")) {
+ return;
+ }
+ target.put("ConditionExpression", condition.path("expression").asText());
+ applyExpressionMaps(target, condition);
+ }
+
+ /**
+ * Merges {@code expressionNames} / {@code expressionValues} into the native request. Merged
+ * rather than set, because a Query can carry both a key condition and a filter and each brings
+ * its own placeholders into the one shared map.
+ */
+ private void applyExpressionMaps(ObjectNode target, JsonNode source) {
+ mergeInto(target, "ExpressionAttributeNames", source.path("expressionNames"));
+ mergeInto(target, "ExpressionAttributeValues", source.path("expressionValues"));
+ }
+
+ private void mergeInto(ObjectNode target, String field, JsonNode addition) {
+ if (addition == null || !addition.isObject() || addition.isEmpty()) {
+ return;
+ }
+ ObjectNode existing = target.has(field) ? (ObjectNode) target.get(field) : objectMapper.createObjectNode();
+ existing.setAll((ObjectNode) addition);
+ target.set(field, existing);
+ }
+
+ private Map<String, JsonNode> fields(JsonNode node) {
+ Map<String, JsonNode> fields = new LinkedHashMap<>();
+ if (node != null && node.isObject()) {
+ node.fields().forEachRemaining(entry -> fields.put(entry.getKey(), entry.getValue()));
+ }
+ return fields;
+ }
+
+ // ── Response translation ─────────────────────────────────────────────────
+
+ private JsonNode call(String action, ObjectNode request, String region) {
+ try {
+ Response response = dynamoDbJsonHandler.handle(action, request, region);
+ Object entity = response.getEntity();
+ if (entity == null) {
+ return objectMapper.createObjectNode();
+ }
+ if (entity instanceof String text) {
+ return text.isBlank() ? objectMapper.createObjectNode() : objectMapper.readTree(text);
+ }
+ return objectMapper.valueToTree(entity);
+ } catch (AwsException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new AwsException("InternalFailureException",
+ "The DynamoDB data source call failed: " + e.getMessage(), 500);
+ }
+ }
+
+ /** Attribute values to plain JSON, which is the only shape a GraphQL field can be built from. */
+ private Object unmarshalItem(JsonNode item) {
+ if (item == null || item.isNull() || !item.isObject()) {
+ return null;
+ }
+ Map<String, Object> plain = new LinkedHashMap<>();
+ item.fields().forEachRemaining(entry -> plain.put(entry.getKey(), unmarshal(entry.getValue())));
+ return plain;
+ }
+
+ private Object unmarshal(JsonNode value) {
+ if (value == null || value.isNull() || !value.isObject()) {
+ return null;
+ }
+ if (value.has("NULL")) {
+ return null;
+ }
+ if (value.has("S")) {
+ return value.get("S").asText();
+ }
+ if (value.has("N")) {
+ return number(value.get("N").asText());
+ }
+ if (value.has("BOOL")) {
+ return value.get("BOOL").asBoolean();
+ }
+ if (value.has("B")) {
+ return value.get("B").asText();
+ }
+ if (value.has("SS")) {
+ return toList(value.get("SS"));
+ }
+ if (value.has("NS")) {
+ List<Object> numbers = new ArrayList<>();
+ value.get("NS").forEach(element -> numbers.add(number(element.asText())));
+ return numbers;
+ }
+ if (value.has("BS")) {
+ return toList(value.get("BS"));
+ }
+ if (value.has("L")) {
+ List<Object> list = new ArrayList<>();
+ value.get("L").forEach(element -> list.add(unmarshal(element)));
+ return list;
+ }
+ if (value.has("M")) {
+ return unmarshalItem(value.get("M"));
+ }
+ return null;
+ }
+
+ /**
+ * A DynamoDB number as the nearest Java type: integral where it can be, so an id field is 7
+ * rather than 7.0 in the response and a GraphQL Int can be built from it.
+ *
+ * <p>Shared by the N and NS branches rather than written twice: the set branch kept returning
+ * Double after the scalar one was fixed. Deliberately not a conditional expression either, since
+ * one with Double and Long branches is subject to binary numeric promotion, which unboxes both
+ * and makes every number a double again.
+ */
+ private Object number(String value) {
+ try {
+ if (value.contains(".") || value.contains("e") || value.contains("E")) {
+ return Double.valueOf(value);
+ }
+ return Long.valueOf(value);
+ } catch (NumberFormatException e) {
+ return value;
+ }
+ }
+
+ private List<Object> toList(JsonNode array) {
+ List<Object> values = new ArrayList<>();
+ array.forEach(element -> values.add(element.asText()));
+ return values;
+ }
+
+ private String encodeNextToken(JsonNode lastEvaluatedKey) {
+ if (lastEvaluatedKey == null || lastEvaluatedKey.isNull() || lastEvaluatedKey.isEmpty()) {
+ return null;
+ }
+ return Base64.getUrlEncoder().withoutPadding()
+ .encodeToString(lastEvaluatedKey.toString().getBytes(StandardCharsets.UTF_8));
+ }
+
+ private JsonNode decodeNextToken(String nextToken) {
+ try {
+ byte[] decoded = Base64.getUrlDecoder().decode(nextToken);
+ return objectMapper.readTree(new String(decoded, StandardCharsets.UTF_8));
+ } catch (Exception e) {
+ throw new AwsException("InternalFailureException",
+ "The nextToken handed to the DynamoDB data source is not one Floci issued", 500);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvoker.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvoker.java
new file mode 100644
index 0000000000..e290f28e33
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvoker.java
@@ -0,0 +1,118 @@
+package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.InvocationType;
+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The {@code AWS_LAMBDA} data source: invokes the function synchronously and returns its parsed
+ * payload.
+ *
+ * <p>The request is AppSync's {@code {operation: "Invoke", payload: …}}, or, for
+ * {@code BatchInvoke}, a list payload the function answers with a list in the same order. A
+ * function that returns a handled error (a Lambda {@code errorMessage}) fails the field rather than
+ * resolving to the error object, which is what AppSync does with an unhandled function error.
+ */
+@ApplicationScoped
+public class LambdaDataSourceInvoker implements AppSyncDataSourceInvoker {
+
+ private final LambdaService lambdaService;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public LambdaDataSourceInvoker(LambdaService lambdaService, ObjectMapper objectMapper) {
+ this.lambdaService = lambdaService;
+ this.objectMapper = objectMapper;
+ }
+
+ @Override
+ public DataSourceType type() {
+ return DataSourceType.AWS_LAMBDA;
+ }
+
+ @Override
+ public Object invoke(DataSource dataSource, Object request, String region) {
+ String functionArn = functionArn(dataSource);
+ Object payload = payloadOf(request);
+ if ("BatchInvoke".equals(operationOf(request)) && payload instanceof List<?> batch) {
+ List<Object> results = new ArrayList<>();
+ // One invocation with the whole list, as AppSync does: the function is expected to
+ // answer with a list of the same length, in order.
+ Object answered = invokeOnce(functionArn, batch, region);
+ if (answered instanceof List<?> list) {
+ return list;
+ }
+ results.add(answered);
+ return results;
+ }
+ return invokeOnce(functionArn, payload, region);
+ }
+
+ private Object invokeOnce(String functionArn, Object payload, String region) {
+ byte[] body;
+ try {
+ body = objectMapper.writeValueAsBytes(payload == null ? Map.of() : payload);
+ } catch (Exception e) {
+ throw new AwsException("InternalFailureException",
+ "Could not serialise the Lambda data source payload: " + e.getMessage(), 500);
+ }
+ InvokeResult result =
+ lambdaService.invokeArn(functionArn, body, InvocationType.RequestResponse);
+ String response = result.getPayload() == null
+ ? null
+ : new String(result.getPayload(), StandardCharsets.UTF_8);
+ if (result.getFunctionError() != null && !result.getFunctionError().isBlank()) {
+ throw new AwsException("LambdaExecutionException",
+ "The Lambda data source function failed: " + response, 400);
+ }
+ if (response == null || response.isBlank()) {
+ return null;
+ }
+ try {
+ return objectMapper.convertValue(objectMapper.readTree(response), Object.class);
+ } catch (Exception e) {
+ // A function that answered something other than JSON: hand back the raw text rather
+ // than failing, since a String-typed field is a legitimate shape.
+ return response;
+ }
+ }
+
+ private String functionArn(DataSource dataSource) {
+ Map<String, Object> config = dataSource.getLambdaConfig();
+ Object arn = config == null ? null : config.get("lambdaFunctionArn");
+ if (arn == null || String.valueOf(arn).isBlank()) {
+ throw new AwsException("InternalFailureException",
+ "Data source " + dataSource.getName() + " has no lambdaConfig.lambdaFunctionArn", 500);
+ }
+ return String.valueOf(arn);
+ }
+
+ private String operationOf(Object request) {
+ return request instanceof Map<?, ?> map && map.get("operation") != null
+ ? String.valueOf(map.get("operation"))
+ : "Invoke";
+ }
+
+ /**
+ * AppSync sends {@code {operation, payload}}; a resolver that returns a bare object with no
+ * {@code operation} is treated as the payload itself, which is how the older function-request
+ * shape behaved.
+ */
+ private Object payloadOf(Object request) {
+ if (request instanceof Map<?, ?> map && map.containsKey("payload")) {
+ return map.get("payload");
+ }
+ return request;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/NoneDataSourceInvoker.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/NoneDataSourceInvoker.java
new file mode 100644
index 0000000000..bd1ec3b386
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/NoneDataSourceInvoker.java
@@ -0,0 +1,29 @@
+package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+import jakarta.enterprise.context.ApplicationScoped;
+
+/**
+ * The {@code NONE} data source: no backing store, the request is the result.
+ *
+ * <p>AppSync passes the request payload straight through, which is what makes NONE the way to write
+ * a local resolver: a pipeline step that only shapes data, or a mutation that just publishes to
+ * subscribers. Real AppSync unwraps a {@code payload} member if there is one, and so does this.
+ */
+@ApplicationScoped
+public class NoneDataSourceInvoker implements AppSyncDataSourceInvoker {
+
+ @Override
+ public DataSourceType type() {
+ return DataSourceType.NONE;
+ }
+
+ @Override
+ public Object invoke(DataSource dataSource, Object request, String region) {
+ if (request instanceof java.util.Map<?, ?> map && map.containsKey("payload")) {
+ return map.get("payload");
+ }
+ return request;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/RelationalDataSourceInvoker.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/RelationalDataSourceInvoker.java
new file mode 100644
index 0000000000..624ef38964
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/RelationalDataSourceInvoker.java
@@ -0,0 +1,297 @@
+package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+
+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.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+import io.github.hectorvent.floci.services.rdsdata.RdsDataService;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * The {@code RELATIONAL_DATABASE} data source: runs the resolver's statements over the RDS Data API
+ * against the cluster in {@code relationalDatabaseConfig}.
+ *
+ * <p>The result is wrapped as {@code {"sqlStatementResults": [ … ]}}, one entry per statement, which
+ * is the shape {@code toJsonObject()} from {@code @aws-appsync/utils/rds} expects: the call every
+ * relational JS resolver's {@code response()} handler ends with.
+ *
+ * <p>Three request shapes are accepted, because AppSync itself moved between them: the classic
+ * {@code {statements, variableMap}}, the {@code {statement, parameters}} that the {@code sql},
+ * {@code select}, {@code insert}, {@code update} and {@code remove} helpers build, and a bare SQL
+ * string. A list of the second form (what {@code createPgStatement} returns) works too.
+ */
+@ApplicationScoped
+public class RelationalDataSourceInvoker implements AppSyncDataSourceInvoker {
+
+ private final RdsDataService rdsDataService;
+ private final RegionResolver regionResolver;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public RelationalDataSourceInvoker(RdsDataService rdsDataService,
+ RegionResolver regionResolver,
+ ObjectMapper objectMapper) {
+ this.rdsDataService = rdsDataService;
+ this.regionResolver = regionResolver;
+ this.objectMapper = objectMapper;
+ }
+
+ @Override
+ public DataSourceType type() {
+ return DataSourceType.RELATIONAL_DATABASE;
+ }
+
+ @Override
+ public Object invoke(DataSource dataSource, Object request, String region) {
+ Map<String, Object> endpoint = rdsEndpointConfig(dataSource);
+ String resourceArn = clusterArn(endpoint, dataSource, region);
+ String secretArn = text(endpoint.get("awsSecretStoreArn"));
+ String database = text(endpoint.get("databaseName"));
+ if (secretArn == null || database == null) {
+ throw new AwsException("InternalFailureException",
+ "Data source " + dataSource.getName()
+ + " is missing rdsHttpEndpointConfig.awsSecretStoreArn or databaseName", 500);
+ }
+
+ List<Statement> statements = statements(request);
+ if (statements.isEmpty()) {
+ throw new AwsException("InternalFailureException",
+ "The resolver produced no SQL statement for data source " + dataSource.getName(), 500);
+ }
+
+ ArrayNode results = objectMapper.createArrayNode();
+ for (Statement statement : statements) {
+ ObjectNode rdsRequest = objectMapper.createObjectNode();
+ rdsRequest.put("resourceArn", resourceArn);
+ rdsRequest.put("secretArn", secretArn);
+ rdsRequest.put("database", database);
+ rdsRequest.put("sql", statement.sql());
+ // Column metadata is what turns records into keyed rows; toJsonObject cannot name a
+ // column without it.
+ rdsRequest.put("includeResultMetadata", true);
+ if (!statement.parameters().isEmpty()) {
+ rdsRequest.set("parameters", parameterNodes(statement.parameters()));
+ }
+ ObjectNode response = rdsDataService.executeStatement(rdsRequest, region);
+ results.add(sqlStatementResult(response));
+ }
+
+ ObjectNode wrapper = objectMapper.createObjectNode();
+ wrapper.set("sqlStatementResults", results);
+ return objectMapper.convertValue(wrapper, Object.class);
+ }
+
+ /** One statement's SQL plus its parameters, named {@code param1..paramN}. */
+ private record Statement(String sql, List<Parameter> parameters) {}
+
+ /**
+ * A bound value and the type the resolver declared for it.
+ *
+ * <p>The hint is load-bearing rather than decorative. A resolver's date filter binds a string
+ * and declares it {@code TIMESTAMP}; without the hint the Data API binds it as text and
+ * PostgreSQL refuses the comparison outright: {@code operator does not exist: timestamp with
+ * time zone >= character varying}, so every filtered query fails.
+ */
+ private record Parameter(String name, Object value, String typeHint) {}
+
+ private List<Statement> statements(Object request) {
+ List<Statement> statements = new ArrayList<>();
+ if (request instanceof String sql) {
+ statements.add(new Statement(sql, List.of()));
+ return statements;
+ }
+ if (request instanceof List<?> list) {
+ for (Object element : list) {
+ statements.addAll(statements(element));
+ }
+ return statements;
+ }
+ if (!(request instanceof Map<?, ?> map)) {
+ return statements;
+ }
+ // Classic AppSync: a list of statements sharing one variableMap.
+ if (map.get("statements") instanceof List<?> list) {
+ List<Parameter> shared = variableMapParameters(map.get("variableMap"),
+ map.get("variableTypeHintMap"));
+ for (Object element : list) {
+ statements.add(new Statement(String.valueOf(element), shared));
+ }
+ return statements;
+ }
+ Object statement = map.get("statement");
+ if (statement != null) {
+ statements.add(new Statement(String.valueOf(statement),
+ positionalParameters(map.get("parameters"), map.get("variableMap"),
+ map.get("variableTypeHintMap"))));
+ }
+ return statements;
+ }
+
+ /**
+ * {@code variableMap} names its own placeholders ({@code {":id": 7}}); the Data API takes the
+ * same names without the colon.
+ */
+ private List<Parameter> variableMapParameters(Object variableMap, Object typeHints) {
+ List<Parameter> parameters = new ArrayList<>();
+ if (variableMap instanceof Map<?, ?> map) {
+ map.forEach((key, value) -> {
+ String placeholder = String.valueOf(key);
+ String name = placeholder.startsWith(":") ? placeholder.substring(1) : placeholder;
+ parameters.add(new Parameter(name, value, typeHint(typeHints, placeholder, name)));
+ });
+ }
+ return parameters;
+ }
+
+ /**
+ * The hint declared for a placeholder. Looked up under both spellings because
+ * {@code variableTypeHintMap} is keyed by the placeholder as written in the statement
+ * ({@code :v0}), while the Data API's parameter name drops the colon.
+ */
+ private String typeHint(Object typeHints, String placeholder, String name) {
+ if (!(typeHints instanceof Map<?, ?> map)) {
+ return null;
+ }
+ Object hint = map.get(placeholder);
+ if (hint == null) {
+ hint = map.get(name);
+ }
+ return hint == null || String.valueOf(hint).isBlank() ? null : String.valueOf(hint);
+ }
+
+ /**
+ * The helpers emit positional parameters and reference them as {@code :param1..:paramN}, so the
+ * index is the name. A {@code variableMap} alongside them is honoured too, for a resolver that
+ * hand-rolls its statement.
+ */
+ private List<Parameter> positionalParameters(Object parameters, Object variableMap, Object typeHints) {
+ List<Parameter> named = new ArrayList<>(variableMapParameters(variableMap, typeHints));
+ if (parameters instanceof List<?> list) {
+ for (int i = 0; i < list.size(); i++) {
+ String name = "param" + (i + 1);
+ named.add(new Parameter(name, list.get(i), typeHint(typeHints, ":" + name, name)));
+ }
+ }
+ return named;
+ }
+
+ private ArrayNode parameterNodes(List<Parameter> parameters) {
+ // The Data API rejects a duplicate parameter name, and silently dropping one would change
+ // which value a placeholder binds to. This only arises when a resolver's variableMap names
+ // a placeholder that collides with the positional paramN the helpers generate, so say which
+ // one collided rather than letting the database report it.
+ Set<String> seen = new HashSet<>();
+ for (Parameter parameter : parameters) {
+ if (!seen.add(parameter.name())) {
+ throw new AwsException("InternalFailureException",
+ "The resolver bound two SQL parameters named :" + parameter.name()
+ + "; a variableMap key cannot reuse a generated positional name", 400);
+ }
+ }
+ ArrayNode nodes = objectMapper.createArrayNode();
+ for (Parameter parameter : parameters) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("name", parameter.name());
+ node.set("value", parameterValue(parameter.value()));
+ if (parameter.typeHint() != null) {
+ node.put("typeHint", parameter.typeHint());
+ }
+ nodes.add(node);
+ }
+ return nodes;
+ }
+
+ private ObjectNode parameterValue(Object value) {
+ ObjectNode node = objectMapper.createObjectNode();
+ if (value == null) {
+ node.put("isNull", true);
+ } else if (value instanceof Boolean bool) {
+ node.put("booleanValue", bool);
+ } else if (value instanceof Integer || value instanceof Long || value instanceof Short) {
+ node.put("longValue", ((Number) value).longValue());
+ } else if (value instanceof Number number) {
+ node.put("doubleValue", number.doubleValue());
+ } else if (value instanceof Map || value instanceof List) {
+ // A structured parameter is bound as its JSON text, which is what a json/jsonb column
+ // takes; Postgres casts it on the way in.
+ node.put("stringValue", writeJson(value));
+ } else {
+ node.put("stringValue", String.valueOf(value));
+ }
+ return node;
+ }
+
+ private String writeJson(Object value) {
+ try {
+ return objectMapper.writeValueAsString(value);
+ } catch (Exception e) {
+ throw new AwsException("InternalFailureException",
+ "Could not serialise a SQL parameter: " + e.getMessage(), 500);
+ }
+ }
+
+ /** Carries a statement's records, metadata and update count into the wrapper. */
+ private ObjectNode sqlStatementResult(ObjectNode response) {
+ ObjectNode result = objectMapper.createObjectNode();
+ result.put("numberOfRecordsUpdated", response.path("numberOfRecordsUpdated").asLong(0));
+ JsonNode records = response.get("records");
+ result.set("records", records == null || records.isNull()
+ ? objectMapper.createArrayNode() : records);
+ JsonNode metadata = response.get("columnMetadata");
+ if (metadata != null && !metadata.isNull()) {
+ result.set("columnMetadata", metadata);
+ }
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Map<String, Object> rdsEndpointConfig(DataSource dataSource) {
+ Map<String, Object> config = dataSource.getRelationalDatabaseConfig();
+ Object endpoint = config == null ? null : config.get("rdsHttpEndpointConfig");
+ if (!(endpoint instanceof Map<?, ?> map)) {
+ throw new AwsException("InternalFailureException",
+ "Data source " + dataSource.getName()
+ + " has no relationalDatabaseConfig.rdsHttpEndpointConfig", 500);
+ }
+ return (Map<String, Object>) map;
+ }
+
+ /**
+ * The Data API addresses a cluster by ARN, while the data source records the identifier a
+ * CloudFormation template gives it. An identifier that is already an ARN is used as-is.
+ */
+ private String clusterArn(Map<String, Object> endpoint, DataSource dataSource, String region) {
+ String identifier = text(endpoint.get("dbClusterIdentifier"));
+ if (identifier == null) {
+ throw new AwsException("InternalFailureException",
+ "Data source " + dataSource.getName()
+ + " has no rdsHttpEndpointConfig.dbClusterIdentifier", 500);
+ }
+ if (identifier.startsWith("arn:")) {
+ return identifier;
+ }
+ String endpointRegion = text(endpoint.get("awsRegion"));
+ return AwsArnUtils.Arn.of("rds", endpointRegion == null ? region : endpointRegion,
+ regionResolver.getAccountId(), "cluster:" + identifier).toString();
+ }
+
+ private String text(Object value) {
+ if (value == null) {
+ return null;
+ }
+ String text = String.valueOf(value);
+ return text.isBlank() ? null : text;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/AppSyncJsRuntime.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/AppSyncJsRuntime.java
new file mode 100644
index 0000000000..55c084a34a
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/AppSyncJsRuntime.java
@@ -0,0 +1,29 @@
+package io.github.hectorvent.floci.services.appsync.graphql.js;
+
+import java.util.Map;
+
+/**
+ * Evaluates {@code APPSYNC_JS} resolver code.
+ *
+ * <p>An interface with one implementation today ({@link NodeAppSyncJsRuntime}, a Node sidecar) so
+ * tests can drive resolver execution without Docker, and so a future in-process engine can replace
+ * the sidecar without touching the pipeline above it. Anything crossing this boundary is plain
+ * JSON-compatible data (maps, lists, strings, numbers, booleans and null), because the sidecar
+ * implementation serialises it.
+ */
+public interface AppSyncJsRuntime {
+
+ /**
+ * Calls {@code handler} ({@code "request"} or {@code "response"}) in {@code code} with
+ * {@code context} as {@code ctx}.
+ *
+ * <p>Never throws for a resolver's own failure: a {@code util.error()} call, a thrown
+ * exception, or a missing handler all come back on the {@link JsEvaluation}, since the pipeline
+ * has to decide what each means. Throws {@link io.github.hectorvent.floci.core.common.AwsException}
+ * only when the runtime itself is unusable: no Docker, the sidecar will not start, a timeout.
+ */
+ JsEvaluation evaluate(String code, String handler, Map<String, Object> context);
+
+ /** Whether resolver JavaScript can run at all, so a caller can fail with a useful message. */
+ boolean isAvailable();
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/JsEvaluation.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/JsEvaluation.java
new file mode 100644
index 0000000000..c1994f3a5e
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/JsEvaluation.java
@@ -0,0 +1,38 @@
+package io.github.hectorvent.floci.services.appsync.graphql.js;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * One resolver-handler call's outcome.
+ *
+ * @param result what the handler returned: a data source request for {@code request()}, the
+ * field's value for {@code response()}
+ * @param stash {@code ctx.stash} as the handler left it, carried to the next pipeline stage
+ * @param earlyReturn the handler called {@code runtime.earlyReturn()}, so the pipeline stops here
+ * and {@code result} is the field's value
+ * @param appendedErrors errors collected by {@code util.appendError}, which do not stop execution
+ * but are reported alongside the data
+ * @param error the handler threw; null on success. A {@code util.error()} call arrives with
+ * the type and data the resolver chose
+ * @param missingHandler the module exports no such function, which the caller reads as "pass the
+ * value through" rather than as a failure
+ */
+public record JsEvaluation(Object result,
+ Map<String, Object> stash,
+ boolean earlyReturn,
+ List<JsError> appendedErrors,
+ JsError error,
+ boolean missingHandler) {
+
+ public boolean failed() {
+ return error != null;
+ }
+
+ /** An error raised by resolver code, shaped like the GraphQL error AppSync reports for it. */
+ public record JsError(String message, String type, Object data, Object errorInfo) {
+ public static JsError of(String message, String type) {
+ return new JsError(message, type, null, null);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntime.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntime.java
new file mode 100644
index 0000000000..3b8480911d
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntime.java
@@ -0,0 +1,478 @@
+package io.github.hectorvent.floci.services.appsync.graphql.js;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.ContainerTeardown;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
+import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
+import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
+import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
+import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
+import com.github.dockerjava.api.model.Container;
+import jakarta.annotation.PreDestroy;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Runs {@code APPSYNC_JS} resolver code in a Node sidecar container.
+ *
+ * <p>The sidecar is one long-lived container per Floci instance, started lazily on the first JS
+ * resolver and reused for every evaluation after that, so the Node boot is paid once rather than
+ * per request. Its server is {@code appsync/appsync-js-runtime.mjs} on the classpath, handed to the
+ * container base64-encoded in its command: no bind mount, which keeps this working when Floci
+ * itself runs in a container and the host path would not resolve inside the Docker daemon.
+ *
+ * <p>The image is a stock {@code node:22-alpine} with no {@code npm install} step, so a resolver
+ * call never depends on registry access. {@code @aws-appsync/utils} is a shim the server writes
+ * into a {@code node_modules} directory at boot.
+ */
+@ApplicationScoped
+public class NodeAppSyncJsRuntime implements AppSyncJsRuntime, ContainerTeardown {
+
+ private static final Logger LOG = Logger.getLogger(NodeAppSyncJsRuntime.class);
+ private static final String SERVER_RESOURCE = "appsync/appsync-js-runtime.mjs";
+ private static final int CONTAINER_INTERNAL_PORT = 4600;
+ private static final String SERVER_PATH = "/tmp/floci-appsync-js-runtime.mjs";
+ /** How long an existing container gets to answer before it is treated as unusable. */
+ private static final int ADOPT_PROBE_SECONDS = 5;
+ /**
+ * Label carrying a digest of the server script the container was started with. The script is
+ * baked into the container's command, so a sidecar left over from an older Floci serves that
+ * older script forever: a fixed shim would never reach a developer who had one running.
+ * Adoption compares this and replaces the container when it differs.
+ */
+ private static final String SCRIPT_LABEL = "io.floci.appsync.js-runtime.script";
+
+ private final ContainerBuilder containerBuilder;
+ private final ContainerLifecycleManager lifecycleManager;
+ private final ContainerLogStreamer logStreamer;
+ private final ContainerDetector containerDetector;
+ private final EmulatorConfig config;
+ private final RegionResolver regionResolver;
+ private final ObjectMapper objectMapper;
+ private final HttpClient httpClient;
+
+ private volatile boolean started;
+ private volatile String containerId;
+ private volatile String baseUrl;
+ private volatile Closeable logStream;
+ private volatile String lastError;
+
+ @Inject
+ public NodeAppSyncJsRuntime(ContainerBuilder containerBuilder,
+ ContainerLifecycleManager lifecycleManager,
+ ContainerLogStreamer logStreamer,
+ ContainerDetector containerDetector,
+ EmulatorConfig config,
+ RegionResolver regionResolver,
+ ObjectMapper objectMapper) {
+ this.containerBuilder = containerBuilder;
+ this.lifecycleManager = lifecycleManager;
+ this.logStreamer = logStreamer;
+ this.containerDetector = containerDetector;
+ this.config = config;
+ this.regionResolver = regionResolver;
+ this.objectMapper = objectMapper;
+ this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
+ }
+
+ @Override
+ public boolean isAvailable() {
+ return jsRuntimeConfig().enabled();
+ }
+
+ @Override
+ public JsEvaluation evaluate(String code, String handler, Map<String, Object> context) {
+ if (!jsRuntimeConfig().enabled()) {
+ throw new AwsException("InternalFailureException",
+ "APPSYNC_JS resolvers need the Node sidecar, which is disabled. Set "
+ + "floci.services.appsync.js-runtime.enabled=true "
+ + "(FLOCI_SERVICES_APPSYNC_JS_RUNTIME_ENABLED) to run them.", 500);
+ }
+ ensureStarted();
+
+ Map<String, Object> body = new LinkedHashMap<>();
+ body.put("code", code);
+ body.put("handler", handler);
+ body.put("context", context);
+ body.put("enforceSubset", jsRuntimeConfig().enforceAppsyncSubset());
+ JsonNode response = post("/evaluate", body);
+ return toEvaluation(response);
+ }
+
+ /** Starts, or adopts, the sidecar. Idempotent; a failed start is retried by the next call. */
+ synchronized void ensureStarted() {
+ if (started && baseUrl != null) {
+ return;
+ }
+ Optional<String> configured = jsRuntimeConfig().url();
+ if (configured.isPresent() && !configured.get().isBlank()) {
+ // A server someone else is running: no container to create, adopt or stop. Probed with
+ // the short timeout, since a URL that is wrong should say so rather than hold the first
+ // resolver for the full start budget.
+ this.baseUrl = configured.get();
+ awaitHealthy(ADOPT_PROBE_SECONDS);
+ this.started = true;
+ this.lastError = null;
+ LOG.infov("Using the pre-configured AppSync JS runtime at {0}", baseUrl);
+ return;
+ }
+ String image = jsRuntimeConfig().image();
+ String name = ContainerStorageHelper.dockerName(config, jsRuntimeConfig().containerName());
+ try {
+ Optional<Container> existing = lifecycleManager.findByName(name);
+ if (existing.isPresent()) {
+ // A sidecar left over from a previous run (keep-running-on-shutdown, or a crash)
+ // serves the same server script, so adopting it skips the Node boot entirely.
+ if (tryAdopt(existing.get())) {
+ return;
+ }
+ // findByName also answers with stopped and exited containers, so a dead leftover
+ // must be cleared rather than adopted again on every call, and its name freed
+ // before the create below asks for it.
+ LOG.infov("Replacing unusable AppSync JS runtime sidecar {0}", name);
+ lifecycleManager.stopAndRemove(existing.get().getId(), null);
+ }
+
+ ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
+ .withName(name)
+ .withEnv(List.of("FLOCI_JS_RUNTIME_PORT=" + CONTAINER_INTERNAL_PORT))
+ // sh -c so the encoded server can be decoded and run in one command. busybox
+ // in the alpine image supplies both sh and base64.
+ .withEntrypoint(List.of("sh", "-c"))
+ .withCmd(List.of(startCommand()))
+ .withLabel(SCRIPT_LABEL, scriptDigest())
+ .withDockerNetwork(jsRuntimeConfig().dockerNetwork())
+ .withLogRotation();
+ int configuredPort = jsRuntimeConfig().port();
+ if (configuredPort > 0) {
+ specBuilder.withPortBinding(CONTAINER_INTERNAL_PORT, configuredPort);
+ } else {
+ specBuilder.withDynamicPort(CONTAINER_INTERNAL_PORT);
+ }
+ if (!containerDetector.isRunningInContainer()) {
+ specBuilder.withHostDockerInternalOnLinux();
+ }
+
+ ContainerSpec spec = specBuilder.build();
+ ContainerInfo info = lifecycleManager.createAndStart(spec);
+ this.containerId = info.containerId();
+ this.baseUrl = endpointUrl(info.getEndpoint(CONTAINER_INTERNAL_PORT));
+ attachLogStream();
+ awaitHealthy();
+ this.started = true;
+ this.lastError = null;
+ LOG.infov("AppSync JS runtime sidecar {0} ready at {1}", name, baseUrl);
+ } catch (AwsException e) {
+ reset();
+ throw e;
+ } catch (Exception e) {
+ reset();
+ this.lastError = e.getMessage();
+ throw new AwsException("InternalFailureException",
+ "Could not start the AppSync JS runtime sidecar from image " + image + ": "
+ + e.getMessage() + ". Resolver JavaScript needs Docker; set "
+ + "floci.services.appsync.js-runtime.enabled=false to disable it.", 500);
+ }
+ }
+
+ /**
+ * Takes over an existing sidecar, or answers false when it cannot serve: stopped, exited, or
+ * failing its health check. Bounded by a short probe rather than the full start timeout: a dead
+ * container should be replaced promptly, not waited on.
+ */
+ private boolean tryAdopt(Container existing) {
+ Map<String, String> labels = existing.getLabels();
+ String ranWith = labels == null ? null : labels.get(SCRIPT_LABEL);
+ if (!scriptDigest().equals(ranWith)) {
+ LOG.infov("Existing AppSync JS runtime sidecar was started from a different server "
+ + "script ({0}); replacing it", ranWith == null ? "unlabelled" : ranWith);
+ return false;
+ }
+ try {
+ this.containerId = existing.getId();
+ ContainerInfo info = lifecycleManager.adopt(containerId, List.of(CONTAINER_INTERNAL_PORT));
+ this.baseUrl = endpointUrl(info.getEndpoint(CONTAINER_INTERNAL_PORT));
+ awaitHealthy(ADOPT_PROBE_SECONDS);
+ this.started = true;
+ this.lastError = null;
+ LOG.infov("Adopted AppSync JS runtime sidecar {0} at {1}", containerId, baseUrl);
+ return true;
+ } catch (RuntimeException e) {
+ LOG.debugv("Could not adopt the existing AppSync JS runtime sidecar: {0}", e.getMessage());
+ // Left running on purpose: ensureStarted removes it by name straight after, since an
+ // adopted container that cannot serve is not ours to have started.
+ reset();
+ return false;
+ }
+ }
+
+ /**
+ * The command that materialises the server inside the container. The script is base64-encoded
+ * rather than quoted into the shell: it contains the quotes, backticks and newlines of the
+ * {@code @aws-appsync/utils} shim it writes, none of which survive shell interpolation.
+ */
+ private String startCommand() {
+ String encoded = Base64.getEncoder().encodeToString(serverScript().getBytes(StandardCharsets.UTF_8));
+ return "echo " + encoded + " | base64 -d > " + SERVER_PATH + " && exec node " + SERVER_PATH;
+ }
+
+ /** Digest of the server script this build would start the sidecar with. */
+ private String scriptDigest() {
+ try {
+ byte[] hash = MessageDigest.getInstance("SHA-256")
+ .digest(serverScript().getBytes(StandardCharsets.UTF_8));
+ StringBuilder hex = new StringBuilder(16);
+ for (int i = 0; i < 8; i++) {
+ hex.append(String.format("%02x", hash[i]));
+ }
+ return hex.toString();
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 is unavailable", e);
+ }
+ }
+
+ private String serverScript() {
+ try (InputStream in = Thread.currentThread().getContextClassLoader()
+ .getResourceAsStream(SERVER_RESOURCE)) {
+ if (in == null) {
+ throw new IllegalStateException(SERVER_RESOURCE + " is missing from the classpath");
+ }
+ return new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ throw new IllegalStateException("Could not read " + SERVER_RESOURCE, e);
+ }
+ }
+
+ private void awaitHealthy() {
+ awaitHealthy(jsRuntimeConfig().startTimeoutSeconds());
+ }
+
+ private void awaitHealthy(int timeoutSeconds) {
+ long deadline = System.currentTimeMillis() + timeoutSeconds * 1000L;
+ Exception last = null;
+ while (System.currentTimeMillis() < deadline) {
+ try {
+ HttpResponse<String> response = httpClient.send(
+ HttpRequest.newBuilder(URI.create(baseUrl + "/health"))
+ .timeout(Duration.ofSeconds(2)).GET().build(),
+ HttpResponse.BodyHandlers.ofString());
+ if (response.statusCode() == 200) {
+ return;
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new AwsException("InternalFailureException",
+ "Interrupted while waiting for the AppSync JS runtime sidecar", 500);
+ } catch (Exception e) {
+ last = e;
+ }
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new AwsException("InternalFailureException",
+ "Interrupted while waiting for the AppSync JS runtime sidecar", 500);
+ }
+ }
+ throw new AwsException("InternalFailureException",
+ "The AppSync JS runtime sidecar did not become healthy within "
+ + timeoutSeconds + "s"
+ + (last == null ? "" : ": " + last.getMessage()), 500);
+ }
+
+ private JsonNode post(String path, Map<String, Object> body) {
+ try {
+ byte[] payload = objectMapper.writeValueAsBytes(body);
+ HttpResponse<String> response = httpClient.send(
+ HttpRequest.newBuilder(URI.create(baseUrl + path))
+ .timeout(Duration.ofSeconds(jsRuntimeConfig().evaluationTimeoutSeconds()))
+ .header("content-type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofByteArray(payload))
+ .build(),
+ HttpResponse.BodyHandlers.ofString());
+ if (response.statusCode() != 200) {
+ throw new AwsException("InternalFailureException",
+ "The AppSync JS runtime sidecar answered " + response.statusCode(), 500);
+ }
+ return objectMapper.readTree(response.body());
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new AwsException("InternalFailureException",
+ "Interrupted while evaluating resolver code", 500);
+ } catch (AwsException e) {
+ throw e;
+ } catch (Exception e) {
+ // The sidecar stopped answering, so the next call starts a fresh one.
+ discardSidecar();
+ throw new AwsException("InternalFailureException",
+ "Could not reach the AppSync JS runtime sidecar: " + e.getMessage(), 500);
+ }
+ }
+
+ private JsEvaluation toEvaluation(JsonNode response) {
+ List<JsEvaluation.JsError> appended = new ArrayList<>();
+ for (JsonNode error : response.path("errors")) {
+ appended.add(toError(error));
+ }
+ Map<String, Object> stash = objectMapper.convertValue(
+ response.has("stash") && response.get("stash").isObject()
+ ? response.get("stash")
+ : objectMapper.createObjectNode(),
+ Map.class);
+ if (response.path("ok").asBoolean(false)) {
+ return new JsEvaluation(unwrap(response.get("result")), stash,
+ response.path("earlyReturn").asBoolean(false), appended, null, false);
+ }
+ return new JsEvaluation(null, stash, false, appended, toError(response.path("error")),
+ response.path("missingHandler").asBoolean(false));
+ }
+
+ private JsEvaluation.JsError toError(JsonNode node) {
+ if (node == null || node.isMissingNode() || node.isNull()) {
+ return null;
+ }
+ return new JsEvaluation.JsError(
+ node.path("message").asText(null),
+ node.path("type").isNull() ? null : node.path("type").asText(null),
+ unwrap(node.get("data")),
+ unwrap(node.get("errorInfo")));
+ }
+
+ private Object unwrap(JsonNode node) {
+ if (node == null || node.isNull() || node.isMissingNode()) {
+ return null;
+ }
+ return objectMapper.convertValue(node, Object.class);
+ }
+
+ private String endpointUrl(EndpointInfo endpoint) {
+ return "http://" + endpoint.host() + ":" + endpoint.port();
+ }
+
+ /**
+ * Follows the sidecar's stdout into CloudWatch Logs, as the other sidecars do: a resolver
+ * that fails to compile says so on Node's stderr and nowhere else.
+ */
+ private void attachLogStream() {
+ try {
+ String shortId = containerId.length() >= 8 ? containerId.substring(0, 8) : containerId;
+ this.logStream = logStreamer.attach(containerId, "/floci/appsync-js",
+ logStreamer.generateLogStreamName(shortId),
+ regionResolver.getDefaultRegion(), "appsync:js");
+ } catch (RuntimeException e) {
+ LOG.debugv("Could not attach to AppSync JS runtime logs: {0}", e.getMessage());
+ }
+ }
+
+ /**
+ * Drops every handle to the sidecar this instance was using. The container id and the log
+ * follower go too: keeping them meant a later shutdown could stop and remove a container this
+ * runtime no longer considered its own, and the follower was never closed on the failure path.
+ *
+ * <p>Synchronized on the same monitor as {@link #ensureStarted()} and
+ * {@link #stopManagedContainers()}, all four fields being shared between them. Without it a
+ * failed evaluation could clear the fields in the window after a container has been created and
+ * its id recorded but before {@code started} is set, which drops the only handle to a live
+ * container: teardown then sees a null id, treats the sidecar as never started, and the
+ * container is leaked rather than stopped. Reentrant, so the callers that already hold the
+ * monitor are unaffected.
+ */
+ private synchronized void reset() {
+ this.started = false;
+ this.baseUrl = null;
+ this.containerId = null;
+ Closeable stream = this.logStream;
+ this.logStream = null;
+ if (stream != null) {
+ try {
+ stream.close();
+ } catch (IOException e) {
+ LOG.debugv("Could not close the AppSync JS runtime log stream: {0}", e.getMessage());
+ }
+ }
+ }
+
+ /**
+ * Gives up on a sidecar that stopped answering, stopping it rather than merely forgetting it.
+ *
+ * <p>Forgetting is what leaks: nothing else holds the id, so the container would run until the
+ * next start happened to find it by name, and teardown could not reach it at all. Synchronized
+ * for the same reason {@link #reset()} is, and a no-op when the runtime is pointed at a URL
+ * someone else is running, which owns no container.
+ */
+ private synchronized void discardSidecar() {
+ String id = this.containerId;
+ Closeable stream = this.logStream;
+ this.containerId = null;
+ this.logStream = null;
+ reset();
+ if (id == null) {
+ return;
+ }
+ try {
+ lifecycleManager.stopAndRemove(id, stream);
+ } catch (RuntimeException e) {
+ LOG.debugv("Could not remove the unreachable AppSync JS runtime sidecar {0}: {1}",
+ id, e.getMessage());
+ }
+ }
+
+ private EmulatorConfig.JsRuntimeConfig jsRuntimeConfig() {
+ return config.services().appsync().jsRuntime();
+ }
+
+ /** For diagnostics: the sidecar's last start failure, or null. */
+ public String lastError() {
+ return lastError;
+ }
+
+ /**
+ * Stops the sidecar, so {@code /state/reset} and the shutdown phase reach it like every other
+ * managed container. Idempotent, and a no-op when the runtime is pointed at a URL someone else
+ * is running: that server is not ours to stop.
+ */
+ @Override
+ public synchronized void stopManagedContainers() {
+ if (containerId == null) {
+ reset();
+ return;
+ }
+ if (jsRuntimeConfig().keepRunningOnShutdown()) {
+ LOG.infov("Leaving AppSync JS runtime sidecar {0} running for next start-up", containerId);
+ return;
+ }
+ lifecycleManager.stopAndRemove(containerId, logStream);
+ reset();
+ }
+
+ @PreDestroy
+ void shutdown() {
+ stopManagedContainers();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverError.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverError.java
new file mode 100644
index 0000000000..73ecb0c3bc
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverError.java
@@ -0,0 +1,19 @@
+package io.github.hectorvent.floci.services.appsync.graphql.resolver;
+
+import java.util.List;
+
+/**
+ * A resolver's own error, shaped the way AppSync reports one.
+ *
+ * <p>{@code util.error("...", "Forbidden")} does not produce a generic
+ * "exception while fetching data": it produces an error carrying that {@code errorType}, which
+ * clients switch on, alongside the {@code data} and {@code errorInfo} the resolver chose.
+ *
+ * <p>The four payload fields are exactly the sidecar callback's {@code {message, type, data, info}}
+ * error shape, which the sidecar copies onto the GraphQL error's {@code extensions} and
+ * {@link io.github.hectorvent.floci.services.appsync.graphql.AppSyncErrorFormatter} lifts back to
+ * AppSync's top-level {@code errorType}/{@code errorInfo}.
+ */
+public record AppSyncResolverError(String message, String errorType, Object data, Object errorInfo,
+ List<Object> path) {
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutor.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutor.java
new file mode 100644
index 0000000000..cf99dd4de4
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutor.java
@@ -0,0 +1,432 @@
+package io.github.hectorvent.floci.services.appsync.graphql.resolver;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.appsync.AppSyncService;
+import io.github.hectorvent.floci.services.appsync.graphql.datasource.AppSyncDataSourceInvokers;
+import io.github.hectorvent.floci.services.appsync.graphql.js.AppSyncJsRuntime;
+import io.github.hectorvent.floci.services.appsync.graphql.js.JsEvaluation;
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.FunctionConfiguration;
+import io.github.hectorvent.floci.services.appsync.model.Resolver;
+import io.github.hectorvent.floci.services.appsync.model.ResolverKind;
+import io.github.hectorvent.floci.services.appsync.model.ResolverRuntimeName;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Runs the resolver attached to a field: its handlers, its data source, and, for a PIPELINE
+ * resolver, each of its functions in order.
+ *
+ * <p>The shape follows AppSync's. A UNIT resolver is {@code request() → data source → response()}.
+ * A PIPELINE resolver is the resolver's own {@code request()} (its "before" step), then every
+ * function as its own request/data-source/response, each seeing the one before it as
+ * {@code ctx.prev.result}, and finally the resolver's {@code response()} ("after"). {@code ctx.stash}
+ * is threaded through all of it, which is how a before step passes work to the functions.
+ *
+ * <p>A data source that fails does not fail the field on its own. AppSync calls the stage's
+ * {@code response()} handler with {@code ctx.error} set to {@code {message, type}} and
+ * {@code ctx.result} null, and the handler decides: re-raise with {@code util.error} (or collect
+ * with {@code util.appendError}), or return a value and <em>suppress</em> the error entirely. That
+ * suppression is deliberate on AWS's part and is why resolvers are written with an explicit
+ * {@code if (ctx.error)} branch: without one, a failed query silently returns whatever the handler
+ * returned. A stage with no {@code response()} handler at all has nothing to make that decision, so
+ * there the error fails the field.
+ *
+ * <p>Two things stop a pipeline early. {@code runtime.earlyReturn(value)} makes {@code value} the
+ * field's result immediately, skipping everything left including the after step, and
+ * {@code util.error()} fails the field. {@code util.appendError} does neither: it collects errors
+ * that are returned <em>alongside</em> the data, which is why a {@link ResolverOutcome} carries
+ * both rather than being a bare value.
+ */
+@ApplicationScoped
+public class AppSyncResolverExecutor {
+
+ private static final Logger LOG = Logger.getLogger(AppSyncResolverExecutor.class);
+ private static final String REQUEST = "request";
+ private static final String RESPONSE = "response";
+
+ private final AppSyncService appSyncService;
+ private final AppSyncJsRuntime jsRuntime;
+ private final AppSyncDataSourceInvokers dataSourceInvokers;
+
+ @Inject
+ public AppSyncResolverExecutor(AppSyncService appSyncService,
+ AppSyncJsRuntime jsRuntime,
+ AppSyncDataSourceInvokers dataSourceInvokers) {
+ this.appSyncService = appSyncService;
+ this.jsRuntime = jsRuntime;
+ this.dataSourceInvokers = dataSourceInvokers;
+ }
+
+ /**
+ * The resolver for a field, or null when it has none. The caller then falls back to reading
+ * the field off its source object, as a GraphQL server does by default.
+ */
+ public Resolver findResolver(String apiId, String typeName, String fieldName) {
+ try {
+ return appSyncService.getResolver(apiId, typeName, fieldName);
+ } catch (AwsException e) {
+ // Only "there is no resolver" means fall back to the default fetcher. Anything else (a schema
+ // mid-recreation answers 409) has to surface, or a field would read as
+ // unresolved during a deploy and quietly return null.
+ if (e.getHttpStatus() == 404) {
+ return null;
+ }
+ throw e;
+ }
+ }
+
+ public ResolverOutcome execute(Resolver resolver, ResolverInvocation invocation) {
+ Execution execution = new Execution(resolver, invocation);
+ try {
+ return execution.run();
+ } catch (ResolverRaisedException e) {
+ return execution.failure(e.error());
+ } catch (AwsException e) {
+ // A failure of the emulator itself (no sidecar, an unusable data source) is reported on
+ // the field rather than thrown: one broken field should not abort the whole operation.
+ LOG.debugv("Resolver {0}.{1} failed: {2}", resolver.getTypeName(), resolver.getFieldName(),
+ e.getMessage());
+ return new ResolverOutcome(null, new AppSyncResolverError(e.getMessage(), e.getErrorCode(),
+ null, null, invocation.path()), List.of());
+ }
+ }
+
+ /**
+ * One stage's code and the runtime it is written for: the resolver itself, or one pipeline
+ * function.
+ *
+ * <p>{@code vtl} is decided from the mapping templates, not from an absent runtime. AppSync
+ * leaves {@code Runtime} unset on a VTL resolver, so treating "no runtime" as APPSYNC_JS made
+ * the VTL check below unreachable and a VTL stage fell through to the pass-through arm: it ran
+ * as if it had no handler instead of saying it is unsupported.
+ */
+ private record Stage(String code, ResolverRuntimeName runtime, boolean vtl) {
+
+ static Stage of(Resolver resolver) {
+ return new Stage(resolver.getCode(), resolver.getRuntime() == null
+ ? null : resolver.getRuntime().getName(),
+ isVtl(resolver.getCode(), resolver.getRuntime() == null
+ ? null : resolver.getRuntime().getName(),
+ resolver.getRequestMappingTemplate(), resolver.getResponseMappingTemplate()));
+ }
+
+ static Stage of(FunctionConfiguration function) {
+ return new Stage(function.getCode(), function.getRuntime() == null
+ ? null : function.getRuntime().getName(),
+ isVtl(function.getCode(), function.getRuntime() == null
+ ? null : function.getRuntime().getName(),
+ function.getRequestMappingTemplate(), function.getResponseMappingTemplate()));
+ }
+
+ private static boolean isVtl(String code, ResolverRuntimeName runtime, String requestTemplate,
+ String responseTemplate) {
+ if (runtime == ResolverRuntimeName.VTL) {
+ return true;
+ }
+ boolean hasCode = code != null && !code.isBlank();
+ boolean hasTemplate = (requestTemplate != null && !requestTemplate.isBlank())
+ || (responseTemplate != null && !responseTemplate.isBlank());
+ return !hasCode && hasTemplate;
+ }
+ }
+
+ /** One field's resolution, holding the mutable pipeline state. */
+ private final class Execution {
+
+ private final String apiId;
+ private final Resolver resolver;
+ private final ResolverInvocation invocation;
+ private final List<Object> path;
+ private final List<AppSyncResolverError> errors = new ArrayList<>();
+
+ private Map<String, Object> stash = new LinkedHashMap<>();
+ private Object previousResult;
+ /** Set when a handler called runtime.earlyReturn: the pipeline stops and this is the value. */
+ private boolean returned;
+ private Object earlyReturnValue;
+
+ private Execution(Resolver resolver, ResolverInvocation invocation) {
+ this.apiId = invocation.apiId();
+ this.resolver = resolver;
+ this.invocation = invocation;
+ this.path = invocation.path();
+ }
+
+ private ResolverOutcome run() {
+ if (resolver.getKind() == ResolverKind.PIPELINE) {
+ return runPipeline();
+ }
+ return runUnit();
+ }
+
+ private ResolverOutcome runUnit() {
+ Stage stage = Stage.of(resolver);
+ Object request = callHandler(stage, REQUEST, null, null, null);
+ if (returned) {
+ return result(earlyReturnValue);
+ }
+ Invocation invocation = invokeDataSource(resolver.getDataSourceName(), request);
+ Object response = callHandler(stage, RESPONSE,
+ invocation.result(), invocation.error(), invocation.result());
+ return result(returned ? earlyReturnValue : response);
+ }
+
+ private ResolverOutcome runPipeline() {
+ // The before step's job is usually to fill ctx.stash for the functions; its return value
+ // is not the field's result, but it is what the first function sees as ctx.prev.result.
+ Stage resolverStage = Stage.of(resolver);
+ Object before = callHandler(resolverStage, REQUEST, null, null, null);
+ if (returned) {
+ return result(earlyReturnValue);
+ }
+ previousResult = before;
+
+ for (String functionId : pipelineFunctionIds()) {
+ FunctionConfiguration function = function(functionId);
+ Stage functionStage = Stage.of(function);
+ Object request = callHandler(functionStage, REQUEST, null, null, null);
+ if (returned) {
+ return result(earlyReturnValue);
+ }
+ Invocation invocation = invokeDataSource(function.getDataSourceName(), request);
+ Object response = callHandler(functionStage, RESPONSE,
+ invocation.result(), invocation.error(), invocation.result());
+ if (returned) {
+ return result(earlyReturnValue);
+ }
+ // Missing response handler: the data source result passes through, which is what a
+ // function with only a request handler does on AppSync.
+ previousResult = response;
+ }
+
+ // The after step has no data source of its own, so it never carries ctx.error: a
+ // function whose error went unsuppressed stopped the pipeline before this point.
+ Object after = callHandler(resolverStage, RESPONSE, previousResult, null, null);
+ return result(returned ? earlyReturnValue : after);
+ }
+
+ private List<String> pipelineFunctionIds() {
+ Map<String, Object> pipelineConfig = resolver.getPipelineConfig();
+ Object functions = pipelineConfig == null ? null : pipelineConfig.get("functions");
+ List<String> ids = new ArrayList<>();
+ if (functions instanceof List<?> list) {
+ list.forEach(id -> ids.add(String.valueOf(id)));
+ }
+ return ids;
+ }
+
+ private FunctionConfiguration function(String functionId) {
+ try {
+ return appSyncService.getFunction(apiId, functionId);
+ } catch (AwsException e) {
+ // Only "no such function" is that. A 409 from a schema mid-recreation, or any other
+ // control-plane failure, has to surface as itself or the real cause is lost.
+ if (e.getHttpStatus() != 404) {
+ throw e;
+ }
+ throw new AwsException("InternalFailureException",
+ "Pipeline resolver " + resolver.getTypeName() + "." + resolver.getFieldName()
+ + " names function " + functionId + ", which does not exist", 500);
+ }
+ }
+
+ private Invocation invokeDataSource(String dataSourceName, Object request) {
+ if (dataSourceName == null || dataSourceName.isBlank()) {
+ // A pipeline resolver's own before/after steps have no data source, and neither do
+ // the local functions AppSync allows: the request is the result.
+ return new Invocation(request, null);
+ }
+ DataSource dataSource;
+ try {
+ dataSource = appSyncService.getDataSource(apiId, dataSourceName);
+ } catch (AwsException e) {
+ // Not a data source error the resolver could handle (the data source it names does
+ // not exist), so this fails the field rather than reaching ctx.error.
+ throw new AwsException("InternalFailureException",
+ "Data source " + dataSourceName + " does not exist on API " + apiId, 500);
+ }
+ try {
+ return new Invocation(dataSourceInvokers.invoke(dataSource, request, regionOf(dataSource)),
+ null);
+ } catch (AwsException e) {
+ // What the store or function answered: the resolver sees it as ctx.error and decides.
+ // Deliberately only AwsException: an unexpected RuntimeException is a defect in the
+ // emulator, and routing it somewhere a resolver can swallow it would hide it.
+ LOG.debugv("Data source {0} failed for {1}.{2}: {3}", dataSourceName,
+ resolver.getTypeName(), resolver.getFieldName(), e.getMessage());
+ return new Invocation(null,
+ new JsEvaluation.JsError(e.getMessage(), e.getErrorCode(), null, null));
+ }
+ }
+
+ /**
+ * One data source call's outcome: its result, or the error {@code ctx.error} carries into the
+ * response handler. Never both.
+ */
+ private record Invocation(Object result, JsEvaluation.JsError error) {}
+
+ private String regionOf(DataSource dataSource) {
+ String arn = dataSource.getDataSourceArn();
+ if (arn != null && arn.startsWith("arn:")) {
+ String[] parts = arn.split(":", 5);
+ if (parts.length > 3 && !parts[3].isBlank()) {
+ return parts[3];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Calls one handler. A handler the module does not export is not an error: AppSync treats a
+ * missing {@code response()} as "pass the data source result through", which is
+ * {@code passThrough} here.
+ */
+ private Object callHandler(Stage stage, String handler, Object result,
+ JsEvaluation.JsError error, Object passThrough) {
+ if (stage.vtl()) {
+ // Said out loud rather than resolved to null: a null that means "not implemented"
+ // is indistinguishable from a null that means "no rows".
+ throw new AwsException("InternalFailureException",
+ "Floci runs APPSYNC_JS resolvers only; " + resolver.getTypeName() + "."
+ + resolver.getFieldName() + " uses VTL mapping templates", 500);
+ }
+ String code = stage.code();
+ if (code == null || code.isBlank()) {
+ // Neither code nor templates: nothing to run, and nothing that could have decided
+ // to suppress a data source error either.
+ if (error != null) {
+ throw new ResolverRaisedException(new AppSyncResolverError(error.message(),
+ error.type(), error.data(), error.errorInfo(), path));
+ }
+ return passThrough;
+ }
+
+ JsEvaluation evaluation = jsRuntime.evaluate(code, handler, context(result, error));
+ collect(evaluation.appendedErrors());
+ if (evaluation.missingHandler()) {
+ // Nothing here could have decided to suppress the data source error, so it stands.
+ if (error != null) {
+ throw new ResolverRaisedException(new AppSyncResolverError(error.message(),
+ error.type(), error.data(), error.errorInfo(), path));
+ }
+ return passThrough;
+ }
+ if (evaluation.failed()) {
+ JsEvaluation.JsError raised = evaluation.error();
+ // util.error() is the resolver deliberately failing the field, so it becomes the
+ // field's error with the type the resolver chose, and the pipeline stops. This is
+ // also the path a resolver takes when it re-raises ctx.error.
+ throw new ResolverRaisedException(new AppSyncResolverError(raised.message(),
+ raised.type(), raised.data(), raised.errorInfo(), path));
+ }
+ if (evaluation.stash() != null) {
+ this.stash = new LinkedHashMap<>(evaluation.stash());
+ }
+ if (evaluation.earlyReturn()) {
+ this.returned = true;
+ this.earlyReturnValue = evaluation.result();
+ }
+ return evaluation.result();
+ }
+
+ private void collect(List<JsEvaluation.JsError> appended) {
+ if (appended == null) {
+ return;
+ }
+ appended.forEach(error -> errors.add(new AppSyncResolverError(error.message(),
+ error.type(), error.data(), error.errorInfo(), path)));
+ }
+
+ /** The {@code ctx} a handler receives. */
+ private Map<String, Object> context(Object result, JsEvaluation.JsError error) {
+ Map<String, Object> context = new LinkedHashMap<>();
+ Map<String, Object> arguments = invocation.arguments();
+ context.put("arguments", arguments);
+ context.put("args", arguments);
+ context.put("source", invocation.source());
+ context.put("stash", stash);
+ Map<String, Object> prev = new LinkedHashMap<>();
+ prev.put("result", previousResult);
+ context.put("prev", prev);
+ context.put("identity", invocation.identity());
+ context.put("request", requestContext());
+ context.put("info", info());
+ context.put("env", environmentVariables());
+ if (result != null) {
+ context.put("result", result);
+ }
+ if (error != null) {
+ // AppSync's shape: message and type, which is what a resolver forwards to
+ // util.error(ctx.error.message, ctx.error.type).
+ Map<String, Object> contextError = new LinkedHashMap<>();
+ contextError.put("message", error.message());
+ contextError.put("type", error.type());
+ context.put("error", contextError);
+ }
+ return context;
+ }
+
+ private Map<String, Object> requestContext() {
+ Map<String, Object> request = new LinkedHashMap<>();
+ // The callback does not carry the client's headers, so ctx.request.headers is empty
+ // rather than wrong. authType it does, and a resolver keying off it behaves as on AWS.
+ request.put("headers", Map.of());
+ request.put("authType", invocation.authType());
+ request.put("domainName", null);
+ return request;
+ }
+
+ private Map<String, Object> info() {
+ Map<String, Object> info = new LinkedHashMap<>();
+ // The resolver's own field name rather than the step info's: identical in every case
+ // that reaches here, and available whether or not the caller supplied step info.
+ info.put("fieldName", resolver.getFieldName());
+ info.put("parentTypeName", resolver.getTypeName());
+ info.put("variables", invocation.variables());
+ // Already qualified names (slash-separated for a nested selection) when they reach here:
+ // the sidecar builds them from graphql-java's own SelectedField.getQualifiedName().
+ info.put("selectionSetList", invocation.selectionSetList());
+ info.put("selectionSetGraphQL", null);
+ return info;
+ }
+
+ private Map<String, String> environmentVariables() {
+ try {
+ Map<String, String> variables = appSyncService.getEnvironmentVariables(apiId);
+ return variables == null ? Map.of() : variables;
+ } catch (AwsException e) {
+ return Map.of();
+ }
+ }
+
+ /** The field's outcome when a resolver raised an error: no data, every error collected. */
+ private ResolverOutcome failure(AppSyncResolverError raised) {
+ return new ResolverOutcome(null, raised, errors);
+ }
+
+ private ResolverOutcome result(Object data) {
+ return new ResolverOutcome(data, null, errors);
+ }
+ }
+
+ /** Carries a resolver-raised error out of the pipeline to the field's result. */
+ static final class ResolverRaisedException extends RuntimeException {
+ private final transient AppSyncResolverError error;
+
+ ResolverRaisedException(AppSyncResolverError error) {
+ super(error.message());
+ this.error = error;
+ }
+
+ AppSyncResolverError error() {
+ return error;
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackResource.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackResource.java
new file mode 100644
index 0000000000..4256205077
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackResource.java
@@ -0,0 +1,187 @@
+package io.github.hectorvent.floci.services.appsync.graphql.resolver;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.appsync.model.Resolver;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.HeaderParam;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import org.jboss.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * The resolver callback the GraphQL sidecar calls back into, one HTTP call per execution level.
+ *
+ * <p>The sidecar runs the query and owns the GraphQL engine; Floci owns the resolvers and the data
+ * sources. This is the seam between them: the sidecar sends every field of one execution level it
+ * cannot resolve itself, Floci runs each field's resolver, and the answers become those fields'
+ * values and the {@code source} of their own children. The contract is {@code graphql/API.md} in
+ * floci-io/floci-sidecars.
+ *
+ * <p>A fixed Floci-internal route, presented to the container as an absolute URL and authorised by
+ * a per-execution bearer token rather than by AWS credentials. It sits under the {@code _floci/}
+ * namespace, with the EKS webhooks, rather than at a bare path: a bare path is reachable as a
+ * path-style S3 request for a bucket of that name, and an S3 bucket name cannot begin with an
+ * underscore, so this prefix cannot be shadowed by one.
+ */
+@Path("/_floci/appsync/resolve")
+public class ResolverCallbackResource {
+
+ private static final Logger LOG = Logger.getLogger(ResolverCallbackResource.class);
+ private static final String BEARER = "Bearer ";
+
+ private final ResolverCallbackSessions sessions;
+ private final AppSyncResolverExecutor executor;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public ResolverCallbackResource(ResolverCallbackSessions sessions,
+ AppSyncResolverExecutor executor,
+ ObjectMapper objectMapper) {
+ this.sessions = sessions;
+ this.executor = executor;
+ this.objectMapper = objectMapper;
+ }
+
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response resolve(@HeaderParam("Authorization") String authorization, String body) {
+ Optional<ResolverCallbackSessions.Session> session = sessions.find(bearerToken(authorization));
+ if (session.isEmpty()) {
+ // The sidecar turns any non-200 into a field error on exactly this batch, so an expired
+ // or forged token fails those fields rather than the whole operation.
+ return Response.status(Response.Status.UNAUTHORIZED)
+ .entity(Map.of("error", "Unknown or expired resolver callback token")).build();
+ }
+
+ JsonNode root;
+ try {
+ root = objectMapper.readTree(body == null ? "" : body);
+ } catch (Exception e) {
+ return Response.status(Response.Status.BAD_REQUEST)
+ .entity(Map.of("error", "Malformed resolver callback body")).build();
+ }
+ JsonNode invocations = root == null ? null : root.get("invocations");
+ if (invocations == null || !invocations.isArray()) {
+ return Response.status(Response.Status.BAD_REQUEST)
+ .entity(Map.of("error", "Resolver callback body is missing invocations")).build();
+ }
+
+ List<Map<String, Object>> results = new ArrayList<>();
+ for (JsonNode node : invocations) {
+ results.add(answer(session.get(), node));
+ }
+ return Response.ok(Map.of("results", results)).build();
+ }
+
+ private Map<String, Object> answer(ResolverCallbackSessions.Session session, JsonNode node) {
+ String id = node.path("id").asText();
+ ResolverInvocation invocation = invocationFrom(session, node);
+ Resolver resolver;
+ try {
+ resolver = executor.findResolver(invocation.apiId(), invocation.typeName(), invocation.fieldName());
+ } catch (AwsException e) {
+ return error(id, new AppSyncResolverError(e.getMessage(), e.getErrorCode(), null, null, null));
+ }
+ if (resolver == null) {
+ // The coordinate had a resolver when the operation was planned and does not now, which a
+ // deploy mid-operation can do. Falling back to the source property is what a GraphQL
+ // server does for a field with no resolver, so the field reads as it would have.
+ return success(id, sourceProperty(invocation));
+ }
+ ResolverOutcome outcome = executor.execute(resolver, invocation);
+ session.appendErrors(outcome.appendedErrors());
+ return outcome.failed() ? error(id, outcome.error()) : success(id, outcome.data());
+ }
+
+ private ResolverInvocation invocationFrom(ResolverCallbackSessions.Session session, JsonNode node) {
+ return new ResolverInvocation(
+ session.apiId(),
+ node.path("typeName").asText(),
+ node.path("fieldName").asText(),
+ asMap(node.get("arguments")),
+ asPlain(node.get("source")),
+ asList(node.get("path")),
+ asMap(node.get("variables")),
+ asStrings(node.get("selectionSetList")),
+ session.identity(),
+ session.authType());
+ }
+
+ /** What graphql-java's own property fetcher would have read off the parent value. */
+ private static Object sourceProperty(ResolverInvocation invocation) {
+ return invocation.source() instanceof Map<?, ?> source ? source.get(invocation.fieldName()) : null;
+ }
+
+ private static Map<String, Object> success(String id, Object data) {
+ Map<String, Object> result = new LinkedHashMap<>();
+ result.put("id", id);
+ // Deliberately a HashMap entry rather than Map.of: a resolver returning null is a valid
+ // value, and Map.of rejects it.
+ result.put("data", data);
+ return result;
+ }
+
+ private static Map<String, Object> error(String id, AppSyncResolverError raised) {
+ Map<String, Object> error = new LinkedHashMap<>();
+ error.put("message", raised.message());
+ error.put("type", raised.errorType());
+ error.put("data", raised.data());
+ error.put("info", raised.errorInfo());
+ Map<String, Object> result = new LinkedHashMap<>();
+ result.put("id", id);
+ result.put("error", error);
+ return result;
+ }
+
+ private static String bearerToken(String authorization) {
+ if (authorization == null || !authorization.regionMatches(true, 0, BEARER, 0, BEARER.length())) {
+ return null;
+ }
+ return authorization.substring(BEARER.length()).trim();
+ }
+
+ @SuppressWarnings("unchecked")
+ private Map<String, Object> asMap(JsonNode node) {
+ Object value = asPlain(node);
+ return value instanceof Map<?, ?> map ? (Map<String, Object>) map : Map.of();
+ }
+
+ @SuppressWarnings("unchecked")
+ private List<Object> asList(JsonNode node) {
+ Object value = asPlain(node);
+ return value instanceof List<?> list ? (List<Object>) list : List.of();
+ }
+
+ private List<String> asStrings(JsonNode node) {
+ List<String> values = new ArrayList<>();
+ if (node != null && node.isArray()) {
+ node.forEach(entry -> values.add(entry.asText()));
+ }
+ return values;
+ }
+
+ private Object asPlain(JsonNode node) {
+ if (node == null || node.isNull() || node.isMissingNode()) {
+ return null;
+ }
+ try {
+ return objectMapper.convertValue(node, Object.class);
+ } catch (IllegalArgumentException e) {
+ LOG.debugv(e, "Unreadable value in a resolver callback invocation");
+ return null;
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackSessions.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackSessions.java
new file mode 100644
index 0000000000..f6693033de
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackSessions.java
@@ -0,0 +1,96 @@
+package io.github.hectorvent.floci.services.appsync.graphql.resolver;
+
+import jakarta.enterprise.context.ApplicationScoped;
+
+import java.security.SecureRandom;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ * The in-flight {@code /v1/execute} calls the GraphQL sidecar may call back into.
+ *
+ * <p>A session exists only for the duration of one GraphQL operation. Its token is what the
+ * sidecar presents on the resolver callback, and it is the only thing tying a callback to the
+ * operation that authorised it: the callback endpoint is reachable from any container Floci
+ * launched, so a request carrying no live token resolves nothing.
+ */
+@ApplicationScoped
+public class ResolverCallbackSessions {
+
+ private static final int TOKEN_BYTES = 32;
+
+ private final SecureRandom random = new SecureRandom();
+ private final Map<String, Session> sessions = new ConcurrentHashMap<>();
+
+ /**
+ * One operation's callback state: who it runs as, and the errors its resolvers appended.
+ *
+ * <p>Closing it is what makes the token stop working, so callers close in a finally: a session
+ * left behind would keep answering callbacks for an operation that already returned.
+ */
+ public static final class Session implements AutoCloseable {
+ private final Map<String, Session> owner;
+ private final String token;
+ private final String apiId;
+ private final Object identity;
+ private final String authType;
+ private final List<AppSyncResolverError> appendedErrors = new CopyOnWriteArrayList<>();
+
+ private Session(Map<String, Session> owner, String token, String apiId, Object identity, String authType) {
+ this.owner = owner;
+ this.token = token;
+ this.apiId = apiId;
+ this.identity = identity;
+ this.authType = authType;
+ }
+
+ public String token() {
+ return token;
+ }
+
+ public String apiId() {
+ return apiId;
+ }
+
+ public Object identity() {
+ return identity;
+ }
+
+ public String authType() {
+ return authType;
+ }
+
+ /** Errors from {@code util.appendError}, which are reported beside the data rather than instead of it. */
+ public void appendErrors(List<AppSyncResolverError> errors) {
+ if (errors != null && !errors.isEmpty()) {
+ appendedErrors.addAll(errors);
+ }
+ }
+
+ public List<AppSyncResolverError> appendedErrors() {
+ return List.copyOf(appendedErrors);
+ }
+
+ @Override
+ public void close() {
+ owner.remove(token);
+ }
+ }
+
+ public Session open(String apiId, Object identity, String authType) {
+ byte[] bytes = new byte[TOKEN_BYTES];
+ random.nextBytes(bytes);
+ String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ Session session = new Session(sessions, token, apiId, identity, authType);
+ sessions.put(token, session);
+ return session;
+ }
+
+ public Optional<Session> find(String token) {
+ return token == null || token.isBlank() ? Optional.empty() : Optional.ofNullable(sessions.get(token));
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverInvocation.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverInvocation.java
new file mode 100644
index 0000000000..5124c2015c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverInvocation.java
@@ -0,0 +1,51 @@
+package io.github.hectorvent.floci.services.appsync.graphql.resolver;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * One field's resolution request, as the GraphQL sidecar's resolver callback describes it.
+ *
+ * <p>This is the whole of what {@link AppSyncResolverExecutor} needs to know about the GraphQL
+ * execution around a field. It used to read the same values off graphql-java's {@code
+ * DataFetchingEnvironment}, back when Floci executed the query itself; since the engine moved into
+ * the {@code floci-sidecar-graphql} container, they arrive over HTTP instead and Floci carries no
+ * graphql-java types at all.
+ *
+ * @param identity the caller's AppSync identity, or null for an auth mode that has none (API key)
+ * @param authType the AppSync auth mode name that authorised the request
+ */
+public record ResolverInvocation(String apiId, String typeName, String fieldName,
+ Map<String, Object> arguments, Object source, List<Object> path,
+ Map<String, Object> variables, List<String> selectionSetList,
+ Object identity, String authType) {
+
+ public ResolverInvocation {
+ // Normalised here rather than at each read: the callback may omit any of them, and every
+ // consumer wants the empty collection rather than a null it has to re-check.
+ arguments = copyOf(arguments);
+ variables = copyOf(variables);
+ selectionSetList = copyOf(selectionSetList);
+ path = path == null || path.isEmpty() ? List.of(fieldName) : copyOf(path);
+ }
+
+ /**
+ * Null-tolerant, unlike {@code Map.copyOf}, which rejects a null value.
+ *
+ * <p>A null argument is ordinary GraphQL: {@code getMessages(nextToken: null)} is how a client
+ * asks for the first page, and an explicit null is not the same as an absent argument to a
+ * resolver reading {@code ctx.args}. Rejecting it here failed every field in the callback batch,
+ * not just the one field that had it.
+ */
+ private static <V> Map<String, V> copyOf(Map<String, V> values) {
+ return values == null ? Map.of() : Collections.unmodifiableMap(new LinkedHashMap<>(values));
+ }
+
+ /** Null-tolerant for the same reason: a list-valued argument may carry a null element. */
+ private static <V> List<V> copyOf(List<V> values) {
+ return values == null ? List.of() : Collections.unmodifiableList(new ArrayList<>(values));
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverOutcome.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverOutcome.java
new file mode 100644
index 0000000000..5285ccc0b0
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverOutcome.java
@@ -0,0 +1,35 @@
+package io.github.hectorvent.floci.services.appsync.graphql.resolver;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * What a resolver produced for one field.
+ *
+ * <p>{@code error} set means the field failed, which is {@code util.error()} or an unsuppressed
+ * data source failure. {@code appendedErrors} is separate because {@code util.appendError} means
+ * the opposite: report these <em>and</em> keep the data. The sidecar's callback response can only
+ * say one or the other per field, so appended errors travel back to the caller instead and are
+ * merged into the response envelope by {@link ResolverCallbackResource}.
+ */
+public record ResolverOutcome(Object data, AppSyncResolverError error,
+ List<AppSyncResolverError> appendedErrors) {
+
+ public ResolverOutcome {
+ appendedErrors = appendedErrors == null ? List.of() : List.copyOf(appendedErrors);
+ }
+
+ public boolean failed() {
+ return error != null;
+ }
+
+ /** Every error on the field, appended ones first and the failing one last, the order AppSync reports. */
+ public List<AppSyncResolverError> errors() {
+ if (error == null) {
+ return appendedErrors;
+ }
+ List<AppSyncResolverError> all = new ArrayList<>(appendedErrors);
+ all.add(error);
+ return List.copyOf(all);
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index addab7015d..9934eefea7 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -55,6 +55,7 @@ quarkus:
includes:
- pricing-snapshots/**
- ui/*.html
+ - appsync/*.mjs
- ec2/*.yaml
- sagemaker/*.yaml
- eks/*.json
@@ -724,6 +725,10 @@ floci:
# graphql-url: http://floci-graphql:8181 # set to skip sidecar container management
# Exact version on purpose: a cached :latest is never re-pulled. Published from floci-io/floci-sidecars.
graphql-image: "floci/floci-sidecar-graphql:0.2.0"
+ js-runtime:
+ # The Node image that evaluates APPSYNC_JS resolver code. Pinned here rather than only in
+ # EmulatorConfig so CI can prefetch it the same way it does the sidecar pins.
+ image: "node:22-alpine"
s3vectors:
enabled: true
s3tables:
diff --git a/src/main/resources/appsync/appsync-js-runtime.mjs b/src/main/resources/appsync/appsync-js-runtime.mjs
new file mode 100644
index 0000000000..f1221f6777
--- /dev/null
+++ b/src/main/resources/appsync/appsync-js-runtime.mjs
@@ -0,0 +1,694 @@
+// Floci's APPSYNC_JS resolver runtime, run inside a Node sidecar container.
+//
+// Floci ships as a Mandrel native executable, which carries no Truffle languages, so resolver
+// JavaScript cannot be evaluated in-process. This server evaluates it in real Node instead, which
+// also means the resolver code AppSync would run is the code that runs here (ES modules,
+// `import` statements and all) rather than a rewritten approximation.
+//
+// Protocol (JSON over HTTP, one request per handler call):
+// GET /health -> {"ok":true,"runtime":"<node version>"}
+// POST /evaluate <- {"code":"<module source>","handler":"request"|"response","context":{...}}
+// -> {"ok":true,"result":<json>,"stash":{...},"earlyReturn":<bool>,"errors":[...]}
+// -> {"ok":false,"error":{"message","type","data","errorInfo","stack"}}
+//
+// Resolver modules are written to disk under a content hash and imported, so Node's own module
+// cache compiles each distinct resolver once. `@aws-appsync/utils` resolves to the shim written
+// below: a bare specifier inside a module can only resolve through node_modules, so the resolver
+// directory sits beneath one.
+import http from 'node:http';
+import fs from 'node:fs';
+import path from 'node:path';
+import crypto from 'node:crypto';
+import { pathToFileURL } from 'node:url';
+import { registerHooks } from 'node:module';
+
+const PORT = Number(process.env.FLOCI_JS_RUNTIME_PORT || 4600);
+const ROOT = process.env.FLOCI_JS_RUNTIME_DIR || '/tmp/floci-appsync';
+const RESOLVER_DIR = path.join(ROOT, 'resolvers');
+const UTILS_DIR = path.join(ROOT, 'node_modules', '@aws-appsync', 'utils');
+
+// ── @aws-appsync/utils ───────────────────────────────────────────────────────
+// Deliberately a shim rather than the published package: pulling from npm would make a resolver
+// call depend on registry access, and Floci has to work offline. Everything AppSync's JS resolvers
+// reach for in practice is here; anything missing throws by name rather than returning undefined,
+// so a gap shows up as a clear error instead of a null field.
+
+// NOTE: UTILS_INDEX and UTILS_RDS below are template literals, so a backtick or a ${ inside them
+// - in code *or in a comment* - ends the string and the sidecar fails to boot with a SyntaxError.
+// Escape them (\` and \${) or write around them.
+const UTILS_INDEX = `
+import { randomUUID } from 'node:crypto';
+const ERROR_MARKER = Symbol.for('floci.appsync.error');
+const RETURN_MARKER = Symbol.for('floci.appsync.earlyReturn');
+
+export const appendedErrors = [];
+export function resetAppendedErrors() { appendedErrors.length = 0; }
+
+class TemplateError extends Error {
+ constructor(message, type, data, errorInfo) {
+ super(message);
+ this[ERROR_MARKER] = true;
+ this.errorType = type ?? null;
+ this.errorData = data ?? null;
+ this.errorInfo = errorInfo ?? null;
+ }
+}
+
+class EarlyReturn extends Error {
+ constructor(value) {
+ super('early return');
+ this[RETURN_MARKER] = true;
+ this.value = value ?? null;
+ }
+}
+
+const pad = (n, width = 2) => String(n).padStart(width, '0');
+
+const toDynamoDB = (value) => {
+ if (value === null || value === undefined) return { NULL: true };
+ if (typeof value === 'string') return { S: value };
+ if (typeof value === 'number') return { N: String(value) };
+ if (typeof value === 'boolean') return { BOOL: value };
+ if (Array.isArray(value)) return { L: value.map(toDynamoDB) };
+ if (typeof value === 'object') {
+ const m = {};
+ for (const [k, v] of Object.entries(value)) m[k] = toDynamoDB(v);
+ return { M: m };
+ }
+ return { S: String(value) };
+};
+
+const fromDynamoDB = (value) => {
+ if (value === null || value === undefined) return null;
+ if ('NULL' in value) return null;
+ if ('S' in value) return value.S;
+ if ('N' in value) return Number(value.N);
+ if ('BOOL' in value) return value.BOOL;
+ if ('L' in value) return value.L.map(fromDynamoDB);
+ if ('M' in value) {
+ const out = {};
+ for (const [k, v] of Object.entries(value.M)) out[k] = fromDynamoDB(v);
+ return out;
+ }
+ if ('SS' in value) return value.SS;
+ if ('NS' in value) return value.NS.map(Number);
+ return null;
+};
+
+const unsupported = (name) => () => {
+ throw new TemplateError(\`util.\${name} is not implemented by Floci's AppSync JS runtime\`,
+ 'FlociUnsupported');
+};
+
+export const util = {
+ error(message, type, data, errorInfo) { throw new TemplateError(message, type, data, errorInfo); },
+ appendError(message, type, data, errorInfo) {
+ // The member is named type, matching what describeError() reports for util.error. Naming it
+ // errorType here instead silently dropped the type off every appended error on its way to Java.
+ appendedErrors.push({ message, type: type ?? null, data: data ?? null, errorInfo: errorInfo ?? null });
+ },
+ unauthorized() { throw new TemplateError('Unauthorized', 'Unauthorized'); },
+ autoId() { return randomUUID(); },
+ autoUlid: unsupported('autoUlid'),
+ autoKsuid: unsupported('autoKsuid'),
+ matches(pattern, value) { return new RegExp(pattern).test(String(value)); },
+ authType() { return globalThis.__floci_authType ?? null; },
+ escapeJavaScript(v) { return String(v).replace(/[\\\\"']/g, (m) => '\\\\' + m); },
+ urlEncode(v) { return encodeURIComponent(String(v)); },
+ urlDecode(v) { return decodeURIComponent(String(v)); },
+ base64Encode(v) { return Buffer.from(v).toString('base64'); },
+ base64Decode(v) { return Buffer.from(v, 'base64').toString('utf8'); },
+ parseJson(v) { try { return typeof v === 'string' ? JSON.parse(v) : v; } catch { return null; } },
+ toJson(v) { return JSON.stringify(v); },
+ isNull(v) { return v === null || v === undefined; },
+ isNullOrEmpty(v) { return v === null || v === undefined || v === ''; },
+ isNullOrBlank(v) { return v === null || v === undefined || String(v).trim() === ''; },
+ defaultIfNull(v, d) { return v === null || v === undefined ? d : v; },
+ defaultIfNullOrEmpty(v, d) { return v === null || v === undefined || v === '' ? d : v; },
+ isString(v) { return typeof v === 'string'; },
+ isNumber(v) { return typeof v === 'number'; },
+ isBoolean(v) { return typeof v === 'boolean'; },
+ isList(v) { return Array.isArray(v); },
+ isMap(v) { return v !== null && typeof v === 'object' && !Array.isArray(v); },
+ typeOf(v) {
+ if (v === null || v === undefined) return 'Null';
+ if (Array.isArray(v)) return 'List';
+ switch (typeof v) {
+ case 'string': return 'String';
+ case 'number': return 'Number';
+ case 'boolean': return 'Boolean';
+ default: return 'Map';
+ }
+ },
+ time: {
+ nowISO8601() { return new Date().toISOString(); },
+ nowEpochSeconds() { return Math.floor(Date.now() / 1000); },
+ nowEpochMilliSeconds() { return Date.now(); },
+ nowFormatted(format) {
+ const d = new Date();
+ return String(format)
+ .replace('yyyy', String(d.getUTCFullYear()))
+ .replace('MM', pad(d.getUTCMonth() + 1))
+ .replace('dd', pad(d.getUTCDate()))
+ .replace('HH', pad(d.getUTCHours()))
+ .replace('mm', pad(d.getUTCMinutes()))
+ .replace('ss', pad(d.getUTCSeconds()));
+ },
+ epochMilliSecondsToISO8601(ms) { return new Date(Number(ms)).toISOString(); },
+ epochMilliSecondsToSeconds(ms) { return Math.floor(Number(ms) / 1000); },
+ epochSecondsToISO8601(s) { return new Date(Number(s) * 1000).toISOString(); },
+ parseISO8601ToEpochMilliSeconds(iso) { return new Date(iso).getTime(); }
+ },
+ dynamodb: {
+ toDynamoDB,
+ fromDynamoDB,
+ toString: (v) => ({ S: String(v) }),
+ toStringSet: (v) => ({ SS: v.map(String) }),
+ toNumber: (v) => ({ N: String(v) }),
+ toNumberSet: (v) => ({ NS: v.map(String) }),
+ toBinary: (v) => ({ B: v }),
+ toBoolean: (v) => ({ BOOL: Boolean(v) }),
+ toNull: () => ({ NULL: true }),
+ toList: (v) => ({ L: v.map(toDynamoDB) }),
+ toMap: (v) => toDynamoDB(v),
+ toMapValues(values) {
+ const out = {};
+ for (const [k, v] of Object.entries(values)) out[k] = toDynamoDB(v);
+ return out;
+ }
+ },
+ transform: {
+ toDynamoDBFilterExpression: unsupported('transform.toDynamoDBFilterExpression'),
+ toElasticsearchQueryDSL: unsupported('transform.toElasticsearchQueryDSL')
+ },
+ str: {
+ normalize: (v) => String(v).normalize(),
+ toUpper: (v) => String(v).toUpperCase(),
+ toLower: (v) => String(v).toLowerCase()
+ }
+};
+
+export const runtime = {
+ earlyReturn(value) { throw new EarlyReturn(value); }
+};
+
+export const extensions = {
+ evictFromApiCache() { return {}; },
+ setSubscriptionFilter() { return {}; },
+ setSubscriptionInvalidationFilter() { return {}; },
+ invalidateSubscriptions() { return {}; }
+};
+
+export default { util, runtime, extensions };
+`;
+
+// The RDS helpers. `toJsonObject` is the one every relational resolver ends with: it turns the
+// rds-data ExecuteStatement response into plain row objects, keyed by column label.
+const UTILS_RDS = `
+const scalar = (field) => {
+ if (field === null || field === undefined) return null;
+ if (field.isNull) return null;
+ if ('stringValue' in field) return field.stringValue;
+ if ('longValue' in field) return field.longValue;
+ if ('doubleValue' in field) return field.doubleValue;
+ if ('booleanValue' in field) return field.booleanValue;
+ if ('blobValue' in field) return field.blobValue;
+ if ('arrayValue' in field) {
+ const array = field.arrayValue ?? {};
+ for (const key of ['stringValues', 'longValues', 'doubleValues', 'booleanValues']) {
+ if (key in array) return array[key];
+ }
+ return [];
+ }
+ return null;
+};
+
+export function toJsonObject(result) {
+ const parsed = typeof result === 'string' ? JSON.parse(result) : result;
+ const statements = parsed?.sqlStatementResults ?? [];
+ return statements.map((statement) => {
+ const columns = statement.columnMetadata ?? [];
+ return (statement.records ?? []).map((record) => {
+ const row = {};
+ record.forEach((field, index) => {
+ const column = columns[index] ?? {};
+ row[column.label ?? column.name ?? String(index)] = scalar(field);
+ });
+ return row;
+ });
+ });
+}
+
+export const typeHint = {
+ DATE: 'DATE', DECIMAL: 'DECIMAL', JSON: 'JSON', TIME: 'TIME',
+ TIMESTAMP: 'TIMESTAMP', UUID: 'UUID'
+};
+
+const quoteIdentifier = (name) => '"' + String(name).replace(/"/g, '""') + '"';
+
+/** Tagged template: sql\`select * from t where id = \${id}\` -> a parameterised statement. */
+export function sql(strings, ...values) {
+ let statement = '';
+ const parameters = [];
+ strings.forEach((chunk, index) => {
+ statement += chunk;
+ if (index < values.length) {
+ parameters.push(values[index]);
+ statement += ':param' + parameters.length;
+ }
+ });
+ return { statement, parameters };
+}
+
+const whereClause = (where, parameters) => {
+ if (!where || Object.keys(where).length === 0) return '';
+ const clauses = [];
+ for (const [column, condition] of Object.entries(where)) {
+ if (condition === null || typeof condition !== 'object') {
+ parameters.push(condition);
+ clauses.push(quoteIdentifier(column) + ' = :param' + parameters.length);
+ continue;
+ }
+ for (const [operator, operand] of Object.entries(condition)) {
+ const sqlOperator = {
+ eq: '=', ne: '<>', gt: '>', ge: '>=', lt: '<', le: '<=',
+ contains: 'LIKE', beginsWith: 'LIKE'
+ }[operator];
+ if (!sqlOperator) {
+ throw new Error('unsupported where operator: ' + operator);
+ }
+ let value = operand;
+ if (operator === 'contains') value = '%' + operand + '%';
+ if (operator === 'beginsWith') value = operand + '%';
+ parameters.push(value);
+ clauses.push(quoteIdentifier(column) + ' ' + sqlOperator + ' :param' + parameters.length);
+ }
+ }
+ return ' WHERE ' + clauses.join(' AND ');
+};
+
+export function select({ table, columns, where, limit, offset, orderBy } = {}) {
+ const parameters = [];
+ const projection = columns && columns.length ? columns.map(quoteIdentifier).join(', ') : '*';
+ let statement = 'SELECT ' + projection + ' FROM ' + quoteIdentifier(table) + whereClause(where, parameters);
+ if (orderBy && orderBy.length) {
+ statement += ' ORDER BY ' + orderBy
+ .map((o) => quoteIdentifier(o.column) + (o.dir ? ' ' + o.dir : ''))
+ .join(', ');
+ }
+ if (limit !== undefined && limit !== null) statement += ' LIMIT ' + Number(limit);
+ if (offset !== undefined && offset !== null) statement += ' OFFSET ' + Number(offset);
+ return { statement, parameters };
+}
+
+export function insert({ table, values } = {}) {
+ const parameters = [];
+ const columns = Object.keys(values ?? {});
+ const placeholders = columns.map((column) => {
+ parameters.push(values[column]);
+ return ':param' + parameters.length;
+ });
+ return {
+ statement: 'INSERT INTO ' + quoteIdentifier(table) + ' (' + columns.map(quoteIdentifier).join(', ')
+ + ') VALUES (' + placeholders.join(', ') + ')',
+ parameters
+ };
+}
+
+export function update({ table, values, where } = {}) {
+ const parameters = [];
+ const assignments = Object.keys(values ?? {}).map((column) => {
+ parameters.push(values[column]);
+ return quoteIdentifier(column) + ' = :param' + parameters.length;
+ });
+ return {
+ statement: 'UPDATE ' + quoteIdentifier(table) + ' SET ' + assignments.join(', ')
+ + whereClause(where, parameters),
+ parameters
+ };
+}
+
+export function remove({ table, where } = {}) {
+ const parameters = [];
+ return {
+ statement: 'DELETE FROM ' + quoteIdentifier(table) + whereClause(where, parameters),
+ parameters
+ };
+}
+
+export function createPgStatement(...statements) {
+ return statements.map((s) => (typeof s === 'string' ? { statement: s, parameters: [] } : s));
+}
+
+export const createMySQLStatement = createPgStatement;
+`;
+
+// @aws-appsync/utils/dynamodb. The helpers take plain values and build the request objects the
+// DynamoDB data source understands, marshalling keys and items on the way. get, put and remove are
+// implemented; the ones that compile a condition or update expression are not, and say so by name
+// rather than returning something the data source would silently mishandle.
+const UTILS_DDB = `
+import { util } from './index.mjs';
+
+const marshal = (value) => util.dynamodb.toMapValues(value ?? {});
+
+const notImplemented = (name) => () => {
+ throw new Error('@aws-appsync/utils/dynamodb.' + name + ' is not implemented by the AppSync '
+ + 'runtime shim in Floci; build the request object by hand for now.');
+};
+
+export function get(request) {
+ const built = { operation: 'GetItem', key: marshal(request.key) };
+ if (request.consistentRead !== undefined) built.consistentRead = request.consistentRead;
+ if (request.projection !== undefined) built.projection = request.projection;
+ return built;
+}
+
+export function put(request) {
+ const built = {
+ operation: 'PutItem',
+ key: marshal(request.key),
+ attributeValues: marshal(request.item)
+ };
+ if (request.condition !== undefined) built.condition = request.condition;
+ return built;
+}
+
+export function remove(request) {
+ const built = { operation: 'DeleteItem', key: marshal(request.key) };
+ if (request.condition !== undefined) built.condition = request.condition;
+ return built;
+}
+
+export const update = notImplemented('update');
+export const scan = notImplemented('scan');
+export const query = notImplemented('query');
+export const sync = notImplemented('sync');
+export const operations = new Proxy({}, {
+ get: (target, name) => notImplemented('operations.' + String(name))
+});
+`;
+
+const UTILS_PACKAGE_JSON = JSON.stringify({
+ name: '@aws-appsync/utils',
+ version: '1.0.0-floci',
+ type: 'module',
+ main: './index.mjs',
+ exports: {
+ '.': './index.mjs',
+ './rds': './rds.mjs',
+ './dynamodb': './dynamodb.mjs'
+ }
+}, null, 2);
+
+fs.mkdirSync(UTILS_DIR, { recursive: true });
+fs.mkdirSync(RESOLVER_DIR, { recursive: true });
+fs.writeFileSync(path.join(UTILS_DIR, 'package.json'), UTILS_PACKAGE_JSON);
+fs.writeFileSync(path.join(UTILS_DIR, 'index.mjs'), UTILS_INDEX);
+fs.writeFileSync(path.join(UTILS_DIR, 'rds.mjs'), UTILS_RDS);
+fs.writeFileSync(path.join(UTILS_DIR, 'dynamodb.mjs'), UTILS_DDB);
+
+// APPSYNC_JS has no filesystem or network access, and resolver code can import nothing but
+// @aws-appsync/utils. A resolve hook enforces that: it sees static and dynamic imports alike, so a
+// dynamic import of a Node builtin cannot slip past a source scan. Imports made by the shim itself
+// still resolve, because there the parent URL is the shim rather than a resolver.
+const RESOLVER_URL_PREFIX = pathToFileURL(RESOLVER_DIR).href;
+const ALLOWED_SPECIFIERS = new Set([
+ '@aws-appsync/utils', '@aws-appsync/utils/rds', '@aws-appsync/utils/dynamodb'
+]);
+
+registerHooks({
+ resolve(specifier, context, nextResolve) {
+ const parent = context.parentURL ?? '';
+ if (parent.startsWith(RESOLVER_URL_PREFIX) && !ALLOWED_SPECIFIERS.has(specifier)) {
+ throw Object.assign(
+ new Error('Unsupported import "' + specifier + '". APPSYNC_JS resolvers run without '
+ + 'filesystem or network access and can import only @aws-appsync/utils.'),
+ { flociUnsupported: true });
+ }
+ return nextResolve(specifier, context);
+ }
+});
+
+// AWS documents APPSYNC_JS as a restricted JavaScript runtime rather than Node. Evaluating resolver
+// code as ordinary Node would accept modules that cannot deploy, which is the worst thing an
+// emulator can do: green-light code that fails in production. These are the constructs AWS lists as
+// unavailable. Recursion is unavailable too and is not detectable lexically, so it is not checked.
+const BANNED_CONSTRUCTS = [
+ [/(?<![.\w$])class(?![\w$])/, 'class declarations'],
+ [/(?<![.\w$])while(?![\w$])/, 'while loops'],
+ [/(?<![.\w$])do(?![\w$])/, 'do...while loops'],
+ [/(?<![.\w$])try(?![\w$])/, 'try/catch'],
+ [/(?<![.\w$])catch(?![\w$])/, 'try/catch'],
+ [/(?<![.\w$])finally(?![\w$])/, 'try/catch/finally'],
+ [/(?<![.\w$])throw(?![\w$])/, 'throw, use util.error instead'],
+ [/(?<![.\w$])yield(?![\w$])/, 'generators'],
+ [/(?<![.\w$])function\s*\*/, 'generators'],
+ [/(?<![.\w$])async(?![\w$])/, 'async functions'],
+ [/(?<![.\w$])await(?![\w$])/, 'await'],
+ [/(?<![.\w$])this(?![\w$])/, 'this'],
+ [/(?<![.\w$])with\s*\(/, 'with statements'],
+ [/(?<![.\w$])eval\s*\(/, 'eval'],
+ [/(?<![.\w$])debugger(?![\w$])/, 'debugger'],
+ [/(?<![.\w$])require\s*\(/, 'require, modules are ES modules'],
+ [/(?<![.\w$])Promise(?![\w$])/, 'promises']
+];
+
+// Replaces the contents of comments, strings, template text and regex literals with spaces, so a
+// keyword inside one is not mistaken for code. Offsets are preserved, which keeps line numbers
+// honest. Expressions inside a template hole stay as code, because that is what they are.
+function blankLiterals(src) {
+ const out = src.split('');
+ const blank = (from, to) => {
+ for (let i = from; i < to && i < out.length; i++) {
+ if (out[i] !== '\n') out[i] = ' ';
+ }
+ };
+ let i = 0;
+ while (i < src.length) {
+ const c = src[i];
+ const next = src[i + 1];
+ if (c === '/' && next === '/') {
+ const end = src.indexOf('\n', i);
+ const stop = end === -1 ? src.length : end;
+ blank(i, stop);
+ i = stop;
+ continue;
+ }
+ if (c === '/' && next === '*') {
+ const end = src.indexOf('*/', i + 2);
+ const stop = end === -1 ? src.length : end + 2;
+ blank(i, stop);
+ i = stop;
+ continue;
+ }
+ if (c === "'" || c === '"') {
+ let j = i + 1;
+ while (j < src.length && src[j] !== c) {
+ if (src[j] === '\\') j++;
+ j++;
+ }
+ blank(i + 1, j);
+ i = j + 1;
+ continue;
+ }
+ if (c === String.fromCharCode(96)) {
+ i++;
+ let j = i;
+ while (j < src.length) {
+ if (src[j] === '\\') { j += 2; continue; }
+ if (src[j] === String.fromCharCode(96)) { blank(i, j); i = j + 1; break; }
+ if (src[j] === '$' && src[j + 1] === '{') { blank(i, j); i = j + 2; break; }
+ j++;
+ }
+ if (j >= src.length) { blank(i, src.length); i = src.length; }
+ continue;
+ }
+ i++;
+ }
+ return out.join('');
+}
+
+function validateAppSyncSubset(code) {
+ const scanned = blankLiterals(code);
+ for (const [pattern, description] of BANNED_CONSTRUCTS) {
+ const match = pattern.exec(scanned);
+ if (match) {
+ const line = code.slice(0, match.index).split('\n').length;
+ return {
+ message: 'Unsupported in the APPSYNC_JS runtime: ' + description + ' (line ' + line
+ + '). AWS runs resolvers on a restricted JavaScript runtime, not Node, so this code '
+ + 'would be rejected on deploy.',
+ type: 'UnsupportedFeature'
+ };
+ }
+ }
+ return null;
+}
+
+
+const ERROR_MARKER = Symbol.for('floci.appsync.error');
+const RETURN_MARKER = Symbol.for('floci.appsync.earlyReturn');
+const utilsModule = await import(pathToFileURL(path.join(UTILS_DIR, 'index.mjs')).href);
+
+/** Writes the module once per distinct source and lets Node's module cache do the rest. */
+async function loadResolver(code) {
+ const hash = crypto.createHash('sha256').update(code).digest('hex');
+ const file = path.join(RESOLVER_DIR, hash + '.mjs');
+ if (!fs.existsSync(file)) {
+ fs.writeFileSync(file, code);
+ }
+ return import(pathToFileURL(file).href);
+}
+
+function describeError(error) {
+ if (error && error[RETURN_MARKER]) {
+ return null;
+ }
+ if (error && error[ERROR_MARKER]) {
+ return {
+ message: error.message,
+ type: error.errorType,
+ data: error.errorData,
+ errorInfo: error.errorInfo,
+ stack: null
+ };
+ }
+ if (error && error.flociUnsupported) {
+ return { message: error.message, type: 'UnsupportedFeature', data: null, errorInfo: null,
+ stack: null };
+ }
+ return {
+ message: error?.message ?? String(error),
+ type: error?.name ?? 'Error',
+ data: null,
+ errorInfo: null,
+ stack: error?.stack ?? null
+ };
+}
+
+async function evaluate(body) {
+ const { code, handler, context, enforceSubset } = body;
+ if (typeof code !== 'string' || !code.trim()) {
+ return { ok: false, error: { message: 'no resolver code supplied', type: 'FlociBadRequest' } };
+ }
+ if (enforceSubset !== false) {
+ const unsupported = validateAppSyncSubset(code);
+ if (unsupported) {
+ return { ok: false, error: { ...unsupported, data: null, errorInfo: null, stack: null } };
+ }
+ }
+ const module = await loadResolver(code);
+ const fn = module[handler];
+ if (typeof fn !== 'function') {
+ // A resolver with no response handler is legal in AppSync only for the request side, so this
+ // is reported rather than treated as a no-op: the caller decides what a missing handler means.
+ return { ok: false, missingHandler: true,
+ error: { message: 'resolver module exports no ' + handler + '() function', type: 'FlociMissingHandler' } };
+ }
+
+ utilsModule.resetAppendedErrors();
+ const ctx = { ...context };
+ ctx.stash = ctx.stash ?? {};
+ // AppSync exposes both spellings, on the same object: a resolver that writes ctx.args sees it
+ // in ctx.arguments too.
+ ctx.args = ctx.arguments = ctx.arguments ?? ctx.args ?? {};
+ globalThis.__floci_authType = context?.request?.authType ?? null;
+
+ if (fn.constructor && fn.constructor.name === 'AsyncFunction') {
+ return { ok: false, error: {
+ message: 'Unsupported in the APPSYNC_JS runtime: ' + handler + '() is an async function. '
+ + 'AWS runs resolvers on a restricted JavaScript runtime with no async support, so this '
+ + 'code would be rejected on deploy.',
+ type: 'UnsupportedFeature', data: null, errorInfo: null, stack: null } };
+ }
+
+ try {
+ // Called without await: a handler that hands back a thenable is doing something the AppSync
+ // runtime cannot, and awaiting it here would hide that.
+ const result = fn(ctx, utilsModule.util, utilsModule.runtime);
+ if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
+ return { ok: false, error: {
+ message: 'Unsupported in the APPSYNC_JS runtime: ' + handler + '() returned a promise. '
+ + 'AWS runs resolvers on a restricted JavaScript runtime with no promise support.',
+ type: 'UnsupportedFeature', data: null, errorInfo: null, stack: null } };
+ }
+ return {
+ ok: true,
+ result: result === undefined ? null : result,
+ stash: ctx.stash,
+ earlyReturn: false,
+ errors: [...utilsModule.appendedErrors]
+ };
+ } catch (error) {
+ if (error && error[RETURN_MARKER]) {
+ return {
+ ok: true,
+ result: error.value,
+ stash: ctx.stash,
+ earlyReturn: true,
+ errors: [...utilsModule.appendedErrors]
+ };
+ }
+ return { ok: false, error: describeError(error), stash: ctx.stash,
+ errors: [...utilsModule.appendedErrors] };
+ }
+}
+
+// Evaluations run one at a time. util.appendError collects into a module-level array and
+// util.authType reads a global, so two evaluations interleaving at an await inside an async
+// resolver would mix one's errors and auth type into the other. Serialising costs nothing here (handlers
+// are short) and removes the whole class of cross-talk.
+let queue = Promise.resolve();
+const evaluateSerially = (body) => {
+ const next = queue.then(() => evaluate(body), () => evaluate(body));
+ // Keep the chain alive whatever this evaluation does, so one rejection cannot wedge the server.
+ queue = next.then(() => undefined, () => undefined);
+ return next;
+};
+
+// AppSync caps resolver code at 32 KB, so this is far above anything legitimate; it exists so a
+// runaway or malformed request cannot grow the sidecar's heap without bound.
+const MAX_BODY_BYTES = 5 * 1024 * 1024;
+
+const readBody = (req) => new Promise((resolve, reject) => {
+ const chunks = [];
+ let size = 0;
+ req.on('data', (chunk) => {
+ size += chunk.length;
+ if (size > MAX_BODY_BYTES) {
+ reject(Object.assign(new Error('request body exceeds ' + MAX_BODY_BYTES + ' bytes'),
+ { status: 413 }));
+ req.destroy();
+ return;
+ }
+ chunks.push(chunk);
+ });
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
+ req.on('error', reject);
+});
+
+const send = (res, status, payload) => {
+ const body = JSON.stringify(payload);
+ res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) });
+ res.end(body);
+};
+
+http.createServer(async (req, res) => {
+ try {
+ if (req.method === 'GET' && req.url === '/health') {
+ send(res, 200, { ok: true, runtime: process.version });
+ return;
+ }
+ if (req.method === 'POST' && req.url === '/evaluate') {
+ const body = JSON.parse(await readBody(req));
+ send(res, 200, await evaluateSerially(body));
+ return;
+ }
+ send(res, 404, { ok: false, error: { message: 'not found', type: 'FlociBadRequest' } });
+ } catch (error) {
+ send(res, error.status === 413 ? 413 : 200, { ok: false, error: describeError(error) });
+ }
+}).listen(PORT, '0.0.0.0', () => {
+ console.log('floci appsync js runtime listening on ' + PORT + ' (node ' + process.version + ')');
+});
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncJsResolverDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncJsResolverDockerIntegrationTest.java
new file mode 100644
index 0000000000..9689bd3ec3
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncJsResolverDockerIntegrationTest.java
@@ -0,0 +1,436 @@
+package io.github.hectorvent.floci.services.appsync;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.awaitility.Awaitility.await;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
+
+/**
+ * Executes real {@code APPSYNC_JS} resolvers end to end: a GraphQL query over HTTP, out to the
+ * GraphQL sidecar, back through Floci's resolver callback, then the pipeline and the Node sidecar.
+ *
+ * <p>Everything here runs the resolver code as written, the {@code @aws-appsync/utils} imports
+ * included, so it is the test that says whether an AppSync API deployed into Floci answers
+ * queries rather than nulls. A {@code NONE} data source keeps the assertions about the pipeline
+ * itself; the data-source adapters have their own tests.
+ *
+ * <p>Needs Docker for both sidecars, and skips without it.
+ */
+@QuarkusTest
+@TestProfile(AppSyncResolverCallbackProfile.class)
+class AppSyncJsResolverDockerIntegrationTest {
+
+ private static final String AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request";
+
+ private static final String SCHEMA = """
+ type Message { id: ID! name: String }
+ type Query {
+ getMessages(orgNo: String!): [Message]
+ ping(x: String): String
+ echoArg(x: String): String
+ failing: String
+ warned: String
+ asyncResolver: String
+ importsNode: String
+ loops: String
+ keywordsInText: String
+ }
+ """;
+
+ /** The before step's only job is to stash what the functions need, as a pipeline usually does. */
+ private static final String PIPELINE_RESOLVER = """
+ export function request(ctx) {
+ ctx.stash.orgNo = ctx.args.orgNo;
+ return {};
+ }
+ export function response(ctx) {
+ return ctx.prev.result;
+ }
+ """;
+
+ private static final String PIPELINE_FUNCTION = """
+ import { util } from "@aws-appsync/utils";
+ export function request(ctx) {
+ if (!ctx.stash.orgNo) {
+ util.error("the before step did not stash orgNo", "BadRequest");
+ }
+ return { payload: [
+ { id: "1", name: "Acme " + ctx.stash.orgNo },
+ { id: "2", name: "Globex" }
+ ] };
+ }
+ export function response(ctx) {
+ return ctx.result;
+ }
+ """;
+
+ private static final String UNIT_RESOLVER = """
+ import { util } from "@aws-appsync/utils";
+ export function request(ctx) {
+ return { payload: { value: "pong", at: util.time.nowISO8601() } };
+ }
+ export function response(ctx) {
+ return ctx.result.value;
+ }
+ """;
+
+ /** Reports back what reached ctx.args, so an explicit null is distinguishable from an absent one. */
+ private static final String ECHO_ARG_RESOLVER = """
+ import { util } from "@aws-appsync/utils";
+ export function request(ctx) {
+ return { payload: { count: Object.keys(ctx.args).length, value: ctx.args.x } };
+ }
+ export function response(ctx) {
+ return "count=" + ctx.result.count + " value=" + util.toJson(ctx.result.value);
+ }
+ """;
+
+ /** Appends an error and still returns data: AppSync reports both. */
+ private static final String WARNING_RESOLVER = """
+ import { util } from "@aws-appsync/utils";
+ export function request(ctx) {
+ return { payload: { value: "partial" } };
+ }
+ export function response(ctx) {
+ util.appendError("one row was dropped", "Partial");
+ return ctx.result.value;
+ }
+ """;
+
+ private static final String FAILING_RESOLVER = """
+ import { util } from "@aws-appsync/utils";
+ export function request(ctx) {
+ util.error("orgNo is required", "BadRequest", { field: "orgNo" });
+ }
+ export function response(ctx) {
+ return ctx.result;
+ }
+ """;
+
+ /** Valid on Node, rejected by AWS: the runtime has no async support. */
+ private static final String ASYNC_RESOLVER = """
+ export async function request(ctx) {
+ return { payload: { value: "nope" } };
+ }
+ export function response(ctx) {
+ return ctx.result.value;
+ }
+ """;
+
+ /** APPSYNC_JS resolvers have no filesystem or network access. */
+ private static final String NODE_IMPORT_RESOLVER = """
+ import fs from "node:fs";
+ export function request(ctx) {
+ return { payload: { value: fs.readdirSync("/").length } };
+ }
+ export function response(ctx) {
+ return ctx.result.value;
+ }
+ """;
+
+ private static final String WHILE_RESOLVER = """
+ export function request(ctx) {
+ let i = 0;
+ while (i < 3) { i = i + 1; }
+ return { payload: { value: String(i) } };
+ }
+ export function response(ctx) {
+ return ctx.result.value;
+ }
+ """;
+
+ /** The same keywords, but only inside a string, a comment and a template: still valid. */
+ private static final String KEYWORDS_IN_TEXT_RESOLVER = """
+ export function request(ctx) {
+ // class while try throw async await this
+ const whileActive = "try catch class while";
+ return { payload: { value: `${whileActive} ok` } };
+ }
+ export function response(ctx) {
+ return ctx.result.value;
+ }
+ """;
+
+ private String apiId;
+ private String apiKey;
+
+ @BeforeAll
+ static void configure() {
+ AppSyncGraphqlSidecarProfile.requireDockerAndTheSidecarImage();
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @BeforeEach
+ void deployApi() {
+ apiId = createApi("js-" + UUID.randomUUID().toString().substring(0, 8));
+ apiKey = createApiKey(apiId);
+ startSchema(apiId, SCHEMA);
+ awaitSchemaSuccess(apiId);
+ createNoneDataSource(apiId, "local");
+
+ String functionId = createFunction(apiId, "Query_getMessages_0", "local", PIPELINE_FUNCTION);
+ createPipelineResolver(apiId, "Query", "getMessages", PIPELINE_RESOLVER, functionId);
+ createUnitResolver(apiId, "Query", "ping", "local", UNIT_RESOLVER);
+ createUnitResolver(apiId, "Query", "echoArg", "local", ECHO_ARG_RESOLVER);
+ createUnitResolver(apiId, "Query", "failing", "local", FAILING_RESOLVER);
+ createUnitResolver(apiId, "Query", "warned", "local", WARNING_RESOLVER);
+ createUnitResolver(apiId, "Query", "asyncResolver", "local", ASYNC_RESOLVER);
+ createUnitResolver(apiId, "Query", "importsNode", "local", NODE_IMPORT_RESOLVER);
+ createUnitResolver(apiId, "Query", "loops", "local", WHILE_RESOLVER);
+ createUnitResolver(apiId, "Query", "keywordsInText", "local", KEYWORDS_IN_TEXT_RESOLVER);
+ }
+
+ @Test
+ void aPipelineResolverAnswersWithItsFunctionsData() {
+ query("{ getMessages(orgNo: \\\"556677\\\") { id name } }")
+ .statusCode(200)
+ .body("errors", nullValue())
+ .body("data.getMessages", hasSize(2))
+ // The before step stashed orgNo and the function read it: the value proves the whole
+ // chain ran, not just that something returned.
+ .body("data.getMessages.name", contains("Acme 556677", "Globex"))
+ .body("data.getMessages.id", contains("1", "2"));
+ }
+
+ @Test
+ void aUnitResolverRunsRequestAndResponseAroundItsDataSource() {
+ query("{ ping }")
+ .statusCode(200)
+ .body("errors", nullValue())
+ .body("data.ping", equalTo("pong"));
+ }
+
+ @Test
+ void anExplicitNullArgumentReachesTheResolverInsteadOfFailingTheBatch() {
+ // nextToken: null is ordinary GraphQL, and an explicit null is not the same as an absent
+ // argument to a resolver reading ctx.args. It also has to survive the callback: one null
+ // used to fail every field in that batch, not only the field carrying it.
+ query("{ ping(x: null) }")
+ .statusCode(200)
+ .body("errors", nullValue())
+ .body("data.ping", equalTo("pong"));
+
+ query("{ echoArg(x: null) }")
+ .statusCode(200)
+ .body("errors", nullValue())
+ .body("data.echoArg", equalTo("count=1 value=null"));
+
+ // The contrast that matters: an absent argument is not in ctx.args at all, where an explicit
+ // null is present and null. Only the count is asserted, since the value of an absent
+ // argument is JavaScript's undefined and how that renders is not this test's subject.
+ query("{ echoArg }")
+ .statusCode(200)
+ .body("errors", nullValue())
+ .body("data.echoArg", containsString("count=0"));
+ }
+
+ @Test
+ void utilErrorBecomesAGraphqlErrorCarryingItsErrorType() {
+ query("{ failing }")
+ .statusCode(200)
+ .body("data.failing", nullValue())
+ .body("errors", hasSize(1))
+ .body("errors[0].message", equalTo("orgNo is required"))
+ // AppSync reports these on the error itself, not under extensions, and clients switch
+ // on errorType.
+ .body("errors[0].errorType", equalTo("BadRequest"))
+ .body("errors[0].data.field", equalTo("orgNo"));
+ }
+
+ @Test
+ void utilAppendErrorReturnsTheErrorBesideTheDataWithItsType() {
+ query("{ warned }")
+ .statusCode(200)
+ // appendError is the one that stops nothing: the field keeps its value.
+ .body("data.warned", equalTo("partial"))
+ .body("errors", hasSize(1))
+ .body("errors[0].message", equalTo("one row was dropped"))
+ // The shim and the Java bridge have to agree on the member carrying the type, or it is
+ // dropped on the way out and every appended error arrives untyped.
+ .body("errors[0].errorType", equalTo("Partial"));
+ }
+
+ // ── The APPSYNC_JS subset is enforced, not just documented ───────────────
+
+ @Test
+ void anAsyncResolverIsRefusedRatherThanRunOnNode() {
+ query("{ asyncResolver }")
+ .statusCode(200)
+ .body("data.asyncResolver", nullValue())
+ // Node would run this happily. AWS rejects it, so accepting it locally would green-light
+ // code that cannot deploy, which is the one thing an emulator must not do.
+ .body("errors[0].errorType", equalTo("UnsupportedFeature"))
+ .body("errors[0].message", containsString("async"));
+ }
+
+ @Test
+ void aResolverImportingANodeBuiltinIsRefused() {
+ query("{ importsNode }")
+ .statusCode(200)
+ .body("data.importsNode", nullValue())
+ // APPSYNC_JS has no filesystem or network access at all.
+ .body("errors[0].errorType", equalTo("UnsupportedFeature"))
+ .body("errors[0].message", containsString("node:fs"));
+ }
+
+ @Test
+ void aWhileLoopIsRefused() {
+ query("{ loops }")
+ .statusCode(200)
+ .body("errors[0].errorType", equalTo("UnsupportedFeature"))
+ .body("errors[0].message", containsString("while"));
+ }
+
+ @Test
+ void theSameKeywordsInStringsAndCommentsAreNotRefused() {
+ // The check would be worse than useless if it rejected valid resolvers, so the scan blanks
+ // comments, strings and template text before looking for constructs.
+ query("{ keywordsInText }")
+ .statusCode(200)
+ .body("errors", nullValue())
+ .body("data.keywordsInText", equalTo("try catch class while ok"));
+ }
+
+ @Test
+ void aFieldWithNoResolverStillResolvesFromItsParent() {
+ // Message.id and Message.name have no resolvers of their own: they come off the objects the
+ // pipeline returned, which is the default fetcher the resolver fetcher defers to.
+ query("{ getMessages(orgNo: \\\"1\\\") { name } }")
+ .statusCode(200)
+ .body("data.getMessages[0].name", equalTo("Acme 1"))
+ .body("data.getMessages[0]", notNullValue());
+ }
+
+ // ── Helpers ──────────────────────────────────────────────────────────────
+
+ private io.restassured.response.ValidatableResponse query(String graphql) {
+ return given()
+ .header("x-api-key", apiKey)
+ .contentType("application/json")
+ .body("{\"query\":\"" + graphql + "\"}")
+ .when()
+ .post("/v1/apis/" + apiId + "/graphql")
+ .then();
+ }
+
+ private static String createApi(String name) {
+ return given()
+ .header("Authorization", AUTH)
+ .contentType("application/json")
+ .body("{\"name\": \"%s\", \"authenticationType\": \"API_KEY\"}".formatted(name))
+ .when()
+ .post("/v1/apis")
+ .then()
+ .statusCode(200)
+ .extract().path("graphqlApi.apiId");
+ }
+
+ private static String createApiKey(String apiId) {
+ return given()
+ .header("Authorization", AUTH)
+ .contentType("application/json")
+ .body("{}")
+ .when()
+ .post("/v1/apis/" + apiId + "/apikeys")
+ .then()
+ .statusCode(200)
+ .extract().path("apiKey.id");
+ }
+
+ private static void startSchema(String apiId, String definition) {
+ given()
+ .header("Authorization", AUTH)
+ .contentType("application/json")
+ .body("{\"definition\": \"" + escape(definition) + "\"}")
+ .when()
+ .post("/v1/apis/" + apiId + "/schemacreation")
+ .then()
+ .statusCode(200);
+ }
+
+ private static void awaitSchemaSuccess(String apiId) {
+ await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(25)).until(() ->
+ "SUCCESS".equals(given().header("Authorization", AUTH)
+ .when().get("/v1/apis/" + apiId + "/schemacreation")
+ .then().statusCode(200).extract().path("status")));
+ }
+
+ private static void createNoneDataSource(String apiId, String name) {
+ given()
+ .header("Authorization", AUTH)
+ .contentType("application/json")
+ .body("{\"name\": \"%s\", \"type\": \"NONE\"}".formatted(name))
+ .when()
+ .post("/v1/apis/" + apiId + "/datasources")
+ .then()
+ .statusCode(200);
+ }
+
+ private static String createFunction(String apiId, String name, String dataSourceName, String code) {
+ return given()
+ .header("Authorization", AUTH)
+ .contentType("application/json")
+ .body("""
+ {"name": "%s", "dataSourceName": "%s", "functionVersion": "2018-05-29",
+ "runtime": {"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},
+ "code": "%s"}
+ """.formatted(name, dataSourceName, escape(code)))
+ .when()
+ .post("/v1/apis/" + apiId + "/functions")
+ .then()
+ .statusCode(200)
+ .extract().path("functionConfiguration.functionId");
+ }
+
+ private static void createPipelineResolver(String apiId, String typeName, String fieldName,
+ String code, String functionId) {
+ given()
+ .header("Authorization", AUTH)
+ .contentType("application/json")
+ .body("""
+ {"typeName": "%s", "fieldName": "%s", "kind": "PIPELINE",
+ "runtime": {"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},
+ "pipelineConfig": {"functions": ["%s"]},
+ "code": "%s"}
+ """.formatted(typeName, fieldName, functionId, escape(code)))
+ .when()
+ .post("/v1/apis/" + apiId + "/types/" + typeName + "/resolvers")
+ .then()
+ .statusCode(200);
+ }
+
+ private static void createUnitResolver(String apiId, String typeName, String fieldName,
+ String dataSourceName, String code) {
+ given()
+ .header("Authorization", AUTH)
+ .contentType("application/json")
+ .body("""
+ {"typeName": "%s", "fieldName": "%s", "kind": "UNIT", "dataSourceName": "%s",
+ "runtime": {"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},
+ "code": "%s"}
+ """.formatted(typeName, fieldName, dataSourceName, escape(code)))
+ .when()
+ .post("/v1/apis/" + apiId + "/types/" + typeName + "/resolvers")
+ .then()
+ .statusCode(200);
+ }
+
+ private static String escape(String value) {
+ return value.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncResolverCallbackProfile.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncResolverCallbackProfile.java
new file mode 100644
index 0000000000..b50c4bd14e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncResolverCallbackProfile.java
@@ -0,0 +1,26 @@
+package io.github.hectorvent.floci.services.appsync;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * {@link AppSyncGraphqlSidecarProfile} plus a Floci base URL the sidecar container can actually
+ * reach back on.
+ *
+ * <p>The resolver callback URL is built from {@code floci.base-url}'s port, which in production is
+ * the port Floci listens on. Under {@code @QuarkusTest} the application listens on the test port
+ * instead, so without this the sidecar would call back to 4566 and every resolver-backed field
+ * would fail with a connection error. Both values are pinned together here so they cannot drift.
+ */
+public class AppSyncResolverCallbackProfile extends AppSyncGraphqlSidecarProfile {
+
+ private static final String TEST_PORT = "8081";
+
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ Map<String, String> overrides = new LinkedHashMap<>(super.getConfigOverrides());
+ overrides.put("quarkus.http.test-port", TEST_PORT);
+ overrides.put("floci.base-url", "http://localhost:" + TEST_PORT);
+ return overrides;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClientTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClientTest.java
index f30f977262..9687608967 100644
--- a/src/test/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClientTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/GraphqlSidecarClientTest.java
@@ -6,6 +6,8 @@ import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.DenyField;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlanResult;
+import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.ResolveField;
+import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.ResolveSpec;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -66,6 +68,37 @@ class GraphqlSidecarClientTest {
assertThat(lastBody.get().get("scalars").get("AWSDateTime").asText(), equalTo("date-time"));
}
+ @Test
+ void executeWiresTheResolverCallbackForTheFieldsThatHaveResolvers() {
+ answer("/v1/execute", 200, "{\"data\":{\"getPost\":null}}");
+
+ client.execute("type Query { getPost: String }", Map.of(), "{ getPost }", Map.of(), null,
+ List.of(), new ResolveSpec("http://floci:4566/_floci/appsync/resolve", "tok-1",
+ List.of(new ResolveField("Query", "getPost")), 100));
+
+ JsonNode resolve = lastBody.get().get("resolve");
+ assertThat(resolve.get("url").asText(), equalTo("http://floci:4566/_floci/appsync/resolve"));
+ assertThat(resolve.get("token").asText(), equalTo("tok-1"));
+ assertThat(resolve.get("maxBatch").asInt(), equalTo(100));
+ assertThat(resolve.get("fields").size(), equalTo(1));
+ assertThat(resolve.get("fields").get(0).get("typeName").asText(), equalTo("Query"));
+ assertThat(resolve.get("fields").get(0).get("fieldName").asText(), equalTo("getPost"));
+ }
+
+ @Test
+ void executeOmitsTheResolverCallbackWhenNoFieldHasOne() {
+ answer("/v1/execute", 200, "{\"data\":{\"hello\":null}}");
+
+ // Both spellings of "nothing to call back for": no spec at all, and a spec with no fields.
+ // Either must leave the sidecar resolving over its own null root value, as it did before.
+ client.execute("type Query { hello: String }", Map.of(), "{ hello }", Map.of(), null, List.of());
+ assertThat(lastBody.get().has("resolve"), is(false));
+
+ client.execute("type Query { hello: String }", Map.of(), "{ hello }", Map.of(), null, List.of(),
+ new ResolveSpec("http://floci:4566/_floci/appsync/resolve", "tok-2", List.of(), 100));
+ assertThat(lastBody.get().has("resolve"), is(false));
+ }
+
@Test
void planPostsTheQueryAndScalarMappingAndReadsFieldsAndDirectives() {
answer("/v1/plan", 200, "{\"operationType\":\"QUERY\",\"fields\":["
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatterTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatterTest.java
index e955277ae7..730be3437f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatterTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatterTest.java
@@ -134,4 +134,37 @@ class AppSyncErrorFormatterTest {
}
return error;
}
+
+ @Test
+ void aResolverErrorReportsTheTypeInfoAndDataTheResolverChose() {
+ // util.error("...", "BadRequest", data, errorInfo) travels back through the sidecar's
+ // resolver callback, which copies it onto the error's extensions as type/data/info.
+ Map<String, Object> result = new AppSyncErrorFormatter().format(Map.of("errors", List.of(Map.of(
+ "message", "orgNo is required",
+ "path", List.of("getMessages"),
+ "extensions", Map.of(
+ "type", "BadRequest",
+ "data", Map.of("field", "orgNo"),
+ "info", Map.of("hint", "pass one"))))));
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> error = ((List<Map<String, Object>>) result.get("errors")).get(0);
+ assertEquals("BadRequest", error.get("errorType"));
+ assertEquals(Map.of("hint", "pass one"), error.get("errorInfo"));
+ assertEquals(Map.of("field", "orgNo"), error.get("data"));
+ assertEquals(List.of("getMessages"), error.get("path"));
+ }
+
+ @Test
+ void anErrorWithNoResolverTypeKeepsTheClassificationDerivedOne() {
+ Map<String, Object> result = new AppSyncErrorFormatter().format(Map.of("errors", List.of(Map.of(
+ "message", "bad query",
+ "extensions", Map.of("classification", "InvalidSyntax")))));
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> error = ((List<Map<String, Object>>) result.get("errors")).get(0);
+ assertEquals("SyntaxError", error.get("errorType"));
+ assertNull(error.get("errorInfo"));
+ assertFalse(error.containsKey("data"));
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java
index f8d508c5b4..099b64821e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java
@@ -8,7 +8,12 @@ import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient;
import io.github.hectorvent.floci.services.appsync.graphql.auth.AppSyncAuth;
import io.github.hectorvent.floci.services.appsync.graphql.auth.AppSyncAuthContext;
import io.github.hectorvent.floci.services.appsync.graphql.auth.AuthMiddleware;
+import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
import io.github.hectorvent.floci.services.appsync.graphql.auth.SidecarFieldAuthorizationPlanner;
+import io.github.hectorvent.floci.services.appsync.graphql.resolver.AppSyncResolverError;
+import io.github.hectorvent.floci.services.appsync.graphql.resolver.AppSyncResolverExecutor;
+import io.github.hectorvent.floci.services.appsync.graphql.resolver.ResolverCallbackSessions;
+import io.github.hectorvent.floci.services.appsync.model.Resolver;
import io.github.hectorvent.floci.services.appsync.model.AuthenticationType;
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
import jakarta.ws.rs.core.HttpHeaders;
@@ -17,6 +22,7 @@ import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@@ -24,12 +30,16 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@@ -49,7 +59,12 @@ class AppSyncExecutionControllerTest {
AuthMiddleware authMiddleware;
@Mock
RequestContext requestContext;
+ @Mock
+ AppSyncResolverExecutor resolverExecutor;
+ @Mock
+ ContainerReachableEndpoint reachableEndpoint;
+ private final ResolverCallbackSessions callbackSessions = new ResolverCallbackSessions();
private AppSyncExecutionController controller;
private HttpHeaders jsonHeaders;
@@ -64,7 +79,10 @@ class AppSyncExecutionControllerTest {
new AppSyncErrorFormatter(),
new ObjectMapper(),
authMiddleware,
- requestContext);
+ requestContext,
+ resolverExecutor,
+ callbackSessions,
+ reachableEndpoint);
jsonHeaders = mock(HttpHeaders.class);
lenient().when(jsonHeaders.getHeaderString(HttpHeaders.CONTENT_TYPE)).thenReturn("application/json");
@@ -169,4 +187,88 @@ class AppSyncExecutionControllerTest {
null, AppSyncAuth.AUTH_TYPE_API_KEY, AuthenticationType.API_KEY, Set.of(),
api, null, "us-east-1", "000000000000");
}
+
+ /** Plans one query over two coordinates, of which only {@code Query.getMessages} has a resolver. */
+ private void planTwoFieldsOneWithAResolver() {
+ GraphqlApi api = new GraphqlApi();
+ api.setApiId("api-1");
+ when(appSyncService.getGraphqlApi("api-1")).thenReturn(api);
+ when(authMiddleware.authenticate(any(), any(), any())).thenReturn(authContext(api));
+ when(schemaRegistry.getSdl("api-1")).thenReturn(Optional.of("type Query { getMessages: String hello: String }"));
+ when(schemaCompiler.withDirectivesAndScalars(any())).thenReturn("prepared-sdl");
+ when(schemaCompiler.scalarKindMapping()).thenReturn(Map.of());
+ when(sidecarClient.plan(any(), any(), any(), any())).thenReturn(new GraphqlSidecarClient.PlanResult("QUERY",
+ List.of(new GraphqlSidecarClient.PlannedField("Query", "getMessages", List.of(), List.of()),
+ new GraphqlSidecarClient.PlannedField("Query", "hello", List.of(), List.of()))));
+ lenient().when(reachableEndpoint.baseUrl()).thenReturn("http://floci.local:4566");
+ Resolver resolver = new Resolver();
+ resolver.setTypeName("Query");
+ resolver.setFieldName("getMessages");
+ lenient().when(resolverExecutor.findResolver("api-1", "Query", "getMessages")).thenReturn(resolver);
+ lenient().when(resolverExecutor.findResolver("api-1", "Query", "hello")).thenReturn(null);
+ }
+
+ @Test
+ void onlyTheFieldsThatHaveResolversAreWiredToTheCallback() {
+ planTwoFieldsOneWithAResolver();
+ when(fieldAuthorizationPlanner.planDenyFields(any(), any())).thenReturn(List.of());
+ ArgumentCaptor<GraphqlSidecarClient.ResolveSpec> spec =
+ ArgumentCaptor.forClass(GraphqlSidecarClient.ResolveSpec.class);
+ when(sidecarClient.execute(any(), any(), any(), any(), any(), any(), any())).thenReturn(Map.of("data", Map.of()));
+
+ controller.execute("api-1", jsonHeaders, "{\"query\":\"{ getMessages hello }\"}");
+
+ verify(sidecarClient).execute(any(), any(), any(), any(), any(), any(), spec.capture());
+ assertEquals(List.of(new GraphqlSidecarClient.ResolveField("Query", "getMessages")),
+ spec.getValue().fields());
+ assertEquals("http://floci.local:4566/_floci/appsync/resolve", spec.getValue().url());
+ assertNotNull(spec.getValue().token());
+ }
+
+ @Test
+ void aDeniedFieldIsNeverWiredToTheCallback() {
+ planTwoFieldsOneWithAResolver();
+ // denyFields always wins, so an unauthorized field must not reach its resolver at all. With
+ // the only resolver-backed field denied there is nothing left to call back for, which is the
+ // plain execute the sidecar answers over its own null root value.
+ when(fieldAuthorizationPlanner.planDenyFields(any(), any())).thenReturn(
+ List.of(new GraphqlSidecarClient.DenyField("Query", "getMessages", "Unauthorized", "no")));
+ when(sidecarClient.execute(any(), any(), any(), any(), any(), any())).thenReturn(Map.of("data", Map.of()));
+
+ controller.execute("api-1", jsonHeaders, "{\"query\":\"{ getMessages hello }\"}");
+
+ verify(sidecarClient).execute(any(), any(), any(), any(), any(), any());
+ verify(sidecarClient, never()).execute(any(), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ void appendedErrorsJoinTheEnvelopeBesideTheDataAndTheSessionIsClosed() {
+ planTwoFieldsOneWithAResolver();
+ when(fieldAuthorizationPlanner.planDenyFields(any(), any())).thenReturn(List.of());
+ AtomicReference<String> token = new AtomicReference<>();
+ when(sidecarClient.execute(any(), any(), any(), any(), any(), any(), any())).thenAnswer(call -> {
+ GraphqlSidecarClient.ResolveSpec spec = call.getArgument(6);
+ token.set(spec.token());
+ // What a resolver calling util.appendError does, by way of the callback.
+ callbackSessions.find(spec.token()).orElseThrow().appendErrors(List.of(
+ new AppSyncResolverError("one row was dropped", "Partial", null, Map.of("rows", 1),
+ List.of("getMessages"))));
+ return Map.of("data", Map.of("getMessages", "partial"));
+ });
+
+ Response response = controller.execute("api-1", jsonHeaders, "{\"query\":\"{ getMessages }\"}");
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> body = (Map<String, Object>) response.getEntity();
+ assertEquals(Map.of("getMessages", "partial"), body.get("data"));
+ @SuppressWarnings("unchecked")
+ List<Map<String, Object>> errors = (List<Map<String, Object>>) body.get("errors");
+ assertEquals(1, errors.size());
+ assertEquals("one row was dropped", errors.get(0).get("message"));
+ assertEquals("Partial", errors.get(0).get("errorType"));
+ assertEquals(Map.of("rows", 1), errors.get(0).get("errorInfo"));
+ assertEquals(List.of("getMessages"), errors.get(0).get("path"));
+ // The token stops working the moment the operation returns, so a late callback resolves nothing.
+ assertTrue(callbackSessions.find(token.get()).isEmpty());
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/DynamoDbDataSourceInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/DynamoDbDataSourceInvokerTest.java
new file mode 100644
index 0000000000..65f02dacf9
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/DynamoDbDataSourceInvokerTest.java
@@ -0,0 +1,239 @@
+package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
+import jakarta.ws.rs.core.Response;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * The AppSync-to-DynamoDB translation, in both directions. The direction that matters is outward:
+ * AppSync hands a resolver plain JSON, never attribute values.
+ */
+class DynamoDbDataSourceInvokerTest {
+
+ private final DynamoDbJsonHandler handler = mock(DynamoDbJsonHandler.class);
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final DynamoDbDataSourceInvoker invoker = new DynamoDbDataSourceInvoker(handler, mapper);
+
+ private DataSource dataSource() {
+ DataSource ds = new DataSource();
+ ds.setName("authKeys");
+ ds.setType(DataSourceType.AMAZON_DYNAMODB);
+ ds.setDynamodbConfig(Map.of("tableName", "auth-keys", "awsRegion", "eu-west-1"));
+ return ds;
+ }
+
+ private void answers(String json) throws Exception {
+ when(handler.handle(anyString(), any(), anyString())).thenReturn(Response.ok(json).build());
+ }
+
+ private JsonNode captureRequest(String action) throws Exception {
+ ArgumentCaptor<JsonNode> captor = ArgumentCaptor.forClass(JsonNode.class);
+ org.mockito.Mockito.verify(handler).handle(eq(action), captor.capture(), anyString());
+ return captor.getValue();
+ }
+
+ private Map<String, Object> request(String json) {
+ try {
+ return mapper.readValue(json, Map.class);
+ } catch (Exception e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
+
+ @Test
+ void getItemUnmarshalsTheItemIntoPlainJson() throws Exception {
+ answers("""
+ {"Item": {"regNo": {"S": "556677"}, "calls": {"N": "42"}, "active": {"BOOL": true},
+ "scopes": {"L": [{"S": "read"}, {"S": "write"}]},
+ "meta": {"M": {"tier": {"S": "small"}}}, "gone": {"NULL": true}}}
+ """);
+
+ Object result = invoker.invoke(dataSource(),
+ request("{\"operation\": \"GetItem\", \"key\": {\"regNo\": {\"S\": \"556677\"}}}"),
+ "eu-west-1");
+
+ // A GraphQL field cannot be built from {"S": …}; AppSync resolvers see plain values.
+ assertEquals(Map.of("regNo", "556677", "calls", 42L, "active", true,
+ "scopes", List.of("read", "write"), "meta", Map.of("tier", "small")),
+ stripNulls(result));
+ JsonNode sent = captureRequest("GetItem");
+ assertEquals("auth-keys", sent.path("TableName").asText());
+ assertEquals("556677", sent.path("Key").path("regNo").path("S").asText());
+ }
+
+ @Test
+ void getItemMissAnswersNullRatherThanAnEmptyMap() throws Exception {
+ answers("{}");
+
+ Object result = invoker.invoke(dataSource(),
+ request("{\"operation\": \"GetItem\", \"key\": {\"regNo\": {\"S\": \"nope\"}}}"),
+ "eu-west-1");
+
+ assertNull(result);
+ }
+
+ @Test
+ void putItemMergesKeyAndAttributeValuesAndAnswersTheWrittenItem() throws Exception {
+ answers("{}");
+
+ Object result = invoker.invoke(dataSource(), request("""
+ {"operation": "PutItem",
+ "key": {"regNo": {"S": "556677"}},
+ "attributeValues": {"name": {"S": "Acme"}},
+ "condition": {"expression": "attribute_not_exists(#r)",
+ "expressionNames": {"#r": "regNo"}}}
+ """), "eu-west-1");
+
+ JsonNode sent = captureRequest("PutItem");
+ // The key is part of the item on the way to DynamoDB, and wins over an attribute of the
+ // same name, as AppSync documents.
+ assertEquals("556677", sent.path("Item").path("regNo").path("S").asText());
+ assertEquals("Acme", sent.path("Item").path("name").path("S").asText());
+ assertEquals("attribute_not_exists(#r)", sent.path("ConditionExpression").asText());
+ assertEquals("regNo", sent.path("ExpressionAttributeNames").path("#r").asText());
+ assertEquals(Map.of("regNo", "556677", "name", "Acme"), result);
+ }
+
+ @Test
+ void updateItemAsksForTheNewImageAndUnmarshalsIt() throws Exception {
+ answers("{\"Attributes\": {\"regNo\": {\"S\": \"556677\"}, \"calls\": {\"N\": \"43\"}}}");
+
+ Object result = invoker.invoke(dataSource(), request("""
+ {"operation": "UpdateItem",
+ "key": {"regNo": {"S": "556677"}},
+ "update": {"expression": "ADD calls :one",
+ "expressionValues": {":one": {"N": "1"}}}}
+ """), "eu-west-1");
+
+ JsonNode sent = captureRequest("UpdateItem");
+ assertEquals("ADD calls :one", sent.path("UpdateExpression").asText());
+ assertEquals("1", sent.path("ExpressionAttributeValues").path(":one").path("N").asText());
+ // ALL_NEW: an AppSync UpdateItem resolver returns the updated item.
+ assertEquals("ALL_NEW", sent.path("ReturnValues").asText());
+ assertEquals(Map.of("regNo", "556677", "calls", 43L), result);
+ }
+
+ @Test
+ void queryMergesKeyConditionAndFilterPlaceholdersIntoOneMap() throws Exception {
+ answers("""
+ {"Items": [{"regNo": {"S": "1"}}, {"regNo": {"S": "2"}}],
+ "ScannedCount": 7,
+ "LastEvaluatedKey": {"regNo": {"S": "2"}}}
+ """);
+
+ Object result = invoker.invoke(dataSource(), request("""
+ {"operation": "Query",
+ "query": {"expression": "#r = :r", "expressionNames": {"#r": "regNo"},
+ "expressionValues": {":r": {"S": "1"}}},
+ "filter": {"expression": "active = :a", "expressionValues": {":a": {"BOOL": true}}},
+ "index": "byRegNo", "limit": 25, "scanIndexForward": false}
+ """), "eu-west-1");
+
+ JsonNode sent = captureRequest("Query");
+ assertEquals("#r = :r", sent.path("KeyConditionExpression").asText());
+ assertEquals("active = :a", sent.path("FilterExpression").asText());
+ // Both the key condition's and the filter's placeholders live in one shared map; setting
+ // rather than merging them would drop whichever came first.
+ assertEquals("1", sent.path("ExpressionAttributeValues").path(":r").path("S").asText());
+ assertTrue(sent.path("ExpressionAttributeValues").path(":a").path("BOOL").asBoolean());
+ assertEquals("byRegNo", sent.path("IndexName").asText());
+ assertEquals(25, sent.path("Limit").asInt());
+ assertTrue(sent.has("ScanIndexForward"));
+
+ Map<?, ?> answered = (Map<?, ?>) result;
+ assertEquals(List.of(Map.of("regNo", "1"), Map.of("regNo", "2")), answered.get("items"));
+ assertEquals(7, answered.get("scannedCount"));
+ assertTrue(answered.get("nextToken") instanceof String, "a page with more rows carries a nextToken");
+ }
+
+ @Test
+ void aQueryPageWithNoMoreRowsCarriesNoNextToken() throws Exception {
+ answers("{\"Items\": [], \"ScannedCount\": 0}");
+
+ Map<?, ?> result = (Map<?, ?>) invoker.invoke(dataSource(), request("""
+ {"operation": "Query", "query": {"expression": "regNo = :r",
+ "expressionValues": {":r": {"S": "1"}}}}
+ """), "eu-west-1");
+
+ assertNull(result.get("nextToken"));
+ assertEquals(List.of(), result.get("items"));
+ }
+
+ @Test
+ void aNextTokenRoundTripsBackIntoExclusiveStartKey() throws Exception {
+ answers("{\"Items\": [], \"LastEvaluatedKey\": {\"regNo\": {\"S\": \"2\"}}}");
+ Map<?, ?> first = (Map<?, ?>) invoker.invoke(dataSource(), request("""
+ {"operation": "Scan"}
+ """), "eu-west-1");
+ String nextToken = (String) first.get("nextToken");
+
+ org.mockito.Mockito.reset(handler);
+ answers("{\"Items\": []}");
+ invoker.invoke(dataSource(), request("""
+ {"operation": "Scan", "nextToken": "%s"}
+ """.formatted(nextToken)), "eu-west-1");
+
+ JsonNode sent = captureRequest("Scan");
+ assertEquals("2", sent.path("ExclusiveStartKey").path("regNo").path("S").asText());
+ }
+
+ @Test
+ void aTokenFlociDidNotIssueIsRefused() {
+ AwsException e = assertThrows(AwsException.class, () -> invoker.invoke(dataSource(),
+ request("{\"operation\": \"Scan\", \"nextToken\": \"not-a-token!!\"}"), "eu-west-1"));
+
+ assertTrue(e.getMessage().contains("nextToken"), e.getMessage());
+ }
+
+ @Test
+ void anUnimplementedOperationSaysSoByName() {
+ AwsException e = assertThrows(AwsException.class, () -> invoker.invoke(dataSource(),
+ request("{\"operation\": \"TransactWriteItems\"}"), "eu-west-1"));
+
+ assertTrue(e.getMessage().contains("TransactWriteItems"), e.getMessage());
+ }
+
+ @Test
+ void aDataSourceWithNoTableNameFailsClearly() {
+ DataSource ds = dataSource();
+ ds.setDynamodbConfig(Map.of("awsRegion", "eu-west-1"));
+
+ AwsException e = assertThrows(AwsException.class, () -> invoker.invoke(ds,
+ request("{\"operation\": \"GetItem\", \"key\": {}}"), "eu-west-1"));
+
+ assertTrue(e.getMessage().contains("tableName"), e.getMessage());
+ }
+
+ /** Drops the null-valued entries a NULL attribute produces, for a tidy comparison. */
+ private Object stripNulls(Object value) {
+ if (value instanceof Map<?, ?> map) {
+ java.util.Map<Object, Object> copy = new java.util.LinkedHashMap<>();
+ map.forEach((k, v) -> {
+ if (v != null) {
+ copy.put(k, stripNulls(v));
+ }
+ });
+ return copy;
+ }
+ return value;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvokerTest.java
new file mode 100644
index 0000000000..c46f9223e8
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvokerTest.java
@@ -0,0 +1,123 @@
+package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.InvocationType;
+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/** What reaches the function, and what a function's answer becomes. */
+class LambdaDataSourceInvokerTest {
+
+ private static final String FN_ARN = "arn:aws:lambda:eu-west-1:000000000000:function:resolver-fn";
+
+ private final LambdaService lambda = mock(LambdaService.class);
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final LambdaDataSourceInvoker invoker = new LambdaDataSourceInvoker(lambda, mapper);
+
+ private DataSource dataSource() {
+ DataSource ds = new DataSource();
+ ds.setName("resolverFn");
+ ds.setType(DataSourceType.AWS_LAMBDA);
+ ds.setLambdaConfig(Map.of("lambdaFunctionArn", FN_ARN));
+ return ds;
+ }
+
+ private void answers(String json) {
+ when(lambda.invokeArn(eq(FN_ARN), any(), eq(InvocationType.RequestResponse)))
+ .thenReturn(new InvokeResult(200, null, json.getBytes(StandardCharsets.UTF_8), null, "req-1"));
+ }
+
+ private String capturePayload() {
+ ArgumentCaptor<byte[]> captor = ArgumentCaptor.forClass(byte[].class);
+ verify(lambda).invokeArn(eq(FN_ARN), captor.capture(), eq(InvocationType.RequestResponse));
+ return new String(captor.getValue(), StandardCharsets.UTF_8);
+ }
+
+ @Test
+ void onlyThePayloadReachesTheFunction() {
+ answers("{\"id\": \"1\"}");
+
+ Object result = invoker.invoke(dataSource(),
+ Map.of("operation", "Invoke", "payload", Map.of("field", "getMessages")), "eu-west-1");
+
+ // The operation is AppSync's envelope, not something the function should see.
+ assertEquals("{\"field\":\"getMessages\"}", capturePayload());
+ assertEquals(Map.of("id", "1"), result);
+ }
+
+ @Test
+ void aRequestWithNoEnvelopeIsThePayload() {
+ answers("{}");
+
+ invoker.invoke(dataSource(), Map.of("field", "getMessages"), "eu-west-1");
+
+ assertEquals("{\"field\":\"getMessages\"}", capturePayload());
+ }
+
+ @Test
+ void aBatchInvokeAnswersTheListTheFunctionReturned() {
+ answers("[{\"id\": \"1\"}, {\"id\": \"2\"}]");
+
+ Object result = invoker.invoke(dataSource(),
+ Map.of("operation", "BatchInvoke", "payload", List.of(Map.of("id", "1"), Map.of("id", "2"))),
+ "eu-west-1");
+
+ assertEquals(List.of(Map.of("id", "1"), Map.of("id", "2")), result);
+ }
+
+ @Test
+ void aFunctionErrorFailsTheFieldRatherThanResolvingToTheErrorObject() {
+ when(lambda.invokeArn(eq(FN_ARN), any(), eq(InvocationType.RequestResponse)))
+ .thenReturn(new InvokeResult(200, "Unhandled",
+ "{\"errorMessage\": \"boom\"}".getBytes(StandardCharsets.UTF_8), null, "req-1"));
+
+ AwsException e = assertThrows(AwsException.class, () -> invoker.invoke(dataSource(),
+ Map.of("payload", Map.of()), "eu-west-1"));
+
+ assertTrue(e.getMessage().contains("boom"), e.getMessage());
+ }
+
+ @Test
+ void anEmptyAnswerIsNull() {
+ answers("");
+
+ assertNull(invoker.invoke(dataSource(), Map.of("payload", Map.of()), "eu-west-1"));
+ }
+
+ @Test
+ void aNonJsonAnswerComesBackAsText() {
+ answers("just text");
+
+ assertEquals("just text", invoker.invoke(dataSource(), Map.of("payload", Map.of()), "eu-west-1"));
+ }
+
+ @Test
+ void aDataSourceWithoutAFunctionArnFailsClearly() {
+ DataSource ds = dataSource();
+ ds.setLambdaConfig(Map.of());
+
+ AwsException e = assertThrows(AwsException.class,
+ () -> invoker.invoke(ds, Map.of(), "eu-west-1"));
+
+ assertTrue(e.getMessage().contains("lambdaFunctionArn"), e.getMessage());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/RelationalDataSourceInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/RelationalDataSourceInvokerTest.java
new file mode 100644
index 0000000000..0c0dc6c9c2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/RelationalDataSourceInvokerTest.java
@@ -0,0 +1,225 @@
+package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+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.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+import io.github.hectorvent.floci.services.rdsdata.RdsDataService;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Statement normalisation and the result wrapper. The wrapper is the contract with
+ * {@code toJsonObject()}: the call every relational JS resolver's response handler ends with only
+ * finds rows under {@code sqlStatementResults}, with column metadata beside them.
+ */
+class RelationalDataSourceInvokerTest {
+
+ private final RdsDataService rdsData = mock(RdsDataService.class);
+ private final RegionResolver regionResolver = mock(RegionResolver.class);
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final RelationalDataSourceInvoker invoker =
+ new RelationalDataSourceInvoker(rdsData, regionResolver, mapper);
+
+ private DataSource dataSource() {
+ DataSource ds = new DataSource();
+ ds.setName("accountDB");
+ ds.setType(DataSourceType.RELATIONAL_DATABASE);
+ ds.setRelationalDatabaseConfig(Map.of(
+ "relationalDatabaseSourceType", "RDS_HTTP_ENDPOINT",
+ "rdsHttpEndpointConfig", Map.of(
+ "awsRegion", "eu-west-1",
+ "dbClusterIdentifier", "ls-db-cluster",
+ "databaseName", "accountdb",
+ "awsSecretStoreArn", "arn:aws:secretsmanager:eu-west-1:000000000000:secret:db")));
+ return ds;
+ }
+
+ private void answersOneRow() {
+ when(regionResolver.getAccountId()).thenReturn("000000000000");
+ ObjectNode response = mapper.createObjectNode();
+ response.put("numberOfRecordsUpdated", 0);
+ response.set("columnMetadata", mapper.createArrayNode()
+ .add(mapper.createObjectNode().put("label", "id").put("typeName", "int4")));
+ response.set("records", mapper.createArrayNode()
+ .add(mapper.createArrayNode().add(mapper.createObjectNode().put("longValue", 7))));
+ when(rdsData.executeStatement(any(), anyString())).thenReturn(response);
+ }
+
+ private JsonNode captureRequest() {
+ ArgumentCaptor<JsonNode> captor = ArgumentCaptor.forClass(JsonNode.class);
+ verify(rdsData).executeStatement(captor.capture(), anyString());
+ return captor.getValue();
+ }
+
+ @Test
+ void theHelpersStatementAndPositionalParametersBecomeNamedDataApiParameters() {
+ answersOneRow();
+
+ invoker.invoke(dataSource(), Map.of(
+ "statement", "SELECT * FROM \"messages\" WHERE \"org_no\" = :param1 LIMIT :param2",
+ "parameters", List.of("556677", 10)), "eu-west-1");
+
+ JsonNode sent = captureRequest();
+ assertEquals("accountdb", sent.path("database").asText());
+ // The Data API needs a cluster ARN; the data source records only the identifier.
+ assertEquals("arn:aws:rds:eu-west-1:000000000000:cluster:ls-db-cluster",
+ sent.path("resourceArn").asText());
+ assertTrue(sent.path("includeResultMetadata").asBoolean(),
+ "without metadata toJsonObject cannot name a column");
+ assertEquals("param1", sent.path("parameters").get(0).path("name").asText());
+ assertEquals("556677", sent.path("parameters").get(0).path("value").path("stringValue").asText());
+ // An integer must not arrive as a string, or a numeric comparison in SQL fails.
+ assertEquals("param2", sent.path("parameters").get(1).path("name").asText());
+ assertEquals(10, sent.path("parameters").get(1).path("value").path("longValue").asLong());
+ }
+
+ @Test
+ void theResultIsWrappedTheWayToJsonObjectReadsIt() {
+ answersOneRow();
+
+ Object result = invoker.invoke(dataSource(),
+ Map.of("statement", "SELECT id FROM messages"), "eu-west-1");
+
+ Map<?, ?> wrapper = (Map<?, ?>) result;
+ List<?> statements = (List<?>) wrapper.get("sqlStatementResults");
+ assertEquals(1, statements.size());
+ Map<?, ?> first = (Map<?, ?>) statements.get(0);
+ assertTrue(first.containsKey("records"));
+ assertTrue(first.containsKey("columnMetadata"));
+ assertEquals(0, ((Number) first.get("numberOfRecordsUpdated")).intValue());
+ }
+
+ @Test
+ void theClassicStatementsAndVariableMapShapeIsAccepted() {
+ answersOneRow();
+
+ invoker.invoke(dataSource(), Map.of(
+ "statements", List.of("SELECT id FROM messages WHERE org_no = :orgNo"),
+ "variableMap", Map.of(":orgNo", "556677")), "eu-west-1");
+
+ JsonNode sent = captureRequest();
+ // AppSync's own variableMap names its placeholders with a colon; the Data API does not.
+ assertEquals("orgNo", sent.path("parameters").get(0).path("name").asText());
+ assertEquals("556677", sent.path("parameters").get(0).path("value").path("stringValue").asText());
+ }
+
+ @Test
+ void declaredTypeHintsTravelWithTheirParameters() {
+ answersOneRow();
+
+ // The shape a resolver's date filter produces: one variable map and one hint map, keyed by
+ // the placeholder as written in the statement.
+ invoker.invoke(dataSource(), Map.of(
+ "statements", List.of("SELECT * FROM message_log WHERE received_at >= :v0 AND owneraccount = :v1"),
+ "variableMap", Map.of(":v0", "2026-09-01 00:00:00", ":v1", "5566778899"),
+ "variableTypeHintMap", Map.of(":v0", "TIMESTAMP")), "eu-west-1");
+
+ JsonNode parameters = captureRequest().path("parameters");
+ Map<String, JsonNode> byName = new java.util.LinkedHashMap<>();
+ parameters.forEach(parameter -> byName.put(parameter.path("name").asText(), parameter));
+ // Without the hint the value binds as text and PostgreSQL refuses the comparison outright:
+ // "operator does not exist: timestamp with time zone >= character varying".
+ assertEquals("TIMESTAMP", byName.get("v0").path("typeHint").asText());
+ assertEquals("2026-09-01 00:00:00", byName.get("v0").path("value").path("stringValue").asText());
+ // A parameter with no declared hint carries none, so it binds as its own JSON type.
+ assertFalse(byName.get("v1").has("typeHint"));
+ }
+
+ @Test
+ void aTypeHintOnAPositionalParameterIsHonoured() {
+ answersOneRow();
+
+ invoker.invoke(dataSource(), Map.of(
+ "statement", "SELECT * FROM t WHERE d = :param1",
+ "parameters", List.of("2026-09-01"),
+ "variableTypeHintMap", Map.of(":param1", "DATE")), "eu-west-1");
+
+ assertEquals("DATE", captureRequest().path("parameters").get(0).path("typeHint").asText());
+ }
+
+ @Test
+ void aBareSqlStringIsAccepted() {
+ answersOneRow();
+
+ invoker.invoke(dataSource(), "SELECT 1", "eu-west-1");
+
+ assertEquals("SELECT 1", captureRequest().path("sql").asText());
+ assertFalse(captureRequest().has("parameters"));
+ }
+
+ @Test
+ void everyStatementInAListRunsAndAnswersItsOwnResult() {
+ answersOneRow();
+
+ Object result = invoker.invoke(dataSource(), List.of(
+ Map.of("statement", "SELECT 1"),
+ Map.of("statement", "SELECT 2")), "eu-west-1");
+
+ Map<?, ?> wrapper = (Map<?, ?>) result;
+ assertEquals(2, ((List<?>) wrapper.get("sqlStatementResults")).size());
+ }
+
+ @Test
+ void nullAndStructuredParametersAreTyped() {
+ answersOneRow();
+
+ invoker.invoke(dataSource(), Map.of("statement", "INSERT INTO t VALUES (:param1, :param2)",
+ "parameters", List.of(Map.of("a", 1), true)), "eu-west-1");
+
+ JsonNode parameters = captureRequest().path("parameters");
+ // A structured parameter binds as its JSON text, which is what a json/jsonb column takes.
+ assertEquals("{\"a\":1}", parameters.get(0).path("value").path("stringValue").asText());
+ assertTrue(parameters.get(1).path("value").path("booleanValue").asBoolean());
+ }
+
+ @Test
+ void aClusterIdentifierThatIsAlreadyAnArnIsUsedAsIs() {
+ answersOneRow();
+ DataSource ds = dataSource();
+ ds.setRelationalDatabaseConfig(Map.of("rdsHttpEndpointConfig", Map.of(
+ "dbClusterIdentifier", "arn:aws:rds:eu-west-1:000000000000:cluster:given",
+ "databaseName", "accountdb",
+ "awsSecretStoreArn", "arn:secret")));
+
+ invoker.invoke(ds, "SELECT 1", "eu-west-1");
+
+ assertEquals("arn:aws:rds:eu-west-1:000000000000:cluster:given",
+ captureRequest().path("resourceArn").asText());
+ }
+
+ @Test
+ void aResolverThatProducedNoStatementFailsClearly() {
+ AwsException e = assertThrows(AwsException.class,
+ () -> invoker.invoke(dataSource(), Map.of(), "eu-west-1"));
+
+ assertTrue(e.getMessage().contains("no SQL statement"), e.getMessage());
+ }
+
+ @Test
+ void aDataSourceWithoutAnEndpointConfigFailsClearly() {
+ DataSource ds = dataSource();
+ ds.setRelationalDatabaseConfig(Map.of());
+
+ AwsException e = assertThrows(AwsException.class,
+ () -> invoker.invoke(ds, "SELECT 1", "eu-west-1"));
+
+ assertTrue(e.getMessage().contains("rdsHttpEndpointConfig"), e.getMessage());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntimeTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntimeTest.java
new file mode 100644
index 0000000000..64c37d8769
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntimeTest.java
@@ -0,0 +1,196 @@
+package io.github.hectorvent.floci.services.appsync.graphql.js;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sun.net.httpserver.HttpServer;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
+import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
+import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
+import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.withSettings;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+/**
+ * The pre-configured URL path: a server someone else is already running, with no container
+ * management at all. Same contract as {@code floci.services.duck.url}.
+ */
+class NodeAppSyncJsRuntimeTest {
+
+ private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
+ private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
+ private final ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
+ private final ContainerDetector containerDetector = mock(ContainerDetector.class);
+ private final EmulatorConfig config = mock(EmulatorConfig.class);
+ private final EmulatorConfig.JsRuntimeConfig jsRuntime = mock(EmulatorConfig.JsRuntimeConfig.class);
+
+ private HttpServer server;
+ private final List<String> requestedPaths = new ArrayList<>();
+ private NodeAppSyncJsRuntime runtime;
+ private volatile boolean failEvaluate;
+
+ @BeforeEach
+ void startStubRuntime() throws IOException {
+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext("/", exchange -> {
+ requestedPaths.add(exchange.getRequestURI().getPath());
+ if (failEvaluate && "/evaluate".equals(exchange.getRequestURI().getPath())) {
+ // Dropped without a response, so the client sees a transport failure. A 500 would
+ // not do: post() rethrows an AwsException before reaching the path under test.
+ exchange.close();
+ return;
+ }
+ byte[] body = ("/health".equals(exchange.getRequestURI().getPath())
+ ? "{\"ok\":true,\"runtime\":\"stub\"}"
+ : "{\"ok\":true,\"result\":\"from-the-stub\",\"stash\":{},\"earlyReturn\":false,\"errors\":[]}")
+ .getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().add("content-type", "application/json");
+ exchange.sendResponseHeaders(200, body.length);
+ try (OutputStream out = exchange.getResponseBody()) {
+ out.write(body);
+ }
+ });
+ server.start();
+
+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
+ EmulatorConfig.AppSyncServiceConfig appsync = mock(EmulatorConfig.AppSyncServiceConfig.class);
+ when(config.services()).thenReturn(services);
+ when(services.appsync()).thenReturn(appsync);
+ when(appsync.jsRuntime()).thenReturn(jsRuntime);
+ when(jsRuntime.enabled()).thenReturn(true);
+ when(jsRuntime.enforceAppsyncSubset()).thenReturn(true);
+ when(jsRuntime.evaluationTimeoutSeconds()).thenReturn(5);
+ when(jsRuntime.url()).thenReturn(
+ Optional.of("http://127.0.0.1:" + server.getAddress().getPort()));
+
+ runtime = new NodeAppSyncJsRuntime(containerBuilder, lifecycleManager, logStreamer,
+ containerDetector, config, mock(RegionResolver.class), new ObjectMapper());
+ }
+
+ @AfterEach
+ void stopStubRuntime() {
+ server.stop(0);
+ }
+
+ @Test
+ void aPreConfiguredUrlIsUsedWithoutTouchingDocker() {
+ JsEvaluation evaluation = runtime.evaluate("export function request() { return {}; }",
+ "request", Map.of("arguments", Map.of()));
+
+ assertEquals("from-the-stub", evaluation.result());
+ // The point of the knob: no image pull, no container created, adopted or inspected.
+ verifyNoInteractions(containerBuilder);
+ verifyNoInteractions(lifecycleManager);
+ verifyNoInteractions(logStreamer);
+ assertTrue(requestedPaths.contains("/health"), "the configured URL is probed before use");
+ assertTrue(requestedPaths.contains("/evaluate"), "the evaluation goes to the configured URL");
+ }
+
+
+ /**
+ * The window the concurrency fix closes: a failing evaluation used to clear containerId without
+ * stopping the container, so the only handle to a live sidecar was dropped and teardown could
+ * not reach it. Racing failures against startup, every container this runtime creates must also
+ * be stopped.
+ */
+ @Test
+ void aFailedEvaluationRacingStartupNeverLeavesAContainerBehind() throws Exception {
+ when(jsRuntime.url()).thenReturn(Optional.empty());
+ when(jsRuntime.image()).thenReturn("node:22-alpine");
+ when(jsRuntime.containerName()).thenReturn("appsync-js-runtime-test");
+ when(jsRuntime.port()).thenReturn(0);
+ when(jsRuntime.startTimeoutSeconds()).thenReturn(5);
+ when(jsRuntime.keepRunningOnShutdown()).thenReturn(false);
+ when(jsRuntime.dockerNetwork()).thenReturn(Optional.empty());
+ when(containerDetector.isRunningInContainer()).thenReturn(false);
+ when(lifecycleManager.findByName(anyString())).thenReturn(Optional.empty());
+
+ // A fluent builder that yields a spec, and a lifecycle manager that hands out a fresh
+ // container each time, pointed at the stub whose /evaluate always fails.
+ ContainerBuilder.Builder builder =
+ mock(ContainerBuilder.Builder.class, withSettings().defaultAnswer(org.mockito.Answers.RETURNS_SELF));
+ when(containerBuilder.newContainer(anyString())).thenReturn(builder);
+ when(builder.build()).thenReturn(mock(ContainerSpec.class));
+
+ Set<String> created = ConcurrentHashMap.newKeySet();
+ Set<String> stopped = ConcurrentHashMap.newKeySet();
+ AtomicInteger counter = new AtomicInteger();
+ when(lifecycleManager.createAndStart(any())).thenAnswer(invocation -> {
+ String id = "container-" + counter.incrementAndGet();
+ created.add(id);
+ return new ContainerInfo(id, Map.of(4600,
+ new EndpointInfo("127.0.0.1", server.getAddress().getPort())));
+ });
+ org.mockito.Mockito.doAnswer(invocation -> {
+ stopped.add(invocation.getArgument(0));
+ return null;
+ }).when(lifecycleManager).stopAndRemove(anyString(), any());
+
+ failEvaluate = true;
+ int threads = 8;
+ ExecutorService pool = Executors.newFixedThreadPool(threads);
+ CountDownLatch start = new CountDownLatch(1);
+ CountDownLatch done = new CountDownLatch(threads);
+ for (int i = 0; i < threads; i++) {
+ pool.submit(() -> {
+ try {
+ start.await();
+ runtime.evaluate("export function request() { return {}; }", "request", Map.of());
+ } catch (Exception expected) {
+ // every evaluation fails; the point is what happens to the container
+ } finally {
+ done.countDown();
+ }
+ });
+ }
+ start.countDown();
+ assertTrue(done.await(30, TimeUnit.SECONDS), "the racing evaluations did not finish");
+ pool.shutdownNow();
+
+ runtime.stopManagedContainers();
+
+ assertTrue(created.size() > 0, "the race never started a container, so it proves nothing");
+ assertEquals(created, stopped,
+ "every sidecar this runtime created must also be stopped; one left in `created` "
+ + "only is a container leaked by a failed evaluation clearing its id");
+ }
+
+ @Test
+ void stoppingManagedContainersLeavesAPreConfiguredServerAlone() {
+ runtime.evaluate("export function request() { return {}; }", "request", Map.of());
+
+ runtime.stopManagedContainers();
+
+ // Not ours to stop: nothing was started, so nothing is removed.
+ verifyNoInteractions(lifecycleManager);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java
new file mode 100644
index 0000000000..9a6f57dee4
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java
@@ -0,0 +1,528 @@
+package io.github.hectorvent.floci.services.appsync.graphql.resolver;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.appsync.AppSyncService;
+import io.github.hectorvent.floci.services.appsync.graphql.datasource.AppSyncDataSourceInvoker;
+import io.github.hectorvent.floci.services.appsync.graphql.datasource.AppSyncDataSourceInvokers;
+import io.github.hectorvent.floci.services.appsync.graphql.js.AppSyncJsRuntime;
+import io.github.hectorvent.floci.services.appsync.graphql.js.JsEvaluation;
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+import io.github.hectorvent.floci.services.appsync.model.FunctionConfiguration;
+import io.github.hectorvent.floci.services.appsync.model.Resolver;
+import io.github.hectorvent.floci.services.appsync.model.ResolverKind;
+import io.github.hectorvent.floci.services.appsync.model.ResolverRuntimeName;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Pipeline mechanics, with a scripted JS runtime in place of the sidecar: the order the handlers
+ * run in, what each one sees of the last, and which of AppSync's three ways of stopping applies.
+ */
+class AppSyncResolverExecutorTest {
+
+ private static final String API_ID = "api1";
+
+ private final AppSyncService appSync = mock(AppSyncService.class);
+ private final ScriptedJsRuntime jsRuntime = new ScriptedJsRuntime();
+ private final RecordingInvoker invoker = new RecordingInvoker();
+ private final AppSyncResolverExecutor executor = new AppSyncResolverExecutor(appSync, jsRuntime,
+ new AppSyncDataSourceInvokers(List.of(invoker)));
+
+ /** A JS runtime whose answers are supplied per (code, handler) by the test. */
+ private static final class ScriptedJsRuntime implements AppSyncJsRuntime {
+ private final Map<String, BiFunction<String, Map<String, Object>, JsEvaluation>> scripts =
+ new LinkedHashMap<>();
+ private final List<String> calls = new ArrayList<>();
+ private final List<Map<String, Object>> contexts = new ArrayList<>();
+
+ void script(String code, String handler,
+ BiFunction<String, Map<String, Object>, JsEvaluation> answer) {
+ scripts.put(code + "#" + handler, answer);
+ }
+
+ @Override
+ public JsEvaluation evaluate(String code, String handler, Map<String, Object> context) {
+ calls.add(code + "#" + handler);
+ contexts.add(context);
+ var script = scripts.get(code + "#" + handler);
+ if (script == null) {
+ // Nothing scripted stands for a module that does not export this handler, which is
+ // how a request-only function behaves.
+ return new JsEvaluation(null, Map.of(), false, List.of(), null, true);
+ }
+ return script.apply(handler, context);
+ }
+
+ @Override
+ public boolean isAvailable() {
+ return true;
+ }
+ }
+
+ /** Records what reached the data source and answers with whatever the test set. */
+ private static final class RecordingInvoker implements AppSyncDataSourceInvoker {
+ private final List<Object> requests = new ArrayList<>();
+ private Object answer = Map.of();
+ private AwsException failure;
+
+ @Override
+ public DataSourceType type() {
+ return DataSourceType.RELATIONAL_DATABASE;
+ }
+
+ @Override
+ public Object invoke(DataSource dataSource, Object request, String region) {
+ requests.add(request);
+ if (failure != null) {
+ throw failure;
+ }
+ return answer;
+ }
+ }
+
+ private static JsEvaluation ok(Object result) {
+ return new JsEvaluation(result, Map.of(), false, List.of(), null, false);
+ }
+
+ private static JsEvaluation ok(Object result, Map<String, Object> stash) {
+ return new JsEvaluation(result, stash, false, List.of(), null, false);
+ }
+
+ private DataSource dataSource(String name) {
+ DataSource ds = new DataSource();
+ ds.setName(name);
+ ds.setType(DataSourceType.RELATIONAL_DATABASE);
+ ds.setDataSourceArn("arn:aws:appsync:eu-west-1:000000000000:apis/" + API_ID + "/datasources/" + name);
+ return ds;
+ }
+
+ private Resolver resolver(ResolverKind kind, String code) {
+ Resolver resolver = new Resolver();
+ resolver.setApiId(API_ID);
+ resolver.setTypeName("Query");
+ resolver.setFieldName("getMessages");
+ resolver.setKind(kind);
+ resolver.setCode(code);
+ return resolver;
+ }
+
+ private FunctionConfiguration function(String id, String name, String dataSourceName, String code) {
+ FunctionConfiguration fn = new FunctionConfiguration();
+ fn.setFunctionId(id);
+ fn.setName(name);
+ fn.setDataSourceName(dataSourceName);
+ fn.setCode(code);
+ return fn;
+ }
+
+ private ResolverInvocation invocation(Map<String, Object> arguments) {
+ return new ResolverInvocation(API_ID, "Query", "getThing", arguments, null, null, null, null, null, null);
+ }
+
+ @Test
+ void unitResolverRunsRequestThenDataSourceThenResponse() {
+ when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
+ when(appSync.getEnvironmentVariables(API_ID)).thenReturn(Map.of("QUOTA", "10"));
+ Resolver resolver = resolver(ResolverKind.UNIT, "unit-code");
+ resolver.setDataSourceName("accountDB");
+ jsRuntime.script("unit-code", "request", (h, ctx) -> ok(Map.of("statement", "select 1")));
+ jsRuntime.script("unit-code", "response", (h, ctx) -> ok(List.of(Map.of("id", 1))));
+ invoker.answer = Map.of("sqlStatementResults", List.of());
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ assertEquals(List.of("unit-code#request", "unit-code#response"), jsRuntime.calls);
+ assertEquals(List.of(Map.of("statement", "select 1")), invoker.requests);
+ assertEquals(List.of(Map.of("id", 1)), result.data());
+ assertTrue(result.errors().isEmpty());
+ // The response handler sees the data source's answer as ctx.result.
+ assertEquals(Map.of("sqlStatementResults", List.of()), jsRuntime.contexts.get(1).get("result"));
+ assertEquals(Map.of("QUOTA", "10"), jsRuntime.contexts.get(0).get("env"));
+ }
+
+ @Test
+ void pipelineRunsBeforeEachFunctionThenAfter() {
+ when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
+ when(appSync.getFunction(API_ID, "fn1")).thenReturn(function("fn1", "one", "accountDB", "fn1-code"));
+ when(appSync.getFunction(API_ID, "fn2")).thenReturn(function("fn2", "two", "accountDB", "fn2-code"));
+ Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
+ resolver.setPipelineConfig(Map.of("functions", List.of("fn1", "fn2")));
+ jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(Map.of(), Map.of("orgNo", "556")));
+ jsRuntime.script("fn1-code", "request", (h, ctx) -> ok(Map.of("statement", "one")));
+ jsRuntime.script("fn1-code", "response", (h, ctx) -> ok("first"));
+ jsRuntime.script("fn2-code", "request", (h, ctx) -> ok(Map.of("statement", "two")));
+ jsRuntime.script("fn2-code", "response", (h, ctx) -> ok("second"));
+ jsRuntime.script("pipeline-code", "response", (h, ctx) -> ok(ctx.get("result")));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ assertEquals(List.of("pipeline-code#request", "fn1-code#request", "fn1-code#response",
+ "fn2-code#request", "fn2-code#response", "pipeline-code#response"), jsRuntime.calls);
+ // The after step is handed the last function's result as ctx.result.
+ assertEquals("second", result.data());
+ }
+
+ @Test
+ void pipelineThreadsStashAndPreviousResultThroughEveryStage() {
+ when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
+ when(appSync.getFunction(API_ID, "fn1")).thenReturn(function("fn1", "one", "accountDB", "fn1-code"));
+ when(appSync.getFunction(API_ID, "fn2")).thenReturn(function("fn2", "two", "accountDB", "fn2-code"));
+ Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
+ resolver.setPipelineConfig(Map.of("functions", List.of("fn1", "fn2")));
+ jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok("before-result", Map.of("orgNo", "556")));
+ jsRuntime.script("fn1-code", "request", (h, ctx) -> ok(Map.of()));
+ jsRuntime.script("fn1-code", "response", (h, ctx) -> ok("fn1-result", Map.of("orgNo", "556", "seen", true)));
+ jsRuntime.script("fn2-code", "request", (h, ctx) -> ok(Map.of()));
+ jsRuntime.script("fn2-code", "response", (h, ctx) -> ok("fn2-result"));
+ jsRuntime.script("pipeline-code", "response", (h, ctx) -> ok(ctx.get("result")));
+
+ executor.execute(resolver, invocation(Map.of()));
+
+ // fn1's request sees the before step's return as ctx.prev.result and its stash.
+ assertEquals(Map.of("result", "before-result"), jsRuntime.contexts.get(1).get("prev"));
+ assertEquals(Map.of("orgNo", "556"), jsRuntime.contexts.get(1).get("stash"));
+ // fn2 sees fn1's response, and the stash fn1 added to.
+ assertEquals(Map.of("result", "fn1-result"), jsRuntime.contexts.get(3).get("prev"));
+ assertEquals(Map.of("orgNo", "556", "seen", true), jsRuntime.contexts.get(3).get("stash"));
+ }
+
+ @Test
+ void earlyReturnInTheBeforeStepSkipsTheFunctionsAndTheAfterStep() {
+ Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
+ resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
+ jsRuntime.script("pipeline-code", "request", (h, ctx) ->
+ new JsEvaluation(Map.of("cached", true), Map.of(), true, List.of(), null, false));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ assertEquals(List.of("pipeline-code#request"), jsRuntime.calls);
+ assertTrue(invoker.requests.isEmpty(), "runtime.earlyReturn must not reach the data source");
+ assertEquals(Map.of("cached", true), result.data());
+ }
+
+ @Test
+ void utilErrorFailsTheFieldWithItsOwnErrorType() {
+ Resolver resolver = resolver(ResolverKind.UNIT, "unit-code");
+ resolver.setDataSourceName("accountDB");
+ jsRuntime.script("unit-code", "request", (h, ctx) -> new JsEvaluation(null, Map.of(), false,
+ List.of(), new JsEvaluation.JsError("orgNo is required", "BadRequest",
+ Map.of("field", "orgNo"), null), false));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ assertNull(result.data());
+ assertTrue(invoker.requests.isEmpty(), "util.error must stop before the data source");
+ assertEquals(1, result.errors().size());
+ AppSyncResolverError error = result.errors().get(0);
+ assertEquals("orgNo is required", error.message());
+ // Clients switch on errorType, so it has to survive into the response extensions.
+ assertEquals("BadRequest", error.errorType());
+ assertEquals(Map.of("field", "orgNo"), error.data());
+ }
+
+ @Test
+ void appendedErrorsAreReturnedBesideTheData() {
+ when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
+ Resolver resolver = resolver(ResolverKind.UNIT, "unit-code");
+ resolver.setDataSourceName("accountDB");
+ jsRuntime.script("unit-code", "request", (h, ctx) -> ok(Map.of()));
+ jsRuntime.script("unit-code", "response", (h, ctx) -> new JsEvaluation(List.of("partial"),
+ Map.of(), false,
+ List.of(new JsEvaluation.JsError("one row was dropped", "Partial", null, null)),
+ null, false));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ // util.appendError is the one that does not stop anything: data and errors together.
+ assertEquals(List.of("partial"), result.data());
+ assertEquals(1, result.errors().size());
+ assertEquals("one row was dropped", result.errors().get(0).message());
+ }
+
+ @Test
+ void aFunctionWithNoResponseHandlerPassesTheDataSourceResultThrough() {
+ when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
+ when(appSync.getFunction(API_ID, "fn1")).thenReturn(function("fn1", "one", "accountDB", "fn1-code"));
+ Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
+ resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
+ jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(null));
+ jsRuntime.script("fn1-code", "request", (h, ctx) -> ok(Map.of("statement", "select 1")));
+ // No fn1-code#response script: the module exports none.
+ jsRuntime.script("pipeline-code", "response", (h, ctx) -> ok(ctx.get("result")));
+ invoker.answer = List.of(Map.of("id", 7));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ assertEquals(List.of(Map.of("id", 7)), result.data());
+ }
+
+ @Test
+ void aMissingPipelineFunctionFailsTheFieldByName() {
+ when(appSync.getFunction(API_ID, "gone"))
+ .thenThrow(new AwsException("NotFoundException", "Function not found: gone", 404));
+ Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
+ resolver.setPipelineConfig(Map.of("functions", List.of("gone")));
+ jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(null));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ assertEquals(1, result.errors().size());
+ assertTrue(result.errors().get(0).message().contains("gone"),
+ result.errors().get(0).message());
+ }
+
+ // ── ctx.error ────────────────────────────────────────────────────────────
+
+ @Test
+ void aDataSourceErrorReachesTheResponseHandlerAsCtxError() {
+ when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
+ Resolver resolver = resolver(ResolverKind.UNIT, "unit-code");
+ resolver.setDataSourceName("accountDB");
+ invoker.failure = new AwsException("DatabaseErrorException",
+ "ERROR: operator does not exist: timestamp >= character varying", 400);
+ jsRuntime.script("unit-code", "request", (h, ctx) -> ok(Map.of("statement", "select 1")));
+ jsRuntime.script("unit-code", "response", (h, ctx) -> ok(Map.of("handled", true)));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ // AppSync's shape, which a resolver forwards as util.error(ctx.error.message, ctx.error.type).
+ Map<?, ?> ctxError = (Map<?, ?>) jsRuntime.contexts.get(1).get("error");
+ assertEquals("ERROR: operator does not exist: timestamp >= character varying",
+ ctxError.get("message"));
+ assertEquals("DatabaseErrorException", ctxError.get("type"));
+ assertNull(jsRuntime.contexts.get(1).get("result"), "a failed call has no result");
+ // The handler returned a value and did not re-raise, so on AWS the error is suppressed.
+ assertEquals(Map.of("handled", true), result.data());
+ assertTrue(result.errors().isEmpty(),
+ "an error the response handler chose not to re-raise is suppressed");
+ }
+
+ @Test
+ void aResponseHandlerThatReRaisesCtxErrorFailsTheField() {
+ when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
+ Resolver resolver = resolver(ResolverKind.UNIT, "unit-code");
+ resolver.setDataSourceName("accountDB");
+ invoker.failure = new AwsException("DatabaseErrorException", "relation does not exist", 400);
+ jsRuntime.script("unit-code", "request", (h, ctx) -> ok(Map.of()));
+ // What `if (ctx.error) return util.error('Error getting messages', ctx.error.type, …)` does.
+ jsRuntime.script("unit-code", "response", (h, ctx) -> new JsEvaluation(null, Map.of(), false,
+ List.of(), new JsEvaluation.JsError("Error getting messages", "DatabaseErrorException",
+ "relation does not exist", null), false));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ assertNull(result.data());
+ assertEquals(1, result.errors().size());
+ AppSyncResolverError error = result.errors().get(0);
+ assertEquals("Error getting messages", error.message());
+ assertEquals("DatabaseErrorException", error.errorType());
+ }
+
+ @Test
+ void aDataSourceErrorWithNoResponseHandlerFailsTheField() {
+ when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
+ Resolver resolver = resolver(ResolverKind.UNIT, "unit-code");
+ resolver.setDataSourceName("accountDB");
+ invoker.failure = new AwsException("DatabaseErrorException", "connection refused", 500);
+ jsRuntime.script("unit-code", "request", (h, ctx) -> ok(Map.of()));
+ // No response script: the module exports none, so nothing can decide to suppress.
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ assertEquals(1, result.errors().size());
+ assertEquals("connection refused", result.errors().get(0).message());
+ assertEquals("DatabaseErrorException",
+ result.errors().get(0).errorType());
+ }
+
+ @Test
+ void aFunctionThatSuppressesItsErrorLetsThePipelineCarryOn() {
+ when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
+ when(appSync.getFunction(API_ID, "fn1")).thenReturn(function("fn1", "one", "accountDB", "fn1-code"));
+ when(appSync.getFunction(API_ID, "fn2")).thenReturn(function("fn2", "two", null, "fn2-code"));
+ Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
+ resolver.setPipelineConfig(Map.of("functions", List.of("fn1", "fn2")));
+ invoker.failure = new AwsException("DatabaseErrorException", "deadlock detected", 400);
+ jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(null));
+ jsRuntime.script("fn1-code", "request", (h, ctx) -> ok(Map.of()));
+ // Swallows the failure and substitutes an empty page, as a resolver may choose to.
+ jsRuntime.script("fn1-code", "response", (h, ctx) -> ok(List.of()));
+ jsRuntime.script("fn2-code", "request", (h, ctx) -> ok(Map.of()));
+ jsRuntime.script("fn2-code", "response", (h, ctx) -> ok(Map.of("items", ctx.get("result"))));
+ jsRuntime.script("pipeline-code", "response", (h, ctx) -> ok(ctx.get("result")));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ // fn2 ran, and saw fn1's substituted value as ctx.prev.result.
+ assertEquals(List.of("pipeline-code#request", "fn1-code#request", "fn1-code#response",
+ "fn2-code#request", "fn2-code#response", "pipeline-code#response"), jsRuntime.calls);
+ assertEquals(Map.of("result", List.of()), jsRuntime.contexts.get(3).get("prev"));
+ assertTrue(result.errors().isEmpty());
+ }
+
+ @Test
+ void aFunctionThatReRaisesStopsThePipeline() {
+ when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
+ when(appSync.getFunction(API_ID, "fn1")).thenReturn(function("fn1", "one", "accountDB", "fn1-code"));
+ when(appSync.getFunction(API_ID, "fn2")).thenReturn(function("fn2", "two", null, "fn2-code"));
+ Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
+ resolver.setPipelineConfig(Map.of("functions", List.of("fn1", "fn2")));
+ invoker.failure = new AwsException("DatabaseErrorException", "deadlock detected", 400);
+ jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(null));
+ jsRuntime.script("fn1-code", "request", (h, ctx) -> ok(Map.of()));
+ jsRuntime.script("fn1-code", "response", (h, ctx) -> new JsEvaluation(null, Map.of(), false,
+ List.of(), new JsEvaluation.JsError("query failed", "DatabaseErrorException", null, null),
+ false));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ // fn2 and the after step never run.
+ assertEquals(List.of("pipeline-code#request", "fn1-code#request", "fn1-code#response"),
+ jsRuntime.calls);
+ assertEquals(1, result.errors().size());
+ assertEquals("query failed", result.errors().get(0).message());
+ }
+
+ @Test
+ void aSuccessfulCallCarriesNoCtxError() {
+ when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
+ Resolver resolver = resolver(ResolverKind.UNIT, "unit-code");
+ resolver.setDataSourceName("accountDB");
+ jsRuntime.script("unit-code", "request", (h, ctx) -> ok(Map.of()));
+ jsRuntime.script("unit-code", "response", (h, ctx) -> ok("fine"));
+
+ executor.execute(resolver, invocation(Map.of()));
+
+ // Absent, not null: `if (ctx.error)` must be false, and the request handler never sees one.
+ assertFalse(jsRuntime.contexts.get(0).containsKey("error"));
+ assertFalse(jsRuntime.contexts.get(1).containsKey("error"));
+ }
+
+ // ── VTL is refused, not silently skipped ─────────────────────────────────
+
+ @Test
+ void aResolverWithMappingTemplatesAndNoCodeIsRefused() {
+ Resolver resolver = resolver(ResolverKind.UNIT, null);
+ resolver.setDataSourceName("accountDB");
+ resolver.setRequestMappingTemplate("{\"version\":\"2018-05-29\"}");
+ resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ // AppSync leaves Runtime unset on a VTL resolver, so "no runtime" must not read as
+ // APPSYNC_JS: that made this fall through to the pass-through arm and resolve to null,
+ // which is indistinguishable from an empty result.
+ assertEquals(1, result.errors().size());
+ assertTrue(result.errors().get(0).message().contains("VTL"),
+ result.errors().get(0).message());
+ assertTrue(invoker.requests.isEmpty(), "a VTL resolver must not reach the data source");
+ }
+
+ @Test
+ void aFunctionWithMappingTemplatesAndNoCodeIsRefused() {
+ when(appSync.getFunction(API_ID, "fn1")).thenReturn(vtlFunction("fn1"));
+ Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
+ resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
+ jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(null));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ assertEquals(1, result.errors().size());
+ assertTrue(result.errors().get(0).message().contains("VTL"),
+ result.errors().get(0).message());
+ }
+
+ @Test
+ void anExplicitVtlRuntimeIsRefusedEvenWithCode() {
+ Resolver resolver = resolver(ResolverKind.UNIT, "$util.toJson($ctx.args)");
+ resolver.setDataSourceName("accountDB");
+ Resolver.ResolverRuntime runtime = new Resolver.ResolverRuntime();
+ runtime.setName(ResolverRuntimeName.VTL);
+ resolver.setRuntime(runtime);
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ assertEquals(1, result.errors().size());
+ assertTrue(result.errors().get(0).message().contains("VTL"));
+ }
+
+ @Test
+ void aStageWithNeitherCodeNorTemplatesStillPassesThrough() {
+ when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
+ when(appSync.getFunction(API_ID, "fn1")).thenReturn(function("fn1", "one", "accountDB", null));
+ Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
+ resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
+ jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(null));
+ jsRuntime.script("pipeline-code", "response", (h, ctx) -> ok(ctx.get("result")));
+ invoker.answer = List.of(Map.of("id", 1));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ // No code and no templates is not VTL: there is simply nothing to run.
+ assertTrue(result.errors().isEmpty());
+ assertEquals(List.of(Map.of("id", 1)), result.data());
+ }
+
+ @Test
+ void aControlPlaneFailureLookingUpAFunctionIsNotReportedAsMissing() {
+ when(appSync.getFunction(API_ID, "fn1"))
+ .thenThrow(new AwsException("ConcurrentModificationException",
+ "Schema is being modified", 409));
+ Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
+ resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
+ jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(null));
+
+ ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
+
+ // Reporting a 409 as "function does not exist" hides the real cause.
+ assertEquals(1, result.errors().size());
+ assertEquals("Schema is being modified", result.errors().get(0).message());
+ assertEquals("ConcurrentModificationException",
+ result.errors().get(0).errorType());
+ }
+
+ private FunctionConfiguration vtlFunction(String id) {
+ FunctionConfiguration fn = new FunctionConfiguration();
+ fn.setFunctionId(id);
+ fn.setName("vtl-" + id);
+ fn.setDataSourceName("accountDB");
+ fn.setRequestMappingTemplate("{\"version\":\"2018-05-29\"}");
+ fn.setResponseMappingTemplate("$util.toJson($ctx.result)");
+ return fn;
+ }
+
+ @Test
+ void findResolverPropagatesAFailureThatIsNotAMissingResolver() {
+ when(appSync.getResolver(anyString(), anyString(), anyString()))
+ .thenThrow(new AwsException("ConcurrentModificationException",
+ "Schema is being modified", 409));
+
+ // Treating this as "no resolver" would make the field read as unresolved mid-deploy and
+ // quietly answer null.
+ assertThrows(AwsException.class, () -> executor.findResolver(API_ID, "Query", "getMessages"));
+ }
+
+ @Test
+ void findResolverAnswersNullWhenTheFieldHasNone() {
+ when(appSync.getResolver(anyString(), anyString(), anyString()))
+ .thenThrow(new AwsException("NotFoundException", "Resolver not found", 404));
+
+ // Null is what tells the data fetcher to fall back to reading the field off its source.
+ assertNull(executor.findResolver(API_ID, "Query", "unresolved"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackResourceTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackResourceTest.java
new file mode 100644
index 0000000000..0451f11a49
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackResourceTest.java
@@ -0,0 +1,218 @@
+package io.github.hectorvent.floci.services.appsync.graphql.resolver;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.appsync.model.Resolver;
+import jakarta.ws.rs.core.Response;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * The Floci half of the GraphQL sidecar's resolver callback: what it accepts, what it answers, and
+ * what it refuses. The invocation shape here is the one in {@code graphql/API.md} of
+ * floci-io/floci-sidecars, so a change to either side shows up as a failure in these assertions.
+ */
+class ResolverCallbackResourceTest {
+
+ private static final String API_ID = "api-1";
+
+ private final AppSyncResolverExecutor executor = mock(AppSyncResolverExecutor.class);
+ private final ResolverCallbackSessions sessions = new ResolverCallbackSessions();
+ private ResolverCallbackResource resource;
+ private ResolverCallbackSessions.Session session;
+
+ @BeforeEach
+ void setUp() {
+ resource = new ResolverCallbackResource(sessions, executor, new ObjectMapper());
+ session = sessions.open(API_ID, Map.of("sub", "u-1"), "AWS_IAM");
+ }
+
+ private String body(String... invocations) {
+ return "{\"invocations\":[" + String.join(",", invocations) + "]}";
+ }
+
+ private String invocation(String id, String typeName, String fieldName) {
+ return "{\"id\":\"" + id + "\",\"typeName\":\"" + typeName + "\",\"fieldName\":\"" + fieldName
+ + "\",\"arguments\":{\"orgNo\":\"7\"},\"source\":null,\"path\":[\"" + fieldName
+ + "\"],\"variables\":{},\"selectionSetList\":[\"id\",\"author/name\"]}";
+ }
+
+ @SuppressWarnings("unchecked")
+ private List<Map<String, Object>> results(Response response) {
+ assertEquals(200, response.getStatus());
+ return (List<Map<String, Object>>) ((Map<String, Object>) response.getEntity()).get("results");
+ }
+
+ private Resolver aResolver() {
+ Resolver resolver = new Resolver();
+ resolver.setTypeName("Query");
+ resolver.setFieldName("getMessages");
+ return resolver;
+ }
+
+ @Test
+ void aBatchIsAnsweredOncePerInvocationKeyedByItsOwnId() {
+ Resolver resolver = aResolver();
+ when(executor.findResolver(eq(API_ID), any(), any())).thenReturn(resolver);
+ when(executor.execute(eq(resolver), any()))
+ .thenReturn(new ResolverOutcome(Map.of("id", "1"), null, List.of()))
+ .thenReturn(new ResolverOutcome(Map.of("id", "2"), null, List.of()));
+
+ List<Map<String, Object>> results = results(resource.resolve("Bearer " + session.token(),
+ body(invocation("0", "Query", "getMessages"), invocation("1", "Query", "getMessages"))));
+
+ assertEquals(2, results.size());
+ assertEquals("0", results.get(0).get("id"));
+ assertEquals(Map.of("id", "1"), results.get(0).get("data"));
+ assertEquals("1", results.get(1).get("id"));
+ assertEquals(Map.of("id", "2"), results.get(1).get("data"));
+ }
+
+ @Test
+ void theInvocationCarriesEverythingTheExecutorUsedToReadOffTheGraphqlEnvironment() {
+ Resolver resolver = aResolver();
+ when(executor.findResolver(eq(API_ID), any(), any())).thenReturn(resolver);
+ when(executor.execute(eq(resolver), any())).thenReturn(new ResolverOutcome(null, null, List.of()));
+
+ resource.resolve("Bearer " + session.token(), body(invocation("0", "Query", "getMessages")));
+
+ org.mockito.ArgumentCaptor<ResolverInvocation> captor =
+ org.mockito.ArgumentCaptor.forClass(ResolverInvocation.class);
+ verify(executor).execute(eq(resolver), captor.capture());
+ ResolverInvocation invocation = captor.getValue();
+ assertEquals(API_ID, invocation.apiId());
+ assertEquals("Query", invocation.typeName());
+ assertEquals("getMessages", invocation.fieldName());
+ assertEquals(Map.of("orgNo", "7"), invocation.arguments());
+ assertEquals(List.of("getMessages"), invocation.path());
+ assertEquals(List.of("id", "author/name"), invocation.selectionSetList());
+ // The session is the only place these can come from: the callback itself is unauthenticated
+ // beyond its token, so it cannot be trusted to state who the caller is.
+ assertEquals(Map.of("sub", "u-1"), invocation.identity());
+ assertEquals("AWS_IAM", invocation.authType());
+ }
+
+ @Test
+ void aNullValuedArgumentIsPassedThroughRatherThanFailingTheWholeBatch() {
+ Resolver resolver = aResolver();
+ when(executor.findResolver(eq(API_ID), any(), any())).thenReturn(resolver);
+ when(executor.execute(eq(resolver), any())).thenReturn(new ResolverOutcome("ok", null, List.of()));
+
+ String withNull = "{\"id\":\"0\",\"typeName\":\"Query\",\"fieldName\":\"getMessages\","
+ + "\"arguments\":{\"nextToken\":null},\"variables\":{\"after\":null},"
+ + "\"path\":[\"getMessages\"],\"selectionSetList\":[\"id\"]}";
+ List<Map<String, Object>> results = results(resource.resolve("Bearer " + session.token(), body(withNull)));
+
+ // getMessages(nextToken: null) is ordinary GraphQL, and an explicit null is not the same as
+ // an absent argument to a resolver reading ctx.args. Copying the map with Map.copyOf threw
+ // on the null, which answered 500 and failed every field in the batch, not just this one.
+ assertEquals("ok", results.get(0).get("data"));
+ org.mockito.ArgumentCaptor<ResolverInvocation> captor =
+ org.mockito.ArgumentCaptor.forClass(ResolverInvocation.class);
+ verify(executor).execute(eq(resolver), captor.capture());
+ assertTrue(captor.getValue().arguments().containsKey("nextToken"));
+ assertNull(captor.getValue().arguments().get("nextToken"));
+ assertTrue(captor.getValue().variables().containsKey("after"));
+ assertNull(captor.getValue().variables().get("after"));
+ }
+
+ @Test
+ void aFailedResolverBecomesAnErrorResultCarryingTheTypeTheResolverChose() {
+ Resolver resolver = aResolver();
+ when(executor.findResolver(eq(API_ID), any(), any())).thenReturn(resolver);
+ when(executor.execute(eq(resolver), any())).thenReturn(new ResolverOutcome(null,
+ new AppSyncResolverError("orgNo is required", "BadRequest", Map.of("field", "orgNo"),
+ Map.of("hint", "pass one"), List.of("getMessages")),
+ List.of()));
+
+ List<Map<String, Object>> results = results(resource.resolve("Bearer " + session.token(),
+ body(invocation("0", "Query", "getMessages"))));
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> error = (Map<String, Object>) results.get(0).get("error");
+ assertEquals("orgNo is required", error.get("message"));
+ assertEquals("BadRequest", error.get("type"));
+ assertEquals(Map.of("field", "orgNo"), error.get("data"));
+ assertEquals(Map.of("hint", "pass one"), error.get("info"));
+ assertTrue(results.get(0).containsKey("error"));
+ }
+
+ @Test
+ void appendedErrorsRideTheSessionRatherThanReplacingTheData() {
+ Resolver resolver = aResolver();
+ AppSyncResolverError appended =
+ new AppSyncResolverError("one row was dropped", "Partial", null, null, List.of("getMessages"));
+ when(executor.findResolver(eq(API_ID), any(), any())).thenReturn(resolver);
+ when(executor.execute(eq(resolver), any()))
+ .thenReturn(new ResolverOutcome(List.of("partial"), null, List.of(appended)));
+
+ List<Map<String, Object>> results = results(resource.resolve("Bearer " + session.token(),
+ body(invocation("0", "Query", "getMessages"))));
+
+ // util.appendError means "report this AND keep the data", which the callback response has no
+ // way to say: it carries a value or an error, never both. So the data comes back here and
+ // the error travels on the session, to be merged into the response envelope.
+ assertEquals(List.of("partial"), results.get(0).get("data"));
+ assertNull(results.get(0).get("error"));
+ assertEquals(List.of(appended), session.appendedErrors());
+ }
+
+ @Test
+ void aFieldWhoseResolverVanishedFallsBackToTheSourceProperty() {
+ when(executor.findResolver(eq(API_ID), any(), any())).thenReturn(null);
+
+ String invocation = "{\"id\":\"0\",\"typeName\":\"Message\",\"fieldName\":\"name\","
+ + "\"source\":{\"name\":\"from the parent\"},\"path\":[\"getMessages\",0,\"name\"]}";
+ List<Map<String, Object>> results = results(resource.resolve("Bearer " + session.token(), body(invocation)));
+
+ assertEquals("from the parent", results.get(0).get("data"));
+ verify(executor, never()).execute(any(), any());
+ }
+
+ @Test
+ void aControlPlaneFailureLookingUpTheResolverFailsThatFieldOnly() {
+ when(executor.findResolver(eq(API_ID), any(), any()))
+ .thenThrow(new AwsException("ConcurrentModificationException", "Schema is being modified", 409));
+
+ List<Map<String, Object>> results = results(resource.resolve("Bearer " + session.token(),
+ body(invocation("0", "Query", "getMessages"))));
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> error = (Map<String, Object>) results.get(0).get("error");
+ assertEquals("Schema is being modified", error.get("message"));
+ assertEquals("ConcurrentModificationException", error.get("type"));
+ }
+
+ @Test
+ void anUnknownOrClosedTokenResolvesNothing() {
+ assertEquals(401, resource.resolve("Bearer not-a-token",
+ body(invocation("0", "Query", "getMessages"))).getStatus());
+ assertEquals(401, resource.resolve(null, body(invocation("0", "Query", "getMessages"))).getStatus());
+
+ String token = session.token();
+ session.close();
+ assertEquals(401, resource.resolve("Bearer " + token,
+ body(invocation("0", "Query", "getMessages"))).getStatus());
+ verify(executor, never()).execute(any(), any());
+ }
+
+ @Test
+ void aBodyThatIsNotAnInvocationBatchIsRefused() {
+ assertEquals(400, resource.resolve("Bearer " + session.token(), "not json").getStatus());
+ assertEquals(400, resource.resolve("Bearer " + session.token(), "{}").getStatus());
+ assertEquals(400, resource.resolve("Bearer " + session.token(), "{\"invocations\":{}}").getStatus());
+ }
+}