mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(appsync): Phase 6 — Query Execution + HTTP Endpoint (#1884)
* feat(appsync): Phase 6 GraphQL HTTP execute endpoint
Expose POST /v1/apis/{apiId}/graphql with AppSync-compatible error
mapping, dual Content-Type, schema rehydrate on boot, and smoke
execution without Phase 8 DataFetchers.
* fix(appsync): initialize graphql IdGenerator at native runtime
Query execution pulls graphql.util.IdGenerator into the native image
reachability graph; its static Random must not be frozen in the heap.
* fix(appsync): cache GraphQL engines and always set x-amzn-errortype
Cache graphql-java GraphQL wrappers per apiId in SchemaRegistry (invalidate
on register/remove/rehydrate), and emit x-amzn-errortype on all data-plane
non-2xx responses for AWS parity with AppSync transport errors.
* fix(appsync): hide unexpected exception details on GraphQL 500
AppSync returns a fixed InternalFailure message for unexpected
errors; keep the real cause in server logs only.
* chore(appsync): drop redundant native-init comment
* fix(appsync): rehydrate schemas across all accounts on boot
Startup has no request context, so keys()/get() only saw the default
account. Mirror recoverOrphans with scanAllAccountsAsMap, persist SDL via
putForAccount in the worker, and drop the shared .atl/ gitignore entry.
* fix(appsync): keep non-404 AwsException on data-plane envelope
Avoid rethrowing AwsException from the GraphQL execute endpoint into
AwsExceptionMapper (__type). Map unexpected lookup failures to
InternalFailure with the AppSync errors[] shape instead.
* docs(appsync): point error formatter @see at $util.error docs
security-authz.html covers authorization types, not errorType/errorInfo.
Cite built-in-util-js.html where $util.error documents those fields.
* refactor(storage): type StorageFactory.create as AccountAwareStorageBackend
The factory always wraps every mode in AccountAwareStorageBackend; declaring
that return type removes unsafe casts at AppSync/CodePipeline/CloudFormation
call sites and updates test overrides/mocks to match production.
* fix(test): stub StorageFactory.create with AccountAware backends
thenAnswer stubs that returned bare InMemoryStorage ClassCast after
create() was typed as AccountAwareStorageBackend; align the remaining
service unit tests with the production return type.
This commit is contained in:
1 parent
a803626c17
commit
819bfedc6c
58 files changed
+1529
-131
No files matched your search
@@ -42,6 +42,14 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
|
||||
this.defaultAccountId = defaultAccountId;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory account-aware store with no request context (uses {@code defaultAccountId}).
|
||||
* Useful for unit tests and for callers that need an explicit {@link AccountAwareStorageBackend}.
|
||||
*/
|
||||
public static <V> AccountAwareStorageBackend<V> inMemory(String defaultAccountId) {
|
||||
return new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, defaultAccountId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void put(String key, V value) {
|
||||
delegate.put(prefixed(key), value);
|
||||
|
||||
@@ -54,7 +54,7 @@ public class StorageFactory {
|
||||
* @param fileName the JSON file name for persistent storage
|
||||
* @param typeReference Jackson type reference for deserialization
|
||||
*/
|
||||
public synchronized <V> StorageBackend<String, V> create(String serviceName, String fileName,
|
||||
public synchronized <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
String mode = resolveMode(serviceName);
|
||||
long flushInterval = resolveFlushInterval(serviceName);
|
||||
@@ -68,7 +68,7 @@ public class StorageFactory {
|
||||
if (existing != null) {
|
||||
LOG.debugv("Reusing existing {0} storage for service {1} (file: {2})", mode, serviceName, filePath);
|
||||
@SuppressWarnings("unchecked")
|
||||
StorageBackend<String, V> typed = (StorageBackend<String, V>) existing;
|
||||
AccountAwareStorageBackend<V> typed = (AccountAwareStorageBackend<V>) existing;
|
||||
return typed;
|
||||
}
|
||||
|
||||
|
||||
@@ -175,6 +175,7 @@ public class EmulatorLifecycle {
|
||||
serviceRegistry.logEnabledServices();
|
||||
storageFactory.loadAll();
|
||||
schemaCreationWorker.recoverOrphans();
|
||||
schemaCreationWorker.rehydrateSchemas();
|
||||
|
||||
sqsPoller.startPersistedPollers();
|
||||
kinesisPoller.startPersistedPollers();
|
||||
|
||||
@@ -25,7 +25,7 @@ public class AppSyncService {
|
||||
private static final Logger LOG = Logger.getLogger(AppSyncService.class);
|
||||
|
||||
private final StorageBackend<String, GraphqlApi> apiStore;
|
||||
private final StorageBackend<String, String> schemaStore;
|
||||
private final AccountAwareStorageBackend<String> schemaStore;
|
||||
private final AccountAwareStorageBackend<SchemaCreationStatus> schemaStatusStore;
|
||||
private final StorageBackend<String, DataSource> dataSourceStore;
|
||||
private final StorageBackend<String, Resolver> resolverStore;
|
||||
@@ -47,7 +47,7 @@ public class AppSyncService {
|
||||
SchemaRegistry schemaRegistry, SchemaCreationWorker schemaCreationWorker,
|
||||
Instance<RequestContext> requestContextInstance, ObjectMapper objectMapper,
|
||||
AccountAwareStorageBackend<SchemaCreationStatus> schemaStatusStore,
|
||||
StorageBackend<String, String> schemaStore) {
|
||||
AccountAwareStorageBackend<String> schemaStore) {
|
||||
this.apiStore = storageFactory.create("appsync", "appsync-apis.json", new TypeReference<>() {});
|
||||
this.schemaStore = schemaStore;
|
||||
this.schemaStatusStore = schemaStatusStore;
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package io.github.hectorvent.floci.services.appsync.graphql;
|
||||
|
||||
import graphql.ErrorType;
|
||||
import graphql.ExecutionResult;
|
||||
import graphql.GraphQLError;
|
||||
import graphql.ErrorClassification;
|
||||
import graphql.language.SourceLocation;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Maps graphql-java {@link ExecutionResult} errors to AWS AppSync wire shapes
|
||||
* with top-level {@code errorType}/{@code errorInfo} (not extensions-only).
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/appsync/latest/devguide/built-in-util-js.html">AppSync DG {@code $util.error} ({@code errorType}/{@code errorInfo})</a>
|
||||
* @see <a href="https://github.com/graphql/graphql-over-http/issues/81">AppSync HTTP behavior (AppSync team / @robzhu)</a>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class AppSyncErrorFormatter {
|
||||
|
||||
/**
|
||||
* Messages from AppSync team sample:
|
||||
* <a href="https://github.com/graphql/graphql-over-http/issues/81">graphql-over-http#81</a>
|
||||
*/
|
||||
public static final String MSG_EMPTY_BODY = "Request body is empty.";
|
||||
public static final String MSG_UNABLE_TO_PARSE = "Unable to parse GraphQL query.";
|
||||
public static final String MSG_MISSING_OPERATION_NAME = "Missing operation name.";
|
||||
public static final String MSG_NO_SCHEMA = "No schema definition exists.";
|
||||
|
||||
public Map<String, Object> format(ExecutionResult result) {
|
||||
Map<String, Object> response = new LinkedHashMap<>();
|
||||
if (result.isDataPresent()) {
|
||||
response.put("data", result.getData());
|
||||
}
|
||||
List<GraphQLError> errors = result.getErrors();
|
||||
if (errors != null && !errors.isEmpty()) {
|
||||
List<Map<String, Object>> formatted = new ArrayList<>(errors.size());
|
||||
for (GraphQLError error : errors) {
|
||||
formatted.add(formatError(error));
|
||||
}
|
||||
response.put("errors", formatted);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
public Map<String, Object> transportError(String errorType, String message) {
|
||||
Map<String, Object> error = new LinkedHashMap<>();
|
||||
error.put("errorType", errorType);
|
||||
error.put("message", message);
|
||||
Map<String, Object> response = new LinkedHashMap<>();
|
||||
response.put("errors", List.of(error));
|
||||
return response;
|
||||
}
|
||||
|
||||
private Map<String, Object> formatError(GraphQLError error) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("message", error.getMessage());
|
||||
List<SourceLocation> locations = error.getLocations();
|
||||
if (locations != null && !locations.isEmpty()) {
|
||||
List<Map<String, Object>> locationMaps = new ArrayList<>(locations.size());
|
||||
for (SourceLocation location : locations) {
|
||||
Map<String, Object> loc = new LinkedHashMap<>();
|
||||
loc.put("line", location.getLine());
|
||||
loc.put("column", location.getColumn());
|
||||
locationMaps.add(loc);
|
||||
}
|
||||
map.put("locations", locationMaps);
|
||||
}
|
||||
List<Object> path = error.getPath();
|
||||
if (path != null && !path.isEmpty()) {
|
||||
map.put("path", path);
|
||||
}
|
||||
map.put("errorType", toAppSyncErrorType(error.getErrorType()));
|
||||
map.put("errorInfo", null);
|
||||
return map;
|
||||
}
|
||||
|
||||
static String toAppSyncErrorType(ErrorClassification classification) {
|
||||
if (classification == ErrorType.InvalidSyntax) {
|
||||
return "SyntaxError";
|
||||
}
|
||||
if (classification == ErrorType.ValidationError) {
|
||||
return "ValidationError";
|
||||
}
|
||||
if (classification == ErrorType.OperationNotSupported) {
|
||||
return "OperationNotSupported";
|
||||
}
|
||||
if (classification == ErrorType.DataFetchingException) {
|
||||
return "DataFetchingException";
|
||||
}
|
||||
if (classification == null) {
|
||||
return "Unknown";
|
||||
}
|
||||
if (classification instanceof ErrorType errorType) {
|
||||
return errorType.name();
|
||||
}
|
||||
return classification.toString();
|
||||
}
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
package io.github.hectorvent.floci.services.appsync.graphql;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.appsync.AppSyncService;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* AppSync GraphQL data-plane HTTP endpoint (separate from management {@code AppSyncController}).
|
||||
* Accepts {@code application/graphql} and {@code application/json}.
|
||||
*/
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public class AppSyncExecutionController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AppSyncExecutionController.class);
|
||||
private static final String HEADER_ERROR_TYPE = "x-amzn-errortype";
|
||||
|
||||
private final AppSyncService appSyncService;
|
||||
private final SchemaRegistry schemaRegistry;
|
||||
private final QueryExecutor queryExecutor;
|
||||
private final AppSyncErrorFormatter errorFormatter;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public AppSyncExecutionController(AppSyncService appSyncService,
|
||||
SchemaRegistry schemaRegistry,
|
||||
QueryExecutor queryExecutor,
|
||||
AppSyncErrorFormatter errorFormatter,
|
||||
ObjectMapper objectMapper) {
|
||||
this.appSyncService = appSyncService;
|
||||
this.schemaRegistry = schemaRegistry;
|
||||
this.queryExecutor = queryExecutor;
|
||||
this.errorFormatter = errorFormatter;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/v1/apis/{apiId}/graphql")
|
||||
public Response execute(@PathParam("apiId") String apiId,
|
||||
@Context HttpHeaders headers,
|
||||
String body) {
|
||||
try {
|
||||
if (!isAcceptedContentType(headers)) {
|
||||
return graphqlError(400, "MalformedHttpRequestException",
|
||||
AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE);
|
||||
}
|
||||
|
||||
ParsedRequest parsed;
|
||||
try {
|
||||
parsed = parseBody(body);
|
||||
} catch (AppSyncTransportException e) {
|
||||
return graphqlError(e.getHttpStatus(), e.getErrorType(), e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
appSyncService.getGraphqlApi(apiId);
|
||||
} catch (AwsException e) {
|
||||
if (e.getHttpStatus() == 404) {
|
||||
return graphqlError(404, "NotFoundException", e.getMessage());
|
||||
}
|
||||
// Stay on the data-plane errors envelope; never leak to AwsExceptionMapper (__type).
|
||||
LOG.errorv(e, "Unexpected AwsException looking up API {0}", apiId);
|
||||
return graphqlError(500, "InternalFailure", "InternalFailure");
|
||||
}
|
||||
|
||||
var graphQLOpt = schemaRegistry.getGraphQL(apiId);
|
||||
if (graphQLOpt.isEmpty()) {
|
||||
return graphqlError(502, "GraphQLSchemaException",
|
||||
AppSyncErrorFormatter.MSG_NO_SCHEMA);
|
||||
}
|
||||
|
||||
try {
|
||||
Map<String, Object> result = queryExecutor.execute(
|
||||
graphQLOpt.get(), parsed.query(), parsed.variables(), parsed.operationName());
|
||||
return Response.ok(result).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (AppSyncTransportException e) {
|
||||
return graphqlError(e.getHttpStatus(), e.getErrorType(), e.getMessage());
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.errorv(e, "Unexpected error executing GraphQL for API {0}", apiId);
|
||||
return graphqlError(500, "InternalFailure", "InternalFailure");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isAcceptedContentType(HttpHeaders headers) {
|
||||
String contentType = headers.getHeaderString(HttpHeaders.CONTENT_TYPE);
|
||||
if (contentType == null || contentType.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String normalized = contentType.toLowerCase(Locale.ROOT).trim();
|
||||
int semicolon = normalized.indexOf(';');
|
||||
if (semicolon >= 0) {
|
||||
normalized = normalized.substring(0, semicolon).trim();
|
||||
}
|
||||
return "application/json".equals(normalized) || "application/graphql".equals(normalized);
|
||||
}
|
||||
|
||||
private ParsedRequest parseBody(String body) {
|
||||
if (body == null || body.isBlank()) {
|
||||
throw new AppSyncTransportException(400, "MalformedHttpRequestException",
|
||||
AppSyncErrorFormatter.MSG_EMPTY_BODY);
|
||||
}
|
||||
|
||||
JsonNode root;
|
||||
try {
|
||||
root = objectMapper.readTree(body);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AppSyncTransportException(400, "MalformedHttpRequestException",
|
||||
AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE);
|
||||
}
|
||||
|
||||
if (root == null || root.isNull() || root.isArray() || !root.isObject()) {
|
||||
throw new AppSyncTransportException(400, "MalformedHttpRequestException",
|
||||
AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE);
|
||||
}
|
||||
if (root.isEmpty()) {
|
||||
throw new AppSyncTransportException(400, "MalformedHttpRequestException",
|
||||
AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE);
|
||||
}
|
||||
|
||||
JsonNode queryNode = root.get("query");
|
||||
if (queryNode == null || !queryNode.isTextual()) {
|
||||
throw new AppSyncTransportException(400, "MalformedHttpRequestException",
|
||||
AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE);
|
||||
}
|
||||
// Blank queries are valid GraphQL-over-HTTP JSON and become SyntaxError (HTTP 200)
|
||||
// via graphql-java — not MalformedHttpRequestException (400).
|
||||
String query = queryNode.asText();
|
||||
|
||||
Map<String, Object> variables = null;
|
||||
JsonNode variablesNode = root.get("variables");
|
||||
if (variablesNode != null && !variablesNode.isNull()) {
|
||||
if (!variablesNode.isObject()) {
|
||||
throw new AppSyncTransportException(400, "MalformedHttpRequestException",
|
||||
AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE);
|
||||
}
|
||||
variables = objectMapper.convertValue(variablesNode, Map.class);
|
||||
}
|
||||
|
||||
String operationName = null;
|
||||
JsonNode opNode = root.get("operationName");
|
||||
if (opNode != null && !opNode.isNull()) {
|
||||
if (!opNode.isTextual()) {
|
||||
throw new AppSyncTransportException(400, "MalformedHttpRequestException",
|
||||
AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE);
|
||||
}
|
||||
operationName = opNode.asText();
|
||||
}
|
||||
|
||||
return new ParsedRequest(query, variables, operationName);
|
||||
}
|
||||
|
||||
private Response graphqlError(int status, String errorType, String message) {
|
||||
return Response.status(status)
|
||||
.header(HEADER_ERROR_TYPE, errorType)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(errorFormatter.transportError(errorType, message))
|
||||
.build();
|
||||
}
|
||||
|
||||
private record ParsedRequest(String query, Map<String, Object> variables, String operationName) {}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package io.github.hectorvent.floci.services.appsync.graphql;
|
||||
|
||||
/**
|
||||
* Transport-layer AppSync GraphQL HTTP error that must be returned as
|
||||
* GraphQL {@code errors[]} body (not management {@code __type} via AwsExceptionMapper).
|
||||
*/
|
||||
public class AppSyncTransportException extends RuntimeException {
|
||||
|
||||
private final int httpStatus;
|
||||
private final String errorType;
|
||||
|
||||
public AppSyncTransportException(int httpStatus, String errorType, String message) {
|
||||
super(message);
|
||||
this.httpStatus = httpStatus;
|
||||
this.errorType = errorType;
|
||||
}
|
||||
|
||||
public int getHttpStatus() {
|
||||
return httpStatus;
|
||||
}
|
||||
|
||||
public String getErrorType() {
|
||||
return errorType;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package io.github.hectorvent.floci.services.appsync.graphql;
|
||||
|
||||
import graphql.ErrorType;
|
||||
import graphql.ExecutionInput;
|
||||
import graphql.ExecutionResult;
|
||||
import graphql.ExecutionResultImpl;
|
||||
import graphql.GraphQL;
|
||||
import graphql.GraphqlErrorBuilder;
|
||||
import graphql.language.Document;
|
||||
import graphql.language.OperationDefinition;
|
||||
import graphql.parser.InvalidSyntaxException;
|
||||
import graphql.parser.Parser;
|
||||
import graphql.schema.GraphQLSchema;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ApplicationScoped
|
||||
public class QueryExecutor {
|
||||
|
||||
private final AppSyncErrorFormatter formatter;
|
||||
|
||||
@Inject
|
||||
public QueryExecutor(AppSyncErrorFormatter formatter) {
|
||||
this.formatter = formatter;
|
||||
}
|
||||
|
||||
public Map<String, Object> execute(GraphQLSchema schema, String query,
|
||||
Map<String, Object> variables, String operationName) {
|
||||
return execute(SchemaRegistry.buildGraphQL(schema), query, variables, operationName);
|
||||
}
|
||||
|
||||
public Map<String, Object> execute(GraphQL graphQL, String query,
|
||||
Map<String, Object> variables, String operationName) {
|
||||
List<OperationDefinition> operations = parseOperations(query);
|
||||
if (operations.size() > 1 && (operationName == null || operationName.isBlank())) {
|
||||
throw new AppSyncTransportException(400, "BadRequestException",
|
||||
AppSyncErrorFormatter.MSG_MISSING_OPERATION_NAME);
|
||||
}
|
||||
|
||||
OperationDefinition selected = selectOperation(operations, operationName);
|
||||
if (selected != null && selected.getOperation() == OperationDefinition.Operation.SUBSCRIPTION) {
|
||||
ExecutionResult rejected = ExecutionResultImpl.newExecutionResult()
|
||||
.addError(GraphqlErrorBuilder.newError()
|
||||
.message("Subscriptions are not supported over HTTP")
|
||||
.errorType(ErrorType.OperationNotSupported)
|
||||
.build())
|
||||
.build();
|
||||
return formatter.format(rejected);
|
||||
}
|
||||
|
||||
ExecutionInput.Builder inputBuilder = ExecutionInput.newExecutionInput().query(query);
|
||||
if (variables != null) {
|
||||
inputBuilder.variables(variables);
|
||||
}
|
||||
if (operationName != null && !operationName.isBlank()) {
|
||||
inputBuilder.operationName(operationName);
|
||||
}
|
||||
|
||||
ExecutionResult result = graphQL.execute(inputBuilder.build());
|
||||
return formatter.format(result);
|
||||
}
|
||||
|
||||
private List<OperationDefinition> parseOperations(String query) {
|
||||
try {
|
||||
Document document = Parser.parse(query);
|
||||
List<OperationDefinition> ops = new ArrayList<>();
|
||||
for (var definition : document.getDefinitions()) {
|
||||
if (definition instanceof OperationDefinition operationDefinition) {
|
||||
ops.add(operationDefinition);
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
} catch (InvalidSyntaxException e) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private OperationDefinition selectOperation(List<OperationDefinition> operations, String operationName) {
|
||||
if (operations.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (operationName == null || operationName.isBlank()) {
|
||||
return operations.get(0);
|
||||
}
|
||||
for (OperationDefinition op : operations) {
|
||||
if (operationName.equals(op.getName())) {
|
||||
return op;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+32
-5
@@ -5,7 +5,6 @@ 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;
|
||||
@@ -15,7 +14,6 @@ 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;
|
||||
@@ -33,7 +31,7 @@ public class SchemaCreationWorker {
|
||||
|
||||
private final SchemaRegistry schemaRegistry;
|
||||
private final AccountAwareStorageBackend<SchemaCreationStatus> schemaStatusStore;
|
||||
private final StorageBackend<String, String> schemaStore;
|
||||
private final AccountAwareStorageBackend<String> schemaStore;
|
||||
private final EmulatorConfig config;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@@ -42,7 +40,7 @@ public class SchemaCreationWorker {
|
||||
@Inject
|
||||
public SchemaCreationWorker(SchemaRegistry schemaRegistry,
|
||||
AccountAwareStorageBackend<SchemaCreationStatus> schemaStatusStore,
|
||||
StorageBackend<String, String> schemaStore,
|
||||
AccountAwareStorageBackend<String> schemaStore,
|
||||
EmulatorConfig config,
|
||||
ObjectMapper objectMapper) {
|
||||
this.schemaRegistry = schemaRegistry;
|
||||
@@ -88,7 +86,8 @@ public class SchemaCreationWorker {
|
||||
private void process(String apiId, String sdl, String accountId) {
|
||||
try {
|
||||
schemaRegistry.register(apiId, sdl);
|
||||
schemaStore.put(apiId, sdl);
|
||||
// Worker thread has no request context; write under the submitting account.
|
||||
schemaStore.putForAccount(accountId, apiId, sdl);
|
||||
markStatus(accountId, apiId, SchemaCreationStatusType.SUCCESS, null);
|
||||
LOG.infov("Schema creation completed for API {0}", apiId);
|
||||
} catch (AwsException e) {
|
||||
@@ -149,4 +148,32 @@ public class SchemaCreationWorker {
|
||||
LOG.infov("Recovered {0} orphan schema creation(s) on startup", recovered);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rehydrates executable schemas from persisted SDL into {@link SchemaRegistry}
|
||||
* after storage load / orphan recovery so GraphQL execute works across restarts.
|
||||
* Scans every account (startup has no request context); apiIds are globally unique.
|
||||
* Parse failures are logged and skipped.
|
||||
*/
|
||||
public void rehydrateSchemas() {
|
||||
int loaded = 0;
|
||||
int skipped = 0;
|
||||
for (Map.Entry<String, String> entry : schemaStore.scanAllAccountsAsMap().entrySet()) {
|
||||
String apiId = entry.getKey();
|
||||
String sdl = entry.getValue();
|
||||
if (sdl == null || sdl.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
schemaRegistry.register(apiId, sdl);
|
||||
loaded++;
|
||||
} catch (RuntimeException e) {
|
||||
skipped++;
|
||||
LOG.warnv(e, "Skipping rehydrate of schema for API {0}: {1}", apiId, e.getMessage());
|
||||
}
|
||||
}
|
||||
if (loaded > 0 || skipped > 0) {
|
||||
LOG.infov("Rehydrated {0} schema(s) into registry ({1} skipped)", loaded, skipped);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.appsync.graphql;
|
||||
|
||||
import graphql.GraphQL;
|
||||
import graphql.execution.AsyncExecutionStrategy;
|
||||
import graphql.execution.AsyncSerialExecutionStrategy;
|
||||
import graphql.execution.SubscriptionExecutionStrategy;
|
||||
import graphql.schema.GraphQLSchema;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -11,6 +15,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
@ApplicationScoped
|
||||
public class SchemaRegistry {
|
||||
private final Map<String, GraphQLSchema> schemas = new ConcurrentHashMap<>();
|
||||
private final Map<String, GraphQL> engines = new ConcurrentHashMap<>();
|
||||
private final AppSyncSchemaParser appSyncSchemaParser;
|
||||
|
||||
@Inject
|
||||
@@ -21,13 +26,27 @@ public class SchemaRegistry {
|
||||
public void register(String apiId, String sdl) {
|
||||
GraphQLSchema schema = appSyncSchemaParser.parse(sdl);
|
||||
schemas.put(apiId, schema);
|
||||
engines.put(apiId, buildGraphQL(schema));
|
||||
}
|
||||
|
||||
public Optional<GraphQLSchema> getSchema(String apiId) {
|
||||
return Optional.ofNullable(schemas.get(apiId));
|
||||
}
|
||||
|
||||
public Optional<GraphQL> getGraphQL(String apiId) {
|
||||
return Optional.ofNullable(engines.get(apiId));
|
||||
}
|
||||
|
||||
public void remove(String apiId) {
|
||||
schemas.remove(apiId);
|
||||
engines.remove(apiId);
|
||||
}
|
||||
|
||||
static GraphQL buildGraphQL(GraphQLSchema schema) {
|
||||
return GraphQL.newGraphQL(schema)
|
||||
.queryExecutionStrategy(new AsyncExecutionStrategy())
|
||||
.mutationExecutionStrategy(new AsyncSerialExecutionStrategy())
|
||||
.subscriptionExecutionStrategy(new SubscriptionExecutionStrategy())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -24,7 +24,7 @@ public class SchemaStatusStoreProducer {
|
||||
|
||||
@Inject
|
||||
public SchemaStatusStoreProducer(StorageFactory storageFactory) {
|
||||
this.store = (AccountAwareStorageBackend<SchemaCreationStatus>) storageFactory.create("appsync", "appsync-schema-status.json",
|
||||
this.store = storageFactory.create("appsync", "appsync-schema-status.json",
|
||||
new TypeReference<Map<String, SchemaCreationStatus>>() {});
|
||||
}
|
||||
|
||||
|
||||
+5
-5
@@ -1,7 +1,7 @@
|
||||
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.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Produces;
|
||||
@@ -10,14 +10,14 @@ import jakarta.inject.Inject;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Produces the shared {@link StorageBackend} used to store compiled SDL schemas.
|
||||
* Produces the shared {@link AccountAwareStorageBackend} used to store compiled SDL schemas.
|
||||
* Shared between {@code AppSyncService} (reads via getIntrospectionSchema) and
|
||||
* {@code SchemaCreationWorker} (writes on successful compilation).
|
||||
* {@code SchemaCreationWorker} (writes on successful compilation / rehydrates on boot).
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SchemaStoreProducer {
|
||||
|
||||
private final StorageBackend<String, String> store;
|
||||
private final AccountAwareStorageBackend<String> store;
|
||||
|
||||
@Inject
|
||||
public SchemaStoreProducer(StorageFactory storageFactory) {
|
||||
@@ -27,7 +27,7 @@ public class SchemaStoreProducer {
|
||||
|
||||
@Produces
|
||||
@ApplicationScoped
|
||||
public StorageBackend<String, String> produce() {
|
||||
public AccountAwareStorageBackend<String> produce() {
|
||||
return store;
|
||||
}
|
||||
}
|
||||
+4
-9
@@ -9,7 +9,6 @@ import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
|
||||
import io.quarkus.arc.Arc;
|
||||
import io.quarkus.arc.ManagedContext;
|
||||
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.cloudformation.model.ChangeSet;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
|
||||
@@ -80,14 +79,10 @@ public class CloudFormationService {
|
||||
this.samTransformProcessor = new SamTransformProcessor(objectMapper);
|
||||
this.clock = clock;
|
||||
this.storageAccount = config.defaultAccountId();
|
||||
this.stackBackend = asAccountAware(storageFactory.create(
|
||||
"cloudformation", "cloudformation-stacks.json", new TypeReference<Map<String, Stack>>() {}));
|
||||
this.exportBackend = asAccountAware(storageFactory.create(
|
||||
"cloudformation", "cloudformation-exports.json", new TypeReference<Map<String, String>>() {}));
|
||||
}
|
||||
|
||||
private static <V> AccountAwareStorageBackend<V> asAccountAware(StorageBackend<String, V> backend) {
|
||||
return (AccountAwareStorageBackend<V>) backend;
|
||||
this.stackBackend = storageFactory.create(
|
||||
"cloudformation", "cloudformation-stacks.json", new TypeReference<Map<String, Stack>>() {});
|
||||
this.exportBackend = storageFactory.create(
|
||||
"cloudformation", "cloudformation-exports.json", new TypeReference<Map<String, String>>() {});
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
|
||||
+3
-3
@@ -70,11 +70,11 @@ public class CodePipelineService {
|
||||
public CodePipelineService(StorageFactory storageFactory, ObjectMapper mapper,
|
||||
CodeBuildService codeBuildService, CodeDeployService codeDeployService,
|
||||
LambdaService lambdaService, S3Service s3Service) {
|
||||
this.pipelineStore = (AccountAwareStorageBackend<CodePipelinePipeline>) storageFactory.create(
|
||||
this.pipelineStore = storageFactory.create(
|
||||
"codepipeline", "codepipeline-pipelines.json", new TypeReference<Map<String, CodePipelinePipeline>>() {});
|
||||
this.executionStore = (AccountAwareStorageBackend<CodePipelineExecution>) storageFactory.create(
|
||||
this.executionStore = storageFactory.create(
|
||||
"codepipeline", "codepipeline-executions.json", new TypeReference<Map<String, CodePipelineExecution>>() {});
|
||||
this.itemStore = (AccountAwareStorageBackend<CodePipelineStoredItem>) storageFactory.create(
|
||||
this.itemStore = storageFactory.create(
|
||||
"codepipeline", "codepipeline-items.json", new TypeReference<Map<String, CodePipelineStoredItem>>() {});
|
||||
this.mapper = mapper;
|
||||
this.codeBuildService = codeBuildService;
|
||||
|
||||
Reference in new issue
Block a user