mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(appsync): execute VTL pipeline resolvers on sidecar (#4586)
* feat(appsync): execute VTL pipeline functions * fix(appsync): validate VTL functions before early return
This commit is contained in:
1 parent
1465251e0c
commit
95cbe7de34
4 files changed
+344
-62
No files matched your search
+24
-14
@@ -274,9 +274,9 @@ Duplicate `API_KEY` / `AWS_IAM` / `AWS_LAMBDA` (and the same Cognito pool or OID
|
||||
|
||||
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. Floci also executes
|
||||
`2018-05-29` VTL request and response templates for UNIT resolvers backed by `NONE`, DynamoDB,
|
||||
Lambda, or RDS data sources. VTL pipeline stages and VTL resolvers over other data sources remain
|
||||
explicit unsupported operations rather than silently resolving to `null`.
|
||||
`2018-05-29` VTL request and response templates for UNIT and PIPELINE resolvers backed by `NONE`,
|
||||
DynamoDB, Lambda, or RDS data sources. VTL resolvers over other data sources remain explicit
|
||||
unsupported operations rather than silently resolving to `null`.
|
||||
|
||||
### How a resolver gets called
|
||||
|
||||
@@ -354,7 +354,7 @@ determined lexically.
|
||||
A rejected resolver fails its field with `errorType: UnsupportedFeature` and the line number, rather
|
||||
than running.
|
||||
|
||||
### VTL UNIT resolvers
|
||||
### VTL resolvers
|
||||
|
||||
A VTL UNIT resolver evaluates the request mapping template, sends the rendered request through the
|
||||
same data source invoker used by APPSYNC_JS, and evaluates the response mapping template with the
|
||||
@@ -362,6 +362,15 @@ answer in `ctx.result`. Request templates must render a JSON object with
|
||||
`version: "2018-05-29"`; invalid JSON, unsupported versions, and malformed data source requests
|
||||
fail the field with `errorType: MappingTemplate`.
|
||||
|
||||
A VTL PIPELINE resolver evaluates its request mapping template as the before step, then runs each
|
||||
configured function's request template, data source, and response template before evaluating the
|
||||
resolver response template as the after step. The previous stage's value is available as
|
||||
`ctx.prev.result`, and one shared `ctx.stash` survives across every stage. VTL and APPSYNC_JS stages
|
||||
can be mixed in the same pipeline.
|
||||
|
||||
VTL functions use their configured `functionVersion`, currently `2018-05-29`. Like UNIT resolvers,
|
||||
their request templates must render a `version: "2018-05-29"` member for the data source request.
|
||||
|
||||
Supported request documents are:
|
||||
|
||||
- `NONE`: `version` plus an optional `payload`, which is unwrapped into `ctx.result`.
|
||||
@@ -382,14 +391,15 @@ APPSYNC_JS execution path. Valid AppSync operations that the invoker does not im
|
||||
|
||||
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
|
||||
the request template to the response template. `#return` in a resolver template returns its value
|
||||
from the resolver and skips the remaining pipeline. In a function template it returns from that
|
||||
function, skips any remaining work in the function, and continues with the next function or the
|
||||
after template. `$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 HTTP, EventBridge,
|
||||
OpenSearch, and Bedrock data sources are not included.
|
||||
`2017-02-28` template version and VTL-backed HTTP, EventBridge, OpenSearch, and Bedrock data sources
|
||||
are not included.
|
||||
|
||||
| Setting | Env | Default |
|
||||
|---|---|---|
|
||||
@@ -441,10 +451,10 @@ 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. Supports APPSYNC_JS and `2018-05-29` VTL UNIT resolvers. |
|
||||
| `AWS_LAMBDA` | `Invoke` and `BatchInvoke` for APPSYNC_JS, and `Invoke` for `2018-05-29` VTL UNIT resolvers. Both runtimes send only the resolved `payload` to the function; `BatchInvoke` sends the payload list. 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. Supports APPSYNC_JS and `2018-05-29` VTL UNIT resolvers. |
|
||||
| `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. Supports APPSYNC_JS and `2018-05-29` VTL UNIT resolvers. |
|
||||
| `NONE` | The request is the result; a `payload` member is unwrapped, as on AWS. Supports APPSYNC_JS plus `2018-05-29` VTL UNIT resolvers and pipeline functions. |
|
||||
| `AWS_LAMBDA` | `Invoke` and `BatchInvoke` for APPSYNC_JS, and `Invoke` for `2018-05-29` VTL UNIT resolvers and pipeline functions. Both runtimes send only the resolved `payload` to the function; `BatchInvoke` sends the payload list. 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. Supports APPSYNC_JS plus `2018-05-29` VTL UNIT resolvers and pipeline functions. |
|
||||
| `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. Supports APPSYNC_JS plus `2018-05-29` VTL UNIT resolvers and pipeline functions. |
|
||||
| `HTTP`, `AMAZON_EVENTBRIDGE`, `AMAZON_OPENSEARCH_SERVICE`, `AMAZON_BEDROCK_RUNTIME` | Not implemented; a resolver using one fails its field naming the type. |
|
||||
|
||||
A field with no resolver falls back to reading its value off the parent object, which is how the
|
||||
@@ -493,7 +503,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:
|
||||
|
||||
- **VTL resolver expansion**: pipeline functions, the `2017-02-28` version, and the remaining data sources
|
||||
- **VTL resolver expansion**: the `2017-02-28` version and the remaining data sources
|
||||
- **Data source adapters**: HTTP, EventBridge, OpenSearch, and Bedrock connectors
|
||||
- **Guardrails** (Phase 10): query depth / complexity limits and related errors
|
||||
- **Realtime subscriptions** (Phase 11+): WebSocket real-time subscriptions
|
||||
|
||||
+60
-35
@@ -47,8 +47,9 @@ import java.util.Set;
|
||||
* there the error fails the field.
|
||||
*
|
||||
* <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 #return(value)} in a resolver template makes {@code value} the field's result immediately,
|
||||
* skipping everything left including the after step, and {@code util.error()} fails the field. A
|
||||
* VTL function's {@code #return(value)} only returns from that function and the pipeline continues.
|
||||
* {@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.
|
||||
*/
|
||||
@@ -127,7 +128,8 @@ public class AppSyncResolverExecutor {
|
||||
* as if it had no handler instead of saying it is unsupported.
|
||||
*/
|
||||
private record Stage(String code, ResolverRuntimeName runtime, boolean vtl,
|
||||
String requestTemplate, String responseTemplate) {
|
||||
String requestTemplate, String responseTemplate,
|
||||
String functionVersion, boolean function) {
|
||||
|
||||
static Stage of(Resolver resolver) {
|
||||
return new Stage(resolver.getCode(), resolver.getRuntime() == null
|
||||
@@ -135,7 +137,8 @@ public class AppSyncResolverExecutor {
|
||||
isVtl(resolver.getCode(), resolver.getRuntime() == null
|
||||
? null : resolver.getRuntime().getName(),
|
||||
resolver.getRequestMappingTemplate(), resolver.getResponseMappingTemplate()),
|
||||
resolver.getRequestMappingTemplate(), resolver.getResponseMappingTemplate());
|
||||
resolver.getRequestMappingTemplate(), resolver.getResponseMappingTemplate(),
|
||||
null, false);
|
||||
}
|
||||
|
||||
static Stage of(FunctionConfiguration function) {
|
||||
@@ -144,7 +147,8 @@ public class AppSyncResolverExecutor {
|
||||
isVtl(function.getCode(), function.getRuntime() == null
|
||||
? null : function.getRuntime().getName(),
|
||||
function.getRequestMappingTemplate(), function.getResponseMappingTemplate()),
|
||||
function.getRequestMappingTemplate(), function.getResponseMappingTemplate());
|
||||
function.getRequestMappingTemplate(), function.getResponseMappingTemplate(),
|
||||
function.getFunctionVersion(), true);
|
||||
}
|
||||
|
||||
private static boolean isVtl(String code, ResolverRuntimeName runtime, String requestTemplate,
|
||||
@@ -173,6 +177,8 @@ public class AppSyncResolverExecutor {
|
||||
/** Set when a handler called runtime.earlyReturn: the pipeline stops and this is the value. */
|
||||
private boolean returned;
|
||||
private Object earlyReturnValue;
|
||||
/** A VTL function return stops only that function, not the whole resolver pipeline. */
|
||||
private boolean vtlFunctionReturned;
|
||||
|
||||
private Execution(Resolver resolver, ResolverInvocation invocation) {
|
||||
this.apiId = invocation.apiId();
|
||||
@@ -191,14 +197,14 @@ public class AppSyncResolverExecutor {
|
||||
private ResolverOutcome runUnit() {
|
||||
Stage stage = Stage.of(resolver);
|
||||
DataSource vtlDataSource = stage.vtl()
|
||||
? requireVtlDataSource(resolver.getDataSourceName()) : null;
|
||||
? requireVtlDataSource(resolver.getDataSourceName(), "UNIT resolver") : null;
|
||||
Object request = callHandler(stage, REQUEST, null, null, null);
|
||||
if (returned) {
|
||||
return result(earlyReturnValue);
|
||||
}
|
||||
Invocation invocation = stage.vtl()
|
||||
? invokeDataSource(vtlDataSource,
|
||||
prepareVtlDataSourceRequest(vtlDataSource, request), true)
|
||||
prepareVtlDataSourceRequest(stage, vtlDataSource, request), true)
|
||||
: invokeDataSource(resolver.getDataSourceName(), request);
|
||||
Object response = callHandler(stage, RESPONSE,
|
||||
invocation.result(), invocation.error(), invocation.result());
|
||||
@@ -209,7 +215,6 @@ 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);
|
||||
@@ -219,16 +224,30 @@ public class AppSyncResolverExecutor {
|
||||
|
||||
for (FunctionConfiguration function : functions) {
|
||||
Stage functionStage = Stage.of(function);
|
||||
if (functionStage.vtl()) {
|
||||
validateVtlFunctionVersion(functionStage);
|
||||
}
|
||||
Object request = callHandler(functionStage, REQUEST, null, null, null);
|
||||
if (returned) {
|
||||
return result(earlyReturnValue);
|
||||
}
|
||||
Invocation invocation = invokeDataSource(function.getDataSourceName(), request);
|
||||
if (consumeVtlFunctionReturn()) {
|
||||
previousResult = request;
|
||||
continue;
|
||||
}
|
||||
DataSource vtlDataSource = functionStage.vtl()
|
||||
? requireVtlDataSource(function.getDataSourceName(),
|
||||
"function " + function.getName()) : null;
|
||||
Invocation invocation = functionStage.vtl()
|
||||
? invokeDataSource(vtlDataSource,
|
||||
prepareVtlDataSourceRequest(functionStage, vtlDataSource, request), true)
|
||||
: invokeDataSource(function.getDataSourceName(), request);
|
||||
Object response = callHandler(functionStage, RESPONSE,
|
||||
invocation.result(), invocation.error(), invocation.result());
|
||||
if (returned) {
|
||||
return result(earlyReturnValue);
|
||||
}
|
||||
consumeVtlFunctionReturn();
|
||||
// Missing response handler: the data source result passes through, which is what a
|
||||
// function with only a request handler does on AppSync.
|
||||
previousResult = response;
|
||||
@@ -269,32 +288,30 @@ public class AppSyncResolverExecutor {
|
||||
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 requireVtlDataSource(String dataSourceName) {
|
||||
private DataSource requireVtlDataSource(String dataSourceName, String stageName) {
|
||||
if (dataSourceName == null || dataSourceName.isBlank()) {
|
||||
throw new AwsException("UnsupportedOperation",
|
||||
"A VTL UNIT resolver must name a supported data source", 400);
|
||||
"A VTL " + stageName + " must name a supported data source", 400);
|
||||
}
|
||||
DataSource dataSource = dataSource(dataSourceName);
|
||||
DataSourceType type = dataSource.getType();
|
||||
return switch (type) {
|
||||
case NONE, AMAZON_DYNAMODB, AWS_LAMBDA, RELATIONAL_DATABASE -> dataSource;
|
||||
default -> throw unsupportedVtlDataSource(type, dataSourceName);
|
||||
default -> throw unsupportedVtlDataSource(type, dataSourceName, stageName);
|
||||
};
|
||||
}
|
||||
|
||||
private boolean consumeVtlFunctionReturn() {
|
||||
boolean functionReturned = vtlFunctionReturned;
|
||||
vtlFunctionReturned = false;
|
||||
return functionReturned;
|
||||
}
|
||||
|
||||
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
|
||||
@@ -338,19 +355,29 @@ public class AppSyncResolverExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
private Object prepareVtlDataSourceRequest(DataSource dataSource, Object request) {
|
||||
private Object prepareVtlDataSourceRequest(Stage stage, DataSource dataSource, Object request) {
|
||||
if (!(request instanceof Map<?, ?> map)) {
|
||||
throw mappingTemplateError("VTL request mapping template must render a JSON object");
|
||||
}
|
||||
validateVtlRequestVersion(map);
|
||||
return switch (dataSource.getType()) {
|
||||
case NONE -> prepareVtlNoneRequest(map);
|
||||
case AMAZON_DYNAMODB -> prepareVtlDynamoDbRequest(map);
|
||||
case AWS_LAMBDA -> prepareVtlLambdaRequest(map);
|
||||
case RELATIONAL_DATABASE -> prepareVtlRdsRequest(map);
|
||||
default -> throw unsupportedVtlDataSource(dataSource.getType(), dataSource.getName());
|
||||
default -> throw unsupportedVtlDataSource(dataSource.getType(), dataSource.getName(),
|
||||
stage.function() ? "function" : "UNIT resolver");
|
||||
};
|
||||
}
|
||||
|
||||
private void validateVtlFunctionVersion(Stage stage) {
|
||||
if (!"2018-05-29".equals(stage.functionVersion())) {
|
||||
throw new AwsException("UnsupportedOperation",
|
||||
"Floci does not execute AppSync VTL function version "
|
||||
+ stage.functionVersion(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
private Object prepareVtlNoneRequest(Map<?, ?> request) {
|
||||
validateVtlRequestMembers(request, NONE_VTL_REQUEST_MEMBERS, "NONE");
|
||||
return request.containsKey("payload") ? request : null;
|
||||
@@ -432,9 +459,10 @@ public class AppSyncResolverExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
private AwsException unsupportedVtlDataSource(DataSourceType type, String name) {
|
||||
private AwsException unsupportedVtlDataSource(DataSourceType type, String name,
|
||||
String stageName) {
|
||||
return new AwsException("UnsupportedOperation",
|
||||
"Floci does not yet execute VTL UNIT resolvers over " + type
|
||||
"Floci does not yet execute VTL " + stageName + " over " + type
|
||||
+ " data sources (data source " + name + ")", 400);
|
||||
}
|
||||
|
||||
@@ -539,16 +567,16 @@ public class AppSyncResolverExecutor {
|
||||
}
|
||||
|
||||
if (evaluation.returned()) {
|
||||
this.returned = true;
|
||||
this.earlyReturnValue = evaluation.output();
|
||||
if (stage.function()) {
|
||||
this.vtlFunctionReturned = true;
|
||||
} else {
|
||||
this.returned = true;
|
||||
this.earlyReturnValue = evaluation.output();
|
||||
}
|
||||
return evaluation.output();
|
||||
}
|
||||
|
||||
Object value = parseRenderedJson(evaluation.output(), handler);
|
||||
if (REQUEST.equals(handler)) {
|
||||
validateVtlRequest(value);
|
||||
}
|
||||
return value;
|
||||
return parseRenderedJson(evaluation.output(), handler);
|
||||
}
|
||||
|
||||
private Map<String, Object> identityMap() {
|
||||
@@ -585,10 +613,7 @@ public class AppSyncResolverExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateVtlRequest(Object request) {
|
||||
if (!(request instanceof Map<?, ?> map)) {
|
||||
throw mappingTemplateError("VTL request mapping template must render a JSON object");
|
||||
}
|
||||
private void validateVtlRequestVersion(Map<?, ?> map) {
|
||||
Object version = map.get("version");
|
||||
if (!"2018-05-29".equals(version)) {
|
||||
throw mappingTemplateError("VTL request mapping template must use version 2018-05-29");
|
||||
|
||||
+47
@@ -39,8 +39,10 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
|
||||
private static final String SCHEMA = """
|
||||
type Message { id: ID! name: String }
|
||||
type VtlPipelineResult { value: String before: String }
|
||||
type Query {
|
||||
getMessages(orgNo: String!): [Message]
|
||||
vtlPipeline(value: String!): VtlPipelineResult
|
||||
ping(x: String): String
|
||||
echoArg(x: String): String
|
||||
failing: String
|
||||
@@ -207,6 +209,51 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
.body("data.getMessages.id", contains("1", "2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVtlPipelineRunsThroughTheGraphqlSidecar() {
|
||||
String functionId = given()
|
||||
.header("Authorization", AUTH)
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{"name":"Query_vtlPipeline_0","dataSourceName":"local",
|
||||
"functionVersion":"2018-05-29",
|
||||
"requestMappingTemplate":"%s",
|
||||
"responseMappingTemplate":"%s"}
|
||||
""".formatted(escape("""
|
||||
{"version":"2018-05-29","payload":{
|
||||
"value":$util.toJson($ctx.stash.value),
|
||||
"before":$util.toJson($ctx.prev.result.before)}}
|
||||
"""), escape("$util.toJson($ctx.result)")))
|
||||
.when()
|
||||
.post("/v1/apis/" + apiId + "/functions")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("functionConfiguration.functionId");
|
||||
|
||||
given()
|
||||
.header("Authorization", AUTH)
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{"typeName":"Query","fieldName":"vtlPipeline","kind":"PIPELINE",
|
||||
"pipelineConfig":{"functions":["%s"]},
|
||||
"requestMappingTemplate":"%s",
|
||||
"responseMappingTemplate":"%s"}
|
||||
""".formatted(functionId, escape("""
|
||||
#set($discard = $ctx.stash.put("value", $ctx.args.value))
|
||||
{"before":$util.toJson($ctx.args.value)}
|
||||
"""), escape("$util.toJson($ctx.prev.result)")))
|
||||
.when()
|
||||
.post("/v1/apis/" + apiId + "/types/Query/resolvers")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
query("{ vtlPipeline(value: \\\"live\\\") { value before } }")
|
||||
.statusCode(200)
|
||||
.body("errors", nullValue())
|
||||
.body("data.vtlPipeline.value", equalTo("live"))
|
||||
.body("data.vtlPipeline.before", equalTo("live"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aUnitResolverRunsRequestAndResponseAroundItsDataSource() {
|
||||
query("{ ping }")
|
||||
|
||||
+213
-13
@@ -40,6 +40,7 @@ import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -897,25 +898,222 @@ class AppSyncResolverExecutorTest {
|
||||
}
|
||||
|
||||
@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"));
|
||||
void vtlPipelineThreadsStashAndPreviousResultThroughItsFunctionAndAfterTemplate() {
|
||||
when(appSync.getDataSource(API_ID, "accountTable"))
|
||||
.thenReturn(dataSource("accountTable", DataSourceType.AMAZON_DYNAMODB));
|
||||
when(appSync.getFunction(API_ID, "fn1")).thenReturn(vtlFunction("fn1", "accountTable", """
|
||||
{"version":"2018-05-29","operation":"GetItem",
|
||||
"key":{"id":{"S":$util.toJson($ctx.stash.id)}}}
|
||||
""", """
|
||||
#set($discard = $ctx.stash.put("function", "seen"))
|
||||
{"id":$util.toJson($ctx.result.id),
|
||||
"before":$util.toJson($ctx.prev.result.before)}
|
||||
"""));
|
||||
dynamoDbInvoker.answer = Map.of("id", "42");
|
||||
Resolver resolver = resolver(ResolverKind.PIPELINE, null);
|
||||
resolver.setRequestMappingTemplate("""
|
||||
#set($discard = $ctx.stash.put("id", $ctx.args.id))
|
||||
{"before":$util.toJson($ctx.args.id)}
|
||||
""");
|
||||
resolver.setResponseMappingTemplate("""
|
||||
{"last":$util.toJson($ctx.prev.result),
|
||||
"stash":$util.toJson($ctx.stash.function)}
|
||||
""");
|
||||
resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
|
||||
|
||||
ResolverOutcome result = executor.execute(resolver, invocation(Map.of("id", "42")));
|
||||
|
||||
assertTrue(result.errors().isEmpty());
|
||||
assertEquals(Map.of("last", Map.of("id", "42", "before", "42"),
|
||||
"stash", "seen"), result.data());
|
||||
assertEquals(1, dynamoDbInvoker.requests.size());
|
||||
Map<?, ?> request = (Map<?, ?>) dynamoDbInvoker.requests.get(0);
|
||||
assertEquals("2018-05-29", request.get("version"));
|
||||
assertEquals("GetItem", request.get("operation"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void vtlPipelineLambdaFunctionSendsOnlyPayloadToTheFunction() throws Exception {
|
||||
String functionArn = "arn:aws:lambda:eu-west-1:000000000000:function:resolver-fn";
|
||||
DataSource lambdaDataSource = dataSource("accountFunction", DataSourceType.AWS_LAMBDA);
|
||||
lambdaDataSource.setLambdaConfig(Map.of("lambdaFunctionArn", functionArn));
|
||||
when(appSync.getDataSource(API_ID, "accountFunction")).thenReturn(lambdaDataSource);
|
||||
when(appSync.getFunction(API_ID, "fn1")).thenReturn(vtlFunction("fn1", "accountFunction", """
|
||||
{"version":"2018-05-29","operation":"Invoke",
|
||||
"payload":{"id":$util.toJson($ctx.args.id)}}
|
||||
""", "$util.toJson($ctx.result)"));
|
||||
LambdaService lambdaService = mock(LambdaService.class);
|
||||
when(lambdaService.invokeArn(eq(functionArn), any(byte[].class),
|
||||
eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(new InvokeResult(200, null, "{}".getBytes(StandardCharsets.UTF_8),
|
||||
null, "request-id"));
|
||||
AppSyncResolverExecutor lambdaExecutor = new AppSyncResolverExecutor(appSync, jsRuntime,
|
||||
new AppSyncDataSourceInvokers(List.of(
|
||||
new LambdaDataSourceInvoker(lambdaService, objectMapper)),
|
||||
mock(AppSyncDataSourceAuthorizer.class)),
|
||||
vtlEngine(), objectMapper);
|
||||
Resolver resolver = resolver(ResolverKind.PIPELINE, null);
|
||||
resolver.setRequestMappingTemplate("{}");
|
||||
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||
resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
|
||||
|
||||
ResolverOutcome result = lambdaExecutor.execute(resolver, invocation(Map.of("id", "42")));
|
||||
|
||||
assertTrue(result.errors().isEmpty());
|
||||
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService).invokeArn(eq(functionArn), payload.capture(),
|
||||
eq(InvocationType.RequestResponse));
|
||||
assertEquals(Map.of("id", "42"), objectMapper.readValue(payload.getValue(), Map.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void vtlFunctionRequestReturnSkipsItsDataSourceAndContinuesThePipeline() {
|
||||
when(appSync.getDataSource(API_ID, "local"))
|
||||
.thenThrow(new AwsException("NotFoundException", "Data source not found", 404));
|
||||
when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
|
||||
when(appSync.getFunction(API_ID, "fn1")).thenReturn(vtlFunction("fn1", "local",
|
||||
"#return({\"cached\":true})", "$util.toJson($ctx.result)"));
|
||||
when(appSync.getFunction(API_ID, "fn2"))
|
||||
.thenReturn(function("fn2", "two", "accountDB", "fn2-code"));
|
||||
Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
|
||||
resolver.setPipelineConfig(Map.of("functions", List.of("fn1", "fn2")));
|
||||
jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(null));
|
||||
jsRuntime.script("fn1-code", "request", (h, ctx) -> ok(Map.of()));
|
||||
jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(Map.of()));
|
||||
jsRuntime.script("fn2-code", "request", (h, ctx) -> {
|
||||
assertEquals(Map.of("cached", true), ((Map<?, ?>) ctx.get("prev")).get("result"));
|
||||
return ok(Map.of("statement", "select 1"));
|
||||
});
|
||||
jsRuntime.script("fn2-code", "response", (h, ctx) -> ok("continued"));
|
||||
jsRuntime.script("pipeline-code", "response", (h, ctx) -> ok(ctx.get("result")));
|
||||
|
||||
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
|
||||
|
||||
assertEquals("continued", result.data());
|
||||
assertTrue(result.errors().isEmpty());
|
||||
assertTrue(noneInvoker.requests.isEmpty());
|
||||
verify(appSync, never()).getDataSource(API_ID, "local");
|
||||
assertEquals(List.of("pipeline-code#request", "fn2-code#request",
|
||||
"fn2-code#response", "pipeline-code#response"), jsRuntime.calls);
|
||||
}
|
||||
|
||||
@Test
|
||||
void vtlFunctionRequestReturnCannotBypassUnsupportedFunctionVersion() {
|
||||
FunctionConfiguration function = vtlFunction("fn1", "local",
|
||||
"#return({\"cached\":true})", "$util.toJson($ctx.result)");
|
||||
function.setFunctionVersion("2017-02-28");
|
||||
when(appSync.getFunction(API_ID, "fn1")).thenReturn(function);
|
||||
Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
|
||||
resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
|
||||
jsRuntime.script("pipeline-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(result.errors().get(0).message().contains("2017-02-28"));
|
||||
verify(appSync, never()).getDataSource(API_ID, "local");
|
||||
assertTrue(noneInvoker.requests.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void vtlFunctionResponseReturnBecomesTheNextFunctionsPreviousResult() {
|
||||
when(appSync.getDataSource(API_ID, "local"))
|
||||
.thenReturn(dataSource("local", DataSourceType.NONE));
|
||||
when(appSync.getFunction(API_ID, "fn1")).thenReturn(vtlFunction("fn1", "local",
|
||||
"{\"version\":\"2018-05-29\",\"payload\":{\"id\":\"1\"}}",
|
||||
"#return({\"from\":\"first\"})"));
|
||||
when(appSync.getFunction(API_ID, "fn2")).thenReturn(vtlFunction("fn2", "local", """
|
||||
{"version":"2018-05-29",
|
||||
"payload":{"previous":$util.toJson($ctx.prev.result.from)}}
|
||||
""", "$util.toJson($ctx.result)"));
|
||||
Resolver resolver = resolver(ResolverKind.PIPELINE, null);
|
||||
resolver.setRequestMappingTemplate("{}");
|
||||
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||
resolver.setPipelineConfig(Map.of("functions", List.of("fn1", "fn2")));
|
||||
|
||||
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
|
||||
|
||||
assertEquals(Map.of("previous", "first"), result.data());
|
||||
assertTrue(result.errors().isEmpty());
|
||||
assertEquals(2, noneInvoker.requests.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void vtlFunctionCanHandleADataSourceErrorAndContinueToTheAfterTemplate() {
|
||||
when(appSync.getDataSource(API_ID, "accountFunction"))
|
||||
.thenReturn(dataSource("accountFunction", DataSourceType.AWS_LAMBDA));
|
||||
when(appSync.getFunction(API_ID, "fn1")).thenReturn(vtlFunction("fn1", "accountFunction",
|
||||
"{\"version\":\"2018-05-29\",\"operation\":\"Invoke\",\"payload\":{}}", """
|
||||
#if($ctx.error)
|
||||
{"handled":$util.toJson($ctx.error.type)}
|
||||
#else
|
||||
$util.toJson($ctx.result)
|
||||
#end
|
||||
"""));
|
||||
lambdaInvoker.failure = new AwsException("LambdaExecutionException", "failed", 400);
|
||||
Resolver resolver = resolver(ResolverKind.PIPELINE, null);
|
||||
resolver.setRequestMappingTemplate("{}");
|
||||
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||
resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
|
||||
|
||||
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
|
||||
|
||||
assertEquals(Map.of("handled", "LambdaExecutionException"), result.data());
|
||||
assertTrue(result.errors().isEmpty());
|
||||
lambdaInvoker.failure = null;
|
||||
}
|
||||
|
||||
@Test
|
||||
void vtlResolverBeforeReturnStopsTheWholePipelineBeforeFunctionLookup() {
|
||||
Resolver resolver = resolver(ResolverKind.PIPELINE, null);
|
||||
resolver.setRequestMappingTemplate("#return({\"cached\":true})");
|
||||
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||
resolver.setPipelineConfig(Map.of("functions", List.of("missing")));
|
||||
|
||||
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
|
||||
|
||||
assertEquals(Map.of("cached", true), result.data());
|
||||
assertTrue(result.errors().isEmpty());
|
||||
assertTrue(invoker.requests.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedVtlFunctionVersionFailsBeforeDataSourceInvocation() {
|
||||
when(appSync.getDataSource(API_ID, "local"))
|
||||
.thenReturn(dataSource("local", DataSourceType.NONE));
|
||||
FunctionConfiguration function = vtlFunction("fn1", "local",
|
||||
"{\"payload\":{}}", "$util.toJson($ctx.result)");
|
||||
function.setFunctionVersion("2017-02-28");
|
||||
when(appSync.getFunction(API_ID, "fn1")).thenReturn(function);
|
||||
Resolver resolver = resolver(ResolverKind.PIPELINE, "pipeline-code");
|
||||
resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
|
||||
jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(Map.of()));
|
||||
|
||||
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("2017-02-28"));
|
||||
assertTrue(noneInvoker.requests.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void vtlFunctionRequestWithoutVersionFailsBeforeDataSourceInvocation() {
|
||||
when(appSync.getDataSource(API_ID, "local"))
|
||||
.thenReturn(dataSource("local", DataSourceType.NONE));
|
||||
when(appSync.getFunction(API_ID, "fn1")).thenReturn(vtlFunction("fn1", "local",
|
||||
"{\"payload\":{}}", "$util.toJson($ctx.result)"));
|
||||
Resolver resolver = resolver(ResolverKind.PIPELINE, null);
|
||||
resolver.setRequestMappingTemplate("{}");
|
||||
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||
resolver.setPipelineConfig(Map.of("functions", List.of("fn1")));
|
||||
|
||||
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
|
||||
|
||||
assertEquals(1, result.errors().size());
|
||||
assertEquals("MappingTemplate", result.errors().get(0).errorType());
|
||||
assertTrue(noneInvoker.requests.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExplicitVtlRuntimeIsRefusedEvenWithCode() {
|
||||
when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
|
||||
@@ -966,13 +1164,15 @@ class AppSyncResolverExecutorTest {
|
||||
result.errors().get(0).errorType());
|
||||
}
|
||||
|
||||
private FunctionConfiguration vtlFunction(String id) {
|
||||
private FunctionConfiguration vtlFunction(String id, String dataSourceName,
|
||||
String requestTemplate, String responseTemplate) {
|
||||
FunctionConfiguration fn = new FunctionConfiguration();
|
||||
fn.setFunctionId(id);
|
||||
fn.setName("vtl-" + id);
|
||||
fn.setDataSourceName("accountDB");
|
||||
fn.setRequestMappingTemplate("{\"version\":\"2018-05-29\"}");
|
||||
fn.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||
fn.setDataSourceName(dataSourceName);
|
||||
fn.setFunctionVersion("2018-05-29");
|
||||
fn.setRequestMappingTemplate(requestTemplate);
|
||||
fn.setResponseMappingTemplate(responseTemplate);
|
||||
return fn;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user