-
Notifications
You must be signed in to change notification settings - Fork 218
Expand file tree
/
Copy pathadapter.go
More file actions
560 lines (471 loc) · 18.8 KB
/
Copy pathadapter.go
File metadata and controls
560 lines (471 loc) · 18.8 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
package dresources
import (
"context"
"errors"
"fmt"
"reflect"
"github.com/databricks/cli/bundle/deployplan"
"github.com/databricks/cli/libs/calladapt"
"github.com/databricks/cli/libs/structs/structpath"
"github.com/databricks/databricks-sdk-go"
)
type (
Changes = deployplan.Changes
ChangeDesc = deployplan.ChangeDesc
PlanEntry = deployplan.PlanEntry
)
// IResource describes core methods for the resource implementation.
// The resources don't actually implement this interface, but implement the same methods with signatures with concrete types.
// The resources need to have all of the methods on IResource that are not marked [Optional].
type IResource interface {
// New returns a new implementation instance for a given resource.
// Note, this is a class method, it will be called with nil receiver.
// The return value must be a pointer to a specific instance of the resource implementation, e.g. *ResourceJob.
// Single instance is reused across all instances, so it must not store any resource-specific state.
New(client *databricks.WorkspaceClient) any
// PrepareState converts resource's config as defined by bundle schema to the concrete type used by create/update and persisted in the state.
// Example: func (*ResourceJob) PrepareState(input *resources.Job) *jobs.JobSettings
PrepareState(input any) any
// [Required if type(remoteState) != type(state)] RemapState adapts remote state to local state type.
// The adapted remote state will then be compared with newState to detect remote drift.
// Adaptation is not necessary (but possible) if types already match.
// Example: func (*ResourceJob) RemapState(jobs *jobs.Job) *jobs.JobSettings
RemapState(input any) any
// DoRead reads and returns remote state from the backend. The return type defines schema for remote field resolution.
// Example: func (r *ResourceJob) DoRead(ctx context.Context, id string) (*jobs.Job, error)
DoRead(ctx context.Context, id string) (remoteState any, e error)
// DoDelete deletes the resource.
// Example: func (r *ResourceJob) DoDelete(ctx context.Context, id string) error
DoDelete(ctx context.Context, id string) error
// [Optional] OverrideChangeDesc can implement custom logic to update a given ChangeDesc; it is run last after built-in classifiers and field triggers.
OverrideChangeDesc(ctx context.Context, path *structpath.PathNode, changedesc *ChangeDesc, remoteState any) error
// DoCreate creates a new resource from the newState. Returns id of the resource and optionally remote state.
// If remote state is available as part of the operation, return it; otherwise return nil.
// Example: func (r *ResourceVolume) DoCreate(ctx context.Context, newState *catalog.CreateVolumeRequestContent) (string, *catalog.VolumeInfo, error)
DoCreate(ctx context.Context, newState any) (id string, remoteState any, e error)
// [Optional] DoUpdate updates the resource. ID must not change as a result of this operation. Returns optionally remote state.
// If remote state is available as part of the operation, return it; otherwise return nil.
// Example: func (r *ResourceSchema) DoUpdate(ctx context.Context, id string, newState *catalog.CreateSchema, entry *PlanEntry) (*catalog.SchemaInfo, error)
DoUpdate(ctx context.Context, id string, newState any, entry *PlanEntry) (remoteState any, e error)
// [Optional] DoUpdateWithID performs an update that may result in resource having a new ID. Returns new id and optionally remote state.
DoUpdateWithID(ctx context.Context, id string, newState any) (newID string, remoteState any, e error)
// [Optional] DoResize resizes the resource. Only supported by clusters
DoResize(ctx context.Context, id string, newState any) error
// [Optional] WaitAfterCreate waits for the resource to become ready after creation. Returns optionally updated remote state.
// TODO: wait status should be persisted in the state.
WaitAfterCreate(ctx context.Context, id string, newState any) (remoteState any, e error)
// [Optional] WaitAfterUpdate waits for the resource to become ready after update. Returns optionally updated remote state.
WaitAfterUpdate(ctx context.Context, id string, newState any) (remoteState any, e error)
// [Optional] KeyedSlices returns a map from path patterns to KeyFunc for comparing slices by key instead of by index.
// Example: func (*ResourcePermissions) KeyedSlices(state *PermissionsState) map[string]any
KeyedSlices() map[string]any
}
// Adapter wraps resource implementation, validates signatures and type consistency across methods
// and provides a unified interface.
type Adapter struct {
// Required:
prepareState *calladapt.BoundCaller
remapState *calladapt.BoundCaller
doRefresh *calladapt.BoundCaller
doDelete *calladapt.BoundCaller
doCreate *calladapt.BoundCaller
// Optional:
doUpdate *calladapt.BoundCaller
doUpdateWithID *calladapt.BoundCaller
waitAfterCreate *calladapt.BoundCaller
waitAfterUpdate *calladapt.BoundCaller
overrideChangeDesc *calladapt.BoundCaller
doResize *calladapt.BoundCaller
resourceConfig *ResourceLifecycleConfig
generatedResourceConfig *ResourceLifecycleConfig
keyedSlices map[string]any
}
func NewAdapter(typedNil any, resourceType string, client *databricks.WorkspaceClient) (*Adapter, error) {
newCall, err := prepareCallRequired(typedNil, "New")
if err != nil {
return nil, err
}
outs, err := newCall.Call(client)
if err != nil {
return nil, err
}
if len(outs) != 1 {
return nil, fmt.Errorf("internal error: New returned %d values, expected 1", len(outs))
}
impl := outs[0]
adapter := &Adapter{
prepareState: nil,
remapState: nil,
doRefresh: nil,
doDelete: nil,
doCreate: nil,
doUpdate: nil,
doUpdateWithID: nil,
doResize: nil,
waitAfterCreate: nil,
waitAfterUpdate: nil,
overrideChangeDesc: nil,
resourceConfig: GetResourceConfig(resourceType),
generatedResourceConfig: GetGeneratedResourceConfig(resourceType),
keyedSlices: nil,
}
err = adapter.initMethods(impl)
if err != nil {
return nil, err
}
err = adapter.validate()
if err != nil {
return nil, err
}
return adapter, nil
}
// loadKeyedSlices validates and calls KeyedSlices method, returning the resulting map.
func loadKeyedSlices(call *calladapt.BoundCaller) (map[string]any, error) {
outs, err := call.Call()
if err != nil {
return nil, fmt.Errorf("failed to call KeyedSlices: %w", err)
}
result := outs[0].(map[string]any)
return result, nil
}
func (a *Adapter) initMethods(resource any) error {
err := calladapt.EnsureNoExtraMethods(resource, reflect.TypeFor[IResource]())
if err != nil {
return err
}
a.prepareState, err = prepareCallRequired(resource, "PrepareState")
if err != nil {
return err
}
// RemapState is optional when remote type already matches state type.
a.remapState, err = calladapt.PrepareCall(resource, reflect.TypeFor[IResource](), "RemapState")
if err != nil {
return err
}
a.doRefresh, err = prepareCallRequired(resource, "DoRead")
if err != nil {
return err
}
a.doDelete, err = prepareCallRequired(resource, "DoDelete")
if err != nil {
return err
}
a.doCreate, err = prepareCallRequired(resource, "DoCreate")
if err != nil {
return err
}
// Optional methods with varying signatures:
a.doUpdate, err = calladapt.PrepareCall(resource, reflect.TypeFor[IResource](), "DoUpdate")
if err != nil {
return err
}
a.doUpdateWithID, err = calladapt.PrepareCall(resource, reflect.TypeFor[IResource](), "DoUpdateWithID")
if err != nil {
return err
}
a.waitAfterCreate, err = calladapt.PrepareCall(resource, reflect.TypeFor[IResource](), "WaitAfterCreate")
if err != nil {
return err
}
a.waitAfterUpdate, err = calladapt.PrepareCall(resource, reflect.TypeFor[IResource](), "WaitAfterUpdate")
if err != nil {
return err
}
a.overrideChangeDesc, err = calladapt.PrepareCall(resource, reflect.TypeFor[IResource](), "OverrideChangeDesc")
if err != nil {
return err
}
a.doResize, err = calladapt.PrepareCall(resource, reflect.TypeFor[IResource](), "DoResize")
if err != nil {
return err
}
keyedSlicesCall, err := calladapt.PrepareCall(resource, reflect.TypeFor[IResource](), "KeyedSlices")
if err != nil {
return err
}
if keyedSlicesCall != nil {
a.keyedSlices, err = loadKeyedSlices(keyedSlicesCall)
if err != nil {
return err
}
}
return nil
}
// validateTypes validates type matches for variadic triples of (name, actual, expected).
func validateTypes(triples ...any) error {
if len(triples)%3 != 0 {
return errors.New("validateTypes requires arguments in triples of (name, actual, expected)")
}
for i := 0; i < len(triples); i += 3 {
name := triples[i].(string)
actual := triples[i+1].(reflect.Type)
expected := triples[i+2].(reflect.Type)
if actual != expected {
return fmt.Errorf("%s type mismatch: expected %v, got %v", name, expected, actual)
}
}
return nil
}
func (a *Adapter) validate() error {
stateType := a.StateType()
err := validatePointerToStruct(stateType, "state type")
if err != nil {
return err
}
remoteType := a.RemoteType()
err = validatePointerToStruct(remoteType, "remote type")
if err != nil {
return err
}
validations := []any{
"PrepareState return", a.prepareState.OutTypes[0], stateType,
"DoCreate newState", a.doCreate.InTypes[1], stateType,
}
// If RemapState is implemented, validate its signature.
// Otherwise require remote type to equal state type so remapping isn't needed.
if a.remapState != nil {
validations = append(validations,
"RemapState input", a.remapState.InTypes[0], remoteType,
"RemapState return", a.remapState.OutTypes[0], stateType,
)
} else if remoteType != stateType {
return fmt.Errorf("RemapState method not found and remote type %v must match state type %v", remoteType, stateType)
}
// Validate DoCreate: must return (string, remoteType, error)
if len(a.doCreate.OutTypes) != 3 {
return fmt.Errorf("DoCreate must return (string, remoteType, error), got %d return values", len(a.doCreate.OutTypes))
}
validations = append(validations, "DoCreate remoteState return", a.doCreate.OutTypes[1], remoteType)
// Validate DoUpdate: must return (remoteType, error) if implemented
if a.doUpdate != nil {
validations = append(validations, "DoUpdate newState", a.doUpdate.InTypes[2], stateType)
if len(a.doUpdate.OutTypes) != 2 {
return fmt.Errorf("DoUpdate must return (remoteType, error), got %d return values", len(a.doUpdate.OutTypes))
}
validations = append(validations, "DoUpdate remoteState return", a.doUpdate.OutTypes[0], remoteType)
}
if a.doResize != nil {
validations = append(validations, "DoResize newState", a.doResize.InTypes[2], stateType)
}
if a.doUpdateWithID != nil {
validations = append(validations, "DoUpdateWithID newState", a.doUpdateWithID.InTypes[2], stateType)
// DoUpdateWithID must return (string, remoteType, error)
if len(a.doUpdateWithID.OutTypes) != 3 {
return fmt.Errorf("DoUpdateWithID must return (string, remoteType, error), got %d return values", len(a.doUpdateWithID.OutTypes))
}
validations = append(validations, "DoUpdateWithID remoteState return", a.doUpdateWithID.OutTypes[1], remoteType)
}
if a.waitAfterCreate != nil {
validations = append(validations, "WaitAfterCreate newState", a.waitAfterCreate.InTypes[2], stateType)
// WaitAfterCreate must return (remoteType, error)
if len(a.waitAfterCreate.OutTypes) != 2 {
return fmt.Errorf("WaitAfterCreate must return (remoteType, error), got %d return values", len(a.waitAfterCreate.OutTypes))
}
validations = append(validations, "WaitAfterCreate remoteState return", a.waitAfterCreate.OutTypes[0], remoteType)
}
if a.waitAfterUpdate != nil {
validations = append(validations, "WaitAfterUpdate newState", a.waitAfterUpdate.InTypes[2], stateType)
// WaitAfterUpdate must return (remoteType, error)
if len(a.waitAfterUpdate.OutTypes) != 2 {
return fmt.Errorf("WaitAfterUpdate must return (remoteType, error), got %d return values", len(a.waitAfterUpdate.OutTypes))
}
validations = append(validations, "WaitAfterUpdate remoteState return", a.waitAfterUpdate.OutTypes[0], remoteType)
}
err = validateTypes(validations...)
if err != nil {
return err
}
// Validate resourceConfig consistency with DoUpdateWithID
if a.overrideChangeDesc == nil {
hasUpdateWithIDTrigger := a.resourceConfig != nil && len(a.resourceConfig.UpdateIDOnChanges) > 0
if hasUpdateWithIDTrigger && a.doUpdateWithID == nil {
return errors.New("resourceConfig has update_id_on_changes but DoUpdateWithID is not implemented")
}
if a.doUpdateWithID != nil && !hasUpdateWithIDTrigger {
return errors.New("DoUpdateWithID is implemented but resourceConfig lacks update_id_on_changes")
}
}
return nil
}
func (a *Adapter) InputConfigType() reflect.Type {
return a.prepareState.InTypes[0]
}
func (a *Adapter) StateType() reflect.Type {
return a.prepareState.OutTypes[0]
}
func (a *Adapter) RemoteType() reflect.Type {
return a.doRefresh.OutTypes[0]
}
func (a *Adapter) ResourceConfig() *ResourceLifecycleConfig {
return a.resourceConfig
}
func (a *Adapter) GeneratedResourceConfig() *ResourceLifecycleConfig {
return a.generatedResourceConfig
}
func (a *Adapter) IsFieldInRecreateOnChanges(path *structpath.PathNode) bool {
for _, p := range a.resourceConfig.RecreateOnChanges {
if path.HasPatternPrefix(p.Field) {
return true
}
}
return false
}
func (a *Adapter) PrepareState(input any) (any, error) {
outs, err := a.prepareState.Call(input)
if err != nil {
return nil, err
}
return outs[0], nil
}
func (a *Adapter) RemapState(remoteState any) (any, error) {
if a.remapState == nil {
return remoteState, nil
}
outs, err := a.remapState.Call(remoteState)
if err != nil {
return nil, err
}
return outs[0], nil
}
func (a *Adapter) DoRead(ctx context.Context, id string) (any, error) {
outs, err := a.doRefresh.Call(ctx, id)
if err != nil {
return nil, err
}
return outs[0], nil
}
func (a *Adapter) DoDelete(ctx context.Context, id string) error {
_, err := a.doDelete.Call(ctx, id)
if err != nil {
return err
}
return nil
}
// normalizeNilPointer converts a nil pointer wrapped in an interface to a nil interface.
// This is needed because reflection can return a typed nil pointer as a non-nil interface.
func normalizeNilPointer(v any) any {
if v == nil {
return nil
}
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Pointer && rv.IsNil() {
return nil
}
return v
}
func (a *Adapter) DoCreate(ctx context.Context, newState any) (string, any, error) {
outs, err := a.doCreate.Call(ctx, newState)
if err != nil {
return "", nil, err
}
id := outs[0].(string)
remoteState := normalizeNilPointer(outs[1])
return id, remoteState, nil
}
// HasDoUpdate returns true if the resource implements DoUpdate method.
func (a *Adapter) HasDoUpdate() bool {
return a.doUpdate != nil
}
// DoUpdate updates the resource with the plan entry computed during plan.
// Returns remote state if available, otherwise nil.
func (a *Adapter) DoUpdate(ctx context.Context, id string, newState any, entry *PlanEntry) (any, error) {
if a.doUpdate == nil {
return nil, errors.New("internal error: DoUpdate not found")
}
outs, err := a.doUpdate.Call(ctx, id, newState, entry)
if err != nil {
return nil, err
}
remoteState := normalizeNilPointer(outs[0])
return remoteState, nil
}
// HasDoUpdateWithID returns true if the resource implements DoUpdateWithID method.
func (a *Adapter) HasDoUpdateWithID() bool {
return a.doUpdateWithID != nil
}
// DoUpdateWithID updates the resource and may change its ID. Returns newID and remoteState if available.
func (a *Adapter) DoUpdateWithID(ctx context.Context, oldID string, newState any) (string, any, error) {
if a.doUpdateWithID == nil {
return "", nil, errors.New("internal error: DoUpdateWithID not found")
}
outs, err := a.doUpdateWithID.Call(ctx, oldID, newState)
if err != nil {
return "", nil, err
}
id := outs[0].(string)
remoteState := normalizeNilPointer(outs[1])
return id, remoteState, nil
}
func (a *Adapter) DoResize(ctx context.Context, id string, newState any) error {
if a.doResize == nil {
return errors.New("internal error: DoResize not found")
}
_, err := a.doResize.Call(ctx, id, newState)
return err
}
// WaitAfterCreate waits for the resource to become ready after creation.
// If the resource doesn't implement this method, this is a no-op.
// Returns the updated remoteState if available, otherwise returns nil
func (a *Adapter) WaitAfterCreate(ctx context.Context, id string, newState any) (any, error) {
if a.waitAfterCreate == nil {
return nil, nil // no-op if not implemented
}
outs, err := a.waitAfterCreate.Call(ctx, id, newState)
if err != nil {
return nil, err
}
remoteState := normalizeNilPointer(outs[0])
return remoteState, nil
}
// WaitAfterUpdate waits for the resource to become ready after update.
// If the resource doesn't implement this method, this is a no-op.
// Returns the updated remoteState if available, otherwise returns nil.
func (a *Adapter) WaitAfterUpdate(ctx context.Context, id string, newState any) (any, error) {
if a.waitAfterUpdate == nil {
return nil, nil // no-op if not implemented
}
outs, err := a.waitAfterUpdate.Call(ctx, id, newState)
if err != nil {
return nil, err
}
remoteState := normalizeNilPointer(outs[0])
return remoteState, nil
}
// HasOverrideChangeDesc returns true if OverrideChangeDesc is defined for this resource impl
func (a *Adapter) HasOverrideChangeDesc() bool {
return a.overrideChangeDesc != nil
}
// OverrideChangeDesc allows custom logic to override change classification.
func (a *Adapter) OverrideChangeDesc(ctx context.Context, path *structpath.PathNode, change *ChangeDesc, remoteState any) error {
_, err := a.overrideChangeDesc.Call(ctx, path, change, remoteState)
return err
}
// KeyedSlices returns a map from path patterns to KeyFunc for comparing slices by key.
// If the resource doesn't implement KeyedSlices, returns nil.
func (a *Adapter) KeyedSlices() map[string]any {
return a.keyedSlices
}
// prepareCallRequired prepares a call and ensures the method is found.
func prepareCallRequired(resource any, methodName string) (*calladapt.BoundCaller, error) {
caller, err := calladapt.PrepareCall(resource, reflect.TypeFor[IResource](), methodName)
if err != nil {
return nil, fmt.Errorf("%s: %w", methodName, err)
}
if caller == nil {
return nil, fmt.Errorf("%s method not found", methodName)
}
return caller, nil
}
// validatePointerToStruct checks if the type is a pointer to a struct.
func validatePointerToStruct(t reflect.Type, context string) error {
if t == nil {
return fmt.Errorf("%s not set", context)
}
if t.Kind() != reflect.Pointer {
return fmt.Errorf("%s must be a pointer, got %s", context, t.Kind())
}
if t.Elem().Kind() != reflect.Struct {
return fmt.Errorf("%s must be a pointer to struct, got pointer to %s", context, t.Elem().Kind())
}
return nil
}