feat(appsync): AWS AppSync management API (Phase 1) (#1108)

* feat(appsync): add GraphQL API management service

Implement Phase 1 CRUDL management API for AWS AppSync.
Includes controller, service layer, and model classes for:
- GraphQL API lifecycle (create/get/update/delete/list)
- Schema creation and introspection
- Data Sources, Resolvers, Functions, Types, API Keys
- Tagging and Environment Variables

* chore(appsync): register service in config and catalog

Add AppSync service configuration (EmulatorConfig), service
descriptor (ResolvedServiceCatalog), YAML config entries, and
SDK test client fixture.

* test(appsync): add integration and SDK compatibility tests

AppSyncIntegrationTest: 44 tests covering CRUDL for all resources
 GraphQL API, Schema, DataSources, Resolvers, Functions, Types,
 API Keys, Tags, Environment Variables, and cascade delete.

AppSyncTest: AWS SDK v2 compatibility tests for management API
 operations using the real AppSyncClient.

* feat(appsync): add typed enums for AWS API models

Add Java enums matching AWS AppSync API constants:
- AuthenticationType (API_KEY, AWS_IAM, COGNITO, OIDC, LAMBDA)
- DataSourceType (NONE, LAMBDA, DYNAMODB, HTTP, EVENTBRIDGE, ...)
- ResolverKind (UNIT, PIPELINE)
- ResolverRuntimeName (APPSYNC_JS, VTL)
- TypeFormat (SDL, JSON)
- SchemaCreationStatusType (PROCESSING, ACTIVE, FAILED, ...)

* refactor(appsync): align model types with AWS API reference

- DataSource.type: String → DataSourceType enum
- GraphqlApi.authenticationType: String → AuthenticationType enum
- GraphqlApi.logConfig: String → Map<String, Object> (structured)
- GraphqlApi.additionalAuthenticationProviders: Map → List<Map> (array)
- GraphqlApi.xrayEnabled: String → Boolean
- Resolver.kind: String → ResolverKind enum
- Resolver.ResolverRuntime.name: String → ResolverRuntimeName enum
- AppSyncType.format: String → TypeFormat enum
- SchemaCreationStatus.status: String → SchemaCreationStatusType enum
- ApiKey.expires: String → Long (epoch seconds)

* fix(appsync): correct ARN format, add enum validation, fix field types

- Function ARN: add missing region parameter
- Add parseEnum() helper for type-safe enum deserialization
- Reject invalid enum values with BadRequestException (400)
- Handle String/Boolean/Number coercion for xrayEnabled, expires
- Remove extra 'details' from StartSchemaCreation response
- Pass region to createFunction from controller

* fix(appsync): validate required fields on resource creation

Reject requests missing required fields with BadRequestException (400):
- CreateGraphqlApi: name required
- CreateDataSource: name and type required
- CreateResolver: fieldName and dataSourceName required
- CreateFunction: name required
- CreateType: name required

* test(appsync): add error handling, delete standalone, and cascade tests

Add 22 new integration tests (44 → 66 total):
- Error handling: missing name, blank name, invalid enum, missing required
  fields for API/DataSources/Resolvers/Functions/Types (11 tests)
- Non-existent resource 404 tests for API, DataSource, Type (3 tests)
- Delete standalone: verify CRUD delete for Resolver, DataSource,
  Function, Type, ApiKey with post-delete 404 confirmation (5 tests)
- Cascade verification: API delete cascades to DataSources and Functions;
  Function delete does not affect resolvers (3 tests)

* feat(appsync): add pagination support for list endpoints

Add maxResults and nextToken query params to all list endpoints:
- ListGraphqlApis, ListDataSources, ListResolvers, ListResolversByFunction
- ListFunctions, ListTypes, ListApiKeys

Uses offset-based pagination with Base64-encoded tokens, following
the Pricing service pattern. Returns nextToken when more results
are available, null when all results have been returned.

* test(appsync): add pagination integration tests

Add 9 pagination tests (66 → 75 total):
- ListApis with maxResults returns subset and nextToken
- ListApis with nextToken returns second page
- ListApis without pagination returns all items
- ListDataSources, ListTypes, ListFunctions, ListApiKeys,
  ListResolvers with maxResults
- Invalid nextToken returns 400

* fix(appsync): align SDK test with AWS SDK v2 model, extract type name from SDL

- Fix SDK test: use typeAsString() for enum comparison, remove apiKey()
  field assertion, use functions() instead of functionConfigurationList()
- Extract type name from SDL definition when name is not provided
  (matches real AWS CreateType behavior)
- Update integration test for type creation without explicit name

* fix(appsync): use extracted type name when definition-based extraction succeeds

The type name extracted from SDL definition was stored in a local
variable but not set on the AppSyncType object, causing createType
to return a type without name and making subsequent get/delete fail.

* refactor(appsync): inject RegionResolver instead of passing region as string

Follow the established pattern used by BackupService and PipesService.
Replace manual ARN string concatenation with regionResolver.buildArn()
and remove the hardcoded accountId field.

* fix(appsync): add functionId to Resolver model and fix listResolversByFunction filtering

The listResolversByFunction endpoint was incorrectly comparing
function.getName() with resolver.getDataSourceName(), which is not
the correct AWS AppSync relationship. Resolvers reference functions
via a functionId field, not by data source name matching.

- Add functionId field to Resolver model
- Handle functionId in createResolver and updateResolver
- Fix listResolversByFunction to filter by functionId
- Add listResolversByType method for per-type filtering

* feat(appsync): add global listResolvers endpoint

Add GET /v1/apis/{apiId}/resolvers to list all resolvers across all
types, matching the AWS AppSync API. The per-type endpoint
(GET /v1/apis/{apiId}/types/{typeName}/resolvers) is preserved.

- Add global listResolvers to controller
- Rename per-type endpoint to listResolversByType for clarity
- Add integration test for global listResolvers
- Update listResolversByFunction test to verify functionId-based filtering

* test(appsync): complete SDK compatibility tests for Phase 1

Add missing SDK v2 compatibility tests to match all Phase 1 operations:

- API Keys: updateApiKey, deleteApiKey
- Resolvers: updateResolver
- Types: createType, getType, listTypes, updateType
- Error handling: getNonExistentApi, getNonExistentDataSource,
  getNonExistentType throw AppSyncException

Total SDK tests: 24 → 35. All operations in Phase 1 are now covered.
This commit is contained in:
AgustinBertagna authored and GitHub committed 2026-06-02 00:17:01 -05:00
1 parent e8441f58a5
commit d7ddac73fe
23 files changed
+3610 -1

No files matched your search

@@ -145,6 +145,7 @@ public interface EmulatorConfig {
NeptuneStorageConfig neptune();
BackupStorageConfig backup();
CloudFrontStorageConfig cloudfront();
AppSyncStorageConfig appsync();
}
interface SsmStorageConfig {
@@ -258,6 +259,13 @@ public interface EmulatorConfig {
Optional<String> mode();
}
interface AppSyncStorageConfig {
Optional<String> mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface WalConfig {
@WithDefault("30000")
long compactionIntervalMs();
@@ -330,6 +338,7 @@ public interface EmulatorConfig {
BcmDataExportsServiceConfig bcmDataExports();
ConfigServiceConfig configservice();
CloudFrontServiceConfig cloudfront();
AppSyncServiceConfig appsync();
}
interface TransferServiceConfig {
@@ -770,6 +779,11 @@ public interface EmulatorConfig {
String domainSuffix();
}
interface AppSyncServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface BcmDataExportsServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.opensearch.OpenSearchController;
import io.github.hectorvent.floci.services.cloudfront.CloudFrontController;
import io.github.hectorvent.floci.services.route53.Route53Controller;
import io.github.hectorvent.floci.services.ses.SesController;
import io.github.hectorvent.floci.services.appsync.AppSyncController;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -278,7 +279,12 @@ public class ResolvedServiceCatalog {
"cloudfront", storageMode(config.storage().services().cloudfront().mode(), config.storage().mode()),
5000L, AwsNamespaces.CLOUDFRONT, ServiceProtocol.REST_XML,
protocols(ServiceProtocol.REST_XML),
Set.of(), Set.of("cloudfront"), Set.of(), Set.of(CloudFrontController.class))
Set.of(), Set.of("cloudfront"), Set.of(), Set.of(CloudFrontController.class)),
descriptor("appsync", "appsync", config.services().appsync().enabled(), true,
"appsync", storageMode(config.storage().services().appsync().mode(), config.storage().mode()),
config.storage().services().appsync().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("appsync"), Set.of(), Set.of(AppSyncController.class))
));
}
@@ -0,0 +1,540 @@
package io.github.hectorvent.floci.services.appsync;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.appsync.model.*;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
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.io.IOException;
import java.util.List;
import java.util.Map;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class AppSyncController {
private static final Logger LOG = Logger.getLogger(AppSyncController.class);
private final AppSyncService service;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public AppSyncController(AppSyncService service,
RegionResolver regionResolver,
ObjectMapper objectMapper) {
this.service = service;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
// ──────────────────────────── GraphQL API ────────────────────────────
@POST
@Path("/v1/apis")
public Response createGraphqlApi(@Context HttpHeaders headers, String body) throws IOException {
String region = regionResolver.resolveRegion(headers);
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
GraphqlApi api = service.createGraphqlApi(request, region);
ObjectNode root = objectMapper.createObjectNode();
root.set("graphqlApi", objectMapper.valueToTree(api));
return Response.status(200).entity(root).build();
}
@GET
@Path("/v1/apis/{apiId}")
public Response getGraphqlApi(@PathParam("apiId") String apiId) {
GraphqlApi api = service.getGraphqlApi(apiId);
ObjectNode root = objectMapper.createObjectNode();
root.set("graphqlApi", objectMapper.valueToTree(api));
return Response.ok(root).build();
}
@POST
@Path("/v1/apis/{apiId}")
public Response updateGraphqlApi(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
String body) throws IOException {
String region = regionResolver.resolveRegion(headers);
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
GraphqlApi api = service.updateGraphqlApi(apiId, request, region);
ObjectNode root = objectMapper.createObjectNode();
root.set("graphqlApi", objectMapper.valueToTree(api));
return Response.ok(root).build();
}
@DELETE
@Path("/v1/apis/{apiId}")
public Response deleteGraphqlApi(@PathParam("apiId") String apiId) {
service.deleteGraphqlApi(apiId);
return Response.noContent().build();
}
@GET
@Path("/v1/apis")
public Response listGraphqlApis(@QueryParam("maxResults") Integer maxResults,
@QueryParam("nextToken") String nextToken) {
var page = service.listGraphqlApis(maxResults, nextToken);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("graphqlApis");
page.items().forEach(items::addPOJO);
if (page.nextToken() != null) {
root.put("nextToken", page.nextToken());
} else {
root.putNull("nextToken");
}
return Response.ok(root).build();
}
// ──────────────────────────── Schema ────────────────────────────
@POST
@Path("/v1/apis/{apiId}/schemacreation")
public Response startSchemaCreation(@PathParam("apiId") String apiId, String body) throws IOException {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
String definition = (String) request.get("definition");
if (definition != null) {
try {
definition = new String(java.util.Base64.getDecoder().decode(definition), java.nio.charset.StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
// Not base64, use as-is
}
}
service.startSchemaCreation(apiId, definition);
SchemaCreationStatus status = new SchemaCreationStatus();
status.setStatus(SchemaCreationStatusType.ACTIVE);
return Response.ok(status).build();
}
@GET
@Path("/v1/apis/{apiId}/schemacreation")
public Response getSchemaCreationStatus(@PathParam("apiId") String apiId) {
return Response.ok(service.getSchemaCreationStatus(apiId)).build();
}
@GET
@Path("/v1/apis/{apiId}/schema")
public Response getIntrospectionSchema(@PathParam("apiId") String apiId) {
String schema = service.getIntrospectionSchema(apiId);
ObjectNode root = objectMapper.createObjectNode();
root.put("schema", schema);
return Response.ok(root).build();
}
// ──────────────────────────── Data Sources ────────────────────────────
@POST
@Path("/v1/apis/{apiId}/datasources")
public Response createDataSource(@PathParam("apiId") String apiId, String body) throws IOException {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
DataSource ds = service.createDataSource(apiId, request);
ObjectNode root = objectMapper.createObjectNode();
root.set("dataSource", objectMapper.valueToTree(ds));
return Response.status(200).entity(root).build();
}
@GET
@Path("/v1/apis/{apiId}/datasources/{name}")
public Response getDataSource(@PathParam("apiId") String apiId, @PathParam("name") String name) {
DataSource ds = service.getDataSource(apiId, name);
ObjectNode root = objectMapper.createObjectNode();
root.set("dataSource", objectMapper.valueToTree(ds));
return Response.ok(root).build();
}
@POST
@Path("/v1/apis/{apiId}/datasources/{name}")
public Response updateDataSource(@PathParam("apiId") String apiId,
@PathParam("name") String name,
String body) throws IOException {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
DataSource ds = service.updateDataSource(apiId, name, request);
ObjectNode root = objectMapper.createObjectNode();
root.set("dataSource", objectMapper.valueToTree(ds));
return Response.ok(root).build();
}
@DELETE
@Path("/v1/apis/{apiId}/datasources/{name}")
public Response deleteDataSource(@PathParam("apiId") String apiId,
@PathParam("name") String name) {
service.deleteDataSource(apiId, name);
return Response.noContent().build();
}
@GET
@Path("/v1/apis/{apiId}/datasources")
public Response listDataSources(@PathParam("apiId") String apiId,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("nextToken") String nextToken) {
var page = service.listDataSources(apiId, maxResults, nextToken);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("dataSources");
page.items().forEach(items::addPOJO);
if (page.nextToken() != null) {
root.put("nextToken", page.nextToken());
} else {
root.putNull("nextToken");
}
return Response.ok(root).build();
}
// ──────────────────────────── Resolvers ────────────────────────────
@POST
@Path("/v1/apis/{apiId}/types/{typeName}/resolvers")
public Response createResolver(@PathParam("apiId") String apiId,
@PathParam("typeName") String typeName,
String body) throws IOException {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
request.put("typeName", typeName);
Resolver resolver = service.createResolver(apiId, request);
ObjectNode root = objectMapper.createObjectNode();
root.set("resolver", objectMapper.valueToTree(resolver));
return Response.status(200).entity(root).build();
}
@GET
@Path("/v1/apis/{apiId}/resolvers")
public Response listResolvers(@PathParam("apiId") String apiId,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("nextToken") String nextToken) {
var page = service.listResolvers(apiId, maxResults, nextToken);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("resolvers");
page.items().forEach(items::addPOJO);
if (page.nextToken() != null) {
root.put("nextToken", page.nextToken());
} else {
root.putNull("nextToken");
}
return Response.ok(root).build();
}
@GET
@Path("/v1/apis/{apiId}/types/{typeName}/resolvers")
public Response listResolversByType(@PathParam("apiId") String apiId,
@PathParam("typeName") String typeName,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("nextToken") String nextToken) {
var page = service.listResolversByType(apiId, typeName, maxResults, nextToken);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("resolvers");
page.items().forEach(items::addPOJO);
if (page.nextToken() != null) {
root.put("nextToken", page.nextToken());
} else {
root.putNull("nextToken");
}
return Response.ok(root).build();
}
@GET
@Path("/v1/apis/{apiId}/types/{typeName}/resolvers/{fieldName}")
public Response getResolver(@PathParam("apiId") String apiId,
@PathParam("typeName") String typeName,
@PathParam("fieldName") String fieldName) {
Resolver resolver = service.getResolver(apiId, typeName, fieldName);
ObjectNode root = objectMapper.createObjectNode();
root.set("resolver", objectMapper.valueToTree(resolver));
return Response.ok(root).build();
}
@POST
@Path("/v1/apis/{apiId}/types/{typeName}/resolvers/{fieldName}")
public Response updateResolver(@PathParam("apiId") String apiId,
@PathParam("typeName") String typeName,
@PathParam("fieldName") String fieldName,
String body) throws IOException {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
Resolver resolver = service.updateResolver(apiId, typeName, fieldName, request);
ObjectNode root = objectMapper.createObjectNode();
root.set("resolver", objectMapper.valueToTree(resolver));
return Response.ok(root).build();
}
@DELETE
@Path("/v1/apis/{apiId}/types/{typeName}/resolvers/{fieldName}")
public Response deleteResolver(@PathParam("apiId") String apiId,
@PathParam("typeName") String typeName,
@PathParam("fieldName") String fieldName) {
service.deleteResolver(apiId, typeName, fieldName);
return Response.noContent().build();
}
@GET
@Path("/v1/apis/{apiId}/functions/{functionId}/resolvers")
public Response listResolversByFunction(@PathParam("apiId") String apiId,
@PathParam("functionId") String functionId,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("nextToken") String nextToken) {
var page = service.listResolversByFunction(apiId, functionId, maxResults, nextToken);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("resolvers");
page.items().forEach(items::addPOJO);
if (page.nextToken() != null) {
root.put("nextToken", page.nextToken());
} else {
root.putNull("nextToken");
}
return Response.ok(root).build();
}
// ──────────────────────────── Functions ────────────────────────────
@POST
@Path("/v1/apis/{apiId}/functions")
public Response createFunction(@Context HttpHeaders headers,
@PathParam("apiId") String apiId, String body) throws IOException {
String region = regionResolver.resolveRegion(headers);
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
FunctionConfiguration fn = service.createFunction(apiId, request, region);
ObjectNode root = objectMapper.createObjectNode();
root.set("functionConfiguration", objectMapper.valueToTree(fn));
return Response.status(200).entity(root).build();
}
@GET
@Path("/v1/apis/{apiId}/functions/{functionId}")
public Response getFunction(@PathParam("apiId") String apiId, @PathParam("functionId") String functionId) {
FunctionConfiguration fn = service.getFunction(apiId, functionId);
ObjectNode root = objectMapper.createObjectNode();
root.set("functionConfiguration", objectMapper.valueToTree(fn));
return Response.ok(root).build();
}
@POST
@Path("/v1/apis/{apiId}/functions/{functionId}")
public Response updateFunction(@PathParam("apiId") String apiId,
@PathParam("functionId") String functionId,
String body) throws IOException {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
FunctionConfiguration fn = service.updateFunction(apiId, functionId, request);
ObjectNode root = objectMapper.createObjectNode();
root.set("functionConfiguration", objectMapper.valueToTree(fn));
return Response.ok(root).build();
}
@DELETE
@Path("/v1/apis/{apiId}/functions/{functionId}")
public Response deleteFunction(@PathParam("apiId") String apiId,
@PathParam("functionId") String functionId) {
service.deleteFunction(apiId, functionId);
return Response.noContent().build();
}
@GET
@Path("/v1/apis/{apiId}/functions")
public Response listFunctions(@PathParam("apiId") String apiId,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("nextToken") String nextToken) {
var page = service.listFunctions(apiId, maxResults, nextToken);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("functions");
page.items().forEach(items::addPOJO);
if (page.nextToken() != null) {
root.put("nextToken", page.nextToken());
} else {
root.putNull("nextToken");
}
return Response.ok(root).build();
}
// ──────────────────────────── Types ────────────────────────────
@POST
@Path("/v1/apis/{apiId}/types")
public Response createType(@PathParam("apiId") String apiId, String body) throws IOException {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
AppSyncType type = service.createType(apiId, request);
ObjectNode root = objectMapper.createObjectNode();
root.set("type", objectMapper.valueToTree(type));
return Response.status(200).entity(root).build();
}
@GET
@Path("/v1/apis/{apiId}/types/{typeName}")
public Response getType(@PathParam("apiId") String apiId, @PathParam("typeName") String typeName) {
AppSyncType type = service.getType(apiId, typeName);
ObjectNode root = objectMapper.createObjectNode();
root.set("type", objectMapper.valueToTree(type));
return Response.ok(root).build();
}
@POST
@Path("/v1/apis/{apiId}/types/{typeName}")
public Response updateType(@PathParam("apiId") String apiId,
@PathParam("typeName") String typeName,
String body) throws IOException {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
AppSyncType type = service.updateType(apiId, typeName, request);
ObjectNode root = objectMapper.createObjectNode();
root.set("type", objectMapper.valueToTree(type));
return Response.ok(root).build();
}
@DELETE
@Path("/v1/apis/{apiId}/types/{typeName}")
public Response deleteType(@PathParam("apiId") String apiId,
@PathParam("typeName") String typeName) {
service.deleteType(apiId, typeName);
return Response.noContent().build();
}
@GET
@Path("/v1/apis/{apiId}/types")
public Response listTypes(@PathParam("apiId") String apiId,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("nextToken") String nextToken) {
var page = service.listTypes(apiId, maxResults, nextToken);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("types");
page.items().forEach(items::addPOJO);
if (page.nextToken() != null) {
root.put("nextToken", page.nextToken());
} else {
root.putNull("nextToken");
}
return Response.ok(root).build();
}
// ──────────────────────────── API Keys ────────────────────────────
@POST
@Path("/v1/apis/{apiId}/apikeys")
public Response createApiKey(@PathParam("apiId") String apiId, String body) throws IOException {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
ApiKey key = service.createApiKey(apiId, request);
ObjectNode root = objectMapper.createObjectNode();
root.set("apiKey", objectMapper.valueToTree(key));
return Response.status(200).entity(root).build();
}
@GET
@Path("/v1/apis/{apiId}/apikeys")
public Response listApiKeys(@PathParam("apiId") String apiId,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("nextToken") String nextToken) {
var page = service.listApiKeys(apiId, maxResults, nextToken);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("apiKeys");
page.items().forEach(items::addPOJO);
if (page.nextToken() != null) {
root.put("nextToken", page.nextToken());
} else {
root.putNull("nextToken");
}
return Response.ok(root).build();
}
@GET
@Path("/v1/apis/{apiId}/apikeys/{keyId}")
public Response getApiKey(@PathParam("apiId") String apiId, @PathParam("keyId") String keyId) {
ApiKey key = service.getApiKey(apiId, keyId);
ObjectNode root = objectMapper.createObjectNode();
root.set("apiKey", objectMapper.valueToTree(key));
return Response.ok(root).build();
}
@POST
@Path("/v1/apis/{apiId}/apikeys/{keyId}")
public Response updateApiKey(@PathParam("apiId") String apiId,
@PathParam("keyId") String keyId,
String body) throws IOException {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
ApiKey key = service.updateApiKey(apiId, keyId, request);
ObjectNode root = objectMapper.createObjectNode();
root.set("apiKey", objectMapper.valueToTree(key));
return Response.ok(root).build();
}
@DELETE
@Path("/v1/apis/{apiId}/apikeys/{keyId}")
public Response deleteApiKey(@PathParam("apiId") String apiId, @PathParam("keyId") String keyId) {
service.deleteApiKey(apiId, keyId);
return Response.noContent().build();
}
// ──────────────────────────── Tags ────────────────────────────
@POST
@Path("/v1/tags/{resourceArn: .+}")
public Response tagResource(@PathParam("resourceArn") String resourceArn, String body) throws IOException {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
@SuppressWarnings("unchecked")
Map<String, String> tags = (Map<String, String>) request.get("tags");
service.tagResource(resourceArn, tags);
return Response.noContent().build();
}
@DELETE
@Path("/v1/tags/{resourceArn: .+}")
public Response untagResource(@PathParam("resourceArn") String resourceArn,
@QueryParam("tagKeys") List<String> tagKeys) {
service.untagResource(resourceArn, tagKeys);
return Response.noContent().build();
}
@GET
@Path("/v1/tags/{resourceArn: .+}")
public Response listTagsForResource(@PathParam("resourceArn") String resourceArn) {
Map<String, String> tags = service.getTags(resourceArn);
ObjectNode root = objectMapper.createObjectNode();
ObjectNode tagsNode = root.putObject("tags");
tags.forEach(tagsNode::put);
return Response.ok(root).build();
}
// ──────────────────────────── Environment Variables ────────────────────────────
@GET
@Path("/v1/apis/{apiId}/environmentvariables")
public Response getEnvironmentVariables(@PathParam("apiId") String apiId) {
Map<String, String> envVars = service.getEnvironmentVariables(apiId);
ObjectNode root = objectMapper.createObjectNode();
ObjectNode envNode = root.putObject("environmentVariables");
envVars.forEach(envNode::put);
return Response.ok(root).build();
}
@PUT
@Path("/v1/apis/{apiId}/environmentvariables")
public Response putEnvironmentVariables(@PathParam("apiId") String apiId,
String body) throws IOException {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
@SuppressWarnings("unchecked")
Map<String, String> envVars = (Map<String, String>) request.get("environmentVariables");
if (envVars == null) {
envVars = Map.of();
}
Map<String, String> result = service.putEnvironmentVariables(apiId, envVars);
ObjectNode root = objectMapper.createObjectNode();
ObjectNode envNode = root.putObject("environmentVariables");
result.forEach(envNode::put);
return Response.ok(root).build();
}
}
@@ -0,0 +1,631 @@
package io.github.hectorvent.floci.services.appsync;
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.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.appsync.model.*;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Base64;
@ApplicationScoped
public class AppSyncService {
private static final Logger LOG = Logger.getLogger(AppSyncService.class);
private final StorageBackend<String, GraphqlApi> apiStore;
private final StorageBackend<String, String> schemaStore; // apiId -> schema SDL
private final StorageBackend<String, SchemaCreationStatus> schemaStatusStore;
private final StorageBackend<String, DataSource> dataSourceStore;
private final StorageBackend<String, Resolver> resolverStore;
private final StorageBackend<String, FunctionConfiguration> functionStore;
private final StorageBackend<String, ApiKey> apiKeyStore;
private final StorageBackend<String, AppSyncType> typeStore;
private final RegionResolver regionResolver;
@Inject
public AppSyncService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) {
this.apiStore = storageFactory.create("appsync", "appsync-apis.json", new TypeReference<>() {});
this.schemaStore = storageFactory.create("appsync", "appsync-schemas.json", new TypeReference<>() {});
this.schemaStatusStore = storageFactory.create("appsync", "appsync-schema-status.json", new TypeReference<>() {});
this.dataSourceStore = storageFactory.create("appsync", "appsync-datasources.json", new TypeReference<>() {});
this.resolverStore = storageFactory.create("appsync", "appsync-resolvers.json", new TypeReference<>() {});
this.functionStore = storageFactory.create("appsync", "appsync-functions.json", new TypeReference<>() {});
this.apiKeyStore = storageFactory.create("appsync", "appsync-apikeys.json", new TypeReference<>() {});
this.typeStore = storageFactory.create("appsync", "appsync-types.json", new TypeReference<>() {});
this.regionResolver = regionResolver;
}
// ──────────────────────────── GraphQL API ────────────────────────────
public GraphqlApi createGraphqlApi(Map<String, Object> request, String region) {
String name = (String) request.get("name");
if (name == null || name.isBlank()) {
throw new AwsException("BadRequestException", "A GraphQL API name is required", 400);
}
String apiId = generateApiId();
GraphqlApi api = new GraphqlApi();
api.setApiId(apiId);
api.setName(name);
api.setAuthenticationType(parseEnum(AuthenticationType.class, request.get("authenticationType")));
Object xrayValue = request.get("xrayEnabled");
if (xrayValue instanceof Boolean b) {
api.setXrayEnabled(b);
} else if (xrayValue instanceof String s) {
api.setXrayEnabled(Boolean.parseBoolean(s));
} else {
api.setXrayEnabled(false);
}
api.setLogConfig((Map<String, Object>) request.get("logConfig"));
Object additionalObj = request.get("additionalAuthenticationProviders");
if (additionalObj instanceof List<?> additionalList) {
List<Map<String, Object>> providers = new ArrayList<>();
for (Object item : additionalList) {
if (item instanceof Map<?, ?> map) {
@SuppressWarnings("unchecked")
Map<String, Object> casted = (Map<String, Object>) map;
providers.add(casted);
}
}
api.setAdditionalAuthenticationProviders(providers);
}
api.setArn(buildApiArn(apiId, region));
Map<String, String> uris = new HashMap<>();
String baseUri = "http://localhost:4566";
uris.put("GRAPHQL", baseUri + "/v1/apis/" + apiId + "/graphql");
uris.put("REALTIME", "ws://localhost:4566/v1/apis/" + apiId + "/graphql/realtime");
api.setUris(uris);
Map<String, Object> tags = (Map<String, Object>) request.get("tags");
if (tags != null) {
Map<String, String> tagMap = new HashMap<>();
tags.forEach((k, v) -> tagMap.put(k, String.valueOf(v)));
api.setTags(tagMap);
}
apiStore.put(apiId, api);
LOG.infov("Created GraphQL API {0}: {1}", apiId, api.getName());
return api;
}
public GraphqlApi getGraphqlApi(String apiId) {
return apiStore.get(apiId)
.orElseThrow(() -> new AwsException("NotFoundException", "GraphQL API not found: " + apiId, 404));
}
public Page<GraphqlApi> listGraphqlApis(Integer maxResults, String nextToken) {
return paginate(apiStore.scan(k -> true), nextToken, maxResults);
}
public GraphqlApi updateGraphqlApi(String apiId, Map<String, Object> request, String region) {
GraphqlApi existing = getGraphqlApi(apiId);
if (request.containsKey("name")) existing.setName((String) request.get("name"));
if (request.containsKey("authenticationType")) existing.setAuthenticationType(parseEnum(AuthenticationType.class, request.get("authenticationType")));
if (request.containsKey("xrayEnabled")) {
Object xrayValue = request.get("xrayEnabled");
if (xrayValue instanceof Boolean b) {
existing.setXrayEnabled(b);
} else if (xrayValue instanceof String s) {
existing.setXrayEnabled(Boolean.parseBoolean(s));
}
}
if (request.containsKey("logConfig")) existing.setLogConfig((Map<String, Object>) request.get("logConfig"));
if (request.containsKey("tags")) {
Map<String, Object> tags = (Map<String, Object>) request.get("tags");
Map<String, String> tagMap = new HashMap<>();
tags.forEach((k, v) -> tagMap.put(k, String.valueOf(v)));
existing.setTags(tagMap);
}
apiStore.put(apiId, existing);
return existing;
}
public void deleteGraphqlApi(String apiId) {
getGraphqlApi(apiId);
apiStore.delete(apiId);
schemaStore.delete(apiId);
schemaStatusStore.delete(apiId);
deleteDataSourcesForApi(apiId);
deleteResolversForApi(apiId);
deleteFunctionsForApi(apiId);
deleteTypesForApi(apiId);
deleteApiKeysForApi(apiId);
LOG.infov("Deleted GraphQL API {0}", apiId);
}
// ──────────────────────────── Schema ────────────────────────────
public void startSchemaCreation(String apiId, String definition) {
getGraphqlApi(apiId);
schemaStore.put(apiId, definition);
SchemaCreationStatus status = new SchemaCreationStatus();
status.setStatus(SchemaCreationStatusType.ACTIVE);
schemaStatusStore.put(apiId, status);
LOG.infov("Schema creation completed for API {0}", apiId);
}
public SchemaCreationStatus getSchemaCreationStatus(String apiId) {
getGraphqlApi(apiId);
return schemaStatusStore.get(apiId).orElseThrow(() ->
new AwsException("NotFoundException", "Schema creation status not found for API: " + apiId, 404));
}
public String getIntrospectionSchema(String apiId) {
getGraphqlApi(apiId);
return schemaStore.get(apiId).orElse(null);
}
// ──────────────────────────── Data Sources ────────────────────────────
public DataSource createDataSource(String apiId, Map<String, Object> request) {
getGraphqlApi(apiId);
String name = (String) request.get("name");
if (name == null || name.isBlank()) {
throw new AwsException("BadRequestException", "A data source name is required", 400);
}
if (request.get("type") == null) {
throw new AwsException("BadRequestException", "A data source type is required", 400);
}
DataSource ds = new DataSource();
ds.setName(name);
ds.setDescription((String) request.get("description"));
ds.setType(parseEnum(DataSourceType.class, request.get("type")));
ds.setServiceRoleArn((String) request.get("serviceRoleArn"));
ds.setDynamodbConfig((Map<String, Object>) request.get("dynamodbConfig"));
ds.setLambdaConfig((Map<String, Object>) request.get("lambdaConfig"));
ds.setHttpConfig((Map<String, Object>) request.get("httpConfig"));
ds.setEventBridgeConfig((Map<String, Object>) request.get("eventBridgeConfig"));
ds.setRelationalDatabaseConfig((Map<String, Object>) request.get("relationalDatabaseConfig"));
ds.setOpenSearchServiceConfig((Map<String, Object>) request.get("openSearchServiceConfig"));
ds.setAmazonBedrockRuntimeConfig((Map<String, Object>) request.get("amazonBedrockRuntimeConfig"));
dataSourceStore.put(apiKey(apiId, ds.getName()), ds);
return ds;
}
public DataSource getDataSource(String apiId, String dataSourceName) {
return dataSourceStore.get(apiKey(apiId, dataSourceName))
.orElseThrow(() -> new AwsException("NotFoundException", "Data source not found: " + dataSourceName, 404));
}
public Page<DataSource> listDataSources(String apiId, Integer maxResults, String nextToken) {
return paginate(dataSourceStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults);
}
public DataSource updateDataSource(String apiId, String dataSourceName, Map<String, Object> request) {
DataSource existing = getDataSource(apiId, dataSourceName);
if (request.containsKey("description")) existing.setDescription((String) request.get("description"));
if (request.containsKey("type")) existing.setType(parseEnum(DataSourceType.class, request.get("type")));
if (request.containsKey("serviceRoleArn")) existing.setServiceRoleArn((String) request.get("serviceRoleArn"));
if (request.containsKey("dynamodbConfig")) existing.setDynamodbConfig((Map<String, Object>) request.get("dynamodbConfig"));
if (request.containsKey("lambdaConfig")) existing.setLambdaConfig((Map<String, Object>) request.get("lambdaConfig"));
if (request.containsKey("httpConfig")) existing.setHttpConfig((Map<String, Object>) request.get("httpConfig"));
if (request.containsKey("eventBridgeConfig")) existing.setEventBridgeConfig((Map<String, Object>) request.get("eventBridgeConfig"));
if (request.containsKey("relationalDatabaseConfig")) existing.setRelationalDatabaseConfig((Map<String, Object>) request.get("relationalDatabaseConfig"));
if (request.containsKey("openSearchServiceConfig")) existing.setOpenSearchServiceConfig((Map<String, Object>) request.get("openSearchServiceConfig"));
if (request.containsKey("amazonBedrockRuntimeConfig")) existing.setAmazonBedrockRuntimeConfig((Map<String, Object>) request.get("amazonBedrockRuntimeConfig"));
dataSourceStore.put(apiKey(apiId, dataSourceName), existing);
return existing;
}
public void deleteDataSource(String apiId, String dataSourceName) {
getDataSource(apiId, dataSourceName);
dataSourceStore.delete(apiKey(apiId, dataSourceName));
}
private void deleteDataSourcesForApi(String apiId) {
dataSourceStore.scan(k -> k.startsWith(apiId + "::"))
.forEach(ds -> {
try {
dataSourceStore.delete(apiKey(apiId, ds.getName()));
} catch (Exception e) {
// ignore - already deleted
}
});
}
// ──────────────────────────── Resolvers ────────────────────────────
public Resolver createResolver(String apiId, Map<String, Object> request) {
getGraphqlApi(apiId);
String fieldName = (String) request.get("fieldName");
if (fieldName == null || fieldName.isBlank()) {
throw new AwsException("BadRequestException", "A resolver field name is required", 400);
}
String dataSourceName = (String) request.get("dataSourceName");
if (dataSourceName == null || dataSourceName.isBlank()) {
throw new AwsException("BadRequestException", "A data source name is required for the resolver", 400);
}
Resolver resolver = new Resolver();
resolver.setApiId(apiId);
resolver.setTypeName((String) request.get("typeName"));
resolver.setFieldName((String) request.get("fieldName"));
resolver.setDataSourceName((String) request.get("dataSourceName"));
resolver.setFunctionId((String) request.get("functionId"));
resolver.setRequestMappingTemplate((String) request.get("requestMappingTemplate"));
resolver.setResponseMappingTemplate((String) request.get("responseMappingTemplate"));
resolver.setKind(parseEnum(ResolverKind.class, request.getOrDefault("kind", "UNIT")));
resolver.setCode((String) request.get("code"));
Map<String, Object> runtime = (Map<String, Object>) request.get("runtime");
if (runtime != null) {
Resolver.ResolverRuntime rt = new Resolver.ResolverRuntime();
rt.setName(parseEnum(ResolverRuntimeName.class, runtime.get("name")));
rt.setRuntimeVersion((String) runtime.get("runtimeVersion"));
resolver.setRuntime(rt);
}
String key = resolverKey(apiId, resolver.getTypeName(), resolver.getFieldName());
resolverStore.put(key, resolver);
return resolver;
}
public Resolver getResolver(String apiId, String typeName, String fieldName) {
return resolverStore.get(resolverKey(apiId, typeName, fieldName))
.orElseThrow(() -> new AwsException("NotFoundException",
"Resolver not found: " + typeName + "." + fieldName, 404));
}
public Page<Resolver> listResolvers(String apiId, Integer maxResults, String nextToken) {
return paginate(resolverStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults);
}
public Page<Resolver> listResolversByType(String apiId, String typeName, Integer maxResults, String nextToken) {
List<Resolver> filtered = resolverStore.scan(k -> k.startsWith(apiId + "::")).stream()
.filter(r -> typeName.equals(r.getTypeName()))
.toList();
return paginate(filtered, nextToken, maxResults);
}
public Page<Resolver> listResolversByFunction(String apiId, String functionId, Integer maxResults, String nextToken) {
getFunction(apiId, functionId);
List<Resolver> all = resolverStore.scan(k -> k.startsWith(apiId + "::")).stream()
.filter(r -> functionId.equals(r.getFunctionId()))
.toList();
return paginate(all, nextToken, maxResults);
}
public Resolver updateResolver(String apiId, String typeName, String fieldName, Map<String, Object> request) {
Resolver existing = getResolver(apiId, typeName, fieldName);
if (request.containsKey("dataSourceName")) existing.setDataSourceName((String) request.get("dataSourceName"));
if (request.containsKey("functionId")) existing.setFunctionId((String) request.get("functionId"));
if (request.containsKey("requestMappingTemplate")) existing.setRequestMappingTemplate((String) request.get("requestMappingTemplate"));
if (request.containsKey("responseMappingTemplate")) existing.setResponseMappingTemplate((String) request.get("responseMappingTemplate"));
if (request.containsKey("kind")) existing.setKind(parseEnum(ResolverKind.class, request.get("kind")));
if (request.containsKey("code")) existing.setCode((String) request.get("code"));
if (request.containsKey("runtime")) {
Map<String, Object> runtime = (Map<String, Object>) request.get("runtime");
Resolver.ResolverRuntime rt = new Resolver.ResolverRuntime();
rt.setName(parseEnum(ResolverRuntimeName.class, runtime.get("name")));
rt.setRuntimeVersion((String) runtime.get("runtimeVersion"));
existing.setRuntime(rt);
}
resolverStore.put(resolverKey(apiId, typeName, fieldName), existing);
return existing;
}
public void deleteResolver(String apiId, String typeName, String fieldName) {
getResolver(apiId, typeName, fieldName);
resolverStore.delete(resolverKey(apiId, typeName, fieldName));
}
private void deleteResolversForApi(String apiId) {
resolverStore.scan(k -> k.startsWith(apiId + "::"))
.forEach(r -> resolverStore.delete(resolverKey(apiId, r.getTypeName(), r.getFieldName())));
}
// ──────────────────────────── Functions ────────────────────────────
public FunctionConfiguration createFunction(String apiId, Map<String, Object> request, String region) {
getGraphqlApi(apiId);
String name = (String) request.get("name");
if (name == null || name.isBlank()) {
throw new AwsException("BadRequestException", "A function name is required", 400);
}
FunctionConfiguration fn = new FunctionConfiguration();
fn.setFunctionId(generateShortId());
fn.setName((String) request.get("name"));
fn.setDescription((String) request.get("description"));
fn.setDataSourceName((String) request.get("dataSourceName"));
fn.setRequestMappingTemplate((String) request.get("requestMappingTemplate"));
fn.setResponseMappingTemplate((String) request.get("responseMappingTemplate"));
fn.setFunctionVersion((String) request.getOrDefault("functionVersion", "2018-05-29"));
fn.setArn(buildFunctionArn(apiId, fn.getFunctionId(), region));
fn.setCode((String) request.get("code"));
functionStore.put(apiKey(apiId, fn.getFunctionId()), fn);
return fn;
}
public FunctionConfiguration getFunction(String apiId, String functionId) {
return functionStore.get(apiKey(apiId, functionId))
.orElseThrow(() -> new AwsException("NotFoundException", "Function not found: " + functionId, 404));
}
public Page<FunctionConfiguration> listFunctions(String apiId, Integer maxResults, String nextToken) {
return paginate(functionStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults);
}
public FunctionConfiguration updateFunction(String apiId, String functionId, Map<String, Object> request) {
FunctionConfiguration existing = getFunction(apiId, functionId);
if (request.containsKey("description")) existing.setDescription((String) request.get("description"));
if (request.containsKey("dataSourceName")) existing.setDataSourceName((String) request.get("dataSourceName"));
if (request.containsKey("requestMappingTemplate")) existing.setRequestMappingTemplate((String) request.get("requestMappingTemplate"));
if (request.containsKey("responseMappingTemplate")) existing.setResponseMappingTemplate((String) request.get("responseMappingTemplate"));
if (request.containsKey("functionVersion")) existing.setFunctionVersion((String) request.get("functionVersion"));
if (request.containsKey("code")) existing.setCode((String) request.get("code"));
functionStore.put(apiKey(apiId, functionId), existing);
return existing;
}
public void deleteFunction(String apiId, String functionId) {
getFunction(apiId, functionId);
functionStore.delete(apiKey(apiId, functionId));
}
private void deleteFunctionsForApi(String apiId) {
functionStore.scan(k -> k.startsWith(apiId + "::"))
.forEach(fn -> functionStore.delete(apiKey(apiId, fn.getFunctionId())));
}
// ──────────────────────────── Types ────────────────────────────
public AppSyncType createType(String apiId, Map<String, Object> request) {
getGraphqlApi(apiId);
String name = (String) request.get("name");
String definition = (String) request.get("definition");
if (name == null || name.isBlank()) {
name = extractTypeNameFromDefinition(definition);
}
if (name == null || name.isBlank()) {
throw new AwsException("BadRequestException", "A type name is required", 400);
}
AppSyncType type = new AppSyncType();
type.setApiId(apiId);
type.setName(name);
type.setDefinition((String) request.get("definition"));
type.setDescription((String) request.get("description"));
type.setFormat(parseEnum(TypeFormat.class, request.getOrDefault("format", "SDL")));
typeStore.put(apiKey(apiId, type.getName()), type);
return type;
}
public AppSyncType getType(String apiId, String typeName) {
return typeStore.get(apiKey(apiId, typeName))
.orElseThrow(() -> new AwsException("NotFoundException", "Type not found: " + typeName, 404));
}
public Page<AppSyncType> listTypes(String apiId, Integer maxResults, String nextToken) {
return paginate(typeStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults);
}
public AppSyncType updateType(String apiId, String typeName, Map<String, Object> request) {
AppSyncType existing = getType(apiId, typeName);
if (request.containsKey("definition")) existing.setDefinition((String) request.get("definition"));
if (request.containsKey("description")) existing.setDescription((String) request.get("description"));
if (request.containsKey("format")) existing.setFormat(parseEnum(TypeFormat.class, request.get("format")));
typeStore.put(apiKey(apiId, typeName), existing);
return existing;
}
public void deleteType(String apiId, String typeName) {
getType(apiId, typeName);
typeStore.delete(apiKey(apiId, typeName));
}
private void deleteTypesForApi(String apiId) {
typeStore.scan(k -> k.startsWith(apiId + "::"))
.forEach(t -> typeStore.delete(apiKey(apiId, t.getName())));
}
// ──────────────────────────── API Keys ────────────────────────────
public ApiKey createApiKey(String apiId, Map<String, Object> request) {
getGraphqlApi(apiId);
ApiKey key = new ApiKey();
key.setId(generateShortId());
key.setApiId(apiId);
key.setDescription((String) request.get("description"));
Object expiresValue = request.get("expires");
if (expiresValue instanceof Long l) {
key.setExpires(l);
} else if (expiresValue instanceof Number n) {
key.setExpires(n.longValue());
} else if (expiresValue instanceof String s) {
try {
key.setExpires(Long.parseLong(s));
} catch (NumberFormatException e) {
// try parsing as ISO date and convert to epoch seconds
key.setExpires(null);
}
}
// Generate a simple API key string
key.setApiKey("da2-" + generateShortId());
apiKeyStore.put(apiKey(apiId, key.getId()), key);
return key;
}
public Page<ApiKey> listApiKeys(String apiId, Integer maxResults, String nextToken) {
return paginate(apiKeyStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults);
}
public ApiKey getApiKey(String apiId, String keyId) {
return apiKeyStore.get(apiKey(apiId, keyId))
.orElseThrow(() -> new AwsException("NotFoundException", "API key not found: " + keyId, 404));
}
public ApiKey updateApiKey(String apiId, String keyId, Map<String, Object> request) {
ApiKey existing = getApiKey(apiId, keyId);
if (request.containsKey("description")) existing.setDescription((String) request.get("description"));
if (request.containsKey("expires")) {
Object expiresValue = request.get("expires");
if (expiresValue instanceof Long l) {
existing.setExpires(l);
} else if (expiresValue instanceof Number n) {
existing.setExpires(n.longValue());
} else if (expiresValue instanceof String s) {
try {
existing.setExpires(Long.parseLong(s));
} catch (NumberFormatException e) {
// keep existing
}
}
}
apiKeyStore.put(apiKey(apiId, keyId), existing);
return existing;
}
public void deleteApiKey(String apiId, String keyId) {
getApiKey(apiId, keyId);
apiKeyStore.delete(apiKey(apiId, keyId));
}
private void deleteApiKeysForApi(String apiId) {
apiKeyStore.scan(k -> k.startsWith(apiId + "::"))
.forEach(k -> apiKeyStore.delete(apiKey(apiId, k.getId())));
}
// ──────────────────────────── Tags ────────────────────────────
public Map<String, String> getTags(String resourceArn) {
String apiId = extractApiIdFromArn(resourceArn);
return getGraphqlApi(apiId).getTags();
}
public void tagResource(String resourceArn, Map<String, String> tags) {
String apiId = extractApiIdFromArn(resourceArn);
GraphqlApi api = getGraphqlApi(apiId);
api.getTags().putAll(tags);
apiStore.put(apiId, api);
}
public void untagResource(String resourceArn, List<String> tagKeys) {
String apiId = extractApiIdFromArn(resourceArn);
GraphqlApi api = getGraphqlApi(apiId);
tagKeys.forEach(api.getTags()::remove);
apiStore.put(apiId, api);
}
// ──────────────────────────── Environment Variables ────────────────────────────
public Map<String, String> getEnvironmentVariables(String apiId) {
GraphqlApi api = getGraphqlApi(apiId);
Map<String, String> envVars = api.getEnvironmentVariables();
return envVars != null ? envVars : Map.of();
}
public Map<String, String> putEnvironmentVariables(String apiId, Map<String, String> environmentVariables) {
GraphqlApi api = getGraphqlApi(apiId);
api.setEnvironmentVariables(new HashMap<>(environmentVariables));
apiStore.put(apiId, api);
return api.getEnvironmentVariables();
}
// ──────────────────────────── Helpers ────────────────────────────
private String generateApiId() {
return UUID.randomUUID().toString().replace("-", "").substring(0, 26);
}
private String generateShortId() {
return UUID.randomUUID().toString().replace("-", "").substring(0, 7);
}
private String apiKey(String apiId, String name) {
return apiId + "::" + name;
}
private String resolverKey(String apiId, String typeName, String fieldName) {
return apiId + "::" + typeName + "::" + fieldName;
}
private String buildApiArn(String apiId, String region) {
return regionResolver.buildArn("appsync", region, "apis/" + apiId);
}
private String buildFunctionArn(String apiId, String functionId, String region) {
return regionResolver.buildArn("appsync", region, "apis/" + apiId + "/functions/" + functionId);
}
private String extractApiIdFromArn(String arn) {
if (arn == null) throw new AwsException("BadRequestException", "Invalid ARN", 400);
String[] parts = arn.split("/");
if (parts.length < 2) throw new AwsException("BadRequestException", "Invalid ARN format", 400);
return parts[parts.length - 1];
}
private String coerceString(Object value) {
if (value == null) return null;
if (value instanceof String s) return s;
return String.valueOf(value);
}
private <E extends Enum<E>> E parseEnum(Class<E> enumClass, Object value) {
if (value == null) return null;
String str = value instanceof String s ? s : String.valueOf(value);
try {
return Enum.valueOf(enumClass, str);
} catch (IllegalArgumentException e) {
throw new AwsException("BadRequestException",
"Invalid value '" + str + "' for " + enumClass.getSimpleName(), 400);
}
}
// ──────────────────────────── Pagination ────────────────────────────
record Page<T>(List<T> items, String nextToken) {}
static <T> Page<T> paginate(List<T> items, String nextToken, Integer maxResults) {
int start = decodeToken(nextToken);
if (start < 0 || start > items.size()) {
throw new AwsException("InvalidNextTokenException", "Invalid NextToken.", 400);
}
int limit = (maxResults == null || maxResults <= 0)
? items.size()
: Math.min(maxResults, items.size() - start);
int end = Math.min(items.size(), start + limit);
List<T> sliced = items.subList(start, end);
String next = (end < items.size()) ? encodeToken(end) : null;
return new Page<>(sliced, next);
}
static String encodeToken(int offset) {
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(Integer.toString(offset).getBytes(java.nio.charset.StandardCharsets.UTF_8));
}
static int decodeToken(String token) {
if (token == null || token.isEmpty()) {
return 0;
}
try {
byte[] decoded = Base64.getUrlDecoder().decode(token);
return Integer.parseInt(new String(decoded, java.nio.charset.StandardCharsets.UTF_8));
} catch (IllegalArgumentException e) {
return -1;
}
}
static String extractTypeNameFromDefinition(String definition) {
if (definition == null || definition.isBlank()) return null;
String trimmed = definition.strip();
// Match: type TypeName { ... } or input TypeName { ... } or enum TypeName { ... }
String[] parts = trimmed.split("\\s+");
if (parts.length >= 2) {
return parts[1].replaceAll("[{(].*", "");
}
return null;
}
}
@@ -0,0 +1,31 @@
package io.github.hectorvent.floci.services.appsync.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiKey {
private String id;
private String description;
private Long expires;
private String apiId;
private String apiKey;
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public Long getExpires() { return expires; }
public void setExpires(Long expires) { this.expires = expires; }
public String getApiId() { return apiId; }
public void setApiId(String apiId) { this.apiId = apiId; }
public String getApiKey() { return apiKey; }
public void setApiKey(String apiKey) { this.apiKey = apiKey; }
}
@@ -0,0 +1,31 @@
package io.github.hectorvent.floci.services.appsync.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AppSyncType {
private String name;
private String definition;
private String description;
private String apiId;
private TypeFormat format;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDefinition() { return definition; }
public void setDefinition(String definition) { this.definition = definition; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getApiId() { return apiId; }
public void setApiId(String apiId) { this.apiId = apiId; }
public TypeFormat getFormat() { return format; }
public void setFormat(TypeFormat format) { this.format = format; }
}
@@ -0,0 +1,9 @@
package io.github.hectorvent.floci.services.appsync.model;
public enum AuthenticationType {
API_KEY,
AWS_IAM,
AMAZON_COGNITO_USER_POOLS,
OPENID_CONNECT,
AWS_LAMBDA
}
@@ -0,0 +1,57 @@
package io.github.hectorvent.floci.services.appsync.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DataSource {
private String name;
private String description;
private DataSourceType type;
private String serviceRoleArn;
private Map<String, Object> dynamodbConfig;
private Map<String, Object> lambdaConfig;
private Map<String, Object> httpConfig;
private Map<String, Object> eventBridgeConfig;
private Map<String, Object> relationalDatabaseConfig;
private Map<String, Object> openSearchServiceConfig;
private Map<String, Object> amazonBedrockRuntimeConfig;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public DataSourceType getType() { return type; }
public void setType(DataSourceType type) { this.type = type; }
public String getServiceRoleArn() { return serviceRoleArn; }
public void setServiceRoleArn(String serviceRoleArn) { this.serviceRoleArn = serviceRoleArn; }
public Map<String, Object> getDynamodbConfig() { return dynamodbConfig; }
public void setDynamodbConfig(Map<String, Object> dynamodbConfig) { this.dynamodbConfig = dynamodbConfig; }
public Map<String, Object> getLambdaConfig() { return lambdaConfig; }
public void setLambdaConfig(Map<String, Object> lambdaConfig) { this.lambdaConfig = lambdaConfig; }
public Map<String, Object> getHttpConfig() { return httpConfig; }
public void setHttpConfig(Map<String, Object> httpConfig) { this.httpConfig = httpConfig; }
public Map<String, Object> getEventBridgeConfig() { return eventBridgeConfig; }
public void setEventBridgeConfig(Map<String, Object> eventBridgeConfig) { this.eventBridgeConfig = eventBridgeConfig; }
public Map<String, Object> getRelationalDatabaseConfig() { return relationalDatabaseConfig; }
public void setRelationalDatabaseConfig(Map<String, Object> config) { this.relationalDatabaseConfig = config; }
public Map<String, Object> getOpenSearchServiceConfig() { return openSearchServiceConfig; }
public void setOpenSearchServiceConfig(Map<String, Object> config) { this.openSearchServiceConfig = config; }
public Map<String, Object> getAmazonBedrockRuntimeConfig() { return amazonBedrockRuntimeConfig; }
public void setAmazonBedrockRuntimeConfig(Map<String, Object> config) { this.amazonBedrockRuntimeConfig = config; }
}
@@ -0,0 +1,12 @@
package io.github.hectorvent.floci.services.appsync.model;
public enum DataSourceType {
NONE,
AWS_LAMBDA,
AMAZON_DYNAMODB,
HTTP,
AMAZON_EVENTBRIDGE,
RELATIONAL_DATABASE,
AMAZON_OPENSEARCH_SERVICE,
AMAZON_BEDROCK_RUNTIME
}
@@ -0,0 +1,47 @@
package io.github.hectorvent.floci.services.appsync.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class FunctionConfiguration {
private String functionId;
private String name;
private String description;
private String dataSourceName;
private String requestMappingTemplate;
private String responseMappingTemplate;
private String functionVersion;
private String arn;
private String code;
public String getFunctionId() { return functionId; }
public void setFunctionId(String functionId) { this.functionId = functionId; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getDataSourceName() { return dataSourceName; }
public void setDataSourceName(String dataSourceName) { this.dataSourceName = dataSourceName; }
public String getRequestMappingTemplate() { return requestMappingTemplate; }
public void setRequestMappingTemplate(String template) { this.requestMappingTemplate = template; }
public String getResponseMappingTemplate() { return responseMappingTemplate; }
public void setResponseMappingTemplate(String template) { this.responseMappingTemplate = template; }
public String getFunctionVersion() { return functionVersion; }
public void setFunctionVersion(String functionVersion) { this.functionVersion = functionVersion; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getCode() { return code; }
public void setCode(String code) { this.code = code; }
}
@@ -0,0 +1,56 @@
package io.github.hectorvent.floci.services.appsync.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class GraphqlApi {
private String apiId;
private String name;
private String arn;
private AuthenticationType authenticationType;
private Map<String, String> uris = new HashMap<>();
private Map<String, Object> logConfig;
private List<Map<String, Object>> additionalAuthenticationProviders;
private Boolean xrayEnabled;
private Map<String, String> tags = new HashMap<>();
private Map<String, String> environmentVariables = new HashMap<>();
public String getApiId() { return apiId; }
public void setApiId(String apiId) { this.apiId = apiId; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public AuthenticationType getAuthenticationType() { return authenticationType; }
public void setAuthenticationType(AuthenticationType authenticationType) { this.authenticationType = authenticationType; }
public Map<String, String> getUris() { return uris; }
public void setUris(Map<String, String> uris) { this.uris = uris; }
public Map<String, Object> getLogConfig() { return logConfig; }
public void setLogConfig(Map<String, Object> logConfig) { this.logConfig = logConfig; }
public List<Map<String, Object>> getAdditionalAuthenticationProviders() { return additionalAuthenticationProviders; }
public void setAdditionalAuthenticationProviders(List<Map<String, Object>> providers) { this.additionalAuthenticationProviders = providers; }
public Boolean getXrayEnabled() { return xrayEnabled; }
public void setXrayEnabled(Boolean xrayEnabled) { this.xrayEnabled = xrayEnabled; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public Map<String, String> getEnvironmentVariables() { return environmentVariables; }
public void setEnvironmentVariables(Map<String, String> environmentVariables) { this.environmentVariables = environmentVariables; }
}
@@ -0,0 +1,65 @@
package io.github.hectorvent.floci.services.appsync.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Resolver {
private String apiId;
private String typeName;
private String fieldName;
private String dataSourceName;
private String functionId;
private String requestMappingTemplate;
private String responseMappingTemplate;
private ResolverKind kind;
private String code;
private ResolverRuntime runtime;
public String getApiId() { return apiId; }
public void setApiId(String apiId) { this.apiId = apiId; }
public String getTypeName() { return typeName; }
public void setTypeName(String typeName) { this.typeName = typeName; }
public String getFieldName() { return fieldName; }
public void setFieldName(String fieldName) { this.fieldName = fieldName; }
public String getDataSourceName() { return dataSourceName; }
public void setDataSourceName(String dataSourceName) { this.dataSourceName = dataSourceName; }
public String getFunctionId() { return functionId; }
public void setFunctionId(String functionId) { this.functionId = functionId; }
public String getRequestMappingTemplate() { return requestMappingTemplate; }
public void setRequestMappingTemplate(String template) { this.requestMappingTemplate = template; }
public String getResponseMappingTemplate() { return responseMappingTemplate; }
public void setResponseMappingTemplate(String template) { this.responseMappingTemplate = template; }
public ResolverKind getKind() { return kind; }
public void setKind(ResolverKind kind) { this.kind = kind; }
public String getCode() { return code; }
public void setCode(String code) { this.code = code; }
public ResolverRuntime getRuntime() { return runtime; }
public void setRuntime(ResolverRuntime runtime) { this.runtime = runtime; }
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class ResolverRuntime {
private ResolverRuntimeName name;
private String runtimeVersion;
public ResolverRuntimeName getName() { return name; }
public void setName(ResolverRuntimeName name) { this.name = name; }
public String getRuntimeVersion() { return runtimeVersion; }
public void setRuntimeVersion(String runtimeVersion) { this.runtimeVersion = runtimeVersion; }
}
}
@@ -0,0 +1,6 @@
package io.github.hectorvent.floci.services.appsync.model;
public enum ResolverKind {
UNIT,
PIPELINE
}
@@ -0,0 +1,6 @@
package io.github.hectorvent.floci.services.appsync.model;
public enum ResolverRuntimeName {
APPSYNC_JS,
VTL
}
@@ -0,0 +1,19 @@
package io.github.hectorvent.floci.services.appsync.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SchemaCreationStatus {
private SchemaCreationStatusType status;
private String details;
public SchemaCreationStatusType getStatus() { return status; }
public void setStatus(SchemaCreationStatusType status) { this.status = status; }
public String getDetails() { return details; }
public void setDetails(String details) { this.details = details; }
}
@@ -0,0 +1,10 @@
package io.github.hectorvent.floci.services.appsync.model;
public enum SchemaCreationStatusType {
PROCESSING,
ACTIVE,
DELETING,
FAILED,
SUCCESS,
NOT_APPLICABLE
}
@@ -0,0 +1,6 @@
package io.github.hectorvent.floci.services.appsync.model;
public enum TypeFormat {
SDL,
JSON
}