iceberg: create and load a table in process

The create handler splits into planCreateTable, which checks the name,
authorizes the create and builds the first metadata, and
registerCreateTable, which stages the metadata file and registers the
table, with stage-create still handled between them in the handler.
Server.CreateTable runs both for a caller inside the cluster, and
Server.LoadTable answers what a load does, sharing the GetTable call and
the metadata parse with the handler. A server-side component that needs
its own table now gets the same location, metadata file, exclusive
staging and cleanup as a REST client, rather than writing metadata by
hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chris LuandClaude Opus 5.5 committed 2026-12-01 15:02:05 -08:00
1 parent f67ef0c0b7
commit a40cacc563
4 files changed
+332 -145

No files matched your search

+4
View File
@@ -103,6 +103,10 @@ type icebergRequestError struct {
message string
}
func (e *icebergRequestError) Error() string {
return fmt.Sprintf("%s: %s", e.errType, e.message)
}
type createOnCommitInput struct {
bucketARN string
markerBucket string
+235 -144
View File
@@ -158,11 +158,115 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) {
}
bucketName := getBucketFromPrefix(r)
bucketARN := buildTableBucketARN(bucketName)
// Extract identity from context
identityName := s3_constants.GetIdentityNameFromContext(r)
plan, reqErr := s.planCreateTable(r.Context(), bucketName, namespace, req, identityName)
if reqErr != nil {
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
return
}
tableName := req.Name
// Stage-create persists metadata in the internal staged area and skips S3Tables registration.
if req.StageCreate {
stagedTablePath := stageCreateStagedTablePath(namespace, tableName, plan.tableUUID)
// The staged path carries the table UUID, so the name cannot already be
// taken; exclusive keeps it that way if it ever is.
if err := s.saveMetadataFile(r.Context(), plan.metadataBucket, stagedTablePath, plan.metadataFileName, plan.metadataBytes, true); err != nil {
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save staged metadata file: "+err.Error())
return
}
stagedMetadataLocation := fmt.Sprintf("s3://%s/%s/metadata/%s", plan.metadataBucket, stagedTablePath, plan.metadataFileName)
// The staged table is not registered yet, so there is nothing to
// authorize an update against; the create gate above is the write
// authority for the prefix the staged table will occupy.
config, storageCredentials := s.buildFileIOConfig(r, plan.location, func() bool { return true })
// The marker is how the commit finds the location handed out here, and
// holds that location for as long as the credentials can write it.
if markerErr := s.writeStageCreateMarker(r.Context(), bucketName, namespace, tableName, plan.tableUUID, plan.location, stagedMetadataLocation, vendedUntil(config)); markerErr != nil {
glog.V(1).Infof("Iceberg: failed to persist stage-create marker for %s.%s: %v", flattenNamespacePath(namespace), tableName, markerErr)
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save stage-create marker")
return
}
if reqErr := s.checkFreshLocation(r.Context(), bucketName, namespace, tableName, plan.metadataPath, plan.location, plan.tableUUID.String(), true); reqErr != nil {
if err := s.deleteStageCreate(r.Context(), bucketName, namespace, tableName, plan.tableUUID); err != nil {
glog.V(1).Infof("Iceberg: failed to remove stage-create for %s.%s: %v", flattenNamespacePath(namespace), tableName, err)
}
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
return
}
result := LoadTableResult{
MetadataLocation: plan.metadataLocation,
Metadata: plan.metadata,
Config: config,
StorageCredentials: storageCredentials,
}
writeLoadResult(w, http.StatusOK, result)
return
}
if reqErr := s.registerCreateTable(r.Context(), plan, identityName); reqErr != nil {
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
return
}
config, storageCredentials := s.buildFileIOConfig(r, plan.location, func() bool {
return s.mayUpdateTable(r, bucketName, namespace, req.Name)
})
result := LoadTableResult{
MetadataLocation: plan.metadataLocation,
Metadata: plan.metadata,
Config: config,
StorageCredentials: storageCredentials,
}
writeLoadResult(w, http.StatusOK, result)
}
// CreateTable creates and registers a table the way a create request without
// stage-create does, for a caller inside the cluster rather than an HTTP
// client. It returns the table's metadata location and metadata.
func (s *Server) CreateTable(ctx context.Context, bucketName string, namespace []string, req CreateTableRequest, identityName string) (string, table.Metadata, error) {
if err := validateCreateTableRequest(req); err != nil {
return "", nil, err
}
if req.StageCreate {
return "", nil, errors.New("stage-create needs a commit to register the table")
}
plan, reqErr := s.planCreateTable(ctx, bucketName, namespace, req, identityName)
if reqErr != nil {
return "", nil, reqErr
}
if reqErr := s.registerCreateTable(ctx, plan, identityName); reqErr != nil {
return "", nil, reqErr
}
return plan.metadataLocation, plan.metadata, nil
}
// createTablePlan is a create the catalog has authorized and built the
// metadata for, ready to stage or register.
type createTablePlan struct {
bucketName string
bucketARN string
namespace []string
tableName string
tableUUID uuid.UUID
tablePath string
location string
clientLocation string
metadata table.Metadata
metadataBytes []byte
metadataFileName string
metadataLocation string
metadataBucket string
metadataPath string
}
// planCreateTable checks a create of req.Name in namespace and builds the
// table's first metadata, writing nothing.
func (s *Server) planCreateTable(ctx context.Context, bucketName string, namespace []string, req CreateTableRequest, identityName string) (*createTablePlan, *icebergRequestError) {
bucketARN := buildTableBucketARN(bucketName)
// Generate UUID for the new table
tableUUID := uuid.New()
// A location the server picks is unique to the table, so its files never
@@ -173,8 +277,7 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) {
if clientLocation != "" {
_, clientPath, err := parseS3Location(clientLocation)
if err != nil {
writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid table location: "+err.Error())
return
return nil, &icebergRequestError{http.StatusBadRequest, "BadRequestException", "Invalid table location: " + err.Error()}
}
if clientPath == "" {
clientLocation = ""
@@ -191,18 +294,15 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) {
// spec or order that does not resolve against its schema is the
// client's error, not a server fault.
if errors.Is(err, table.ErrInvalidMetadata) || errors.Is(err, table.ErrInvalidSortSourceID) {
writeError(w, http.StatusBadRequest, "BadRequestException", err.Error())
return
return nil, &icebergRequestError{http.StatusBadRequest, "BadRequestException", err.Error()}
}
writeManagerError(w, err)
return
return nil, managerRequestError(err)
}
// Serialize metadata to JSON
metadataBytes, err := json.Marshal(metadata)
if err != nil {
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to serialize metadata: "+err.Error())
return
return nil, &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Failed to serialize metadata: " + err.Error()}
}
// Backfill Iceberg spec-required fields that iceberg-go v0.5.0 omits when
// empty (e.g. current-snapshot-id), so the persisted v*.metadata.json is
@@ -214,20 +314,17 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) {
metadataLocation := fmt.Sprintf("%s/metadata/%s", location, metadataFileName)
metadataBucket, metadataPath, err := parseS3Location(location)
if err != nil {
writeError(w, http.StatusInternalServerError, "InternalServerError", "Invalid table location: "+err.Error())
return
return nil, &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Invalid table location: " + err.Error()}
}
// location/name are client-supplied; confine the metadata write to the
// authorized catalog bucket and reject traversal segments so path.Join in
// saveMetadataFile cannot escape into another bucket.
if metadataBucket != bucketName {
writeError(w, http.StatusBadRequest, "BadRequestException", "table location must be within bucket "+bucketName)
return
return nil, &icebergRequestError{http.StatusBadRequest, "BadRequestException", "table location must be within bucket " + bucketName}
}
if !isValidTablePath(metadataPath) {
writeError(w, http.StatusBadRequest, "BadRequestException", "invalid table location path")
return
return nil, &icebergRequestError{http.StatusBadRequest, "BadRequestException", "invalid table location path"}
}
// Authoritative existence check: ask the catalog whether a table is registered
@@ -245,103 +342,82 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) {
var existsResp s3tables.GetTableResponse
existsErr := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
mgrClient := s3tables.NewManagerClient(client)
return s.tablesManager.Execute(r.Context(), mgrClient, "GetTable", existsReq, &existsResp, identityName)
return s.tablesManager.Execute(ctx, mgrClient, "GetTable", existsReq, &existsResp, identityName)
})
if existsErr == nil {
writeTableAlreadyExists(w, namespace, tableName)
return
return nil, tableAlreadyExists(namespace, tableName)
}
if !isNoSuchTableError(existsErr) {
glog.V(1).Infof("Iceberg: CreateTable existence check failed for %s.%s: %v", flattenNamespacePath(namespace), tableName, existsErr)
writeManagerError(w, existsErr)
return
return nil, managerRequestError(existsErr)
}
// Both branches below write into the table bucket, and stage-create never
// reaches the registration that carries the authorization, so the caller has
// to pass the CreateTable gate here.
if authErr := s.authorizeCreateTable(r.Context(), bucketARN, namespace, tableName, identityName, metadataLocation); authErr != nil {
writeManagerError(w, authErr)
return
if authErr := s.authorizeCreateTable(ctx, bucketARN, namespace, tableName, identityName, metadataLocation); authErr != nil {
return nil, managerRequestError(authErr)
}
// Registration confines the location to the table's namespace, but both
// branches write, and stage-create vends credentials, before it runs.
if err := s3tables.ValidateMetadataLocation(metadataLocation, bucketName, flattenNamespacePath(namespace)); err != nil {
writeError(w, http.StatusBadRequest, "BadRequestException", err.Error())
return
return nil, &icebergRequestError{http.StatusBadRequest, "BadRequestException", err.Error()}
}
if clientLocation != "" {
if reqErr := s.checkFreshLocation(r.Context(), bucketName, namespace, tableName, metadataPath, location, "", true); reqErr != nil {
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
return
if reqErr := s.checkFreshLocation(ctx, bucketName, namespace, tableName, metadataPath, location, "", true); reqErr != nil {
return nil, reqErr
}
}
return &createTablePlan{
bucketName: bucketName,
bucketARN: bucketARN,
namespace: namespace,
tableName: tableName,
tableUUID: tableUUID,
tablePath: tablePath,
location: location,
clientLocation: clientLocation,
metadata: metadata,
metadataBytes: metadataBytes,
metadataFileName: metadataFileName,
metadataLocation: metadataLocation,
metadataBucket: metadataBucket,
metadataPath: metadataPath,
}, nil
}
// Stage-create persists metadata in the internal staged area and skips S3Tables registration.
if req.StageCreate {
stagedTablePath := stageCreateStagedTablePath(namespace, tableName, tableUUID)
// The staged path carries the table UUID, so the name cannot already be
// taken; exclusive keeps it that way if it ever is.
if err := s.saveMetadataFile(r.Context(), metadataBucket, stagedTablePath, metadataFileName, metadataBytes, true); err != nil {
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save staged metadata file: "+err.Error())
return
}
stagedMetadataLocation := fmt.Sprintf("s3://%s/%s/metadata/%s", metadataBucket, stagedTablePath, metadataFileName)
// The staged table is not registered yet, so there is nothing to
// authorize an update against; the create gate above is the write
// authority for the prefix the staged table will occupy.
config, storageCredentials := s.buildFileIOConfig(r, location, func() bool { return true })
// The marker is how the commit finds the location handed out here, and
// holds that location for as long as the credentials can write it.
if markerErr := s.writeStageCreateMarker(r.Context(), bucketName, namespace, tableName, tableUUID, location, stagedMetadataLocation, vendedUntil(config)); markerErr != nil {
glog.V(1).Infof("Iceberg: failed to persist stage-create marker for %s.%s: %v", flattenNamespacePath(namespace), tableName, markerErr)
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save stage-create marker")
return
}
if reqErr := s.checkFreshLocation(r.Context(), bucketName, namespace, tableName, metadataPath, location, tableUUID.String(), true); reqErr != nil {
if err := s.deleteStageCreate(r.Context(), bucketName, namespace, tableName, tableUUID); err != nil {
glog.V(1).Infof("Iceberg: failed to remove stage-create for %s.%s: %v", flattenNamespacePath(namespace), tableName, err)
}
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
return
}
result := LoadTableResult{
MetadataLocation: metadataLocation,
Metadata: metadata,
Config: config,
StorageCredentials: storageCredentials,
}
writeLoadResult(w, http.StatusOK, result)
return
}
// registerCreateTable writes plan's metadata file and registers the table in
// the catalog, recording in plan where the file landed.
func (s *Server) registerCreateTable(ctx context.Context, plan *createTablePlan, identityName string) *icebergRequestError {
bucketName, namespace, tableName := plan.bucketName, plan.namespace, plan.tableName
metadataBucket, metadataPath, location := plan.metadataBucket, plan.metadataPath, plan.location
// The location may already hold a v1.metadata.json: a table created there
// earlier and since dropped, an unregistered file, or a request racing this
// one for the same name. Writing it exclusively keeps this request from
// replacing that file, and from deleting it below if registration fails.
metadataFileName, metadataLocation, stageToken, err := s.stageOwnedMetadata(r.Context(), metadataBucket, metadataPath, location, metadataFileName, metadataBytes)
metadataFileName, metadataLocation, stageToken, err := s.stageOwnedMetadata(ctx, metadataBucket, metadataPath, location, plan.metadataFileName, plan.metadataBytes)
if err != nil {
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save metadata file: "+err.Error())
return
return &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Failed to save metadata file: " + err.Error()}
}
if clientLocation != "" {
if reqErr := s.checkFreshLocation(r.Context(), bucketName, namespace, tableName, metadataPath, location, "", false); reqErr != nil {
s.discardStagedMetadata(r.Context(), metadataBucket, metadataPath, metadataFileName, metadataLocation, stageToken)
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
return
plan.metadataFileName, plan.metadataLocation = metadataFileName, metadataLocation
if plan.clientLocation != "" {
if reqErr := s.checkFreshLocation(ctx, bucketName, namespace, tableName, metadataPath, location, "", false); reqErr != nil {
s.discardStagedMetadata(ctx, metadataBucket, metadataPath, metadataFileName, metadataLocation, stageToken)
return reqErr
}
}
// Use S3 Tables manager to create table
createReq := &s3tables.CreateTableRequest{
TableBucketARN: bucketARN,
TableBucketARN: plan.bucketARN,
Namespace: namespace,
Name: tableName,
Format: "ICEBERG",
Metadata: &s3tables.TableMetadata{
Iceberg: &s3tables.IcebergMetadata{
TableUUID: tableUUID.String(),
TableUUID: plan.tableUUID.String(),
},
FullMetadata: metadataBytes,
FullMetadata: plan.metadataBytes,
},
MetadataLocation: metadataLocation,
MetadataVersion: 1,
@@ -350,7 +426,7 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) {
err = s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
mgrClient := s3tables.NewManagerClient(client)
return s.tablesManager.Execute(s3tables.WithCatalogAssignedLocation(r.Context()), mgrClient, "CreateTable", createReq, &createResp, identityName)
return s.tablesManager.Execute(s3tables.WithCatalogAssignedLocation(ctx), mgrClient, "CreateTable", createReq, &createResp, identityName)
})
if err == nil && createResp.MetadataLocation != metadataLocation {
// Another create registered the name first.
@@ -364,38 +440,26 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) {
// under this name or one it was renamed to, could point at it, and
// removing it would leave the table unreadable.
if registrationRefused(err) {
s.discardStagedMetadata(r.Context(), metadataBucket, metadataPath, metadataFileName, metadataLocation, stageToken)
s.discardStagedMetadata(ctx, metadataBucket, metadataPath, metadataFileName, metadataLocation, stageToken)
}
if isS3TablesAlreadyExists(err) {
if strings.HasSuffix(metadataPath, tablePath) {
if strings.HasSuffix(metadataPath, plan.tablePath) {
// The name went to another table before this request wrote a
// record, so nothing names the directory the server picked.
if cleanupErr := s.cleanupStaleTableLocation(r.Context(), metadataBucket, metadataPath, nil); cleanupErr != nil {
if cleanupErr := s.cleanupStaleTableLocation(ctx, metadataBucket, metadataPath, nil); cleanupErr != nil {
glog.V(1).Infof("Iceberg: CreateTable cleanup %s: %v", metadataPath, cleanupErr)
}
}
writeTableAlreadyExists(w, namespace, tableName)
return
return tableAlreadyExists(namespace, tableName)
}
glog.V(1).Infof("Iceberg: CreateTable error: %v", err)
writeManagerError(w, err)
return
return managerRequestError(err)
}
if markerErr := s.deleteStageCreateMarkers(r.Context(), bucketName, namespace, tableName, location); markerErr != nil {
if markerErr := s.deleteStageCreateMarkers(ctx, bucketName, namespace, tableName, location); markerErr != nil {
glog.V(1).Infof("Iceberg: failed to cleanup stage-create markers for %s.%s after create: %v", flattenNamespacePath(namespace), tableName, markerErr)
}
config, storageCredentials := s.buildFileIOConfig(r, location, func() bool {
return s.mayUpdateTable(r, bucketName, namespace, req.Name)
})
result := LoadTableResult{
MetadataLocation: metadataLocation,
Metadata: metadata,
Config: config,
StorageCredentials: storageCredentials,
}
writeLoadResult(w, http.StatusOK, result)
return nil
}
// handleRegisterTable registers an existing metadata.json under a new catalog
@@ -526,23 +590,11 @@ func (s *Server) handleLoadTable(w http.ResponseWriter, r *http.Request) {
}
bucketName := getBucketFromPrefix(r)
bucketARN := buildTableBucketARN(bucketName)
// Extract identity from context
identityName := s3_constants.GetIdentityNameFromContext(r)
getReq := &s3tables.GetTableRequest{
TableBucketARN: bucketARN,
Namespace: namespace,
Name: tableName,
}
var getResp s3tables.GetTableResponse
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
mgrClient := s3tables.NewManagerClient(client)
return s.tablesManager.Execute(r.Context(), mgrClient, "GetTable", getReq, &getResp, identityName)
})
getResp, err := s.getTable(r.Context(), bucketName, namespace, tableName, identityName)
if err != nil {
if strings.Contains(err.Error(), "not found") {
@@ -568,40 +620,39 @@ func (s *Server) handleLoadTable(w http.ResponseWriter, r *http.Request) {
writeLoadResult(w, http.StatusOK, result)
}
// LoadTable returns the metadata location and current metadata of a table,
// as a load request does, for a caller inside the cluster.
func (s *Server) LoadTable(ctx context.Context, bucketName string, namespace []string, tableName, identityName string) (string, table.Metadata, error) {
getResp, err := s.getTable(ctx, bucketName, namespace, tableName, identityName)
if err != nil {
return "", nil, err
}
metadata, _, err := s.loadTableMetadata(ctx, getResp, bucketName, namespace, tableName)
if err != nil {
return "", nil, err
}
return getResp.MetadataLocation, metadata, nil
}
func (s *Server) getTable(ctx context.Context, bucketName string, namespace []string, tableName, identityName string) (s3tables.GetTableResponse, error) {
getReq := &s3tables.GetTableRequest{
TableBucketARN: buildTableBucketARN(bucketName),
Namespace: namespace,
Name: tableName,
}
var getResp s3tables.GetTableResponse
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
mgrClient := s3tables.NewManagerClient(client)
return s.tablesManager.Execute(ctx, mgrClient, "GetTable", getReq, &getResp, identityName)
})
return getResp, err
}
func (s *Server) buildLoadTableResult(r *http.Request, getResp s3tables.GetTableResponse, bucketName string, namespace []string, tableName string) (LoadTableResult, error) {
location := tableLocation(getResp, bucketName, namespace, tableName)
tableUUID := uuid.Nil
if getResp.Metadata != nil && getResp.Metadata.Iceberg != nil && getResp.Metadata.Iceberg.TableUUID != "" {
if parsed, err := uuid.Parse(getResp.Metadata.Iceberg.TableUUID); err == nil {
tableUUID = parsed
}
}
// Use Nil UUID if not found in storage (legacy table)
// Stability is guaranteed by not generating random UUIDs on read
metadataBytes, err := s.currentMetadataBytes(r.Context(), getResp, bucketName)
metadata, cached, err := s.loadTableMetadata(r.Context(), getResp, bucketName, namespace, tableName)
if err != nil {
return LoadTableResult{}, fmt.Errorf("load metadata for %s: %w", tableName, err)
}
var metadata table.Metadata
var cached *cachedMetadata
if len(metadataBytes) > 0 {
// metadata that does not parse fails the load: an empty table in its
// place reads as no rows, and a writer could commit over it
cached, err = tableMetadataCache.parse(bucketName, getResp.MetadataLocation, metadataBytes)
if err != nil {
return LoadTableResult{}, fmt.Errorf("read metadata of %s at %s: %w", tableName, getResp.MetadataLocation, err)
}
metadata = cached.parsed
} else {
// No full metadata, create synthetic
// TODO: If we had stored schema in IcebergMetadata, we would pass it here
metadata, err = newTableMetadata(tableUUID, location, nil, nil, nil, nil)
}
// A nil metadata would serialize as "metadata":null under HTTP 200, which no
// Iceberg client can parse. Fail the request instead.
if err != nil {
return LoadTableResult{}, fmt.Errorf("build metadata for %s: %w", tableName, err)
return LoadTableResult{}, err
}
catalogOnly := s3tables.IsCatalogOnlyFormat(getResp.Format)
@@ -617,6 +668,46 @@ func (s *Server) buildLoadTableResult(r *http.Request, getResp s3tables.GetTable
}, nil
}
// loadTableMetadata is the current metadata of the table GetTable answered
// with, parsed once per version.
func (s *Server) loadTableMetadata(ctx context.Context, getResp s3tables.GetTableResponse, bucketName string, namespace []string, tableName string) (table.Metadata, *cachedMetadata, error) {
location := tableLocation(getResp, bucketName, namespace, tableName)
tableUUID := uuid.Nil
if getResp.Metadata != nil && getResp.Metadata.Iceberg != nil && getResp.Metadata.Iceberg.TableUUID != "" {
if parsed, err := uuid.Parse(getResp.Metadata.Iceberg.TableUUID); err == nil {
tableUUID = parsed
}
}
// Use Nil UUID if not found in storage (legacy table)
// Stability is guaranteed by not generating random UUIDs on read
metadataBytes, err := s.currentMetadataBytes(ctx, getResp, bucketName)
if err != nil {
return nil, nil, fmt.Errorf("load metadata for %s: %w", tableName, err)
}
var metadata table.Metadata
var cached *cachedMetadata
if len(metadataBytes) > 0 {
// metadata that does not parse fails the load: an empty table in its
// place reads as no rows, and a writer could commit over it
cached, err = tableMetadataCache.parse(bucketName, getResp.MetadataLocation, metadataBytes)
if err != nil {
return nil, nil, fmt.Errorf("read metadata of %s at %s: %w", tableName, getResp.MetadataLocation, err)
}
metadata = cached.parsed
} else {
// No full metadata, create synthetic
// TODO: If we had stored schema in IcebergMetadata, we would pass it here
metadata, err = newTableMetadata(tableUUID, location, nil, nil, nil, nil)
}
// A nil metadata would serialize as "metadata":null under HTTP 200, which no
// Iceberg client can parse. Fail the request instead.
if err != nil {
return nil, nil, fmt.Errorf("build metadata for %s: %w", tableName, err)
}
return metadata, cached, nil
}
// applySnapshotsParam honours ?snapshots=refs, which asks for only the
// snapshots that branches and tags point at. Clients use it to avoid pulling a
// long snapshot history they will not read. Anything else, including the
@@ -965,10 +1056,10 @@ func (s *Server) handleRenameTable(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
// writeTableAlreadyExists answers a create for a name that holds a table with
// the 409 the Iceberg REST spec defines for it.
func writeTableAlreadyExists(w http.ResponseWriter, namespace []string, tableName string) {
writeError(w, http.StatusConflict, "AlreadyExistsException", fmt.Sprintf("Table already exists: %s.%s", strings.Join(namespace, "."), tableName))
// tableAlreadyExists answers a create for a name that holds a table with the
// 409 the Iceberg REST spec defines for it.
func tableAlreadyExists(namespace []string, tableName string) *icebergRequestError {
return &icebergRequestError{http.StatusConflict, "AlreadyExistsException", fmt.Sprintf("Table already exists: %s.%s", strings.Join(namespace, "."), tableName)}
}
// isNoSuchTableError reports whether an error from the S3 Tables manager
@@ -0,0 +1,86 @@
package iceberg
import (
"errors"
"strings"
"testing"
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/table"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
)
// A caller inside the cluster creates a table through the same path a REST
// create takes and loads it back.
func TestCreateTableInProcess(t *testing.T) {
filer := s3tablestest.Start(t)
server := NewServer(s3tables.NewManagerClient(filer.Client), nil)
admin := s3tables.NewManager()
admin.SetTrusted(true)
arn, err := s3tables.BuildBucketARN(s3tables.DefaultRegion, s3tables.DefaultAccountID, "whouse")
if err != nil {
t.Fatal(err)
}
mgrClient := s3tables.NewManagerClient(filer.Client)
if err := admin.Execute(t.Context(), mgrClient, "CreateTableBucket", &s3tables.CreateTableBucketRequest{Name: "whouse", Format: s3tables.FormatIceberg}, nil, ""); err != nil {
t.Fatal(err)
}
if err := admin.Execute(t.Context(), mgrClient, "CreateNamespace", &s3tables.CreateNamespaceRequest{TableBucketARN: arn, Namespace: []string{"ns"}}, nil, ""); err != nil {
t.Fatal(err)
}
schema := iceberg.NewSchema(0,
iceberg.NestedField{ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true},
iceberg.NestedField{ID: 2, Name: "day", Type: iceberg.PrimitiveTypes.TimestampTz, Required: true},
)
spec := iceberg.NewPartitionSpec(iceberg.PartitionField{SourceIDs: []int{2}, FieldID: 1000, Name: "day", Transform: iceberg.DayTransform{}})
order, err := table.NewSortOrder(1, []table.SortField{{SourceIDs: []int{1}, Transform: iceberg.IdentityTransform{}, Direction: table.SortASC, NullOrder: table.NullsFirst}})
if err != nil {
t.Fatal(err)
}
req := CreateTableRequest{
Name: "events",
Schema: schema,
PartitionSpec: &iceberg.UnboundPartitionSpec{PartitionSpec: spec},
WriteOrder: &table.UnboundSortOrder{SortOrder: order},
Properties: iceberg.Properties{"owner.tag": "x"},
}
location, created, err := server.CreateTable(t.Context(), "whouse", []string{"ns"}, req, "")
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(location, "s3://whouse/ns/events-") || !strings.HasSuffix(location, "/metadata/v1.metadata.json") {
t.Fatalf("metadata location %s", location)
}
loadedLocation, loaded, err := server.LoadTable(t.Context(), "whouse", []string{"ns"}, "events", "")
if err != nil {
t.Fatal(err)
}
if loadedLocation != location || loaded.TableUUID() != created.TableUUID() {
t.Fatalf("loaded %s %s, created %s %s", loadedLocation, loaded.TableUUID(), location, created.TableUUID())
}
loadedSpec := loaded.PartitionSpec()
if loaded.Properties()["owner.tag"] != "x" || loadedSpec.NumFields() != 1 || loaded.SortOrder().Len() != 1 {
t.Fatalf("loaded properties %v spec %v order %v", loaded.Properties(), loadedSpec, loaded.SortOrder())
}
var reqErr *icebergRequestError
if _, _, err := server.CreateTable(t.Context(), "whouse", []string{"ns"}, req, ""); !errors.As(err, &reqErr) || reqErr.errType != "AlreadyExistsException" {
t.Fatalf("second create: %v", err)
}
var tableErr *s3tables.S3TablesError
if _, _, err := server.LoadTable(t.Context(), "whouse", []string{"ns"}, "missing", ""); !errors.As(err, &tableErr) || tableErr.Type != s3tables.ErrCodeNoSuchTable {
t.Fatalf("load of a missing table: %v", err)
}
if _, _, err := server.CreateTable(t.Context(), "whouse", []string{"nope"}, req, ""); !errors.As(err, &reqErr) || reqErr.errType != "NoSuchNamespaceException" {
t.Fatalf("create in a missing namespace: %v", err)
}
stage := req
stage.StageCreate = true
if _, _, err := server.CreateTable(t.Context(), "whouse", []string{"ns"}, stage, ""); err == nil {
t.Fatal("stage-create registered a table")
}
}
+7 -1
View File
@@ -311,8 +311,14 @@ func classifyManagerError(err error) (int, string, string) {
}
func writeManagerError(w http.ResponseWriter, err error) {
reqErr := managerRequestError(err)
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
}
// managerRequestError is the answer classifyManagerError gives err.
func managerRequestError(err error) *icebergRequestError {
status, typ, msg := classifyManagerError(err)
writeError(w, status, typ, msg)
return &icebergRequestError{status, typ, msg}
}
// A storage-layer error the catalog answers with a 4xx (access denied, not