fix(appsync): keep GraphQL APIs and custom domain names in their Region (#8745)

This commit is contained in:
mrfelek authored and GitHub committed 2026-11-17 19:09:57 -04:00
1 parent 1942378624
commit f0c234485b
23 files changed
+526 -138

No files matched your search

@@ -301,6 +301,19 @@ public class RegionResolver {
return defaultRegion;
}
/**
* The Region {@code arn} names: the default Region for a record stored without an ARN, or with one that names
* none, as records stored before their service kept them per Region are.
*/
public String regionOf(String arn) {
return AwsArnUtils.regionOrDefault(arn, getDefaultRegion());
}
/** Whether a resource whose ARN is {@code arn} is of the request's Region, as {@link #regionOf} reads it. */
public boolean inRequestRegion(String arn) {
return getRegion().equals(regionOf(arn));
}
/**
* Returns the account ID for the current request when called from a request context,
* or the configured default account ID otherwise (async workers, startup, tests).
@@ -7,8 +7,6 @@ import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.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;
@@ -42,8 +40,8 @@ public class AppSyncController {
@POST
@Path("/v1/apis")
public Response createGraphqlApi(@Context HttpHeaders headers, String body) throws IOException {
String region = regionResolver.resolveRegion(headers);
public Response createGraphqlApi(String body) throws IOException {
String region = regionResolver.getRegion();
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
GraphqlApi api = service.createGraphqlApi(request, region);
@@ -63,10 +61,9 @@ public class AppSyncController {
@POST
@Path("/v1/apis/{apiId}")
public Response updateGraphqlApi(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
public Response updateGraphqlApi(@PathParam("apiId") String apiId,
String body) throws IOException {
String region = regionResolver.resolveRegion(headers);
String region = regionResolver.getRegion();
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
GraphqlApi api = service.updateGraphqlApi(apiId, request, region);
@@ -137,10 +134,9 @@ public class AppSyncController {
@POST
@Path("/v1/apis/{apiId}/datasources")
public Response createDataSource(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
public Response createDataSource(@PathParam("apiId") String apiId,
String body) throws IOException {
String region = regionResolver.resolveRegion(headers);
String region = regionResolver.getRegion();
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
DataSource ds = service.createDataSource(apiId, request, region);
@@ -200,11 +196,10 @@ public class AppSyncController {
@POST
@Path("/v1/apis/{apiId}/types/{typeName}/resolvers")
public Response createResolver(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
public Response createResolver(@PathParam("apiId") String apiId,
@PathParam("typeName") String typeName,
String body) throws IOException {
String region = regionResolver.resolveRegion(headers);
String region = regionResolver.getRegion();
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
request.put("typeName", typeName);
@@ -288,9 +283,8 @@ public class AppSyncController {
@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);
public Response createFunction(@PathParam("apiId") String apiId, String body) throws IOException {
String region = regionResolver.getRegion();
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
FunctionConfiguration fn = service.createFunction(apiId, request, region);
@@ -637,10 +631,9 @@ public class AppSyncController {
@POST
@Path("/v1/sourceApis/{sourceApiIdentifier}/mergedApiAssociations")
public Response associateMergedGraphqlApi(@Context HttpHeaders headers,
@PathParam("sourceApiIdentifier") String sourceApiIdentifier,
public Response associateMergedGraphqlApi(@PathParam("sourceApiIdentifier") String sourceApiIdentifier,
String body) throws IOException {
String region = regionResolver.resolveRegion(headers);
String region = regionResolver.getRegion();
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
SourceApiAssociation assoc = service.createMergedApiAssociation(sourceApiIdentifier, request, region);
@@ -651,10 +644,9 @@ public class AppSyncController {
@POST
@Path("/v1/mergedApis/{mergedApiIdentifier}/sourceApiAssociations")
public Response associateSourceGraphqlApi(@Context HttpHeaders headers,
@PathParam("mergedApiIdentifier") String mergedApiIdentifier,
public Response associateSourceGraphqlApi(@PathParam("mergedApiIdentifier") String mergedApiIdentifier,
String body) throws IOException {
String region = regionResolver.resolveRegion(headers);
String region = regionResolver.getRegion();
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
SourceApiAssociation assoc = service.createSourceApiAssociation(mergedApiIdentifier, request, region);
@@ -80,14 +80,20 @@ public class AppSyncService {
this.apiStore = storageFactory.create("appsync", "appsync-apis.json", new TypeReference<>() {});
this.schemaStore = schemaStore;
this.schemaStatusStore = schemaStatusStore;
this.dataSourceStore = storageFactory.create("appsync", "appsync-datasources.json", new TypeReference<>() {});
this.resolverStore = storageFactory.create("appsync", "appsync-resolvers.json", new TypeReference<>() {});
this.functionStore = storageFactory.create("appsync", "appsync-functions.json", new TypeReference<>() {});
this.apiKeyStore = storageFactory.create("appsync", "appsync-apikeys.json", new TypeReference<>() {});
this.typeStore = storageFactory.create("appsync", "appsync-types.json", new TypeReference<>() {});
this.dataSourceStore = apiResources(storageFactory.create("appsync", "appsync-datasources.json",
new TypeReference<Map<String, DataSource>>() {}));
this.resolverStore = apiResources(storageFactory.create("appsync", "appsync-resolvers.json",
new TypeReference<Map<String, Resolver>>() {}));
this.functionStore = apiResources(storageFactory.create("appsync", "appsync-functions.json",
new TypeReference<Map<String, FunctionConfiguration>>() {}));
this.apiKeyStore = apiResources(storageFactory.create("appsync", "appsync-apikeys.json",
new TypeReference<Map<String, ApiKey>>() {}));
this.typeStore = apiResources(storageFactory.create("appsync", "appsync-types.json",
new TypeReference<Map<String, AppSyncType>>() {}));
this.domainStore = storageFactory.create("appsync", "appsync-domainnames.json", new TypeReference<>() {});
this.associationStore = storageFactory.create("appsync", "appsync-associations.json", new TypeReference<>() {});
this.channelNamespaceStore = storageFactory.create("appsync", "appsync-channelnamespaces.json", new TypeReference<>() {});
this.channelNamespaceStore = apiResources(storageFactory.create("appsync", "appsync-channelnamespaces.json",
new TypeReference<Map<String, ChannelNamespace>>() {}));
this.mergedApiAssociationStore = storageFactory.create("appsync", "appsync-merged-api-associations.json", new TypeReference<>() {});
this.regionResolver = regionResolver;
this.schemaRegistry = schemaRegistry;
@@ -166,8 +172,10 @@ public class AppSyncService {
return api;
}
/** The request's Region's GraphQL API {@code apiId}: another Region's is not found, as one that doesn't exist. */
public GraphqlApi getGraphqlApi(String apiId) {
return apiStore.get(apiId)
.filter(api -> regionResolver.inRequestRegion(api.getArn()))
.map(this::refreshGraphqlApiUris)
.orElseThrow(() -> new AwsException("NotFoundException", "GraphQL API not found: " + apiId, 404));
}
@@ -175,7 +183,9 @@ public class AppSyncService {
public Page<GraphqlApi> listGraphqlApis(Integer maxResults, String nextToken) {
List<GraphqlApi> apis = new ArrayList<>();
for (GraphqlApi stored : apiStore.scan(k -> true)) {
apis.add(refreshGraphqlApiUris(stored));
if (regionResolver.inRequestRegion(stored.getArn())) {
apis.add(refreshGraphqlApiUris(stored));
}
}
return paginate(apis, nextToken, maxResults);
}
@@ -287,7 +297,10 @@ public class AppSyncService {
* creation is in flight.
*/
void assertSchemaNotBusy(String apiId) {
schemaStatusStore.getForAccount(currentAccountId(), apiId).ifPresent(s -> throwIfProcessing(s.getStatus()));
// Another Region's API doesn't exist here: the operation's own lookup answers NotFoundException.
schemaStatusStore.getForAccount(currentAccountId(), apiId)
.filter(status -> status.getStatus() == SchemaCreationStatusType.PROCESSING && apiInRequestRegion(apiId))
.ifPresent(status -> throwIfProcessing(status.getStatus()));
}
/**
@@ -718,22 +731,29 @@ public class AppSyncService {
// ──────────────────────────── Tags ────────────────────────────
public Map<String, String> getTags(String resourceArn) {
String apiId = extractApiIdFromArn(resourceArn);
return getGraphqlApi(apiId).getTags();
return taggedApi(resourceArn).getTags();
}
public synchronized void tagResource(String resourceArn, Map<String, String> tags) {
String apiId = extractApiIdFromArn(resourceArn);
GraphqlApi api = getGraphqlApi(apiId);
GraphqlApi api = taggedApi(resourceArn);
api.getTags().putAll(tags);
apiStore.put(apiId, api);
apiStore.put(api.getApiId(), api);
}
public synchronized void untagResource(String resourceArn, List<String> tagKeys) {
GraphqlApi api = taggedApi(resourceArn);
tagKeys.forEach(api.getTags()::remove);
apiStore.put(api.getApiId(), api);
}
/** The API {@code resourceArn} names: the request's Region's API whose ARN it is, partition, Region and account. */
private GraphqlApi taggedApi(String resourceArn) {
String apiId = extractApiIdFromArn(resourceArn);
GraphqlApi api = getGraphqlApi(apiId);
tagKeys.forEach(api.getTags()::remove);
apiStore.put(apiId, api);
if (!resourceArn.equals(api.getArn())) {
throw new AwsException("NotFoundException", "GraphQL API not found: " + apiId, 404);
}
return api;
}
// ──────────────────────────── Environment Variables ────────────────────────────
@@ -795,13 +815,16 @@ public class AppSyncService {
dn.setHostedZoneId(edge.hostedZoneId());
}
/** The request's Region's domain name: another Region's is not found, as one that doesn't exist. */
public DomainName getDomainName(String domainName) {
return domainStore.get(domainName)
.filter(dn -> regionResolver.inRequestRegion(dn.getDomainNameArn()))
.orElseThrow(() -> new AwsException("NotFoundException", "Domain name not found: " + domainName, 404));
}
public Page<DomainName> listDomainNames(Integer maxResults, String nextToken) {
return paginate(domainStore.scan(k -> true), nextToken, maxResults);
return paginate(domainStore.scan(k -> true).stream()
.filter(dn -> regionResolver.inRequestRegion(dn.getDomainNameArn())).toList(), nextToken, maxResults);
}
public synchronized DomainName updateDomainName(String domainName, Map<String, Object> request) {
@@ -871,7 +894,7 @@ public class AppSyncService {
ns.setName(name);
ns.setApiId(apiId);
ns.setDescription((String) request.get("description"));
ns.setChannelNamespaceArn(regionResolver.buildArn("appsync", apiRegion(api),
ns.setChannelNamespaceArn(regionResolver.buildArn("appsync", regionResolver.regionOf(api.getArn()),
"apis/" + apiId + "/channelNamespaces/" + name));
ns.setCodeHandlers((String) request.get("codeHandlers"));
ns.setCreated(System.currentTimeMillis());
@@ -964,8 +987,13 @@ public class AppSyncService {
return assoc;
}
/**
* The request's Region's association {@code associationId} of {@code mergedApiIdentifier}. It is the Region its own
* ARN names, not the APIs': an association outlives a source API deleted without it, and can still be removed.
*/
public SourceApiAssociation getSourceApiAssociation(String mergedApiIdentifier, String associationId) {
SourceApiAssociation assoc = mergedApiAssociationStore.get(associationId)
.filter(a -> regionResolver.inRequestRegion(a.getAssociationArn()))
.orElseThrow(() -> new AwsException("NotFoundException",
"Source API association not found: " + associationId, 404));
if (!mergedApiIdentifier.equals(assoc.getMergedApiId())) {
@@ -1001,6 +1029,7 @@ public class AppSyncService {
public Page<SourceApiAssociationSummary> listSourceApiAssociations(String apiId, Integer maxResults, String nextToken) {
List<SourceApiAssociationSummary> summaries = mergedApiAssociationStore.scan(k -> true).stream()
.filter(a -> apiId.equals(a.getMergedApiId()) || apiId.equals(a.getSourceApiId()))
.filter(a -> regionResolver.inRequestRegion(a.getAssociationArn()))
.map(this::toSummary)
.toList();
return paginate(summaries, nextToken, maxResults);
@@ -1027,6 +1056,7 @@ public class AppSyncService {
public synchronized SourceApiAssociation deleteMergedApiAssociation(String sourceApiIdentifier, String associationId) {
assertSchemaNotBusy(sourceApiIdentifier);
SourceApiAssociation assoc = mergedApiAssociationStore.get(associationId)
.filter(a -> regionResolver.inRequestRegion(a.getAssociationArn()))
.orElseThrow(() -> new AwsException("NotFoundException",
"Source API association not found: " + associationId, 404));
if (!sourceApiIdentifier.equals(assoc.getSourceApiId())) {
@@ -1205,12 +1235,25 @@ public class AppSyncService {
return apiId + "::" + typeName + "::" + fieldName;
}
/** The region of an API's ARN, where its child resources live; the request region if it has none. */
private String apiRegion(GraphqlApi api) {
if (api.getArn() != null && AwsArnUtils.isArn(api.getArn())) {
return AwsArnUtils.parse(api.getArn()).region();
}
return regionResolver.getRegion();
/** The request's Region's view of {@code store}, a store of the APIs' resources ({@link RegionalApiResources}). */
private <V> StorageBackend<String, V> apiResources(StorageBackend<String, V> store) {
return new RegionalApiResources<>(store, this::apiInRequestRegion);
}
/**
* Whether {@code apiId} is a GraphQL API of the request's Region, or of no stored API: the resources of another
* Region's are hidden from the request ({@link RegionalApiResources}).
*/
private boolean apiInRequestRegion(String apiId) {
return apiStore.get(apiId).map(api -> regionResolver.inRequestRegion(api.getArn())).orElse(true);
}
/**
* The Region of the GraphQL API {@code apiId}, whatever Region the request is in. The data plane reaches an API by
* its own endpoint, which names no Region, and runs in the API's.
*/
public Optional<String> graphqlApiRegion(String apiId) {
return apiStore.get(apiId).map(api -> regionResolver.regionOf(api.getArn()));
}
private String buildApiArn(String apiId, String region) {
@@ -0,0 +1,93 @@
package io.floci.aws.services.appsync;
import io.floci.aws.core.storage.StorageBackend;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* The request's Region's view of a store of GraphQL APIs' resources (data sources, resolvers, functions, types, API
* keys, channel namespaces), each keyed {@code <apiId>::...}. A resource of an API of another Region is absent here,
* as a deleted API's is, so every operation answers for it as for one that doesn't exist. Writes go through: an
* operation finds its API, in the request's Region, before it stores one.
*/
final class RegionalApiResources<V> implements StorageBackend<String, V> {
private static final String SEPARATOR = "::";
private final StorageBackend<String, V> delegate;
private final Predicate<String> apiInRequestRegion;
/** {@code apiInRequestRegion} tells whether an API id is of the request's Region, or of no stored API. */
RegionalApiResources(StorageBackend<String, V> delegate, Predicate<String> apiInRequestRegion) {
this.delegate = delegate;
this.apiInRequestRegion = apiInRequestRegion;
}
@Override
public void put(String key, V value) {
delegate.put(key, value);
}
@Override
public void putAll(Map<String, V> entries) {
delegate.putAll(entries);
}
@Override
public void putAllAtomically(Map<String, V> entries) {
delegate.putAllAtomically(entries);
}
@Override
public Optional<V> get(String key) {
return visible(key) ? delegate.get(key) : Optional.empty();
}
@Override
public void delete(String key) {
if (visible(key)) {
delegate.delete(key);
}
}
@Override
public void deleteAllAtomically(Set<String> keys) {
delegate.deleteAllAtomically(keys.stream().filter(this::visible).collect(Collectors.toSet()));
}
@Override
public List<V> scan(Predicate<String> keyFilter) {
return delegate.scan(key -> keyFilter.test(key) && visible(key));
}
@Override
public Set<String> keys() {
return delegate.keys().stream().filter(this::visible).collect(Collectors.toSet());
}
/** Clears what this view holds, the request's Region's APIs' resources, as {@code RegionScopedStorage} does. */
@Override
public void clear() {
keys().forEach(delegate::delete);
}
@Override
public void flush() {
delegate.flush();
}
@Override
public void load() {
delegate.load();
}
private boolean visible(String key) {
int separator = key.indexOf(SEPARATOR);
return separator < 0 || apiInRequestRegion.test(key.substring(0, separator));
}
}
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestContext;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
import io.floci.aws.services.appsync.AppSyncService;
import io.floci.aws.services.appsync.GraphqlSidecarClient;
@@ -105,11 +106,30 @@ public class AppSyncExecutionController {
this.reachableEndpoint = reachableEndpoint;
}
/**
* An API's endpoint names no Region, so a request reaches the API whatever Region it is signed for, or none with
* an API key, and runs in the API's Region, where its data sources, resolvers and functions are. A request for an
* API that doesn't exist is answered as before.
*/
@POST
@Path("/v1/apis/{apiId}/graphql")
public Response execute(@PathParam("apiId") String apiId,
@Context HttpHeaders headers,
String body) {
Optional<String> apiRegion;
try {
apiRegion = appSyncService.graphqlApiRegion(apiId);
} catch (RuntimeException e) {
// Stay on the data-plane errors envelope, as a failed lookup of the API itself does.
LOG.errorv(e, "Unexpected failure looking up API {0}", apiId);
return graphqlError(500, "InternalFailure", "InternalFailure");
}
return apiRegion
.map(region -> RequestScopes.callAs(null, region, () -> executeInItsRegion(apiId, headers, body)))
.orElseGet(() -> executeInItsRegion(apiId, headers, body));
}
private Response executeInItsRegion(String apiId, HttpHeaders headers, String body) {
try {
if (!isAcceptedContentType(headers)) {
return graphqlError(400, "MalformedHttpRequestException",
@@ -316,7 +316,7 @@ public class CloudControlService {
private void submitCreate(String region, String accountId, String typeName, String desiredStateJson,
String token, ProgressEvent pending, JsonNode props, boolean replay) {
persistRequest(new PersistedRequest(pending, region, desiredStateJson, System.currentTimeMillis()));
Runnable task = () -> RequestScopes.runAs(accountId, () -> {
Runnable task = () -> RequestScopes.runAs(accountId, region, () -> {
try {
StackResource resource = provisioner.provisionStandalone(typeName, props, region, accountId);
if (resource == null || resource.getPhysicalId() == null) {
@@ -510,7 +510,7 @@ public class CloudControlService {
+ "not hold for " + identifier + ".", null, accountId));
}
RequestScopes.runAs(accountId,
RequestScopes.runAs(accountId, region,
() -> provisioner.deleteStandalone(typeName, identifier, region, attributes));
created.remove(key);
removePersistedCreated(accountId, region, typeName, identifier);
@@ -559,11 +559,6 @@ public class DocDbService {
}
}
/** The region a record was created in, taken from its ARN; older records carry the default. */
private String regionOf(String arn) {
return AwsArnUtils.regionOrDefault(arn, regionResolver.getDefaultRegion());
}
/**
* Whether an ARN names a DocumentDB cluster or instance, matched against the stored ARN.
*
@@ -522,12 +522,12 @@ public class ElastiCacheQueryHandler {
// Cache clusters are stored per account; like AWS, only the request's Region's are listed.
List<ElastiCacheService.MemberCacheCluster> members = service.listMemberCacheClusters(filterId);
List<CacheCluster> clusterList = new ArrayList<>(service.findCacheClusters(filterId).stream()
.filter(c -> service.inRequestRegion(c.getArn())).toList());
.filter(c -> regionResolver.inRequestRegion(c.getArn())).toList());
// The Memcached lookup is the one that raises CacheClusterNotFound for an unknown id,
// which is the right answer only once no other source has answered.
if (!filtered || (members.isEmpty() && clusterList.isEmpty())) {
memcachedService.listCacheClusters(filterId).stream()
.filter(c -> service.inRequestRegion(c.getArn()))
.filter(c -> regionResolver.inRequestRegion(c.getArn()))
.forEach(clusterList::add);
if (filtered && clusterList.isEmpty()) {
throw new AwsException("CacheClusterNotFound", "Cache cluster " + filterId + " not found.", 404);
@@ -919,21 +919,6 @@ public class ElastiCacheService implements ResourceProvider {
}
}
/** The region in a restored resource's ARN; one recorded without an ARN counts as the default region's. */
private String regionOf(String arn) {
return AwsArnUtils.regionOrDefault(arn, regionResolver.getDefaultRegion());
}
/**
* Whether a resource belongs to the request's Region. Replication groups, cache clusters (including
* Memcached ones, which DescribeCacheClusters lists too), users and user groups are stored per account;
* like AWS, the Describe* listings only show the requesting Region's.
* The getters stay unscoped: credential lookups, restore and validation run outside a request.
*/
boolean inRequestRegion(String arn) {
return regionResolver.getRegion().equals(regionOf(arn));
}
/**
* Restarts the container and auth proxy behind a standalone Redis or Valkey cache cluster,
* the same pair {@link #provisionCacheCluster} creates. The cache comes back empty, as it
@@ -954,7 +939,8 @@ public class ElastiCacheService implements ResourceProvider {
String clusterId = cluster.getCacheClusterId();
String image = config.services().elasticache().defaultImage();
try {
ElastiCacheContainerHandle handle = containerManager.tryStart(clusterId, image, regionOf(cluster.getArn()));
ElastiCacheContainerHandle handle = containerManager.tryStart(clusterId, image,
regionResolver.regionOf(cluster.getArn()));
synchronized (lockFor("cc:" + clusterId)) {
if (cacheClusterRestoreTargetLost(accountId, clusterId)) {
abandonRestoredCacheClusterContainer(clusterId, handle);
@@ -1083,7 +1069,8 @@ public class ElastiCacheService implements ResourceProvider {
String groupId = group.getReplicationGroupId();
String image = config.services().elasticache().defaultImage();
try {
ElastiCacheContainerHandle handle = containerManager.tryStart(groupId, image, regionOf(group.getArn()));
ElastiCacheContainerHandle handle = containerManager.tryStart(groupId, image,
regionResolver.regionOf(group.getArn()));
synchronized (lockFor("rg:" + groupId)) {
if (restoreTargetLost(accountId, groupId)) {
abandonRestoredContainer(groupId, handle);
@@ -1221,7 +1208,8 @@ public class ElastiCacheService implements ResourceProvider {
inFlightMemberId = node.getMemberClusterId();
ElastiCacheContainerHandle handle = containerManager.start(
node.getMemberClusterId(), image,
clusterNodeFlags(endpointHost, announceIp, node.getProxyPort()), regionOf(group.getArn()));
clusterNodeFlags(endpointHost, announceIp, node.getProxyPort()),
regionResolver.regionOf(group.getArn()));
inFlightMemberId = null;
handles.add(handle);
node.setContainerId(handle.getContainerId());
@@ -1333,12 +1321,12 @@ public class ElastiCacheService implements ResourceProvider {
public Collection<ReplicationGroup> listReplicationGroups(String filterGroupId) {
if (filterGroupId != null && !filterGroupId.isBlank()) {
return groups.get(filterGroupId).filter(g -> inRequestRegion(g.getArn()))
return groups.get(filterGroupId).filter(g -> regionResolver.inRequestRegion(g.getArn()))
.map(List::of)
.orElseThrow(() -> new AwsException("ReplicationGroupNotFoundFault",
"Replication group " + filterGroupId + " not found.", 404));
}
return groups.scan(k -> true).stream().filter(g -> inRequestRegion(g.getArn())).toList();
return groups.scan(k -> true).stream().filter(g -> regionResolver.inRequestRegion(g.getArn())).toList();
}
public void deleteReplicationGroup(String groupId) {
@@ -1454,7 +1442,7 @@ public class ElastiCacheService implements ResourceProvider {
snapshot.setEngineVersion(group.getEngineVersion());
snapshot.setCacheNodeType(group.getCacheNodeType());
snapshot.setNumCacheClusters(group.getNumCacheClusters());
snapshot.setArn(regionResolver.buildArn("elasticache", regionOf(group.getArn()),
snapshot.setArn(regionResolver.buildArn("elasticache", regionResolver.regionOf(group.getArn()),
"snapshot:" + snapshotName));
snapshot.setCreatedAt(Instant.now());
snapshot.setSizeBytes(archive.length() * 3L / 4L);
@@ -2129,7 +2117,7 @@ public class ElastiCacheService implements ResourceProvider {
public List<MemberCacheCluster> listMemberCacheClusters(String filterClusterId) {
List<MemberCacheCluster> members = new ArrayList<>();
for (ReplicationGroup group : groups.scan(k -> true)) {
if (!inRequestRegion(group.getArn())) {
if (!regionResolver.inRequestRegion(group.getArn())) {
continue;
}
for (MemberCacheCluster member : memberCacheClusters(group)) {
@@ -2731,13 +2719,18 @@ public class ElastiCacheService implements ResourceProvider {
}
/**
* {@code user} as the request's Region lists it, or empty when it is another Region's. AWS has the built-in
* Replication groups, cache clusters (including Memcached ones, which DescribeCacheClusters lists too), users and
* user groups are stored per account; like AWS, the Describe* listings only show the requesting Region's
* ({@link RegionResolver#inRequestRegion}). The getters stay unscoped: credential lookups, restore and validation
* run outside a request.
*
* <p>{@code user} as the request's Region lists it, or empty when it is another Region's. AWS has the built-in
* default user in every Region; Floci seeds one per account, so it is listed in every Region, with that
* Region's ARN.
*/
private Optional<ElastiCacheUser> inRequestRegion(ElastiCacheUser user) {
if (!DEFAULT_USER_ID.equals(user.getUserId())) {
return inRequestRegion(user.getArn()) ? Optional.of(user) : Optional.empty();
return regionResolver.inRequestRegion(user.getArn()) ? Optional.of(user) : Optional.empty();
}
String arn = regionResolver.buildArn("elasticache", regionResolver.getRegion(), "user:" + DEFAULT_USER_ID);
if (arn.equals(user.getArn())) {
@@ -2911,12 +2904,12 @@ public class ElastiCacheService implements ResourceProvider {
public Collection<ElastiCacheUserGroup> listUserGroups(String filterUserGroupId) {
if (filterUserGroupId != null && !filterUserGroupId.isBlank()) {
ElastiCacheUserGroup userGroup = getUserGroup(filterUserGroupId);
if (!inRequestRegion(userGroup.getArn())) {
if (!regionResolver.inRequestRegion(userGroup.getArn())) {
throw userGroupNotFound(filterUserGroupId);
}
return List.of(userGroup);
}
return userGroups.scan(k -> true).stream().filter(g -> inRequestRegion(g.getArn())).toList();
return userGroups.scan(k -> true).stream().filter(g -> regionResolver.inRequestRegion(g.getArn())).toList();
}
public ElastiCacheUserGroup modifyUserGroup(String userGroupId, List<String> userIdsToAdd,
@@ -3026,7 +3019,7 @@ public class ElastiCacheService implements ResourceProvider {
/** The request Region's user groups the user is a member of, as DescribeUserGroups lists them there. */
public List<String> userGroupIdsContaining(String userId) {
return userGroups.scan(k -> true).stream()
.filter(g -> inRequestRegion(g.getArn()))
.filter(g -> regionResolver.inRequestRegion(g.getArn()))
.filter(g -> g.getUserIds().contains(userId))
.map(ElastiCacheUserGroup::getUserGroupId)
.toList();
@@ -3712,7 +3705,8 @@ public class ElastiCacheService implements ResourceProvider {
private void recordParameterGroupUse(Map<String, Set<String>> regionsUsing, String accountId, String name,
String arn) {
if (name != null) {
regionsUsing.computeIfAbsent(accountId + "/" + name, ignored -> new LinkedHashSet<>()).add(regionOf(arn));
regionsUsing.computeIfAbsent(accountId + "/" + name, ignored -> new LinkedHashSet<>())
.add(regionResolver.regionOf(arn));
}
}
@@ -3834,10 +3828,10 @@ public class ElastiCacheService implements ResourceProvider {
return reservedParameterGroups.containsKey(parameterGroupReservationKey(name))
|| groups.scan(key -> true).stream()
.anyMatch(group -> name.equals(group.getCacheParameterGroupName())
&& inRequestRegion(group.getArn()))
&& regionResolver.inRequestRegion(group.getArn()))
|| cacheClusters.scan(key -> true).stream()
.anyMatch(cluster -> name.equals(cluster.getCacheParameterGroupName())
&& inRequestRegion(cluster.getArn()));
&& regionResolver.inRequestRegion(cluster.getArn()));
}
@Override
@@ -992,7 +992,7 @@ public class GlueSchemaRegistryService {
private Schema schemaForVersion(SchemaVersion version) {
String[] parts = parseSchemaArn(version.getSchemaArn());
String key = schemaKey(regionOf(version.getSchemaArn()), parts[0], parts[1]);
String key = schemaKey(regionResolver.regionOf(version.getSchemaArn()), parts[0], parts[1]);
return schemaStore.get(key)
.orElseThrow(() -> new AwsException("EntityNotFoundException",
"Schema not found for version: " + version.getSchemaVersionId(), 400));
@@ -1089,25 +1089,21 @@ public class GlueSchemaRegistryService {
/** A stored schema's key, in the Region its ARN names. */
private String schemaKey(Schema schema) {
return schemaKey(regionOf(schema.getSchemaArn()), schema.getRegistryName(), schema.getSchemaName());
}
/** The Region an ARN this service minted names; one stored without an ARN counts as the default Region's. */
private String regionOf(String arn) {
return AwsArnUtils.regionOrDefault(arn, regionResolver.getDefaultRegion());
return schemaKey(regionResolver.regionOf(schema.getSchemaArn()), schema.getRegistryName(),
schema.getSchemaName());
}
/** The version by that id, if its schema is of {@code region}: another Region's is not found. */
private SchemaVersion versionIn(String schemaVersionId, String region) {
return versionStore.get(schemaVersionId)
.filter(version -> region.equals(regionOf(version.getSchemaArn())))
.filter(version -> region.equals(regionResolver.regionOf(version.getSchemaArn())))
.orElseThrow(() -> new AwsException("EntityNotFoundException",
"Schema version not found: " + schemaVersionId, 400));
}
/** Refuses an ARN naming another Region: registries and schemas are Regional, so it names none here. */
private void requireArnInRegion(String arn, String region, Supplier<AwsException> notFound) {
if (arn != null && !arn.isBlank() && !region.equals(regionOf(arn))) {
if (arn != null && !arn.isBlank() && !region.equals(regionResolver.regionOf(arn))) {
throw notFound.get();
}
}
@@ -1131,9 +1127,9 @@ public class GlueSchemaRegistryService {
List<AccountEntry<Schema>> renamed = new ArrayList<>();
for (AccountEntry<Schema> entry : schemaAccounts.scanAllAccountEntries(LEGACY_KEY)) {
Schema schema = entry.value();
String region = regionOf(schema.getSchemaArn());
String region = regionResolver.regionOf(schema.getSchemaArn());
AccountEntry<Registry> registry = registries.get(entry.accountId() + "/" + schema.getRegistryName());
if (registry == null || region.equals(regionOf(registry.value().getRegistryArn()))) {
if (registry == null || region.equals(regionResolver.regionOf(registry.value().getRegistryArn()))) {
continue;
}
String key = registryKey(region, schema.getRegistryName());
@@ -1147,7 +1143,8 @@ public class GlueSchemaRegistryService {
}
}
registryAccounts.migrateLegacyEntriesInAllAccounts(LEGACY_KEY,
registry -> registryKey(regionOf(registry.getRegistryArn()), registry.getRegistryName()));
registry -> registryKey(regionResolver.regionOf(registry.getRegistryArn()),
registry.getRegistryName()));
schemaAccounts.migrateLegacyEntriesInAllAccounts(LEGACY_KEY, this::schemaKey);
// Written once moved, under the new key: a schema stored before accounts prefixed keys would otherwise
// leave its unprefixed record beside a second legacy one.