/
task_generator.go
670 lines (579 loc) · 23.3 KB
/
task_generator.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
// 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.
//go:generate mockgen -copyright_file ../../../LICENSE -package $GOPACKAGE -source $GOFILE -destination task_generator_mock.go
package workflow
import (
"fmt"
"time"
enumspb "go.temporal.io/api/enums/v1"
historypb "go.temporal.io/api/history/v1"
"go.temporal.io/api/serviceerror"
enumsspb "go.temporal.io/server/api/enums/v1"
"go.temporal.io/server/common/archiver"
"go.temporal.io/server/common/backoff"
"go.temporal.io/server/common/namespace"
"go.temporal.io/server/common/persistence/versionhistory"
"go.temporal.io/server/common/primitives/timestamp"
"go.temporal.io/server/service/history/configs"
"go.temporal.io/server/service/history/tasks"
)
type (
TaskGenerator interface {
GenerateWorkflowStartTasks(
startEvent *historypb.HistoryEvent,
) error
GenerateWorkflowCloseTasks(
// TODO: remove closeEvent parameter
// when deprecating the backward compatible logic
// for getting close time from close event.
closeEvent *historypb.HistoryEvent,
deleteAfterClose bool,
) error
// GenerateDeleteHistoryEventTask adds a tasks.DeleteHistoryEventTask to the mutable state.
// This task is used to delete the history events of the workflow execution after the retention period expires.
// If workflowDataAlreadyArchived is true, then the workflow data is already archived,
// so we can delete the history immediately. Otherwise, we need to archive the history first before we can
// safely delete it.
GenerateDeleteHistoryEventTask(closeTime time.Time, workflowDataAlreadyArchived bool) error
GenerateDeleteExecutionTask() (*tasks.DeleteExecutionTask, error)
GenerateRecordWorkflowStartedTasks(
startEvent *historypb.HistoryEvent,
) error
GenerateDelayedWorkflowTasks(
startEvent *historypb.HistoryEvent,
) error
GenerateScheduleWorkflowTaskTasks(
workflowTaskScheduledEventID int64,
) error
GenerateStartWorkflowTaskTasks(
workflowTaskScheduledEventID int64,
) error
GenerateActivityTasks(
event *historypb.HistoryEvent,
) error
GenerateActivityRetryTasks(
activityScheduledEventID int64,
) error
GenerateChildWorkflowTasks(
event *historypb.HistoryEvent,
) error
GenerateRequestCancelExternalTasks(
event *historypb.HistoryEvent,
) error
GenerateSignalExternalTasks(
event *historypb.HistoryEvent,
) error
GenerateUpsertVisibilityTask() error
GenerateWorkflowResetTasks() error
// these 2 APIs should only be called when mutable state transaction is being closed
GenerateActivityTimerTasks() error
GenerateUserTimerTasks() error
// replication tasks
GenerateHistoryReplicationTasks(
branchToken []byte,
events []*historypb.HistoryEvent,
) error
GenerateMigrationTasks() (tasks.Task, error)
}
TaskGeneratorImpl struct {
namespaceRegistry namespace.Registry
mutableState MutableState
config *configs.Config
archivalMetadata archiver.ArchivalMetadata
}
)
const defaultWorkflowRetention = 1 * 24 * time.Hour
var _ TaskGenerator = (*TaskGeneratorImpl)(nil)
type TaskGeneratorOption func(*TaskGeneratorImpl)
func NewTaskGenerator(
namespaceRegistry namespace.Registry,
mutableState MutableState,
config *configs.Config,
opts ...TaskGeneratorOption,
) *TaskGeneratorImpl {
r := &TaskGeneratorImpl{
namespaceRegistry: namespaceRegistry,
mutableState: mutableState,
config: config,
archivalMetadata: archiver.NewDisabledArchivalMetadata(),
}
for _, opt := range opts {
opt(r)
}
return r
}
// WithArchivalMetadata is used to set the archival metadata for the task generator to determine whether to generate
// archival tasks. The default value is disabled archival metadata.
func WithArchivalMetadata(metadata archiver.ArchivalMetadata) TaskGeneratorOption {
return func(r *TaskGeneratorImpl) {
r.archivalMetadata = metadata
}
}
func (r *TaskGeneratorImpl) GenerateWorkflowStartTasks(
startEvent *historypb.HistoryEvent,
) error {
startVersion := startEvent.GetVersion()
workflowRunExpirationTime := timestamp.TimeValue(r.mutableState.GetExecutionInfo().WorkflowRunExpirationTime)
if workflowRunExpirationTime.IsZero() {
// this mean infinite timeout
return nil
}
r.mutableState.AddTasks(&tasks.WorkflowTimeoutTask{
// TaskID is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
VisibilityTimestamp: workflowRunExpirationTime,
Version: startVersion,
})
return nil
}
func (r *TaskGeneratorImpl) GenerateWorkflowCloseTasks(
closeEvent *historypb.HistoryEvent,
deleteAfterClose bool,
) error {
currentVersion := r.mutableState.GetCurrentVersion()
closeExecutionTask := &tasks.CloseExecutionTask{
// TaskID, Visiblitytimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
Version: currentVersion,
DeleteAfterClose: deleteAfterClose,
}
closeTasks := []tasks.Task{
closeExecutionTask,
}
// To avoid race condition between visibility close and delete tasks, visibility close task is not created here.
// Also, there is no reason to schedule history retention task if workflow executions in about to be deleted.
// This will also save one call to visibility storage and one timer task creation.
if !deleteAfterClose {
// In most cases, the value of "now" is the closeEvent time.
// however this is not true for task refresh, where now is
// the refresh time, not the close time.
// Also can't always use close time as "now" when calling the method
// as it will be used as visibilityTimestamp for immediate task and
// for emitting task_latency_queue/load metric. If close time is used
// as now, upon refresh the latency metric may see a huge value.
// TODO: remove all "now" parameters from task generator interface,
// visibility timestamp for scheduled task should be calculated from event
// or execution info in mutable state. For immediate task, visibility timestamp
// should always be when the task is generated so that task_latency_queue/load
// truly measures only task processing/loading latency.
closeTasks = append(closeTasks,
&tasks.CloseExecutionVisibilityTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
Version: currentVersion,
},
)
if r.archivalQueueEnabled() {
retention, err := r.getRetention()
if err != nil {
return err
}
// We schedule the archival task for a random time in the near future to avoid sending a surge of tasks
// to the archival system at the same time
delay := backoff.FullJitter(r.config.ArchivalProcessorArchiveDelay())
if delay > retention {
delay = retention
}
// archiveTime is the time when the archival queue recognizes the ArchiveExecutionTask as ready-to-process
archiveTime := closeEvent.GetEventTime().Add(delay)
// We can skip visibility archival in the close execution task if we are using the durable archival flow.
// The visibility archival will be handled by the archival queue.
closeExecutionTask.CanSkipVisibilityArchival = true
task := &tasks.ArchiveExecutionTask{
// TaskID is set by the shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
VisibilityTimestamp: archiveTime,
Version: currentVersion,
}
closeTasks = append(closeTasks, task)
} else {
closeTime := timestamp.TimeValue(closeEvent.GetEventTime())
if err := r.GenerateDeleteHistoryEventTask(closeTime, false); err != nil {
return err
}
}
}
r.mutableState.AddTasks(closeTasks...)
return nil
}
// getRetention returns the retention period for this task generator's workflow execution.
// The retention period represents how long the workflow data should exist in primary storage after the workflow closes.
// If the workflow namespace is not found, the default retention period is returned.
// This method returns an error when the GetNamespaceByID call fails with anything other than
// serviceerror.NamespaceNotFound.
func (r *TaskGeneratorImpl) getRetention() (time.Duration, error) {
retention := defaultWorkflowRetention
executionInfo := r.mutableState.GetExecutionInfo()
namespaceEntry, err := r.namespaceRegistry.GetNamespaceByID(namespace.ID(executionInfo.NamespaceId))
switch err.(type) {
case nil:
retention = namespaceEntry.Retention()
case *serviceerror.NamespaceNotFound:
// namespace is not accessible, use default value above
default:
return 0, err
}
return retention, nil
}
// GenerateDeleteHistoryEventTask adds a task to delete all history events for a workflow execution.
// This method only adds the task to the mutable state object in memory; it does not write the task to the database.
// You must call shard.Context#AddTasks to notify the history engine of this task.
func (r *TaskGeneratorImpl) GenerateDeleteHistoryEventTask(closeTime time.Time, workflowDataAlreadyArchived bool) error {
retention, err := r.getRetention()
if err != nil {
return err
}
currentVersion := r.mutableState.GetCurrentVersion()
branchToken, err := r.mutableState.GetCurrentBranchToken()
if err != nil {
return err
}
retentionJitterDuration := backoff.FullJitter(r.config.RetentionTimerJitterDuration())
deleteTime := closeTime.Add(retention).Add(retentionJitterDuration)
r.mutableState.AddTasks(&tasks.DeleteHistoryEventTask{
// TaskID is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
VisibilityTimestamp: deleteTime,
Version: currentVersion,
BranchToken: branchToken,
WorkflowDataAlreadyArchived: workflowDataAlreadyArchived,
})
return nil
}
func (r *TaskGeneratorImpl) GenerateDeleteExecutionTask() (*tasks.DeleteExecutionTask, error) {
return &tasks.DeleteExecutionTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
}, nil
}
func (r *TaskGeneratorImpl) GenerateDelayedWorkflowTasks(
startEvent *historypb.HistoryEvent,
) error {
startVersion := startEvent.GetVersion()
// start time may not be "now" if method called by refresher
startTime := timestamp.TimeValue(startEvent.GetEventTime())
startAttr := startEvent.GetWorkflowExecutionStartedEventAttributes()
workflowTaskBackoffDuration := timestamp.DurationValue(startAttr.GetFirstWorkflowTaskBackoff())
executionTimestamp := startTime.Add(workflowTaskBackoffDuration)
var workflowBackoffType enumsspb.WorkflowBackoffType
switch startAttr.GetInitiator() {
case enumspb.CONTINUE_AS_NEW_INITIATOR_RETRY:
workflowBackoffType = enumsspb.WORKFLOW_BACKOFF_TYPE_RETRY
case enumspb.CONTINUE_AS_NEW_INITIATOR_CRON_SCHEDULE, enumspb.CONTINUE_AS_NEW_INITIATOR_WORKFLOW:
workflowBackoffType = enumsspb.WORKFLOW_BACKOFF_TYPE_CRON
default:
return serviceerror.NewInternal(fmt.Sprintf("unknown initiator: %v", startAttr.GetInitiator()))
}
r.mutableState.AddTasks(&tasks.WorkflowBackoffTimerTask{
// TaskID is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
VisibilityTimestamp: executionTimestamp,
WorkflowBackoffType: workflowBackoffType,
Version: startVersion,
})
return nil
}
func (r *TaskGeneratorImpl) GenerateRecordWorkflowStartedTasks(
startEvent *historypb.HistoryEvent,
) error {
startVersion := startEvent.GetVersion()
r.mutableState.AddTasks(&tasks.StartExecutionVisibilityTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
Version: startVersion,
})
return nil
}
func (r *TaskGeneratorImpl) GenerateScheduleWorkflowTaskTasks(
workflowTaskScheduledEventID int64,
) error {
workflowTask, ok := r.mutableState.GetWorkflowTaskInfo(
workflowTaskScheduledEventID,
)
if !ok {
return serviceerror.NewInternal(fmt.Sprintf("it could be a bug, cannot get pending workflow task: %v", workflowTaskScheduledEventID))
}
r.mutableState.AddTasks(&tasks.WorkflowTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
TaskQueue: workflowTask.TaskQueue.GetName(),
ScheduledEventID: workflowTask.ScheduledEventID,
Version: workflowTask.Version,
})
if r.mutableState.IsStickyTaskQueueEnabled() {
scheduledTime := timestamp.TimeValue(workflowTask.ScheduledTime)
scheduleToStartTimeout := timestamp.DurationValue(r.mutableState.GetExecutionInfo().StickyScheduleToStartTimeout)
r.mutableState.AddTasks(&tasks.WorkflowTaskTimeoutTask{
// TaskID is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
VisibilityTimestamp: scheduledTime.Add(scheduleToStartTimeout),
TimeoutType: enumspb.TIMEOUT_TYPE_SCHEDULE_TO_START,
EventID: workflowTask.ScheduledEventID,
ScheduleAttempt: workflowTask.Attempt,
Version: workflowTask.Version,
})
}
return nil
}
func (r *TaskGeneratorImpl) GenerateStartWorkflowTaskTasks(
workflowTaskScheduledEventID int64,
) error {
workflowTask, ok := r.mutableState.GetWorkflowTaskInfo(
workflowTaskScheduledEventID,
)
if !ok {
return serviceerror.NewInternal(fmt.Sprintf("it could be a bug, cannot get pending workflowTaskInfo: %v", workflowTaskScheduledEventID))
}
startedTime := timestamp.TimeValue(workflowTask.StartedTime)
workflowTaskTimeout := timestamp.DurationValue(workflowTask.WorkflowTaskTimeout)
r.mutableState.AddTasks(&tasks.WorkflowTaskTimeoutTask{
// TaskID is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
VisibilityTimestamp: startedTime.Add(workflowTaskTimeout),
TimeoutType: enumspb.TIMEOUT_TYPE_START_TO_CLOSE,
EventID: workflowTask.ScheduledEventID,
ScheduleAttempt: workflowTask.Attempt,
Version: workflowTask.Version,
})
return nil
}
func (r *TaskGeneratorImpl) GenerateActivityTasks(
event *historypb.HistoryEvent,
) error {
activityScheduledEventID := event.GetEventId()
activityInfo, ok := r.mutableState.GetActivityInfo(activityScheduledEventID)
if !ok {
return serviceerror.NewInternal(fmt.Sprintf("it could be a bug, cannot get pending activity: %v", activityScheduledEventID))
}
r.mutableState.AddTasks(&tasks.ActivityTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
TaskQueue: activityInfo.TaskQueue,
ScheduledEventID: activityInfo.ScheduledEventId,
Version: activityInfo.Version,
})
return nil
}
func (r *TaskGeneratorImpl) GenerateActivityRetryTasks(
activityScheduledEventID int64,
) error {
ai, ok := r.mutableState.GetActivityInfo(activityScheduledEventID)
if !ok {
return serviceerror.NewInternal(fmt.Sprintf("it could be a bug, cannot get pending activity: %v", activityScheduledEventID))
}
r.mutableState.AddTasks(&tasks.ActivityRetryTimerTask{
// TaskID is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
Version: ai.Version,
VisibilityTimestamp: *ai.ScheduledTime,
EventID: ai.ScheduledEventId,
Attempt: ai.Attempt,
})
return nil
}
func (r *TaskGeneratorImpl) GenerateChildWorkflowTasks(
event *historypb.HistoryEvent,
) error {
attr := event.GetStartChildWorkflowExecutionInitiatedEventAttributes()
childWorkflowScheduledEventID := event.GetEventId()
childWorkflowInfo, ok := r.mutableState.GetChildExecutionInfo(childWorkflowScheduledEventID)
if !ok {
return serviceerror.NewInternal(fmt.Sprintf("it could be a bug, cannot get pending child workflow: %v", childWorkflowScheduledEventID))
}
targetNamespaceID, err := r.getTargetNamespaceID(namespace.Name(attr.GetNamespace()), namespace.ID(attr.GetNamespaceId()))
if err != nil {
return err
}
r.mutableState.AddTasks(&tasks.StartChildExecutionTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
TargetNamespaceID: targetNamespaceID.String(),
TargetWorkflowID: childWorkflowInfo.StartedWorkflowId,
InitiatedEventID: childWorkflowInfo.InitiatedEventId,
Version: childWorkflowInfo.Version,
})
return nil
}
func (r *TaskGeneratorImpl) GenerateRequestCancelExternalTasks(
event *historypb.HistoryEvent,
) error {
attr := event.GetRequestCancelExternalWorkflowExecutionInitiatedEventAttributes()
scheduledEventID := event.GetEventId()
version := event.GetVersion()
targetWorkflowID := attr.GetWorkflowExecution().GetWorkflowId()
targetRunID := attr.GetWorkflowExecution().GetRunId()
targetChildOnly := attr.GetChildWorkflowOnly()
_, ok := r.mutableState.GetRequestCancelInfo(scheduledEventID)
if !ok {
return serviceerror.NewInternal(fmt.Sprintf("it could be a bug, cannot get pending request cancel external workflow: %v", scheduledEventID))
}
targetNamespaceID, err := r.getTargetNamespaceID(namespace.Name(attr.GetNamespace()), namespace.ID(attr.GetNamespaceId()))
if err != nil {
return err
}
r.mutableState.AddTasks(&tasks.CancelExecutionTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
TargetNamespaceID: targetNamespaceID.String(),
TargetWorkflowID: targetWorkflowID,
TargetRunID: targetRunID,
TargetChildWorkflowOnly: targetChildOnly,
InitiatedEventID: scheduledEventID,
Version: version,
})
return nil
}
func (r *TaskGeneratorImpl) GenerateSignalExternalTasks(
event *historypb.HistoryEvent,
) error {
attr := event.GetSignalExternalWorkflowExecutionInitiatedEventAttributes()
scheduledEventID := event.GetEventId()
version := event.GetVersion()
targetWorkflowID := attr.GetWorkflowExecution().GetWorkflowId()
targetRunID := attr.GetWorkflowExecution().GetRunId()
targetChildOnly := attr.GetChildWorkflowOnly()
_, ok := r.mutableState.GetSignalInfo(scheduledEventID)
if !ok {
return serviceerror.NewInternal(fmt.Sprintf("it could be a bug, cannot get pending signal external workflow: %v", scheduledEventID))
}
targetNamespaceID, err := r.getTargetNamespaceID(namespace.Name(attr.GetNamespace()), namespace.ID(attr.GetNamespaceId()))
if err != nil {
return err
}
r.mutableState.AddTasks(&tasks.SignalExecutionTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
TargetNamespaceID: targetNamespaceID.String(),
TargetWorkflowID: targetWorkflowID,
TargetRunID: targetRunID,
TargetChildWorkflowOnly: targetChildOnly,
InitiatedEventID: scheduledEventID,
Version: version,
})
return nil
}
func (r *TaskGeneratorImpl) GenerateUpsertVisibilityTask() error {
currentVersion := r.mutableState.GetCurrentVersion()
r.mutableState.AddTasks(&tasks.UpsertExecutionVisibilityTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
Version: currentVersion, // task processing does not check this version
})
return nil
}
func (r *TaskGeneratorImpl) GenerateWorkflowResetTasks() error {
currentVersion := r.mutableState.GetCurrentVersion()
r.mutableState.AddTasks(&tasks.ResetWorkflowTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
Version: currentVersion,
})
return nil
}
func (r *TaskGeneratorImpl) GenerateActivityTimerTasks() error {
_, err := r.getTimerSequence().CreateNextActivityTimer()
return err
}
func (r *TaskGeneratorImpl) GenerateUserTimerTasks() error {
_, err := r.getTimerSequence().CreateNextUserTimer()
return err
}
func (r *TaskGeneratorImpl) GenerateHistoryReplicationTasks(
branchToken []byte,
events []*historypb.HistoryEvent,
) error {
firstEvent := events[0]
lastEvent := events[len(events)-1]
if firstEvent.GetVersion() != lastEvent.GetVersion() {
return serviceerror.NewInternal("TaskGeneratorImpl encountered contradicting versions")
}
version := firstEvent.GetVersion()
r.mutableState.AddTasks(&tasks.HistoryReplicationTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
FirstEventID: firstEvent.GetEventId(),
NextEventID: lastEvent.GetEventId() + 1,
Version: version,
})
return nil
}
func (r *TaskGeneratorImpl) GenerateMigrationTasks() (tasks.Task, error) {
executionInfo := r.mutableState.GetExecutionInfo()
versionHistory, err := versionhistory.GetCurrentVersionHistory(executionInfo.GetVersionHistories())
if err != nil {
return nil, err
}
lastItem, err := versionhistory.GetLastVersionHistoryItem(versionHistory)
if err != nil {
return nil, err
}
if r.mutableState.GetExecutionState().State == enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED {
return &tasks.SyncWorkflowStateTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
Version: lastItem.GetVersion(),
}, nil
} else {
return &tasks.HistoryReplicationTask{
// TaskID, VisibilityTimestamp is set by shard
WorkflowKey: r.mutableState.GetWorkflowKey(),
FirstEventID: executionInfo.LastFirstEventId,
NextEventID: lastItem.GetEventId() + 1,
Version: lastItem.GetVersion(),
}, nil
}
}
func (r *TaskGeneratorImpl) getTimerSequence() TimerSequence {
return NewTimerSequence(r.mutableState)
}
func (r *TaskGeneratorImpl) getTargetNamespaceID(
targetNamespace namespace.Name,
targetNamespaceID namespace.ID,
) (namespace.ID, error) {
if !targetNamespaceID.IsEmpty() {
return targetNamespaceID, nil
}
// TODO (alex): Remove targetNamespace after NamespaceId is back filled. Backward compatibility: old events doesn't have targetNamespaceID.
if !targetNamespace.IsEmpty() {
targetNamespaceEntry, err := r.namespaceRegistry.GetNamespace(targetNamespace)
if err != nil {
return "", err
}
return targetNamespaceEntry.ID(), nil
}
return namespace.ID(r.mutableState.GetExecutionInfo().NamespaceId), nil
}
// archivalQueueEnabled returns true if archival is enabled for either history or visibility, and the archival queue
// itself is also enabled.
// For both history and visibility, we check that archival is enabled for both the cluster and the namespace.
func (r *TaskGeneratorImpl) archivalQueueEnabled() bool {
if !r.config.DurableArchivalEnabled() {
return false
}
namespaceEntry := r.mutableState.GetNamespaceEntry()
return r.archivalMetadata.GetHistoryConfig().ClusterConfiguredForArchival() &&
namespaceEntry.HistoryArchivalState().State == enumspb.ARCHIVAL_STATE_ENABLED ||
r.archivalMetadata.GetVisibilityConfig().ClusterConfiguredForArchival() &&
namespaceEntry.VisibilityArchivalState().State == enumspb.ARCHIVAL_STATE_ENABLED
}