Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(appsync): schema creation, pipeline functions, updates and the API cache (#1559)

Jacob Schooleyf9a0f36ce14b
diff --git a/ministack/services/appsync.py b/ministack/services/appsync.py
index ae1823ea..278d782f 100644
--- a/ministack/services/appsync.py
+++ b/ministack/services/appsync.py
@@ -17,6 +17,7 @@ Wire protocol:
Credential scope: appsync
"""
+import base64
import copy
import json
import logging
@@ -50,6 +51,13 @@ _api_keys = AccountRegionScopedDict() # apiId -> {keyId -> key record}
_data_sources = AccountRegionScopedDict() # apiId -> {name -> data source record}
_resolvers = AccountRegionScopedDict() # apiId -> {typeName -> {fieldName -> resolver record}}
_types = AccountRegionScopedDict() # apiId -> {typeName -> type record}
+_functions = AccountRegionScopedDict() # apiId -> {functionId -> function record}
+_schemas = AccountRegionScopedDict() # apiId -> {"definition": str, "status": str, "details": str}
+_caches = AccountRegionScopedDict() # apiId -> ApiCache record
+# apiId -> {cache key -> (expires_at, value)}. Separate from _caches, which holds
+# the ApiCache configuration; this is the cached data itself. Not persisted: a
+# restart is a cold cache, as replacing the cache instance would be on AWS.
+_cache_entries: dict = {}
_tags = AccountScopedDict() # resource_arn -> {key: value}
# ---------------------------------------------------------------------------
@@ -167,6 +175,14 @@ def _create_graphql_api(body):
},
"additionalAuthenticationProviders": additional_auth,
"xrayEnabled": xray,
+ # Fields with server-side defaults. Omitting them makes a Terraform plan
+ # see api_type and visibility as newly set, and both force replacement —
+ # so every plan wanted to recreate the API and all of its children.
+ "apiType": body.get("apiType", "GRAPHQL"),
+ "visibility": body.get("visibility", "GLOBAL"),
+ "introspectionConfig": body.get("introspectionConfig", "ENABLED"),
+ "queryDepthLimit": body.get("queryDepthLimit", 0),
+ "resolverCountLimit": body.get("resolverCountLimit", 0),
"wafWebAclArn": body.get("wafWebAclArn"),
"createdAt": now,
"lastUpdatedAt": now,
@@ -189,18 +205,25 @@ def _create_graphql_api(body):
if tags:
_tags[arn] = tags
- return _json(200, {"graphqlApi": record})
+ return _json(200, {"graphqlApi": _api_with_tags(record)})
+
+
+def _api_with_tags(api):
+ """AWS returns tags on the GraphqlApi itself, which is where the Terraform
+ provider reads them. Merged in on read rather than copied onto the record so
+ TagResource and UntagResource stay reflected without a second write."""
+ return {**api, "tags": dict(_tags.get(api.get("arn", ""), {}))}
def _get_graphql_api(api_id):
api = _apis.get(api_id)
if not api:
return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
- return _json(200, {"graphqlApi": api})
+ return _json(200, {"graphqlApi": _api_with_tags(api)})
def _list_graphql_apis(query_params):
- apis = list(_apis.values())
+ apis = [_api_with_tags(a) for a in _apis.values()]
return _json(200, {"graphqlApis": apis})
@@ -240,6 +263,10 @@ def _delete_graphql_api(api_id):
_data_sources.pop(api_id, None)
_resolvers.pop(api_id, None)
_types.pop(api_id, None)
+ _functions.pop(api_id, None)
+ _schemas.pop(api_id, None)
+ _caches.pop(api_id, None)
+ _cache_entries.pop(api_id, None)
_tags.pop(arn, None)
return _json(200, {})
@@ -498,6 +525,233 @@ def _list_types(api_id, query_params):
# Tags
# ---------------------------------------------------------------------------
+# ---------------------------------------------------------------------------
+# Schema
+# ---------------------------------------------------------------------------
+
+def _start_schema_creation(api_id, body):
+ """StartSchemaCreation.
+
+ AWS accepts the SDL, validates and compiles it asynchronously, and the caller
+ polls GetSchemaCreationStatus until SUCCESS or FAILED. The definition arrives
+ base64-encoded because it is a blob member.
+
+ The SDL is stored verbatim rather than parsed: nothing here consumes a type
+ graph — resolvers are addressed by type and field name, and _execute_graphql
+ resolves fields against the registered resolvers — so parsing would add a
+ dependency and a new failure mode without changing any behaviour. Compilation
+ is therefore synchronous and always succeeds, and the status is reported the
+ way a completed creation reports it.
+ """
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ definition = body.get("definition", "")
+ if not definition:
+ return error_response_json("BadRequestException", "definition is required", 400)
+
+ if isinstance(definition, str):
+ try:
+ definition = base64.b64decode(definition).decode("utf-8")
+ except Exception:
+ # Already-plain SDL: accept it rather than refusing a readable schema.
+ pass
+ elif isinstance(definition, (bytes, bytearray)):
+ definition = definition.decode("utf-8", "replace")
+
+ _schemas[api_id] = {
+ "definition": definition,
+ "status": "SUCCESS",
+ "details": "Schema creation successful.",
+ }
+ logger.info("AppSync: schema created for %s (%d bytes)", api_id, len(definition))
+ return _json(200, {"status": "PROCESSING"})
+
+
+def _get_schema_creation_status(api_id):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ schema = _schemas.get(api_id)
+ if not schema:
+ return _json(200, {"status": "NOT_APPLICABLE", "details": ""})
+ return _json(200, {"status": schema["status"], "details": schema["details"]})
+
+
+def _get_introspection_schema(api_id, query_params):
+ """GetIntrospectionSchema — the response body is the schema blob itself."""
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ schema = _schemas.get(api_id)
+ if not schema:
+ return error_response_json("GraphQLSchemaException", "No schema found for this API", 404)
+
+ fmt = (query_params.get("format") or ["SDL"])
+ fmt = (fmt[0] if isinstance(fmt, list) else fmt or "SDL").upper()
+ if fmt not in ("SDL", "JSON"):
+ return error_response_json("BadRequestException", f"Unsupported format: {fmt}", 400)
+ if fmt == "JSON":
+ # A JSON introspection result requires a parsed type graph, which is
+ # deliberately not built here; SDL is what tooling against MiniStack uses.
+ return error_response_json(
+ "BadRequestException",
+ "JSON introspection is not supported by MiniStack; request format=SDL.", 400)
+
+ return 200, {"Content-Type": "application/octet-stream"}, schema["definition"].encode("utf-8")
+
+
+def _is_ok(response):
+ """True when a handler tuple carries a 2xx status."""
+ return isinstance(response, tuple) and 200 <= response[0] < 300
+
+
+def _update_data_source(api_id, name, body):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ if name not in _data_sources.get(api_id, {}):
+ return error_response_json("NotFoundException", f"Data source {name} not found", 404)
+ created_at = _data_sources[api_id][name].get("createdAt")
+ body = dict(body)
+ body["name"] = name
+ response = _create_data_source(api_id, body)
+ if not _is_ok(response):
+ return response
+ # AWS keeps the original creation time across an update, so restore it on the
+ # stored record and answer with that rather than the freshly stamped one.
+ record = _data_sources[api_id][name]
+ if created_at:
+ record["createdAt"] = created_at
+ return _json(200, {"dataSource": record})
+
+
+def _update_resolver(api_id, type_name, field_name, body):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ if field_name not in _resolvers.get(api_id, {}).get(type_name, {}):
+ return error_response_json(
+ "NotFoundException", f"Resolver {type_name}.{field_name} not found", 404)
+ created_at = _resolvers[api_id][type_name][field_name].get("createdAt")
+ body = dict(body)
+ body["fieldName"] = field_name
+ response = _create_resolver(api_id, type_name, body)
+ if not _is_ok(response):
+ return response
+ record = _resolvers[api_id][type_name][field_name]
+ if created_at:
+ record["createdAt"] = created_at
+ return _json(200, {"resolver": record})
+
+
+def _update_type(api_id, type_name, body):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ if type_name not in _types.get(api_id, {}):
+ return error_response_json("NotFoundException", f"Type {type_name} not found", 404)
+ body = dict(body)
+ body.setdefault("name", type_name)
+ return _create_type(api_id, body)
+
+
+def _update_api_key(api_id, key_id, body):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ key = _api_keys.get(api_id, {}).get(key_id)
+ if not key:
+ return error_response_json("NotFoundException", f"API key {key_id} not found", 404)
+ if body.get("description") is not None:
+ key["description"] = body["description"]
+ if body.get("expires") is not None:
+ key["expires"] = int(body["expires"])
+ return _json(200, {"apiKey": key})
+
+
+def _put_environment_variables(api_id, body):
+ """PutGraphqlApiEnvironmentVariables — replaces the whole map, as AWS does."""
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ env = body.get("environmentVariables")
+ if env is None:
+ return error_response_json("BadRequestException", "environmentVariables is required", 400)
+ if not isinstance(env, dict):
+ return error_response_json("BadRequestException", "environmentVariables must be a map", 400)
+ _apis[api_id]["environmentVariables"] = env
+ return _json(200, {"environmentVariables": env})
+
+
+def _get_environment_variables(api_id):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ return _json(200, {"environmentVariables": _apis[api_id].get("environmentVariables", {})})
+
+
+# ---------------------------------------------------------------------------
+# Pipeline functions
+# ---------------------------------------------------------------------------
+
+def _function_record(api_id, function_id, body):
+ arn = f"{_apis[api_id]['arn']}/functions/{function_id}"
+ record = {
+ "functionId": function_id,
+ "functionArn": arn,
+ "name": body.get("name", ""),
+ "description": body.get("description", ""),
+ "dataSourceName": body.get("dataSourceName", ""),
+ "requestMappingTemplate": body.get("requestMappingTemplate", ""),
+ "responseMappingTemplate": body.get("responseMappingTemplate", ""),
+ "functionVersion": body.get("functionVersion", "2018-05-29"),
+ }
+ for optional in ("syncConfig", "maxBatchSize", "runtime", "code"):
+ if body.get(optional) is not None:
+ record[optional] = body[optional]
+ return record
+
+
+def _create_function(api_id, body):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+
+ name = body.get("name")
+ if not name:
+ return error_response_json("BadRequestException", "name is required", 400)
+
+ function_id = new_uuid().replace("-", "")[:26]
+ record = _function_record(api_id, function_id, body)
+ _functions.setdefault(api_id, {})[function_id] = record
+ return _json(200, {"functionConfiguration": record})
+
+
+def _get_function(api_id, function_id):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ record = _functions.get(api_id, {}).get(function_id)
+ if not record:
+ return error_response_json("NotFoundException", f"Function {function_id} not found", 404)
+ return _json(200, {"functionConfiguration": record})
+
+
+def _list_functions(api_id):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ return _json(200, {"functions": list(_functions.get(api_id, {}).values())})
+
+
+def _update_function(api_id, function_id, body):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ if function_id not in _functions.get(api_id, {}):
+ return error_response_json("NotFoundException", f"Function {function_id} not found", 404)
+ record = _function_record(api_id, function_id, body)
+ _functions[api_id][function_id] = record
+ return _json(200, {"functionConfiguration": record})
+
+
+def _delete_function(api_id, function_id):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ if _functions.get(api_id, {}).pop(function_id, None) is None:
+ return error_response_json("NotFoundException", f"Function {function_id} not found", 404)
+ return _json(200, {})
+
+
def _tag_resource(body):
arn = body.get("resourceArn", "")
tags = body.get("tags", {})
@@ -529,6 +783,82 @@ def _list_tags_for_resource(arn):
return _json(200, {"tags": tags})
+def _cache_record(data, existing=None):
+ """Build an ApiCache from a create or update request.
+
+ atRestEncryptionEnabled and transitEncryptionEnabled are set at create time
+ and cannot be changed afterwards, so an update carries them forward from the
+ existing cache rather than defaulting them back to false.
+ """
+ base = existing or {}
+ return {
+ "ttl": int(data.get("ttl", base.get("ttl", 0))),
+ "apiCachingBehavior": data.get(
+ "apiCachingBehavior", base.get("apiCachingBehavior", "FULL_REQUEST_CACHING")
+ ),
+ "type": data.get("type", base.get("type", "SMALL")),
+ "transitEncryptionEnabled": bool(
+ base.get("transitEncryptionEnabled",
+ data.get("transitEncryptionEnabled", False))
+ ),
+ "atRestEncryptionEnabled": bool(
+ base.get("atRestEncryptionEnabled",
+ data.get("atRestEncryptionEnabled", False))
+ ),
+ # No cache is actually kept — AppSync's cache is not observable through
+ # the control plane, and emulating eviction would invent behaviour a
+ # caller cannot verify. The record exists so the resource can be
+ # created, read back and destroyed.
+ "status": "AVAILABLE",
+ }
+
+
+def _create_api_cache(api_id, data):
+ if api_id not in _apis:
+ return error_response_json("NotFoundException", f"GraphQL API {api_id} not found", 404)
+ if _caches.get(api_id) is not None:
+ return error_response_json(
+ "BadRequestException", f"Cache already exists for API {api_id}", 400)
+ record = _cache_record(data)
+ _caches[api_id] = record
+ return _json(200, {"apiCache": record})
+
+
+def _get_api_cache(api_id):
+ cache = _caches.get(api_id)
+ if cache is None:
+ return error_response_json(
+ "NotFoundException", f"Cache not found for API {api_id}", 404)
+ return _json(200, {"apiCache": cache})
+
+
+def _update_api_cache(api_id, data):
+ existing = _caches.get(api_id)
+ if existing is None:
+ return error_response_json(
+ "NotFoundException", f"Cache not found for API {api_id}", 404)
+ record = _cache_record(data, existing)
+ _caches[api_id] = record
+ return _json(200, {"apiCache": record})
+
+
+def _delete_api_cache(api_id):
+ if _caches.get(api_id) is None:
+ return error_response_json(
+ "NotFoundException", f"Cache not found for API {api_id}", 404)
+ _caches.pop(api_id, None)
+ _cache_entries.pop(api_id, None)
+ return _json(200, {})
+
+
+def _flush_api_cache(api_id):
+ if _caches.get(api_id) is None:
+ return error_response_json(
+ "NotFoundException", f"Cache not found for API {api_id}", 404)
+ _cache_entries.pop(api_id, None)
+ return _json(200, {})
+
+
# ---------------------------------------------------------------------------
# Request router
# ---------------------------------------------------------------------------
@@ -620,6 +950,23 @@ async def handle_request(method, path, headers, body, query_params):
return _delete_graphql_api(api_id)
# /v1/apis/{apiId}/apikeys
+ # ApiCaches: /v1/apis/{apiId}/ApiCaches[/update], and the separate
+ # /FlushCache path. UpdateApiCache is a POST to .../ApiCaches/update, not a
+ # PUT on the collection, so it has to be matched before the bare form.
+ if sub1 == "ApiCaches":
+ if sub2 == "update" and method == "POST":
+ return _update_api_cache(api_id, data)
+ if sub2 is None:
+ if method == "POST":
+ return _create_api_cache(api_id, data)
+ if method == "GET":
+ return _get_api_cache(api_id)
+ if method == "DELETE":
+ return _delete_api_cache(api_id)
+
+ if sub1 == "FlushCache" and method == "DELETE":
+ return _flush_api_cache(api_id)
+
if sub1 == "apikeys":
# Real SDKs route AppSync API key operations through the v1 path even
# for Event APIs. If the id is not a GraphQL API but is an Event API,
@@ -641,9 +988,45 @@ async def handle_request(method, path, headers, body, query_params):
return _list_api_keys(api_id)
else:
# /v1/apis/{apiId}/apikeys/{keyId}
- if method == "DELETE":
+ if method == "POST":
+ return _update_api_key(api_id, sub2, data)
+ elif method == "DELETE":
return _delete_api_key(api_id, sub2)
+ # /v1/apis/{apiId}/environmentVariables
+ if sub1 == "environmentVariables" and sub2 is None:
+ if method == "PUT":
+ return _put_environment_variables(api_id, data)
+ elif method == "GET":
+ return _get_environment_variables(api_id)
+
+ # /v1/apis/{apiId}/schemacreation
+ if sub1 == "schemacreation" and sub2 is None:
+ if method == "POST":
+ return _start_schema_creation(api_id, data)
+ elif method == "GET":
+ return _get_schema_creation_status(api_id)
+
+ # /v1/apis/{apiId}/schema
+ if sub1 == "schema" and sub2 is None and method == "GET":
+ return _get_introspection_schema(api_id, query_params)
+
+ # /v1/apis/{apiId}/functions
+ if sub1 == "functions":
+ if sub2 is None:
+ if method == "POST":
+ return _create_function(api_id, data)
+ elif method == "GET":
+ return _list_functions(api_id)
+ else:
+ # /v1/apis/{apiId}/functions/{functionId}
+ if method == "GET":
+ return _get_function(api_id, sub2)
+ elif method == "POST":
+ return _update_function(api_id, sub2, data)
+ elif method == "DELETE":
+ return _delete_function(api_id, sub2)
+
# /v1/apis/{apiId}/datasources
if sub1 == "datasources":
if sub2 is None:
@@ -655,6 +1038,8 @@ async def handle_request(method, path, headers, body, query_params):
# /v1/apis/{apiId}/datasources/{name}
if method == "GET":
return _get_data_source(api_id, sub2)
+ elif method == "POST":
+ return _update_data_source(api_id, sub2, data)
elif method == "DELETE":
return _delete_data_source(api_id, sub2)
@@ -678,12 +1063,16 @@ async def handle_request(method, path, headers, body, query_params):
field_name = sub4
if method == "GET":
return _get_resolver(api_id, type_name, field_name)
+ elif method == "POST":
+ return _update_resolver(api_id, type_name, field_name, data)
elif method == "DELETE":
return _delete_resolver(api_id, type_name, field_name)
else:
- # /v1/apis/{apiId}/types/{typeName} — GetType
+ # /v1/apis/{apiId}/types/{typeName}
if sub3 is None and method == "GET":
return _get_type(api_id, sub2, query_params)
+ if sub3 is None and method == "POST":
+ return _update_type(api_id, sub2, data)
return error_response_json("BadRequestException", f"Unsupported route: {method} {path}")
@@ -699,6 +1088,10 @@ def reset():
_data_sources.clear()
_resolvers.clear()
_types.clear()
+ _functions.clear()
+ _schemas.clear()
+ _caches.clear()
+ _cache_entries.clear()
_tags.clear()
@@ -710,6 +1103,9 @@ def get_state():
"data_sources": _data_sources,
"resolvers": _resolvers,
"types": _types,
+ "functions": _functions,
+ "schemas": _schemas,
+ "caches": _caches,
"tags": _tags,
})
@@ -727,6 +1123,9 @@ def restore_state(data):
(_data_sources, "data_sources"),
(_resolvers, "resolvers"),
(_types, "types"),
+ (_functions, "functions"),
+ (_schemas, "schemas"),
+ (_caches, "caches"),
):
_restore_api_child_store(store, data.get(key, {}), api_regions)
_tags.update(data.get("tags", {}))
@@ -950,6 +1349,14 @@ def _execute_graphql(api_id, data, request_headers=None):
for field_name, args, sub_fields in fields:
resolver = _find_resolver(api_id, "Mutation" if is_mutation else "Query", field_name)
if resolver:
+ # A mutation is never served from cache, and never populates it.
+ cache_hit = None if is_mutation else _cache_key_for(
+ api_id, resolver, field_name, args, identity, {})
+ if cache_hit:
+ cached = _cache_get(api_id, cache_hit[0])
+ if cached is not None:
+ results[field_name] = cached
+ continue
try:
result = _resolve_field(
api_id, resolver, args, sub_fields, variables,
@@ -959,6 +1366,10 @@ def _execute_graphql(api_id, data, request_headers=None):
source={},
)
results[field_name] = result
+ # 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 Exception as e:
errors.append({"message": str(e), "path": [field_name]})
results[field_name] = None
@@ -1014,6 +1425,61 @@ def _parse_args(args_str, variables):
return args
+def _cache_key_for(api_id, resolver, field_name, args, identity, source):
+ """Build a cache key for this field call, or None when it must not be cached.
+
+ Mirrors AppSync: under PER_RESOLVER_CACHING only a resolver carrying a
+ cachingConfig ttl is cached; under FULL_REQUEST_CACHING every resolver is,
+ using the cache's own ttl. A caching key that cannot be resolved disables
+ caching for the call rather than collapsing to a shared entry — two callers
+ sharing an entry they should not is worse than not caching.
+ """
+ cache_cfg = _caches.get(api_id)
+ if not cache_cfg:
+ return None
+ behavior = cache_cfg.get("apiCachingBehavior", "FULL_REQUEST_CACHING")
+ resolver_cfg = (resolver or {}).get("cachingConfig") or {}
+
+ if behavior == "PER_RESOLVER_CACHING":
+ ttl = resolver_cfg.get("ttl")
+ if not ttl:
+ return None
+ else:
+ ttl = cache_cfg.get("ttl")
+ if not ttl:
+ return None
+
+ ctx = {"arguments": args or {}, "args": args or {},
+ "identity": identity or {}, "source": source or {}}
+ parts = []
+ for expr in resolver_cfg.get("cachingKeys") or []:
+ path = expr.split(".")
+ if path and path[0].lstrip("$") in ("context", "ctx"):
+ path = path[1:]
+ cur = ctx
+ for seg in path:
+ if not isinstance(cur, dict) or seg not in cur:
+ return None
+ cur = cur[seg]
+ parts.append(f"{expr}={json.dumps(cur, sort_keys=True, default=str)}")
+ return f"{field_name}|" + "&".join(parts), int(ttl)
+
+
+def _cache_get(api_id, key):
+ entry = _cache_entries.get(api_id, {}).get(key)
+ if not entry:
+ return None
+ expires_at, value = entry
+ if expires_at <= time.time():
+ _cache_entries.get(api_id, {}).pop(key, None)
+ return None
+ return copy.deepcopy(value)
+
+
+def _cache_put(api_id, key, ttl, value):
+ _cache_entries.setdefault(api_id, {})[key] = (time.time() + ttl, copy.deepcopy(value))
+
+
def _find_resolver(api_id, type_name, field_name):
"""Find a resolver for Query.fieldName or Mutation.fieldName."""
resolvers = _resolvers.get(api_id, {})
diff --git a/tests/test_appsync.py b/tests/test_appsync.py
index 7009c61c..c81b4fbc 100644
--- a/tests/test_appsync.py
+++ b/tests/test_appsync.py
@@ -963,3 +963,440 @@ def test_appsync_lambda_failing_authorizer_returns_unauthorized(appsync, lam):
_APPSYNC_IDENTITY_PROBE_RESOLVER)
_appsync_expect_unauthorized(url, "{ testField { hasIdentity } }",
headers={"Authorization": "Bearer fake-jwt"})
+
+
+SDL = """type Query {
+ hello: String
+}
+schema { query: Query }
+"""
+
+
+def test_appsync_schema_creation_and_introspection():
+ """StartSchemaCreation stores the SDL; the status polls to SUCCESS and it reads back."""
+ from conftest import make_client
+ appsync = make_client("appsync")
+ api = appsync.create_graphql_api(name="schema-api", authenticationType="API_KEY")["graphqlApi"]
+
+ started = appsync.start_schema_creation(apiId=api["apiId"], definition=SDL.encode())
+ assert started["status"] in ("PROCESSING", "SUCCESS")
+
+ status = appsync.get_schema_creation_status(apiId=api["apiId"])
+ assert status["status"] == "SUCCESS"
+
+ schema = appsync.get_introspection_schema(apiId=api["apiId"], format="SDL")
+ assert schema["schema"].read().decode() == SDL
+
+
+def test_appsync_schema_creation_status_without_a_schema():
+ """An API that has never had a schema reports NOT_APPLICABLE rather than failing."""
+ from conftest import make_client
+ appsync = make_client("appsync")
+ api = appsync.create_graphql_api(name="noschema-api", authenticationType="API_KEY")["graphqlApi"]
+ assert appsync.get_schema_creation_status(apiId=api["apiId"])["status"] == "NOT_APPLICABLE"
+
+
+def test_appsync_pipeline_function_crud():
+ """Create, get, list, update and delete a pipeline function."""
+ from conftest import make_client
+ appsync = make_client("appsync")
+ api = appsync.create_graphql_api(name="fn-api", authenticationType="API_KEY")["graphqlApi"]
+ appsync.create_data_source(apiId=api["apiId"], name="NoneDS", type="NONE")
+
+ created = appsync.create_function(
+ apiId=api["apiId"], name="fnOne", dataSourceName="NoneDS",
+ functionVersion="2018-05-29",
+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},
+ code="export function request(ctx){return {};} export function response(ctx){return ctx.result;}",
+ )["functionConfiguration"]
+ assert created["name"] == "fnOne"
+ assert created["functionId"]
+ assert created["functionArn"].endswith(f"/functions/{created['functionId']}")
+ assert created["runtime"]["name"] == "APPSYNC_JS"
+
+ got = appsync.get_function(apiId=api["apiId"], functionId=created["functionId"])
+ assert got["functionConfiguration"]["name"] == "fnOne"
+
+ listed = appsync.list_functions(apiId=api["apiId"])["functions"]
+ assert [f["functionId"] for f in listed] == [created["functionId"]]
+
+ updated = appsync.update_function(
+ apiId=api["apiId"], functionId=created["functionId"],
+ name="fnOneRenamed", dataSourceName="NoneDS", functionVersion="2018-05-29",
+ )["functionConfiguration"]
+ assert updated["name"] == "fnOneRenamed"
+ assert updated["functionId"] == created["functionId"]
+
+ appsync.delete_function(apiId=api["apiId"], functionId=created["functionId"])
+ assert appsync.list_functions(apiId=api["apiId"])["functions"] == []
+
+
+def test_appsync_pipeline_resolver_referencing_functions():
+ """A PIPELINE resolver keeps the function ids it was created with.
+
+ This is the shape Terraform produces: functions first, then a resolver whose
+ pipelineConfig lists their ids.
+ """
+ from conftest import make_client
+ appsync = make_client("appsync")
+ api = appsync.create_graphql_api(name="pipe-api", authenticationType="API_KEY")["graphqlApi"]
+ appsync.start_schema_creation(apiId=api["apiId"], definition=SDL.encode())
+ appsync.create_data_source(apiId=api["apiId"], name="NoneDS", type="NONE")
+
+ ids = [
+ appsync.create_function(
+ apiId=api["apiId"], name=f"step{i}", dataSourceName="NoneDS",
+ functionVersion="2018-05-29",
+ )["functionConfiguration"]["functionId"]
+ for i in range(2)
+ ]
+
+ resolver = appsync.create_resolver(
+ apiId=api["apiId"], typeName="Query", fieldName="hello",
+ kind="PIPELINE", pipelineConfig={"functions": ids},
+ )["resolver"]
+ assert resolver["kind"] == "PIPELINE"
+ assert resolver["pipelineConfig"]["functions"] == ids
+
+
+def test_appsync_graphql_api_environment_variables():
+ """Environment variables round-trip, and a put replaces the whole map."""
+ from conftest import make_client
+ appsync = make_client("appsync")
+ api = appsync.create_graphql_api(name="env-api", authenticationType="API_KEY")["graphqlApi"]
+
+ assert appsync.get_graphql_api_environment_variables(apiId=api["apiId"])["environmentVariables"] == {}
+
+ put = appsync.put_graphql_api_environment_variables(
+ apiId=api["apiId"], environmentVariables={"FEATURE": "on", "TIER": "local"},
+ )["environmentVariables"]
+ assert put == {"FEATURE": "on", "TIER": "local"}
+
+ got = appsync.get_graphql_api_environment_variables(apiId=api["apiId"])["environmentVariables"]
+ assert got == {"FEATURE": "on", "TIER": "local"}
+
+ # AWS replaces rather than merges
+ replaced = appsync.put_graphql_api_environment_variables(
+ apiId=api["apiId"], environmentVariables={"ONLY": "this"},
+ )["environmentVariables"]
+ assert replaced == {"ONLY": "this"}
+
+
+def test_appsync_update_data_source_and_resolver():
+ """Terraform re-applies an existing API by updating in place, not recreating."""
+ from conftest import make_client
+ appsync = make_client("appsync")
+ api = appsync.create_graphql_api(name="upd-api", authenticationType="API_KEY")["graphqlApi"]
+ appsync.start_schema_creation(apiId=api["apiId"], definition=SDL.encode())
+ appsync.create_data_source(apiId=api["apiId"], name="DS", type="NONE", description="first")
+
+ updated = appsync.update_data_source(
+ apiId=api["apiId"], name="DS", type="NONE", description="second",
+ )["dataSource"]
+ assert updated["description"] == "second"
+ assert appsync.get_data_source(apiId=api["apiId"], name="DS")["dataSource"]["description"] == "second"
+
+ appsync.create_resolver(
+ apiId=api["apiId"], typeName="Query", fieldName="hello", dataSourceName="DS",
+ )
+ appsync.update_resolver(
+ apiId=api["apiId"], typeName="Query", fieldName="hello", dataSourceName="DS",
+ kind="PIPELINE", pipelineConfig={"functions": []},
+ )
+ got = appsync.get_resolver(apiId=api["apiId"], typeName="Query", fieldName="hello")["resolver"]
+ assert got["kind"] == "PIPELINE"
+
+
+def test_appsync_update_api_key():
+ """UpdateApiKey changes the description without minting a new key."""
+ from conftest import make_client
+ appsync = make_client("appsync")
+ api = appsync.create_graphql_api(name="key-api", authenticationType="API_KEY")["graphqlApi"]
+ key = appsync.create_api_key(apiId=api["apiId"], description="before")["apiKey"]
+
+ updated = appsync.update_api_key(
+ apiId=api["apiId"], id=key["id"], description="after",
+ )["apiKey"]
+ assert updated["id"] == key["id"]
+ assert updated["description"] == "after"
+
+
+def test_appsync_graphql_api_reports_server_side_defaults():
+ """apiType and visibility must come back, or a Terraform plan forces replacement.
+
+ Both are ForceNew in the AWS provider, so an API that omits them reads as
+ needing to be recreated on every plan — taking every datasource, function and
+ resolver with it.
+ """
+ from conftest import make_client
+ appsync = make_client("appsync")
+ api = appsync.create_graphql_api(name="defaults-api", authenticationType="API_KEY")["graphqlApi"]
+ assert api["apiType"] == "GRAPHQL"
+ assert api["visibility"] == "GLOBAL"
+ assert api["introspectionConfig"] == "ENABLED"
+
+ got = appsync.get_graphql_api(apiId=api["apiId"])["graphqlApi"]
+ assert got["apiType"] == "GRAPHQL"
+ assert got["visibility"] == "GLOBAL"
+
+
+def test_appsync_delete_api_removes_functions_and_schema():
+ """Deleting an API must drop its functions and schema from the stores.
+
+ Asserted against the stores directly: every read path checks the API exists
+ first, so going through the API would report NotFoundException whether or not
+ the child state was actually released.
+ """
+ import json as _json_mod
+
+ from ministack.services import appsync as _appsync
+
+ resp = _appsync._create_graphql_api({"name": "cascade", "authenticationType": "API_KEY"})
+ api_id = _json_mod.loads(resp[2])["graphqlApi"]["apiId"]
+ _appsync._start_schema_creation(api_id, {"definition": "type Query { hi: String }"})
+ _appsync._create_data_source(api_id, {"name": "DS", "type": "NONE"})
+ _appsync._create_function(api_id, {"name": "fn", "dataSourceName": "DS"})
+
+ assert api_id in _appsync._functions
+ assert api_id in _appsync._schemas
+
+ _appsync._delete_graphql_api(api_id)
+
+ assert api_id not in _appsync._functions, "functions leaked after DeleteGraphqlApi"
+ assert api_id not in _appsync._schemas, "schema leaked after DeleteGraphqlApi"
+ assert api_id not in _appsync._data_sources
+
+
+def test_appsync_update_preserves_creation_time(monkeypatch):
+ """An update must not restamp createdAt, as AWS does not.
+
+ _now() has whole-second granularity, so a create and an update in the same
+ second are indistinguishable; the clock is advanced between them.
+ """
+ import json as _json_mod
+
+ from ministack.services import appsync as _appsync
+
+ clock = {"t": 1_700_000_000}
+ monkeypatch.setattr(_appsync, "_now", lambda: clock["t"])
+
+ resp = _appsync._create_graphql_api({"name": "ctime", "authenticationType": "API_KEY"})
+ api_id = _json_mod.loads(resp[2])["graphqlApi"]["apiId"]
+ created = _json_mod.loads(
+ _appsync._create_data_source(api_id, {"name": "DS", "type": "NONE", "description": "one"})[2]
+ )["dataSource"]
+
+ clock["t"] += 3600
+ updated = _json_mod.loads(
+ _appsync._update_data_source(api_id, "DS", {"type": "NONE", "description": "two"})[2]
+ )["dataSource"]
+
+ assert updated["description"] == "two"
+ assert updated["createdAt"] == created["createdAt"], "createdAt was restamped by the update"
+ assert updated["lastUpdatedAt"] == clock["t"], "lastUpdatedAt should advance"
+
+
+def test_appsync_graphql_api_echoes_its_tags(appsync):
+ """The GraphqlApi object must carry `tags`.
+
+ AWS returns tags on the API itself, and that is where the Terraform provider
+ reads them. CreateGraphqlApi stored them in the ARN-keyed tag store but left
+ them off the record, so tags_all refreshed to empty and every plan proposed
+ the same tag change.
+ """
+ api = appsync.create_graphql_api(
+ name="qa-api-tags",
+ authenticationType="API_KEY",
+ tags={"ourco:env": "ministack"},
+ )["graphqlApi"]
+ assert api.get("tags") == {"ourco:env": "ministack"}
+
+ got = appsync.get_graphql_api(apiId=api["apiId"])["graphqlApi"]
+ assert got.get("tags") == {"ourco:env": "ministack"}
+
+ listed = [
+ a for a in appsync.list_graphql_apis()["graphqlApis"]
+ if a["apiId"] == api["apiId"]
+ ]
+ assert listed and listed[0].get("tags") == {"ourco:env": "ministack"}
+
+ # A tag added later through TagResource must show up on the API too.
+ appsync.tag_resource(resourceArn=api["arn"], tags={"team": "platform"})
+ got = appsync.get_graphql_api(apiId=api["apiId"])["graphqlApi"]
+ assert got["tags"]["team"] == "platform"
+ assert got["tags"]["ourco:env"] == "ministack"
+
+
+def _cache_api(appsync, name):
+ return appsync.create_graphql_api(name=name, authenticationType="API_KEY")[
+ "graphqlApi"
+ ]["apiId"]
+
+
+def test_appsync_api_cache_lifecycle(appsync):
+ """CreateApiCache / Get / Update / Flush / Delete.
+
+ aws_appsync_api_cache cannot be applied at all without these, so an
+ environment that enables caching in the cloud has to disable it locally and
+ silently diverges from the thing it is meant to reproduce.
+ """
+ api_id = _cache_api(appsync, "qa-cache-lifecycle")
+
+ created = appsync.create_api_cache(
+ apiId=api_id,
+ ttl=60,
+ apiCachingBehavior="PER_RESOLVER_CACHING",
+ type="SMALL",
+ atRestEncryptionEnabled=True,
+ transitEncryptionEnabled=True,
+ )["apiCache"]
+ assert created["ttl"] == 60
+ assert created["apiCachingBehavior"] == "PER_RESOLVER_CACHING"
+ assert created["type"] == "SMALL"
+ assert created["atRestEncryptionEnabled"] is True
+ assert created["transitEncryptionEnabled"] is True
+ assert created["status"] == "AVAILABLE"
+
+ got = appsync.get_api_cache(apiId=api_id)["apiCache"]
+ assert got == created
+
+ updated = appsync.update_api_cache(
+ apiId=api_id, ttl=300, apiCachingBehavior="FULL_REQUEST_CACHING", type="MEDIUM"
+ )["apiCache"]
+ assert updated["ttl"] == 300
+ assert updated["apiCachingBehavior"] == "FULL_REQUEST_CACHING"
+ assert updated["type"] == "MEDIUM"
+ # Encryption is set at create time and cannot be changed by an update; it
+ # must survive one rather than silently reverting to false.
+ assert updated["atRestEncryptionEnabled"] is True
+ assert updated["transitEncryptionEnabled"] is True
+
+ appsync.flush_api_cache(apiId=api_id)
+ assert appsync.get_api_cache(apiId=api_id)["apiCache"]["ttl"] == 300
+
+ appsync.delete_api_cache(apiId=api_id)
+ with pytest.raises(ClientError) as e:
+ appsync.get_api_cache(apiId=api_id)
+ assert e.value.response["Error"]["Code"] == "NotFoundException"
+
+
+def test_appsync_api_cache_rejects_a_second_cache_and_unknown_apis(appsync):
+ """One cache per API, and the operations 404 on an API that does not exist."""
+ api_id = _cache_api(appsync, "qa-cache-errors")
+ appsync.create_api_cache(
+ apiId=api_id, ttl=60, apiCachingBehavior="PER_RESOLVER_CACHING", type="SMALL"
+ )
+
+ with pytest.raises(ClientError) as e:
+ appsync.create_api_cache(
+ apiId=api_id, ttl=60, apiCachingBehavior="PER_RESOLVER_CACHING", type="SMALL"
+ )
+ assert e.value.response["Error"]["Code"] == "BadRequestException"
+
+ for call in (
+ lambda: appsync.get_api_cache(apiId="doesnotexist"),
+ lambda: appsync.delete_api_cache(apiId="doesnotexist"),
+ lambda: appsync.flush_api_cache(apiId="doesnotexist"),
+ ):
+ with pytest.raises(ClientError) as e:
+ call()
+ assert e.value.response["Error"]["Code"] == "NotFoundException"
+
+
+def test_appsync_deleting_an_api_releases_its_cache(appsync):
+ """A cache must not outlive its API — a later API reusing the id would
+ otherwise inherit a cache nobody created."""
+ api_id = _cache_api(appsync, "qa-cache-cascade")
+ appsync.create_api_cache(
+ apiId=api_id, ttl=60, apiCachingBehavior="PER_RESOLVER_CACHING", type="SMALL"
+ )
+ appsync.delete_graphql_api(apiId=api_id)
+
+ with pytest.raises(ClientError) as e:
+ appsync.get_api_cache(apiId=api_id)
+ assert e.value.response["Error"]["Code"] == "NotFoundException"
+
+
+def _graphql(api_id, api_key, query):
+ """POST a query to the API's data plane the way an SDK would."""
+ import requests as _rq
+ r = _rq.post(f"{_ENDPOINT}/v1/apis/{api_id}/graphql",
+ headers={"x-api-key": api_key, "content-type": "application/json"},
+ json={"query": query}, timeout=15)
+ return r.json()
+
+def _cache_ds_api(appsync, ddb, name):
+ """An API with a DynamoDB-backed resolver, which is what ministack executes."""
+ 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"]
+ table = f"{name}-table"
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ appsync.create_data_source(
+ apiId=api_id, name="Things", type="AMAZON_DYNAMODB",
+ dynamodbConfig={"tableName": table, "awsRegion": "us-east-1"},
+ )
+ return api_id, key, table
+
+
+def test_appsync_caches_a_resolver_that_declares_a_ttl(appsync, ddb):
+ """A cached resolver must not re-read its datasource within the TTL.
+
+ An API can declare an ApiCache and per-resolver cachingConfig, and both
+ round-trip through the control plane, but the data plane ignored them: every
+ query re-ran the resolver. A caching bug — a stale read, a key collision —
+ could not be reproduced locally at all.
+ """
+ api_id, key, table = _cache_ds_api(appsync, ddb, "qa-cache-exec")
+ appsync.create_resolver(
+ apiId=api_id, typeName="Query", fieldName="getThing", dataSourceName="Things",
+ cachingConfig={"ttl": 300, "cachingKeys": ["$context.arguments.id"]},
+ )
+ appsync.create_api_cache(
+ apiId=api_id, ttl=60, apiCachingBehavior="PER_RESOLVER_CACHING", type="SMALL")
+
+ ddb.put_item(TableName=table, Item={"id": {"S": "t1"}, "v": {"S": "first"}})
+ q = '{ getThing(id: "t1") { id v } }'
+ first = _graphql(api_id, key, q)
+ assert first["data"]["getThing"]["v"] == "first"
+
+ # Change the row underneath. A cached resolver must still answer "first".
+ ddb.put_item(TableName=table, Item={"id": {"S": "t1"}, "v": {"S": "second"}})
+ cached = _graphql(api_id, key, q)
+ assert cached["data"]["getThing"]["v"] == "first", "resolver was not cached"
+
+ # A different argument is a different entry and must see the new value.
+ ddb.put_item(TableName=table, Item={"id": {"S": "t2"}, "v": {"S": "other"}})
+ other = _graphql(api_id, key, '{ getThing(id: "t2") { id v } }')
+ assert other["data"]["getThing"]["v"] == "other", "caching keys must isolate entries"
+
+ # FlushApiCache drops it, so the next read sees the new value.
+ appsync.flush_api_cache(apiId=api_id)
+ assert _graphql(api_id, key, q)["data"]["getThing"]["v"] == "second"
+
+
+def test_appsync_does_not_cache_without_an_api_cache_or_a_ttl(appsync, ddb):
+ """No ApiCache means no caching, and under PER_RESOLVER_CACHING a resolver
+ that declares no ttl is not cached either — otherwise enabling the cache
+ would silently start serving stale data from resolvers that never asked."""
+ api_id, key, table = _cache_ds_api(appsync, ddb, "qa-cache-off")
+ appsync.create_resolver(
+ apiId=api_id, typeName="Query", fieldName="getThing", dataSourceName="Things")
+
+ ddb.put_item(TableName=table, Item={"id": {"S": "t1"}, "v": {"S": "first"}})
+ q = '{ getThing(id: "t1") { id v } }'
+ assert _graphql(api_id, key, q)["data"]["getThing"]["v"] == "first"
+ ddb.put_item(TableName=table, Item={"id": {"S": "t1"}, "v": {"S": "second"}})
+ # No cache on the API at all.
+ assert _graphql(api_id, key, q)["data"]["getThing"]["v"] == "second"
+
+ # Now add a cache, but the resolver still declares no ttl.
+ appsync.create_api_cache(
+ 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"