diff --git a/docs/services/appsync.md b/docs/services/appsync.md
index 8e0cbab664..6fa0dd34ee 100644
--- a/docs/services/appsync.md
+++ b/docs/services/appsync.md
@@ -454,7 +454,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. 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. |
+| `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: `ctx.error.type` is `Lambda:` and the invoke's `FunctionError` (`Lambda:Unhandled` for a thrown error), and `ctx.error.message` is the function's `errorMessage`, or the raw error payload when it has none. |
| `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. |
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvoker.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvoker.java
index ec9508226a..f77a718632 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvoker.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvoker.java
@@ -1,6 +1,10 @@
package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectReader;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.appsync.model.DataSource;
import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
@@ -21,19 +25,22 @@ import java.util.Map;
*
*
The request is AppSync's {@code {operation: "Invoke", payload: …}}, or, for
* {@code BatchInvoke}, a list payload the function answers with a list in the same order. A
- * function that returns a handled error (a Lambda {@code errorMessage}) fails the field rather than
- * resolving to the error object, which is what AppSync does with an unhandled function error.
+ * function error fails the field rather than resolving to the error object: its type is
+ * {@code Lambda:} and the invoke's {@code FunctionError}, and its message the {@code errorMessage}
+ * Lambda set, which is what AppSync reports for an unhandled function error.
*/
@ApplicationScoped
public class LambdaDataSourceInvoker implements AppSyncDataSourceInvoker {
private final LambdaService lambdaService;
private final ObjectMapper objectMapper;
+ private final ObjectReader strictPayloadReader;
@Inject
public LambdaDataSourceInvoker(LambdaService lambdaService, ObjectMapper objectMapper) {
this.lambdaService = lambdaService;
this.objectMapper = objectMapper;
+ this.strictPayloadReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
}
@Override
@@ -79,8 +86,8 @@ public class LambdaDataSourceInvoker implements AppSyncDataSourceInvoker {
? null
: new String(result.getPayload(), StandardCharsets.UTF_8);
if (result.getFunctionError() != null && !result.getFunctionError().isBlank()) {
- throw new AwsException("LambdaExecutionException",
- "The Lambda data source function failed: " + response, 400);
+ throw new AwsException("Lambda:" + result.getFunctionError(),
+ functionErrorMessage(response), 400);
}
if (response == null || response.isBlank()) {
return null;
@@ -94,6 +101,20 @@ public class LambdaDataSourceInvoker implements AppSyncDataSourceInvoker {
}
}
+ /** The payload's {@code errorMessage}, or the raw payload when it does not carry a textual one. */
+ private String functionErrorMessage(String response) {
+ if (response == null) {
+ return "";
+ }
+ try {
+ JsonNode errorMessage = strictPayloadReader.readTree(response).path("errorMessage");
+ return errorMessage.isTextual() ? errorMessage.textValue() : response;
+ } catch (JsonProcessingException ignored) {
+ // A function that failed with something other than JSON: the text is all there is to report.
+ return response;
+ }
+ }
+
private String functionArn(DataSource dataSource) {
Map config = dataSource.getLambdaConfig();
Object arn = config == null ? null : config.get("lambdaFunctionArn");
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvokerTest.java
index 7c29133384..ee0d9ed585 100644
--- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvokerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/LambdaDataSourceInvokerTest.java
@@ -8,6 +8,8 @@ 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.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.nio.charset.StandardCharsets;
@@ -115,16 +117,99 @@ class LambdaDataSourceInvokerTest {
assertEquals(List.of(Map.of("id", "1"), Map.of("id", "2")), result);
}
+ private void failsWith(String functionError, byte[] payload) {
+ when(lambda.invokeArn(eq(FN_ARN), any(), eq(InvocationType.RequestResponse)))
+ .thenReturn(new InvokeResult(200, functionError, payload, null, "req-1"));
+ }
+
+ private AwsException functionFailure(Map request) {
+ return assertThrows(AwsException.class, () -> invoker.invoke(dataSource(), request, "eu-west-1"));
+ }
+
@Test
void aFunctionErrorFailsTheFieldRatherThanResolvingToTheErrorObject() {
- when(lambda.invokeArn(eq(FN_ARN), any(), eq(InvocationType.RequestResponse)))
- .thenReturn(new InvokeResult(200, "Unhandled",
- "{\"errorMessage\": \"boom\"}".getBytes(StandardCharsets.UTF_8), null, "req-1"));
+ failsWith("Unhandled", ("{\"errorType\":\"Error\",\"errorMessage\":\"I always fail.\","
+ + "\"trace\":[\"Error: I always fail.\"]}").getBytes(StandardCharsets.UTF_8));
- AwsException e = assertThrows(AwsException.class, () -> invoker.invoke(dataSource(),
- Map.of("payload", Map.of()), "eu-west-1"));
+ AwsException e = functionFailure(Map.of("payload", Map.of()));
- assertTrue(e.getMessage().contains("boom"), e.getMessage());
+ assertEquals("Lambda:Unhandled", e.getErrorCode());
+ assertEquals("I always fail.", e.getMessage());
+ }
+
+ @Test
+ void theErrorTypeIsTheFunctionErrorTheInvokeReported() {
+ failsWith("Handled", "{\"errorMessage\":\"boom\"}".getBytes(StandardCharsets.UTF_8));
+
+ AwsException e = functionFailure(Map.of("payload", Map.of()));
+
+ assertEquals("Lambda:Handled", e.getErrorCode());
+ assertEquals("boom", e.getMessage());
+ }
+
+ @Test
+ void aVtlInvokeReportsTheFunctionErrorTheSameWay() {
+ failsWith("Unhandled", "{\"errorMessage\":\"boom\"}".getBytes(StandardCharsets.UTF_8));
+
+ AwsException e = assertThrows(AwsException.class, () -> invoker.invokeVtl(dataSource(),
+ Map.of("version", "2018-05-29", "operation", "Invoke", "payload", Map.of()), "eu-west-1"));
+
+ assertEquals("Lambda:Unhandled", e.getErrorCode());
+ assertEquals("boom", e.getMessage());
+ }
+
+ @Test
+ void aBatchInvokeReportsTheFunctionErrorTheSameWay() {
+ failsWith("Unhandled", "{\"errorMessage\":\"boom\"}".getBytes(StandardCharsets.UTF_8));
+
+ AwsException e = functionFailure(Map.of("operation", "BatchInvoke",
+ "payload", List.of(Map.of("id", "1"))));
+
+ assertEquals("Lambda:Unhandled", e.getErrorCode());
+ assertEquals("boom", e.getMessage());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "{\"errorType\":\"Error\"}",
+ "{\"errorMessage\":{\"nested\":true}}",
+ "{\"errorMessage\":42}",
+ "{\"errorMessage\":null}",
+ "[\"errorMessage\"]",
+ "\"errorMessage\"",
+ "not json {",
+ "{\"errorMessage\":\"boom\"} trailing garbage",
+ "{\"errorMessage\":\"first\"}{\"errorMessage\":\"second\"}",
+ " ",
+ ""
+ })
+ void aPayloadWithoutATextualErrorMessageIsTheMessageAsIs(String payload) {
+ failsWith("Unhandled", payload.getBytes(StandardCharsets.UTF_8));
+
+ AwsException e = functionFailure(Map.of("payload", Map.of()));
+
+ assertEquals("Lambda:Unhandled", e.getErrorCode());
+ assertEquals(payload, e.getMessage());
+ }
+
+ @Test
+ void whitespaceAfterTheErrorPayloadStillYieldsTheErrorMessage() {
+ failsWith("Unhandled", "{\"errorMessage\":\"boom\"}\n".getBytes(StandardCharsets.UTF_8));
+
+ AwsException e = functionFailure(Map.of("payload", Map.of()));
+
+ assertEquals("Lambda:Unhandled", e.getErrorCode());
+ assertEquals("boom", e.getMessage());
+ }
+
+ @Test
+ void aNullErrorPayloadStillFailsWithTheFunctionErrorType() {
+ failsWith("Unhandled", null);
+
+ AwsException e = functionFailure(Map.of("payload", Map.of()));
+
+ assertEquals("Lambda:Unhandled", e.getErrorCode());
+ assertEquals("", e.getMessage());
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java
index 900e14916c..cff07f0cf5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java
@@ -659,6 +659,96 @@ class AppSyncResolverExecutorTest {
assertEquals(request.get("payload"), objectMapper.readValue(payload.getValue(), Map.class));
}
+ private AppSyncResolverExecutor executorOverAThrowingFunction(byte[] errorPayload) {
+ 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, "Unhandled", errorPayload, null, "request-id"));
+ return new AppSyncResolverExecutor(appSync, jsRuntime,
+ new AppSyncDataSourceInvokers(List.of(new LambdaDataSourceInvoker(lambdaService, objectMapper)),
+ mock(AppSyncDataSourceAuthorizer.class)),
+ vtlEngine(), objectMapper);
+ }
+
+ private static byte[] thrownErrorPayload() {
+ return "{\"errorType\":\"Error\",\"errorMessage\":\"I always fail.\",\"trace\":[]}"
+ .getBytes(StandardCharsets.UTF_8);
+ }
+
+ private Resolver vtlResolverForwardingCtxError() {
+ Resolver resolver = resolver(ResolverKind.UNIT, null);
+ resolver.setDataSourceName("accountFunction");
+ resolver.setRequestMappingTemplate(
+ "{\"version\":\"2018-05-29\",\"operation\":\"Invoke\",\"payload\":{}}");
+ resolver.setResponseMappingTemplate("""
+ #if($ctx.error)
+ $util.error($ctx.error.message, $ctx.error.type)
+ #end
+ $util.toJson($ctx.result)
+ """);
+ return resolver;
+ }
+
+ private void assertFieldFailedWithFunctionError(ResolverOutcome result, String message) {
+ assertNull(result.data());
+ assertEquals(1, result.errors().size());
+ assertEquals(message, result.errors().get(0).message());
+ assertEquals("Lambda:Unhandled", result.errors().get(0).errorType());
+ }
+
+ @Test
+ void jsResponseHandlerThatForwardsCtxErrorReportsTheFunctionError() {
+ AppSyncResolverExecutor lambdaExecutor = executorOverAThrowingFunction(thrownErrorPayload());
+ Resolver resolver = resolver(ResolverKind.UNIT, "unit-code");
+ resolver.setDataSourceName("accountFunction");
+ jsRuntime.script("unit-code", "request",
+ (handler, context) -> ok(Map.of("operation", "Invoke", "payload", Map.of())));
+ // What `if (ctx.error) util.error(ctx.error.message, ctx.error.type)` does.
+ jsRuntime.script("unit-code", "response", (handler, context) -> {
+ Map, ?> ctxError = (Map, ?>) context.get("error");
+ return new JsEvaluation(null, Map.of(), false, List.of(), new JsEvaluation.JsError(
+ (String) ctxError.get("message"), (String) ctxError.get("type"), null, null), false);
+ });
+
+ ResolverOutcome result = lambdaExecutor.execute(resolver, invocation(Map.of()));
+
+ assertFieldFailedWithFunctionError(result, "I always fail.");
+ }
+
+ @Test
+ void jsResolverWithNoResponseHandlerReportsTheFunctionError() {
+ AppSyncResolverExecutor lambdaExecutor = executorOverAThrowingFunction(thrownErrorPayload());
+ Resolver resolver = resolver(ResolverKind.UNIT, "unit-code");
+ resolver.setDataSourceName("accountFunction");
+ jsRuntime.script("unit-code", "request",
+ (handler, context) -> ok(Map.of("operation", "Invoke", "payload", Map.of())));
+
+ ResolverOutcome result = lambdaExecutor.execute(resolver, invocation(Map.of()));
+
+ assertFieldFailedWithFunctionError(result, "I always fail.");
+ }
+
+ @Test
+ void vtlResponseTemplateThatForwardsCtxErrorReportsTheFunctionError() {
+ AppSyncResolverExecutor lambdaExecutor = executorOverAThrowingFunction(thrownErrorPayload());
+
+ ResolverOutcome result = lambdaExecutor.execute(vtlResolverForwardingCtxError(), invocation(Map.of()));
+
+ assertFieldFailedWithFunctionError(result, "I always fail.");
+ }
+
+ @Test
+ void vtlResponseTemplateSurvivesAFunctionErrorWithNoPayload() {
+ AppSyncResolverExecutor lambdaExecutor = executorOverAThrowingFunction(null);
+
+ ResolverOutcome result = lambdaExecutor.execute(vtlResolverForwardingCtxError(), invocation(Map.of()));
+
+ assertFieldFailedWithFunctionError(result, "");
+ }
+
@Test
void vtlLambdaResolverSendsOnlyPayloadToTheFunction() throws Exception {
String functionArn = "arn:aws:lambda:eu-west-1:000000000000:function:resolver-fn";