diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayResourceMethodsCompatibilityTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayResourceMethodsCompatibilityTest.java new file mode 100644 index 0000000000..492a594077 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayResourceMethodsCompatibilityTest.java @@ -0,0 +1,98 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.apigateway.ApiGatewayClient; +import software.amazon.awssdk.services.apigateway.model.IntegrationType; +import software.amazon.awssdk.services.apigateway.model.Method; +import software.amazon.awssdk.services.apigateway.model.Resource; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("API Gateway embedded resource methods") +class ApiGatewayResourceMethodsCompatibilityTest { + + @Test + @DisplayName("Collection and individual resource reads embed supported method fields") + void sdkResourceReadsEmbedMethodConfiguration() { + try (ApiGatewayClient client = TestFixtures.apiGatewayClient()) { + String apiId = client.createRestApi(request -> request + .name(TestFixtures.uniqueName("resource-methods"))).id(); + try { + String rootId = client.getResources(request -> request.restApiId(apiId)).items().get(0).id(); + String resourceId = client.createResource(request -> request.restApiId(apiId) + .parentId(rootId).pathPart("widgets")).id(); + client.putMethod(request -> request.restApiId(apiId).resourceId(resourceId).httpMethod("GET") + .authorizationType("NONE") + .requestParameters(Map.of("method.request.header.X-Trace", true)) + .requestModels(Map.of("application/json", "Empty"))); + client.putMethod(request -> request.restApiId(apiId).resourceId(resourceId).httpMethod("POST") + .authorizationType("AWS_IAM").apiKeyRequired(true)); + client.putIntegration(request -> request.restApiId(apiId).resourceId(resourceId).httpMethod("GET") + .type(IntegrationType.MOCK).timeoutInMillis(9000) + .requestTemplates(Map.of("application/json", "{\"statusCode\":200}"))); + client.putMethodResponse(request -> request.restApiId(apiId).resourceId(resourceId).httpMethod("GET") + .statusCode("200").responseParameters(Map.of("method.response.header.X-Trace", true))); + + List resources = client.getResources(request -> request.restApiId(apiId) + .embed("methods")).items(); + Resource embedded = resources.stream().filter(resource -> resource.id().equals(resourceId)) + .findFirst().orElseThrow(); + assertThat(embedded.resourceMethods()).containsOnlyKeys("GET", "POST"); + Method get = embedded.resourceMethods().get("GET"); + assertThat(get.httpMethod()).isEqualTo("GET"); + assertThat(get.authorizationType()).isEqualTo("NONE"); + assertThat(get.requestParameters()).containsEntry("method.request.header.X-Trace", true); + assertThat(get.requestModels()).containsEntry("application/json", "Empty"); + assertThat(get.methodIntegration().type()).isEqualTo(IntegrationType.MOCK); + assertThat(get.methodIntegration().timeoutInMillis()).isEqualTo(9000); + assertThat(get.methodIntegration().requestTemplates()) + .containsEntry("application/json", "{\"statusCode\":200}"); + assertThat(get.methodResponses().get("200").responseParameters()) + .containsEntry("method.response.header.X-Trace", true); + assertThat(embedded.resourceMethods().get("POST").authorizationType()).isEqualTo("AWS_IAM"); + assertThat(embedded.resourceMethods().get("POST").apiKeyRequired()).isTrue(); + + assertThat(client.getResource(request -> request.restApiId(apiId).resourceId(resourceId) + .embed("methods")).resourceMethods()).isEqualTo(embedded.resourceMethods()); + Resource summary = client.getResources(request -> request.restApiId(apiId)).items().stream() + .filter(resource -> resource.id().equals(resourceId)).findFirst().orElseThrow(); + assertThat(summary.resourceMethods()).containsOnlyKeys("GET", "POST"); + assertThat(summary.resourceMethods().get("GET").httpMethod()).isNull(); + assertThat(summary.resourceMethods().get("GET").methodIntegration()).isNull(); + assertThat(client.getResource(request -> request.restApiId(apiId).resourceId(resourceId)) + .resourceMethods()).isEqualTo(summary.resourceMethods()); + assertThat(client.getMethod(request -> request.restApiId(apiId).resourceId(resourceId) + .httpMethod("GET")).methodIntegration().type()).isEqualTo(IntegrationType.MOCK); + } finally { + client.deleteRestApi(request -> request.restApiId(apiId)); + } + } + } + + @Test + @DisplayName("Root resource ANY method is listed and disappears after deletion") + void sdkRootMethodsReflectDeletion() { + try (ApiGatewayClient client = TestFixtures.apiGatewayClient()) { + String apiId = client.createRestApi(request -> request + .name(TestFixtures.uniqueName("root-methods"))).id(); + try { + String rootId = client.getResources(request -> request.restApiId(apiId)).items().get(0).id(); + assertThat(client.getResource(request -> request.restApiId(apiId).resourceId(rootId) + .embed("methods")).resourceMethods()).isEmpty(); + client.putMethod(request -> request.restApiId(apiId).resourceId(rootId).httpMethod("ANY") + .authorizationType("NONE")); + assertThat(client.getResources(request -> request.restApiId(apiId).embed("methods")) + .items().get(0).resourceMethods().get("ANY").httpMethod()).isEqualTo("ANY"); + client.deleteMethod(request -> request.restApiId(apiId).resourceId(rootId).httpMethod("ANY")); + assertThat(client.getResources(request -> request.restApiId(apiId).embed("methods")) + .items().get(0).resourceMethods()).isEmpty(); + } finally { + client.deleteRestApi(request -> request.restApiId(apiId)); + } + } + } +} diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index aa1d497a18..7c61fdce99 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -379,6 +379,17 @@ Passthrough keeps repeated values repeated, in both directions: `?tag=a&tag=b` r - **Request** — the body is the rendered `requestTemplates` entry selected by the incoming `Content-Type` (falling back to the type without its charset), subject to `passthroughBehavior` (`NEVER` and `WHEN_NO_TEMPLATES` return `415`). Only headers and query parameters named by `integration.request.*` mappings are forwarded; unmapped inbound headers are **not** passed through — that passthrough is `HTTP_PROXY`'s job. - **Response** — the backend's reply runs through the method's integration responses. As in AWS, `selectionPattern` is matched against the backend's **HTTP status code** (for `AWS`/Lambda integrations it is matched against the error message instead), so `"5\\d{2}"` on a `502` integration response remaps any backend `5xx` to `502`. The matched response's `responseTemplates` render the body, `responseParameters` map `integration.response.header.*` (case-insensitively) or `integration.response.body.` onto `method.response.header.*`, and `$context.responseOverride` assignments take precedence. With no integration responses configured, the backend's status and body are relayed as-is. +### Resource Method Introspection + +`GetResources` and `GetResource` return the configured HTTP method names in `resourceMethods`, +with empty objects by default. Request `embed=methods` to include the supported method fields: +authorization settings, request parameters and models, method responses, and integration +configuration. Resources without methods omit `resourceMethods`. + +For example, `aws apigateway get-resources --rest-api-id --embed methods` lists method +metadata without a separate `get-method` call for each operation. Stage OpenAPI export +(`GetExport`) is not implemented. + ### Integration Settings `PutIntegration` persists and `GetIntegration` returns the full configuration, including the mapping templates and integration responses that IaC tools diff against: diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java index 39cc902340..7dee3e1fd3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java @@ -419,12 +419,14 @@ public class ApiGatewayController { @GET @Path("/restapis/{apiId}/resources") - public Response getResources(@Context HttpHeaders headers, @PathParam("apiId") String apiId) { + public Response getResources(@Context HttpHeaders headers, @PathParam("apiId") String apiId, + @QueryParam("embed") List embed) { String region = regionResolver.resolveRegion(headers); List resources = service.getResources(region, apiId); ObjectNode root = objectMapper.createObjectNode(); ArrayNode items = root.putArray("item"); - resources.forEach(r -> items.add(toResourceNode(r))); + boolean embedMethods = embed != null && embed.contains("methods"); + resources.forEach(r -> items.add(toResourceNode(r, embedMethods))); return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build(); } @@ -432,9 +434,11 @@ public class ApiGatewayController { @Path("/restapis/{apiId}/resources/{resourceId}") public Response getResource(@Context HttpHeaders headers, @PathParam("apiId") String apiId, - @PathParam("resourceId") String resourceId) { + @PathParam("resourceId") String resourceId, + @QueryParam("embed") List embed) { String region = regionResolver.resolveRegion(headers); - return Response.ok(toResourceNode(service.getResource(region, apiId, resourceId))).build(); + boolean embedMethods = embed != null && embed.contains("methods"); + return Response.ok(toResourceNode(service.getResource(region, apiId, resourceId), embedMethods)).build(); } @PATCH @@ -2215,11 +2219,20 @@ public class ApiGatewayController { } private ObjectNode toResourceNode(ApiGatewayResource r) { + return toResourceNode(r, false); + } + + private ObjectNode toResourceNode(ApiGatewayResource r, boolean embedMethods) { ObjectNode node = objectMapper.createObjectNode(); node.put("id", r.getId()); if (r.getParentId() != null) node.put("parentId", r.getParentId()); if (r.getPathPart() != null) node.put("pathPart", r.getPathPart()); node.put("path", r.getPath()); + if (!r.getResourceMethods().isEmpty()) { + ObjectNode methods = node.putObject("resourceMethods"); + r.getResourceMethods().forEach((httpMethod, method) -> methods.set(httpMethod, + embedMethods ? toMethodNode(method, r.getId()) : objectMapper.createObjectNode())); + } return node; } @@ -2245,6 +2258,10 @@ public class ApiGatewayController { if (m.getMethodIntegration() != null) { node.set("methodIntegration", toIntegrationNode(m.getMethodIntegration(), resourceId)); } + if (!m.getMethodResponses().isEmpty()) { + ObjectNode responses = node.putObject("methodResponses"); + m.getMethodResponses().forEach((status, response) -> responses.set(status, toMethodResponseNode(response))); + } return node; } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/ApiGatewayResource.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/ApiGatewayResource.java index 25fe58e0c2..0b0cf6593e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/ApiGatewayResource.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/ApiGatewayResource.java @@ -4,8 +4,8 @@ import io.quarkus.runtime.annotations.RegisterForReflection; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; @JsonIgnoreProperties(ignoreUnknown = true) @RegisterForReflection @@ -16,7 +16,7 @@ public class ApiGatewayResource { private String parentId; private String pathPart; private String path; - private Map resourceMethods = new HashMap<>(); + private Map resourceMethods = new ConcurrentHashMap<>(); public String getId() { return id; } public void setId(String id) { this.id = id; } @@ -35,6 +35,6 @@ public class ApiGatewayResource { public Map getResourceMethods() { return resourceMethods; } public void setResourceMethods(Map resourceMethods) { - this.resourceMethods = resourceMethods != null ? resourceMethods : new HashMap<>(); + this.resourceMethods = resourceMethods != null ? new ConcurrentHashMap<>(resourceMethods) : new ConcurrentHashMap<>(); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodConfig.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodConfig.java index 76e677f325..ed87154fca 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodConfig.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodConfig.java @@ -8,6 +8,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; @JsonIgnoreProperties(ignoreUnknown = true) @RegisterForReflection @@ -21,7 +22,7 @@ public class MethodConfig { private boolean apiKeyRequired; private Map requestParameters = new HashMap<>(); private Map requestModels = new HashMap<>(); - private Map methodResponses = new HashMap<>(); + private Map methodResponses = new ConcurrentHashMap<>(); private Integration methodIntegration; public String getHttpMethod() { return httpMethod; } @@ -56,7 +57,7 @@ public class MethodConfig { public Map getMethodResponses() { return methodResponses; } public void setMethodResponses(Map methodResponses) { - this.methodResponses = methodResponses != null ? methodResponses : new HashMap<>(); + this.methodResponses = methodResponses != null ? new ConcurrentHashMap<>(methodResponses) : new ConcurrentHashMap<>(); } public Integration getMethodIntegration() { return methodIntegration; } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayResourceMethodsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayResourceMethodsIntegrationTest.java new file mode 100644 index 0000000000..1fed60631c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayResourceMethodsIntegrationTest.java @@ -0,0 +1,139 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.anEmptyMap; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; + +@QuarkusTest +class ApiGatewayResourceMethodsIntegrationTest { + + private String apiId; + private String rootId; + private String resourceId; + + @BeforeEach + void setup() { + apiId = given().contentType(ContentType.JSON).body("{\"name\":\"resource-methods\"}") + .when().post("/restapis").then().statusCode(201).extract().path("id"); + rootId = given().when().get(resourcesPath()).then().statusCode(200).extract().path("item[0].id"); + resourceId = given().contentType(ContentType.JSON).body("{\"pathPart\":\"widgets\"}") + .when().post(resourcesPath() + "/" + rootId) + .then().statusCode(201).extract().path("id"); + given().contentType(ContentType.JSON).body(""" + {"authorizationType":"NONE","requestParameters":{"method.request.header.X-Trace":true}, + "requestModels":{"application/json":"Empty"}} + """) + .when().put(methodPath("GET")).then().statusCode(201); + given().contentType(ContentType.JSON).body("{\"authorizationType\":\"AWS_IAM\",\"apiKeyRequired\":true}") + .when().put(methodPath("POST")).then().statusCode(201); + given().contentType(ContentType.JSON).body(""" + {"responseParameters":{"method.response.header.X-Trace":true}} + """) + .when().put(methodPath("GET") + "/responses/200").then().statusCode(201); + given().contentType(ContentType.JSON).body(""" + {"type":"HTTP","httpMethod":"POST","uri":"https://example.invalid/widgets", + "timeoutInMillis":12000,"requestTemplates":{"application/json":"{}"}, + "requestParameters":{"integration.request.header.X-Trace":"method.request.header.X-Trace"}} + """) + .when().put(methodPath("GET") + "/integration").then().statusCode(201); + } + + @AfterEach + void cleanup() { + if (apiId != null) { + given().when().delete("/restapis/" + apiId).then().statusCode(202); + } + } + + @Test + void collectionEmbedReturnsMethodAndIntegrationMetadata() { + given().queryParam("embed", "methods").when().get(resourcesPath()) + .then().statusCode(200) + .body("item.find { it.id == '" + resourceId + "' }.resourceMethods.GET.httpMethod", equalTo("GET")) + .body("item.find { it.id == '" + resourceId + "' }.resourceMethods.GET.authorizationType", equalTo("NONE")) + .body("item.find { it.id == '" + resourceId + "' }.resourceMethods.POST.authorizationType", equalTo("AWS_IAM")) + .body("item.find { it.id == '" + resourceId + "' }.resourceMethods.POST.apiKeyRequired", equalTo(true)) + .body("item.find { it.id == '" + resourceId + "' }.resourceMethods.GET.methodIntegration.uri", + equalTo("https://example.invalid/widgets")); + } + + @Test + void individualEmbedPreservesStoredRequestAndResponseConfiguration() { + given().queryParam("embed", "methods").when().get(resourcePath()) + .then().statusCode(200) + .body("resourceMethods.GET.requestParameters.'method.request.header.X-Trace'", equalTo(true)) + .body("resourceMethods.GET.requestModels.'application/json'", equalTo("Empty")) + .body("resourceMethods.GET.methodResponses.'200'.statusCode", equalTo("200")) + .body("resourceMethods.GET.methodResponses.'200'.responseParameters.'method.response.header.X-Trace'", + equalTo(true)) + .body("resourceMethods.GET.methodIntegration.timeoutInMillis", equalTo(12000)) + .body("resourceMethods.GET.methodIntegration.requestTemplates.'application/json'", equalTo("{}")) + .body("resourceMethods.GET.methodIntegration.requestParameters.'integration.request.header.X-Trace'", + equalTo("method.request.header.X-Trace")); + } + + @Test + void ordinaryReadsReturnMethodNamesWithoutErasingStoredMetadata() { + given().when().get(resourcesPath()).then().statusCode(200) + .body("item.find { it.id == '" + resourceId + "' }.resourceMethods.GET", anEmptyMap()) + .body("item.find { it.id == '" + resourceId + "' }.resourceMethods.POST", anEmptyMap()); + given().when().get(resourcePath()).then().statusCode(200) + .body("resourceMethods.GET", anEmptyMap()).body("resourceMethods.POST", anEmptyMap()); + given().when().get(methodPath("GET")).then().statusCode(200) + .body("authorizationType", equalTo("NONE")) + .body("methodIntegration.uri", equalTo("https://example.invalid/widgets")); + given().queryParam("embed", "methods").when().get(resourcePath()).then().statusCode(200) + .body("resourceMethods.GET.authorizationType", equalTo("NONE")); + } + + @Test + void emptyResourcesDoNotInventMethods() { + given().queryParam("embed", "methods").when().get(resourcesPath() + "/" + rootId) + .then().statusCode(200).body("resourceMethods", nullValue()); + given().queryParam("embed", "methods").when().get(resourcesPath()).then().statusCode(200) + .body("item.find { it.id == '" + rootId + "' }.resourceMethods", nullValue()); + } + + @Test + void embeddedReadsReflectMethodUpdatesAndDeletion() { + given().contentType(ContentType.JSON).body(""" + {"patchOperations":[{"op":"replace","path":"/authorizationType","value":"AWS_IAM"}]} + """) + .when().patch(methodPath("GET")).then().statusCode(200); + given().when().delete(methodPath("POST")).then().statusCode(202); + given().queryParam("embed", "methods").when().get(resourcePath()).then().statusCode(200) + .body("resourceMethods.GET.authorizationType", equalTo("AWS_IAM")) + .body("resourceMethods", not(hasKey("POST"))); + given().queryParam("embed", "methods").when().get(resourcesPath()).then().statusCode(200) + .body("item.find { it.id == '" + resourceId + "' }.resourceMethods", not(hasKey("POST"))); + } + + @Test + void embeddedReadsKeepNotFoundErrors() { + given().queryParam("embed", "methods").when().get("/restapis/missing-api/resources") + .then().statusCode(404); + given().queryParam("embed", "methods").when().get(resourcesPath() + "/missing-resource") + .then().statusCode(404); + } + + private String resourcesPath() { + return "/restapis/" + apiId + "/resources"; + } + + private String resourcePath() { + return resourcesPath() + "/" + resourceId; + } + + private String methodPath(String httpMethod) { + return resourcePath() + "/methods/" + httpMethod; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/model/ApiGatewayMethodMapConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/model/ApiGatewayMethodMapConcurrencyTest.java new file mode 100644 index 0000000000..ca59ad04f7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/model/ApiGatewayMethodMapConcurrencyTest.java @@ -0,0 +1,121 @@ +package io.github.hectorvent.floci.services.apigateway.model; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +import java.util.HashMap; +import java.util.Map; +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.AtomicBoolean; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ApiGatewayMethodMapConcurrencyTest { + + enum MapSource { NEW, SETTER, JACKSON, NULL_RESET } + + @ParameterizedTest + @EnumSource(MapSource.class) + void resourceMethodsTolerateWritesDuringReadTraversal(MapSource source) throws Exception { + ApiGatewayResource resource = switch (source) { + case NEW -> new ApiGatewayResource(); + case SETTER -> { + ApiGatewayResource configured = new ApiGatewayResource(); + configured.setResourceMethods(new HashMap<>()); + yield configured; + } + case JACKSON -> new ObjectMapper().readValue( + "{\"resourceMethods\":{\"GET\":{\"httpMethod\":\"GET\"}}}", ApiGatewayResource.class); + case NULL_RESET -> { + ApiGatewayResource configured = new ApiGatewayResource(); + configured.setResourceMethods(null); + yield configured; + } + }; + MethodConfig method = new MethodConfig(); + method.setHttpMethod("GET"); + mutateDuringTraversal(resource.getResourceMethods(), "GET", "POST", "DELETE", method); + } + + @ParameterizedTest + @EnumSource(MapSource.class) + void methodResponsesTolerateWritesDuringReadTraversal(MapSource source) throws Exception { + MethodConfig method = switch (source) { + case NEW -> new MethodConfig(); + case SETTER -> { + MethodConfig configured = new MethodConfig(); + configured.setMethodResponses(new HashMap<>()); + yield configured; + } + case JACKSON -> new ObjectMapper().readValue( + "{\"methodResponses\":{\"200\":{\"statusCode\":\"200\"}}}", MethodConfig.class); + case NULL_RESET -> { + MethodConfig configured = new MethodConfig(); + configured.setMethodResponses(null); + yield configured; + } + }; + mutateDuringTraversal(method.getMethodResponses(), "200", "400", "500", + new MethodResponse("200", Map.of("method.response.header.X-Trace", true))); + } + + @Test + void resourceSetterOwnsItsMapAndKeepsMethodConfiguration() { + MethodConfig method = new MethodConfig(); + method.setHttpMethod("GET"); + Map input = new HashMap<>(Map.of("GET", method)); + ApiGatewayResource resource = new ApiGatewayResource(); + resource.setResourceMethods(input); + input.clear(); + + assertSame(method, resource.getResourceMethods().get("GET")); + resource.getResourceMethods().put("POST", new MethodConfig()); + assertTrue(input.isEmpty(), "Mutating the stored map must not mutate the setter's input"); + } + + @Test + void responseSetterOwnsItsMapAndKeepsResponseConfiguration() { + MethodResponse response = new MethodResponse("200", Map.of("method.response.header.X-Trace", true)); + Map input = new HashMap<>(Map.of("200", response)); + MethodConfig method = new MethodConfig(); + method.setMethodResponses(input); + input.clear(); + + assertEquals(response, method.getMethodResponses().get("200")); + method.getMethodResponses().put("400", new MethodResponse("400", Map.of())); + assertTrue(input.isEmpty(), "Mutating the stored map must not mutate the setter's input"); + } + + private static void mutateDuringTraversal(Map map, String first, String second, + String added, T value) { + map.put(first, value); + map.put(second, value); + AtomicBoolean changed = new AtomicBoolean(); + try (ExecutorService writer = Executors.newSingleThreadExecutor()) { + assertDoesNotThrow(() -> map.forEach((key, entry) -> { + if (changed.compareAndSet(false, true)) { + Future mutation = writer.submit(() -> { + map.put(added, value); + map.remove(second); + }); + assertDoesNotThrow(() -> mutation.get(5, TimeUnit.SECONDS)); + } + assertNotNull(key); + assertNotNull(entry); + })); + } + assertTrue(changed.get(), "The writer must run while the reader is traversing the map"); + assertSame(value, map.get(added)); + assertFalse(map.containsKey(second)); + } +}