-
Notifications
You must be signed in to change notification settings - Fork 1
/
bind.go
538 lines (492 loc) · 12.2 KB
/
bind.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
package miruken
import (
"errors"
"fmt"
"reflect"
"strings"
"github.com/miruken-go/miruken/internal"
"github.com/miruken-go/miruken/promise"
)
type (
// Binding connects a Callback to a handler.
Binding interface {
Filtered
Key() any
Strict() bool
SkipFilters() bool
Async() bool
Exported() bool
Metadata() []any
LogicalOutputType() reflect.Type
Invoke(
ctx HandleContext,
initArgs ...any,
) ([]any, *promise.Promise[[]any], error)
}
// BindingBase implements common binding contract.
BindingBase struct {
FilteredScope
flags bindingFlags
metadata []any
}
// BindingReducer aggregates Binding results.
BindingReducer func(
binding Binding,
result HandleResult,
) (HandleResult, bool)
// BindingParser is an extension for binding customizations.
BindingParser interface {
parse(
index int,
field *reflect.StructField,
binding any,
) (bound bool, err error)
}
// BindingParserFunc implements a BindingParser using a function.
BindingParserFunc func(
index int,
field *reflect.StructField,
binding any,
) (bound bool, err error)
// Strict Binding's do not expand results.
Strict struct{}
// Optional marks a dependency not required.
Optional struct{}
// SkipFilters skips all non-required filters.
SkipFilters struct{}
// BindingGroup marks bindings that aggregate
// one or more binding metadata.
BindingGroup struct{}
)
// BindingParserFunc
func (b BindingParserFunc) parse(
index int,
field *reflect.StructField,
binding any,
) (bound bool, err error) {
return b(index, field, binding)
}
// BindingGroup
func (BindingGroup) DefinesBindingGroup() {}
// BindingBase
func (b *BindingBase) Strict() bool {
return b.flags&bindingStrict == bindingStrict
}
func (b *BindingBase) SkipFilters() bool {
return b.flags&bindingSkipFilters == bindingSkipFilters
}
func (b *BindingBase) Async() bool {
return b.flags&bindingAsync == bindingAsync
}
func (b *BindingBase) Metadata() []any {
return b.metadata
}
type (
// bindingSpec captures a Binding specification.
bindingFlags uint8
bindingSpec struct {
policies []policyKey
flags bindingFlags
filters []FilterProvider
constraints []Constraint
metadata []any
arg arg
lt reflect.Type
}
// bindingSpecFactory creates bindingSpec's from type metadata.
bindingSpecFactory struct {
cache map[reflect.Type]Policy
parsers []BindingParser
}
// policyKey binds a Policy to a key for lookup.
policyKey struct {
policy Policy
key any
}
)
const (
bindingNone bindingFlags = 0
bindingStrict bindingFlags = 1 << iota
bindingOptional
bindingSkipFilters
bindingAsync
)
// bindingSpec
func (b *bindingSpec) addPolicy(
policy Policy,
field *reflect.StructField,
) error {
pk := policyKey{policy: policy}
if key, ok := field.Tag.Lookup("key"); ok {
for _, pk := range b.policies {
if pk.policy == policy && pk.key == key {
return fmt.Errorf("duplicate key \"%s\"", key)
}
}
pk.key = key
}
b.policies = append(b.policies, pk)
return nil
}
func (b *bindingSpec) addFilterProvider(
provider FilterProvider,
) error {
b.filters = append(b.filters, provider)
// Add any constraints required by the provider.
if constraints, ok := provider.(ConstraintSource); ok {
for _, constraint := range constraints.Constraints() {
if err := b.addConstraint(constraint); err != nil {
return err
}
}
}
return nil
}
func (b *bindingSpec) addConstraint(
constraint Constraint,
) error {
for _, c := range b.constraints {
if merge, ok := c.(interface {
Merge(Constraint) bool
}); ok && merge.Merge(constraint) {
return nil
}
}
b.constraints = append(b.constraints, constraint)
return nil
}
func (b *bindingSpec) setStrict(
index int,
field *reflect.StructField,
strict bool,
) error {
b.flags |= bindingStrict
return nil
}
func (b *bindingSpec) setSkipFilters(
index int,
field *reflect.StructField,
strict bool,
) error {
b.flags |= bindingSkipFilters
return nil
}
func (b *bindingSpec) addMetadata(
metadata any,
) error {
b.metadata = append(b.metadata, metadata)
return nil
}
func (b *bindingSpec) setLogicalOutputType(lt reflect.Type) {
switch lt {
case internal.ErrorType, handleResType:
break
default:
b.lt = lt
}
}
func (b *bindingSpec) complete() error {
provider := ConstraintProvider{b.constraints}
b.filters = append(b.filters, &provider)
return nil
}
// bindingSpecFactory
func (p *bindingSpecFactory) createSpec(
typ reflect.Type,
minArgs int,
) (spec *bindingSpec, err error) {
if typ.Kind() != reflect.Func || typ.NumIn() < minArgs {
return nil, nil
}
specType := typ.In(minArgs - 1)
// Is it a policy spec?
if specType.Kind() == reflect.Ptr {
if at := specType.Elem(); // anonymous struct
at.Name() == "" &&
at.Kind() == reflect.Struct {
spec = &bindingSpec{}
if err := parseSpec(at, spec, p.parsers); err != nil {
return nil, err
}
spec.arg = zeroArg{} // spec is just a placeholder
if len(spec.policies) > 0 {
return spec, nil
}
}
}
if spec == nil {
// Is it a Callback arg?
if specType.Kind() != reflect.Interface && specType.Implements(callbackType) {
spec = &bindingSpec{
arg: CallbackArg{},
policies: []policyKey{{policy: p.policyOf(specType)}},
filters: []FilterProvider{&ConstraintProvider{}},
}
}
}
if spec != nil {
// Discover additional callbacks
for i := minArgs; i < typ.NumIn(); i++ {
argType := typ.In(i)
if argType.Kind() != reflect.Interface && argType.Implements(callbackType) {
addPolicy := true
policy := p.policyOf(argType)
for _, pk := range spec.policies {
if pk.policy == policy && pk.key == nil {
addPolicy = false
break
}
}
if addPolicy {
spec.policies = append(spec.policies, policyKey{policy: policy})
}
}
}
if len(spec.policies) == 0 {
return nil, nil
}
}
return spec, nil
}
func (p *bindingSpecFactory) policyOf(
callbackType reflect.Type,
) Policy {
if p.cache == nil {
p.cache = make(map[reflect.Type]Policy)
} else if policy, ok := p.cache[callbackType]; ok {
return policy
}
policy := reflect.Zero(callbackType).Interface().(Callback).Policy()
p.cache[callbackType] = policy
return policy
}
func (p *bindingSpecFactory) parse(
index int,
field *reflect.StructField,
binding any,
) (bound bool, err error) {
typ := field.Type
if cb := internal.CoerceToPtr(typ, callbackType); cb != nil {
if typ.Kind() == reflect.Interface {
return false, fmt.Errorf("callback cannot be an interface: %v", typ)
}
bound = true
if b, ok := binding.(interface {
addPolicy(Policy, *reflect.StructField) error
}); ok {
policy := p.policyOf(cb)
if inv := b.addPolicy(policy, field); inv != nil {
err = fmt.Errorf("parse: %v at index %v failed: %w", typ, index, inv)
}
}
}
return bound, err
}
func parseSpec(
source reflect.Type,
spec any,
parsers []BindingParser,
) (err error) {
if err = parseStruct(source, spec, parsers); err == nil {
if b, ok := spec.(interface {
complete() error
}); ok {
err = b.complete()
}
}
return
}
func parseStruct(
typ reflect.Type,
binding any,
parsers []BindingParser,
) (err error) {
checkedMetadata := false
var metadataOwner interface {
addMetadata(metadata any) error
}
NextField:
for i := range typ.NumField() {
bound := false
field := typ.Field(i)
fieldType := field.Type
if fieldType == bindingGroupType {
continue
}
if fieldType.Kind() == reflect.Struct && fieldType.Implements(definesBindingGroup) {
if inv := parseStruct(fieldType, binding, parsers); inv != nil {
err = errors.Join(err, inv)
}
continue
}
for _, parser := range parsers {
if b, inv := parser.parse(i, &field, binding); inv != nil {
err = errors.Join(err, inv)
continue NextField
} else if b {
bound = true
break
}
}
if !bound && (metadataOwner != nil || !checkedMetadata) {
if !checkedMetadata {
checkedMetadata = true
metadataOwner, _ = binding.(interface {
addMetadata(metadata any) error
})
}
if metadataOwner != nil {
if inv := addMetadata(field.Type, field.Tag, metadataOwner); inv != nil {
err = errors.Join(err, inv)
}
}
}
}
return err
}
func parseFilters(
index int,
field *reflect.StructField,
binding any,
) (bound bool, err error) {
typ := field.Type
if filter := internal.CoerceToPtr(typ, filterType); filter != nil {
bound = true
if b, ok := binding.(interface {
addFilterProvider(FilterProvider) error
}); ok {
spec := filterSpec{filter, false, -1}
if f, ok := field.Tag.Lookup(filterTag); ok {
args := strings.Split(f, ",")
for _, arg := range args {
if arg == requiredArg {
spec.required = true
} else {
if count, _ := fmt.Sscanf(arg, "order=%d", &spec.order); count > 0 {
continue
}
}
}
}
provider := &filterSpecProvider{spec}
if inv := b.addFilterProvider(provider); inv != nil {
err = fmt.Errorf(
"parseFilters: filter spec provider %v at index %v failed: %w",
provider, index, inv)
}
}
} else if fp := internal.CoerceToPtr(typ, filterProviderType); fp != nil {
bound = true
if b, ok := binding.(interface {
addFilterProvider(FilterProvider) error
}); ok {
if provider, inv := internal.NewWithTag(fp, field.Tag); inv != nil {
err = fmt.Errorf(
"parseFilters: new filter provider at index %v failed: %w",
index, inv)
} else if inv := b.addFilterProvider(provider.(FilterProvider)); inv != nil {
err = fmt.Errorf(
"parseFilters: filter provider %v at index %v failed: %w",
provider, index, inv)
}
}
}
return
}
func parseConstraints(
index int,
field *reflect.StructField,
binding any,
) (bound bool, err error) {
typ := field.Type
if ct := internal.CoerceToPtr(typ, constraintType); ct != nil {
bound = true
if b, ok := binding.(interface {
addConstraint(Constraint) error
}); ok {
if constraint, inv := internal.NewWithTag(ct, field.Tag); inv != nil {
err = fmt.Errorf(
"parseConstraints: new key at index %v failed: %w", index, inv)
} else if inv := b.addConstraint(constraint.(Constraint)); inv != nil {
err = fmt.Errorf(
"parseConstraints: key %v at index %v failed: %w", constraint, index, inv)
}
}
}
return
}
func parseOptions(
index int,
field *reflect.StructField,
binding any,
) (bound bool, err error) {
switch field.Type {
case strictType:
bound = true
if b, ok := binding.(interface {
setStrict(int, *reflect.StructField, bool) error
}); ok {
if inv := b.setStrict(index, field, true); inv != nil {
err = errors.Join(err, fmt.Errorf(
"parseOptions: strict field %v (%v) failed: %w",
field.Name, index, inv))
}
}
case optionalType:
bound = true
if b, ok := binding.(interface {
setOptional(int, *reflect.StructField, bool) error
}); ok {
if inv := b.setOptional(index, field, true); inv != nil {
err = errors.Join(err, fmt.Errorf(
"parseOptions: optional field %v (%v) failed: %w",
field.Name, index, inv))
}
}
case skipFiltersType:
bound = true
if b, ok := binding.(interface {
setSkipFilters(int, *reflect.StructField, bool) error
}); ok {
if inv := b.setSkipFilters(index, field, true); inv != nil {
err = errors.Join(err, fmt.Errorf(
"parseOptions: skipFilters on field %v (%v) failed: %w",
field.Name, index, inv))
}
}
}
return
}
func addMetadata(
typ reflect.Type,
tag reflect.StructTag,
owner interface {
addMetadata(metadata any) error
},
) error {
writeable := typ.Kind() == reflect.Ptr
if !writeable {
typ = reflect.PointerTo(typ)
}
if metadata, err := internal.NewWithTag(typ, tag); metadata != nil && err == nil {
if !writeable {
metadata = reflect.Indirect(reflect.ValueOf(metadata)).Interface()
}
return owner.addMetadata(metadata)
} else {
return err
}
}
const (
filterTag = "filter"
requiredArg = "required"
)
var (
strictType = reflect.TypeFor[Strict]()
optionalType = reflect.TypeFor[Optional]()
skipFiltersType = reflect.TypeFor[SkipFilters]()
bindingGroupType = reflect.TypeFor[BindingGroup]()
definesBindingGroup = reflect.TypeFor[interface{ DefinesBindingGroup() }]()
filterType = reflect.TypeFor[Filter]()
constraintType = reflect.TypeFor[Constraint]()
)