-
Notifications
You must be signed in to change notification settings - Fork 230
/
Copy pathworkflow.go
2371 lines (2126 loc) · 93.2 KB
/
workflow.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
// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package internal
import (
"context"
"errors"
"fmt"
"strings"
"time"
"golang.org/x/exp/constraints"
"golang.org/x/exp/slices"
"google.golang.org/protobuf/types/known/durationpb"
commonpb "go.temporal.io/api/common/v1"
enumspb "go.temporal.io/api/enums/v1"
failurepb "go.temporal.io/api/failure/v1"
"go.temporal.io/sdk/converter"
"go.temporal.io/sdk/internal/common/metrics"
"go.temporal.io/sdk/log"
)
// HandlerUnfinishedPolicy actions taken if a workflow completes with running handlers.
//
// Policy defining actions taken when a workflow exits while update or signal handlers are running.
// The workflow exit may be due to successful return, failure, cancellation, or continue-as-new
type HandlerUnfinishedPolicy int
const (
// WarnAndAbandon issues a warning in addition to abandoning.
HandlerUnfinishedPolicyWarnAndAbandon HandlerUnfinishedPolicy = iota
// ABANDON abandons the handler.
HandlerUnfinishedPolicyAbandon
)
var (
errWorkflowIDNotSet = errors.New("workflowId is not set")
errLocalActivityParamsBadRequest = errors.New("missing local activity parameters through context, check LocalActivityOptions")
errSearchAttributesNotSet = errors.New("search attributes is empty")
errMemoNotSet = errors.New("memo is empty")
)
type (
// SendChannel is a write only view of the Channel
SendChannel interface {
// Name returns the name of the Channel.
// If the Channel was retrieved from a GetSignalChannel call, Name returns the signal name.
//
// A Channel created without an explicit name will use a generated name by the SDK and
// is not deterministic.
Name() string
// Send blocks until the data is sent.
Send(ctx Context, v interface{})
// SendAsync try to send without blocking. It returns true if the data was sent, otherwise it returns false.
SendAsync(v interface{}) (ok bool)
// Close close the Channel, and prohibit subsequent sends.
Close()
}
// ReceiveChannel is a read only view of the Channel
ReceiveChannel interface {
// Name returns the name of the Channel.
// If the Channel was retrieved from a GetSignalChannel call, Name returns the signal name.
//
// A Channel created without an explicit name will use a generated name by the SDK and
// is not deterministic.
Name() string
// Receive blocks until it receives a value, and then assigns the received value to the provided pointer.
// Returns false when Channel is closed.
// Parameter valuePtr is a pointer to the expected data structure to be received. For example:
// var v string
// c.Receive(ctx, &v)
//
// Note, values should not be reused for extraction here because merging on
// top of existing values may result in unexpected behavior similar to
// json.Unmarshal.
Receive(ctx Context, valuePtr interface{}) (more bool)
// ReceiveWithTimeout blocks up to timeout until it receives a value, and then assigns the received value to the
// provided pointer.
// Returns more value of false when Channel is closed.
// Returns ok value of false when no value was found in the channel for the duration of timeout or
// the ctx was canceled.
// The valuePtr is not modified if ok is false.
// Parameter valuePtr is a pointer to the expected data structure to be received. For example:
// var v string
// c.ReceiveWithTimeout(ctx, time.Minute, &v)
//
// Note, values should not be reused for extraction here because merging on
// top of existing values may result in unexpected behavior similar to
// json.Unmarshal.
ReceiveWithTimeout(ctx Context, timeout time.Duration, valuePtr interface{}) (ok, more bool)
// ReceiveAsync try to receive from Channel without blocking. If there is data available from the Channel, it
// assign the data to valuePtr and returns true. Otherwise, it returns false immediately.
//
// Note, values should not be reused for extraction here because merging on
// top of existing values may result in unexpected behavior similar to
// json.Unmarshal.
ReceiveAsync(valuePtr interface{}) (ok bool)
// ReceiveAsyncWithMoreFlag is same as ReceiveAsync with extra return value more to indicate if there could be
// more value from the Channel. The more is false when Channel is closed.
//
// Note, values should not be reused for extraction here because merging on
// top of existing values may result in unexpected behavior similar to
// json.Unmarshal.
ReceiveAsyncWithMoreFlag(valuePtr interface{}) (ok bool, more bool)
// Len returns the number of buffered messages plus the number of blocked Send calls.
Len() int
}
// Channel must be used instead of native go channel by workflow code.
// Use workflow.NewChannel(ctx) method to create Channel instance.
Channel interface {
SendChannel
ReceiveChannel
}
// Selector must be used instead of native go select by workflow code.
// Create through workflow.NewSelector(ctx).
Selector interface {
// AddReceive registers a callback function to be called when a channel has a message to receive.
// The callback is called when Select(ctx) is called.
// The message is expected be consumed by the callback function.
// The branch is automatically removed after the channel is closed and callback function is called once
// with more parameter set to false.
AddReceive(c ReceiveChannel, f func(c ReceiveChannel, more bool)) Selector
// AddSend registers a callback function to be called when a message is sent on a channel.
// The callback is called after the message is sent to the channel and Select(ctx) is called
AddSend(c SendChannel, v interface{}, f func()) Selector
// AddFuture registers a callback function to be called when a future is ready.
// The callback is called when Select(ctx) is called.
// The callback is called once per ready future even if Select is called multiple times for the same
// Selector instance.
AddFuture(future Future, f func(f Future)) Selector
// AddDefault register callback function to be called if none of other branches matched.
// The callback is called when Select(ctx) is called.
// When the default branch is registered Select never blocks.
AddDefault(f func())
// Select checks if any of the registered branches satisfies its condition blocking if necessary.
// When a branch becomes eligible its callback is invoked.
// If multiple branches are eligible only one of them (picked randomly) is invoked per Select call.
// It is OK to call Select multiple times for the same Selector instance.
Select(ctx Context)
// HasPending returns true if call to Select is guaranteed to not block.
HasPending() bool
}
// WaitGroup must be used instead of native go sync.WaitGroup by
// workflow code. Use workflow.NewWaitGroup(ctx) method to create
// a new WaitGroup instance
WaitGroup interface {
Add(delta int)
Done()
Wait(ctx Context)
}
// Mutex must be used instead of native go sync.Mutex by
// workflow code. Use workflow.NewMutex(ctx) method to create
// a new Mutex instance
Mutex interface {
// Lock blocks until the mutex is acquired.
// Returns CanceledError if the ctx is canceled.
Lock(ctx Context) error
// TryLock tries to acquire the mutex without blocking.
// Returns true if the mutex was acquired, otherwise false.
TryLock(ctx Context) bool
// Unlock releases the mutex.
// It is a run-time error if the mutex is not locked on entry to Unlock.
Unlock()
// IsLocked returns true if the mutex is currently locked.
IsLocked() bool
}
// Semaphore must be used instead of semaphore.Weighted by
// workflow code. Use workflow.NewSemaphore(ctx) method to create
// a new Semaphore instance
Semaphore interface {
// Acquire acquires the semaphore with a weight of n.
// On success, returns nil. On failure, returns CanceledError and leaves the semaphore unchanged.
Acquire(ctx Context, n int64) error
// TryAcquire acquires the semaphore with a weight of n without blocking.
// On success, returns true. On failure, returns false and leaves the semaphore unchanged.
TryAcquire(ctx Context, n int64) bool
// Release releases the semaphore with a weight of n.
Release(n int64)
}
// Future represents the result of an asynchronous computation.
Future interface {
// Get blocks until the future is ready. When ready it either returns non nil error or assigns result value to
// the provided pointer.
// Example:
// var v string
// if err := f.Get(ctx, &v); err != nil {
// return err
// }
//
// The valuePtr parameter can be nil when the encoded result value is not needed.
// Example:
// err = f.Get(ctx, nil)
//
// Note, values should not be reused for extraction here because merging on
// top of existing values may result in unexpected behavior similar to
// json.Unmarshal.
Get(ctx Context, valuePtr interface{}) error
// When true Get is guaranteed to not block
IsReady() bool
}
// Settable is used to set value or error on a future.
// See more: workflow.NewFuture(ctx).
Settable interface {
Set(value interface{}, err error)
SetValue(value interface{})
SetError(err error)
Chain(future Future) // EncodedValue (or error) of the future become the same of the chained one.
}
// ChildWorkflowFuture represents the result of a child workflow execution
ChildWorkflowFuture interface {
Future
// GetChildWorkflowExecution returns a future that will be ready when child workflow execution started. You can
// get the WorkflowExecution of the child workflow from the future. Then you can use Workflow ID and RunID of
// child workflow to cancel or send signal to child workflow.
// childWorkflowFuture := workflow.ExecuteChildWorkflow(ctx, child, ...)
// var childWE workflow.Execution
// if err := childWorkflowFuture.GetChildWorkflowExecution().Get(ctx, &childWE); err == nil {
// // child workflow started, you can use childWE to get the WorkflowID and RunID of child workflow
// }
GetChildWorkflowExecution() Future
// SignalChildWorkflow sends a signal to the child workflow. This call will block until child workflow is started.
SignalChildWorkflow(ctx Context, signalName string, data interface{}) Future
}
// WorkflowType identifies a workflow type.
WorkflowType struct {
Name string
}
// WorkflowExecution details.
WorkflowExecution struct {
ID string
RunID string
}
// EncodedValue is type used to encapsulate/extract encoded result from workflow/activity.
EncodedValue struct {
value *commonpb.Payloads
dataConverter converter.DataConverter
}
// Version represents a change version. See GetVersion call.
Version int
// ChildWorkflowOptions stores all child workflow specific parameters that will be stored inside of a Context.
// The current timeout resolution implementation is in seconds and uses math.Ceil(d.Seconds()) as the duration. But is
// subjected to change in the future.
ChildWorkflowOptions struct {
// Namespace of the child workflow.
// Optional: the current workflow (parent)'s namespace will be used if this is not provided.
Namespace string
// WorkflowID of the child workflow to be scheduled.
// Optional: an auto generated workflowID will be used if this is not provided.
WorkflowID string
// TaskQueue that the child workflow needs to be scheduled on.
// Optional: the parent workflow task queue will be used if this is not provided.
TaskQueue string
// WorkflowExecutionTimeout - The end to end timeout for the child workflow execution including retries
// and continue as new.
// Optional: defaults to unlimited.
WorkflowExecutionTimeout time.Duration
// WorkflowRunTimeout - The timeout for a single run of the child workflow execution. Each retry or
// continue as new should obey this timeout. Use WorkflowExecutionTimeout to specify how long the parent
// is willing to wait for the child completion.
// Optional: defaults to WorkflowExecutionTimeout
WorkflowRunTimeout time.Duration
// WorkflowTaskTimeout - Maximum execution time of a single Workflow Task. In the majority of cases there is
// no need to change this timeout. Note that this timeout is not related to the overall Workflow duration in
// any way. It defines for how long the Workflow can get blocked in the case of a Workflow Worker crash.
// Default is 10 seconds. Maximum value allowed by the Temporal Server is 1 minute.
WorkflowTaskTimeout time.Duration
// WaitForCancellation - Whether to wait for canceled child workflow to be ended (child workflow can be ended
// as: completed/failed/timedout/terminated/canceled)
// Optional: default false
WaitForCancellation bool
// WorkflowIDReusePolicy - Whether server allow reuse of workflow ID, can be useful
// for dedup logic if set to WorkflowIdReusePolicyRejectDuplicate
WorkflowIDReusePolicy enumspb.WorkflowIdReusePolicy
// RetryPolicy specify how to retry child workflow if error happens.
// Optional: default is no retry
RetryPolicy *RetryPolicy
// CronSchedule - Optional cron schedule for workflow. If a cron schedule is specified, the workflow will run
// as a cron based on the schedule. The scheduling will be based on UTC time. Schedule for next run only happen
// after the current run is completed/failed/timeout. If a RetryPolicy is also supplied, and the workflow failed
// or timeout, the workflow will be retried based on the retry policy. While the workflow is retrying, it won't
// schedule its next run. If next schedule is due while workflow is running (or retrying), then it will skip that
// schedule. Cron workflow will not stop until it is terminated or canceled (by returning temporal.CanceledError).
// The cron spec is as following:
// ┌───────────── minute (0 - 59)
// │ ┌───────────── hour (0 - 23)
// │ │ ┌───────────── day of the month (1 - 31)
// │ │ │ ┌───────────── month (1 - 12)
// │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday)
// │ │ │ │ │
// │ │ │ │ │
// * * * * *
CronSchedule string
// Memo - Optional non-indexed info that will be shown in list workflow.
Memo map[string]interface{}
// SearchAttributes - Optional indexed info that can be used in query of List/Scan/Count workflow APIs. The key and value type must be registered on Temporal server side.
// Use GetSearchAttributes API to get valid key and corresponding value type.
// For supported operations on different server versions see [Visibility].
//
// Deprecated: Use TypedSearchAttributes instead.
//
// [Visibility]: https://docs.temporal.io/visibility
SearchAttributes map[string]interface{}
// TypedSearchAttributes - Specifies Search Attributes that will be attached to the Workflow. Search Attributes are
// additional indexed information attributed to workflow and used for search and visibility. The search attributes
// can be used in query of List/Scan/Count workflow APIs. The key and its value type must be registered on Temporal
// server side. For supported operations on different server versions see [Visibility].
//
// Optional: default to none.
//
// [Visibility]: https://docs.temporal.io/visibility
TypedSearchAttributes SearchAttributes
// ParentClosePolicy - Optional policy to decide what to do for the child.
// Default is Terminate (if onboarded to this feature)
ParentClosePolicy enumspb.ParentClosePolicy
// VersioningIntent specifies whether this child workflow should run on a worker with a
// compatible build ID or not. See VersioningIntent.
// WARNING: Worker versioning is currently experimental
VersioningIntent VersioningIntent
}
// RegisterWorkflowOptions consists of options for registering a workflow
RegisterWorkflowOptions struct {
// Custom name for this workflow instead of the function name.
//
// If this is set, users are strongly recommended to set
// worker.Options.DisableRegistrationAliasing at the worker level to prevent
// ambiguity between string names and function references. Also users should
// always use this string name when executing this workflow from a client or
// inside a workflow as a child workflow.
Name string
DisableAlreadyRegisteredCheck bool
}
localActivityContext struct {
fn interface{}
isMethod bool
}
// UpdateHandlerOptions consists of options for executing a named workflow update.
//
// NOTE: Experimental
UpdateHandlerOptions struct {
// Validator is an optional (i.e. can be left nil) func with exactly the
// same type signature as the required update handler func but returning
// only a single value of type error. The implementation of this
// function MUST NOT alter workflow state in any way however it need not
// be pure - it is permissible to observe workflow state without
// mutating it as part of performing validation. The prohibition against
// mutating workflow state includes normal variable mutation/assignment
// as well as workflow actions such as scheduling activities and
// performing side-effects. A panic from this function will be treated
// as equivalent to returning an error.
Validator interface{}
// UnfinishedPolicy is the policy to apply when a workflow exits while
// the update handler is still running.
UnfinishedPolicy HandlerUnfinishedPolicy
}
)
// Await blocks the calling thread until condition() returns true
// Returns CanceledError if the ctx is canceled.
func Await(ctx Context, condition func() bool) error {
assertNotInReadOnlyState(ctx)
state := getState(ctx)
return state.dispatcher.interceptor.Await(ctx, condition)
}
func (wc *workflowEnvironmentInterceptor) Await(ctx Context, condition func() bool) error {
state := getState(ctx)
defer state.unblocked()
for !condition() {
doneCh := ctx.Done()
// TODO: Consider always returning a channel
if doneCh != nil {
if _, more := doneCh.ReceiveAsyncWithMoreFlag(nil); !more {
return NewCanceledError("Await context canceled")
}
}
state.yield("Await")
}
return nil
}
// AwaitWithTimeout blocks the calling thread until condition() returns true
// Returns ok equals to false if timed out and err equals to CanceledError if the ctx is canceled.
func AwaitWithTimeout(ctx Context, timeout time.Duration, condition func() bool) (ok bool, err error) {
assertNotInReadOnlyState(ctx)
state := getState(ctx)
return state.dispatcher.interceptor.AwaitWithTimeout(ctx, timeout, condition)
}
func (wc *workflowEnvironmentInterceptor) AwaitWithTimeout(ctx Context, timeout time.Duration, condition func() bool) (ok bool, err error) {
state := getState(ctx)
defer state.unblocked()
timer := NewTimer(ctx, timeout)
for !condition() {
doneCh := ctx.Done()
// TODO: Consider always returning a channel
if doneCh != nil {
if _, more := doneCh.ReceiveAsyncWithMoreFlag(nil); !more {
return false, NewCanceledError("AwaitWithTimeout context canceled")
}
}
if timer.IsReady() {
return false, nil
}
state.yield("AwaitWithTimeout")
}
return true, nil
}
// NewChannel create new Channel instance
func NewChannel(ctx Context) Channel {
state := getState(ctx)
state.dispatcher.channelSequence++
return NewNamedChannel(ctx, fmt.Sprintf("chan-%v", state.dispatcher.channelSequence))
}
// NewNamedChannel create new Channel instance with a given human readable name.
// Name appears in stack traces that are blocked on this channel.
func NewNamedChannel(ctx Context, name string) Channel {
env := getWorkflowEnvironment(ctx)
return &channelImpl{name: name, dataConverter: getDataConverterFromWorkflowContext(ctx), env: env}
}
// NewBufferedChannel create new buffered Channel instance
func NewBufferedChannel(ctx Context, size int) Channel {
env := getWorkflowEnvironment(ctx)
return &channelImpl{size: size, dataConverter: getDataConverterFromWorkflowContext(ctx), env: env}
}
// NewNamedBufferedChannel create new BufferedChannel instance with a given human readable name.
// Name appears in stack traces that are blocked on this Channel.
func NewNamedBufferedChannel(ctx Context, name string, size int) Channel {
env := getWorkflowEnvironment(ctx)
return &channelImpl{name: name, size: size, dataConverter: getDataConverterFromWorkflowContext(ctx), env: env}
}
// NewSelector creates a new Selector instance.
func NewSelector(ctx Context) Selector {
state := getState(ctx)
state.dispatcher.selectorSequence++
return NewNamedSelector(ctx, fmt.Sprintf("selector-%v", state.dispatcher.selectorSequence))
}
// NewNamedSelector creates a new Selector instance with a given human readable name.
// Name appears in stack traces that are blocked on this Selector.
func NewNamedSelector(ctx Context, name string) Selector {
assertNotInReadOnlyState(ctx)
return &selectorImpl{name: name}
}
// NewWaitGroup creates a new WaitGroup instance.
func NewWaitGroup(ctx Context) WaitGroup {
assertNotInReadOnlyState(ctx)
f, s := NewFuture(ctx)
return &waitGroupImpl{future: f, settable: s}
}
// NewMutex creates a new Mutex instance.
func NewMutex(ctx Context) Mutex {
assertNotInReadOnlyState(ctx)
return &mutexImpl{}
}
// NewSemaphore creates a new Semaphore instance with an initial weight.
func NewSemaphore(ctx Context, n int64) Semaphore {
assertNotInReadOnlyState(ctx)
return &semaphoreImpl{size: n}
}
// Go creates a new coroutine. It has similar semantic to goroutine in a context of the workflow.
func Go(ctx Context, f func(ctx Context)) {
assertNotInReadOnlyState(ctx)
state := getState(ctx)
state.dispatcher.interceptor.Go(ctx, "", f)
}
// GoNamed creates a new coroutine with a given human readable name.
// It has similar semantic to goroutine in a context of the workflow.
// Name appears in stack traces that are blocked on this Channel.
func GoNamed(ctx Context, name string, f func(ctx Context)) {
assertNotInReadOnlyState(ctx)
state := getState(ctx)
state.dispatcher.interceptor.Go(ctx, name, f)
}
// NewFuture creates a new future as well as associated Settable that is used to set its value.
func NewFuture(ctx Context) (Future, Settable) {
assertNotInReadOnlyState(ctx)
impl := &futureImpl{channel: NewChannel(ctx).(*channelImpl)}
return impl, impl
}
func (wc *workflowEnvironmentInterceptor) HandleSignal(ctx Context, in *HandleSignalInput) error {
// Remove header from the context
ctx = workflowContextWithoutHeader(ctx)
eo := getWorkflowEnvOptions(ctx)
// We don't want this code to be blocked ever, using sendAsync().
ch := eo.getSignalChannel(ctx, in.SignalName).(*channelImpl)
if !ch.SendAsync(in.Arg) {
return fmt.Errorf("exceeded channel buffer size for signal: %v", in.SignalName)
}
return nil
}
func (wc *workflowEnvironmentInterceptor) ValidateUpdate(ctx Context, in *UpdateInput) error {
eo := getWorkflowEnvOptions(ctx)
handler, ok := eo.updateHandlers[in.Name]
if !ok {
keys := make([]string, 0, len(eo.updateHandlers))
for k := range eo.updateHandlers {
keys = append(keys, k)
}
return fmt.Errorf("unknown update %v. KnownUpdates=%v", in.Name, keys)
}
return handler.validate(ctx, in.Args)
}
func (wc *workflowEnvironmentInterceptor) ExecuteUpdate(ctx Context, in *UpdateInput) (interface{}, error) {
eo := getWorkflowEnvOptions(ctx)
handler, ok := eo.updateHandlers[in.Name]
if !ok {
keys := make([]string, 0, len(eo.updateHandlers))
for k := range eo.updateHandlers {
keys = append(keys, k)
}
return nil, fmt.Errorf("unknown update %v. KnownUpdates=%v", in.Name, keys)
}
return handler.execute(ctx, in.Args)
}
func (wc *workflowEnvironmentInterceptor) HandleQuery(ctx Context, in *HandleQueryInput) (interface{}, error) {
eo := getWorkflowEnvOptions(ctx)
handler, ok := eo.queryHandlers[in.QueryType]
// Should never happen because its presence is checked before this call too
if !ok {
keys := []string{QueryTypeStackTrace, QueryTypeOpenSessions}
for k := range eo.queryHandlers {
keys = append(keys, k)
}
return nil, fmt.Errorf("unknown queryType %v. KnownQueryTypes=%v", in.QueryType, keys)
}
return handler.execute(in.Args)
}
func (wc *workflowEnvironmentInterceptor) ExecuteWorkflow(ctx Context, in *ExecuteWorkflowInput) (interface{}, error) {
// Remove header from the context
ctx = workflowContextWithoutHeader(ctx)
// Always put the context first
args := append([]interface{}{ctx}, in.Args...)
return executeFunction(wc.fn, args)
}
func (wc *workflowEnvironmentInterceptor) Init(outbound WorkflowOutboundInterceptor) error {
wc.outboundInterceptor = outbound
return nil
}
// ExecuteActivity requests activity execution in the context of a workflow.
// Context can be used to pass the settings for this activity.
// For example: task queue that this need to be routed, timeouts that need to be configured.
// Use ActivityOptions to pass down the options.
//
// ao := ActivityOptions{
// TaskQueue: "exampleTaskQueue",
// ScheduleToStartTimeout: 10 * time.Second,
// StartToCloseTimeout: 5 * time.Second,
// ScheduleToCloseTimeout: 10 * time.Second,
// HeartbeatTimeout: 0,
// }
// ctx := WithActivityOptions(ctx, ao)
//
// Or to override a single option
//
// ctx := WithTaskQueue(ctx, "exampleTaskQueue")
//
// Input activity is either an activity name (string) or a function representing an activity that is getting scheduled.
// Input args are the arguments that need to be passed to the scheduled activity.
//
// If the activity failed to complete then the future get error would indicate the failure.
// The error will be of type *ActivityError. It will have important activity information and actual error that caused
// activity failure. Use errors.Unwrap to get this error or errors.As to check it type which can be one of
// *ApplicationError, *TimeoutError, *CanceledError, or *PanicError.
//
// You can cancel the pending activity using context(workflow.WithCancel(ctx)) and that will fail the activity with
// *CanceledError set as cause for *ActivityError.
//
// ExecuteActivity returns Future with activity result or failure.
func ExecuteActivity(ctx Context, activity interface{}, args ...interface{}) Future {
assertNotInReadOnlyState(ctx)
i := getWorkflowOutboundInterceptor(ctx)
registry := getRegistryFromWorkflowContext(ctx)
activityType := getActivityFunctionName(registry, activity)
// Put header on context before executing
ctx = workflowContextWithNewHeader(ctx)
return i.ExecuteActivity(ctx, activityType, args...)
}
func (wc *workflowEnvironmentInterceptor) ExecuteActivity(ctx Context, typeName string, args ...interface{}) Future {
// Validate type and its arguments.
dataConverter := getDataConverterFromWorkflowContext(ctx)
registry := getRegistryFromWorkflowContext(ctx)
future, settable := newDecodeFuture(ctx, typeName)
activityType, err := getValidatedActivityFunction(typeName, args, registry)
if err != nil {
settable.Set(nil, err)
return future
}
// Validate context options.
options := getActivityOptions(ctx)
// Validate session state.
if sessionInfo := getSessionInfo(ctx); sessionInfo != nil {
isCreationActivity := isSessionCreationActivity(typeName)
if sessionInfo.SessionState == SessionStateFailed && !isCreationActivity {
settable.Set(nil, ErrSessionFailed)
return future
}
if sessionInfo.SessionState == SessionStateOpen && !isCreationActivity {
// Use session taskqueue
oldTaskQueueName := options.TaskQueueName
options.TaskQueueName = sessionInfo.taskqueue
defer func() {
options.TaskQueueName = oldTaskQueueName
}()
}
}
// Retrieve headers from context to pass them on
envOptions := getWorkflowEnvOptions(ctx)
header, err := workflowHeaderPropagated(ctx, envOptions.ContextPropagators)
if err != nil {
settable.Set(nil, err)
return future
}
input, err := encodeArgs(dataConverter, args)
if err != nil {
panic(err)
}
params := ExecuteActivityParams{
ExecuteActivityOptions: *options,
ActivityType: *activityType,
Input: input,
DataConverter: dataConverter,
Header: header,
}
ctxDone, cancellable := ctx.Done().(*channelImpl)
cancellationCallback := &receiveCallback{}
a := getWorkflowEnvironment(ctx).ExecuteActivity(params, func(r *commonpb.Payloads, e error) {
settable.Set(r, e)
if cancellable {
// future is done, we don't need the cancellation callback anymore.
ctxDone.removeReceiveCallback(cancellationCallback)
}
})
if cancellable {
cancellationCallback.fn = func(v interface{}, more bool) bool {
assertNotInReadOnlyStateCancellation(ctx)
if ctx.Err() == ErrCanceled {
wc.env.RequestCancelActivity(a)
}
return false
}
_, ok, more := ctxDone.receiveAsyncImpl(cancellationCallback)
if ok || !more {
cancellationCallback.fn(nil, more)
}
}
return future
}
// ExecuteLocalActivity requests to run a local activity. A local activity is like a regular activity with some key
// differences:
// * Local activity is scheduled and run by the workflow worker locally.
// * Local activity does not need Temporal server to schedule activity task and does not rely on activity worker.
// * No need to register local activity.
// * Local activity is for short living activities (usually finishes within seconds).
// * Local activity cannot heartbeat.
//
// Context can be used to pass the settings for this local activity.
// For now there is only one setting for timeout to be set:
//
// lao := LocalActivityOptions{
// ScheduleToCloseTimeout: 5 * time.Second,
// }
// ctx := WithLocalActivityOptions(ctx, lao)
//
// The timeout here should be relative shorter than the WorkflowTaskTimeout of the workflow. If you need a
// longer timeout, you probably should not use local activity and instead should use regular activity. Local activity is
// designed to be used for short living activities (usually finishes within seconds).
//
// Input args are the arguments that will to be passed to the local activity. The input args will be hand over directly
// to local activity function without serialization/deserialization because we don't need to pass the input across process
// boundary. However, the result will still go through serialization/deserialization because we need to record the result
// as history to temporal server so if the workflow crashes, a different worker can replay the history without running
// the local activity again.
//
// If the activity failed to complete then the future get error would indicate the failure.
// The error will be of type *ActivityError. It will have important activity information and actual error that caused
// activity failure. Use errors.Unwrap to get this error or errors.As to check it type which can be one of
// *ApplicationError, *TimeoutError, *CanceledError, or *PanicError.
//
// You can cancel the pending activity using context(workflow.WithCancel(ctx)) and that will fail the activity with
// *CanceledError set as cause for *ActivityError.
//
// ExecuteLocalActivity returns Future with local activity result or failure.
func ExecuteLocalActivity(ctx Context, activity interface{}, args ...interface{}) Future {
assertNotInReadOnlyState(ctx)
i := getWorkflowOutboundInterceptor(ctx)
env := getWorkflowEnvironment(ctx)
activityType, isMethod := getFunctionName(activity)
if alias, ok := env.GetRegistry().getActivityAlias(activityType); ok {
activityType = alias
}
var fn interface{}
if _, ok := activity.(string); ok {
fn = nil
} else {
fn = activity
}
localCtx := &localActivityContext{
fn: fn,
isMethod: isMethod,
}
ctx = WithValue(ctx, localActivityFnContextKey, localCtx)
// Put header on context before executing
ctx = workflowContextWithNewHeader(ctx)
return i.ExecuteLocalActivity(ctx, activityType, args...)
}
func (wc *workflowEnvironmentInterceptor) ExecuteLocalActivity(ctx Context, typeName string, args ...interface{}) Future {
future, settable := newDecodeFuture(ctx, typeName)
envOptions := getWorkflowEnvOptions(ctx)
header, err := workflowHeaderPropagated(ctx, envOptions.ContextPropagators)
if err != nil {
settable.Set(nil, err)
return future
}
var activityFn interface{}
localCtx := ctx.Value(localActivityFnContextKey).(*localActivityContext)
if localCtx == nil {
panic("ExecuteLocalActivity: Expected context key " + localActivityFnContextKey + " is missing")
}
if localCtx.isMethod {
registry := getRegistryFromWorkflowContext(ctx)
activity, ok := registry.GetActivity(typeName)
// Uses registered function if found as the registration is required with a nil receiver.
// Calls function directly if not registered. It is to support legacy applications
// that called local activities using non nil receiver.
if ok {
activityFn = activity.GetFunction()
} else {
if err := validateFunctionArgs(localCtx.fn, args, false); err != nil {
settable.Set(nil, err)
return future
}
activityFn = localCtx.fn
}
} else if localCtx.fn == nil {
registry := getRegistryFromWorkflowContext(ctx)
activityType, err := getValidatedActivityFunction(typeName, args, registry)
if err != nil {
settable.Set(nil, err)
return future
}
activity, ok := registry.GetActivity(activityType.Name)
if ok {
activityFn = activity.GetFunction()
} else if IsReplayNamespace(GetWorkflowInfo(ctx).Namespace) {
// When running the replayer (but not necessarily during all replays), we
// don't require the activities to be registered, so use a dummy function
activityFn = func(context.Context) error { panic("dummy replayer function") }
} else {
settable.Set(nil, fmt.Errorf("local activity %s is not registered by the worker", activityType.Name))
return future
}
} else {
if err := validateFunctionArgs(localCtx.fn, args, false); err != nil {
settable.Set(nil, err)
return future
}
activityFn = localCtx.fn
}
options, err := getValidatedLocalActivityOptions(ctx)
if err != nil {
settable.Set(nil, err)
return future
}
params := &ExecuteLocalActivityParams{
ExecuteLocalActivityOptions: *options,
ActivityFn: activityFn,
ActivityType: typeName,
InputArgs: args,
WorkflowInfo: GetWorkflowInfo(ctx),
DataConverter: getDataConverterFromWorkflowContext(ctx),
ScheduledTime: Now(ctx), // initial scheduled time
Header: header,
Attempt: 1, // Attempts always start at one
}
Go(ctx, func(ctx Context) {
for {
f := wc.scheduleLocalActivity(ctx, params)
var result *commonpb.Payloads
err := f.Get(ctx, &result)
if retryErr, ok := err.(*needRetryError); ok && retryErr.Backoff > 0 {
// Backoff for retry
_ = Sleep(ctx, retryErr.Backoff)
// increase the attempt, and retry the local activity
params.Attempt = retryErr.Attempt + 1
continue
}
// not more retry, return whatever is received.
settable.Set(result, err)
return
}
})
return future
}
type needRetryError struct {
Backoff time.Duration
Attempt int32
}
func (e *needRetryError) Error() string {
return fmt.Sprintf("Retry backoff: %v, Attempt: %v", e.Backoff, e.Attempt)
}
func (wc *workflowEnvironmentInterceptor) scheduleLocalActivity(ctx Context, params *ExecuteLocalActivityParams) Future {
f := &futureImpl{channel: NewChannel(ctx).(*channelImpl)}
ctxDone, cancellable := ctx.Done().(*channelImpl)
cancellationCallback := &receiveCallback{}
la := wc.env.ExecuteLocalActivity(*params, func(lar *LocalActivityResultWrapper) {
if cancellable {
// future is done, we don't need cancellation anymore
ctxDone.removeReceiveCallback(cancellationCallback)
}
if lar.Err == nil || IsCanceledError(lar.Err) || lar.Backoff <= 0 {
f.Set(lar.Result, lar.Err)
return
}
// set retry error, and it will be handled by workflow.ExecuteLocalActivity().
f.Set(nil, &needRetryError{Backoff: lar.Backoff, Attempt: lar.Attempt})
})
if cancellable {
cancellationCallback.fn = func(v interface{}, more bool) bool {
assertNotInReadOnlyStateCancellation(ctx)
if ctx.Err() == ErrCanceled {
getWorkflowEnvironment(ctx).RequestCancelLocalActivity(la)
}
return false
}
_, ok, more := ctxDone.receiveAsyncImpl(cancellationCallback)
if ok || !more {
cancellationCallback.fn(nil, more)
}
}
return f
}
// ExecuteChildWorkflow requests child workflow execution in the context of a workflow.
// Context can be used to pass the settings for the child workflow.
// For example: task queue that this child workflow should be routed, timeouts that need to be configured.
// Use ChildWorkflowOptions to pass down the options.
//
// cwo := ChildWorkflowOptions{
// WorkflowExecutionTimeout: 10 * time.Minute,
// WorkflowTaskTimeout: time.Minute,
// }
// ctx := WithChildWorkflowOptions(ctx, cwo)
//
// Input childWorkflow is either a workflow name or a workflow function that is getting scheduled.
// Input args are the arguments that need to be passed to the child workflow function represented by childWorkflow.
//
// If the child workflow failed to complete then the future get error would indicate the failure.
// The error will be of type *ChildWorkflowExecutionError. It will have important child workflow information and actual error that caused
// child workflow failure. Use errors.Unwrap to get this error or errors.As to check it type which can be one of
// *ApplicationError, *TimeoutError, or *CanceledError.
//
// You can cancel the pending child workflow using context(workflow.WithCancel(ctx)) and that will fail the workflow with
// *CanceledError set as cause for *ChildWorkflowExecutionError.
//
// ExecuteChildWorkflow returns ChildWorkflowFuture.
func ExecuteChildWorkflow(ctx Context, childWorkflow interface{}, args ...interface{}) ChildWorkflowFuture {
assertNotInReadOnlyState(ctx)
i := getWorkflowOutboundInterceptor(ctx)
env := getWorkflowEnvironment(ctx)
workflowType, err := getWorkflowFunctionName(env.GetRegistry(), childWorkflow)
if err != nil {
panic(err)
}
// Put header on context before executing
ctx = workflowContextWithNewHeader(ctx)
return i.ExecuteChildWorkflow(ctx, workflowType, args...)
}
func (wc *workflowEnvironmentInterceptor) ExecuteChildWorkflow(ctx Context, childWorkflowType string, args ...interface{}) ChildWorkflowFuture {
mainFuture, mainSettable := newDecodeFuture(ctx, childWorkflowType)
executionFuture, executionSettable := NewFuture(ctx)
result := &childWorkflowFutureImpl{
decodeFutureImpl: mainFuture.(*decodeFutureImpl),
executionFuture: executionFuture.(*futureImpl),
}
// Immediately return if the context has an error without spawning the child workflow
if ctx.Err() != nil {
executionSettable.Set(nil, ctx.Err())
mainSettable.Set(nil, ctx.Err())
return result
}
workflowOptionsFromCtx := getWorkflowEnvOptions(ctx)
dc := WithWorkflowContext(ctx, workflowOptionsFromCtx.DataConverter)
env := getWorkflowEnvironment(ctx)
wfType, input, err := getValidatedWorkflowFunction(childWorkflowType, args, dc, env.GetRegistry())