fix(s3tables): give each table a warehouse bucket and report its location (#8413)

GetTable and GetTableMetadataLocation never returned warehouseLocation,
which the S3 Tables model marks required, so Spark's S3TablesCatalog
had nowhere to write: CREATE TABLE failed with "Invalid S3 URI, cannot
determine scheme: null/metadata/00000-...metadata.json".

CreateTable now creates the table's warehouse, a bucket of its own named
like AWS's (<uuid>--table-s3), and both responses report it; a table
persisted before this gets one the first time it is read. An Iceberg
client writes the table's files there and commits with
UpdateTableMetadataLocation, which already existed. DeleteTable deletes
the warehouse with its contents, as deleting an S3 Tables table deletes
its data. GetTable also reports the required createdBy and modifiedBy.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-14 23:16:22 -04:00
1 parent 2cb54dad8f
commit b18feb39d1
7 files changed
+287 -12

No files matched your search

+11 -5
View File
@@ -9,13 +9,19 @@ convergence, and SDK integration tests. It is a separate AWS service from S3:
S3 Tables requests are signed as `s3tables` and use REST JSON routes such as
`/buckets` and `/tables/{tableBucketARN}/{namespace}`.
## Metadata-only scope
## Scope
This service stores table-bucket, namespace, table, policy, maintenance
configuration, and metadata-location state. It does **not** run an Apache
Iceberg engine or create data-plane artifacts: manifests, warehouse objects,
queries, compaction, snapshot expiry, replication, encryption-management, and
metrics are intentionally outside this implementation.
configuration, and metadata-location state, and gives every table a warehouse:
a bucket of its own, named like the ones AWS creates (`<id>--table-s3`), which
`GetTable` and `GetTableMetadataLocation` report as `warehouseLocation`. An
Iceberg client such as Spark's `S3TablesCatalog` writes the table's data and
metadata files there through Floci's S3 and commits each new metadata file
with `UpdateTableMetadataLocation`. Deleting the table deletes its warehouse
and everything in it, every object version included. A warehouse bucket is the
table's storage, not a general purpose bucket, so `ListBuckets` leaves it out. Floci does not run an Iceberg engine itself: compaction,
snapshot expiry, replication, encryption management, and metrics are outside
this implementation.
## Supported operations
@@ -127,6 +127,12 @@ public class S3Service implements Resettable, ResourceProvider {
public static final String REDSHIFT_UNLOAD_STAGING_TAG_VALUE = "redshift-unload-staging";
public static final String INTERNAL_BUCKET_TAG_KEY = "floci:internal";
public static final String REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE = "redshift-spectrum-scratch";
/**
* The suffix S3 Tables gives the bucket behind each table's warehouse. Such a bucket is the table's
* storage, not a general purpose bucket, so it is left out of {@code ListBuckets} as on AWS.
*/
public static final String TABLE_WAREHOUSE_BUCKET_SUFFIX = "--table-s3";
private static final String AUTHENTICATED_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
private static final String LOG_DELIVERY_GROUP_URI = "http://acs.amazonaws.com/groups/s3/LogDelivery";
private static final String LEGACY_ACCESS_KEY_ID = "test";
@@ -669,6 +675,7 @@ public class S3Service implements Resettable, ResourceProvider {
public List<Bucket> listBuckets() {
return bucketStore.scan(key -> true).stream()
.filter(bucket -> !isScratchBucket(bucket))
.filter(bucket -> !bucket.getName().endsWith(TABLE_WAREHOUSE_BUCKET_SUFFIX))
.toList();
}
@@ -280,8 +280,11 @@ public class S3TablesController {
response.put("namespace", List.of(table.getNamespace()));
response.put("versionToken", table.getVersionToken());
putIfNotNull(response, "metadataLocation", table.getMetadataLocation());
putIfNotNull(response, "warehouseLocation", table.getWarehouseLocation());
response.put("createdAt", table.getCreatedAt());
response.put("createdBy", table.getOwnerAccountId());
response.put("modifiedAt", table.getModifiedAt());
response.put("modifiedBy", table.getOwnerAccountId());
response.put("ownerAccountId", table.getOwnerAccountId());
response.put("format", table.getFormat());
return response;
@@ -291,6 +294,7 @@ public class S3TablesController {
Map<String, Object> response = new LinkedHashMap<>();
putIfNotNull(response, "metadataLocation", table.getMetadataLocation());
response.put("versionToken", table.getVersionToken());
putIfNotNull(response, "warehouseLocation", table.getWarehouseLocation());
return response;
}
@@ -6,6 +6,8 @@ import io.floci.aws.core.common.AwsException;
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.services.s3.S3Service;
import io.floci.aws.services.s3.model.S3Object;
import io.floci.aws.services.s3tables.model.Namespace;
import io.floci.aws.services.s3tables.model.S3Table;
import io.floci.aws.services.s3tables.model.TableBucket;
@@ -25,14 +27,17 @@ import java.util.UUID;
public class S3TablesService {
private static final Logger LOG = Logger.getLogger(S3TablesService.class);
private static final String BUCKET_PREFIX = "bucket/";
private static final int LIST_PAGE_SIZE = 1000;
private final StorageBackend<String, TableBucket> store;
private final RegionResolver regionResolver;
private final S3Service s3Service;
@Inject
public S3TablesService(StorageFactory factory, RegionResolver regionResolver) {
public S3TablesService(StorageFactory factory, RegionResolver regionResolver, S3Service s3Service) {
this.store = factory.create("s3tables", "s3tables.json", new TypeReference<Map<String, TableBucket>>() {});
this.regionResolver = regionResolver;
this.s3Service = s3Service;
}
public synchronized TableBucket createTableBucket(String name, Object encryptionConfiguration,
@@ -122,13 +127,23 @@ public class S3TablesService {
S3Table table = new S3Table(name, bucket.getArn() + "/table/" + name, namespaceName, format,
versionToken(), metadataLocation(metadata), now(), regionResolver.getAccountId(), metadata,
encryptionConfiguration, storageClassConfiguration, tags);
table.setWarehouseLocation(createWarehouse(region));
namespace.getTables().put(name, table);
persist(bucket, region);
try {
persist(bucket, region);
} catch (RuntimeException e) {
namespace.getTables().remove(name);
deleteWarehouse(table.getWarehouseLocation());
throw e;
}
return table;
}
public synchronized S3Table getTable(String tableBucketArn, String namespaceName, String name, String region) {
return getTable(getTableBucket(tableBucketArn, region), namespaceName, name);
TableBucket bucket = getTableBucket(tableBucketArn, region);
S3Table table = getTable(bucket, namespaceName, name);
withWarehouses(bucket, List.of(table), region);
return table;
}
public synchronized List<S3Table> listTables(String tableBucketArn, String namespaceName, String prefix, String region) {
@@ -139,18 +154,96 @@ public class S3TablesService {
} else {
tables.addAll(getNamespace(bucket, namespaceName).getTables().values());
}
return tables.stream().filter(table -> prefix == null || table.getName().startsWith(prefix))
List<S3Table> listed = tables.stream().filter(table -> prefix == null || table.getName().startsWith(prefix))
.sorted(Comparator.comparing(S3Table::getName)).toList();
withWarehouses(bucket, listed, region);
return listed;
}
public synchronized void deleteTable(String tableBucketArn, String namespaceName, String name, String region) {
TableBucket bucket = getTableBucket(tableBucketArn, region);
Namespace namespace = getNamespace(bucket, namespaceName);
getTable(bucket, namespaceName, name);
S3Table table = getTable(bucket, namespaceName, name);
// The warehouse goes first: if emptying it fails, the table is still there to delete again.
deleteWarehouse(table.getWarehouseLocation());
namespace.getTables().remove(name);
persist(bucket, region);
}
/**
* Gives each table persisted before tables had a warehouse one of its own, so every response
* that reports {@code warehouseLocation} has one. A save that fails takes the new warehouses
* back out.
*/
private void withWarehouses(TableBucket bucket, List<S3Table> tables, String region) {
List<S3Table> backfilled = new ArrayList<>();
for (S3Table table : tables) {
if (table.getWarehouseLocation() == null) {
table.setWarehouseLocation(createWarehouse(region));
backfilled.add(table);
}
}
if (backfilled.isEmpty()) {
return;
}
try {
persist(bucket, region);
} catch (RuntimeException e) {
for (S3Table table : backfilled) {
deleteWarehouse(table.getWarehouseLocation());
table.setWarehouseLocation(null);
}
throw e;
}
}
/**
* Creates the bucket that holds a table's data and metadata files and returns its location, as
* S3 Tables gives every table a warehouse of its own: an Iceberg client such as Spark's
* {@code S3TablesCatalog} writes there and commits with {@code UpdateTableMetadataLocation}.
*/
private String createWarehouse(String region) {
String name = UUID.randomUUID() + S3Service.TABLE_WAREHOUSE_BUCKET_SUFFIX;
s3Service.createBucket(name, region);
return "s3://" + name;
}
/** Deletes a table's warehouse with everything in it, as deleting an S3 Tables table deletes its data. */
private void deleteWarehouse(String warehouseLocation) {
if (warehouseLocation == null || !warehouseLocation.startsWith("s3://")) {
return;
}
String name = warehouseLocation.substring("s3://".length());
try {
String keyMarker = null;
String versionIdMarker = null;
do {
S3Service.ListVersionsResult versions = s3Service.listObjectVersions(name, null, null, LIST_PAGE_SIZE,
keyMarker, versionIdMarker);
for (S3Object version : versions.versions()) {
s3Service.deleteObject(name, version.getKey(), version.getVersionId());
}
keyMarker = versions.isTruncated() ? versions.nextKeyMarker() : null;
versionIdMarker = versions.isTruncated() ? versions.nextVersionIdMarker() : null;
} while (keyMarker != null);
String continuation = null;
do {
S3Service.ListObjectsResult page = s3Service.listObjectsWithPrefixes(name, null, null, LIST_PAGE_SIZE,
continuation, null);
for (S3Object object : page.objects()) {
s3Service.deleteObject(name, object.getKey());
}
continuation = page.isTruncated() ? page.nextContinuationToken() : null;
} while (continuation != null);
s3Service.deleteBucket(name);
} catch (AwsException e) {
if (!"NoSuchBucket".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("Warehouse bucket {0} was already gone", name);
}
}
public synchronized S3Table renameTable(String tableBucketArn, String namespaceName, String name, String newNamespaceName,
String newName, String versionToken, String region) {
TableBucket bucket = getTableBucket(tableBucketArn, region);
@@ -186,6 +279,7 @@ public class S3TablesService {
table.setMetadataLocation(metadataLocation);
touch(table);
persist(bucket, region);
withWarehouses(bucket, List.of(table), region);
return table;
}
@@ -13,6 +13,7 @@ public class S3Table {
private String format;
private String versionToken;
private String metadataLocation;
private String warehouseLocation;
private String createdAt;
private String modifiedAt;
private String ownerAccountId;
@@ -58,6 +59,8 @@ public class S3Table {
public void setVersionToken(String versionToken) { this.versionToken = versionToken; }
public String getMetadataLocation() { return metadataLocation; }
public void setMetadataLocation(String metadataLocation) { this.metadataLocation = metadataLocation; }
public String getWarehouseLocation() { return warehouseLocation; }
public void setWarehouseLocation(String warehouseLocation) { this.warehouseLocation = warehouseLocation; }
public String getCreatedAt() { return createdAt; }
public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
public String getModifiedAt() { return modifiedAt; }
@@ -5,11 +5,13 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.s3tables.model.S3Table;
import io.floci.aws.services.s3tables.model.TableBucket;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.mockito.Mockito;
import java.util.List;
import java.util.Map;
@@ -22,6 +24,7 @@ import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class S3TablesServiceTest {
private static final String ACCOUNT_ID = "000000000000";
@@ -29,17 +32,55 @@ class S3TablesServiceTest {
private static final String BUCKET = "unit-test-table-bucket";
private S3TablesService service;
private S3Service s3Service;
private AccountAwareStorageBackend<TableBucket> store;
@BeforeEach
void setUp() {
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
@SuppressWarnings("unchecked")
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
store = Mockito.spy(AccountAwareStorageBackend.<TableBucket>inMemory(ACCOUNT_ID));
return (AccountAwareStorageBackend<V>) store;
}
};
service = new S3TablesService(storageFactory, new RegionResolver(REGION, ACCOUNT_ID));
s3Service = Mockito.mock(S3Service.class);
Mockito.when(s3Service.listObjectsWithPrefixes(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.anyInt(),
Mockito.any(), Mockito.any())).thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
Mockito.when(s3Service.listObjectVersions(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.anyInt(),
Mockito.any(), Mockito.any())).thenReturn(new S3Service.ListVersionsResult(List.of(), List.of(), false, null, null));
service = new S3TablesService(storageFactory, new RegionResolver(REGION, ACCOUNT_ID), s3Service);
}
@Test
void listingAndUpdatingATableFromBeforeWarehousesGiveItOne() {
String arn = service.createTableBucket(BUCKET, null, null, Map.of(), REGION).getArn();
service.createNamespace(arn, List.of("analytics"), REGION);
S3Table legacy = createTable(arn, "analytics", "events");
legacy.setWarehouseLocation(null);
S3Table listed = service.listTables(arn, "analytics", null, REGION).getFirst();
listed.setWarehouseLocation(null);
S3Table updated = service.updateTableMetadataLocation(arn, "analytics", "events", "s3://w/m.json",
listed.getVersionToken(), REGION);
assertTrue(updated.getWarehouseLocation().matches("s3://[0-9a-f-]{36}--table-s3"), updated.getWarehouseLocation());
Mockito.verify(s3Service, Mockito.times(3)).createBucket(Mockito.endsWith("--table-s3"), Mockito.eq(REGION));
}
@Test
void aFailedSaveTakesTheNewTableAndItsWarehouseBackOut() {
String arn = service.createTableBucket(BUCKET, null, null, Map.of(), REGION).getArn();
service.createNamespace(arn, List.of("analytics"), REGION);
Mockito.doThrow(new IllegalStateException("disk full")).when(store).put(Mockito.anyString(), Mockito.any());
assertThrows(IllegalStateException.class, () -> createTable(arn, "analytics", "events"));
Mockito.verify(s3Service).deleteBucket(Mockito.endsWith("--table-s3"));
Mockito.doCallRealMethod().when(store).put(Mockito.anyString(), Mockito.any());
assertEquals(List.of(), service.listTables(arn, "analytics", null, REGION));
}
@Test
@@ -0,0 +1,120 @@
package io.floci.aws.services.s3tables;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.BucketVersioningStatus;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Every S3 Tables table has a warehouse, a bucket of its own that an Iceberg client such as Spark's
* {@code S3TablesCatalog} writes the table's data and metadata files to before committing with
* {@code UpdateTableMetadataLocation}.
*/
@QuarkusTest
class S3TablesWarehouseIntegrationTest {
private static final String JSON = "application/json";
private String encodedBucketArn;
private S3Client s3;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void createTable() {
String bucketName = "warehouse-" + System.nanoTime();
String bucketArn = given().contentType(JSON).body("{\"name\": \"" + bucketName + "\"}")
.when().put("/buckets").then().statusCode(200).extract().path("arn");
encodedBucketArn = URLEncoder.encode(bucketArn, StandardCharsets.UTF_8);
given().urlEncodingEnabled(false).contentType(JSON).body("{\"namespace\": [\"analytics\"]}")
.when().put("/namespaces/" + encodedBucketArn).then().statusCode(200);
given().urlEncodingEnabled(false).contentType(JSON).body("{\"name\": \"events\", \"format\": \"ICEBERG\"}")
.when().put("/tables/" + encodedBucketArn + "/analytics").then().statusCode(200);
s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), "000000000000", Region.US_EAST_1);
}
@AfterEach
void closeClient() {
s3.close();
}
private String warehouseLocation() {
return given().urlEncodingEnabled(false)
.when().get("/get-table?tableBucketARN=" + encodedBucketArn + "&namespace=analytics&name=events")
.then().statusCode(200)
.body("warehouseLocation", matchesPattern("s3://[0-9a-f-]{36}--table-s3"))
.body("createdBy", equalTo("000000000000"))
.body("modifiedBy", equalTo("000000000000"))
.extract().path("warehouseLocation");
}
@Test
void aTablesWarehouseIsABucketItsMetadataLocationAlsoNames() {
String warehouse = warehouseLocation();
String bucket = warehouse.substring("s3://".length());
s3.putObject(r -> r.bucket(bucket).key("metadata/00000-a.metadata.json"), RequestBody.fromString("{}"));
given().urlEncodingEnabled(false)
.when().get("/tables/" + encodedBucketArn + "/analytics/events/metadata-location")
.then().statusCode(200)
.body("warehouseLocation", equalTo(warehouse));
assertEquals(1, s3.listObjectsV2(r -> r.bucket(bucket)).keyCount());
assertEquals(warehouse, warehouseLocation(), "the warehouse stays the same across reads");
}
@Test
void warehousesAreNotListedAsGeneralPurposeBuckets() {
String bucket = warehouseLocation().substring("s3://".length());
assertFalse(s3.listBuckets().buckets().stream().anyMatch(b -> b.name().equals(bucket)));
}
@Test
void deletingATableDeletesEveryVersionInAVersionedWarehouse() {
String bucket = warehouseLocation().substring("s3://".length());
s3.putBucketVersioning(r -> r.bucket(bucket).versioningConfiguration(v -> v.status(BucketVersioningStatus.ENABLED)));
s3.putObject(r -> r.bucket(bucket).key("data/part-0.parquet"), RequestBody.fromString("v1"));
s3.putObject(r -> r.bucket(bucket).key("data/part-0.parquet"), RequestBody.fromString("v2"));
s3.deleteObject(r -> r.bucket(bucket).key("data/part-0.parquet"));
given().urlEncodingEnabled(false)
.when().delete("/tables/" + encodedBucketArn + "/analytics/events")
.then().statusCode(204);
assertThrows(NoSuchBucketException.class, () -> s3.headBucket(r -> r.bucket(bucket)));
}
@Test
void deletingATableDeletesItsWarehouse() {
String bucket = warehouseLocation().substring("s3://".length());
s3.putObject(r -> r.bucket(bucket).key("data/part-0.parquet"), RequestBody.fromString("x"));
given().urlEncodingEnabled(false)
.when().delete("/tables/" + encodedBucketArn + "/analytics/events")
.then().statusCode(204);
assertThrows(NoSuchBucketException.class, () -> s3.headBucket(r -> r.bucket(bucket)));
}
}