diff --git a/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java index 47fa39e3ec..518f7a9b76 100644 --- a/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java +++ b/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java @@ -466,14 +466,24 @@ public class AccountAwareStorageBackend implements StorageBackend * keys only for the configured default account. Does not migrate or rewrite survivors. */ public synchronized void deleteMatchingIncludingLegacyAtomically(Predicate valueFilter) { + deleteMatchingIncludingLegacyAtomically(key -> true, valueFilter); + } + + /** + * As above; with {@code keyFilter}, only among the keys it accepts: the account-relative key, or an + * unprefixed legacy key as it is stored. + */ + public synchronized void deleteMatchingIncludingLegacyAtomically(Predicate keyFilter, + Predicate valueFilter) { String account = prefix(); String accountPrefix = account + "/"; Set rawKeys = new LinkedHashSet<>(); for (String rawKey : delegate.keys()) { - boolean owned = hasAccountPrefix(rawKey) - ? rawKey.startsWith(accountPrefix) : defaultAccountId.equals(account); + boolean prefixed = hasAccountPrefix(rawKey); + boolean owned = prefixed ? rawKey.startsWith(accountPrefix) : defaultAccountId.equals(account); if (owned) { - if (delegate.get(rawKey).filter(valueFilter).isPresent()) { + String key = prefixed ? rawKey.substring(accountPrefix.length()) : rawKey; + if (keyFilter.test(key) && delegate.get(rawKey).filter(valueFilter).isPresent()) { rawKeys.add(rawKey); } } diff --git a/src/main/java/io/floci/aws/core/storage/RegionScopedStorage.java b/src/main/java/io/floci/aws/core/storage/RegionScopedStorage.java new file mode 100644 index 0000000000..e482c5f3e2 --- /dev/null +++ b/src/main/java/io/floci/aws/core/storage/RegionScopedStorage.java @@ -0,0 +1,151 @@ +package io.floci.aws.core.storage; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.core.common.RegionResolver; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; + +/** + * Region view of a factory-owned account store, for a service whose resources are Regional: each key is + * stored under the request's Region ({@code us-east-1/key}), so a Region sees only its own. Older, + * regionless keys belong only to the configured default region; new writes always record their region + * explicitly. A logical key may hold any character, a slash and a leading Region included, since every key + * this view writes starts with its own Region. Only a stored key without one is read as regionless, so a + * regionless key is one whose first label is not a Region: one {@link RegionResolver#isKnownRegion} admits, + * the rule {@code AccountContextFilter} serves requests by. With + * {@code floci.partitions.allow-unknown-regions}, a key stored for a Region no partition knows therefore reads + * as a regionless one, and a regionless key stored before this view under a name starting with a Region + * reads as that Region's. + */ +public final class RegionScopedStorage implements StorageBackend { + + private final StorageBackend delegate; + private final RegionResolver regions; + + public RegionScopedStorage(StorageFactory factory, RegionResolver regions, String service, String file, + TypeReference> type) { + this(factory.create(service, file, type), regions); + } + + /** The Region view of {@code delegate}, a store the caller made with options of its own. */ + public RegionScopedStorage(StorageBackend delegate, RegionResolver regions) { + this.delegate = delegate; + this.regions = regions; + } + + @Override + public void put(String key, V value) { + delegate.put(prefix() + key, value); + if (regionlessHere(key) && delegate.get(key).isPresent()) { + delegate.delete(key); + } + } + + @Override + public Optional get(String key) { + return delegate.get(prefix() + key) + .or(() -> regionlessHere(key) ? delegate.get(key) : Optional.empty()); + } + + @Override + public void delete(String key) { + if (regionlessHere(key)) { + delegate.delete(key); + } + delegate.delete(prefix() + key); + } + + @Override + public List scan(Predicate keyFilter) { + List values = new ArrayList<>(); + for (String key : keys()) { + if (keyFilter.test(key)) { + get(key).ifPresent(values::add); + } + } + return values; + } + + @Override + public Set keys() { + String prefix = prefix(); + boolean includeLegacy = defaultRegion(); + Set keys = new HashSet<>(); + for (String stored : delegate.keys()) { + String key = logicalKeyOf(stored, prefix, includeLegacy); + if (key != null) { + keys.add(key); + } + } + return keys; + } + + /** + * Deletes, in one commit, the request's Region's values that {@code valueFilter} accepts, among the + * logical keys {@code keyFilter} accepts. In the default Region the regionless keys go too, an account + * store's unprefixed ones included, as {@link StorageOperations#deleteMatchingAtomically} deletes them + * from the account store itself. + */ + void deleteMatchingAtomically(Predicate keyFilter, Predicate valueFilter) { + String prefix = prefix(); + boolean includeLegacy = defaultRegion(); + StorageOperations.deleteMatchingAtomically(delegate, stored -> { + String key = logicalKeyOf(stored, prefix, includeLegacy); + return key != null && keyFilter.test(key); + }, valueFilter); + } + + /** + * The logical key {@code stored} holds in the Region whose keys start with {@code prefix}, or null when + * it is another Region's. A regionless key is the default Region's, so it counts with {@code includeLegacy}. + */ + private static String logicalKeyOf(String stored, String prefix, boolean includeLegacy) { + if (stored.startsWith(prefix)) { + return stored.substring(prefix.length()); + } + return includeLegacy && !regionPrefixed(stored) ? stored : null; + } + + @Override + public void clear() { + keys().forEach(this::delete); + } + + @Override + public void flush() { + delegate.flush(); + } + + @Override + public void load() { + delegate.load(); + } + + private String prefix() { + return regions.getRegion() + "/"; + } + + private boolean defaultRegion() { + return regions.getRegion().equals(regions.getDefaultRegion()); + } + + /** + * Whether {@code key} may also be stored regionless, as it was before this view, and is read here that way: + * only in the default Region, and only when it doesn't start with a Region, as a stored key of this view does. + */ + private boolean regionlessHere(String key) { + return key != null && defaultRegion() && !regionPrefixed(key); + } + + /** Whether {@code key} starts with a Region and a slash, as every key this view stores does. */ + private static boolean regionPrefixed(String key) { + int slash = key.indexOf('/'); + return slash > 0 && RegionResolver.isKnownRegion(key.substring(0, slash)); + } +} diff --git a/src/main/java/io/floci/aws/core/storage/StorageOperations.java b/src/main/java/io/floci/aws/core/storage/StorageOperations.java index 9ed22a37e6..1e937f5740 100644 --- a/src/main/java/io/floci/aws/core/storage/StorageOperations.java +++ b/src/main/java/io/floci/aws/core/storage/StorageOperations.java @@ -17,12 +17,23 @@ public final class StorageOperations { /** Deletes matching values in one commit, preserving account ownership of legacy keys. */ public static void deleteMatchingAtomically(StorageBackend store, Predicate valueFilter) { + deleteMatchingAtomically(store, key -> true, valueFilter); + } + + /** + * As above; with {@code keyFilter}, only among the keys it accepts, each as {@code store} names it: a + * Region view's logical key, an account store's account-relative key or unprefixed legacy key. + */ + public static void deleteMatchingAtomically(StorageBackend store, Predicate keyFilter, + Predicate valueFilter) { if (store instanceof AccountAwareStorageBackend accountAware) { - accountAware.deleteMatchingIncludingLegacyAtomically(valueFilter); + accountAware.deleteMatchingIncludingLegacyAtomically(keyFilter, valueFilter); + } else if (store instanceof RegionScopedStorage regional) { + regional.deleteMatchingAtomically(keyFilter, valueFilter); } else { Set keys = new LinkedHashSet<>(); for (String key : store.keys()) { - if (store.get(key).filter(valueFilter).isPresent()) { + if (keyFilter.test(key) && store.get(key).filter(valueFilter).isPresent()) { keys.add(key); } } diff --git a/src/main/java/io/floci/aws/services/appconfig/AppConfigDataService.java b/src/main/java/io/floci/aws/services/appconfig/AppConfigDataService.java index f23e8ccee0..dfc7260618 100644 --- a/src/main/java/io/floci/aws/services/appconfig/AppConfigDataService.java +++ b/src/main/java/io/floci/aws/services/appconfig/AppConfigDataService.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.RegionScopedStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.appconfig.model.Application; @@ -35,7 +36,7 @@ public class AppConfigDataService { @Inject public AppConfigDataService(StorageFactory storageFactory, AppConfigService appConfigService, ObjectMapper objectMapper, RegionResolver regions) { - this.sessionStore = new AppConfigStorage<>(storageFactory, regions, + this.sessionStore = new RegionScopedStorage<>(storageFactory, regions, "appconfigdata", "appconfigdata-sessions.json", new TypeReference<>() {}); this.appConfigService = appConfigService; this.objectMapper = objectMapper; diff --git a/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java b/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java index 3e4694e3ea..b0b36ce9ca 100644 --- a/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java +++ b/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java @@ -7,6 +7,7 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.RegionScopedStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.core.storage.StorageOperations; @@ -66,19 +67,19 @@ public class AppConfigService { AppConfigService(StorageFactory storageFactory, RegionResolver regions, Clock clock) { this.clock = clock; this.regions = regions; - this.applicationStore = new AppConfigStorage<>(storageFactory, regions, + this.applicationStore = new RegionScopedStorage<>(storageFactory, regions, "appconfig", "appconfig-applications.json", new TypeReference<>() {}); - this.environmentStore = new AppConfigStorage<>(storageFactory, regions, + this.environmentStore = new RegionScopedStorage<>(storageFactory, regions, "appconfig", "appconfig-environments.json", new TypeReference<>() {}); - this.profileStore = new AppConfigStorage<>(storageFactory, regions, + this.profileStore = new RegionScopedStorage<>(storageFactory, regions, "appconfig", "appconfig-profiles.json", new TypeReference<>() {}); - this.strategyStore = new AppConfigStorage<>(storageFactory, regions, + this.strategyStore = new RegionScopedStorage<>(storageFactory, regions, "appconfig", "appconfig-strategies.json", new TypeReference<>() {}); - this.versionStore = new AppConfigStorage<>(storageFactory, regions, + this.versionStore = new RegionScopedStorage<>(storageFactory, regions, "appconfig", "appconfig-versions.json", new TypeReference<>() {}); - this.deploymentStore = new AppConfigStorage<>(storageFactory, regions, + this.deploymentStore = new RegionScopedStorage<>(storageFactory, regions, "appconfig", "appconfig-deployments.json", new TypeReference<>() {}); - this.activeConfigStore = new AppConfigStorage<>(storageFactory, regions, + this.activeConfigStore = new RegionScopedStorage<>(storageFactory, regions, "appconfig", "appconfig-active-configs.json", new TypeReference<>() {}); } diff --git a/src/main/java/io/floci/aws/services/appconfig/AppConfigStorage.java b/src/main/java/io/floci/aws/services/appconfig/AppConfigStorage.java deleted file mode 100644 index be734b0006..0000000000 --- a/src/main/java/io/floci/aws/services/appconfig/AppConfigStorage.java +++ /dev/null @@ -1,116 +0,0 @@ -package io.floci.aws.services.appconfig; - -import com.fasterxml.jackson.core.type.TypeReference; -import io.floci.aws.core.common.RegionResolver; -import io.floci.aws.core.storage.StorageBackend; -import io.floci.aws.core.storage.StorageFactory; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Predicate; - -/** - * Region view of a factory-owned account store. Older, regionless keys belong only to - * the configured default region; new writes always record their region explicitly. - */ -final class AppConfigStorage implements StorageBackend { - private final StorageBackend delegate; - private final RegionResolver regions; - - AppConfigStorage(StorageFactory factory, RegionResolver regions, String service, String file, - TypeReference> type) { - this.delegate = factory.create(service, file, type); - this.regions = regions; - } - - @Override - public void put(String key, V value) { - if (!logicalKey(key)) { - throw new IllegalArgumentException("AppConfig storage keys cannot contain a region prefix"); - } - delegate.put(prefix() + key, value); - if (defaultRegion() && delegate.get(key).isPresent()) { - delegate.delete(key); - } - } - - @Override - public Optional get(String key) { - if (!logicalKey(key)) { - return Optional.empty(); - } - return delegate.get(prefix() + key) - .or(() -> defaultRegion() ? delegate.get(key) : Optional.empty()); - } - - @Override - public void delete(String key) { - if (logicalKey(key)) { - if (defaultRegion()) { - delegate.delete(key); - } - delegate.delete(prefix() + key); - } - } - - @Override - public List scan(Predicate keyFilter) { - List values = new ArrayList<>(); - for (String key : keys()) { - if (keyFilter.test(key)) { - get(key).ifPresent(values::add); - } - } - return values; - } - - @Override - public Set keys() { - String prefix = prefix(); - boolean includeLegacy = defaultRegion(); - Set keys = new HashSet<>(); - for (String stored : delegate.keys()) { - if (stored.startsWith(prefix)) { - String key = stored.substring(prefix.length()); - if (logicalKey(key)) { - keys.add(key); - } - } else if (includeLegacy && logicalKey(stored)) { - keys.add(stored); - } - } - return keys; - } - - @Override - public void clear() { - keys().forEach(this::delete); - } - - @Override - public void flush() { - delegate.flush(); - } - - @Override - public void load() { - delegate.load(); - } - - private String prefix() { - return regions.getRegion() + "/"; - } - - private boolean defaultRegion() { - return regions.getRegion().equals(regions.getDefaultRegion()); - } - - private static boolean logicalKey(String key) { - // Resource IDs, configuration tokens and the service's "::" composite keys contain no slash. - return key != null && !key.contains("/"); - } -} diff --git a/src/main/java/io/floci/aws/services/athena/AthenaService.java b/src/main/java/io/floci/aws/services/athena/AthenaService.java index 5dadeb42e6..3d03d75d09 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaService.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaService.java @@ -8,6 +8,7 @@ import io.floci.aws.core.common.CsvParser; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.athena.model.CreateWorkGroupConfigurationRequest; @@ -35,6 +36,7 @@ import io.floci.aws.services.glue.model.Database; import io.floci.aws.services.glue.model.Table; import io.floci.aws.services.s3.S3Service; import io.floci.aws.services.s3.model.S3Object; +import io.smallrye.common.vertx.VertxContext; import io.vertx.core.Vertx; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -184,30 +186,37 @@ public class AthenaService { return id; } - // Submit async — caller gets the ID immediately while execution runs in background - vertx.executeBlocking(() -> { - // Athena fails a query that reads a table with an incomplete location template, or that - // leaves an injected partition column unconstrained. It fails the query rather than the - // submission, which is what throwing here produces. - List projectionTables = tablesForProjectionCheck(database); - PartitionProjection.assertLocationTemplatesComplete(query, projectionTables); - PartitionProjection.assertInjectedColumnsFiltered(query, projectionTables); - String setupDdl = ddlBuilder.build(database); - if (outputLocation != null) { - ensureOutputBucket(outputLocation); - } - duckClient.execute(query, setupDdl, outputLocation); - if (outputLocation != null) { - resultColumnTypeStore.put(id, describeColumnTypes(query, setupDdl)); - } - return null; - }).onSuccess(v -> { + // Submit async: the caller gets the ID immediately while execution runs in the background. The + // query outlives this request and must not share its CDI context, so it runs in a context of its + // own, as ReplayDispatcher runs a replay, as the account and in the Region it was started in: they + // decide the Glue catalog it reads and the stores its record and result column types go to. + String accountId = regionResolver.getAccountId(); + String region = regionResolver.getRegion(); + VertxContext.createNewDuplicatedContext(vertx.getOrCreateContext()).executeBlocking(() -> + RequestScopes.callAsChecked(accountId, region, () -> { + // Athena fails a query that reads a table with an incomplete location template, or that + // leaves an injected partition column unconstrained. It fails the query rather than the + // submission, which is what throwing here produces. + List
projectionTables = tablesForProjectionCheck(database); + PartitionProjection.assertLocationTemplatesComplete(query, projectionTables); + PartitionProjection.assertInjectedColumnsFiltered(query, projectionTables); + String setupDdl = ddlBuilder.build(database); + if (outputLocation != null) { + ensureOutputBucket(outputLocation); + } + duckClient.execute(query, setupDdl, outputLocation, accountId); + if (outputLocation != null) { + resultColumnTypeStore.put(id, describeColumnTypes(query, setupDdl, accountId)); + } + return null; + }) + ).onSuccess(v -> RequestScopes.runAs(accountId, region, () -> { markSucceeded(id, execution); LOG.infov("Query {0} succeeded", id); - }).onFailure(e -> { + })).onFailure(e -> RequestScopes.runAs(accountId, region, () -> { markFailed(id, execution, e); LOG.warnv("Query {0} failed: {1}", id, e.getMessage()); - }); + })); return id; } @@ -1122,12 +1131,12 @@ public class AthenaService { /** * The DuckDB type of each result column, in order. The result CSV carries only the column names, - * so the types come from DuckDB describing the same query. The query has already succeeded, so a + * so the types come from DuckDB describing the same query, as the account that ran it. The query has already succeeded, so a * failure here only costs the types: its columns are reported as varchar. */ - private List describeColumnTypes(String query, String setupDdl) { + private List describeColumnTypes(String query, String setupDdl, String accountId) { try { - return duckClient.query("DESCRIBE " + query, setupDdl).stream() + return duckClient.query("DESCRIBE " + query, setupDdl, accountId).stream() .map(column -> String.valueOf(column.get("column_type"))) .toList(); } catch (RuntimeException e) { diff --git a/src/main/java/io/floci/aws/services/firehose/FirehoseParquetConverter.java b/src/main/java/io/floci/aws/services/firehose/FirehoseParquetConverter.java index add3e59965..db8635ef3d 100644 --- a/src/main/java/io/floci/aws/services/firehose/FirehoseParquetConverter.java +++ b/src/main/java/io/floci/aws/services/firehose/FirehoseParquetConverter.java @@ -12,6 +12,7 @@ import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestScopes; import io.floci.aws.services.firehose.model.DeliveryStreamDescription; import io.floci.aws.services.firehose.model.DeliveryStreamDescription.DataFormatConversionConfiguration; import io.floci.aws.services.firehose.model.DeliveryStreamDescription.OpenXJsonSerDe; @@ -236,12 +237,16 @@ public class FirehoseParquetConverter { // ── schema resolution ──────────────────────────────────────────────────── /** - * The Glue store is not region- or catalog-partitioned, so - * SchemaConfiguration.Region and CatalogId only flow into the error-output - * metadata; VersionId is not resolved (the live table is always used). + * The Glue table is read in SchemaConfiguration.Region when it names one, and in the + * stream's own Region otherwise, as AWS reads it. The catalog is the stream account's, so + * CatalogId only flows into the error-output metadata; VersionId is not resolved (the live + * table is always used). */ private List resolveSchema(SchemaConfiguration schemaConfig, SerDeRules rules) { - Table table = glueService.getTable(schemaConfig.getDatabaseName(), schemaConfig.getTableName()); + Table table = schemaConfig.getRegion() == null || schemaConfig.getRegion().isBlank() + ? glueService.getTable(schemaConfig.getDatabaseName(), schemaConfig.getTableName()) + : RequestScopes.callAs(regionResolver.getAccountId(), schemaConfig.getRegion(), + () -> glueService.getTable(schemaConfig.getDatabaseName(), schemaConfig.getTableName())); List columns = table.getStorageDescriptor() == null ? null : table.getStorageDescriptor().getColumns(); if (columns == null || columns.isEmpty()) { diff --git a/src/main/java/io/floci/aws/services/firehose/FirehoseService.java b/src/main/java/io/floci/aws/services/firehose/FirehoseService.java index 1147854b2c..b53f5496aa 100644 --- a/src/main/java/io/floci/aws/services/firehose/FirehoseService.java +++ b/src/main/java/io/floci/aws/services/firehose/FirehoseService.java @@ -1144,12 +1144,13 @@ public class FirehoseService implements ResourceProvider { return; } - // Every store this delivery touches, Glue and S3 included, reads the account - // from the request context, and a scheduled flush has none. Without this the - // work would run as the default account rather than the stream's owner: the + // Every store this delivery touches, Glue and S3 included, reads the account and + // the Region from the request context, and a scheduled flush has none. Without this + // the work would run as the default account and Region rather than the stream's: the // stream's Glue table would be missed and its objects would land in the wrong // partition. The sidecar follows the same context, so both sides stay together. RequestScopes.runAs(stream.getAccountId(), + AwsArnUtils.regionOrDefault(stream.getDeliveryStreamARN(), regionResolver.getDefaultRegion()), () -> deliverBuffer(streamName, stream, toFlush, since, checkpoint)); } } diff --git a/src/main/java/io/floci/aws/services/glue/GlueCrawlerRunService.java b/src/main/java/io/floci/aws/services/glue/GlueCrawlerRunService.java index ebe92660c8..75dea8107d 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueCrawlerRunService.java +++ b/src/main/java/io/floci/aws/services/glue/GlueCrawlerRunService.java @@ -3,6 +3,8 @@ package io.floci.aws.services.glue; import com.fasterxml.jackson.core.type.TypeReference; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.RegionScopedStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.glue.model.Crawler; @@ -57,9 +59,11 @@ public class GlueCrawlerRunService { private final Clock clock; @Inject - public GlueCrawlerRunService(StorageFactory storageFactory, GlueService glueService, EmulatorConfig config) { - this(storageFactory.create("glue", "crawler_runs.json", new TypeReference<>() {}), - storageFactory.create("glue", "workflow_run_crawls.json", new TypeReference<>() {}), + public GlueCrawlerRunService(StorageFactory storageFactory, GlueService glueService, EmulatorConfig config, + RegionResolver regionResolver) { + this(new RegionScopedStorage<>(storageFactory, regionResolver, "glue", "crawler_runs.json", new TypeReference<>() {}), + new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "workflow_run_crawls.json", new TypeReference<>() {}), glueService, config.services().glue().crawlerRunDurationSeconds(), Clock.systemUTC()); } diff --git a/src/main/java/io/floci/aws/services/glue/GlueJobRunService.java b/src/main/java/io/floci/aws/services/glue/GlueJobRunService.java index 0ccd5a9e6b..a84175da92 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueJobRunService.java +++ b/src/main/java/io/floci/aws/services/glue/GlueJobRunService.java @@ -3,6 +3,8 @@ package io.floci.aws.services.glue; import com.fasterxml.jackson.core.type.TypeReference; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.RegionScopedStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.glue.model.ExecutionProperty; @@ -60,9 +62,11 @@ public class GlueJobRunService { private final Clock clock; @Inject - public GlueJobRunService(StorageFactory storageFactory, GlueService glueService, EmulatorConfig config) { - this(storageFactory.create("glue", "job_runs.json", new TypeReference<>() {}), - storageFactory.create("glue", "job_run_bookkeeping.json", new TypeReference<>() {}), + public GlueJobRunService(StorageFactory storageFactory, GlueService glueService, EmulatorConfig config, + RegionResolver regionResolver) { + this(new RegionScopedStorage<>(storageFactory, regionResolver, "glue", "job_runs.json", new TypeReference<>() {}), + new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "job_run_bookkeeping.json", new TypeReference<>() {}), glueService, config.services().glue().jobRunDurationSeconds(), Clock.systemUTC()); } diff --git a/src/main/java/io/floci/aws/services/glue/GlueService.java b/src/main/java/io/floci/aws/services/glue/GlueService.java index cb4f3e44f8..be726d7957 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueService.java +++ b/src/main/java/io/floci/aws/services/glue/GlueService.java @@ -14,6 +14,7 @@ import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.SmithyValidationErrors; +import io.floci.aws.core.storage.RegionScopedStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.core.storage.StorageOperations; @@ -225,29 +226,42 @@ public class GlueService { RegionResolver regionResolver, ResourceGroupsTaggingService resourceGroupsTaggingService, KmsService kmsService) { - this.databaseStore = storageFactory.create("glue", "databases.json", new TypeReference<>() {}); - this.tableStore = storageFactory.create("glue", "tables.json", new TypeReference<>() {}); - this.tableVersionStore = storageFactory.create("glue", "table_versions.json", new TypeReference<>() {}); - this.columnStatisticsStore = storageFactory.create("glue", "column_statistics.json", new TypeReference<>() {}); - this.partitionStore = storageFactory.create("glue", "partitions.json", new TypeReference<>() {}); - this.partitionIndexStore = storageFactory.create( + this.databaseStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "databases.json", new TypeReference<>() {}); + this.tableStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "tables.json", new TypeReference<>() {}); + this.tableVersionStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "table_versions.json", new TypeReference<>() {}); + this.columnStatisticsStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "column_statistics.json", new TypeReference<>() {}); + this.partitionStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "partitions.json", new TypeReference<>() {}); + this.partitionIndexStore = new RegionScopedStorage<>(storageFactory, regionResolver, "glue", "partition_indexes.json", new TypeReference<>() {}); - this.partitionColumnStatisticsStore = storageFactory.create( + this.partitionColumnStatisticsStore = new RegionScopedStorage<>(storageFactory, regionResolver, "glue", "partition_column_statistics.json", new TypeReference<>() {}); - this.functionStore = storageFactory.create("glue", "functions.json", new TypeReference<>() {}); - this.jobStore = storageFactory.create("glue", "jobs.json", new TypeReference<>() {}); - this.crawlerStore = storageFactory.create("glue", "crawlers.json", new TypeReference<>() {}); - this.classifierStore = storageFactory.create("glue", "classifiers.json", new TypeReference<>() {}); - this.connectionStore = storageFactory.create("glue", "connections.json", new TypeReference<>() {}); - this.resourcePolicyStore = storageFactory.create("glue", "resource_policy.json", new TypeReference<>() {}); - this.encryptionSettingsStore = storageFactory.create( + this.functionStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "functions.json", new TypeReference<>() {}); + this.jobStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "jobs.json", new TypeReference<>() {}); + this.crawlerStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "crawlers.json", new TypeReference<>() {}); + this.classifierStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "classifiers.json", new TypeReference<>() {}); + this.connectionStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "connections.json", new TypeReference<>() {}); + this.resourcePolicyStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "resource_policy.json", new TypeReference<>() {}); + this.encryptionSettingsStore = new RegionScopedStorage<>(storageFactory, regionResolver, "glue", "catalog_encryption_settings.json", new TypeReference<>() {}); this.securityConfigurationStore = storageFactory.create( "glue", "security_configurations.json", new TypeReference<>() {}); this.dataQualityRulesetStore = storageFactory.create( "glue", "data_quality_rulesets.json", new TypeReference<>() {}); - this.triggerStore = storageFactory.create("glue", "triggers.json", new TypeReference<>() {}); - this.workflowStore = storageFactory.create("glue", "workflows.json", new TypeReference<>() {}); + this.triggerStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "triggers.json", new TypeReference<>() {}); + this.workflowStore = new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "workflows.json", new TypeReference<>() {}); this.schemaRegistryService = schemaRegistryService; this.regionResolver = regionResolver; this.resourceGroupsTaggingService = resourceGroupsTaggingService; @@ -364,7 +378,7 @@ public class GlueService { } public void createDatabase(Database database) { - createDatabase(database, null, regionResolver.getDefaultRegion()); + createDatabase(database, null, regionResolver.getRegion()); } public synchronized void createDatabase(Database database, Map tags, String region) { @@ -429,7 +443,7 @@ public class GlueService { } public void deleteDatabase(String name) { - deleteDatabase(name, regionResolver.getDefaultRegion()); + deleteDatabase(name, regionResolver.getRegion()); } public synchronized void deleteDatabase(String name, String region) { @@ -1394,7 +1408,7 @@ public class GlueService { boolean latest = ref.getSchemaVersionId() == null && ref.getSchemaVersionNumber() == null; return schemaRegistryService.getSchemaVersion( ref.getSchemaId(), ref.getSchemaVersionId(), - ref.getSchemaVersionNumber(), latest, regionResolver.getDefaultRegion()); + ref.getSchemaVersionNumber(), latest, regionResolver.getRegion()); } private static SchemaReference schemaReferenceOf(Table table) { @@ -2025,7 +2039,7 @@ public class GlueService { } public void createJob(Job job) { - createJob(job, null, regionResolver.getDefaultRegion()); + createJob(job, null, regionResolver.getRegion()); } public void createJob(Job job, Map tags, String region) { @@ -2331,7 +2345,7 @@ public class GlueService { } public void createCrawler(Crawler crawler) { - createCrawler(crawler, null, regionResolver.getDefaultRegion()); + createCrawler(crawler, null, regionResolver.getRegion()); } public void createCrawler(Crawler crawler, Map tags, String region) { diff --git a/src/main/java/io/floci/aws/services/glue/GlueTriggerService.java b/src/main/java/io/floci/aws/services/glue/GlueTriggerService.java index 7be2a6da20..a3b907bec9 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueTriggerService.java +++ b/src/main/java/io/floci/aws/services/glue/GlueTriggerService.java @@ -3,6 +3,8 @@ package io.floci.aws.services.glue; import com.fasterxml.jackson.core.type.TypeReference; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.EpochSeconds; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.RegionScopedStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.core.storage.WriteProfile; @@ -91,13 +93,16 @@ public class GlueTriggerService { @Inject public GlueTriggerService(StorageFactory storageFactory, GlueService glueService, - GlueJobRunService jobRunService, GlueCrawlerRunService crawlerRunService) { - this(storageFactory.create("glue", "trigger_seen_runs.json", new TypeReference<>() {}), + GlueJobRunService jobRunService, GlueCrawlerRunService crawlerRunService, + RegionResolver regionResolver) { + this(new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "trigger_seen_runs.json", new TypeReference<>() {}), // Every claimed run writes here, so under persistent mode the store is journaled rather // than rewritten in full on each claim. - storageFactory.create("glue", "trigger_chain_budgets.json", new TypeReference<>() {}, - WriteProfile.APPEND_HEAVY), - storageFactory.create("glue", "workflow_runs.json", new TypeReference<>() {}), + new RegionScopedStorage<>(storageFactory.create("glue", "trigger_chain_budgets.json", + new TypeReference<>() {}, WriteProfile.APPEND_HEAVY), regionResolver), + new RegionScopedStorage<>(storageFactory, regionResolver, + "glue", "workflow_runs.json", new TypeReference<>() {}), glueService, jobRunService, crawlerRunService); } diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftService.java b/src/main/java/io/floci/aws/services/redshift/RedshiftService.java index 2273978049..8e77adc72a 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftService.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftService.java @@ -1147,7 +1147,7 @@ public class RedshiftService implements ManagedSecretRotator { /** The region the cluster was created in, or empty when the account has no such cluster. */ public Optional clusterRegion(String accountId, String identifier) { - return clusters.getForAccount(accountId, identifier).map(this::snapshotRegion); + return clusters.getForAccount(accountId, identifier).map(this::clusterRegion); } /** A failing listener must not abort the removal: the cluster is already gone by now. */ @@ -1210,7 +1210,7 @@ public class RedshiftService implements ManagedSecretRotator { public List availableMetricTargets() { return clusters.scanAllAccountEntries(k -> true).stream() .filter(entry -> "available".equals(entry.value().getClusterStatus())) - .map(entry -> new RedshiftMetricTarget(entry.accountId(), snapshotRegion(entry.value()), + .map(entry -> new RedshiftMetricTarget(entry.accountId(), clusterRegion(entry.value()), entry.value(), relayKey(entry.accountId(), entry.value().getClusterIdentifier()))) .toList(); } @@ -2055,7 +2055,7 @@ public class RedshiftService implements ManagedSecretRotator { snapshot.setMasterUsername(cluster.getMasterUsername()); snapshot.setMasterPassword(cluster.getMasterPassword()); snapshot.setSnapshotArn(scheduledTime == null ? snapshotArn(clusterIdentifier, snapshotIdentifier) - : AwsArnUtils.Arn.of("redshift", snapshotRegion(cluster), accountId, + : AwsArnUtils.Arn.of("redshift", clusterRegion(cluster), accountId, "snapshot:" + clusterIdentifier + "/" + snapshotIdentifier).toString()); snapshot.setSnapshotCreateTime(now); snapshot.setManualSnapshotRetentionPeriod(retentionPeriod); @@ -2082,7 +2082,7 @@ public class RedshiftService implements ManagedSecretRotator { throw new AwsException("InvalidParameterValue", "Invalid snapshot identifier", 400); } boolean finalSnapshot = retentionPeriod != null; - String eventRegion = scheduledTime == null ? regionResolver.getRegion() : snapshotRegion(cluster); + String eventRegion = scheduledTime == null ? regionResolver.getRegion() : clusterRegion(cluster); emitSnapshotEvent(accountId, eventRegion, finalSnapshot ? RedshiftEventCatalog.FINAL_SNAPSHOT_STARTED : RedshiftEventCatalog.SNAPSHOT_STARTED, snapshotIdentifier, (finalSnapshot ? "The final snapshot '" : "A user snapshot '") + snapshotIdentifier @@ -3194,7 +3194,7 @@ public class RedshiftService implements ManagedSecretRotator { throw new AwsException("UnknownSnapshotCopyRegionFault", "Unknown destination region: " + destinationRegion, 404); } - if (destinationRegion.equals(snapshotRegion(cluster))) { + if (destinationRegion.equals(clusterRegion(cluster))) { // A copy in the cluster's own Region would shadow the snapshots it was copied from. throw new AwsException("UnknownSnapshotCopyRegionFault", "The destination region must differ from the cluster's region: " + destinationRegion, 404); @@ -3434,7 +3434,8 @@ public class RedshiftService implements ManagedSecretRotator { new AutomatedSnapshotState(scheduleKey, state.anchor(), scheduled))); } - private String snapshotRegion(Cluster cluster) { + /** The Region the cluster was created in; the default Region for a cluster stored before clusters kept one. */ + private String clusterRegion(Cluster cluster) { return cluster.getSnapshotRegion() == null ? regionResolver.getDefaultRegion() : cluster.getSnapshotRegion(); } @@ -3600,7 +3601,7 @@ public class RedshiftService implements ManagedSecretRotator { Snapshot copy = new Snapshot(source); copy.setSnapshotArn(AwsArnUtils.Arn.of("redshift", destination, accountId, "snapshot:" + source.getClusterIdentifier() + "/" + source.getSnapshotIdentifier()).toString()); - copy.setSourceRegion(snapshotRegion(cluster)); + copy.setSourceRegion(clusterRegion(cluster)); copy.setSourceSnapshotArn(source.getSnapshotArn()); copy.setSourceSnapshotCreateTime(source.getSnapshotCreateTime()); copy.setSqlDump(dump == null ? null : dump.toString()); diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftAuthProxy.java b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftAuthProxy.java index 95e1282372..c7e7e83d50 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftAuthProxy.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftAuthProxy.java @@ -11,6 +11,7 @@ import io.floci.aws.services.redshift.RedshiftCredentialBroker; import io.floci.aws.services.redshift.RedshiftDbIdentityProvisioner; import io.floci.aws.services.redshift.TempCredential; import io.floci.aws.services.redshift.spectrum.SpectrumInterceptor; +import io.floci.aws.services.redshift.spectrum.SpectrumSession; import io.floci.aws.services.s3.S3Service; import org.jboss.logging.Logger; import org.postgresql.ds.PGSimpleDataSource; @@ -398,9 +399,8 @@ public class RedshiftAuthProxy { return; } String remoteAddress = client.getInetAddress() == null ? null : client.getInetAddress().getHostAddress(); - String clusterIdentifier = clusterKey.substring(clusterKey.indexOf(':') + 1); - auditLogPublisher.publishRegisteredConnection(clusterAccountId, clusterIdentifier, login.database, login.username, - event, remoteAddress, client.getPort()); + auditLogPublisher.publishRegisteredConnection(clusterAccountId, SpectrumSession.clusterIdentifier(clusterKey), + login.database, login.username, event, remoteAddress, client.getPort()); } private static void closeQuietly(Socket s) { diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java index efee75a023..a782906a58 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java @@ -1048,8 +1048,8 @@ public class RedshiftInterceptingBridge { if (auditLogPublisher == null) { return; } - auditLogPublisher.publishRegisteredActivity(clusterAccountId, clusterIdentifier(), databaseName, - databaseUser, sql); + auditLogPublisher.publishRegisteredActivity(clusterAccountId, SpectrumSession.clusterIdentifier(clusterKey), + databaseName, databaseUser, sql); } private BiConsumer auditResponses(String sql) { @@ -1088,16 +1088,12 @@ public class RedshiftInterceptingBridge { private void publishCompletedUserChanges() { for (UserChange change : auditUserChanges.drainCommitted()) { - auditLogPublisher.publishRegisteredUserChange(clusterAccountId, clusterIdentifier(), databaseName, - change.username(), change.action(), change.oldUsername()); + auditLogPublisher.publishRegisteredUserChange(clusterAccountId, + SpectrumSession.clusterIdentifier(clusterKey), databaseName, change.username(), change.action(), + change.oldUsername()); } } - private String clusterIdentifier() { - int separator = clusterKey.indexOf(':'); - return separator < 0 ? clusterKey : clusterKey.substring(separator + 1); - } - private void closeQuietly(Socket socket, String which) { try { if (socket != null && !socket.isClosed()) { diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java index 4b44fd2c82..de324b1913 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java @@ -7,7 +7,9 @@ import io.floci.aws.services.glue.GlueService; import io.floci.aws.services.glue.model.Database; import io.floci.aws.services.glue.model.Partition; import io.floci.aws.services.glue.model.Table; +import io.floci.aws.services.redshift.RedshiftService; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -20,6 +22,7 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.BiFunction; @ApplicationScoped public class SpectrumQueryPreparation { @@ -30,6 +33,8 @@ public class SpectrumQueryPreparation { private final GlueService glue; private final ExternalMetadataWriter metadata; private final ExternalCatalogLocks catalogLocks; + /** The Region of an account's cluster, by its identifier; null when it isn't known. */ + private final BiFunction clusterRegion; private final Map> pendingBindings = new ConcurrentHashMap<>(); public SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer, @@ -37,10 +42,24 @@ public class SpectrumQueryPreparation { this(registry, materializer, parser, glue, metadata, new ExternalCatalogLocks()); } - @Inject public SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer, ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks) { + this(registry, materializer, parser, glue, metadata, catalogLocks, (accountId, clusterIdentifier) -> null); + } + + @Inject + public SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer, + ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata, + ExternalCatalogLocks catalogLocks, Instance redshift) { + this(registry, materializer, parser, glue, metadata, catalogLocks, + (accountId, clusterIdentifier) -> redshift.get().clusterRegion(accountId, clusterIdentifier).orElse(null)); + } + + SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer, + ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata, + ExternalCatalogLocks catalogLocks, BiFunction clusterRegion) { + this.clusterRegion = clusterRegion; this.registry = registry; this.materializer = materializer; this.parser = parser; @@ -49,6 +68,16 @@ public class SpectrumQueryPreparation { this.catalogLocks = catalogLocks; } + /** + * The Region whose Glue catalog the session's cluster reads: the cluster's own, as on AWS. Null when the + * cluster isn't a provisioned one Floci knows, which leaves the Region the call already runs in, such as a + * Data API request's. + */ + private String catalogRegion(SpectrumSession session) { + String clusterIdentifier = session.clusterIdentifier(); + return clusterIdentifier == null ? null : clusterRegion.apply(session.accountId(), clusterIdentifier); + } + public boolean prepare(String sql, SpectrumSession session, BackendSql backend) { return prepare(sql, session, backend, List.of()); } @@ -59,7 +88,8 @@ public class SpectrumQueryPreparation { */ public boolean prepare(String sql, SpectrumSession session, BackendSql backend, List parameters) { try { - return RequestScopes.callAs(session.accountId(), () -> prepareInScope(sql, session, backend, parameters)); + return RequestScopes.callAs(session.accountId(), catalogRegion(session), + () -> prepareInScope(sql, session, backend, parameters)); } catch (AwsException exception) { String state = switch (exception.getErrorCode()) { case "AlreadyExistsException" -> "42P07"; diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumSession.java b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumSession.java index 58f79fdecb..db1291275c 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumSession.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumSession.java @@ -7,4 +7,21 @@ public record SpectrumSession(String accountId, String clusterKey, String databa public SpectrumSession { iamRoleArns = iamRoleArns == null ? List.of() : List.copyOf(iamRoleArns); } + + /** {@link #clusterIdentifier(String)} of this session's cluster key. */ + public String clusterIdentifier() { + return clusterIdentifier(clusterKey); + } + + /** + * The cluster identifier a cluster key {@code :} names, the key the proxy and the Data + * API run a cluster's sessions under; the whole key when it has no account part, and null for none. + */ + public static String clusterIdentifier(String clusterKey) { + if (clusterKey == null) { + return null; + } + int separator = clusterKey.indexOf(':'); + return separator < 0 ? clusterKey : clusterKey.substring(separator + 1); + } } diff --git a/src/test/java/io/floci/aws/core/storage/RegionScopedStorageTest.java b/src/test/java/io/floci/aws/core/storage/RegionScopedStorageTest.java new file mode 100644 index 0000000000..f7b6b76df1 --- /dev/null +++ b/src/test/java/io/floci/aws/core/storage/RegionScopedStorageTest.java @@ -0,0 +1,146 @@ +package io.floci.aws.core.storage; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.testing.StorageFactories; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class RegionScopedStorageTest { + @TempDir + Path directory; + + @ParameterizedTest + @ValueSource(strings = {"memory", "persistent", "hybrid", "wal"}) + void legacyKeysAndScopedKeysCannotEscapeTheirRegion(String mode) { + StorageFactory factory = StorageFactories.open(directory, mode, "000000000000"); + try { + StorageBackend legacy = factory.create( + "appconfig", "records.json", new TypeReference<>() {}); + legacy.put("existing", "legacy"); + RegionScopedStorage east = store(factory, "us-east-1"); + RegionScopedStorage west = store(factory, "us-west-2"); + assertEquals(Optional.of("legacy"), east.get("existing")); + assertEquals(Optional.empty(), west.get("existing")); + east.put("existing", "east"); + west.put("existing", "west"); + legacy.put("untouched", "older-record"); + + assertEquals(Optional.empty(), legacy.get("existing")); + assertEquals(Optional.of("east"), east.get("existing")); + assertEquals(Optional.of("west"), west.get("existing")); + assertEquals(Set.of("existing", "untouched"), east.keys()); + assertEquals(Set.of("existing"), west.keys()); + assertEquals(List.of("west"), west.scan(key -> key.equals("existing"))); + List selected = west.scan(key -> true); + selected.clear(); + assertEquals(List.of("west"), west.scan(key -> true)); + + // A key naming another Region is a key of this one: it never reaches that Region's record. + assertEquals(Optional.empty(), east.get("us-west-2/existing")); + east.delete("us-west-2/existing"); + east.put("us-west-2/existing", "east-named-west"); + assertEquals(Optional.of("east-named-west"), east.get("us-west-2/existing")); + assertEquals(Set.of("existing", "untouched", "us-west-2/existing"), east.keys()); + assertEquals(Optional.of("west"), west.get("existing")); + assertEquals(Set.of("existing"), west.keys()); + east.clear(); + assertEquals(Set.of(), east.keys()); + assertEquals(Optional.of("west"), west.get("existing")); + } finally { + factory.shutdownAll(); + } + } + + /** + * A key may hold a slash, as a Glue name may, a Region and a slash at its start included. A label shaped + * like a Region that no partition admits ({@code my-cd-1}) is part of the key. + */ + @ParameterizedTest + @ValueSource(strings = {"memory", "persistent", "hybrid", "wal"}) + void aKeyWithASlashThatIsNotARegionStaysInItsRegion(String mode) { + StorageFactory factory = StorageFactories.open(directory, mode, "000000000000"); + try { + StorageBackend legacy = factory.create( + "appconfig", "records.json", new TypeReference<>() {}); + legacy.put("older/record", "legacy"); + RegionScopedStorage east = store(factory, "us-east-1"); + RegionScopedStorage west = store(factory, "us-west-2"); + + west.put("sales/2024:orders", "west"); + west.put("my-cd-1/plan", "west-plan"); + + assertEquals(Optional.of("west"), west.get("sales/2024:orders")); + assertEquals(Optional.of("west-plan"), west.get("my-cd-1/plan")); + assertEquals(Optional.empty(), east.get("sales/2024:orders")); + assertEquals(Set.of("sales/2024:orders", "my-cd-1/plan"), west.keys()); + assertEquals(Optional.of("legacy"), east.get("older/record")); + assertEquals(Set.of("older/record"), east.keys()); + assertEquals(Optional.empty(), west.get("older/record")); + + west.put("eu-west-1/plan", "west-named-eu"); + east.put("us-east-1/plan", "east-named-east"); + assertEquals(Optional.of("west-named-eu"), west.get("eu-west-1/plan")); + assertEquals(Optional.of("east-named-east"), east.get("us-east-1/plan")); + assertEquals(Optional.empty(), east.get("eu-west-1/plan")); + assertEquals(Optional.empty(), west.get("us-east-1/plan")); + assertEquals(Set.of("sales/2024:orders", "my-cd-1/plan", "eu-west-1/plan"), west.keys()); + assertEquals(Set.of("older/record", "us-east-1/plan"), east.keys()); + east.delete("us-east-1/plan"); + assertEquals(Optional.empty(), east.get("us-east-1/plan")); + assertEquals(Optional.of("legacy"), east.get("older/record")); + } finally { + factory.shutdownAll(); + } + } + + /** + * A matching deletion acts in the request's Region only, in one commit; in the default Region it takes + * the regionless keys too. + */ + @ParameterizedTest + @ValueSource(strings = {"memory", "persistent", "hybrid", "wal"}) + void matchingDeletionsStayInTheirRegion(String mode) { + StorageFactory factory = StorageFactories.open(directory, mode, "000000000000"); + try { + StorageBackend legacy = factory.create( + "appconfig", "records.json", new TypeReference<>() {}); + legacy.put("older", "db"); + RegionScopedStorage east = store(factory, "us-east-1"); + RegionScopedStorage west = store(factory, "us-west-2"); + east.put("a", "db"); + east.put("kept", "other"); + west.put("a", "db"); + + StorageOperations.deleteMatchingAtomically(west, "db"::equals); + + assertEquals(Set.of(), west.keys()); + assertEquals(Set.of("a", "kept", "older"), east.keys()); + + StorageOperations.deleteMatchingAtomically(east, "db"::equals); + + assertEquals(Set.of("kept"), east.keys()); + assertEquals(Set.of("us-east-1/kept"), legacy.keys()); + } finally { + factory.shutdownAll(); + } + } + + private static RegionScopedStorage store(StorageFactory factory, String region) { + RegionResolver regions = mock(RegionResolver.class); + when(regions.getDefaultRegion()).thenReturn("us-east-1"); + when(regions.getRegion()).thenReturn(region); + return new RegionScopedStorage<>(factory, regions, "appconfig", "records.json", new TypeReference<>() {}); + } + +} diff --git a/src/test/java/io/floci/aws/core/storage/StorageOperationsTest.java b/src/test/java/io/floci/aws/core/storage/StorageOperationsTest.java index 63a02f08fd..577fb0f1cc 100644 --- a/src/test/java/io/floci/aws/core/storage/StorageOperationsTest.java +++ b/src/test/java/io/floci/aws/core/storage/StorageOperationsTest.java @@ -1,5 +1,6 @@ package io.floci.aws.core.storage; +import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestContext; import jakarta.enterprise.inject.Instance; import org.junit.jupiter.api.Test; @@ -65,6 +66,37 @@ class StorageOperationsTest { verify(raw, never()).put(any(), any()); } + /** + * A Region view deletes its own Region's matches; in the default Region the regionless ones go too, + * the account store's unprefixed legacy keys included, as the account store deletes them itself. + */ + @ParameterizedTest + @ValueSource(strings = {"us-east-1", "eu-west-1"}) + void regionViewDeletionKeepsOtherRegionsAndLegacyOwnership(String region) { + InMemoryStorage raw = spy(new InMemoryStorage<>()); + raw.putAll(Map.of( + "db:legacy", "db", + "111111111111/db:regionless", "db", + "111111111111/us-east-1/db:east", "db", + "111111111111/eu-west-1/db:west", "db", + "111111111111/eu-west-1/db:neighbor:kept", "neighbor")); + RegionResolver regions = mock(RegionResolver.class); + when(regions.getDefaultRegion()).thenReturn("us-east-1"); + when(regions.getRegion()).thenReturn(region); + RegionScopedStorage storage = new RegionScopedStorage<>( + new AccountAwareStorageBackend<>(raw, null, "111111111111"), regions); + clearInvocations(raw); + + StorageOperations.deleteMatchingAtomically(storage, "db"::equals); + + Set removed = region.equals("us-east-1") + ? Set.of("db:legacy", "111111111111/db:regionless", "111111111111/us-east-1/db:east") + : Set.of("111111111111/eu-west-1/db:west"); + verify(raw).deleteAllAtomically(removed); + verify(raw, never()).delete(any()); + verify(raw, never()).put(any(), any()); + } + @Test void failedAtomicDeletionDoesNotMigrateLegacyEntries() { InMemoryStorage raw = spy(new InMemoryStorage<>()); diff --git a/src/test/java/io/floci/aws/services/appconfig/AppConfigDataServiceTest.java b/src/test/java/io/floci/aws/services/appconfig/AppConfigDataServiceTest.java index e8f52ccc5b..06ac453132 100644 --- a/src/test/java/io/floci/aws/services/appconfig/AppConfigDataServiceTest.java +++ b/src/test/java/io/floci/aws/services/appconfig/AppConfigDataServiceTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; 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.storage.RegionScopedStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.services.appconfig.model.ConfigurationSession; import io.floci.aws.testing.InMemoryStorageFactory; @@ -39,7 +40,7 @@ class AppConfigDataServiceTest { AppConfigService appConfig = mock(AppConfigService.class); RegionResolver regions = new RegionResolver("us-east-1", "000000000000"); AppConfigDataService service = new AppConfigDataService(factory, appConfig, MAPPER, regions); - StorageBackend sessions = new AppConfigStorage<>(factory, regions, "appconfigdata", + StorageBackend sessions = new RegionScopedStorage<>(factory, regions, "appconfigdata", "appconfigdata-sessions.json", new TypeReference>() {}); ConfigurationSession session = new ConfigurationSession(); session.setApplicationId("app"); diff --git a/src/test/java/io/floci/aws/services/appconfig/AppConfigStorageTest.java b/src/test/java/io/floci/aws/services/appconfig/AppConfigStorageTest.java deleted file mode 100644 index 69e5871e23..0000000000 --- a/src/test/java/io/floci/aws/services/appconfig/AppConfigStorageTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package io.floci.aws.services.appconfig; - -import com.fasterxml.jackson.core.type.TypeReference; -import io.floci.aws.core.common.RegionResolver; -import io.floci.aws.core.storage.StorageBackend; -import io.floci.aws.core.storage.StorageFactory; -import io.floci.aws.testing.StorageFactories; -import org.junit.jupiter.api.io.TempDir; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -import java.nio.file.Path; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -class AppConfigStorageTest { - @TempDir - Path directory; - - @ParameterizedTest - @ValueSource(strings = {"memory", "persistent", "hybrid", "wal"}) - void legacyKeysAndScopedKeysCannotEscapeTheirRegion(String mode) { - StorageFactory factory = StorageFactories.open(directory, mode, "000000000000"); - try { - StorageBackend legacy = factory.create( - "appconfig", "records.json", new TypeReference<>() {}); - legacy.put("existing", "legacy"); - AppConfigStorage east = store(factory, "us-east-1"); - AppConfigStorage west = store(factory, "us-west-2"); - assertEquals(Optional.of("legacy"), east.get("existing")); - assertEquals(Optional.empty(), west.get("existing")); - east.put("existing", "east"); - west.put("existing", "west"); - legacy.put("untouched", "older-record"); - - assertEquals(Optional.empty(), legacy.get("existing")); - assertEquals(Optional.of("east"), east.get("existing")); - assertEquals(Optional.of("west"), west.get("existing")); - assertEquals(Set.of("existing", "untouched"), east.keys()); - assertEquals(Set.of("existing"), west.keys()); - assertEquals(List.of("west"), west.scan(key -> key.equals("existing"))); - List selected = west.scan(key -> true); - selected.clear(); - assertEquals(List.of("west"), west.scan(key -> true)); - - assertEquals(Optional.empty(), east.get("us-west-2/existing")); - east.delete("us-west-2/existing"); - assertThrows(IllegalArgumentException.class, () -> east.put("us-west-2/existing", "wrong")); - assertEquals(Optional.of("west"), west.get("existing")); - east.clear(); - assertEquals(Set.of(), east.keys()); - assertEquals(Optional.of("west"), west.get("existing")); - } finally { - factory.shutdownAll(); - } - } - - private static AppConfigStorage store(StorageFactory factory, String region) { - RegionResolver regions = mock(RegionResolver.class); - when(regions.getDefaultRegion()).thenReturn("us-east-1"); - when(regions.getRegion()).thenReturn(region); - return new AppConfigStorage<>(factory, regions, "appconfig", "records.json", new TypeReference<>() {}); - } - -} diff --git a/src/test/java/io/floci/aws/services/athena/AthenaQueryScopeTest.java b/src/test/java/io/floci/aws/services/athena/AthenaQueryScopeTest.java new file mode 100644 index 0000000000..816c7c83f3 --- /dev/null +++ b/src/test/java/io/floci/aws/services/athena/AthenaQueryScopeTest.java @@ -0,0 +1,103 @@ +package io.floci.aws.services.athena; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.athena.model.QueryExecutionContext; +import io.floci.aws.services.athena.model.QueryExecutionState; +import io.floci.aws.services.floci.duck.FlociDuckClient; +import io.floci.aws.services.glue.GlueService; +import io.floci.aws.services.glue.model.Database; +import io.floci.aws.services.s3.S3Service; +import io.floci.aws.testing.TestAccounts; +import io.quarkus.test.junit.QuarkusTest; +import io.vertx.core.Vertx; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * A query runs on a worker after the call that started it has returned, with no request scope of its own; + * it still reads the Glue catalog of the account and Region it was started in, and its record stays in + * that account. Runs under Quarkus, where a scope sets the account and the Region; the duck client is + * stubbed and hands back the DDL the query was set up with. + */ +@QuarkusTest +class AthenaQueryScopeTest { + + private static final String REGION = "eu-west-1"; + + @Inject + StorageFactory storageFactory; + + @Inject + GlueService glueService; + + @Inject + GlueViewDdlBuilder ddlBuilder; + + @Inject + RegionResolver regionResolver; + + @Inject + Vertx vertx; + + @Test + void aQueryReadsTheCatalogOfTheAccountAndRegionItWasStartedIn() throws Exception { + String account = TestAccounts.randomId(); + String database = "scope_" + account; + // The setup DDL the query reads the catalog through, and the account its S3 reads and writes go to. + CompletableFuture> handedToDuck = new CompletableFuture<>(); + FlociDuckClient duckClient = mock(FlociDuckClient.class); + doAnswer(invocation -> { + handedToDuck.complete(List.of(invocation.getArgument(1), invocation.getArgument(3))); + return null; + }).when(duckClient).execute(anyString(), any(), any(), any()); + AthenaService athena = new AthenaService(storageFactory, duckClient, glueService, mock(S3Service.class), + realQueries(), vertx, ddlBuilder, regionResolver); + try { + String expected = RequestScopes.callAs(account, REGION, () -> { + glueService.createDatabase(new Database(database)); + return ddlBuilder.build(database); + }); + assertNotEquals(RequestScopes.callAs(account, "us-east-1", () -> ddlBuilder.build(database)), expected); + QueryExecutionContext context = new QueryExecutionContext(); + context.setDatabase(database); + + String id = RequestScopes.callAs(account, REGION, + () -> athena.startQueryExecution("SELECT 1", "primary", context, null)); + + assertEquals(List.of(expected, account), handedToDuck.get(10, TimeUnit.SECONDS)); + await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(50)).untilAsserted(() -> + assertEquals(QueryExecutionState.SUCCEEDED, RequestScopes.callAs(account, REGION, + () -> athena.getQueryExecution(id).getStatus().getState()))); + } finally { + RequestScopes.runAs(account, REGION, () -> glueService.deleteDatabase(database)); + } + } + + /** A configuration under which a query is handed to the duck client rather than answered at once. */ + private static EmulatorConfig realQueries() { + EmulatorConfig config = mock(EmulatorConfig.class); + EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); + EmulatorConfig.AthenaServiceConfig athena = mock(EmulatorConfig.AthenaServiceConfig.class); + when(config.services()).thenReturn(services); + when(services.athena()).thenReturn(athena); + when(athena.mock()).thenReturn(false); + return config; + } +} diff --git a/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java b/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java index cfc92d3b3f..42c80367e9 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java @@ -84,7 +84,7 @@ class AthenaServiceTest { release.await(10, TimeUnit.SECONDS); finished.countDown(); return null; - }).when(duckClient).execute(anyString(), any(), any()); + }).when(duckClient).execute(anyString(), any(), any(), any()); String id = service.startQueryExecution("SELECT 1", "primary", null, null); assertTrue(started.await(10, TimeUnit.SECONDS), "the worker never started"); @@ -108,7 +108,7 @@ class AthenaServiceTest { release.await(10, TimeUnit.SECONDS); finished.countDown(); throw new IllegalStateException("duck failed"); - }).when(duckClient).execute(anyString(), any(), any()); + }).when(duckClient).execute(anyString(), any(), any(), any()); String id = service.startQueryExecution("SELECT 1", "primary", null, null); assertTrue(started.await(10, TimeUnit.SECONDS), "the worker never started"); @@ -135,7 +135,7 @@ class AthenaServiceTest { void stopAfterFailureLeavesTheExecutionFailed() throws Exception { doAnswer(invocation -> { throw new IllegalStateException("duck failed"); - }).when(duckClient).execute(anyString(), any(), any()); + }).when(duckClient).execute(anyString(), any(), any(), any()); String id = service.startQueryExecution("SELECT 1", "primary", null, null); @@ -150,7 +150,7 @@ class AthenaServiceTest { void getQueryResultsReportsTheSqlTypeOfEachColumn() throws Exception { String query = "SELECT CAST(1 AS BIGINT) AS n, CAST(1.5 AS DOUBLE) AS d, true AS b, " + "DATE '2026-01-01' AS dt, CAST(2.50 AS DECIMAL(10,2)) AS p, 'x' AS s"; - when(duckClient.query(eq("DESCRIBE " + query), any())).thenReturn(List.of( + when(duckClient.query(eq("DESCRIBE " + query), any(), any())).thenReturn(List.of( Map.of("column_name", "n", "column_type", "BIGINT"), Map.of("column_name", "d", "column_type", "DOUBLE"), Map.of("column_name", "b", "column_type", "BOOLEAN"), @@ -166,7 +166,7 @@ class AthenaServiceTest { @Test void getQueryResultsReportsThePrecisionAndScaleOfADecimalColumn() throws Exception { String query = "SELECT CAST(2.50 AS DECIMAL(10,2)) AS p"; - when(duckClient.query(eq("DESCRIBE " + query), any())).thenReturn(List.of( + when(duckClient.query(eq("DESCRIBE " + query), any(), any())).thenReturn(List.of( Map.of("column_name", "p", "column_type", "DECIMAL(10,2)"))); ResultSet.ColumnInfo column = columnInfo(query, "p\n2.50\n").get(0); @@ -179,7 +179,7 @@ class AthenaServiceTest { @Test void getQueryResultsReportsTimeAndTimestampVariantsByTheirAthenaNames() throws Exception { String query = "SELECT t, ts_s, ts_ms, ts_ns, ts_tz, t_tz FROM times"; - when(duckClient.query(eq("DESCRIBE " + query), any())).thenReturn(List.of( + when(duckClient.query(eq("DESCRIBE " + query), any(), any())).thenReturn(List.of( Map.of("column_name", "t", "column_type", "TIME"), Map.of("column_name", "ts_s", "column_type", "TIMESTAMP_S"), Map.of("column_name", "ts_ms", "column_type", "TIMESTAMP_MS"), @@ -195,7 +195,7 @@ class AthenaServiceTest { @Test void getQueryResultsReportsVarcharWhenTheTypesCannotBeDescribed() throws Exception { - when(duckClient.query(anyString(), any())).thenThrow(new IllegalStateException("not describable")); + when(duckClient.query(anyString(), any(), any())).thenThrow(new IllegalStateException("not describable")); assertEquals(List.of("varchar", "varchar"), columnInfo("SELECT 1 AS a, 2 AS b", "a,b\n1,2\n").stream() .map(ResultSet.ColumnInfo::getType).toList()); diff --git a/src/test/java/io/floci/aws/services/firehose/FirehoseFlushRegionTest.java b/src/test/java/io/floci/aws/services/firehose/FirehoseFlushRegionTest.java new file mode 100644 index 0000000000..424bbe6eda --- /dev/null +++ b/src/test/java/io/floci/aws/services/firehose/FirehoseFlushRegionTest.java @@ -0,0 +1,100 @@ +package io.floci.aws.services.firehose; + +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.services.s3.S3Service; +import io.floci.aws.services.s3.model.PutObjectOptions; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.FirehoseRequests; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.mockito.InjectSpy; +import io.restassured.response.ValidatableResponse; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; + +/** + * A flush outside any request, as the scheduled one runs, delivers as its stream's account and in its + * stream's Region: every store the delivery touches, the Regional Glue catalog included, reads both from + * the request scope. + */ +@QuarkusTest +class FirehoseFlushRegionTest { + + private static final AtomicLong ACCOUNTS = new AtomicLong(731200000000L); + private static final String REGION = "eu-west-1"; + + @InjectSpy + S3Service s3Service; + + @Inject + FirehoseService firehoseService; + + @Inject + RegionResolver regionResolver; + + @TestHTTPResource + URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureAwsJson() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aFlushOutsideARequestDeliversInItsStreamsAccountAndRegion() { + String account = Long.toString(ACCOUNTS.incrementAndGet()); + String stream = "flush-region-" + account; + String bucket = "flush-region-" + account; + AtomicReference scope = new AtomicReference<>(); + doAnswer(invocation -> { + scope.set(regionResolver.getAccountId() + " " + regionResolver.getRegion()); + return invocation.callRealMethod(); + }).when(s3Service).putObject(eq(bucket), anyString(), any(byte[].class), anyString(), anyMap(), + any(PutObjectOptions.class)); + firehose(account, "CreateDeliveryStream", """ + {"DeliveryStreamName": "%s", "DeliveryStreamType": "DirectPut", + "ExtendedS3DestinationConfiguration": { + "RoleARN": "arn:aws:iam::%s:role/firehose-delivery-role", + "BucketARN": "arn:aws:s3:::%s", + "BufferingHints": {"SizeInMBs": 5, "IntervalInSeconds": 60}}} + """.formatted(stream, account, bucket)).statusCode(200); + cleanup.register(() -> EnforcementFixtures.removeBucket(baseUri.getPort(), + EnforcementFixtures.auth(account, "s3"), bucket)); + cleanup.register(() -> firehose(account, "DeleteDeliveryStream", + "{\"DeliveryStreamName\": \"" + stream + "\"}")); + firehose(account, "PutRecord", "{\"DeliveryStreamName\": \"" + stream + "\", \"Record\": {\"Data\": \"" + + FirehoseRequests.encode("{\"n\":1}") + "\"}}").statusCode(200); + + firehoseService.flush(account, REGION, stream); + + assertEquals(account + " " + REGION, scope.get()); + } + + private static ValidatableResponse firehose(String account, String action, String body) { + return given().contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "Firehose_20150804." + action) + .header("Authorization", EnforcementFixtures.auth(account, REGION, "firehose")) + .body(body) + .when().post("/") + .then(); + } +} diff --git a/src/test/java/io/floci/aws/services/firehose/FirehoseParquetConverterTest.java b/src/test/java/io/floci/aws/services/firehose/FirehoseParquetConverterTest.java index 8cc491387a..e565e86048 100644 --- a/src/test/java/io/floci/aws/services/firehose/FirehoseParquetConverterTest.java +++ b/src/test/java/io/floci/aws/services/firehose/FirehoseParquetConverterTest.java @@ -65,9 +65,9 @@ import static org.mockito.Mockito.when; */ class FirehoseParquetConverterTest { - private static final String BUCKET = "results"; - private static final String STAGING = "floci-firehose-staging"; - private static final Instant DELIVERY_TIME = Instant.parse("2026-01-01T00:00:00Z"); + static final String BUCKET = "results"; + static final String STAGING = "floci-firehose-staging"; + static final Instant DELIVERY_TIME = Instant.parse("2026-01-01T00:00:00Z"); private static final byte[] STAGED_PARQUET = "PAR1staged".getBytes(StandardCharsets.UTF_8); private GlueService glueService; @@ -94,7 +94,7 @@ class FirehoseParquetConverterTest { new Column("ts", "timestamp"))); } - private static Table table(Column... columns) { + static Table table(Column... columns) { StorageDescriptor descriptor = new StorageDescriptor(); descriptor.setColumns(Arrays.asList(columns)); Table table = new Table(); @@ -102,7 +102,7 @@ class FirehoseParquetConverterTest { return table; } - private static DeliveryStreamDescription stream() { + static DeliveryStreamDescription stream() { SchemaConfiguration schema = new SchemaConfiguration(); schema.setRoleArn("arn:aws:iam::000000000000:role/firehose-role"); schema.setDatabaseName("db"); @@ -130,7 +130,7 @@ class FirehoseParquetConverterTest { return new DeliveryStreamDescription("stream", "arn:aws:firehose:::stream", s3); } - private static byte[] record(String json) { + static byte[] record(String json) { return (json + "\n").getBytes(StandardCharsets.UTF_8); } diff --git a/src/test/java/io/floci/aws/services/firehose/FirehoseParquetSchemaRegionTest.java b/src/test/java/io/floci/aws/services/firehose/FirehoseParquetSchemaRegionTest.java new file mode 100644 index 0000000000..da91e7a73b --- /dev/null +++ b/src/test/java/io/floci/aws/services/firehose/FirehoseParquetSchemaRegionTest.java @@ -0,0 +1,68 @@ +package io.floci.aws.services.firehose; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.services.firehose.model.DeliveryStreamDescription; +import io.floci.aws.services.floci.duck.FlociDuckClient; +import io.floci.aws.services.glue.GlueService; +import io.floci.aws.services.glue.model.Column; +import io.floci.aws.services.s3.S3Service; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * A Parquet conversion reads its Glue table in SchemaConfiguration.Region when the stream names one, as + * AWS does, and in the Region the delivery runs in otherwise. The Glue catalog is Regional, so the Region + * decides which table is found. Runs under Quarkus, where a scoped call can set the Region; each delivery + * runs in a Region that is not the default, as a scheduled flush runs in its stream's. + */ +@QuarkusTest +class FirehoseParquetSchemaRegionTest { + + private static final String ACCOUNT = "000000000000"; + private static final String DELIVERY_REGION = "ap-southeast-2"; + + @Inject + RegionResolver regionResolver; + + @Test + void theSchemasTableIsReadInTheRegionItsConfigurationNames() { + assertEquals("eu-west-1", RequestScopes.callAs(ACCOUNT, DELIVERY_REGION, + () -> regionOfTheTableRead("eu-west-1"))); + } + + @Test + void withoutARegionTheTableIsReadInTheDeliverysOwnRegion() { + assertEquals(DELIVERY_REGION, RequestScopes.callAs(ACCOUNT, DELIVERY_REGION, + () -> regionOfTheTableRead(null))); + } + + /** The Region current when the converter read the Glue table, for a schema naming {@code schemaRegion}. */ + private String regionOfTheTableRead(String schemaRegion) { + GlueService glueService = mock(GlueService.class); + AtomicReference region = new AtomicReference<>(); + when(glueService.getTable("db", "events")).thenAnswer(invocation -> { + region.set(regionResolver.getRegion()); + return FirehoseParquetConverterTest.table(new Column("ticker", "string")); + }); + FirehoseParquetConverter converter = new FirehoseParquetConverter(glueService, mock(FlociDuckClient.class), + mock(S3Service.class), new ObjectMapper(), regionResolver, FirehoseParquetConverterTest.STAGING); + DeliveryStreamDescription stream = FirehoseParquetConverterTest.stream(); + stream.s3Destination().getDataFormatConversionConfiguration().getSchemaConfiguration().setRegion(schemaRegion); + + converter.deliver(stream, FirehoseParquetConverterTest.BUCKET, + List.of(FirehoseParquetConverterTest.record("{\"ticker\": \"AAA\"}")), + FirehoseParquetConverterTest.DELIVERY_TIME); + + return region.get(); + } +} diff --git a/src/test/java/io/floci/aws/services/glue/GlueDataQualityRulesetIntegrationTest.java b/src/test/java/io/floci/aws/services/glue/GlueDataQualityRulesetIntegrationTest.java index d6943f5db0..78975303b7 100644 --- a/src/test/java/io/floci/aws/services/glue/GlueDataQualityRulesetIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/glue/GlueDataQualityRulesetIntegrationTest.java @@ -3,14 +3,13 @@ package io.floci.aws.services.glue; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; -import io.restassured.response.ValidatableResponse; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.List; import java.util.UUID; -import static io.restassured.RestAssured.given; +import static io.floci.aws.testing.GlueRequests.call; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; @@ -29,7 +28,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class GlueDataQualityRulesetIntegrationTest { private static final ObjectMapper MAPPER = new ObjectMapper(); - private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; private static final String REGION = "us-east-1"; private static final String RULESET = "Rules = [ RowCount > 0, IsComplete \"id\", " + "(ColumnValues \"age\" > 0) and (ColumnValues \"age\" < 150) ]"; @@ -253,15 +251,6 @@ class GlueDataQualityRulesetIntegrationTest { .extract().jsonPath().getList("Rulesets.Name", String.class); } - private static ValidatableResponse call(String action, String account, String region, String body) { - return given().contentType(CONTENT_TYPE) - .header("X-Amz-Target", "AWSGlue." + action) - .header("Authorization", authorization(account, region)) - .body(body) - .when().post("/") - .then(); - } - private static String json(String text) { return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; } @@ -269,9 +258,4 @@ class GlueDataQualityRulesetIntegrationTest { private static String unique(String prefix) { return prefix + "-" + UUID.randomUUID().toString().substring(0, 8); } - - private static String authorization(String account, String region) { - return "AWS4-HMAC-SHA256 Credential=" + account - + "/20260918/" + region + "/glue/aws4_request, SignedHeaders=host, Signature=abc"; - } } diff --git a/src/test/java/io/floci/aws/services/glue/GlueRegionScopingIntegrationTest.java b/src/test/java/io/floci/aws/services/glue/GlueRegionScopingIntegrationTest.java new file mode 100644 index 0000000000..a0ef75c8d2 --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/GlueRegionScopingIntegrationTest.java @@ -0,0 +1,141 @@ +package io.floci.aws.services.glue; + +import io.floci.aws.testing.GlueRequests; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The Glue Data Catalog and Glue's ETL resources are Regional, as on AWS: a resource created in one Region + * is listed and reached only there, and its name can be used again in another Region of the account. Each + * test works in an account of its own, so a listing holds only what that test created. + */ +@QuarkusTest +class GlueRegionScopingIntegrationTest { + + private static final AtomicLong ACCOUNTS = new AtomicLong(731100000000L); + private static final String ROLE = "arn:aws:iam::000000000000:role/glue"; + + /** + * One resource of each type: its name; how to create, get and delete it; how to list its type, and where + * the listing puts the names. + */ + private record Kind(String resource, String createAction, String createBody, String getAction, + String getBody, String deleteAction, String deleteBody, String listAction, + String listBody, String names) {} + + private static final List KINDS = List.of( + new Kind("sales", "CreateDatabase", "{\"DatabaseInput\":{\"Name\":\"sales\"}}", + "GetDatabase", "{\"Name\":\"sales\"}", "DeleteDatabase", "{\"Name\":\"sales\"}", + "GetDatabases", "{}", "DatabaseList.Name"), + new Kind("orders", "CreateTable", "{\"DatabaseName\":\"sales\",\"TableInput\":{\"Name\":\"orders\"}}", + "GetTable", "{\"DatabaseName\":\"sales\",\"Name\":\"orders\"}", + "DeleteTable", "{\"DatabaseName\":\"sales\",\"Name\":\"orders\"}", + "GetTables", "{\"DatabaseName\":\"sales\"}", "TableList.Name"), + new Kind("etl", "CreateJob", "{\"Name\":\"etl\",\"Role\":\"" + ROLE + + "\",\"Command\":{\"Name\":\"glueetl\",\"ScriptLocation\":\"s3://b/s.py\"}}", + "GetJob", "{\"JobName\":\"etl\"}", "DeleteJob", "{\"JobName\":\"etl\"}", + "ListJobs", "{}", "JobNames"), + new Kind("warehouse", "CreateConnection", "{\"ConnectionInput\":{\"Name\":\"warehouse\"," + + "\"ConnectionType\":\"JDBC\",\"ConnectionProperties\":{\"JDBC_CONNECTION_URL\":" + + "\"jdbc:mysql://h:3306/d\",\"USERNAME\":\"u\",\"PASSWORD\":\"p\"}}}", + "GetConnection", "{\"Name\":\"warehouse\"}", + "DeleteConnection", "{\"ConnectionName\":\"warehouse\"}", + "GetConnections", "{}", "ConnectionList.Name"), + new Kind("crawl", "CreateCrawler", "{\"Name\":\"crawl\",\"Role\":\"" + ROLE + + "\",\"Targets\":{\"S3Targets\":[{\"Path\":\"s3://b/p\"}]}}", + "GetCrawler", "{\"Name\":\"crawl\"}", "DeleteCrawler", "{\"Name\":\"crawl\"}", + "ListCrawlers", "{}", "CrawlerNames"), + new Kind("csv", "CreateClassifier", "{\"CsvClassifier\":{\"Name\":\"csv\"}}", + "GetClassifier", "{\"Name\":\"csv\"}", "DeleteClassifier", "{\"Name\":\"csv\"}", + "GetClassifiers", "{}", "Classifiers.CsvClassifier.Name"), + new Kind("nightly", "CreateWorkflow", "{\"Name\":\"nightly\"}", + "GetWorkflow", "{\"Name\":\"nightly\"}", "DeleteWorkflow", "{\"Name\":\"nightly\"}", + "ListWorkflows", "{}", "Workflows"), + new Kind("start", "CreateTrigger", "{\"Name\":\"start\",\"Type\":\"ON_DEMAND\"," + + "\"Actions\":[{\"JobName\":\"etl\"}]}", + "GetTrigger", "{\"Name\":\"start\"}", "DeleteTrigger", "{\"Name\":\"start\"}", + "ListTriggers", "{}", "TriggerNames")); + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private String account; + + @BeforeAll + static void configureAwsJson() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void accountOfItsOwn() { + account = Long.toString(ACCOUNTS.incrementAndGet()); + } + + @Test + void eachResourceIsSeenOnlyInTheRegionItWasCreatedIn() { + createAll("us-east-1"); + + for (Kind kind : KINDS) { + assertEquals(List.of(), names("eu-west-1", kind), kind.listAction()); + glue("eu-west-1", kind.getAction(), kind.getBody()) + .statusCode(400).body("__type", equalTo("EntityNotFoundException")); + } + + createAll("eu-west-1"); + + for (Kind kind : KINDS) { + for (String region : List.of("us-east-1", "eu-west-1")) { + assertEquals(List.of(kind.resource()), names(region, kind), region + " " + kind.listAction()); + glue(region, kind.getAction(), kind.getBody()).statusCode(200); + } + } + } + + @Test + void deletingADatabaseInOneRegionLeavesTheOthersCatalog() { + for (String region : List.of("us-east-1", "eu-west-1")) { + create(region, KINDS.get(0)); + create(region, KINDS.get(1)); + } + + glue("eu-west-1", "DeleteDatabase", "{\"Name\":\"sales\"}").statusCode(200); + + glue("eu-west-1", "GetDatabase", "{\"Name\":\"sales\"}") + .statusCode(400).body("__type", equalTo("EntityNotFoundException")); + glue("us-east-1", "GetTable", "{\"DatabaseName\":\"sales\",\"Name\":\"orders\"}") + .statusCode(200).body("Table.Name", equalTo("orders")); + } + + /** Creates one resource of each kind in {@code region}, each deleted after the test. */ + private void createAll(String region) { + KINDS.forEach(kind -> create(region, kind)); + } + + /** Creates {@code kind}'s resource in {@code region}; the cleanup deletes it, unless the test already did. */ + private void create(String region, Kind kind) { + glue(region, kind.createAction(), kind.createBody()).statusCode(200); + cleanup.register(() -> glue(region, kind.deleteAction(), kind.deleteBody())); + } + + /** The names {@code region} lists for the kind's type. */ + private List names(String region, Kind kind) { + return glue(region, kind.listAction(), kind.listBody()).statusCode(200) + .extract().jsonPath().getList(kind.names(), String.class); + } + + private ValidatableResponse glue(String region, String action, String body) { + return GlueRequests.call(action, account, region, body); + } +} diff --git a/src/test/java/io/floci/aws/services/glue/GlueSecurityConfigurationIntegrationTest.java b/src/test/java/io/floci/aws/services/glue/GlueSecurityConfigurationIntegrationTest.java index fff9740e06..1659b52840 100644 --- a/src/test/java/io/floci/aws/services/glue/GlueSecurityConfigurationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/glue/GlueSecurityConfigurationIntegrationTest.java @@ -3,6 +3,7 @@ package io.floci.aws.services.glue; import com.fasterxml.jackson.core.type.TypeReference; import io.floci.aws.core.storage.PersistentStorage; import io.floci.aws.services.glue.model.SecurityConfiguration; +import io.floci.aws.testing.GlueRequests; import io.floci.aws.testing.PartitionCleanup; import io.floci.aws.testing.PersistentStorageProfile; import io.floci.aws.testing.RestAssuredJsonUtils; @@ -117,20 +118,12 @@ class GlueSecurityConfigurationIntegrationTest { create(NAME, "us-east-1", "000000000001"); cleanup.register(() -> delete(NAME, "us-east-1", "000000000001")); - given().contentType(CONTENT_TYPE) - .header("X-Amz-Target", "AWSGlue.GetSecurityConfiguration") - .header("Authorization", authorization("000000000002", "us-east-1")) - .body("{\"Name\":\"" + NAME + "\"}") - .when().post("/") - .then().statusCode(400) + GlueRequests.call("GetSecurityConfiguration", "000000000002", "us-east-1", "{\"Name\":\"" + NAME + "\"}") + .statusCode(400) .body("__type", containsString("EntityNotFoundException")); - given().contentType(CONTENT_TYPE) - .header("X-Amz-Target", "AWSGlue.GetSecurityConfiguration") - .header("Authorization", authorization("000000000001", "us-west-2")) - .body("{\"Name\":\"" + NAME + "\"}") - .when().post("/") - .then().statusCode(400) + GlueRequests.call("GetSecurityConfiguration", "000000000001", "us-west-2", "{\"Name\":\"" + NAME + "\"}") + .statusCode(400) .body("__type", containsString("EntityNotFoundException")); PersistentStorage store = new PersistentStorage<>( @@ -141,37 +134,21 @@ class GlueSecurityConfigurationIntegrationTest { } private static void create(String name, String region, String account) { - given().contentType(CONTENT_TYPE) - .header("X-Amz-Target", "AWSGlue.CreateSecurityConfiguration") - .header("Authorization", authorization(account, region)) - .body("{\"Name\":\"" + name + "\",\"EncryptionConfiguration\":" + ENCRYPTION + "}") - .when().post("/") - .then().statusCode(200) + GlueRequests.call("CreateSecurityConfiguration", account, region, + "{\"Name\":\"" + name + "\",\"EncryptionConfiguration\":" + ENCRYPTION + "}") + .statusCode(200) .body("Name", equalTo(name)) .body("CreatedTimestamp", instanceOf(Number.class)); } private static void delete(String name, String region, String account) { - given().contentType(CONTENT_TYPE) - .header("X-Amz-Target", "AWSGlue.DeleteSecurityConfiguration") - .header("Authorization", authorization(account, region)) - .body("{\"Name\":\"" + name + "\"}") - .when().post("/") - .then().statusCode(200); + GlueRequests.call("DeleteSecurityConfiguration", account, region, "{\"Name\":\"" + name + "\"}") + .statusCode(200); } /** For cleanup: each test deletes its configuration itself, unless an assertion stops it. */ private static void deleteIfPresent(String name, String region, String account) { - given().contentType(CONTENT_TYPE) - .header("X-Amz-Target", "AWSGlue.DeleteSecurityConfiguration") - .header("Authorization", authorization(account, region)) - .body("{\"Name\":\"" + name + "\"}") - .when().post("/") - .then().statusCode(anyOf(equalTo(200), equalTo(400))); - } - - private static String authorization(String account, String region) { - return "AWS4-HMAC-SHA256 Credential=" + account - + "/20260918/" + region + "/glue/aws4_request, SignedHeaders=host, Signature=abc"; + GlueRequests.call("DeleteSecurityConfiguration", account, region, "{\"Name\":\"" + name + "\"}") + .statusCode(anyOf(equalTo(200), equalTo(400))); } } diff --git a/src/test/java/io/floci/aws/services/glue/GlueServiceTest.java b/src/test/java/io/floci/aws/services/glue/GlueServiceTest.java index a99da7e866..53d124a746 100644 --- a/src/test/java/io/floci/aws/services/glue/GlueServiceTest.java +++ b/src/test/java/io/floci/aws/services/glue/GlueServiceTest.java @@ -8,6 +8,7 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.core.storage.PersistentStorage; +import io.floci.aws.core.storage.RegionScopedStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.glue.model.AuthenticationConfiguration; @@ -2406,7 +2407,9 @@ class GlueServiceTest { ACCOUNT_ID + "/db1:neighbor:legacy", function("db1:neighbor", "legacy"))); PersistentStorage reloaded = new PersistentStorage<>(file, new TypeReference<>() {}); reloaded.load(); - setUp(new InMemoryStorage<>(), new AccountAwareStorageBackend<>(reloaded, null, ACCOUNT_ID)); + // As GlueService's own constructor builds it: the Region view over the account store. + setUp(new InMemoryStorage<>(), new RegionScopedStorage<>( + new AccountAwareStorageBackend<>(reloaded, null, ACCOUNT_ID), new RegionResolver(REGION, ACCOUNT_ID))); glueService.deleteDatabase("db1"); glueService.createDatabase(new Database("db1")); diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java index 524f3aa7f7..5ff8e2fe54 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java @@ -980,6 +980,25 @@ class RedshiftServiceTest { autoCopyConsumer); } + /** + * Work done outside a request on a cluster's behalf, Redshift Spectrum over JDBC, learns the cluster's Region: the + * one it was created in, and the default Region for a cluster stored before clusters kept one. + */ + @Test + void aClustersRegionIsTheOneItWasCreatedIn() { + Cluster analytics = new Cluster(); + analytics.setClusterIdentifier("analytics"); + analytics.setSnapshotRegion("eu-west-1"); + Cluster legacy = new Cluster(); + legacy.setClusterIdentifier("legacy"); + when(clusterBackend.getForAccount("111111111111", "analytics")).thenReturn(Optional.of(analytics)); + when(clusterBackend.getForAccount("111111111111", "legacy")).thenReturn(Optional.of(legacy)); + + assertEquals(Optional.of("eu-west-1"), service.clusterRegion("111111111111", "analytics")); + assertEquals(Optional.of("us-east-1"), service.clusterRegion("111111111111", "legacy")); + assertEquals(Optional.empty(), service.clusterRegion("111111111111", "missing")); + } + private static final String ORDERS_TABLE_ARN = "arn:aws:dynamodb:us-east-1:111111111111:table/orders"; private static final String NAMESPACE_ARN = "arn:aws:redshift-serverless:us-east-1:111111111111:namespace/" + "8f3e0b52-6c1a-4f0e-9d7b-2a4c5e6f7a8b"; diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumCatalogRegionTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumCatalogRegionTest.java new file mode 100644 index 0000000000..e4db7afded --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumCatalogRegionTest.java @@ -0,0 +1,60 @@ +package io.floci.aws.services.redshift.spectrum; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.services.glue.GlueService; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiFunction; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Redshift Spectrum reads the Glue catalog of its cluster's Region, as on AWS, whatever Region the call runs + * in: over a JDBC connection that is no request's. Runs under Quarkus, where a scoped call sets the Region. + */ +@QuarkusTest +class SpectrumCatalogRegionTest { + + private static final String ROLE = "arn:aws:iam::000000000000:role/spectrum"; + private static final SpectrumSession SESSION = new SpectrumSession("000000000000", "000000000000:analytics", + "dev", List.of(ROLE), false); + + @Inject + RegionResolver regionResolver; + + @Test + void anExternalSchemaReadsTheCatalogOfTheClustersRegion() { + assertEquals("eu-west-1", regionOfTheCatalogRead( + (accountId, cluster) -> "analytics".equals(cluster) ? "eu-west-1" : null)); + } + + @Test + void aClusterFlociDoesNotKnowKeepsTheRegionTheCallRunsIn() { + assertEquals(regionResolver.getDefaultRegion(), regionOfTheCatalogRead((accountId, cluster) -> null)); + } + + /** The Region current when Spectrum looked the external schema's Glue database up. */ + private String regionOfTheCatalogRead(BiFunction clusterRegion) { + GlueService glue = mock(GlueService.class); + AtomicReference region = new AtomicReference<>(); + when(glue.getDatabase("sales")).thenAnswer(invocation -> { + region.set(regionResolver.getRegion()); + throw new AwsException("EntityNotFoundException", "Database not found: sales", 400); + }); + SpectrumQueryPreparation preparation = new SpectrumQueryPreparation(mock(ExternalCatalogRegistry.class), + mock(ExternalTableMaterializer.class), new ExternalStatementParser(), glue, + mock(ExternalMetadataWriter.class), new ExternalCatalogLocks(), clusterRegion); + + preparation.prepare("CREATE EXTERNAL SCHEMA lake FROM DATA CATALOG DATABASE 'sales' IAM_ROLE '" + ROLE + "'", + SESSION, mock(BackendSql.class)); + + return region.get(); + } +} diff --git a/src/test/java/io/floci/aws/services/s3/S3GlobalLegacyListingTest.java b/src/test/java/io/floci/aws/services/s3/S3GlobalLegacyListingTest.java index ca9ff1e319..243342c10b 100644 --- a/src/test/java/io/floci/aws/services/s3/S3GlobalLegacyListingTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3GlobalLegacyListingTest.java @@ -125,6 +125,14 @@ class S3GlobalLegacyListingTest { invocation.getArgument(1).run(); return null; })); + // A Firehose flush runs as the stream's account and in its Region. + scopes.when(() -> RequestScopes.callAs(anyString(), anyString(), any(Supplier.class))).thenAnswer(invocation -> + inScope(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2))); + scopes.when(() -> RequestScopes.runAs(anyString(), anyString(), any(Runnable.class))).thenAnswer(invocation -> + inScope(invocation.getArgument(0), invocation.getArgument(1), () -> { + invocation.getArgument(2).run(); + return null; + })); s3.createBucket(BUCKET, "us-east-1"); s3.putObject(BUCKET, "object.txt", "owner-data".getBytes(UTF_8), "text/plain", Map.of()); } @@ -246,4 +254,14 @@ class S3GlobalLegacyListingTest { request.setAccountId(previous); } } + + private T inScope(String account, String regionName, Supplier action) { + String previous = request.getRegion(); + request.setRegion(regionName); + try { + return inAccount(account, action); + } finally { + request.setRegion(previous); + } + } } diff --git a/src/test/java/io/floci/aws/testing/GlueRequests.java b/src/test/java/io/floci/aws/testing/GlueRequests.java new file mode 100644 index 0000000000..17ebb93dd1 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/GlueRequests.java @@ -0,0 +1,26 @@ +package io.floci.aws.testing; + +import io.restassured.response.ValidatableResponse; + +import static io.restassured.RestAssured.given; + +/** + * Glue JSON calls signed for an account and a Region, over the test's RestAssured port. The caller + * registers the AWS JSON content types first ({@link RestAssuredJsonUtils#configureAwsContentTypes}). + */ +public final class GlueRequests { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + + private GlueRequests() {} + + /** {@code AWSGlue.} with {@code body}, signed for {@code account} in {@code region}. */ + public static ValidatableResponse call(String action, String account, String region, String body) { + return given().contentType(CONTENT_TYPE) + .header("X-Amz-Target", "AWSGlue." + action) + .header("Authorization", EnforcementFixtures.auth(account, "20260918", region, "glue")) + .body(body) + .when().post("/") + .then(); + } +}