feat(appsync): execute VTL unit resolvers over NONE (#4356)

* feat(appsync): execute VTL unit resolvers over NONE

* fix(appsync): preserve pipeline early returns

* style(appsync): fix pipeline lookup indentation

* style(appsync): align pipeline result assignment
This commit is contained in:
XuJian authored and GitHub committed 2026-09-25 11:13:45 -04:00
1 parent 7334cac52b
commit 73ea1e2463
8 files changed
+512 -65

No files matched your search

+25 -8
View File
@@ -230,7 +230,7 @@ Responses are `application/json` with AWS AppSync wire shapes (`data` / `errors[
| Case | HTTP | Notes |
|---|---|---|
| Query / introspection / validation / syntax (incl. blank `query`) | 200 | Fields with an `APPSYNC_JS` resolver are resolved (see [Resolver execution](#resolver-execution)). A field with no resolver is `null`; one with a VTL mapping template fails with an error saying so, rather than resolving to `null` |
| Query / introspection / validation / syntax (incl. blank `query`) | 200 | Fields with an `APPSYNC_JS` resolver or a VTL UNIT resolver over `NONE` are resolved (see [Resolver execution](#resolver-execution)). A field with no resolver is `null` |
| HTTP subscription operation | 200 | `OperationNotSupported` (realtime WebSocket is a later phase) |
| Empty body / `{}` / `[]` / unparseable JSON / bad Content-Type | 400 | `MalformedHttpRequestException` |
| Missing `operationName` with multiple operations | 400 | `BadRequestException` — `Missing operation name.` |
@@ -273,11 +273,10 @@ Duplicate `API_KEY` / `AWS_IAM` / `AWS_LAMBDA` (and the same Cognito pool or OID
## Resolver execution
A field with an `APPSYNC_JS` resolver is executed, not stubbed: the resolver's own code runs, its
data source is called, and the field gets the value the code returned.
`VTL` mapping templates are **not** executed. A resolver declaring the VTL runtime fails its field
with a message saying so, rather than resolving to `null`: a null that means "not implemented" is
indistinguishable from a null that means "no rows".
data source is called, and the field gets the value the code returned. Floci also executes
`2018-05-29` VTL request and response templates for UNIT resolvers backed by a `NONE` data source.
VTL pipeline stages and VTL resolvers over other data sources remain explicit unsupported
operations rather than silently resolving to `null`.
### How a resolver gets called
@@ -338,6 +337,24 @@ determined lexically.
A rejected resolver fails its field with `errorType: UnsupportedFeature` and the line number, rather
than running.
### VTL UNIT resolvers
A VTL UNIT resolver over `NONE` evaluates the request mapping template, unwraps the request's
`payload`, and evaluates the response mapping template with that value in `ctx.result`. Request
templates must render a JSON object with `version: "2018-05-29"`; invalid JSON and unsupported
versions fail the field with `errorType: MappingTemplate`.
The VTL context includes `ctx.arguments` / `ctx.args`, `ctx.source`, `ctx.stash`, `ctx.result`,
`ctx.error`, `ctx.identity`, `ctx.request`, `ctx.info`, and `ctx.prev`. Stash mutations survive from
the request template to the response template. `#return` returns its value from the resolver,
skipping the remaining template and data-source work. `$util.error` fails the field with its
selected type and details, and
`$util.appendError` reports an error beside the returned data.
The existing VTL loop, output-size, timeout, and reflection-sandbox limits apply. The
`2017-02-28` template version, VTL pipeline functions, and VTL-backed DynamoDB, Lambda, RDS, and
other data sources are not included in this first execution slice.
| Setting | Env | Default |
|---|---|---|
| `floci.services.appsync.js-runtime.enabled` | `FLOCI_SERVICES_APPSYNC_JS_RUNTIME_ENABLED` | `true` |
@@ -388,7 +405,7 @@ environment variables). `ctx.request.headers` is empty: the GraphQL context does
| Type | Behaviour |
|---|---|
| `NONE` | The request is the result; a `payload` member is unwrapped, as on AWS. |
| `NONE` | The request is the result; a `payload` member is unwrapped, as on AWS. Supports APPSYNC_JS and `2018-05-29` VTL UNIT resolvers. |
| `AWS_LAMBDA` | `Invoke` and `BatchInvoke`. Only `payload` reaches the function. A function error fails the field rather than resolving to the error object. |
| `RELATIONAL_DATABASE` | Statements run over the RDS Data API against `rdsHttpEndpointConfig`. Accepts `{statements, variableMap}`, the `{statement, parameters}` the `/rds` helpers build, a list of either, or a bare SQL string. `variableTypeHintMap` is honoured, without it a bound date binds as text and PostgreSQL refuses the comparison (`operator does not exist: timestamp with time zone >= character varying`), so a resolver's date filters need it. The result is wrapped as `{sqlStatementResults: […]}`, which is what `toJsonObject()` reads. |
| `AMAZON_DYNAMODB` | `GetItem`, `PutItem`, `UpdateItem`, `DeleteItem`, `Query`, `Scan`, through the native DynamoDB path so expressions, conditions and indexes all apply. Items come back as **plain JSON**, not attribute values, as AppSync returns them. `nextToken` is an opaque encoding of `LastEvaluatedKey`. `BatchGetItem`, `TransactWriteItems` and `Sync` are not implemented and say so. |
@@ -440,7 +457,7 @@ This matches AWS behavior where deleting an API removes its entire configuration
These AWS AppSync capabilities are not yet implemented and are tracked in future phases:
- **DataFetcher / resolver dispatch** (Phase 8): resolver mapping templates and field resolution with non-null values
- **VTL resolver expansion**: pipeline functions, the `2017-02-28` version, and data sources beyond `NONE`
- **Data source adapters** (Phase 9): DynamoDB, Lambda, HTTP, EventBridge, OpenSearch, RDS connectors
- **Guardrails** (Phase 10): query depth / complexity limits and related errors
- **Realtime subscriptions** (Phase 11+): WebSocket real-time subscriptions
@@ -3,7 +3,10 @@ package io.github.hectorvent.floci.services.appsync.graphql;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.appsync.graphql.util.AppSyncUtil;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AppSyncVtlContext {
@@ -23,7 +26,8 @@ public class AppSyncVtlContext {
String authType,
ObjectMapper objectMapper
) {
this.contextMap = buildContextMap(arguments, source, identity, request, info, stash, prev, result);
this.contextMap = buildContextMap(arguments, source, identity, request, info, stash, prev,
result, null);
this.appendedErrors = new ArrayList<>();
this.util = new AppSyncUtil(objectMapper);
this.util.setErrorList(this.appendedErrors);
@@ -33,7 +37,7 @@ public class AppSyncVtlContext {
private AppSyncVtlContext(Builder builder) {
this.contextMap = buildContextMap(
builder.arguments, builder.source, builder.identity, builder.request,
builder.info, builder.stash, builder.prev, builder.result);
builder.info, builder.stash, builder.prev, builder.result, builder.error);
this.appendedErrors = new ArrayList<>();
this.util = new AppSyncUtil(builder.objectMapper);
this.util.setErrorList(this.appendedErrors);
@@ -42,23 +46,26 @@ public class AppSyncVtlContext {
private static Map<String, Object> buildContextMap(
Map<String, Object> arguments,
Map<String, Object> source,
Object source,
Map<String, Object> identity,
Map<String, Object> request,
Map<String, Object> info,
Map<String, Object> stash,
Map<String, Object> prev,
Object result) {
Object result,
Object error) {
Map<String, Object> map = new HashMap<>();
map.put("arguments", arguments != null ? arguments : Map.of());
map.put("source", source != null ? source : Map.of());
Map<String, Object> normalizedArguments = arguments != null ? arguments : Map.of();
map.put("arguments", normalizedArguments);
map.put("args", normalizedArguments);
map.put("source", source);
map.put("result", result);
map.put("identity", identity);
map.put("request", request != null ? request : Map.of("headers", Map.of()));
map.put("stash", stash != null ? stash : new HashMap<>());
map.put("prev", prev);
map.put("info", info != null ? info : Map.of());
map.put("error", null);
map.put("error", error);
return map;
}
@@ -81,13 +88,14 @@ public class AppSyncVtlContext {
public static class Builder {
private final ObjectMapper objectMapper;
private Map<String, Object> arguments;
private Map<String, Object> source;
private Object source;
private Map<String, Object> identity;
private Map<String, Object> request;
private Map<String, Object> info;
private Map<String, Object> stash;
private Map<String, Object> prev;
private Object result;
private Object error;
private String authType;
Builder(ObjectMapper objectMapper) {
@@ -99,7 +107,7 @@ public class AppSyncVtlContext {
return this;
}
public Builder source(Map<String, Object> source) {
public Builder source(Object source) {
this.source = source;
return this;
}
@@ -134,6 +142,11 @@ public class AppSyncVtlContext {
return this;
}
public Builder error(Object error) {
this.error = error;
return this;
}
public Builder authType(String authType) {
this.authType = authType;
return this;
@@ -44,7 +44,7 @@ public class AppSyncVtlEngine {
public AppSyncVtlResult evaluate(String template, AppSyncVtlContext ctx) {
if (template == null || template.isEmpty()) {
return new AppSyncVtlResult("", null, List.of());
return new AppSyncVtlResult("", null, List.of(), false);
}
VelocityContext vc = new VelocityContext();
@@ -67,12 +67,12 @@ public class AppSyncVtlEngine {
try {
engine.evaluate(vc, writer, "appsync-template", template);
} catch (ReturnSignal signal) {
return new AppSyncVtlResult(signal.getValue(), null, ctx.getAppendedErrors());
return new AppSyncVtlResult(signal.getValue(), null, ctx.getAppendedErrors(), true);
} catch (Exception e) {
Throwable cause = e;
while (cause != null) {
if (cause instanceof VtlErrorSignal signal) {
return new AppSyncVtlResult("", signal, ctx.getAppendedErrors());
return new AppSyncVtlResult("", signal, ctx.getAppendedErrors(), false);
}
cause = cause.getCause();
}
@@ -81,7 +81,7 @@ public class AppSyncVtlEngine {
VtlExecutionGuard.end();
}
return new AppSyncVtlResult(rawWriter.toString(), null, ctx.getAppendedErrors());
return new AppSyncVtlResult(rawWriter.toString(), null, ctx.getAppendedErrors(), false);
}
}
@@ -8,7 +8,8 @@ import java.util.Map;
public record AppSyncVtlResult(
Object output,
VtlErrorSignal error,
List<Map<String, Object>> appendedErrors
List<Map<String, Object>> appendedErrors,
boolean returned
) {
public boolean hasError() {
return error != null;
@@ -4,6 +4,8 @@ import io.github.hectorvent.floci.services.appsync.model.DataSource;
import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.Map;
/**
* The {@code NONE} data source: no backing store, the request is the result.
*
@@ -21,7 +23,7 @@ public class NoneDataSourceInvoker implements AppSyncDataSourceInvoker {
@Override
public Object invoke(DataSource dataSource, Object request, String region) {
if (request instanceof java.util.Map<?, ?> map && map.containsKey("payload")) {
if (request instanceof Map<?, ?> map && map.containsKey("payload")) {
return map.get("payload");
}
return request;
@@ -1,11 +1,18 @@
package io.github.hectorvent.floci.services.appsync.graphql.resolver;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncVtlContext;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncVtlEngine;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncVtlResult;
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.graphql.util.VtlErrorSignal;
import io.github.hectorvent.floci.services.appsync.model.DataSource;
import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
import io.github.hectorvent.floci.services.appsync.model.FunctionConfiguration;
import io.github.hectorvent.floci.services.appsync.model.Resolver;
import io.github.hectorvent.floci.services.appsync.model.ResolverKind;
@@ -38,11 +45,11 @@ import java.util.Map;
* 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.
* <p>Two things stop resolver execution early. {@code runtime.earlyReturn(value)} or VTL
* {@code #return(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 {
@@ -54,14 +61,20 @@ public class AppSyncResolverExecutor {
private final AppSyncService appSyncService;
private final AppSyncJsRuntime jsRuntime;
private final AppSyncDataSourceInvokers dataSourceInvokers;
private final AppSyncVtlEngine vtlEngine;
private final ObjectMapper objectMapper;
@Inject
public AppSyncResolverExecutor(AppSyncService appSyncService,
AppSyncJsRuntime jsRuntime,
AppSyncDataSourceInvokers dataSourceInvokers) {
AppSyncDataSourceInvokers dataSourceInvokers,
AppSyncVtlEngine vtlEngine,
ObjectMapper objectMapper) {
this.appSyncService = appSyncService;
this.jsRuntime = jsRuntime;
this.dataSourceInvokers = dataSourceInvokers;
this.vtlEngine = vtlEngine;
this.objectMapper = objectMapper;
}
/**
@@ -107,14 +120,16 @@ public class AppSyncResolverExecutor {
* 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) {
private record Stage(String code, ResolverRuntimeName runtime, boolean vtl,
String requestTemplate, String responseTemplate) {
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()));
resolver.getRequestMappingTemplate(), resolver.getResponseMappingTemplate()),
resolver.getRequestMappingTemplate(), resolver.getResponseMappingTemplate());
}
static Stage of(FunctionConfiguration function) {
@@ -122,7 +137,8 @@ public class AppSyncResolverExecutor {
? null : function.getRuntime().getName(),
isVtl(function.getCode(), function.getRuntime() == null
? null : function.getRuntime().getName(),
function.getRequestMappingTemplate(), function.getResponseMappingTemplate()));
function.getRequestMappingTemplate(), function.getResponseMappingTemplate()),
function.getRequestMappingTemplate(), function.getResponseMappingTemplate());
}
private static boolean isVtl(String code, ResolverRuntimeName runtime, String requestTemplate,
@@ -168,11 +184,15 @@ public class AppSyncResolverExecutor {
private ResolverOutcome runUnit() {
Stage stage = Stage.of(resolver);
DataSource vtlDataSource = stage.vtl()
? requireVtlNoneDataSource(resolver.getDataSourceName()) : null;
Object request = callHandler(stage, REQUEST, null, null, null);
if (returned) {
return result(earlyReturnValue);
}
Invocation invocation = invokeDataSource(resolver.getDataSourceName(), request);
Invocation invocation = stage.vtl()
? invokeDataSource(vtlDataSource, normalizeVtlNoneRequest(request))
: invokeDataSource(resolver.getDataSourceName(), request);
Object response = callHandler(stage, RESPONSE,
invocation.result(), invocation.error(), invocation.result());
return result(returned ? earlyReturnValue : response);
@@ -182,14 +202,15 @@ public class AppSyncResolverExecutor {
// 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);
rejectVtlPipelineStage(resolverStage, "resolver");
Object before = callHandler(resolverStage, REQUEST, null, null, null);
if (returned) {
return result(earlyReturnValue);
}
List<FunctionConfiguration> functions = pipelineFunctions();
previousResult = before;
for (String functionId : pipelineFunctionIds()) {
FunctionConfiguration function = function(functionId);
for (FunctionConfiguration function : functions) {
Stage functionStage = Stage.of(function);
Object request = callHandler(functionStage, REQUEST, null, null, null);
if (returned) {
@@ -237,12 +258,47 @@ public class AppSyncResolverExecutor {
}
}
private List<FunctionConfiguration> pipelineFunctions() {
List<FunctionConfiguration> functions = new ArrayList<>();
for (String functionId : pipelineFunctionIds()) {
FunctionConfiguration function = function(functionId);
rejectVtlPipelineStage(Stage.of(function), "function " + function.getName());
functions.add(function);
}
return functions;
}
private void rejectVtlPipelineStage(Stage stage, String stageName) {
if (stage.vtl()) {
throw new AwsException("UnsupportedOperation",
"Floci does not yet execute VTL " + stageName + " stages in PIPELINE resolvers", 400);
}
}
private DataSource requireVtlNoneDataSource(String dataSourceName) {
if (dataSourceName == null || dataSourceName.isBlank()) {
throw new AwsException("UnsupportedOperation",
"Floci currently executes VTL UNIT resolvers only with NONE data sources", 400);
}
DataSource dataSource = dataSource(dataSourceName);
if (dataSource.getType() != DataSourceType.NONE) {
throw new AwsException("UnsupportedOperation",
"Floci currently executes VTL UNIT resolvers only with NONE data sources; "
+ dataSourceName + " uses " + dataSource.getType(), 400);
}
return dataSource;
}
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);
}
return invokeDataSource(dataSource(dataSourceName), request);
}
private DataSource dataSource(String dataSourceName) {
DataSource dataSource;
try {
dataSource = appSyncService.getDataSource(apiId, dataSourceName);
@@ -252,6 +308,14 @@ public class AppSyncResolverExecutor {
throw new AwsException("InternalFailureException",
"Data source " + dataSourceName + " does not exist on API " + apiId, 500);
}
if (dataSource == null) {
throw new AwsException("InternalFailureException",
"Data source " + dataSourceName + " does not exist on API " + apiId, 500);
}
return dataSource;
}
private Invocation invokeDataSource(DataSource dataSource, Object request) {
try {
return new Invocation(dataSourceInvokers.invoke(dataSource, request, regionOf(dataSource)),
null);
@@ -259,13 +323,20 @@ public class AppSyncResolverExecutor {
// 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,
LOG.debugv("Data source {0} failed for {1}.{2}: {3}", dataSource.getName(),
resolver.getTypeName(), resolver.getFieldName(), e.getMessage());
return new Invocation(null,
new JsEvaluation.JsError(e.getMessage(), e.getErrorCode(), null, null));
}
}
private Object normalizeVtlNoneRequest(Object request) {
if (request instanceof Map<?, ?> map && !map.containsKey("payload")) {
return null;
}
return request;
}
/**
* One data source call's outcome: its result, or the error {@code ctx.error} carries into the
* response handler. Never both.
@@ -289,13 +360,9 @@ public class AppSyncResolverExecutor {
* {@code passThrough} here.
*/
private Object callHandler(Stage stage, String handler, Object result,
JsEvaluation.JsError error, Object passThrough) {
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);
return callVtlHandler(stage, handler, result, error);
}
String code = stage.code();
if (code == null || code.isBlank()) {
@@ -336,6 +403,130 @@ public class AppSyncResolverExecutor {
return evaluation.result();
}
private Object callVtlHandler(Stage stage, String handler, Object result,
JsEvaluation.JsError error) {
String template = REQUEST.equals(handler) ? stage.requestTemplate() : stage.responseTemplate();
if (template == null || template.isBlank()) {
throw mappingTemplateError("VTL " + handler + " mapping template is required");
}
Map<String, Object> previous = new LinkedHashMap<>();
previous.put("result", previousResult);
AppSyncVtlContext context = AppSyncVtlContext.builder(objectMapper)
.arguments(invocation.arguments())
.source(invocation.source())
.identity(identityMap())
.request(requestContext())
.info(info())
.stash(stash)
.prev(previous)
.result(result)
.error(errorMap(error))
.authType(invocation.authType())
.build();
AppSyncVtlResult evaluation;
try {
evaluation = vtlEngine.evaluate(template, context);
} catch (RuntimeException e) {
throw mappingTemplateError("VTL mapping template evaluation failed: " + rootMessage(e));
}
collectVtl(evaluation.appendedErrors());
if (evaluation.hasError()) {
VtlErrorSignal raised = evaluation.error();
throw resolverError(raised.getMessage(), raised.getErrorType(),
raised.getData(), raised.getErrorInfo());
}
if (evaluation.returned()) {
this.returned = true;
this.earlyReturnValue = evaluation.output();
return evaluation.output();
}
Object value = parseRenderedJson(evaluation.output(), handler);
if (REQUEST.equals(handler)) {
validateVtlRequest(value);
}
return value;
}
private Map<String, Object> identityMap() {
if (invocation.identity() instanceof Map<?, ?> values) {
Map<String, Object> identity = new LinkedHashMap<>();
values.forEach((key, value) -> identity.put(String.valueOf(key), value));
return identity;
}
return null;
}
private Map<String, Object> errorMap(JsEvaluation.JsError error) {
if (error == null) {
return null;
}
Map<String, Object> value = new LinkedHashMap<>();
value.put("message", error.message());
value.put("type", error.type());
return value;
}
private Object parseRenderedJson(Object output, String handler) {
if (!(output instanceof CharSequence rendered)) {
return output;
}
String text = rendered.toString().trim();
if (text.isEmpty()) {
return null;
}
try {
return objectMapper.readValue(text, Object.class);
} catch (JsonProcessingException e) {
throw mappingTemplateError("VTL " + handler + " mapping template did not render valid JSON");
}
}
private void validateVtlRequest(Object request) {
if (!(request instanceof Map<?, ?> map)) {
throw mappingTemplateError("VTL request mapping template must render a JSON object");
}
Object version = map.get("version");
if (!"2018-05-29".equals(version)) {
throw mappingTemplateError("VTL request mapping template must use version 2018-05-29");
}
for (Object key : map.keySet()) {
if (!"version".equals(key) && !"payload".equals(key)) {
throw mappingTemplateError("VTL NONE request mapping template supports only version and payload");
}
}
}
private ResolverRaisedException mappingTemplateError(String message) {
return resolverError(message, "MappingTemplate", null, null);
}
private ResolverRaisedException resolverError(String message, String type,
Object data, Object errorInfo) {
return new ResolverRaisedException(new AppSyncResolverError(message, type, data,
errorInfo, path));
}
private String rootMessage(RuntimeException failure) {
Throwable cause = failure;
while (cause.getCause() != null) {
cause = cause.getCause();
}
return cause.getMessage() == null ? cause.getClass().getSimpleName() : cause.getMessage();
}
private void collectVtl(List<Map<String, Object>> appended) {
if (appended == null) {
return;
}
appended.forEach(error -> errors.add(new AppSyncResolverError(
String.valueOf(error.get("message")),
String.valueOf(error.getOrDefault("type", "Unknown")),
error.get("data"), error.get("errorInfo"), path)));
}
private void collect(List<JsEvaluation.JsError> appended) {
if (appended == null) {
return;
@@ -82,6 +82,13 @@ class AppSyncVtlEngineTest {
assertEquals("123", result.output());
}
@Test
void b2b_ctxArgsAlias() {
AppSyncVtlContext ctx = ctxWith(builder -> builder.arguments(Map.of("id", "123")));
AppSyncVtlResult result = engine.evaluate("$ctx.args.id", ctx);
assertEquals("123", result.output());
}
@Test
void b3_argsShortcut() {
var ctx = ctxWith(b -> b.arguments(Map.of("id", "123")));
@@ -104,10 +111,10 @@ class AppSyncVtlEngineTest {
}
@Test
void b6_contextSourceEmptyForTopLevel() {
var ctx = ctxWith(b -> b.source(Map.of()));
void b6_contextSourceNullForTopLevel() {
var ctx = ctxWith(b -> b.source(null));
var result = engine.evaluate("$util.toJson($context.source)", ctx);
assertEquals("{}", result.output());
assertEquals("null", result.output());
}
@Test
@@ -1,7 +1,10 @@
package io.github.hectorvent.floci.services.appsync.graphql.resolver;
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.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncVtlEngine;
import io.github.hectorvent.floci.services.appsync.graphql.datasource.AppSyncDataSourceInvoker;
import io.github.hectorvent.floci.services.appsync.graphql.datasource.AppSyncDataSourceInvokers;
import io.github.hectorvent.floci.services.appsync.graphql.js.AppSyncJsRuntime;
@@ -26,6 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -39,9 +43,19 @@ class AppSyncResolverExecutorTest {
private final AppSyncService appSync = mock(AppSyncService.class);
private final ScriptedJsRuntime jsRuntime = new ScriptedJsRuntime();
private final RecordingInvoker invoker = new RecordingInvoker();
private final RecordingInvoker invoker = new RecordingInvoker(DataSourceType.RELATIONAL_DATABASE);
private final RecordingInvoker noneInvoker = new RecordingInvoker(DataSourceType.NONE);
private final ObjectMapper objectMapper = new ObjectMapper();
private final AppSyncResolverExecutor executor = new AppSyncResolverExecutor(appSync, jsRuntime,
new AppSyncDataSourceInvokers(List.of(invoker)));
new AppSyncDataSourceInvokers(List.of(invoker, noneInvoker)), vtlEngine(), objectMapper);
private static AppSyncVtlEngine vtlEngine() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().appsync().vtlMaxLoops()).thenReturn(10_000);
when(config.services().appsync().vtlMaxOutputChars()).thenReturn(1_048_576);
when(config.services().appsync().vtlTimeoutMillis()).thenReturn(5_000L);
return new AppSyncVtlEngine(config);
}
/** A JS runtime whose answers are supplied per (code, handler) by the test. */
private static final class ScriptedJsRuntime implements AppSyncJsRuntime {
@@ -76,13 +90,18 @@ class AppSyncResolverExecutorTest {
/** Records what reached the data source and answers with whatever the test set. */
private static final class RecordingInvoker implements AppSyncDataSourceInvoker {
private final DataSourceType type;
private final List<Object> requests = new ArrayList<>();
private Object answer = Map.of();
private AwsException failure;
private RecordingInvoker(DataSourceType type) {
this.type = type;
}
@Override
public DataSourceType type() {
return DataSourceType.RELATIONAL_DATABASE;
return type;
}
@Override
@@ -91,6 +110,12 @@ class AppSyncResolverExecutorTest {
if (failure != null) {
throw failure;
}
if (type == DataSourceType.NONE) {
if (request instanceof Map<?, ?> map && map.containsKey("payload")) {
return map.get("payload");
}
return request;
}
return answer;
}
}
@@ -104,9 +129,13 @@ class AppSyncResolverExecutorTest {
}
private DataSource dataSource(String name) {
return dataSource(name, DataSourceType.RELATIONAL_DATABASE);
}
private DataSource dataSource(String name, DataSourceType type) {
DataSource ds = new DataSource();
ds.setName(name);
ds.setType(DataSourceType.RELATIONAL_DATABASE);
ds.setType(type);
ds.setDataSourceArn("arn:aws:appsync:eu-west-1:000000000000:apis/" + API_ID + "/datasources/" + name);
return ds;
}
@@ -131,7 +160,12 @@ class AppSyncResolverExecutorTest {
}
private ResolverInvocation invocation(Map<String, Object> arguments) {
return new ResolverInvocation(API_ID, "Query", "getThing", arguments, null, null, null, null, null, null);
return invocation(arguments, null);
}
private ResolverInvocation invocation(Map<String, Object> arguments, Object source) {
return new ResolverInvocation(API_ID, "Query", "getThing", arguments, source,
null, null, null, null, null);
}
@Test
@@ -204,7 +238,7 @@ class AppSyncResolverExecutorTest {
@Test
void earlyReturnInTheBeforeStepSkipsTheFunctionsAndTheAfterStep() {
Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
resolver.setPipelineConfig(Map.of("functions", List.of("missing")));
jsRuntime.script("pipeline-code", "request", (h, ctx) ->
new JsEvaluation(Map.of("cached", true), Map.of(), true, List.of(), null, false));
@@ -413,42 +447,224 @@ class AppSyncResolverExecutorTest {
assertFalse(jsRuntime.contexts.get(1).containsKey("error"));
}
// ── VTL is refused, not silently skipped ─────────────────────────────────
// ── VTL UNIT resolvers over NONE ─────────────────────────────────────────
@Test
void aResolverWithMappingTemplatesAndNoCodeIsRefused() {
void jsNoneRequestWithVtlVersionMemberRemainsTheRequestObject() {
when(appSync.getDataSource(API_ID, "local")).thenReturn(dataSource("local", DataSourceType.NONE));
Resolver resolver = resolver(ResolverKind.UNIT, "unit-code");
resolver.setDataSourceName("local");
Map<String, Object> request = Map.of("version", "2018-05-29");
jsRuntime.script("unit-code", "request", (h, ctx) -> ok(request));
jsRuntime.script("unit-code", "response", (h, ctx) -> ok(ctx.get("result")));
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
assertTrue(result.errors().isEmpty());
assertEquals(request, result.data());
assertEquals(List.of(request), noneInvoker.requests);
}
@Test
void vtlUnitResolverUsesArgumentsSourceStashAndResult() {
when(appSync.getDataSource(API_ID, "local")).thenReturn(dataSource("local", DataSourceType.NONE));
Resolver resolver = resolver(ResolverKind.UNIT, null);
resolver.setDataSourceName("accountDB");
resolver.setDataSourceName("local");
resolver.setRequestMappingTemplate("""
#set($discard = $ctx.stash.put("prefix", $ctx.source.prefix))
{"version":"2018-05-29","payload":{
"id":$util.toJson($ctx.args.id),
"source":$util.toJson($ctx.source.prefix)
}}
""");
resolver.setResponseMappingTemplate("""
{"id":$util.toJson($ctx.result.id),
"source":$util.toJson($ctx.result.source),
"stash":$util.toJson($ctx.stash.prefix)}
""");
ResolverOutcome result = executor.execute(resolver,
invocation(Map.of("id", "42"), Map.of("prefix", "parent")));
assertTrue(result.errors().isEmpty());
assertEquals(Map.of("id", "42", "source", "parent", "stash", "parent"), result.data());
assertEquals(1, noneInvoker.requests.size());
assertEquals("2018-05-29", ((Map<?, ?>) noneInvoker.requests.get(0)).get("version"));
}
@Test
void vtlReturnHandsTheValueDirectlyToTheField() {
when(appSync.getDataSource(API_ID, "local")).thenReturn(dataSource("local", DataSourceType.NONE));
Resolver resolver = resolver(ResolverKind.UNIT, null);
resolver.setDataSourceName("local");
resolver.setRequestMappingTemplate("""
{"version":"2018-05-29","payload":{"id":$util.toJson($ctx.args.id)}}
""");
resolver.setResponseMappingTemplate("#return($ctx.result)");
ResolverOutcome result = executor.execute(resolver, invocation(Map.of("id", "42")));
assertEquals(Map.of("id", "42"), result.data());
assertTrue(result.errors().isEmpty());
}
@Test
void vtlReturnFromRequestSkipsTheDataSourceAndResponseTemplate() {
when(appSync.getDataSource(API_ID, "local")).thenReturn(dataSource("local", DataSourceType.NONE));
Resolver resolver = resolver(ResolverKind.UNIT, null);
resolver.setDataSourceName("local");
resolver.setRequestMappingTemplate("#return({\"short\":\"circuit\"})");
resolver.setResponseMappingTemplate("$util.error(\"response should not run\")");
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
assertEquals(Map.of("short", "circuit"), result.data());
assertTrue(result.errors().isEmpty());
assertTrue(noneInvoker.requests.isEmpty());
}
@Test
void vtlNoneRequestWithoutPayloadProducesNullResult() {
when(appSync.getDataSource(API_ID, "local")).thenReturn(dataSource("local", DataSourceType.NONE));
Resolver resolver = resolver(ResolverKind.UNIT, null);
resolver.setDataSourceName("local");
resolver.setRequestMappingTemplate("{\"version\":\"2018-05-29\"}");
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
// AppSync leaves Runtime unset on a VTL resolver, so "no runtime" must not read as
// APPSYNC_JS: that made this fall through to the pass-through arm and resolve to null,
// which is indistinguishable from an empty result.
assertEquals(1, result.errors().size());
assertTrue(result.errors().get(0).message().contains("VTL"),
result.errors().get(0).message());
assertTrue(invoker.requests.isEmpty(), "a VTL resolver must not reach the data source");
assertNull(result.data());
assertTrue(result.errors().isEmpty());
}
@Test
void aFunctionWithMappingTemplatesAndNoCodeIsRefused() {
when(appSync.getFunction(API_ID, "fn1")).thenReturn(vtlFunction("fn1"));
void vtlNoneRequestRejectsUnsupportedMembers() {
when(appSync.getDataSource(API_ID, "local")).thenReturn(dataSource("local", DataSourceType.NONE));
Resolver resolver = resolver(ResolverKind.UNIT, null);
resolver.setDataSourceName("local");
resolver.setRequestMappingTemplate("{\"version\":\"2018-05-29\",\"operation\":\"GetItem\"}");
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
assertNull(result.data());
assertEquals(1, result.errors().size());
assertEquals("MappingTemplate", result.errors().get(0).errorType());
assertTrue(noneInvoker.requests.isEmpty());
}
@Test
void vtlAppendErrorKeepsTheResponseData() {
when(appSync.getDataSource(API_ID, "local")).thenReturn(dataSource("local", DataSourceType.NONE));
Resolver resolver = resolver(ResolverKind.UNIT, null);
resolver.setDataSourceName("local");
resolver.setRequestMappingTemplate("""
{"version":"2018-05-29","payload":{"id":"1"}}
""");
resolver.setResponseMappingTemplate("""
$util.appendError("partial", "Partial", {"id":"1"})
$util.toJson($ctx.result)
""");
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
assertEquals(Map.of("id", "1"), result.data());
assertEquals(1, result.appendedErrors().size());
assertEquals("partial", result.appendedErrors().get(0).message());
assertEquals("Partial", result.appendedErrors().get(0).errorType());
assertEquals(Map.of("id", "1"), result.appendedErrors().get(0).data());
}
@Test
void vtlUtilErrorFailsTheFieldWithTheChosenDetails() {
when(appSync.getDataSource(API_ID, "local")).thenReturn(dataSource("local", DataSourceType.NONE));
Resolver resolver = resolver(ResolverKind.UNIT, null);
resolver.setDataSourceName("local");
resolver.setRequestMappingTemplate("""
{"version":"2018-05-29","payload":{"id":"1"}}
""");
resolver.setResponseMappingTemplate(
"$util.error(\"denied\", \"Denied\", {\"id\":\"1\"}, {\"retry\":false})");
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
assertNull(result.data());
assertEquals(1, result.errors().size());
assertEquals("denied", result.errors().get(0).message());
assertEquals("Denied", result.errors().get(0).errorType());
assertEquals(Map.of("id", "1"), result.errors().get(0).data());
assertEquals(Map.of("retry", false), result.errors().get(0).errorInfo());
}
@Test
void vtlResponseCanInspectAndSuppressADataSourceError() {
when(appSync.getDataSource(API_ID, "local")).thenReturn(dataSource("local", DataSourceType.NONE));
noneInvoker.failure = new AwsException("LocalFailure", "none failed", 500);
Resolver resolver = resolver(ResolverKind.UNIT, null);
resolver.setDataSourceName("local");
resolver.setRequestMappingTemplate("{\"version\":\"2018-05-29\"}");
resolver.setResponseMappingTemplate("$util.toJson({\"handled\":$ctx.error.type})");
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
assertEquals(Map.of("handled", "LocalFailure"), result.data());
assertTrue(result.errors().isEmpty());
noneInvoker.failure = null;
}
@Test
void vtlRequestReturnCannotBypassNonNoneDataSourceValidation() {
when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
Resolver resolver = resolver(ResolverKind.UNIT, null);
resolver.setDataSourceName("accountDB");
resolver.setRequestMappingTemplate("#return({\"short\":\"circuit\"})");
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
assertEquals(1, result.errors().size());
assertEquals("UnsupportedOperation", result.errors().get(0).errorType());
assertTrue(result.errors().get(0).message().contains("VTL"));
assertTrue(invoker.requests.isEmpty());
}
@Test
void vtlRequestReturnCannotBypassMissingDataSourceValidation() {
Resolver resolver = resolver(ResolverKind.UNIT, null);
resolver.setRequestMappingTemplate("#return({\"short\":\"circuit\"})");
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
assertNull(result.data());
assertEquals(1, result.errors().size());
assertEquals("UnsupportedOperation", result.errors().get(0).errorType());
assertTrue(noneInvoker.requests.isEmpty());
}
@Test
void aLaterVtlFunctionIsRejectedBeforeAnyPipelineStageRuns() {
when(appSync.getFunction(API_ID, "fn1"))
.thenReturn(function("fn1", "one", "accountDB", "fn1-code"));
when(appSync.getFunction(API_ID, "fn2")).thenReturn(vtlFunction("fn2"));
Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
resolver.setPipelineConfig(Map.of("functions", List.of("fn1", "fn2")));
jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(null));
jsRuntime.script("fn1-code", "request", (h, ctx) -> ok(Map.of()));
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
assertEquals(1, result.errors().size());
assertTrue(result.errors().get(0).message().contains("VTL"),
result.errors().get(0).message());
assertEquals("UnsupportedOperation", result.errors().get(0).errorType());
assertEquals(List.of("pipeline-code#request"), jsRuntime.calls);
assertTrue(invoker.requests.isEmpty());
}
@Test
void anExplicitVtlRuntimeIsRefusedEvenWithCode() {
when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
Resolver resolver = resolver(ResolverKind.UNIT, "$util.toJson($ctx.args)");
resolver.setDataSourceName("accountDB");
Resolver.ResolverRuntime runtime = new Resolver.ResolverRuntime();