diff --git a/compatibility-tests/sdk-test-python/tests/test_appconfig_deployment_lifecycle.py b/compatibility-tests/sdk-test-python/tests/test_appconfig_deployment_lifecycle.py new file mode 100644 index 0000000000..56da872f95 --- /dev/null +++ b/compatibility-tests/sdk-test-python/tests/test_appconfig_deployment_lifecycle.py @@ -0,0 +1,117 @@ +"""AppConfig baking and manual rollback through both retrieval APIs.""" + +from contextlib import ExitStack +from datetime import datetime + +import boto3 +import pytest +from botocore.exceptions import ClientError + + +@pytest.mark.parametrize("zero_padded", [False, True], ids=["decimal", "zero-padded"]) +@pytest.mark.parametrize("delete_previous", [False, True], ids=["restore", "deleted"]) +def test_deployment_rollback_restores_both_retrieval_apis( + aws_config, client_config, unique_name, delete_previous, zero_padded): + with ExitStack() as cleanup: + client = boto3.client("appconfig", config=client_config, **aws_config) + data = boto3.client("appconfigdata", config=client_config, **aws_config) + cleanup.callback(client.close) + cleanup.callback(data.close) + app = client.create_application(Name=unique_name)["Id"] + cleanup.callback(client.delete_application, ApplicationId=app) + profile = client.create_configuration_profile( + ApplicationId=app, Name="settings", LocationUri="hosted", Type="AWS.Freeform" + )["Id"] + cleanup.callback( + client.delete_configuration_profile, ApplicationId=app, ConfigurationProfileId=profile) + versions = [] + for content in (b'{"version":1}', b'{"version":2}'): + version = client.create_hosted_configuration_version( + ApplicationId=app, ConfigurationProfileId=profile, + Content=content, ContentType="application/json", + )["VersionNumber"] + versions.append(version) + cleanup.callback( + client.delete_hosted_configuration_version, ApplicationId=app, + ConfigurationProfileId=profile, VersionNumber=version, + ) + strategies = [] + for bake in (0, 1): + strategy = client.create_deployment_strategy( + Name=f"{unique_name}-{bake}", DeploymentDurationInMinutes=0, + FinalBakeTimeInMinutes=bake, GrowthFactor=100, + GrowthType="LINEAR", ReplicateTo="NONE", + )["Id"] + strategies.append(strategy) + cleanup.callback(client.delete_deployment_strategy, DeploymentStrategyId=strategy) + env = client.create_environment(ApplicationId=app, Name="local")["Id"] + cleanup.callback(client.delete_environment, ApplicationId=app, EnvironmentId=env) + scope = {"ApplicationId": app, "EnvironmentId": env} + + def deploy(version, strategy): + return client.start_deployment( + **scope, ConfigurationProfileId=profile, + ConfigurationVersion=str(version), DeploymentStrategyId=strategy) + + def assert_content(version, content): + response = client.get_configuration( + Application=app, Environment=env, Configuration=profile, ClientId=unique_name) + with response["Content"] as stream: + assert stream.read() == content + assert response["ConfigurationVersion"] == str(version) + token = data.start_configuration_session( + ApplicationIdentifier=app, EnvironmentIdentifier=env, + ConfigurationProfileIdentifier=profile, + )["InitialConfigurationToken"] + response = data.get_latest_configuration(ConfigurationToken=token) + with response["Configuration"] as stream: + assert stream.read() == content + + previous_version = ("0" if zero_padded else "") + str(versions[0]) + first = deploy(previous_version, strategies[0]) + assert first["State"] == "COMPLETE" + assert isinstance(first["StartedAt"], datetime) + assert first["CompletedAt"] == first["StartedAt"] + assert_content(previous_version, b'{"version":1}') + second = deploy(versions[1], strategies[1]) + target = {**scope, "DeploymentNumber": second["DeploymentNumber"]} + assert second["State"] == "BAKING" + assert second["PercentageComplete"] == 100 + assert second["FinalBakeTimeInMinutes"] == 1 + assert "CompletedAt" not in second + assert_content(versions[1], b'{"version":2}') + assert client.get_deployment(**target)["State"] == "BAKING" + with pytest.raises(ClientError) as error: + client.stop_deployment(**target) + assert error.value.response["Error"]["Code"] == "BadRequestException" + assert client.get_deployment(**target)["State"] == "BAKING" + + if delete_previous: + client.delete_hosted_configuration_version( + ApplicationId=app, ConfigurationProfileId=profile, VersionNumber=versions[0]) + before = client.get_deployment(**target) + with pytest.raises(ClientError) as error: + client.stop_deployment(**target, AllowRevert=True) + assert error.value.response["Error"]["Code"] == "BadRequestException" + assert error.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400 + after = client.get_deployment(**target) + assert after["State"] == before["State"] + assert after.get("CompletedAt") == before.get("CompletedAt") + assert after["PercentageComplete"] == before["PercentageComplete"] + assert_content(versions[1], b'{"version":2}') + return + + stopped = client.stop_deployment(**target, AllowRevert=True) + assert stopped["ResponseMetadata"]["HTTPStatusCode"] == 202 + assert stopped["State"] == "ROLLED_BACK" + assert isinstance(stopped["CompletedAt"], datetime) + assert client.get_deployment(**target)["State"] == "ROLLED_BACK" + listed = { + row["DeploymentNumber"]: row for row in client.list_deployments(**scope)["Items"]} + assert listed[second["DeploymentNumber"]]["State"] == "ROLLED_BACK" + assert listed[second["DeploymentNumber"]]["CompletedAt"] == stopped["CompletedAt"] + assert_content(previous_version, b'{"version":1}') + with pytest.raises(ClientError) as error: + client.stop_deployment(**target, AllowRevert=True) + assert error.value.response["Error"]["Code"] == "BadRequestException" + assert_content(previous_version, b'{"version":1}') diff --git a/docs/services/appconfig.md b/docs/services/appconfig.md index d3ef6a4914..c02bef48a9 100644 --- a/docs/services/appconfig.md +++ b/docs/services/appconfig.md @@ -28,6 +28,7 @@ The management plane allows you to create and manage applications, environments, - `ListDeploymentStrategies` - `DeleteDeploymentStrategy` - `StartDeployment` +- `StopDeployment` - `GetDeployment` - `ListDeployments` (`GET /applications/{ApplicationId}/environments/{EnvironmentId}/deployments`) - `GetConfiguration` (deprecated by AWS in favor of the [data plane](#data-plane)) @@ -48,7 +49,7 @@ such as one from an S3 or SSM source, returns `ResourceNotFoundException`. `CreateEnvironment` keeps up to five `Monitors`, each a CloudWatch `AlarmArn` with an optional IAM role `AlarmRoleArn`, and environment reads return them; an environment created without monitors returns none. -Floci does not evaluate the alarms or roll a deployment back. More than five monitors, or an `AlarmRoleArn` +Floci does not evaluate the alarms or trigger automatic rollback. More than five monitors, or an `AlarmRoleArn` that is not an IAM role ARN, returns `BadRequestException`. `StartDeployment` and `GetDeployment` return the deployed profile's name and location URI as `ConfigurationName` and `ConfigurationLocationUri`. Deployments stored by earlier Floci versions did not @@ -60,6 +61,20 @@ A deployment stored by an earlier Floci version returns no strategy settings fro `ListDeployments` reports the strategy's current settings while the strategy exists. A configuration profile created without `Type` reports no type, as AWS documents no default. +Configuration content becomes available immediately. A positive `FinalBakeTimeInMinutes` +keeps the deployment in `BAKING` at 100 percent until that time has elapsed; get and list +readback then report `COMPLETE`. Started and completed timestamps use the API's ISO 8601 +format and survive restart. Gradual per-client rollout and alarm evaluation are not implemented. + +`StopDeployment` with `AllowRevert=true` returns an in-progress deployment as `ROLLED_BACK` +or a completed deployment as `REVERTED`, restoring the previous available configuration +for that environment and profile. It rejects older deployments while a newer one is +active, and rejects completed deployments outside their 72-hour revert window. +If the previous hosted configuration version has been deleted, the stop is rejected +with `BadRequestException` before changing the active version or stopping the deployment. +Older persisted deployments without completion timestamps cannot be reverted because +that window cannot be verified. + ## Data Plane (AppConfigData) {#data-plane} The data plane is used by applications to retrieve the active configuration for an environment and profile. diff --git a/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigController.java b/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigController.java index 9fc2f9d1f6..5a2840ebfe 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigController.java +++ b/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigController.java @@ -275,6 +275,14 @@ public class AppConfigController { return Response.ok(service.getDeployment(appId, envId, deploymentNumber)).build(); } + @DELETE + @Path("/applications/{appId}/environments/{envId}/deployments/{deploymentNumber}") + public Response stopDeployment(@PathParam("appId") String appId, @PathParam("envId") String envId, + @PathParam("deploymentNumber") int deploymentNumber, + @HeaderParam("Allow-Revert") boolean allowRevert) { + return Response.status(202).entity(service.stopDeployment(appId, envId, deploymentNumber, allowRevert)).build(); + } + // ──────────────────────────── Configuration ──────────────────────────── // The deprecated GetConfiguration: superseded by AppConfigData, but still an AppConfig operation. diff --git a/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigService.java b/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigService.java index 107b014c22..523f2d61ba 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigService.java +++ b/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigService.java @@ -21,6 +21,9 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; @@ -42,6 +45,7 @@ public class AppConfigService { private final StorageBackend versionStore; private final StorageBackend deploymentStore; private final StorageBackend activeConfigStore; // envId::profileId -> versionNumber + private final Clock clock; private final Map deploymentPageTokens = new ConcurrentHashMap<>(); private static final int MAX_DEPLOYMENT_PAGE_TOKENS = 1000; private static final int MAX_MONITORS = 5; @@ -51,6 +55,11 @@ public class AppConfigService { @Inject public AppConfigService(StorageFactory storageFactory, EmulatorConfig config) { + this(storageFactory, config, Clock.systemUTC()); + } + + AppConfigService(StorageFactory storageFactory, EmulatorConfig config, Clock clock) { + this.clock = clock; this.applicationStore = storageFactory.create("appconfig", "appconfig-applications.json", new TypeReference<>() {}); this.environmentStore = storageFactory.create("appconfig", "appconfig-environments.json", new TypeReference<>() {}); this.profileStore = storageFactory.create("appconfig", "appconfig-profiles.json", new TypeReference<>() {}); @@ -407,7 +416,7 @@ public class AppConfigService { .toList(); } - public void deleteHostedConfigurationVersion(String applicationIdentifier, + public synchronized void deleteHostedConfigurationVersion(String applicationIdentifier, String profileIdentifier, int versionNumber) { String appId = resolveApplication(applicationIdentifier).getId(); @@ -552,7 +561,13 @@ public class AppConfigService { .max() .orElse(0) + 1; deployment.setDeploymentNumber(nextDeploymentNumber); - deployment.setState("COMPLETE"); // Synchronous immediate deployment + Instant started = clock.instant(); + deployment.setStartedAt(started.toString()); + deployment.setPercentageComplete(100.0f); + deployment.setState(strategy.getFinalBakeTimeInMinutes() > 0 ? "BAKING" : "COMPLETE"); + if ("COMPLETE".equals(deployment.getState())) { + deployment.setCompletedAt(started.toString()); + } deployment.setDescription((String) request.get("Description")); deploymentStore.put(appId + "::" + envId + "::" + deployment.getDeploymentNumber(), deployment); @@ -560,20 +575,101 @@ public class AppConfigService { // Update active configuration activeConfigStore.put(envId + "::" + profileId, version); - LOG.infov("Started deployment for app {0}, env {1}, profile {2}, version {3}. State: COMPLETE", appId, envId, profileId, version); + LOG.infov("Started deployment for app {0}, env {1}, profile {2}, version {3}. State: {4}", + appId, envId, profileId, version, deployment.getState()); return deployment; } - public Deployment getDeployment(String applicationIdentifier, + public synchronized Deployment getDeployment(String applicationIdentifier, String environmentIdentifier, int deploymentNumber) { String appId = resolveApplication(applicationIdentifier).getId(); String envId = resolveEnvironment(appId, environmentIdentifier).getId(); - return deploymentStore.get(appId + "::" + envId + "::" + deploymentNumber) + Deployment deployment = deploymentStore.get(appId + "::" + envId + "::" + deploymentNumber) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Deployment not found", 404)); + return refreshDeployment(deployment); } - public DeploymentPage listDeployments(String applicationIdentifier, + public synchronized Deployment stopDeployment(String applicationIdentifier, String environmentIdentifier, + int deploymentNumber, boolean allowRevert) { + Deployment deployment = copy(getDeployment(applicationIdentifier, environmentIdentifier, deploymentNumber)); + String state = deployment.getState(); + boolean completed = "COMPLETE".equals(state); + if (!"DEPLOYING".equals(state) && !(allowRevert && ("BAKING".equals(state) || completed))) { + throw new AwsException("BadRequestException", "The deployment cannot be stopped in its current state.", 400); + } + if (completed && (deployment.getCompletedAt() == null + || clock.instant().isAfter(Instant.parse(deployment.getCompletedAt()).plus(Duration.ofHours(72))))) { + throw new AwsException("BadRequestException", + "A completed deployment can only be reverted within 72 hours of its recorded completion.", 400); + } + List available = deploymentStore.scan(k -> true).stream() + .filter(row -> deployment.getApplicationId().equals(row.getApplicationId())) + .filter(row -> deployment.getEnvironmentId().equals(row.getEnvironmentId())) + .filter(row -> deployment.getConfigurationProfileId().equals(row.getConfigurationProfileId())) + .filter(row -> List.of("BAKING", "COMPLETE", "DEPLOYING").contains(row.getState())) + .sorted(Comparator.comparingInt(Deployment::getDeploymentNumber).reversed()) + .toList(); + if (available.isEmpty() || available.getFirst().getDeploymentNumber() != deploymentNumber) { + throw new AwsException("BadRequestException", "A newer deployment is active for this configuration.", 400); + } + Deployment previous = available.stream() + .filter(row -> row.getDeploymentNumber() < deploymentNumber) + .filter(row -> !"DEPLOYING".equals(row.getState())) + .findFirst().orElse(null); + if (previous != null) { + ConfigurationProfile profile = resolveConfigurationProfile( + deployment.getApplicationId(), deployment.getConfigurationProfileId()); + String location = previous.getConfigurationLocationUri() != null + ? previous.getConfigurationLocationUri() : profile.getLocationUri(); + if ("hosted".equals(location) && !hasHostedConfigurationVersion(previous)) { + throw new AwsException("BadRequestException", + "The previous hosted configuration version is no longer available.", 400); + } + } + String activeKey = deployment.getEnvironmentId() + "::" + deployment.getConfigurationProfileId(); + if (previous == null) { + activeConfigStore.delete(activeKey); + } else { + activeConfigStore.put(activeKey, previous.getConfigurationVersion()); + } + deployment.setState(completed ? "REVERTED" : "ROLLED_BACK"); + deployment.setPercentageComplete(0.0f); + deployment.setCompletedAt(clock.instant().toString()); + deploymentStore.put(deployment.getApplicationId() + "::" + deployment.getEnvironmentId() + + "::" + deploymentNumber, deployment); + return deployment; + } + + private boolean hasHostedConfigurationVersion(Deployment deployment) { + int versionNumber; + try { + versionNumber = Integer.parseInt(deployment.getConfigurationVersion()); + } catch (NumberFormatException ignored) { + // Non-numeric deployed versions cannot identify content in the hosted version store. + return false; + } + return versionStore.get(deployment.getApplicationId() + "::" + deployment.getConfigurationProfileId() + + "::" + versionNumber).isPresent(); + } + + private Deployment refreshDeployment(Deployment deployment) { + if ("BAKING".equals(deployment.getState()) && deployment.getStartedAt() != null + && deployment.getFinalBakeTimeInMinutes() != null) { + Instant completed = Instant.parse(deployment.getStartedAt()) + .plus(Duration.ofMinutes(deployment.getFinalBakeTimeInMinutes())); + if (!clock.instant().isBefore(completed)) { + deployment = copy(deployment); + deployment.setState("COMPLETE"); + deployment.setCompletedAt(completed.toString()); + deploymentStore.put(deployment.getApplicationId() + "::" + deployment.getEnvironmentId() + + "::" + deployment.getDeploymentNumber(), deployment); + } + } + return deployment; + } + + public synchronized DeploymentPage listDeployments(String applicationIdentifier, String environmentIdentifier, Integer maxResults, String nextToken) { @@ -629,6 +725,7 @@ public class AppConfigService { * is read from the profile. */ private DeploymentSummary toDeploymentSummary(Deployment deployment) { + deployment = refreshDeployment(deployment); DeploymentSummary summary = new DeploymentSummary(); summary.setConfigurationProfileId(deployment.getConfigurationProfileId()); summary.setConfigurationVersion(deployment.getConfigurationVersion()); @@ -655,7 +752,11 @@ public class AppConfigService { summary.setGrowthType(strategy.getGrowthType()); }); } - summary.setPercentageComplete("COMPLETE".equals(deployment.getState()) ? 100.0f : 0.0f); + summary.setPercentageComplete(deployment.getPercentageComplete() != null + ? deployment.getPercentageComplete() : "COMPLETE".equals(deployment.getState()) ? 100.0f : 0.0f); + summary.setStartedAt(deployment.getStartedAt()); + summary.setCompletedAt(deployment.getCompletedAt()); + return summary; } @@ -674,7 +775,7 @@ public class AppConfigService { public record DeploymentPage(List items, String nextToken) { } - public String getActiveVersion(String envId, String profileId) { + public synchronized String getActiveVersion(String envId, String profileId) { return activeConfigStore.get(envId + "::" + profileId).orElse(null); } diff --git a/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Deployment.java b/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Deployment.java index db751bde0b..405405ffb5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Deployment.java +++ b/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Deployment.java @@ -44,6 +44,15 @@ public class Deployment { private String state; // BAKING, VALIDATING, DEPLOYING, COMPLETE, ROLLING_BACK, ROLLED_BACK @JsonProperty("Description") private String description; + @JsonProperty("StartedAt") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String startedAt; + @JsonProperty("CompletedAt") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String completedAt; + @JsonProperty("PercentageComplete") + @JsonInclude(JsonInclude.Include.NON_NULL) + private Float percentageComplete; public Deployment() {} @@ -88,4 +97,13 @@ public class Deployment { public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } + + public String getStartedAt() { return startedAt; } + public void setStartedAt(String startedAt) { this.startedAt = startedAt; } + + public String getCompletedAt() { return completedAt; } + public void setCompletedAt(String completedAt) { this.completedAt = completedAt; } + + public Float getPercentageComplete() { return percentageComplete; } + public void setPercentageComplete(Float percentageComplete) { this.percentageComplete = percentageComplete; } } diff --git a/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigDeploymentLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigDeploymentLifecycleTest.java new file mode 100644 index 0000000000..7869855f1a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigDeploymentLifecycleTest.java @@ -0,0 +1,264 @@ +package io.github.hectorvent.floci.services.appconfig; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.ServiceConfigAccess; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.appconfig.model.Deployment; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class AppConfigDeploymentLifecycleTest { + private static final Instant START = Instant.parse("2026-01-01T00:00:00Z"); + + private final List openFactories = new ArrayList<>(); + + @AfterEach + void closeRemainingFactories() { + List cleanup = openFactories.reversed().stream() + .map(factory -> factory::shutdownAll).toList(); + openFactories.clear(); + assertAll(cleanup); + } + + @TempDir + Path directory; + + @Test + void bakingDeadlineAndRollbackSurviveRestart() { + StorageFactory first = factory(); + AppConfigService service = service(first, START); + Scope scope = scope(service); + deploy(service, scope, "1", scope.fast()); + Deployment baking = deploy(service, scope, "2", scope.bake()); + assertEquals("BAKING", baking.getState()); + assertEquals(100.0f, baking.getPercentageComplete()); + close(first); + + StorageFactory second = factory(); + service = service(second, START.plusSeconds(30)); + assertEquals("BAKING", service.getDeployment(scope.app(), scope.env(), baking.getDeploymentNumber()).getState()); + assertEquals("2", service.getActiveVersion(scope.env(), scope.profile())); + assertEquals("ROLLED_BACK", service.stopDeployment( + scope.app(), scope.env(), baking.getDeploymentNumber(), true).getState()); + assertEquals("1", service.getActiveVersion(scope.env(), scope.profile())); + close(second); + + StorageFactory third = factory(); + service = service(third, START.plusSeconds(120)); + assertEquals("ROLLED_BACK", service.getDeployment(scope.app(), scope.env(), baking.getDeploymentNumber()).getState()); + assertEquals("1", service.getActiveVersion(scope.env(), scope.profile())); + close(third); + } + + @Test + void completionUsesTheDeadlineAndExpiredRevertDoesNotChangeConfiguration() { + StorageFactory first = factory(); + AppConfigService service = service(first, START); + Scope scope = scope(service); + Deployment baking = deploy(service, scope, "1", scope.bake()); + close(first); + + StorageFactory second = factory(); + AppConfigService afterDeadline = service(second, START.plus(Duration.ofHours(74))); + Deployment completed = afterDeadline.getDeployment(scope.app(), scope.env(), baking.getDeploymentNumber()); + assertEquals("COMPLETE", completed.getState()); + assertEquals(START.plusSeconds(60).toString(), completed.getCompletedAt()); + assertEquals("COMPLETE", afterDeadline.listDeployments( + scope.app(), scope.env(), 50, null).items().getFirst().getState()); + AwsException failure = assertThrows(AwsException.class, () -> afterDeadline.stopDeployment( + scope.app(), scope.env(), baking.getDeploymentNumber(), true)); + assertEquals("BadRequestException", failure.getErrorCode()); + assertEquals("1", afterDeadline.getActiveVersion(scope.env(), scope.profile())); + close(second); + } + + @Test + void newerDeploymentProtectsItsConfigurationFromAnOlderRevert() { + StorageFactory storage = factory(); + AppConfigService service = service(storage, START); + Scope scope = scope(service); + Deployment first = deploy(service, scope, "1", scope.fast()); + Deployment second = deploy(service, scope, "2", scope.fast()); + assertThrows(AwsException.class, () -> service.stopDeployment( + scope.app(), scope.env(), first.getDeploymentNumber(), true)); + assertEquals("2", service.getActiveVersion(scope.env(), scope.profile())); + assertThrows(AwsException.class, () -> service.stopDeployment( + scope.app(), scope.env(), second.getDeploymentNumber(), false)); + assertEquals("REVERTED", service.stopDeployment( + scope.app(), scope.env(), second.getDeploymentNumber(), true).getState()); + assertEquals("1", service.getActiveVersion(scope.env(), scope.profile())); + close(storage); + } + + @Test + void deletedPreviousContentRejectsRevertWithoutChangingEitherStore() { + StorageFactory storage = factory(); + AppConfigService service = service(storage, START); + Scope scope = scope(service); + deploy(service, scope, "1", scope.fast()); + Deployment current = deploy(service, scope, "2", scope.fast()); + service.deleteHostedConfigurationVersion(scope.app(), scope.profile(), 1); + + AwsException failure = assertThrows(AwsException.class, () -> service.stopDeployment( + scope.app(), scope.env(), current.getDeploymentNumber(), true)); + assertEquals("BadRequestException", failure.getErrorCode()); + assertEquals("2", service.getActiveVersion(scope.env(), scope.profile())); + assertEquals("COMPLETE", service.getDeployment(scope.app(), scope.env(), + current.getDeploymentNumber()).getState()); + assertEquals(START.toString(), current.getCompletedAt()); + close(storage); + + StorageFactory restarted = factory(); + AppConfigService restored = service(restarted, START); + assertEquals("2", restored.getActiveVersion(scope.env(), scope.profile())); + assertEquals("COMPLETE", restored.getDeployment(scope.app(), scope.env(), + current.getDeploymentNumber()).getState()); + } + + @Test + void rollbackDoesNotMutateAnEarlierDeploymentResponse() { + StorageFactory storage = factory(); + AppConfigService service = service(storage, START); + Scope scope = scope(service); + deploy(service, scope, "1", scope.fast()); + Deployment baking = deploy(service, scope, "2", scope.bake()); + Deployment response = service.getDeployment(scope.app(), scope.env(), baking.getDeploymentNumber()); + Deployment stopped = service.stopDeployment(scope.app(), scope.env(), baking.getDeploymentNumber(), true); + assertNotSame(response, stopped); + assertEquals("BAKING", response.getState()); + assertEquals(100.0f, response.getPercentageComplete()); + assertNull(response.getCompletedAt()); + assertEquals("ROLLED_BACK", stopped.getState()); + assertEquals("1", service.getActiveVersion(scope.env(), scope.profile())); + } + + @Test + void completionDoesNotMutateAnEarlierResponseAndListUsesTheNewSnapshot() { + StorageFactory storage = factory(); + Clock clock = mock(Clock.class); + when(clock.instant()).thenReturn(START); + AppConfigService service = new AppConfigService(storage, mock(EmulatorConfig.class), clock); + Scope scope = scope(service); + Deployment baking = deploy(service, scope, "1", scope.bake()); + Deployment response = service.getDeployment(scope.app(), scope.env(), baking.getDeploymentNumber()); + when(clock.instant()).thenReturn(START.plusSeconds(60)); + + assertEquals("COMPLETE", service.listDeployments(scope.app(), scope.env(), 50, null) + .items().getFirst().getState()); + Deployment completed = service.getDeployment(scope.app(), scope.env(), baking.getDeploymentNumber()); + assertNotSame(response, completed); + assertEquals("BAKING", response.getState()); + assertNull(response.getCompletedAt()); + assertEquals("COMPLETE", completed.getState()); + assertEquals(START.plusSeconds(60).toString(), completed.getCompletedAt()); + } + + @ParameterizedTest + @ValueSource(strings = {"01", "0001", "+1"}) + void numericPreviousVersionUsesTheHostedStoreIdentity(String previousVersion) { + StorageFactory storage = factory(); + AppConfigService service = service(storage, START); + Scope scope = scope(service); + deploy(service, scope, previousVersion, scope.fast()); + Deployment current = deploy(service, scope, "2", scope.fast()); + + Deployment reverted = service.stopDeployment(scope.app(), scope.env(), current.getDeploymentNumber(), true); + assertEquals("REVERTED", reverted.getState()); + assertEquals(previousVersion, service.getActiveVersion(scope.env(), scope.profile())); + assertEquals("COMPLETE", current.getState()); + close(storage); + + StorageFactory restarted = factory(); + AppConfigService restored = service(restarted, START); + assertEquals(previousVersion, restored.getActiveVersion(scope.env(), scope.profile())); + assertEquals("REVERTED", restored.getDeployment(scope.app(), scope.env(), + current.getDeploymentNumber()).getState()); + } + + @ParameterizedTest + @ValueSource(strings = {"invalid", "2147483648", "", "0003"}) + void unavailablePreviousVersionRejectsRevertWithoutChangingActiveState(String previousVersion) { + StorageFactory storage = factory(); + AppConfigService service = service(storage, START); + Scope scope = scope(service); + deploy(service, scope, previousVersion, scope.fast()); + Deployment current = deploy(service, scope, "2", scope.fast()); + + AwsException failure = assertThrows(AwsException.class, () -> service.stopDeployment( + scope.app(), scope.env(), current.getDeploymentNumber(), true)); + assertEquals("BadRequestException", failure.getErrorCode()); + assertEquals("2", service.getActiveVersion(scope.env(), scope.profile())); + assertEquals("COMPLETE", service.getDeployment(scope.app(), scope.env(), + current.getDeploymentNumber()).getState()); + assertEquals("COMPLETE", current.getState()); + } + + private Scope scope(AppConfigService service) { + String app = service.createApplication(Map.of("Name", "deployment-lifecycle")).getId(); + String env = service.createEnvironment(app, Map.of("Name", "environment")).getId(); + String profile = service.createConfigurationProfile(app, Map.of("Name", "profile", "LocationUri", "hosted")).getId(); + service.createHostedConfigurationVersion(app, profile, "one".getBytes(StandardCharsets.UTF_8), + "text/plain", "first"); + service.createHostedConfigurationVersion(app, profile, "two".getBytes(StandardCharsets.UTF_8), + "text/plain", "second"); + String fast = service.createDeploymentStrategy(Map.of("Name", "fast", "FinalBakeTimeInMinutes", 0)).getId(); + String bake = service.createDeploymentStrategy(Map.of("Name", "bake", "FinalBakeTimeInMinutes", 1)).getId(); + return new Scope(app, env, profile, fast, bake); + } + + private Deployment deploy(AppConfigService service, Scope scope, String version, String strategy) { + return service.startDeployment(scope.app(), scope.env(), Map.of( + "ConfigurationProfileId", scope.profile(), "ConfigurationVersion", version, + "DeploymentStrategyId", strategy)); + } + + private AppConfigService service(StorageFactory storage, Instant time) { + return new AppConfigService(storage, mock(EmulatorConfig.class), Clock.fixed(time, ZoneOffset.UTC)); + } + + private StorageFactory factory() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.defaultAccountId()).thenReturn("000000000000"); + when(config.storage().persistentPath()).thenReturn(directory.toString()); + ServiceConfigAccess access = mock(ServiceConfigAccess.class); + when(access.storageMode(anyString())).thenReturn("persistent"); + StorageFactory storage = new StorageFactory(config, access); + openFactories.add(storage); + return storage; + } + + private void close(StorageFactory storage) { + try { + storage.shutdownAll(); + } finally { + openFactories.remove(storage); + } + } + + private record Scope(String app, String env, String profile, String fast, String bake) {} +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigIntegrationTest.java index bfa5fdab10..565e5c8bf3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigIntegrationTest.java @@ -376,7 +376,8 @@ class AppConfigIntegrationTest { .when().post("/applications/" + appId + "/environments/" + envId + "/deployments") .then() .statusCode(201) - .body("State", equalTo("COMPLETE")) + .body("State", equalTo("BAKING")) + .body("PercentageComplete", equalTo(100.0f)) .body("DeploymentStrategyId", equalTo("AppConfig.AllAtOnce")); } @@ -391,7 +392,8 @@ class AppConfigIntegrationTest { .body("Items[0].DeploymentNumber", equalTo(3)) .body("Items[0].ConfigurationProfileId", equalTo(profileId)) .body("Items[0].ConfigurationVersion", equalTo("1")) - .body("Items[0].State", equalTo("COMPLETE")) + .body("Items[0].State", equalTo("BAKING")) + .body("Items[0].PercentageComplete", equalTo(100.0f)) .body("Items[0].ConfigurationName", equalTo("test-profile")) .body("Items[0].Type", equalTo("AWS.Freeform")) .extract().path("NextToken");