Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(appsync): execute APPSYNC_JS resolvers (#1562)
Jacob Schooley7f99cf04ce2d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 75c6eca3..44881e4e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,7 +23,14 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **IoT Core — provisioning templates, and `AWS::IoT::ProvisioningTemplate`** — `CreateProvisioningTemplate` and the four other template operations answered `Unsupported IoT path` and the CloudFormation type rolled back as unsupported; both now work with the wire shapes of the real service (`ResourceAlreadyExistsException` on duplicates, absent-not-empty `description`, 1-36 char names, a `templateBody` without an `AWS::IoT::Certificate` resource refused). Storage + CRUD only: the fleet-provisioning MQTT workflow is not implemented and versions are not modeled. Contributed by @iot-rocket.- **API Gateway — registered custom domains route the data plane** — a request addressed by a registered domain fell through host-pattern service guessing (typically into S3, or into IoT when the name contained `iot.`); it now resolves through the domain's base-path mappings before any guessing — longest base path wins, `"(none)"` is the root mapping, a mapping's stage is authoritative — matching the `BASE_PATH_MAPPING_ONLY` routing mode the records default to. Unregistered hosts are unchanged. Contributed by @iot-rocket.- **CloudFormation — in-place update handlers** — a stack update fell through to a destructive re-create for 106 of 132 registered types, wiping published Lambda versions, DynamoDB items, SQS messages and IAM attachments; `AWS::Lambda::Function`, `AWS::DynamoDB::Table`, the four API Gateway types, `AWS::IoT::TopicRule`, `AWS::SNS::Topic`, `AWS::SQS::Queue`, `AWS::Logs::LogGroup`, `AWS::S3::BucketPolicy`, `AWS::IAM::Role` and `AWS::IAM::ManagedPolicy` now update in place through their service's own APIs, replacing only for genuinely create-only properties, as CloudFormation documents per property. Contributed by @iot-rocket.+- **AppSync — `util.transform` DynamoDB expression builders** — DynamoDB is the data source most AppSync APIs use, and `toDynamoDBFilterExpression` is how a resolver turns a GraphQL filter argument into something DynamoDB can evaluate, so of the four transform functions it is the one that gets called; it returned nothing, because `util.transform` was an empty object. It now builds the `{expression, expressionNames, expressionValues}` triple over AWS’s documented operator set — `eq`, `ne`, `lt`, `le`, `gt`, `ge`, `contains`, `notContains`, `beginsWith`, `between`, `in`, `attributeExists`, `attributeType` — with `and`/`or`/`not` nesting and sibling conditions ANDed. `toDynamoDBConditionExpression` shares it, being the same grammar. Contributed by @jbschooley.+- **AppSync — the rest of the `util` surface** — 8 of the 21 members `@aws-appsync/utils` declares were provided, and three of those were wrong rather than incomplete: `autoUlid` returned a UUID, `util.dynamodb` had a single pass-through `toDynamoDB` that produced no AttributeValue shapes, and `util.transform` was an empty object so a call failed as “not a function” away from the cause. Adds `base64Encode`/`Decode`, `urlEncode`/`Decode`, `escapeJavaScript`, `matches`, `authType`, real `autoUlid` and `autoKsuid`, `util.str.normalize`, all of `util.math`, the six missing `util.time` functions, the full `util.dynamodb` `to*` family, and `util.rds.toJsonObject`. `util.xml`, `util.transform` and the `util.http` response-header functions throw naming themselves, since they need an XML parser, a DynamoDB expression builder, or the response AppSync is building. Contributed by @jbschooley.+- **AppSync — the `@aws-appsync/utils/dynamodb` helpers, and `EvaluateCode`** — the helper sub-module was stripped along with every other import, which is right for the types-only root package but wrong here: `ddb.get`/`put`/`update`/`remove`/`scan`/`query` build the request objects a resolver returns, so a resolver using them died with “ddb is not defined”. They are now provided and bound to whatever name the import used. Fixing that surfaced a second bug — the compile cache re-ran the module on every call, throwing on any top-level `const` a resolver declares — so a module is now evaluated once with the injected globals closing over a mutable holder. `EvaluateCode` is implemented on top of the evaluator, so a resolver can be tested before it is attached to an API, as it can against AWS. Contributed by @jbschooley.+- **AppSync — nested type resolvers, `ctx.identity` from Cognito, `ctx.env` and `ctx.error`** — only top-level `Query`/`Mutation` fields resolved, so a resolver on a nested type never fired and its field was simply absent from the response, which is where most of an API’s resolvers live. A resolved value’s type is now looked up in the API’s SDL and the resolvers attached to it run with the parent as `ctx.source`. `ctx.identity` is populated from a Cognito token when the API is configured for a user pool — it was only ever set by a Lambda authorizer, so a Cognito API saw `null` and every permission check failed. `ctx.env` exposes the API’s environment variables, and `ctx.error` is set when the data source fails so `response()` can turn an upstream failure into its own error or a fallback. Contributed by @jbschooley.+- **AppSync — `APPSYNC_JS` resolvers execute** — resolver code was stored and never run: the executor dispatched on data source type and inferred an operation from the field arguments, so a resolver’s own logic never affected the answer, and four of the six data source types the control plane accepts fell through to a mock that echoed the arguments. `request()` now decides what the data source is asked for and `response()` shapes the answer, with `util.error` becoming a GraphQL error carrying its `errorType`, `util.appendError` riding alongside the data, and `runtime.earlyReturn` following what AWS documents in both places it can appear — from a function the data source and response handler are skipped and the next function runs, from a pipeline resolver the pipeline is skipped and the resolver’s own response handler still runs. Pipeline resolvers run their functions in order with `ctx.stash` carried across, and response handlers see both `ctx.prev.result` and `ctx.result`. All three `APPSYNC_JS` globals are provided, `extensions` included: its `evictFromApiCache` calls are recorded and handed back to the service, which is how a mutation invalidates a cached query. A resolver returning `{operation: "Invoke", payload}` sends that payload to a Lambda data source verbatim. Data source handlers and runtimes are registries, so `NONE`, `HTTP`, `AMAZON_DYNAMODB` and `AWS_LAMBDA` are entries rather than branches and the two remaining types refuse with `NotImplemented` instead of answering a mock. A resolver with no `APPSYNC_JS` code behaves exactly as before. No new dependency — evaluation reuses the Node the image already ships for the `nodejs*` Lambda runtimes. Note that Node is more permissive than the real `APPSYNC_JS` sandbox, so a resolver that runs here can still be refused on deploy. Contributed by @jbschooley.- **S3 — replication delivers, with `x-amz-replication-status`** — a bucket's replication configuration was stored and echoed but never acted on: no object ever reached the destination and `HeadObject` showed no replication metadata. A write (put, POST upload, copy, or multipart complete) matching an Enabled rule's prefix now lands a copy in the destination bucket with its own version, the source's metadata, storage class override, and tags; the source object answers `ReplicationStatus: COMPLETED` (or `FAILED` when the destination is gone or no longer versioned) and the replica answers `REPLICA`, on current and version-addressed reads alike. The copy is synchronous so tests see a deterministic status. Delete-marker replication and replica re-replication are not modeled. Reported by @cringdahl.+- **AppSync — the API cache, control plane and data plane** — `CreateApiCache`, `GetApiCache`, `UpdateApiCache`, `DeleteApiCache` and `FlushApiCache` all answered `Unsupported route`, so `aws_appsync_api_cache` could not be applied and an environment that enables caching in the cloud had to turn it off locally, diverging from the thing it is meant to reproduce. The five operations now round-trip a cache record — one per API, released with its API, surviving a restore — with `atRestEncryptionEnabled` and `transitEncryptionEnabled` fixed at create time and carried across an update rather than reverting to false. The data plane honours it as well, which the control plane alone did not: query resolvers consult the cache, following AppSync’s behaviour for `PER_RESOLVER_CACHING` and `FULL_REQUEST_CACHING`, with caching keys evaluated against the field’s arguments, identity and source, and a key that cannot be resolved disabling caching for that call rather than collapsing two callers onto one entry. Mutations neither read nor populate it, only successful results are cached, and `FlushApiCache` empties it. Contributed by @jbschooley.+- **AppSync — schema creation, pipeline functions, environment variables and the `Update*` operations** — `StartSchemaCreation`, `GetSchemaCreationStatus`, `GetIntrospectionSchema`, the function operations, `Put`/`GetGraphqlApiEnvironmentVariables` and `UpdateDataSource` / `UpdateResolver` / `UpdateFunction` / `UpdateType` all answered `Unsupported route`, so an API could be created but had no schema, no pipeline functions, and nothing about it could be changed in place. `CreateGraphqlApi` also omitted `apiType`, `visibility` and `introspectionConfig` — the first two `ForceNew` in the Terraform provider, so a no-change plan proposed replacing the API and every resource beneath it — and left the tags it was given off the API object, where the provider reads them. The SDL is stored as given and served back verbatim rather than parsed. Contributed by @jbschooley.### Fixed- **CloudFormation — a resource that cannot be deleted fails the operation** — a missing delete handler was a log warning and `DeleteStack` reported `DELETE_COMPLETE` while resources lived on; the stack now lands `DELETE_FAILED` (failed resources retained for a retry, exports kept, deleted siblings gone) and a failed rollback lands `ROLLBACK_FAILED`/`UPDATE_ROLLBACK_FAILED`, per the documented lifecycle. `AWS::Lambda::Version` gained a real delete handler (its `Ref` now returns the qualified version ARN, as on AWS) and `AWS::AppSync::GraphQLSchema` one that removes the stored schema. Contributed by @iot-rocket.diff --git a/ministack/core/appsync_js.py b/ministack/core/appsync_js.pynew file mode 100644index 00000000..662acbe9--- /dev/null+++ b/ministack/core/appsync_js.py@@ -0,0 +1,583 @@+"""APPSYNC_JS resolver evaluation.++AppSync resolvers are ES modules exporting `request(ctx)` and `response(ctx)`.+Evaluating them needs a JavaScript engine, and the image already ships Node for+the `nodejs*` Lambda runtimes (`Dockerfile`, `core/lambda_runtime.py`), so this+reuses it rather than adding a dependency.++One long-lived worker handles every evaluation over a JSON-line protocol, the+same shape `lambda_runtime` uses: a request per line on stdin, a reply per line+on stdout. Compiled modules are cached in the worker by the hash of their source,+so a resolver is only compiled once however many times it runs.++Fidelity note: Node is more permissive than the real APPSYNC_JS sandbox, which+forbids `async`/`await`, `try`/`catch` and most globals. A resolver that runs+here can still be refused on deploy. Enforcing the sandbox is a separate piece of+work; `aws appsync evaluate-code` is the check for that.+"""++from __future__ import annotations++import json+import logging+import subprocess+import threading++logger = logging.getLogger("appsync")++_NODE_BINARY = "node"++# stdout carries the protocol, so anything the resolver logs goes to stderr.+_WORKER_SCRIPT = r"""+const readline = require("readline");+const vm = require("vm");+const crypto = require("crypto");++const _stderrWrite = process.stderr.write.bind(process.stderr);+const _stdoutWrite = process.stdout.write.bind(process.stdout);+process.stdout.write = (chunk, enc, cb) => _stderrWrite(chunk, enc, cb);++// Signals a resolver raised through util.error / util.appendError, and the+// early return that ends a pipeline. Carried back to Python as structured+// results rather than thrown, so the caller can tell them apart from a bug.+class AppSyncError extends Error {+ constructor(message, errorType, data, errorInfo) {+ super(message);+ this.errorType = errorType || "UnknownError";+ this.data = data ?? null;+ this.errorInfo = errorInfo ?? null;+ }+}+class EarlyReturn extends Error {+ // skipTo is 'NEXT' (skip this function, run the next) or 'END' (skip the rest+ // of the pipeline and go to the resolver's response handler).+ constructor(value, skipTo) { super("early return"); this.value = value; this.skipTo = skipTo; }+}++function makeGlobals(state) {+ // AWS's util surface, from @aws-appsync/utils' own type definitions. What is+ // not implemented throws naming itself, rather than returning undefined and+ // failing somewhere later in the resolver.+ const notImplemented = (name) => () => {+ throw new Error(`util.${name} is not implemented by ministack yet`);+ };+ const b64 = (v) => Buffer.from(typeof v === "string" ? v : String(v));++ const util = {+ error(message, errorType, data, errorInfo) {+ throw new AppSyncError(message, errorType, data, errorInfo);+ },+ appendError(message, errorType, data, errorInfo) {+ state.appended.push({ message, errorType: errorType || "UnknownError",+ data: data ?? null, errorInfo: errorInfo ?? null });+ },+ unauthorized() { throw new AppSyncError("Unauthorized", "Unauthorized"); },++ autoId: () => crypto.randomUUID(),+ // ULID and KSUID are sortable ids with their own alphabets — a UUID would+ // be the wrong shape for anything that parses or orders them.+ autoUlid: () => {+ const A = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";+ let t = Date.now(), time = "";+ for (let i = 9; i >= 0; i--) { time = A[t % 32] + time; t = Math.floor(t / 32); }+ let rand = "";+ const bytes = crypto.randomBytes(16);+ for (let i = 0; i < 16; i++) rand += A[bytes[i] % 32];+ return time + rand;+ },+ autoKsuid: () => {+ const A = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";+ const buf = Buffer.concat([+ (() => { const b = Buffer.alloc(4);+ b.writeUInt32BE(Math.floor(Date.now() / 1000) - 1400000000); return b; })(),+ crypto.randomBytes(16),+ ]);+ let n = BigInt("0x" + buf.toString("hex")), out = "";+ while (n > 0n) { out = A[Number(n % 62n)] + out; n /= 62n; }+ return out.padStart(27, "0");+ },++ base64Encode: (v) => b64(v).toString("base64"),+ base64Decode: (v) => Buffer.from(String(v), "base64").toString("utf8"),+ urlEncode: (v) => encodeURIComponent(String(v)).replace(/[!'()*]/g,+ (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()),+ urlDecode: (v) => decodeURIComponent(String(v)),+ escapeJavaScript: (v) => String(v)+ .replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/"/g, '\\"')+ .replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"),+ matches: (pattern, value) => new RegExp(pattern).test(String(value)),+ authType: () => state.authType || "API Key Authorization",++ str: { normalize: (s2, form) => String(s2).normalize(form || "NFC") },++ math: {+ roundNum: (n) => Math.round(n),+ minVal: (a, b) => Math.min(a, b),+ maxVal: (a, b) => Math.max(a, b),+ randomDouble: () => Math.random(),+ randomWithinRange: (start, end) =>+ Math.floor(Math.random() * (end - start)) + start,+ },++ time: {+ nowISO8601: () => new Date().toISOString(),+ nowEpochSeconds: () => Math.floor(Date.now() / 1000),+ nowEpochMilliSeconds: () => Date.now(),+ nowFormatted: (fmt) => _fmt(new Date(), fmt),+ epochMilliSecondsToSeconds: (ms) => Math.floor(ms / 1000),+ epochMilliSecondsToISO8601: (ms) => new Date(ms).toISOString(),+ epochMilliSecondsToFormatted: (ms, fmt) => _fmt(new Date(ms), fmt),+ parseISO8601ToEpochMilliSeconds: (v) => Date.parse(v),+ parseFormattedToEpochMilliSeconds: (v) => Date.parse(v),+ },++ dynamodb: {+ toString: (v) => ({ S: String(v) }),+ toStringSet: (v) => ({ SS: (v || []).map(String) }),+ toNumber: (v) => ({ N: String(v) }),+ toNumberSet: (v) => ({ NS: (v || []).map(String) }),+ toBinary: (v) => ({ B: v }),+ toBinarySet: (v) => ({ BS: v || [] }),+ toBoolean: (v) => ({ BOOL: Boolean(v) }),+ toNull: () => ({ NULL: true }),+ toList: (v) => ({ L: (v || []).map(util.dynamodb.toDynamoDB) }),+ toMap: (v) => ({ M: util.dynamodb.toMapValues(v) }),+ toMapValues: (v) => Object.fromEntries(+ Object.entries(v || {}).map(([k, x]) => [k, util.dynamodb.toDynamoDB(x)])),+ toDynamoDB: (v) => {+ if (v === null || v === undefined) return { NULL: true };+ if (typeof v === "string") return { S: v };+ if (typeof v === "number") return { N: String(v) };+ if (typeof v === "boolean") return { BOOL: v };+ if (Array.isArray(v)) return { L: v.map(util.dynamodb.toDynamoDB) };+ return { M: util.dynamodb.toMapValues(v) };+ },+ toS3Object: (key, bucket, region, version) => ({+ s3: { key, bucket, region, ...(version ? { version } : {}) } }),+ fromS3ObjectJson: (v) => {+ const o = typeof v === "string" ? JSON.parse(v) : v;+ return (o && o.s3) || null;+ },+ },++ rds: {+ // The shape RDS Data API returns, flattened the way AppSync flattens it.+ toJsonObject: (result) => {+ const out = [];+ for (const set of (result && result.sqlStatementResults) || []) {+ const cols = ((set.resultFrame || {}).resultSetMetadata || {}).columnMetadata || [];+ const rows = ((set.resultFrame || {}).records) || [];+ out.push(rows.map((r) => Object.fromEntries(+ (r.values || []).map((cell, i) => {+ const name = (cols[i] || {}).name || String(i);+ const [, value] = Object.entries(cell || {})[0] || [null, null];+ return [name, value];+ }))));+ }+ return out;+ },+ },++ // Response headers need the response AppSync is building, which the+ // evaluator does not own; xml and transform need a parser and a DynamoDB+ // expression builder. Refuse by name rather than silently do nothing.+ http: {+ addResponseHeader: notImplemented("http.addResponseHeader"),+ addResponseHeaders: notImplemented("http.addResponseHeaders"),+ copyHeaders: (headers) => ({ ...(headers || {}) }),+ },+ xml: {+ toJsonString: notImplemented("xml.toJsonString"),+ toMap: notImplemented("xml.toMap"),+ },+ transform: {+ toDynamoDBFilterExpression: (filter) => _ddbExpression(filter),+ // A condition expression is the same grammar; DynamoDB just applies it to+ // the item being written rather than to the items being read.+ toDynamoDBConditionExpression: (filter) => _ddbExpression(filter),+ toElasticsearchQueryDSL: notImplemented("transform.toElasticsearchQueryDSL"),+ toSubscriptionFilter: notImplemented("transform.toSubscriptionFilter"),+ },+ };++ const runtime = {+ earlyReturn(value, returnOptions) {+ throw new EarlyReturn(value, returnOptions && returnOptions.skipTo);+ },+ };++ // `extensions` is the third global AppSync injects, alongside util and+ // runtime. Its calls are side effects on AppSync's own machinery, so they are+ // recorded and handed back rather than executed here — the cache lives in the+ // service, not in this worker.+ const extensions = {+ evictFromApiCache(typeName, fieldName, keys) {+ state.extensions.push({ op: "evictFromApiCache", typeName, fieldName, keys });+ return {};+ },+ setSubscriptionFilter(filter) {+ state.extensions.push({ op: "setSubscriptionFilter", filter });+ },+ setSubscriptionInvalidationFilter(filter) {+ state.extensions.push({ op: "setSubscriptionInvalidationFilter", filter });+ },+ invalidateSubscriptions(payload) {+ state.extensions.push({ op: "invalidateSubscriptions", payload });+ },+ };+ return { util, runtime, extensions };+}++// @aws-appsync/utils/dynamodb — unlike the root package, this one is not+// types-only: its helpers build the request objects a resolver returns. They+// are pure functions over their arguments, so they are reimplemented here+// rather than resolved from node_modules the resolver does not ship with.+function makeDdbHelpers() {+ const cond = (c) => (c === undefined ? undefined : c);+ return {+ get: ({ key }) => ({ operation: "GetItem", key }),+ put: ({ key, item, condition }) => ({+ operation: "PutItem", key, attributeValues: item || {},+ ...(cond(condition) ? { condition } : {}),+ }),+ update: ({ key, update, condition }) => ({+ operation: "UpdateItem", key, update: update || {},+ ...(cond(condition) ? { condition } : {}),+ }),+ remove: ({ key, condition }) => ({+ operation: "DeleteItem", key,+ ...(cond(condition) ? { condition } : {}),+ }),+ scan: ({ filter, index, limit, nextToken, consistentRead, segment, totalSegments } = {}) => ({+ operation: "Scan",+ ...(filter ? { filter } : {}), ...(index ? { index } : {}),+ ...(limit ? { limit } : {}), ...(nextToken ? { nextToken } : {}),+ ...(consistentRead ? { consistentRead } : {}),+ ...(segment !== undefined ? { segment } : {}),+ ...(totalSegments !== undefined ? { totalSegments } : {}),+ }),+ query: ({ query, filter, index, limit, nextToken, scanIndexForward, consistentRead, select } = {}) => ({+ operation: "Query", query,+ ...(filter ? { filter } : {}), ...(index ? { index } : {}),+ ...(limit ? { limit } : {}), ...(nextToken ? { nextToken } : {}),+ ...(scanIndexForward !== undefined ? { scanIndexForward } : {}),+ ...(consistentRead ? { consistentRead } : {}),+ ...(select ? { select } : {}),+ }),+ sync: (args = {}) => ({ operation: "Sync", ...args }),+ // Condition/update expression builders.+ operations: {+ add: (value) => ({ __op: "add", value }),+ append: (value) => ({ __op: "append", value }),+ prepend: (value) => ({ __op: "prepend", value }),+ increment: (by) => ({ __op: "increment", by }),+ decrement: (by) => ({ __op: "decrement", by }),+ replace: (value) => ({ __op: "replace", value }),+ updateListItem: (value, index) => ({ __op: "updateListItem", value, index }),+ remove: () => ({ __op: "remove" }),+ },+ };+}++// util.transform.toDynamoDB{Filter,Condition}Expression+//+// Turns the filter object a GraphQL argument carries into the+// {expression, expressionNames, expressionValues} triple DynamoDB wants.+// DynamoDB is the data source most AppSync APIs use, so this is the transform+// function that actually gets called.+function _ddbExpression(filter) {+ const names = {};+ const values = {};++ const toAttr = (v) => {+ if (v === null || v === undefined) return { NULL: true };+ if (typeof v === "string") return { S: v };+ if (typeof v === "number") return { N: String(v) };+ if (typeof v === "boolean") return { BOOL: v };+ if (Array.isArray(v)) return { L: v.map(toAttr) };+ return { M: Object.fromEntries(Object.entries(v).map(([k, x]) => [k, toAttr(x)])) };+ };+ const nameRef = (field) => { names[`#${field}`] = field; return `#${field}`; };+ const valueRef = (field, op, v, suffix) => {+ const k = `:${field}_${op}${suffix === undefined ? "" : "_" + suffix}`;+ values[k] = toAttr(v);+ return k;+ };++ // AppSync's documented operator set.+ const OPS = {+ eq: (n, f, v) => `${n} = ${valueRef(f, "eq", v)}`,+ ne: (n, f, v) => `${n} <> ${valueRef(f, "ne", v)}`,+ lt: (n, f, v) => `${n} < ${valueRef(f, "lt", v)}`,+ le: (n, f, v) => `${n} <= ${valueRef(f, "le", v)}`,+ gt: (n, f, v) => `${n} > ${valueRef(f, "gt", v)}`,+ ge: (n, f, v) => `${n} >= ${valueRef(f, "ge", v)}`,+ contains: (n, f, v) => `contains(${n}, ${valueRef(f, "contains", v)})`,+ notContains: (n, f, v) => `NOT contains(${n}, ${valueRef(f, "notContains", v)})`,+ beginsWith: (n, f, v) => `begins_with(${n}, ${valueRef(f, "beginsWith", v)})`,+ between: (n, f, v) =>+ `${n} BETWEEN ${valueRef(f, "between", v[0], 0)} AND ${valueRef(f, "between", v[1], 1)}`,+ in: (n, f, v) =>+ `${n} IN (${v.map((x, i) => valueRef(f, "in", x, i)).join(",")})`,+ attributeExists: (n, _f, v) => (v ? `attribute_exists(${n})` : `attribute_not_exists(${n})`),+ attributeType: (n, f, v) => `attribute_type(${n}, ${valueRef(f, "attributeType", v)})`,+ };++ const walk = (node) => {+ const parts = [];+ for (const [key, value] of Object.entries(node || {})) {+ if (value === null || value === undefined) continue;+ if (key === "and" || key === "or") {+ const list = Array.isArray(value) ? value : [value];+ const sub = list.map(walk).filter(Boolean);+ if (sub.length) parts.push(`(${sub.join(key === "and" ? " AND " : " OR ")})`);+ continue;+ }+ if (key === "not") {+ const sub = walk(value);+ if (sub) parts.push(`NOT (${sub})`);+ continue;+ }+ const n = nameRef(key);+ for (const [op, operand] of Object.entries(value || {})) {+ if (operand === null || operand === undefined) continue;+ const build = OPS[op];+ if (!build) {+ throw new Error(`util.transform: unsupported operator ${op!==undefined?op:""}`);+ }+ parts.push(build(n, key, operand));+ }+ }+ return parts.join(" AND ");+ };++ return { expression: walk(filter), expressionNames: names, expressionValues: values };+}++function _fmt(d, fmt) {+ // AppSync uses Java's DateTimeFormatter patterns; the handful that appear in+ // practice are supported and anything else falls back to ISO-8601.+ if (!fmt) return d.toISOString();+ const p = (n, w = 2) => String(n).padStart(w, "0");+ return fmt+ .replace(/yyyy/g, d.getUTCFullYear())+ .replace(/MM/g, p(d.getUTCMonth() + 1))+ .replace(/dd/g, p(d.getUTCDate()))+ .replace(/HH/g, p(d.getUTCHours()))+ .replace(/mm/g, p(d.getUTCMinutes()))+ .replace(/ss/g, p(d.getUTCSeconds()))+ .replace(/SSS/g, p(d.getUTCMilliseconds(), 3));+}++const compiled = new Map();++/**+ * Turn a resolver's ES module source into { request, response }.+ *+ * The `@aws-appsync/utils` import is stripped rather than resolved: AppSync+ * injects util/runtime natively, and the npm package is types-only — its+ * functions are undefined at runtime — so importing it would break a resolver+ * that runs correctly on AWS.+ */+function compile(code) {+ const key = crypto.createHash("sha256").update(code).digest("hex");+ const hit = compiled.get(key);+ if (hit) return hit;++ // Imports are stripped because AppSync injects util/runtime natively and the+ // npm package is types-only. The dynamodb sub-module is the exception — its+ // helpers are real — so whatever name it was bound to is declared instead.+ const ddbBindings = [];+ const stripped = code.replace(+ /^\s*import\s+(?:(\*\s*as\s*\w+)|\{([^}]*)\}|(\w+))?\s*(?:from\s*)?['"]([^'"]+)['"]\s*;?\s*$/gm,+ (_m, star, named, deflt, source) => {+ // The root package: util and runtime are injected as globals, but a+ // bundler renames on collision — esbuild emits `import { util as util2 }`+ // when several modules import it — so an alias has to be bound or the+ // resolver dies with "util2 is not defined".+ if (/@aws-appsync\/utils$/.test(source)) {+ if (named) {+ for (const part of named.split(",")) {+ const [orig, alias] = part.split(/\s+as\s+/).map((x) => x.trim());+ if (orig && alias && alias !== orig) {+ ddbBindings.push(`const ${alias} = ${orig};`);+ }+ }+ }+ return "";+ }+ if (!/@aws-appsync\/utils\/dynamodb$/.test(source)) return "";+ if (star) {+ ddbBindings.push(`const ${star.replace(/^\*\s*as\s*/, "")} = __ddb;`);+ } else if (named) {+ for (const part of named.split(",")) {+ const [orig, alias] = part.split(/\s+as\s+/).map((x) => x.trim());+ if (orig) ddbBindings.push(`const ${alias || orig} = __ddb.${orig};`);+ }+ } else if (deflt) {+ ddbBindings.push(`const ${deflt} = __ddb;`);+ }+ return "";+ },+ ).replace(/^\s*export\s+/gm, "");++ const src = `${ddbBindings.join("\n")}+${stripped}+;__exports.request = typeof request === "function" ? request : null;+;__exports.response = typeof response === "function" ? response : null;`;++ const handlers = {};+ // One mutable holder the injected globals close over, so the module is+ // evaluated once and each call just swaps what util/runtime see. Re-running+ // the module per call would throw on any top-level const it declares —+ // including the binding for the dynamodb helpers.+ const state = { appended: [], extensions: [] };+ const sandbox = { __exports: handlers, __ddb: makeDdbHelpers(), console, JSON,+ Math, Date, Object, Array, String, Number, Boolean, RegExp,+ Map, Set, Error, ...makeGlobals(state) };+ vm.createContext(sandbox);+ new vm.Script(src, { filename: "resolver.js" }).runInContext(sandbox);+ const entry = { sandbox, handlers, state };+ compiled.set(key, entry);+ return entry;+}++function run(req) {+ const { code, fn, ctx } = req;+ const entry = compile(code);+ entry.state.appended = [];+ entry.state.extensions = [];+ const appended = entry.state.appended;++ const handler = entry.handlers[fn];+ if (typeof handler !== "function") {+ // A resolver may legitimately omit response(); the caller decides.+ return { status: "missing", appended, stash: ctx.stash ?? {} };+ }+ try {+ const value = handler(ctx) ?? null;+ // A resolver stashes by mutating ctx.stash; that mutation happens in this+ // process, so it has to travel back or a pipeline loses everything a+ // function put there.+ return { status: "ok", value, appended, stash: ctx.stash ?? {},+ extensions: entry.state.extensions };+ } catch (e) {+ if (e instanceof EarlyReturn) {+ return { status: "earlyReturn", value: e.value ?? null, appended,+ skipTo: e.skipTo ?? null, stash: ctx.stash ?? {} };+ }+ if (e instanceof AppSyncError) {+ return { status: "error", error: {+ message: e.message, errorType: e.errorType,+ data: e.data, errorInfo: e.errorInfo }, appended };+ }+ return { status: "error", error: {+ message: String(e && e.message || e), errorType: "InternalError",+ data: null, errorInfo: null }, appended };+ }+}++const rl = readline.createInterface({ input: process.stdin });+rl.on("line", (line) => {+ if (!line.trim()) return;+ let out;+ try {+ out = run(JSON.parse(line));+ } catch (e) {+ out = { status: "error", appended: [], error: {+ message: String(e && e.message || e), errorType: "WorkerError",+ data: null, errorInfo: null } };+ }+ _stdoutWrite(JSON.stringify(out) + "\n");+});+"""+++class AppSyncJsError(Exception):+ """A resolver raised through util.error, or failed to evaluate."""++ def __init__(self, message, error_type="UnknownError", data=None, error_info=None):+ super().__init__(message)+ self.error_type = error_type+ self.data = data+ self.error_info = error_info+++class _Worker:+ """One Node process, shared by every evaluation."""++ def __init__(self):+ self._proc = None+ self._lock = threading.Lock()++ def _ensure(self):+ if self._proc is not None and self._proc.poll() is None:+ return self._proc+ self._proc = subprocess.Popen(+ [_NODE_BINARY, "-e", _WORKER_SCRIPT],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,+ text=True, bufsize=1,+ )+ return self._proc++ def evaluate(self, code, fn, ctx):+ """Run `fn` (request/response) from `code` against `ctx`.++ Returns (status, value, appended_errors, stash, skip_to) where status is+ "ok", "earlyReturn" or "missing". Raises AppSyncJsError on a resolver+ error, and RuntimeError when the worker cannot be used at all.+ """+ payload = json.dumps({"code": code, "fn": fn, "ctx": ctx}) + "\n"+ with self._lock:+ try:+ proc = self._ensure()+ proc.stdin.write(payload)+ proc.stdin.flush()+ line = proc.stdout.readline()+ except (BrokenPipeError, OSError) as exc:+ self._proc = None+ raise RuntimeError(f"APPSYNC_JS worker failed: {exc}") from exc+ except FileNotFoundError as exc: # no node on PATH+ raise RuntimeError(+ "APPSYNC_JS resolvers need Node, which was not found") from exc+ if not line:+ self._proc = None+ raise RuntimeError("APPSYNC_JS worker closed unexpectedly")++ out = json.loads(line)+ if out["status"] == "error":+ err = out["error"]+ raise AppSyncJsError(err["message"], err.get("errorType"),+ err.get("data"), err.get("errorInfo"))+ return (out["status"], out.get("value"), out.get("appended") or [],+ out.get("stash") or {}, out.get("skipTo"))++ def shutdown(self):+ with self._lock:+ if self._proc is not None:+ try:+ self._proc.terminate()+ except Exception:+ pass+ self._proc = None+++_worker = _Worker()+++def evaluate(code, fn, ctx):+ return _worker.evaluate(code, fn, ctx)+++def reset():+ """Drop the worker, so a reset leaves no compiled-module cache behind."""+ _worker.shutdown()+++def available():+ """Whether APPSYNC_JS can be evaluated at all in this environment."""+ try:+ subprocess.run([_NODE_BINARY, "--version"], capture_output=True, timeout=5)+ return True+ except Exception:+ return Falsediff --git a/ministack/services/appsync.py b/ministack/services/appsync.pyindex 278d782f..72dfc2bc 100644--- a/ministack/services/appsync.py+++ b/ministack/services/appsync.py@@ -17,6 +17,7 @@ Wire protocol:Credential scope: appsync"""+import asyncioimport base64import copyimport json@@ -859,6 +860,56 @@ def _flush_api_cache(api_id):return _json(200, {})+def _evaluate_code(body):+ """EvaluateCode — run a handler against a supplied context, without deploying.++ This is how AWS lets a resolver be tested before it exists on an API, and it+ is the operation a CI conformance check calls. Errors come back in the+ response rather than as a fault, because a resolver raising is a normal+ outcome of an evaluation.+ """+ runtime = body.get("runtime") or {}+ if runtime.get("name") != "APPSYNC_JS":+ return error_response_json(+ "BadRequestException",+ f"Unsupported runtime {runtime.get('name')!r}; only APPSYNC_JS is evaluated",+ 400)+ code = body.get("code")+ if not code:+ return error_response_json("BadRequestException", "code is required", 400)++ raw_ctx = body.get("context")+ try:+ ctx = json.loads(raw_ctx) if isinstance(raw_ctx, str) else (raw_ctx or {})+ except (TypeError, ValueError):+ return error_response_json("BadRequestException", "context must be JSON", 400)+ if not isinstance(ctx, dict):+ return error_response_json("BadRequestException", "context must be an object", 400)+ # AppSync's ctx exposes arguments under both names.+ ctx.setdefault("arguments", ctx.get("args") or {})+ ctx.setdefault("args", ctx.get("arguments") or {})+ ctx.setdefault("stash", {})++ fn = body.get("function") or "request"+ from ministack.core import appsync_js+ try:+ status, value, appended, _stash, _skip = appsync_js.evaluate(code, fn, ctx)+ except appsync_js.AppSyncJsError as exc:+ return _json(200, {"error": {"message": str(exc),+ "codeErrors": []},+ "logs": []})+ except RuntimeError as exc:+ return error_response_json("InternalFailureException", str(exc), 500)++ if status == "missing":+ return _json(200, {"error": {+ "message": f"code does not export {fn}()", "codeErrors": []}, "logs": []})+ return _json(200, {+ "evaluationResult": json.dumps(value),+ "logs": [f"appendError: {a.get('message')}" for a in appended],+ })++# ---------------------------------------------------------------------------# Request router# ---------------------------------------------------------------------------@@ -899,6 +950,9 @@ async def handle_request(method, path, headers, body, query_params):else: # GETreturn _list_tags_for_resource(arn)+ if path == "/v1/dataplane-evaluatecode" and method == "POST":+ return _evaluate_code(json.loads(body) if body else {})+# GraphQL data plane: POST /graphql or POST /v1/apis/{apiId}/graphqlif path == "/graphql" and method == "POST":api_key = headers.get("x-api-key", "")@@ -909,7 +963,10 @@ async def handle_request(method, path, headers, body, query_params):if not api_id:return error_response_json("UnauthorizedException", "Valid API key required", 401)data = json.loads(body) if body else {}- return _execute_graphql(api_id, data, request_headers=headers)+ # Resolver execution blocks — an HTTP or Lambda data source may call+ # back into ministack, and a nested request cannot be served while+ # the event loop waits on it. Run it on a worker thread.+ return await asyncio.to_thread(_execute_graphql, api_id, data, headers)if path.startswith("/v1/apis/") and path.endswith("/graphql") and method == "POST":parts = path.split("/")@@ -918,7 +975,10 @@ async def handle_request(method, path, headers, body, query_params):if not _has_sigv4_credentials(headers, query_params):_select_api_region(api_id)data = json.loads(body) if body else {}- return _execute_graphql(api_id, data, request_headers=headers)+ # Resolver execution blocks — an HTTP or Lambda data source may call+ # back into ministack, and a nested request cannot be served while+ # the event loop waits on it. Run it on a worker thread.+ return await asyncio.to_thread(_execute_graphql, api_id, data, headers)m = _PATH_RE.match(path)if not m:@@ -1092,6 +1152,9 @@ def reset():_schemas.clear()_caches.clear()_cache_entries.clear()+ # Drop the JS worker so its compiled-module cache does not outlive a reset.+ from ministack.core import appsync_js+ appsync_js.reset()_tags.clear()@@ -1158,8 +1221,13 @@ def _restore_api_child_store(store, restored, api_regions):import re as _re# Simple GraphQL parser — handles queries/mutations that Amplify generates+# An operation may be anonymous and still declare variables, in which case the+# parenthesis follows the keyword with no space — `mutation($x: T!) { ... }`.+# That is what every SDK and generated client sends, so the whitespace after the+# keyword has to be optional; requiring it made the pattern miss, and the bare+# field fallback then read the whole document as one field named "mutation"._GQL_OP_RE = _re.compile(- r'(?:query|mutation|subscription)\s+(\w+)?\s*(?:\(([^)]*)\))?\s*\{(.*)\}',+ r'\b(?:query|mutation|subscription)\b\s*(\w+)?\s*(?:\(([^)]*)\))?\s*\{(.*)\}',_re.DOTALL,)_GQL_FIELD_RE = _re.compile(r'(\w+)\s*(?:\(([^)]*)\))?\s*(?:\{([^}]*)\})?')@@ -1333,6 +1401,11 @@ def _execute_graphql(api_id, data, request_headers=None):# (HTTP 401), not as a HTTP 200 with identity=null.identity = Noneapi = _apis.get(api_id, {})+ # A Cognito-authenticated API populates identity from the caller's token.+ # Resolvers read identity.sub to decide what the caller may see, so leaving+ # it null makes every permission check fail against an API that works on AWS.+ if api.get("userPoolConfig"):+ identity = _cognito_identity(api, request_headers or {})if api.get("lambdaAuthorizerConfig"):try:identity = _invoke_lambda_authorizer(@@ -1358,18 +1431,42 @@ def _execute_graphql(api_id, data, request_headers=None):results[field_name] = cachedcontinuetry:+ appended = []result = _resolve_field(api_id, resolver, args, sub_fields, variables,field_name=field_name,identity=identity,request_headers=request_headers or {},source={},+ appended_errors=appended,)+ # Resolve the fields of whatever this field returned — the+ # resolvers attached to its own type, with it as ctx.source.+ field_types = _schema_field_types(api_id)+ child_type = field_types.get(+ f"{'Mutation' if is_mutation else 'Query'}.{field_name}")+ if child_type and sub_fields:+ result = _resolve_selection(+ api_id, child_type, result, sub_fields, variables,+ identity, request_headers or {}, errors)results[field_name] = result+ # util.appendError is non-fatal: the field still resolves and+ # the errors ride alongside the data, as AppSync does.+ for a in appended:+ errors.append({"message": a.get("message"),+ "errorType": a.get("errorType"),+ "path": [field_name]})# Only a successful result is cached; caching an error would# make a transient failure stick for the whole ttl.if cache_hit and result is not None:_cache_put(api_id, cache_hit[0], cache_hit[1], result)+ except _AppSyncResolverError as e:+ # util.error and the executor's own refusals carry an errorType,+ # which clients switch on.+ errors.append({"message": str(e), "errorType": e.error_type,+ "path": [field_name],+ **({"data": e.data} if e.data is not None else {})})+ results[field_name] = Noneexcept Exception as e:errors.append({"message": str(e), "path": [field_name]})results[field_name] = None@@ -1493,9 +1590,465 @@ def _find_resolver(api_id, type_name, field_name):return None+# ---------------------------------------------------------------------------+# Resolver execution+#+# Two registries rather than an elif chain, so a new runtime or data source type+# is a new entry rather than a new branch in the middle of the executor.+# ---------------------------------------------------------------------------+++def _ds_none(api_id, data_source, request_obj, ctx):+ """A NONE data source echoes the request's payload — this is how AppSync+ supports resolvers that compute their whole answer locally."""+ if isinstance(request_obj, dict):+ return request_obj.get("payload")+ return None+++def _ds_http(api_id, data_source, request_obj, ctx):+ """An HTTP data source performs the request the resolver described.++ AppSync puts {statusCode, headers, body} into ctx.result, with body as a+ string — a resolver parses it itself, so it must not be decoded here.+ """+ import urllib.error+ import urllib.request++ cfg = data_source.get("httpConfig", {})+ endpoint = (cfg.get("endpoint") or "").rstrip("/")+ req = request_obj if isinstance(request_obj, dict) else {}+ params = req.get("params") or {}+ url = f"{endpoint}{req.get('resourcePath', '/')}"+ body = params.get("body")+ if isinstance(body, str):+ body = body.encode()++ http_req = urllib.request.Request(+ url, data=body, method=req.get("method", "POST"),+ headers={k: str(v) for k, v in (params.get("headers") or {}).items()})+ try:+ with urllib.request.urlopen(http_req, timeout=15) as resp:+ return {"statusCode": resp.status,+ "headers": dict(resp.headers.items()),+ "body": resp.read().decode("utf-8", errors="replace")}+ except urllib.error.HTTPError as exc:+ # A non-2xx is a result the resolver inspects, not a failure — AppSync+ # hands the status back rather than raising.+ return {"statusCode": exc.code, "headers": dict(exc.headers.items()),+ "body": exc.read().decode("utf-8", errors="replace")}+ except Exception as exc:+ raise _AppSyncResolverError(f"HTTP data source request failed: {exc}",+ "HttpDataSourceError") from exc+++def _ds_dynamodb(api_id, data_source, request_obj, ctx):+ """Run the operation the resolver asked for.++ The non-JS path infers an operation from the field name because it has no+ request object to read; here the resolver said what it wanted, so honour it.+ """+ import ministack.services.dynamodb as _ddb++ cfg = data_source.get("dynamodbConfig", {})+ table_name = cfg.get("tableName", "")+ table = _ddb._tables.get(table_name) if table_name else None+ if table is None:+ return None++ req = request_obj if isinstance(request_obj, dict) else {}+ op = req.get("operation", "GetItem")+ # AppSync's DynamoDB helpers emit AttributeValue-shaped keys and values.+ key = _ddb_plain(req.get("key") or {})+ if op == "GetItem":+ return _ddb_get_item(table, table_name, key, None)+ if op in ("PutItem", "UpdateItem"):+ item = {**key, **_ddb_plain(req.get("attributeValues") or {})}+ return (_ddb_put_item if op == "PutItem" else _ddb_update_item)(+ table, table_name, item)+ if op == "DeleteItem":+ return _ddb_delete_item(table, table_name, key)+ if op in ("Scan", "Query"):+ return _ddb_scan(table, table_name, key, None)+ raise _AppSyncResolverError(+ f"DynamoDB operation {op} is not supported yet", "NotImplemented")+++def _ddb_plain(value):+ """Unwrap AttributeValue shapes ({"S": "x"}) into plain JSON.++ A resolver may hand back either form — the @aws-appsync/utils dynamodb+ helpers produce the wrapped one, hand-written request objects usually do+ not — so accept both.+ """+ if isinstance(value, dict):+ if len(value) == 1:+ (tag, inner), = value.items()+ if tag in ("S", "N", "BOOL", "B"):+ return int(inner) if tag == "N" and str(inner).isdigit() else inner+ if tag == "NULL":+ return None+ if tag == "M":+ return {k: _ddb_plain(v) for k, v in inner.items()}+ if tag == "L":+ return [_ddb_plain(v) for v in inner]+ return {k: _ddb_plain(v) for k, v in value.items()}+ return value+++def _ds_lambda(api_id, data_source, request_obj, ctx):+ """Invoke the Lambda with what the resolver's request() returned.++ A JS resolver returning {operation: "Invoke", payload} sends that payload as+ the event, verbatim — AppSync does not wrap it. Wrapping it in the standard+ resolver event means a function expecting its own shape receives something+ else entirely, and the failure surfaces back in the resolver rather than+ where it was caused.++ Without an explicit payload there is nothing the resolver has shaped, so the+ standard resolver event is the right thing to send, which is what a data+ source with no JS code has always received.+ """+ req = request_obj if isinstance(request_obj, dict) else {}+ if isinstance(req, dict) and "payload" in req:+ return _invoke_lambda_with_event(data_source, req["payload"])+ return _resolve_lambda(+ api_id=api_id,+ resolver={"fieldName": (ctx.get("info") or {}).get("fieldName", "")},+ data_source=data_source,+ args=(ctx.get("args") or {}),+ field_name=(ctx.get("info") or {}).get("fieldName", ""),+ identity=ctx.get("identity"),+ request_headers=(ctx.get("request") or {}).get("headers") or {},+ source=ctx.get("source") or {},+ variables=(ctx.get("info") or {}).get("variables") or {},+ )+++def _invoke_lambda_with_event(data_source, event):+ """Invoke a data source's Lambda with an exact event, and unwrap its body."""+ config = data_source.get("lambdaConfig", {})+ func_arn = config.get("lambdaFunctionArn", "")+ if not func_arn:+ raise _AppSyncResolverError(+ "Lambda data source has no lambdaFunctionArn", "InvalidDataSource")++ import ministack.services.lambda_svc as _lambda_svc+ func, func_config, func_name = _lambda_svc._get_func_record_for_ref(func_arn)+ if not func or not func_config:+ raise _AppSyncResolverError(+ f"Lambda function {func_arn} not found", "FunctionNotFound")++ try:+ exec_record = _lambda_svc._execution_record_for_config(func, func_config)+ result = _lambda_svc._execute_function_with_config_scope(exec_record, event)+ except Exception as exc:+ raise _AppSyncResolverError(+ f"Lambda invocation error: {exc}", "LambdaExecutionError") from exc++ if not isinstance(result, dict) or result.get("error"):+ body = result.get("body") if isinstance(result, dict) else None+ msg = body.get("errorMessage") if isinstance(body, dict) else "Lambda execution error"+ raise _AppSyncResolverError(msg or "Lambda execution error", "LambdaExecutionError")++ body = result.get("body")+ if isinstance(body, (str, bytes)):+ try:+ return json.loads(body)+ except (json.JSONDecodeError, ValueError):+ return body+ return body+++# type -> handler. RELATIONAL_DATABASE and AMAZON_OPENSEARCH_SERVICE are+# accepted by the control plane and have no handler yet; a resolver over one+# refuses clearly rather than silently answering a mock.+_DATA_SOURCE_HANDLERS = {+ "NONE": _ds_none,+ "HTTP": _ds_http,+ "AMAZON_DYNAMODB": _ds_dynamodb,+ "AWS_LAMBDA": _ds_lambda,+}+++class _AppSyncResolverError(Exception):+ def __init__(self, message, error_type="UnknownError", data=None, error_info=None):+ super().__init__(message)+ self.error_type = error_type+ self.data = data+ self.error_info = error_info+++_SDL_TYPE_RE = _re.compile(r"\btype\s+(\w+)\s*(?:implements[^{]*)?\{([^}]*)\}", _re.S)+_SDL_FIELD_RE = _re.compile(r"^\s*(\w+)\s*(?:\([^)]*\))?\s*:\s*([\[\]\w!]+)", _re.M)+++def _schema_field_types(api_id):+ """Map "Type.field" -> the field's type name, parsed from the API's SDL.++ Nested resolution needs to know what type a field returns so it can look up+ the resolvers attached to that type. Parsed from the stored schema rather+ than inferred, and cached per API — the alternative is a GraphQL parser,+ which is a dependency for something this small.+ """+ schema = _schemas.get(api_id) or {}+ sdl = schema.get("definition") or ""+ if not sdl:+ return {}+ cached = schema.get("_field_types")+ if cached is not None and schema.get("_field_types_for") == len(sdl):+ return cached++ out = {}+ for type_name, body in _SDL_TYPE_RE.findall(sdl):+ for field, ftype in _SDL_FIELD_RE.findall(body):+ out[f"{type_name}.{field}"] = ftype.strip("[]!")+ schema["_field_types"] = out+ schema["_field_types_for"] = len(sdl)+ return out+++def _resolve_selection(api_id, type_name, value, sub_fields, variables,+ identity, request_headers, errors, depth=0):+ """Run the resolvers attached to a resolved value's own type.++ AppSync resolves a field, then resolves the fields of whatever that field+ returned, passing the parent as ctx.source. Without this only the top-level+ Query/Mutation fields ever run.+ """+ if depth > 10 or not sub_fields or not isinstance(value, dict):+ return value+ field_types = _schema_field_types(api_id)+ type_resolvers = (_resolvers.get(api_id) or {}).get(type_name) or {}+ if not type_resolvers:+ return value++ for sub in sub_fields:+ name = sub if isinstance(sub, str) else sub.get("name")+ nested = None if isinstance(sub, str) else sub.get("sub_fields")+ resolver = type_resolvers.get(name)+ if not resolver:+ continue+ try:+ child = _resolve_field(+ api_id, resolver, {}, nested or [], variables,+ field_name=name, identity=identity,+ request_headers=request_headers, source=value,+ appended_errors=errors, type_name=type_name)+ except _AppSyncResolverError as exc:+ errors.append({"message": str(exc), "errorType": exc.error_type,+ "path": [name]})+ child = None+ child_type = field_types.get(f"{type_name}.{name}")+ if child_type and nested:+ child = _resolve_selection(+ api_id, child_type, child, nested, variables, identity,+ request_headers, errors, depth + 1)+ value[name] = child+ return value+++def _cognito_identity(api, request_headers):+ """Build ctx.identity from a Cognito token on the request.++ The token's claims are read, not verified — ministack has no auth by design+ and its own Cognito issues these tokens. What matters for a resolver is that+ sub, username, groups and the claim set are present and consistent with the+ pool that issued them.+ """+ auth = request_headers.get("authorization") or request_headers.get("Authorization") or ""+ token = auth[7:] if auth[:7].lower() == "bearer " else auth+ parts = token.split(".")+ if len(parts) != 3:+ return None+ try:+ padded = parts[1] + "=" * (-len(parts[1]) % 4)+ claims = json.loads(base64.urlsafe_b64decode(padded))+ except Exception:+ return None+ if not isinstance(claims, dict) or not claims.get("sub"):+ return None+ return {+ "sub": claims.get("sub"),+ "username": claims.get("cognito:username") or claims.get("username") or claims.get("sub"),+ "claims": claims,+ "sourceIp": ["127.0.0.1"],+ "defaultAuthStrategy": (api.get("userPoolConfig") or {}).get("defaultAction", "ALLOW"),+ "groups": claims.get("cognito:groups"),+ "issuer": claims.get("iss"),+ }+++def _api_env(api_id):+ """The API's environment variables, which resolvers read as ctx.env."""+ return (_apis.get(api_id) or {}).get("environmentVariables") or {}+++def _js_ctx(args, identity, source, request_headers, variables, field_name,+ type_name, stash, prev, result=None, api_env=None, error=None):+ """The ctx an APPSYNC_JS resolver sees."""+ ctx = {+ "arguments": args or {},+ "args": args or {},+ "identity": identity,+ "source": source or {},+ "stash": stash if stash is not None else {},+ "prev": {"result": prev},+ "request": {"headers": request_headers or {}},+ "info": {+ "fieldName": field_name,+ "parentTypeName": type_name,+ "variables": variables or {},+ "selectionSetList": [],+ },+ }+ if result is not None:+ ctx["result"] = result+ if api_env:+ ctx["env"] = api_env+ if error is not None:+ # AppSync sets ctx.error when the data source failed, and still runs+ # response() so the resolver can turn it into its own error or a value.+ ctx["error"] = error+ return ctx+++def _js_evaluate(code, fn, ctx, errors):+ """Evaluate one handler, translating a resolver error into the executor's."""+ from ministack.core import appsync_js+ try:+ status, value, appended, stash, skip_to = appsync_js.evaluate(code, fn, ctx)+ except appsync_js.AppSyncJsError as exc:+ raise _AppSyncResolverError(str(exc), exc.error_type, exc.data,+ exc.error_info) from exc+ errors.extend(appended)+ # Carry the mutated stash back into the ctx the caller holds, so the next+ # stage of a pipeline sees what this one stashed.+ if isinstance(ctx.get("stash"), dict) and isinstance(stash, dict):+ ctx["stash"].clear()+ ctx["stash"].update(stash)+ return status, value, skip_to+++def _run_js_stage(api_id, unit, args, identity, source, request_headers,+ variables, field_name, type_name, stash, prev, errors):+ """Run one APPSYNC_JS unit — a resolver or a pipeline function.++ Returns (status, value): "ok" with the response value, or "earlyReturn"+ with the value the caller must return immediately.+ """+ code = unit.get("code") or ""+ ds_name = unit.get("dataSourceName", "")+ data_source = _data_sources.get(api_id, {}).get(ds_name)++ ctx = _js_ctx(args, identity, source, request_headers, variables,+ field_name, type_name, stash, prev, api_env=_api_env(api_id))+ status, request_obj, skip_to = _js_evaluate(code, "request", ctx, errors)+ if status == "earlyReturn":+ # AWS: the data source and this handler's response are skipped, and the+ # value becomes the result the next stage sees. skipTo "END" ends the+ # pipeline instead; anything else continues.+ return ("earlyReturnEnd" if skip_to == "END" else "earlyReturn"), request_obj+ if status == "missing":+ raise _AppSyncResolverError(+ f"{type_name}.{field_name}: APPSYNC_JS code exports no request()",+ "InvalidResolver")++ ds_error = None+ if data_source is None:+ result = None+ else:+ ds_type = data_source.get("type", "NONE")+ handler = _DATA_SOURCE_HANDLERS.get(ds_type)+ if handler is None:+ raise _AppSyncResolverError(+ f"Data source type {ds_type} is not executable yet", "NotImplemented")+ try:+ result = handler(api_id, data_source, request_obj, ctx)+ except _AppSyncResolverError as exc:+ # AppSync hands a data source failure to response() as ctx.error+ # rather than skipping it, so the resolver can map it to its own.+ result = None+ ds_error = {"message": str(exc), "type": exc.error_type}++ ctx = _js_ctx(args, identity, source, request_headers, variables,+ field_name, type_name, stash, prev, result=result,+ api_env=_api_env(api_id), error=ds_error)+ status, value, skip_to = _js_evaluate(code, "response", ctx, errors)+ if status == "earlyReturn":+ return ("earlyReturnEnd" if skip_to == "END" else "earlyReturn"), value+ if status == "missing":+ # AppSync requires response() on a JS resolver, but returning the raw+ # result is more useful than failing the field outright.+ return "ok", result+ return "ok", value+++def _resolve_appsync_js(api_id, resolver, args, variables, field_name,+ type_name, identity, request_headers, source, errors):+ """Execute an APPSYNC_JS resolver — unit, or pipeline with its functions."""+ stash = {}+ if resolver.get("kind") == "PIPELINE":+ # The resolver's own request() is the "before" step; it may stash values+ # or end the whole pipeline.+ ctx = _js_ctx(args, identity, source, request_headers, variables,+ field_name, type_name, stash, None)+ status, _before, _skip = _js_evaluate(+ resolver.get("code") or "", "request", ctx, errors)+ stash = ctx["stash"]+ prev = None+ if status == "earlyReturn":+ # AWS: the pipeline is skipped and the resolver's response handler+ # runs immediately — it is not bypassed, so a resolver that shapes+ # its answer there still gets to.+ prev = _before+ else:+ for fn_id in (resolver.get("pipelineConfig") or {}).get("functions") or []:+ fn = (_functions.get(api_id) or {}).get(fn_id)+ if not fn:+ raise _AppSyncResolverError(+ f"Pipeline function {fn_id} not found", "InvalidResolver")+ status, value = _run_js_stage(+ api_id, fn, args, identity, source, request_headers, variables,+ fn.get("name", field_name), type_name, stash, prev, errors)+ prev = value+ if status == "earlyReturnEnd":+ break++ # The resolver's response handler sees both: ctx.prev.result is the last+ # function's result, and ctx.result is the resolver's own result, which+ # for a pipeline is the same value. AWS provides both, and resolvers use+ # either — a template returning ctx.result got null without this.+ ctx = _js_ctx(args, identity, source, request_headers, variables,+ field_name, type_name, stash, prev, result=prev)+ status, value, _ = _js_evaluate(+ resolver.get("code") or "", "response", ctx, errors)+ return prev if status == "missing" else value++ status, value = _run_js_stage(+ api_id, resolver, args, identity, source, request_headers, variables,+ field_name, type_name, stash, None, errors)+ return value++def _resolve_field(api_id, resolver, args, sub_fields, variables,- field_name=None, identity=None, request_headers=None, source=None):- """Execute a resolver against its data source (DynamoDB or Lambda)."""+ field_name=None, identity=None, request_headers=None, source=None,+ appended_errors=None, type_name=None):+ """Execute a resolver against its data source.++ An APPSYNC_JS resolver runs its own code; anything else keeps the previous+ behaviour of dispatching on the data source type and inferring an operation+ from the field arguments.+ """+ runtime_name = (resolver.get("runtime") or {}).get("name")+ if runtime_name == "APPSYNC_JS" and resolver.get("code"):+ return _resolve_appsync_js(+ api_id, resolver, args or {}, variables or {},+ field_name or resolver.get("fieldName", ""),+ type_name or resolver.get("typeName", "Query"),+ identity, request_headers or {}, source or {},+ appended_errors if appended_errors is not None else [])+ds_name = resolver.get("dataSourceName", "")data_source = _data_sources.get(api_id, {}).get(ds_name)diff --git a/tests/test_appsync.py b/tests/test_appsync.pyindex c81b4fbc..265820db 100644--- a/tests/test_appsync.py+++ b/tests/test_appsync.py@@ -1400,3 +1400,654 @@ def test_appsync_does_not_cache_without_an_api_cache_or_a_ttl(appsync, ddb):apiId=api_id, ttl=60, apiCachingBehavior="PER_RESOLVER_CACHING", type="SMALL")ddb.put_item(TableName=table, Item={"id": {"S": "t1"}, "v": {"S": "third"}})assert _graphql(api_id, key, q)["data"]["getThing"]["v"] == "third"++[email protected](scope="module")+def httpserver_url():+ """A tiny echo server for the HTTP data source test.++ Bound on all interfaces because the ministack under test may be another+ process — or a container — reaching back to the test host.+ """+ import http.server+ import socket+ import threading++ class _Echo(http.server.BaseHTTPRequestHandler):+ def do_POST(self):+ body = self.rfile.read(int(self.headers.get("content-length", 0)))+ self.send_response(200)+ self.send_header("content-type", "application/json")+ self.end_headers()+ self.wfile.write(body or b"{}")++ def log_message(self, *a):+ pass++ srv = http.server.ThreadingHTTPServer(("0.0.0.0", 0), _Echo)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ host = socket.gethostbyname(socket.gethostname())+ try:+ yield f"http://{host}:{srv.server_address[1]}"+ finally:+ srv.shutdown()++def _js_api(appsync, name, ds_type="NONE", **ds_kwargs):+ api = appsync.create_graphql_api(name=name, authenticationType="API_KEY")["graphqlApi"]+ api_id = api["apiId"]+ key = appsync.create_api_key(apiId=api_id)["apiKey"]["id"]+ appsync.create_data_source(apiId=api_id, name="DS", type=ds_type, **ds_kwargs)+ return api_id, key+++def _js_resolver(appsync, api_id, field, code, kind="UNIT", **kw):+ appsync.create_resolver(+ apiId=api_id, typeName="Query", fieldName=field, dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"}, code=code,+ kind=kind, **kw)+++def test_appsync_js_unit_resolver_runs_its_code(appsync):+ """A resolver's request() decides what the data source is asked for, and its+ response() shapes the answer. Neither ran before: the executor dispatched on+ data source type and inferred an operation from the field arguments, so the+ resolver's own logic never affected the result."""+ api_id, key = _js_api(appsync, "qa-js-unit")+ _js_resolver(appsync, api_id, "ping", """+ export function request(ctx) {+ return { payload: { pong: true, echoed: ctx.args.name } }+ }+ export function response(ctx) {+ return { ...ctx.result, seen: true }+ }+ """)+ out = _graphql(api_id, key, '{ ping(name: "hi") }')+ assert out["data"]["ping"] == {"pong": True, "echoed": "hi", "seen": True}+++def test_appsync_js_resolver_error_becomes_a_graphql_error(appsync):+ """util.error must surface as a GraphQL error with its errorType, not a+ 500 and not a silent null."""+ api_id, key = _js_api(appsync, "qa-js-error")+ _js_resolver(appsync, api_id, "ping", """+ import { util } from '@aws-appsync/utils'+ export function request(ctx) { util.error('not allowed', 'Forbidden') }+ """)+ out = _graphql(api_id, key, '{ ping }')+ assert out["data"]["ping"] is None+ assert out["errors"][0]["message"] == "not allowed"+ assert out["errors"][0].get("errorType") == "Forbidden"+++def test_appsync_js_early_return_skips_the_data_source(appsync):+ """runtime.earlyReturn ends the resolver before the data source is touched."""+ api_id, key = _js_api(appsync, "qa-js-early")+ _js_resolver(appsync, api_id, "ping", """+ import { runtime } from '@aws-appsync/utils'+ export function request(ctx) { runtime.earlyReturn({ short: true }) }+ export function response(ctx) { return { neverReached: true } }+ """)+ assert _graphql(api_id, key, '{ ping }')["data"]["ping"] == {"short": True}+++def test_appsync_js_http_data_source_is_called(appsync, httpserver_url):+ """HTTP is one of the four data source types the control plane accepts and+ the executor ignored — a resolver over one answered the mock."""+ api_id, key = _js_api(appsync, "qa-js-http", ds_type="HTTP",+ httpConfig={"endpoint": httpserver_url})+ _js_resolver(appsync, api_id, "ping", """+ export function request(ctx) {+ return { method: 'POST', resourcePath: '/echo',+ params: { headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ sent: ctx.args.name }) } }+ }+ export function response(ctx) {+ return JSON.parse(ctx.result.body)+ }+ """)+ out = _graphql(api_id, key, '{ ping(name: "over-http") }')+ assert out["data"]["ping"]["sent"] == "over-http"+++def test_appsync_js_pipeline_threads_stash_and_prev(appsync):+ """A pipeline runs its functions in order, with ctx.stash carried across and+ ctx.prev.result holding the previous function's value."""+ api_id, key = _js_api(appsync, "qa-js-pipeline")+ fn1 = appsync.create_function(+ apiId=api_id, name="one", dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ export function request(ctx) { ctx.stash.step = 1; return { payload: { a: 1 } } }+ export function response(ctx) { return ctx.result }+ """)["functionConfiguration"]["functionId"]+ fn2 = appsync.create_function(+ apiId=api_id, name="two", dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ export function request(ctx) {+ return { payload: { a: ctx.prev.result.a + 1, step: ctx.stash.step } }+ }+ export function response(ctx) { return ctx.result }+ """)["functionConfiguration"]["functionId"]++ appsync.create_resolver(+ apiId=api_id, typeName="Query", fieldName="chain", kind="PIPELINE",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ pipelineConfig={"functions": [fn1, fn2]},+ code="""+ export function request(ctx) { return {} }+ export function response(ctx) { return ctx.prev.result }+ """)+ out = _graphql(api_id, key, '{ chain }')+ assert out["data"]["chain"] == {"a": 2, "step": 1}+++def test_appsync_non_js_resolver_keeps_its_existing_behaviour(appsync, ddb):+ """A resolver with no APPSYNC_JS code still resolves the way it did before,+ so adding execution does not change any API that worked already."""+ api_id, key, table = _cache_ds_api(appsync, ddb, "qa-js-legacy")+ appsync.create_resolver(+ apiId=api_id, typeName="Query", fieldName="getThing", dataSourceName="Things")+ ddb.put_item(TableName=table, Item={"id": {"S": "t1"}, "v": {"S": "legacy"}})+ out = _graphql(api_id, key, '{ getThing(id: "t1") { id v } }')+ assert out["data"]["getThing"]["v"] == "legacy"+++_NESTED_SDL = """+type Thing { id: ID! label: String owner: String }+type Query { getThing(id: ID!): Thing }+schema { query: Query }+"""+++def test_appsync_js_nested_type_resolvers_run(appsync):+ """A resolver on a nested type must run, with ctx.source set to the parent.++ Only top-level Query/Mutation fields resolved before, so a field like+ Thing.label was simply absent from the response. Most of a real API's+ resolvers live on nested types — ctx.source is read 371 times across this+ API's resolvers — so without this the graph barely executes.+ """+ api_id, key = _js_api(appsync, "qa-js-nested")+ appsync.start_schema_creation(apiId=api_id, definition=_NESTED_SDL.encode())+ _js_resolver(appsync, api_id, "getThing", """+ export function request(ctx) { return { payload: { id: ctx.args.id } } }+ export function response(ctx) { return ctx.result }+ """)+ appsync.create_resolver(+ apiId=api_id, typeName="Thing", fieldName="label", dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ export function request(ctx) {+ return { payload: 'label-for-' + ctx.source.id }+ }+ export function response(ctx) { return ctx.result }+ """)++ out = _graphql(api_id, key, '{ getThing(id: "t1") { id label } }')+ assert out["data"]["getThing"]["id"] == "t1"+ assert out["data"]["getThing"]["label"] == "label-for-t1", \+ "the nested resolver must run with ctx.source from its parent"+++def test_appsync_js_identity_comes_from_a_cognito_token(appsync, cognito_idp):+ """ctx.identity must be populated from a verified Cognito token.++ identity is read 617 times across this API's resolvers and identity.sub 309+ times; it was only ever populated by a Lambda authorizer, so a Cognito API+ saw null and every permission check failed.+ """+ pool = cognito_idp.create_user_pool(PoolName="qa-js-identity-pool")["UserPool"]+ client = cognito_idp.create_user_pool_client(+ UserPoolId=pool["Id"], ClientName="app", ExplicitAuthFlows=["ADMIN_NO_SRP_AUTH"],+ )["UserPoolClient"]+ username = "[email protected]"+ cognito_idp.admin_create_user(UserPoolId=pool["Id"], Username=username,+ MessageAction="SUPPRESS")+ cognito_idp.admin_set_user_password(UserPoolId=pool["Id"], Username=username,+ Password="TestPass123!", Permanent=True)+ token = cognito_idp.admin_initiate_auth(+ UserPoolId=pool["Id"], ClientId=client["ClientId"],+ AuthFlow="ADMIN_USER_PASSWORD_AUTH",+ AuthParameters={"USERNAME": username, "PASSWORD": "TestPass123!"},+ )["AuthenticationResult"]["IdToken"]++ api = appsync.create_graphql_api(+ name="qa-js-identity", authenticationType="AMAZON_COGNITO_USER_POOLS",+ userPoolConfig={"userPoolId": pool["Id"], "awsRegion": "us-east-1",+ "defaultAction": "ALLOW"},+ )["graphqlApi"]+ api_id = api["apiId"]+ appsync.create_data_source(apiId=api_id, name="DS", type="NONE")+ _js_resolver(appsync, api_id, "whoami", """+ export function request(ctx) { return { payload: { sub: ctx.identity.sub } } }+ export function response(ctx) { return ctx.result }+ """)++ import requests as _rq+ out = _rq.post(f"{_ENDPOINT}/v1/apis/{api_id}/graphql",+ headers={"Authorization": f"Bearer {token}",+ "content-type": "application/json"},+ json={"query": "{ whoami }"}, timeout=15).json()+ assert out["data"]["whoami"]["sub"], "ctx.identity.sub must be populated"+++def test_appsync_js_ctx_error_is_visible_to_response(appsync):+ """response() sees a data source failure in ctx.error rather than being+ skipped, which is how a resolver turns an upstream error into its own."""+ api_id, key = _js_api(appsync, "qa-js-ctxerror", ds_type="HTTP",+ httpConfig={"endpoint": "http://127.0.0.1:1"})+ _js_resolver(appsync, api_id, "ping", """+ export function request(ctx) { return { method: 'GET', resourcePath: '/' } }+ export function response(ctx) {+ if (ctx.error) { return { failed: true, type: ctx.error.type } }+ return ctx.result+ }+ """)+ out = _graphql(api_id, key, '{ ping }')+ assert out["data"]["ping"]["failed"] is True+++def test_appsync_js_ctx_env_exposes_api_environment_variables(appsync):+ """ctx.env carries the API's environment variables, which is how a resolver+ reads a secret it must not hold in code."""+ api_id, key = _js_api(appsync, "qa-js-env")+ appsync.put_graphql_api_environment_variables(+ apiId=api_id, environmentVariables={"SOME_SECRET": "s3cr3t"})+ _js_resolver(appsync, api_id, "ping", """+ export function request(ctx) { return { payload: { seen: ctx.env.SOME_SECRET } } }+ export function response(ctx) { return ctx.result }+ """)+ assert _graphql(api_id, key, '{ ping }')["data"]["ping"]["seen"] == "s3cr3t"+++def test_appsync_js_dynamodb_helper_module_is_available(appsync, ddb):+ """`@aws-appsync/utils/dynamodb` must resolve, not vanish with the import.++ The worker strips imports because AppSync injects util and runtime natively+ and the npm package is types-only — but that sub-module is not types-only:+ ddb.get/put/update/remove build real request objects. Stripping its import+ left the binding undefined and the resolver died with "ddb is not defined".+ """+ api_id, key, table = _cache_ds_api(appsync, ddb, "qa-js-ddbutils")+ ddb.put_item(TableName=table, Item={"id": {"S": "d1"}, "v": {"S": "found"}})+ appsync.create_resolver(+ apiId=api_id, typeName="Query", fieldName="getThing", dataSourceName="Things",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ import * as ddb from '@aws-appsync/utils/dynamodb'+ export function request(ctx) { return ddb.get({ key: { id: ctx.args.id } }) }+ export function response(ctx) { return ctx.result }+ """)+ out = _graphql(api_id, key, '{ getThing(id: "d1") { id v } }')+ assert out["data"]["getThing"]["v"] == "found"+++def test_appsync_js_named_dynamodb_helper_import_also_works(appsync, ddb):+ """The named form — import { get } from '...' — must bind too."""+ api_id, key, table = _cache_ds_api(appsync, ddb, "qa-js-ddbnamed")+ ddb.put_item(TableName=table, Item={"id": {"S": "d2"}, "v": {"S": "named"}})+ appsync.create_resolver(+ apiId=api_id, typeName="Query", fieldName="getThing", dataSourceName="Things",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ import { get } from '@aws-appsync/utils/dynamodb'+ export function request(ctx) { return get({ key: { id: ctx.args.id } }) }+ export function response(ctx) { return ctx.result }+ """)+ assert _graphql(api_id, key, '{ getThing(id: "d2") { id v } }')["data"]["getThing"]["v"] == "named"+++def test_appsync_evaluate_code_runs_a_handler(appsync):+ """EvaluateCode is how AWS lets you test a resolver without deploying it.++ ministack has an evaluator now, so it can answer the same operation — which+ is what makes a resolver testable locally the way it is against AWS.+ """+ out = appsync.evaluate_code(+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ export function request(ctx) { return { payload: { got: ctx.arguments.n } } }+ export function response(ctx) { return ctx.result }+ """,+ context=json.dumps({"arguments": {"n": 7}}),+ function="request",+ )+ assert json.loads(out["evaluationResult"]) == {"payload": {"got": 7}}+++def test_appsync_evaluate_code_reports_a_resolver_error(appsync):+ """A resolver that raises must come back as an error, not a crash."""+ out = appsync.evaluate_code(+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ import { util } from '@aws-appsync/utils'+ export function request(ctx) { util.error('nope', 'Forbidden') }+ """,+ context=json.dumps({"arguments": {}}),+ function="request",+ )+ assert out["error"]["message"] == "nope"+++def test_appsync_js_util_surface_matches_what_appsync_provides(appsync):+ """The util namespaces a resolver can reach.++ ministack provided 8 of the 21 members AWS declares, and three of those were+ wrong rather than missing: autoUlid returned a UUID, util.dynamodb had only+ a pass-through toDynamoDB, and util.transform was an empty object, so a call+ failed as "not a function" well away from the cause.+ """+ api_id, key = _js_api(appsync, "qa-js-utils")+ _js_resolver(appsync, api_id, "ping", """+ import { util } from '@aws-appsync/utils'+ export function request(ctx) {+ return { payload: {+ b64: util.base64Decode(util.base64Encode('hello')),+ url: util.urlDecode(util.urlEncode('a b&c')),+ matches: util.matches('^a.*z$', 'abcz'),+ ulid: util.autoUlid().length,+ ksuid: util.autoKsuid().length,+ round: util.math.roundNum(2.6),+ ddb: util.dynamodb.toDynamoDB({ a: 1, b: true }),+ iso: util.time.epochMilliSecondsToISO8601(0),+ } }+ }+ export function response(ctx) { return ctx.result }+ """)+ got = _graphql(api_id, key, '{ ping }')["data"]["ping"]+ assert got["b64"] == "hello"+ assert got["url"] == "a b&c"+ assert got["matches"] is True+ assert got["ulid"] == 26, "a ULID is 26 characters, not a UUID"+ assert got["ksuid"] == 27+ assert got["round"] == 3+ assert got["ddb"] == {"M": {"a": {"N": "1"}, "b": {"BOOL": True}}}+ assert got["iso"] == "1970-01-01T00:00:00.000Z"+++def test_appsync_js_unimplemented_util_refuses_by_name(appsync):+ """What is not implemented says so, rather than returning undefined and+ failing somewhere later with no trace of the cause."""+ api_id, key = _js_api(appsync, "qa-js-utils-gap")+ _js_resolver(appsync, api_id, "ping", """+ import { util } from '@aws-appsync/utils'+ export function request(ctx) { return util.xml.toMap('<a/>') }+ """)+ out = _graphql(api_id, key, '{ ping }')+ assert "xml.toMap" in out["errors"][0]["message"]+++def test_appsync_js_transform_builds_a_dynamodb_filter_expression(appsync):+ """util.transform.toDynamoDBFilterExpression builds a real expression.++ DynamoDB is the data source most AppSync APIs use, and this is how a+ resolver turns a GraphQL filter argument into one — so it is the transform+ function that actually gets called. It returned nothing before, because+ util.transform was an empty object.+ """+ api_id, key = _js_api(appsync, "qa-js-transform")+ _js_resolver(appsync, api_id, "ping", """+ import { util } from '@aws-appsync/utils'+ export function request(ctx) {+ return { payload: util.transform.toDynamoDBFilterExpression({+ title: { beginsWith: 'foo' },+ views: { gt: 10 },+ }) }+ }+ export function response(ctx) { return ctx.result }+ """)+ got = _graphql(api_id, key, '{ ping }')["data"]["ping"]+ assert "begins_with" in got["expression"]+ assert got["expressionNames"]["#title"] == "title"+ assert got["expressionValues"][":title_beginsWith"] == {"S": "foo"}+ assert got["expressionValues"][":views_gt"] == {"N": "10"}+ # Two conditions on one filter are ANDed, as AppSync does.+ assert " AND " in got["expression"]+++def test_appsync_js_transform_handles_or_not_and_the_operator_set(appsync):+ """The operators AppSync documents, and the and/or/not nesting."""+ api_id, key = _js_api(appsync, "qa-js-transform-ops")+ _js_resolver(appsync, api_id, "ping", """+ import { util } from '@aws-appsync/utils'+ export function request(ctx) {+ return { payload: {+ ops: util.transform.toDynamoDBFilterExpression({+ a: { eq: 1 }, b: { ne: 2 }, c: { between: [1, 5] },+ d: { in: ['x', 'y'] }, e: { contains: 'z' },+ f: { attributeExists: true },+ }),+ nested: util.transform.toDynamoDBFilterExpression({+ or: [{ p: { eq: 1 } }, { not: { q: { eq: 2 } } }],+ }),+ } }+ }+ export function response(ctx) { return ctx.result }+ """)+ got = _graphql(api_id, key, '{ ping }')["data"]["ping"]+ e = got["ops"]["expression"]+ assert "#a = :a_eq" in e and "#b <> :b_ne" in e+ assert "#c BETWEEN :c_between_0 AND :c_between_1" in e+ assert "#d IN (:d_in_0,:d_in_1)" in e+ assert "contains(#e, :e_contains)" in e+ assert "attribute_exists(#f)" in e+ n = got["nested"]["expression"]+ assert " OR " in n and "NOT" in n+++def test_appsync_anonymous_operation_with_variables_is_parsed(appsync):+ """`mutation($x: T!) { ... }` — no space before the parenthesis.++ This is the form every SDK and generated client sends. The operation regex+ required whitespace after the keyword, so it did not match, and the fallback+ parsed the whole document as a single field literally named "mutation" —+ answering {"data": {"mutation": null}} with no error to say why.+ """+ api_id, key = _js_api(appsync, "qa-anon-op")+ _js_resolver(appsync, api_id, "echo", """+ export function request(ctx) { return { payload: { got: ctx.args.n } } }+ export function response(ctx) { return ctx.result }+ """)++ import requests as _rq+ for query in (+ 'query($n: Int) { echo(n: $n) }', # anonymous, variables, no space+ 'query ($n: Int) { echo(n: $n) }', # anonymous, with a space+ 'query Named($n: Int) { echo(n: $n) }', # named+ # The shape that actually failed: a non-null variable type, which is+ # what an input object argument always is.+ 'query($n: Int!) { echo(n: $n) }',+ ):+ r = _rq.post(f"{_ENDPOINT}/v1/apis/{api_id}/graphql",+ headers={"x-api-key": key, "content-type": "application/json"},+ json={"query": query, "variables": {"n": 7}}, timeout=15).json()+ assert "echo" in (r.get("data") or {}), f"{query!r} parsed as {r}"+ assert r["data"]["echo"] == {"got": 7}, f"{query!r} gave {r}"+++def test_appsync_js_aliased_utils_import_binds(appsync):+ """`import { util as util2 }` — what a bundler emits on a name collision.++ esbuild renames when several bundled modules import util, so 93 of this+ API's 191 resolvers arrive as util2 or util3. Stripping the import left the+ alias undefined and the resolver died with "util2 is not defined".+ """+ api_id, key = _js_api(appsync, "qa-js-alias")+ _js_resolver(appsync, api_id, "ping", """+ import { util as util2 } from '@aws-appsync/utils'+ import { runtime as runtime2 } from '@aws-appsync/utils'+ export function request(ctx) {+ return { payload: { id: util2.autoId().length, hasRuntime: typeof runtime2.earlyReturn } }+ }+ export function response(ctx) { return ctx.result }+ """)+ got = _graphql(api_id, key, '{ ping }')["data"]["ping"]+ assert got["id"] == 36+ assert got["hasRuntime"] == "function"+def test_appsync_js_function_early_return_continues_the_pipeline(appsync):+ """earlyReturn in a FUNCTION skips its data source and response — and the+ pipeline continues to the next function.+ AWS: "the data source and response handler are skipped, and the next+ function request handler (or the pipeline resolver response handler if this+ was the last AWS AppSync function) is called."+ Ending the whole pipeline instead means every later function is silently+ skipped. A real resolver that guards its first function this way then+ returns null with no error, because the function that would have set the+ result never ran.+ """+ api_id, key = _js_api(appsync, "qa-early-fn")+ first = appsync.create_function(+ apiId=api_id, name="skipper", dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ import { runtime } from '@aws-appsync/utils'+ export function request(ctx) { runtime.earlyReturn() }+ export function response(ctx) { return 'RESPONSE_SHOULD_BE_SKIPPED' }+ """)["functionConfiguration"]["functionId"]+ second = appsync.create_function(+ apiId=api_id, name="setter", dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ export function request(ctx) { ctx.stash.result = 'SECOND_RAN'; return { payload: 1 } }+ export function response(ctx) { return ctx.result }+ """)["functionConfiguration"]["functionId"]+ appsync.create_resolver(+ apiId=api_id, typeName="Query", fieldName="chain", kind="PIPELINE",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ pipelineConfig={"functions": [first, second]},+ code="""+ export function request(ctx) { return {} }+ export function response(ctx) { return ctx.stash.result }+ """)+ out = _graphql(api_id, key, '{ chain }')+ assert out["data"]["chain"] == "SECOND_RAN", \+ f"a function's earlyReturn must not end the pipeline: {out}"+def test_appsync_js_resolver_early_return_still_runs_the_response(appsync):+ """earlyReturn in the pipeline RESOLVER's request skips the functions, and+ the resolver's own response handler still runs.+ AWS: "the pipeline execution is skipped, and the pipeline resolver response+ handler is called immediately."+ """+ api_id, key = _js_api(appsync, "qa-early-resolver")+ fn = appsync.create_function(+ apiId=api_id, name="never", dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ export function request(ctx) { ctx.stash.ran = true; return { payload: 1 } }+ export function response(ctx) { return ctx.result }+ """)["functionConfiguration"]["functionId"]+ appsync.create_resolver(+ apiId=api_id, typeName="Query", fieldName="chain", kind="PIPELINE",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ pipelineConfig={"functions": [fn]},+ code="""+ import { runtime } from '@aws-appsync/utils'+ export function request(ctx) { runtime.earlyReturn({ short: true }) }+ export function response(ctx) {+ return ctx.stash.ran ? 'FUNCTIONS_RAN' : 'RESPONSE_RAN'+ }+ """)+ out = _graphql(api_id, key, '{ chain }')+ assert out["data"]["chain"] == "RESPONSE_RAN", \+ f"the resolver's response must still run, and the functions must not: {out}"+def test_appsync_js_early_return_skip_to_end(appsync):+ """skipTo: 'END' from a function skips the rest of the pipeline and goes+ straight to the resolver's response handler."""+ api_id, key = _js_api(appsync, "qa-early-skipend")+ first = appsync.create_function(+ apiId=api_id, name="ender", dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ import { runtime } from '@aws-appsync/utils'+ export function request(ctx) { runtime.earlyReturn('ENDED', { skipTo: 'END' }) }+ export function response(ctx) { return ctx.result }+ """)["functionConfiguration"]["functionId"]+ second = appsync.create_function(+ apiId=api_id, name="shouldNotRun", dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ export function request(ctx) { ctx.stash.ran = true; return { payload: 1 } }+ export function response(ctx) { return ctx.result }+ """)["functionConfiguration"]["functionId"]+ appsync.create_resolver(+ apiId=api_id, typeName="Query", fieldName="chain", kind="PIPELINE",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ pipelineConfig={"functions": [first, second]},+ code="""+ export function request(ctx) { return {} }+ export function response(ctx) {+ return ctx.stash.ran ? 'SECOND_RAN' : String(ctx.prev.result)+ }+ """)+ out = _graphql(api_id, key, '{ chain }')+ assert out["data"]["chain"] == "ENDED", f"skipTo END must stop the pipeline: {out}"+def test_appsync_js_pipeline_response_sees_ctx_result(appsync):+ """A pipeline resolver's response handler gets ctx.result as well as+ ctx.prev.result — AWS documents result as "available only to response+ handlers", and real resolvers return ctx.result from the after step."""+ api_id, key = _js_api(appsync, "qa-pipe-ctxresult")+ fn = appsync.create_function(+ apiId=api_id, name="produce", dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ export function request(ctx) { return { payload: { v: 'FROM_FUNCTION' } } }+ export function response(ctx) { return ctx.result }+ """)["functionConfiguration"]["functionId"]+ appsync.create_resolver(+ apiId=api_id, typeName="Query", fieldName="chain", kind="PIPELINE",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ pipelineConfig={"functions": [fn]},+ code="""+ export function request(ctx) { return {} }+ export function response(ctx) { return ctx.result.v }+ """)+ assert _graphql(api_id, key, '{ chain }')["data"]["chain"] == "FROM_FUNCTION"+def test_appsync_js_lambda_datasource_receives_the_payload_verbatim(appsync, lam):+ """A JS resolver returning {operation: 'Invoke', payload} sends exactly that+ payload as the Lambda event.+ It was being wrapped in the standard resolver event instead, so a function+ expecting its own shape — say {text: [...]} — received+ {arguments: {text: [...]}, info: {...}} and returned something the resolver+ could not use. The failure surfaces inside the resolver, far from the cause.+ """+ import io+ import zipfile+ def _zip(src):+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as z:+ z.writestr("index.py", src)+ return buf.getvalue()+ code = _zip(+ "def handler(e, c):\n"+ " # Echo the event back so the test can see exactly what arrived.\n"+ " return e\n"+ )+ fn = "qa-appsync-payload-fn"+ lam.create_function(+ FunctionName=fn, Runtime="python3.12",+ Role="arn:aws:iam::000000000000:role/r", Handler="index.handler",+ Code={"ZipFile": code},+ )+ api = appsync.create_graphql_api(name="qa-lambda-payload",+ authenticationType="API_KEY")["graphqlApi"]+ api_id = api["apiId"]+ key = appsync.create_api_key(apiId=api_id)["apiKey"]["id"]+ appsync.create_data_source(+ apiId=api_id, name="DS", type="AWS_LAMBDA",+ lambdaConfig={"lambdaFunctionArn":+ f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"},+ )+ appsync.create_resolver(+ apiId=api_id, typeName="Query", fieldName="echo", dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ export function request(ctx) {+ return { operation: 'Invoke', payload: { text: ['a', 'b'] } }+ }+ export function response(ctx) { return ctx.result }+ """,+ )+ got = _graphql(api_id, key, '{ echo }')["data"]["echo"]+ assert got == {"text": ["a", "b"]}, \+ f"the payload must arrive verbatim, not wrapped in a resolver event: {got}"