Files
seaweedfs/weed/mq/topictable/layout.go
T
Chris LuandClaude Opus 5.5 2b157f2ef1 test: clear the codespell hits left after #13290 (#13264)
* test: use a codespell-clean non-ASCII key in TestEncodeKey

Codespell reads caf%C3%A9 as the misspelling caf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topictable: reword want's in the CheckSchema comment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:28:00 -08:00

269 lines
9.8 KiB
Go

// Package topictable lays out the Iceberg table that holds an MQ topic's
// compacted history: its columns, partition spec, sort order and the property
// that ties it to the topic.
package topictable
import (
"errors"
"fmt"
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/table"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
)
// TopicProperty is the table property naming the topic that owns the table,
// as <namespace>/<topic>.
const TopicProperty = "seaweedfs.mq.topic"
// System columns, ahead of the record's own.
const (
PartitionColumn = "_partition" // <generation>/<start>-<stop>, the partition directory name
OffsetColumn = "_offset"
TsNsColumn = "_ts_ns"
TsColumn = "_ts" // _ts_ns as a timestamp, for day partitioning
KeyColumn = "_key"
ValueColumn = "_value" // the whole message, when the record type cannot hold it
)
// TsDayField is the partition field day(_ts).
const TsDayField = "_ts_day"
// A DECIMAL field carries no precision or scale, so every one takes the
// decimal the topic's parquet files are written with.
const (
DecimalPrecision = 38
DecimalScale = 18
)
// TopicPropertyValue is TopicProperty's value for t: its directory under
// /topics, so two topics share a value only when they share a topic.conf.
func TopicPropertyValue(t topic.Topic) string {
return t.Namespace + "/" + t.Name
}
// LockKey is the filer lock held by the one writer copying t into its table,
// and by a configure that changes t's table, so the change cannot land
// between the writer's check of topic.conf and its commit.
func LockKey(t topic.Topic) string {
return "mq.table." + t.Namespace + "." + t.Name
}
// SameTable reports whether a and b name the same table, whatever UUID
// either has recorded.
func SameTable(a, b *mq_pb.TopicTable) bool {
if a == nil || b == nil {
return a == b
}
return a.TableBucketArn == b.TableBucketArn && a.Namespace == b.Namespace && a.Name == b.Name
}
// Schema maps a topic's record type to the table's columns: the system
// columns, then the record's fields, each optional whatever is_required says.
// _value holds the whole message of a schemaless topic (a nil record type),
// and of a schematized one whose value is empty or not a record of its type.
// Field ids are numbered fresh from 1; the table renumbers them on create and
// they are matched by name after that.
func Schema(recordType *schema_pb.RecordType) (*iceberg.Schema, error) {
fields := []iceberg.NestedField{
{Name: PartitionColumn, Type: iceberg.PrimitiveTypes.String, Required: true},
{Name: OffsetColumn, Type: iceberg.PrimitiveTypes.Int64, Required: true},
{Name: TsNsColumn, Type: iceberg.PrimitiveTypes.Int64, Required: true},
{Name: TsColumn, Type: iceberg.PrimitiveTypes.TimestampTz, Required: true},
{Name: KeyColumn, Type: iceberg.PrimitiveTypes.Binary},
{Name: ValueColumn, Type: iceberg.PrimitiveTypes.Binary},
}
if recordType != nil {
for _, field := range recordType.Fields {
if isReservedName(field.Name) {
return nil, fmt.Errorf("field %s: name is reserved for a system column or partition field", field.Name)
}
mapped, err := mapField(field)
if err != nil {
return nil, err
}
fields = append(fields, mapped)
}
}
return iceberg.AssignFreshSchemaIDs(iceberg.NewSchema(0, fields...), nil)
}
// isReservedName reports a name the table layout itself uses: a partition
// field sharing a column's name only binds when it is that column's identity.
func isReservedName(name string) bool {
switch name {
case PartitionColumn, OffsetColumn, TsNsColumn, TsColumn, KeyColumn, ValueColumn, TsDayField:
return true
}
return false
}
func mapField(field *schema_pb.Field) (iceberg.NestedField, error) {
if field.Name == "" {
return iceberg.NestedField{}, errors.New("field without a name")
}
fieldType, err := mapType(field.Type)
if err != nil {
return iceberg.NestedField{}, fmt.Errorf("field %s: %w", field.Name, err)
}
// Avro marks an array by its item type; the protobuf and JSON Schema decoders also give the list type
if field.IsRepeated && field.Type.GetListType() == nil {
fieldType = &iceberg.ListType{Element: fieldType}
}
// a message missing a required field still has a row: the table is its only copy
return iceberg.NestedField{Name: field.Name, Type: fieldType}, nil
}
func mapType(t *schema_pb.Type) (iceberg.Type, error) {
switch kind := t.GetKind().(type) {
case *schema_pb.Type_ScalarType:
return mapScalar(kind.ScalarType)
case *schema_pb.Type_RecordType:
if kind.RecordType == nil || len(kind.RecordType.Fields) == 0 {
return nil, errors.New("record without fields")
}
fields := make([]iceberg.NestedField, 0, len(kind.RecordType.Fields))
for _, field := range kind.RecordType.Fields {
mapped, err := mapField(field)
if err != nil {
return nil, err
}
fields = append(fields, mapped)
}
return &iceberg.StructType{FieldList: fields}, nil
case *schema_pb.Type_ListType:
element, err := mapType(kind.ListType.GetElementType())
if err != nil {
return nil, fmt.Errorf("list element: %w", err)
}
return &iceberg.ListType{Element: element}, nil
}
return nil, fmt.Errorf("unsupported type %v", t)
}
func mapScalar(scalar schema_pb.ScalarType) (iceberg.Type, error) {
switch scalar {
case schema_pb.ScalarType_BOOL:
return iceberg.PrimitiveTypes.Bool, nil
case schema_pb.ScalarType_INT32:
return iceberg.PrimitiveTypes.Int32, nil
case schema_pb.ScalarType_INT64:
return iceberg.PrimitiveTypes.Int64, nil
case schema_pb.ScalarType_FLOAT:
return iceberg.PrimitiveTypes.Float32, nil
case schema_pb.ScalarType_DOUBLE:
return iceberg.PrimitiveTypes.Float64, nil
case schema_pb.ScalarType_BYTES:
return iceberg.PrimitiveTypes.Binary, nil
case schema_pb.ScalarType_STRING:
return iceberg.PrimitiveTypes.String, nil
case schema_pb.ScalarType_TIMESTAMP:
return iceberg.PrimitiveTypes.TimestampTz, nil
case schema_pb.ScalarType_DATE:
return iceberg.PrimitiveTypes.Date, nil
case schema_pb.ScalarType_TIME:
return iceberg.PrimitiveTypes.Time, nil
case schema_pb.ScalarType_DECIMAL:
return iceberg.DecimalTypeOf(DecimalPrecision, DecimalScale), nil
}
return nil, fmt.Errorf("unsupported scalar type %v", scalar)
}
// PartitionSpec is identity(_partition), day(_ts) over schema.
func PartitionSpec(schema *iceberg.Schema) (iceberg.PartitionSpec, error) {
partition, ts, err := systemFieldIDs(schema, PartitionColumn, TsColumn)
if err != nil {
return iceberg.PartitionSpec{}, err
}
return iceberg.NewPartitionSpec(
iceberg.PartitionField{SourceIDs: []int{partition}, FieldID: iceberg.PartitionDataIDStart, Name: PartitionColumn, Transform: iceberg.IdentityTransform{}},
iceberg.PartitionField{SourceIDs: []int{ts}, FieldID: iceberg.PartitionDataIDStart + 1, Name: TsDayField, Transform: iceberg.DayTransform{}},
), nil
}
// SortOrder is _partition, _offset ascending over schema, so a data file
// holds one partition's contiguous offset range.
func SortOrder(schema *iceberg.Schema) (table.SortOrder, error) {
partition, offset, err := systemFieldIDs(schema, PartitionColumn, OffsetColumn)
if err != nil {
return table.SortOrder{}, err
}
return table.NewSortOrder(table.InitialSortOrderID, []table.SortField{
{SourceIDs: []int{partition}, Transform: iceberg.IdentityTransform{}, Direction: table.SortASC, NullOrder: table.NullsFirst},
{SourceIDs: []int{offset}, Transform: iceberg.IdentityTransform{}, Direction: table.SortASC, NullOrder: table.NullsFirst},
})
}
func systemFieldIDs(schema *iceberg.Schema, a, b string) (int, int, error) {
fieldA, ok := schema.FindFieldByName(a)
if !ok {
return 0, 0, fmt.Errorf("schema has no %s column", a)
}
fieldB, ok := schema.FindFieldByName(b)
if !ok {
return 0, 0, fmt.Errorf("schema has no %s column", b)
}
return fieldA.ID, fieldB.ID, nil
}
// CheckSchema reports whether a table with columns tableSchema can hold the
// rows of a topic laid out as want: every column want has is in the table by
// name with the same type, nullable wherever its want column is, and every other table
// column is nullable. Field ids are not compared.
func CheckSchema(tableSchema, want *iceberg.Schema) error {
return checkFields("", tableSchema.Fields(), want.Fields())
}
func checkFields(parent string, have, want []iceberg.NestedField) error {
byName := make(map[string]iceberg.NestedField, len(have))
for _, field := range have {
byName[field.Name] = field
}
for _, field := range want {
name := parent + field.Name
got, ok := byName[field.Name]
if !ok {
return fmt.Errorf("table has no column %s", name)
}
delete(byName, field.Name)
if got.Required && !field.Required {
return fmt.Errorf("table column %s is required, the topic's is optional", name)
}
if err := checkType(name, got.Type, field.Type); err != nil {
return err
}
}
for _, field := range have {
if _, extra := byName[field.Name]; extra && field.Required {
return fmt.Errorf("table column %s is required and not in the topic", parent+field.Name)
}
}
return nil
}
func checkType(name string, have, want iceberg.Type) error {
switch want := want.(type) {
case *iceberg.StructType:
got, ok := have.(*iceberg.StructType)
if !ok {
return fmt.Errorf("table column %s is %s, the topic's is %s", name, have, want)
}
return checkFields(name+".", got.FieldList, want.FieldList)
case *iceberg.ListType:
got, ok := have.(*iceberg.ListType)
if !ok {
return fmt.Errorf("table column %s is %s, the topic's is %s", name, have, want)
}
if got.ElementRequired && !want.ElementRequired {
return fmt.Errorf("table column %s has required elements, the topic's are optional", name)
}
return checkType(name+".element", got.Element, want.Element)
}
if !want.Equals(have) {
return fmt.Errorf("table column %s is %s, the topic's is %s", name, have, want)
}
return nil
}