Light, fluffy, and always free - The AWS Local Emulator alternative
perf(apigateway): avoid repeated root resource scans (#3404)
XuJian0a45d2e13130
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.javaindex 0dabe26a67..e4b2bce706 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@@ -1933,7 +1933,11 @@ public class ApiGatewayController {// as aws_api_gateway_rest_api.root_resource_id, which is how the first resource// under "/" gets its parent, so leaving it out breaks the conventional way of// building a REST API.- service.findRootResourceId(region, api.getId()).ifPresent(id -> node.put("rootResourceId", id));+ if (api.getRootResourceId() != null) {+ node.put("rootResourceId", api.getRootResourceId());+ } else {+ service.findRootResourceId(region, api.getId()).ifPresent(id -> node.put("rootResourceId", id));+ }// Neither member is settable on a REST API here: createRestApi ignores both and// updateRestApi patches only /name and /description, so the emulated value is alwaysdiff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.javaindex d431bff0a7..d5be72d7b6 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java@@ -260,12 +260,13 @@ public class ApiGatewayService {api.setEndpointConfiguration(endpointConfiguration);- apiStore.put(apiKey(region, api.getId()), api);-// Create root resource "/"ApiGatewayResource root = new ApiGatewayResource();root.setId(shortId(8));root.setPath("/");+ api.setRootResourceId(root.getId());++ apiStore.put(apiKey(region, api.getId()), api);resourceStore.put(resourceKey(region, api.getId(), root.getId()), root);LOG.infov("Created REST API: {0} ({1}) in {2}", name, api.getId(), region);@@ -315,25 +316,18 @@ public class ApiGatewayService {return resourceStore.scan(k -> k.startsWith(prefix));}- /**- * The id of the resource at "/", or empty if there is no API to read it from.- * <p>- * ListRestApis renders a snapshot of the APIs and resolves this per API afterwards, so an- * API deleted in between is already gone by the time its root is looked up. That must cost- * the caller the one member rather than failing the whole listing, which is why a missing- * API is empty here instead of a not-found. Every other failure still propagates.- */+ /** The root resource id, with a resource-store fallback for data persisted before it was stored on the API. */public Optional<String> findRootResourceId(String region, String apiId) {- List<ApiGatewayResource> resources;- try {- resources = getResources(region, apiId);- } catch (AwsException e) {- if ("NotFoundException".equals(e.getErrorCode())) {- return Optional.empty();- }- throw e;+ Optional<RestApi> api = apiStore.get(apiKey(region, apiId));+ if (api.isEmpty()) {+ return Optional.empty();+ }+ if (api.get().getRootResourceId() != null) {+ return Optional.of(api.get().getRootResourceId());}- return resources.stream()++ String prefix = region + "::" + apiId + "::";+ return resourceStore.scan(k -> k.startsWith(prefix)).stream().filter(r -> "/".equals(r.getPath())).map(ApiGatewayResource::getId).findFirst();diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/RestApi.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/RestApi.javaindex efa73b75c4..3d19571be9 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/RestApi.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/RestApi.java@@ -15,6 +15,7 @@ public class RestApi {private String name;private String description;private long createdDate;+ private String rootResourceId;private Map<String, String> tags = new HashMap<>();private EndpointConfiguration endpointConfiguration;@@ -51,6 +52,14 @@ public class RestApi {this.createdDate = createdDate;}+ public String getRootResourceId() {+ return rootResourceId;+ }++ public void setRootResourceId(String rootResourceId) {+ this.rootResourceId = rootResourceId;+ }+public Map<String, String> getTags() {return tags;}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRootResourceLookupTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRootResourceLookupTest.javanew file mode 100644index 0000000000..fe83078437--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRootResourceLookupTest.java@@ -0,0 +1,110 @@+package io.github.hectorvent.floci.services.apigateway;++import java.util.List;+import java.util.Map;+import java.util.Optional;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.config.TlsCertificateManager;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;+import io.github.hectorvent.floci.services.apigateway.model.RestApi;+import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2OpenApiImporter;+import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;+import jakarta.ws.rs.core.HttpHeaders;+import jakarta.ws.rs.core.Response;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.clearInvocations;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.spy;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++class ApiGatewayRootResourceLookupTest {++ private static final String REGION = "us-east-1";++ private AccountAwareStorageBackend<RestApi> apiStore;+ private AccountAwareStorageBackend<ApiGatewayResource> resourceStore;+ private ApiGatewayService service;++ @BeforeEach+ void setUp() {+ apiStore = spy(AccountAwareStorageBackend.inMemory("000000000000"));+ resourceStore = spy(AccountAwareStorageBackend.inMemory("000000000000"));+ StorageFactory storageFactory = mock(StorageFactory.class);+ when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(invocation -> {+ String fileName = invocation.getArgument(1);+ return switch (fileName) {+ case "apigateway-apis.json" -> apiStore;+ case "apigateway-resources.json" -> resourceStore;+ default -> AccountAwareStorageBackend.inMemory("000000000000");+ };+ });+ service = new ApiGatewayService(storageFactory, mock(EmulatorConfig.class),+ mock(TlsCertificateManager.class));+ }++ @Test+ void newApisResolveTheirRootsWithoutScanningResources() {+ for (int i = 0; i < 3; i++) {+ RestApi api = service.createRestApi(REGION, Map.of("name", "api-" + i));+ assertNotNull(api.getRootResourceId());+ }+ clearInvocations(resourceStore);++ for (RestApi api : service.getRestApis(REGION)) {+ assertEquals(Optional.of(api.getRootResourceId()),+ service.findRootResourceId(REGION, api.getId()));+ }++ verify(resourceStore, never()).scan(any());+ }++ @Test+ void persistedApisWithoutRootIdsFallBackToTheResourceStore() {+ RestApi api = service.createRestApi(REGION, Map.of("name", "legacy-api"));+ String rootResourceId = api.getRootResourceId();+ api.setRootResourceId(null);+ clearInvocations(resourceStore);++ assertEquals(Optional.of(rootResourceId), service.findRootResourceId(REGION, api.getId()));++ verify(resourceStore).scan(any());+ }++ @Test+ void listRenderingUsesTheRootIdAlreadyCarriedByTheApi() throws Exception {+ RestApi api = new RestApi();+ api.setId("api-id");+ api.setName("direct-root-read");+ api.setRootResourceId("root-id");++ ApiGatewayService mockedService = mock(ApiGatewayService.class);+ when(mockedService.getRestApis(REGION)).thenReturn(List.of(api));+ RegionResolver regionResolver = mock(RegionResolver.class);+ HttpHeaders headers = mock(HttpHeaders.class);+ when(regionResolver.resolveRegion(headers)).thenReturn(REGION);+ ObjectMapper objectMapper = new ObjectMapper();+ ApiGatewayController controller = new ApiGatewayController(mockedService,+ mock(ApiGatewayV2Service.class), mock(ApiGatewayV2OpenApiImporter.class),+ regionResolver, objectMapper);++ Response response = controller.getRestApis(headers);+ JsonNode body = objectMapper.readTree((String) response.getEntity());++ assertEquals("root-id", body.path("item").get(0).path("rootResourceId").asText());+ verify(mockedService, never()).findRootResourceId(anyString(), anyString());+ }+}