mirror of
https://github.com/floci-io/floci.git
synced 2026-11-30 08:55:17 -05:00
feat(appsync): execute VTL unit resolvers over data sources (#4423)
* feat(appsync): execute VTL unit resolvers over data sources * fix(appsync): reject unbatched VTL Lambda BatchInvoke * fix(appsync): normalize VTL Lambda payload and transact RDS statements * fix(appsync): preserve sequential RDS statement effects * fix(appsync): send full VTL request document to Lambda
This commit is contained in:
1 parent
ce48b9f91b
commit
5e2edcb89b
9 files changed
+464
-45
No files matched your search
+34
-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
|
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
|
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.
|
`2018-05-29` VTL request and response templates for UNIT resolvers backed by `NONE`, DynamoDB,
|
||||||
VTL pipeline stages and VTL resolvers over other data sources remain explicit unsupported
|
Lambda, or RDS data sources. VTL pipeline stages and VTL resolvers over other data sources remain
|
||||||
operations rather than silently resolving to `null`.
|
explicit unsupported operations rather than silently resolving to `null`.
|
||||||
|
|
||||||
### How a resolver gets called
|
### How a resolver gets called
|
||||||
|
|
||||||
@@ -339,10 +339,30 @@ than running.
|
|||||||
|
|
||||||
### VTL UNIT resolvers
|
### VTL UNIT resolvers
|
||||||
|
|
||||||
A VTL UNIT resolver over `NONE` evaluates the request mapping template, unwraps the request's
|
A VTL UNIT resolver evaluates the request mapping template, sends the rendered request through the
|
||||||
`payload`, and evaluates the response mapping template with that value in `ctx.result`. Request
|
same data source invoker used by APPSYNC_JS, and evaluates the response mapping template with the
|
||||||
templates must render a JSON object with `version: "2018-05-29"`; invalid JSON and unsupported
|
answer in `ctx.result`. Request templates must render a JSON object with
|
||||||
versions fail the field with `errorType: MappingTemplate`.
|
`version: "2018-05-29"`; invalid JSON, unsupported versions, and malformed data source requests
|
||||||
|
fail the field with `errorType: MappingTemplate`.
|
||||||
|
|
||||||
|
Supported request documents are:
|
||||||
|
|
||||||
|
- `NONE`: `version` plus an optional `payload`, which is unwrapped into `ctx.result`.
|
||||||
|
- DynamoDB: `GetItem`, `PutItem`, `UpdateItem`, `DeleteItem`, `Query`, and `Scan` requests.
|
||||||
|
- Lambda: `Invoke` with synchronous `RequestResponse` invocation. The entire resolved
|
||||||
|
VTL request document reaches the function, including `version` and `operation`.
|
||||||
|
When `payload` is omitted, it remains absent from that document, as shown by the
|
||||||
|
[AWS Lambda VTL mapping reference](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-lambda.html).
|
||||||
|
VTL `BatchInvoke`
|
||||||
|
requires batching field requests and is not implemented by the per-field resolver callback.
|
||||||
|
- RDS: one or two `statements`, with optional `variableMap` and `variableTypeHintMap`.
|
||||||
|
Statements run sequentially without a transaction. If the second fails, the first
|
||||||
|
statement's effects remain committed.
|
||||||
|
|
||||||
|
A backing-service failure is exposed as `ctx.error` in the response template. The template may
|
||||||
|
raise it, append it beside response data, or return a value and suppress it, matching the existing
|
||||||
|
APPSYNC_JS execution path. Valid AppSync operations that the invoker does not implement fail with
|
||||||
|
`errorType: UnsupportedOperation` instead of running with altered semantics.
|
||||||
|
|
||||||
The VTL context includes `ctx.arguments` / `ctx.args`, `ctx.source`, `ctx.stash`, `ctx.result`,
|
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
|
`ctx.error`, `ctx.identity`, `ctx.request`, `ctx.info`, and `ctx.prev`. Stash mutations survive from
|
||||||
@@ -352,8 +372,8 @@ selected type and details, and
|
|||||||
`$util.appendError` reports an error beside the returned data.
|
`$util.appendError` reports an error beside the returned data.
|
||||||
|
|
||||||
The existing VTL loop, output-size, timeout, and reflection-sandbox limits apply. The
|
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
|
`2017-02-28` template version, VTL pipeline functions, and VTL-backed HTTP, EventBridge,
|
||||||
other data sources are not included in this first execution slice.
|
OpenSearch, and Bedrock data sources are not included.
|
||||||
|
|
||||||
| Setting | Env | Default |
|
| Setting | Env | Default |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
@@ -406,9 +426,9 @@ environment variables). `ctx.request.headers` is empty: the GraphQL context does
|
|||||||
| Type | Behaviour |
|
| 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. |
|
| `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. |
|
| `AWS_LAMBDA` | `Invoke` and `BatchInvoke` for APPSYNC_JS, and `Invoke` for `2018-05-29` VTL UNIT resolvers. VTL sends the entire resolved request document to the function. The existing APPSYNC_JS path sends only `payload`, a Floci deviation from AWS that this VTL feature does not change. 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. |
|
| `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. |
|
| `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. |
|
||||||
| `HTTP`, `AMAZON_EVENTBRIDGE`, `AMAZON_OPENSEARCH_SERVICE`, `AMAZON_BEDROCK_RUNTIME` | Not implemented; a resolver using one fails its field naming the type. |
|
| `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
|
A field with no resolver falls back to reading its value off the parent object, which is how the
|
||||||
@@ -457,8 +477,8 @@ 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:
|
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 data sources beyond `NONE`
|
- **VTL resolver expansion**: pipeline functions, the `2017-02-28` version, and the remaining data sources
|
||||||
- **Data source adapters** (Phase 9): DynamoDB, Lambda, HTTP, EventBridge, OpenSearch, RDS connectors
|
- **Data source adapters**: HTTP, EventBridge, OpenSearch, and Bedrock connectors
|
||||||
- **Guardrails** (Phase 10): query depth / complexity limits and related errors
|
- **Guardrails** (Phase 10): query depth / complexity limits and related errors
|
||||||
- **Realtime subscriptions** (Phase 11+): WebSocket real-time subscriptions
|
- **Realtime subscriptions** (Phase 11+): WebSocket real-time subscriptions
|
||||||
- **Caching**: API-level and per-resolver caching
|
- **Caching**: API-level and per-resolver caching
|
||||||
|
|||||||
+5
@@ -26,4 +26,9 @@ public interface AppSyncDataSourceInvoker {
|
|||||||
* @return the value to expose as {@code ctx.result}
|
* @return the value to expose as {@code ctx.result}
|
||||||
*/
|
*/
|
||||||
Object invoke(DataSource dataSource, Object request, String region);
|
Object invoke(DataSource dataSource, Object request, String region);
|
||||||
|
|
||||||
|
/** VTL UNIT requests share the data source path unless their wire contract differs. */
|
||||||
|
default Object invokeVtl(DataSource dataSource, Object request, String region) {
|
||||||
|
return invoke(dataSource, request, region);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+9
-1
@@ -41,6 +41,14 @@ public class AppSyncDataSourceInvokers {
|
|||||||
* mode this whole layer exists to remove.
|
* mode this whole layer exists to remove.
|
||||||
*/
|
*/
|
||||||
public Object invoke(DataSource dataSource, Object request, String region) {
|
public Object invoke(DataSource dataSource, Object request, String region) {
|
||||||
|
return invokerFor(dataSource).invoke(dataSource, request, region);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object invokeVtl(DataSource dataSource, Object request, String region) {
|
||||||
|
return invokerFor(dataSource).invokeVtl(dataSource, request, region);
|
||||||
|
}
|
||||||
|
|
||||||
|
private AppSyncDataSourceInvoker invokerFor(DataSource dataSource) {
|
||||||
DataSourceType type = dataSource.getType();
|
DataSourceType type = dataSource.getType();
|
||||||
AppSyncDataSourceInvoker invoker = byType.get(type);
|
AppSyncDataSourceInvoker invoker = byType.get(type);
|
||||||
if (invoker == null) {
|
if (invoker == null) {
|
||||||
@@ -48,7 +56,7 @@ public class AppSyncDataSourceInvokers {
|
|||||||
"Floci cannot invoke AppSync data sources of type " + type
|
"Floci cannot invoke AppSync data sources of type " + type
|
||||||
+ " (data source " + dataSource.getName() + ")", 500);
|
+ " (data source " + dataSource.getName() + ")", 500);
|
||||||
}
|
}
|
||||||
return invoker.invoke(dataSource, request, region);
|
return invoker;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean supports(DataSourceType type) {
|
public boolean supports(DataSourceType type) {
|
||||||
|
|||||||
+6
@@ -59,6 +59,12 @@ public class LambdaDataSourceInvoker implements AppSyncDataSourceInvoker {
|
|||||||
return invokeOnce(functionArn, payload, region);
|
return invokeOnce(functionArn, payload, region);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object invokeVtl(DataSource dataSource, Object request, String region) {
|
||||||
|
// AWS sends the entire resolved VTL request document to the Lambda function.
|
||||||
|
return invokeOnce(functionArn(dataSource), request, region);
|
||||||
|
}
|
||||||
|
|
||||||
private Object invokeOnce(String functionArn, Object payload, String region) {
|
private Object invokeOnce(String functionArn, Object payload, String region) {
|
||||||
byte[] body;
|
byte[] body;
|
||||||
try {
|
try {
|
||||||
|
|||||||
+118
-22
@@ -25,6 +25,7 @@ import java.util.ArrayList;
|
|||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Runs the resolver attached to a field: its handlers, its data source, and, for a PIPELINE
|
* Runs the resolver attached to a field: its handlers, its data source, and, for a PIPELINE
|
||||||
@@ -57,6 +58,11 @@ public class AppSyncResolverExecutor {
|
|||||||
private static final Logger LOG = Logger.getLogger(AppSyncResolverExecutor.class);
|
private static final Logger LOG = Logger.getLogger(AppSyncResolverExecutor.class);
|
||||||
private static final String REQUEST = "request";
|
private static final String REQUEST = "request";
|
||||||
private static final String RESPONSE = "response";
|
private static final String RESPONSE = "response";
|
||||||
|
private static final Set<String> NONE_VTL_REQUEST_MEMBERS = Set.of("version", "payload");
|
||||||
|
private static final Set<String> LAMBDA_VTL_REQUEST_MEMBERS =
|
||||||
|
Set.of("version", "operation", "payload", "invocationType");
|
||||||
|
private static final Set<String> DYNAMODB_VTL_OPERATIONS =
|
||||||
|
Set.of("GetItem", "PutItem", "UpdateItem", "DeleteItem", "Query", "Scan");
|
||||||
|
|
||||||
private final AppSyncService appSyncService;
|
private final AppSyncService appSyncService;
|
||||||
private final AppSyncJsRuntime jsRuntime;
|
private final AppSyncJsRuntime jsRuntime;
|
||||||
@@ -185,13 +191,14 @@ public class AppSyncResolverExecutor {
|
|||||||
private ResolverOutcome runUnit() {
|
private ResolverOutcome runUnit() {
|
||||||
Stage stage = Stage.of(resolver);
|
Stage stage = Stage.of(resolver);
|
||||||
DataSource vtlDataSource = stage.vtl()
|
DataSource vtlDataSource = stage.vtl()
|
||||||
? requireVtlNoneDataSource(resolver.getDataSourceName()) : null;
|
? requireVtlDataSource(resolver.getDataSourceName()) : null;
|
||||||
Object request = callHandler(stage, REQUEST, null, null, null);
|
Object request = callHandler(stage, REQUEST, null, null, null);
|
||||||
if (returned) {
|
if (returned) {
|
||||||
return result(earlyReturnValue);
|
return result(earlyReturnValue);
|
||||||
}
|
}
|
||||||
Invocation invocation = stage.vtl()
|
Invocation invocation = stage.vtl()
|
||||||
? invokeDataSource(vtlDataSource, normalizeVtlNoneRequest(request))
|
? invokeDataSource(vtlDataSource,
|
||||||
|
prepareVtlDataSourceRequest(vtlDataSource, request), true)
|
||||||
: invokeDataSource(resolver.getDataSourceName(), request);
|
: invokeDataSource(resolver.getDataSourceName(), request);
|
||||||
Object response = callHandler(stage, RESPONSE,
|
Object response = callHandler(stage, RESPONSE,
|
||||||
invocation.result(), invocation.error(), invocation.result());
|
invocation.result(), invocation.error(), invocation.result());
|
||||||
@@ -275,18 +282,17 @@ public class AppSyncResolverExecutor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private DataSource requireVtlNoneDataSource(String dataSourceName) {
|
private DataSource requireVtlDataSource(String dataSourceName) {
|
||||||
if (dataSourceName == null || dataSourceName.isBlank()) {
|
if (dataSourceName == null || dataSourceName.isBlank()) {
|
||||||
throw new AwsException("UnsupportedOperation",
|
throw new AwsException("UnsupportedOperation",
|
||||||
"Floci currently executes VTL UNIT resolvers only with NONE data sources", 400);
|
"A VTL UNIT resolver must name a supported data source", 400);
|
||||||
}
|
}
|
||||||
DataSource dataSource = dataSource(dataSourceName);
|
DataSource dataSource = dataSource(dataSourceName);
|
||||||
if (dataSource.getType() != DataSourceType.NONE) {
|
DataSourceType type = dataSource.getType();
|
||||||
throw new AwsException("UnsupportedOperation",
|
return switch (type) {
|
||||||
"Floci currently executes VTL UNIT resolvers only with NONE data sources; "
|
case NONE, AMAZON_DYNAMODB, AWS_LAMBDA, RELATIONAL_DATABASE -> dataSource;
|
||||||
+ dataSourceName + " uses " + dataSource.getType(), 400);
|
default -> throw unsupportedVtlDataSource(type, dataSourceName);
|
||||||
}
|
};
|
||||||
return dataSource;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Invocation invokeDataSource(String dataSourceName, Object request) {
|
private Invocation invokeDataSource(String dataSourceName, Object request) {
|
||||||
@@ -295,7 +301,7 @@ public class AppSyncResolverExecutor {
|
|||||||
// the local functions AppSync allows: the request is the result.
|
// the local functions AppSync allows: the request is the result.
|
||||||
return new Invocation(request, null);
|
return new Invocation(request, null);
|
||||||
}
|
}
|
||||||
return invokeDataSource(dataSource(dataSourceName), request);
|
return invokeDataSource(dataSource(dataSourceName), request, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private DataSource dataSource(String dataSourceName) {
|
private DataSource dataSource(String dataSourceName) {
|
||||||
@@ -315,10 +321,12 @@ public class AppSyncResolverExecutor {
|
|||||||
return dataSource;
|
return dataSource;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Invocation invokeDataSource(DataSource dataSource, Object request) {
|
private Invocation invokeDataSource(DataSource dataSource, Object request, boolean vtl) {
|
||||||
try {
|
try {
|
||||||
return new Invocation(dataSourceInvokers.invoke(dataSource, request, regionOf(dataSource)),
|
Object result = vtl
|
||||||
null);
|
? dataSourceInvokers.invokeVtl(dataSource, request, regionOf(dataSource))
|
||||||
|
: dataSourceInvokers.invoke(dataSource, request, regionOf(dataSource));
|
||||||
|
return new Invocation(result, null);
|
||||||
} catch (AwsException e) {
|
} catch (AwsException e) {
|
||||||
// What the store or function answered: the resolver sees it as ctx.error and decides.
|
// 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
|
// Deliberately only AwsException: an unexpected RuntimeException is a defect in the
|
||||||
@@ -330,13 +338,106 @@ public class AppSyncResolverExecutor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private Object normalizeVtlNoneRequest(Object request) {
|
private Object prepareVtlDataSourceRequest(DataSource dataSource, Object request) {
|
||||||
if (request instanceof Map<?, ?> map && !map.containsKey("payload")) {
|
if (!(request instanceof Map<?, ?> map)) {
|
||||||
return null;
|
throw mappingTemplateError("VTL request mapping template must render a JSON object");
|
||||||
|
}
|
||||||
|
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());
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object prepareVtlNoneRequest(Map<?, ?> request) {
|
||||||
|
validateVtlRequestMembers(request, NONE_VTL_REQUEST_MEMBERS, "NONE");
|
||||||
|
return request.containsKey("payload") ? request : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object prepareVtlDynamoDbRequest(Map<?, ?> request) {
|
||||||
|
String operation = requireVtlOperation(request, "DynamoDB");
|
||||||
|
if (!DYNAMODB_VTL_OPERATIONS.contains(operation)) {
|
||||||
|
throw new AwsException("UnsupportedOperation",
|
||||||
|
"Floci's AppSync VTL DynamoDB data source does not implement the "
|
||||||
|
+ operation + " operation yet", 400);
|
||||||
}
|
}
|
||||||
return request;
|
return request;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Object prepareVtlLambdaRequest(Map<?, ?> request) {
|
||||||
|
validateVtlRequestMembers(request, LAMBDA_VTL_REQUEST_MEMBERS, "Lambda");
|
||||||
|
String operation = requireVtlOperation(request, "Lambda");
|
||||||
|
if (!"Invoke".equals(operation)) {
|
||||||
|
throw new AwsException("UnsupportedOperation",
|
||||||
|
"Floci's AppSync VTL Lambda data source does not implement the "
|
||||||
|
+ operation + " operation yet", 400);
|
||||||
|
}
|
||||||
|
Object invocationType = request.get("invocationType");
|
||||||
|
if (invocationType != null && !(invocationType instanceof String)) {
|
||||||
|
throw mappingTemplateError("VTL Lambda invocationType must be a string");
|
||||||
|
}
|
||||||
|
if ("Event".equals(invocationType)) {
|
||||||
|
throw new AwsException("UnsupportedOperation",
|
||||||
|
"Floci's AppSync Lambda data source does not implement Event invocation yet", 400);
|
||||||
|
}
|
||||||
|
if (invocationType != null && !"RequestResponse".equals(invocationType)) {
|
||||||
|
throw mappingTemplateError(
|
||||||
|
"VTL Lambda invocationType must be RequestResponse or Event");
|
||||||
|
}
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object prepareVtlRdsRequest(Map<?, ?> request) {
|
||||||
|
Object statements = request.get("statements");
|
||||||
|
if (!(statements instanceof List<?> list) || list.isEmpty()) {
|
||||||
|
throw mappingTemplateError("VTL RDS request must contain a non-empty statements array");
|
||||||
|
}
|
||||||
|
if (list.size() > 2) {
|
||||||
|
throw mappingTemplateError("VTL RDS request supports at most two statements");
|
||||||
|
}
|
||||||
|
if (list.stream().anyMatch(statement -> !(statement instanceof String))) {
|
||||||
|
throw mappingTemplateError("VTL RDS statements must be strings");
|
||||||
|
}
|
||||||
|
validateOptionalMap(request, "variableMap", "VTL RDS variableMap must be an object");
|
||||||
|
validateOptionalMap(request, "variableTypeHintMap",
|
||||||
|
"VTL RDS variableTypeHintMap must be an object");
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String requireVtlOperation(Map<?, ?> request, String dataSourceType) {
|
||||||
|
Object operation = request.get("operation");
|
||||||
|
if (!(operation instanceof String text) || text.isBlank()) {
|
||||||
|
throw mappingTemplateError(
|
||||||
|
"VTL " + dataSourceType + " request must contain a non-empty operation");
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateVtlRequestMembers(Map<?, ?> request, Set<String> allowed,
|
||||||
|
String dataSourceType) {
|
||||||
|
for (Object key : request.keySet()) {
|
||||||
|
if (!(key instanceof String name) || !allowed.contains(name)) {
|
||||||
|
throw mappingTemplateError("VTL " + dataSourceType
|
||||||
|
+ " request contains unsupported member " + key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateOptionalMap(Map<?, ?> request, String member, String message) {
|
||||||
|
Object value = request.get(member);
|
||||||
|
if (value != null && !(value instanceof Map<?, ?>)) {
|
||||||
|
throw mappingTemplateError(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private AwsException unsupportedVtlDataSource(DataSourceType type, String name) {
|
||||||
|
return new AwsException("UnsupportedOperation",
|
||||||
|
"Floci does not yet execute VTL UNIT resolvers over " + type
|
||||||
|
+ " data sources (data source " + name + ")", 400);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One data source call's outcome: its result, or the error {@code ctx.error} carries into the
|
* One data source call's outcome: its result, or the error {@code ctx.error} carries into the
|
||||||
* response handler. Never both.
|
* response handler. Never both.
|
||||||
@@ -492,11 +593,6 @@ public class AppSyncResolverExecutor {
|
|||||||
if (!"2018-05-29".equals(version)) {
|
if (!"2018-05-29".equals(version)) {
|
||||||
throw mappingTemplateError("VTL request mapping template must use version 2018-05-29");
|
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) {
|
private ResolverRaisedException mappingTemplateError(String message) {
|
||||||
|
|||||||
+2
-1
@@ -68,7 +68,8 @@ class DynamoDbDataSourceInvokerTest {
|
|||||||
""");
|
""");
|
||||||
|
|
||||||
Object result = invoker.invoke(dataSource(),
|
Object result = invoker.invoke(dataSource(),
|
||||||
request("{\"operation\": \"GetItem\", \"key\": {\"regNo\": {\"S\": \"556677\"}}}"),
|
request("{\"version\": \"2018-05-29\", \"operation\": \"GetItem\", "
|
||||||
|
+ "\"key\": {\"regNo\": {\"S\": \"556677\"}}}"),
|
||||||
"eu-west-1");
|
"eu-west-1");
|
||||||
|
|
||||||
// A GraphQL field cannot be built from {"S": …}; AppSync resolvers see plain values.
|
// A GraphQL field cannot be built from {"S": …}; AppSync resolvers see plain values.
|
||||||
|
|||||||
+18
-3
@@ -53,17 +53,32 @@ class LambdaDataSourceInvokerTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void onlyThePayloadReachesTheFunction() {
|
void jsOnlyThePayloadReachesTheFunction() {
|
||||||
answers("{\"id\": \"1\"}");
|
answers("{\"id\": \"1\"}");
|
||||||
|
|
||||||
Object result = invoker.invoke(dataSource(),
|
Object result = invoker.invoke(dataSource(),
|
||||||
Map.of("operation", "Invoke", "payload", Map.of("field", "getMessages")), "eu-west-1");
|
Map.of("version", "2018-05-29", "operation", "Invoke",
|
||||||
|
"payload", Map.of("field", "getMessages")), "eu-west-1");
|
||||||
|
|
||||||
// The operation is AppSync's envelope, not something the function should see.
|
// Preserve the existing APPSYNC_JS behavior independently of VTL.
|
||||||
assertEquals("{\"field\":\"getMessages\"}", capturePayload());
|
assertEquals("{\"field\":\"getMessages\"}", capturePayload());
|
||||||
assertEquals(Map.of("id", "1"), result);
|
assertEquals(Map.of("id", "1"), result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void vtlSendsTheEntireRequestDocumentToTheFunction() throws Exception {
|
||||||
|
answers("{\"id\": \"1\"}");
|
||||||
|
|
||||||
|
Object result = invoker.invokeVtl(dataSource(),
|
||||||
|
Map.of("version", "2018-05-29", "operation", "Invoke",
|
||||||
|
"payload", Map.of("field", "getMessages")), "eu-west-1");
|
||||||
|
|
||||||
|
assertEquals(Map.of("version", "2018-05-29", "operation", "Invoke",
|
||||||
|
"payload", Map.of("field", "getMessages")),
|
||||||
|
mapper.readValue(capturePayload(), Map.class));
|
||||||
|
assertEquals(Map.of("id", "1"), result);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void aRequestWithNoEnvelopeIsThePayload() {
|
void aRequestWithNoEnvelopeIsThePayload() {
|
||||||
answers("{}");
|
answers("{}");
|
||||||
|
|||||||
+48
@@ -10,17 +10,22 @@ import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
|
|||||||
import io.github.hectorvent.floci.services.rdsdata.RdsDataService;
|
import io.github.hectorvent.floci.services.rdsdata.RdsDataService;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.InOrder;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.inOrder;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@@ -111,6 +116,7 @@ class RelationalDataSourceInvokerTest {
|
|||||||
answersOneRow();
|
answersOneRow();
|
||||||
|
|
||||||
invoker.invoke(dataSource(), Map.of(
|
invoker.invoke(dataSource(), Map.of(
|
||||||
|
"version", "2018-05-29",
|
||||||
"statements", List.of("SELECT id FROM messages WHERE org_no = :orgNo"),
|
"statements", List.of("SELECT id FROM messages WHERE org_no = :orgNo"),
|
||||||
"variableMap", Map.of(":orgNo", "556677")), "eu-west-1");
|
"variableMap", Map.of(":orgNo", "556677")), "eu-west-1");
|
||||||
|
|
||||||
@@ -120,6 +126,48 @@ class RelationalDataSourceInvokerTest {
|
|||||||
assertEquals("556677", sent.path("parameters").get(0).path("value").path("stringValue").asText());
|
assertEquals("556677", sent.path("parameters").get(0).path("value").path("stringValue").asText());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoVtlStatementsRunSequentiallyWithoutATransaction() {
|
||||||
|
answersOneRow();
|
||||||
|
|
||||||
|
invoker.invoke(dataSource(), Map.of("version", "2018-05-29",
|
||||||
|
"statements", List.of("UPDATE t SET value = 1", "UPDATE t SET value = 2")), "eu-west-1");
|
||||||
|
|
||||||
|
InOrder order = inOrder(rdsData);
|
||||||
|
ArgumentCaptor<JsonNode> statements = ArgumentCaptor.forClass(JsonNode.class);
|
||||||
|
order.verify(rdsData, times(2)).executeStatement(statements.capture(), anyString());
|
||||||
|
assertEquals("UPDATE t SET value = 1", statements.getAllValues().get(0).path("sql").asText());
|
||||||
|
assertEquals("UPDATE t SET value = 2", statements.getAllValues().get(1).path("sql").asText());
|
||||||
|
assertFalse(statements.getAllValues().get(0).has("transactionId"));
|
||||||
|
assertFalse(statements.getAllValues().get(1).has("transactionId"));
|
||||||
|
verify(rdsData, never()).beginTransaction(any(), anyString());
|
||||||
|
verify(rdsData, never()).commitTransaction(any(), anyString());
|
||||||
|
verify(rdsData, never()).rollbackTransaction(any(), anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void failedSecondVtlStatementDoesNotRollBackTheFirstWrite() {
|
||||||
|
answersOneRow();
|
||||||
|
AwsException failure = new AwsException("DatabaseErrorException", "second statement failed", 400);
|
||||||
|
when(rdsData.executeStatement(any(), anyString()))
|
||||||
|
.thenReturn(mapper.createObjectNode())
|
||||||
|
.thenThrow(failure);
|
||||||
|
|
||||||
|
AwsException actual = assertThrows(AwsException.class, () -> invoker.invoke(dataSource(),
|
||||||
|
Map.of("version", "2018-05-29",
|
||||||
|
"statements", List.of("UPDATE t SET value = 1", "BAD SQL")), "eu-west-1"));
|
||||||
|
|
||||||
|
assertSame(failure, actual);
|
||||||
|
ArgumentCaptor<JsonNode> statements = ArgumentCaptor.forClass(JsonNode.class);
|
||||||
|
InOrder order = inOrder(rdsData);
|
||||||
|
order.verify(rdsData, times(2)).executeStatement(statements.capture(), anyString());
|
||||||
|
assertEquals("UPDATE t SET value = 1", statements.getAllValues().get(0).path("sql").asText());
|
||||||
|
assertEquals("BAD SQL", statements.getAllValues().get(1).path("sql").asText());
|
||||||
|
verify(rdsData, never()).beginTransaction(any(), anyString());
|
||||||
|
verify(rdsData, never()).commitTransaction(any(), anyString());
|
||||||
|
verify(rdsData, never()).rollbackTransaction(any(), anyString());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void declaredTypeHintsTravelWithTheirParameters() {
|
void declaredTypeHintsTravelWithTheirParameters() {
|
||||||
answersOneRow();
|
answersOneRow();
|
||||||
|
|||||||
+224
-4
@@ -7,6 +7,7 @@ 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.AppSyncVtlEngine;
|
||||||
import io.github.hectorvent.floci.services.appsync.graphql.datasource.AppSyncDataSourceInvoker;
|
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.datasource.AppSyncDataSourceInvokers;
|
||||||
|
import io.github.hectorvent.floci.services.appsync.graphql.datasource.LambdaDataSourceInvoker;
|
||||||
import io.github.hectorvent.floci.services.appsync.graphql.js.AppSyncJsRuntime;
|
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.js.JsEvaluation;
|
||||||
import io.github.hectorvent.floci.services.appsync.model.DataSource;
|
import io.github.hectorvent.floci.services.appsync.model.DataSource;
|
||||||
@@ -15,8 +16,13 @@ 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.Resolver;
|
||||||
import io.github.hectorvent.floci.services.appsync.model.ResolverKind;
|
import io.github.hectorvent.floci.services.appsync.model.ResolverKind;
|
||||||
import io.github.hectorvent.floci.services.appsync.model.ResolverRuntimeName;
|
import io.github.hectorvent.floci.services.appsync.model.ResolverRuntimeName;
|
||||||
|
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||||
|
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||||
|
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -28,9 +34,12 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
|||||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -45,9 +54,13 @@ class AppSyncResolverExecutorTest {
|
|||||||
private final ScriptedJsRuntime jsRuntime = new ScriptedJsRuntime();
|
private final ScriptedJsRuntime jsRuntime = new ScriptedJsRuntime();
|
||||||
private final RecordingInvoker invoker = new RecordingInvoker(DataSourceType.RELATIONAL_DATABASE);
|
private final RecordingInvoker invoker = new RecordingInvoker(DataSourceType.RELATIONAL_DATABASE);
|
||||||
private final RecordingInvoker noneInvoker = new RecordingInvoker(DataSourceType.NONE);
|
private final RecordingInvoker noneInvoker = new RecordingInvoker(DataSourceType.NONE);
|
||||||
|
private final RecordingInvoker dynamoDbInvoker =
|
||||||
|
new RecordingInvoker(DataSourceType.AMAZON_DYNAMODB);
|
||||||
|
private final RecordingInvoker lambdaInvoker = new RecordingInvoker(DataSourceType.AWS_LAMBDA);
|
||||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||||
private final AppSyncResolverExecutor executor = new AppSyncResolverExecutor(appSync, jsRuntime,
|
private final AppSyncResolverExecutor executor = new AppSyncResolverExecutor(appSync, jsRuntime,
|
||||||
new AppSyncDataSourceInvokers(List.of(invoker, noneInvoker)), vtlEngine(), objectMapper);
|
new AppSyncDataSourceInvokers(List.of(invoker, noneInvoker, dynamoDbInvoker, lambdaInvoker)),
|
||||||
|
vtlEngine(), objectMapper);
|
||||||
|
|
||||||
private static AppSyncVtlEngine vtlEngine() {
|
private static AppSyncVtlEngine vtlEngine() {
|
||||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||||
@@ -553,6 +566,212 @@ class AppSyncResolverExecutorTest {
|
|||||||
assertTrue(noneInvoker.requests.isEmpty());
|
assertTrue(noneInvoker.requests.isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void vtlDynamoDbResolverUsesTheExistingDataSourceInvoker() {
|
||||||
|
when(appSync.getDataSource(API_ID, "accountTable"))
|
||||||
|
.thenReturn(dataSource("accountTable", DataSourceType.AMAZON_DYNAMODB));
|
||||||
|
dynamoDbInvoker.answer = Map.of("id", "42", "name", "Acme");
|
||||||
|
Resolver resolver = resolver(ResolverKind.UNIT, null);
|
||||||
|
resolver.setDataSourceName("accountTable");
|
||||||
|
resolver.setRequestMappingTemplate("""
|
||||||
|
{"version":"2018-05-29","operation":"GetItem",
|
||||||
|
"key":{"id":{"S":$util.toJson($ctx.args.id)}}}
|
||||||
|
""");
|
||||||
|
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||||
|
|
||||||
|
ResolverOutcome result = executor.execute(resolver, invocation(Map.of("id", "42")));
|
||||||
|
|
||||||
|
assertEquals(Map.of("id", "42", "name", "Acme"), result.data());
|
||||||
|
assertTrue(result.errors().isEmpty());
|
||||||
|
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 vtlLambdaResolverUsesTheExistingDataSourceInvoker() {
|
||||||
|
when(appSync.getDataSource(API_ID, "accountFunction"))
|
||||||
|
.thenReturn(dataSource("accountFunction", DataSourceType.AWS_LAMBDA));
|
||||||
|
lambdaInvoker.answer = Map.of("accepted", true);
|
||||||
|
Resolver resolver = resolver(ResolverKind.UNIT, null);
|
||||||
|
resolver.setDataSourceName("accountFunction");
|
||||||
|
resolver.setRequestMappingTemplate("""
|
||||||
|
{"version":"2018-05-29","operation":"Invoke",
|
||||||
|
"payload":{"id":$util.toJson($ctx.args.id)}}
|
||||||
|
""");
|
||||||
|
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||||
|
|
||||||
|
ResolverOutcome result = executor.execute(resolver, invocation(Map.of("id", "42")));
|
||||||
|
|
||||||
|
assertEquals(Map.of("accepted", true), result.data());
|
||||||
|
assertTrue(result.errors().isEmpty());
|
||||||
|
Map<?, ?> request = (Map<?, ?>) lambdaInvoker.requests.get(0);
|
||||||
|
assertEquals("Invoke", request.get("operation"));
|
||||||
|
assertEquals(Map.of("id", "42"), request.get("payload"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void vtlLambdaInvokeWithoutPayloadKeepsTheMemberAbsent() {
|
||||||
|
when(appSync.getDataSource(API_ID, "accountFunction"))
|
||||||
|
.thenReturn(dataSource("accountFunction", DataSourceType.AWS_LAMBDA));
|
||||||
|
Resolver resolver = resolver(ResolverKind.UNIT, null);
|
||||||
|
resolver.setDataSourceName("accountFunction");
|
||||||
|
resolver.setRequestMappingTemplate("{\"version\":\"2018-05-29\",\"operation\":\"Invoke\"}");
|
||||||
|
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||||
|
|
||||||
|
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
|
||||||
|
|
||||||
|
assertTrue(result.errors().isEmpty());
|
||||||
|
Map<?, ?> request = (Map<?, ?>) lambdaInvoker.requests.get(0);
|
||||||
|
assertEquals("Invoke", request.get("operation"));
|
||||||
|
assertFalse(request.containsKey("payload"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void vtlLambdaInvokeWithoutPayloadSendsTheDocumentToTheFunction() 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);
|
||||||
|
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))),
|
||||||
|
vtlEngine(), objectMapper);
|
||||||
|
Resolver resolver = resolver(ResolverKind.UNIT, null);
|
||||||
|
resolver.setDataSourceName("accountFunction");
|
||||||
|
resolver.setRequestMappingTemplate("{\"version\":\"2018-05-29\",\"operation\":\"Invoke\"}");
|
||||||
|
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||||
|
|
||||||
|
ResolverOutcome result = lambdaExecutor.execute(resolver, invocation(Map.of()));
|
||||||
|
|
||||||
|
assertTrue(result.errors().isEmpty());
|
||||||
|
assertEquals(Map.of(), result.data());
|
||||||
|
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
|
||||||
|
verify(lambdaService).invokeArn(eq(functionArn), payload.capture(),
|
||||||
|
eq(InvocationType.RequestResponse));
|
||||||
|
assertEquals(Map.of("version", "2018-05-29", "operation", "Invoke"),
|
||||||
|
objectMapper.readValue(payload.getValue(), Map.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void vtlRdsResolverUsesTheExistingDataSourceInvoker() {
|
||||||
|
when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
|
||||||
|
invoker.answer = Map.of("sqlStatementResults", List.of(Map.of("numberOfRecordsUpdated", 1)));
|
||||||
|
Resolver resolver = resolver(ResolverKind.UNIT, null);
|
||||||
|
resolver.setDataSourceName("accountDB");
|
||||||
|
resolver.setRequestMappingTemplate("""
|
||||||
|
{"version":"2018-05-29",
|
||||||
|
"statements":["UPDATE account SET active = :active WHERE id = :id"],
|
||||||
|
"variableMap":{":active":true,":id":$util.toJson($ctx.args.id)}}
|
||||||
|
""");
|
||||||
|
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||||
|
|
||||||
|
ResolverOutcome result = executor.execute(resolver, invocation(Map.of("id", "42")));
|
||||||
|
|
||||||
|
assertEquals(invoker.answer, result.data());
|
||||||
|
assertTrue(result.errors().isEmpty());
|
||||||
|
Map<?, ?> request = (Map<?, ?>) invoker.requests.get(0);
|
||||||
|
assertEquals(List.of("UPDATE account SET active = :active WHERE id = :id"),
|
||||||
|
request.get("statements"));
|
||||||
|
assertEquals(Map.of(":active", true, ":id", "42"), request.get("variableMap"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void vtlDataSourceErrorIsAvailableToTheResponseTemplate() {
|
||||||
|
when(appSync.getDataSource(API_ID, "accountFunction"))
|
||||||
|
.thenReturn(dataSource("accountFunction", DataSourceType.AWS_LAMBDA));
|
||||||
|
lambdaInvoker.failure = new AwsException("LambdaExecutionException", "function failed", 400);
|
||||||
|
Resolver resolver = resolver(ResolverKind.UNIT, null);
|
||||||
|
resolver.setDataSourceName("accountFunction");
|
||||||
|
resolver.setRequestMappingTemplate(
|
||||||
|
"{\"version\":\"2018-05-29\",\"operation\":\"Invoke\",\"payload\":{}}");
|
||||||
|
resolver.setResponseMappingTemplate("$util.toJson({\"handled\":$ctx.error.type})");
|
||||||
|
|
||||||
|
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
|
||||||
|
|
||||||
|
assertEquals(Map.of("handled", "LambdaExecutionException"), result.data());
|
||||||
|
assertTrue(result.errors().isEmpty());
|
||||||
|
lambdaInvoker.failure = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unsupportedVtlDynamoDbOperationFailsBeforeInvocation() {
|
||||||
|
when(appSync.getDataSource(API_ID, "accountTable"))
|
||||||
|
.thenReturn(dataSource("accountTable", DataSourceType.AMAZON_DYNAMODB));
|
||||||
|
Resolver resolver = resolver(ResolverKind.UNIT, null);
|
||||||
|
resolver.setDataSourceName("accountTable");
|
||||||
|
resolver.setRequestMappingTemplate(
|
||||||
|
"{\"version\":\"2018-05-29\",\"operation\":\"TransactWriteItems\"}");
|
||||||
|
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("TransactWriteItems"));
|
||||||
|
assertTrue(dynamoDbInvoker.requests.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void eventLambdaInvocationIsExplicitlyUnsupported() {
|
||||||
|
when(appSync.getDataSource(API_ID, "accountFunction"))
|
||||||
|
.thenReturn(dataSource("accountFunction", DataSourceType.AWS_LAMBDA));
|
||||||
|
Resolver resolver = resolver(ResolverKind.UNIT, null);
|
||||||
|
resolver.setDataSourceName("accountFunction");
|
||||||
|
resolver.setRequestMappingTemplate("""
|
||||||
|
{"version":"2018-05-29","operation":"Invoke",
|
||||||
|
"invocationType":"Event","payload":{}}
|
||||||
|
""");
|
||||||
|
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(lambdaInvoker.requests.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void batchLambdaInvocationDoesNotRunAsAnIndependentFieldCall() {
|
||||||
|
when(appSync.getDataSource(API_ID, "accountFunction"))
|
||||||
|
.thenReturn(dataSource("accountFunction", DataSourceType.AWS_LAMBDA));
|
||||||
|
Resolver resolver = resolver(ResolverKind.UNIT, null);
|
||||||
|
resolver.setDataSourceName("accountFunction");
|
||||||
|
resolver.setRequestMappingTemplate("""
|
||||||
|
{"version":"2018-05-29","operation":"BatchInvoke",
|
||||||
|
"payload":[{"id":"42"}]}
|
||||||
|
""");
|
||||||
|
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(lambdaInvoker.requests.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void malformedVtlRdsStatementsFailAsAMappingTemplateError() {
|
||||||
|
when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
|
||||||
|
Resolver resolver = resolver(ResolverKind.UNIT, null);
|
||||||
|
resolver.setDataSourceName("accountDB");
|
||||||
|
resolver.setRequestMappingTemplate(
|
||||||
|
"{\"version\":\"2018-05-29\",\"statements\":\"SELECT 1\"}");
|
||||||
|
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||||
|
|
||||||
|
ResolverOutcome result = executor.execute(resolver, invocation(Map.of()));
|
||||||
|
|
||||||
|
assertEquals(1, result.errors().size());
|
||||||
|
assertEquals("MappingTemplate", result.errors().get(0).errorType());
|
||||||
|
assertTrue(invoker.requests.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void vtlAppendErrorKeepsTheResponseData() {
|
void vtlAppendErrorKeepsTheResponseData() {
|
||||||
when(appSync.getDataSource(API_ID, "local")).thenReturn(dataSource("local", DataSourceType.NONE));
|
when(appSync.getDataSource(API_ID, "local")).thenReturn(dataSource("local", DataSourceType.NONE));
|
||||||
@@ -613,10 +832,11 @@ class AppSyncResolverExecutorTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void vtlRequestReturnCannotBypassNonNoneDataSourceValidation() {
|
void vtlRequestReturnCannotBypassUnsupportedDataSourceValidation() {
|
||||||
when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(dataSource("accountDB"));
|
when(appSync.getDataSource(API_ID, "accountHttp"))
|
||||||
|
.thenReturn(dataSource("accountHttp", DataSourceType.HTTP));
|
||||||
Resolver resolver = resolver(ResolverKind.UNIT, null);
|
Resolver resolver = resolver(ResolverKind.UNIT, null);
|
||||||
resolver.setDataSourceName("accountDB");
|
resolver.setDataSourceName("accountHttp");
|
||||||
resolver.setRequestMappingTemplate("#return({\"short\":\"circuit\"})");
|
resolver.setRequestMappingTemplate("#return({\"short\":\"circuit\"})");
|
||||||
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
resolver.setResponseMappingTemplate("$util.toJson($ctx.result)");
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user