-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathplugin.go
More file actions
272 lines (229 loc) · 7.58 KB
/
plugin.go
File metadata and controls
272 lines (229 loc) · 7.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package plugin
import (
"context"
"errors"
"fmt"
"sync"
"github.com/apache/arrow-go/v18/arrow"
cqapi "github.com/cloudquery/cloudquery-api-go"
"github.com/cloudquery/plugin-sdk/v4/message"
"github.com/cloudquery/plugin-sdk/v4/schema"
"github.com/rs/zerolog"
"github.com/santhosh-tekuri/jsonschema/v6"
)
var ErrNotImplemented = errors.New("not implemented")
type NewClientOptions struct {
NoConnection bool
InvocationID string
PluginMeta Meta
}
type NewClientFunc func(context.Context, zerolog.Logger, []byte, NewClientOptions) (Client, error)
type Client interface {
SourceClient
DestinationClient
TransformerClient
}
type UnimplementedDestination struct {
UnimplementedTransformer
}
func (UnimplementedDestination) Write(context.Context, <-chan message.WriteMessage) error {
return ErrNotImplemented
}
func (UnimplementedDestination) Read(context.Context, *schema.Table, chan<- arrow.RecordBatch) error {
return ErrNotImplemented
}
type UnimplementedSource struct {
UnimplementedTransformer
}
func (UnimplementedSource) Sync(context.Context, SyncOptions, chan<- message.SyncMessage) error {
return ErrNotImplemented
}
func (UnimplementedSource) Tables(context.Context, TableOptions) (schema.Tables, error) {
return nil, ErrNotImplemented
}
type UnimplementedTransformer struct{}
func (UnimplementedTransformer) Transform(context.Context, <-chan arrow.RecordBatch, chan<- arrow.RecordBatch) error {
return ErrNotImplemented
}
func (UnimplementedTransformer) TransformSchema(context.Context, *arrow.Schema) (*arrow.Schema, error) {
return nil, ErrNotImplemented
}
// Plugin is the base structure required to pass to sdk.serve
// We take a declarative approach to API here similar to Cobra
type Plugin struct {
// Name of plugin, e.g. aws, gcp, azure etc
name string
// Kind of plugin, e.g. source, destination
kind Kind
// Team name of author of the plugin, e.g. cloudquery, vercel, github, etc
team string
// Version of the plugin
version string
// targets to build plugin for
targets []BuildTarget
// Called upon init call to validate and init configuration
newClient NewClientFunc
// Logger to call, this logger is passed to the serve.Serve Client, if not defined Serve will create one instead.
logger zerolog.Logger
// mu is a mutex that limits the number of concurrent init/syncs (can only be one at a time)
mu sync.Mutex
// client is the initialized session client
client Client
// spec is the spec the client was initialized with
spec any
// NoInternalColumns if set to true will not add internal columns to tables such as _cq_id and _cq_parent_id
// useful for sources such as PostgreSQL and other databases
internalColumns bool
// schema is the JSONSchema of the plugin spec
schema string
// validator object to validate specs
schemaValidator *jsonschema.Schema
// skips the usage client
skipUsageClient bool
// skips table validation
skipTableValidation bool
// the invocation ID for the current execution
invocationID string
// Method to test connection given a spec
testConnFn ConnectionTester
}
// NewPlugin returns a new CloudQuery Plugin with the given name, version and implementation.
// Depending on the options, it can be a write-only plugin, read-only plugin, or both.
func NewPlugin(name string, version string, newClient NewClientFunc, options ...Option) *Plugin {
p := Plugin{
name: name,
version: version,
internalColumns: true,
newClient: newClient,
targets: DefaultBuildTargets,
testConnFn: UnimplementedTestConnectionFn,
}
for _, opt := range options {
opt(&p)
}
if p.schema != "" {
schemaValidator, err := JSONSchemaValidator(p.schema)
if err != nil {
panic(fmt.Errorf("failed to compile plugin JSONSchema: %w", err))
}
p.schemaValidator = schemaValidator
}
return &p
}
// InvocationID returns the invocation ID for the current execution
func (p *Plugin) InvocationID() string {
return p.invocationID
}
// Name returns the name of this plugin
func (p *Plugin) Name() string {
return p.name
}
// Kind returns the kind of this plugin
func (p *Plugin) Kind() Kind {
return p.kind
}
// Team returns the name of the team that authored this plugin
func (p *Plugin) Team() string {
return p.team
}
// Version returns the version of this plugin
func (p *Plugin) Version() string {
return p.version
}
func (p *Plugin) JSONSchema() string {
return p.schema
}
func (p *Plugin) Meta() Meta {
return Meta{
Team: p.team,
Kind: cqapi.PluginKind(p.kind),
Name: p.name,
SkipUsageClient: p.skipUsageClient,
}
}
func (p *Plugin) PackageAndVersion() string {
return fmt.Sprintf("%s/%s/%s@%s", p.team, p.kind, p.name, p.version)
}
// SetSkipUsageClient sets whether the usage client should be skipped
func (p *Plugin) SetSkipUsageClient(v bool) {
p.skipUsageClient = v
}
// SetSkipTableValidation sets whether table validation should be skipped
func (p *Plugin) SetSkipTableValidation(v bool) {
p.skipTableValidation = v
}
type OnBeforeSender interface {
OnBeforeSend(context.Context, message.SyncMessage) (message.SyncMessage, error)
}
// OnBeforeSend gets called before every message is sent to the destination. A plugin client
// that implements the OnBeforeSender interface will have this method called.
func (p *Plugin) OnBeforeSend(ctx context.Context, msg message.SyncMessage) (message.SyncMessage, error) {
// This method is called once for every message, so it is on the hot path, and we should be careful about its performance.
// However, most recent versions of Go have optimized type assertions and type switches to be very fast, so
// we use them here without expecting a significant impact on performance.
// See: https://stackoverflow.com/questions/28024884/does-a-type-assertion-type-switch-have-bad-performance-is-slow-in-go
if v, ok := p.client.(OnBeforeSender); ok {
return v.OnBeforeSend(ctx, msg)
}
return msg, nil
}
// OnSyncFinisher is an interface that can be implemented by a plugin client to be notified when a sync finishes.
type OnSyncFinisher interface {
OnSyncFinish(context.Context) error
}
// OnSyncFinish gets called after a sync finishes.
func (p *Plugin) OnSyncFinish(ctx context.Context) error {
if v, ok := p.client.(OnSyncFinisher); ok {
return v.OnSyncFinish(ctx)
}
return nil
}
func (p *Plugin) Targets() []BuildTarget {
return p.targets
}
func (p *Plugin) SetLogger(logger zerolog.Logger) {
p.logger = logger
}
func (p *Plugin) Tables(ctx context.Context, options TableOptions) (schema.Tables, error) {
if p.client == nil {
return nil, errors.New("plugin not initialized")
}
tables, err := p.client.Tables(ctx, options)
if err != nil {
return nil, fmt.Errorf("failed to get tables: %w", err)
}
return tables, nil
}
// Init initializes the plugin with the given spec.
func (p *Plugin) Init(ctx context.Context, spec []byte, options NewClientOptions) error {
if !p.mu.TryLock() {
return errors.New("plugin already in use")
}
defer p.mu.Unlock()
var err error
options.PluginMeta = p.Meta()
clientLogger := p.logger
p.invocationID = options.InvocationID
if options.InvocationID != "" {
clientLogger = p.logger.With().Str("invocation_id", p.invocationID).Logger()
}
p.client, err = p.newClient(ctx, clientLogger, spec, options)
if err != nil {
return fmt.Errorf("failed to initialize client: %w", err)
}
if err := p.validate(ctx); err != nil {
return fmt.Errorf("failed to validate tables: %w", err)
}
p.spec = spec
return nil
}
func (p *Plugin) Close(ctx context.Context) error {
if !p.mu.TryLock() {
return errors.New("plugin already in use")
}
defer p.mu.Unlock()
if p.client == nil {
return nil
}
return p.client.Close(ctx)
}