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

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

A field with a resolver resolved to null: no data fetchers were registered, so graphql-java
fell through to its property fetcher on an empty root. This runs the resolver instead, for
UNIT and PIPELINE alike, over NONE, AWS_LAMBDA, RELATIONAL_DATABASE and AMAZON_DYNAMODB data
sources.

Resolver JavaScript runs in a Node sidecar container rather than in process. 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. @aws-appsync/utils is a shim the sidecar writes at boot rather than the
published package, so a resolver call never depends on npm being reachable.

The pipeline follows AppSync's: ctx.stash threads through every stage, each stage sees the last
as ctx.prev.result, runtime.earlyReturn stops everything, util.error fails the field with the
type the resolver chose, and util.appendError returns its errors beside the data. A data source
failure does not fail the field on its own: the stage's response() handler is called with
ctx.error set and decides whether to re-raise or suppress, which is why resolvers carry an
explicit if (ctx.error) branch.

VTL mapping templates are not executed. A VTL stage fails its field saying so rather than
resolving to null, since a null that means "not implemented" is indistinguishable from a null
that means "no rows".

Carries model/FunctionConfiguration and AppSyncService so it builds and tests standalone; both
are identical to the copies in the AppSync CloudFormation change and collapse on merge.

* feat(appsync): enforce the APPSYNC_JS subset before evaluating resolver code

The sidecar is real Node, so it accepted JavaScript AWS rejects: async functions, promises,
classes, try/catch, while loops, this, and imports of Node builtins. For an emulator that is
the worst failure available, since a local run green-lights resolver code that cannot deploy.

Imports are restricted by a module resolve hook rather than a source scan, so a dynamic import
of a builtin cannot slip past either. An async handler is caught before it runs and a handler
returning a promise after. The remaining constructs are found by scanning the source with
comments, strings and template text blanked first, so the same keywords inside them are not
flagged. A rejected resolver fails its field with errorType UnsupportedFeature and the line.

Enforcement is on by default and can be turned off with
floci.services.appsync.js-runtime.enforce-appsync-subset, which exists only so a false positive
cannot block someone whose code AWS does accept.

Checking real resolvers against it found a gap of the same kind in the other direction:
@aws-appsync/utils/dynamodb is a real module the shim did not provide, so valid code was being
rejected. It now implements get, put and remove; the helpers that compile a condition or update
expression throw by name rather than returning something the data source would mishandle.

Also from review: cap the /evaluate request body, keep integer precision in the DynamoDB NS
branch as the N branch already did, reject two SQL parameters bound to the same name instead of
letting the Data API report it, drop the container id and close the log follower in reset(), and
bound the docker probe in the integration test so an unresponsive daemon cannot hang CI.

* feat(appsync): add the js-runtime url knob and stop the sidecar through ContainerTeardown

Follows the sidecar contract the other managed containers use. floci.services.appsync.
js-runtime.url points the runtime at a Node server that is already running, in which case
ensureStarted skips container management entirely: nothing is created, adopted or stopped, and
the URL is probed with the short adopt budget so a wrong one says so instead of holding the
first resolver for the full start timeout. Same shape and meaning as floci.services.duck.url.

NodeAppSyncJsRuntime now implements ContainerTeardown, so EmulatorLifecycle stops the sidecar
with the other process-bound containers at a deterministic point rather than only through
@PreDestroy, which the interface documents as running too late for the final storage flush.
Teardown is a no-op for a pre-configured URL, since that server is not ours to stop.

* fix(appsync): serialize reset() and stop the sidecar it gives up on

reset() touched started, baseUrl, containerId and logStream without holding the monitor that
ensureStarted() and stopManagedContainers() both take. A failed evaluation could therefore clear
those fields in the window after a container had been created and its id recorded but before
started was set, dropping the only handle to a live container: teardown then saw a null id,
treated the sidecar as never started, and the container was leaked rather than stopped.

