diff --git a/docs/services/appconfig.md b/docs/services/appconfig.md index b2c23f6873..94da796bc7 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, - `DeleteDeploymentStrategy` - `StartDeployment` - `GetDeployment` +- `ListDeployments` (`GET /applications/{ApplicationId}/environments/{EnvironmentId}/deployments`) ## Data Plane (AppConfigData) {#data-plane} 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 d96cec673d..cb88d460a0 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 @@ -3,14 +3,26 @@ package io.github.hectorvent.floci.services.appconfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import io.github.hectorvent.floci.core.common.AwsException; -import io.github.hectorvent.floci.services.appconfig.model.*; +import io.github.hectorvent.floci.core.common.Pagination; +import io.github.hectorvent.floci.services.appconfig.model.Application; +import io.github.hectorvent.floci.services.appconfig.model.ConfigurationProfile; +import io.github.hectorvent.floci.services.appconfig.model.Deployment; +import io.github.hectorvent.floci.services.appconfig.model.DeploymentStrategy; +import io.github.hectorvent.floci.services.appconfig.model.Environment; +import io.github.hectorvent.floci.services.appconfig.model.HostedConfigurationVersion; +import io.github.hectorvent.floci.services.appconfig.model.HostedConfigurationVersionSummary; import jakarta.inject.Inject; -import jakarta.ws.rs.*; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.HeaderParam; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; -import org.jboss.logging.Logger; - import java.io.IOException; import java.util.List; import java.util.Map; @@ -19,8 +31,6 @@ import java.util.Map; @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class AppConfigController { - private static final Logger LOG = Logger.getLogger(AppConfigController.class); - private final AppConfigService service; private final ObjectMapper objectMapper; @@ -228,6 +238,23 @@ public class AppConfigController { return Response.status(201).entity(deployment).build(); } + @GET + @Path("/applications/{appId}/environments/{envId}/deployments") + public Response listDeployments(@PathParam("appId") String appId, + @PathParam("envId") String envId, + @QueryParam("max_results") String maxResults, + @QueryParam("next_token") String nextToken) { + AppConfigService.DeploymentPage page = service.listDeployments(appId, envId, + Pagination.parseMaxResults(maxResults, "BadRequestException"), nextToken); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("Items"); + page.items().forEach(items::addPOJO); + if (page.nextToken() != null) { + root.put("NextToken", page.nextToken()); + } + return Response.ok(root).build(); + } + @GET @Path("/applications/{appId}/environments/{envId}/deployments/{deploymentNumber}") public Response getDeployment(@PathParam("appId") String appId, @PathParam("envId") String envId, @PathParam("deploymentNumber") int deploymentNumber) { 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 e93ce0e412..dba040acfd 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 @@ -5,12 +5,24 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; -import io.github.hectorvent.floci.services.appconfig.model.*; +import io.github.hectorvent.floci.services.appconfig.model.Application; +import io.github.hectorvent.floci.services.appconfig.model.ConfigurationProfile; +import io.github.hectorvent.floci.services.appconfig.model.Deployment; +import io.github.hectorvent.floci.services.appconfig.model.DeploymentStrategy; +import io.github.hectorvent.floci.services.appconfig.model.DeploymentSummary; +import io.github.hectorvent.floci.services.appconfig.model.Environment; +import io.github.hectorvent.floci.services.appconfig.model.HostedConfigurationVersion; +import io.github.hectorvent.floci.services.appconfig.model.HostedConfigurationVersionSummary; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; -import java.util.*; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; @ApplicationScoped public class AppConfigService { @@ -23,6 +35,8 @@ public class AppConfigService { private final StorageBackend versionStore; private final StorageBackend deploymentStore; private final StorageBackend activeConfigStore; // envId::profileId -> versionNumber + private final Map deploymentPageTokens = new ConcurrentHashMap<>(); + private static final int MAX_DEPLOYMENT_PAGE_TOKENS = 1000; @Inject public AppConfigService(StorageFactory storageFactory, EmulatorConfig config) { @@ -294,6 +308,87 @@ public class AppConfigService { .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Deployment not found", 404)); } + public DeploymentPage listDeployments(String appId, String envId, Integer maxResults, String nextToken) { + getEnvironment(appId, envId); + int pageSize = maxResults == null ? 50 : maxResults; + if (pageSize < 1 || pageSize > 50) { + throw new AwsException("BadRequestException", "max_results must be between 1 and 50", 400); + } + + String scope = appId + "::" + envId; + Integer afterDeploymentNumber = null; + if (nextToken != null) { + DeploymentPageToken token = deploymentPageTokens.get(nextToken); + if (token == null || !token.scope().equals(scope)) { + throw new AwsException("BadRequestException", "Invalid next_token", 400); + } + afterDeploymentNumber = token.lastDeploymentNumber(); + } + + List deployments = deploymentStore.scan(k -> true).stream() + .filter(deployment -> appId.equals(deployment.getApplicationId())) + .filter(deployment -> envId.equals(deployment.getEnvironmentId())) + .sorted(Comparator.comparingInt(Deployment::getDeploymentNumber).reversed()) + .toList(); + + int start = 0; + if (afterDeploymentNumber != null) { + while (start < deployments.size() + && deployments.get(start).getDeploymentNumber() >= afterDeploymentNumber) { + start++; + } + } + + int end = Math.min(start + pageSize, deployments.size()); + List items = deployments.subList(start, end).stream() + .map(this::toDeploymentSummary) + .toList(); + String resultToken = null; + if (end < deployments.size()) { + resultToken = createDeploymentPageToken(scope, + items.get(items.size() - 1).getDeploymentNumber()); + } else if (nextToken != null) { + deploymentPageTokens.remove(nextToken); + } + return new DeploymentPage(items, resultToken); + } + + private DeploymentSummary toDeploymentSummary(Deployment deployment) { + DeploymentSummary summary = new DeploymentSummary(); + summary.setConfigurationProfileId(deployment.getConfigurationProfileId()); + summary.setConfigurationVersion(deployment.getConfigurationVersion()); + summary.setDeploymentNumber(deployment.getDeploymentNumber()); + summary.setState(deployment.getState()); + summary.setConfigurationName(deployment.getConfigurationName()); + ConfigurationProfile profile = profileStore.get(deployment.getConfigurationProfileId()).orElse(null); + if (profile != null) { + summary.setConfigurationName(profile.getName()); + summary.setType(profile.getType()); + } + DeploymentStrategy strategy = getDeploymentStrategy(deployment.getDeploymentStrategyId()); + summary.setDeploymentDurationInMinutes(strategy.getDeploymentDurationInMinutes()); + summary.setFinalBakeTimeInMinutes(strategy.getFinalBakeTimeInMinutes()); + summary.setGrowthFactor(strategy.getGrowthFactor()); + summary.setGrowthType(strategy.getGrowthType()); + summary.setPercentageComplete("COMPLETE".equals(deployment.getState()) ? 100.0f : 0.0f); + return summary; + } + + private String createDeploymentPageToken(String scope, int lastDeploymentNumber) { + while (deploymentPageTokens.size() >= MAX_DEPLOYMENT_PAGE_TOKENS) { + deploymentPageTokens.keySet().stream().findFirst().ifPresent(deploymentPageTokens::remove); + } + String token = UUID.randomUUID().toString().replace("-", ""); + deploymentPageTokens.put(token, new DeploymentPageToken(scope, lastDeploymentNumber)); + return token; + } + + private record DeploymentPageToken(String scope, int lastDeploymentNumber) { + } + + public record DeploymentPage(List items, String nextToken) { + } + public 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/DeploymentSummary.java b/src/main/java/io/github/hectorvent/floci/services/appconfig/model/DeploymentSummary.java new file mode 100644 index 0000000000..523b8da268 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appconfig/model/DeploymentSummary.java @@ -0,0 +1,70 @@ +package io.github.hectorvent.floci.services.appconfig.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class DeploymentSummary { + @JsonProperty("CompletedAt") + private String completedAt; + @JsonProperty("ConfigurationName") + private String configurationName; + @JsonProperty("ConfigurationProfileId") + private String configurationProfileId; + @JsonProperty("ConfigurationVersion") + private String configurationVersion; + @JsonProperty("DeploymentDurationInMinutes") + private Integer deploymentDurationInMinutes; + @JsonProperty("DeploymentNumber") + private int deploymentNumber; + @JsonProperty("FinalBakeTimeInMinutes") + private Integer finalBakeTimeInMinutes; + @JsonProperty("GrowthFactor") + private Float growthFactor; + @JsonProperty("GrowthType") + private String growthType; + @JsonProperty("PercentageComplete") + private Float percentageComplete; + @JsonProperty("StartedAt") + private String startedAt; + @JsonProperty("State") + private String state; + @JsonProperty("Type") + private String type; + @JsonProperty("VersionLabel") + private String versionLabel; + + public DeploymentSummary() { + } + + public String getCompletedAt() { return completedAt; } + public void setCompletedAt(String completedAt) { this.completedAt = completedAt; } + public String getConfigurationName() { return configurationName; } + public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } + public String getConfigurationProfileId() { return configurationProfileId; } + public void setConfigurationProfileId(String configurationProfileId) { this.configurationProfileId = configurationProfileId; } + public String getConfigurationVersion() { return configurationVersion; } + public void setConfigurationVersion(String configurationVersion) { this.configurationVersion = configurationVersion; } + public Integer getDeploymentDurationInMinutes() { return deploymentDurationInMinutes; } + public void setDeploymentDurationInMinutes(Integer deploymentDurationInMinutes) { this.deploymentDurationInMinutes = deploymentDurationInMinutes; } + public int getDeploymentNumber() { return deploymentNumber; } + public void setDeploymentNumber(int deploymentNumber) { this.deploymentNumber = deploymentNumber; } + public Integer getFinalBakeTimeInMinutes() { return finalBakeTimeInMinutes; } + public void setFinalBakeTimeInMinutes(Integer finalBakeTimeInMinutes) { this.finalBakeTimeInMinutes = finalBakeTimeInMinutes; } + public Float getGrowthFactor() { return growthFactor; } + public void setGrowthFactor(Float growthFactor) { this.growthFactor = growthFactor; } + public String getGrowthType() { return growthType; } + public void setGrowthType(String growthType) { this.growthType = growthType; } + public Float getPercentageComplete() { return percentageComplete; } + public void setPercentageComplete(Float percentageComplete) { this.percentageComplete = percentageComplete; } + public String getStartedAt() { return startedAt; } + public void setStartedAt(String startedAt) { this.startedAt = startedAt; } + public String getState() { return state; } + public void setState(String state) { this.state = state; } + public String getType() { return type; } + public void setType(String type) { this.type = type; } + public String getVersionLabel() { return versionLabel; } + public void setVersionLabel(String versionLabel) { this.versionLabel = versionLabel; } +} 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 821454665e..0a72b2519c 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 @@ -28,6 +28,8 @@ class AppConfigIntegrationTest { private static String emptyAppId; private static String emptyEnvId; private static String emptyProfileId; + private static String deploymentNextToken; + private static String secondDeploymentNextToken; @BeforeAll static void setup() { @@ -372,6 +374,92 @@ class AppConfigIntegrationTest { .body("DeploymentStrategyId", equalTo("AppConfig.AllAtOnce")); } + @Test @Order(39) + void listDeploymentsReturnsDescendingFirstPage() { + deploymentNextToken = given() + .queryParam("max_results", 1) + .when().get("/applications/" + appId + "/environments/" + envId + "/deployments") + .then() + .statusCode(200) + .body("Items.size()", equalTo(1)) + .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].ConfigurationName", equalTo("test-profile")) + .body("Items[0].Type", equalTo("AWS.Freeform")) + .extract().path("NextToken"); + } + + @Test @Order(40) + void listDeploymentsReturnsSecondPageAndConsumesFinalToken() { + secondDeploymentNextToken = given() + .queryParam("max_results", 1) + .queryParam("next_token", deploymentNextToken) + .when().get("/applications/" + appId + "/environments/" + envId + "/deployments") + .then() + .statusCode(200) + .body("Items.size()", equalTo(1)) + .body("Items[0].DeploymentNumber", equalTo(2)) + .body("NextToken", notNullValue()) + .extract().path("NextToken"); + + given() + .queryParam("max_results", 1) + .queryParam("next_token", secondDeploymentNextToken) + .when().get("/applications/" + appId + "/environments/" + envId + "/deployments") + .then() + .statusCode(200) + .body("Items[0].DeploymentNumber", equalTo(1)) + .body("NextToken", nullValue()); + + given() + .queryParam("next_token", secondDeploymentNextToken) + .when().get("/applications/" + appId + "/environments/" + envId + "/deployments") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test @Order(41) + void listDeploymentsRejectsInvalidPagination() { + given() + .queryParam("max_results", 0) + .when().get("/applications/" + appId + "/environments/" + envId + "/deployments") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + + given() + .queryParam("max_results", 51) + .when().get("/applications/" + appId + "/environments/" + envId + "/deployments") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + + given() + .queryParam("max_results", "not-a-number") + .when().get("/applications/" + appId + "/environments/" + envId + "/deployments") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test @Order(42) + void listDeploymentsRejectsMissingResources() { + given() + .when().get("/applications/missing-app/environments/" + envId + "/deployments") + .then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + + given() + .when().get("/applications/" + appId + "/environments/missing-env/deployments") + .then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + } + // ──────────────────────────── Application tagging ──────────────────────────── @Test @Order(17) diff --git a/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceTest.java new file mode 100644 index 0000000000..d3b2cae2cd --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceTest.java @@ -0,0 +1,125 @@ +package io.github.hectorvent.floci.services.appconfig; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.appconfig.model.Application; +import io.github.hectorvent.floci.services.appconfig.model.Deployment; +import io.github.hectorvent.floci.services.appconfig.model.Environment; +import io.github.hectorvent.floci.services.appconfig.model.DeploymentSummary; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class AppConfigServiceTest { + private AccountAwareStorageBackend applicationStore; + private AccountAwareStorageBackend environmentStore; + private AccountAwareStorageBackend deploymentStore; + private AppConfigService service; + + @BeforeEach + void setUp() { + applicationStore = mock(AccountAwareStorageBackend.class); + environmentStore = mock(AccountAwareStorageBackend.class); + deploymentStore = mock(AccountAwareStorageBackend.class); + Map deployments = new HashMap<>(); + doAnswer(invocation -> { + deployments.put(invocation.getArgument(0, String.class), invocation.getArgument(1, Deployment.class)); + return null; + }).when(deploymentStore).put(anyString(), any(Deployment.class)); + when(deploymentStore.scan(any())).thenAnswer(invocation -> List.copyOf(deployments.values())); + StorageFactory storageFactory = mock(StorageFactory.class); + doAnswer(invocation -> switch (invocation.getArgument(1, String.class)) { + case "appconfig-applications.json" -> applicationStore; + case "appconfig-environments.json" -> environmentStore; + case "appconfig-deployments.json" -> deploymentStore; + default -> mock(AccountAwareStorageBackend.class); + }).when(storageFactory).create(anyString(), anyString(), any(TypeReference.class)); + + Application application = new Application(); + application.setId("app"); + applicationStore.put("app", application); + when(applicationStore.get("app")).thenReturn(Optional.of(application)); + Environment environment = new Environment(); + environment.setId("env"); + environment.setApplicationId("app"); + environmentStore.put("env", environment); + when(environmentStore.get("env")).thenReturn(Optional.of(environment)); + service = new AppConfigService(storageFactory, mock(EmulatorConfig.class)); + } + + @Test + void listDeploymentsReturnsDescendingPages() { + deploymentStore.put("app::env::1", deployment("app", "env", 1)); + deploymentStore.put("app::env::2", deployment("app", "env", 2)); + + AppConfigService.DeploymentPage page = service.listDeployments("app", "env", 1, null); + + assertEquals(List.of(2), page.items().stream().map(DeploymentSummary::getDeploymentNumber).toList()); + assertNotNull(page.nextToken()); + } + + @Test + void listDeploymentsCursorSurvivesNewDeployment() { + deploymentStore.put("app::env::1", deployment("app", "env", 1)); + deploymentStore.put("app::env::2", deployment("app", "env", 2)); + deploymentStore.put("app::env::3", deployment("app", "env", 3)); + + AppConfigService.DeploymentPage firstPage = service.listDeployments("app", "env", 1, null); + deploymentStore.put("app::env::4", deployment("app", "env", 4)); + + AppConfigService.DeploymentPage secondPage = service.listDeployments( + "app", "env", 1, firstPage.nextToken()); + + assertEquals(List.of(2), secondPage.items().stream() + .map(DeploymentSummary::getDeploymentNumber).toList()); + } + + @Test + void listDeploymentsFiltersApplicationAndEnvironment() { + deploymentStore.put("app::env::1", deployment("app", "env", 1)); + deploymentStore.put("other::env::2", deployment("other", "env", 2)); + deploymentStore.put("app::other-env::3", deployment("app", "other-env", 3)); + + AppConfigService.DeploymentPage page = service.listDeployments("app", "env", null, null); + + assertEquals(List.of(1), page.items().stream().map(DeploymentSummary::getDeploymentNumber).toList()); + } + + @Test + void listDeploymentsRejectsInvalidPageSize() { + assertThrows(RuntimeException.class, () -> service.listDeployments("app", "env", 0, null)); + assertThrows(RuntimeException.class, () -> service.listDeployments("app", "env", 51, null)); + } + + @Test + void listDeploymentsRejectsUnknownToken() { + assertThrows(RuntimeException.class, () -> service.listDeployments("app", "env", 1, "unknown")); + } + + private static Deployment deployment(String applicationId, String environmentId, int number) { + Deployment deployment = new Deployment(); + deployment.setApplicationId(applicationId); + deployment.setEnvironmentId(environmentId); + deployment.setDeploymentNumber(number); + deployment.setConfigurationProfileId("profile"); + deployment.setConfigurationVersion("version"); + deployment.setDeploymentStrategyId("AppConfig.AllAtOnce"); + deployment.setState("COMPLETE"); + return deployment; + } +}