-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathtree.go
More file actions
3689 lines (3229 loc) · 116 KB
/
Copy pathtree.go
File metadata and controls
3689 lines (3229 loc) · 116 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
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
package chasm
import (
"bytes"
"cmp"
"context"
"errors"
"fmt"
"iter"
"maps"
"reflect"
"slices"
"strconv"
"time"
commonpb "go.temporal.io/api/common/v1"
enumspb "go.temporal.io/api/enums/v1"
historypb "go.temporal.io/api/history/v1"
sdkpb "go.temporal.io/api/sdk/v1"
"go.temporal.io/api/serviceerror"
enumsspb "go.temporal.io/server/api/enums/v1"
persistencespb "go.temporal.io/server/api/persistence/v1"
"go.temporal.io/server/common"
"go.temporal.io/server/common/clock"
"go.temporal.io/server/common/definition"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
"go.temporal.io/server/common/metrics"
"go.temporal.io/server/common/namespace"
"go.temporal.io/server/common/nexus/nexusrpc"
"go.temporal.io/server/common/persistence/serialization"
"go.temporal.io/server/common/persistence/transitionhistory"
"go.temporal.io/server/common/softassert"
"go.temporal.io/server/service/history/tasks"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
var (
protoMessageT = reflect.TypeFor[proto.Message]()
)
var (
errAccessCheckFailed = serviceerror.NewNotFound("access check failed, CHASM tree is closed for writes")
errComponentNotFound = serviceerror.NewNotFound("component not found")
errDataNotFound = serviceerror.NewNotFound("data not found")
errTaskNotValid = serviceerror.NewNotFound("task is no longer valid")
)
// valueState is an in-memory indicator of the dirtiness of a deserialized node value.
// The dirtiness has two parts:
// 1. If the data part of the value is in sync with the serializedNode field.
// 2. For component node, if the structure of the component is in sync with the children field.
//
// The enum value below is defined in increasing order of "dirtiness".
// - NeedDeserialize: Value is not even deserialized yet.
// - Synced: Value is deserialized and in sync with both serializedNode and children.
// - NeedSerialize: Value is deserialized, the child tree structure is synced, but the value is not in sync with serializedNode.
// - NeedSyncStructure: Value is deserialized, neither data nor tree structure is synced.
//
// For simplicity, for a dirty component node, the logic always sync structure (potentially multiple times within a transaction) first,
// and the serialize the data at the very end of a transaction. So there will never base a case where value is synced with seralizedNode,
// but not with children.
//
// To update this field, ALWAYS use setValueState() method.
//
// NOTE: This is a different concept from the IsDirty() method which is needed by MutableState implementation to determine
// if the state in memory matches the state in DB.
type valueState uint8
const (
valueStateUndefined valueState = iota
valueStateNeedDeserialize
valueStateSynced
valueStateNeedSerialize
valueStateNeedSyncStructure
)
const (
physicalTaskStatusNone int32 = iota
physicalTaskStatusCreated
)
type (
// Node is the in-memory representation of a persisted CHASM node.
//
// Node and all its methods are NOT meant to be used by CHASM component authors.
// They are exported for use by the CHASM engine and underlying MutableState implementation only.
Node struct {
*nodeBase
parent *Node
children map[string]*Node // child name (path segment) -> child node
nodeName string // key of this node in parent's children map, empty string for root node.
// Type of attributes controls the type of the node.
serializedNode *persistencespb.ChasmNode // serialized component | data | collection with metadata
// Deserialized component | data | map
// Do NOT set this field directly, use setValue() method instead.
value any
// Do NOT set this field directly, use setValueState() method instead.
valueState valueState
// Cached encoded path for this node.
// DO NOT read this field directly. Always use getEncodedPath() method to retrieve the encoded path.
//
// Empty string is a valid encoded path (for root node), so using *string here to differentiate.
//
// TODO: Consider using unique package here.
// Encoded path for different runs of the same Component type are the same.
encodedPath *string
// When terminated is true, regardless of the Lifecycle state of the component,
// the component will be considered as closed.
//
// NOTE: this is an in-memory only field and will be lost upon mutable state reload or replication.
// The purpose of this field is only for the transaction that force terminates the execution to
// update executionState & State in mutable state and generate retention timers, so it only needs to be
// in-memory and on the active side.
// If your logic needs to check if an execution is ever force terminated, check both this field (for the current
// transaction) and also the executionState from backend (for previous transactions).
//
// We can consider extending the force terminate concept to sub-components as well, and make the field durable.
terminated bool
// deleteAfterClose suppresses the close visibility task when an execution is being
// terminated as part of a delete operation. Like terminated, this is in-memory only
// and only needed for the current transaction. Set via SetDeleteAfterClose.
deleteAfterClose bool
}
// nodeBase is a set of dependencies and states shared by all nodes in a CHASM tree.
nodeBase struct {
registry *Registry
timeSource clock.TimeSource
backend NodeBackend
pathEncoder NodePathEncoder
logger log.Logger
metricsHandler metrics.Handler
// Following fields are changes accumulated in this transaction,
// and will get cleaned up after CloseTransaction().
// mutation field captures all user state changes (those will be replicated)
mutation NodesMutation
// systemMutation field captures all cell specific system changes (those will NOT be replicated)
systemMutation NodesMutation
newTasks map[any][]taskWithAttributes // component value -> task & attributes
immediatePureTasks map[any][]taskWithAttributes // similar to newTasks, but will be executed at the end of the transaction
// Pending framework metadata writes keyed by component value. Applied to
// each component's ChasmComponentAttributes during CloseTransaction so
// callers can stage writes before the component is registered as a node.
pendingRequestLinks map[any]map[string][]*commonpb.Link
pendingUserMetadata map[any]*sdkpb.UserMetadata
// Node value -> node
// Only component and data node values are tracked right now
valueToNode map[any]*Node
taskValueCache map[*commonpb.DataBlob]reflect.Value
// isActiveStateDirty is true if any user data is mutated.
// NOTE: this only captures active cluster's user data mutation.
// Replication logic (ApplySnapshot/Mutation) will not set this field.
//
// This flag in a CHASM tree level, while valueState is on node level.
// Tracking this flag on tree level avoids traversing the whole tree every time
// we want to know if something is updated.
//
// This flag is equivalent to checking if any node's valueState >= valueStateNeedSerialize
isActiveStateDirty bool
// Root component's search attributes and memo at the start of a transaction.
// They will be updated upon CloseTransaction() if they are changed.
currentSA map[string]VisibilityValue
currentMemo proto.Message
needsPointerResolution bool
}
taskWithAttributes struct {
task any
attributes TaskAttributes
}
// NodesMutation is a set of mutations for all nodes rooted at a given node n,
// including the node n itself.
NodesMutation struct {
UpdatedNodes map[string]*persistencespb.ChasmNode // encoded node path -> chasm node
DeletedNodes map[string]struct{}
}
// NodesSnapshot is a snapshot for all nodes rooted at a given node n,
// including the node n itself.
NodesSnapshot struct {
Nodes map[string]*persistencespb.ChasmNode // encoded node path -> chasm node
}
// NodeBackend is a set of methods needed from MutableState.
//
// This is for breaking cycle dependency between
// this package and service/history/workflow package
// where MutableState is defined.
NodeBackend interface {
// TODO: Add methods needed from MutateState here.
ExecutionStateUpdated() bool
GetExecutionState() *persistencespb.WorkflowExecutionState
GetExecutionInfo() *persistencespb.WorkflowExecutionInfo
GetApproximatePersistedSize() int
GetNamespaceEntry() *namespace.Namespace
GetCurrentVersion() int64
NextTransitionCount() int64
CurrentVersionedTransition() *persistencespb.VersionedTransition
GetWorkflowKey() definition.WorkflowKey
AddTasks(...tasks.Task)
AddHistoryEvent(t enumspb.EventType, setAttributes func(*historypb.HistoryEvent)) *historypb.HistoryEvent
GenerateEventLoadToken(event *historypb.HistoryEvent) ([]byte, error)
LoadHistoryEvent(ctx context.Context, token []byte) (*historypb.HistoryEvent, error)
HasAnyBufferedEvent(filter func(*historypb.HistoryEvent) bool) bool
DeleteCHASMPureTasks(maxScheduledTime time.Time)
UpdateWorkflowStateStatus(
state enumsspb.WorkflowExecutionState,
status enumspb.WorkflowExecutionStatus,
) (bool, error)
IsWorkflow() bool
GetNexusCompletion(
ctx context.Context,
requestID string,
) (nexusrpc.CompleteOperationOptions, error)
GetNexusUpdateCompletion(
ctx context.Context,
updateID string,
requestID string,
) (nexusrpc.CompleteOperationOptions, error)
EndpointRegistry() EndpointRegistry
}
// NodePathEncoder is an interface for encoding and decoding node paths.
// Logic outside the chasm package should only work with encoded paths.
NodePathEncoder interface {
Encode(node *Node, path []string) (string, error)
// TODO: Return a iterator on node name instead of []string,
// so that we can get a node by encoded path without additional
// allocation for the decoded path.
Decode(encodedPath string) ([]string, error)
}
// NodePureTask is intended to be implemented and used within the CHASM
// framework only.
NodePureTask interface {
ExecutePureTask(baseCtx context.Context, taskAttributes TaskAttributes, taskInstance any) (bool, error)
ValidatePureTask(baseCtx context.Context, taskAttributes TaskAttributes, taskInstance any) (bool, error)
}
)
// NewTreeFromDB creates a new in-memory CHASM tree from a collection of flattened persistence CHASM nodes.
// This method should only be used when loading an existing CHASM tree from database.
// If serializedNodes is empty, the tree will be considered as a legacy Workflow execution without any CHASM nodes.
func NewTreeFromDB(
serializedNodes map[string]*persistencespb.ChasmNode, // This is coming from MS map[nodePath]ChasmNode.
registry *Registry,
timeSource clock.TimeSource,
backend NodeBackend,
pathEncoder NodePathEncoder,
logger log.Logger,
metricsHandler metrics.Handler,
) (*Node, error) {
if len(serializedNodes) == 0 {
root := NewEmptyTree(registry, timeSource, backend, pathEncoder, logger, metricsHandler)
// NewEmptyTree initializes the serializedNode to an empty component node,
root.serializedNode.Metadata.GetComponentAttributes().TypeId = WorkflowArchetypeID
return root, nil
}
root := newTreeHelper(registry, timeSource, backend, pathEncoder, logger, metricsHandler)
for encodedPath, serializedNode := range serializedNodes {
nodePath, err := pathEncoder.Decode(encodedPath)
if err != nil {
return nil, err
}
root.setSerializedNode(nodePath, encodedPath, serializedNode)
}
if err := newTreeInitSearchAttributesAndMemo(root, registry); err != nil {
return nil, err
}
return root, nil
}
// NewEmptyTree creates a new empty in-memory CHASM tree.
func NewEmptyTree(
registry *Registry,
timeSource clock.TimeSource,
backend NodeBackend,
pathEncoder NodePathEncoder,
logger log.Logger,
metricsHandler metrics.Handler,
) *Node {
root := newTreeHelper(registry, timeSource, backend, pathEncoder, logger, metricsHandler)
// If serializedNodes is empty, it means that this new tree.
// Initialize empty serializedNode.
root.initSerializedNode(fieldTypeComponent)
// Default to Workflow archetype as empty tree is created for workflow as well.
root.serializedNode.Metadata.GetComponentAttributes().TypeId = WorkflowArchetypeID
// Although both value and serializedNode.Data are nil, they are considered NOT synced
// because value has no type and serializedNode does.
// deserialize method should set value when called.
root.setValueState(valueStateNeedDeserialize)
return root
}
func newTreeHelper(
registry *Registry,
timeSource clock.TimeSource,
backend NodeBackend,
pathEncoder NodePathEncoder,
logger log.Logger,
metricsHandler metrics.Handler,
) *Node {
base := &nodeBase{
registry: registry,
timeSource: timeSource,
backend: backend,
pathEncoder: pathEncoder,
logger: logger,
metricsHandler: metricsHandler,
mutation: NodesMutation{
UpdatedNodes: make(map[string]*persistencespb.ChasmNode),
DeletedNodes: make(map[string]struct{}),
},
systemMutation: NodesMutation{
UpdatedNodes: make(map[string]*persistencespb.ChasmNode),
DeletedNodes: make(map[string]struct{}),
},
newTasks: make(map[any][]taskWithAttributes),
immediatePureTasks: make(map[any][]taskWithAttributes),
pendingRequestLinks: make(map[any]map[string][]*commonpb.Link),
pendingUserMetadata: make(map[any]*sdkpb.UserMetadata),
valueToNode: make(map[any]*Node),
taskValueCache: make(map[*commonpb.DataBlob]reflect.Value),
needsPointerResolution: false,
}
return newNode(base, nil, "")
}
func newTreeInitSearchAttributesAndMemo(
root *Node,
registry *Registry,
) error {
immutableContext := NewContext(context.Background(), root)
rootComponent, err := root.Component(immutableContext, ComponentRef{})
if err != nil {
return err
}
// Theoritically we should check if the root node has a Visibility component or not.
// But that doesn't really matter. Even if it doesn't have one, currentSearchAttributes
// and currentMemo will just never be used.
if saProvider, ok := rootComponent.(VisibilitySearchAttributesProvider); ok {
saSlice := saProvider.SearchAttributes(immutableContext)
root.currentSA = searchAttributeKeyValuesToMap(saSlice)
}
if memoProvider, ok := rootComponent.(VisibilityMemoProvider); ok {
root.currentMemo = proto.Clone(memoProvider.Memo(immutableContext))
}
return nil
}
func searchAttributeKeyValuesToMap(saSlice []SearchAttributeKeyValue) map[string]VisibilityValue {
result := make(map[string]VisibilityValue, len(saSlice))
for _, sa := range saSlice {
result[sa.Field] = sa.Value
}
return result
}
func (n *Node) SetRootComponent(
rootComponent RootComponent,
) error {
root := n.root()
root.setValue(rootComponent)
root.setValueState(valueStateNeedSyncStructure)
if componentID, ok := n.registry.ComponentIDFor(rootComponent); ok {
root.serializedNode.GetMetadata().GetComponentAttributes().TypeId = componentID
}
return root.syncSubComponents()
}
// setValue sets the value field of the node.
// If the node is a component or data node, the index from node value to node (valueToNode)
// is also updated.
func (n *Node) setValue(value any) {
if !n.isComponent() && !n.isData() {
n.value = value
return
}
if n.value != nil {
delete(n.valueToNode, n.value)
}
n.value = value
if value != nil {
n.valueToNode[value] = n
}
}
func (n *Node) setValueState(state valueState) {
n.valueState = state
if state >= valueStateNeedSerialize {
n.isActiveStateDirty = true
}
}
// Component retrieves a component from the tree rooted at node n
// using the provided component reference
// It also performs access rule, and task validation checks
// (for task processing requests) before returning the component.
func (n *Node) Component(
chasmContext Context,
ref ComponentRef,
) (Component, error) {
// Archetype is already validated before this method is called.
// (when the mutable state is loaded, in chasm engine implementation)
node, ok := n.findNode(ref.componentPath)
if !ok {
return nil, errComponentNotFound
}
if ref.componentInitialVT != nil && transitionhistory.Compare(
ref.componentInitialVT,
node.serializedNode.Metadata.InitialVersionedTransition,
) != 0 {
return nil, errComponentNotFound
}
validationContext := NewContext(chasmContext.goContext(), node)
if err := node.prepareComponentValue(validationContext); err != nil {
return nil, err
}
componentValue, ok := node.value.(Component)
if !ok {
return nil, softassert.UnexpectedInternalErr(
n.logger,
"component value is not of type Component",
fmt.Errorf("%s", reflect.TypeOf(node.value).String()))
}
if err := node.validateAccess(validationContext, false); err != nil {
return nil, err
}
if ref.validationFn != nil {
if err := ref.validationFn(node.root().backend, validationContext, componentValue, node.registry); err != nil {
return nil, err
}
}
// prepare component value again using incoming context to mark node as dirty if needed.
if err := node.prepareComponentValue(chasmContext); err != nil {
return nil, err
}
return componentValue, nil
}
// validateAccess performs the access rule check on a node.
//
// When the context's intent is OperationIntentProgress, This check validates that
// all of a node's ancestors are still in a running state, and can accept writes. In
// the case of a newly created node, a detached node, or an OperationIntentObserve
// intent, the check is skipped.
//
// When checkPaused is true (used during task validation), the check is extended to
// also treat a paused lifecycle state as a blocking condition - for both ancestors
// and the node itself. This collapses the paused-subtree traversal into the same
// single pass, avoiding a second tree walk.
// Note: engine mutations on paused components are still accepted (checkPaused=false),
// per the current requirement.
func (n *Node) validateAccess(ctx Context, checkPaused bool) error {
intent := operationIntentFromContext(ctx.goContext())
if intent != OperationIntentProgress {
// Read-only operations are always allowed.
return nil
}
// Detached nodes skip ancestor validation entirely.
if n.isDetached() {
return nil
}
if n.parent != nil {
if err := n.parent.validateAccessHelper(ctx, checkPaused); err != nil {
return err
}
}
// validateAccessHelper traverses ancestors but never checks n itself.
// For task validation we must also check whether n is paused.
if checkPaused && n.isComponent() {
if err := n.prepareComponentValue(ctx); err != nil {
return err
}
componentValue, _ := n.value.(Component) //nolint:revive // unchecked-type-assertion
if componentValue.LifecycleState(ctx).IsPaused() {
return errAccessCheckFailed
}
}
return nil
}
// validateAccessHelper is a helper method that validates both the current
// node's lifecycle state AND its ancestors recursively.
// Do not call this method directly, call validateAccess instead.
func (n *Node) validateAccessHelper(ctx Context, checkPaused bool) error {
// Check ancestors first (if not detached).
if !n.isDetached() && n.parent != nil {
if err := n.parent.validateAccessHelper(ctx, checkPaused); err != nil {
return err
}
}
// Only Component nodes need to be validated.
if !n.isComponent() {
return nil
}
// Hydrate the component so we can access its LifecycleState.
if err := n.prepareComponentValue(ctx); err != nil {
return err
}
componentValue, _ := n.value.(Component) //nolint:revive // unchecked-type-assertion
lifecycleState := componentValue.LifecycleState(ctx)
if lifecycleState.IsClosed() {
return errAccessCheckFailed
}
if checkPaused && lifecycleState.IsPaused() {
return errAccessCheckFailed
}
if n.terminated {
// Terminated nodes can never be written to.
// This handles the case where root is terminated in the current transaction.
return errAccessCheckFailed
}
// terminated field check above is in memory only, so handle the case where root is terminated (closed)
// in a previous transaction and we have a mutable state reload which clears the field.
if n.parent == nil && n.backend.GetExecutionState().State == enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED {
return errAccessCheckFailed
}
return nil
}
func (n *Node) prepareComponentValue(
chasmContext Context,
) error {
if n.valueState == valueStateNeedDeserialize {
metadata := n.serializedNode.Metadata
componentAttr := metadata.GetComponentAttributes()
if componentAttr == nil {
return softassert.UnexpectedInternalErr(
n.logger,
"expect chasm node to have ComponentAttributes",
fmt.Errorf("actual attributes: %v", metadata.Attributes))
}
registrableComponent, ok := n.registry.ComponentByID(componentAttr.GetTypeId())
if !ok {
return softassert.UnexpectedInternalErr(
n.logger,
"unknown component type ID",
fmt.Errorf("%d", componentAttr.GetTypeId()))
}
if err := n.deserialize(registrableComponent.goType); err != nil {
return fmt.Errorf("failed to deserialize component: %w", err)
}
}
// For now, we assume if a node is accessed with a MutableContext,
// its value will be mutated and no longer in sync with the serializedNode.
_, componentCanBeMutated := chasmContext.(MutableContext)
if componentCanBeMutated {
n.setValueState(valueStateNeedSyncStructure)
}
return nil
}
func (n *Node) prepareDataValue(
chasmContext Context,
valueT reflect.Type,
) error {
metadata := n.serializedNode.Metadata
dataAttr := metadata.GetDataAttributes()
if dataAttr == nil {
return softassert.UnexpectedInternalErr(
n.logger,
"expect chasm node to have DataAttributes",
fmt.Errorf("actual attributes: %v", metadata.Attributes))
}
if n.valueState == valueStateNeedDeserialize {
if err := n.deserialize(valueT); err != nil {
return fmt.Errorf("failed to deserialize data: %w", err)
}
}
// For now, we assume if a node is accessed with a MutableContext,
// its value will be mutated and no longer in sync with the serializedNode.
_, componentCanBeMutated := chasmContext.(MutableContext)
if componentCanBeMutated {
n.setValueState(valueStateNeedSerialize)
}
return nil
}
func (n *Node) preparePointerValue() error {
metadata := n.serializedNode.Metadata
pointerAttr := metadata.GetPointerAttributes()
if pointerAttr == nil {
return softassert.UnexpectedInternalErr(
n.logger,
"expect chasm node to have PointerAttributes",
fmt.Errorf("actual attributes: %v", metadata.Attributes))
}
if n.valueState == valueStateNeedDeserialize {
if err := n.deserialize(nil); err != nil {
return fmt.Errorf("failed to deserialize data: %w", err)
}
}
return nil
}
func (n *Node) isComponent() bool {
return n.serializedNode.GetMetadata().GetComponentAttributes() != nil
}
func (n *Node) isData() bool {
return n.serializedNode.GetMetadata().GetDataAttributes() != nil
}
func (n *Node) isMap() bool {
return n.serializedNode.GetMetadata().GetCollectionAttributes() != nil
}
func (n *Node) isDetached() bool {
componentAttr := n.serializedNode.GetMetadata().GetComponentAttributes()
if componentAttr == nil {
return false
}
componentTypeID := componentAttr.GetTypeId()
if componentTypeID == CallbackComponentID ||
componentTypeID == visibilityComponentTypeID {
// For backward compatibility purpose, we need to special handle callback and visibility components,
// which are implemented before detached component is properly supported by the framework.
return true
}
return componentAttr.GetDetached()
}
func (n *Node) fieldType() fieldType {
if n.serializedNode.GetMetadata().GetComponentAttributes() != nil {
return fieldTypeComponent
}
if n.serializedNode.GetMetadata().GetDataAttributes() != nil {
return fieldTypeData
}
if n.serializedNode.GetMetadata().GetPointerAttributes() != nil {
return fieldTypePointer
}
if n.serializedNode.GetMetadata().GetCollectionAttributes() != nil {
softassert.Fail(
n.logger,
"fieldType can't be called on Collection node because Collection is not a Field")
}
return fieldTypeUnspecified
}
func (n *Node) valueFields() iter.Seq[fieldInfo] {
return fieldsOf(reflect.ValueOf(n.value))
}
func assertStructPointer(t reflect.Type) error {
if t == nil {
return nil
}
if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct {
return serviceerror.NewInternalf("only pointer to struct is supported for tree node value: got %s", t.String())
}
return nil
}
func (n *Node) initSerializedNode(ft fieldType) {
switch ft {
case fieldTypeData:
n.serializedNode = &persistencespb.ChasmNode{
Metadata: &persistencespb.ChasmNodeMetadata{
InitialVersionedTransition: &persistencespb.VersionedTransition{
TransitionCount: n.backend.NextTransitionCount(),
NamespaceFailoverVersion: n.backend.GetCurrentVersion(),
},
Attributes: &persistencespb.ChasmNodeMetadata_DataAttributes{
DataAttributes: &persistencespb.ChasmDataAttributes{},
},
},
}
case fieldTypeComponent:
n.serializedNode = &persistencespb.ChasmNode{
Metadata: &persistencespb.ChasmNodeMetadata{
InitialVersionedTransition: &persistencespb.VersionedTransition{
TransitionCount: n.backend.NextTransitionCount(),
NamespaceFailoverVersion: n.backend.GetCurrentVersion(),
},
Attributes: &persistencespb.ChasmNodeMetadata_ComponentAttributes{
ComponentAttributes: &persistencespb.ChasmComponentAttributes{},
},
},
}
case fieldTypePointer, fieldTypeDeferredPointer:
// A deferred pointer will be resolved to a regular pointer before persistence.
n.serializedNode = &persistencespb.ChasmNode{
Metadata: &persistencespb.ChasmNodeMetadata{
InitialVersionedTransition: &persistencespb.VersionedTransition{
TransitionCount: n.backend.NextTransitionCount(),
NamespaceFailoverVersion: n.backend.GetCurrentVersion(),
},
Attributes: &persistencespb.ChasmNodeMetadata_PointerAttributes{
PointerAttributes: &persistencespb.ChasmPointerAttributes{},
},
},
}
case fieldTypeUnspecified:
softassert.Fail(n.logger,
"initSerializedNode can't be called with unspecified field type")
}
}
func (n *Node) initSerializedCollectionNode() {
n.serializedNode = &persistencespb.ChasmNode{
Metadata: &persistencespb.ChasmNodeMetadata{
InitialVersionedTransition: &persistencespb.VersionedTransition{
TransitionCount: n.backend.NextTransitionCount(),
NamespaceFailoverVersion: n.backend.GetCurrentVersion(),
},
Attributes: &persistencespb.ChasmNodeMetadata_CollectionAttributes{
CollectionAttributes: &persistencespb.ChasmCollectionAttributes{},
},
},
}
}
func (n *Node) setSerializedNode(
nodePath []string,
encodedPath string,
serializedNode *persistencespb.ChasmNode,
) *Node {
if len(nodePath) == 0 {
n.serializedNode = serializedNode
n.setValueState(valueStateNeedDeserialize)
n.encodedPath = &encodedPath
return n
}
childName := nodePath[0]
childNode, ok := n.children[childName]
if !ok {
childNode = newNode(n.nodeBase, n, childName)
n.children[childName] = childNode
}
return childNode.setSerializedNode(nodePath[1:], encodedPath, serializedNode)
}
// hasNewTransactionSideEffects returns true when the transaction has observable
// effects that must be persisted regardless of whether data bytes changed:
// new tasks scheduled on this node, or lifecycle termination.
func (n *Node) hasNewTransactionSideEffects() bool {
return len(n.newTasks[n.value]) > 0 || n.terminated
}
// serialize sets or updates serializedValue field of the node n with serialized value.
// It sets node's valueState to valueStateSynced and updates LastUpdateVersionedTransition.
func (n *Node) serialize() error {
switch n.serializedNode.GetMetadata().GetAttributes().(type) {
case *persistencespb.ChasmNodeMetadata_ComponentAttributes:
return n.serializeComponentNode()
case *persistencespb.ChasmNodeMetadata_DataAttributes:
return n.serializeDataNode()
case *persistencespb.ChasmNodeMetadata_CollectionAttributes:
return n.serializeCollectionNode()
case *persistencespb.ChasmNodeMetadata_PointerAttributes:
return n.serializePointerNode()
default:
return softassert.UnexpectedInternalErr(n.logger, "unknown node type", nil)
}
}
// serializeComponentNode serializes the component node.
// If this method is updated to modify serialized fields beyond Data and
// LastUpdateVersionedTransition, the skip-if-clean revert logic in
// closeTransactionSerializeNodes must be updated accordingly.
func (n *Node) serializeComponentNode() error {
for field := range n.valueFields() {
if field.err != nil {
return field.err
}
if field.kind != fieldKindData {
continue
}
var blob *commonpb.DataBlob
if !field.val.IsNil() {
var err error
if blob, err = encodeChasmBlob(field.val.Interface().(proto.Message)); err != nil {
return err
}
}
n.serializedNode.Data = blob
if n.serializedNode.GetMetadata().GetLastUpdateVersionedTransition() == nil {
rc, ok := n.registry.componentFor(n.value)
if !ok {
return softassert.UnexpectedInternalErr(
n.logger,
"component type is not registered",
fmt.Errorf("%s", reflect.TypeOf(n.value).String()))
}
// TypeId mismatch on a brand new node indicates node reassignment.
existingTypeID := n.serializedNode.GetMetadata().GetComponentAttributes().GetTypeId()
if existingTypeID != 0 && existingTypeID != rc.componentID {
return softassert.UnexpectedInternalErr(
n.logger,
"component node TypeId changed on first serialization",
fmt.Errorf("existing: %d, new: %d", existingTypeID, rc.componentID),
)
}
n.serializedNode.GetMetadata().GetComponentAttributes().TypeId = rc.componentID
}
n.updateLastUpdateVersionedTransition()
n.setValueState(valueStateSynced)
// continue to iterate over fields to validate that there is only one proto field in the component.
}
return nil
}
// syncSubComponents syncs the entire tree recursively (starting from the root node n) from the underlining component value:
// - Create:
// -- if child node is nil but subcomponent is not empty or key present in the collection,
// a new node with subcomponent/collection_item value is created.
// - Delete:
// -- if subcomponent is empty, the corresponding child is removed from the tree,
// -- if subcomponent is no longer in a component, the corresponding child is removed from the tree,
// -- if collection item is not in the collection, the corresponding child is removed from the tree,
// -- when a child is removed, all its children are removed too.
//
// All removed paths are added to mutation.DeletedNodes (which is shared between all nodes in the tree).
//
// True is returned when CHASM must perform deferred pointer resolution.
//
// nolint:revive,cognitive-complexity
func (n *Node) syncSubComponents() error {
if n.valueState < valueStateNeedSyncStructure {
for _, childNode := range n.children {
err := childNode.syncSubComponents()
if err != nil {
return err
}
}
return nil
}
childrenToKeep := make(map[string]struct{})
for field := range n.valueFields() {
if field.err != nil {
return field.err
}
switch field.kind {
case fieldKindUnspecified:
softassert.Fail(n.logger,
"field.kind can be unspecified only if err is not nil, and there is a check for it above")
case fieldKindData:
// Nothing to sync.
case fieldKindSubField:
keepChild, updatedFieldV, err := n.syncSubField(field.val, field.name)
if err != nil {
return err
}
if updatedFieldV.IsValid() {
field.val.Set(updatedFieldV)
}
if keepChild {
childrenToKeep[field.name] = struct{}{}
}
case fieldKindParentPtr:
internalField := field.val.FieldByName(parentPtrInternalFieldName)
internal, ok := internalField.Interface().(parentPtrInternal)
if !ok {
return softassert.UnexpectedInternalErr(
n.logger,
"CHASM parent pointer's internal field is not of parentPtrInternal type",
fmt.Errorf("node %s, actual type: %T", n.nodeName, internalField.Interface()))
}
if internal.currentNode == nil || internal.currentNode != n {
internal.currentNode = n
internalField.Set(reflect.ValueOf(internal))
}
case fieldKindSubMap:
// Validate map type before doing anything with it.
if !field.val.IsNil() && field.val.Kind() != reflect.Map {
return softassert.UnexpectedInternalErr(
n.logger,
"CHASM map must be of map type",
fmt.Errorf("node %s", n.nodeName))
}
if field.val.IsNil() || len(field.val.MapKeys()) == 0 {
// nil or empty map: skip without creating a collection node.
// Any existing collection node will be removed by deleteChildren below.
continue
}
collectionNode := n.children[field.name]
if collectionNode == nil {
collectionNode = newNode(n.nodeBase, n, field.name)
collectionNode.initSerializedCollectionNode()
collectionNode.setValueState(valueStateNeedSyncStructure)
n.children[field.name] = collectionNode
}
mapValT := field.typ.Elem()
if mapValT.Kind() != reflect.Struct || genericTypePrefix(mapValT) != chasmFieldTypePrefix {
return softassert.UnexpectedInternalErr(
n.logger,
"CHASM map value must be of Field[T] type",
fmt.Errorf("node %s got %s", n.nodeName, mapValT))
}
collectionItemsToKeep := make(map[string]struct{})
for _, mapKeyV := range field.val.MapKeys() {
mapItemV := field.val.MapIndex(mapKeyV)
collectionKey, err := n.mapKeyToString(mapKeyV)
if err != nil {
return err
}
keepItem, updatedMapItemV, err := collectionNode.syncSubField(mapItemV, collectionKey)
if err != nil {
return err
}
if updatedMapItemV.IsValid() {
// The only way to update item in the map is to set it back.
field.val.SetMapIndex(mapKeyV, updatedMapItemV)
}
if keepItem {
collectionItemsToKeep[collectionKey] = struct{}{}
}
}
if err := collectionNode.deleteChildren(collectionItemsToKeep); err != nil {
return err
}
collectionNode.setValueState(min(valueStateNeedSerialize, collectionNode.valueState))
childrenToKeep[field.name] = struct{}{}
}
}
err := n.deleteChildren(childrenToKeep)
n.setValueState(valueStateNeedSerialize)
return err
}
func (n *Node) mapKeyToString(keyV reflect.Value) (string, error) {
switch keyV.Kind() {
case reflect.String: