fix(cloudformation): roll back an AppSync update when a later resource fails (#7186)

A failed stack update left AppSync entities changed or cleared by the update:
the provisioner had no rollbackUpdate, so the stack ended in
UPDATE_ROLLBACK_FAILED with "Rollback is not implemented".

Before an in-place update of a GraphQL API, data source, function, resolver or
API key, the provisioner records the members the update can change or clear.
The service applies an update member by containsKey, so replaying them puts
back both the changed and the cleared values. An update that fails part way
undoes itself through CfnRollback.guarded, and a failed undo keeps the
snapshot for ContinueUpdateRollback.

GraphQLSchema and a replaced AppSync resource are not covered.

tagResource, untagResource and putEnvironmentVariables change the stored API in place while updateGraphqlApi saves a copy, so a copy could overwrite a tag or variable written in between. Every method that writes a store now holds the service monitor, as startSchemaCreation does, and startSchemaCreation checks the API under it too. refreshGraphqlApiUris refreshes the stored API under the monitor instead of putting the instance it read earlier.
This commit is contained in:
Oleksandr Nikolaichuk authored and GitHub committed 2026-11-04 16:25:04 -04:00
1 parent e0b8da1b6c
commit 0c3af7dc4b
8 files changed
+1292 -139

No files matched your search

@@ -30,6 +30,11 @@ import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Writers hold the service monitor across each read, change and save, as startSchemaCreation
* does, so two writers never lose each other's changes. Readers do not take it, and the schema
* worker's own writes to the schema and schema-status stores are outside it.
*/
@ApplicationScoped
public class AppSyncService {
private static final Logger LOG = Logger.getLogger(AppSyncService.class);
@@ -97,7 +102,7 @@ public class AppSyncService {
// ──────────────────────────── GraphQL API ────────────────────────────
public GraphqlApi createGraphqlApi(Map<String, Object> request, String region) {
public synchronized GraphqlApi createGraphqlApi(Map<String, Object> request, String region) {
assertNoSchemaBusyAnywhere();
String name = (String) request.get("name");
if (name == null || name.isBlank()) {
@@ -168,15 +173,17 @@ public class AppSyncService {
}
public Page<GraphqlApi> listGraphqlApis(Integer maxResults, String nextToken) {
List<GraphqlApi> apis = apiStore.scan(k -> true);
apis.forEach(this::refreshGraphqlApiUris);
List<GraphqlApi> apis = new ArrayList<>();
for (GraphqlApi stored : apiStore.scan(k -> true)) {
apis.add(refreshGraphqlApiUris(stored));
}
return paginate(apis, nextToken, maxResults);
}
@SuppressWarnings("unchecked")
public GraphqlApi updateGraphqlApi(String apiId, Map<String, Object> request, String region) {
public synchronized GraphqlApi updateGraphqlApi(String apiId, Map<String, Object> request, String region) {
assertSchemaNotBusy(apiId);
GraphqlApi existing = getGraphqlApi(apiId);
GraphqlApi existing = copyOf(getGraphqlApi(apiId), GraphqlApi.class);
if (request.containsKey("name")) existing.setName((String) request.get("name"));
if (request.containsKey("authenticationType")) existing.setAuthenticationType(parseEnum(AuthenticationType.class, request.get("authenticationType")));
if (request.containsKey("xrayEnabled")) {
@@ -223,7 +230,7 @@ public class AppSyncService {
return existing;
}
public void deleteGraphqlApi(String apiId) {
public synchronized void deleteGraphqlApi(String apiId) {
assertSchemaNotBusy(apiId);
getGraphqlApi(apiId);
apiStore.delete(apiId);
@@ -244,10 +251,11 @@ public class AppSyncService {
// ──────────────────────────── Schema ────────────────────────────
public SchemaCreationStatus startSchemaCreation(String apiId, String definition) {
getGraphqlApi(apiId);
String accountId = currentAccountId();
SchemaCreationStatus status;
String accountId;
synchronized (this) {
getGraphqlApi(apiId);
accountId = currentAccountId();
assertSchemaNotBusy(apiId);
status = new SchemaCreationStatus();
status.setStatus(SchemaCreationStatusType.PROCESSING);
@@ -312,7 +320,7 @@ public class AppSyncService {
// ──────────────────────────── Data Sources ────────────────────────────
public DataSource createDataSource(String apiId, Map<String, Object> request, String region) {
public synchronized DataSource createDataSource(String apiId, Map<String, Object> request, String region) {
assertSchemaNotBusy(apiId);
getGraphqlApi(apiId);
String name = (String) request.get("name");
@@ -355,9 +363,9 @@ public class AppSyncService {
}
@SuppressWarnings("unchecked")
public DataSource updateDataSource(String apiId, String dataSourceName, Map<String, Object> request) {
public synchronized DataSource updateDataSource(String apiId, String dataSourceName, Map<String, Object> request) {
assertSchemaNotBusy(apiId);
DataSource existing = getDataSource(apiId, dataSourceName);
DataSource existing = copyOf(getDataSource(apiId, dataSourceName), DataSource.class);
if (request.containsKey("description")) existing.setDescription((String) request.get("description"));
if (request.containsKey("type")) existing.setType(parseEnum(DataSourceType.class, request.get("type")));
if (request.containsKey("serviceRoleArn")) existing.setServiceRoleArn((String) request.get("serviceRoleArn"));
@@ -372,7 +380,7 @@ public class AppSyncService {
return existing;
}
public void deleteDataSource(String apiId, String dataSourceName) {
public synchronized void deleteDataSource(String apiId, String dataSourceName) {
assertSchemaNotBusy(apiId);
getDataSource(apiId, dataSourceName);
dataSourceStore.delete(apiKey(apiId, dataSourceName));
@@ -396,7 +404,7 @@ public class AppSyncService {
return rt;
}
public Resolver createResolver(String apiId, Map<String, Object> request, String region) {
public synchronized Resolver createResolver(String apiId, Map<String, Object> request, String region) {
assertSchemaNotBusy(apiId);
getGraphqlApi(apiId);
String fieldName = (String) request.get("fieldName");
@@ -476,9 +484,9 @@ public class AppSyncService {
}
@SuppressWarnings("unchecked")
public Resolver updateResolver(String apiId, String typeName, String fieldName, Map<String, Object> request) {
public synchronized Resolver updateResolver(String apiId, String typeName, String fieldName, Map<String, Object> request) {
assertSchemaNotBusy(apiId);
Resolver existing = getResolver(apiId, typeName, fieldName);
Resolver existing = copyOf(getResolver(apiId, typeName, fieldName), Resolver.class);
if (request.containsKey("dataSourceName")) existing.setDataSourceName((String) request.get("dataSourceName"));
if (request.containsKey("functionId")) existing.setFunctionId((String) request.get("functionId"));
if (request.containsKey("requestMappingTemplate")) existing.setRequestMappingTemplate((String) request.get("requestMappingTemplate"));
@@ -495,7 +503,7 @@ public class AppSyncService {
return existing;
}
public void deleteResolver(String apiId, String typeName, String fieldName) {
public synchronized void deleteResolver(String apiId, String typeName, String fieldName) {
assertSchemaNotBusy(apiId);
getResolver(apiId, typeName, fieldName);
resolverStore.delete(resolverKey(apiId, typeName, fieldName));
@@ -503,7 +511,7 @@ public class AppSyncService {
// ──────────────────────────── Functions ────────────────────────────
public FunctionConfiguration createFunction(String apiId, Map<String, Object> request, String region) {
public synchronized FunctionConfiguration createFunction(String apiId, Map<String, Object> request, String region) {
assertSchemaNotBusy(apiId);
getGraphqlApi(apiId);
String name = (String) request.get("name");
@@ -541,9 +549,9 @@ public class AppSyncService {
return paginate(functionStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults);
}
public FunctionConfiguration updateFunction(String apiId, String functionId, Map<String, Object> request) {
public synchronized FunctionConfiguration updateFunction(String apiId, String functionId, Map<String, Object> request) {
assertSchemaNotBusy(apiId);
FunctionConfiguration existing = getFunction(apiId, functionId);
FunctionConfiguration existing = copyOf(getFunction(apiId, functionId), FunctionConfiguration.class);
// UpdateFunction takes a new name on AWS, and CloudFormation drives FunctionConfiguration
// renames through it. Leaving the name alone let a stack complete while GetFunction still
// reported the old one.
@@ -560,7 +568,7 @@ public class AppSyncService {
return existing;
}
public void deleteFunction(String apiId, String functionId) {
public synchronized void deleteFunction(String apiId, String functionId) {
assertSchemaNotBusy(apiId);
getFunction(apiId, functionId);
functionStore.delete(apiKey(apiId, functionId));
@@ -568,7 +576,7 @@ public class AppSyncService {
// ──────────────────────────── Types ────────────────────────────
public AppSyncType createType(String apiId, Map<String, Object> request) {
public synchronized AppSyncType createType(String apiId, Map<String, Object> request) {
assertSchemaNotBusy(apiId);
getGraphqlApi(apiId);
String name = (String) request.get("name");
@@ -605,7 +613,7 @@ public class AppSyncService {
return paginate(typeStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults);
}
public AppSyncType updateType(String apiId, String typeName, Map<String, Object> request) {
public synchronized AppSyncType updateType(String apiId, String typeName, Map<String, Object> request) {
assertSchemaNotBusy(apiId);
AppSyncType existing = getType(apiId, typeName);
if (request.containsKey("definition")) existing.setDefinition((String) request.get("definition"));
@@ -615,7 +623,7 @@ public class AppSyncService {
return existing;
}
public void deleteType(String apiId, String typeName) {
public synchronized void deleteType(String apiId, String typeName) {
assertSchemaNotBusy(apiId);
getType(apiId, typeName);
typeStore.delete(apiKey(apiId, typeName));
@@ -623,7 +631,7 @@ public class AppSyncService {
// ──────────────────────────── API Keys ────────────────────────────
public ApiKey createApiKey(String apiId, Map<String, Object> request) {
public synchronized ApiKey createApiKey(String apiId, Map<String, Object> request) {
getGraphqlApi(apiId);
long existingCount = apiKeyStore.scan(k -> k.startsWith(apiId + "::")).size();
if (existingCount >= 2) {
@@ -671,19 +679,21 @@ public class AppSyncService {
return Optional.empty();
}
public ApiKey updateApiKey(String apiId, String keyId, Map<String, Object> request) {
ApiKey existing = getApiKey(apiId, keyId);
if (request.containsKey("description")) {
existing.setDescription((String) request.get("description"));
}
public synchronized ApiKey updateApiKey(String apiId, String keyId, Map<String, Object> request) {
ApiKey existing = copyOf(getApiKey(apiId, keyId), ApiKey.class);
// Applied to a copy and stored last, so a refused expiry or a description of the wrong
// type leaves the stored key as it was.
if (request.containsKey("expires")) {
applyApiKeyExpires(existing, parseExpires(request.get("expires")));
}
if (request.containsKey("description")) {
existing.setDescription((String) request.get("description"));
}
apiKeyStore.put(apiKey(apiId, keyId), existing);
return existing;
}
public void deleteApiKey(String apiId, String keyId) {
public synchronized void deleteApiKey(String apiId, String keyId) {
getApiKey(apiId, keyId);
apiKeyStore.delete(apiKey(apiId, keyId));
}
@@ -695,14 +705,14 @@ public class AppSyncService {
return getGraphqlApi(apiId).getTags();
}
public void tagResource(String resourceArn, Map<String, String> tags) {
public synchronized void tagResource(String resourceArn, Map<String, String> tags) {
String apiId = extractApiIdFromArn(resourceArn);
GraphqlApi api = getGraphqlApi(apiId);
api.getTags().putAll(tags);
apiStore.put(apiId, api);
}
public void untagResource(String resourceArn, List<String> tagKeys) {
public synchronized void untagResource(String resourceArn, List<String> tagKeys) {
String apiId = extractApiIdFromArn(resourceArn);
GraphqlApi api = getGraphqlApi(apiId);
tagKeys.forEach(api.getTags()::remove);
@@ -717,7 +727,7 @@ public class AppSyncService {
return envVars != null ? envVars : Map.of();
}
public Map<String, String> putEnvironmentVariables(String apiId, Map<String, String> environmentVariables) {
public synchronized Map<String, String> putEnvironmentVariables(String apiId, Map<String, String> environmentVariables) {
assertSchemaNotBusy(apiId);
GraphqlApi api = getGraphqlApi(apiId);
api.setEnvironmentVariables(new HashMap<>(environmentVariables));
@@ -727,7 +737,7 @@ public class AppSyncService {
// ──────────────────────────── Domain Names ────────────────────────────
public DomainName createDomainName(Map<String, Object> request) {
public synchronized DomainName createDomainName(Map<String, Object> request) {
String domainName = (String) request.get("domainName");
if (domainName == null || domainName.isBlank()) {
throw new AwsException("BadRequestException", "A domain name is required", 400);
@@ -777,7 +787,7 @@ public class AppSyncService {
return paginate(domainStore.scan(k -> true), nextToken, maxResults);
}
public DomainName updateDomainName(String domainName, Map<String, Object> request) {
public synchronized DomainName updateDomainName(String domainName, Map<String, Object> request) {
DomainName existing = getDomainName(domainName);
associationStore.get(domainName).ifPresent(apiId -> assertSchemaNotBusy(apiId));
if (request.containsKey("description")) existing.setDescription((String) request.get("description"));
@@ -785,14 +795,14 @@ public class AppSyncService {
return existing;
}
public void deleteDomainName(String domainName) {
public synchronized void deleteDomainName(String domainName) {
getDomainName(domainName);
associationStore.get(domainName).ifPresent(apiId -> assertSchemaNotBusy(apiId));
associationStore.delete(domainName);
domainStore.delete(domainName);
}
public ApiAssociation associateApi(String domainName, String apiId) {
public synchronized ApiAssociation associateApi(String domainName, String apiId) {
getDomainName(domainName);
getGraphqlApi(apiId);
if (associationStore.get(domainName).isPresent()) {
@@ -820,7 +830,7 @@ public class AppSyncService {
return assoc;
}
public void disassociateApi(String domainName) {
public synchronized void disassociateApi(String domainName) {
getDomainName(domainName);
associationStore.get(domainName).ifPresent(apiId -> assertSchemaNotBusy(apiId));
associationStore.delete(domainName);
@@ -828,7 +838,7 @@ public class AppSyncService {
// ──────────────────────────── Channel Namespaces ────────────────────────────
public ChannelNamespace createChannelNamespace(String apiId, Map<String, Object> request) {
public synchronized ChannelNamespace createChannelNamespace(String apiId, Map<String, Object> request) {
assertSchemaNotBusy(apiId);
GraphqlApi api = getGraphqlApi(apiId);
String name = (String) request.get("name");
@@ -859,7 +869,7 @@ public class AppSyncService {
"Channel namespace not found: " + name, 404));
}
public ChannelNamespace updateChannelNamespace(String apiId, String name, Map<String, Object> request) {
public synchronized ChannelNamespace updateChannelNamespace(String apiId, String name, Map<String, Object> request) {
assertSchemaNotBusy(apiId);
ChannelNamespace existing = getChannelNamespace(apiId, name);
if (request.containsKey("description")) existing.setDescription((String) request.get("description"));
@@ -869,7 +879,7 @@ public class AppSyncService {
return existing;
}
public void deleteChannelNamespace(String apiId, String name) {
public synchronized void deleteChannelNamespace(String apiId, String name) {
assertSchemaNotBusy(apiId);
getChannelNamespace(apiId, name);
channelNamespaceStore.delete(apiKey(apiId, name));
@@ -881,7 +891,7 @@ public class AppSyncService {
// ──────────────────────────── Merged API Associations ─────────────────
public SourceApiAssociation createMergedApiAssociation(String sourceApiIdentifier, Map<String, Object> request, String region) {
public synchronized SourceApiAssociation createMergedApiAssociation(String sourceApiIdentifier, Map<String, Object> request, String region) {
getGraphqlApi(sourceApiIdentifier);
String mergedApiIdentifier = (String) request.getOrDefault("mergedApiIdentifier", request.get("mergedApiId"));
if (mergedApiIdentifier == null || mergedApiIdentifier.isBlank()) {
@@ -909,7 +919,7 @@ public class AppSyncService {
return assoc;
}
public SourceApiAssociation createSourceApiAssociation(String mergedApiIdentifier, Map<String, Object> request, String region) {
public synchronized SourceApiAssociation createSourceApiAssociation(String mergedApiIdentifier, Map<String, Object> request, String region) {
getGraphqlApi(mergedApiIdentifier);
String sourceApiId = (String) request.getOrDefault("sourceApiId", request.get("sourceApiIdentifier"));
if (sourceApiId == null || sourceApiId.isBlank()) {
@@ -948,7 +958,7 @@ public class AppSyncService {
return assoc;
}
public SourceApiAssociation updateSourceApiAssociation(String mergedApiIdentifier, String associationId,
public synchronized SourceApiAssociation updateSourceApiAssociation(String mergedApiIdentifier, String associationId,
Map<String, Object> request) {
assertSchemaNotBusy(mergedApiIdentifier);
SourceApiAssociation assoc = getSourceApiAssociation(mergedApiIdentifier, associationId);
@@ -979,7 +989,7 @@ public class AppSyncService {
return paginate(summaries, nextToken, maxResults);
}
public void deleteSourceApiAssociation(String mergedApiIdentifier, String associationId) {
public synchronized void deleteSourceApiAssociation(String mergedApiIdentifier, String associationId) {
assertSchemaNotBusy(mergedApiIdentifier);
getSourceApiAssociation(mergedApiIdentifier, associationId);
mergedApiAssociationStore.delete(associationId);
@@ -997,7 +1007,7 @@ public class AppSyncService {
}
}
public SourceApiAssociation deleteMergedApiAssociation(String sourceApiIdentifier, String associationId) {
public synchronized SourceApiAssociation deleteMergedApiAssociation(String sourceApiIdentifier, String associationId) {
assertSchemaNotBusy(sourceApiIdentifier);
SourceApiAssociation assoc = mergedApiAssociationStore.get(associationId)
.orElseThrow(() -> new AwsException("NotFoundException",
@@ -1105,6 +1115,15 @@ public class AppSyncService {
};
}
/**
* An update is applied to a copy and stored only once every member has been read and checked,
* so a request the service refuses leaves the stored entity untouched. The stores hand out
* their own instances, which a half-applied update would otherwise have changed in place.
*/
private <T> T copyOf(T entity, Class<T> type) {
return objectMapper.convertValue(entity, type);
}
private long parseExpires(Object expiresValue) {
if (expiresValue instanceof Long l) {
return l;
@@ -1246,11 +1265,23 @@ public class AppSyncService {
private GraphqlApi refreshGraphqlApiUris(GraphqlApi api) {
Map<String, String> expectedUris = graphqlApiUris(api.getApiId());
if (!expectedUris.equals(api.getUris())) {
api.setUris(expectedUris);
apiStore.put(api.getApiId(), api);
if (expectedUris.equals(api.getUris())) {
return api;
}
synchronized (this) {
// Refresh what is stored now, never the instance read before the lock: a concurrent
// update may have saved a newer one in between.
GraphqlApi current = apiStore.get(api.getApiId()).orElse(null);
if (current == null) {
api.setUris(expectedUris);
return api;
}
if (!expectedUris.equals(current.getUris())) {
current.setUris(expectedUris);
apiStore.put(current.getApiId(), current);
}
return current;
}
return api;
}
private Integer castInt(Object value) {
@@ -1,6 +1,9 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.appsync.AppSyncService;
@@ -24,8 +27,11 @@ import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Provisions the AppSync resource types a GraphQL API is deployed from: the API itself, its schema,
@@ -57,11 +63,20 @@ import java.util.function.Consumer;
* <p><b>Inline definitions only.</b> {@code DefinitionS3Location} and {@code CodeS3Location} are
* refused with a clear message rather than silently producing an API with an empty schema or a
* resolver with no code. Serverless Framework and the AppSync plugins inline both.
*
* <p><b>An in-place update is undone from a snapshot.</b> Before the update call of an API, data
* source, function, resolver or API key, the members the update can change or clear are read back
* from the service and kept on the resource ({@link CfnRollback#APPSYNC_UPDATE_SNAPSHOT_ATTR}).
* The service applies an update member by {@code containsKey}, so replaying every recorded member,
* an old value or an explicit null, puts back what the update changed and what it cleared. A
* stack update that fails afterwards, or the update call itself failing part way, restores it.
*/
@ApplicationScoped
public class AppSyncCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(AppSyncCfnProvisioner.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final TypeReference<Map<String, Object>> OBJECT_MAP = new TypeReference<>() { };
private static final String GRAPHQL_API = "AWS::AppSync::GraphQLApi";
private static final String GRAPHQL_SCHEMA = "AWS::AppSync::GraphQLSchema";
@@ -115,6 +130,29 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner {
FUNCTION_CONFIGURATION, Map.of("FunctionVersion", "2018-05-29"),
RESOLVER, Map.of("Kind", "UNIT"));
/**
* The members an update of each type can change or clear, which a snapshot records and a
* restore replays. A GraphQL API's {@code apiType} and {@code visibility} are here because a
* template that changes them reaches the update request, which applies both. An API key's
* {@code expires} joins when the update sends it.
*/
private static final Map<String, List<String>> ROLLBACK_MEMBERS = Map.of(
GRAPHQL_API, List.of("name", "authenticationType", "apiType", "visibility", "xrayEnabled",
"logConfig", "additionalAuthenticationProviders", "tags", "owner", "ownerContact",
"introspectionConfig", "queryDepthLimit", "resolverCountLimit",
"enhancedMetricsConfig", "lambdaAuthorizerConfig", "openIDConnectConfig",
"userPoolConfig", "dns", "wafWebAclArn", "mergedApiExecutionRoleArn"),
DATA_SOURCE, List.of("description", "type", "serviceRoleArn", "dynamodbConfig",
"lambdaConfig", "httpConfig", "eventBridgeConfig", "relationalDatabaseConfig",
"openSearchServiceConfig", "amazonBedrockRuntimeConfig"),
FUNCTION_CONFIGURATION, List.of("name", "description", "dataSourceName",
"requestMappingTemplate", "responseMappingTemplate", "functionVersion", "code",
"runtime", "maxBatchSize"),
RESOLVER, List.of("dataSourceName", "functionId", "requestMappingTemplate",
"responseMappingTemplate", "kind", "code", "runtime", "cachingConfig",
"maxBatchSize", "metricsConfig", "pipelineConfig", "syncConfig"),
API_KEY, List.of("description"));
/**
* How long a stack resource waits for a schema to compile. Generous: the wait is bounded only so
* a wedged worker cannot hang a stack operation forever, and a schema that hits this is reported
@@ -137,6 +175,8 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner {
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
// A snapshot describes the update in flight; one an earlier update left behind is stale.
r.getAttributes().remove(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR);
switch (r.getResourceType()) {
case GRAPHQL_API -> provisionGraphqlApi(r, props, ctx);
case GRAPHQL_SCHEMA -> provisionSchema(r, props, ctx);
@@ -173,19 +213,29 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner {
clearDropped(req, props, ctx, GRAPHQL_API);
}
GraphqlApi api = ctx.isUpdate()
? appSyncService.updateGraphqlApi(ctx.priorPhysicalId(), req, ctx.region())
: appSyncService.createGraphqlApi(req, ctx.region());
Map<String, String> resolvedEnvironment = stringMap(environmentVariables);
if (resolvedEnvironment == null && ctx.isUpdate()) {
// The property was dropped from the template. The call replaces the whole set, so an
// empty map is what clears it; skipping the call left the old variables readable by
// every resolver.
resolvedEnvironment = Map.of();
}
if (resolvedEnvironment != null) {
appSyncService.putEnvironmentVariables(api.getApiId(), resolvedEnvironment);
Map<String, String> templateEnvironment = stringMap(environmentVariables);
// The property was dropped from the template. The call replaces the whole set, so an
// empty map is what clears it; skipping the call left the old variables readable by
// every resolver.
Map<String, String> resolvedEnvironment = templateEnvironment == null && ctx.isUpdate()
? Map.of() : templateEnvironment;
GraphqlApi api;
if (ctx.isUpdate()) {
String priorApiId = ctx.priorPhysicalId();
snapshotBeforeUpdate(r, ctx, appSyncService.getGraphqlApi(priorApiId),
Map.of("apiId", priorApiId), req, appSyncService.getEnvironmentVariables(priorApiId));
api = updateInPlace(r, ctx, () -> {
GraphqlApi updated = appSyncService.updateGraphqlApi(priorApiId, req, ctx.region());
if (resolvedEnvironment != null) {
appSyncService.putEnvironmentVariables(updated.getApiId(), resolvedEnvironment);
}
return updated;
});
} else {
api = appSyncService.createGraphqlApi(req, ctx.region());
if (resolvedEnvironment != null) {
appSyncService.putEnvironmentVariables(api.getApiId(), resolvedEnvironment);
}
}
r.setPhysicalId(api.getApiId());
@@ -284,12 +334,16 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner {
}
boolean update = reusesEntity(r, ctx, apiId) && name.equals(attribute(r, "Name"));
DataSource ds;
if (update) {
clearDropped(req, props, ctx, DATA_SOURCE);
String dataSourceName = name;
snapshotBeforeUpdate(r, ctx, appSyncService.getDataSource(apiId, dataSourceName),
Map.of("apiId", apiId, "name", dataSourceName), req, null);
ds = updateInPlace(r, ctx, () -> appSyncService.updateDataSource(apiId, dataSourceName, req));
} else {
ds = appSyncService.createDataSource(apiId, req, ctx.region());
}
DataSource ds = update
? appSyncService.updateDataSource(apiId, name, req)
: appSyncService.createDataSource(apiId, req, ctx.region());
r.setPhysicalId(ds.getDataSourceArn());
r.getAttributes().put("DataSourceArn", ds.getDataSourceArn());
@@ -310,12 +364,15 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner {
String priorFunctionId = attribute(r, "FunctionId");
boolean update = reusesEntity(r, ctx, apiId) && !blank(priorFunctionId);
FunctionConfiguration fn;
if (update) {
clearDropped(req, props, ctx, FUNCTION_CONFIGURATION);
snapshotBeforeUpdate(r, ctx, appSyncService.getFunction(apiId, priorFunctionId),
Map.of("apiId", apiId, "functionId", priorFunctionId), req, null);
fn = updateInPlace(r, ctx, () -> appSyncService.updateFunction(apiId, priorFunctionId, req));
} else {
fn = appSyncService.createFunction(apiId, req, ctx.region());
}
FunctionConfiguration fn = update
? appSyncService.updateFunction(apiId, priorFunctionId, req)
: appSyncService.createFunction(apiId, req, ctx.region());
r.setPhysicalId(fn.getFunctionArn());
r.getAttributes().put("FunctionArn", fn.getFunctionArn());
@@ -343,6 +400,7 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner {
boolean sameField = typeName.equals(attribute(r, "TypeName"))
&& fieldName.equals(attribute(r, "FieldName"));
boolean update = reusesEntity(r, ctx, apiId) && sameField;
Resolver resolver;
if (update) {
clearDropped(req, props, ctx, RESOLVER);
// A UNIT resolver needs its data source (createResolver refuses none): clear it only on a pipeline.
@@ -350,10 +408,13 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner {
&& isPipeline(req, apiId, typeName, fieldName)) {
req.put("dataSourceName", null);
}
snapshotBeforeUpdate(r, ctx, appSyncService.getResolver(apiId, typeName, fieldName),
Map.of("apiId", apiId, "typeName", typeName, "fieldName", fieldName), req, null);
resolver = updateInPlace(r, ctx,
() -> appSyncService.updateResolver(apiId, typeName, fieldName, req));
} else {
resolver = appSyncService.createResolver(apiId, req, ctx.region());
}
Resolver resolver = update
? appSyncService.updateResolver(apiId, typeName, fieldName, req)
: appSyncService.createResolver(apiId, req, ctx.region());
r.setPhysicalId(resolver.getResolverArn());
r.getAttributes().put("ResolverArn", resolver.getResolverArn());
@@ -369,12 +430,16 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner {
String apiId = requiredApiId(req, API_KEY);
boolean update = reusesEntity(r, ctx, apiId);
ApiKey key;
if (update) {
clearDropped(req, props, ctx, API_KEY);
String priorKeyId = ctx.priorPhysicalId();
snapshotBeforeUpdate(r, ctx, appSyncService.getApiKey(apiId, priorKeyId),
Map.of("apiId", apiId, "keyId", priorKeyId), req, null);
key = updateInPlace(r, ctx, () -> appSyncService.updateApiKey(apiId, priorKeyId, req));
} else {
key = appSyncService.createApiKey(apiId, req);
}
ApiKey key = update
? appSyncService.updateApiKey(apiId, ctx.priorPhysicalId(), req)
: appSyncService.createApiKey(apiId, req);
r.setPhysicalId(key.getId());
// On AWS the key id and the key value are the same string (the da2-… secret), and both
@@ -386,6 +451,148 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("ApiId", apiId);
}
// ── Rollback ─────────────────────────────────────────────────────────────
/**
* Puts an entity this update changed in place back to the members it had before, and answers
* false for one it did not: a resource the failed update created is deleted by the engine, and
* a replacement leaves no snapshot. The snapshot is spent only once the restore succeeded, so
* a restore that throws keeps it for the next attempt.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
if (!resource.getAttributes().containsKey(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR)) {
return false;
}
restoreSnapshot(resource);
return true;
}
/**
* Keeps the snapshot of an in-place update whose own undo did not complete. The engine restores
* the previous resource and reports the rollback failure once; with the snapshot of the state
* the update started from, a ContinueUpdateRollback restores that state.
*/
@Override
public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
String snapshot = attempted.getAttributes().get(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR);
if (snapshot != null && attempted.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)) {
previous.getAttributes().put(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR, snapshot);
}
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR);
return UpdateCleanupResult.notApplicable();
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR);
}
/**
* Runs an in-place update so that a failure inside it, the call or a step after it, puts the
* entity back from the snapshot before the failure propagates. The engine discards the
* attempted resource, snapshot included, when the resource itself fails.
*/
private <T> T updateInPlace(StackResource r, ProvisionContext ctx, Supplier<T> update) {
AtomicReference<T> updated = new AtomicReference<>();
CfnRollback.guarded(r, ctx, false, () -> { }, () -> restoreSnapshot(r),
() -> updated.set(update.get()));
return updated.get();
}
/**
* Records what the entity looks like now, before the update call about to change it. The
* service's getters throw NotFound for an entity that is gone, so the null guard only covers a
* service that answers with nothing, as the mocked one in the unit tests does; the update then
* runs without a snapshot. A member the entity does not carry is recorded as null, which the
* restore sends as a clear. {@code environment} is a GraphQL API's variables, which have a
* call of their own.
*/
private void snapshotBeforeUpdate(StackResource r, ProvisionContext ctx, Object current,
Map<String, String> identity, Map<String, Object> request,
Map<String, String> environment) {
if (current == null) {
return;
}
Map<String, Object> entity = MAPPER.convertValue(current, OBJECT_MAP);
Map<String, Object> members = new LinkedHashMap<>();
for (String member : ROLLBACK_MEMBERS.get(r.getResourceType())) {
members.put(member, entity.get(member));
}
if (API_KEY.equals(r.getResourceType()) && request.containsKey("expires")) {
members.put("expires", entity.get("expires"));
}
Map<String, Object> snapshot = new LinkedHashMap<>();
snapshot.put("region", ctx.region());
snapshot.putAll(identity);
snapshot.put("members", members);
if (environment != null) {
snapshot.put("environmentVariables", environment);
}
try {
r.getAttributes().put(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR, MAPPER.writeValueAsString(snapshot));
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not record the AppSync update snapshot for "
+ r.getLogicalId(), e);
}
}
/**
* Replays the snapshot through the update call that changed the entity, if the resource carries
* one, and spends it. A GraphQL API's {@code xrayEnabled}, {@code additionalAuthenticationProviders}
* and tags are not cleared by a null, so an API that had none gets {@code false}, an empty list
* and an empty map back.
*/
@SuppressWarnings("unchecked")
private void restoreSnapshot(StackResource r) {
JsonNode node = CfnRollback.updateSnapshot(r, CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR);
if (node == null) {
return;
}
Map<String, Object> snapshot = MAPPER.convertValue(node, OBJECT_MAP);
Map<String, Object> members = (Map<String, Object>) snapshot.get("members");
String apiId = str(snapshot.get("apiId"));
switch (r.getResourceType()) {
case GRAPHQL_API -> {
members.computeIfAbsent("xrayEnabled", name -> false);
members.computeIfAbsent("additionalAuthenticationProviders", name -> List.of());
members.computeIfAbsent("tags", name -> Map.of());
appSyncService.updateGraphqlApi(apiId, members, str(snapshot.get("region")));
appSyncService.putEnvironmentVariables(apiId, stringMap(snapshot.get("environmentVariables")));
}
case DATA_SOURCE -> appSyncService.updateDataSource(apiId, str(snapshot.get("name")), members);
case FUNCTION_CONFIGURATION -> {
appSyncService.updateFunction(apiId, str(snapshot.get("functionId")), members);
r.getAttributes().put("Name", str(members.get("name")));
if (blank(str(members.get("dataSourceName")))) {
r.getAttributes().remove("DataSourceName");
} else {
r.getAttributes().put("DataSourceName", str(members.get("dataSourceName")));
}
}
case RESOLVER -> appSyncService.updateResolver(apiId, str(snapshot.get("typeName")),
str(snapshot.get("fieldName")), members);
case API_KEY -> {
String keyId = str(snapshot.get("keyId"));
// The service refuses an expiry inside the next day, so one that has not moved is
// not sent again.
Object expires = members.get("expires");
if (expires instanceof Number prior
&& Objects.equals(prior.longValue(), appSyncService.getApiKey(apiId, keyId).getExpires())) {
members.remove("expires");
}
appSyncService.updateApiKey(apiId, keyId, members);
}
default -> throw new IllegalStateException(
"AppSyncCfnProvisioner cannot restore " + r.getResourceType());
}
r.getAttributes().remove(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR);
}
// ── Deletes ──────────────────────────────────────────────────────────────
/**
@@ -219,6 +219,16 @@ public final class CfnRollback {
*/
public static final String APPCONFIG_UPDATE_SNAPSHOT_ATTR = "__FlociAppConfigUpdateSnapshot";
/**
* Holds the members an AppSync GraphQL API, data source, function, resolver or API key carried
* before an in-place update changed or cleared them, in the request shape its update call takes,
* with the identifiers that address it, so a failed stack update can put them back. Written by
* {@code AppSyncCfnProvisioner} before its update call and spent by its {@code rollbackUpdate};
* when its own undo did not complete, the provisioner carries it onto the restored resource
* through {@code mergeFailedUpdateResourceTracking}.
*/
public static final String APPSYNC_UPDATE_SNAPSHOT_ATTR = "__FlociAppSyncUpdateSnapshot";
/**
* Holds the name and tags an API Gateway V2 VPC link carried before an in-place update changed
* them, so a failed stack update can put them back. Written by {@code ApiGatewayV2CfnProvisioner}