reset() is now synchronized on the same monitor, and reentrant so the callers already holding it
are unaffected. The failure path in post() goes through discardSidecar(), which stops and removes
the container before clearing the fields instead of forgetting it, since forgetting is what leaks:
nothing else holds the id. A pre-configured url owns no container, so teardown there stays a no-op.

The regression races eight failing evaluations against startup and asserts every container the
runtime created was also stopped. It needs a transport-level failure to reach the path: a 500 is
rethrown as an AwsException before it, so the stub drops the connection instead. Against the
previous reset() it fails with expected <[container-1]> but was <[]>.

* refactor(appsync): run resolvers through the GraphQL sidecar callback

out of Floci, which left this branch building DataFetchers for a schema that no
longer has any. Resolver execution moves onto the sidecar's batched resolver
callback instead, so the engine stays in the sidecar and the resolvers, the data
sources and the Node runtime stay here.

/v1/execute now carries a resolve block naming every planned coordinate that has
a resolver, with a callback URL and a token minted for that one operation. The
sidecar batches each execution level into one POST /appsync-resolve, which runs
the field's resolver and answers with a value or an error. denyFields still win,
so a denied coordinate is never listed and never reaches a resolver, and the
token stops working as soon as the operation returns.

AppSyncResolverExecutor takes a ResolverInvocation record instead of a
DataFetchingEnvironment. Every value it read off the environment is on the
record, so the pipeline, the data source invokers and the JS runtime are
unchanged. ResolverDataFetcher is gone: fields with no resolver are the sidecar's
own property fetcher again, and a resolver that disappears mid-operation falls
back to the source property rather than failing.

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, so those errors come back on the operation's session and are
merged into the response envelope, which keeps data and appended errors together
as AppSync returns them.

Also gives the sidecar container host.docker.internal on Linux, since it now has
to reach Floci back, moves the JS runtime image pin into application.yml so CI
prefetches it the way it does the sidecar pins, and puts the Docker integration
test on the shared AppSyncGraphqlSidecarProfile so it is namespaced and gated
like the other AppSync integration tests.

* ci(appsync): prefetch the Node image only on the shard that starts it

The js-runtime prefetch matched /appsync/, so all four shards pulled
node:22-alpine although only the shard carrying
AppSyncJsResolverDockerIntegrationTest starts that container. Every other test
in the package is a unit test. Matching the class name instead is three fewer
Docker Hub pulls per run, which is what this script exists to avoid.

* fix(appsync): keep null arguments and move the resolver callback under _floci

Two review points from #3422.

ResolverInvocation copied arguments and variables with Map.copyOf, which rejects
a null value, so getMessages(nextToken: null) threw out of the callback and
answered 500. That failed every field in the batch, not only the field carrying
the null. Both copies are now null tolerant, and an explicit null stays
distinguishable from an absent argument: it is present in ctx.args and null,
where an absent one is not there at all.

The callback moves from /appsync-resolve to /_floci/appsync/resolve, with the
EKS webhooks. 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 the
prefix cannot be shadowed.

The null case is covered both ways: a unit test in ResolverCallbackResourceTest
that fails with a NullPointerException against the previous code, and three
queries in the Docker round trip covering an explicit null, its value reaching
ctx.args, and an absent argument for contrast.
This commit is contained in:
Anders Wasen authored and GitHub committed 2026-09-22 14:41:55 -04:00
1 parent 235ee91a76
commit 27633bf94d
35 files changed
+5488 -12

No files matched your search

@@ -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 {
@@ -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);
}
@@ -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);
@@ -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;
}
@@ -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()) {
@@ -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);
}
@@ -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);
}
}
@@ -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);
}
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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();
}
@@ -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);
}
}
}
@@ -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();
}
}
@@ -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) {
}
@@ -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;
}
}
}
@@ -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;
}
}
}
@@ -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));
}
}
@@ -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));
}
}
@@ -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);
}
}