diff --git a/docs/services/appsync.md b/docs/services/appsync.md index 73e445088a..3011737207 100644 --- a/docs/services/appsync.md +++ b/docs/services/appsync.md @@ -133,7 +133,9 @@ Floci implements the AWS AppSync Management API, providing local emulation of Gr ## Schema Registry -`StartSchemaCreation` validates the provided GraphQL SDL using [graphql-java](https://github.com/graphql-java/graphql-java). Invalid schemas are rejected with a `BadRequestException` (400) at registration time, preventing them from being caught later during query execution. +`StartSchemaCreation` validates the provided GraphQL SDL using [graphql-java](https://github.com/graphql-java/graphql-java). Invalid schemas are rejected asynchronously (status `FAILED` with details after `PROCESSING`). Valid schemas are registered in an in-memory `SchemaRegistry` and persisted to the schema store. + +On emulator startup, after storage load and orphan recovery, Floci **rehydrates** SUCCESS SDLs from the schema store into `SchemaRegistry` so `POST /v1/apis/{apiId}/graphql` works across restarts (memory/persistent/hybrid/wal). The following **AWS scalar types** are pre-registered and available in any schema without requiring explicit `scalar` declarations: @@ -174,6 +176,30 @@ Unknown directives are rejected during schema registration. Schema extensions (`extend type Query { ... }`) are supported natively through graphql-java. +## GraphQL execute (data-plane) + +| Surface | Path | Content-Types | +|---|---|---| +| HTTP GraphQL | `POST /v1/apis/{apiId}/graphql` | `application/json`, `application/graphql` (+ charset) | + +Execute is a **separate** data-plane endpoint from the management API. Request body is GraphQL-over-HTTP JSON: `{ "query", "variables?", "operationName?" }`. + +Responses are `application/json` with AWS AppSync wire shapes (`data` / `errors[]` with top-level `errorType` / `errorInfo`). Most GraphQL syntax and validation errors return **HTTP 200** with `errors[]`. + +| Case | HTTP | Notes | +|---|---|---| +| Query / introspection / validation / syntax (incl. blank `query`) | 200 | Nullable fields may be `null` until DataFetchers (Phase 8) | +| HTTP subscription operation | 200 | `OperationNotSupported` (realtime WebSocket is a later phase) | +| Empty body / `{}` / `[]` / unparseable JSON / bad Content-Type | 400 | `MalformedHttpRequestException` | +| Missing `operationName` with multiple operations | 400 | `BadRequestException` — `Missing operation name.` | +| Unknown `apiId` | 404 | `NotFoundException` | +| API exists but no executable schema (incl. PROCESSING) | **502** | `GraphQLSchemaException` — `No schema definition exists.` + `x-amzn-errortype` | +| Unexpected failure | 500 | `InternalFailure` | + +**Evidence for data-plane statuses** (empty/`[]`/`{}` → 400; missing schema → 502): AppSync team sample in [graphql/graphql-over-http#81](https://github.com/graphql/graphql-over-http/issues/81) (@robzhu). The management API Reference lists `GraphQLSchemaException` as HTTP 400 for “schema not valid” on management operations — a different surface than the GraphQL execute data plane. + +Auth on the execute endpoint, DataFetcher/resolver dispatch, data-source adapters, guardrails, and WebSocket subscriptions are later phases. + ## Pagination All `List` operations support cursor-based pagination via query parameters: @@ -215,15 +241,14 @@ This matches AWS behavior where deleting an API removes its entire configuration ## Not Implemented -These AWS AppSync operations are not yet implemented and are tracked in future phases: +These AWS AppSync capabilities are not yet implemented and are tracked in future phases: -- **Execution engine** (Phase 5): GraphQL query execution, resolver dispatch, VTL template evaluation -- **Data source adapters** (Phase 7): DynamoDB, Lambda, HTTP, EventBridge, OpenSearch, RDS connectors -- **Pipeline resolvers** (Phase 8): Function chaining with `$prev` and `$stash` -- **Subscriptions** (Phase 9): WebSocket real-time subscriptions -- **Caching** (Phase 10): API-level and per-resolver caching -- **Authentication** (Phase 4): API key validation on the GraphQL endpoint -- **Introspection** (Phase 6): `__schema` and `__type` queries +- **Authentication on execute** (Phase 7): API key / IAM / Cognito validation on the GraphQL endpoint +- **DataFetcher / resolver dispatch** (Phase 8): resolver mapping templates and field resolution with non-null values +- **Data source adapters** (Phase 9): DynamoDB, Lambda, HTTP, EventBridge, OpenSearch, RDS connectors +- **Guardrails** (Phase 10): query depth / complexity limits and related errors +- **Realtime subscriptions** (Phase 11+): WebSocket real-time subscriptions +- **Caching**: API-level and per-resolver caching - **Merged API source management**: `AssociateMergedGraphqlApi`, `AssociateSourceGraphqlApi`, `StartSchemaMerge`, `ListTypesByAssociation` - **Data source introspection**: `StartDataSourceIntrospection`, `GetDataSourceIntrospection` @@ -287,6 +312,11 @@ aws appsync associate-api \ --api-id API_ID \ --endpoint-url $AWS_ENDPOINT_URL +# Execute a GraphQL query (data-plane; null fields OK until resolvers) +curl -s -X POST "$AWS_ENDPOINT_URL/v1/apis/API_ID/graphql" \ + -H "Content-Type: application/json" \ + -d '{"query":"{ hello }"}' + # Create a channel namespace aws appsync create-channel-namespace \ --api-id API_ID \ diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java index 56e0515e8c..7aa1f4a33c 100644 --- a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java +++ b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java @@ -42,6 +42,14 @@ public class AccountAwareStorageBackend implements StorageBackend 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 AccountAwareStorageBackend inMemory(String defaultAccountId) { + return new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, defaultAccountId); + } + @Override public void put(String key, V value) { delegate.put(prefixed(key), value); diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java b/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java index 0f9e4fb742..fb7ca5405b 100644 --- a/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java +++ b/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java @@ -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 StorageBackend create(String serviceName, String fileName, + public synchronized AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> 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 typed = (StorageBackend) existing; + AccountAwareStorageBackend typed = (AccountAwareStorageBackend) existing; return typed; } diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java index 5580dc0b26..0e3c1d6211 100644 --- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java @@ -175,6 +175,7 @@ public class EmulatorLifecycle { serviceRegistry.logEnabledServices(); storageFactory.loadAll(); schemaCreationWorker.recoverOrphans(); + schemaCreationWorker.rehydrateSchemas(); sqsPoller.startPersistedPollers(); kinesisPoller.startPersistedPollers(); diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java index 9defcc4570..57cdfa19b1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java @@ -25,7 +25,7 @@ public class AppSyncService { private static final Logger LOG = Logger.getLogger(AppSyncService.class); private final StorageBackend apiStore; - private final StorageBackend schemaStore; + private final AccountAwareStorageBackend schemaStore; private final AccountAwareStorageBackend schemaStatusStore; private final StorageBackend dataSourceStore; private final StorageBackend resolverStore; @@ -47,7 +47,7 @@ public class AppSyncService { SchemaRegistry schemaRegistry, SchemaCreationWorker schemaCreationWorker, Instance requestContextInstance, ObjectMapper objectMapper, AccountAwareStorageBackend schemaStatusStore, - StorageBackend schemaStore) { + AccountAwareStorageBackend schemaStore) { this.apiStore = storageFactory.create("appsync", "appsync-apis.json", new TypeReference<>() {}); this.schemaStore = schemaStore; this.schemaStatusStore = schemaStatusStore; diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatter.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatter.java new file mode 100644 index 0000000000..790a024a78 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatter.java @@ -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 AppSync DG {@code $util.error} ({@code errorType}/{@code errorInfo}) + * @see AppSync HTTP behavior (AppSync team / @robzhu) + */ +@ApplicationScoped +public class AppSyncErrorFormatter { + + /** + * Messages from AppSync team sample: + * graphql-over-http#81 + */ + 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 format(ExecutionResult result) { + Map response = new LinkedHashMap<>(); + if (result.isDataPresent()) { + response.put("data", result.getData()); + } + List errors = result.getErrors(); + if (errors != null && !errors.isEmpty()) { + List> formatted = new ArrayList<>(errors.size()); + for (GraphQLError error : errors) { + formatted.add(formatError(error)); + } + response.put("errors", formatted); + } + return response; + } + + public Map transportError(String errorType, String message) { + Map error = new LinkedHashMap<>(); + error.put("errorType", errorType); + error.put("message", message); + Map response = new LinkedHashMap<>(); + response.put("errors", List.of(error)); + return response; + } + + private Map formatError(GraphQLError error) { + Map map = new LinkedHashMap<>(); + map.put("message", error.getMessage()); + List locations = error.getLocations(); + if (locations != null && !locations.isEmpty()) { + List> locationMaps = new ArrayList<>(locations.size()); + for (SourceLocation location : locations) { + Map loc = new LinkedHashMap<>(); + loc.put("line", location.getLine()); + loc.put("column", location.getColumn()); + locationMaps.add(loc); + } + map.put("locations", locationMaps); + } + List 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(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java new file mode 100644 index 0000000000..90d113a674 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java @@ -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 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 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 variables, String operationName) {} +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncTransportException.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncTransportException.java new file mode 100644 index 0000000000..0dceda82d4 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncTransportException.java @@ -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; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/QueryExecutor.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/QueryExecutor.java new file mode 100644 index 0000000000..67b82fa8e4 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/QueryExecutor.java @@ -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 execute(GraphQLSchema schema, String query, + Map variables, String operationName) { + return execute(SchemaRegistry.buildGraphQL(schema), query, variables, operationName); + } + + public Map execute(GraphQL graphQL, String query, + Map variables, String operationName) { + List 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 parseOperations(String query) { + try { + Document document = Parser.parse(query); + List 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 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; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorker.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorker.java index d65bdbdb71..34c480a833 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorker.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorker.java @@ -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 schemaStatusStore; - private final StorageBackend schemaStore; + private final AccountAwareStorageBackend schemaStore; private final EmulatorConfig config; private final ObjectMapper objectMapper; @@ -42,7 +40,7 @@ public class SchemaCreationWorker { @Inject public SchemaCreationWorker(SchemaRegistry schemaRegistry, AccountAwareStorageBackend schemaStatusStore, - StorageBackend schemaStore, + AccountAwareStorageBackend 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 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); + } + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistry.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistry.java index 4574e1b2a2..dc6763f93b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistry.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistry.java @@ -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 schemas = new ConcurrentHashMap<>(); + private final Map 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 getSchema(String apiId) { return Optional.ofNullable(schemas.get(apiId)); } + public Optional 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(); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStatusStoreProducer.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStatusStoreProducer.java index 149f41e87d..aade3f675d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStatusStoreProducer.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStatusStoreProducer.java @@ -24,7 +24,7 @@ public class SchemaStatusStoreProducer { @Inject public SchemaStatusStoreProducer(StorageFactory storageFactory) { - this.store = (AccountAwareStorageBackend) storageFactory.create("appsync", "appsync-schema-status.json", + this.store = storageFactory.create("appsync", "appsync-schema-status.json", new TypeReference>() {}); } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStoreProducer.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStoreProducer.java index 4f863a50fd..00b049a329 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStoreProducer.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaStoreProducer.java @@ -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 store; + private final AccountAwareStorageBackend store; @Inject public SchemaStoreProducer(StorageFactory storageFactory) { @@ -27,7 +27,7 @@ public class SchemaStoreProducer { @Produces @ApplicationScoped - public StorageBackend produce() { + public AccountAwareStorageBackend produce() { return store; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index 776bf4cd1e..b74aed46f9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -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>() {})); - this.exportBackend = asAccountAware(storageFactory.create( - "cloudformation", "cloudformation-exports.json", new TypeReference>() {})); - } - - private static AccountAwareStorageBackend asAccountAware(StorageBackend backend) { - return (AccountAwareStorageBackend) backend; + this.stackBackend = storageFactory.create( + "cloudformation", "cloudformation-stacks.json", new TypeReference>() {}); + this.exportBackend = storageFactory.create( + "cloudformation", "cloudformation-exports.json", new TypeReference>() {}); } @PostConstruct diff --git a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java index a238bd5860..bce62efef2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java +++ b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java @@ -70,11 +70,11 @@ public class CodePipelineService { public CodePipelineService(StorageFactory storageFactory, ObjectMapper mapper, CodeBuildService codeBuildService, CodeDeployService codeDeployService, LambdaService lambdaService, S3Service s3Service) { - this.pipelineStore = (AccountAwareStorageBackend) storageFactory.create( + this.pipelineStore = storageFactory.create( "codepipeline", "codepipeline-pipelines.json", new TypeReference>() {}); - this.executionStore = (AccountAwareStorageBackend) storageFactory.create( + this.executionStore = storageFactory.create( "codepipeline", "codepipeline-executions.json", new TypeReference>() {}); - this.itemStore = (AccountAwareStorageBackend) storageFactory.create( + this.itemStore = storageFactory.create( "codepipeline", "codepipeline-items.json", new TypeReference>() {}); this.mapper = mapper; this.codeBuildService = codeBuildService; diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index b5c23bf726..7d80e25013 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -56,6 +56,7 @@ quarkus: - --initialize-at-run-time=io.github.hectorvent.floci.services.cloudfront.CloudFrontService - --initialize-at-run-time=io.github.hectorvent.floci.services.emr.EmrService - --initialize-at-run-time=io.github.hectorvent.floci.services.elasticbeanstalk.ElasticBeanstalkService + - --initialize-at-run-time=graphql.util.IdGenerator floci: diff --git a/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java b/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java index 36aaa76eba..3c87f8c755 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.eks.EksOidcService; import com.fasterxml.jackson.core.type.TypeReference; @@ -38,9 +39,9 @@ class WebIdentityTokenVerifierTest { verifier = new WebIdentityTokenVerifier(objectMapper); oidcService = new EksOidcService(new StorageFactory(null, null) { @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } }, objectMapper); oidcService.ensureKey(CLUSTER, ISSUER); diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java index 6386460862..55d28a9d51 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java @@ -164,6 +164,21 @@ class EmulatorLifecycleTest { Mockito.verify(elbV2Service, Mockito.never()).restorePersistedRuntime(); } + @Test + @DisplayName("Should rehydrate AppSync schemas after orphan recovery on startup") + void shouldRehydrateAppSyncSchemasAfterOrphanRecovery() { + stubStorageConfig(); + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + var inOrder = Mockito.inOrder(storageFactory, schemaCreationWorker); + inOrder.verify(storageFactory).loadAll(); + inOrder.verify(schemaCreationWorker).recoverOrphans(); + inOrder.verify(schemaCreationWorker).rehydrateSchemas(); + } + @Test @DisplayName("Should validate the persistent path after BOOT hooks and before loading storage") void shouldValidatePersistentPathBeforeStorageLoad() { diff --git a/src/test/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqServiceTest.java index 0c7efff3e2..24eb87b664 100644 --- a/src/test/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqServiceTest.java @@ -4,6 +4,7 @@ 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.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.amazonmq.container.RabbitMqManager; import io.github.hectorvent.floci.services.amazonmq.model.Broker; @@ -26,7 +27,7 @@ class AmazonMqServiceTest { void setUp() { StorageFactory storageFactory = Mockito.mock(StorageFactory.class); when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenReturn(new InMemoryStorage<>()); + .thenReturn(AccountAwareStorageBackend.inMemory("000000000000")); EmulatorConfig config = Mockito.mock(EmulatorConfig.class); var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class); @@ -173,7 +174,7 @@ class AmazonMqServiceTest { private AmazonMqService realModeServiceWithFailingManager() { StorageFactory storageFactory = Mockito.mock(StorageFactory.class); when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenReturn(new InMemoryStorage<>()); + .thenReturn(AccountAwareStorageBackend.inMemory("000000000000")); EmulatorConfig config = Mockito.mock(EmulatorConfig.class); var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncExecutionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncExecutionIntegrationTest.java new file mode 100644 index 0000000000..122742082c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncExecutionIntegrationTest.java @@ -0,0 +1,371 @@ +package io.github.hectorvent.floci.services.appsync; + +import io.github.hectorvent.floci.services.appsync.graphql.AppSyncErrorFormatter; +import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class AppSyncExecutionIntegrationTest { + + private static final String AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/appsync/aws4_request"; + + @Inject + SchemaRegistry schemaRegistry; + + private String apiId; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void createApiWithSchema() { + apiId = createApi("exec-" + UUID.randomUUID().toString().substring(0, 8)); + startSchema(apiId, "type Query { hello: String }"); + awaitSchemaSuccess(apiId); + } + + @Test + void dualContentTypeJsonReturnsNullHello() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"query\":\"{ hello }\"}") + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(200) + .contentType(containsString("application/json")) + .body("data.hello", nullValue()) + .body("errors", nullValue()); + } + + @Test + void dualContentTypeGraphqlReturnsNullHello() { + given() + .header("Authorization", AUTH) + .contentType("application/graphql") + .body("{\"query\":\"{ hello }\"}") + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(200) + .body("data.hello", nullValue()); + } + + @Test + void missingContentTypeReturns400GraphqlErrors() { + given() + .header("Authorization", AUTH) + .body("{\"query\":\"{ hello }\"}") + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(400) + .body("errors[0].errorType", equalTo("MalformedHttpRequestException")) + .body("__type", nullValue()); + } + + @Test + void unsupportedContentTypeReturns400GraphqlErrors() { + given() + .header("Authorization", AUTH) + .contentType("text/plain") + .body("{\"query\":\"{ hello }\"}") + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(400) + .body("errors[0].errorType", equalTo("MalformedHttpRequestException")) + .body("__type", nullValue()); + } + + @Test + void emptyBodyReturns400MalformedWithEmptyMessage() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("") + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(400) + .header("x-amzn-errortype", containsString("MalformedHttpRequestException")) + .body("errors[0].errorType", equalTo("MalformedHttpRequestException")) + .body("errors[0].message", equalTo(AppSyncErrorFormatter.MSG_EMPTY_BODY)); + } + + @Test + void emptyObjectBodyReturns400UnableToParse() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{}") + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(400) + .body("errors[0].errorType", equalTo("MalformedHttpRequestException")) + .body("errors[0].message", equalTo(AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE)); + } + + @Test + void arrayBodyReturns400UnableToParse() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("[{\"query\":\"{ hello }\"}]") + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(400) + .body("errors[0].errorType", equalTo("MalformedHttpRequestException")) + .body("errors[0].message", equalTo(AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE)); + } + + @Test + void unparseableBodyReturns400UnableToParse() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("meow") + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(400) + .body("errors[0].errorType", equalTo("MalformedHttpRequestException")) + .body("errors[0].message", equalTo(AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE)); + } + + @Test + void unknownApiIdReturns404() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"query\":\"{ hello }\"}") + .when() + .post("/v1/apis/does-not-exist-xyz/graphql") + .then() + .statusCode(404) + .header("x-amzn-errortype", containsString("NotFoundException")); + } + + @Test + void apiWithoutSchemaReturns502GraphQLSchemaException() { + String bareApiId = createApi("bare-" + UUID.randomUUID().toString().substring(0, 8)); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"query\":\"{ hello }\"}") + .when() + .post("/v1/apis/" + bareApiId + "/graphql") + .then() + .statusCode(502) + .header("x-amzn-errortype", containsString("GraphQLSchemaException")) + .body("errors[0].errorType", equalTo("GraphQLSchemaException")) + .body("errors[0].message", equalTo(AppSyncErrorFormatter.MSG_NO_SCHEMA)); + } + + @Test + void validationErrorReturns200WithTopLevelErrorType() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"query\":\"{ nope }\"}") + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(200) + .body("errors[0].errorType", equalTo("ValidationError")) + .body("errors[0].extensions", nullValue()); + } + + @Test + void syntaxErrorReturns200WithSyntaxError() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"query\":\"{ hello\"}") + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(200) + .body("errors[0].errorType", equalTo("SyntaxError")); + } + + @Test + void introspectionReturnsNonEmptyTypes() { + Map body = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"query\":\"{ __schema { types { name } } }\"}") + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(200) + .extract().jsonPath().getMap(""); + + @SuppressWarnings("unchecked") + Map data = (Map) body.get("data"); + @SuppressWarnings("unchecked") + Map schema = (Map) data.get("__schema"); + @SuppressWarnings("unchecked") + List types = (List) schema.get("types"); + assertThat(types, hasSize(greaterThan(0))); + } + + @Test + void variablesAndOperationNameExecuteSelectedOp() { + String multiApi = createApi("multi-" + UUID.randomUUID().toString().substring(0, 8)); + startSchema(multiApi, "type Query { hello(id: String): String }"); + awaitSchemaSuccess(multiApi); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "query": "query GetHello($id: String) { hello(id: $id) } query Other { hello }", + "variables": {"id": "x"}, + "operationName": "GetHello" + } + """) + .when() + .post("/v1/apis/" + multiApi + "/graphql") + .then() + .statusCode(200) + .body("data.hello", nullValue()); + } + + @Test + void httpSubscriptionReturns200OperationNotSupported() { + String subApi = createApi("sub-" + UUID.randomUUID().toString().substring(0, 8)); + startSchema(subApi, """ + type Query { hello: String } + type Subscription { onHello: String } + """); + awaitSchemaSuccess(subApi); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"query\":\"subscription { onHello }\"}") + .when() + .post("/v1/apis/" + subApi + "/graphql") + .then() + .statusCode(200) + .body("errors[0].errorType", equalTo("OperationNotSupported")); + } + + @Test + void whitespaceOnlyQueryReturns200SyntaxError() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"query\":\" \"}") + .when() + .post("/v1/apis/" + apiId + "/graphql") + .then() + .statusCode(200) + .body("errors[0].errorType", equalTo("SyntaxError")); + } + + @Test + void rehydrateFromSchemaStoreEnablesExecute() { + String hydrateApi = createApi("hydrate-" + UUID.randomUUID().toString().substring(0, 8)); + startSchema(hydrateApi, "type Query { hello: String }"); + awaitSchemaSuccess(hydrateApi); + + schemaRegistry.remove(hydrateApi); + assertTrue(schemaRegistry.getSchema(hydrateApi).isEmpty()); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"query\":\"{ hello }\"}") + .when() + .post("/v1/apis/" + hydrateApi + "/graphql") + .then() + .statusCode(502); + + // invoke rehydrate via worker (package-visible through CDI bean) + rehydrateWorker().rehydrateSchemas(); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"query\":\"{ hello }\"}") + .when() + .post("/v1/apis/" + hydrateApi + "/graphql") + .then() + .statusCode(200) + .body("data.hello", nullValue()); + } + + @Inject + io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker schemaCreationWorker; + + private io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker rehydrateWorker() { + return schemaCreationWorker; + } + + private static String createApi(String name) { + return given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"name": "%s", "authenticationType": "API_KEY"} + """.formatted(name)) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + } + + private static void startSchema(String apiId, String definition) { + String escaped = definition.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n"); + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"definition\": \"" + escaped + "\"}") + .when() + .post("/v1/apis/" + apiId + "/schemacreation") + .then() + .statusCode(200) + .body("status", equalTo("PROCESSING")); + } + + private static void awaitSchemaSuccess(String apiId) { + await().atMost(Duration.ofSeconds(10)) + .pollInterval(Duration.ofMillis(25)) + .until(() -> { + String status = given() + .header("Authorization", AUTH) + .when() + .get("/v1/apis/" + apiId + "/schemacreation") + .then() + .statusCode(200) + .extract().path("status"); + return "SUCCESS".equals(status); + }); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatterTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatterTest.java new file mode 100644 index 0000000000..26c9b349e1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncErrorFormatterTest.java @@ -0,0 +1,119 @@ +package io.github.hectorvent.floci.services.appsync.graphql; + +import graphql.ErrorType; +import graphql.ExecutionResult; +import graphql.ExecutionResultImpl; +import graphql.GraphQLError; +import graphql.GraphqlErrorBuilder; +import graphql.language.SourceLocation; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AppSyncErrorFormatterTest { + + private final AppSyncErrorFormatter formatter = new AppSyncErrorFormatter(); + + @Test + void invalidSyntaxMapsToTopLevelSyntaxError() { + GraphQLError syntaxError = GraphqlErrorBuilder.newError() + .message("Invalid syntax near '{'") + .errorType(ErrorType.InvalidSyntax) + .location(new SourceLocation(1, 1)) + .build(); + ExecutionResult result = ExecutionResultImpl.newExecutionResult() + .addError(syntaxError) + .build(); + + Map response = formatter.format(result); + + assertFalse(response.containsKey("data")); + @SuppressWarnings("unchecked") + List> errors = (List>) response.get("errors"); + assertEquals(1, errors.size()); + Map error = errors.get(0); + assertEquals("Invalid syntax near '{'", error.get("message")); + assertEquals("SyntaxError", error.get("errorType")); + assertTrue(error.containsKey("errorInfo")); + assertNull(error.get("errorInfo")); + assertFalse(error.containsKey("extensions")); + } + + @Test + void validationErrorUsesTopLevelErrorTypeNotExtensionsOnly() { + GraphQLError validationError = GraphqlErrorBuilder.newError() + .message("Validation error of type FieldUndefined: Field 'nope' is undefined") + .errorType(ErrorType.ValidationError) + .location(new SourceLocation(1, 3)) + .path(List.of("nope")) + .build(); + ExecutionResult result = ExecutionResultImpl.newExecutionResult() + .data(null) + .addError(validationError) + .build(); + + Map response = formatter.format(result); + + @SuppressWarnings("unchecked") + List> errors = (List>) response.get("errors"); + Map error = errors.get(0); + assertEquals("ValidationError", error.get("errorType")); + assertTrue(error.containsKey("errorInfo")); + assertNull(error.get("errorInfo")); + assertEquals(List.of("nope"), error.get("path")); + assertFalse(error.containsKey("extensions"), + "AppSync wire uses top-level errorType, not extensions-only classification"); + } + + @Test + void emptyBodyMessageMatchesAppSyncSample() { + Map response = formatter.transportError( + "MalformedHttpRequestException", + AppSyncErrorFormatter.MSG_EMPTY_BODY); + + @SuppressWarnings("unchecked") + List> errors = (List>) response.get("errors"); + assertEquals(1, errors.size()); + assertEquals("MalformedHttpRequestException", errors.get(0).get("errorType")); + assertEquals("Request body is empty.", errors.get(0).get("message")); + } + + @Test + void unparseableBodyMessageMatchesAppSyncSample() { + Map forBraces = formatter.transportError( + "MalformedHttpRequestException", + AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE); + Map forArray = formatter.transportError( + "MalformedHttpRequestException", + AppSyncErrorFormatter.MSG_UNABLE_TO_PARSE); + + assertEquals("Unable to parse GraphQL query.", + ((List) forBraces.get("errors")).isEmpty() ? null + : ((Map) ((List) forBraces.get("errors")).get(0)).get("message")); + assertEquals("Unable to parse GraphQL query.", + ((Map) ((List) forArray.get("errors")).get(0)).get("message")); + } + + @Test + void successfulDataIncludedWithoutErrors() { + Map data = new java.util.LinkedHashMap<>(); + data.put("hello", null); + ExecutionResult result = ExecutionResultImpl.newExecutionResult() + .data(data) + .build(); + + Map response = formatter.format(result); + + @SuppressWarnings("unchecked") + Map responseData = (Map) response.get("data"); + assertNull(responseData.get("hello")); + assertTrue(responseData.containsKey("hello")); + assertFalse(response.containsKey("errors")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java new file mode 100644 index 0000000000..fc274e6898 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java @@ -0,0 +1,121 @@ +package io.github.hectorvent.floci.services.appsync.graphql; + +import com.fasterxml.jackson.databind.ObjectMapper; +import graphql.GraphQL; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.appsync.AppSyncService; +import io.github.hectorvent.floci.services.appsync.model.GraphqlApi; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class AppSyncExecutionControllerTest { + + @Mock + AppSyncService appSyncService; + @Mock + SchemaRegistry schemaRegistry; + @Mock + QueryExecutor queryExecutor; + + private AppSyncExecutionController controller; + private HttpHeaders jsonHeaders; + + @BeforeEach + void setUp() { + controller = new AppSyncExecutionController( + appSyncService, + schemaRegistry, + queryExecutor, + new AppSyncErrorFormatter(), + new ObjectMapper()); + + jsonHeaders = mock(HttpHeaders.class); + when(jsonHeaders.getHeaderString(HttpHeaders.CONTENT_TYPE)).thenReturn("application/json"); + } + + @Test + void unexpectedExecutorFailureReturns500InternalFailure() { + when(appSyncService.getGraphqlApi("api-1")).thenReturn(new GraphqlApi()); + when(schemaRegistry.getGraphQL("api-1")).thenReturn(Optional.of(mock(GraphQL.class))); + when(queryExecutor.execute(any(GraphQL.class), eq("{ hello }"), isNull(), isNull())) + .thenThrow(new RuntimeException("boom")); + + Response response = controller.execute("api-1", jsonHeaders, "{\"query\":\"{ hello }\"}"); + + assertEquals(500, response.getStatus()); + assertEquals("InternalFailure", response.getHeaderString("x-amzn-errortype")); + @SuppressWarnings("unchecked") + Map body = (Map) response.getEntity(); + assertNotNull(body.get("errors")); + @SuppressWarnings("unchecked") + Map error = ((List>) body.get("errors")).get(0); + assertEquals("InternalFailure", error.get("errorType")); + assertEquals("InternalFailure", error.get("message")); + } + + @Test + void emptyBodyReturns400WithErrorTypeHeader() { + Response response = controller.execute("api-1", jsonHeaders, ""); + + assertEquals(400, response.getStatus()); + assertEquals("MalformedHttpRequestException", response.getHeaderString("x-amzn-errortype")); + @SuppressWarnings("unchecked") + Map body = (Map) response.getEntity(); + @SuppressWarnings("unchecked") + Map error = ((List>) body.get("errors")).get(0); + assertEquals("MalformedHttpRequestException", error.get("errorType")); + assertEquals(AppSyncErrorFormatter.MSG_EMPTY_BODY, error.get("message")); + } + + @Test + void unknownApiReturns404WithErrorTypeHeader() { + when(appSyncService.getGraphqlApi("missing")) + .thenThrow(new AwsException("NotFoundException", "API not found", 404)); + + Response response = controller.execute("missing", jsonHeaders, "{\"query\":\"{ hello }\"}"); + + assertEquals(404, response.getStatus()); + assertEquals("NotFoundException", response.getHeaderString("x-amzn-errortype")); + @SuppressWarnings("unchecked") + Map body = (Map) response.getEntity(); + @SuppressWarnings("unchecked") + Map error = ((List>) body.get("errors")).get(0); + assertEquals("NotFoundException", error.get("errorType")); + } + + @Test + void non404AwsExceptionFromLookupReturnsDataPlaneInternalFailure() { + when(appSyncService.getGraphqlApi("api-1")) + .thenThrow(new AwsException("BadRequestException", "unexpected management error", 400)); + + Response response = controller.execute("api-1", jsonHeaders, "{\"query\":\"{ hello }\"}"); + + assertEquals(500, response.getStatus()); + assertEquals("InternalFailure", response.getHeaderString("x-amzn-errortype")); + @SuppressWarnings("unchecked") + Map body = (Map) response.getEntity(); + assertNotNull(body.get("errors")); + @SuppressWarnings("unchecked") + Map error = ((List>) body.get("errors")).get(0); + assertEquals("InternalFailure", error.get("errorType")); + assertEquals("InternalFailure", error.get("message")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/QueryExecutorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/QueryExecutorTest.java new file mode 100644 index 0000000000..6ef487bf11 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/QueryExecutorTest.java @@ -0,0 +1,115 @@ +package io.github.hectorvent.floci.services.appsync.graphql; + +import graphql.schema.GraphQLSchema; +import io.github.hectorvent.floci.services.appsync.graphql.scalars.AppSyncScalarRegistry; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class QueryExecutorTest { + + private QueryExecutor executor; + private GraphQLSchema helloSchema; + private GraphQLSchema subscriptionSchema; + private GraphQLSchema multiOpSchema; + + @BeforeEach + void setUp() { + AppSyncErrorFormatter formatter = new AppSyncErrorFormatter(); + executor = new QueryExecutor(formatter); + AppSyncSchemaParser parser = new AppSyncSchemaParser(new AppSyncScalarRegistry()); + helloSchema = parser.parse("type Query { hello: String }"); + subscriptionSchema = parser.parse(""" + type Query { hello: String } + type Subscription { onHello: String } + """); + multiOpSchema = parser.parse(""" + type Query { + hello: String + bye: String + } + """); + } + + @Test + void nullableFieldReturnsNullWithoutDataFetcher() { + Map response = executor.execute(helloSchema, "{ hello }", null, null); + + @SuppressWarnings("unchecked") + Map data = (Map) response.get("data"); + assertTrue(data.containsKey("hello")); + assertNull(data.get("hello")); + assertTrue(!response.containsKey("errors") || ((List) response.get("errors")).isEmpty()); + } + + @Test + void usesAsyncStrategiesAndSupportsSimpleQuery() { + Map response = executor.execute(helloSchema, "query Q { hello }", Map.of(), "Q"); + + @SuppressWarnings("unchecked") + Map data = (Map) response.get("data"); + assertNull(data.get("hello")); + } + + @Test + void httpSubscriptionReturnsOperationNotSupported() { + Map response = executor.execute( + subscriptionSchema, + "subscription { onHello }", + null, + null); + + assertTrue(response.containsKey("errors")); + @SuppressWarnings("unchecked") + List> errors = (List>) response.get("errors"); + assertEquals(1, errors.size()); + assertEquals("OperationNotSupported", errors.get(0).get("errorType")); + Object data = response.get("data"); + if (data != null) { + assertTrue(!(data instanceof org.reactivestreams.Publisher), + "Must not return Publisher JSON for HTTP subscriptions"); + } + } + + @Test + void missingOperationNameWithMultipleOpsThrowsBadRequest() { + AppSyncTransportException ex = assertThrows(AppSyncTransportException.class, () -> + executor.execute(multiOpSchema, """ + query A { hello } + query B { bye } + """, null, null)); + + assertEquals(400, ex.getHttpStatus()); + assertEquals("BadRequestException", ex.getErrorType()); + assertEquals("Missing operation name.", ex.getMessage()); + } + + @Test + void operationNameSelectsAmongMultipleOps() { + Map response = executor.execute(multiOpSchema, """ + query A { hello } + query B { bye } + """, null, "B"); + + @SuppressWarnings("unchecked") + Map data = (Map) response.get("data"); + assertTrue(data.containsKey("bye")); + assertNull(data.get("bye")); + } + + @Test + void syntaxErrorFormattedAsSyntaxError() { + Map response = executor.execute(helloSchema, "{ hello", null, null); + + @SuppressWarnings("unchecked") + List> errors = (List>) response.get("errors"); + assertEquals("SyntaxError", errors.get(0).get("errorType")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorkerRehydrateTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorkerRehydrateTest.java new file mode 100644 index 0000000000..18cc295bae --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaCreationWorkerRehydrateTest.java @@ -0,0 +1,91 @@ +package io.github.hectorvent.floci.services.appsync.graphql; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.services.appsync.graphql.scalars.AppSyncScalarRegistry; +import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatus; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class SchemaCreationWorkerRehydrateTest { + + @Mock + AccountAwareStorageBackend schemaStatusStore; + @Mock + AccountAwareStorageBackend schemaStore; + @Mock + EmulatorConfig config; + + private SchemaRegistry schemaRegistry; + private SchemaCreationWorker worker; + + @BeforeEach + void setUp() { + schemaRegistry = new SchemaRegistry(new AppSyncSchemaParser(new AppSyncScalarRegistry())); + worker = new SchemaCreationWorker( + schemaRegistry, schemaStatusStore, schemaStore, config, new ObjectMapper()); + } + + @Test + void rehydrateRegistersSdlFromSchemaStore() { + when(schemaStore.scanAllAccountsAsMap()) + .thenReturn(Map.of("api-1", "type Query { hello: String }")); + + worker.rehydrateSchemas(); + + assertTrue(schemaRegistry.getSchema("api-1").isPresent()); + assertTrue(schemaRegistry.getGraphQL("api-1").isPresent()); + } + + @Test + void rehydrateLoadsSchemasFromNonDefaultAccounts() { + // Startup has no request context; keys()/get() would only see the default account. + // scanAllAccountsAsMap must surface SDLs stored under other accounts. + Map acrossAccounts = new LinkedHashMap<>(); + acrossAccounts.put("default-api", "type Query { fromDefault: String }"); + acrossAccounts.put("other-acct-api", "type Query { fromOther: String }"); + when(schemaStore.scanAllAccountsAsMap()).thenReturn(acrossAccounts); + + worker.rehydrateSchemas(); + + assertTrue(schemaRegistry.getSchema("default-api").isPresent()); + assertTrue(schemaRegistry.getSchema("other-acct-api").isPresent()); + assertTrue(schemaRegistry.getGraphQL("other-acct-api").isPresent()); + verify(schemaStore, never()).keys(); + verify(schemaStore, never()).get(anyString()); + } + + @Test + void rehydrateSkipsUnparseableSdl() { + when(schemaStore.scanAllAccountsAsMap()) + .thenReturn(Map.of("bad-api", "not valid sdl {{{")); + + worker.rehydrateSchemas(); + + assertTrue(schemaRegistry.getSchema("bad-api").isEmpty()); + } + + @Test + void rehydrateSkipsBlankEntries() { + when(schemaStore.scanAllAccountsAsMap()).thenReturn(Map.of("empty", " ")); + + worker.rehydrateSchemas(); + + assertTrue(schemaRegistry.getSchema("empty").isEmpty()); + verify(schemaStore, never()).put(anyString(), anyString()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistryTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistryTest.java new file mode 100644 index 0000000000..7723e84499 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistryTest.java @@ -0,0 +1,55 @@ +package io.github.hectorvent.floci.services.appsync.graphql; + +import graphql.GraphQL; +import io.github.hectorvent.floci.services.appsync.graphql.scalars.AppSyncScalarRegistry; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SchemaRegistryTest { + + private static final String SDL = "type Query { hello: String }"; + + private SchemaRegistry registry; + + @BeforeEach + void setUp() { + registry = new SchemaRegistry(new AppSyncSchemaParser(new AppSyncScalarRegistry())); + } + + @Test + void getGraphQLReturnsSameInstanceAcrossCalls() { + registry.register("api-1", SDL); + + GraphQL first = registry.getGraphQL("api-1").orElseThrow(); + GraphQL second = registry.getGraphQL("api-1").orElseThrow(); + + assertSame(first, second); + } + + @Test + void removeClearsCachedGraphQL() { + registry.register("api-1", SDL); + assertTrue(registry.getGraphQL("api-1").isPresent()); + + registry.remove("api-1"); + + assertTrue(registry.getGraphQL("api-1").isEmpty()); + assertTrue(registry.getSchema("api-1").isEmpty()); + } + + @Test + void reregisterReplacesCachedGraphQL() { + registry.register("api-1", SDL); + GraphQL original = registry.getGraphQL("api-1").orElseThrow(); + + registry.register("api-1", "type Query { bye: String }"); + GraphQL replaced = registry.getGraphQL("api-1").orElseThrow(); + + assertNotSame(original, replaced); + assertSame(replaced, registry.getGraphQL("api-1").orElseThrow()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/StackSetServiceDeleteFailureTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/StackSetServiceDeleteFailureTest.java index ea418fdb0e..3ff8e96d1d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/StackSetServiceDeleteFailureTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/StackSetServiceDeleteFailureTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.cloudformation.model.Stack; import io.github.hectorvent.floci.services.cloudformation.model.StackInstance; @@ -100,10 +101,10 @@ class StackSetServiceDeleteFailureTest { } @Override - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java index 46d0e0b8e7..55e0ab6338 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudfront; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.cloudfront.model.Distribution; import io.github.hectorvent.floci.services.cloudfront.model.StreamingDistribution; @@ -20,7 +21,7 @@ class CloudFrontServiceTest { private CloudFrontService serviceWithDomainSuffix(String domainSuffix) { StorageFactory storageFactory = Mockito.mock(StorageFactory.class); when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenReturn(new InMemoryStorage<>()); + .thenReturn(AccountAwareStorageBackend.inMemory("000000000000")); EmulatorConfig config = Mockito.mock(EmulatorConfig.class); var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/codebuild/CodeBuildServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/codebuild/CodeBuildServicePersistenceTest.java index bda08e6adf..e27c3d3a52 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codebuild/CodeBuildServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codebuild/CodeBuildServicePersistenceTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.codebuild.model.Build; import io.github.hectorvent.floci.services.codebuild.model.Project; @@ -149,10 +150,10 @@ class CodeBuildServicePersistenceTest { @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return (StorageBackend) stores.computeIfAbsent(fileName, ignored -> new InMemoryStorage<>()); + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000")); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployServicePersistenceTest.java index 2c3214aebd..b103f4117f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployServicePersistenceTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.codedeploy.model.DeploymentGroup; import io.github.hectorvent.floci.services.ec2.Ec2Service; @@ -112,10 +113,10 @@ class CodeDeployServicePersistenceTest { @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return (StorageBackend) stores.computeIfAbsent(fileName, ignored -> new InMemoryStorage<>()); + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000")); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java index 7fd8afcb05..39e8c1e7d5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java @@ -1,6 +1,6 @@ package io.github.hectorvent.floci.services.cognito.verification; -import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,7 +30,7 @@ class VerificationCodeServiceTest { void setUp() { clock = new MutableClock(Instant.parse("2026-05-15T12:00:00Z")); StorageFactory storageFactory = mock(StorageFactory.class); - when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> new InMemoryStorage<>()); + when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000")); service = new VerificationCodeService(storageFactory, clock); } diff --git a/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServicePersistenceTest.java index b235f3da84..b9a57df64d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServicePersistenceTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.configservice.model.ConfigRule; import io.github.hectorvent.floci.services.configservice.model.ConfigRuleSource; @@ -93,10 +94,10 @@ class AwsConfigServicePersistenceTest { @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return (StorageBackend) stores.computeIfAbsent(fileName, ignored -> new InMemoryStorage<>()); + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000")); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbServiceTest.java index afd2692c9a..21f7197078 100644 --- a/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbServiceTest.java @@ -2,7 +2,7 @@ package io.github.hectorvent.floci.services.docdb; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.RegionResolver; -import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.docdb.container.DocDbContainerManager; import io.github.hectorvent.floci.services.docdb.model.DocDbCluster; @@ -29,7 +29,7 @@ class DocDbServiceTest { void setUp() { StorageFactory storageFactory = Mockito.mock(StorageFactory.class); when(storageFactory.create(anyString(), anyString(), any())) - .thenAnswer(invocation -> new InMemoryStorage<>()); + .thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000")); EmulatorConfig config = Mockito.mock(EmulatorConfig.class); var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceConcurrencyTest.java index b843cccf0c..560628d506 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceConcurrencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceConcurrencyTest.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager; import io.github.hectorvent.floci.services.ec2.model.IpPermission; @@ -259,9 +260,9 @@ class Ec2ServiceConcurrencyTest { } @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index a1871a7df2..4765860cee 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -3,8 +3,7 @@ package io.github.hectorvent.floci.services.ec2; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; -import io.github.hectorvent.floci.core.storage.InMemoryStorage; -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 io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager; import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping; @@ -396,7 +395,7 @@ class Ec2ServiceTest { @Test void describeSnapshotsDefaultsToOwnedSnapshots() { - InMemoryStorage snapshotStore = new InMemoryStorage<>(); + AccountAwareStorageBackend snapshotStore = AccountAwareStorageBackend.inMemory("000000000000"); Snapshot foreign = new Snapshot(); foreign.setSnapshotId("snap-foreign"); foreign.setOwnerId("111111111111"); @@ -834,26 +833,26 @@ class Ec2ServiceTest { } private static final class InMemoryStorageFactory extends StorageFactory { - private final Map> overrides; + private final Map> overrides; private InMemoryStorageFactory() { this(Map.of()); } - private InMemoryStorageFactory(Map> overrides) { + private InMemoryStorageFactory(Map> overrides) { super(null, null); this.overrides = overrides; } @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - StorageBackend override = overrides.get(fileName); + AccountAwareStorageBackend override = overrides.get(fileName); if (override != null) { - return (StorageBackend) override; + return (AccountAwareStorageBackend) override; } - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServicePersistenceTest.java index 7e0a3c615e..794f574ae2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServicePersistenceTest.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.ecs.container.EcsContainerManager; import io.github.hectorvent.floci.services.ecs.model.Attribute; @@ -127,10 +128,10 @@ class EcsServicePersistenceTest { @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return (StorageBackend) stores.computeIfAbsent(fileName, ignored -> new InMemoryStorage<>()); + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000")); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTeardownTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTeardownTest.java index bcce5ad76b..30bedf7546 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTeardownTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTeardownTest.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.ecs.container.EcsContainerManager; import io.github.hectorvent.floci.services.ecs.container.EcsTaskHandle; @@ -127,10 +128,10 @@ class EcsServiceTeardownTest { @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return (StorageBackend) stores.computeIfAbsent(fileName, ignored -> new InMemoryStorage<>()); + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000")); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcServiceTest.java index 67ecf24f5c..5592ff7eaa 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksOidcServiceTest.java @@ -32,9 +32,9 @@ class EksOidcServiceTest { void setUp() { oidcService = new EksOidcService(new StorageFactory(null, null) { @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } }, new ObjectMapper()); } @@ -83,9 +83,9 @@ class EksOidcServiceTest { EksOidcService service = new EksOidcService(new StorageFactory(null, null) { @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return (StorageBackend) accountAware; + return (AccountAwareStorageBackend) accountAware; } }, new ObjectMapper()); diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java index 2d21dfd0b4..9bb67c36fc 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.ec2.AmiImageResolver; import io.github.hectorvent.floci.services.ec2.Ec2ContainerManager; @@ -51,9 +52,9 @@ class EksServiceTest { void setUp() { StorageFactory storageFactory = new StorageFactory(null, null) { @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } }; @@ -131,9 +132,9 @@ class EksServiceTest { StorageFactory storageFactory = new StorageFactory(null, null) { @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } }; @@ -287,9 +288,13 @@ class EksServiceTest { private StorageFactory fixedStorageFactory(StorageBackend backend) { return new StorageFactory(null, null) { @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return (StorageBackend) backend; + if (backend instanceof AccountAwareStorageBackend aware) { + return (AccountAwareStorageBackend) aware; + } + return new AccountAwareStorageBackend<>( + (StorageBackend) backend, null, "000000000000"); } }; } @@ -309,9 +314,9 @@ class EksServiceTest { void createClusterWithNonExistentSubnetFails() { StorageFactory storageFactory = new StorageFactory(null, null) { @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } }; RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); @@ -336,9 +341,9 @@ class EksServiceTest { void createClusterWithExistingSubnetSucceeds() { StorageFactory storageFactory = new StorageFactory(null, null) { @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } }; RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); @@ -369,9 +374,9 @@ class EksServiceTest { // resolved Subnet, which carries the vpcId; it was simply discarded. StorageFactory storageFactory = new StorageFactory(null, null) { @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } }; RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); @@ -398,9 +403,9 @@ class EksServiceTest { // the validation half. StorageFactory storageFactory = new StorageFactory(null, null) { @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } }; RegionResolver regionResolver = new RegionResolver("eu-west-2", "000000000000"); @@ -437,9 +442,9 @@ class EksServiceTest { // behaviour. StorageFactory storageFactory = new StorageFactory(null, null) { @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } }; Ec2Service ec2Service = realEc2Service(); diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedServiceTest.java index cbb0da82e3..bd10437abd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedServiceTest.java @@ -2,7 +2,7 @@ package io.github.hectorvent.floci.services.elasticache; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; -import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle; import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheMemcachedContainerManager; @@ -38,7 +38,7 @@ class ElastiCacheMemcachedServiceTest { when(ecConfig.defaultMemcachedImage()).thenReturn("memcached:1.6"); when(config.hostname()).thenReturn(Optional.of("localhost")); - when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> new InMemoryStorage<>()); + when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000")); when(containerManager.start(anyString(), anyString())) .thenReturn(new ElastiCacheContainerHandle("cid", "cluster", "localhost", 11211)); @@ -110,7 +110,7 @@ class ElastiCacheMemcachedServiceTest { when(ecConfig.defaultMemcachedImage()).thenReturn("memcached:1.6"); when(config.hostname()).thenReturn(Optional.empty()); - when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> new InMemoryStorage<>()); + when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000")); when(containerManager.start(anyString(), anyString())) .thenReturn(new ElastiCacheContainerHandle("cid", "cluster", "172.20.0.10", 11211)); diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java index 14e396523b..e4d599ca54 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java @@ -2,7 +2,7 @@ package io.github.hectorvent.floci.services.elasticache; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; -import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle; import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager; @@ -53,7 +53,7 @@ class ElastiCacheServiceTest { when(ecConfig.defaultImage()).thenReturn("valkey/valkey:8"); when(config.hostname()).thenReturn(java.util.Optional.of("localhost")); - when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> new InMemoryStorage<>()); + when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000")); when(containerManager.start(anyString(), anyString())) .thenReturn(new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379)); doNothing().when(proxyManager).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any()); diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticbeanstalk/ElasticBeanstalkServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticbeanstalk/ElasticBeanstalkServicePersistenceTest.java index 5c408dc572..ceab78eb44 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticbeanstalk/ElasticBeanstalkServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticbeanstalk/ElasticBeanstalkServicePersistenceTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.elasticbeanstalk.model.BeanstalkApplication; import io.github.hectorvent.floci.services.elasticbeanstalk.model.BeanstalkApplicationVersion; @@ -118,10 +119,10 @@ class ElasticBeanstalkServicePersistenceTest { @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return (StorageBackend) stores.computeIfAbsent(fileName, ignored -> new InMemoryStorage<>()); + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000")); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java index 2d7d316b83..2e63bf6b05 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ec2.model.Subnet; @@ -334,10 +335,10 @@ class ElbV2ServiceTest { @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return (StorageBackend) stores.computeIfAbsent(fileName, ignored -> new InMemoryStorage<>()); + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000")); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseServiceTest.java index 605305e4ba..b83fbeefe2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseServiceTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.firehose; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription; import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination; @@ -34,7 +35,7 @@ class FirehoseServiceTest { void setUp() { StorageFactory storageFactory = Mockito.mock(StorageFactory.class); when(storageFactory.create(anyString(), anyString(), any())) - .thenReturn(new InMemoryStorage<>()); + .thenReturn(AccountAwareStorageBackend.inMemory("000000000000")); s3Service = Mockito.mock(S3Service.class); firehoseService = new FirehoseService(storageFactory, s3Service, new RegionResolver("us-east-1", "000000000000"), new MutableClock()); diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerEmptyListTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerEmptyListTest.java index 95965c8051..47beb213b3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerEmptyListTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerEmptyListTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.glue.schemaregistry.GlueSchemaRegistryService; import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingService; @@ -83,10 +84,10 @@ class GlueJsonHandlerEmptyListTest { } @Override - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java index f57bf9b948..865946c84c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.glue.model.Column; import io.github.hectorvent.floci.services.glue.model.Database; @@ -1032,10 +1033,10 @@ class GlueServiceTest { } @Override - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2JsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2JsonHandlerTest.java index 96fd91540f..b91a659c18 100644 --- a/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2JsonHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2JsonHandlerTest.java @@ -6,6 +6,7 @@ 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.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.kinesisanalytics.container.FlinkContainerManager; import jakarta.ws.rs.core.Response; @@ -413,7 +414,7 @@ class KinesisAnalyticsV2JsonHandlerTest { private KinesisAnalyticsV2Service mockModeService() { StorageFactory storageFactory = Mockito.mock(StorageFactory.class); when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenReturn(new InMemoryStorage<>()); + .thenReturn(AccountAwareStorageBackend.inMemory("000000000000")); EmulatorConfig config = Mockito.mock(EmulatorConfig.class); var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2ServiceTest.java index bf620c094d..7b974e8b94 100644 --- a/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/KinesisAnalyticsV2ServiceTest.java @@ -3,7 +3,7 @@ package io.github.hectorvent.floci.services.kinesisanalytics; 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.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.kinesisanalytics.container.FlinkContainerManager; import io.github.hectorvent.floci.services.kinesisanalytics.model.ApplicationStatus; @@ -552,9 +552,10 @@ class KinesisAnalyticsV2ServiceTest { // intermediate state must still be persisted — not just the final RUNNING transition — since // pendingJars (a separate in-process-only cache) is already cleared by then; an emulator // restart before the next persist would otherwise leave the application permanently stuck. - InMemoryStorage backing = Mockito.spy(new InMemoryStorage<>()); + AccountAwareStorageBackend store = + Mockito.spy(AccountAwareStorageBackend.inMemory("000000000000")); StorageFactory storageFactory = Mockito.mock(StorageFactory.class); - Mockito.doReturn(backing).when(storageFactory) + Mockito.doReturn(store).when(storageFactory) .create(Mockito.anyString(), Mockito.anyString(), Mockito.any()); EmulatorConfig config = Mockito.mock(EmulatorConfig.class); @@ -580,7 +581,7 @@ class KinesisAnalyticsV2ServiceTest { realMode.createApplication("demo", "FLINK-1_18", ROLE, null, null, "bucket", "app.jar", null, 1); FlinkApplication app = realMode.describeApplication("demo"); app.setApplicationStatus(ApplicationStatus.STARTING); - Mockito.clearInvocations(backing); // ignore createApplication's own put() + Mockito.clearInvocations(store); // ignore createApplication's own put() try { // @PostConstruct isn't wired by a plain `new` in this unit test; start the poller manually. @@ -588,7 +589,8 @@ class KinesisAnalyticsV2ServiceTest { // The poller's first tick fires ~1s after scheduling; give it margin. Thread.sleep(1500); - Mockito.verify(backing, Mockito.atLeastOnce()).put(Mockito.eq("demo"), Mockito.any()); + Mockito.verify(store, Mockito.atLeastOnce()) + .putForAccount(Mockito.eq("000000000000"), Mockito.eq("demo"), Mockito.any()); assertEquals("job-1", realMode.describeApplication("demo").getFlinkJobId()); } finally { realMode.shutdown(); @@ -609,7 +611,7 @@ class KinesisAnalyticsV2ServiceTest { private KinesisAnalyticsV2Service buildService(boolean mock, FlinkContainerManager manager) { StorageFactory storageFactory = Mockito.mock(StorageFactory.class); when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenReturn(new InMemoryStorage<>()); + .thenReturn(AccountAwareStorageBackend.inMemory("000000000000")); EmulatorConfig config = Mockito.mock(EmulatorConfig.class); var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.java index eef5856ba2..36cdb5604d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServicePersistenceTest.java @@ -109,13 +109,13 @@ class LambdaServicePersistenceTest { @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { // Wrap like the production factory does so the tests exercise the // account-prefixed key space, not a bare backend. - return (StorageBackend) stores.computeIfAbsent(fileName, - ignored -> new AccountAwareStorageBackend(new InMemoryStorage<>(), null, ACCOUNT_ID)); + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, + ignored -> AccountAwareStorageBackend.inMemory(ACCOUNT_ID)); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsServicePersistenceTest.java index cad110299a..3d6ef0ac01 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsServicePersistenceTest.java @@ -165,12 +165,12 @@ class LambdaMicrovmsServicePersistenceTest { @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { // Wrap like the production factory does so the tests exercise the // account-prefixed key space, not a bare backend. - return (StorageBackend) stores.computeIfAbsent(fileName, ignored -> { + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, ignored -> { PersistentStorage inner = new PersistentStorage<>(directory.resolve(fileName), typeReference); inner.load(); diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java index ebbc24e6a1..f28a67aef5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java @@ -4,7 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; -import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator; import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerHandle; @@ -71,7 +71,7 @@ class MemoryDbServiceTest { AwsArnUtils.Arn.of(inv.getArgument(0), inv.getArgument(1), "000000000000", inv.getArgument(2)).toString()); - when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> new InMemoryStorage<>()); + when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000")); when(containerManager.start(anyString(), anyString())) .thenReturn(new MemoryDbContainerHandle("cid", "cluster", "localhost", 6379)); doNothing().when(proxyManager).startProxy(anyString(), anyBoolean(), anyInt(), anyString(), anyInt(), any()); diff --git a/src/test/java/io/github/hectorvent/floci/services/msk/MskServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/msk/MskServiceTest.java index 5ad3b7d301..1616215c4c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/msk/MskServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/msk/MskServiceTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.msk; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.msk.model.ClusterState; import io.github.hectorvent.floci.services.msk.model.MskCluster; @@ -26,7 +27,7 @@ class MskServiceTest { void setUp() { storageFactory = Mockito.mock(StorageFactory.class); when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenReturn(new InMemoryStorage<>()); + .thenReturn(AccountAwareStorageBackend.inMemory("000000000000")); config = Mockito.mock(EmulatorConfig.class); var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaServiceTest.java index cac2b2dfc7..08a8f704f4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaServiceTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.docker.PortAllocator; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.mwaa.model.CreateEnvironmentRequest; import io.github.hectorvent.floci.services.mwaa.model.Environment; @@ -45,9 +46,9 @@ class MwaaServiceTest { void setUp() { StorageFactory storageFactory = new StorageFactory(null, null) { @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } }; @@ -329,9 +330,9 @@ class MwaaServiceTest { void setUpRealMode() { StorageFactory storageFactory = new StorageFactory(null, null) { @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } }; diff --git a/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneServiceTest.java index 18c87b9fb3..d0214324d3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneServiceTest.java @@ -3,7 +3,7 @@ package io.github.hectorvent.floci.services.neptune; 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.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerHandle; import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerManager; @@ -57,7 +57,7 @@ class NeptuneServiceTest { when(config.hostname()).thenReturn(Optional.of("localhost")); when(storageFactory.create(anyString(), anyString(), any())) - .thenAnswer(inv -> new InMemoryStorage<>()); + .thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000")); when(containerManager.start(anyString(), anyString(), any(NeptuneDbType.class))) .thenReturn(new NeptuneContainerHandle("cid", "c", "localhost", 8182)); doNothing().when(proxyManager).startProxy(anyString(), anyInt(), anyString(), anyInt()); diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesServiceTest.java index 619ecef9b3..4007414ea6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesServiceTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.pipes; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.pipes.model.DesiredState; import io.github.hectorvent.floci.services.pipes.model.Pipe; @@ -26,7 +27,7 @@ class PipesServiceTest { void setUp() { StorageFactory storageFactory = Mockito.mock(StorageFactory.class); when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenReturn(new InMemoryStorage<>()); + .thenReturn(AccountAwareStorageBackend.inMemory("000000000000")); RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); diff --git a/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingServicePersistenceTest.java index 3894ce4451..71a0f653d1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingServicePersistenceTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.resourcegroupstagging; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.resourcegroupstagging.model.ResourceTagMapping; import org.junit.jupiter.api.Test; @@ -80,10 +81,10 @@ class ResourceGroupsTaggingServicePersistenceTest { @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return (StorageBackend) stores.computeIfAbsent(fileName, ignored -> new InMemoryStorage<>()); + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000")); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmCommandServiceDirectExecutionTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmCommandServiceDirectExecutionTest.java index be6ebf5d17..d9a6be623a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmCommandServiceDirectExecutionTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmCommandServiceDirectExecutionTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.ssm.model.Command; import io.github.hectorvent.floci.services.ssm.model.CommandInvocation; @@ -390,9 +391,9 @@ class SsmCommandServiceDirectExecutionTest { } @Override - public StorageBackend create(String serviceName, String fileName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return new InMemoryStorage<>(); + return AccountAwareStorageBackend.inMemory("000000000000"); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/transcribe/TranscribeServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/transcribe/TranscribeServicePersistenceTest.java index cd27ac6836..4ffb79122f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/transcribe/TranscribeServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/transcribe/TranscribeServicePersistenceTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.InMemoryStorage; 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 io.github.hectorvent.floci.services.transcribe.model.VocabularyInfo; import org.junit.jupiter.api.Test; @@ -65,10 +66,10 @@ class TranscribeServicePersistenceTest { @Override @SuppressWarnings("unchecked") - public StorageBackend create(String serviceName, + public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { - return (StorageBackend) stores.computeIfAbsent(fileName, ignored -> new InMemoryStorage<>()); + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000")); } } } diff --git a/src/test/java/io/github/hectorvent/floci/testing/RestAssuredJsonUtils.java b/src/test/java/io/github/hectorvent/floci/testing/RestAssuredJsonUtils.java index daec30ce42..e63e92b5ba 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/RestAssuredJsonUtils.java +++ b/src/test/java/io/github/hectorvent/floci/testing/RestAssuredJsonUtils.java @@ -39,7 +39,8 @@ public class RestAssuredJsonUtils { RestAssured.config = RestAssured.config().encoderConfig( EncoderConfig.encoderConfig() .encodeContentTypeAs(CONTENT_TYPE_AWS_JSON_1_0, ContentType.JSON) - .encodeContentTypeAs(CONTENT_TYPE_AWS_JSON_1_1, ContentType.JSON)); + .encodeContentTypeAs(CONTENT_TYPE_AWS_JSON_1_1, ContentType.JSON) + .encodeContentTypeAs("application/graphql", ContentType.JSON)); if (!RestAssured.filters().contains(AWS_CONTENT_TYPE_FILTER)) { RestAssured.filters(AWS_CONTENT_TYPE_FILTER);