From afdf694e0377e3d3a6bc9820b718d0bcf3db7fc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Fri, 18 Sep 2026 13:53:31 +0300 Subject: [PATCH 01/13] feat(plugin): add watch types and Plugin watch methods Adds the SDK-side vocabulary for event-based syncing: Op, Change, WatchOptions, Position, Ready, RefreshResource, the optional WatchClient interface and SyncOptions.Refresh. Plugin.WatchReady, Plugin.Watch and Plugin.Ack type-assert the client to WatchClient and return ErrNotImplemented otherwise. None of them takes Plugin.mu: a watch stream is long-lived and must not block the refresh syncs that run alongside it. Co-Authored-By: Claude Fable 5.1 --- plugin/plugin_source.go | 143 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) diff --git a/plugin/plugin_source.go b/plugin/plugin_source.go index f626244c10..fb6aa10b22 100644 --- a/plugin/plugin_source.go +++ b/plugin/plugin_source.go @@ -4,7 +4,9 @@ import ( "context" "errors" "fmt" + "time" + "github.com/apache/arrow-go/v18/arrow" "github.com/cloudquery/plugin-sdk/v4/glob" "github.com/cloudquery/plugin-sdk/v4/message" "github.com/cloudquery/plugin-sdk/v4/schema" @@ -28,6 +30,90 @@ type SyncOptions struct { DeterministicCQID bool BackendOptions *BackendOptions Shard *Shard + // Refresh, when non-empty, limits the sync to the listed resources: the plugin + // re-fetches each one and emits an Insert for the resources it finds and a + // DeleteRecord for the ones it does not. `Tables` is ignored and no + // MigrateTable message is emitted. + Refresh []RefreshResource +} + +// Op is the kind of change that happened to a resource. +type Op int + +const ( + // OpUpsert means the resource was created or updated and should be re-fetched. + OpUpsert Op = iota + // OpDelete means the resource no longer exists and should be deleted downstream. + OpDelete +) + +func (o Op) String() string { + switch o { + case OpUpsert: + return "upsert" + case OpDelete: + return "delete" + default: + return fmt.Sprintf("Op(%d)", int(o)) + } +} + +// Change is a single resource-level change observed by a WatchClient. +type Change struct { + // Table is the name of the table the changed resource belongs to. + Table string + // Keys is a one-row record whose columns are the table's primary key columns. + Keys arrow.RecordBatch + Op Op + // EventID identifies this change in the source's event stream. It is echoed + // back by Ack to checkpoint progress. + EventID string + // Time is when the change happened at the source. + Time time.Time +} + +// WatchOptions configures a Watch stream. +type WatchOptions struct { + Tables []string + SkipTables []string + BackendOptions *BackendOptions + Shard *Shard + // Drain asks Watch to return once the sources are caught up instead of + // following the stream indefinitely. + Drain bool +} + +// Position tells Watch where to start reading from. +type Position struct { + // Since starts the stream at the given time. When nil, Watch resumes from the + // stored checkpoint. + Since *time.Time +} + +// Ready is the result of WatchReady: the state of the stored checkpoint. +type Ready struct { + HasCheckpoint bool + CheckpointTime time.Time +} + +// RefreshResource identifies one resource to re-fetch during a refresh sync. +type RefreshResource struct { + Table string + // Keys is a one-row record whose columns are the table's primary key columns. + Keys arrow.RecordBatch + Op Op +} + +// WatchClient is an optional interface a source client can implement to support +// event-based syncing. It is type-asserted on the client, like OnBeforeSender. +type WatchClient interface { + // WatchReady prepares the watch and reports the state of the stored checkpoint. + WatchReady(ctx context.Context, opts WatchOptions) (Ready, error) + // Watch streams changes to the given channel. It returns nil once the sources + // are drained (when WatchOptions.Drain is set) or when ctx is done. + Watch(ctx context.Context, pos Position, changes chan<- Change) error + // Ack checkpoints every change up to and including eventID. + Ack(ctx context.Context, eventID string) error } type SourceClient interface { @@ -102,3 +188,60 @@ func (p *Plugin) Sync(ctx context.Context, options SyncOptions, res chan<- messa return nil } + +// watchClient returns the client as a WatchClient, or ErrNotImplemented if the +// client does not support watching. +func (p *Plugin) watchClient() (WatchClient, error) { + if p.client == nil { + return nil, errors.New("plugin not initialized. call Init() first") + } + c, ok := p.client.(WatchClient) + if !ok { + return nil, ErrNotImplemented + } + return c, nil +} + +// WatchReady prepares a watch stream and reports the state of the stored checkpoint. +// It returns ErrNotImplemented if the client does not implement WatchClient. +// +// Unlike Sync, the watch methods do not take the plugin lock: a watch stream is +// long-lived and must not block refresh syncs running alongside it. +func (p *Plugin) WatchReady(ctx context.Context, opts WatchOptions) (Ready, error) { + c, err := p.watchClient() + if err != nil { + return Ready{}, err + } + ready, err := c.WatchReady(ctx, opts) + if err != nil { + return Ready{}, fmt.Errorf("failed to prepare watch: %w", err) + } + return ready, nil +} + +// Watch streams changes from the client to the given channel until it is drained +// or ctx is done. It returns ErrNotImplemented if the client does not implement +// WatchClient. +func (p *Plugin) Watch(ctx context.Context, pos Position, changes chan<- Change) error { + c, err := p.watchClient() + if err != nil { + return err + } + if err := c.Watch(ctx, pos, changes); err != nil { + return fmt.Errorf("failed to watch: %w", err) + } + return nil +} + +// Ack checkpoints every change up to and including eventID. It returns +// ErrNotImplemented if the client does not implement WatchClient. +func (p *Plugin) Ack(ctx context.Context, eventID string) error { + c, err := p.watchClient() + if err != nil { + return err + } + if err := c.Ack(ctx, eventID); err != nil { + return fmt.Errorf("failed to ack event %q: %w", eventID, err) + } + return nil +} From af1d8bd4a0493bfdbca72679ad7d56150fa3b9df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Fri, 18 Sep 2026 13:53:31 +0300 Subject: [PATCH 02/13] feat(schema): add NewKeysRecord and KeysString NewKeysRecord builds the one-row record that identifies a single resource by its primary keys, always in table.PrimaryKeys() order so the same resource always produces the same record. KeysString renders one as "col=val,col=val" for logging and for coalescing changes. Co-Authored-By: Claude Fable 5.1 --- schema/keys.go | 91 +++++++++++++++++++++++++++++++++ schema/keys_test.go | 120 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 211 insertions(+) create mode 100644 schema/keys.go create mode 100644 schema/keys_test.go diff --git a/schema/keys.go b/schema/keys.go new file mode 100644 index 0000000000..f9f9341add --- /dev/null +++ b/schema/keys.go @@ -0,0 +1,91 @@ +package schema + +import ( + "fmt" + "strings" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/cloudquery/plugin-sdk/v4/scalar" +) + +// NewKeysRecord builds the one-row record that identifies a single resource of +// the given table. Its schema is the table's primary key columns, in +// table.PrimaryKeys() order, so that two records for the same resource are +// always byte-identical regardless of the iteration order of values. +// +// It is an error for values to omit a primary key column or to carry any column +// that is not one. +func NewKeysRecord(table *Table, values map[string]any) (arrow.RecordBatch, error) { + pks := table.PrimaryKeys() + if len(pks) == 0 { + return nil, fmt.Errorf("table %q has no primary keys", table.Name) + } + + for name := range values { + col := table.Column(name) + switch { + case col == nil: + return nil, fmt.Errorf("column %q does not exist on table %q", name, table.Name) + case !col.PrimaryKey: + return nil, fmt.Errorf("column %q is not a primary key of table %q", name, table.Name) + } + } + + fields := make([]arrow.Field, len(pks)) + scalars := make(scalar.Vector, len(pks)) + for i, name := range pks { + value, ok := values[name] + if !ok { + return nil, fmt.Errorf("missing primary key %q for table %q", name, table.Name) + } + col := table.Column(name) + fields[i] = arrow.Field{Name: col.Name, Type: col.Type, Nullable: true} + s := scalar.NewScalar(col.Type) + if err := s.Set(value); err != nil { + return nil, fmt.Errorf("failed to set primary key %q for table %q: %w", name, table.Name, err) + } + scalars[i] = s + } + + bldr := array.NewRecordBuilder(memory.DefaultAllocator, arrow.NewSchema(fields, nil)) + defer bldr.Release() + for i, s := range scalars { + scalar.AppendToBuilder(bldr.Field(i), s) + } + return bldr.NewRecordBatch(), nil +} + +// KeysString renders a keys record as a canonical "col=val,col=val" string in +// column order. It is used for logging and for coalescing changes that refer to +// the same resource. +func KeysString(keys arrow.RecordBatch) string { + if keys == nil || keys.NumRows() == 0 { + return "" + } + + var sb strings.Builder + sc := keys.Schema() + for i, field := range sc.Fields() { + if i > 0 { + sb.WriteByte(',') + } + sb.WriteString(field.Name) + sb.WriteByte('=') + sb.WriteString(columnValueString(field.Type, keys.Column(i))) + } + return sb.String() +} + +// columnValueString renders the first row of arr through the scalar that matches +// the column type, so that the output matches what NewKeysRecord was given. +func columnValueString(dt arrow.DataType, arr arrow.Array) string { + s := scalar.NewScalar(dt) + if err := s.Set(arr.GetOneForMarshal(0)); err != nil { + // Not every arrow type round-trips through its marshalled form; the array's + // own rendering is still stable for a given value. + return arr.ValueStr(0) + } + return s.String() +} diff --git a/schema/keys_test.go b/schema/keys_test.go new file mode 100644 index 0000000000..2dcefe6e9b --- /dev/null +++ b/schema/keys_test.go @@ -0,0 +1,120 @@ +package schema + +import ( + "testing" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/stretchr/testify/require" +) + +func keysTestTable() *Table { + return &Table{ + Name: "test_table", + Columns: ColumnList{ + {Name: "account_id", Type: arrow.BinaryTypes.String, PrimaryKey: true}, + {Name: "not_a_key", Type: arrow.BinaryTypes.String}, + {Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKey: true}, + }, + } +} + +func TestNewKeysRecord_StringPK(t *testing.T) { + table := &Table{ + Name: "test_table", + Columns: ColumnList{ + {Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKey: true}, + {Name: "other", Type: arrow.PrimitiveTypes.Int64}, + }, + } + + rec, err := NewKeysRecord(table, map[string]any{"arn": "arn:aws:ec2:i-123"}) + require.NoError(t, err) + require.EqualValues(t, 1, rec.NumRows()) + require.EqualValues(t, 1, rec.NumCols()) + require.Equal(t, "arn", rec.Schema().Field(0).Name) + require.Equal(t, "arn:aws:ec2:i-123", rec.Column(0).ValueStr(0)) +} + +func TestNewKeysRecord_CompositePKOrder(t *testing.T) { + table := &Table{ + Name: "test_table", + Columns: ColumnList{ + {Name: "account_id", Type: arrow.BinaryTypes.String, PrimaryKey: true}, + {Name: "region", Type: arrow.BinaryTypes.String}, + {Name: "id", Type: arrow.PrimitiveTypes.Int64, PrimaryKey: true}, + }, + } + + // Map iteration order must not affect the record's column order: it follows + // table.PrimaryKeys(). + rec, err := NewKeysRecord(table, map[string]any{"id": int64(42), "account_id": "123456789012"}) + require.NoError(t, err) + require.EqualValues(t, 2, rec.NumCols()) + require.Equal(t, []string{"account_id", "id"}, []string{rec.Schema().Field(0).Name, rec.Schema().Field(1).Name}) + require.Equal(t, "123456789012", rec.Column(0).ValueStr(0)) + require.Equal(t, "42", rec.Column(1).ValueStr(0)) +} + +func TestNewKeysRecord_MissingPK(t *testing.T) { + _, err := NewKeysRecord(keysTestTable(), map[string]any{"account_id": "123456789012"}) + require.ErrorContains(t, err, "arn") + require.ErrorContains(t, err, "test_table") +} + +func TestNewKeysRecord_ExtraColumn(t *testing.T) { + _, err := NewKeysRecord(keysTestTable(), map[string]any{ + "account_id": "123456789012", + "arn": "arn:aws:ec2:i-123", + "not_a_key": "nope", + }) + require.ErrorContains(t, err, "not_a_key") +} + +func TestNewKeysRecord_UnknownColumn(t *testing.T) { + _, err := NewKeysRecord(keysTestTable(), map[string]any{ + "account_id": "123456789012", + "arn": "arn:aws:ec2:i-123", + "nonexistent": "nope", + }) + require.ErrorContains(t, err, "nonexistent") +} + +func TestNewKeysRecord_NoPrimaryKeys(t *testing.T) { + table := &Table{ + Name: "test_table", + Columns: ColumnList{{Name: "col", Type: arrow.BinaryTypes.String}}, + } + _, err := NewKeysRecord(table, map[string]any{}) + require.ErrorContains(t, err, "no primary keys") +} + +func TestKeysString(t *testing.T) { + table := &Table{ + Name: "test_table", + Columns: ColumnList{ + {Name: "account_id", Type: arrow.BinaryTypes.String, PrimaryKey: true}, + {Name: "id", Type: arrow.PrimitiveTypes.Int64, PrimaryKey: true}, + }, + } + + rec, err := NewKeysRecord(table, map[string]any{"account_id": "123456789012", "id": int64(42)}) + require.NoError(t, err) + require.Equal(t, "account_id=123456789012,id=42", KeysString(rec)) +} + +func TestKeysString_Null(t *testing.T) { + table := &Table{ + Name: "test_table", + Columns: ColumnList{ + {Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKey: true}, + }, + } + + rec, err := NewKeysRecord(table, map[string]any{"arn": nil}) + require.NoError(t, err) + require.Equal(t, "arn=(null)", KeysString(rec)) +} + +func TestKeysString_Empty(t *testing.T) { + require.Equal(t, "", KeysString(nil)) +} From eed56a107779eb831b90cc8c80681ecf4929531b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Fri, 18 Sep 2026 13:53:31 +0300 Subject: [PATCH 03/13] feat(message): add NewDeleteRecordByKeys Builds the delete message for a single resource from its keys record: one AND group of EQ predicates, one per primary key column, plus the relations of every descendant table so destinations can cascade the delete. Co-Authored-By: Claude Fable 5.1 --- message/delete_record.go | 76 +++++++++++++++++++++ message/delete_record_test.go | 122 ++++++++++++++++++++++++++++++++++ 2 files changed, 198 insertions(+) create mode 100644 message/delete_record.go create mode 100644 message/delete_record_test.go diff --git a/message/delete_record.go b/message/delete_record.go new file mode 100644 index 0000000000..20f21b9d32 --- /dev/null +++ b/message/delete_record.go @@ -0,0 +1,76 @@ +package message + +import ( + "fmt" + "slices" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + pb "github.com/cloudquery/plugin-pb-go/pb/plugin/v3" + "github.com/cloudquery/plugin-sdk/v4/schema" +) + +// NewDeleteRecordByKeys builds the delete message for the single resource +// identified by keys, a one-row record whose columns are the table's primary +// keys (see schema.NewKeysRecord). +// +// The where clause is one AND group with an EQ predicate per primary key column, +// and the relations cover every descendant table so destinations can cascade the +// delete. +func NewDeleteRecordByKeys(table *schema.Table, keys arrow.RecordBatch) (*SyncDeleteRecord, error) { + if keys == nil { + return nil, fmt.Errorf("no keys record for table %q", table.Name) + } + if keys.NumRows() != 1 { + return nil, fmt.Errorf("keys record for table %q must have exactly one row, got %d", table.Name, keys.NumRows()) + } + + pks := table.PrimaryKeys() + fields := keys.Schema().Fields() + names := make([]string, len(fields)) + for i, field := range fields { + names[i] = field.Name + } + if !slices.Equal(names, pks) { + return nil, fmt.Errorf("keys record columns %v do not match the primary keys %v of table %q", names, pks, table.Name) + } + + predicates := make(Predicates, len(pks)) + for i, name := range pks { + column := keys.Column(i) + sc := arrow.NewSchema([]arrow.Field{fields[i]}, nil) + predicates[i] = Predicate{ + Operator: pb.Predicate_EQ.String(), + Column: name, + Record: array.NewRecordBatch(sc, []arrow.Array{column}, 1), + } + } + + return &SyncDeleteRecord{ + DeleteRecord: DeleteRecord{ + TableName: table.Name, + TableRelations: descendantRelations(table), + WhereClause: PredicateGroups{{ + GroupingType: pb.PredicatesGroup_AND.String(), + Predicates: predicates, + }}, + }, + }, nil +} + +// descendantRelations lists every table below the given one, each paired with its +// immediate parent. +func descendantRelations(table *schema.Table) TableRelations { + relations := make(TableRelations, 0, len(table.Relations)) + for _, child := range table.Relations { + relations = append(relations, TableRelation{ + TableName: child.Name, + ParentTable: table.Name, + }) + relations = append(relations, descendantRelations(child)...) + } + if len(relations) == 0 { + return nil + } + return relations +} diff --git a/message/delete_record_test.go b/message/delete_record_test.go new file mode 100644 index 0000000000..2cc0b706dc --- /dev/null +++ b/message/delete_record_test.go @@ -0,0 +1,122 @@ +package message + +import ( + "testing" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/cloudquery/plugin-sdk/v4/schema" + "github.com/stretchr/testify/require" +) + +func deleteRecordTestTable() *schema.Table { + grandChild := &schema.Table{ + Name: "test_grandchild", + Columns: schema.ColumnList{{Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKey: true}}, + } + child1 := &schema.Table{ + Name: "test_child_one", + Columns: schema.ColumnList{{Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKey: true}}, + Relations: schema.Tables{grandChild}, + } + child2 := &schema.Table{ + Name: "test_child_two", + Columns: schema.ColumnList{{Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKey: true}}, + } + table := &schema.Table{ + Name: "test_parent", + Columns: schema.ColumnList{ + {Name: "account_id", Type: arrow.BinaryTypes.String, PrimaryKey: true}, + {Name: "region", Type: arrow.BinaryTypes.String}, + {Name: "id", Type: arrow.PrimitiveTypes.Int64, PrimaryKey: true}, + }, + Relations: schema.Tables{child1, child2}, + } + return table.Copy(nil) +} + +func TestNewDeleteRecordByKeys(t *testing.T) { + table := deleteRecordTestTable() + keys, err := schema.NewKeysRecord(table, map[string]any{"account_id": "123456789012", "id": int64(42)}) + require.NoError(t, err) + + msg, err := NewDeleteRecordByKeys(table, keys) + require.NoError(t, err) + require.Equal(t, "test_parent", msg.TableName) + + require.Len(t, msg.WhereClause, 1) + group := msg.WhereClause[0] + require.Equal(t, "AND", group.GroupingType) + require.Len(t, group.Predicates, 2) + + require.Equal(t, "EQ", group.Predicates[0].Operator) + require.Equal(t, "account_id", group.Predicates[0].Column) + require.EqualValues(t, 1, group.Predicates[0].Record.NumCols()) + require.EqualValues(t, 1, group.Predicates[0].Record.NumRows()) + require.Equal(t, "account_id", group.Predicates[0].Record.Schema().Field(0).Name) + require.Equal(t, "123456789012", group.Predicates[0].Record.Column(0).ValueStr(0)) + + require.Equal(t, "EQ", group.Predicates[1].Operator) + require.Equal(t, "id", group.Predicates[1].Column) + require.Equal(t, "id", group.Predicates[1].Record.Schema().Field(0).Name) + require.Equal(t, "42", group.Predicates[1].Record.Column(0).ValueStr(0)) + + require.ElementsMatch(t, TableRelations{ + {TableName: "test_child_one", ParentTable: "test_parent"}, + {TableName: "test_grandchild", ParentTable: "test_child_one"}, + {TableName: "test_child_two", ParentTable: "test_parent"}, + }, msg.TableRelations) +} + +func TestNewDeleteRecordByKeys_NoRelations(t *testing.T) { + table := &schema.Table{ + Name: "test_leaf", + Columns: schema.ColumnList{{Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKey: true}}, + } + keys, err := schema.NewKeysRecord(table, map[string]any{"arn": "arn:aws:ec2:i-123"}) + require.NoError(t, err) + + msg, err := NewDeleteRecordByKeys(table, keys) + require.NoError(t, err) + require.Empty(t, msg.TableRelations) + require.Len(t, msg.WhereClause[0].Predicates, 1) +} + +func TestNewDeleteRecordByKeys_ColumnMismatch(t *testing.T) { + table := deleteRecordTestTable() + other := &schema.Table{ + Name: "test_other", + Columns: schema.ColumnList{{Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKey: true}}, + } + keys, err := schema.NewKeysRecord(other, map[string]any{"arn": "arn:aws:ec2:i-123"}) + require.NoError(t, err) + + _, err = NewDeleteRecordByKeys(table, keys) + require.ErrorContains(t, err, "test_parent") +} + +func TestNewDeleteRecordByKeys_TooManyRows(t *testing.T) { + table := &schema.Table{ + Name: "test_leaf", + Columns: schema.ColumnList{{Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKey: true}}, + } + + sc := arrow.NewSchema([]arrow.Field{{Name: "arn", Type: arrow.BinaryTypes.String, Nullable: true}}, nil) + bldr := array.NewRecordBuilder(memory.DefaultAllocator, sc) + defer bldr.Release() + bldr.Field(0).(*array.StringBuilder).AppendValues([]string{"a", "b"}, nil) + twoRows := bldr.NewRecordBatch() + + _, err := NewDeleteRecordByKeys(table, twoRows) + require.ErrorContains(t, err, "exactly one row") +} + +func TestNewDeleteRecordByKeys_NilKeys(t *testing.T) { + table := &schema.Table{ + Name: "test_leaf", + Columns: schema.ColumnList{{Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKey: true}}, + } + _, err := NewDeleteRecordByKeys(table, nil) + require.Error(t, err) +} From f46fa9b56c861151c3e91237beb5c7c30d78a014 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Fri, 18 Sep 2026 13:53:31 +0300 Subject: [PATCH 04/13] feat(scheduler): add Scheduler.Refresh Refresh re-fetches individual resources by their keys and runs the items the Refresher returns through the regular resolve pipeline: column resolvers, PostResourceResolver, relations, CQID calculation and insert batching. It emits no migrate messages and never multiplexes, since the caller already knows the table and the client. OP_DELETE skips the fetch and ErrNotFound turns into a delete message. A resource that fails is reported as a SyncError and does not stop the others; all failures come back joined. Co-Authored-By: Claude Fable 5.1 --- scheduler/refresh.go | 171 ++++++++++++++++++++++++++ scheduler/refresh_test.go | 245 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 416 insertions(+) create mode 100644 scheduler/refresh.go create mode 100644 scheduler/refresh_test.go diff --git a/scheduler/refresh.go b/scheduler/refresh.go new file mode 100644 index 0000000000..7cd8a0412a --- /dev/null +++ b/scheduler/refresh.go @@ -0,0 +1,171 @@ +package scheduler + +import ( + "context" + "errors" + "fmt" + "sync" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/cloudquery/plugin-sdk/v4/message" + "github.com/cloudquery/plugin-sdk/v4/plugin" + "github.com/cloudquery/plugin-sdk/v4/scheduler/metrics" + "github.com/cloudquery/plugin-sdk/v4/schema" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/trace" +) + +// ErrNotFound is what a Refresher returns for a resource that no longer exists at +// the source. Refresh turns it into a delete message. +var ErrNotFound = errors.New("resource not found") + +// Refresher re-fetches single resources by their primary keys. It is implemented +// by source plugins that support event-based syncing. +type Refresher interface { + // Refresh returns the client scoped to the resource and the resource's current + // items, or ErrNotFound if it no longer exists. + Refresh(ctx context.Context, table *schema.Table, keys arrow.RecordBatch) (schema.ClientMeta, []any, error) +} + +// Refresh re-fetches the given resources and emits the result to res: an insert +// for every item the Refresher returns (relations included) and a delete message +// for resources that are gone or explicitly deleted. +// +// Unlike Sync it emits no migrate messages and never multiplexes: the caller +// already knows which table and which client each resource belongs to. +// +// A resource that fails does not stop the others. Every failure is reported as a +// SyncError message and all of them are returned joined once every resource has +// been processed. +func (s *Scheduler) Refresh(ctx context.Context, tables schema.Tables, r Refresher, resources []plugin.RefreshResource, res chan<- message.SyncMessage, opts ...SyncOption) error { + if len(resources) == 0 { + return nil + } + + ctx, span := otel.Tracer(metrics.ResourceName).Start(ctx, + "refresh", + trace.WithAttributes(attribute.Key("sync.invocation.id").String(s.invocationID)), + ) + defer span.End() + + if maxDepth(tables) > s.maxDepth { + return fmt.Errorf("max depth exceeded, max depth is %d", s.maxDepth) + } + + // Only the sync-scoped options are meaningful here; the shard, if any, was + // already applied when the changes were produced. + settings := &syncClient{scheduler: s} + for _, opt := range opts { + opt(settings) + } + + // One slot per resource plus one for the context's cause. + errs := make([]error, len(resources), len(resources)+1) + resolved := make(chan *schema.Resource) + go func() { + defer close(resolved) + var wg sync.WaitGroup + for i, resource := range resources { + // Bound the fan-out with the same semaphore top-level tables use. + if err := s.tableSems[0].Acquire(ctx, 1); err != nil { + errs[i] = fmt.Errorf("failed to refresh resource of table %q: %w", resource.Table, err) + continue + } + wg.Add(1) + go func() { + defer wg.Done() + defer s.tableSems[0].Release(1) + errs[i] = s.refreshResource(ctx, tables, r, resource, settings.deterministicCQID, res, resolved) + }() + } + wg.Wait() + }() + + b := s.batchSettings.getBatcher(ctx, res, s.logger) + defer b.close() // wait for all resources to be processed + for resource := range resolved { + b.process(resource) + } + + return errors.Join(append(errs, context.Cause(ctx))...) +} + +// refreshResource handles one resource: it either emits a delete message or runs +// the freshly fetched items through the regular resolve pipeline. +func (s *Scheduler) refreshResource(ctx context.Context, tables schema.Tables, r Refresher, resource plugin.RefreshResource, deterministicCQID bool, res chan<- message.SyncMessage, resolved chan<- *schema.Resource) error { + table := tables.Get(resource.Table) + if table == nil { + return fmt.Errorf("table %q not found", resource.Table) + } + + if resource.Op == plugin.OpDelete { + return sendDeleteRecord(ctx, table, resource.Keys, res) + } + + client, items, err := r.Refresh(ctx, table, resource.Keys) + switch { + case errors.Is(err, ErrNotFound): + return sendDeleteRecord(ctx, table, resource.Keys, res) + case err != nil: + err = fmt.Errorf("failed to refresh resource %s of table %q: %w", schema.KeysString(resource.Keys), table.Name, err) + select { + case res <- &message.SyncError{TableName: table.Name, Error: err.Error()}: + case <-ctx.Done(): + } + return err + } + + if len(items) == 0 { + return nil + } + if client == nil { + return fmt.Errorf("refresher returned no client for resource %s of table %q", schema.KeysString(resource.Keys), table.Name) + } + + // A per-call copy of the table whose resolver replays the items we already + // have. Everything below it - column resolvers, PostResourceResolver, + // relations, CQID calculation - runs exactly as it does during a full sync. + refreshTable := table.Copy(nil) + refreshTable.Multiplex = nil + refreshTable.Resolver = func(ctx context.Context, _ schema.ClientMeta, _ *schema.Resource, out chan<- any) error { + for _, item := range items { + select { + case out <- item: + case <-ctx.Done(): + return context.Cause(ctx) + } + } + return nil + } + + // Metrics are per resource: the scheduler-wide structure is written to without + // locks, so sharing it across the concurrent refreshes would race. + sc := &syncClient{ + metrics: metrics.NewMetrics(), + tables: schema.Tables{refreshTable}, + client: client, + scheduler: s, + deterministicCQID: deterministicCQID, + logger: s.logger, + invocationID: s.invocationID, + msgChan: res, + } + sc.metrics.InitWithClients(refreshTable, []schema.ClientMeta{client}) + sc.resolveTableDfs(ctx, refreshTable, client, nil, resolved, 1) + + return nil +} + +func sendDeleteRecord(ctx context.Context, table *schema.Table, keys arrow.RecordBatch, res chan<- message.SyncMessage) error { + msg, err := message.NewDeleteRecordByKeys(table, keys) + if err != nil { + return fmt.Errorf("failed to build delete message for table %q: %w", table.Name, err) + } + select { + case res <- msg: + return nil + case <-ctx.Done(): + return context.Cause(ctx) + } +} diff --git a/scheduler/refresh_test.go b/scheduler/refresh_test.go new file mode 100644 index 0000000000..3e36509f37 --- /dev/null +++ b/scheduler/refresh_test.go @@ -0,0 +1,245 @@ +package scheduler + +import ( + "context" + "errors" + "slices" + "sync" + "testing" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/cloudquery/plugin-sdk/v4/message" + "github.com/cloudquery/plugin-sdk/v4/plugin" + "github.com/cloudquery/plugin-sdk/v4/schema" + "github.com/stretchr/testify/require" +) + +type refreshCall struct { + table string + keys string +} + +// fakeRefresher answers Refresh from a canned map keyed by ":". +type fakeRefresher struct { + items map[string][]any + errs map[string]error + + mu sync.Mutex + calls []refreshCall +} + +func (f *fakeRefresher) Refresh(_ context.Context, table *schema.Table, keys arrow.RecordBatch) (schema.ClientMeta, []any, error) { + key := table.Name + ":" + schema.KeysString(keys) + f.mu.Lock() + f.calls = append(f.calls, refreshCall{table: table.Name, keys: schema.KeysString(keys)}) + f.mu.Unlock() + if err, ok := f.errs[key]; ok { + return nil, nil, err + } + return &testExecutionClient{}, f.items[key], nil +} + +func (f *fakeRefresher) refreshCalls() []refreshCall { + f.mu.Lock() + defer f.mu.Unlock() + return slices.Clone(f.calls) +} + +func refreshTestTables() schema.Tables { + child := &schema.Table{ + Name: "test_refresh_child", + Resolver: func(_ context.Context, _ schema.ClientMeta, parent *schema.Resource, res chan<- any) error { + item := parent.Item.(map[string]any) + res <- map[string]any{"child_id": item["id"].(string) + "-child"} + return nil + }, + Columns: schema.ColumnList{ + {Name: "child_id", Type: arrow.BinaryTypes.String, PrimaryKey: true, Resolver: schema.PathResolver("child_id")}, + }, + } + parent := &schema.Table{ + Name: "test_refresh_parent", + Resolver: func(context.Context, schema.ClientMeta, *schema.Resource, chan<- any) error { + return errors.New("the table resolver must not run during a refresh") + }, + Multiplex: func(schema.ClientMeta) []schema.ClientMeta { + panic("Multiplex must not be called during a refresh") + }, + Columns: schema.ColumnList{ + {Name: "id", Type: arrow.BinaryTypes.String, PrimaryKey: true, Resolver: schema.PathResolver("id")}, + {Name: "name", Type: arrow.BinaryTypes.String, Resolver: schema.PathResolver("name")}, + }, + Relations: schema.Tables{child}, + } + schema.AddCqIDs(parent) + return schema.Tables{parent.Copy(nil)} +} + +func refreshKeys(t *testing.T, table *schema.Table, id string) arrow.RecordBatch { + t.Helper() + keys, err := schema.NewKeysRecord(table, map[string]any{"id": id}) + require.NoError(t, err) + return keys +} + +func runRefresh(t *testing.T, tables schema.Tables, r Refresher, resources []plugin.RefreshResource, opts ...SyncOption) (message.SyncMessages, error) { + t.Helper() + s := NewScheduler(WithConcurrency(2)) + res := make(chan message.SyncMessage, 128) + var refreshErr error + done := make(chan struct{}) + go func() { + defer close(done) + defer close(res) + refreshErr = s.Refresh(context.Background(), tables, r, resources, res, opts...) + }() + <-done + var msgs message.SyncMessages + for msg := range res { + msgs = append(msgs, msg) + } + return msgs, refreshErr +} + +func TestRefresh_InsertsItemsAndRelations(t *testing.T) { + tables := refreshTestTables() + parent := tables.Get("test_refresh_parent") + keys := refreshKeys(t, parent, "abc") + + r := &fakeRefresher{items: map[string][]any{ + "test_refresh_parent:id=abc": {map[string]any{"id": "abc", "name": "hello"}}, + }} + + msgs, err := runRefresh(t, tables, r, []plugin.RefreshResource{ + {Table: "test_refresh_parent", Keys: keys, Op: plugin.OpUpsert}, + }) + require.NoError(t, err) + + inserts := msgs.GetInserts() + require.True(t, inserts.Exists("test_refresh_parent"), "expected an insert for the refreshed table") + require.True(t, inserts.Exists("test_refresh_child"), "expected an insert for the relation") + require.EqualValues(t, 2, msgs.InsertItems()) + + for _, msg := range msgs { + _, isMigrate := msg.(*message.SyncMigrateTable) + require.False(t, isMigrate, "Refresh must not emit migrate messages") + } +} + +func TestRefresh_DeterministicCQID(t *testing.T) { + run := func(opts ...SyncOption) string { + tables := refreshTestTables() + parent := tables.Get("test_refresh_parent") + r := &fakeRefresher{items: map[string][]any{ + "test_refresh_parent:id=abc": {map[string]any{"id": "abc", "name": "hello"}}, + }} + msgs, err := runRefresh(t, tables, r, []plugin.RefreshResource{ + {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "abc"), Op: plugin.OpUpsert}, + }, opts...) + require.NoError(t, err) + + records := msgs.GetInserts().GetRecordsForTable(tables.Get("test_refresh_parent")) + require.Len(t, records, 1) + idx := records[0].Schema().FieldIndices(schema.CqIDColumn.Name) + require.Len(t, idx, 1) + return records[0].Column(idx[0]).ValueStr(0) + } + + first := run(WithSyncDeterministicCQID(true)) + second := run(WithSyncDeterministicCQID(true)) + require.Equal(t, first, second, "deterministic _cq_id must be stable across runs") + + require.NotEqual(t, first, run(), "random _cq_id must not match the deterministic one") +} + +func TestRefresh_NotFoundEmitsDeleteRecord(t *testing.T) { + tables := refreshTestTables() + parent := tables.Get("test_refresh_parent") + + r := &fakeRefresher{errs: map[string]error{ + "test_refresh_parent:id=gone": ErrNotFound, + }} + + msgs, err := runRefresh(t, tables, r, []plugin.RefreshResource{ + {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "gone"), Op: plugin.OpUpsert}, + }) + require.NoError(t, err) + require.Len(t, msgs, 1) + + del, ok := msgs[0].(*message.SyncDeleteRecord) + require.True(t, ok, "expected a delete record, got %T", msgs[0]) + require.Equal(t, "test_refresh_parent", del.TableName) + require.Len(t, del.WhereClause, 1) + require.Equal(t, "AND", del.WhereClause[0].GroupingType) + require.Len(t, del.WhereClause[0].Predicates, 1) + require.Equal(t, "EQ", del.WhereClause[0].Predicates[0].Operator) + require.Equal(t, "id", del.WhereClause[0].Predicates[0].Column) + require.Equal(t, "gone", del.WhereClause[0].Predicates[0].Record.Column(0).ValueStr(0)) + require.Equal(t, message.TableRelations{ + {TableName: "test_refresh_child", ParentTable: "test_refresh_parent"}, + }, del.TableRelations) +} + +func TestRefresh_OpDeleteSkipsRefresh(t *testing.T) { + tables := refreshTestTables() + parent := tables.Get("test_refresh_parent") + + r := &fakeRefresher{} + msgs, err := runRefresh(t, tables, r, []plugin.RefreshResource{ + {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "abc"), Op: plugin.OpDelete}, + }) + require.NoError(t, err) + require.Empty(t, r.refreshCalls(), "OpDelete must not call Refresh") + require.Len(t, msgs, 1) + require.IsType(t, &message.SyncDeleteRecord{}, msgs[0]) +} + +func TestRefresh_OneFailureDoesNotStopTheOthers(t *testing.T) { + tables := refreshTestTables() + parent := tables.Get("test_refresh_parent") + + boom := errors.New("boom") + r := &fakeRefresher{ + items: map[string][]any{ + "test_refresh_parent:id=ok1": {map[string]any{"id": "ok1", "name": "one"}}, + "test_refresh_parent:id=ok2": {map[string]any{"id": "ok2", "name": "two"}}, + }, + errs: map[string]error{"test_refresh_parent:id=bad": boom}, + } + + msgs, err := runRefresh(t, tables, r, []plugin.RefreshResource{ + {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "ok1"), Op: plugin.OpUpsert}, + {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "bad"), Op: plugin.OpUpsert}, + {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "ok2"), Op: plugin.OpUpsert}, + }) + require.ErrorIs(t, err, boom) + + // Both healthy resources produced their parent row and their relation row. + require.EqualValues(t, 4, msgs.InsertItems()) + + var syncErrors []*message.SyncError + for _, msg := range msgs { + if e, ok := msg.(*message.SyncError); ok { + syncErrors = append(syncErrors, e) + } + } + require.Len(t, syncErrors, 1) + require.Equal(t, "test_refresh_parent", syncErrors[0].TableName) + require.Contains(t, syncErrors[0].Error, "boom") +} + +func TestRefresh_UnknownTable(t *testing.T) { + tables := refreshTestTables() + parent := tables.Get("test_refresh_parent") + + _, err := runRefresh(t, tables, &fakeRefresher{}, []plugin.RefreshResource{ + {Table: "test_no_such_table", Keys: refreshKeys(t, parent, "abc"), Op: plugin.OpUpsert}, + }) + require.ErrorContains(t, err, "test_no_such_table") +} + +func TestRefresh_NoResources(t *testing.T) { + msgs, err := runRefresh(t, refreshTestTables(), &fakeRefresher{}, nil) + require.NoError(t, err) + require.Empty(t, msgs) +} From 85ca498bc30ad07c5f68214d7a99a3cb59c81691 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Fri, 18 Sep 2026 13:53:41 +0300 Subject: [PATCH 05/13] feat(servers/plugin/v3): implement the Watch RPC and refresh syncs Watch drives the stream handshake - Start, Ready, Position, Change..., Drained - forwards the client's Acks while changes stream out, and reports Unimplemented for plugins that do not implement WatchClient. Sync maps Sync.Request.refresh into SyncOptions.Refresh. Co-Authored-By: Claude Fable 5.1 --- internal/servers/plugin/v3/plugin.go | 221 +++++++++++++++++++++++++++ 1 file changed, 221 insertions(+) diff --git a/internal/servers/plugin/v3/plugin.go b/internal/servers/plugin/v3/plugin.go index df5c42dbd5..9ee13b2969 100644 --- a/internal/servers/plugin/v3/plugin.go +++ b/internal/servers/plugin/v3/plugin.go @@ -19,6 +19,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" ) const MaxMsgSize = 100 * 1024 * 1024 // 100 MiB @@ -184,6 +185,20 @@ func (s *Server) Sync(req *pb.Sync_Request, stream pb.Plugin_SyncServer) error { Total: req.Shard.Total, } } + if len(req.Refresh) > 0 { + syncOptions.Refresh = make([]plugin.RefreshResource, len(req.Refresh)) + for i, resource := range req.Refresh { + keys, err := pb.NewRecordFromBytes(resource.Keys) + if err != nil { + return status.Errorf(codes.InvalidArgument, "failed to decode keys for table %q: %v", resource.Table, err) + } + syncOptions.Refresh[i] = plugin.RefreshResource{ + Table: resource.Table, + Keys: keys, + Op: opFromPB(resource.Op), + } + } + } go func() { defer flushMetrics() @@ -519,3 +534,209 @@ func (s *Server) TransformSchema(ctx context.Context, req *pb.TransformSchema_Re func (s *Server) Close(ctx context.Context, _ *pb.Close_Request) (*pb.Close_Response, error) { return &pb.Close_Response{}, s.Plugin.Close(ctx) } + +func opFromPB(op pb.Op) plugin.Op { + if op == pb.Op_OP_DELETE { + return plugin.OpDelete + } + return plugin.OpUpsert +} + +func opToPB(op plugin.Op) pb.Op { + if op == plugin.OpDelete { + return pb.Op_OP_DELETE + } + return pb.Op_OP_UPSERT +} + +// Watch streams resource-level changes from the plugin to the client. +// +// The client opens with Start, the server answers Ready, the client answers +// Position, and from then on the server streams Change messages while the client +// sends Acks. With Start.drain set, the server sends Drained and closes once the +// sources are caught up. +func (s *Server) Watch(stream pb.Plugin_WatchServer) error { + opts, err := recvWatchStart(stream) + if err != nil { + return err + } + + ready, err := s.Plugin.WatchReady(stream.Context(), opts) + if err != nil { + if errors.Is(err, plugin.ErrNotImplemented) { + return status.Error(codes.Unimplemented, "Watch is not implemented in this plugin") + } + return status.Errorf(codes.Internal, "failed to prepare watch: %v", err) + } + + readyMsg := &pb.Watch_Ready{HasCheckpoint: ready.HasCheckpoint} + if !ready.CheckpointTime.IsZero() { + readyMsg.CheckpointTime = timestamppb.New(ready.CheckpointTime) + } + if err := stream.Send(&pb.Watch_Response{Message: &pb.Watch_Response_Ready{Ready: readyMsg}}); err != nil { + return status.Errorf(codes.Internal, "failed to send watch ready: %v", err) + } + + pos, err := recvWatchPosition(stream) + if err != nil { + return err + } + + // Cancelling this context stops the watch, both when the stream goes away and + // when we stop being able to forward its changes. + ctx, cancel := context.WithCancel(stream.Context()) + defer cancel() + + changes := make(chan plugin.Change) + watchDone := make(chan error, 1) + go func() { + defer close(changes) + watchDone <- s.Plugin.Watch(ctx, pos, changes) + }() + + recvErrs := make(chan error, 1) + go func() { + err := s.recvWatchAcks(ctx, stream) + if err != nil { + cancel() + } + recvErrs <- err + }() + + var streamErr error + acks := recvErrs +loop: + for { + select { + case change, ok := <-changes: + if !ok { + break loop + } + if err := sendWatchChange(stream, change); err != nil { + streamErr = err + break loop + } + case err := <-acks: + if err != nil { + streamErr = err + break loop + } + // The client closed its send side; keep streaming changes to it. + acks = nil + case <-ctx.Done(): + break loop + } + } + + cancel() + for range changes { //nolint:revive // drain so the watch can return + } + watchErr := <-watchDone + + if streamErr != nil { + return streamErr + } + if watchErr != nil { + return status.Errorf(codes.Internal, "failed to watch: %v", watchErr) + } + if err := context.Cause(stream.Context()); err != nil { + return status.Errorf(codes.Canceled, "context done: %v", err) + } + if !opts.Drain { + return nil + } + if err := stream.Send(&pb.Watch_Response{Message: &pb.Watch_Response_Drained{Drained: &pb.Watch_Drained{}}}); err != nil { + return status.Errorf(codes.Internal, "failed to send watch drained: %v", err) + } + return nil +} + +// recvWatchStart reads the opening message of a watch stream, which must be Start. +func recvWatchStart(stream pb.Plugin_WatchServer) (plugin.WatchOptions, error) { + req, err := stream.Recv() + if err != nil { + return plugin.WatchOptions{}, status.Errorf(codes.Internal, "failed to receive watch start: %v", err) + } + msg, ok := req.Message.(*pb.Watch_Request_Start) + if !ok { + return plugin.WatchOptions{}, status.Errorf(codes.InvalidArgument, "the first watch message must be Start, got %T", req.Message) + } + + opts := plugin.WatchOptions{ + Tables: msg.Start.Tables, + SkipTables: msg.Start.SkipTables, + Drain: msg.Start.Drain, + } + if backend := msg.Start.Backend; backend != nil { + opts.BackendOptions = &plugin.BackendOptions{ + TableName: backend.TableName, + Connection: backend.Connection, + } + } + if shard := msg.Start.Shard; shard != nil { + opts.Shard = &plugin.Shard{Num: shard.Num, Total: shard.Total} + } + return opts, nil +} + +// recvWatchPosition reads the message that follows Ready, which must be Position. +func recvWatchPosition(stream pb.Plugin_WatchServer) (plugin.Position, error) { + req, err := stream.Recv() + if err != nil { + return plugin.Position{}, status.Errorf(codes.Internal, "failed to receive watch position: %v", err) + } + msg, ok := req.Message.(*pb.Watch_Request_Position) + if !ok { + return plugin.Position{}, status.Errorf(codes.InvalidArgument, "expected Position after Ready, got %T", req.Message) + } + var pos plugin.Position + if since := msg.Position.Since; since != nil { + at := since.AsTime() + pos.Since = &at + } + return pos, nil +} + +// recvWatchAcks forwards every Ack the client sends until it closes its send side. +// Any other message on an established stream is a protocol error. +func (s *Server) recvWatchAcks(ctx context.Context, stream pb.Plugin_WatchServer) error { + for { + req, err := stream.Recv() + switch { + case errors.Is(err, io.EOF): + return nil + case err != nil: + if ctx.Err() != nil { + return nil + } + return status.Errorf(codes.Internal, "failed to receive watch message: %v", err) + } + msg, ok := req.Message.(*pb.Watch_Request_Ack) + if !ok { + return status.Errorf(codes.InvalidArgument, "expected Ack on an established watch stream, got %T", req.Message) + } + if err := s.Plugin.Ack(ctx, msg.Ack.EventId); err != nil { + return status.Errorf(codes.Internal, "failed to ack event %q: %v", msg.Ack.EventId, err) + } + } +} + +func sendWatchChange(stream pb.Plugin_WatchServer, change plugin.Change) error { + keys, err := pb.RecordToBytes(change.Keys) + if err != nil { + return status.Errorf(codes.Internal, "failed to encode keys of table %q: %v", change.Table, err) + } + pbChange := &pb.Watch_Change{ + Table: change.Table, + Keys: keys, + Op: opToPB(change.Op), + EventId: change.EventID, + } + if !change.Time.IsZero() { + pbChange.Time = timestamppb.New(change.Time) + } + if err := stream.Send(&pb.Watch_Response{Message: &pb.Watch_Response_Change{Change: pbChange}}); err != nil { + return status.Errorf(codes.Internal, "failed to send change: %v", err) + } + return nil +} From 2b4b521cbc8722e45b839bb7cc681bfbd4d4f721 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Fri, 18 Sep 2026 13:53:41 +0300 Subject: [PATCH 06/13] feat(serve): add gRPC keepalive and bounded graceful shutdown A watch stream can sit idle between changes, so the server pings idle connections every 30s and permits client pings without a stream. Shutdown now lets in-flight RPCs finish, falling back to a hard stop after 30s so a long-lived watch cannot hold the server open. Co-Authored-By: Claude Fable 5.1 --- serve/plugin.go | 43 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/serve/plugin.go b/serve/plugin.go index 397431768a..4884a99200 100644 --- a/serve/plugin.go +++ b/serve/plugin.go @@ -10,6 +10,7 @@ import ( "strconv" "strings" "syscall" + "time" "github.com/cloudquery/plugin-sdk/v4/helpers/grpczerolog" "github.com/cloudquery/plugin-sdk/v4/plugin" @@ -33,6 +34,7 @@ import ( "github.com/rs/zerolog/log" "github.com/spf13/cobra" "google.golang.org/grpc" + "google.golang.org/grpc/keepalive" "google.golang.org/grpc/test/bufconn" ) @@ -196,6 +198,14 @@ func (s *PluginServe) newCmdPluginServe() *cobra.Command { ), grpc.MaxRecvMsgSize(MaxGrpcMsgSize), grpc.MaxSendMsgSize(MaxGrpcMsgSize), + // A watch stream can sit idle for a long time between changes, so the + // server pings the client to keep the connection alive and allows the + // client to do the same. + grpc.KeepaliveParams(keepalive.ServerParameters{Time: keepaliveTime}), + grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{ + MinTime: keepaliveMinTime, + PermitWithoutStream: true, + }), ) s.plugin.SetLogger(logger) pbv3.RegisterPluginServer(grpcServer, &serversv3.Server{ @@ -257,11 +267,10 @@ func (s *PluginServe) newCmdPluginServe() *cobra.Command { select { case sig := <-c: logger.Info().Str("address", listener.Addr().String()).Str("signal", sig.String()).Msg("Got stop signal. Plugin server shutting down") - grpcServer.Stop() case <-ctx.Done(): logger.Info().Str("address", listener.Addr().String()).Msg("Context cancelled. Plugin server shutting down") - grpcServer.Stop() } + stopGracefully(grpcServer, logger) }() logger.Info().Str("address", listener.Addr().String()).Str("plugin", s.plugin.PackageAndVersion()).Msg("Plugin server listening") @@ -295,3 +304,33 @@ func (s *PluginServe) newCmdPluginRoot() *cobra.Command { cmd.Version = s.plugin.Version() return cmd } + +const ( + // keepaliveTime is how often the server pings an otherwise idle connection. + keepaliveTime = 30 * time.Second + // keepaliveMinTime is the shortest client ping interval the server accepts. + keepaliveMinTime = 10 * time.Second + // gracefulStopTimeout bounds how long in-flight RPCs get to finish before the + // server is torn down. + gracefulStopTimeout = 30 * time.Second +) + +// stopGracefully lets in-flight RPCs finish, but not forever: a watch stream +// never ends on its own, so the server is forced down once the timeout expires. +func stopGracefully(grpcServer *grpc.Server, logger zerolog.Logger) { + stopped := make(chan struct{}) + go func() { + defer close(stopped) + grpcServer.GracefulStop() + }() + + timer := time.NewTimer(gracefulStopTimeout) + defer timer.Stop() + select { + case <-stopped: + case <-timer.C: + logger.Warn().Dur("timeout_ms", gracefulStopTimeout).Msg("Graceful shutdown timed out. Forcing plugin server to stop") + grpcServer.Stop() + <-stopped + } +} From 24326af05c9cdfde61d3fec8111095d21c294ea2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Fri, 18 Sep 2026 13:53:41 +0300 Subject: [PATCH 07/13] test(serve): cover the Watch RPC and refresh syncs over gRPC Exercises the handshake and drain, ack forwarding, the first message having to be Start, Unimplemented without a WatchClient, and refresh syncs producing inserts for found keys and delete records for missing ones. The refresh-while-watching case fails if Plugin.Watch takes the plugin lock. Co-Authored-By: Claude Fable 5.1 --- serve/plugin_watch_test.go | 414 +++++++++++++++++++++++++++++++++++++ 1 file changed, 414 insertions(+) create mode 100644 serve/plugin_watch_test.go diff --git a/serve/plugin_watch_test.go b/serve/plugin_watch_test.go new file mode 100644 index 0000000000..14f8b28ac3 --- /dev/null +++ b/serve/plugin_watch_test.go @@ -0,0 +1,414 @@ +package serve + +import ( + "context" + "errors" + "io" + "sync" + "testing" + "time" + + "github.com/apache/arrow-go/v18/arrow" + pb "github.com/cloudquery/plugin-pb-go/pb/plugin/v3" + "github.com/cloudquery/plugin-sdk/v4/internal/memdb" + "github.com/cloudquery/plugin-sdk/v4/message" + "github.com/cloudquery/plugin-sdk/v4/plugin" + "github.com/cloudquery/plugin-sdk/v4/scheduler" + "github.com/cloudquery/plugin-sdk/v4/schema" + "github.com/rs/zerolog" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +type watchTestMeta struct{} + +func (*watchTestMeta) ID() string { return "watch_test_client" } + +func watchTestTable() *schema.Table { + table := &schema.Table{ + Name: "watch_test_table", + Resolver: func(_ context.Context, _ schema.ClientMeta, _ *schema.Resource, res chan<- any) error { + res <- map[string]any{"id": "full-sync", "name": "from full sync"} + return nil + }, + Columns: schema.ColumnList{ + {Name: "id", Type: arrow.BinaryTypes.String, PrimaryKey: true, Resolver: schema.PathResolver("id")}, + {Name: "name", Type: arrow.BinaryTypes.String, Resolver: schema.PathResolver("name")}, + }, + } + schema.AddCqIDs(table) + return table +} + +// watchTestClient is a source client that implements both optional event-sync +// interfaces: it replays canned changes over Watch and answers Refresh from a +// canned map. +type watchTestClient struct { + plugin.UnimplementedDestination + + tables schema.Tables + sched *scheduler.Scheduler + + // changes are emitted by Watch, in order. + changes []plugin.Change + // follow keeps Watch open until the context is done instead of returning + // once the changes have been emitted. + follow bool + // refreshItems maps schema.KeysString(keys) to the items Refresh returns. + // A key that is absent is reported as gone. + refreshItems map[string][]any + + mu sync.Mutex + acked []string + watchStarted chan struct{} + readyCalls []plugin.WatchOptions +} + +func newWatchTestClient() *watchTestClient { + return &watchTestClient{ + tables: schema.Tables{watchTestTable()}, + sched: scheduler.NewScheduler(), + refreshItems: map[string][]any{}, + watchStarted: make(chan struct{}), + } +} + +func (*watchTestClient) Close(context.Context) error { return nil } + +func (c *watchTestClient) Tables(_ context.Context, options plugin.TableOptions) (schema.Tables, error) { + return c.tables.FilterDfs(options.Tables, options.SkipTables, options.SkipDependentTables) +} + +func (c *watchTestClient) Sync(ctx context.Context, options plugin.SyncOptions, res chan<- message.SyncMessage) error { + if len(options.Refresh) > 0 { + return c.sched.Refresh(ctx, c.tables, c, options.Refresh, res) + } + tt, err := c.tables.FilterDfs(options.Tables, options.SkipTables, options.SkipDependentTables) + if err != nil { + return err + } + return c.sched.Sync(ctx, &watchTestMeta{}, tt, res, scheduler.WithSyncDeterministicCQID(options.DeterministicCQID)) +} + +func (c *watchTestClient) Refresh(_ context.Context, _ *schema.Table, keys arrow.RecordBatch) (schema.ClientMeta, []any, error) { + items, ok := c.refreshItems[schema.KeysString(keys)] + if !ok { + return nil, nil, scheduler.ErrNotFound + } + return &watchTestMeta{}, items, nil +} + +func (c *watchTestClient) WatchReady(_ context.Context, opts plugin.WatchOptions) (plugin.Ready, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.readyCalls = append(c.readyCalls, opts) + return plugin.Ready{HasCheckpoint: true, CheckpointTime: time.Unix(1700000000, 0).UTC()}, nil +} + +func (c *watchTestClient) Watch(ctx context.Context, _ plugin.Position, changes chan<- plugin.Change) error { + close(c.watchStarted) + for _, change := range c.changes { + select { + case changes <- change: + case <-ctx.Done(): + return nil + } + } + if c.follow { + <-ctx.Done() + } + return nil +} + +func (c *watchTestClient) Ack(_ context.Context, eventID string) error { + c.mu.Lock() + defer c.mu.Unlock() + c.acked = append(c.acked, eventID) + return nil +} + +func (c *watchTestClient) ackedEvents() []string { + c.mu.Lock() + defer c.mu.Unlock() + return append([]string(nil), c.acked...) +} + +func (c *watchTestClient) watchOptions() []plugin.WatchOptions { + c.mu.Lock() + defer c.mu.Unlock() + return append([]plugin.WatchOptions(nil), c.readyCalls...) +} + +// serveTestPlugin starts the plugin over a bufconn listener and returns a +// connected gRPC client. The server is stopped when the test ends. +func serveTestPlugin(t *testing.T, newClient plugin.NewClientFunc) pb.PluginClient { + t.Helper() + + p := plugin.NewPlugin("test_watch_plugin", "v1.0.0", newClient) + p.SetLogger(zerolog.Nop()) + srv := Plugin(p, WithArgs("serve"), WithTestListener()) + + ctx, cancel := context.WithCancel(context.Background()) + var wg sync.WaitGroup + wg.Add(1) + var serveErr error + go func() { + defer wg.Done() + serveErr = srv.Serve(ctx) + }() + t.Cleanup(func() { + cancel() + wg.Wait() + require.NoError(t, serveErr) + }) + + // nolint:staticcheck // bufconn dialing still needs the deprecated DialContext + conn, err := grpc.DialContext(ctx, "bufnet", + grpc.WithContextDialer(srv.bufPluginDialer), + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithBlock(), + ) + require.NoError(t, err) + t.Cleanup(func() { conn.Close() }) + + c := pb.NewPluginClient(conn) + _, err = c.Init(ctx, &pb.Init_Request{}) + require.NoError(t, err) + return c +} + +func serveWatchTestClient(t *testing.T, cl *watchTestClient) pb.PluginClient { + t.Helper() + return serveTestPlugin(t, func(context.Context, zerolog.Logger, []byte, plugin.NewClientOptions) (plugin.Client, error) { + return cl, nil + }) +} + +func watchTestKeys(t *testing.T, id string) arrow.RecordBatch { + t.Helper() + keys, err := schema.NewKeysRecord(watchTestTable(), map[string]any{"id": id}) + require.NoError(t, err) + return keys +} + +func TestWatch_HandshakeAndDrain(t *testing.T) { + cl := newWatchTestClient() + cl.changes = []plugin.Change{ + {Table: "watch_test_table", Keys: watchTestKeys(t, "a"), Op: plugin.OpUpsert, EventID: "e1", Time: time.Unix(1700000001, 0).UTC()}, + {Table: "watch_test_table", Keys: watchTestKeys(t, "b"), Op: plugin.OpDelete, EventID: "e2", Time: time.Unix(1700000002, 0).UTC()}, + } + c := serveWatchTestClient(t, cl) + ctx := context.Background() + + stream, err := c.Watch(ctx) + require.NoError(t, err) + + require.NoError(t, stream.Send(&pb.Watch_Request{Message: &pb.Watch_Request_Start{Start: &pb.Watch_Start{ + Tables: []string{"*"}, + Drain: true, + Backend: &pb.Sync_BackendOptions{TableName: "cq_state", Connection: "@@plugin.test.connection@@"}, + }}})) + + resp, err := stream.Recv() + require.NoError(t, err) + ready, ok := resp.Message.(*pb.Watch_Response_Ready) + require.True(t, ok, "expected Ready first, got %T", resp.Message) + require.True(t, ready.Ready.HasCheckpoint) + require.Equal(t, time.Unix(1700000000, 0).UTC(), ready.Ready.CheckpointTime.AsTime()) + + opts := cl.watchOptions() + require.Len(t, opts, 1) + require.Equal(t, []string{"*"}, opts[0].Tables) + require.True(t, opts[0].Drain) + require.NotNil(t, opts[0].BackendOptions) + require.Equal(t, "cq_state", opts[0].BackendOptions.TableName) + + require.NoError(t, stream.Send(&pb.Watch_Request{Message: &pb.Watch_Request_Position{Position: &pb.Watch_Position{}}})) + + var got []*pb.Watch_Change + drained := false + for { + resp, err := stream.Recv() + if errors.Is(err, io.EOF) { + break + } + require.NoError(t, err) + switch m := resp.Message.(type) { + case *pb.Watch_Response_Change: + got = append(got, m.Change) + case *pb.Watch_Response_Drained: + drained = true + default: + t.Fatalf("unexpected message %T", resp.Message) + } + if drained { + break + } + } + + require.True(t, drained, "expected a Drained message") + require.Len(t, got, 2) + require.Equal(t, "e1", got[0].EventId) + require.Equal(t, pb.Op_OP_UPSERT, got[0].Op) + require.Equal(t, time.Unix(1700000001, 0).UTC(), got[0].Time.AsTime()) + require.Equal(t, "e2", got[1].EventId) + require.Equal(t, pb.Op_OP_DELETE, got[1].Op) + + keys, err := pb.NewRecordFromBytes(got[0].Keys) + require.NoError(t, err) + require.Equal(t, "id=a", schema.KeysString(keys)) +} + +func TestWatch_AckIsForwarded(t *testing.T) { + cl := newWatchTestClient() + cl.follow = true + cl.changes = []plugin.Change{ + {Table: "watch_test_table", Keys: watchTestKeys(t, "a"), Op: plugin.OpUpsert, EventID: "e1"}, + } + c := serveWatchTestClient(t, cl) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + stream, err := c.Watch(ctx) + require.NoError(t, err) + require.NoError(t, stream.Send(&pb.Watch_Request{Message: &pb.Watch_Request_Start{Start: &pb.Watch_Start{Tables: []string{"*"}}}})) + _, err = stream.Recv() + require.NoError(t, err) + require.NoError(t, stream.Send(&pb.Watch_Request{Message: &pb.Watch_Request_Position{Position: &pb.Watch_Position{}}})) + + resp, err := stream.Recv() + require.NoError(t, err) + change, ok := resp.Message.(*pb.Watch_Response_Change) + require.True(t, ok) + + require.NoError(t, stream.Send(&pb.Watch_Request{Message: &pb.Watch_Request_Ack{Ack: &pb.Watch_Ack{EventId: change.Change.EventId}}})) + + require.Eventually(t, func() bool { + return len(cl.ackedEvents()) == 1 + }, 5*time.Second, 10*time.Millisecond, "expected the ack to reach the client") + require.Equal(t, []string{"e1"}, cl.ackedEvents()) +} + +func TestWatch_FirstMessageMustBeStart(t *testing.T) { + c := serveWatchTestClient(t, newWatchTestClient()) + + stream, err := c.Watch(context.Background()) + require.NoError(t, err) + require.NoError(t, stream.Send(&pb.Watch_Request{Message: &pb.Watch_Request_Position{Position: &pb.Watch_Position{}}})) + + _, err = stream.Recv() + require.Error(t, err) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + require.Contains(t, status.Convert(err).Message(), "must be Start") +} + +func TestWatch_UnimplementedWithoutWatchClient(t *testing.T) { + c := serveTestPlugin(t, memdb.NewMemDBClient) + + stream, err := c.Watch(context.Background()) + require.NoError(t, err) + require.NoError(t, stream.Send(&pb.Watch_Request{Message: &pb.Watch_Request_Start{Start: &pb.Watch_Start{Tables: []string{"*"}}}})) + + _, err = stream.Recv() + require.Error(t, err) + require.Equal(t, codes.Unimplemented, status.Code(err)) +} + +// syncRefresh runs a refresh sync and collects the messages it produces. +func syncRefresh(ctx context.Context, t *testing.T, c pb.PluginClient, resources []*pb.Sync_Resource) []*pb.Sync_Response { + t.Helper() + syncClient, err := c.Sync(ctx, &pb.Sync_Request{Refresh: resources}) + require.NoError(t, err) + + var msgs []*pb.Sync_Response + for { + resp, err := syncClient.Recv() + if errors.Is(err, io.EOF) { + break + } + require.NoError(t, err) + msgs = append(msgs, resp) + } + return msgs +} + +func watchTestResource(t *testing.T, id string, op pb.Op) *pb.Sync_Resource { + t.Helper() + keys, err := pb.RecordToBytes(watchTestKeys(t, id)) + require.NoError(t, err) + return &pb.Sync_Resource{Table: "watch_test_table", Keys: keys, Op: op} +} + +func TestSyncRefresh_InsertAndDelete(t *testing.T) { + cl := newWatchTestClient() + cl.refreshItems["id=here"] = []any{map[string]any{"id": "here", "name": "still around"}} + c := serveWatchTestClient(t, cl) + + msgs := syncRefresh(context.Background(), t, c, []*pb.Sync_Resource{ + watchTestResource(t, "here", pb.Op_OP_UPSERT), + watchTestResource(t, "gone", pb.Op_OP_UPSERT), + }) + + var inserts, deletes, migrates int + for _, msg := range msgs { + switch m := msg.Message.(type) { + case *pb.Sync_Response_Insert: + inserts++ + record, err := pb.NewRecordFromBytes(m.Insert.Record) + require.NoError(t, err) + require.EqualValues(t, 1, record.NumRows()) + case *pb.Sync_Response_DeleteRecord: + deletes++ + require.Equal(t, "watch_test_table", m.DeleteRecord.TableName) + require.Len(t, m.DeleteRecord.WhereClause, 1) + require.Equal(t, pb.PredicatesGroup_AND, m.DeleteRecord.WhereClause[0].GroupingType) + require.Len(t, m.DeleteRecord.WhereClause[0].Predicates, 1) + require.Equal(t, pb.Predicate_EQ, m.DeleteRecord.WhereClause[0].Predicates[0].Operator) + require.Equal(t, "id", m.DeleteRecord.WhereClause[0].Predicates[0].Column) + case *pb.Sync_Response_MigrateTable: + migrates++ + } + } + + require.Equal(t, 1, inserts, "expected one insert for the resource that still exists") + require.Equal(t, 1, deletes, "expected one delete for the resource that is gone") + require.Zero(t, migrates, "a refresh sync must not emit migrate messages") +} + +func TestSyncRefresh_WhileWatchStreamIsOpen(t *testing.T) { + cl := newWatchTestClient() + cl.follow = true + cl.refreshItems["id=here"] = []any{map[string]any{"id": "here", "name": "still around"}} + c := serveWatchTestClient(t, cl) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + stream, err := c.Watch(ctx) + require.NoError(t, err) + require.NoError(t, stream.Send(&pb.Watch_Request{Message: &pb.Watch_Request_Start{Start: &pb.Watch_Start{Tables: []string{"*"}}}})) + _, err = stream.Recv() + require.NoError(t, err) + require.NoError(t, stream.Send(&pb.Watch_Request{Message: &pb.Watch_Request_Position{Position: &pb.Watch_Position{}}})) + + // The watch is running: a refresh sync on the same plugin must still go through. + select { + case <-cl.watchStarted: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the watch to start") + } + + msgs := syncRefresh(ctx, t, c, []*pb.Sync_Resource{watchTestResource(t, "here", pb.Op_OP_UPSERT)}) + + var inserts int + for _, msg := range msgs { + if _, ok := msg.Message.(*pb.Sync_Response_Insert); ok { + inserts++ + } + } + require.Equal(t, 1, inserts, "refresh sync must succeed while a watch stream is open") +} From 050dfb1a92828207f7a1d985327766f1ad5df900 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Fri, 18 Sep 2026 13:58:18 +0300 Subject: [PATCH 08/13] feat(examples): make simple_plugin watchable and refreshable The example now implements plugin.WatchClient and scheduler.Refresher so an event-based sync can be driven end to end without a cloud behind it. Two optional spec fields: `changes` replays canned events over the Watch stream, `refresh_data` holds the rows a refresh sync can find. WatchReady connects to the state backend and reports the checkpoint stored under `events:checkpoint`; Ack writes it back and flushes. Full syncs are unchanged. Co-Authored-By: Claude Fable 5.1 --- examples/simple_plugin/client/client.go | 5 +- examples/simple_plugin/client/spec.go | 62 ++++++- examples/simple_plugin/docs/configuration.md | 40 ++++- examples/simple_plugin/plugin/client.go | 174 ++++++++++++++++++- examples/simple_plugin/plugin/client_test.go | 156 +++++++++++++++++ 5 files changed, 428 insertions(+), 9 deletions(-) create mode 100644 examples/simple_plugin/plugin/client_test.go diff --git a/examples/simple_plugin/client/client.go b/examples/simple_plugin/client/client.go index 62f8f8ff92..5c2064f892 100644 --- a/examples/simple_plugin/client/client.go +++ b/examples/simple_plugin/client/client.go @@ -17,7 +17,8 @@ func (*TestClient) ID() string { return "TestClient" } -func (c *TestClient) withClientID(i int) *TestClient { +// WithClientID returns a copy of the client scoped to the given multiplexed ID. +func (c *TestClient) WithClientID(i int) *TestClient { t := *c t.ClientID = i return &t @@ -27,7 +28,7 @@ func MultiplexBySpec(meta schema.ClientMeta) []schema.ClientMeta { cl := meta.(*TestClient) clients := make([]schema.ClientMeta, cl.Spec.NumClients) for i := 0; i < cl.Spec.NumClients; i++ { - clients[i] = cl.withClientID(i) + clients[i] = cl.WithClientID(i) } return clients } diff --git a/examples/simple_plugin/client/spec.go b/examples/simple_plugin/client/spec.go index ed3dded818..c2fe070b97 100644 --- a/examples/simple_plugin/client/spec.go +++ b/examples/simple_plugin/client/spec.go @@ -1,15 +1,73 @@ package client +import ( + "fmt" + + "github.com/cloudquery/plugin-sdk/v4/plugin" +) + +// Change is one canned event the example replays over the Watch stream. +type Change struct { + // Table is the name of the table the changed resource belongs to. + Table string `json:"table"` + // Keys maps every primary key column of the table to its value. + Keys map[string]any `json:"keys"` + // Op is "upsert" (the default) or "delete". + Op string `json:"op"` + // EventID identifies the change. Acking it checkpoints everything up to it. + EventID string `json:"event_id"` +} + +// PluginOp returns the SDK operation the change describes. +func (c Change) PluginOp() plugin.Op { + if c.Op == OpDelete { + return plugin.OpDelete + } + return plugin.OpUpsert +} + +const ( + OpUpsert = "upsert" + OpDelete = "delete" +) + type Spec struct { NumClients int `json:"num_clients"` + // Changes are replayed, in order, over the Watch stream. + Changes []Change `json:"changes,omitempty"` + // RefreshData holds the rows a refresh sync can find, per table. A row must + // carry every primary key column of its table. + RefreshData map[string][]map[string]any `json:"refresh_data,omitempty"` } func (s *Spec) SetDefaults() { if s.NumClients <= 0 { s.NumClients = 1 } + for i := range s.Changes { + if s.Changes[i].Op == "" { + s.Changes[i].Op = OpUpsert + } + } } -func (*Spec) Validate() error { +func (s *Spec) Validate() error { + seen := make(map[string]struct{}, len(s.Changes)) + for i, change := range s.Changes { + switch { + case change.Table == "": + return fmt.Errorf("changes[%d]: table is required", i) + case change.EventID == "": + return fmt.Errorf("changes[%d]: event_id is required", i) + case len(change.Keys) == 0: + return fmt.Errorf("changes[%d]: keys is required", i) + case change.Op != OpUpsert && change.Op != OpDelete: + return fmt.Errorf("changes[%d]: op must be %q or %q, got %q", i, OpUpsert, OpDelete, change.Op) + } + if _, ok := seen[change.EventID]; ok { + return fmt.Errorf("changes[%d]: duplicate event_id %q", i, change.EventID) + } + seen[change.EventID] = struct{}{} + } return nil -} \ No newline at end of file +} diff --git a/examples/simple_plugin/docs/configuration.md b/examples/simple_plugin/docs/configuration.md index 95a0a9698f..c3b3ccb5a8 100644 --- a/examples/simple_plugin/docs/configuration.md +++ b/examples/simple_plugin/docs/configuration.md @@ -6,4 +6,42 @@ description: How to configure the simple_plugin example. # Configuration -This plugin requires no configuration. \ No newline at end of file +Every field is optional. + +| Field | Type | Description | +|---|---|---| +| `num_clients` | int | How many multiplexed clients to fetch with. Defaults to `1`. | +| `changes` | list | Canned events replayed over the `Watch` stream, in order. | +| `refresh_data` | map | The rows a refresh sync can find, per table. | + +## Event-based sync + +`changes` and `refresh_data` drive `sync_mode: events` without a cloud behind +the plugin. + +```yaml +spec: + num_clients: 1 + changes: + - table: test_some_table + keys: { column1: "test_project_id", client_id: 0 } + op: upsert # upsert (default) or delete + event_id: "1" + - table: test_some_table + keys: { column1: "gone", client_id: 0 } + op: delete + event_id: "2" + refresh_data: + test_some_table: + - { column1: "test_project_id", column2: 123, client_id: 0 } +``` + +- `changes[].keys` must carry every primary key column of the table. For + `test_some_table` those are `column1` and `client_id`. +- `changes[].event_id` must be unique. Acking one checkpoints every change up to + and including it, in the state backend under `events:checkpoint` (with + `events:checkpoint_time` alongside it). A later `Watch` with no explicit + position resumes after that event. +- `refresh_data` rows must also carry every primary key column. A refresh for + keys that match a row emits an insert for it; keys that match nothing emit a + delete record. diff --git a/examples/simple_plugin/plugin/client.go b/examples/simple_plugin/plugin/client.go index 2806ef1f85..f1e2b95540 100644 --- a/examples/simple_plugin/plugin/client.go +++ b/examples/simple_plugin/plugin/client.go @@ -3,7 +3,9 @@ package plugin import ( "context" "encoding/json" + "errors" "fmt" + "time" "github.com/apache/arrow-go/v18/arrow" "github.com/cloudquery/plugin-sdk/examples/simple_plugin/client" @@ -12,15 +14,32 @@ import ( "github.com/cloudquery/plugin-sdk/v4/plugin" "github.com/cloudquery/plugin-sdk/v4/scheduler" "github.com/cloudquery/plugin-sdk/v4/schema" + "github.com/cloudquery/plugin-sdk/v4/state" "github.com/cloudquery/plugin-sdk/v4/transformers" "github.com/rs/zerolog" ) +const ( + // checkpointKey holds the id of the last acked event. + checkpointKey = "events:checkpoint" + // checkpointTimeKey holds when that event was acked, as RFC3339. + checkpointTimeKey = "events:checkpoint_time" +) + +var ( + _ plugin.WatchClient = (*Client)(nil) + _ scheduler.Refresher = (*Client)(nil) +) + type Client struct { logger zerolog.Logger config client.Spec tables schema.Tables scheduler *scheduler.Scheduler + + // stateClient and checkpoint are set by WatchReady. + stateClient state.Client + checkpoint string } func (c *Client) Logger() *zerolog.Logger { @@ -28,17 +47,159 @@ func (c *Client) Logger() *zerolog.Logger { } func (c *Client) Sync(ctx context.Context, options plugin.SyncOptions, res chan<- message.SyncMessage) error { + if len(options.Refresh) > 0 { + return c.scheduler.Refresh(ctx, c.tables, c, options.Refresh, res, scheduler.WithSyncDeterministicCQID(options.DeterministicCQID)) + } + tt, err := c.tables.FilterDfs(options.Tables, options.SkipTables, options.SkipDependentTables) if err != nil { return err } - schedulerClient := &client.TestClient{ + return c.scheduler.Sync(ctx, c.schedulerClient(), tt, res, scheduler.WithSyncDeterministicCQID(options.DeterministicCQID)) +} + +func (c *Client) schedulerClient() *client.TestClient { + return &client.TestClient{ Logger: c.logger, Spec: c.config, } +} + +// Refresh answers a refresh sync from the `refresh_data` rows in the spec. A row +// matches when every primary key column of the table holds the requested value. +func (c *Client) Refresh(_ context.Context, table *schema.Table, keys arrow.RecordBatch) (schema.ClientMeta, []any, error) { + want := schema.KeysString(keys) + for _, row := range c.config.RefreshData[table.Name] { + rowKeys, err := rowKeysRecord(table, row) + if err != nil { + return nil, nil, fmt.Errorf("refresh_data row of table %q: %w", table.Name, err) + } + if schema.KeysString(rowKeys) != want { + continue + } + return c.schedulerClient().WithClientID(rowClientID(row)), []any{row}, nil + } + return nil, nil, scheduler.ErrNotFound +} + +// rowKeysRecord builds the keys record of a `refresh_data` row so it can be +// compared with the keys of the resource being refreshed. +func rowKeysRecord(table *schema.Table, row map[string]any) (arrow.RecordBatch, error) { + values := make(map[string]any, len(table.PrimaryKeys())) + for _, name := range table.PrimaryKeys() { + value, ok := row[name] + if !ok { + return nil, fmt.Errorf("missing primary key %q", name) + } + values[name] = value + } + return schema.NewKeysRecord(table, values) +} - return c.scheduler.Sync(ctx, schedulerClient, tt, res, scheduler.WithSyncDeterministicCQID(options.DeterministicCQID)) +// rowClientID reports which multiplexed client a `refresh_data` row belongs to. +func rowClientID(row map[string]any) int { + switch id := row["client_id"].(type) { + case float64: + return int(id) + case int: + return id + default: + return 0 + } +} + +// WatchReady connects to the state backend and reports the stored checkpoint. +func (c *Client) WatchReady(ctx context.Context, opts plugin.WatchOptions) (plugin.Ready, error) { + stateClient, err := state.NewConnectedClient(ctx, opts.BackendOptions) + if err != nil { + return plugin.Ready{}, fmt.Errorf("failed to connect to the state backend: %w", err) + } + c.stateClient = stateClient + + eventID, err := stateClient.GetKey(ctx, checkpointKey) + if err != nil { + return plugin.Ready{}, fmt.Errorf("failed to read %s: %w", checkpointKey, err) + } + c.checkpoint = eventID + if eventID == "" { + return plugin.Ready{}, nil + } + + ready := plugin.Ready{HasCheckpoint: true} + at, err := stateClient.GetKey(ctx, checkpointTimeKey) + if err != nil { + return plugin.Ready{}, fmt.Errorf("failed to read %s: %w", checkpointTimeKey, err) + } + if at != "" { + ready.CheckpointTime, err = time.Parse(time.RFC3339, at) + if err != nil { + return plugin.Ready{}, fmt.Errorf("failed to parse %s %q: %w", checkpointTimeKey, at, err) + } + } + return ready, nil +} + +// Watch replays the changes configured in the spec and returns. Everything is +// replayed when the caller asked for a point in time or when there is no +// checkpoint; otherwise only the changes after the checkpointed event are. +func (c *Client) Watch(ctx context.Context, pos plugin.Position, changes chan<- plugin.Change) error { + pending := c.config.Changes + if pos.Since == nil && c.checkpoint != "" { + pending = changesAfter(pending, c.checkpoint) + } + + for _, change := range pending { + table := c.tables.Get(change.Table) + if table == nil { + return fmt.Errorf("change %q refers to unknown table %q", change.EventID, change.Table) + } + keys, err := schema.NewKeysRecord(table, change.Keys) + if err != nil { + return fmt.Errorf("failed to build the keys of change %q: %w", change.EventID, err) + } + select { + case changes <- plugin.Change{ + Table: change.Table, + Keys: keys, + Op: change.PluginOp(), + EventID: change.EventID, + Time: time.Now().UTC(), + }: + case <-ctx.Done(): + return nil + } + } + return nil +} + +// changesAfter returns the changes that follow the given event id. An id that is +// not in the list leaves every change pending. +func changesAfter(changes []client.Change, eventID string) []client.Change { + for i, change := range changes { + if change.EventID == eventID { + return changes[i+1:] + } + } + return changes +} + +// Ack checkpoints every change up to and including eventID. +func (c *Client) Ack(ctx context.Context, eventID string) error { + if c.stateClient == nil { + return errors.New("watch not started: call WatchReady first") + } + if err := c.stateClient.SetKey(ctx, checkpointKey, eventID); err != nil { + return fmt.Errorf("failed to store %s: %w", checkpointKey, err) + } + if err := c.stateClient.SetKey(ctx, checkpointTimeKey, time.Now().UTC().Format(time.RFC3339)); err != nil { + return fmt.Errorf("failed to store %s: %w", checkpointTimeKey, err) + } + if err := c.stateClient.Flush(ctx); err != nil { + return fmt.Errorf("failed to flush the state backend: %w", err) + } + c.checkpoint = eventID + return nil } func (c *Client) Tables(_ context.Context, options plugin.TableOptions) (schema.Tables, error) { @@ -50,8 +211,13 @@ func (c *Client) Tables(_ context.Context, options plugin.TableOptions) (schema. return tt, nil } -func (*Client) Close(_ context.Context) error { - return nil +func (c *Client) Close(_ context.Context) error { + if c.stateClient == nil { + return nil + } + err := c.stateClient.Close() + c.stateClient = nil + return err } func (*Client) Write(context.Context, <-chan message.WriteMessage) error { diff --git a/examples/simple_plugin/plugin/client_test.go b/examples/simple_plugin/plugin/client_test.go new file mode 100644 index 0000000000..c5c20b0690 --- /dev/null +++ b/examples/simple_plugin/plugin/client_test.go @@ -0,0 +1,156 @@ +package plugin + +import ( + "context" + "strings" + "testing" + + "github.com/cloudquery/plugin-sdk/v4/message" + "github.com/cloudquery/plugin-sdk/v4/plugin" + "github.com/cloudquery/plugin-sdk/v4/schema" + "github.com/rs/zerolog" +) + +const eventSyncSpec = `{ + "num_clients": 1, + "changes": [ + {"table": "test_some_table", "keys": {"column1": "a", "client_id": 0}, "op": "upsert", "event_id": "e1"}, + {"table": "test_some_table", "keys": {"column1": "b", "client_id": 0}, "op": "delete", "event_id": "e2"} + ], + "refresh_data": { + "test_some_table": [ + {"column1": "a", "column2": 7, "client_id": 0} + ] + } +}` + +// syncMessages runs a sync on the client and collects everything it emits. +func syncMessages(ctx context.Context, c *Client, options plugin.SyncOptions) (message.SyncMessages, error) { + res := make(chan message.SyncMessage) + var syncErr error + go func() { + defer close(res) + syncErr = c.Sync(ctx, options, res) + }() + var msgs message.SyncMessages + for msg := range res { + msgs = append(msgs, msg) + } + return msgs, syncErr +} + +func newEventSyncClient(t *testing.T) *Client { + t.Helper() + cl, err := Configure(context.Background(), zerolog.Nop(), []byte(eventSyncSpec), plugin.NewClientOptions{}) + if err != nil { + t.Fatalf("failed to configure the client: %v", err) + } + return cl.(*Client) +} + +func TestWatchReplaysConfiguredChanges(t *testing.T) { + c := newEventSyncClient(t) + ctx := context.Background() + + // No backend options: the state client falls back to the no-op client, so + // there is no checkpoint and every change is replayed. + ready, err := c.WatchReady(ctx, plugin.WatchOptions{Tables: []string{"*"}, Drain: true}) + if err != nil { + t.Fatalf("WatchReady failed: %v", err) + } + if ready.HasCheckpoint { + t.Fatal("expected no checkpoint without a state backend") + } + + changes := make(chan plugin.Change, 8) + if err := c.Watch(ctx, plugin.Position{}, changes); err != nil { + t.Fatalf("Watch failed: %v", err) + } + close(changes) + + var got []plugin.Change + for change := range changes { + got = append(got, change) + } + if len(got) != 2 { + t.Fatalf("expected 2 changes, got %d", len(got)) + } + + if got[0].EventID != "e1" || got[0].Op != plugin.OpUpsert { + t.Errorf("unexpected first change: %+v", got[0]) + } + if keys := schema.KeysString(got[0].Keys); keys != "column1=a,client_id=0" { + t.Errorf("unexpected keys on the first change: %s", keys) + } + if got[1].EventID != "e2" || got[1].Op != plugin.OpDelete { + t.Errorf("unexpected second change: %+v", got[1]) + } + + if err := c.Ack(ctx, "e1"); err != nil { + t.Fatalf("Ack failed: %v", err) + } +} + +func TestSyncRefreshFindsAndMissesRows(t *testing.T) { + c := newEventSyncClient(t) + ctx := context.Background() + + table := c.tables.Get("test_some_table") + if table == nil { + t.Fatal("test_some_table is missing") + } + + found, err := schema.NewKeysRecord(table, map[string]any{"column1": "a", "client_id": 0}) + if err != nil { + t.Fatalf("failed to build keys: %v", err) + } + missing, err := schema.NewKeysRecord(table, map[string]any{"column1": "zz", "client_id": 0}) + if err != nil { + t.Fatalf("failed to build keys: %v", err) + } + + msgs, err := syncMessages(ctx, c, plugin.SyncOptions{Refresh: []plugin.RefreshResource{ + {Table: "test_some_table", Keys: found, Op: plugin.OpUpsert}, + {Table: "test_some_table", Keys: missing, Op: plugin.OpUpsert}, + }}) + if err != nil { + t.Fatalf("refresh sync failed: %v", err) + } + + var inserts, deletes int + for _, msg := range msgs { + switch msg.(type) { + case *message.SyncInsert: + inserts++ + case *message.SyncDeleteRecord: + deletes++ + case *message.SyncMigrateTable: + t.Fatal("a refresh sync must not emit migrate messages") + } + } + if inserts != 1 { + t.Errorf("expected 1 insert, got %d", inserts) + } + if deletes != 1 { + t.Errorf("expected 1 delete record, got %d", deletes) + } +} + +func TestFullSyncStillWorks(t *testing.T) { + c := newEventSyncClient(t) + + msgs, err := syncMessages(context.Background(), c, plugin.SyncOptions{Tables: []string{"*"}}) + if err != nil { + t.Fatalf("full sync failed: %v", err) + } + if items := msgs.InsertItems(); items != 1 { + t.Errorf("expected 1 row from the full sync, got %d", items) + } +} + +func TestSpecValidation(t *testing.T) { + _, err := Configure(context.Background(), zerolog.Nop(), []byte(`{"changes":[{"table":"test_some_table"}]}`), plugin.NewClientOptions{}) + if err == nil || !strings.Contains(err.Error(), "event_id is required") { + t.Fatalf("expected an event_id validation error, got %v", err) + } +} From 4337fbc78d7e1c7d6aeb124f78c18e472880c1af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Fri, 18 Sep 2026 14:15:31 +0300 Subject: [PATCH 09/13] docs(plugin): document the WatchClient concurrency contract WatchReady is called first and alone; Watch and Ack then run concurrently from different goroutines for the lifetime of the stream, and an Ack routinely lands while Watch is blocked. Neither the SDK nor the gRPC server locks around them, and a refresh Sync can run on the same client at the same time, so implementations must guard whatever the two share. Close can also land on a live watch. Co-Authored-By: Claude Fable 5.1 --- plugin/plugin_source.go | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/plugin/plugin_source.go b/plugin/plugin_source.go index fb6aa10b22..b56f882efc 100644 --- a/plugin/plugin_source.go +++ b/plugin/plugin_source.go @@ -106,13 +106,32 @@ type RefreshResource struct { // WatchClient is an optional interface a source client can implement to support // event-based syncing. It is type-asserted on the client, like OnBeforeSender. +// +// Call order and concurrency, which implementations must honour: +// +// - WatchReady is called first and on its own. Watch and Ack are not called +// until it has returned. +// - Watch and Ack are then called concurrently, from different goroutines, for +// the lifetime of the stream. An Ack routinely arrives while Watch is blocked +// sending a change or waiting for the next one, so Watch must not be the only +// thing that can make progress. +// - Acks are serialised with respect to each other, but not with respect to +// Watch. Any state the two share - a checkpoint, a state client, a cursor - +// must be guarded by the implementation. Neither the SDK nor the gRPC server +// takes a lock around these calls, and Plugin.Sync can run a refresh on the +// same client at the same time. +// - Close may be called while a watch is still running, so it must be safe +// against a concurrent Ack. type WatchClient interface { // WatchReady prepares the watch and reports the state of the stored checkpoint. + // It is called once, before Watch and Ack. WatchReady(ctx context.Context, opts WatchOptions) (Ready, error) // Watch streams changes to the given channel. It returns nil once the sources - // are drained (when WatchOptions.Drain is set) or when ctx is done. + // are drained (when WatchOptions.Drain is set) or when ctx is done. It runs + // concurrently with Ack. Watch(ctx context.Context, pos Position, changes chan<- Change) error - // Ack checkpoints every change up to and including eventID. + // Ack checkpoints every change up to and including eventID. It is called from + // a different goroutine than Watch, and may be called while Watch is blocked. Ack(ctx context.Context, eventID string) error } From e9fd3666b60b9a3906d5bd0b3967aa4d40706be7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Fri, 18 Sep 2026 14:15:40 +0300 Subject: [PATCH 10/13] fix(examples): guard simple_plugin state shared by Watch and Ack Watch read the checkpoint while Ack wrote it, and Close nil'd the state client that Ack dereferences, all without synchronization. A mutex now covers stateClient and checkpoint; Ack holds it for the whole write, so Close waits for an in-flight ack instead of closing underneath it. Adds two tests that drive Watch, Ack and Close concurrently. Both report a data race against the previous code under -race. Co-Authored-By: Claude Fable 5.1 --- examples/simple_plugin/plugin/client.go | 40 +++++++-- examples/simple_plugin/plugin/client_test.go | 91 ++++++++++++++++++++ 2 files changed, 125 insertions(+), 6 deletions(-) diff --git a/examples/simple_plugin/plugin/client.go b/examples/simple_plugin/plugin/client.go index f1e2b95540..6816f9a308 100644 --- a/examples/simple_plugin/plugin/client.go +++ b/examples/simple_plugin/plugin/client.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "sync" "time" "github.com/apache/arrow-go/v18/arrow" @@ -37,7 +38,9 @@ type Client struct { tables schema.Tables scheduler *scheduler.Scheduler - // stateClient and checkpoint are set by WatchReady. + // watchMu guards stateClient and checkpoint. Watch and Ack run concurrently + // for the lifetime of a watch stream, and Close can land on top of either. + watchMu sync.Mutex stateClient state.Client checkpoint string } @@ -115,13 +118,12 @@ func (c *Client) WatchReady(ctx context.Context, opts plugin.WatchOptions) (plug if err != nil { return plugin.Ready{}, fmt.Errorf("failed to connect to the state backend: %w", err) } - c.stateClient = stateClient eventID, err := stateClient.GetKey(ctx, checkpointKey) if err != nil { return plugin.Ready{}, fmt.Errorf("failed to read %s: %w", checkpointKey, err) } - c.checkpoint = eventID + c.setWatchState(stateClient, eventID) if eventID == "" { return plugin.Ready{}, nil } @@ -145,8 +147,8 @@ func (c *Client) WatchReady(ctx context.Context, opts plugin.WatchOptions) (plug // checkpoint; otherwise only the changes after the checkpointed event are. func (c *Client) Watch(ctx context.Context, pos plugin.Position, changes chan<- plugin.Change) error { pending := c.config.Changes - if pos.Since == nil && c.checkpoint != "" { - pending = changesAfter(pending, c.checkpoint) + if checkpoint := c.watchCheckpoint(); pos.Since == nil && checkpoint != "" { + pending = changesAfter(pending, checkpoint) } for _, change := range pending { @@ -184,8 +186,29 @@ func changesAfter(changes []client.Change, eventID string) []client.Change { return changes } -// Ack checkpoints every change up to and including eventID. +// setWatchState records what WatchReady found. +func (c *Client) setWatchState(stateClient state.Client, checkpoint string) { + c.watchMu.Lock() + defer c.watchMu.Unlock() + c.stateClient = stateClient + c.checkpoint = checkpoint +} + +// watchCheckpoint returns the last acked event id. +func (c *Client) watchCheckpoint() string { + c.watchMu.Lock() + defer c.watchMu.Unlock() + return c.checkpoint +} + +// Ack checkpoints every change up to and including eventID. It runs on a +// different goroutine than Watch, so it takes the lock for the whole write: +// acks are serialised with each other anyway, and Close must not pull the state +// client out from under one. func (c *Client) Ack(ctx context.Context, eventID string) error { + c.watchMu.Lock() + defer c.watchMu.Unlock() + if c.stateClient == nil { return errors.New("watch not started: call WatchReady first") } @@ -211,7 +234,12 @@ func (c *Client) Tables(_ context.Context, options plugin.TableOptions) (schema. return tt, nil } +// Close releases the state backend. It can be called while a watch is still +// running, so it waits for an in-flight Ack instead of closing underneath it. func (c *Client) Close(_ context.Context) error { + c.watchMu.Lock() + defer c.watchMu.Unlock() + if c.stateClient == nil { return nil } diff --git a/examples/simple_plugin/plugin/client_test.go b/examples/simple_plugin/plugin/client_test.go index c5c20b0690..8aeb59f6dd 100644 --- a/examples/simple_plugin/plugin/client_test.go +++ b/examples/simple_plugin/plugin/client_test.go @@ -3,6 +3,7 @@ package plugin import ( "context" "strings" + "sync" "testing" "github.com/cloudquery/plugin-sdk/v4/message" @@ -154,3 +155,93 @@ func TestSpecValidation(t *testing.T) { t.Fatalf("expected an event_id validation error, got %v", err) } } + +// TestWatchAndAckRunConcurrently exercises the WatchClient contract: Watch and +// Ack are called from different goroutines for the lifetime of the stream, so +// everything they share has to be guarded. Run it under -race. +func TestWatchAndAckRunConcurrently(t *testing.T) { + c := newEventSyncClient(t) + ctx := context.Background() + + if _, err := c.WatchReady(ctx, plugin.WatchOptions{Tables: []string{"*"}}); err != nil { + t.Fatalf("WatchReady failed: %v", err) + } + + // Several episodes so the two goroutines actually overlap rather than + // happening to run one after the other. + for range 50 { + changes := make(chan plugin.Change) + var ( + wg sync.WaitGroup + watchErr error + ackErr error + ) + + wg.Add(3) + go func() { + defer wg.Done() + defer close(changes) + watchErr = c.Watch(ctx, plugin.Position{}, changes) + }() + go func() { + defer wg.Done() + for range changes { //revive:disable-line:empty-block // the acker below drives the checkpoint + } + }() + go func() { + defer wg.Done() + for _, eventID := range []string{"e1", "e2"} { + if err := c.Ack(ctx, eventID); err != nil { + ackErr = err + return + } + } + }() + wg.Wait() + + if watchErr != nil { + t.Fatalf("Watch failed: %v", watchErr) + } + if ackErr != nil { + t.Fatalf("Ack failed: %v", ackErr) + } + } + + if checkpoint := c.watchCheckpoint(); checkpoint != "e2" { + t.Errorf("expected the checkpoint to be e2, got %q", checkpoint) + } +} + +// TestCloseIsSafeDuringAcks closes the client while acks are still in flight, +// which is what happens when a follow-mode sync is cancelled. +func TestCloseIsSafeDuringAcks(t *testing.T) { + c := newEventSyncClient(t) + ctx := context.Background() + + if _, err := c.WatchReady(ctx, plugin.WatchOptions{Tables: []string{"*"}}); err != nil { + t.Fatalf("WatchReady failed: %v", err) + } + + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + // An ack that lands after Close is rejected, not a panic or a race. + for range 100 { + if err := c.Ack(ctx, "e1"); err != nil && !strings.Contains(err.Error(), "watch not started") { + t.Errorf("unexpected ack error: %v", err) + return + } + } + }() + + if err := c.Close(ctx); err != nil { + t.Fatalf("Close failed: %v", err) + } + wg.Wait() + + // Closing twice is a no-op. + if err := c.Close(ctx); err != nil { + t.Fatalf("second Close failed: %v", err) + } +} From 2aa9dca61d0ba5a1c9b309960804d1df555abfa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Fri, 18 Sep 2026 15:03:28 +0300 Subject: [PATCH 11/13] fix(schema,message,scheduler): key records on PK components when declared AWS tables keep _cq_id as their only primary key and carry resource identity in PrimaryKeyComponent columns, which is also what Resource.CalculateCQID hashes. Keying on PrimaryKeys() rejected every one of them. Table.IdentityColumns() now defines the set once - components when the table declares any, otherwise primary keys - and NewKeysRecord, NewDeleteRecordByKeys and the refresh delete path all use it. KeysString is unchanged, since it just walks the record it is given. Co-Authored-By: Claude Fable 5.1 --- message/delete_record.go | 17 ++++---- message/delete_record_test.go | 52 +++++++++++++++++++++++ plugin/plugin_source.go | 8 +++- scheduler/refresh.go | 10 +++-- scheduler/refresh_test.go | 78 +++++++++++++++++++++++++++++++++++ schema/keys.go | 39 ++++++++++-------- schema/keys_test.go | 68 +++++++++++++++++++++++++++++- schema/table.go | 15 +++++++ 8 files changed, 255 insertions(+), 32 deletions(-) diff --git a/message/delete_record.go b/message/delete_record.go index 20f21b9d32..c43755a26a 100644 --- a/message/delete_record.go +++ b/message/delete_record.go @@ -11,10 +11,11 @@ import ( ) // NewDeleteRecordByKeys builds the delete message for the single resource -// identified by keys, a one-row record whose columns are the table's primary -// keys (see schema.NewKeysRecord). +// identified by keys, a one-row record whose columns are the table's identity +// columns - the primary key components when the table declares any, otherwise +// the primary keys (see schema.NewKeysRecord). // -// The where clause is one AND group with an EQ predicate per primary key column, +// The where clause is one AND group with an EQ predicate per identity column, // and the relations cover every descendant table so destinations can cascade the // delete. func NewDeleteRecordByKeys(table *schema.Table, keys arrow.RecordBatch) (*SyncDeleteRecord, error) { @@ -25,18 +26,18 @@ func NewDeleteRecordByKeys(table *schema.Table, keys arrow.RecordBatch) (*SyncDe return nil, fmt.Errorf("keys record for table %q must have exactly one row, got %d", table.Name, keys.NumRows()) } - pks := table.PrimaryKeys() + identity := table.IdentityColumns() fields := keys.Schema().Fields() names := make([]string, len(fields)) for i, field := range fields { names[i] = field.Name } - if !slices.Equal(names, pks) { - return nil, fmt.Errorf("keys record columns %v do not match the primary keys %v of table %q", names, pks, table.Name) + if !slices.Equal(names, identity) { + return nil, fmt.Errorf("keys record columns %v do not match the identity columns %v of table %q", names, identity, table.Name) } - predicates := make(Predicates, len(pks)) - for i, name := range pks { + predicates := make(Predicates, len(identity)) + for i, name := range identity { column := keys.Column(i) sc := arrow.NewSchema([]arrow.Field{fields[i]}, nil) predicates[i] = Predicate{ diff --git a/message/delete_record_test.go b/message/delete_record_test.go index 2cc0b706dc..acbf12fb10 100644 --- a/message/delete_record_test.go +++ b/message/delete_record_test.go @@ -83,6 +83,57 @@ func TestNewDeleteRecordByKeys_NoRelations(t *testing.T) { require.Len(t, msg.WhereClause[0].Predicates, 1) } +// componentsDeleteTestTable is shaped like an AWS table: _cq_id is the only +// primary key and identity lives in the primary key components. +func componentsDeleteTestTable() *schema.Table { + child := &schema.Table{ + Name: "test_components_child", + Columns: schema.ColumnList{{Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}}, + } + table := &schema.Table{ + Name: "test_components", + Columns: schema.ColumnList{ + {Name: "account_id", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}, + {Name: "region", Type: arrow.BinaryTypes.String}, + {Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}, + }, + Relations: schema.Tables{child}, + } + schema.AddCqIDs(table) + return table.Copy(nil) +} + +func TestNewDeleteRecordByKeys_PrimaryKeyComponents(t *testing.T) { + table := componentsDeleteTestTable() + require.Equal(t, []string{schema.CqIDColumn.Name}, table.PrimaryKeys()) + + keys, err := schema.NewKeysRecord(table, map[string]any{ + "account_id": "123456789012", + "arn": "arn:aws:ec2:i-123", + }) + require.NoError(t, err) + + msg, err := NewDeleteRecordByKeys(table, keys) + require.NoError(t, err) + require.Equal(t, "test_components", msg.TableName) + + group := msg.WhereClause[0] + require.Equal(t, "AND", group.GroupingType) + require.Len(t, group.Predicates, 2, "predicates must be on the components, not on _cq_id") + + require.Equal(t, "EQ", group.Predicates[0].Operator) + require.Equal(t, "account_id", group.Predicates[0].Column) + require.Equal(t, "123456789012", group.Predicates[0].Record.Column(0).ValueStr(0)) + + require.Equal(t, "EQ", group.Predicates[1].Operator) + require.Equal(t, "arn", group.Predicates[1].Column) + require.Equal(t, "arn:aws:ec2:i-123", group.Predicates[1].Record.Column(0).ValueStr(0)) + + require.Equal(t, TableRelations{ + {TableName: "test_components_child", ParentTable: "test_components"}, + }, msg.TableRelations) +} + func TestNewDeleteRecordByKeys_ColumnMismatch(t *testing.T) { table := deleteRecordTestTable() other := &schema.Table{ @@ -94,6 +145,7 @@ func TestNewDeleteRecordByKeys_ColumnMismatch(t *testing.T) { _, err = NewDeleteRecordByKeys(table, keys) require.ErrorContains(t, err, "test_parent") + require.ErrorContains(t, err, "identity columns") } func TestNewDeleteRecordByKeys_TooManyRows(t *testing.T) { diff --git a/plugin/plugin_source.go b/plugin/plugin_source.go index b56f882efc..2c2f38632e 100644 --- a/plugin/plugin_source.go +++ b/plugin/plugin_source.go @@ -62,7 +62,9 @@ func (o Op) String() string { type Change struct { // Table is the name of the table the changed resource belongs to. Table string - // Keys is a one-row record whose columns are the table's primary key columns. + // Keys is a one-row record whose columns are the table's identity columns: + // its primary key components when it declares any, otherwise its primary + // keys. Build it with schema.NewKeysRecord. Keys arrow.RecordBatch Op Op // EventID identifies this change in the source's event stream. It is echoed @@ -99,7 +101,9 @@ type Ready struct { // RefreshResource identifies one resource to re-fetch during a refresh sync. type RefreshResource struct { Table string - // Keys is a one-row record whose columns are the table's primary key columns. + // Keys is a one-row record whose columns are the table's identity columns: + // its primary key components when it declares any, otherwise its primary + // keys. Build it with schema.NewKeysRecord. Keys arrow.RecordBatch Op Op } diff --git a/scheduler/refresh.go b/scheduler/refresh.go index 7cd8a0412a..2dfb35768e 100644 --- a/scheduler/refresh.go +++ b/scheduler/refresh.go @@ -20,11 +20,13 @@ import ( // the source. Refresh turns it into a delete message. var ErrNotFound = errors.New("resource not found") -// Refresher re-fetches single resources by their primary keys. It is implemented -// by source plugins that support event-based syncing. +// Refresher re-fetches single resources by their identity columns. It is +// implemented by source plugins that support event-based syncing. type Refresher interface { // Refresh returns the client scoped to the resource and the resource's current - // items, or ErrNotFound if it no longer exists. + // items, or ErrNotFound if it no longer exists. keys is a one-row record whose + // columns are the table's identity columns: its primary key components when it + // declares any, otherwise its primary keys. Refresh(ctx context.Context, table *schema.Table, keys arrow.RecordBatch) (schema.ClientMeta, []any, error) } @@ -157,6 +159,8 @@ func (s *Scheduler) refreshResource(ctx context.Context, tables schema.Tables, r return nil } +// sendDeleteRecord emits the delete for one resource. NewDeleteRecordByKeys is +// what validates that the keys record matches the table's identity columns. func sendDeleteRecord(ctx context.Context, table *schema.Table, keys arrow.RecordBatch, res chan<- message.SyncMessage) error { msg, err := message.NewDeleteRecordByKeys(table, keys) if err != nil { diff --git a/scheduler/refresh_test.go b/scheduler/refresh_test.go index 3e36509f37..7e67c506d9 100644 --- a/scheduler/refresh_test.go +++ b/scheduler/refresh_test.go @@ -194,6 +194,84 @@ func TestRefresh_OpDeleteSkipsRefresh(t *testing.T) { require.IsType(t, &message.SyncDeleteRecord{}, msgs[0]) } +// componentsRefreshTable is shaped like an AWS table: _cq_id is the only primary +// key and identity lives in the primary key components. +func componentsRefreshTable() schema.Tables { + table := &schema.Table{ + Name: "test_components", + Resolver: func(_ context.Context, _ schema.ClientMeta, _ *schema.Resource, res chan<- any) error { + res <- map[string]any{"arn": "arn:aws:ec2:i-123", "name": "hello"} + return nil + }, + Columns: schema.ColumnList{ + {Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true, Resolver: schema.PathResolver("arn")}, + {Name: "name", Type: arrow.BinaryTypes.String, Resolver: schema.PathResolver("name")}, + }, + } + schema.AddCqIDs(table) + return schema.Tables{table.Copy(nil)} +} + +func TestRefresh_OpDeleteOnPrimaryKeyComponentTable(t *testing.T) { + tables := componentsRefreshTable() + table := tables.Get("test_components") + require.Equal(t, []string{schema.CqIDColumn.Name}, table.PrimaryKeys()) + + keys, err := schema.NewKeysRecord(table, map[string]any{"arn": "arn:aws:ec2:i-123"}) + require.NoError(t, err) + + r := &fakeRefresher{} + msgs, err := runRefresh(t, tables, r, []plugin.RefreshResource{ + {Table: "test_components", Keys: keys, Op: plugin.OpDelete}, + }) + require.NoError(t, err) + require.Empty(t, r.refreshCalls(), "OpDelete must not call Refresh") + require.Len(t, msgs, 1) + + del, ok := msgs[0].(*message.SyncDeleteRecord) + require.True(t, ok, "expected a delete record, got %T", msgs[0]) + require.Equal(t, "test_components", del.TableName) + require.Len(t, del.WhereClause[0].Predicates, 1) + require.Equal(t, "arn", del.WhereClause[0].Predicates[0].Column) + require.Equal(t, "arn:aws:ec2:i-123", del.WhereClause[0].Predicates[0].Record.Column(0).ValueStr(0)) +} + +func TestRefresh_NotFoundOnPrimaryKeyComponentTable(t *testing.T) { + tables := componentsRefreshTable() + table := tables.Get("test_components") + + keys, err := schema.NewKeysRecord(table, map[string]any{"arn": "arn:aws:ec2:i-gone"}) + require.NoError(t, err) + + r := &fakeRefresher{errs: map[string]error{ + "test_components:arn=arn:aws:ec2:i-gone": ErrNotFound, + }} + msgs, err := runRefresh(t, tables, r, []plugin.RefreshResource{ + {Table: "test_components", Keys: keys, Op: plugin.OpUpsert}, + }) + require.NoError(t, err) + require.Len(t, msgs, 1) + require.IsType(t, &message.SyncDeleteRecord{}, msgs[0]) +} + +func TestRefresh_UpsertOnPrimaryKeyComponentTable(t *testing.T) { + tables := componentsRefreshTable() + table := tables.Get("test_components") + + keys, err := schema.NewKeysRecord(table, map[string]any{"arn": "arn:aws:ec2:i-123"}) + require.NoError(t, err) + + r := &fakeRefresher{items: map[string][]any{ + "test_components:arn=arn:aws:ec2:i-123": {map[string]any{"arn": "arn:aws:ec2:i-123", "name": "hello"}}, + }} + msgs, err := runRefresh(t, tables, r, []plugin.RefreshResource{ + {Table: "test_components", Keys: keys, Op: plugin.OpUpsert}, + }, WithSyncDeterministicCQID(true)) + require.NoError(t, err) + require.EqualValues(t, 1, msgs.InsertItems()) + require.True(t, msgs.GetInserts().Exists("test_components")) +} + func TestRefresh_OneFailureDoesNotStopTheOthers(t *testing.T) { tables := refreshTestTables() parent := tables.Get("test_refresh_parent") diff --git a/schema/keys.go b/schema/keys.go index f9f9341add..43e42f654e 100644 --- a/schema/keys.go +++ b/schema/keys.go @@ -11,40 +11,45 @@ import ( ) // NewKeysRecord builds the one-row record that identifies a single resource of -// the given table. Its schema is the table's primary key columns, in -// table.PrimaryKeys() order, so that two records for the same resource are +// the given table. Its schema is the table's identity columns - the primary key +// components when the table declares any, otherwise the primary keys - in +// Table.IdentityColumns() order, so that two records for the same resource are // always byte-identical regardless of the iteration order of values. // -// It is an error for values to omit a primary key column or to carry any column -// that is not one. +// It is an error for values to omit an identity column or to carry any column +// that is not one. In particular a table whose only primary key is _cq_id is +// keyed on its components, and passing _cq_id is rejected. func NewKeysRecord(table *Table, values map[string]any) (arrow.RecordBatch, error) { - pks := table.PrimaryKeys() - if len(pks) == 0 { - return nil, fmt.Errorf("table %q has no primary keys", table.Name) + identity := table.IdentityColumns() + if len(identity) == 0 { + return nil, fmt.Errorf("table %q has no identity columns", table.Name) + } + wanted := make(map[string]struct{}, len(identity)) + for _, name := range identity { + wanted[name] = struct{}{} } for name := range values { - col := table.Column(name) - switch { - case col == nil: + if table.Column(name) == nil { return nil, fmt.Errorf("column %q does not exist on table %q", name, table.Name) - case !col.PrimaryKey: - return nil, fmt.Errorf("column %q is not a primary key of table %q", name, table.Name) + } + if _, ok := wanted[name]; !ok { + return nil, fmt.Errorf("column %q is not an identity column of table %q (expected %v)", name, table.Name, identity) } } - fields := make([]arrow.Field, len(pks)) - scalars := make(scalar.Vector, len(pks)) - for i, name := range pks { + fields := make([]arrow.Field, len(identity)) + scalars := make(scalar.Vector, len(identity)) + for i, name := range identity { value, ok := values[name] if !ok { - return nil, fmt.Errorf("missing primary key %q for table %q", name, table.Name) + return nil, fmt.Errorf("missing identity column %q for table %q", name, table.Name) } col := table.Column(name) fields[i] = arrow.Field{Name: col.Name, Type: col.Type, Nullable: true} s := scalar.NewScalar(col.Type) if err := s.Set(value); err != nil { - return nil, fmt.Errorf("failed to set primary key %q for table %q: %w", name, table.Name, err) + return nil, fmt.Errorf("failed to set identity column %q for table %q: %w", name, table.Name, err) } scalars[i] = s } diff --git a/schema/keys_test.go b/schema/keys_test.go index 2dcefe6e9b..617401922c 100644 --- a/schema/keys_test.go +++ b/schema/keys_test.go @@ -79,13 +79,77 @@ func TestNewKeysRecord_UnknownColumn(t *testing.T) { require.ErrorContains(t, err, "nonexistent") } -func TestNewKeysRecord_NoPrimaryKeys(t *testing.T) { +func TestNewKeysRecord_NoIdentityColumns(t *testing.T) { table := &Table{ Name: "test_table", Columns: ColumnList{{Name: "col", Type: arrow.BinaryTypes.String}}, } _, err := NewKeysRecord(table, map[string]any{}) - require.ErrorContains(t, err, "no primary keys") + require.ErrorContains(t, err, "no identity columns") +} + +// componentsTestTable is shaped like an AWS table: _cq_id is the only primary +// key and resource identity lives in the primary key components. +func componentsTestTable() *Table { + table := &Table{ + Name: "test_components", + Columns: ColumnList{ + {Name: "account_id", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}, + {Name: "region", Type: arrow.BinaryTypes.String}, + {Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}, + }, + } + AddCqIDs(table) + return table +} + +func TestIdentityColumns(t *testing.T) { + // Components win when the table declares any. + table := componentsTestTable() + require.Equal(t, []string{CqIDColumn.Name}, table.PrimaryKeys()) + require.Equal(t, []string{"account_id", "arn"}, table.IdentityColumns()) + + // Otherwise the primary keys are the identity. + require.Equal(t, []string{"account_id", "arn"}, keysTestTable().PrimaryKeys()) + require.Equal(t, []string{"account_id", "arn"}, keysTestTable().IdentityColumns()) + + // Neither: no identity at all. + require.Empty(t, (&Table{Name: "t", Columns: ColumnList{{Name: "c", Type: arrow.BinaryTypes.String}}}).IdentityColumns()) +} + +func TestNewKeysRecord_PrimaryKeyComponents(t *testing.T) { + table := componentsTestTable() + + rec, err := NewKeysRecord(table, map[string]any{ + "arn": "arn:aws:ec2:i-123", + "account_id": "123456789012", + }) + require.NoError(t, err) + require.EqualValues(t, 1, rec.NumRows()) + require.EqualValues(t, 2, rec.NumCols()) + require.Equal(t, []string{"account_id", "arn"}, []string{rec.Schema().Field(0).Name, rec.Schema().Field(1).Name}) + require.Equal(t, "123456789012", rec.Column(0).ValueStr(0)) + require.Equal(t, "arn:aws:ec2:i-123", rec.Column(1).ValueStr(0)) + require.Equal(t, "account_id=123456789012,arn=arn:aws:ec2:i-123", KeysString(rec)) +} + +func TestNewKeysRecord_ComponentTableRejectsCqID(t *testing.T) { + table := componentsTestTable() + + // _cq_id is the table's only primary key, but it is not an identity column. + _, err := NewKeysRecord(table, map[string]any{ + "account_id": "123456789012", + "arn": "arn:aws:ec2:i-123", + CqIDColumn.Name: "5c3b1d9e-0000-0000-0000-000000000000", + }) + require.ErrorContains(t, err, CqIDColumn.Name) + require.ErrorContains(t, err, "not an identity column") +} + +func TestNewKeysRecord_ComponentTableMissingComponent(t *testing.T) { + _, err := NewKeysRecord(componentsTestTable(), map[string]any{"account_id": "123456789012"}) + require.ErrorContains(t, err, "missing identity column") + require.ErrorContains(t, err, "arn") } func TestKeysString(t *testing.T) { diff --git a/schema/table.go b/schema/table.go index 48712ac35b..15e9f0bbd0 100644 --- a/schema/table.go +++ b/schema/table.go @@ -742,6 +742,21 @@ func (t *Table) PrimaryKeyComponents() []string { return primaryKeyComponents } +// IdentityColumns returns the columns that identify a single resource of this +// table: the primary key components when the table declares any, otherwise the +// primary keys. +// +// Tables that keep _cq_id as their only primary key carry resource identity in +// the components instead, which is also what Resource.CalculateCQID hashes to +// derive a deterministic _cq_id. Anything that has to name one resource - a keys +// record, a delete predicate - uses this set rather than the primary keys. +func (t *Table) IdentityColumns() []string { + if components := t.PrimaryKeyComponents(); len(components) > 0 { + return components + } + return t.PrimaryKeys() +} + func (t *Table) TableNames() []string { //nolint:prealloc ret := []string{t.Name} From d187589475303e5dcf0419b8366fa067cd5c1358 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Fri, 18 Sep 2026 15:15:26 +0300 Subject: [PATCH 12/13] fix(schema,message,scheduler): accept identity-column subsets in key records An event rarely knows a resource's whole identity: aws_iam_policies has identity columns account_id, id, input_hash and arn, while a CloudTrail event carries only account_id and arn. Requiring all of them rejected those tables outright. A keys record may now carry any non-empty subset of the identity columns, still in the table's declaration order, and deletes predicate on exactly the columns present. Columns outside the identity set, and empty records, are still rejected. Co-Authored-By: Claude Fable 5.1 --- message/delete_record.go | 45 ++++++++++++++++------ message/delete_record_test.go | 72 ++++++++++++++++++++++++++++++++++- plugin/plugin_source.go | 16 +++++--- scheduler/refresh.go | 7 ++-- scheduler/refresh_test.go | 69 +++++++++++++++++++++++++++++++++ schema/keys.go | 39 +++++++++++-------- schema/keys_test.go | 69 +++++++++++++++++++++++++++++---- 7 files changed, 273 insertions(+), 44 deletions(-) diff --git a/message/delete_record.go b/message/delete_record.go index c43755a26a..a1f00a5d89 100644 --- a/message/delete_record.go +++ b/message/delete_record.go @@ -2,7 +2,6 @@ package message import ( "fmt" - "slices" "github.com/apache/arrow-go/v18/arrow" "github.com/apache/arrow-go/v18/arrow/array" @@ -10,14 +9,15 @@ import ( "github.com/cloudquery/plugin-sdk/v4/schema" ) -// NewDeleteRecordByKeys builds the delete message for the single resource -// identified by keys, a one-row record whose columns are the table's identity -// columns - the primary key components when the table declares any, otherwise -// the primary keys (see schema.NewKeysRecord). +// NewDeleteRecordByKeys builds the delete message for the resource identified by +// keys, a one-row record whose columns are a non-empty subset of the table's +// identity columns - the primary key components when the table declares any, +// otherwise the primary keys (see schema.NewKeysRecord). // -// The where clause is one AND group with an EQ predicate per identity column, -// and the relations cover every descendant table so destinations can cascade the -// delete. +// The where clause is one AND group with an EQ predicate for exactly the columns +// the record carries, so a record holding part of a resource's identity deletes +// everything matching that part. The relations cover every descendant table so +// destinations can cascade the delete. func NewDeleteRecordByKeys(table *schema.Table, keys arrow.RecordBatch) (*SyncDeleteRecord, error) { if keys == nil { return nil, fmt.Errorf("no keys record for table %q", table.Name) @@ -32,12 +32,17 @@ func NewDeleteRecordByKeys(table *schema.Table, keys arrow.RecordBatch) (*SyncDe for i, field := range fields { names[i] = field.Name } - if !slices.Equal(names, identity) { - return nil, fmt.Errorf("keys record columns %v do not match the identity columns %v of table %q", names, identity, table.Name) + if len(names) == 0 { + return nil, fmt.Errorf("keys record for table %q has no columns, expected a subset of %v", table.Name, identity) + } + // The record must be a subset of the identity columns, in the table's + // declaration order, which is what schema.NewKeysRecord produces. + if !isOrderedSubset(names, identity) { + return nil, fmt.Errorf("keys record columns %v are not a subset of the identity columns %v of table %q", names, identity, table.Name) } - predicates := make(Predicates, len(identity)) - for i, name := range identity { + predicates := make(Predicates, len(names)) + for i, name := range names { column := keys.Column(i) sc := arrow.NewSchema([]arrow.Field{fields[i]}, nil) predicates[i] = Predicate{ @@ -59,6 +64,22 @@ func NewDeleteRecordByKeys(table *schema.Table, keys arrow.RecordBatch) (*SyncDe }, nil } +// isOrderedSubset reports whether every name appears in whole, in the same order +// and without repeats. +func isOrderedSubset(names, whole []string) bool { + i := 0 + for _, name := range names { + for i < len(whole) && whole[i] != name { + i++ + } + if i == len(whole) { + return false + } + i++ + } + return true +} + // descendantRelations lists every table below the given one, each paired with its // immediate parent. func descendantRelations(table *schema.Table) TableRelations { diff --git a/message/delete_record_test.go b/message/delete_record_test.go index acbf12fb10..2684d9dc6a 100644 --- a/message/delete_record_test.go +++ b/message/delete_record_test.go @@ -134,6 +134,48 @@ func TestNewDeleteRecordByKeys_PrimaryKeyComponents(t *testing.T) { }, msg.TableRelations) } +func TestNewDeleteRecordByKeys_IdentityColumnSubset(t *testing.T) { + // Mirrors aws_iam_policies: four identity columns, an event that knows two. + table := (&schema.Table{ + Name: "test_iam_policies", + Columns: schema.ColumnList{ + {Name: "account_id", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}, + {Name: "id", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}, + {Name: "input_hash", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}, + {Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}, + }, + }).Copy(nil) + schema.AddCqIDs(table) + + keys, err := schema.NewKeysRecord(table, map[string]any{ + "account_id": "123456789012", + "arn": "arn:aws:iam::123456789012:policy/demo", + }) + require.NoError(t, err) + + msg, err := NewDeleteRecordByKeys(table, keys) + require.NoError(t, err) + + group := msg.WhereClause[0] + require.Len(t, group.Predicates, 2, "predicates must cover exactly the columns the record carries") + require.Equal(t, "account_id", group.Predicates[0].Column) + require.Equal(t, "123456789012", group.Predicates[0].Record.Column(0).ValueStr(0)) + require.Equal(t, "arn", group.Predicates[1].Column) + require.Equal(t, "arn:aws:iam::123456789012:policy/demo", group.Predicates[1].Record.Column(0).ValueStr(0)) +} + +func TestNewDeleteRecordByKeys_SingleColumnSubset(t *testing.T) { + table := componentsDeleteTestTable() + + keys, err := schema.NewKeysRecord(table, map[string]any{"arn": "arn:aws:ec2:i-123"}) + require.NoError(t, err) + + msg, err := NewDeleteRecordByKeys(table, keys) + require.NoError(t, err) + require.Len(t, msg.WhereClause[0].Predicates, 1) + require.Equal(t, "arn", msg.WhereClause[0].Predicates[0].Column) +} + func TestNewDeleteRecordByKeys_ColumnMismatch(t *testing.T) { table := deleteRecordTestTable() other := &schema.Table{ @@ -145,7 +187,35 @@ func TestNewDeleteRecordByKeys_ColumnMismatch(t *testing.T) { _, err = NewDeleteRecordByKeys(table, keys) require.ErrorContains(t, err, "test_parent") - require.ErrorContains(t, err, "identity columns") + require.ErrorContains(t, err, "not a subset") +} + +func TestNewDeleteRecordByKeys_NoColumns(t *testing.T) { + table := &schema.Table{ + Name: "test_leaf", + Columns: schema.ColumnList{{Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKey: true}}, + } + // A one-row record that carries no columns at all. + empty := array.NewRecordBatch(arrow.NewSchema(nil, nil), nil, 1) + + _, err := NewDeleteRecordByKeys(table, empty) + require.ErrorContains(t, err, "no columns") +} + +func TestNewDeleteRecordByKeys_WrongOrder(t *testing.T) { + table := deleteRecordTestTable() + // Same columns as the identity set, but reversed: not a subset in order. + sc := arrow.NewSchema([]arrow.Field{ + {Name: "id", Type: arrow.PrimitiveTypes.Int64, Nullable: true}, + {Name: "account_id", Type: arrow.BinaryTypes.String, Nullable: true}, + }, nil) + bldr := array.NewRecordBuilder(memory.DefaultAllocator, sc) + defer bldr.Release() + bldr.Field(0).(*array.Int64Builder).Append(42) + bldr.Field(1).(*array.StringBuilder).Append("123456789012") + + _, err := NewDeleteRecordByKeys(table, bldr.NewRecordBatch()) + require.ErrorContains(t, err, "not a subset") } func TestNewDeleteRecordByKeys_TooManyRows(t *testing.T) { diff --git a/plugin/plugin_source.go b/plugin/plugin_source.go index 2c2f38632e..2aec14b97d 100644 --- a/plugin/plugin_source.go +++ b/plugin/plugin_source.go @@ -62,9 +62,11 @@ func (o Op) String() string { type Change struct { // Table is the name of the table the changed resource belongs to. Table string - // Keys is a one-row record whose columns are the table's identity columns: - // its primary key components when it declares any, otherwise its primary - // keys. Build it with schema.NewKeysRecord. + // Keys is a one-row record whose columns are a non-empty subset of the + // table's identity columns: its primary key components when it declares any, + // otherwise its primary keys. An event that knows only part of a resource's + // identity, such as its ARN, supplies just that part. Build it with + // schema.NewKeysRecord. Keys arrow.RecordBatch Op Op // EventID identifies this change in the source's event stream. It is echoed @@ -101,9 +103,11 @@ type Ready struct { // RefreshResource identifies one resource to re-fetch during a refresh sync. type RefreshResource struct { Table string - // Keys is a one-row record whose columns are the table's identity columns: - // its primary key components when it declares any, otherwise its primary - // keys. Build it with schema.NewKeysRecord. + // Keys is a one-row record whose columns are a non-empty subset of the + // table's identity columns: its primary key components when it declares any, + // otherwise its primary keys. An event that knows only part of a resource's + // identity, such as its ARN, supplies just that part. Build it with + // schema.NewKeysRecord. Keys arrow.RecordBatch Op Op } diff --git a/scheduler/refresh.go b/scheduler/refresh.go index 2dfb35768e..892299b7c9 100644 --- a/scheduler/refresh.go +++ b/scheduler/refresh.go @@ -25,8 +25,8 @@ var ErrNotFound = errors.New("resource not found") type Refresher interface { // Refresh returns the client scoped to the resource and the resource's current // items, or ErrNotFound if it no longer exists. keys is a one-row record whose - // columns are the table's identity columns: its primary key components when it - // declares any, otherwise its primary keys. + // columns are a non-empty subset of the table's identity columns: its primary + // key components when it declares any, otherwise its primary keys. Refresh(ctx context.Context, table *schema.Table, keys arrow.RecordBatch) (schema.ClientMeta, []any, error) } @@ -160,7 +160,8 @@ func (s *Scheduler) refreshResource(ctx context.Context, tables schema.Tables, r } // sendDeleteRecord emits the delete for one resource. NewDeleteRecordByKeys is -// what validates that the keys record matches the table's identity columns. +// what validates that the keys record is a subset of the table's identity +// columns, and it predicates on exactly the columns the record carries. func sendDeleteRecord(ctx context.Context, table *schema.Table, keys arrow.RecordBatch, res chan<- message.SyncMessage) error { msg, err := message.NewDeleteRecordByKeys(table, keys) if err != nil { diff --git a/scheduler/refresh_test.go b/scheduler/refresh_test.go index 7e67c506d9..3300268cde 100644 --- a/scheduler/refresh_test.go +++ b/scheduler/refresh_test.go @@ -236,6 +236,75 @@ func TestRefresh_OpDeleteOnPrimaryKeyComponentTable(t *testing.T) { require.Equal(t, "arn:aws:ec2:i-123", del.WhereClause[0].Predicates[0].Record.Column(0).ValueStr(0)) } +// iamPolicyLikeRefreshTable mirrors aws_iam_policies: four identity columns, of +// which an event knows only account_id and arn. +func iamPolicyLikeRefreshTable() schema.Tables { + table := &schema.Table{ + Name: "test_iam_policies", + Resolver: func(context.Context, schema.ClientMeta, *schema.Resource, chan<- any) error { + return errors.New("the table resolver must not run during a refresh") + }, + Columns: schema.ColumnList{ + {Name: "account_id", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true, Resolver: schema.PathResolver("account_id")}, + {Name: "id", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true, Resolver: schema.PathResolver("id")}, + {Name: "input_hash", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true, Resolver: schema.PathResolver("input_hash")}, + {Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true, Resolver: schema.PathResolver("arn")}, + }, + } + schema.AddCqIDs(table) + return schema.Tables{table.Copy(nil)} +} + +func TestRefresh_OpDeleteWithIdentityColumnSubset(t *testing.T) { + tables := iamPolicyLikeRefreshTable() + table := tables.Get("test_iam_policies") + require.Equal(t, []string{"account_id", "id", "input_hash", "arn"}, table.IdentityColumns()) + + // The event knows 2 of the 4 identity columns. + keys, err := schema.NewKeysRecord(table, map[string]any{ + "account_id": "123456789012", + "arn": "arn:aws:iam::123456789012:policy/demo", + }) + require.NoError(t, err) + + r := &fakeRefresher{} + msgs, err := runRefresh(t, tables, r, []plugin.RefreshResource{ + {Table: "test_iam_policies", Keys: keys, Op: plugin.OpDelete}, + }) + require.NoError(t, err) + require.Empty(t, r.refreshCalls(), "OpDelete must not call Refresh") + require.Len(t, msgs, 1) + + del, ok := msgs[0].(*message.SyncDeleteRecord) + require.True(t, ok, "expected a delete record, got %T", msgs[0]) + require.Len(t, del.WhereClause[0].Predicates, 2, "predicates must cover exactly the columns the event supplied") + require.Equal(t, "account_id", del.WhereClause[0].Predicates[0].Column) + require.Equal(t, "arn", del.WhereClause[0].Predicates[1].Column) + require.Equal(t, "arn:aws:iam::123456789012:policy/demo", del.WhereClause[0].Predicates[1].Record.Column(0).ValueStr(0)) +} + +func TestRefresh_NotFoundWithIdentityColumnSubset(t *testing.T) { + tables := iamPolicyLikeRefreshTable() + table := tables.Get("test_iam_policies") + + keys, err := schema.NewKeysRecord(table, map[string]any{"arn": "arn:aws:iam::123456789012:policy/gone"}) + require.NoError(t, err) + + r := &fakeRefresher{errs: map[string]error{ + "test_iam_policies:arn=arn:aws:iam::123456789012:policy/gone": ErrNotFound, + }} + msgs, err := runRefresh(t, tables, r, []plugin.RefreshResource{ + {Table: "test_iam_policies", Keys: keys, Op: plugin.OpUpsert}, + }) + require.NoError(t, err) + require.Len(t, msgs, 1) + + del, ok := msgs[0].(*message.SyncDeleteRecord) + require.True(t, ok, "expected a delete record, got %T", msgs[0]) + require.Len(t, del.WhereClause[0].Predicates, 1) + require.Equal(t, "arn", del.WhereClause[0].Predicates[0].Column) +} + func TestRefresh_NotFoundOnPrimaryKeyComponentTable(t *testing.T) { tables := componentsRefreshTable() table := tables.Get("test_components") diff --git a/schema/keys.go b/schema/keys.go index 43e42f654e..395f78a681 100644 --- a/schema/keys.go +++ b/schema/keys.go @@ -11,47 +11,56 @@ import ( ) // NewKeysRecord builds the one-row record that identifies a single resource of -// the given table. Its schema is the table's identity columns - the primary key -// components when the table declares any, otherwise the primary keys - in -// Table.IdentityColumns() order, so that two records for the same resource are -// always byte-identical regardless of the iteration order of values. +// the given table. Its columns are a non-empty subset of the table's identity +// columns - the primary key components when the table declares any, otherwise +// the primary keys - always in Table.IdentityColumns() order, so that two +// records naming the same columns of the same resource are byte-identical +// regardless of the iteration order of values. // -// It is an error for values to omit an identity column or to carry any column -// that is not one. In particular a table whose only primary key is _cq_id is -// keyed on its components, and passing _cq_id is rejected. +// A subset is allowed because an event often knows only part of a resource's +// identity: a CloudTrail event carries the ARN, while the table's components may +// also include derived columns such as an input hash. Whatever is supplied has +// to identify the resource well enough for the caller's purpose; this function +// only enforces that it is non-empty and that every column is an identity +// column. In particular a table whose only primary key is _cq_id is keyed on its +// components, and passing _cq_id is rejected. func NewKeysRecord(table *Table, values map[string]any) (arrow.RecordBatch, error) { identity := table.IdentityColumns() if len(identity) == 0 { return nil, fmt.Errorf("table %q has no identity columns", table.Name) } + if len(values) == 0 { + return nil, fmt.Errorf("no values given for table %q, expected at least one of %v", table.Name, identity) + } + wanted := make(map[string]struct{}, len(identity)) for _, name := range identity { wanted[name] = struct{}{} } - for name := range values { if table.Column(name) == nil { return nil, fmt.Errorf("column %q does not exist on table %q", name, table.Name) } if _, ok := wanted[name]; !ok { - return nil, fmt.Errorf("column %q is not an identity column of table %q (expected %v)", name, table.Name, identity) + return nil, fmt.Errorf("column %q is not an identity column of table %q (expected a subset of %v)", name, table.Name, identity) } } - fields := make([]arrow.Field, len(identity)) - scalars := make(scalar.Vector, len(identity)) - for i, name := range identity { + // Follow the table's declaration order, skipping what was not supplied. + fields := make([]arrow.Field, 0, len(values)) + scalars := make(scalar.Vector, 0, len(values)) + for _, name := range identity { value, ok := values[name] if !ok { - return nil, fmt.Errorf("missing identity column %q for table %q", name, table.Name) + continue } col := table.Column(name) - fields[i] = arrow.Field{Name: col.Name, Type: col.Type, Nullable: true} + fields = append(fields, arrow.Field{Name: col.Name, Type: col.Type, Nullable: true}) s := scalar.NewScalar(col.Type) if err := s.Set(value); err != nil { return nil, fmt.Errorf("failed to set identity column %q for table %q: %w", name, table.Name, err) } - scalars[i] = s + scalars = append(scalars, s) } bldr := array.NewRecordBuilder(memory.DefaultAllocator, arrow.NewSchema(fields, nil)) diff --git a/schema/keys_test.go b/schema/keys_test.go index 617401922c..70c8a3c7fc 100644 --- a/schema/keys_test.go +++ b/schema/keys_test.go @@ -55,9 +55,19 @@ func TestNewKeysRecord_CompositePKOrder(t *testing.T) { require.Equal(t, "42", rec.Column(1).ValueStr(0)) } -func TestNewKeysRecord_MissingPK(t *testing.T) { - _, err := NewKeysRecord(keysTestTable(), map[string]any{"account_id": "123456789012"}) - require.ErrorContains(t, err, "arn") +func TestNewKeysRecord_SubsetOfPKs(t *testing.T) { + // A subset is fine: an event that knows only one of the keys still names a + // resource well enough to delete by. + rec, err := NewKeysRecord(keysTestTable(), map[string]any{"account_id": "123456789012"}) + require.NoError(t, err) + require.EqualValues(t, 1, rec.NumCols()) + require.Equal(t, "account_id", rec.Schema().Field(0).Name) + require.Equal(t, "account_id=123456789012", KeysString(rec)) +} + +func TestNewKeysRecord_EmptyValues(t *testing.T) { + _, err := NewKeysRecord(keysTestTable(), map[string]any{}) + require.ErrorContains(t, err, "no values given") require.ErrorContains(t, err, "test_table") } @@ -146,10 +156,55 @@ func TestNewKeysRecord_ComponentTableRejectsCqID(t *testing.T) { require.ErrorContains(t, err, "not an identity column") } -func TestNewKeysRecord_ComponentTableMissingComponent(t *testing.T) { - _, err := NewKeysRecord(componentsTestTable(), map[string]any{"account_id": "123456789012"}) - require.ErrorContains(t, err, "missing identity column") - require.ErrorContains(t, err, "arn") +// iamPolicyLikeTable mirrors aws_iam_policies: four identity columns, of which a +// CloudTrail event knows only account_id and arn. +func iamPolicyLikeTable() *Table { + table := &Table{ + Name: "test_iam_policies", + Columns: ColumnList{ + {Name: "account_id", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}, + {Name: "id", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}, + {Name: "input_hash", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}, + {Name: "arn", Type: arrow.BinaryTypes.String, PrimaryKeyComponent: true}, + {Name: "description", Type: arrow.BinaryTypes.String}, + }, + } + AddCqIDs(table) + return table +} + +func TestNewKeysRecord_SubsetOfIdentityColumns(t *testing.T) { + table := iamPolicyLikeTable() + require.Equal(t, []string{"account_id", "id", "input_hash", "arn"}, table.IdentityColumns()) + + // The event knows 2 of the 4 identity columns. + rec, err := NewKeysRecord(table, map[string]any{ + "arn": "arn:aws:iam::123456789012:policy/demo", + "account_id": "123456789012", + }) + require.NoError(t, err) + require.EqualValues(t, 1, rec.NumRows()) + require.EqualValues(t, 2, rec.NumCols()) + + // Declaration order, not map order: account_id is declared before arn. + require.Equal(t, []string{"account_id", "arn"}, []string{rec.Schema().Field(0).Name, rec.Schema().Field(1).Name}) + require.Equal(t, "account_id=123456789012,arn=arn:aws:iam::123456789012:policy/demo", KeysString(rec)) +} + +func TestNewKeysRecord_SubsetStillRejectsNonIdentityColumn(t *testing.T) { + _, err := NewKeysRecord(iamPolicyLikeTable(), map[string]any{ + "arn": "arn:aws:iam::123456789012:policy/demo", + "description": "not an identity column", + }) + require.ErrorContains(t, err, "description") + require.ErrorContains(t, err, "not an identity column") +} + +func TestNewKeysRecord_ComponentTableSubset(t *testing.T) { + rec, err := NewKeysRecord(componentsTestTable(), map[string]any{"arn": "arn:aws:ec2:i-123"}) + require.NoError(t, err) + require.EqualValues(t, 1, rec.NumCols()) + require.Equal(t, "arn=arn:aws:ec2:i-123", KeysString(rec)) } func TestKeysString(t *testing.T) { From fb0bd4143600574f74d049fa9e250a864dff8d65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muraru=20=C8=98tefan?= Date: Thu, 26 Nov 2026 11:05:50 +0200 Subject: [PATCH 13/13] fix(scheduler): keep a failed refresh of one resource from failing the call --- scheduler/refresh.go | 15 +++++++--- scheduler/refresh_test.go | 63 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 73 insertions(+), 5 deletions(-) diff --git a/scheduler/refresh.go b/scheduler/refresh.go index 892299b7c9..46b8bb4749 100644 --- a/scheduler/refresh.go +++ b/scheduler/refresh.go @@ -37,9 +37,11 @@ type Refresher interface { // Unlike Sync it emits no migrate messages and never multiplexes: the caller // already knows which table and which client each resource belongs to. // -// A resource that fails does not stop the others. Every failure is reported as a -// SyncError message and all of them are returned joined once every resource has -// been processed. +// A resource that cannot be fetched or resolved does not stop the others and does +// not fail the call: the failure is logged and reported as a SyncError message. +// Only systemic failures are returned, joined, once every resource has been +// processed: a cancelled context, an unknown table, an exceeded max depth, a +// Refresher that returns no client, or a failure to emit a message. func (s *Scheduler) Refresh(ctx context.Context, tables schema.Tables, r Refresher, resources []plugin.RefreshResource, res chan<- message.SyncMessage, opts ...SyncOption) error { if len(resources) == 0 { return nil @@ -110,12 +112,17 @@ func (s *Scheduler) refreshResource(ctx context.Context, tables schema.Tables, r case errors.Is(err, ErrNotFound): return sendDeleteRecord(ctx, table, resource.Keys, res) case err != nil: + if ctxErr := context.Cause(ctx); ctxErr != nil { + return fmt.Errorf("failed to refresh resource %s of table %q: %w", schema.KeysString(resource.Keys), table.Name, ctxErr) + } err = fmt.Errorf("failed to refresh resource %s of table %q: %w", schema.KeysString(resource.Keys), table.Name, err) + s.logger.Error().Err(err).Str("table", table.Name).Str("keys", schema.KeysString(resource.Keys)).Msg("refresh failed, skipping resource") select { case res <- &message.SyncError{TableName: table.Name, Error: err.Error()}: + return nil case <-ctx.Done(): + return context.Cause(ctx) } - return err } if len(items) == 0 { diff --git a/scheduler/refresh_test.go b/scheduler/refresh_test.go index 3300268cde..9dd054a599 100644 --- a/scheduler/refresh_test.go +++ b/scheduler/refresh_test.go @@ -359,7 +359,7 @@ func TestRefresh_OneFailureDoesNotStopTheOthers(t *testing.T) { {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "bad"), Op: plugin.OpUpsert}, {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "ok2"), Op: plugin.OpUpsert}, }) - require.ErrorIs(t, err, boom) + require.NoError(t, err) // Both healthy resources produced their parent row and their relation row. require.EqualValues(t, 4, msgs.InsertItems()) @@ -390,3 +390,64 @@ func TestRefresh_NoResources(t *testing.T) { require.NoError(t, err) require.Empty(t, msgs) } + +type noClientRefresher struct{} + +func (noClientRefresher) Refresh(context.Context, *schema.Table, arrow.RecordBatch) (schema.ClientMeta, []any, error) { + return nil, []any{map[string]any{"id": "abc"}}, nil +} + +func TestRefresh_NoClientIsSystemic(t *testing.T) { + tables := refreshTestTables() + parent := tables.Get("test_refresh_parent") + + _, err := runRefresh(t, tables, noClientRefresher{}, []plugin.RefreshResource{ + {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "abc"), Op: plugin.OpUpsert}, + }) + require.ErrorContains(t, err, "no client") +} + +func TestRefresh_MaxDepthExceeded(t *testing.T) { + tables := refreshTestTables() + parent := tables.Get("test_refresh_parent") + + s := NewScheduler(WithMaxDepth(1)) + res := make(chan message.SyncMessage, 16) + err := s.Refresh(context.Background(), tables, &fakeRefresher{}, []plugin.RefreshResource{ + {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "abc"), Op: plugin.OpUpsert}, + }, res) + require.ErrorContains(t, err, "max depth exceeded") +} + +func TestRefresh_ContextCancelIsSystemic(t *testing.T) { + tables := refreshTestTables() + parent := tables.Get("test_refresh_parent") + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + s := NewScheduler(WithConcurrency(2)) + res := make(chan message.SyncMessage, 16) + err := s.Refresh(ctx, tables, &fakeRefresher{ + errs: map[string]error{"test_refresh_parent:id=abc": context.Canceled}, + }, []plugin.RefreshResource{ + {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "abc"), Op: plugin.OpUpsert}, + }, res) + require.ErrorIs(t, err, context.Canceled) +} + +func TestRefresh_AllResourcesFailing(t *testing.T) { + tables := refreshTestTables() + parent := tables.Get("test_refresh_parent") + + r := &fakeRefresher{errs: map[string]error{ + "test_refresh_parent:id=a": errors.New("denied"), + "test_refresh_parent:id=b": errors.New("denied"), + }} + msgs, err := runRefresh(t, tables, r, []plugin.RefreshResource{ + {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "a"), Op: plugin.OpUpsert}, + {Table: "test_refresh_parent", Keys: refreshKeys(t, parent, "b"), Op: plugin.OpUpsert}, + }) + require.NoError(t, err) + require.EqualValues(t, 0, msgs.InsertItems()) + require.Len(t, msgs, 2) +}