fix(glue): scope the Data Catalog and ETL resources to the request's Region (#8315)

This commit is contained in:
mrfelek authored and GitHub committed 2026-11-14 15:11:58 -04:00
1 parent 0816789e30
commit 7120e65ab3
35 files changed
+1101 -350

No files matched your search

@@ -466,14 +466,24 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
* keys only for the configured default account. Does not migrate or rewrite survivors.
*/
public synchronized void deleteMatchingIncludingLegacyAtomically(Predicate<V> 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<String> keyFilter,
Predicate<V> valueFilter) {
String account = prefix();
String accountPrefix = account + "/";
Set<String> 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);
}
}
@@ -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<V> implements StorageBackend<String, V> {
private final StorageBackend<String, V> delegate;
private final RegionResolver regions;
public RegionScopedStorage(StorageFactory factory, RegionResolver regions, String service, String file,
TypeReference<Map<String, V>> 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<String, V> 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<V> 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<V> scan(Predicate<String> keyFilter) {
List<V> values = new ArrayList<>();
for (String key : keys()) {
if (keyFilter.test(key)) {
get(key).ifPresent(values::add);
}
}
return values;
}
@Override
public Set<String> keys() {
String prefix = prefix();
boolean includeLegacy = defaultRegion();
Set<String> 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<String> keyFilter, Predicate<V> 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));
}
}
@@ -17,12 +17,23 @@ public final class StorageOperations {
/** Deletes matching values in one commit, preserving account ownership of legacy keys. */
public static <V> void deleteMatchingAtomically(StorageBackend<String, V> store, Predicate<V> 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 <V> void deleteMatchingAtomically(StorageBackend<String, V> store, Predicate<String> keyFilter,
Predicate<V> valueFilter) {
if (store instanceof AccountAwareStorageBackend<V> accountAware) {
accountAware.deleteMatchingIncludingLegacyAtomically(valueFilter);
accountAware.deleteMatchingIncludingLegacyAtomically(keyFilter, valueFilter);
} else if (store instanceof RegionScopedStorage<V> regional) {
regional.deleteMatchingAtomically(keyFilter, valueFilter);
} else {
Set<String> 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);
}
}
@@ -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;
@@ -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<>() {});
}
@@ -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<V> implements StorageBackend<String, V> {
private final StorageBackend<String, V> delegate;
private final RegionResolver regions;
AppConfigStorage(StorageFactory factory, RegionResolver regions, String service, String file,
TypeReference<Map<String, V>> 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<V> 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<V> scan(Predicate<String> keyFilter) {
List<V> values = new ArrayList<>();
for (String key : keys()) {
if (keyFilter.test(key)) {
get(key).ifPresent(values::add);
}
}
return values;
}
@Override
public Set<String> keys() {
String prefix = prefix();
boolean includeLegacy = defaultRegion();
Set<String> 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("/");
}
}
@@ -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<Table> 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<Table> 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<String> describeColumnTypes(String query, String setupDdl) {
private List<String> 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) {
@@ -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<SchemaColumn> 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<Column> columns = table.getStorageDescriptor() == null
? null : table.getStorageDescriptor().getColumns();
if (columns == null || columns.isEmpty()) {
@@ -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));
}
}
@@ -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());
}
@@ -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());
}
@@ -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<String, String> 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<String, String> 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<String, String> tags, String region) {
@@ -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);
}
@@ -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<String> 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<RedshiftMetricTarget> 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());
@@ -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) {
@@ -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<Character, byte[]> 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()) {
@@ -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<String, String, String> clusterRegion;
private final Map<BackendSql, List<ExternalSchemaBinding>> 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<RedshiftService> 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<String, String, String> 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<String> 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";
@@ -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 <account>:<identifier>} 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);
}
}