-
Notifications
You must be signed in to change notification settings - Fork 43
/
executor.go
731 lines (575 loc) · 22.5 KB
/
executor.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
package workflow
import (
"context"
"errors"
"fmt"
"log/slog"
"reflect"
"slices"
"testing"
"github.com/benbjohnson/clock"
"github.com/cschleiden/go-workflows/backend"
"github.com/cschleiden/go-workflows/backend/converter"
"github.com/cschleiden/go-workflows/backend/history"
"github.com/cschleiden/go-workflows/backend/metadata"
"github.com/cschleiden/go-workflows/backend/payload"
"github.com/cschleiden/go-workflows/core"
"github.com/cschleiden/go-workflows/internal/command"
"github.com/cschleiden/go-workflows/internal/contextvalue"
"github.com/cschleiden/go-workflows/internal/continueasnew"
"github.com/cschleiden/go-workflows/internal/log"
"github.com/cschleiden/go-workflows/internal/sync"
"github.com/cschleiden/go-workflows/internal/workflowerrors"
"github.com/cschleiden/go-workflows/internal/workflowstate"
"github.com/cschleiden/go-workflows/internal/workflowtracer"
"github.com/cschleiden/go-workflows/registry"
wf "github.com/cschleiden/go-workflows/workflow"
"go.opentelemetry.io/otel/trace"
)
type ExecutionResult struct {
State core.WorkflowInstanceState
Executed []*history.Event
ActivityEvents []*history.Event
TimerEvents []*history.Event
WorkflowEvents []history.WorkflowEvent
}
type WorkflowHistoryProvider interface {
GetWorkflowInstanceHistory(ctx context.Context, instance *core.WorkflowInstance, lastSequenceID *int64) ([]*history.Event, error)
}
type WorkflowExecutor interface {
ExecuteTask(ctx context.Context, t *backend.WorkflowTask) (*ExecutionResult, error)
Close()
}
type executor struct {
registry *registry.Registry
historyProvider WorkflowHistoryProvider
workflow *workflow
workflowName string
workflowTracer *workflowtracer.WorkflowTracer
workflowState *workflowstate.WfState
workflowCtx sync.Context
workflowCtxCancel sync.CancelFunc
cv converter.Converter
clock clock.Clock
logger *slog.Logger
tracer trace.Tracer
lastSequenceID int64
parentSpan trace.Span
}
func NewExecutor(
logger *slog.Logger,
tracer trace.Tracer,
registry *registry.Registry,
cv converter.Converter,
propagators []wf.ContextPropagator,
historyProvider WorkflowHistoryProvider,
instance *core.WorkflowInstance,
metadata *metadata.WorkflowMetadata,
clock clock.Clock,
) (WorkflowExecutor, error) {
s := workflowstate.NewWorkflowState(instance, logger, clock)
wfTracer := workflowtracer.New(tracer)
wfCtx := sync.Background()
wfCtx = contextvalue.WithConverter(wfCtx, cv)
wfCtx = workflowtracer.WithWorkflowTracer(wfCtx, wfTracer)
wfCtx = workflowstate.WithWorkflowState(wfCtx, s)
wfCtx = sync.WithValue(wfCtx, contextvalue.PropagatorsCtxKey, propagators)
wfCtx, cancel := sync.WithCancel(wfCtx)
for _, propagator := range propagators {
var err error
wfCtx, err = propagator.ExtractToWorkflow(wfCtx, metadata)
if err != nil {
return nil, fmt.Errorf("extracting context: %w", err)
}
}
logger = logger.With(
slog.String(log.InstanceIDKey, instance.InstanceID),
slog.String(log.ExecutionIDKey, instance.ExecutionID),
)
// Get span from the workflow context, set by the default context propagator
parentSpan := workflowtracer.SpanFromContext(wfCtx)
return &executor{
registry: registry,
historyProvider: historyProvider,
workflowTracer: wfTracer,
workflowState: s,
workflowCtx: wfCtx,
workflowCtxCancel: cancel,
cv: cv,
clock: clock,
logger: logger,
tracer: tracer,
parentSpan: parentSpan,
}, nil
}
func (e *executor) ExecuteTask(ctx context.Context, t *backend.WorkflowTask) (*ExecutionResult, error) {
logger := e.logger.With(
log.TaskIDKey, t.ID,
)
logger.Debug("Executing workflow task", log.TaskLastSequenceIDKey, t.LastSequenceID)
if t.WorkflowInstanceState == core.WorkflowInstanceStateFinished {
// This could happen if signals are delivered after the workflow is finished
logger.Error("Received workflow task for finished workflow instance, discarding events")
// Log events that caused this task to be scheduled
for _, event := range t.NewEvents {
logger.Debug("Discarded event:",
log.EventIDKey, event.ID,
log.EventTypeKey, event.Type.String(),
log.ScheduleEventIDKey, event.ScheduleEventID)
}
return &ExecutionResult{
State: core.WorkflowInstanceStateFinished,
}, nil
}
skipNewEvents := false
if t.LastSequenceID > e.lastSequenceID {
logger.Debug("Task has newer history than current state, fetching and replaying history",
log.TaskSequenceIDKey, t.LastSequenceID,
log.LocalSequenceIDKey, e.lastSequenceID)
h, err := e.historyProvider.GetWorkflowInstanceHistory(ctx, t.WorkflowInstance, &e.lastSequenceID)
if err != nil {
return nil, fmt.Errorf("getting workflow history: %w", err)
}
if err := e.replayHistory(h); err != nil {
logger.Error("Error while replaying history", "error", err)
// Fail workflow with an error. Skip executing new events, but still go through the commands
e.workflowCompleted(nil, err)
skipNewEvents = true
// With an error occurred during replay, we need to ensure new events don't get duplicate sequence ids
e.lastSequenceID = t.LastSequenceID
} else if t.LastSequenceID != e.lastSequenceID {
logger.Error("After replaying history, task still has newer history than current state",
log.TaskSequenceIDKey, t.LastSequenceID,
log.LocalSequenceIDKey, e.lastSequenceID)
return nil, errors.New("even after fetching history and replaying history executor state does not match task")
}
} else if t.LastSequenceID < e.lastSequenceID {
return nil, fmt.Errorf("task has older history than current state, cannot execute")
}
// Always add a WorkflowTaskStarted event before executing new tasks
toExecute := []*history.Event{e.createNewEvent(history.EventType_WorkflowTaskStarted, &history.WorkflowTaskStartedAttributes{})}
executedEvents := toExecute
toExecute = append(toExecute, t.NewEvents...)
// Execute new events received from the backend
if !skipNewEvents {
var err error
executedEvents, err = e.executeNewEvents(toExecute)
if err != nil {
logger.Error("Error while executing new events", "error", err)
// Transition workflow to error state
e.workflowCompleted(nil, err)
}
}
// Process any commands added while executing new events
state := core.WorkflowInstanceStateActive
newCommandEvents := make([]*history.Event, 0)
activityEvents := make([]*history.Event, 0)
timerEvents := make([]*history.Event, 0)
workflowEvents := make([]history.WorkflowEvent, 0)
for _, c := range e.workflowState.Commands() {
if c.State() == command.CommandState_Done {
continue
}
r := c.Execute(e.clock)
if r == nil {
continue
}
if r.State > state {
state = r.State
}
newCommandEvents = append(newCommandEvents, r.Events...)
activityEvents = append(activityEvents, r.ActivityEvents...)
timerEvents = append(timerEvents, r.TimerEvents...)
workflowEvents = append(workflowEvents, r.WorkflowEvents...)
}
// Events from commands don't have to be executed again, add them to the executed events.
executedEvents = append(executedEvents, newCommandEvents...)
// Set SequenceIDs for all executed events
for i := range executedEvents {
executedEvents[i].SequenceID = e.nextSequenceID()
}
logger.Debug("Finished workflow task",
log.ExecutedEventsKey, len(executedEvents),
log.TaskLastSequenceIDKey, e.lastSequenceID,
log.WorkflowInstanceStateKey, state,
)
return &ExecutionResult{
State: state,
Executed: executedEvents,
ActivityEvents: activityEvents,
TimerEvents: timerEvents,
WorkflowEvents: workflowEvents,
}, nil
}
func (e *executor) replayHistory(h []*history.Event) error {
e.workflowState.SetReplaying(true)
for _, event := range h {
if event.SequenceID < e.lastSequenceID {
e.logger.Error("history has older events than current state")
return errors.New("history has older events than current state")
}
if err := e.executeEvent(event); err != nil {
return err
}
e.lastSequenceID = event.SequenceID
}
return nil
}
func (e *executor) executeNewEvents(newEvents []*history.Event) ([]*history.Event, error) {
e.workflowState.SetReplaying(false)
for i, event := range newEvents {
if err := e.executeEvent(event); err != nil {
return newEvents[:i], err
}
}
if e.workflow.Completed() {
if e.workflowState.HasPendingFutures() {
var pending []string
pf := e.workflowState.PendingFutureNames()
for id, name := range pf {
pending = append(pending, fmt.Sprintf("%d-%s", id, name))
}
slices.Sort(pending)
if testing.Testing() {
panic(fmt.Sprintf("workflow completed, but there are still pending futures: %s", pending))
}
return newEvents, fmt.Errorf("workflow completed, but there are still pending futures: %s", pending)
}
if canErr, ok := e.workflow.Error().(*continueasnew.Error); ok {
e.workflowRestarted(e.workflow.Result(), canErr)
} else {
e.workflowCompleted(e.workflow.Result(), e.workflow.Error())
}
}
return newEvents, nil
}
func (e *executor) Close() {
if e.workflow != nil {
e.logger.Debug("Stopping workflow executor", log.InstanceIDKey, e.workflowState.Instance().InstanceID)
// End workflow if running to prevent leaking goroutines
e.workflow.Close()
}
}
func (e *executor) executeEvent(event *history.Event) error {
fields := []any{
log.InstanceIDKey, e.workflowState.Instance().InstanceID,
log.EventIDKey, event.ID,
log.SeqIDKey, event.SequenceID,
log.EventTypeKey, event.Type,
log.ScheduleEventIDKey, event.ScheduleEventID,
log.IsReplayingKey, e.workflowState.Replaying(),
}
attributesFields := getAttributesLoggingFields(event)
if attributesFields != nil {
fields = append(fields, attributesFields...)
}
e.logger.Debug("Executing event", fields...)
var err error
switch event.Type {
case history.EventType_WorkflowExecutionStarted:
err = e.handleWorkflowExecutionStarted(event.Attributes.(*history.ExecutionStartedAttributes))
case history.EventType_WorkflowExecutionFinished:
// Ignore
case history.EventType_WorkflowExecutionCanceled:
err = e.handleWorkflowCanceled()
case history.EventType_WorkflowTaskStarted:
err = e.handleWorkflowTaskStarted(event, event.Attributes.(*history.WorkflowTaskStartedAttributes))
case history.EventType_ActivityScheduled:
err = e.handleActivityScheduled(event, event.Attributes.(*history.ActivityScheduledAttributes))
case history.EventType_ActivityFailed:
err = e.handleActivityFailed(event, event.Attributes.(*history.ActivityFailedAttributes))
case history.EventType_ActivityCompleted:
err = e.handleActivityCompleted(event, event.Attributes.(*history.ActivityCompletedAttributes))
case history.EventType_TimerScheduled:
err = e.handleTimerScheduled(event, event.Attributes.(*history.TimerScheduledAttributes))
case history.EventType_TimerFired:
err = e.handleTimerFired(event, event.Attributes.(*history.TimerFiredAttributes))
case history.EventType_TimerCanceled:
err = e.handleTimerCanceled(event, event.Attributes.(*history.TimerCanceledAttributes))
case history.EventType_SignalReceived:
err = e.handleSignalReceived(event, event.Attributes.(*history.SignalReceivedAttributes))
case history.EventType_SideEffectResult:
err = e.handleSideEffectResult(event, event.Attributes.(*history.SideEffectResultAttributes))
case history.EventType_SubWorkflowScheduled:
err = e.handleSubWorkflowScheduled(event, event.Attributes.(*history.SubWorkflowScheduledAttributes))
case history.EventType_SubWorkflowCancellationRequested:
err = e.handleSubWorkflowCancellationRequest(event, event.Attributes.(*history.SubWorkflowCancellationRequestedAttributes))
case history.EventType_SubWorkflowFailed:
err = e.handleSubWorkflowFailed(event, event.Attributes.(*history.SubWorkflowFailedAttributes))
case history.EventType_SubWorkflowCompleted:
err = e.handleSubWorkflowCompleted(event, event.Attributes.(*history.SubWorkflowCompletedAttributes))
default:
return fmt.Errorf("unknown event type: %v", event.Type)
}
return err
}
func (e *executor) handleWorkflowExecutionStarted(a *history.ExecutionStartedAttributes) error {
e.workflowName = a.Name
wfFn, err := e.registry.GetWorkflow(a.Name)
if err != nil {
return fmt.Errorf("workflow %s not found", a.Name)
}
e.workflow = NewWorkflow(reflect.ValueOf(wfFn))
return e.workflow.Execute(e.workflowCtx, a.Inputs)
}
func (e *executor) handleWorkflowCanceled() error {
e.workflowCtxCancel()
return e.workflow.Continue()
}
func (e *executor) handleWorkflowTaskStarted(event *history.Event, a *history.WorkflowTaskStartedAttributes) error {
e.workflowState.SetTime(event.Timestamp)
return nil
}
func (e *executor) handleActivityScheduled(event *history.Event, a *history.ActivityScheduledAttributes) error {
c := e.workflowState.CommandByScheduleEventID(event.ScheduleEventID)
if c == nil {
return fmt.Errorf("previous workflow execution scheduled an activity which could not be found")
}
sac, ok := c.(*command.ScheduleActivityCommand)
if !ok {
return fmt.Errorf("previous workflow execution scheduled an activity, not: %v", c.Type())
}
// Ensure the same activity was scheduled again
if a.Name != sac.Name {
return fmt.Errorf("previous workflow execution scheduled different type of activity: %s, %s", a.Name, sac.Name)
}
c.Commit()
return nil
}
func (e *executor) handleActivityCompleted(event *history.Event, a *history.ActivityCompletedAttributes) error {
f, ok := e.workflowState.FutureByScheduleEventID(event.ScheduleEventID)
if !ok {
return fmt.Errorf("could not find pending future for activity completion")
}
err := f.Set(a.Result, nil)
if err != nil {
return fmt.Errorf("setting activity completed result: %w", err)
}
e.workflowState.RemoveFuture(event.ScheduleEventID)
c := e.workflowState.CommandByScheduleEventID(event.ScheduleEventID)
if c == nil {
return fmt.Errorf("previous workflow execution scheduled an activity which could not be found")
}
sac, ok := c.(*command.ScheduleActivityCommand)
if !ok {
return fmt.Errorf("previous workflow execution scheduled an activity, not: %v", c.Type())
}
sac.Done()
return e.workflow.Continue()
}
func (e *executor) handleActivityFailed(event *history.Event, a *history.ActivityFailedAttributes) error {
f, ok := e.workflowState.FutureByScheduleEventID(event.ScheduleEventID)
if !ok {
return errors.New("no pending future for activity failed event")
}
actErr := workflowerrors.ToError(a.Error)
if err := f.Set(nil, actErr); err != nil {
return fmt.Errorf("setting activity failed result: %w", err)
}
e.workflowState.RemoveFuture(event.ScheduleEventID)
c := e.workflowState.CommandByScheduleEventID(event.ScheduleEventID)
if c == nil {
return fmt.Errorf("previous workflow execution scheduled an activity which could not be found")
}
sac, ok := c.(*command.ScheduleActivityCommand)
if !ok {
return fmt.Errorf("previous workflow execution scheduled an activity, not: %v", c.Type())
}
sac.Done()
return e.workflow.Continue()
}
func (e *executor) handleTimerScheduled(event *history.Event, a *history.TimerScheduledAttributes) error {
c := e.workflowState.CommandByScheduleEventID(event.ScheduleEventID)
if c == nil {
return fmt.Errorf("previous workflow execution scheduled a timer")
}
if _, ok := c.(*command.ScheduleTimerCommand); !ok {
return fmt.Errorf("previous workflow execution scheduled a timer, not: %v", c.Type())
}
c.Commit()
return nil
}
func (e *executor) handleTimerFired(event *history.Event, a *history.TimerFiredAttributes) error {
f, ok := e.workflowState.FutureByScheduleEventID(event.ScheduleEventID)
if !ok {
// Timer already canceled ignore
return nil
}
if err := f.Set(nil, nil); err != nil {
return fmt.Errorf("setting timer fired result: %w", err)
}
e.workflowState.RemoveFuture(event.ScheduleEventID)
c := e.workflowState.CommandByScheduleEventID(event.ScheduleEventID)
if c == nil {
return fmt.Errorf("no command found for timer fired event")
}
if _, ok := c.(*command.ScheduleTimerCommand); !ok {
return fmt.Errorf("schedule timer command not found, instead: %v", c.Type())
}
c.Done()
return e.workflow.Continue()
}
func (e *executor) handleTimerCanceled(event *history.Event, a *history.TimerCanceledAttributes) error {
c := e.workflowState.CommandByScheduleEventID(event.ScheduleEventID)
if c == nil {
return fmt.Errorf("previous workflow execution canceled a timer")
}
stc, ok := c.(*command.ScheduleTimerCommand)
if !ok {
return fmt.Errorf("previous workflow execution canceled a timer, not: %v", c.Type())
}
stc.HandleCancel()
// Cancel the pending future
f, ok := e.workflowState.FutureByScheduleEventID(event.ScheduleEventID)
if !ok {
// Timer already canceled ignore
return nil
}
if err := f.Set(nil, sync.Canceled); err != nil {
return fmt.Errorf("setting timer canceled result: %w", err)
}
e.workflowState.RemoveFuture(event.ScheduleEventID)
return e.workflow.Continue()
}
func (e *executor) handleSubWorkflowScheduled(event *history.Event, a *history.SubWorkflowScheduledAttributes) error {
c := e.workflowState.CommandByScheduleEventID(event.ScheduleEventID)
if c == nil {
return fmt.Errorf("previous workflow execution scheduled a sub workflow")
}
sswc, ok := c.(*command.ScheduleSubWorkflowCommand)
if !ok {
return fmt.Errorf("previous workflow execution scheduled a sub workflow, not: %v", c.Type())
}
if a.Name != sswc.Name {
return fmt.Errorf("previous workflow execution scheduled different type of sub workflow: %s, %s", a.Name, sswc.Name)
}
// If we are replaying this event, the command will have generated a new instance ID. Ensure we use the same one as
// when the command was originally committed.
sswc.Instance = a.SubWorkflowInstance
c.Commit()
return nil
}
func (e *executor) handleSubWorkflowCancellationRequest(event *history.Event, a *history.SubWorkflowCancellationRequestedAttributes) error {
c := e.workflowState.CommandByScheduleEventID(event.ScheduleEventID)
if c == nil {
return fmt.Errorf("previous workflow execution cancelled a sub-workflow execution")
}
sswc, ok := c.(*command.ScheduleSubWorkflowCommand)
if !ok {
return fmt.Errorf("previous workflow execution cancelled a sub-workflow execution, not: %v", c.Type())
}
sswc.HandleCancel()
return e.workflow.Continue()
}
func (e *executor) handleSubWorkflowFailed(event *history.Event, a *history.SubWorkflowFailedAttributes) error {
f, ok := e.workflowState.FutureByScheduleEventID(event.ScheduleEventID)
if !ok {
return errors.New("no pending future found for sub workflow failed event")
}
wfErr := workflowerrors.ToError(a.Error)
if err := f.Set(nil, wfErr); err != nil {
return fmt.Errorf("setting sub workflow failed result: %w", err)
}
e.workflowState.RemoveFuture(event.ScheduleEventID)
c := e.workflowState.CommandByScheduleEventID(event.ScheduleEventID)
if c == nil {
return fmt.Errorf("previous workflow execution scheduled a sub-workflow execution")
}
if _, ok := c.(*command.ScheduleSubWorkflowCommand); !ok {
return fmt.Errorf("previous workflow execution cancelled a sub-workflow execution, not: %v", c.Type())
}
c.Done()
return e.workflow.Continue()
}
func (e *executor) handleSubWorkflowCompleted(event *history.Event, a *history.SubWorkflowCompletedAttributes) error {
f, ok := e.workflowState.FutureByScheduleEventID(event.ScheduleEventID)
if !ok {
return errors.New("no pending future found for sub workflow completed event")
}
if err := f.Set(a.Result, nil); err != nil {
return fmt.Errorf("setting sub workflow completed result: %w", err)
}
e.workflowState.RemoveFuture(event.ScheduleEventID)
c := e.workflowState.CommandByScheduleEventID(event.ScheduleEventID)
if c == nil {
return fmt.Errorf("previous workflow execution cancelled a sub-workflow execution")
}
if _, ok := c.(*command.ScheduleSubWorkflowCommand); !ok {
return fmt.Errorf("previous workflow execution cancelled a sub-workflow execution, not: %v", c.Type())
}
c.Done()
return e.workflow.Continue()
}
func (e *executor) handleSignalReceived(event *history.Event, a *history.SignalReceivedAttributes) error {
// Send signal to workflow channel
workflowstate.ReceiveSignal(e.workflowState, a.Name, a.Arg)
return e.workflow.Continue()
}
func (e *executor) handleSideEffectResult(event *history.Event, a *history.SideEffectResultAttributes) error {
c := e.workflowState.CommandByScheduleEventID(event.ScheduleEventID)
if c == nil {
return fmt.Errorf("previous workflow execution scheduled a side effect")
}
sec, ok := c.(*command.SideEffectCommand)
if !ok {
return fmt.Errorf("previous workflow execution scheduled a side effect, not: %v", c.Type())
}
sec.Done()
f, ok := e.workflowState.FutureByScheduleEventID(event.ScheduleEventID)
if !ok {
return errors.New("no pending future found for side effect result event")
}
if err := f.Set(a.Result, nil); err != nil {
return fmt.Errorf("setting side effect result result: %w", err)
}
e.workflowState.RemoveFuture(event.ScheduleEventID)
return e.workflow.Continue()
}
func (e *executor) workflowCompleted(result payload.Payload, wfErr error) {
eventId := e.workflowState.GetNextScheduleEventID()
cmd := command.NewCompleteWorkflowCommand(eventId, e.workflowState.Instance(), result, workflowerrors.FromError(wfErr))
e.workflowState.AddCommand(cmd)
}
func (e *executor) workflowRestarted(result payload.Payload, continueAsNew *continueasnew.Error) {
eventId := e.workflowState.GetNextScheduleEventID()
cmd := command.NewContinueAsNewCommand(eventId, e.workflowState.Instance(), result, e.workflowName, continueAsNew.Metadata, continueAsNew.Inputs)
e.workflowState.AddCommand(cmd)
}
func (e *executor) nextSequenceID() int64 {
e.lastSequenceID++
return e.lastSequenceID
}
func (e *executor) createNewEvent(eventType history.EventType, attributes interface{}, opts ...history.HistoryEventOption) *history.Event {
return history.NewPendingEvent(
e.clock.Now(),
eventType,
attributes,
opts...,
)
}
func getAttributesLoggingFields(event *history.Event) []any {
switch event.Type {
case history.EventType_WorkflowExecutionStarted:
attributes := event.Attributes.(*history.ExecutionStartedAttributes)
return []any{
log.WorkflowNameKey, attributes.Name,
}
case history.EventType_SubWorkflowScheduled:
attributes := event.Attributes.(*history.SubWorkflowScheduledAttributes)
return []any{
log.WorkflowNameKey, attributes.Name,
}
case history.EventType_SignalReceived:
attributes := event.Attributes.(*history.SignalReceivedAttributes)
return []any{
log.SignalNameKey, attributes.Name,
}
case history.EventType_ActivityScheduled:
attributes := event.Attributes.(*history.ActivityScheduledAttributes)
return []any{
log.ActivityNameKey, attributes.Name,
}
default:
return nil
}
}