/
resource.go
1368 lines (1216 loc) · 39.7 KB
/
resource.go
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package infer
import (
"context"
"errors"
"fmt"
"reflect"
"github.com/hashicorp/go-multierror"
pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/mapper"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
p "github.com/pulumi/pulumi-go-provider"
"github.com/pulumi/pulumi-go-provider/infer/internal/ende"
"github.com/pulumi/pulumi-go-provider/internal"
"github.com/pulumi/pulumi-go-provider/internal/introspect"
t "github.com/pulumi/pulumi-go-provider/middleware"
"github.com/pulumi/pulumi-go-provider/middleware/schema"
)
// A [custom resource](https://www.pulumi.com/docs/concepts/resources/) inferred from code. This is the
// minimum requirement for defining a new custom resource.
//
// This interface should be implemented by the resource controller, with `I` the resource
// inputs and `O` the full set of resource fields. It is recommended that `O` is a
// superset of `I`, but it is not strictly required. The fields of `I` and `O` should
// consist of non-pulumi types i.e. `string` and `int` instead of `pulumi.StringInput` and
// `pulumi.IntOutput`.
//
// The behavior of a CustomResource resource can be extended by implementing any of the
// following interfaces on the resource controller:
//
// - [CustomCheck]
// - [CustomDiff]
// - [CustomUpdate]
// - [CustomRead]
// - [CustomDelete]
// - [CustomStateMigrations]
// - [Annotated]
//
// Example:
//
// type MyResource struct{}
//
// type MyResourceInputs struct {
// MyString string `pulumi:"myString"`
// OptionalInt *int `pulumi:"myInt,optional"`
// }
//
// type MyResourceOutputs struct {
// MyResourceInputs
// Result string `pulumi:"result"`
// }
//
// func (*MyResource) Create(
// ctx context.Context, name string, inputs MyResourceInputs, preview bool,
// ) (string, MyResourceOutputs, error) {
// id := input.MyString + ".id"
// if preview {
// return id, MyResourceOutputs{MyResourceInputs: inputs}, nil
// }
//
// result := input.MyString
// if inputs.OptionalInt != nil {
// result = fmt.Sprintf("%s.%d", result, *inputs.OptionalInt)
// }
//
// return id, MyResourceOutputs{inputs, result}, nil
// }
type CustomResource[I, O any] interface {
// All custom resources must be able to be created.
CustomCreate[I, O]
}
type CustomCreate[I, O any] interface {
Create(ctx context.Context, name string, inputs I, preview bool) (id string, output O, err error)
}
// A resource that understands how to check its inputs.
//
// By default, infer handles checks by ensuring that a inputs de-serialize correctly. This
// is where you can extend that behavior. The returned input is given to subsequent calls
// to `Create` and `Update`.
//
// Example:
// TODO - Maybe a resource that has a regex. We could reject invalid regex before the up
// actually happens.
type CustomCheck[I any] interface {
// Maybe oldInputs can be of type I
Check(ctx context.Context, name string, oldInputs resource.PropertyMap, newInputs resource.PropertyMap) (
I, []p.CheckFailure, error)
}
// A resource that understands how to diff itself given a new set of inputs.
//
// By default, infer handles diffs by structural equality among inputs. If CustomUpdate is
// implemented, changes will result in updates. Otherwise changes will result in replaces.
//
// Example:
// TODO - Indicate replacements for certain changes but not others.
type CustomDiff[I, O any] interface {
// Maybe oldInputs can be of type I
Diff(ctx context.Context, id string, olds O, news I) (p.DiffResponse, error)
}
// A resource that can adapt to new inputs with a delete and replace.
//
// There is no default behavior for CustomUpdate.
//
// Here the old state (as returned by Create or Update) as well as the new inputs are
// passed. Update should return the new state of the resource. If preview is true, then
// the update is part of `pulumi preview` and no changes should be made.
//
// Example:
// TODO
type CustomUpdate[I, O any] interface {
Update(ctx context.Context, id string, olds O, news I, preview bool) (O, error)
}
// A resource that can recover its state from the provider.
//
// If CustomRead is not implemented, it will default to checking that the inputs and state
// fit into I and O respectively. If they do, then the values will be returned as is.
// Otherwise an error will be returned.
//
// Example:
// TODO - Probably something to do with the file system.
type CustomRead[I, O any] interface {
// Read accepts a resource id, and a best guess of the input and output state. It returns
// a normalized version of each, assuming it can be recovered.
Read(ctx context.Context, id string, inputs I, state O) (
canonicalID string, normalizedInputs I, normalizedState O, err error)
}
// A resource that knows how to delete itself.
//
// If a resource does not implement Delete, no code will be run on resource deletion.
type CustomDelete[O any] interface {
// Delete is called before a resource is removed from pulumi state.
Delete(ctx context.Context, id string, props O) error
}
// StateMigrationFunc represents a stateless mapping from an old state shape to a new
// state shape. Each StateMigrationFunc is parameterized by the shape of the type it
// produces, ensuring that all successful migrations end up in a valid state.
//
// To create a StateMigrationFunc, use [StateMigration].
type StateMigrationFunc[New any] interface {
isStateMigrationFunc()
oldShape() reflect.Type
newShape() reflect.Type
migrateFunc() reflect.Value
}
// StateMigration creates a mapping from an old state shape (type Old) to a new state
// shape (type New).
//
// If Old = [resource.PropertyMap], then the migration is always run.
//
// Example:
//
// type MyResource struct{}
//
// type MyInput struct{}
//
// type MyStateV1 struct {
// SomeInt *int `pulumi:"someInt,optional"`
// }
//
// type MyStateV2 struct {
// AString string `pulumi:"aString"`
// AInt *int `pulumi:"aInt,optional"`
// }
//
// func migrateFromV1(ctx context.Context, v1 StateV1) (infer.MigrationResult[MigrateStateV2], error) {
// return infer.MigrationResult[MigrateStateV2]{
// Result: &MigrateStateV2{
// AString: "default-string", // Add a new required field
// AInt: v1.SomeInt, // Rename an existing field
// },
// }, nil
// }
//
// // Associate your migration with the resource it encapsulates.
// func (*MyResource) StateMigrations(context.Context) []infer.StateMigrationFunc[MigrateStateV2] {
// return []infer.StateMigrationFunc[MigrateStateV2]{
// infer.StateMigration(migrateFromV1),
// }
// }
func StateMigration[Old, New any, F func(context.Context, Old) (MigrationResult[New], error)](
f F,
) StateMigrationFunc[New] {
return stateMigrationFunc[Old, New, F]{f}
}
// MigrationResult represents the result of a migration.
type MigrationResult[T any] struct {
// Result is the result of the migration.
//
// If Result is nil, then the migration is considered to have been unnecessary.
//
// If Result is non-nil, then the migration is considered to have completed and
// the new value state value will be *Result.
Result *T
}
type stateMigrationFunc[Old, New any, F func(context.Context, Old) (MigrationResult[New], error)] struct{ f F }
// typeFor returns the [Type] that represents the type argument T.
//
// reflect.TypeFor is included in go1.22.
func typeFor[T any]() reflect.Type {
return reflect.TypeOf((*T)(nil)).Elem()
}
func (stateMigrationFunc[O, N, F]) isStateMigrationFunc() {}
func (stateMigrationFunc[O, N, F]) oldShape() reflect.Type { return typeFor[O]() }
func (stateMigrationFunc[O, N, F]) newShape() reflect.Type { return typeFor[N]() }
func (m stateMigrationFunc[O, N, F]) migrateFunc() reflect.Value { return reflect.ValueOf(m.f) }
type CustomStateMigrations[O any] interface {
// StateMigrations is the list of know migrations.
//
// Each migration should return a valid State object.
//
// The first migration to return a non-nil Result will be used.
StateMigrations(ctx context.Context) []StateMigrationFunc[O]
}
// The methods of Annotator must be called on pointers to fields of their receivers, or on
// their receiver itself.
//
// func (*s Struct) Annotated(a Annotator) {
// a.Describe(&s, "A struct") // Legal
// a.Describe(&s.field1, "A field") // Legal
// a.Describe(s.field2, "A field") // Not legal, since the pointer is missing.
// otherS := &Struct{}
// a.Describe(&otherS.field1, "A field") // Not legal, since describe is not called on its receiver.
// }
type Annotator interface {
// Annotate a struct field with a text description.
Describe(i any, description string)
// Annotate a struct field with a default value. The default value must be a primitive
// type in the pulumi type system.
SetDefault(i any, defaultValue any, env ...string)
// Set the token of the annotated type.
//
// module and name should be valid Pulumi token segments. The package name will be
// inferred from the provider.
//
// For example:
//
// a.SetToken("mymodule", "MyResource")
//
// On a provider created with the name "mypkg" will have the token:
//
// mypkg:mymodule:MyResource
//
SetToken(module, name string)
}
// Annotated is used to describe the fields of an object or a resource. Annotated can be
// implemented by `CustomResource`s, the input and output types for all resources and
// invokes, as well as other structs used the above.
type Annotated interface {
Annotate(Annotator)
}
// An interface to help wire fields together.
type FieldSelector interface {
// Create an input field. The argument to InputField must be a pointer to a field of
// the associated input type I.
//
// For example:
// ```go
// func (r *MyResource) WireDependencies(f infer.FieldSelector, args *MyArgs, state *MyState) {
// f.InputField(&args.Field)
// }
// ```
InputField(any) InputField
// Create an output field. The argument to OutputField must be a pointer to a field of
// the associated output type O.
//
// For example:
// ```go
// func (r *MyResource) WireDependencies(f infer.FieldSelector, args *MyArgs, state *MyState) {
// f.OutputField(&state.Field)
// }
// ```
OutputField(any) OutputField
// Seal the interface.
isFieldSelector()
}
func (*fieldGenerator) isFieldSelector() {}
// A custom resource with the dataflow between its arguments (`I`) and outputs (`O`)
// specified. If a CustomResource implements ExplicitDependencies then WireDependencies
// will be called for each Create and Update call with `args` and `state` holding the
// values they will have for that call.
//
// If ExplicitDependencies is not implemented, it is assumed that all outputs depend on
// all inputs.
type ExplicitDependencies[I, O any] interface {
// WireDependencies specifies the dependencies between inputs and outputs.
WireDependencies(f FieldSelector, args *I, state *O)
}
// A field of the output (state).
type OutputField interface {
// Specify that a state (output) field is always secret, regardless of its dependencies.
AlwaysSecret()
// Specify that a state (output) field is never secret, regardless of its dependencies.
NeverSecret()
// Specify that a state (output) field is always known, regardless of dependencies
// or preview.
AlwaysKnown()
// Specify that a state (output) Field uses data from some args (input) Fields.
DependsOn(dependencies ...InputField)
// Seal the interface.
isOutputField()
}
// A field of the input (args).
type InputField interface {
// Seal the interface.
isInputField()
// Only wire secretness, not computedness.
Secret() InputField
// Only flow computedness, not secretness.
Computed() InputField
}
type fieldGenerator struct {
args, state any
argsMatcher introspect.FieldMatcher
stateMatcher introspect.FieldMatcher
err multierror.Error
fields map[string]*field
}
func (g *fieldGenerator) getField(name string) *field {
f, ok := g.fields[name]
if !ok {
f = new(field)
g.fields[name] = f
}
return f
}
type field struct {
// The set of tags that should always be secret
alwaysSecret bool
// The set of tags that should never be secret
neverSecret bool
// A map from a field to its dependencies.
deps []dependency
// If the output is known, regardless of other factors.
known bool
}
type dependency struct {
name string
kind inputKind
}
// Check if we should apply this dependency to a kind.
func (d dependency) has(kind inputKind) bool {
return d.kind == inputAll || kind == d.kind
}
// MarkMap mutates m to comply with the result of the fieldGenerator, applying
// computedness and secretness as appropriate.
func (g *fieldGenerator) MarkMap(isCreate, isPreview bool) func(oldInputs, inputs, m resource.PropertyMap) {
return func(oldInputs, inputs, m resource.PropertyMap) {
// Flow secretness and computedness
for k, v := range m {
m[k] = markField(g.getField(string(k)), k, v, oldInputs, inputs, isCreate, isPreview)
}
}
}
func markComputed(
field *field, key resource.PropertyKey, prop resource.PropertyValue,
oldInputs, inputs resource.PropertyMap, isCreate bool,
) resource.PropertyValue {
// If the value is already computed or if it is guaranteed to be known, we don't need to do anything
if field.known || ende.IsComputed(prop) {
return prop
}
if input, ok := inputs[key]; ok && !ende.IsComputed(prop) && ende.DeepEquals(input, prop) {
// prop is an output during a create, but the output mirrors an
// input in name and value. We don't make it computed.
return prop
}
// If this is during a create and the value is not explicitly marked as known, we mark it computed.
if isCreate {
return ende.MakeComputed(prop)
}
// If a dependency is computed or has changed, we mark this field as computed.
for _, k := range field.deps {
if !k.has(inputComputed) {
continue
}
k := resource.PropertyKey(k.name)
// Not all resources embed their inputs as outputs. When they don't we are
// unable to perform old-vs-new diffing here.
//
// This may lead to applies running on old information during
// preview. This is possible anyway, if user's dependencies don't
// accurately reflect their logic. This is not a problem for non-preview
// updates.
//
// The solution is to require embedding input structs in output structs
// (or do it for the user), ensuring that we have access to information
// that changed..
oldInput, hasOldInput := oldInputs[k]
if ende.IsComputed(inputs[k]) || (hasOldInput && !ende.DeepEquals(inputs[k], oldInput)) {
return ende.MakeComputed(prop)
}
}
return prop
}
func markSecret(
field *field, key resource.PropertyKey, prop resource.PropertyValue, inputs resource.PropertyMap,
) resource.PropertyValue {
// If we should never return a secret, ensure that the field *is not* marked as
// secret, then return.
if field.neverSecret {
return ende.MakePublic(prop)
}
if ende.IsSecret(prop) {
return prop
}
// If we should always return a secret, ensure that the field *is* marked as secret,
// then return.
if field.alwaysSecret {
return ende.MakeSecret(prop)
}
if input, ok := inputs[key]; ok && ende.DeepEquals(input, prop) {
// prop might depend on a secret value, but the output mirrors a input in
// name and value. We don't make it secret since it will either be public
// in the state as an input, or is already a secret.
return prop
}
// Otherwise secretness is derived from dependencies: any dependency that is
// secret makes the field secret.
for _, k := range field.deps {
if !k.has(inputSecret) {
continue
}
if inputs[resource.PropertyKey(k.name)].ContainsSecrets() {
return ende.MakeSecret(prop)
}
}
return prop
}
func markField(
field *field, key resource.PropertyKey, prop resource.PropertyValue,
oldInputs, inputs resource.PropertyMap, isCreate, isPreview bool,
) resource.PropertyValue {
// Fields can only be computed during preview. They must be known by when the resource is actually created.
if isPreview {
prop = markComputed(field, key, prop, oldInputs, inputs, isCreate)
}
return markSecret(field, key, prop, inputs)
}
func (g *fieldGenerator) InputField(a any) InputField {
if allFields, ok, err := g.argsMatcher.TargetStructFields(a); ok {
if err != nil {
g.err.Errors = append(g.err.Errors, err)
return &errField{}
}
return &inputField{fields: allFields}
}
field, ok, err := g.argsMatcher.GetField(a)
if err != nil {
g.err.Errors = append(g.err.Errors, err)
return &errField{}
}
if ok {
return &inputField{fields: []introspect.FieldTag{field}}
}
// Couldn't find the field on the args, try the state
field, ok, err = g.stateMatcher.GetField(a)
if err == nil && ok {
g.err.Errors = append(g.err.Errors,
fmt.Errorf("internal error: %v (%v) is an output field, not an input field", a, field.Name))
}
g.err.Errors = append(g.err.Errors, fmt.Errorf("internal error: could not find the input field for value %v", a))
return &errField{}
}
func (g *fieldGenerator) OutputField(a any) OutputField {
if allFields, ok, err := g.stateMatcher.TargetStructFields(a); ok {
if err != nil {
g.err.Errors = append(g.err.Errors, err)
return &errField{}
}
return &outputField{g, allFields}
}
field, ok, err := g.stateMatcher.GetField(a)
if err != nil {
g.err.Errors = append(g.err.Errors, err)
return &errField{}
}
if ok {
return &outputField{g, []introspect.FieldTag{field}}
}
// Couldn't find the field on the state, try the args
field, ok, err = g.argsMatcher.GetField(a)
if err == nil && ok {
g.err.Errors = append(g.err.Errors, fmt.Errorf("%v (%v) is an input field, not an output field", a, field.Name))
}
g.err.Errors = append(g.err.Errors, fmt.Errorf("could not find the output field for value %v", a))
return &errField{}
}
func newFieldGenerator(i, o any) *fieldGenerator {
return &fieldGenerator{
args: i, state: o,
argsMatcher: introspect.NewFieldMatcher(i),
stateMatcher: introspect.NewFieldMatcher(o),
err: multierror.Error{
ErrorFormat: func(es []error) string {
return "wiring error: " + multierror.ListFormatFunc(es)
},
},
fields: map[string]*field{},
}
}
// userSetKind is true if the user has set a dependency of a matching kind.
func (g *fieldGenerator) userSetKind(kind inputKind) bool {
for _, f := range g.fields {
for _, dep := range f.deps {
if dep.has(kind) {
return true
}
}
}
return false
}
// ensureDefaultComputed ensures that some computedness flow exists on the provider.
//
// If the user has not specified any flow, then we apply the default flow:
//
// Since we can't see inside the user's code to view data flow, we default to
// assuming that all inputs will be used to effect all outputs.
//
// Consider this example:
//
// Input: { a, b, c }
// Output: { a, b, d }
//
// We would see this computedness flow:
//
// Output | Input
// -------+------
// a | a b c
// b | a b c
// d | a b c
func (g *fieldGenerator) ensureDefaultComputed() {
if g.userSetKind(inputComputed) {
// The user has specified something, so we respect that.
return
}
// The user has not set a flow, so apply our own:
//
// Set every output to depend on each input (for computed only)
g.OutputField(g.state).DependsOn(g.InputField(g.args).Computed())
}
// ensureDefaultSecrets that some secretness flow is explicit.
//
// If the user has not specified any flow, then we apply the default flow:
//
// Outputs that share a name with inputs have the secretness flow from input to
// output.
//
// Consider this example:
//
// Input: { a, b, c }
// Output: { a, b, d }
//
// We would see this secretness flow:
//
// Output | Input
// -------+------
// a | a
// b | b
func (g *fieldGenerator) ensureDefaultSecrets() {
if g.userSetKind(inputSecret) {
// The user has specified something, so we respect that.
return
}
// The user has not set a flow, so apply our own
args, ok, err := g.argsMatcher.TargetStructFields(g.args)
contract.Assertf(ok, "we match by construction")
contract.AssertNoError(err)
state, ok, err := g.stateMatcher.TargetStructFields(g.state)
contract.Assertf(ok, "we match by construction")
contract.AssertNoError(err)
for _, f := range state {
if f.Internal {
continue
}
for _, a := range args {
if f.Name != a.Name {
continue
}
v := g.getField(a.Name)
v.deps = append(v.deps, dependency{
name: a.Name,
kind: inputSecret,
})
// There will only be one field with the name f.Name, we so may
// safely break.
break
}
}
}
// The return value when an error happens. The error is reported when the errField is
// created, so this type only exists so we can return a valid instance of
// InputField/OutputField. The functions on errField do nothing.
type errField struct{}
func (*errField) AlwaysSecret() {}
func (*errField) AlwaysKnown() {}
func (*errField) NeverSecret() {}
func (*errField) DependsOn(...InputField) {}
func (*errField) isInputField() {}
func (*errField) isOutputField() {}
func (*errField) Computed() InputField { return &errField{} }
func (*errField) Secret() InputField { return &errField{} }
type inputField struct {
kind inputKind
fields []introspect.FieldTag
}
type inputKind int
const (
inputAll = 0
inputSecret = iota
inputComputed = iota
)
func (i *inputField) Computed() InputField {
input := new(inputField)
input.kind = inputComputed
// Copy input fields
input.fields = make([]introspect.FieldTag, len(i.fields))
for i, f := range i.fields {
input.fields[i] = f
}
return input
}
func (i *inputField) Secret() InputField {
input := new(inputField)
input.kind = inputSecret
// Copy input fields
input.fields = make([]introspect.FieldTag, len(i.fields))
for i, f := range i.fields {
input.fields[i] = f
}
return input
}
func (*inputField) isInputField() {}
type outputField struct {
g *fieldGenerator
fields []introspect.FieldTag
}
func (f *outputField) set(set func(string, *field)) {
for _, field := range f.fields {
name := field.Name
set(name, f.g.getField(name))
}
}
func (f *outputField) AlwaysSecret() {
f.set(func(name string, field *field) {
field.alwaysSecret = true
if field.neverSecret {
f.g.err.Errors = append(f.g.err.Errors,
fmt.Errorf("marked field %q as both always secret and never secret", name))
}
})
}
func (f *outputField) AlwaysKnown() { f.set(func(_ string, field *field) { field.known = true }) }
func (f *outputField) NeverSecret() {
f.set(func(name string, field *field) {
field.neverSecret = true
if field.alwaysSecret {
f.g.err.Errors = append(f.g.err.Errors,
fmt.Errorf("marked field %q as both always secret and never secret", name))
}
})
}
func typeInput(i InputField) (*inputField, bool) {
switch i := i.(type) {
case *inputField:
return i, true
case *errField:
return nil, false
default:
panic(fmt.Sprintf("Unknown InputField type: %T", i))
}
}
func (f *outputField) DependsOn(deps ...InputField) {
depNames := make([]dependency, 0, len(deps))
for _, d := range deps {
d, ok := typeInput(d)
if !ok {
// The error was already reported, so do nothing
continue
}
for _, field := range d.fields {
depNames = append(depNames, dependency{
name: field.Name,
kind: d.kind,
})
}
}
f.set(func(_ string, f *field) { f.deps = append(f.deps, depNames...) })
}
func (*outputField) isOutputField() {}
// A resource inferred by the Resource function.
//
// This interface cannot be implemented directly. Instead consult the Resource function.
type InferredResource interface {
t.CustomResource
schema.Resource
isInferredResource()
}
// Create a new InferredResource, where `R` is the resource controller, `I` is the
// resources inputs and `O` is the resources outputs.
func Resource[R CustomResource[I, O], I, O any]() InferredResource {
return &derivedResourceController[R, I, O]{}
}
type derivedResourceController[R CustomResource[I, O], I, O any] struct{}
func (*derivedResourceController[R, I, O]) isInferredResource() {}
func (*derivedResourceController[R, I, O]) GetSchema(reg schema.RegisterDerivativeType) (
pschema.ResourceSpec, error) {
if err := registerTypes[I](reg); err != nil {
return pschema.ResourceSpec{}, err
}
if err := registerTypes[O](reg); err != nil {
return pschema.ResourceSpec{}, err
}
r, errs := getResourceSchema[R, I, O](false)
return r, errs.ErrorOrNil()
}
func getToken[R any](transform func(tokens.Type) tokens.Type) (tokens.Type, error) {
var r R
return getTokenOf(reflect.TypeOf(r), transform)
}
func getTokenOf(t reflect.Type, transform func(tokens.Type) tokens.Type) (tokens.Type, error) {
annotator := getAnnotated(t)
if annotator.Token != "" {
return tokens.Type(annotator.Token), nil
}
tk, err := introspect.GetToken("pkg", t)
if transform == nil || err != nil {
return tk, err
}
return transform(tk), nil
}
func (*derivedResourceController[R, I, O]) GetToken() (tokens.Type, error) {
return getToken[R](nil)
}
func (*derivedResourceController[R, I, O]) getInstance() *R {
var r R
return &r
}
func (rc *derivedResourceController[R, I, O]) Check(ctx context.Context, req p.CheckRequest) (p.CheckResponse, error) {
var r R
encoder, i, err := ende.Decode[I](req.News)
if r, ok := ((interface{})(r)).(CustomCheck[I]); ok {
// The user implemented check manually, so call that
i, failures, err := r.Check(ctx, req.Urn.Name(), req.Olds, req.News)
if err != nil {
return p.CheckResponse{}, err
}
inputs, err := encoder.Encode(i)
if err != nil {
return p.CheckResponse{}, err
}
return p.CheckResponse{
Inputs: inputs,
Failures: failures,
}, nil
}
if err == nil {
if err := applyDefaults(&i); err != nil {
return p.CheckResponse{}, fmt.Errorf("unable to apply defaults: %w", err)
}
inputs, err := encoder.Encode(i)
return p.CheckResponse{
Inputs: inputs,
}, err
}
failures, e := checkFailureFromMapError(err)
if e != nil {
return p.CheckResponse{}, e
}
return p.CheckResponse{
Inputs: req.News,
Failures: failures,
}, nil
}
// Ensure that `inputs` can deserialize cleanly into `I`.
func DefaultCheck[I any](inputs resource.PropertyMap) (I, []p.CheckFailure, error) {
_, i, err := ende.Decode[I](inputs)
if err == nil {
return i, nil, nil
}
failures, e := checkFailureFromMapError(err)
return i, failures, e
}
func checkFailureFromMapError(err mapper.MappingError) ([]p.CheckFailure, error) {
if err == nil {
return nil, nil
}
failures := []p.CheckFailure{}
for _, err := range err.Failures() {
switch err := err.(type) {
case mapper.FieldError:
failures = append(failures, p.CheckFailure{
Property: err.Field(),
Reason: err.Reason(),
})
default:
return failures, fmt.Errorf("unknown mapper error: %w", err)
}
}
return failures, nil
}
func (rc *derivedResourceController[R, I, O]) Diff(ctx context.Context, req p.DiffRequest) (p.DiffResponse, error) {
r := rc.getInstance()
_, hasUpdate := ((interface{})(*r)).(CustomUpdate[I, O])
var forceReplace func(string) bool
if hasUpdate {
schema, err := rc.GetSchema(func(tokens.Type, pschema.ComplexTypeSpec) bool { return false })
if err != nil {
return p.DiffResponse{}, err
}
forceReplace = func(s string) bool {
if schema.InputProperties == nil {
return false
}
return schema.InputProperties[s].ReplaceOnChanges
}
} else {
// No update => every change is a replace
forceReplace = func(string) bool { return true }
}
return diff[R, I, O](ctx, req, r, forceReplace)
}
// Compute a diff request.
func diff[R, I, O any](
ctx context.Context, req p.DiffRequest, r *R, forceReplace func(string) bool,
) (p.DiffResponse, error) {
for _, ignoredChange := range req.IgnoreChanges {
req.News[ignoredChange] = req.Olds[ignoredChange]
}
if r, ok := ((interface{})(*r)).(CustomDiff[I, O]); ok {
_, olds, err := hydrateFromState[R, I, O](ctx, req.Olds) // TODO
if err != nil {
return p.DiffResponse{}, err
}
_, news, err := ende.Decode[I](req.News)
if err != nil {
return p.DiffResponse{}, err
}
diff, err := r.Diff(ctx, req.ID, olds, news)
if err != nil {
return p.DiffResponse{}, err
}
return diff, nil
}
inputProps, err := introspect.FindProperties(new(I))
if err != nil {
return p.DiffResponse{}, err
}
// Olds is an Output, but news is an Input. Output should be a superset of Input,
// so we need to filter out fields that are in Output but not Input.
oldInputs := resource.PropertyMap{}
for k := range inputProps {
key := resource.PropertyKey(k)
oldInputs[key] = req.Olds[key]
}
objDiff := oldInputs.Diff(req.News)
pluginDiff := plugin.NewDetailedDiffFromObjectDiff(objDiff, false)
diff := map[string]p.PropertyDiff{}
for k, v := range pluginDiff {
set := func(kind p.DiffKind) {
diff[k] = p.PropertyDiff{
Kind: kind,
InputDiff: v.InputDiff,
}
}
if forceReplace(k) {
// We force replaces if we don't have access to updates
v.Kind = v.Kind.AsReplace()
}
switch v.Kind {
case plugin.DiffAdd:
set(p.Add)
case plugin.DiffAddReplace: