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..6816f9a308 100644 --- a/examples/simple_plugin/plugin/client.go +++ b/examples/simple_plugin/plugin/client.go @@ -3,7 +3,10 @@ package plugin import ( "context" "encoding/json" + "errors" "fmt" + "sync" + "time" "github.com/apache/arrow-go/v18/arrow" "github.com/cloudquery/plugin-sdk/examples/simple_plugin/client" @@ -12,15 +15,34 @@ 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 + + // 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 } func (c *Client) Logger() *zerolog.Logger { @@ -28,17 +50,179 @@ 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, } +} - return c.scheduler.Sync(ctx, schedulerClient, tt, res, scheduler.WithSyncDeterministicCQID(options.DeterministicCQID)) +// 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) +} + +// 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) + } + + eventID, err := stateClient.GetKey(ctx, checkpointKey) + if err != nil { + return plugin.Ready{}, fmt.Errorf("failed to read %s: %w", checkpointKey, err) + } + c.setWatchState(stateClient, 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 checkpoint := c.watchCheckpoint(); pos.Since == nil && checkpoint != "" { + pending = changesAfter(pending, 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 +} + +// 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") + } + 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 +234,18 @@ func (c *Client) Tables(_ context.Context, options plugin.TableOptions) (schema. return tt, nil } -func (*Client) Close(_ context.Context) error { - return 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 + } + 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..8aeb59f6dd --- /dev/null +++ b/examples/simple_plugin/plugin/client_test.go @@ -0,0 +1,247 @@ +package plugin + +import ( + "context" + "strings" + "sync" + "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) + } +} + +// 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) + } +} 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 +} diff --git a/message/delete_record.go b/message/delete_record.go new file mode 100644 index 0000000000..a1f00a5d89 --- /dev/null +++ b/message/delete_record.go @@ -0,0 +1,98 @@ +package message + +import ( + "fmt" + + "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 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 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) + } + if keys.NumRows() != 1 { + return nil, fmt.Errorf("keys record for table %q must have exactly one row, got %d", table.Name, keys.NumRows()) + } + + identity := table.IdentityColumns() + fields := keys.Schema().Fields() + names := make([]string, len(fields)) + for i, field := range fields { + names[i] = field.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(names)) + for i, name := range names { + 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 +} + +// 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 { + 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..2684d9dc6a --- /dev/null +++ b/message/delete_record_test.go @@ -0,0 +1,244 @@ +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) +} + +// 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_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{ + 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") + 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) { + 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) +} diff --git a/plugin/plugin_source.go b/plugin/plugin_source.go index f626244c10..2aec14b97d 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,117 @@ 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 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 + // 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 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 +} + +// 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. It runs + // concurrently with Ack. + Watch(ctx context.Context, pos Position, changes chan<- Change) error + // 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 } type SourceClient interface { @@ -102,3 +215,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 +} diff --git a/scheduler/refresh.go b/scheduler/refresh.go new file mode 100644 index 0000000000..46b8bb4749 --- /dev/null +++ b/scheduler/refresh.go @@ -0,0 +1,183 @@ +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 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. 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. + 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 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 + } + + 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: + 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) + } + } + + 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 +} + +// sendDeleteRecord emits the delete for one resource. NewDeleteRecordByKeys is +// 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 { + 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..9dd054a599 --- /dev/null +++ b/scheduler/refresh_test.go @@ -0,0 +1,453 @@ +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 "