mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
e0b8da1b6c
commit
0c3af7dc4b
8 files changed
+1292
-139
No files matched your search
@@ -0,0 +1,97 @@
|
||||
package io.github.hectorvent.floci.services.appsync;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker;
|
||||
import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry;
|
||||
import io.github.hectorvent.floci.services.appsync.graphql.auth.LambdaAuthorizerCache;
|
||||
import io.github.hectorvent.floci.services.appsync.model.ApiKey;
|
||||
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
|
||||
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.mockito.Answers.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** A real {@link AppSyncService} over in-memory storage, shared by the tests that need one. */
|
||||
public final class AppSyncServiceFixture {
|
||||
|
||||
private AppSyncServiceFixture() {
|
||||
}
|
||||
|
||||
public static AppSyncService create(Clock clock) {
|
||||
return create(clock, "http://localhost:4566", "us-east-1", null,
|
||||
AccountAwareStorageBackend.inMemory("000000000000"), null,
|
||||
mock(SchemaRegistry.class), new LambdaAuthorizerCache());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param partition the deployment partition, or null to derive it from {@code region}
|
||||
* @param apiKeyStore the store for API keys, or null for a fresh in-memory one
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static AppSyncService create(Clock clock, String baseUrl, String region, String partition,
|
||||
AccountAwareStorageBackend<GraphqlApi> apiStore, AccountAwareStorageBackend<ApiKey> apiKeyStore,
|
||||
SchemaRegistry schemaRegistry, LambdaAuthorizerCache lambdaAuthorizerCache) {
|
||||
InMemoryStorageFactory storageFactory = new InMemoryStorageFactory("000000000000")
|
||||
.withStore("appsync-apis.json", apiStore);
|
||||
if (apiKeyStore != null) {
|
||||
storageFactory.withStore("appsync-apikeys.json", apiKeyStore);
|
||||
}
|
||||
Instance<RequestContext> requestContext = mock(Instance.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.effectiveBaseUrl()).thenReturn(baseUrl);
|
||||
when(config.services().cloudfront().domainSuffix()).thenReturn(Optional.empty());
|
||||
return new AppSyncService(
|
||||
storageFactory,
|
||||
config,
|
||||
partition == null ? new RegionResolver(region, "000000000000")
|
||||
: new RegionResolver(region, "000000000000", partition),
|
||||
schemaRegistry,
|
||||
mock(SchemaCreationWorker.class),
|
||||
requestContext,
|
||||
new ObjectMapper(),
|
||||
AccountAwareStorageBackend.inMemory("000000000000"),
|
||||
AccountAwareStorageBackend.inMemory("000000000000"),
|
||||
clock,
|
||||
lambdaAuthorizerCache);
|
||||
}
|
||||
|
||||
/** A clock a test moves by hand. */
|
||||
public static final class MutableClock extends Clock {
|
||||
private Instant instant;
|
||||
|
||||
public MutableClock(Instant instant) {
|
||||
this.instant = instant;
|
||||
}
|
||||
|
||||
public void set(Instant instant) {
|
||||
this.instant = instant;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ZoneId getZone() {
|
||||
return ZoneOffset.UTC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Clock withZone(ZoneId zone) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant instant() {
|
||||
return instant;
|
||||
}
|
||||
}
|
||||
}
|
||||
+244
-63
@@ -1,12 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.appsync;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker;
|
||||
import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry;
|
||||
import io.github.hectorvent.floci.services.appsync.graphql.auth.LambdaAuthorizerCache;
|
||||
import io.github.hectorvent.floci.services.appsync.graphql.auth.LambdaAuthorizerResult;
|
||||
@@ -15,9 +10,8 @@ import io.github.hectorvent.floci.services.appsync.model.AuthenticationType;
|
||||
import io.github.hectorvent.floci.services.appsync.model.DomainName;
|
||||
import io.github.hectorvent.floci.services.appsync.model.FunctionConfiguration;
|
||||
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
|
||||
import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatus;
|
||||
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatusType;
|
||||
import io.github.hectorvent.floci.testing.ParkingStore;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -26,18 +20,24 @@ import org.junit.jupiter.params.provider.CsvSource;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Answers.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -152,7 +152,7 @@ class AppSyncServiceTest {
|
||||
|
||||
@Test
|
||||
void validateApiKeyExpiresAtBoundaryFails() {
|
||||
MutableClock clock = new MutableClock(NOW);
|
||||
AppSyncServiceFixture.MutableClock clock = new AppSyncServiceFixture.MutableClock(NOW);
|
||||
AppSyncService svc = newService(clock);
|
||||
GraphqlApi api = svc.createGraphqlApi(Map.of("name", "b", "authenticationType", "API_KEY"), "us-east-1");
|
||||
long expires = NOW.getEpochSecond() + Duration.ofDays(1).getSeconds();
|
||||
@@ -193,6 +193,89 @@ class AppSyncServiceTest {
|
||||
assertEquals("ApiKeyValidityOutOfBoundsException", tooFar.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedApiKeyUpdateLeavesTheDescriptionAsItWas() {
|
||||
GraphqlApi api = service.createGraphqlApi(Map.of("name", "refuse-key", "authenticationType", "API_KEY"), "us-east-1");
|
||||
ApiKey created = service.createApiKey(api.getApiId(), Map.of("description", "kept"));
|
||||
long expires = created.getExpires();
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> service.updateApiKey(api.getApiId(),
|
||||
created.getId(), Map.of("description", "changed", "expires", NOW.getEpochSecond())));
|
||||
|
||||
assertEquals("ApiKeyValidityOutOfBoundsException", refused.getErrorCode());
|
||||
ApiKey stored = service.getApiKey(api.getApiId(), created.getId());
|
||||
assertEquals("kept", stored.getDescription());
|
||||
assertEquals(expires, stored.getExpires());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedApiKeyDescriptionLeavesTheExpiryAsItWas() {
|
||||
GraphqlApi api = service.createGraphqlApi(Map.of("name", "refuse-desc", "authenticationType", "API_KEY"), "us-east-1");
|
||||
long original = NOW.getEpochSecond() + Duration.ofDays(10).getSeconds();
|
||||
ApiKey created = service.createApiKey(api.getApiId(), Map.of("description", "kept", "expires", original));
|
||||
ApiKey before = service.getApiKey(api.getApiId(), created.getId());
|
||||
Long expiresBefore = before.getExpires();
|
||||
Long deletesBefore = before.getDeletes();
|
||||
long newExpires = NOW.getEpochSecond() + Duration.ofDays(30).getSeconds();
|
||||
|
||||
assertThrows(RuntimeException.class, () -> service.updateApiKey(api.getApiId(), created.getId(),
|
||||
Map.of("expires", newExpires, "description", 42)));
|
||||
|
||||
ApiKey stored = service.getApiKey(api.getApiId(), created.getId());
|
||||
assertEquals(expiresBefore, stored.getExpires());
|
||||
assertEquals(deletesBefore, stored.getDeletes());
|
||||
assertEquals("kept", stored.getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedDataSourceUpdateLeavesTheDescriptionAsItWas() {
|
||||
GraphqlApi api = service.createGraphqlApi(Map.of("name", "refuse-ds", "authenticationType", "API_KEY"), "us-east-1");
|
||||
service.createDataSource(api.getApiId(), Map.of("name", "ds", "type", "NONE", "description", "kept"), "us-east-1");
|
||||
|
||||
assertThrows(AwsException.class, () -> service.updateDataSource(api.getApiId(), "ds",
|
||||
Map.of("description", "changed", "type", "NOT_A_TYPE")));
|
||||
|
||||
assertEquals("kept", service.getDataSource(api.getApiId(), "ds").getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedFunctionUpdateLeavesTheNameAsItWas() {
|
||||
GraphqlApi api = service.createGraphqlApi(Map.of("name", "refuse-fn", "authenticationType", "API_KEY"), "us-east-1");
|
||||
FunctionConfiguration created = service.createFunction(api.getApiId(), Map.of("name", "kept"), "us-east-1");
|
||||
|
||||
assertThrows(AwsException.class, () -> service.updateFunction(api.getApiId(), created.getFunctionId(),
|
||||
Map.of("name", "changed", "runtime", Map.of("name", "NOT_A_RUNTIME"))));
|
||||
|
||||
assertEquals("kept", service.getFunction(api.getApiId(), created.getFunctionId()).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedResolverUpdateLeavesTheDataSourceAsItWas() {
|
||||
GraphqlApi api = service.createGraphqlApi(Map.of("name", "refuse-rs", "authenticationType", "API_KEY"), "us-east-1");
|
||||
service.createDataSource(api.getApiId(), Map.of("name", "ds", "type", "NONE"), "us-east-1");
|
||||
service.createResolver(api.getApiId(), Map.of("typeName", "Query", "fieldName", "hello",
|
||||
"dataSourceName", "ds"), "us-east-1");
|
||||
|
||||
assertThrows(AwsException.class, () -> service.updateResolver(api.getApiId(), "Query", "hello",
|
||||
Map.of("dataSourceName", "other", "kind", "NOT_A_KIND")));
|
||||
|
||||
assertEquals("ds", service.getResolver(api.getApiId(), "Query", "hello").getDataSourceName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedGraphqlApiUpdateLeavesTheNameAsItWas() {
|
||||
GraphqlApi api = service.createGraphqlApi(Map.of("name", "kept", "authenticationType", "API_KEY"), "us-east-1");
|
||||
Map<String, Object> pool = Map.of("userPoolId", "pool-1", "awsRegion", "us-east-1");
|
||||
Map<String, Object> provider = Map.of("authenticationType", "AMAZON_COGNITO_USER_POOLS",
|
||||
"userPoolConfig", pool);
|
||||
|
||||
assertThrows(AwsException.class, () -> service.updateGraphqlApi(api.getApiId(),
|
||||
Map.of("name", "changed", "additionalAuthenticationProviders", List.of(provider, provider)),
|
||||
"us-east-1"));
|
||||
|
||||
assertEquals("kept", service.getGraphqlApi(api.getApiId()).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateApiKeyWrongApiFails() {
|
||||
GraphqlApi a = service.createGraphqlApi(Map.of("name", "c", "authenticationType", "API_KEY"), "us-east-1");
|
||||
@@ -364,7 +447,9 @@ class AppSyncServiceTest {
|
||||
apiId, Map.of("name", "updated-api"), "us-east-1");
|
||||
assertEquals("updated-api", updated.getName());
|
||||
assertEquals(expectedUris, updated.getUris());
|
||||
verify(apiStore, times(2)).put(apiId, api);
|
||||
// The URI repair on read stores the persisted instance; the update then stores its own copy.
|
||||
verify(apiStore).put(apiId, api);
|
||||
verify(apiStore, times(2)).put(eq(apiId), any(GraphqlApi.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -408,60 +493,12 @@ class AppSyncServiceTest {
|
||||
return newService(clock, baseUrl, AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private AppSyncService newService(Clock clock, String baseUrl,
|
||||
AccountAwareStorageBackend<GraphqlApi> apiStore) {
|
||||
InMemoryStorageFactory storageFactory = new InMemoryStorageFactory("000000000000")
|
||||
.withStore("appsync-apis.json", apiStore);
|
||||
if (apiKeyStoreOverride != null) {
|
||||
storageFactory.withStore("appsync-apikeys.json", apiKeyStoreOverride);
|
||||
}
|
||||
Instance<RequestContext> requestContext = mock(Instance.class);
|
||||
schemaRegistry = mock(SchemaRegistry.class);
|
||||
lambdaAuthorizerCache = new LambdaAuthorizerCache();
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.effectiveBaseUrl()).thenReturn(baseUrl);
|
||||
when(config.services().cloudfront().domainSuffix()).thenReturn(Optional.empty());
|
||||
return new AppSyncService(
|
||||
storageFactory,
|
||||
config,
|
||||
partition == null ? new RegionResolver(region, "000000000000")
|
||||
: new RegionResolver(region, "000000000000", partition),
|
||||
schemaRegistry,
|
||||
mock(SchemaCreationWorker.class),
|
||||
requestContext,
|
||||
new ObjectMapper(),
|
||||
AccountAwareStorageBackend.inMemory("000000000000"),
|
||||
AccountAwareStorageBackend.inMemory("000000000000"),
|
||||
clock,
|
||||
lambdaAuthorizerCache);
|
||||
}
|
||||
|
||||
private static final class MutableClock extends Clock {
|
||||
private Instant instant;
|
||||
|
||||
private MutableClock(Instant instant) {
|
||||
this.instant = instant;
|
||||
}
|
||||
|
||||
void set(Instant instant) {
|
||||
this.instant = instant;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ZoneId getZone() {
|
||||
return ZoneOffset.UTC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Clock withZone(ZoneId zone) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant instant() {
|
||||
return instant;
|
||||
}
|
||||
return AppSyncServiceFixture.create(clock, baseUrl, region, partition, apiStore,
|
||||
apiKeyStoreOverride, schemaRegistry, lambdaAuthorizerCache);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -524,4 +561,148 @@ class AppSyncServiceTest {
|
||||
assertThrows(AwsException.class, () -> service.tagResource("apis/abc", Map.of()));
|
||||
assertThrows(AwsException.class, () -> service.tagResource(null, Map.of()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Parks {@code first} in its next write to {@code store}, starts {@code second} on another
|
||||
* thread, waits until it is blocked behind the first or done, then lets the first go and waits
|
||||
* for both. The second can only be blocked if a lock covers the first's read, change and write;
|
||||
* the callers assert the final state.
|
||||
*/
|
||||
private static void secondWriterRunsAroundTheFirst(ParkingStore<?> store, Runnable first, Runnable second)
|
||||
throws Exception {
|
||||
secondCallRunsAroundTheFirst(store, store::parkNextWrite, first, second);
|
||||
}
|
||||
|
||||
/** As above, with the caller choosing which store call of the first one is parked. */
|
||||
private static void secondCallRunsAroundTheFirst(ParkingStore<?> store, Runnable arm, Runnable first,
|
||||
Runnable second) throws Exception {
|
||||
arm.run();
|
||||
ExecutorService pool = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<?> firstWrite = pool.submit(first);
|
||||
assertTrue(store.awaitParked(), "the first write must reach the store");
|
||||
AtomicReference<Thread> secondThread = new AtomicReference<>();
|
||||
Future<?> secondWrite = pool.submit(() -> {
|
||||
secondThread.set(Thread.currentThread());
|
||||
second.run();
|
||||
});
|
||||
awaitBlockedOrDone(secondThread, secondWrite);
|
||||
|
||||
store.release();
|
||||
firstWrite.get(2, TimeUnit.SECONDS);
|
||||
secondWrite.get(2, TimeUnit.SECONDS);
|
||||
} catch (ExecutionException e) {
|
||||
throw new AssertionError(e.getCause());
|
||||
} finally {
|
||||
store.release();
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
private AppSyncService serviceWithApiStore(ParkingStore<GraphqlApi> apiStore) {
|
||||
return newService(Clock.fixed(NOW, ZoneOffset.UTC), "http://localhost:4566",
|
||||
new AccountAwareStorageBackend<>(apiStore, null, "000000000000"));
|
||||
}
|
||||
|
||||
private static String arnOf(GraphqlApi api) {
|
||||
return "arn:aws:appsync:us-east-1:000000000000:apis/" + api.getApiId();
|
||||
}
|
||||
|
||||
private static Map<String, Object> apiRequest(String name) {
|
||||
return Map.of("name", name, "authenticationType", "API_KEY");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTagDuringAnApiUpdateSurvivesTheUpdate() throws Exception {
|
||||
ParkingStore<GraphqlApi> store = new ParkingStore<>();
|
||||
AppSyncService svc = serviceWithApiStore(store);
|
||||
GraphqlApi api = svc.createGraphqlApi(apiRequest("before"), "us-east-1");
|
||||
|
||||
secondWriterRunsAroundTheFirst(store,
|
||||
() -> svc.updateGraphqlApi(api.getApiId(), apiRequest("after"), "us-east-1"),
|
||||
() -> svc.tagResource(arnOf(api), Map.of("env", "test")));
|
||||
|
||||
assertEquals("after", svc.getGraphqlApi(api.getApiId()).getName());
|
||||
assertEquals("test", svc.getTags(arnOf(api)).get("env"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUntagDuringAnApiUpdateStaysRemoved() throws Exception {
|
||||
ParkingStore<GraphqlApi> store = new ParkingStore<>();
|
||||
AppSyncService svc = serviceWithApiStore(store);
|
||||
GraphqlApi api = svc.createGraphqlApi(apiRequest("before"), "us-east-1");
|
||||
svc.tagResource(arnOf(api), Map.of("drop", "1", "keep", "2"));
|
||||
|
||||
secondWriterRunsAroundTheFirst(store,
|
||||
() -> svc.updateGraphqlApi(api.getApiId(), apiRequest("after"), "us-east-1"),
|
||||
() -> svc.untagResource(arnOf(api), List.of("drop")));
|
||||
|
||||
assertEquals("after", svc.getGraphqlApi(api.getApiId()).getName());
|
||||
assertFalse(svc.getTags(arnOf(api)).containsKey("drop"), svc.getTags(arnOf(api)).toString());
|
||||
assertEquals("2", svc.getTags(arnOf(api)).get("keep"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void environmentVariablesWrittenDuringAnApiUpdateSurviveTheUpdate() throws Exception {
|
||||
ParkingStore<GraphqlApi> store = new ParkingStore<>();
|
||||
AppSyncService svc = serviceWithApiStore(store);
|
||||
GraphqlApi api = svc.createGraphqlApi(apiRequest("before"), "us-east-1");
|
||||
|
||||
secondWriterRunsAroundTheFirst(store,
|
||||
() -> svc.updateGraphqlApi(api.getApiId(), apiRequest("after"), "us-east-1"),
|
||||
() -> svc.putEnvironmentVariables(api.getApiId(), Map.of("TABLE_NAME", "my-table")));
|
||||
|
||||
assertEquals("after", svc.getGraphqlApi(api.getApiId()).getName());
|
||||
assertEquals("my-table", svc.getEnvironmentVariables(api.getApiId()).get("TABLE_NAME"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoUpdatesOfDifferentApiKeyMembersBothLand() throws Exception {
|
||||
ParkingStore<ApiKey> keyStore = new ParkingStore<>();
|
||||
apiKeyStoreOverride = new AccountAwareStorageBackend<>(keyStore, null, "000000000000");
|
||||
AppSyncService svc = newService(Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
GraphqlApi api = svc.createGraphqlApi(apiRequest("keys"), "us-east-1");
|
||||
ApiKey created = svc.createApiKey(api.getApiId(), Map.of());
|
||||
long expires = NOW.plus(Duration.ofDays(30)).getEpochSecond();
|
||||
|
||||
secondWriterRunsAroundTheFirst(keyStore,
|
||||
() -> svc.updateApiKey(api.getApiId(), created.getId(), Map.of("description", "renewed")),
|
||||
() -> svc.updateApiKey(api.getApiId(), created.getId(), Map.of("expires", expires)));
|
||||
|
||||
ApiKey result = svc.getApiKey(api.getApiId(), created.getId());
|
||||
assertEquals("renewed", result.getDescription());
|
||||
assertEquals(expires, result.getExpires());
|
||||
}
|
||||
|
||||
/**
|
||||
* StartSchemaCreation checks the API and writes its PROCESSING status as one step under the
|
||||
* service monitor that DeleteGraphqlApi holds, so a delete arriving between the two waits. It
|
||||
* then finds the schema busy and is refused with a 409, leaving the API and its PROCESSING
|
||||
* status in place. Without the shared hold the delete would succeed and leave a PROCESSING
|
||||
* status for a deleted API. The schema creation worker is the fixture's mock, so the status
|
||||
* stays PROCESSING.
|
||||
*/
|
||||
@Test
|
||||
void anApiDeleteDuringSchemaStartIsRefusedAndKeepsTheApi() throws Exception {
|
||||
ParkingStore<GraphqlApi> store = new ParkingStore<>();
|
||||
AppSyncService svc = serviceWithApiStore(store);
|
||||
GraphqlApi api = svc.createGraphqlApi(apiRequest("kept"), "us-east-1");
|
||||
AtomicReference<Throwable> deleteFailure = new AtomicReference<>();
|
||||
|
||||
secondCallRunsAroundTheFirst(store, store::parkNextRead,
|
||||
() -> svc.startSchemaCreation(api.getApiId(), "type Query { a: String }"),
|
||||
() -> {
|
||||
try {
|
||||
svc.deleteGraphqlApi(api.getApiId());
|
||||
} catch (AwsException e) {
|
||||
deleteFailure.set(e);
|
||||
}
|
||||
});
|
||||
|
||||
assertTrue(deleteFailure.get() instanceof AwsException, "the delete must be refused: " + deleteFailure.get());
|
||||
assertEquals(409, ((AwsException) deleteFailure.get()).getHttpStatus());
|
||||
assertEquals("kept", svc.getGraphqlApi(api.getApiId()).getName());
|
||||
assertEquals(SchemaCreationStatusType.PROCESSING,
|
||||
svc.getSchemaCreationStatus(api.getApiId()).getStatus());
|
||||
}
|
||||
}
|
||||
+184
@@ -10,6 +10,8 @@ import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
|
||||
@@ -54,6 +56,7 @@ class AppSyncCfnIntegrationTest {
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/appsync/aws4_request";
|
||||
private static final String STACK = "appsync-cfn-it";
|
||||
private static final String REMOVAL_STACK = "appsync-cfn-removal-it";
|
||||
private static final String ROLLBACK_STACK = "appsync-cfn-rollback-it";
|
||||
|
||||
private static final String TEMPLATE = """
|
||||
{
|
||||
@@ -185,6 +188,140 @@ class AppSyncCfnIntegrationTest {
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String ROLLBACK_FIRST = """
|
||||
{
|
||||
"Resources": {
|
||||
"GraphQlApi": {
|
||||
"Type": "AWS::AppSync::GraphQLApi",
|
||||
"Properties": {
|
||||
"Name": "appsync-cfn-rollback-it-api",
|
||||
"AuthenticationType": "API_KEY",
|
||||
"OwnerContact": "platform-team",
|
||||
"QueryDepthLimit": 10
|
||||
}
|
||||
},
|
||||
"GraphQlDs": {
|
||||
"Type": "AWS::AppSync::DataSource",
|
||||
"Properties": {
|
||||
"ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
|
||||
"Name": "rollbackDs",
|
||||
"Type": "NONE",
|
||||
"Description": "first",
|
||||
"ServiceRoleArn": "arn:aws:iam::000000000000:role/rollback-it"
|
||||
}
|
||||
},
|
||||
"GraphQlFn": {
|
||||
"Type": "AWS::AppSync::FunctionConfiguration",
|
||||
"Properties": {
|
||||
"ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
|
||||
"Name": "rollbackFn",
|
||||
"DataSourceName": {"Fn::GetAtt": ["GraphQlDs", "Name"]},
|
||||
"FunctionVersion": "2018-05-29",
|
||||
"RequestMappingTemplate": "first request",
|
||||
"ResponseMappingTemplate": "first response"
|
||||
}
|
||||
},
|
||||
"GraphQlResolver": {
|
||||
"Type": "AWS::AppSync::Resolver",
|
||||
"Properties": {
|
||||
"ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
|
||||
"TypeName": "Query",
|
||||
"FieldName": "getMessages",
|
||||
"DataSourceName": {"Fn::GetAtt": ["GraphQlDs", "Name"]},
|
||||
"RequestMappingTemplate": "first request",
|
||||
"ResponseMappingTemplate": "first response"
|
||||
}
|
||||
},
|
||||
"GraphQlApiKey": {
|
||||
"Type": "AWS::AppSync::ApiKey",
|
||||
"Properties": {
|
||||
"ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
|
||||
"Description": "first"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"ApiId": {"Value": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}},
|
||||
"FunctionId": {"Value": {"Fn::GetAtt": ["GraphQlFn", "FunctionId"]}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
/**
|
||||
* Changes one member and drops another on every type, adds a data source, then fails on a
|
||||
* resolver that names resolver code in S3, which the provisioner refuses. {@code %d} is the
|
||||
* API key's new expiry.
|
||||
*/
|
||||
private static final String ROLLBACK_SECOND = """
|
||||
{
|
||||
"Resources": {
|
||||
"GraphQlApi": {
|
||||
"Type": "AWS::AppSync::GraphQLApi",
|
||||
"Properties": {
|
||||
"Name": "appsync-cfn-rollback-it-api",
|
||||
"AuthenticationType": "API_KEY",
|
||||
"QueryDepthLimit": 20
|
||||
}
|
||||
},
|
||||
"GraphQlDs": {
|
||||
"Type": "AWS::AppSync::DataSource",
|
||||
"Properties": {
|
||||
"ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
|
||||
"Name": "rollbackDs",
|
||||
"Type": "NONE",
|
||||
"Description": "second"
|
||||
}
|
||||
},
|
||||
"GraphQlFn": {
|
||||
"Type": "AWS::AppSync::FunctionConfiguration",
|
||||
"Properties": {
|
||||
"ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
|
||||
"Name": "rollbackFn",
|
||||
"DataSourceName": {"Fn::GetAtt": ["GraphQlDs", "Name"]},
|
||||
"FunctionVersion": "2018-05-29",
|
||||
"RequestMappingTemplate": "second request"
|
||||
}
|
||||
},
|
||||
"GraphQlResolver": {
|
||||
"Type": "AWS::AppSync::Resolver",
|
||||
"Properties": {
|
||||
"ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
|
||||
"TypeName": "Query",
|
||||
"FieldName": "getMessages",
|
||||
"DataSourceName": {"Fn::GetAtt": ["GraphQlDs", "Name"]},
|
||||
"RequestMappingTemplate": "second request"
|
||||
}
|
||||
},
|
||||
"GraphQlApiKey": {
|
||||
"Type": "AWS::AppSync::ApiKey",
|
||||
"Properties": {
|
||||
"ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
|
||||
"Expires": %d
|
||||
}
|
||||
},
|
||||
"GraphQlDsCreated": {
|
||||
"Type": "AWS::AppSync::DataSource",
|
||||
"Properties": {
|
||||
"ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
|
||||
"Name": "createdByTheUpdate",
|
||||
"Type": "NONE"
|
||||
}
|
||||
},
|
||||
"GraphQlResolverLater": {
|
||||
"Type": "AWS::AppSync::Resolver",
|
||||
"DependsOn": ["GraphQlResolver", "GraphQlApiKey", "GraphQlDsCreated"],
|
||||
"Properties": {
|
||||
"ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
|
||||
"TypeName": "Query",
|
||||
"FieldName": "later",
|
||||
"DataSourceName": {"Fn::GetAtt": ["GraphQlDs", "Name"]},
|
||||
"CodeS3Location": "s3://rollback-it/resolver.js"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
@Test
|
||||
void createUpdateAndDeleteAnAppSyncApi() {
|
||||
cloudFormation("CreateStack", STACK, TEMPLATE, Map.of("FieldLogLevel", "ERROR"));
|
||||
@@ -305,6 +442,53 @@ class AppSyncCfnIntegrationTest {
|
||||
CfnStackWaits.awaitStackDeleted(REMOVAL_STACK);
|
||||
}
|
||||
|
||||
/**
|
||||
* A failing later resource rolls an AppSync stack back: each type gets back the member the
|
||||
* update changed and the member it cleared, an API key its expiry and description, and the
|
||||
* data source the update created is deleted.
|
||||
*/
|
||||
@Test
|
||||
void aFailingLaterResourceRestoresWhatTheUpdateChangedAndCleared() {
|
||||
cloudFormation("CreateStack", ROLLBACK_STACK, ROLLBACK_FIRST, Map.of());
|
||||
CfnStackWaits.awaitStatus(ROLLBACK_STACK, "CREATE_COMPLETE");
|
||||
String created = describeStacks(ROLLBACK_STACK, "CREATE_COMPLETE");
|
||||
String apiId = outputValue(created, "ApiId");
|
||||
String functionId = outputValue(created, "FunctionId");
|
||||
String keyId = appSync("/v1/apis/" + apiId + "/apikeys").extract().path("apiKeys[0].id");
|
||||
long expires = ((Number) appSync("/v1/apis/" + apiId + "/apikeys").extract()
|
||||
.path("apiKeys[0].expires")).longValue();
|
||||
|
||||
long newExpiry = Instant.now().plus(30, ChronoUnit.DAYS).getEpochSecond();
|
||||
cloudFormation("UpdateStack", ROLLBACK_STACK, ROLLBACK_SECOND.formatted(newExpiry), Map.of());
|
||||
CfnStackWaits.awaitStatus(ROLLBACK_STACK, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
appSync("/v1/apis/" + apiId)
|
||||
.statusCode(200)
|
||||
.body("graphqlApi.queryDepthLimit", equalTo(10))
|
||||
.body("graphqlApi.ownerContact", equalTo("platform-team"));
|
||||
appSync("/v1/apis/" + apiId + "/datasources/rollbackDs")
|
||||
.statusCode(200)
|
||||
.body("dataSource.description", equalTo("first"))
|
||||
.body("dataSource.serviceRoleArn", equalTo("arn:aws:iam::000000000000:role/rollback-it"));
|
||||
appSync("/v1/apis/" + apiId + "/functions/" + functionId)
|
||||
.statusCode(200)
|
||||
.body("functionConfiguration.requestMappingTemplate", equalTo("first request"))
|
||||
.body("functionConfiguration.responseMappingTemplate", equalTo("first response"));
|
||||
appSync("/v1/apis/" + apiId + "/types/Query/resolvers/getMessages")
|
||||
.statusCode(200)
|
||||
.body("resolver.requestMappingTemplate", equalTo("first request"))
|
||||
.body("resolver.responseMappingTemplate", equalTo("first response"));
|
||||
appSync("/v1/apis/" + apiId + "/apikeys")
|
||||
.statusCode(200)
|
||||
.body("apiKeys[0].id", equalTo(keyId))
|
||||
.body("apiKeys[0].description", equalTo("first"))
|
||||
.body("apiKeys[0].expires", equalTo((int) expires));
|
||||
appSync("/v1/apis/" + apiId + "/datasources/createdByTheUpdate").statusCode(404);
|
||||
|
||||
cloudFormation("DeleteStack", ROLLBACK_STACK, null, Map.of());
|
||||
CfnStackWaits.awaitStackDeleted(ROLLBACK_STACK);
|
||||
}
|
||||
|
||||
private static void cloudFormation(String action, String stackName, String template,
|
||||
Map<String, String> parameters) {
|
||||
RequestSpecification request = cfn(action, stackName).header("Authorization", CFN_AUTH);
|
||||
|
||||
+437
@@ -5,8 +5,11 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.appsync.AppSyncService;
|
||||
import io.github.hectorvent.floci.services.appsync.AppSyncServiceFixture;
|
||||
import io.github.hectorvent.floci.services.appsync.model.ApiKey;
|
||||
import io.github.hectorvent.floci.services.appsync.model.AuthenticationType;
|
||||
import io.github.hectorvent.floci.services.appsync.model.DataSource;
|
||||
import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
|
||||
import io.github.hectorvent.floci.services.appsync.model.FunctionConfiguration;
|
||||
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
|
||||
import io.github.hectorvent.floci.services.appsync.model.Resolver;
|
||||
@@ -19,6 +22,10 @@ import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -973,6 +980,436 @@ class AppSyncCfnProvisionerTest {
|
||||
assertTrue(updateRequest(captor).isEmpty());
|
||||
}
|
||||
|
||||
// ── Rollback of an in-place update ───────────────────────────────────────
|
||||
|
||||
private static final String SNAPSHOT = CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR;
|
||||
|
||||
/** Every request the mock received on an update method, oldest first. */
|
||||
@SuppressWarnings("unchecked")
|
||||
private static List<Map<String, Object>> requests(ArgumentCaptor<Map<String, Object>> captor) {
|
||||
return captor.getAllValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
void graphqlApiRollbackPutsBackWhatTheUpdateChangedAndCleared() throws Exception {
|
||||
GraphqlApi before = api();
|
||||
before.setAuthenticationType(AuthenticationType.API_KEY);
|
||||
before.setOwnerContact("team");
|
||||
before.setXrayEnabled(true);
|
||||
before.setTags(Map.of("env", "dev"));
|
||||
before.setUserPoolConfig(Map.of("awsRegion", "eu-west-1"));
|
||||
before.setApiType("MERGED");
|
||||
before.setVisibility("PRIVATE");
|
||||
when(appSync.getGraphqlApi(API_ID)).thenReturn(before);
|
||||
when(appSync.getEnvironmentVariables(API_ID)).thenReturn(Map.of("STAGE", "dev"));
|
||||
when(appSync.updateGraphqlApi(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(api());
|
||||
StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi");
|
||||
|
||||
provisioner.provision(r, mapper.readTree(
|
||||
"{\"Name\":\"renamed-api\",\"AuthenticationType\":\"AWS_IAM\","
|
||||
+ "\"ApiType\":\"GRAPHQL\",\"Visibility\":\"GLOBAL\","
|
||||
+ "\"EnvironmentVariables\":{\"STAGE\":\"prod\"}}"),
|
||||
updateCtx(API_ID, "{\"Name\":\"account-api\",\"AuthenticationType\":\"API_KEY\","
|
||||
+ "\"OwnerContact\":\"team\",\"UserPoolConfig\":{\"AwsRegion\":\"eu-west-1\"}}"));
|
||||
assertTrue(r.getAttributes().containsKey(SNAPSHOT));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(appSync, Mockito.times(2)).updateGraphqlApi(eq(API_ID), captor.capture(), eq("eu-west-1"));
|
||||
Map<String, Object> restore = requests(captor).get(1);
|
||||
assertEquals("account-api", restore.get("name"));
|
||||
assertEquals("API_KEY", restore.get("authenticationType"));
|
||||
assertEquals("team", restore.get("ownerContact"));
|
||||
assertEquals(Map.of("awsRegion", "eu-west-1"), restore.get("userPoolConfig"));
|
||||
assertEquals(true, restore.get("xrayEnabled"));
|
||||
assertEquals(Map.of("env", "dev"), restore.get("tags"));
|
||||
// The service ignores a null list, so an API that had none gets an empty one back.
|
||||
assertEquals(List.of(), restore.get("additionalAuthenticationProviders"));
|
||||
// A member the API never had is replayed as a clear.
|
||||
assertTrue(restore.containsKey("introspectionConfig"));
|
||||
assertNull(restore.get("introspectionConfig"));
|
||||
// ApiType and Visibility are applied by the update, so the restore puts them back too.
|
||||
assertEquals("MERGED", restore.get("apiType"));
|
||||
assertEquals("PRIVATE", restore.get("visibility"));
|
||||
verify(appSync).putEnvironmentVariables(API_ID, Map.of("STAGE", "dev"));
|
||||
assertFalse(r.getAttributes().containsKey(SNAPSHOT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dataSourceRollbackPutsBackWhatTheUpdateChangedAndCleared() throws Exception {
|
||||
DataSource before = new DataSource();
|
||||
before.setName("accountDB");
|
||||
before.setDataSourceArn("arn:ds");
|
||||
before.setType(DataSourceType.AMAZON_DYNAMODB);
|
||||
before.setDescription("old");
|
||||
before.setDynamodbConfig(Map.of("tableName", "t"));
|
||||
when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(before);
|
||||
when(appSync.updateDataSource(eq(API_ID), eq("accountDB"), any())).thenReturn(before);
|
||||
StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb");
|
||||
r.getAttributes().put("ApiId", API_ID);
|
||||
r.getAttributes().put("Name", "accountDB");
|
||||
|
||||
provisioner.provision(r, mapper.readTree(
|
||||
"{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\",\"Type\":\"HTTP\","
|
||||
+ "\"HttpConfig\":{\"Endpoint\":\"https://example.com\"}}"),
|
||||
updateCtx("arn:ds", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\","
|
||||
+ "\"Type\":\"AMAZON_DYNAMODB\",\"Description\":\"old\","
|
||||
+ "\"DynamoDBConfig\":{\"TableName\":\"t\"}}"));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(appSync, Mockito.times(2)).updateDataSource(eq(API_ID), eq("accountDB"), captor.capture());
|
||||
Map<String, Object> restore = requests(captor).get(1);
|
||||
assertEquals("AMAZON_DYNAMODB", restore.get("type"));
|
||||
assertEquals("old", restore.get("description"));
|
||||
assertEquals(Map.of("tableName", "t"), restore.get("dynamodbConfig"));
|
||||
// The config the update added is cleared again.
|
||||
assertTrue(restore.containsKey("httpConfig"));
|
||||
assertNull(restore.get("httpConfig"));
|
||||
assertFalse(r.getAttributes().containsKey(SNAPSHOT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void functionRollbackPutsBackWhatTheUpdateChangedAndCleared() throws Exception {
|
||||
FunctionConfiguration before = new FunctionConfiguration();
|
||||
before.setFunctionId("fn1");
|
||||
before.setFunctionArn("arn:fn");
|
||||
before.setName("old-name");
|
||||
before.setDataSourceName("accountDB");
|
||||
before.setDescription("old");
|
||||
before.setFunctionVersion("2018-05-29");
|
||||
before.setCode("export function request() {}");
|
||||
when(appSync.getFunction(API_ID, "fn1")).thenReturn(before);
|
||||
FunctionConfiguration after = new FunctionConfiguration();
|
||||
after.setFunctionId("fn1");
|
||||
after.setFunctionArn("arn:fn");
|
||||
after.setName("new-name");
|
||||
after.setDataSourceName("otherDB");
|
||||
when(appSync.updateFunction(eq(API_ID), eq("fn1"), any())).thenReturn(after);
|
||||
StackResource r = resource("AWS::AppSync::FunctionConfiguration", "GraphQlFn");
|
||||
r.getAttributes().put("ApiId", API_ID);
|
||||
r.getAttributes().put("FunctionId", "fn1");
|
||||
|
||||
provisioner.provision(r, mapper.readTree(
|
||||
"{\"ApiId\":\"" + API_ID + "\",\"Name\":\"new-name\",\"DataSourceName\":\"otherDB\"}"),
|
||||
updateCtx("arn:fn", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"old-name\","
|
||||
+ "\"DataSourceName\":\"accountDB\",\"Description\":\"old\","
|
||||
+ "\"Code\":\"export function request() {}\"}"));
|
||||
assertEquals("new-name", r.getAttributes().get("Name"));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(appSync, Mockito.times(2)).updateFunction(eq(API_ID), eq("fn1"), captor.capture());
|
||||
Map<String, Object> restore = requests(captor).get(1);
|
||||
assertEquals("old-name", restore.get("name"));
|
||||
assertEquals("accountDB", restore.get("dataSourceName"));
|
||||
assertEquals("old", restore.get("description"));
|
||||
assertEquals("export function request() {}", restore.get("code"));
|
||||
assertEquals("2018-05-29", restore.get("functionVersion"));
|
||||
// The engine keeps the attempted resource, so its attributes name the restored function.
|
||||
assertEquals("old-name", r.getAttributes().get("Name"));
|
||||
assertEquals("accountDB", r.getAttributes().get("DataSourceName"));
|
||||
assertFalse(r.getAttributes().containsKey(SNAPSHOT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void functionRollbackDropsADataSourceNameTheFunctionDidNotHave() throws Exception {
|
||||
FunctionConfiguration before = new FunctionConfiguration();
|
||||
before.setFunctionId("fn1");
|
||||
before.setFunctionArn("arn:fn");
|
||||
before.setName("fn-name");
|
||||
when(appSync.getFunction(API_ID, "fn1")).thenReturn(before);
|
||||
FunctionConfiguration after = new FunctionConfiguration();
|
||||
after.setFunctionId("fn1");
|
||||
after.setFunctionArn("arn:fn");
|
||||
after.setName("fn-name");
|
||||
after.setDataSourceName("otherDB");
|
||||
when(appSync.updateFunction(eq(API_ID), eq("fn1"), any())).thenReturn(after);
|
||||
StackResource r = resource("AWS::AppSync::FunctionConfiguration", "GraphQlFn");
|
||||
r.getAttributes().put("ApiId", API_ID);
|
||||
r.getAttributes().put("FunctionId", "fn1");
|
||||
|
||||
provisioner.provision(r, mapper.readTree(
|
||||
"{\"ApiId\":\"" + API_ID + "\",\"Name\":\"fn-name\",\"DataSourceName\":\"otherDB\"}"),
|
||||
updateCtx("arn:fn", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"fn-name\"}"));
|
||||
assertEquals("otherDB", r.getAttributes().get("DataSourceName"));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
assertFalse(r.getAttributes().containsKey("DataSourceName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolverRollbackPutsBackWhatTheUpdateChangedAndCleared() throws Exception {
|
||||
Resolver before = new Resolver();
|
||||
before.setApiId(API_ID);
|
||||
before.setTypeName("Query");
|
||||
before.setFieldName("getMessages");
|
||||
before.setKind(ResolverKind.UNIT);
|
||||
before.setDataSourceName("accountDB");
|
||||
before.setRequestMappingTemplate("old request");
|
||||
before.setResponseMappingTemplate("old response");
|
||||
when(appSync.getResolver(API_ID, "Query", "getMessages")).thenReturn(before);
|
||||
Resolver after = new Resolver();
|
||||
after.setResolverArn("arn:resolver");
|
||||
when(appSync.updateResolver(eq(API_ID), eq("Query"), eq("getMessages"), any())).thenReturn(after);
|
||||
StackResource r = resource("AWS::AppSync::Resolver", "GraphQlResolver");
|
||||
r.getAttributes().put("ApiId", API_ID);
|
||||
r.getAttributes().put("TypeName", "Query");
|
||||
r.getAttributes().put("FieldName", "getMessages");
|
||||
String declared = "{\"ApiId\":\"" + API_ID + "\",\"TypeName\":\"Query\",\"FieldName\":\"getMessages\","
|
||||
+ "\"DataSourceName\":\"accountDB\",\"RequestMappingTemplate\":\"old request\","
|
||||
+ "\"ResponseMappingTemplate\":\"old response\"}";
|
||||
|
||||
provisioner.provision(r, mapper.readTree("{\"ApiId\":\"" + API_ID + "\",\"TypeName\":\"Query\","
|
||||
+ "\"FieldName\":\"getMessages\",\"DataSourceName\":\"accountDB\","
|
||||
+ "\"RequestMappingTemplate\":\"new request\"}"),
|
||||
updateCtx("arn:resolver", declared));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(appSync, Mockito.times(2)).updateResolver(eq(API_ID), eq("Query"), eq("getMessages"),
|
||||
captor.capture());
|
||||
Map<String, Object> restore = requests(captor).get(1);
|
||||
assertEquals("old request", restore.get("requestMappingTemplate"));
|
||||
assertEquals("old response", restore.get("responseMappingTemplate"));
|
||||
assertEquals("UNIT", restore.get("kind"));
|
||||
assertEquals("accountDB", restore.get("dataSourceName"));
|
||||
// A member the resolver never carried is replayed as a clear.
|
||||
assertTrue(restore.containsKey("pipelineConfig"));
|
||||
assertNull(restore.get("pipelineConfig"));
|
||||
assertFalse(r.getAttributes().containsKey(SNAPSHOT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void apiKeyRollbackPutsBackADroppedDescriptionAndSkipsAnExpiryThatDidNotMove() throws Exception {
|
||||
ApiKey before = new ApiKey();
|
||||
before.setId("da2-key");
|
||||
before.setDescription("old");
|
||||
before.setExpires(1_900_000_000L);
|
||||
when(appSync.getApiKey(API_ID, "da2-key")).thenReturn(before);
|
||||
when(appSync.updateApiKey(eq(API_ID), eq("da2-key"), any())).thenReturn(before);
|
||||
StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey");
|
||||
r.getAttributes().put("ApiId", API_ID);
|
||||
|
||||
provisioner.provision(r, mapper.readTree("{\"ApiId\":\"" + API_ID + "\",\"Expires\":1900000000}"),
|
||||
updateCtx("da2-key", "{\"ApiId\":\"" + API_ID + "\",\"Description\":\"old\","
|
||||
+ "\"Expires\":1900000000}"));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(appSync, Mockito.times(2)).updateApiKey(eq(API_ID), eq("da2-key"), captor.capture());
|
||||
Map<String, Object> restore = requests(captor).get(1);
|
||||
assertEquals("old", restore.get("description"));
|
||||
// The store still holds the prior expiry, so sending it again could only trip the service's bounds.
|
||||
assertFalse(restore.containsKey("expires"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void apiKeyRollbackPutsBackAnExpiryTheUpdateMoved() throws Exception {
|
||||
ApiKey before = new ApiKey();
|
||||
before.setId("da2-key");
|
||||
before.setExpires(1_900_000_000L);
|
||||
ApiKey moved = new ApiKey();
|
||||
moved.setId("da2-key");
|
||||
moved.setExpires(1_950_000_000L);
|
||||
when(appSync.getApiKey(API_ID, "da2-key")).thenReturn(before, moved);
|
||||
when(appSync.updateApiKey(eq(API_ID), eq("da2-key"), any())).thenReturn(moved);
|
||||
StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey");
|
||||
r.getAttributes().put("ApiId", API_ID);
|
||||
|
||||
provisioner.provision(r, mapper.readTree("{\"ApiId\":\"" + API_ID + "\",\"Expires\":1950000000}"),
|
||||
updateCtx("da2-key", "{\"ApiId\":\"" + API_ID + "\",\"Expires\":1900000000}"));
|
||||
provisioner.rollbackUpdate(r);
|
||||
|
||||
ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(appSync, Mockito.times(2)).updateApiKey(eq(API_ID), eq("da2-key"), captor.capture());
|
||||
assertEquals(1_900_000_000L, ((Number) requests(captor).get(1).get("expires")).longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRollbackThatTheServiceRefusesLeavesTheApiKeyAsTheUpdateLeftItAndKeepsTheSnapshot() throws Exception {
|
||||
Instant start = Instant.parse("2026-01-01T00:00:00Z");
|
||||
AppSyncServiceFixture.MutableClock clock = new AppSyncServiceFixture.MutableClock(start);
|
||||
AppSyncService real = AppSyncServiceFixture.create(clock);
|
||||
AppSyncCfnProvisioner onRealService = new AppSyncCfnProvisioner(real);
|
||||
GraphqlApi created = real.createGraphqlApi(Map.of("name", "keys", "authenticationType", "API_KEY"), "eu-west-1");
|
||||
long soonExpiry = start.getEpochSecond() + Duration.ofHours(25).getSeconds();
|
||||
long laterExpiry = start.getEpochSecond() + Duration.ofDays(100).getSeconds();
|
||||
ApiKey key = real.createApiKey(created.getApiId(), Map.of("description", "before", "expires", soonExpiry));
|
||||
StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey");
|
||||
r.getAttributes().put("ApiId", created.getApiId());
|
||||
|
||||
onRealService.provision(r, mapper.readTree("{\"ApiId\":\"" + created.getApiId()
|
||||
+ "\",\"Description\":\"after\",\"Expires\":" + laterExpiry + "}"),
|
||||
updateCtx(key.getId(), "{\"ApiId\":\"" + created.getApiId() + "\",\"Description\":\"before\","
|
||||
+ "\"Expires\":" + soonExpiry + "}"));
|
||||
// Three hours on, the prior expiry is under a day away, which the service no longer accepts.
|
||||
clock.set(start.plus(Duration.ofHours(3)));
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> onRealService.rollbackUpdate(r));
|
||||
|
||||
assertEquals("ApiKeyValidityOutOfBoundsException", refused.getErrorCode());
|
||||
ApiKey stored = real.getApiKey(created.getApiId(), key.getId());
|
||||
assertEquals("after", stored.getDescription());
|
||||
assertEquals(laterExpiry - laterExpiry % 3600, stored.getExpires());
|
||||
assertTrue(r.getAttributes().containsKey(SNAPSHOT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSnapshotThatIsNotJsonFailsTheRollbackNamingTheResourceAndChangesNothing() {
|
||||
AppSyncService real = AppSyncServiceFixture.create(Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC));
|
||||
AppSyncCfnProvisioner onRealService = new AppSyncCfnProvisioner(real);
|
||||
GraphqlApi created = real.createGraphqlApi(Map.of("name", "corrupt", "authenticationType", "API_KEY"), "eu-west-1");
|
||||
real.createDataSource(created.getApiId(), Map.of("name", "ds", "type", "NONE", "description", "kept"), "eu-west-1");
|
||||
StackResource r = resource("AWS::AppSync::DataSource", "CorruptSnapshotDs");
|
||||
r.getAttributes().put("ApiId", created.getApiId());
|
||||
r.getAttributes().put("Name", "ds");
|
||||
r.getAttributes().put(SNAPSHOT, "this is { not json");
|
||||
|
||||
Exception failure = assertThrows(Exception.class, () -> onRealService.rollbackUpdate(r));
|
||||
|
||||
assertTrue(failure.getMessage().contains("CorruptSnapshotDs"));
|
||||
DataSource stored = real.getDataSource(created.getApiId(), "ds");
|
||||
assertEquals("kept", stored.getDescription());
|
||||
assertEquals(DataSourceType.NONE, stored.getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateThatFailsPartWayPutsTheEntityBackBeforeItFails() throws Exception {
|
||||
DataSource before = new DataSource();
|
||||
before.setName("accountDB");
|
||||
before.setType(DataSourceType.AMAZON_DYNAMODB);
|
||||
before.setDescription("old");
|
||||
when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(before);
|
||||
when(appSync.updateDataSource(eq(API_ID), eq("accountDB"), any()))
|
||||
.thenThrow(new AwsException("BadRequestException", "refused", 400))
|
||||
.thenReturn(before);
|
||||
StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb");
|
||||
r.getAttributes().put("ApiId", API_ID);
|
||||
r.getAttributes().put("Name", "accountDB");
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(r, mapper.readTree(
|
||||
"{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\",\"Type\":\"HTTP\"}"),
|
||||
updateCtx("arn:ds", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\"}")));
|
||||
|
||||
ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(appSync, Mockito.times(2)).updateDataSource(eq(API_ID), eq("accountDB"), captor.capture());
|
||||
assertEquals("AMAZON_DYNAMODB", requests(captor).get(1).get("type"));
|
||||
assertEquals("old", requests(captor).get(1).get("description"));
|
||||
assertFalse(r.getAttributes().containsKey(SNAPSHOT));
|
||||
assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUndoThatFailsKeepsTheSnapshotAndReportsWhyForAContinueUpdateRollback() throws Exception {
|
||||
DataSource before = new DataSource();
|
||||
before.setName("accountDB");
|
||||
before.setType(DataSourceType.AMAZON_DYNAMODB);
|
||||
when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(before);
|
||||
when(appSync.updateDataSource(eq(API_ID), eq("accountDB"), any()))
|
||||
.thenThrow(new AwsException("BadRequestException", "refused", 400))
|
||||
.thenThrow(new AwsException("ConcurrentModificationException", "busy", 409));
|
||||
StackResource attempted = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb");
|
||||
attempted.getAttributes().put("ApiId", API_ID);
|
||||
attempted.getAttributes().put("Name", "accountDB");
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(attempted, mapper.readTree(
|
||||
"{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\",\"Type\":\"HTTP\"}"),
|
||||
updateCtx("arn:ds", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\"}")));
|
||||
|
||||
assertTrue(attempted.getAttributes().containsKey(SNAPSHOT));
|
||||
assertTrue(attempted.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR).contains("busy"));
|
||||
StackResource previous = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb");
|
||||
provisioner.mergeFailedUpdateResourceTracking(previous, attempted);
|
||||
assertEquals(attempted.getAttributes().get(SNAPSHOT), previous.getAttributes().get(SNAPSHOT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoreThatFailsKeepsTheSnapshotForTheNextAttempt() throws Exception {
|
||||
DataSource before = new DataSource();
|
||||
before.setName("accountDB");
|
||||
before.setType(DataSourceType.AMAZON_DYNAMODB);
|
||||
when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(before);
|
||||
when(appSync.updateDataSource(eq(API_ID), eq("accountDB"), any()))
|
||||
.thenReturn(before)
|
||||
.thenThrow(new AwsException("ConcurrentModificationException", "busy", 409))
|
||||
.thenReturn(before);
|
||||
StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb");
|
||||
r.getAttributes().put("ApiId", API_ID);
|
||||
r.getAttributes().put("Name", "accountDB");
|
||||
provisioner.provision(r, mapper.readTree(
|
||||
"{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\",\"Type\":\"HTTP\"}"),
|
||||
updateCtx("arn:ds", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\"}"));
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
|
||||
assertTrue(r.getAttributes().containsKey(SNAPSHOT));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
assertFalse(r.getAttributes().containsKey(SNAPSHOT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aResourceTheFailedUpdateCreatedHasNothingToRestore() throws Exception {
|
||||
DataSource created = new DataSource();
|
||||
created.setName("accountDB");
|
||||
created.setDataSourceArn("arn:ds");
|
||||
when(appSync.createDataSource(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(created);
|
||||
StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb");
|
||||
|
||||
provisioner.provision(r, mapper.readTree(
|
||||
"{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\",\"Type\":\"HTTP\"}"), ctx());
|
||||
|
||||
// The engine deletes it from the recorded attributes; the provisioner answers no restore.
|
||||
assertFalse(r.getAttributes().containsKey(SNAPSHOT));
|
||||
assertFalse(provisioner.rollbackUpdate(r));
|
||||
verify(appSync, never()).updateDataSource(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReplacementLeavesNoSnapshotAndKeepsTheUnsupportedAnswer() throws Exception {
|
||||
ApiKey created = new ApiKey();
|
||||
created.setId("da2-new");
|
||||
when(appSync.createApiKey(eq("other-api"), any())).thenReturn(created);
|
||||
StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey");
|
||||
r.getAttributes().put("ApiId", API_ID);
|
||||
|
||||
provisioner.provision(r, mapper.readTree("{\"ApiId\":\"other-api\"}"), updateCtx("da2-key"));
|
||||
|
||||
assertFalse(r.getAttributes().containsKey(SNAPSHOT));
|
||||
assertFalse(provisioner.rollbackUpdate(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSnapshotAnEarlierUpdateLeftBehindIsDroppedWhenTheNextProvisionStarts() throws Exception {
|
||||
ApiKey created = new ApiKey();
|
||||
created.setId("da2-new");
|
||||
when(appSync.createApiKey(eq(API_ID), any())).thenReturn(created);
|
||||
StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey");
|
||||
r.getAttributes().put(SNAPSHOT, "{}");
|
||||
|
||||
provisioner.provision(r, mapper.readTree("{\"ApiId\":\"" + API_ID + "\"}"), ctx());
|
||||
|
||||
assertFalse(r.getAttributes().containsKey(SNAPSHOT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCommittedUpdateDropsItsSnapshotAndOwesNoCleanup() {
|
||||
StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey");
|
||||
r.getAttributes().put(SNAPSHOT, "{}");
|
||||
|
||||
assertFalse(provisioner.completeUpdate(r).applicable());
|
||||
assertFalse(r.getAttributes().containsKey(SNAPSHOT));
|
||||
r.getAttributes().put(SNAPSHOT, "{}");
|
||||
provisioner.clearUpdate(r);
|
||||
assertFalse(r.getAttributes().containsKey(SNAPSHOT));
|
||||
}
|
||||
|
||||
// ── Deletes ──────────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user