From f915622e36e1dcebd7d43e4423f580bc7d06f308 Mon Sep 17 00:00:00 2001 From: AgustinBertagna Date: Fri, 10 Jul 2026 22:50:14 -0300 Subject: [PATCH] =?UTF-8?q?feat(appsync):=20Phase=205=20=E2=80=94=20Manage?= =?UTF-8?q?ment=20API=20Coverage=20+=20AWS=20Behavior=20Alignment=20+=20As?= =?UTF-8?q?ync=20Schema=20Creation=20(#1590)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * test(appsync): strengthen existing integration error tests with __type and message assertions All 30 existing error assertions (400/404) previously checked only the HTTP status code. Each now also verifies the AWS error body shape: {"__type":"","message":"<...>"} This locks in the __type field that the AWS SDK v2 uses to instantiate the typed exception (NotFoundException, BadRequestException, etc.) and guards against accidental changes to error codes and messages. * test(appsync): add 409 conflict and 429 limit tests Add 7 new integration tests covering previously untested error paths: ConflictException (409): - createDataSourceDuplicateReturns409 - createResolverDuplicateReturns409 - createTypeDuplicateReturns409 - createDomainNameDuplicateReturns409 - createChannelNamespaceDuplicateReturns409 - associateApiDuplicateReturns409 (domain already associated) LimitExceededException (429): - createApiKeyExceedsLimitReturns429 (3rd key exceeds max 2 per API) All tests are self-contained: create resources, assert the error, then clean up. Each asserts statusCode + __type + message substring. * test(appsync): add 404 tests for update/delete and cross-resource create Add 11 new integration tests covering previously untested 404 paths: Update/delete of non-existent resources (8): - updateResolverNonExistentReturns404 - deleteResolverNonExistentReturns404 - updateFunctionNonExistentReturns404 - deleteFunctionNonExistentReturns404 - updateApiKeyNonExistentReturns404 - deleteApiKeyNonExistentReturns404 - updateDomainNameNonExistentReturns404 - updateChannelNamespaceNonExistentReturns404 Cross-resource 404 on create (3) — missing referenced resource: - createResolverMissingDataSourceReturns404 - createFunctionMissingDataSourceReturns404 - associateApiMissingDomainReturns404 Each asserts statusCode + __type=NotFoundException + message substring. * test(appsync): add pagination, edge case, and updateChannelNamespace tests Add 7 new integration tests: Pagination for previously untested list operations (3): - listDomainNamesWithMaxResults - listChannelNamespacesWithMaxResults - listSourceApiAssociationsWithMaxResults Each creates >=2 items, verifies page size + nextToken, follows token, and cleans up. Pagination edge cases (3): - listWithMaxResultsZero (empty page + nextToken present) - listWithNegativeMaxResultsReturns400 - listWithInvalidNextTokenNonApiReturns400 (data sources path) Update channel namespace (1): - updateChannelNamespace (verify description field change) * test(appsync): upgrade SDK error tests to typed exceptions Upgrade 4 existing SDK error tests from the generic AppSyncException to the typed exception classes that the AWS SDK v2 maps from the __type response field: - getNonExistentApiThrowsException -> NotFoundException - getNonExistentDataSourceThrowsException -> NotFoundException - getNonExistentTypeThrowsException -> NotFoundException - startSchemaCreation_invalidSchema -> BadRequestException Each now also asserts hasMessageContaining with the expected message substring. This aligns AppSyncTest with the repo convention used by ApiGatewayV2ManagementTest, SchedulerTest, and ElbV2Test. Also strengthen two existing update tests with field assertions: - updateChannelNamespace: now sets codeHandlers and verifies the response - updateDomainName: now asserts description field equals updated value * fix: correct environment variables API path case for SDK compatibility The AppSync controller used lowercase /v1/apis/{apiId}/environmentvariables but the AWS SDK v2 sends to /v1/apis/{apiId}/environmentVariables (capital V). This broke both getGraphqlApiEnvironmentVariables and putGraphqlApiEnvironmentVariables for all SDK clients. Fix the @Path annotations in the controller and update integration test paths to match the SDK-expected casing. * fix(appsync): align error codes and messages with AWS AppSync behavior - DataSource duplicate: ConflictException 409 → BadRequestException 400 - Resolver duplicate: ConflictException 409 → BadRequestException 400 - Type duplicate: ConflictException 409 → BadRequestException 400 - DomainName duplicate: ConflictException 409 → BadRequestException 400 - Domain association duplicate: ConflictException 409 → BadRequestException 400 - API key limit: LimitExceededException 429 → ApiKeyLimitExceededException 400 - Add duplicate validation for Source API associations - Add checkDuplicateSourceApiAssociation helper method - Update all integration and SDK test assertions to match AWS exact messages * feat(core): add extended data support to AwsException for AWS error parity Add optional extended data to AwsException so the exception mapper can emit structured error payloads matching the AWS error contract (e.g. AppSync BadRequestException with reason=CODE_ERROR and detail.codeErrors). The mapper auto-detects extended data and serializes it as additional JSON fields alongside __type and message. When extended data is null the previous simple AwsErrorResponse is returned, preserving behavior for every existing error site. * fix(appsync): return ConcurrentModificationException for duplicate source API association AWS AppSync's AssociateSourceGraphqlApi returns ConcurrentModificationException (HTTP 409) when an association already exists for the same source and merged API pair. Floci was returning BadRequestException (400) with an association ID in the message that did not match AWS. Also filter out associations in DELETION_SCHEDULED status so a new association can be created after the previous one has been removed, matching AWS behavior where the previous association is no longer 'live'. Message format now mirrors AWS: 'Source API association already exists for Source API ID: and Merged API ID: .' * refactor(appsync): remove non-AWS endpoints getApiKey and listAllResolvers AWS AppSync does not expose: - GetApiKey: there is no GetApiKey operation in the AppSync API Reference. API keys can be listed, created, updated, and deleted but not retrieved by id. - ListAllResolvers: ListResolvers requires typeName. There is no endpoint that lists resolvers across all types for an API. Both endpoints were Floci-only and violated the 'no custom endpoint shapes' rule. The associated service method (listResolvers) is also removed. The corresponding integration tests are dropped in a follow-up commit. The getApiKey service helper stays because it is still used internally by updateApiKey and deleteApiKey flows. * feat(appsync): emit AWS-compatible BadRequestException extended format for SDL errors AWS AppSync's StartSchemaCreation returns 400 BadRequestException with a reason=CODE_ERROR field and a detail.codeErrors array. Each code error carries errorType, value, and location{line, column, span}. This commit: - Catches SchemaProblem and InvalidSyntaxException from the parser and throws BadRequestException with extended data built from graphql-java's GraphQLError locations. - Catches SchemaProblem from makeExecutableSchema for validation errors (unknown types, missing fields) with errorType=VALIDATION_ERROR. - Catches generic RuntimeException without extended data so flow exceptions (NPE, OOM) do not produce a misleading codeErrors array. - Validates unknown AppSync directives with errorType=VALIDATION_ERROR and line/column/span from the SDL. The errorType values follow the AWS Javadoc (PARSER_ERROR, VALIDATION_ERROR) and span defaults to -1 when unknown, matching CodeErrorLocation.span() in the AWS SDK. * test(appsync): cover AWS-aligned error format, dead-code cleanup - Add Order 157: createSourceApiAssociationDuplicateReturns409 asserts ConcurrentModificationException 409 with the AWS message format. - Add Order 158: createSourceApiAssociationReplacesDeletionScheduled covers the new DELETION_SCHEDULED filter (a new association can replace a previously deleted one). - Add Orders 700, 701, 702: extended BadRequestException format for PARSER_ERROR (syntax), VALIDATION_ERROR (semantic), and unknown directive cases. Each asserts reason=CODE_ERROR, detail.codeErrors, and the location{line, column, span=-1} shape. - Update Order 124 (deleteApiKeyStandalone): the verification step used the removed getApiKey endpoint, replace it with listApiKeys asserting the deleted key is no longer present. - Update Orders 600 and 607 to assert the new extended format for generic SDL validation and unknown directive cases. - Drop Order 32 (getApiKey) and Order 62 (listAllResolvers): the underlying endpoints no longer exist. - Drop encodeArn helper and the URLEncoder / StandardCharsets imports that were no longer used by any test. * test(sdk-java): cover AssociateSourceGraphqlApi 409 and extended schema error body - Add Order 137 (createSourceApiAssociationDuplicateThrowsConcurrentModificationException): use the typed AWS SDK exception ConcurrentModificationException instead of the generic AppSyncException, validating the message format that AWS returns. - Add Order 200 (startSchemaCreation_syntaxError_throwsBadRequestWithExtendedBody): send a raw HTTP POST with an invalid schema, then inspect the JSON body to assert the AWS-compatible shape (__type, reason, detail.codeErrors[], errorType=PARSER_ERROR, location{line, column, span=-1}). Uses a jackson mapper rather than the SDK to read the response body directly. - Import java.util.List to support the new deserialization in Order 200. * feat(appsync): async schema creation with 409 in-progress gates StartSchemaCreation is asynchronous in AWS: the request returns 200 + PROCESSING, and the schema compiles in a background thread, transitioning to ACTIVE (success) or FAILED (error) with the extended error format in the polled GetSchemaCreationStatus response. This commit: - Adds SchemaCreationWorker, a singleton executor with configurable thread count and graceful shutdown, that transitions the schema status asynchronously and serializes the AwsException extended data into the FAILED details string. - Adds SchemaStatusStoreProducer so AppSyncService and the worker see the same in-memory state for the schema status store (otherwise two StorageFactory.create() calls would create independent maps). - Refactors startSchemaCreation to set PROCESSING synchronously and hand off compilation to the worker. - Removes the synchronous ACTIVE override from the controller. - Gates 27 per-API mutations and 2 account-wide operations (CreateGraphqlApi, CreateApi) plus self-blocking on second StartSchemaCreation with ConcurrentModificationException 409, matching the AWS behavior documented in the AppSync API Reference and service-2.json. - Adds recoverOrphans() to EmulatorLifecycle.onStart so schemas left in PROCESSING by a previous emulator run are marked FAILED instead of permanently blocking the API. - Adds schemaWorkerThreads and schemaWorkerShutdownTimeoutSeconds to EmulatorConfig (FLOCI_SERVICES_APPSYNC_SCHEMA_WORKER_THREADS, FLOCI_SERVICES_APPSYNC_SCHEMA_WORKER_SHUTDOWN_TIMEOUT_SECONDS). * test(appsync): cover async schema polling, FAILED state, and 409 gates - Adapts the 7 existing schema creation tests to the async pattern: the post returns PROCESSING, tests poll for the terminal status with Awaitility, and the extended format body is now read from the polled FAILED details. - Adds 9 new tests (Orders 703-711) covering the 409 in-progress gates for createDataSource, createResolver, createFunction, createType, putEnvironmentVariables, startSchemaCreation, createGraphqlApi, updateGraphqlApi, and deleteGraphqlApi. The gates are exercised by setting the status to PROCESSING directly via the shared store backend, which is deterministic and avoids the race window of waiting for the worker. - Updates the EmulatorLifecycleTest constructor for the new SchemaCreationWorker dependency. * test(sdk-java): cover async schema with typed SDK polling - Adds awaitility 4.2.2 to pom.xml (test scope) so the SDK test for the polled status can use the same Awaitility DSL the integration tests use. - Updates the existing getSchemaCreationStatus test (Order 11) to poll via the typed SDK call until the terminal status is reached (ACTIVE in this case) instead of a single request. Without this, the gate added in the previous commit would 409 every subsequent SDK test that runs while the schema is still PROCESSING. * fix(build): remove duplicate awaitility declaration in pom.xml The pre-existing version-less awaitility declaration (BOM-managed by Quarkus) was shadowed by the pinned 4.2.2 declaration added in this PR. Maven resolves the first declaration it encounters, silently ignoring the BOM version. Removed the version-less dup so the pinned 4.2.2 takes effect. Addresses P1 from Greptile review. * fix(appsync): add missing 409 gates and synchronize startSchemaCreation Validating all 43 ConcurrentModificationException operations from service-2.json against the code surfaced 5 operations missing the PROCESSING gate (Greptile caught 1, 4 more were found during review): - getChannelNamespace: added assertSchemaNotBusy (protects both get and deleteChannelNamespace, matching getResolver/getFunction/getType) - deleteDomainName: resolves the associated apiId from the domain association store and gates on it (no-op if no association exists) - disassociateApi: same pattern as deleteDomainName - deleteMergedApiAssociation: gate on sourceApiIdentifier - updateDomainName: resolves the associated apiId and gates on it Also wraps the startSchemaCreation check-and-set in synchronized(this) to close the TOCTOU race window between assertSchemaNotBusy and the PROCESSING put. The async submitSchemaCreation call stays outside the lock to avoid blocking the worker thread. Addresses P1 and P2 from Greptile review. * chore(appsync): document schema worker config in application.yml Adds the appsync section under storage.services in both main and test application.yml, documenting the three AppSyncStorageConfig keys: - flush-interval-ms (5000 main / 60000 test, matching other services) - schema-worker-threads (4) - schema-worker-shutdown-timeout-seconds (30) These already had @WithDefault fallbacks so the code worked without the YAML entries, but the repository convention (AGENTS.md) requires storage config to be documented in application.yml as the source of truth for operators. Addresses P2 from Greptile review. * test(appsync): cover additional 409 gates for domain and merged operations Adds 5 new integration tests (Orders 712-716) covering the PROCESSING 409 gates added in the previous commit: - 712: deleteChannelNamespace_busy_returns409 - 713: deleteDomainName_busy_returns409 - 714: disassociateApi_busy_returns409 - 715: disassociateMergedGraphqlApi_busy_returns409 - 716: updateDomainName_busy_returns409 Each test creates the necessary resources (temp API, channel namespace, domain name + association, or merged API association) before setting the schema status to PROCESSING directly via the shared store, then asserts the gated operation returns 409 ConcurrentModificationException with the AWS-style message. Integration test count: 154 -> 159. * fix(appsync): remove incorrect CME gate from getChannelNamespace, add to deleteChannelNamespace GetChannelNamespace does not declare ConcurrentModificationException in service-2.json or the AWS Java SDK v2. Only BadRequestException, NotFoundException, UnauthorizedException, InternalFailureException, and AccessDeniedException are declared. The gate was incorrectly returning 409 during PROCESSING for an undeclared error code. DeleteChannelNamespace does declare CME, so the gate is now applied directly in deleteChannelNamespace instead of being inherited from getChannelNamespace. * fix(appsync): account-aware schema creation and worker store isolation Scope schema creation status to the requesting account so concurrent accounts cannot interfere with each other's in-flight schema operations. - Add accountId field to SchemaCreationStatus - Worker uses AccountAwareStorageBackend (putForAccount/getForAccount) - SchemaStatusStoreProducer now produces AccountAwareStorageBackend - SchemaStoreProducer CDI bean shares schemaStore between service and worker - schemaStore.put moved to worker success path only - assertSchemaNotBusy scoped to current account via getForAccount - assertNoSchemaBusyAnywhere scoped to keysForAccount - currentAccountId() helper reads RequestContext - Worker config moved from AppSyncStorageConfig to AppSyncServiceConfig * fix(appsync): ACTIVE→SUCCESS terminal schema status Match AWS behavior: a successfully compiled schema is SUCCESS, not ACTIVE. ACTIVE is not a valid terminal status in real AppSync. - Worker marks SUCCESS on successful compilation - Integration tests assert SUCCESS - SDK compatibility test asserts SUCCESS * refactor(appsync): remove circular dependency between SchemaRegistry and SchemaCreationWorker SchemaRegistry depended on SchemaCreationWorker solely to delegate submitSchemaCreation calls, creating a circular dependency. AppSyncService now calls the worker directly, making the delegation unnecessary. - Remove SchemaCreationWorker dependency from SchemaRegistry - Remove submitSchemaCreation method * fix(appsync): add assertSchemaNotBusy to deleteResolver, deleteFunction, deleteType These three delete operations mutate the schema and should be blocked while a schema creation is in PROCESSING state, matching the 409 gates on the other schema-mutating operations. * fix(appsync): return PROCESSING status synchronously from StartSchemaCreation The controller was re-reading the status from the store after submitting to the worker pool. In fast environments the worker could complete (fail) before the read, causing the POST response to return FAILED instead of PROCESSING — breaking the SDK compatibility test. startSchemaCreation now returns the PROCESSING status it just set, and the controller uses it directly instead of re-reading. --- .../test/java/com/floci/test/AppSyncTest.java | 315 +++- pom.xml | 11 +- .../floci/config/EmulatorConfig.java | 8 + .../floci/core/common/AwsException.java | 21 + .../floci/core/common/AwsExceptionMapper.java | 29 +- .../floci/lifecycle/EmulatorLifecycle.java | 7 +- .../services/appsync/AppSyncController.java | 35 +- .../services/appsync/AppSyncService.java | 148 +- .../appsync/graphql/AppSyncSchemaParser.java | 73 +- .../appsync/graphql/SchemaCreationWorker.java | 152 ++ .../graphql/SchemaStatusStoreProducer.java | 36 + .../appsync/graphql/SchemaStoreProducer.java | 33 + .../appsync/model/SchemaCreationStatus.java | 4 + src/main/resources/application.yml | 4 + .../lifecycle/EmulatorLifecycleTest.java | 4 +- .../appsync/AppSyncIntegrationTest.java | 1539 ++++++++++++++++- src/test/resources/application.yml | 4 + 17 files changed, 2252 insertions(+), 171 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorker.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStatusStoreProducer.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStoreProducer.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppSyncTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppSyncTest.java index 386d9b8d0a..b609e47884 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppSyncTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppSyncTest.java @@ -12,6 +12,7 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.time.Instant; +import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.*; @@ -106,12 +107,11 @@ class AppSyncTest { @Test @Order(11) void getSchemaCreationStatus() { - GetSchemaCreationStatusResponse resp = client.getSchemaCreationStatus( - GetSchemaCreationStatusRequest.builder() - .apiId(apiId) - .build()); - - assertThat(resp.statusAsString()).isEqualTo("ACTIVE"); + // Schema creation is async in real AWS: poll until terminal (SUCCESS + // or FAILED). All subsequent tests in this class depend on the + // schema being ACTIVE because the 409 gate fires while PROCESSING. + SchemaStatus status = pollSchemaStatusToTerminal(); + assertThat(status).isEqualTo(SchemaStatus.SUCCESS); } // ── API Keys ──────────────────────────────────────────────────────── @@ -540,12 +540,28 @@ class AppSyncTest { @Test @Order(93) void startSchemaCreation_invalidSchema() { - assertThatThrownBy(() -> client.startSchemaCreation(StartSchemaCreationRequest.builder() - .apiId(apiId) - .definition(SdkBytes.fromUtf8String("type Query { invalid !!! }")) - .build())) - .isInstanceOf(AppSyncException.class) - .hasMessageContaining("Invalid schema"); + StartSchemaCreationResponse resp = client.startSchemaCreation(StartSchemaCreationRequest.builder() + .apiId(apiId) + .definition(SdkBytes.fromUtf8String("type Query { invalid !!! }")) + .build()); + assertThat(resp.status()).isEqualTo(SchemaStatus.PROCESSING); + SchemaStatus terminal = pollSchemaStatusToTerminal(); + assertThat(terminal).isEqualTo(SchemaStatus.FAILED); + } + + private SchemaStatus pollSchemaStatusToTerminal() { + Instant deadline = Instant.now().plus(Duration.ofSeconds(10)); + SchemaStatus s = client.getSchemaCreationStatus(r -> r.apiId(apiId)).status(); + while (s == SchemaStatus.PROCESSING && Instant.now().isBefore(deadline)) { + try { + Thread.sleep(50); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + throw new RuntimeException(ie); + } + s = client.getSchemaCreationStatus(r -> r.apiId(apiId)).status(); + } + return s; } @Test @@ -600,9 +616,11 @@ class AppSyncTest { UpdateChannelNamespaceRequest.builder() .apiId(apiId) .name(channelNsName) + .codeHandlers("export function handler(ctx) { return ctx; }") .build()); assertThat(resp.channelNamespace()).isNotNull(); + assertThat(resp.channelNamespace().codeHandlers()).contains("handler"); } @Test @@ -672,6 +690,7 @@ class AppSyncTest { assertThat(resp.domainNameConfig()).isNotNull(); assertThat(resp.domainNameConfig().domainName()).isEqualTo(tempDomainName); + assertThat(resp.domainNameConfig().description()).isEqualTo("updated-domain"); } @Test @@ -949,31 +968,34 @@ class AppSyncTest { @Test @Order(80) - void getNonExistentApiThrowsException() { + void getNonExistentApiThrowsNotFoundException() { assertThatThrownBy(() -> client.getGraphqlApi(GetGraphqlApiRequest.builder() .apiId("nonexistent12345678901234") .build())) - .isInstanceOf(AppSyncException.class); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("GraphQL API not found:"); } @Test @Order(81) - void getNonExistentDataSourceThrowsException() { + void getNonExistentDataSourceThrowsNotFoundException() { assertThatThrownBy(() -> client.getDataSource(GetDataSourceRequest.builder() .apiId(apiId) .name("nonexistent-ds") .build())) - .isInstanceOf(AppSyncException.class); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Data source not found:"); } @Test @Order(82) - void getNonExistentTypeThrowsException() { + void getNonExistentTypeThrowsNotFoundException() { assertThatThrownBy(() -> client.getType(GetTypeRequest.builder() .apiId(apiId) .typeName("NonExistentType") .build())) - .isInstanceOf(AppSyncException.class); + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Type not found:"); } @Test @@ -986,4 +1008,261 @@ class AppSyncTest { assertThat(resp.apiKey()).isNotNull(); assertThat(resp.apiKey().id()).isNotBlank(); } + + // ── SDK Coverage Gaps: Environment Variables ─────────────────────────── + + @Test + @Order(120) + void putGraphqlApiEnvironmentVariables() { + PutGraphqlApiEnvironmentVariablesResponse resp = client.putGraphqlApiEnvironmentVariables( + PutGraphqlApiEnvironmentVariablesRequest.builder() + .apiId(apiId) + .environmentVariables(Map.of("TABLE_NAME", "my-table", "REGION", "us-east-1")) + .build()); + + assertThat(resp.environmentVariables()) + .containsEntry("TABLE_NAME", "my-table") + .containsEntry("REGION", "us-east-1"); + } + + @Test + @Order(121) + void getGraphqlApiEnvironmentVariables() { + GetGraphqlApiEnvironmentVariablesResponse resp = client.getGraphqlApiEnvironmentVariables( + GetGraphqlApiEnvironmentVariablesRequest.builder() + .apiId(apiId) + .build()); + + assertThat(resp.environmentVariables()) + .containsEntry("TABLE_NAME", "my-table") + .containsEntry("REGION", "us-east-1"); + } + + // ── SDK Coverage Gaps: Pagination ────────────────────────────────────── + + @Test + @Order(122) + void listGraphqlApisWithMaxResults() { + for (int i = 0; i < 2; i++) { + client.createGraphqlApi(CreateGraphqlApiRequest.builder() + .name("pg-sdk-api-" + i + "-" + java.util.UUID.randomUUID().toString().substring(0, 8)) + .authenticationType("API_KEY") + .build()); + } + + ListGraphqlApisResponse page1 = client.listGraphqlApis(ListGraphqlApisRequest.builder() + .maxResults(2) + .build()); + + assertThat(page1.graphqlApis()).hasSizeLessThanOrEqualTo(2); + if (page1.nextToken() != null) { + ListGraphqlApisResponse page2 = client.listGraphqlApis(ListGraphqlApisRequest.builder() + .maxResults(2) + .nextToken(page1.nextToken()) + .build()); + assertThat(page2.graphqlApis()).isNotEmpty(); + } + } + + @Test + @Order(123) + void listDataSourcesWithMaxResults() { + for (int i = 0; i < 2; i++) { + client.createDataSource(CreateDataSourceRequest.builder() + .apiId(apiId) + .name("pg-sdk-ds-" + i + "-" + java.util.UUID.randomUUID().toString().substring(0, 8)) + .type("NONE") + .build()); + } + + ListDataSourcesResponse page1 = client.listDataSources(ListDataSourcesRequest.builder() + .apiId(apiId) + .maxResults(1) + .build()); + + assertThat(page1.dataSources()).hasSize(1); + assertThat(page1.nextToken()).isNotNull(); + + ListDataSourcesResponse page2 = client.listDataSources(ListDataSourcesRequest.builder() + .apiId(apiId) + .maxResults(1) + .nextToken(page1.nextToken()) + .build()); + + assertThat(page2.dataSources()).isNotEmpty(); + } + + // ── SDK Coverage Gaps: Mirror Error Tests (409/429/404) ──────────────── + + @Test + @Order(130) + void createDataSourceDuplicateThrowsBadRequestException() { + String dsName = "sdk-conflict-ds-" + java.util.UUID.randomUUID().toString().substring(0, 8); + client.createDataSource(CreateDataSourceRequest.builder() + .apiId(apiId) + .name(dsName) + .type("NONE") + .build()); + + assertThatThrownBy(() -> client.createDataSource(CreateDataSourceRequest.builder() + .apiId(apiId) + .name(dsName) + .type("NONE") + .build())) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Data source with name"); + + client.deleteDataSource(r -> r.apiId(apiId).name(dsName)); + } + + @Test + @Order(131) + void createApiKeyExceedsLimitThrowsApiKeyLimitExceededException() { + CreateGraphqlApiResponse tempApi = client.createGraphqlApi(CreateGraphqlApiRequest.builder() + .name("sdk-limit-test-" + java.util.UUID.randomUUID().toString().substring(0, 8)) + .authenticationType("API_KEY") + .build()); + String tempApiId = tempApi.graphqlApi().apiId(); + + try { + client.createApiKey(CreateApiKeyRequest.builder().apiId(tempApiId).build()); + client.createApiKey(CreateApiKeyRequest.builder().apiId(tempApiId).build()); + + assertThatThrownBy(() -> client.createApiKey(CreateApiKeyRequest.builder().apiId(tempApiId).build())) + .isInstanceOf(ApiKeyLimitExceededException.class) + .hasMessageContaining("The API key exceeded a limit"); + } finally { + client.deleteGraphqlApi(r -> r.apiId(tempApiId)); + } + } + + @Test + @Order(132) + void updateResolverNonExistentThrowsNotFoundException() { + assertThatThrownBy(() -> client.updateResolver(UpdateResolverRequest.builder() + .apiId(apiId) + .typeName("Query") + .fieldName("nonExistentSdkField") + .dataSourceName("none-ds") + .build())) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Resolver not found:"); + } + + @Test + @Order(133) + void deleteFunctionNonExistentThrowsNotFoundException() { + assertThatThrownBy(() -> client.deleteFunction(DeleteFunctionRequest.builder() + .apiId(apiId) + .functionId("nonexistent00000000000") + .build())) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Function not found:"); + } + + @Test + @Order(134) + void updateApiKeyNonExistentThrowsNotFoundException() { + assertThatThrownBy(() -> client.updateApiKey(UpdateApiKeyRequest.builder() + .apiId(apiId) + .id("nonexistent00000000000") + .description("updated") + .build())) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("API key not found:"); + } + + @Test + @Order(135) + void updateDomainNameNonExistentThrowsNotFoundException() { + assertThatThrownBy(() -> client.updateDomainName(UpdateDomainNameRequest.builder() + .domainName("nonexistent.example.com") + .description("updated") + .build())) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Domain name not found:"); + } + + @Test + @Order(136) + void createResolverMissingDataSourceThrowsNotFoundException() { + assertThatThrownBy(() -> client.createResolver(CreateResolverRequest.builder() + .apiId(apiId) + .typeName("Query") + .fieldName("crossRefSdkField") + .dataSourceName("nonexistent-ds-for-sdk-resolver") + .build())) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Data source not found:"); + } + + @Test + @Order(137) + void createSourceApiAssociationDuplicateThrowsConcurrentModificationException() { + String sourceApiId = client.createGraphqlApi(CreateGraphqlApiRequest.builder() + .name("sdk-dup-source-" + java.util.UUID.randomUUID().toString().substring(0, 8)) + .authenticationType("API_KEY") + .build()).graphqlApi().apiId(); + + try { + client.associateSourceGraphqlApi(AssociateSourceGraphqlApiRequest.builder() + .mergedApiIdentifier(apiId) + .sourceApiIdentifier(sourceApiId) + .build()); + + assertThatThrownBy(() -> client.associateSourceGraphqlApi(AssociateSourceGraphqlApiRequest.builder() + .mergedApiIdentifier(apiId) + .sourceApiIdentifier(sourceApiId) + .build())) + .isInstanceOf(ConcurrentModificationException.class) + .hasMessageContaining("Source API association already exists for Source API ID") + .hasMessageContaining("and Merged API ID"); + } finally { + client.deleteGraphqlApi(r -> r.apiId(sourceApiId)); + } + } + + @Test + @Order(200) + void startSchemaCreation_syntaxError_throwsBadRequestWithExtendedBody() throws Exception { + String body = """ + { "definition": "type Query { invalid syntax!!! }" } + """; + String url = TestFixtures.endpoint() + "/v1/apis/" + apiId + "/schemacreation"; + HttpRequest req = HttpRequest.newBuilder() + .uri(URI.create(url)) + .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request") + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(body)) + .build(); + HttpResponse resp = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString()); + + // Async path: 200 + PROCESSING; the error surfaces in the FAILED details. + assertThat(resp.statusCode()).isEqualTo(200); + @SuppressWarnings("unchecked") + Map jsonBody = mapper.readValue(resp.body(), Map.class); + assertThat(jsonBody.get("status")).isEqualTo("PROCESSING"); + + SchemaStatus terminal = pollSchemaStatusToTerminal(); + assertThat(terminal).isEqualTo(SchemaStatus.FAILED); + + GetSchemaCreationStatusResponse status = client.getSchemaCreationStatus(r -> r.apiId(apiId)); + @SuppressWarnings("unchecked") + Map extended = mapper.readValue(status.details(), Map.class); + assertThat(extended.get("reason")).isEqualTo("CODE_ERROR"); + assertThat(extended).containsKey("detail"); + @SuppressWarnings("unchecked") + Map detail = (Map) extended.get("detail"); + @SuppressWarnings("unchecked") + List> codeErrors = (List>) detail.get("codeErrors"); + assertThat(codeErrors).isNotEmpty(); + Map first = codeErrors.get(0); + assertThat(first.get("errorType")).isEqualTo("PARSER_ERROR"); + assertThat(first.get("value")).isNotNull(); + @SuppressWarnings("unchecked") + Map location = (Map) first.get("location"); + assertThat(location.get("line")).isNotNull(); + assertThat(location.get("column")).isNotNull(); + assertThat(location.get("span")).isEqualTo(-1); + } } diff --git a/pom.xml b/pom.xml index 9a04ec1b4f..8537024500 100644 --- a/pom.xml +++ b/pom.xml @@ -260,6 +260,12 @@ rest-assured test + + org.awaitility + awaitility + 4.2.2 + test + org.eclipse.paho org.eclipse.paho.client.mqttv3 @@ -297,11 +303,6 @@ 6.1.0 test - - org.awaitility - awaitility - test - diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index f131ba9615..94c165fc99 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -1189,6 +1189,14 @@ public interface EmulatorConfig { interface AppSyncServiceConfig { @WithDefault("true") boolean enabled(); + + /** Worker threads for async schema creation. Env: FLOCI_SERVICES_APPSYNC_SCHEMA_WORKER_THREADS */ + @WithDefault("4") + int schemaWorkerThreads(); + + /** Seconds to wait for in-flight schema workers on shutdown. Env: FLOCI_SERVICES_APPSYNC_SCHEMA_WORKER_SHUTDOWN_TIMEOUT_SECONDS */ + @WithDefault("30") + int schemaWorkerShutdownTimeoutSeconds(); } interface BcmDataExportsServiceConfig { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsException.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsException.java index f792d3ac25..51a1d645bd 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsException.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsException.java @@ -1,5 +1,7 @@ package io.github.hectorvent.floci.core.common; +import java.util.Collections; +import java.util.HashMap; import java.util.Map; /** @@ -9,6 +11,10 @@ import java.util.Map; * Some services use different error code formats for Query (XML) and JSON protocols. * {@link #jsonType()} returns the JSON-protocol {@code __type} value that the AWS SDK v2 * uses to instantiate a specific typed exception rather than falling back to a generic one. + *

+ * When {@link #getExtendedData()} is non-null, the exception mapper produces an extended + * response with a {@code reason} and {@code detail} field (e.g. {@code reason: "CODE_ERROR"} + * with structured code errors for schema validation failures). */ public class AwsException extends RuntimeException { @@ -26,11 +32,17 @@ public class AwsException extends RuntimeException { private final String errorCode; private final int httpStatus; + private final Map extendedData; public AwsException(String errorCode, String message, int httpStatus) { + this(errorCode, message, httpStatus, null); + } + + public AwsException(String errorCode, String message, int httpStatus, Map extendedData) { super(message); this.errorCode = errorCode; this.httpStatus = httpStatus; + this.extendedData = extendedData != null ? new HashMap<>(extendedData) : null; } public String getErrorCode() { @@ -41,6 +53,15 @@ public class AwsException extends RuntimeException { return httpStatus; } + /** + * Returns the extended data for structured error responses, or {@code null} if not present. + * Used for schema validation errors that include {@code reason: "CODE_ERROR"} and + * {@code detail.codeErrors}. + */ + public Map getExtendedData() { + return extendedData != null ? Collections.unmodifiableMap(extendedData) : null; + } + /** * Returns the JSON-protocol {@code __type} value for this error. * The AWS SDK v2 uses this to map responses to typed exception classes. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsExceptionMapper.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsExceptionMapper.java index 7ddb33f84a..2004e947e2 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsExceptionMapper.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsExceptionMapper.java @@ -1,25 +1,46 @@ package io.github.hectorvent.floci.core.common; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import jakarta.inject.Inject; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.ext.ExceptionMapper; import jakarta.ws.rs.ext.Provider; import org.jboss.logging.Logger; -/** - * JAX-RS exception mapper that converts AwsException to AWS-formatted JSON error responses. - */ +import java.util.Map; + @Provider public class AwsExceptionMapper implements ExceptionMapper { private static final Logger LOG = Logger.getLogger(AwsExceptionMapper.class); + private final ObjectMapper objectMapper; + + @Inject + public AwsExceptionMapper(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } @Override public Response toResponse(AwsException exception) { LOG.debugv("Mapping exception: {0} - {1}", exception.getErrorCode(), exception.getMessage()); + Object entity = exception.getExtendedData() != null + ? buildExtendedResponse(exception) + : new AwsErrorResponse(exception.jsonType(), exception.getMessage()); return Response.status(exception.getHttpStatus()) .type(MediaType.APPLICATION_JSON) - .entity(new AwsErrorResponse(exception.jsonType(), exception.getMessage())) + .entity(entity) .build(); } + + private ObjectNode buildExtendedResponse(AwsException exception) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("__type", exception.jsonType()); + node.put("message", exception.getMessage()); + for (Map.Entry entry : exception.getExtendedData().entrySet()) { + node.set(entry.getKey(), objectMapper.valueToTree(entry.getValue())); + } + return node; + } } diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java index effbe02fc0..498835fc87 100644 --- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java @@ -19,6 +19,7 @@ import io.github.hectorvent.floci.services.lambda.SqsEventSourcePoller; import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerManager; import io.github.hectorvent.floci.services.neptune.proxy.NeptuneProxyManager; import io.github.hectorvent.floci.services.pipes.PipesService; +import io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker; import io.github.hectorvent.floci.services.rds.RdsService; import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerManager; import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager; @@ -81,6 +82,7 @@ public class EmulatorLifecycle { private final EcrRegistryManager ecrRegistryManager; private final FlociUiManager flociUiManager; private final InitLifecycleState initLifecycleState; + private final SchemaCreationWorker schemaCreationWorker; @Inject public EmulatorLifecycle(StorageFactory storageFactory, ServiceRegistry serviceRegistry, @@ -105,7 +107,8 @@ public class EmulatorLifecycle { Ec2MetadataServer ec2MetadataServer, EcrRegistryManager ecrRegistryManager, FlociUiManager flociUiManager, - InitLifecycleState initLifecycleState) { + InitLifecycleState initLifecycleState, + SchemaCreationWorker schemaCreationWorker) { this.storageFactory = storageFactory; this.serviceRegistry = serviceRegistry; this.config = config; @@ -130,6 +133,7 @@ public class EmulatorLifecycle { this.ecrRegistryManager = ecrRegistryManager; this.flociUiManager = flociUiManager; this.initLifecycleState = initLifecycleState; + this.schemaCreationWorker = schemaCreationWorker; } void onStart(@Observes StartupEvent ignored) { @@ -152,6 +156,7 @@ public class EmulatorLifecycle { serviceRegistry.logEnabledServices(); storageFactory.loadAll(); + schemaCreationWorker.recoverOrphans(); sqsPoller.startPersistedPollers(); kinesisPoller.startPersistedPollers(); diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncController.java b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncController.java index 4dc05929b1..b42a4046fd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncController.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncController.java @@ -111,10 +111,7 @@ public class AppSyncController { // Not base64, use as-is } } - service.startSchemaCreation(apiId, definition); - SchemaCreationStatus status = new SchemaCreationStatus(); - status.setStatus(SchemaCreationStatusType.ACTIVE); - return Response.ok(status).build(); + return Response.ok(service.startSchemaCreation(apiId, definition)).build(); } @GET @@ -215,23 +212,6 @@ public class AppSyncController { return Response.status(200).entity(root).build(); } - @GET - @Path("/v1/apis/{apiId}/resolvers") - public Response listResolvers(@PathParam("apiId") String apiId, - @QueryParam("maxResults") Integer maxResults, - @QueryParam("nextToken") String nextToken) { - var page = service.listResolvers(apiId, maxResults, nextToken); - ObjectNode root = objectMapper.createObjectNode(); - ArrayNode items = root.putArray("resolvers"); - page.items().forEach(items::addPOJO); - if (page.nextToken() != null) { - root.put("nextToken", page.nextToken()); - } else { - root.putNull("nextToken"); - } - return Response.ok(root).build(); - } - @GET @Path("/v1/apis/{apiId}/types/{typeName}/resolvers") public Response listResolversByType(@PathParam("apiId") String apiId, @@ -454,15 +434,6 @@ public class AppSyncController { return Response.ok(root).build(); } - @GET - @Path("/v1/apis/{apiId}/apikeys/{keyId}") - public Response getApiKey(@PathParam("apiId") String apiId, @PathParam("keyId") String keyId) { - ApiKey key = service.getApiKey(apiId, keyId); - ObjectNode root = objectMapper.createObjectNode(); - root.set("apiKey", objectMapper.valueToTree(key)); - return Response.ok(root).build(); - } - @POST @Path("/v1/apis/{apiId}/apikeys/{keyId}") public Response updateApiKey(@PathParam("apiId") String apiId, @@ -517,7 +488,7 @@ public class AppSyncController { // ──────────────────────────── Environment Variables ──────────────────────────── @GET - @Path("/v1/apis/{apiId}/environmentvariables") + @Path("/v1/apis/{apiId}/environmentVariables") public Response getEnvironmentVariables(@PathParam("apiId") String apiId) { Map envVars = service.getEnvironmentVariables(apiId); ObjectNode root = objectMapper.createObjectNode(); @@ -527,7 +498,7 @@ public class AppSyncController { } @PUT - @Path("/v1/apis/{apiId}/environmentvariables") + @Path("/v1/apis/{apiId}/environmentVariables") public Response putEnvironmentVariables(@PathParam("apiId") String apiId, String body) throws IOException { @SuppressWarnings("unchecked") diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java index 318974a571..9defcc4570 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java @@ -5,11 +5,15 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.RequestContext; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker; import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry; import io.github.hectorvent.floci.services.appsync.model.*; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -22,7 +26,7 @@ public class AppSyncService { private final StorageBackend apiStore; private final StorageBackend schemaStore; - private final StorageBackend schemaStatusStore; + private final AccountAwareStorageBackend schemaStatusStore; private final StorageBackend dataSourceStore; private final StorageBackend resolverStore; private final StorageBackend functionStore; @@ -34,14 +38,19 @@ public class AppSyncService { private final StorageBackend mergedApiAssociationStore; private final RegionResolver regionResolver; private final SchemaRegistry schemaRegistry; + private final SchemaCreationWorker schemaCreationWorker; + private final Instance requestContextInstance; private final ObjectMapper objectMapper; @Inject public AppSyncService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, - SchemaRegistry schemaRegistry, ObjectMapper objectMapper) { + SchemaRegistry schemaRegistry, SchemaCreationWorker schemaCreationWorker, + Instance requestContextInstance, ObjectMapper objectMapper, + AccountAwareStorageBackend schemaStatusStore, + StorageBackend schemaStore) { this.apiStore = storageFactory.create("appsync", "appsync-apis.json", new TypeReference<>() {}); - this.schemaStore = storageFactory.create("appsync", "appsync-schemas.json", new TypeReference<>() {}); - this.schemaStatusStore = storageFactory.create("appsync", "appsync-schema-status.json", new TypeReference<>() {}); + this.schemaStore = schemaStore; + this.schemaStatusStore = schemaStatusStore; this.dataSourceStore = storageFactory.create("appsync", "appsync-datasources.json", new TypeReference<>() {}); this.resolverStore = storageFactory.create("appsync", "appsync-resolvers.json", new TypeReference<>() {}); this.functionStore = storageFactory.create("appsync", "appsync-functions.json", new TypeReference<>() {}); @@ -53,12 +62,15 @@ public class AppSyncService { this.mergedApiAssociationStore = storageFactory.create("appsync", "appsync-merged-api-associations.json", new TypeReference<>() {}); this.regionResolver = regionResolver; this.schemaRegistry = schemaRegistry; + this.schemaCreationWorker = schemaCreationWorker; + this.requestContextInstance = requestContextInstance; this.objectMapper = objectMapper; } // ──────────────────────────── GraphQL API ──────────────────────────── public GraphqlApi createGraphqlApi(Map request, String region) { + assertNoSchemaBusyAnywhere(); String name = (String) request.get("name"); if (name == null || name.isBlank()) { throw new AwsException("BadRequestException", "A GraphQL API name is required", 400); @@ -135,6 +147,7 @@ public class AppSyncService { @SuppressWarnings("unchecked") public GraphqlApi updateGraphqlApi(String apiId, Map request, String region) { + assertSchemaNotBusy(apiId); GraphqlApi existing = getGraphqlApi(apiId); if (request.containsKey("name")) existing.setName((String) request.get("name")); if (request.containsKey("authenticationType")) existing.setAuthenticationType(parseEnum(AuthenticationType.class, request.get("authenticationType"))); @@ -182,6 +195,7 @@ public class AppSyncService { } public void deleteGraphqlApi(String apiId) { + assertSchemaNotBusy(apiId); getGraphqlApi(apiId); apiStore.delete(apiId); schemaStore.delete(apiId); @@ -199,19 +213,25 @@ public class AppSyncService { // ──────────────────────────── Schema ──────────────────────────── - public void startSchemaCreation(String apiId, String definition) { + public SchemaCreationStatus startSchemaCreation(String apiId, String definition) { getGraphqlApi(apiId); - schemaRegistry.register(apiId, definition); - schemaStore.put(apiId, definition); - SchemaCreationStatus status = new SchemaCreationStatus(); - status.setStatus(SchemaCreationStatusType.ACTIVE); - schemaStatusStore.put(apiId, status); - LOG.infov("Schema creation completed for API {0}", apiId); + String accountId = currentAccountId(); + SchemaCreationStatus status; + synchronized (this) { + assertSchemaNotBusy(apiId); + status = new SchemaCreationStatus(); + status.setStatus(SchemaCreationStatusType.PROCESSING); + status.setAccountId(accountId); + schemaStatusStore.putForAccount(accountId, apiId, status); + } + schemaCreationWorker.submit(apiId, definition, accountId); + LOG.infov("Schema creation submitted for API {0}", apiId); + return status; } public SchemaCreationStatus getSchemaCreationStatus(String apiId) { getGraphqlApi(apiId); - return schemaStatusStore.get(apiId).orElseThrow(() -> + return schemaStatusStore.getForAccount(currentAccountId(), apiId).orElseThrow(() -> new AwsException("NotFoundException", "Schema creation status not found for API: " + apiId, 404)); } @@ -222,9 +242,48 @@ public class AppSyncService { "Schema not found for API: " + apiId, 404)); } + /** + * Throw 409 ConcurrentModificationException if the given API has a schema + * creation currently in PROCESSING state. Mirrors AWS behavior where + * schema-mutating operations are blocked while a previous schema + * creation is in flight. + */ + void assertSchemaNotBusy(String apiId) { + schemaStatusStore.getForAccount(currentAccountId(), apiId).ifPresent(s -> throwIfProcessing(s.getStatus())); + } + + /** + * Throw 409 if ANY API in the account has a schema creation in + * PROCESSING state. Used by account-wide operations like + * CreateGraphqlApi / CreateApi that AWS also blocks when a schema + * creation is in flight. + */ + void assertNoSchemaBusyAnywhere() { + for (String apiId : schemaStatusStore.keysForAccount(currentAccountId())) { + schemaStatusStore.getForAccount(currentAccountId(), apiId).ifPresent(s -> throwIfProcessing(s.getStatus())); + } + } + + private void throwIfProcessing(SchemaCreationStatusType status) { + if (status == SchemaCreationStatusType.PROCESSING) { + throw new AwsException("ConcurrentModificationException", + "Another modification is in progress at this time and it must complete before you can make your change.", + 409); + } + } + + private String currentAccountId() { + try { + return requestContextInstance.get().getAccountId(); + } catch (Exception e) { + return "000000000000"; + } + } + // ──────────────────────────── Data Sources ──────────────────────────── public DataSource createDataSource(String apiId, Map request, String region) { + assertSchemaNotBusy(apiId); getGraphqlApi(apiId); String name = (String) request.get("name"); if (name == null || name.isBlank()) { @@ -249,13 +308,14 @@ public class AppSyncService { String dsKey = apiKey(apiId, ds.getName()); if (dataSourceStore.get(dsKey).isPresent()) { - throw new AwsException("ConflictException", "Data source already exists: " + name, 409); + throw new AwsException("BadRequestException", "Data source with name %s already exists.".formatted(name), 400); } dataSourceStore.put(dsKey, ds); return ds; } public DataSource getDataSource(String apiId, String dataSourceName) { + assertSchemaNotBusy(apiId); return dataSourceStore.get(apiKey(apiId, dataSourceName)) .orElseThrow(() -> new AwsException("NotFoundException", "Data source not found: " + dataSourceName, 404)); } @@ -266,6 +326,7 @@ public class AppSyncService { @SuppressWarnings("unchecked") public DataSource updateDataSource(String apiId, String dataSourceName, Map request) { + assertSchemaNotBusy(apiId); DataSource existing = getDataSource(apiId, dataSourceName); if (request.containsKey("description")) existing.setDescription((String) request.get("description")); if (request.containsKey("type")) existing.setType(parseEnum(DataSourceType.class, request.get("type"))); @@ -282,6 +343,7 @@ public class AppSyncService { } public void deleteDataSource(String apiId, String dataSourceName) { + assertSchemaNotBusy(apiId); getDataSource(apiId, dataSourceName); dataSourceStore.delete(apiKey(apiId, dataSourceName)); } @@ -289,6 +351,7 @@ public class AppSyncService { // ──────────────────────────── Resolvers ──────────────────────────── public Resolver createResolver(String apiId, Map request, String region) { + assertSchemaNotBusy(apiId); getGraphqlApi(apiId); String fieldName = (String) request.get("fieldName"); if (fieldName == null || fieldName.isBlank()) { @@ -332,23 +395,19 @@ public class AppSyncService { String key = resolverKey(apiId, resolver.getTypeName(), resolver.getFieldName()); if (resolverStore.get(key).isPresent()) { - throw new AwsException("ConflictException", - "Resolver already exists for " + typeName + "." + fieldName, 409); + throw new AwsException("BadRequestException", "Only one resolver is allowed per field.", 400); } resolverStore.put(key, resolver); return resolver; } public Resolver getResolver(String apiId, String typeName, String fieldName) { + assertSchemaNotBusy(apiId); return resolverStore.get(resolverKey(apiId, typeName, fieldName)) .orElseThrow(() -> new AwsException("NotFoundException", "Resolver not found: " + typeName + "." + fieldName, 404)); } - public Page listResolvers(String apiId, Integer maxResults, String nextToken) { - return paginate(resolverStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults); - } - public Page listResolversByType(String apiId, String typeName, Integer maxResults, String nextToken) { List filtered = resolverStore.scan(k -> k.startsWith(apiId + "::")).stream() .filter(r -> typeName.equals(r.getTypeName())) @@ -366,6 +425,7 @@ public class AppSyncService { @SuppressWarnings("unchecked") public Resolver updateResolver(String apiId, String typeName, String fieldName, Map request) { + assertSchemaNotBusy(apiId); Resolver existing = getResolver(apiId, typeName, fieldName); if (request.containsKey("dataSourceName")) existing.setDataSourceName((String) request.get("dataSourceName")); if (request.containsKey("functionId")) existing.setFunctionId((String) request.get("functionId")); @@ -390,6 +450,7 @@ public class AppSyncService { } public void deleteResolver(String apiId, String typeName, String fieldName) { + assertSchemaNotBusy(apiId); getResolver(apiId, typeName, fieldName); resolverStore.delete(resolverKey(apiId, typeName, fieldName)); } @@ -397,6 +458,7 @@ public class AppSyncService { // ──────────────────────────── Functions ──────────────────────────── public FunctionConfiguration createFunction(String apiId, Map request, String region) { + assertSchemaNotBusy(apiId); getGraphqlApi(apiId); String name = (String) request.get("name"); if (name == null || name.isBlank()) { @@ -422,6 +484,7 @@ public class AppSyncService { } public FunctionConfiguration getFunction(String apiId, String functionId) { + assertSchemaNotBusy(apiId); return functionStore.get(apiKey(apiId, functionId)) .orElseThrow(() -> new AwsException("NotFoundException", "Function not found: " + functionId, 404)); } @@ -431,6 +494,7 @@ public class AppSyncService { } public FunctionConfiguration updateFunction(String apiId, String functionId, Map request) { + assertSchemaNotBusy(apiId); FunctionConfiguration existing = getFunction(apiId, functionId); if (request.containsKey("description")) existing.setDescription((String) request.get("description")); if (request.containsKey("dataSourceName")) existing.setDataSourceName((String) request.get("dataSourceName")); @@ -443,6 +507,7 @@ public class AppSyncService { } public void deleteFunction(String apiId, String functionId) { + assertSchemaNotBusy(apiId); getFunction(apiId, functionId); functionStore.delete(apiKey(apiId, functionId)); } @@ -450,6 +515,7 @@ public class AppSyncService { // ──────────────────────────── Types ──────────────────────────── public AppSyncType createType(String apiId, Map request) { + assertSchemaNotBusy(apiId); getGraphqlApi(apiId); String name = (String) request.get("name"); String definition = (String) request.get("definition"); @@ -461,7 +527,7 @@ public class AppSyncService { } String typeKey = apiKey(apiId, name); if (typeStore.get(typeKey).isPresent()) { - throw new AwsException("ConflictException", "Type already exists: " + name, 409); + throw new AwsException("BadRequestException", "Type with name %s already exists.".formatted(name), 400); } AppSyncType type = new AppSyncType(); type.setApiId(apiId); @@ -475,15 +541,18 @@ public class AppSyncService { } public AppSyncType getType(String apiId, String typeName) { + assertSchemaNotBusy(apiId); return typeStore.get(apiKey(apiId, typeName)) .orElseThrow(() -> new AwsException("NotFoundException", "Type not found: " + typeName, 404)); } public Page listTypes(String apiId, Integer maxResults, String nextToken) { + assertSchemaNotBusy(apiId); return paginate(typeStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults); } public AppSyncType updateType(String apiId, String typeName, Map request) { + assertSchemaNotBusy(apiId); AppSyncType existing = getType(apiId, typeName); if (request.containsKey("definition")) existing.setDefinition((String) request.get("definition")); if (request.containsKey("description")) existing.setDescription((String) request.get("description")); @@ -493,6 +562,7 @@ public class AppSyncService { } public void deleteType(String apiId, String typeName) { + assertSchemaNotBusy(apiId); getType(apiId, typeName); typeStore.delete(apiKey(apiId, typeName)); } @@ -503,8 +573,8 @@ public class AppSyncService { getGraphqlApi(apiId); long existingCount = apiKeyStore.scan(k -> k.startsWith(apiId + "::")).size(); if (existingCount >= 2) { - throw new AwsException("LimitExceededException", - "Maximum of 2 API keys per API reached", 429); + throw new AwsException("ApiKeyLimitExceededException", + "The API key exceeded a limit.", 400); } ApiKey key = new ApiKey(); key.setId(generateShortId()); @@ -604,6 +674,7 @@ public class AppSyncService { } public Map putEnvironmentVariables(String apiId, Map environmentVariables) { + assertSchemaNotBusy(apiId); GraphqlApi api = getGraphqlApi(apiId); api.setEnvironmentVariables(new HashMap<>(environmentVariables)); apiStore.put(apiId, api); @@ -618,7 +689,7 @@ public class AppSyncService { throw new AwsException("BadRequestException", "A domain name is required", 400); } if (domainStore.get(domainName).isPresent()) { - throw new AwsException("ConflictException", "Domain name already exists: " + domainName, 409); + throw new AwsException("BadRequestException", "The domain name you provided already exists.", 400); } DomainName dn = new DomainName(); dn.setDomainName(domainName); @@ -652,6 +723,7 @@ public class AppSyncService { public DomainName updateDomainName(String domainName, Map request) { DomainName existing = getDomainName(domainName); + associationStore.get(domainName).ifPresent(apiId -> assertSchemaNotBusy(apiId)); if (request.containsKey("description")) existing.setDescription((String) request.get("description")); domainStore.put(domainName, existing); return existing; @@ -659,6 +731,7 @@ public class AppSyncService { public void deleteDomainName(String domainName) { getDomainName(domainName); + associationStore.get(domainName).ifPresent(apiId -> assertSchemaNotBusy(apiId)); associationStore.delete(domainName); domainStore.delete(domainName); } @@ -667,8 +740,8 @@ public class AppSyncService { getDomainName(domainName); getGraphqlApi(apiId); if (associationStore.get(domainName).isPresent()) { - throw new AwsException("ConflictException", - "Domain name already associated with an API", 409); + throw new AwsException("BadRequestException", + "The domain name %s is already associated with API %s.".formatted(domainName, apiId), 400); } associationStore.put(domainName, apiId); ApiAssociation assoc = new ApiAssociation(); @@ -693,12 +766,14 @@ public class AppSyncService { public void disassociateApi(String domainName) { getDomainName(domainName); + associationStore.get(domainName).ifPresent(apiId -> assertSchemaNotBusy(apiId)); associationStore.delete(domainName); } // ──────────────────────────── Channel Namespaces ──────────────────────────── public ChannelNamespace createChannelNamespace(String apiId, Map request) { + assertSchemaNotBusy(apiId); getGraphqlApi(apiId); String name = (String) request.get("name"); if (name == null || name.isBlank()) { @@ -729,6 +804,7 @@ public class AppSyncService { } public ChannelNamespace updateChannelNamespace(String apiId, String name, Map request) { + assertSchemaNotBusy(apiId); ChannelNamespace existing = getChannelNamespace(apiId, name); if (request.containsKey("description")) existing.setDescription((String) request.get("description")); if (request.containsKey("codeHandlers")) existing.setCodeHandlers((String) request.get("codeHandlers")); @@ -738,6 +814,7 @@ public class AppSyncService { } public void deleteChannelNamespace(String apiId, String name) { + assertSchemaNotBusy(apiId); getChannelNamespace(apiId, name); channelNamespaceStore.delete(apiKey(apiId, name)); } @@ -755,6 +832,9 @@ public class AppSyncService { throw new AwsException("BadRequestException", "A merged API identifier is required", 400); } getGraphqlApi(mergedApiIdentifier); + assertSchemaNotBusy(sourceApiIdentifier); + assertSchemaNotBusy(mergedApiIdentifier); + checkDuplicateSourceApiAssociation(sourceApiIdentifier, mergedApiIdentifier); SourceApiAssociation assoc = new SourceApiAssociation(); assoc.setAssociationId(generateShortId()); assoc.setAssociationArn(regionResolver.buildArn("appsync", region, @@ -780,6 +860,9 @@ public class AppSyncService { throw new AwsException("BadRequestException", "A source API ID is required", 400); } getGraphqlApi(sourceApiId); + assertSchemaNotBusy(mergedApiIdentifier); + assertSchemaNotBusy(sourceApiId); + checkDuplicateSourceApiAssociation(sourceApiId, mergedApiIdentifier); SourceApiAssociation assoc = new SourceApiAssociation(); assoc.setAssociationId(generateShortId()); assoc.setAssociationArn(regionResolver.buildArn("appsync", region, @@ -811,6 +894,7 @@ public class AppSyncService { public SourceApiAssociation updateSourceApiAssociation(String mergedApiIdentifier, String associationId, Map request) { + assertSchemaNotBusy(mergedApiIdentifier); SourceApiAssociation assoc = getSourceApiAssociation(mergedApiIdentifier, associationId); if (request.containsKey("description")) { assoc.setDescription((String) request.get("description")); @@ -840,11 +924,25 @@ public class AppSyncService { } public void deleteSourceApiAssociation(String mergedApiIdentifier, String associationId) { + assertSchemaNotBusy(mergedApiIdentifier); getSourceApiAssociation(mergedApiIdentifier, associationId); mergedApiAssociationStore.delete(associationId); } + private void checkDuplicateSourceApiAssociation(String sourceApiId, String mergedApiId) { + List existing = mergedApiAssociationStore.scan(k -> true).stream() + .filter(a -> sourceApiId.equals(a.getSourceApiId()) && mergedApiId.equals(a.getMergedApiId())) + .filter(a -> !"DELETION_SCHEDULED".equals(a.getSourceApiAssociationStatus())) + .toList(); + if (!existing.isEmpty()) { + throw new AwsException("ConcurrentModificationException", + "Source API association already exists for Source API ID: %s and Merged API ID: %s." + .formatted(sourceApiId, mergedApiId), 409); + } + } + public SourceApiAssociation deleteMergedApiAssociation(String sourceApiIdentifier, String associationId) { + assertSchemaNotBusy(sourceApiIdentifier); SourceApiAssociation assoc = mergedApiAssociationStore.get(associationId) .orElseThrow(() -> new AwsException("NotFoundException", "Source API association not found: " + associationId, 404)); diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncSchemaParser.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncSchemaParser.java index 6f86958d79..189155775a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncSchemaParser.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncSchemaParser.java @@ -1,15 +1,23 @@ package io.github.hectorvent.floci.services.appsync.graphql; +import graphql.GraphQLError; +import graphql.language.SourceLocation; +import graphql.parser.InvalidSyntaxException; import graphql.schema.GraphQLSchema; import graphql.schema.idl.RuntimeWiring; import graphql.schema.idl.SchemaGenerator; import graphql.schema.idl.SchemaParser; import graphql.schema.idl.TypeDefinitionRegistry; +import graphql.schema.idl.errors.SchemaProblem; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.appsync.graphql.scalars.AppSyncScalarRegistry; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -31,8 +39,18 @@ public class AppSyncSchemaParser { TypeDefinitionRegistry typeRegistry; try { typeRegistry = parser.parse(sdlWithDirectives); - } catch (Exception e) { - throw new AwsException("BadRequestException", "Invalid schema: " + e.getMessage(), 400); + } catch (SchemaProblem e) { + List> codeErrors = new ArrayList<>(); + for (GraphQLError ge : e.getErrors()) { + codeErrors.add(toCodeErrorFromGraphQL("PARSER_ERROR", ge)); + } + throw new AwsException("BadRequestException", + "Invalid schema: " + e.getMessage(), 400, + buildExtendedData(codeErrors)); + } catch (InvalidSyntaxException e) { + throw new AwsException("BadRequestException", + "Invalid schema: " + e.getMessage(), 400, + buildExtendedData(List.of(toCodeError("PARSER_ERROR", e.getMessage(), 0, 0)))); } RuntimeWiring.Builder wiringBuilder = RuntimeWiring.newRuntimeWiring(); @@ -42,27 +60,68 @@ public class AppSyncSchemaParser { try { return new SchemaGenerator().makeExecutableSchema(typeRegistry, wiringBuilder.build()); + } catch (SchemaProblem e) { + List> codeErrors = new ArrayList<>(); + for (GraphQLError ge : e.getErrors()) { + codeErrors.add(toCodeErrorFromGraphQL("VALIDATION_ERROR", ge)); + } + throw new AwsException("BadRequestException", + "Invalid schema: " + e.getMessage(), 400, + buildExtendedData(codeErrors)); } catch (RuntimeException e) { - throw new AwsException("BadRequestException", "Invalid schema: " + e.getMessage(), 400); + throw new AwsException("BadRequestException", + "Invalid schema: " + e.getMessage(), 400); } } private void validateNoUnknownDirectives(String sdl) { String clean = sdl - .replaceAll("\"\"\"[\\s\\S]*?\"\"\"", "") - .replaceAll("\"(?:[^\"\\\\]|\\\\.)*\"", "") - .replaceAll("#[^\n]*", ""); + .replaceAll("\"\"\"[\\s\\S]*?\"\"\"", "") + .replaceAll("\"(?:[^\"\\\\]|\\\\.)*\"", "") + .replaceAll("#[^\n]*", ""); Pattern directivePattern = Pattern.compile("@(\\w+)"); Matcher matcher = directivePattern.matcher(clean); while (matcher.find()) { String name = matcher.group(1); if (!AppSyncDirective.isKnown(name)) { throw new AwsException("BadRequestException", - "Unknown directive: @" + name, 400); + "Unknown directive: @" + name, 400, + buildExtendedData(List.of( + toCodeError("VALIDATION_ERROR", "Unknown directive: @" + name, 0, 0)))); } } } + private Map toCodeErrorFromGraphQL(String errorType, GraphQLError ge) { + List locs = ge.getLocations(); + if (locs != null && !locs.isEmpty()) { + SourceLocation first = locs.get(0); + return toCodeError(errorType, ge.getMessage(), first.getLine(), first.getColumn()); + } + return toCodeError(errorType, ge.getMessage(), 0, 0); + } + + private Map toCodeError(String errorType, String value, int line, int column) { + Map codeError = new LinkedHashMap<>(); + codeError.put("errorType", errorType); + codeError.put("value", value); + Map location = new LinkedHashMap<>(); + location.put("line", line); + location.put("column", column); + location.put("span", -1); + codeError.put("location", location); + return codeError; + } + + private Map buildExtendedData(List> codeErrors) { + Map detail = new LinkedHashMap<>(); + detail.put("codeErrors", codeErrors); + Map extendedData = new LinkedHashMap<>(); + extendedData.put("reason", "CODE_ERROR"); + extendedData.put("detail", detail); + return extendedData; + } + private String injectDirectiveDefinitions(String sdl) { StringBuilder sb = new StringBuilder(); for (AppSyncDirective directive : AppSyncDirective.values()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorker.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorker.java new file mode 100644 index 0000000000..d65bdbdb71 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorker.java @@ -0,0 +1,152 @@ +package io.github.hectorvent.floci.services.appsync.graphql; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatus; +import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatusType; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * Async worker that processes schema creation jobs in background threads. + * Mirrors AWS AppSync behavior where StartSchemaCreation is asynchronous: + * the request returns PROCESSING immediately, and the schema is compiled + * in the background, transitioning to ACTIVE (success) or FAILED (error). + */ +@ApplicationScoped +public class SchemaCreationWorker { + + private static final Logger LOG = Logger.getLogger(SchemaCreationWorker.class); + + private final SchemaRegistry schemaRegistry; + private final AccountAwareStorageBackend schemaStatusStore; + private final StorageBackend schemaStore; + private final EmulatorConfig config; + private final ObjectMapper objectMapper; + + private ExecutorService executor; + + @Inject + public SchemaCreationWorker(SchemaRegistry schemaRegistry, + AccountAwareStorageBackend schemaStatusStore, + StorageBackend schemaStore, + EmulatorConfig config, + ObjectMapper objectMapper) { + this.schemaRegistry = schemaRegistry; + this.schemaStatusStore = schemaStatusStore; + this.schemaStore = schemaStore; + this.config = config; + this.objectMapper = objectMapper; + } + + @PostConstruct + void init() { + int threads = config.services().appsync().schemaWorkerThreads(); + executor = Executors.newFixedThreadPool(threads, r -> { + Thread t = new Thread(r, "appsync-schema-worker"); + t.setDaemon(true); + return t; + }); + LOG.infov("SchemaCreationWorker started with {0} threads", threads); + } + + @PreDestroy + void shutdown() { + if (executor == null) { + return; + } + int timeout = config.services().appsync().schemaWorkerShutdownTimeoutSeconds(); + executor.shutdown(); + try { + if (!executor.awaitTermination(timeout, TimeUnit.SECONDS)) { + LOG.warnv("Schema workers did not finish within {0}s, forcing shutdown", timeout); + executor.shutdownNow(); + } + } catch (InterruptedException e) { + executor.shutdownNow(); + Thread.currentThread().interrupt(); + } + } + + public void submit(String apiId, String sdl, String accountId) { + executor.submit(() -> process(apiId, sdl, accountId)); + } + + private void process(String apiId, String sdl, String accountId) { + try { + schemaRegistry.register(apiId, sdl); + schemaStore.put(apiId, sdl); + markStatus(accountId, apiId, SchemaCreationStatusType.SUCCESS, null); + LOG.infov("Schema creation completed for API {0}", apiId); + } catch (AwsException e) { + String details = serializeExtendedData(e); + markStatus(accountId, apiId, SchemaCreationStatusType.FAILED, details); + LOG.warnv("Schema creation failed for API {0}: {1}", apiId, e.getMessage()); + } catch (RuntimeException e) { + markStatus(accountId, apiId, SchemaCreationStatusType.FAILED, e.getMessage()); + LOG.errorv(e, "Unexpected error during schema creation for API {0}", apiId); + } + } + + private void markStatus(String accountId, String apiId, SchemaCreationStatusType status, String details) { + SchemaCreationStatus s = new SchemaCreationStatus(); + s.setStatus(status); + s.setAccountId(accountId); + if (details != null) { + s.setDetails(details); + } + schemaStatusStore.putForAccount(accountId, apiId, s); + } + + private String serializeExtendedData(AwsException e) { + if (e.getExtendedData() == null) { + return e.getMessage(); + } + try { + return objectMapper.writeValueAsString(e.getExtendedData()); + } catch (JsonProcessingException ex) { + return e.getMessage(); + } + } + + /** + * Used at startup to recover orphan PROCESSING statuses from a previous run. + */ + public void recoverOrphans() { + int recovered = 0; + Map allEntries = schemaStatusStore.scanAllAccountsAsMap(); + for (Map.Entry entry : allEntries.entrySet()) { + SchemaCreationStatus s = entry.getValue(); + if (s.getStatus() == SchemaCreationStatusType.PROCESSING) { + String apiId = entry.getKey(); + String accountId = s.getAccountId(); + if (accountId == null) { + accountId = "000000000000"; + } + s.setStatus(SchemaCreationStatusType.FAILED); + if (s.getDetails() == null) { + s.setDetails("{\"reason\":\"ORPHAN_PROCESSING\",\"message\":\"Recovered from orphan PROCESSING on emulator startup\"}"); + } + schemaStatusStore.putForAccount(accountId, apiId, s); + recovered++; + LOG.warnv("Marked orphan schema creation for API {0} as FAILED", apiId); + } + } + if (recovered > 0) { + LOG.infov("Recovered {0} orphan schema creation(s) on startup", recovered); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStatusStoreProducer.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStatusStoreProducer.java new file mode 100644 index 0000000000..149f41e87d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStatusStoreProducer.java @@ -0,0 +1,36 @@ +package io.github.hectorvent.floci.services.appsync.graphql; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatus; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Produces; +import jakarta.inject.Inject; + +import java.util.Map; + +/** + * Produces the shared {@link AccountAwareStorageBackend} used to track schema creation + * status. Lives as a CDI bean so both {@code AppSyncService} (which mutates + * the status from request threads) and {@code SchemaCreationWorker} (which + * transitions the status from background worker threads) see the same + * in-memory state and the same flush cycle. + */ +@ApplicationScoped +public class SchemaStatusStoreProducer { + + private final AccountAwareStorageBackend store; + + @Inject + public SchemaStatusStoreProducer(StorageFactory storageFactory) { + this.store = (AccountAwareStorageBackend) storageFactory.create("appsync", "appsync-schema-status.json", + new TypeReference>() {}); + } + + @Produces + @ApplicationScoped + public AccountAwareStorageBackend produce() { + return store; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStoreProducer.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStoreProducer.java new file mode 100644 index 0000000000..4f863a50fd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStoreProducer.java @@ -0,0 +1,33 @@ +package io.github.hectorvent.floci.services.appsync.graphql; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Produces; +import jakarta.inject.Inject; + +import java.util.Map; + +/** + * Produces the shared {@link StorageBackend} used to store compiled SDL schemas. + * Shared between {@code AppSyncService} (reads via getIntrospectionSchema) and + * {@code SchemaCreationWorker} (writes on successful compilation). + */ +@ApplicationScoped +public class SchemaStoreProducer { + + private final StorageBackend store; + + @Inject + public SchemaStoreProducer(StorageFactory storageFactory) { + this.store = storageFactory.create("appsync", "appsync-schemas.json", + new TypeReference>() {}); + } + + @Produces + @ApplicationScoped + public StorageBackend produce() { + return store; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/SchemaCreationStatus.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/SchemaCreationStatus.java index c685d141c4..a777d15af0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/model/SchemaCreationStatus.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/SchemaCreationStatus.java @@ -10,10 +10,14 @@ import io.quarkus.runtime.annotations.RegisterForReflection; public class SchemaCreationStatus { private SchemaCreationStatusType status; private String details; + private String accountId; public SchemaCreationStatusType getStatus() { return status; } public void setStatus(SchemaCreationStatusType status) { this.status = status; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } + + public String getAccountId() { return accountId; } + public void setAccountId(String accountId) { this.accountId = accountId; } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 2a560042f9..243c02f003 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -134,6 +134,8 @@ floci: # Override storage mode for EC2 (defaults to the global storage mode). EC2 networking and # instance metadata persist so CloudFormation-created VPC/subnet ids survive a restart (#1297). # mode: memory + appsync: + flush-interval-ms: 5000 dns: # Extra hostname suffixes resolved to Floci's container IP by the embedded DNS server. @@ -420,6 +422,8 @@ floci: enabled: true appsync: enabled: true + schema-worker-threads: 4 + schema-worker-shutdown-timeout-seconds: 30 s3vectors: enabled: true iot: diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java index 6cac5cd364..ef86720356 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java @@ -77,6 +77,7 @@ class EmulatorLifecycleTest { @Mock private io.github.hectorvent.floci.services.floci.ui.FlociUiManager flociUiManager; @Mock private InitLifecycleState initLifecycleState; @Mock private EmulatorConfig.TlsConfig tlsConfig; + @Mock private io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker schemaCreationWorker; private EmulatorLifecycle emulatorLifecycle; @@ -96,7 +97,8 @@ class EmulatorLifecycleTest { docDbContainerManager, neptuneContainerManager, neptuneProxyManager, rabbitMqManager, rdsService, initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller, - pipesService, ec2MetadataServer, ecrRegistryManager, flociUiManager, initLifecycleState); + pipesService, ec2MetadataServer, ecrRegistryManager, flociUiManager, initLifecycleState, + schemaCreationWorker); } private void stubStorageConfig() { diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncIntegrationTest.java index 01517aacef..de964a1dc0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncIntegrationTest.java @@ -1,5 +1,8 @@ package io.github.hectorvent.floci.services.appsync; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatus; +import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatusType; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.BeforeAll; @@ -8,10 +11,11 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; +import java.time.Duration; import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @QuarkusTest @@ -22,13 +26,71 @@ class AppSyncIntegrationTest { private static String apiId; private static String keyId; + @jakarta.inject.Inject + StorageBackend schemaStatusStore; + @BeforeAll static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); } - private static String encodeArn(String arn) { - return URLEncoder.encode(arn, StandardCharsets.UTF_8).replace("+", "%20"); + /** + * Polls GetSchemaCreationStatus until status is no longer PROCESSING + * (i.e. ACTIVE or FAILED) and returns the full response payload. Mirrors + * how a real AWS SDK client would poll after StartSchemaCreation + * returns PROCESSING. Use {@link #getTerminalStatus(String)} if only + * the status string is needed. + */ + private static java.util.Map awaitSchemaTerminal(String apiId) { + return await().atMost(Duration.ofSeconds(10)) + .pollInterval(Duration.ofMillis(25)) + .until(() -> given() + .header("Authorization", AUTH) + .when() + .get("/v1/apis/" + apiId + "/schemacreation") + .then() + .statusCode(200) + .extract().jsonPath().getMap(""), + m -> !"PROCESSING".equals(m.get("status"))); + } + + /** + * Asserts that the schema reaches the expected terminal status (ACTIVE or FAILED). + * Used after a StartSchemaCreation that returns PROCESSING. + */ + private static void assertTerminalStatus(String apiId, String expected) { + assertThat(awaitSchemaTerminal(apiId).get("status"), equalTo(expected)); + } + + /** + * Posts a StartSchemaCreation, then polls to FAILED and returns the + * deserialized extended data (containing reason + detail.codeErrors). + * Used by tests that previously expected a synchronous 400 with the + * extended format body — AWS now returns 200 + PROCESSING and the + * error surfaces in the polled FAILED status. + */ + @SuppressWarnings("unchecked") + private static java.util.Map postSchemaAndAwaitFailed(String apiId, String body) { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(body) + .when() + .post("/v1/apis/" + apiId + "/schemacreation") + .then() + .statusCode(200) + .body("status", equalTo("PROCESSING")); + + java.util.Map full = awaitSchemaTerminal(apiId); + assertThat(full.get("status"), equalTo("FAILED")); + String detailsJson = (String) full.get("details"); + assertThat(detailsJson, notNullValue()); + try { + return new com.fasterxml.jackson.databind.ObjectMapper() + .readValue(detailsJson, java.util.Map.class); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + throw new RuntimeException(e); + } } // ── GraphQL API ────────────────────────────────────────────────────────── @@ -120,19 +182,21 @@ class AppSyncIntegrationTest { .post("/v1/apis/" + apiId + "/schemacreation") .then() .statusCode(200) - .body("status", equalTo("ACTIVE")); + .body("status", equalTo("PROCESSING")); + assertTerminalStatus(apiId, "SUCCESS"); } @Test @Order(21) void getSchemaCreationStatus() { + assertTerminalStatus(apiId, "SUCCESS"); given() .header("Authorization", AUTH) .when() .get("/v1/apis/" + apiId + "/schemacreation") .then() .statusCode(200) - .body("status", equalTo("ACTIVE")); + .body("status", equalTo("SUCCESS")); } @Test @@ -184,19 +248,6 @@ class AppSyncIntegrationTest { .body("apiKeys[0].id", notNullValue()); } - @Test - @Order(32) - void getApiKey() { - given() - .header("Authorization", AUTH) - .when() - .get("/v1/apis/" + apiId + "/apikeys/" + keyId) - .then() - .statusCode(200) - .body("apiKey.id", equalTo(keyId)) - .body("apiKey.description", equalTo("test-key")); - } - @Test @Order(33) void updateApiKey() { @@ -404,7 +455,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + apiId + "/types/TempType") .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Type not found:")); } // ── Resolvers ──────────────────────────────────────────────────────────── @@ -457,20 +510,6 @@ class AppSyncIntegrationTest { .body("resolvers", hasSize(greaterThanOrEqualTo(1))); } - @Test - @Order(62) - void listAllResolvers() { - given() - .header("Authorization", AUTH) - .when() - .get("/v1/apis/" + apiId + "/resolvers") - .then() - .statusCode(200) - .body("resolvers", hasSize(greaterThanOrEqualTo(1))) - .body("resolvers[0].typeName", notNullValue()) - .body("resolvers[0].fieldName", notNullValue()); - } - @Test @Order(63) void updateResolver() { @@ -627,7 +666,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + apiId + "/functions/" + tempFnId) .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Function not found:")); } // ── Tags ───────────────────────────────────────────────────────────────── @@ -708,7 +749,7 @@ class AppSyncIntegrationTest { } """) .when() - .put("/v1/apis/" + apiId + "/environmentvariables") + .put("/v1/apis/" + apiId + "/environmentVariables") .then() .statusCode(200) .body("environmentVariables.TABLE_NAME", equalTo("my-table")) @@ -721,7 +762,7 @@ class AppSyncIntegrationTest { given() .header("Authorization", AUTH) .when() - .get("/v1/apis/" + apiId + "/environmentvariables") + .get("/v1/apis/" + apiId + "/environmentVariables") .then() .statusCode(200) .body("environmentVariables.TABLE_NAME", equalTo("my-table")) @@ -742,7 +783,7 @@ class AppSyncIntegrationTest { } """) .when() - .put("/v1/apis/" + apiId + "/environmentvariables") + .put("/v1/apis/" + apiId + "/environmentVariables") .then() .statusCode(200) .body("environmentVariables.NEW_VAR", equalTo("new-value")) @@ -763,7 +804,9 @@ class AppSyncIntegrationTest { .when() .post("/v1/apis") .then() - .statusCode(400); + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("A GraphQL API name is required")); } @Test @@ -778,7 +821,9 @@ class AppSyncIntegrationTest { .when() .post("/v1/apis") .then() - .statusCode(400); + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("A GraphQL API name is required")); } @Test @@ -793,7 +838,9 @@ class AppSyncIntegrationTest { .when() .post("/v1/apis") .then() - .statusCode(400); + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("Invalid value 'INVALID_TYPE' for AuthenticationType")); } @Test @@ -808,7 +855,9 @@ class AppSyncIntegrationTest { .when() .post("/v1/apis/" + apiId + "/datasources") .then() - .statusCode(400); + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("A data source name is required")); } @Test @@ -823,7 +872,9 @@ class AppSyncIntegrationTest { .when() .post("/v1/apis/" + apiId + "/datasources") .then() - .statusCode(400); + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("A data source type is required")); } @Test @@ -838,7 +889,9 @@ class AppSyncIntegrationTest { .when() .post("/v1/apis/" + apiId + "/datasources") .then() - .statusCode(400); + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("Invalid value 'NOT_A_REAL_TYPE' for DataSourceType")); } @Test @@ -853,7 +906,9 @@ class AppSyncIntegrationTest { .when() .post("/v1/apis/" + apiId + "/types/Query/resolvers") .then() - .statusCode(400); + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("A resolver field name is required")); } @Test @@ -868,7 +923,9 @@ class AppSyncIntegrationTest { .when() .post("/v1/apis/" + apiId + "/types/Query/resolvers") .then() - .statusCode(400); + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("A data source name is required for the resolver")); } @Test @@ -894,7 +951,9 @@ class AppSyncIntegrationTest { .when() .post("/v1/apis/" + apiId + "/types") .then() - .statusCode(400); + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("A type name is required")); } @Test @@ -909,7 +968,9 @@ class AppSyncIntegrationTest { .when() .post("/v1/apis/" + apiId + "/functions") .then() - .statusCode(400); + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("A function name is required")); } @Test @@ -920,7 +981,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/doesnotexist12345678901234") .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("GraphQL API not found:")); } @Test @@ -931,7 +994,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + apiId + "/datasources/nonexistent-ds") .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Data source not found:")); } @Test @@ -942,7 +1007,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + apiId + "/types/NonExistentType") .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Type not found:")); } // ── Delete Standalone ────────────────────────────────────────────────── @@ -976,7 +1043,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + apiId + "/types/Query/resolvers/tempResolver") .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Resolver not found:")); } @Test @@ -1008,7 +1077,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + apiId + "/datasources/temp-ds-delete") .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Data source not found:")); } @Test @@ -1041,7 +1112,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + apiId + "/functions/" + tempFnId) .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Function not found:")); } @Test @@ -1073,7 +1146,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + apiId + "/types/StandaloneDeleteType") .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Type not found:")); } @Test @@ -1098,12 +1173,14 @@ class AppSyncIntegrationTest { .then() .statusCode(204); + // Verify deletion by listing (getApiKey endpoint does not exist in AWS) given() .header("Authorization", AUTH) .when() - .get("/v1/apis/" + apiId + "/apikeys/" + tempKeyId) + .get("/v1/apis/" + apiId + "/apikeys") .then() - .statusCode(404); + .statusCode(200) + .body("apiKeys.id", not(hasItem(tempKeyId))); } @Test @@ -1187,7 +1264,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + tempApiId + "/datasources/cascade-ds") .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Data source not found:")); } @Test @@ -1250,7 +1329,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + tempApiId + "/functions/" + fnId) .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Function not found:")); } @Test @@ -1456,7 +1537,734 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis") .then() - .statusCode(400); + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("Invalid NextToken.")); + } + + // ── BadRequestException (400) for duplicates ────────────────────────────── + + @Test + @Order(150) + void createDataSourceDuplicateReturns400() { + String dsName = "conflict-ds-" + System.nanoTime(); + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "%s", "type": "NONE"} + """.formatted(dsName)) + .when() + .post("/v1/apis/" + apiId + "/datasources") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "%s", "type": "NONE"} + """.formatted(dsName)) + .when() + .post("/v1/apis/" + apiId + "/datasources") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("Data source with name")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + apiId + "/datasources/" + dsName).then().statusCode(204); + } + + @Test + @Order(151) + void createResolverDuplicateReturns400() { + String fieldName = "conflictField" + System.nanoTime(); + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"fieldName": "%s", "dataSourceName": "none-ds"} + """.formatted(fieldName)) + .when() + .post("/v1/apis/" + apiId + "/types/Query/resolvers") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"fieldName": "%s", "dataSourceName": "none-ds"} + """.formatted(fieldName)) + .when() + .post("/v1/apis/" + apiId + "/types/Query/resolvers") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("Only one resolver is allowed per field")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + apiId + "/types/Query/resolvers/" + fieldName).then().statusCode(204); + } + + @Test + @Order(152) + void createTypeDuplicateReturns400() { + String typeName = "ConflictType" + System.nanoTime(); + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "%s", "definition": "type %s { id: ID }"} + """.formatted(typeName, typeName)) + .when() + .post("/v1/apis/" + apiId + "/types") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "%s", "definition": "type %s { id: ID }"} + """.formatted(typeName, typeName)) + .when() + .post("/v1/apis/" + apiId + "/types") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("Type with name")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + apiId + "/types/" + typeName).then().statusCode(204); + } + + @Test + @Order(153) + void createDomainNameDuplicateReturns400() { + String domain = "conflict-" + System.nanoTime() + ".example.com"; + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"domainName": "%s", "certificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/1"} + """.formatted(domain)) + .when() + .post("/v1/domainnames") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"domainName": "%s", "certificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/2"} + """.formatted(domain)) + .when() + .post("/v1/domainnames") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("The domain name you provided already exists")); + + given().header("Authorization", AUTH).delete("/v1/domainnames/" + domain).then().statusCode(204); + } + + @Test + @Order(154) + void createChannelNamespaceDuplicateReturns409() { + String nsName = "conflict-ns-" + System.nanoTime(); + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "%s"} + """.formatted(nsName)) + .when() + .post("/v2/apis/" + apiId + "/channelNamespaces") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "%s"} + """.formatted(nsName)) + .when() + .post("/v2/apis/" + apiId + "/channelNamespaces") + .then() + .statusCode(409) + .body("__type", equalTo("ConflictException")) + .body("message", containsString("Channel namespace already exists:")); + + given().header("Authorization", AUTH).delete("/v2/apis/" + apiId + "/channelNamespaces/" + nsName).then().statusCode(204); + } + + @Test + @Order(157) + void createSourceApiAssociationDuplicateReturns409() { + String sourceApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "dup-source-157", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "sourceApiId": "%s" } + """.formatted(sourceApiId)) + .when() + .post("/v1/mergedApis/" + apiId + "/sourceApiAssociations") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "sourceApiId": "%s" } + """.formatted(sourceApiId)) + .when() + .post("/v1/mergedApis/" + apiId + "/sourceApiAssociations") + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")) + .body("message", containsString("Source API association already exists for Source API ID")) + .body("message", containsString("and Merged API ID")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + sourceApiId).then().statusCode(204); + } + + @Test + @Order(158) + void createSourceApiAssociationReplacesDeletionScheduled() { + String sourceApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "replace-source-158", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + String assocId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "sourceApiId": "%s" } + """.formatted(sourceApiId)) + .when() + .post("/v1/mergedApis/" + apiId + "/sourceApiAssociations") + .then() + .statusCode(200) + .extract().path("sourceApiAssociation.associationId"); + + given() + .header("Authorization", AUTH) + .delete("/v1/mergedApis/" + apiId + "/sourceApiAssociations/" + assocId) + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "sourceApiId": "%s" } + """.formatted(sourceApiId)) + .when() + .post("/v1/mergedApis/" + apiId + "/sourceApiAssociations") + .then() + .statusCode(200); + + given().header("Authorization", AUTH).delete("/v1/apis/" + sourceApiId).then().statusCode(204); + } + + @Test + @Order(155) + void associateApiDuplicateReturns400() { + String domain = "assoc-conflict-" + System.nanoTime() + ".example.com"; + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "assoc-conflict-api", "authenticationType": "API_KEY"} + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"domainName": "%s", "certificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/ac"} + """.formatted(domain)) + .when() + .post("/v1/domainnames") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"apiId": "%s"} + """.formatted(tempApiId)) + .when() + .post("/v1/domainnames/" + domain + "/apiassociation") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"apiId": "%s"} + """.formatted(apiId)) + .when() + .post("/v1/domainnames/" + domain + "/apiassociation") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("already associated with API")); + + given().header("Authorization", AUTH).delete("/v1/domainnames/" + domain).then().statusCode(204); + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + // ── ApiKeyLimitExceededException (400) ───────────────────────────────── + + @Test + @Order(160) + void createApiKeyExceedsLimitReturns400() { + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "limit-test-api", "authenticationType": "API_KEY"} + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"description": "key-1"} + """) + .when() + .post("/v1/apis/" + tempApiId + "/apikeys") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"description": "key-2"} + """) + .when() + .post("/v1/apis/" + tempApiId + "/apikeys") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"description": "key-3"} + """) + .when() + .post("/v1/apis/" + tempApiId + "/apikeys") + .then() + .statusCode(400) + .body("__type", equalTo("ApiKeyLimitExceededException")) + .body("message", containsString("The API key exceeded a limit")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + // ── NotFoundException (404) on update/delete of missing resources ──────── + + @Test + @Order(170) + void updateResolverNonExistentReturns404() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"dataSourceName": "none-ds"} + """) + .when() + .post("/v1/apis/" + apiId + "/types/Query/resolvers/nonExistentField") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Resolver not found:")); + } + + @Test + @Order(171) + void deleteResolverNonExistentReturns404() { + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/apis/" + apiId + "/types/Query/resolvers/nonExistentField") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Resolver not found:")); + } + + @Test + @Order(172) + void updateFunctionNonExistentReturns404() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "nonexistent-fn", "dataSourceName": "none-ds"} + """) + .when() + .post("/v1/apis/" + apiId + "/functions/nonexistent00000000000") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Function not found:")); + } + + @Test + @Order(173) + void deleteFunctionNonExistentReturns404() { + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/apis/" + apiId + "/functions/nonexistent00000000000") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Function not found:")); + } + + @Test + @Order(174) + void updateApiKeyNonExistentReturns404() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"description": "updated"} + """) + .when() + .post("/v1/apis/" + apiId + "/apikeys/nonexistent00000000000") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("API key not found:")); + } + + @Test + @Order(175) + void deleteApiKeyNonExistentReturns404() { + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/apis/" + apiId + "/apikeys/nonexistent00000000000") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("API key not found:")); + } + + @Test + @Order(176) + void updateDomainNameNonExistentReturns404() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"description": "updated"} + """) + .when() + .post("/v1/domainnames/nonexistent.example.com") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Domain name not found:")); + } + + @Test + @Order(177) + void updateChannelNamespaceNonExistentReturns404() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"description": "updated"} + """) + .when() + .post("/v2/apis/" + apiId + "/channelNamespaces/nonexistent-ns") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Channel namespace not found:")); + } + + // ── Cross-resource 404 on create (missing referenced resource) ─────────── + + @Test + @Order(190) + void createResolverMissingDataSourceReturns404() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"fieldName": "crossRefField", "dataSourceName": "nonexistent-ds-for-resolver"} + """) + .when() + .post("/v1/apis/" + apiId + "/types/Query/resolvers") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Data source not found:")); + } + + @Test + @Order(191) + void createFunctionMissingDataSourceReturns404() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "cross-ref-fn", "dataSourceName": "nonexistent-ds-for-fn"} + """) + .when() + .post("/v1/apis/" + apiId + "/functions") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Data source not found:")); + } + + @Test + @Order(192) + void associateApiMissingDomainReturns404() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"apiId": "%s"} + """.formatted(apiId)) + .when() + .post("/v1/domainnames/nonexistent-for-assoc.example.com/apiassociation") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Domain name not found:")); + } + + // ── Pagination for previously untested list operations ─────────────────── + + @Test + @Order(180) + void listDomainNamesWithMaxResults() { + String d1 = "pg-domain-1-" + System.nanoTime() + ".example.com"; + String d2 = "pg-domain-2-" + System.nanoTime() + ".example.com"; + String cert = "arn:aws:acm:us-east-1:000000000000:certificate/pg"; + + for (String d : new String[]{d1, d2}) { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"domainName": "%s", "certificateArn": "%s"} + """.formatted(d, cert)) + .when() + .post("/v1/domainnames") + .then() + .statusCode(200); + } + + String nextToken = given() + .header("Authorization", AUTH) + .queryParam("maxResults", 1) + .when() + .get("/v1/domainnames") + .then() + .statusCode(200) + .body("domainNameConfigs", hasSize(1)) + .body("nextToken", notNullValue()) + .extract().path("nextToken"); + + given() + .header("Authorization", AUTH) + .queryParam("maxResults", 1) + .queryParam("nextToken", nextToken) + .when() + .get("/v1/domainnames") + .then() + .statusCode(200) + .body("domainNameConfigs", hasSize(greaterThanOrEqualTo(1))); + + given().header("Authorization", AUTH).delete("/v1/domainnames/" + d1).then().statusCode(204); + given().header("Authorization", AUTH).delete("/v1/domainnames/" + d2).then().statusCode(204); + } + + @Test + @Order(181) + void listChannelNamespacesWithMaxResults() { + String ns1 = "pg-ns-1-" + System.nanoTime(); + String ns2 = "pg-ns-2-" + System.nanoTime(); + + for (String ns : new String[]{ns1, ns2}) { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "%s"} + """.formatted(ns)) + .when() + .post("/v2/apis/" + apiId + "/channelNamespaces") + .then() + .statusCode(200); + } + + String nextToken = given() + .header("Authorization", AUTH) + .queryParam("maxResults", 1) + .when() + .get("/v2/apis/" + apiId + "/channelNamespaces") + .then() + .statusCode(200) + .body("channelNamespaces", hasSize(1)) + .body("nextToken", notNullValue()) + .extract().path("nextToken"); + + given() + .header("Authorization", AUTH) + .queryParam("maxResults", 1) + .queryParam("nextToken", nextToken) + .when() + .get("/v2/apis/" + apiId + "/channelNamespaces") + .then() + .statusCode(200) + .body("channelNamespaces", hasSize(greaterThanOrEqualTo(1))); + + given().header("Authorization", AUTH).delete("/v2/apis/" + apiId + "/channelNamespaces/" + ns1).then().statusCode(204); + given().header("Authorization", AUTH).delete("/v2/apis/" + apiId + "/channelNamespaces/" + ns2).then().statusCode(204); + } + + @Test + @Order(182) + void listSourceApiAssociationsWithMaxResults() { + String s1 = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "pg-src-1", "authenticationType": "API_KEY"} + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + String s2 = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "pg-src-2", "authenticationType": "API_KEY"} + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + for (String s : new String[]{s1, s2}) { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"sourceApiId": "%s"} + """.formatted(s)) + .when() + .post("/v1/mergedApis/" + apiId + "/sourceApiAssociations") + .then() + .statusCode(200); + } + + given() + .header("Authorization", AUTH) + .queryParam("maxResults", 1) + .when() + .get("/v1/apis/" + apiId + "/sourceApiAssociations") + .then() + .statusCode(200) + .body("sourceApiAssociationSummaries", hasSize(1)) + .body("nextToken", notNullValue()); + + given().header("Authorization", AUTH).delete("/v1/apis/" + s1).then().statusCode(204); + given().header("Authorization", AUTH).delete("/v1/apis/" + s2).then().statusCode(204); + } + + // ── Pagination edge cases ──────────────────────────────────────────────── + + @Test + @Order(195) + void listWithMaxResultsZero() { + given() + .header("Authorization", AUTH) + .queryParam("maxResults", 0) + .when() + .get("/v1/apis/" + apiId + "/datasources") + .then() + .statusCode(200) + .body("dataSources", hasSize(0)) + .body("nextToken", notNullValue()); + } + + @Test + @Order(196) + void listWithNegativeMaxResultsReturns400() { + given() + .header("Authorization", AUTH) + .queryParam("maxResults", -1) + .when() + .get("/v1/apis/" + apiId + "/datasources") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("maxResults must be non-negative")); + } + + @Test + @Order(197) + void listWithInvalidNextTokenNonApiReturns400() { + given() + .header("Authorization", AUTH) + .queryParam("nextToken", "!!!invalid-token!!!") + .when() + .get("/v1/apis/" + apiId + "/datasources") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", containsString("Invalid NextToken.")); } // ── Phase 2: Model Completeness ───────────────────────────────────────── @@ -1717,7 +2525,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/domainnames/nonexistent.example.com") .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Domain name not found:")); } @Test @@ -1751,7 +2561,9 @@ class AppSyncIntegrationTest { .when() .post("/v1/domainnames/" + tempDomain + "/apiassociation") .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("GraphQL API not found:")); // cleanup given().header("Authorization", AUTH).delete("/v1/domainnames/" + tempDomain).then().statusCode(204); @@ -1817,6 +2629,38 @@ class AppSyncIntegrationTest { .statusCode(204); } + @Test + @Order(410) + void updateChannelNamespace() { + String nsName = "update-ns-" + System.nanoTime(); + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "%s", "description": "original"} + """.formatted(nsName)) + .when() + .post("/v2/apis/" + apiId + "/channelNamespaces") + .then() + .statusCode(200) + .body("channelNamespace.description", equalTo("original")); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"description": "updated-ns"} + """) + .when() + .post("/v2/apis/" + apiId + "/channelNamespaces/" + nsName) + .then() + .statusCode(200) + .body("channelNamespace.name", equalTo(nsName)) + .body("channelNamespace.description", equalTo("updated-ns")); + + given().header("Authorization", AUTH).delete("/v2/apis/" + apiId + "/channelNamespaces/" + nsName).then().statusCode(204); + } + // ── Phase 2: Schema Registry ───────────────────────────────────────────── @Test @@ -1833,7 +2677,12 @@ class AppSyncIntegrationTest { .when() .post("/v1/apis/" + apiId + "/schemacreation") .then() - .statusCode(400); + .statusCode(200) + .body("status", equalTo("PROCESSING")); + java.util.Map body = awaitSchemaTerminal(apiId); + assertThat(body.get("status"), equalTo("FAILED")); + String details = (String) body.get("details"); + assertThat(details, notNullValue()); } @Test @@ -1863,7 +2712,8 @@ class AppSyncIntegrationTest { .post("/v1/apis/" + tempApiId + "/schemacreation") .then() .statusCode(200) - .body("status", equalTo("ACTIVE")); + .body("status", equalTo("PROCESSING")); + assertTerminalStatus(tempApiId, "SUCCESS"); given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); } @@ -1895,7 +2745,8 @@ class AppSyncIntegrationTest { .post("/v1/apis/" + tempApiId + "/schemacreation") .then() .statusCode(200) - .body("status", equalTo("ACTIVE")); + .body("status", equalTo("PROCESSING")); + assertTerminalStatus(tempApiId, "SUCCESS"); given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); } @@ -1927,7 +2778,8 @@ class AppSyncIntegrationTest { .post("/v1/apis/" + tempApiId + "/schemacreation") .then() .statusCode(200) - .body("status", equalTo("ACTIVE")); + .body("status", equalTo("PROCESSING")); + assertTerminalStatus(tempApiId, "SUCCESS"); given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); } @@ -1959,7 +2811,8 @@ class AppSyncIntegrationTest { .post("/v1/apis/" + tempApiId + "/schemacreation") .then() .statusCode(200) - .body("status", equalTo("ACTIVE")); + .body("status", equalTo("PROCESSING")); + assertTerminalStatus(tempApiId, "SUCCESS"); given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); } @@ -1991,7 +2844,8 @@ class AppSyncIntegrationTest { .post("/v1/apis/" + tempApiId + "/schemacreation") .then() .statusCode(200) - .body("status", equalTo("ACTIVE")); + .body("status", equalTo("PROCESSING")); + assertTerminalStatus(tempApiId, "SUCCESS"); given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); } @@ -2027,7 +2881,8 @@ class AppSyncIntegrationTest { .post("/v1/apis/" + tempApiId + "/schemacreation") .then() .statusCode(200) - .body("status", equalTo("ACTIVE")); + .body("status", equalTo("PROCESSING")); + assertTerminalStatus(tempApiId, "SUCCESS"); given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); } @@ -2047,20 +2902,542 @@ class AppSyncIntegrationTest { .statusCode(200) .extract().path("graphqlApi.apiId"); + java.util.Map ext = postSchemaAndAwaitFailed(tempApiId, """ + { + "definition": "type Query { hello: String } directive @unknownDirective on FIELD_DEFINITION" + } + """); + assertThat(ext.get("reason"), equalTo("CODE_ERROR")); + java.util.List> codeErrors = + (java.util.List>) ((java.util.Map) ext.get("detail")).get("codeErrors"); + assertThat(codeErrors.get(0).get("errorType"), equalTo("VALIDATION_ERROR")); + assertThat((String) codeErrors.get(0).get("value"), containsString("Unknown directive")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + @Test + @Order(700) + void startSchemaCreation_syntaxError_returnsExtendedBadRequest() { + java.util.Map ext = postSchemaAndAwaitFailed(apiId, """ + { + "definition": "type Query { invalid syntax!!! }" + } + """); + assertThat(ext.get("reason"), equalTo("CODE_ERROR")); + java.util.List> codeErrors = + (java.util.List>) ((java.util.Map) ext.get("detail")).get("codeErrors"); + assertThat(codeErrors.size(), greaterThanOrEqualTo(1)); + assertThat(codeErrors.get(0).get("errorType"), equalTo("PARSER_ERROR")); + assertThat(codeErrors.get(0).get("value"), notNullValue()); + java.util.Map location = (java.util.Map) codeErrors.get(0).get("location"); + assertThat(location, notNullValue()); + assertThat(location.get("line"), notNullValue()); + assertThat(location.get("column"), notNullValue()); + assertThat(location.get("span"), equalTo(-1)); + } + + @Test + @Order(701) + void startSchemaCreation_semanticError_returnsExtendedBadRequest() { + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "semantic-701", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + java.util.Map ext = postSchemaAndAwaitFailed(tempApiId, """ + { + "definition": "type Query { hello: NonExistentType }" + } + """); + assertThat(ext.get("reason"), equalTo("CODE_ERROR")); + java.util.List> codeErrors = + (java.util.List>) ((java.util.Map) ext.get("detail")).get("codeErrors"); + assertThat(codeErrors.get(0).get("errorType"), equalTo("VALIDATION_ERROR")); + assertThat((String) codeErrors.get(0).get("value"), containsString("NonExistentType")); + java.util.Map location = (java.util.Map) codeErrors.get(0).get("location"); + assertThat(location.get("line"), notNullValue()); + assertThat(location.get("column"), notNullValue()); + assertThat(location.get("span"), equalTo(-1)); + + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + @Test + @Order(702) + void startSchemaCreation_unknownDirective_returnsExtendedBadRequest() { + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "unknown-dir-702", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + java.util.Map ext = postSchemaAndAwaitFailed(tempApiId, """ + { + "definition": "type Query { hello: String @unknownDirective }" + } + """); + assertThat(ext.get("reason"), equalTo("CODE_ERROR")); + java.util.List> codeErrors = + (java.util.List>) ((java.util.Map) ext.get("detail")).get("codeErrors"); + assertThat(codeErrors.get(0).get("errorType"), equalTo("VALIDATION_ERROR")); + assertThat((String) codeErrors.get(0).get("value"), containsString("Unknown directive: @unknownDirective")); + java.util.Map location = (java.util.Map) codeErrors.get(0).get("location"); + assertThat(location.get("span"), equalTo(-1)); + + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + // ── Phase 2: Schema-Creation 409 Gates ─────────────────────────────────── + + /** + * Sets the schema status of {@code apiId} to PROCESSING directly via the + * shared storage backend. Used by the 409-gate tests below to simulate an + * in-flight schema creation deterministically, without relying on the + * async worker timing. + */ + private void setSchemaProcessing(String apiId) { + SchemaCreationStatus s = new SchemaCreationStatus(); + s.setStatus(SchemaCreationStatusType.PROCESSING); + schemaStatusStore.put(apiId, s); + } + + /** + * Removes any schema status for {@code apiId}, cleaning up after a test. + */ + private void clearSchemaStatus(String apiId) { + schemaStatusStore.delete(apiId); + } + + /** + * Creates a temporary API for use by 409-gate tests. Returns its id. + */ + private String createTempApi(String name) { + return given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"name\":\"" + name + "\",\"authenticationType\":\"API_KEY\"}") + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + } + + /** + * Deletes a temporary API. Used in {@link #assertBusyReturns409}. + */ + private void deleteTempApi(String apiId) { + given().header("Authorization", AUTH) + .delete("/v1/apis/" + apiId) + .then() + .statusCode(204); + } + + /** + * Sets the schema status of {@code tempApiId} to PROCESSING, runs the given + * body (which should expect 409), and finally cleans up the status and + * deletes the temporary API. Centralizes the boilerplate of the 9 + * 409-gate tests below. + */ + private void assertBusyReturns409(String tempApiId, Runnable body) { + setSchemaProcessing(tempApiId); + try { + body.run(); + } finally { + clearSchemaStatus(tempApiId); + deleteTempApi(tempApiId); + } + } + + @Test + @Order(703) + void createDataSource_busy_returns409() { + String tempApiId = createTempApi("busy-703-ds"); + assertBusyReturns409(tempApiId, () -> { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "ds-busy", "type": "NONE" } + """) + .when() + .post("/v1/apis/" + tempApiId + "/datasources") + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")) + .body("message", containsString("Another modification is in progress")); + }); + } + + @Test + @Order(704) + void createResolver_busy_returns409() { + String tempApiId = createTempApi("busy-704"); + assertBusyReturns409(tempApiId, () -> { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "dataSourceName": "ds-704", "fieldName": "hello", "typeName": "Query", + "requestMappingTemplate": "{\\"version\\":\\"2018-05-29\\",\\"operation\\":\\"GetItem\\"}", + "responseMappingTemplate": "$util.toJson($ctx.result)" } + """) + .when() + .post("/v1/apis/" + tempApiId + "/types/Query/resolvers") + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")); + }); + } + + @Test + @Order(705) + void createFunction_busy_returns409() { + String tempApiId = createTempApi("busy-705"); + assertBusyReturns409(tempApiId, () -> { + given().header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "fn-705", "dataSourceName": "ds-705", + "requestMappingTemplate": "{\\"version\\":\\"2018-05-29\\",\\"operation\\":\\"GetItem\\"}", + "responseMappingTemplate": "$util.toJson($ctx.result)" } + """) + .when() + .post("/v1/apis/" + tempApiId + "/functions") + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")); + }); + } + + @Test + @Order(706) + void createType_busy_returns409() { + String tempApiId = createTempApi("busy-706"); + assertBusyReturns409(tempApiId, () -> { + given().header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "CustomType", "definition": "type CustomType { x: String }", "format": "SDL" } + """) + .when() + .post("/v1/apis/" + tempApiId + "/types") + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")); + }); + } + + @Test + @Order(707) + void putEnvironmentVariables_busy_returns409() { + String tempApiId = createTempApi("busy-707"); + assertBusyReturns409(tempApiId, () -> { + given().header("Authorization", AUTH) + .contentType("application/json") + .body("{\"environmentVariables\":{\"FOO\":\"bar\"}}") + .when() + .put("/v1/apis/" + tempApiId + "/environmentVariables") + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")); + }); + } + + @Test + @Order(708) + void startSchemaCreation_busy_returns409() { + // The StartSchemaCreation gate is self-blocking: a second submission + // for the same API while one is PROCESSING must return 409. + String tempApiId = createTempApi("busy-708"); + assertBusyReturns409(tempApiId, () -> { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"definition\":\"type Query { a: String }\"}") + .when() + .post("/v1/apis/" + tempApiId + "/schemacreation") + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")) + .body("message", containsString("Another modification is in progress")); + }); + } + + @Test + @Order(709) + void createGraphqlApi_anyApiBusy_returns409() { + // Account-level gate: when ANY API has a schema creation in + // PROCESSING, creating a new GraphqlApi is blocked. + String tempApiId = createTempApi("busy-709-any"); + assertBusyReturns409(tempApiId, () -> { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "should-fail-709", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")); + }); + } + + @Test + @Order(710) + void updateGraphqlApi_busy_returns409() { + String tempApiId = createTempApi("busy-710-update"); + assertBusyReturns409(tempApiId, () -> { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "renamed-710" } + """) + .when() + .post("/v1/apis/" + tempApiId) + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")); + }); + } + + @Test + @Order(711) + void deleteGraphqlApi_busy_returns409() { + // For delete we need the API to exist when the gate fires; clear + // status BEFORE the delete so the finally block's delete succeeds. + String tempApiId = createTempApi("busy-711-delete"); + setSchemaProcessing(tempApiId); + try { + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/apis/" + tempApiId) + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")); + } finally { + clearSchemaStatus(tempApiId); + } + } + + @Test + @Order(712) + void deleteChannelNamespace_busy_returns409() { + String tempApiId = createTempApi("busy-712-chns"); + // Create the channel namespace BEFORE setting PROCESSING so the + // delete path finds it (otherwise we'd get 404 instead of 409). + String nsName = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "busy-chns", "description": "temp" } + """) + .when() + .post("/v2/apis/" + tempApiId + "/channelNamespaces") + .then() + .statusCode(200) + .extract().path("channelNamespace.name"); + setSchemaProcessing(tempApiId); + try { + given() + .header("Authorization", AUTH) + .when() + .delete("/v2/apis/" + tempApiId + "/channelNamespaces/" + nsName) + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")) + .body("message", containsString("Another modification is in progress")); + } finally { + clearSchemaStatus(tempApiId); + } + } + + @Test + @Order(713) + void deleteDomainName_busy_returns409() { + String tempApiId = createTempApi("busy-713-domain"); + String domainName = "busy-713-" + System.nanoTime() + ".example.com"; + // Create domain name + associate it with the temp API so the + // gate can resolve the apiId and return 409. given() .header("Authorization", AUTH) .contentType("application/json") .body(""" - { - "definition": "type Query { hello: String } directive @unknownDirective on FIELD_DEFINITION" - } + { "domainName": "%s", "certificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/123" } + """.formatted(domainName)) + .when() + .post("/v1/domainnames") + .then() + .statusCode(200); + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "apiId": "%s" } + """.formatted(tempApiId)) + .when() + .post("/v1/domainnames/" + domainName + "/apiassociation") + .then() + .statusCode(200); + setSchemaProcessing(tempApiId); + try { + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/domainnames/" + domainName) + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")) + .body("message", containsString("Another modification is in progress")); + } finally { + clearSchemaStatus(tempApiId); + } + } + + @Test + @Order(714) + void disassociateApi_busy_returns409() { + String tempApiId = createTempApi("busy-714-disassoc"); + String domainName = "busy-714-" + System.nanoTime() + ".example.com"; + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "domainName": "%s", "certificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/123" } + """.formatted(domainName)) + .when() + .post("/v1/domainnames") + .then() + .statusCode(200); + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "apiId": "%s" } + """.formatted(tempApiId)) + .when() + .post("/v1/domainnames/" + domainName + "/apiassociation") + .then() + .statusCode(200); + setSchemaProcessing(tempApiId); + try { + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/domainnames/" + domainName + "/apiassociation") + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")) + .body("message", containsString("Another modification is in progress")); + } finally { + clearSchemaStatus(tempApiId); + } + } + + @Test + @Order(715) + void disassociateMergedGraphqlApi_busy_returns409() { + String tempApiId = createTempApi("busy-715-merged"); + // Create a source API, associate it as merged, then attempt to + // disassociate while the source API schema is PROCESSING. + String sourceApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "busy-715-source", "authenticationType": "API_KEY" } """) .when() - .post("/v1/apis/" + tempApiId + "/schemacreation") + .post("/v1/apis") .then() - .statusCode(400); + .statusCode(200) + .extract().path("graphqlApi.apiId"); + String assocId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "mergedApiIdentifier": "%s" } + """.formatted(tempApiId)) + .when() + .post("/v1/sourceApis/" + sourceApiId + "/mergedApiAssociations") + .then() + .statusCode(200) + .extract().path("sourceApiAssociation.associationId"); + setSchemaProcessing(sourceApiId); + try { + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/sourceApis/" + sourceApiId + "/mergedApiAssociations/" + assocId) + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")) + .body("message", containsString("Another modification is in progress")); + } finally { + clearSchemaStatus(sourceApiId); + given().header("Authorization", AUTH).delete("/v1/apis/" + sourceApiId).then().statusCode(204); + } + } - given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + @Test + @Order(716) + void updateDomainName_busy_returns409() { + String tempApiId = createTempApi("busy-716-upd-domain"); + String domainName = "busy-716-" + System.nanoTime() + ".example.com"; + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "domainName": "%s", "certificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/123" } + """.formatted(domainName)) + .when() + .post("/v1/domainnames") + .then() + .statusCode(200); + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "apiId": "%s" } + """.formatted(tempApiId)) + .when() + .post("/v1/domainnames/" + domainName + "/apiassociation") + .then() + .statusCode(200); + setSchemaProcessing(tempApiId); + try { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "description": "updated" } + """) + .when() + .post("/v1/domainnames/" + domainName) + .then() + .statusCode(409) + .body("__type", equalTo("ConcurrentModificationException")) + .body("message", containsString("Another modification is in progress")); + } finally { + clearSchemaStatus(tempApiId); + } } // ── Phase 2: Merged APIs ─────────────────────────────────────────────── @@ -2630,7 +4007,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + apiId) .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("GraphQL API not found:")); } @Test @@ -2641,7 +4020,9 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + apiId + "/datasources/none-ds") .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Data source not found:")); } @Test @@ -2652,6 +4033,8 @@ class AppSyncIntegrationTest { .when() .get("/v1/apis/" + apiId + "/types/Query") .then() - .statusCode(404); + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", containsString("Type not found:")); } } diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 99a5d9974b..c42761017f 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -59,6 +59,8 @@ floci: elasticbeanstalk: flush-interval-ms: 60000 cloudfront: + appsync: + flush-interval-ms: 60000 auth: validate-signatures: false @@ -267,6 +269,8 @@ floci: enabled: true appsync: enabled: true + schema-worker-threads: 4 + schema-worker-shutdown-timeout-seconds: 30 s3vectors: enabled: true iot: