mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(appsync): Phase 5 — Management API Coverage + AWS Behavior Alignment + Async Schema Creation (#1590)
* 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":"<ExceptionClass>","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: <id> and Merged API ID: <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.
This commit is contained in:
1 parent
27f0124e36
commit
f915622e36
17 files changed
+2252
-171
No files matched your search
@@ -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 {
|
||||
|
||||
@@ -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.
|
||||
* <p>
|
||||
* 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<String, Object> extendedData;
|
||||
|
||||
public AwsException(String errorCode, String message, int httpStatus) {
|
||||
this(errorCode, message, httpStatus, null);
|
||||
}
|
||||
|
||||
public AwsException(String errorCode, String message, int httpStatus, Map<String, Object> 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<String, Object> 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.
|
||||
|
||||
@@ -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<AwsException> {
|
||||
|
||||
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<String, Object> entry : exception.getExtendedData().entrySet()) {
|
||||
node.set(entry.getKey(), objectMapper.valueToTree(entry.getValue()));
|
||||
}
|
||||
return node;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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<String, String> 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")
|
||||
|
||||
@@ -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<String, GraphqlApi> apiStore;
|
||||
private final StorageBackend<String, String> schemaStore;
|
||||
private final StorageBackend<String, SchemaCreationStatus> schemaStatusStore;
|
||||
private final AccountAwareStorageBackend<SchemaCreationStatus> schemaStatusStore;
|
||||
private final StorageBackend<String, DataSource> dataSourceStore;
|
||||
private final StorageBackend<String, Resolver> resolverStore;
|
||||
private final StorageBackend<String, FunctionConfiguration> functionStore;
|
||||
@@ -34,14 +38,19 @@ public class AppSyncService {
|
||||
private final StorageBackend<String, SourceApiAssociation> mergedApiAssociationStore;
|
||||
private final RegionResolver regionResolver;
|
||||
private final SchemaRegistry schemaRegistry;
|
||||
private final SchemaCreationWorker schemaCreationWorker;
|
||||
private final Instance<RequestContext> requestContextInstance;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public AppSyncService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
SchemaRegistry schemaRegistry, ObjectMapper objectMapper) {
|
||||
SchemaRegistry schemaRegistry, SchemaCreationWorker schemaCreationWorker,
|
||||
Instance<RequestContext> requestContextInstance, ObjectMapper objectMapper,
|
||||
AccountAwareStorageBackend<SchemaCreationStatus> schemaStatusStore,
|
||||
StorageBackend<String, String> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<Resolver> listResolvers(String apiId, Integer maxResults, String nextToken) {
|
||||
return paginate(resolverStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults);
|
||||
}
|
||||
|
||||
public Page<Resolver> listResolversByType(String apiId, String typeName, Integer maxResults, String nextToken) {
|
||||
List<Resolver> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<AppSyncType> 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<String, Object> 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<String, String> putEnvironmentVariables(String apiId, Map<String, String> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<SourceApiAssociation> 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));
|
||||
|
||||
+66
-7
@@ -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<Map<String, Object>> 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<Map<String, Object>> 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<String, Object> toCodeErrorFromGraphQL(String errorType, GraphQLError ge) {
|
||||
List<SourceLocation> 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<String, Object> toCodeError(String errorType, String value, int line, int column) {
|
||||
Map<String, Object> codeError = new LinkedHashMap<>();
|
||||
codeError.put("errorType", errorType);
|
||||
codeError.put("value", value);
|
||||
Map<String, Object> location = new LinkedHashMap<>();
|
||||
location.put("line", line);
|
||||
location.put("column", column);
|
||||
location.put("span", -1);
|
||||
codeError.put("location", location);
|
||||
return codeError;
|
||||
}
|
||||
|
||||
private Map<String, Object> buildExtendedData(List<Map<String, Object>> codeErrors) {
|
||||
Map<String, Object> detail = new LinkedHashMap<>();
|
||||
detail.put("codeErrors", codeErrors);
|
||||
Map<String, Object> 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()) {
|
||||
|
||||
+152
@@ -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<SchemaCreationStatus> schemaStatusStore;
|
||||
private final StorageBackend<String, String> schemaStore;
|
||||
private final EmulatorConfig config;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private ExecutorService executor;
|
||||
|
||||
@Inject
|
||||
public SchemaCreationWorker(SchemaRegistry schemaRegistry,
|
||||
AccountAwareStorageBackend<SchemaCreationStatus> schemaStatusStore,
|
||||
StorageBackend<String, String> 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<String, SchemaCreationStatus> allEntries = schemaStatusStore.scanAllAccountsAsMap();
|
||||
for (Map.Entry<String, SchemaCreationStatus> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
@@ -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<SchemaCreationStatus> store;
|
||||
|
||||
@Inject
|
||||
public SchemaStatusStoreProducer(StorageFactory storageFactory) {
|
||||
this.store = (AccountAwareStorageBackend<SchemaCreationStatus>) storageFactory.create("appsync", "appsync-schema-status.json",
|
||||
new TypeReference<Map<String, SchemaCreationStatus>>() {});
|
||||
}
|
||||
|
||||
@Produces
|
||||
@ApplicationScoped
|
||||
public AccountAwareStorageBackend<SchemaCreationStatus> produce() {
|
||||
return store;
|
||||
}
|
||||
}
|
||||
+33
@@ -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<String, String> store;
|
||||
|
||||
@Inject
|
||||
public SchemaStoreProducer(StorageFactory storageFactory) {
|
||||
this.store = storageFactory.create("appsync", "appsync-schemas.json",
|
||||
new TypeReference<Map<String, String>>() {});
|
||||
}
|
||||
|
||||
@Produces
|
||||
@ApplicationScoped
|
||||
public StorageBackend<String, String> produce() {
|
||||
return store;
|
||||
}
|
||||
}
|
||||
+4
@@ -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; }
|
||||
}
|
||||
Reference in new issue
Block a user