-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathinternal_workflow.go
More file actions
2028 lines (1812 loc) · 62 KB
/
internal_workflow.go
File metadata and controls
2028 lines (1812 loc) · 62 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 internal
// All code in this file is private to the package.
import (
"bytes"
"errors"
"fmt"
"reflect"
"runtime"
"slices"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
commonpb "go.temporal.io/api/common/v1"
enumspb "go.temporal.io/api/enums/v1"
"go.temporal.io/api/sdk/v1"
systemnexus "go.temporal.io/api/workflowservice/v1/workflowservicenexus/json"
"go.temporal.io/sdk/converter"
"go.temporal.io/sdk/internal/common/metrics"
"go.temporal.io/sdk/log"
)
const (
defaultSignalChannelSize = 100000 // really large buffering size(100K)
defaultCoroutineExitTimeout = 100 * time.Millisecond
panicIllegalAccessCoroutineState = "getState: illegal access from outside of workflow context"
unhandledUpdateWarningMessage = "[TMPRL1102] Workflow finished while update handlers are still running. This may have interrupted work that the" +
" update handler was doing, and the client that sent the update will receive a 'workflow execution" +
" already completed' RPCError instead of the update result. You can wait for all update" +
" handlers to complete by using `workflow.Await(ctx, func() bool { return workflow.AllHandlersFinished(ctx) })`. Alternatively, if both you and the clients sending the update" +
" are okay with interrupting running handlers when the workflow finishes, and causing clients to" +
" receive errors, then you can disable this warning via UnfinishedPolicy in UpdateHandlerOptions."
)
type (
syncWorkflowDefinition struct {
workflow workflow
dispatcher dispatcher
cancel CancelFunc
rootCtx Context
}
workflowResult struct {
workflowResult *commonpb.Payloads
error error
}
futureImpl struct {
value interface{}
err error
ready bool
channel *channelImpl
chained []asyncFuture // Futures that are chained to this one
}
// Implements WaitGroup interface
waitGroupImpl struct {
n int // the number of coroutines to wait on
waiting bool // indicates whether WaitGroup.Wait() has been called yet for the WaitGroup
future Future // future to signal that all awaited members of the WaitGroup have completed
settable Settable // used to unblock the future when all coroutines have completed
}
// Implements Mutex interface
mutexImpl struct {
locked bool
}
// Implements Semaphore interface
semaphoreImpl struct {
size int64
cur int64
}
// Dispatcher is a container of a set of coroutines.
dispatcher interface {
// ExecuteUntilAllBlocked executes coroutines one by one in deterministic order
// until all of them are completed or blocked on Channel or Selector or timeout is reached.
ExecuteUntilAllBlocked(deadlockDetectionTimeout time.Duration) (err error)
// IsDone returns true when all of coroutines are completed
IsDone() bool
IsClosed() bool
IsExecuting() bool
Close() // Destroys all coroutines without waiting for their completion
StackTrace() string // Stack trace of all coroutines owned by the Dispatcher instance
// NewCoroutine creates a new coroutine. To be called from within another coroutine.
// Used by the interceptors.
NewCoroutine(ctx Context, name string, highPriority bool, f func(ctx Context)) Context
}
// Workflow is an interface that any workflow should implement.
// Code of a workflow must be deterministic. It must use workflow.Channel, workflow.Selector, and workflow.Go instead of
// native channels, select and go. It also must not use range operation over map as it is randomized by go runtime.
// All time manipulation should use current time returned by GetTime(ctx) method.
// Note that workflow.Context is used instead of context.Context to avoid use of raw channels.
workflow interface {
Execute(ctx Context, input *commonpb.Payloads) (result *commonpb.Payloads, err error)
}
sendCallback struct {
value interface{}
fn func() bool // false indicates that callback didn't accept the value
}
receiveCallback struct {
// false result means that callback didn't accept the value and it is still up for delivery
fn func(v interface{}, more bool) bool
}
channelImpl struct {
name string // human readable channel name
size int // Channel buffer size. 0 for non buffered.
buffer []interface{} // buffered messages
blockedSends []*sendCallback // puts waiting when buffer is full.
blockedReceives []*receiveCallback // receives waiting when no messages are available.
closed bool // true if channel is closed.
recValue *interface{} // Used only while receiving value, this is used as pre-fetch buffer value from the channel.
dataConverter converter.DataConverter // for decode data
env WorkflowEnvironment
}
// Single case statement of the Select
selectCase struct {
channel *channelImpl // Channel of this case.
receiveFunc *func(c ReceiveChannel, more bool) // function to call when channel has a message. nil for send case.
sendFunc *func() // function to call when channel accepted a message. nil for receive case.
sendValue *interface{} // value to send to the channel. Used only for send case.
future asyncFuture // Used for future case
futureFunc *func(f Future) // function to call when Future is ready
}
// Implements Selector interface
selectorImpl struct {
name string
cases []*selectCase // cases that this select is comprised from
defaultFunc *func() // default case
}
// unblockFunc is passed evaluated by a coroutine yield. When it returns false the yield returns to a caller.
// stackDepth is the depth of stack from the last blocking call relevant to user.
// Used to truncate internal stack frames from thread stack.
unblockFunc func(status string, stackDepth int) (keepBlocked bool)
coroutineState struct {
name string
dispatcher *dispatcherImpl // dispatcher this context belongs to
aboutToBlock chan bool // used to notify dispatcher that coroutine that owns this context is about to block
unblock chan unblockFunc // used to notify coroutine that it should continue executing.
keptBlocked bool // true indicates that coroutine didn't make any progress since the last yield unblocking
closed atomic.Bool // indicates that owning coroutine has finished execution
blocked atomic.Bool
panicError error // non nil if coroutine had unhandled panic
}
dispatcherImpl struct {
sequence int
channelSequence int // used to name channels
selectorSequence int // used to name channels
coroutines []*coroutineState
executing bool // currently running ExecuteUntilAllBlocked. Used to avoid recursive calls to it.
mutex sync.Mutex // used to synchronize executing
closed bool
interceptor WorkflowOutboundInterceptor
logger log.Logger
deadlockDetector *deadlockDetector
readOnly bool
// allBlockedCallback is called when all coroutines are blocked,
// returns true if the callback updated any coroutines state and there may be more work
allBlockedCallback func() bool
newEagerCoroutines []*coroutineState
}
// WorkflowOptions options passed to the workflow function
// The current timeout resolution implementation is in seconds and uses math.Ceil() as the duration. But is
// subjected to change in the future.
WorkflowOptions struct {
TaskQueueName string
WorkflowExecutionTimeout time.Duration
WorkflowRunTimeout time.Duration
WorkflowTaskTimeout time.Duration
Namespace string
WorkflowID string
WaitForCancellation bool
WorkflowIDReusePolicy enumspb.WorkflowIdReusePolicy
// WorkflowIDConflictPolicy and OnConflictOptions are only used in test environment for
// running Nexus operations as child workflow.
WorkflowIDConflictPolicy enumspb.WorkflowIdConflictPolicy
OnConflictOptions *OnConflictOptions
DataConverter converter.DataConverter
RetryPolicy *commonpb.RetryPolicy
Priority *commonpb.Priority
CronSchedule string
ContextPropagators []ContextPropagator
Memo map[string]interface{}
SearchAttributes map[string]interface{}
TypedSearchAttributes SearchAttributes
ParentClosePolicy enumspb.ParentClosePolicy
StaticSummary string
StaticDetails string
signalChannels map[string]Channel
requestedSignalChannels map[string]*requestedSignalChannel
queryHandlers map[string]*queryHandler
updateHandlers map[string]*updateHandler
// runningUpdatesHandles is a map of update handlers that are currently running.
runningUpdatesHandles map[string]UpdateInfo
VersioningIntent VersioningIntent
InitialVersioningBehavior ContinueAsNewVersioningBehavior
// currentDetails is the user-set string returned on metadata query as
// WorkflowMetadata.current_details
currentDetails string
}
// ExecuteWorkflowParams parameters of the workflow invocation
ExecuteWorkflowParams struct {
WorkflowOptions
WorkflowType *WorkflowType
Input *commonpb.Payloads
Header *commonpb.Header
attempt int32 // used by test framework to support child workflow retry
scheduledTime time.Time // used by test framework to support child workflow retry
lastCompletionResult *commonpb.Payloads // used by test framework to support cron
}
// decodeFutureImpl
decodeFutureImpl struct {
*futureImpl
fn interface{}
}
childWorkflowFutureImpl struct {
*decodeFutureImpl // for child workflow result
executionFuture *futureImpl // for child workflow execution future
}
nexusOperationFutureImpl struct {
*decodeFutureImpl // for the result
executionFuture *futureImpl // for the NexusOperationExecution
}
asyncFuture interface {
Future
// Used by selectorImpl
// If Future is ready returns its value immediately.
// If not registers callback which is called when it is ready.
GetAsync(callback *receiveCallback) (v interface{}, ok bool, err error)
// Used by selectorImpl
RemoveReceiveCallback(callback *receiveCallback)
// This future will added to list of dependency futures.
ChainFuture(f Future)
// Gets the current value and error.
// Make sure this is called once the future is ready.
GetValueAndError() (v interface{}, err error)
Set(value interface{}, err error)
}
requestedSignalChannel struct {
options SignalChannelOptions
}
queryHandler struct {
fn interface{}
queryType string
dataConverter converter.DataConverter
options QueryHandlerOptions
}
// updateSchedulerImpl adapts the coro dispatcher to the UpdateScheduler interface
updateSchedulerImpl struct {
dispatcher dispatcher
}
)
const (
workflowEnvironmentContextKey = "workflowEnv"
workflowInterceptorContextKey = "workflowInterceptor"
localActivityFnContextKey = "localActivityFn"
workflowEnvInterceptorContextKey = "envInterceptor"
workflowResultContextKey = "workflowResult"
coroutinesContextKey = "coroutines"
workflowEnvOptionsContextKey = "wfEnvOptions"
updateInfoContextKey = "updateInfo"
)
// Assert that structs do indeed implement the interfaces
var _ Channel = (*channelImpl)(nil)
var _ Selector = (*selectorImpl)(nil)
var _ WaitGroup = (*waitGroupImpl)(nil)
var _ dispatcher = (*dispatcherImpl)(nil)
// 1MB buffer to fit combined stack trace of all active goroutines
var stackBuf [1024 * 1024]byte
var (
errCoroStackNotFound = errors.New("coroutine stack not found")
errStackTraceTruncated = errors.New("stack trace truncated: stackBuf is too small")
)
// Pointer to pointer to workflow result
func getWorkflowResultPointerPointer(ctx Context) **workflowResult {
rpp := ctx.Value(workflowResultContextKey)
if rpp == nil {
panic("getWorkflowResultPointerPointer: Not a workflow context")
}
return rpp.(**workflowResult)
}
func getWorkflowEnvironment(ctx Context) WorkflowEnvironment {
wc := ctx.Value(workflowEnvironmentContextKey)
if wc == nil {
panic("getWorkflowContext: Not a workflow context")
}
return wc.(WorkflowEnvironment)
}
func getWorkflowEnvironmentInterceptor(ctx Context) *workflowEnvironmentInterceptor {
wc := ctx.Value(workflowEnvInterceptorContextKey)
if wc == nil {
panic("getWorkflowContext: Not a workflow context")
}
return wc.(*workflowEnvironmentInterceptor)
}
type workflowEnvironmentInterceptor struct {
env WorkflowEnvironment
dispatcher dispatcher
inboundInterceptor WorkflowInboundInterceptor
fn interface{}
outboundInterceptor WorkflowOutboundInterceptor
}
func (wc *workflowEnvironmentInterceptor) Go(ctx Context, name string, f func(ctx Context)) Context {
return wc.dispatcher.NewCoroutine(ctx, name, false, f)
}
func getWorkflowOutboundInterceptor(ctx Context) WorkflowOutboundInterceptor {
wc := ctx.Value(workflowInterceptorContextKey)
if wc == nil {
panic("getWorkflowOutboundInterceptor: Not a workflow context")
}
return wc.(WorkflowOutboundInterceptor)
}
func (f *futureImpl) Get(ctx Context, valuePtr interface{}) error {
assertNotInReadOnlyState(ctx)
more := f.channel.Receive(ctx, nil)
if more {
panic("not closed")
}
if !f.ready {
panic("not ready")
}
if f.err != nil || f.value == nil || valuePtr == nil {
return f.err
}
rf := reflect.ValueOf(valuePtr)
if rf.Type().Kind() != reflect.Ptr {
return errors.New("valuePtr parameter is not a pointer")
}
if payload, ok := f.value.(*commonpb.Payloads); ok {
if _, ok2 := valuePtr.(**commonpb.Payloads); !ok2 {
if err := decodeArg(getDataConverterFromWorkflowContext(ctx), payload, valuePtr); err != nil {
return err
}
return f.err
}
}
fv := reflect.ValueOf(f.value)
// If the value set was a pointer and is the same type as the wanted result,
// instead of panicking because it is not a pointer to a pointer, we will just
// set the pointer
if fv.Kind() == reflect.Ptr && fv.Type() == rf.Type() {
rf.Elem().Set(fv.Elem())
} else {
rf.Elem().Set(fv)
}
return f.err
}
// Used by selectorImpl
// If Future is ready returns its value immediately.
// If not registers callback which is called when it is ready.
func (f *futureImpl) GetAsync(callback *receiveCallback) (v interface{}, ok bool, err error) {
_, _, more := f.channel.receiveAsyncImpl(callback)
// Future uses Channel.Close to indicate that it is ready.
// So more being true (channel is still open) indicates future is not ready.
if more {
return nil, false, nil
}
if !f.ready {
panic("not ready")
}
return f.value, true, f.err
}
// RemoveReceiveCallback removes the callback from future's channel to avoid closure leak.
// Used by selectorImpl
func (f *futureImpl) RemoveReceiveCallback(callback *receiveCallback) {
f.channel.removeReceiveCallback(callback)
}
func (f *futureImpl) IsReady() bool {
return f.ready
}
func (f *futureImpl) Set(value interface{}, err error) {
if f.ready {
panic("already set")
}
f.value = value
f.err = err
f.ready = true
f.channel.Close()
for _, ch := range f.chained {
ch.Set(f.value, f.err)
}
}
func (f *futureImpl) SetValue(value interface{}) {
if f.ready {
panic("already set")
}
f.Set(value, nil)
}
func (f *futureImpl) SetError(err error) {
if f.ready {
panic("already set")
}
f.Set(nil, err)
}
func (f *futureImpl) Chain(future Future) {
if f.ready {
panic("already set")
}
ch, ok := future.(asyncFuture)
if !ok {
panic("cannot chain Future that wasn't created with workflow.NewFuture")
}
if !ch.IsReady() {
ch.ChainFuture(f)
return
}
val, err := ch.GetValueAndError()
f.value = val
f.err = err
f.ready = true
}
func (f *futureImpl) ChainFuture(future Future) {
f.chained = append(f.chained, future.(asyncFuture))
}
func (f *futureImpl) GetValueAndError() (interface{}, error) {
return f.value, f.err
}
func (f *childWorkflowFutureImpl) GetChildWorkflowExecution() Future {
return f.executionFuture
}
func (f *childWorkflowFutureImpl) SignalChildWorkflow(ctx Context, signalName string, data interface{}) Future {
assertNotInReadOnlyState(ctx)
var childExec WorkflowExecution
if err := f.GetChildWorkflowExecution().Get(ctx, &childExec); err != nil {
return f.GetChildWorkflowExecution()
}
i := getWorkflowOutboundInterceptor(ctx)
// Put header on context before executing
ctx = workflowContextWithNewHeader(ctx)
return i.SignalChildWorkflow(ctx, childExec.ID, signalName, data)
}
func (f *nexusOperationFutureImpl) GetNexusOperationExecution() Future {
return f.executionFuture
}
func newWorkflowContext(
env WorkflowEnvironment,
interceptors []WorkerInterceptor,
) (*workflowEnvironmentInterceptor, Context, error) {
// Create context with default values
ctx := WithValue(background, workflowEnvironmentContextKey, env)
var resultPtr *workflowResult
ctx = WithValue(ctx, workflowResultContextKey, &resultPtr)
info := env.WorkflowInfo()
ctx = WithWorkflowNamespace(ctx, info.Namespace)
ctx = WithWorkflowTaskQueue(ctx, info.TaskQueueName)
getWorkflowEnvOptions(ctx).WorkflowExecutionTimeout = info.WorkflowExecutionTimeout
ctx = WithWorkflowRunTimeout(ctx, info.WorkflowRunTimeout)
ctx = WithWorkflowTaskTimeout(ctx, info.WorkflowTaskTimeout)
ctx = WithTaskQueue(ctx, info.TaskQueueName)
ctx = WithDataConverter(ctx, env.GetDataConverter())
ctx = withContextPropagators(ctx, env.GetContextPropagators())
getActivityOptions(ctx).OriginalTaskQueueName = info.TaskQueueName
// Create interceptor and put it on context as inbound and put it on context
// as the default outbound interceptor before init
envInterceptor := &workflowEnvironmentInterceptor{env: env}
envInterceptor.inboundInterceptor = envInterceptor
envInterceptor.outboundInterceptor = envInterceptor
ctx = WithValue(ctx, workflowEnvInterceptorContextKey, envInterceptor)
ctx = WithValue(ctx, workflowInterceptorContextKey, envInterceptor.outboundInterceptor)
// Intercept, run init, and put the new outbound interceptor on the context
for i := len(interceptors) - 1; i >= 0; i-- {
envInterceptor.inboundInterceptor = interceptors[i].InterceptWorkflow(ctx, envInterceptor.inboundInterceptor)
}
err := envInterceptor.inboundInterceptor.Init(envInterceptor)
if err != nil {
return nil, nil, err
}
ctx = WithValue(ctx, workflowInterceptorContextKey, envInterceptor.outboundInterceptor)
return envInterceptor, ctx, nil
}
func (d *syncWorkflowDefinition) Execute(env WorkflowEnvironment, header *commonpb.Header, input *commonpb.Payloads) {
envInterceptor, rootCtx, err := newWorkflowContext(env, env.GetRegistry().interceptors)
if err != nil {
panic(err)
}
dispatcher, rootCtx := newDispatcher(
rootCtx,
envInterceptor,
func(ctx Context) {
r := &workflowResult{}
// We want to execute the user workflow definition from the first workflow task started,
// so they can see everything before that. Here we would have all initialization done, hence
// we are yielding.
state := getState(d.rootCtx)
state.yield("yield before executing to setup state")
state.unblocked()
r.workflowResult, r.error = d.workflow.Execute(d.rootCtx, input)
rpp := getWorkflowResultPointerPointer(ctx)
*rpp = r
}, getWorkflowEnvironment(rootCtx).DrainUnhandledUpdates)
// set the information from the headers that is to be propagated in the workflow context
rootCtx, err = workflowContextWithHeaderPropagated(rootCtx, header, env.GetContextPropagators())
if err != nil {
panic(err)
}
d.rootCtx, d.cancel = WithCancel(rootCtx)
d.dispatcher = dispatcher
envInterceptor.dispatcher = dispatcher
getWorkflowEnvironment(d.rootCtx).RegisterCancelHandler(func() {
// It is ok to call this method multiple times.
// it doesn't do anything new, the context remains canceled.
d.cancel()
})
getWorkflowEnvironment(d.rootCtx).RegisterSignalHandler(
func(name string, input *commonpb.Payloads, header *commonpb.Header) error {
// Put the header on context
rootCtx, err := workflowContextWithHeaderPropagated(d.rootCtx, header, env.GetContextPropagators())
if err != nil {
return err
}
return envInterceptor.inboundInterceptor.HandleSignal(rootCtx, &HandleSignalInput{SignalName: name, Arg: input})
},
)
getWorkflowEnvironment(d.rootCtx).RegisterUpdateHandler(
func(name string, id string, serializedArgs *commonpb.Payloads, header *commonpb.Header, callbacks UpdateCallbacks) {
defaultUpdateHandler(d.rootCtx, name, id, serializedArgs, header, callbacks, updateSchedulerImpl{d.dispatcher})
})
getWorkflowEnvironment(d.rootCtx).RegisterQueryHandler(
func(queryType string, queryArgs *commonpb.Payloads, header *commonpb.Header) (*commonpb.Payloads, error) {
// Put the header on context if server supports it
rootCtx, err := workflowContextWithHeaderPropagated(d.rootCtx, header, env.GetContextPropagators())
if err != nil {
return nil, err
}
// As a special case, we handle __temporal_workflow_metadata query
// here instead of in workflowExecutionEventHandlerImpl.ProcessQuery
// because we need the context environment to do so.
if queryType == QueryTypeWorkflowMetadata {
if result, err := getWorkflowMetadata(rootCtx); err != nil {
return nil, err
} else {
// Use raw value built from default converter because we don't want to use
// user-conversion
resultPayload, err := converter.GetDefaultDataConverter().ToPayload(result)
if err != nil {
return nil, err
}
return encodeArg(getDataConverterFromWorkflowContext(rootCtx), converter.NewRawValue(resultPayload))
}
}
eo := getWorkflowEnvOptions(rootCtx)
// A handler must be present since it is needed for argument decoding,
// even if the interceptor intercepts query handling
handler, ok := eo.queryHandlers[queryType]
if !ok {
keys := []string{QueryTypeStackTrace, QueryTypeOpenSessions, QueryTypeWorkflowMetadata}
for k := range eo.queryHandlers {
keys = append(keys, k)
}
return nil, fmt.Errorf("unknown queryType %v. KnownQueryTypes=%v", queryType, keys)
}
// Decode the arguments
args, err := decodeArgsToRawValues(handler.dataConverter, reflect.TypeOf(handler.fn), queryArgs)
if err != nil {
return nil, fmt.Errorf("unable to decode the input for queryType: %v, with error: %w", handler.queryType, err)
}
// Invoke
result, err := envInterceptor.inboundInterceptor.HandleQuery(
rootCtx,
&HandleQueryInput{QueryType: queryType, Args: args},
)
// Encode the result
var serializedResult *commonpb.Payloads
if err == nil {
serializedResult, err = encodeArg(handler.dataConverter, result)
}
return serializedResult, err
},
)
}
func (d *syncWorkflowDefinition) OnWorkflowTaskStarted(deadlockDetectionTimeout time.Duration) {
executeDispatcher(d.rootCtx, d.dispatcher, deadlockDetectionTimeout)
}
func (d *syncWorkflowDefinition) StackTrace() string {
return d.dispatcher.StackTrace()
}
func (d *syncWorkflowDefinition) Close() {
if d.dispatcher != nil {
d.dispatcher.Close()
}
}
// NewDispatcher creates a new Dispatcher instance with a root coroutine function.
// Context passed to the root function is child of the passed rootCtx.
// This way rootCtx can be used to pass values to the coroutine code.
func newDispatcher(rootCtx Context, interceptor *workflowEnvironmentInterceptor, root func(ctx Context), allBlockedCallback func() bool) (*dispatcherImpl, Context) {
env := getWorkflowEnvironment(rootCtx)
result := &dispatcherImpl{
interceptor: interceptor.outboundInterceptor,
logger: env.GetLogger(),
deadlockDetector: newDeadlockDetector(),
allBlockedCallback: allBlockedCallback,
}
interceptor.dispatcher = result
ctxWithState := result.interceptor.Go(rootCtx, "root", root)
return result, ctxWithState
}
// executeDispatcher executed coroutines in the calling thread and calls workflow completion callbacks
// if root workflow function returned
func executeDispatcher(ctx Context, dispatcher dispatcher, timeout time.Duration) {
env := getWorkflowEnvironment(ctx)
panicErr := dispatcher.ExecuteUntilAllBlocked(timeout)
if panicErr != nil {
env.Complete(nil, panicErr)
return
}
rp := *getWorkflowResultPointerPointer(ctx)
if rp == nil {
// Result is not set, so workflow is still executing
return
}
weo := getWorkflowEnvOptions(ctx)
us := weo.getUnhandledSignalNames()
if len(us) > 0 {
env.GetLogger().Warn("Workflow has unhandled signals", "SignalNames", us)
}
// Warn if there are any update handlers still running
type warnUpdate struct {
Name string `json:"name"`
ID string `json:"id"`
}
var updatesToWarn []warnUpdate
for _, info := range weo.getRunningUpdateHandles() {
if weo.updateHandlers[info.Name].unfinishedPolicy == HandlerUnfinishedPolicyWarnAndAbandon {
updatesToWarn = append(updatesToWarn, warnUpdate{
Name: info.Name,
ID: info.ID,
})
}
}
// Verify that the workflow did not fail. If it did we will not warn about unhandled updates.
var canceledErr *CanceledError
var contErr *ContinueAsNewError
if len(updatesToWarn) > 0 && (rp.error == nil || errors.As(rp.error, &canceledErr) || errors.As(rp.error, &contErr)) {
env.GetLogger().Warn(unhandledUpdateWarningMessage, "Updates", updatesToWarn)
}
env.Complete(rp.workflowResult, rp.error)
}
// For troubleshooting stack pretty printing only.
// Set to true to see full stack trace that includes framework methods.
const disableCleanStackTraces = false
func getState(ctx Context) *coroutineState {
s := ctx.Value(coroutinesContextKey)
if s == nil {
panic("getState: not workflow context")
}
state := s.(*coroutineState)
if !state.dispatcher.IsExecuting() {
panic(panicIllegalAccessCoroutineState)
}
return state
}
func assertNotInReadOnlyState(ctx Context) {
state := getState(ctx)
// use the dispatcher state instead of the coroutine state because contexts can be
// shared
if state.dispatcher.getIsReadOnly() {
panic(panicIllegalAccessCoroutineState)
}
}
func assertNotInReadOnlyStateCancellation(ctx Context) {
s := ctx.Value(coroutinesContextKey)
if s == nil {
panic("assertNotInReadOnlyStateCtxCancellation: not workflow context")
}
state := s.(*coroutineState)
// For cancellation the dispatcher may not be running because workflow cancellation
// is sent outside of the dispatchers loop.
if state.dispatcher.IsClosed() {
panic(panicIllegalAccessCoroutineState)
}
// use the dispatcher state instead of the coroutine state because contexts can be
// shared
if state.dispatcher.getIsReadOnly() {
panic(panicIllegalAccessCoroutineState)
}
}
func getStateIfRunning(ctx Context) *coroutineState {
if ctx == nil {
return nil
}
s := ctx.Value(coroutinesContextKey)
if s == nil {
return nil
}
state := s.(*coroutineState)
if !state.dispatcher.IsExecuting() {
return nil
}
return state
}
func (c *channelImpl) Name() string {
return c.name
}
func (c *channelImpl) CanReceiveWithoutBlocking() bool {
return c.recValue != nil || len(c.buffer) > 0 || len(c.blockedSends) > 0 || c.closed
}
func (c *channelImpl) CanSendWithoutBlocking() bool {
return len(c.buffer) < c.size || len(c.blockedReceives) > 0
}
func (c *channelImpl) Receive(ctx Context, valuePtr interface{}) (more bool) {
assertNotInReadOnlyState(ctx)
state := getState(ctx)
hasResult := false
var result interface{}
callback := &receiveCallback{
fn: func(v interface{}, m bool) bool {
result = v
hasResult = true
more = m
return true
},
}
for {
hasResult = false
v, ok, m := c.receiveAsyncImpl(callback)
if !ok && !m { // channel closed and empty
return m
}
if ok || !m {
err := c.assignValue(v, valuePtr)
if err == nil {
state.unblocked()
return m
}
continue // corrupt signal. Drop and reset process
}
for {
if hasResult {
err := c.assignValue(result, valuePtr)
if err == nil {
state.unblocked()
return more
}
break // Corrupt signal. Drop and reset process.
}
state.yield("blocked on " + c.name + ".Receive")
}
}
}
func (c *channelImpl) ReceiveWithTimeout(ctx Context, timeout time.Duration, valuePtr interface{}) (ok, more bool) {
okAwait, err := AwaitWithTimeout(ctx, timeout, func() bool { return c.Len() > 0 })
if err != nil { // context canceled
return false, true
}
if !okAwait { // timed out
return false, true
}
ok, more = c.ReceiveAsyncWithMoreFlag(valuePtr)
if !ok {
panic("unexpected empty channel")
}
return true, more
}
func (c *channelImpl) ReceiveAsync(valuePtr interface{}) (ok bool) {
ok, _ = c.ReceiveAsyncWithMoreFlag(valuePtr)
return ok
}
func (c *channelImpl) ReceiveAsyncWithMoreFlag(valuePtr interface{}) (ok bool, more bool) {
for {
v, ok, more := c.receiveAsyncImpl(nil)
if !ok && !more { // channel closed and empty
return ok, more
}
err := c.assignValue(v, valuePtr)
if err != nil {
continue
// keep consuming until a good signal is hit or channel is drained
}
return ok, more
}
}
func (c *channelImpl) Len() int {
result := len(c.buffer) + len(c.blockedSends)
if c.recValue != nil {
result = result + 1
}
return result
}
// ok = true means that value was received
// more = true means that channel is not closed and more deliveries are possible
func (c *channelImpl) receiveAsyncImpl(callback *receiveCallback) (v interface{}, ok bool, more bool) {
if c.recValue != nil {
r := *c.recValue
c.recValue = nil
return r, true, true
}
if len(c.buffer) > 0 {
r := c.buffer[0]
c.buffer[0] = nil
c.buffer = c.buffer[1:]
// Move blocked sends into buffer
for len(c.blockedSends) > 0 {
b := c.blockedSends[0]
c.blockedSends[0] = nil
c.blockedSends = c.blockedSends[1:]
if b.fn() {
c.buffer = append(c.buffer, b.value)
break
}
}
return r, true, true
}
if c.closed {
return nil, false, false
}
for len(c.blockedSends) > 0 {
b := c.blockedSends[0]
c.blockedSends[0] = nil
c.blockedSends = c.blockedSends[1:]
if b.fn() {
return b.value, true, true
}
}
if callback != nil {
c.blockedReceives = append(c.blockedReceives, callback)
}
return nil, false, true
}
func (c *channelImpl) removeReceiveCallback(callback *receiveCallback) {
for i, blockedCallback := range c.blockedReceives {
if callback == blockedCallback {
c.blockedReceives = append(c.blockedReceives[:i], c.blockedReceives[i+1:]...)
break
}
}
}
func (c *channelImpl) removeSendCallback(callback *sendCallback) {
for i, blockedCallback := range c.blockedSends {
if callback == blockedCallback {
c.blockedSends = append(c.blockedSends[:i], c.blockedSends[i+1:]...)
break
}
}
}
func (c *channelImpl) Send(ctx Context, v interface{}) {
state := getState(ctx)
valueConsumed := false
callback := &sendCallback{
value: v,
fn: func() bool {
valueConsumed = true
return true
},
}
ok := c.sendAsyncImpl(v, callback)
if ok {
state.unblocked()
return
}
for {
if valueConsumed {
state.unblocked()
return
}
// Check for closed in the loop as close can be called when send is blocked
if c.closed {
panic("Closed channel")
}
state.yield("blocked on " + c.name + ".Send")
}
}
func (c *channelImpl) SendAsync(v interface{}) (ok bool) {
return c.sendAsyncImpl(v, nil)
}
func (c *channelImpl) sendAsyncImpl(v interface{}, pair *sendCallback) (ok bool) {
if c.closed {
panic("Closed channel")
}
for len(c.blockedReceives) > 0 {
blockedGet := c.blockedReceives[0].fn
c.blockedReceives[0] = nil
c.blockedReceives = c.blockedReceives[1:]
// false from callback indicates that value wasn't consumed
if blockedGet(v, true) {
return true
}
}
if len(c.buffer) < c.size {
c.buffer = append(c.buffer, v)
return true
}
if pair != nil {
c.blockedSends = append(c.blockedSends, pair)
}
return false
}