Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions examples/simple_plugin/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand Down
62 changes: 60 additions & 2 deletions examples/simple_plugin/client/spec.go
Original file line number Diff line number Diff line change
@@ -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
}
}
40 changes: 39 additions & 1 deletion examples/simple_plugin/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,42 @@ description: How to configure the simple_plugin example.

# Configuration

This plugin requires no configuration.
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.
202 changes: 198 additions & 4 deletions examples/simple_plugin/plugin/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -12,33 +15,214 @@ 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 {
return &c.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) {
Expand All @@ -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 {
Expand Down
Loading
Loading