Atlas › Test

TestRequestCancel_RespondWorkflowTaskCompleted_NoHeartBeat

Exact test identity: go.temporal.io/server/service/history/TestEngineSuite/TestRequestCancel_RespondWorkflowTaskCompleted_NoHeartBeat

Package
go.temporal.io/server/service/history
Suite / test hierarchy
TestEngineSuite/TestRequestCancel_RespondWorkflowTaskCompleted_NoHeartBeat
Test
TestRequestCancel_RespondWorkflowTaskCompleted_NoHeartBeat
Introduced at
TestRequestCancel_RespondWorkflowTaskCompleted_NoHeartBeat Frontier kind: Test frontier
Covered ranges
2345
Covered lines
10622
Covered files
270

Covered source

Expand a file to inspect source; the > gutter marks covered lines.

go.temporal.io/server/service/history/workflow/mutable_state_impl.go 1631 covered LOC · 454 ranges

Open complete file

298 runID string,
299 startTime time.Time,
300 > ) *MutableStateImpl { mutable_state_impl.go
301 >
302 > namespaceName := namespaceEntry.Name().String()
303 > logger = log.NewLazyLogger(logger, func() []tag.Tag {
304 > return []tag.Tag{ mutable_state_impl.go
305 > tag.WorkflowNamespace(namespaceName),
306 > tag.WorkflowID(workflowID),
307 > tag.WorkflowRunID(runID),
308 > }
309 > })
310
311 > s := &MutableStateImpl{ mutable_state_impl.go
312 > updateActivityInfos: make(map[int64]*persistencespb.ActivityInfo),
313 > pendingActivityTimerHeartbeats: make(map[int64]time.Time),
314 > pendingActivityInfoIDs: make(map[int64]*persistencespb.ActivityInfo),
315 > pendingActivityIDToEventID: make(map[string]int64),
316 > deleteActivityInfos: make(map[int64]struct{}),
317 > syncActivityTasks: make(map[int64]struct{}),
318 >
319 > pendingTimerInfoIDs: make(map[string]*persistencespb.TimerInfo),
320 > pendingTimerEventIDToID: make(map[int64]string),
321 > updateTimerInfos: make(map[string]*persistencespb.TimerInfo),
322 > deleteTimerInfos: make(map[string]struct{}),
323 >
324 > updateChildExecutionInfos: make(map[int64]*persistencespb.ChildExecutionInfo),
325 > pendingChildExecutionInfoIDs: make(map[int64]*persistencespb.ChildExecutionInfo),
326 > deleteChildExecutionInfos: make(map[int64]struct{}),
327 >
328 > updateRequestCancelInfos: make(map[int64]*persistencespb.RequestCancelInfo),
329 > pendingRequestCancelInfoIDs: make(map[int64]*persistencespb.RequestCancelInfo),
330 > deleteRequestCancelInfos: make(map[int64]struct{}),
331 >
332 > updateSignalInfos: make(map[int64]*persistencespb.SignalInfo),
333 > pendingSignalInfoIDs: make(map[int64]*persistencespb.SignalInfo),
334 > deleteSignalInfos: make(map[int64]struct{}),
335 >
336 > updateSignalRequestedIDs: make(map[string]struct{}),
337 > pendingSignalRequestedIDs: make(map[string]struct{}),
338 > deleteSignalRequestedIDs: make(map[string]struct{}),
339 >
340 > // This field will be initialized with a real chasm tree at the end of this function
341 > // when feature flag is enabled.
342 > chasmTree: &noopChasmTree{},
343 >
344 > approximateSize: 0,
345 > chasmNodeSizes: make(map[string]int),
346 > totalTombstones: 0,
347 > currentVersion: namespaceEntry.FailoverVersion(workflowID),
348 > bufferEventsInDB: nil,
349 > stateInDB: enumsspb.WORKFLOW_EXECUTION_STATE_VOID,
350 > nextEventIDInDB: common.FirstEventID,
351 > dbRecordVersion: 1,
352 > namespaceEntry: namespaceEntry,
353 > appliedEvents: make(map[string]struct{}),
354 > InsertTasks: make(map[tasks.Category][]tasks.Task),
355 > BestEffortDeleteTasks: make(map[tasks.Category][]tasks.Key),
356 > transitionHistoryEnabled: shard.GetConfig().EnableTransitionHistory(namespaceName),
357 > visibilityUpdated: false,
358 > executionStateUpdated: false,
359 > workflowTaskUpdated: false,
360 > updateInfoUpdated: make(map[string]struct{}),
361 > timerInfosUserDataUpdated: make(map[string]struct{}),
362 > activityInfosUserDataUpdated: make(map[int64]struct{}),
363 > reapplyEventsCandidate: []*historypb.HistoryEvent{},
364 >
365 > QueryRegistry: NewQueryRegistry(),
366 >
367 > shard: shard,
368 > clusterMetadata: shard.GetClusterMetadata(),
369 > eventsCache: eventsCache,
370 > config: shard.GetConfig(),
371 > timeSource: shard.GetTimeSource(),
372 > logger: logger,
373 > metricsHandler: shard.GetMetricsHandler().WithTags(metrics.OperationTag(metrics.WorkflowContextScope)),
374 > endpointRegistry: shard.EndpointRegistry(),
375 > }
376 >
377 > s.executionInfo = &persistencespb.WorkflowExecutionInfo{
378 > NamespaceId: namespaceEntry.ID().String(),
379 > WorkflowId: workflowID,
380 >
381 > WorkflowTaskVersion: common.EmptyVersion,
382 > WorkflowTaskScheduledEventId: common.EmptyEventID,
383 > WorkflowTaskStartedEventId: common.EmptyEventID,
384 > WorkflowTaskRequestId: emptyUUID,
385 > WorkflowTaskTimeout: timestamp.DurationFromSeconds(0),
386 > WorkflowTaskAttempt: 1,
387 >
388 > LastCompletedWorkflowTaskStartedEventId: common.EmptyEventID,
389 >
390 > StartTime: timestamppb.New(startTime),
391 > ExecutionTime: timestamppb.New(startTime),
392 > VersionHistories: versionhistory.NewVersionHistories(&historyspb.VersionHistory{}),
393 > ExecutionStats: &persistencespb.ExecutionStats{HistorySize: 0},
394 > SubStateMachinesByType: make(map[string]*persistencespb.StateMachineMap),
395 > }
396 > s.executionInfo.TaskGenerationShardClockTimestamp = shard.CurrentVectorClock().GetClock()
397 > s.approximateSize += s.executionInfo.Size()
398 >
399 > s.executionState = &persistencespb.WorkflowExecutionState{
400 > RunId: runID,
401 >
402 > State: enumsspb.WORKFLOW_EXECUTION_STATE_CREATED,
403 > Status: enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING,
404 > StartTime: timestamppb.New(startTime),
405 > RequestIds: make(map[string]*persistencespb.RequestIDInfo),
406 > }
407 > s.approximateSize += s.executionState.Size()
408 >
409 > s.hBuilder = historybuilder.New(
410 > s.timeSource,
411 > s.shard.GenerateTaskIDs,
412 > s.currentVersion,
413 > common.FirstEventID,
414 > s.bufferEventsInDB,
415 > s.metricsHandler,
416 > s.config.MaximumEventBatchSizeInBytes,
417 > )
418 > s.taskGenerator = GetTaskGeneratorProvider().NewTaskGenerator(shard, s)
419 > s.workflowTaskManager = newWorkflowTaskStateMachine(s, s.metricsHandler)
420 >
421 > s.mustInitHSM()
422 >
423 > // TODO@time-skipping: support time skipping for chasm
424 > if s.config.EnableChasm(namespaceName) {
425 s.chasmTree = chasm.NewEmptyTree(
426 shard.ChasmRegistry(),
446 dbRecord *persistencespb.WorkflowMutableState,
447 dbRecordVersion int64,
448 > ) (*MutableStateImpl, error) { mutable_state_impl.go
449 > // startTime will be overridden by DB record
450 > startTime := time.Time{}
451 >
452 > mutableState := NewMutableState(
453 > shard,
454 > eventsCache,
455 > logger,
456 > namespaceEntry,
457 > dbRecord.ExecutionInfo.WorkflowId,
458 > dbRecord.ExecutionState.RunId,
459 > startTime,
460 > )
461 >
462 > if dbRecord.ActivityInfos != nil {
463 > mutableState.pendingActivityInfoIDs = dbRecord.ActivityInfos mutable_state_impl.go
464 > mutableState.approximateSize += int64SizeBytes * len(mutableState.pendingActivityInfoIDs)
465 > }
466 > for _, activityInfo := range dbRecord.ActivityInfos { mutable_state_impl.go
467 > mutableState.pendingActivityIDToEventID[activityInfo.ActivityId] = activityInfo.ScheduledEventId mutable_state_impl.go
468 > mutableState.approximateSize += activityInfo.Size()
469 > if (activityInfo.TimerTaskStatus & TimerTaskStatusCreatedHeartbeat) > 0 {
470 // Sets last pending timer heartbeat to year 2000.
471 // This ensures at least one heartbeat task will be processed for the pending activity.
474 }
475
476 > if dbRecord.TimerInfos != nil { mutable_state_impl.go
477 mutableState.pendingTimerInfoIDs = dbRecord.TimerInfos
478 }
479 > for timerID, timerInfo := range dbRecord.TimerInfos { mutable_state_impl.go
480 mutableState.pendingTimerEventIDToID[timerInfo.GetStartedEventId()] = timerInfo.GetTimerId()
481 mutableState.approximateSize += timerInfo.Size()
483 }
484
485 > if dbRecord.ChildExecutionInfos != nil { mutable_state_impl.go
486 mutableState.pendingChildExecutionInfoIDs = dbRecord.ChildExecutionInfos
487 mutableState.approximateSize += int64SizeBytes * len(mutableState.pendingChildExecutionInfoIDs)
488 }
489 > for _, childInfo := range dbRecord.ChildExecutionInfos { mutable_state_impl.go
490 mutableState.approximateSize += childInfo.Size()
491 }
492
493 > if dbRecord.RequestCancelInfos != nil { mutable_state_impl.go
494 mutableState.pendingRequestCancelInfoIDs = dbRecord.RequestCancelInfos
495 mutableState.approximateSize += int64SizeBytes * len(mutableState.pendingRequestCancelInfoIDs)
496 }
497 > for _, cancelInfo := range dbRecord.RequestCancelInfos { mutable_state_impl.go
498 mutableState.approximateSize += cancelInfo.Size()
499 }
500
501 > if dbRecord.SignalInfos != nil { mutable_state_impl.go
502 mutableState.pendingSignalInfoIDs = dbRecord.SignalInfos
503 mutableState.approximateSize += int64SizeBytes * len(mutableState.pendingSignalInfoIDs)
504 }
505 > for _, signalInfo := range dbRecord.SignalInfos { mutable_state_impl.go
506 mutableState.approximateSize += signalInfo.Size()
507 }
508
509 > mutableState.pendingSignalRequestedIDs = convert.StringSliceToSet(dbRecord.SignalRequestedIds) mutable_state_impl.go
510 > for requestID := range mutableState.pendingSignalRequestedIDs {
511 mutableState.approximateSize += len(requestID)
512 }
513
514 > for _, tombstoneBatch := range dbRecord.ExecutionInfo.SubStateMachineTombstoneBatches { mutable_state_impl.go
515 > mutableState.totalTombstones += len(tombstoneBatch.StateMachineTombstones) mutable_state_impl.go
516 > }
517
518 // FirstExecutionRunId was duplicated from ExecutionInfo onto ExecutionState so the dedup /
519 // conflict path can surface it without loading ExecutionInfo. Backfill in memory for records
520 // written before that change so the next persist writes it through.
521 > if dbRecord.ExecutionState.FirstExecutionRunId == "" && dbRecord.ExecutionInfo.FirstExecutionRunId != "" { mutable_state_impl.go
522 dbRecord.ExecutionState.FirstExecutionRunId = dbRecord.ExecutionInfo.FirstExecutionRunId
523 }
524
525 > mutableState.approximateSize += dbRecord.ExecutionState.Size() - mutableState.executionState.Size() mutable_state_impl.go
526 > mutableState.executionState = dbRecord.ExecutionState
527 > mutableState.approximateSize += dbRecord.ExecutionInfo.Size() - mutableState.executionInfo.Size()
528 > mutableState.executionInfo = dbRecord.ExecutionInfo
529 >
530 > // StartTime was moved from ExecutionInfo to executionState
531 > if mutableState.executionState.StartTime == nil && dbRecord.ExecutionInfo.StartTime != nil {
532 mutableState.executionState.StartTime = dbRecord.ExecutionInfo.StartTime
533 }
534
535 > mutableState.hBuilder = historybuilder.New( mutable_state_impl.go
536 > mutableState.timeSource,
537 > mutableState.shard.GenerateTaskIDs,
538 > common.EmptyVersion,
539 > dbRecord.NextEventId,
540 > dbRecord.BufferedEvents,
541 > mutableState.metricsHandler,
542 > mutableState.config.MaximumEventBatchSizeInBytes,
543 > )
544 > mutableState.currentVersion = common.EmptyVersion
545 > mutableState.bufferEventsInDB = dbRecord.BufferedEvents
546 > mutableState.stateInDB = dbRecord.ExecutionState.State
547 > mutableState.nextEventIDInDB = dbRecord.NextEventId
548 > mutableState.dbRecordVersion = dbRecordVersion
549 > mutableState.checksum = dbRecord.Checksum
550 > mutableState.initVersionedTransitionInDB()
551 >
552 > if len(dbRecord.Checksum.GetValue()) > 0 {
553 switch {
554 case mutableState.shouldInvalidateCheckum():
566 }
567
568 > mutableState.mustInitHSM() mutable_state_impl.go
569 >
570 > // Track chasm node size even if chasm is not enabled,
571 > // because those nodes are still stored in the mutable state,
572 > // and should be taken into account when deciding if execution
573 > // should be terminated based on mutable state size.
574 > for key, node := range dbRecord.ChasmNodes {
575 nodeSize := len(key) + node.Size()
576 mutableState.approximateSize += nodeSize
579
580 // TODO@time-skipping: support time skipping for chasm
581 > if shard.GetConfig().EnableChasm(namespaceEntry.Name().String()) { mutable_state_impl.go
582 var err error
583 mutableState.chasmTree, err = chasm.NewTreeFromDB(
594 }
595 }
596 > if mutableState.executionInfo.GetTimeSkippingInfo() != nil { mutable_state_impl.go
597 mutableState.wrapTimeSourceWithTimeSkipping()
598 }
599 > return mutableState, nil mutable_state_impl.go
600 }
601
655 }
656
657 > func (ms *MutableStateImpl) mustInitHSM() { mutable_state_impl.go
658 > if ms.executionInfo.SubStateMachinesByType == nil {
659 > ms.executionInfo.SubStateMachinesByType = make(map[string]*persistencespb.StateMachineMap) mutable_state_impl.go
660 > }
661
662 // Error only occurs if some initialization path forgets to register the workflow state machine.
663 > stateMachineNode, err := hsm.NewRoot(ms.shard.StateMachineRegistry(), StateMachineType, ms, ms.executionInfo.SubStateMachinesByType, ms) mutable_state_impl.go
664 > if err != nil {
665 panic(err)
666 }
667 > ms.stateMachineNode = stateMachineNode mutable_state_impl.go
668 }
669
670 > func (ms *MutableStateImpl) IsWorkflow() bool { mutable_state_impl.go
671 > return ms.chasmTree.ArchetypeID() == chasm.WorkflowArchetypeID
672 > }
673
674 > func (ms *MutableStateImpl) HSM() *hsm.Node { mutable_state_impl.go
675 > return ms.stateMachineNode
676 > }
677
678 > func (ms *MutableStateImpl) ChasmTree() historyi.ChasmTree { mutable_state_impl.go
679 > return ms.chasmTree
680 > }
681
682 // ChasmEnabled returns true if the mutable state has a real chasm tree.
972 }
973
974 > func (ms *MutableStateImpl) CloneToProto() *persistencespb.WorkflowMutableState { mutable_state_impl.go
975 > msProto := &persistencespb.WorkflowMutableState{
976 > ActivityInfos: ms.pendingActivityInfoIDs,
977 > TimerInfos: ms.pendingTimerInfoIDs,
978 > ChildExecutionInfos: ms.pendingChildExecutionInfoIDs,
979 > RequestCancelInfos: ms.pendingRequestCancelInfoIDs,
980 > SignalInfos: ms.pendingSignalInfoIDs,
981 > ChasmNodes: ms.chasmTree.Snapshot(nil).Nodes,
982 > SignalRequestedIds: convert.StringSetToSlice(ms.pendingSignalRequestedIDs),
983 > ExecutionInfo: ms.executionInfo,
984 > ExecutionState: ms.executionState,
985 > NextEventId: ms.hBuilder.NextEventID(),
986 > BufferedEvents: ms.bufferEventsInDB,
987 > Checksum: ms.checksum,
988 > }
989 >
990 > return common.CloneProto(msProto)
991 > }
992
993 > func (ms *MutableStateImpl) GetWorkflowKey() definition.WorkflowKey { mutable_state_impl.go
994 > return definition.NewWorkflowKey(
995 > ms.executionInfo.NamespaceId,
996 > ms.executionInfo.WorkflowId,
997 > ms.executionState.RunId,
998 > )
999 > }
1000
1001 > func (ms *MutableStateImpl) GetCurrentBranchToken() ([]byte, error) { mutable_state_impl.go
1002 > currentVersionHistory, err := versionhistory.GetCurrentVersionHistory(ms.executionInfo.VersionHistories)
1003 > if err != nil {
1004 return nil, err
1005 }
1006 > return currentVersionHistory.GetBranchToken(), nil mutable_state_impl.go
1007 }
1008
1024 runTimeout *durationpb.Duration,
1025 treeID string,
1026 > ) error { mutable_state_impl.go
1027 > // NOTE: Unfortunately execution timeout and run timeout are not yet initialized into ms.executionInfo at this point.
1028 > // TODO: Consider explicitly initializing mutable state with these timeout parameters instead of passing them in.
1029 > workflowKey := ms.GetWorkflowKey()
1030 >
1031 > archetypeID := ms.ChasmTree().ArchetypeID()
1032 > if archetypeID != chasm.WorkflowArchetypeID {
1033 return softassert.UnexpectedInternalErr(
1034 ms.logger,
1042 }
1043
1044 > var retentionDuration *durationpb.Duration mutable_state_impl.go
1045 > if duration := ms.namespaceEntry.Retention(); duration > 0 {
1046 > retentionDuration = durationpb.New(duration) mutable_state_impl.go
1047 > }
1048 > initialBranchToken, err := ms.shard.GetExecutionManager().GetHistoryBranchUtil().NewHistoryBranch( mutable_state_impl.go
1049 > workflowKey.NamespaceID,
1050 > workflowKey.WorkflowID,
1051 > workflowKey.RunID,
1052 > treeID,
1053 > nil,
1054 > []*persistencespb.HistoryBranchRange{},
1055 > runTimeout.AsDuration(),
1056 > executionTimeout.AsDuration(),
1057 > retentionDuration.AsDuration(),
1058 > )
1059 > if err != nil {
1060 return err
1061 }
1062 > return ms.SetCurrentBranchToken(initialBranchToken) mutable_state_impl.go
1063 }
1064
1065 func (ms *MutableStateImpl) SetCurrentBranchToken(
1066 branchToken []byte,
1067 > ) error { mutable_state_impl.go
1068 > currentVersionHistory, err := versionhistory.GetCurrentVersionHistory(ms.executionInfo.VersionHistories)
1069 > if err != nil {
1070 return err
1071 }
1072 > versionhistory.SetVersionHistoryBranchToken(currentVersionHistory, branchToken) mutable_state_impl.go
1073 > return nil
1074 }
1075
1120 }
1121
1122 > func (ms *MutableStateImpl) GetExecutionInfo() *persistencespb.WorkflowExecutionInfo { mutable_state_impl.go
1123 > return ms.executionInfo
1124 > }
1125
1126 > func (ms *MutableStateImpl) GetExecutionState() *persistencespb.WorkflowExecutionState { mutable_state_impl.go
1127 > return ms.executionState
1128 > }
1129
1130 > func (ms *MutableStateImpl) FlushBufferedEvents() { mutable_state_impl.go
1131 > if ms.HasStartedWorkflowTask() {
1132 return
1133 }
1134 > ms.updatePendingEventIDs(ms.hBuilder.FlushBufferToCurrentBatch()) mutable_state_impl.go
1135 }
1136
1138 version int64,
1139 forceUpdate bool,
1140 > ) error { mutable_state_impl.go
1141 > if ms.transitionHistoryEnabled && len(ms.executionInfo.TransitionHistory) != 0 {
1142 > // this make sure current version >= last write version mutable_state_impl.go
1143 > lastVersionedTransition := ms.CurrentVersionedTransition()
1144 > ms.currentVersion = lastVersionedTransition.NamespaceFailoverVersion
1145 > } else { mutable_state_impl.go
1146 versionHistory, err := versionhistory.GetCurrentVersionHistory(ms.executionInfo.VersionHistories)
1147 if err != nil {
1159 }
1160
1161 > if version > ms.currentVersion || forceUpdate { mutable_state_impl.go
1162 ms.currentVersion = version
1163 }
1164
1165 > ms.hBuilder = historybuilder.New( mutable_state_impl.go
1166 > ms.timeSource,
1167 > ms.shard.GenerateTaskIDs,
1168 > ms.currentVersion,
1169 > ms.nextEventIDInDB,
1170 > ms.bufferEventsInDB,
1171 > ms.metricsHandler,
1172 > ms.config.MaximumEventBatchSizeInBytes,
1173 > )
1174 >
1175 > return nil
1176 }
1177
1178 > func (ms *MutableStateImpl) GetCurrentVersion() int64 { mutable_state_impl.go
1179 > // TODO: can we always return ms.currentVersion here?
1180 > if ms.executionInfo.VersionHistories != nil {
1181 > return ms.currentVersion
1182 > }
1183
1184 if ms.transitionHistoryEnabled && len(ms.executionInfo.TransitionHistory) != 0 {
1287 }
1288
1289 > func (ms *MutableStateImpl) GetLastWriteVersion() (int64, error) { mutable_state_impl.go
1290 > if ms.transitionHistoryEnabled && len(ms.executionInfo.TransitionHistory) != 0 {
1291 > lastVersionedTransition := ms.CurrentVersionedTransition() mutable_state_impl.go
1292 > return lastVersionedTransition.NamespaceFailoverVersion, nil
1293 > }
1294
1295 return ms.GetLastEventVersion()
1312 }
1313
1314 > func (ms *MutableStateImpl) IsCurrentWorkflowGuaranteed() bool { mutable_state_impl.go
1315 > // stateInDB is used like a bloom filter:
1316 > //
1317 > // 1. stateInDB being created / running meaning that this workflow must be the current
1318 > // workflow (assuming there is no rebuild of mutable state).
1319 > // 2. stateInDB being completed does not guarantee this workflow being the current workflow
1320 > // 3. stateInDB being zombie guarantees this workflow not being the current workflow
1321 > // 4. stateInDB cannot be void, void is only possible when mutable state is just initialized
1322 >
1323 > switch ms.stateInDB {
1324 case enumsspb.WORKFLOW_EXECUTION_STATE_VOID:
1325 return false
1326 case enumsspb.WORKFLOW_EXECUTION_STATE_CREATED:
1327 return true
1328 > case enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: mutable_state_impl.go
1329 > return true
1330 case enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED:
1331 return false
1358 }
1359
1360 > func (ms *MutableStateImpl) GetNamespaceEntry() *namespace.Namespace { mutable_state_impl.go
1361 > return ms.namespaceEntry
1362 > }
1363
1364 // AddHistoryEvent adds any history event to this workflow execution.
1429 }
1430
1431 > func (ms *MutableStateImpl) CurrentTaskQueue() *taskqueuepb.TaskQueue { mutable_state_impl.go
1432 > if ms.IsStickyTaskQueueSet() {
1433 return &taskqueuepb.TaskQueue{
1434 Name: ms.executionInfo.StickyTaskQueue,
1437 }
1438 }
1439 > return &taskqueuepb.TaskQueue{ mutable_state_impl.go
1440 > Name: ms.executionInfo.TaskQueue,
1441 > Kind: enumspb.TASK_QUEUE_KIND_NORMAL,
1442 > }
1443 }
1444
1448 }
1449
1450 > func (ms *MutableStateImpl) ClearStickyTaskQueue() { mutable_state_impl.go
1451 > ms.executionInfo.StickyTaskQueue = ""
1452 > ms.executionInfo.StickyScheduleToStartTimeout = nil
1453 > }
1454
1455 > func (ms *MutableStateImpl) IsStickyTaskQueueSet() bool { mutable_state_impl.go
1456 > return ms.executionInfo.StickyTaskQueue != ""
1457 > }
1458
1459 // TaskQueueScheduleToStartTimeout returns TaskQueue struct and corresponding StartToClose timeout.
1485 }
1486
1487 > func (ms *MutableStateImpl) GetWorkflowType() *commonpb.WorkflowType { mutable_state_impl.go
1488 > wType := &commonpb.WorkflowType{}
1489 > wType.Name = ms.executionInfo.WorkflowTypeName
1490 >
1491 > return wType
1492 > }
1493
1494 > func (ms *MutableStateImpl) GetQueryRegistry() historyi.QueryRegistry { mutable_state_impl.go
1495 > return ms.QueryRegistry
1496 > }
1497
1498 // VisitUpdates visits mutable state update entries, ordered by the ID of the history event pointed to by the mutable
1499 // state entry. Thus, for example, updates entries in Admitted state will be visited in the order that their Admitted
1500 // events were added to history.
1501 > func (ms *MutableStateImpl) VisitUpdates(visitor func(updID string, updInfo *persistencespb.UpdateInfo)) { mutable_state_impl.go
1502 > type updateEvent struct {
1503 > updId string
1504 > updInfo *persistencespb.UpdateInfo
1505 > eventId int64
1506 > }
1507 > var updateEvents []updateEvent
1508 > for updID, updInfo := range ms.executionInfo.GetUpdateInfos() {
1509 u := updateEvent{
1510 updId: updID,
1520 updateEvents = append(updateEvents, u)
1521 }
1522 > slices.SortFunc(updateEvents, func(u1, u2 updateEvent) int { return cmp.Compare(u1.eventId, u2.eventId) }) mutable_state_impl.go
1523
1524 > for _, u := range updateEvents { mutable_state_impl.go
1525 visitor(u.updId, u.updInfo)
1526 }
1615 func (ms *MutableStateImpl) GetActivityInfo(
1616 scheduledEventID int64,
1617 > ) (*persistencespb.ActivityInfo, bool) { mutable_state_impl.go
1618 > ai, ok := ms.pendingActivityInfoIDs[scheduledEventID]
1619 > return ai, ok
1620 > }
1621
1622 // GetActivityInfoWithTimerHeartbeat gives details about an activity that is currently in progress.
1636 func (ms *MutableStateImpl) GetActivityByActivityID(
1637 activityID string,
1638 > ) (*persistencespb.ActivityInfo, bool) { mutable_state_impl.go
1639 > eventID, ok := ms.pendingActivityIDToEventID[activityID]
1640 > if !ok {
1641 > return nil, false mutable_state_impl.go
1642 > }
1643 return ms.GetActivityInfo(eventID)
1644 }
1916 }
1917
1918 > func (ms *MutableStateImpl) Now() time.Time { mutable_state_impl.go
1919 > return ms.timeSource.Now()
1920 > }
1921
1922 // GetWorkflowCloseTime returns workflow closed time, returns a zero time for open workflow
2071 func (ms *MutableStateImpl) writeEventToCache(
2072 event *historypb.HistoryEvent,
2074 > // For start event: store it here so the recordWorkflowStarted transfer task doesn't need to
2075 > // load it from database.
2076 > // For completion event: store it here so we can communicate the result to parent execution
2077 > // during the processing of DeleteTransferTask without loading this event from database.
2078 > // For Update events: store it here so that Update disposition lookups can be fast.
2079 > ms.eventsCache.PutEvent(
2080 > events.EventKey{
2081 > NamespaceID: namespace.ID(ms.executionInfo.NamespaceId),
2082 > WorkflowID: ms.executionInfo.WorkflowId,
2083 > RunID: ms.executionState.RunId,
2084 > EventID: event.GetEventId(),
2085 > Version: event.GetVersion(),
2086 > },
2087 > event,
2088 > )
2089 > }
2090
2091 func (ms *MutableStateImpl) HasParentExecution() bool {
2096 ai *persistencespb.ActivityInfo,
2097 request *workflowservice.RecordActivityTaskHeartbeatRequest,
2099 > if prev, existed := ms.pendingActivityInfoIDs[ai.ScheduledEventId]; existed {
2100 > ms.approximateSize -= prev.Size()
2101 > }
2102 > ai.Version = ms.GetCurrentVersion()
2103 > ai.LastHeartbeatDetails = request.Details
2104 > now := ms.timeSource.Now()
2105 > ai.LastHeartbeatUpdateTime = timestamppb.New(now)
2106 > ms.updateActivityInfos[ai.ScheduledEventId] = ai
2107 > ms.activityInfosUserDataUpdated[ai.ScheduledEventId] = struct{}{}
2108 > ms.approximateSize += ai.Size()
2109 > ms.syncActivityTasks[ai.ScheduledEventId] = struct{}{}
2110 >
2111 > payloadSize := request.Details.Size()
2112 > if payloadSize > 0 {
2113 > ms.metricsHandler.Counter(metrics.ActivityPayloadSize.Name()).Record(
2114 > int64(payloadSize),
2115 > metrics.OperationTag(metrics.HistoryRecordActivityTaskHeartbeatScope),
2116 > metrics.NamespaceTag(ms.namespaceEntry.Name().String()))
2117 > }
2118 > ms.metricsHandler.Counter(metrics.ActivityHeartbeatCount.Name()).Record(1,
2119 > metrics.OperationTag(metrics.HistoryRecordActivityTaskHeartbeatScope),
2120 > metrics.NamespaceTag(ms.namespaceEntry.Name().String()),
2121 > metrics.StringTag("has_details", strconv.FormatBool(payloadSize > 0)))
2122 }
2123
2188
2189 // UpdateActivityTaskStatusWithTimerHeartbeat updates an activity's timer task status or/and timer heartbeat
2190 > func (ms *MutableStateImpl) UpdateActivityTaskStatusWithTimerHeartbeat(scheduleEventID int64, timerTaskStatus int32, heartbeatTimeoutVisibility *time.Time) error { mutable_state_impl.go
2191 > ai, ok := ms.pendingActivityInfoIDs[scheduleEventID]
2192 > if !ok {
2193 ms.logError(
2194 fmt.Sprintf("unable to find activity event ID: %v in mutable state", scheduleEventID),
2198 }
2199
2200 > ai.TimerTaskStatus = timerTaskStatus mutable_state_impl.go
2201 > ms.updateActivityInfos[ai.ScheduledEventId] = ai
2202 >
2203 > if heartbeatTimeoutVisibility != nil {
2204 ms.pendingActivityTimerHeartbeats[scheduleEventID] = *heartbeatTimeoutVisibility
2205 }
2206 > return nil mutable_state_impl.go
2207 }
2208
2210 func (ms *MutableStateImpl) DeleteActivity(
2211 scheduledEventID int64,
2212 > ) error { mutable_state_impl.go
2213 > if activityInfo, ok := ms.pendingActivityInfoIDs[scheduledEventID]; ok {
2214 > delete(ms.pendingActivityInfoIDs, scheduledEventID)
2215 > delete(ms.pendingActivityTimerHeartbeats, scheduledEventID)
2216 > ms.approximateSize -= activityInfo.Size() + int64SizeBytes
2217 >
2218 > if _, ok = ms.pendingActivityIDToEventID[activityInfo.ActivityId]; ok {
2219 > delete(ms.pendingActivityIDToEventID, activityInfo.ActivityId)
2220 > } else {
2221 ms.logError(
2222 fmt.Sprintf("unable to find activity ID: %v in mutable state", activityInfo.ActivityId),
2235 }
2236
2237 > delete(ms.updateActivityInfos, scheduledEventID) mutable_state_impl.go
2238 > delete(ms.activityInfosUserDataUpdated, scheduledEventID)
2239 > delete(ms.syncActivityTasks, scheduledEventID)
2240 > ms.deleteActivityInfos[scheduledEventID] = struct{}{}
2241 > return nil
2242 }
2243
2336
2337 // GetWorkflowTaskByID returns details about the current workflow task by scheduled event ID.
2338 > func (ms *MutableStateImpl) GetWorkflowTaskByID(scheduledEventID int64) *historyi.WorkflowTaskInfo { mutable_state_impl.go
2339 > return ms.workflowTaskManager.GetWorkflowTaskByID(scheduledEventID)
2340 > }
2341
2342 > func (ms *MutableStateImpl) GetPendingActivityInfos() map[int64]*persistencespb.ActivityInfo { mutable_state_impl.go
2343 > return ms.pendingActivityInfoIDs
2344 > }
2345
2346 > func (ms *MutableStateImpl) GetPendingTimerInfos() map[string]*persistencespb.TimerInfo { mutable_state_impl.go
2347 > return ms.pendingTimerInfoIDs
2348 > }
2349
2350 > func (ms *MutableStateImpl) GetPendingChildExecutionInfos() map[int64]*persistencespb.ChildExecutionInfo { mutable_state_impl.go
2351 > return ms.pendingChildExecutionInfoIDs
2352 > }
2353
2354 func (ms *MutableStateImpl) GetPendingChildIds() map[int64]struct{} {
2360 }
2361
2362 > func (ms *MutableStateImpl) GetPendingRequestCancelExternalInfos() map[int64]*persistencespb.RequestCancelInfo { mutable_state_impl.go
2363 > return ms.pendingRequestCancelInfoIDs
2364 > }
2365
2366 > func (ms *MutableStateImpl) GetPendingSignalExternalInfos() map[int64]*persistencespb.SignalInfo { mutable_state_impl.go
2367 > return ms.pendingSignalInfoIDs
2368 > }
2369
2370 func (ms *MutableStateImpl) GetPendingSignalRequestedIds() []string {
2376 }
2377
2378 > func (ms *MutableStateImpl) HasPendingWorkflowTask() bool { mutable_state_impl.go
2379 > return ms.workflowTaskManager.HasPendingWorkflowTask()
2380 > }
2381
2382 func (ms *MutableStateImpl) GetPendingWorkflowTask() *historyi.WorkflowTaskInfo {
2384 }
2385
2386 > func (ms *MutableStateImpl) HasStartedWorkflowTask() bool { mutable_state_impl.go
2387 > return ms.workflowTaskManager.HasStartedWorkflowTask()
2388 > }
2389
2390 > func (ms *MutableStateImpl) GetStartedWorkflowTask() *historyi.WorkflowTaskInfo { mutable_state_impl.go
2391 > return ms.workflowTaskManager.GetStartedWorkflowTask()
2392 > }
2393
2394 > func (ms *MutableStateImpl) IsTransientWorkflowTask() bool { mutable_state_impl.go
2395 > return ms.executionInfo.WorkflowTaskAttempt > 1
2396 > }
2397
2398 func (ms *MutableStateImpl) ClearTransientWorkflowTask() error {
2441 }
2442
2443 > func (ms *MutableStateImpl) GetAssignedBuildId() string { mutable_state_impl.go
2444 > return ms.executionInfo.AssignedBuildId
2445 > }
2446
2447 func (ms *MutableStateImpl) GetInheritedBuildId() string {
2449 }
2450
2451 > func (ms *MutableStateImpl) GetMostRecentWorkerVersionStamp() *commonpb.WorkerVersionStamp { mutable_state_impl.go
2452 > return ms.executionInfo.MostRecentWorkerVersionStamp
2453 > }
2454
2455 > func (ms *MutableStateImpl) HasBufferedEvents() bool { mutable_state_impl.go
2456 > return ms.hBuilder.HasBufferEvents()
2457 > }
2458
2459 // HasAnyBufferedEvent returns true if there is at least one buffered event that matches the provided filter.
2469
2470 // GetNextEventID returns next event ID
2471 > func (ms *MutableStateImpl) GetNextEventID() int64 { mutable_state_impl.go
2472 > return ms.hBuilder.NextEventID()
2473 > }
2474
2475 // GetStartedEventIdForLastCompletedWorkflowTask returns last started workflow task event ID
2478 }
2479
2480 > func (ms *MutableStateImpl) IsWorkflowExecutionRunning() bool { mutable_state_impl.go
2481 > switch ms.executionState.State {
2482 > case enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: mutable_state_impl.go
2483 > return true
2484 > case enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: mutable_state_impl.go
2485 > return true
2486 case enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED:
2487 return false
2534 // GetApproximatePersistedSize returns approximate size of in-memory objects that will be written to
2535 // persistence + size of buffered events in history builder if they will not be flushed
2536 > func (ms *MutableStateImpl) GetApproximatePersistedSize() int { mutable_state_impl.go
2537 > // include buffered events in the size if they will not be flushed
2538 > if ms.BufferSizeAcceptable() && ms.HasStartedWorkflowTask() {
2539 return ms.approximateSize + ms.hBuilder.SizeInBytesOfBufferedEvents()
2540 }
2541 > return ms.approximateSize mutable_state_impl.go
2542 }
2543
2580 eventType enumspb.EventType,
2581 eventID int64,
2583 > ms.approximateSize -= ms.executionState.Size()
2584 > if ms.executionState.RequestIds == nil {
2585 ms.executionState.RequestIds = make(map[string]*persistencespb.RequestIDInfo, 1)
2586 }
2587 > ms.executionState.RequestIds[requestID] = &persistencespb.RequestIDInfo{ mutable_state_impl.go
2588 > EventType: eventType,
2589 > EventId: eventID,
2590 > }
2591 > if eventType == enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_STARTED {
2592 > ms.executionState.CreateRequestId = requestID
2593 > }
2594 > ms.approximateSize += ms.executionState.Size()
2595 }
2596
2887 execution *commonpb.WorkflowExecution,
2888 startRequest *historyservice.StartWorkflowExecutionRequest,
2889 > ) (*historypb.HistoryEvent, error) { mutable_state_impl.go
2890 > return ms.AddWorkflowExecutionStartedEventWithOptions(
2891 > execution,
2892 > startRequest,
2893 > nil, // resetPoints
2894 > "", // prevRunID
2895 > execution.GetRunId(),
2896 > )
2897 > }
2898
2899 func (ms *MutableStateImpl) AddWorkflowExecutionStartedEventWithOptions(
2903 prevRunID string,
2904 firstRunID string,
2905 > ) (*historypb.HistoryEvent, error) { mutable_state_impl.go
2906 > opTag := tag.WorkflowActionWorkflowStarted
2907 > if err := ms.checkMutability(opTag); err != nil {
2908 return nil, err
2909 }
2910
2911 > eventID := ms.GetNextEventID() mutable_state_impl.go
2912 > if eventID != common.FirstEventID {
2913 ms.logger.Warn(mutableStateInvalidHistoryActionMsg, opTag,
2914 tag.WorkflowEventID(eventID),
2917 }
2918
2919 > event := ms.hBuilder.AddWorkflowExecutionStartedEvent( mutable_state_impl.go
2920 > ms.executionState.StartTime.AsTime(),
2921 > startRequest,
2922 > resetPoints,
2923 > prevRunID,
2924 > firstRunID,
2925 > execution.GetRunId(),
2926 > )
2927 > if err := ms.ApplyWorkflowExecutionStartedEvent(
2928 > startRequest.GetParentExecutionInfo().GetClock(),
2929 > execution,
2930 > startRequest.StartRequest.GetRequestId(),
2931 > event,
2932 > ); err != nil {
2933 return nil, err
2934 }
2935
2936 // TODO merge active & passive task generation
2937 > var err error mutable_state_impl.go
2938 > ms.executionInfo.WorkflowExecutionTimerTaskStatus, err = ms.taskGenerator.GenerateWorkflowStartTasks(
2939 > event,
2940 > )
2941 > if err != nil {
2942 return nil, err
2943 }
2944
2945 > if err := ms.taskGenerator.GenerateRecordWorkflowStartedTasks( mutable_state_impl.go
2946 > event,
2947 > ); err != nil {
2948 return nil, err
2949 }
2950
2951 // Versioning Override set on StartWorkflowExecutionRequest
2952 > if startRequest.GetStartRequest().GetVersioningOverride() != nil { mutable_state_impl.go
2953 metrics.WorkerDeploymentVersioningOverrideCounter.With(
2954 ms.metricsHandler.WithTags(
2969 requestID string,
2970 startEvent *historypb.HistoryEvent,
2971 > ) error { mutable_state_impl.go
2972 > if ms.executionInfo.NamespaceId != ms.namespaceEntry.ID().String() {
2973 return serviceerror.NewInternalf("applying conflicting namespace ID: %v != %v",
2974 ms.executionInfo.NamespaceId, ms.namespaceEntry.ID().String())
2975 }
2976 > if ms.executionInfo.WorkflowId != execution.GetWorkflowId() { mutable_state_impl.go
2977 return serviceerror.NewInternalf("applying conflicting workflow ID: %v != %v",
2978 ms.executionInfo.WorkflowId, execution.GetWorkflowId())
2979 }
2980 > if ms.executionState.RunId != execution.GetRunId() { mutable_state_impl.go
2981 return serviceerror.NewInternalf("applying conflicting run ID: %v != %v",
2982 ms.executionState.RunId, execution.GetRunId())
2983 }
2984
2985 > event := startEvent.GetWorkflowExecutionStartedEventAttributes() mutable_state_impl.go
2986 > ms.AttachRequestID(requestID, startEvent.EventType, startEvent.EventId)
2987 >
2988 > ms.approximateSize -= ms.executionInfo.Size()
2989 > ms.executionInfo.FirstExecutionRunId = event.GetFirstExecutionRunId()
2990 > ms.executionInfo.TaskQueue = event.TaskQueue.GetName()
2991 > ms.executionInfo.WorkflowTypeName = event.WorkflowType.GetName()
2992 > ms.executionInfo.WorkflowRunTimeout = event.GetWorkflowRunTimeout()
2993 > ms.executionInfo.WorkflowExecutionTimeout = event.GetWorkflowExecutionTimeout()
2994 > ms.executionInfo.DefaultWorkflowTaskTimeout = event.GetWorkflowTaskTimeout()
2995 > ms.executionInfo.OriginalExecutionRunId = event.GetOriginalExecutionRunId()
2996 >
2997 > ms.approximateSize -= ms.executionState.Size()
2998 > ms.executionState.FirstExecutionRunId = event.GetFirstExecutionRunId()
2999 > if err := ms.addCompletionCallbacks(
3000 > startEvent,
3001 > requestID,
3002 > event.GetCompletionCallbacks(),
3003 > ); err != nil {
3004 return err
3005 }
3006 > if _, err := ms.UpdateWorkflowStateStatus( mutable_state_impl.go
3007 > enumsspb.WORKFLOW_EXECUTION_STATE_CREATED,
3008 > enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING,
3009 > ); err != nil {
3010 return err
3011 }
3012 > ms.executionInfo.LastCompletedWorkflowTaskStartedEventId = common.EmptyEventID mutable_state_impl.go
3013 > ms.executionInfo.LastFirstEventId = startEvent.GetEventId()
3014 >
3015 > ms.executionInfo.WorkflowTaskVersion = common.EmptyVersion
3016 > ms.executionInfo.WorkflowTaskScheduledEventId = common.EmptyEventID
3017 > ms.executionInfo.WorkflowTaskStartedEventId = common.EmptyEventID
3018 > ms.executionInfo.WorkflowTaskRequestId = emptyUUID
3019 > ms.executionInfo.WorkflowTaskTimeout = timestamp.DurationFromSeconds(0)
3020 >
3021 > ms.executionInfo.CronSchedule = event.GetCronSchedule()
3022 >
3023 > if event.ParentWorkflowExecution != nil {
3024 ms.executionInfo.ParentNamespaceId = event.GetParentWorkflowNamespaceId()
3025 ms.executionInfo.ParentWorkflowId = event.ParentWorkflowExecution.GetWorkflowId()
3028 }
3029
3030 > if event.ParentInitiatedEventId != 0 { mutable_state_impl.go
3031 ms.executionInfo.ParentInitiatedId = event.GetParentInitiatedEventId()
3032 > } else { mutable_state_impl.go
3033 > ms.executionInfo.ParentInitiatedId = common.EmptyEventID mutable_state_impl.go
3034 > }
3035
3036 > if event.ParentInitiatedEventVersion != 0 { mutable_state_impl.go
3037 ms.executionInfo.ParentInitiatedVersion = event.GetParentInitiatedEventVersion()
3038 > } else { mutable_state_impl.go
3039 > ms.executionInfo.ParentInitiatedVersion = common.EmptyVersion mutable_state_impl.go
3040 > }
3041
3042 > if event.RootWorkflowExecution != nil { mutable_state_impl.go
3043 ms.executionInfo.RootWorkflowId = event.RootWorkflowExecution.GetWorkflowId()
3044 ms.executionInfo.RootRunId = event.RootWorkflowExecution.GetRunId()
3045 > } else { mutable_state_impl.go
3046 > ms.executionInfo.RootWorkflowId = execution.GetWorkflowId()
3047 > ms.executionInfo.RootRunId = execution.GetRunId()
3048 > }
3049
3050 // todo@time-skipping: apply time skipping to WorkflowStartDelay
3051 > ms.executionInfo.ExecutionTime = timestamppb.New( mutable_state_impl.go
3052 > ms.executionState.StartTime.AsTime().Add(event.GetFirstWorkflowTaskBackoff().AsDuration()),
3053 > )
3054 >
3055 > ms.executionInfo.Attempt = event.GetAttempt()
3056 > if !timestamp.TimeValue(event.GetWorkflowExecutionExpirationTime()).IsZero() {
3057 ms.executionInfo.WorkflowExecutionExpirationTime = event.GetWorkflowExecutionExpirationTime()
3058 }
3059
3060 > var workflowRunTimeoutTime time.Time mutable_state_impl.go
3061 > workflowRunTimeoutDuration := ms.executionInfo.WorkflowRunTimeout.AsDuration()
3062 > // if workflowRunTimeoutDuration == 0 then the workflowRunTimeoutTime will be 0
3063 > // meaning that there is not workflow run timeout
3064 > if workflowRunTimeoutDuration != 0 {
3065 > firstWorkflowTaskDelayDuration := event.GetFirstWorkflowTaskBackoff().AsDuration() mutable_state_impl.go
3066 > workflowRunTimeoutDuration = workflowRunTimeoutDuration + firstWorkflowTaskDelayDuration
3067 > workflowRunTimeoutTime = ms.executionState.StartTime.AsTime().Add(workflowRunTimeoutDuration)
3068 >
3069 > workflowExecutionTimeoutTime := timestamp.TimeValue(ms.executionInfo.WorkflowExecutionExpirationTime)
3070 > if !workflowExecutionTimeoutTime.IsZero() && workflowRunTimeoutTime.After(workflowExecutionTimeoutTime) {
3071 workflowRunTimeoutTime = workflowExecutionTimeoutTime
3072 }
3073 }
3074 > ms.executionInfo.WorkflowRunExpirationTime = timestamppb.New(workflowRunTimeoutTime) mutable_state_impl.go
3075 >
3076 > if event.RetryPolicy != nil {
3077 ms.executionInfo.HasRetryPolicy = true
3078 ms.executionInfo.RetryBackoffCoefficient = event.RetryPolicy.GetBackoffCoefficient()
3083 }
3084
3085 > ms.executionInfo.AutoResetPoints = rolloverAutoResetPointsWithExpiringTime( mutable_state_impl.go
3086 > event.GetPrevAutoResetPoints(),
3087 > event.GetContinuedExecutionRunId(),
3088 > timestamp.TimeValue(startEvent.GetEventTime()),
3089 > ms.namespaceEntry.Retention(),
3090 > )
3091 >
3092 > if event.Memo != nil {
3093 ms.executionInfo.Memo = event.Memo.GetFields()
3094 }
3095 > if event.SearchAttributes != nil { mutable_state_impl.go
3096 ms.executionInfo.SearchAttributes = event.SearchAttributes.GetIndexedFields()
3097 }
3098
3099 > if event.GetVersioningOverride() != nil { mutable_state_impl.go
3100 if ms.executionInfo.VersioningInfo == nil {
3101 ms.executionInfo.VersioningInfo = &workflowpb.WorkflowExecutionVersioningInfo{}
3136 }
3137
3138 > if event.GetInheritedPinnedVersion() != nil { mutable_state_impl.go
3139 if ms.executionInfo.VersioningInfo == nil {
3140 ms.executionInfo.VersioningInfo = &workflowpb.WorkflowExecutionVersioningInfo{}
3147 // target version upgrade from the started event. This is the same public API
3148 // type, so no conversion needed.
3149 > if event.GetContinuedExecutionRunId() != "" && event.GetInheritedPinnedVersion() != nil { mutable_state_impl.go
3150 ms.executionInfo.DeclinedTargetVersionUpgrade = event.GetDeclinedTargetVersionUpgrade()
3151 }
3152
3153 // Populate the versioningInfo if the inheritedAutoUpgradeInfo is present.
3154 > if event.GetInheritedAutoUpgradeInfo() != nil { mutable_state_impl.go
3155 ms.SetVersioningRevisionNumber(event.GetInheritedAutoUpgradeInfo().GetSourceDeploymentRevisionNumber())
3156 // TODO (Shivam): Remove this once you make SetDeploymentVersion and SetVersioningBehavior methods with nil checks
3164 }
3165
3166 > if inheritedBuildId := event.InheritedBuildId; inheritedBuildId != "" { mutable_state_impl.go
3167 ms.executionInfo.InheritedBuildId = inheritedBuildId
3168 if err := ms.UpdateBuildIdAssignment(inheritedBuildId); err != nil {
3169 return err
3170 }
3171 > } else if event.SourceVersionStamp.GetUseVersioning() && event.SourceVersionStamp.GetBuildId() != "" || mutable_state_impl.go
3172 > ms.GetEffectiveVersioningBehavior() != enumspb.VERSIONING_BEHAVIOR_UNSPECIFIED {
3173 // TODO: [cleanup-old-wv]
3174 limit := ms.config.SearchAttributesSizeOfValueLimit(string(ms.namespaceEntry.Name()))
3181
3182 // This will include override and inheritance, but not transition, because WF never starts with a transition
3183 > ms.executionInfo.WorkerDeploymentName = ms.GetEffectiveDeployment().GetSeriesName() mutable_state_impl.go
3184 >
3185 > if inheritedBuildId := event.InheritedBuildId; inheritedBuildId != "" {
3186 ms.executionInfo.InheritedBuildId = inheritedBuildId
3187 if err := ms.UpdateBuildIdAssignment(inheritedBuildId); err != nil {
3190 }
3191
3192 > ms.executionInfo.MostRecentWorkerVersionStamp = event.SourceVersionStamp mutable_state_impl.go
3193 > ms.executionInfo.Priority = event.Priority
3194 >
3195 > if tsc, stateProp := event.GetTimeSkippingConfig(), event.GetTimeSkippingStatePropagation(); tsc != nil || stateProp.GetInitialSkippedDuration().AsDuration() > 0 {
3196 if err := ms.initTimeSkippingInfo(tsc, stateProp); err != nil {
3197 return err
3199 }
3200
3201 > ms.approximateSize += ms.executionInfo.Size() mutable_state_impl.go
3202 > ms.approximateSize += ms.executionState.Size()
3203 >
3204 > ms.writeEventToCache(startEvent)
3205 > return nil
3206 }
3207
3208 > func (ms *MutableStateImpl) IsWorkflowExecutionStatusPaused() bool { mutable_state_impl.go
3209 > return ms.executionState.GetStatus() == enumspb.WORKFLOW_EXECUTION_STATUS_PAUSED
3210 > }
3211
3212 func (ms *MutableStateImpl) AddWorkflowExecutionPausedEvent(
3386 requestID string,
3387 completionCallbacks []*commonpb.Callback,
3388 > ) error { mutable_state_impl.go
3389 > if len(completionCallbacks) == 0 {
3390 > return nil mutable_state_impl.go
3391 > }
3392 if ms.chasmCallbacksEnabled() {
3393 // Initialize chasm tree once for new workflows.
3489 bypassTaskGeneration bool,
3490 workflowTaskType enumsspb.WorkflowTaskType,
3491 > ) (*historyi.WorkflowTaskInfo, error) { mutable_state_impl.go
3492 > opTag := tag.WorkflowActionWorkflowTaskScheduled
3493 > if err := ms.checkMutability(opTag); err != nil {
3494 return nil, err
3495 }
3496 > return ms.workflowTaskManager.AddWorkflowTaskScheduledEvent(bypassTaskGeneration, workflowTaskType) mutable_state_impl.go
3497 }
3498
3538 targetDeploymentVersion *deploymentpb.WorkerDeploymentVersion,
3539 targetRevisionNumber int64,
3540 > ) (*historypb.HistoryEvent, *historyi.WorkflowTaskInfo, error) { mutable_state_impl.go
3541 > opTag := tag.WorkflowActionWorkflowTaskStarted
3542 > if err := ms.checkMutability(opTag); err != nil {
3543 return nil, nil, err
3544 }
3545 > return ms.workflowTaskManager.AddWorkflowTaskStartedEvent(scheduledEventID, requestID, taskQueue, identity, versioningStamp, redirectInfo, skipVersioningCheck, updateReg, targetDeploymentVersion, targetRevisionNumber) mutable_state_impl.go
3546 }
3547
3607 eventID int64,
3608 maxResetPoints int,
3609 > ) bool { mutable_state_impl.go
3610 > resetPoints := ms.executionInfo.AutoResetPoints.GetPoints()
3611 > for _, rp := range resetPoints {
3612 > if rp.GetBinaryChecksum() == binaryChecksum && rp.GetBuildId() == buildId { mutable_state_impl.go
3613 > return false
3614 > }
3615 }
3616
3617 // todo@time-skipping: time skipping is naturally supported for auto reset points, and need to
3618 // decide if this the best default policy for auto reset points
3619 > newPoint := &workflowpb.ResetPointInfo{ mutable_state_impl.go
3620 > BinaryChecksum: binaryChecksum,
3621 > BuildId: buildId,
3622 > RunId: ms.executionState.GetRunId(),
3623 > FirstWorkflowTaskCompletedId: eventID,
3624 > CreateTime: timestamppb.New(ms.timeSource.Now()),
3625 > Resettable: ms.CheckResettable() == nil,
3626 > }
3627 > ms.executionInfo.AutoResetPoints = &workflowpb.ResetPoints{
3628 > Points: util.SliceTail(append(resetPoints, newPoint), maxResetPoints),
3629 > }
3630 > return true
3631 }
3632
3762 usedVersion *deploymentpb.WorkerDeploymentVersion,
3763 maxSearchAttributeValueSize int,
3764 > ) error { mutable_state_impl.go
3765 > changed, err := ms.addBuildIDAndDeploymentInfoToSearchAttributesWithNoVisibilityTask(stamp, usedVersion, maxSearchAttributeValueSize)
3766 > if err != nil {
3767 return err
3768 }
3769
3770 > if !changed { mutable_state_impl.go
3771 > return nil mutable_state_impl.go
3772 > }
3773 > return ms.taskGenerator.GenerateUpsertVisibilityTask() mutable_state_impl.go
3774 }
3775
3776 > func (ms *MutableStateImpl) loadBuildIds() ([]string, error) { mutable_state_impl.go
3777 > searchAttributes := ms.executionInfo.SearchAttributes
3778 > if searchAttributes == nil {
3779 > return []string{}, nil
3780 > }
3781 > saPayload, found := searchAttributes[sadefs.BuildIds] mutable_state_impl.go
3782 > if !found {
3783 return []string{}, nil
3784 }
3785 > decoded, err := sadefs.DecodeValue(saPayload, enumspb.INDEXED_VALUE_TYPE_KEYWORD_LIST, false) mutable_state_impl.go
3786 > if err != nil {
3787 return nil, err
3788 }
3789 > if decoded == nil { mutable_state_impl.go
3790 return []string{}, nil
3791 }
3792 > searchAttributeValues, ok := decoded.([]string) mutable_state_impl.go
3793 > if !ok {
3794 return nil, serviceerror.NewInternal("invalid search attribute value stored for BuildIds")
3795 }
3796 > return searchAttributeValues, nil mutable_state_impl.go
3797 }
3798
3799 > func (ms *MutableStateImpl) loadSearchAttributeString(saName string) (string, error) { mutable_state_impl.go
3800 > searchAttributes := ms.executionInfo.SearchAttributes
3801 > if searchAttributes == nil {
3802 > return "", nil
3803 > }
3804 > saPayload, found := searchAttributes[saName] mutable_state_impl.go
3805 > if !found {
3806 > return "", nil
3807 > }
3808 decoded, err := sadefs.DecodeValue(saPayload, enumspb.INDEXED_VALUE_TYPE_KEYWORD, false)
3809 if err != nil {
3820 }
3821
3822 > func (ms *MutableStateImpl) loadUsedDeploymentVersions() ([]string, error) { mutable_state_impl.go
3823 > searchAttributes := ms.executionInfo.SearchAttributes
3824 > if searchAttributes == nil {
3825 > return []string{}, nil
3826 > }
3827 > saPayload, found := searchAttributes[sadefs.TemporalUsedWorkerDeploymentVersions] mutable_state_impl.go
3828 > if !found {
3829 > return []string{}, nil
3830 > }
3831 decoded, err := sadefs.DecodeValue(saPayload, enumspb.INDEXED_VALUE_TYPE_KEYWORD_LIST, false)
3832 if err != nil {
3851 existingValues []string,
3852 stamp *commonpb.WorkerVersionStamp,
3853 > ) []string { mutable_state_impl.go
3854 > var newValues []string
3855 > var buildId string
3856 >
3857 > behavior := ms.GetWorkflowVersioningBehaviorSA()
3858 >
3859 > // set up the unversioned or assigned:x sentinels (versioning v2)
3860 > if !stamp.GetUseVersioning() && behavior == enumspb.VERSIONING_BEHAVIOR_UNSPECIFIED { // unversioned workflows may still have non-nil deployment, so we don't check deployment
3861 > newValues = append(newValues, worker_versioning.UnversionedSearchAttribute)
3862 > } else if ms.GetAssignedBuildId() != "" && behavior == enumspb.VERSIONING_BEHAVIOR_UNSPECIFIED {
3863 newValues = append(newValues, worker_versioning.AssignedBuildIdSearchAttribute(ms.GetAssignedBuildId()))
3864 }
3865
3866 // get the most up-to-date pinned entry put it at the front (v3 reachability and v3.1 drainage)
3867 > if behavior == enumspb.VERSIONING_BEHAVIOR_PINNED { mutable_state_impl.go
3868 newValues = append(newValues, worker_versioning.PinnedBuildIdSearchAttribute(ms.GetWorkerDeploymentVersionSA()))
3869 }
3870
3871 // get the build id entry (all versions of versioning)
3872 > if stamp != nil { mutable_state_impl.go
3873 buildId = worker_versioning.VersionStampToBuildIdSearchAttribute(stamp)
3874 }
3875
3876 // add all previous values except for unversioned, assigned, or pinned (there can only be one, and we just added it)
3877 > foundBuildId := false mutable_state_impl.go
3878 > for _, existingValue := range existingValues {
3879 > if existingValue == buildId { mutable_state_impl.go
3880 foundBuildId = true
3881 }
3882 > if !worker_versioning.IsUnversionedOrAssignedBuildIdSearchAttribute(existingValue) && mutable_state_impl.go
3883 > !strings.HasPrefix(existingValue, worker_versioning.BuildIdSearchAttributePrefixPinned) {
3884 newValues = append(newValues, existingValue)
3885 }
3887
3888 // add buildId to the list only if it wasn't there before
3889 > if !foundBuildId && buildId != "" { mutable_state_impl.go
3890 newValues = append(newValues, buildId)
3891 }
3892 > return newValues mutable_state_impl.go
3893 }
3894
3895 > func (ms *MutableStateImpl) addUsedDeploymentVersionToLoadedSearchAttribute(existingValues []string, usedVersion *deploymentpb.WorkerDeploymentVersion) []string { mutable_state_impl.go
3896 > if usedVersion == nil {
3897 > return existingValues
3898 > }
3899
3900 // Get the current deployment version string (already formatted via ExternalWorkerDeploymentVersionToString)
3918 }
3919
3920 > func (ms *MutableStateImpl) saveBuildIds(buildIds []string, maxSearchAttributeValueSize int) error { mutable_state_impl.go
3921 > searchAttributes := ms.executionInfo.SearchAttributes
3922 > if searchAttributes == nil {
3923 > searchAttributes = make(map[string]*commonpb.Payload, 1)
3924 > ms.executionInfo.SearchAttributes = searchAttributes
3925 > }
3926
3927 > hasUnversionedOrAssigned := false mutable_state_impl.go
3928 > if len(buildIds) > 0 { // len is 0 if we are removing the pinned search attribute and the workflow was never unversioned or assigned
3929 > hasUnversionedOrAssigned = worker_versioning.IsUnversionedOrAssignedBuildIdSearchAttribute(buildIds[0])
3930 > }
3931 > for {
3932 > saPayload, err := sadefs.EncodeValue(buildIds, enumspb.INDEXED_VALUE_TYPE_KEYWORD_LIST)
3933 > if err != nil {
3934 return err
3935 }
3936 > if len(buildIds) == 0 || len(saPayload.GetData()) <= maxSearchAttributeValueSize { mutable_state_impl.go
3937 > ms.updateSearchAttributes(map[string]*commonpb.Payload{sadefs.BuildIds: saPayload})
3938 > break
3939 }
3940 if len(buildIds) == 1 {
4025 usedVersion *deploymentpb.WorkerDeploymentVersion,
4026 maxSearchAttributeValueSize int,
4027 > ) (bool, error) { mutable_state_impl.go
4028 > // get all the existing SAs
4029 > existingBuildIds, err := ms.loadBuildIds()
4030 > if err != nil {
4031 return false, err
4032 }
4033 > existingUsedDeploymentVersions, err := ms.loadUsedDeploymentVersions() mutable_state_impl.go
4034 > if err != nil {
4035 return false, err
4036 }
4037 > existingDeployment, err := ms.loadSearchAttributeString(sadefs.TemporalWorkerDeployment) mutable_state_impl.go
4038 > if err != nil {
4039 return false, err
4040 }
4041 > existingVersion, err := ms.loadSearchAttributeString(sadefs.TemporalWorkerDeploymentVersion) mutable_state_impl.go
4042 > if err != nil {
4043 return false, err
4044 }
4045 > existingBehavior, err := ms.loadSearchAttributeString(sadefs.TemporalWorkflowVersioningBehavior) mutable_state_impl.go
4046 > if err != nil {
4047 return false, err
4048 }
4049
4050 // modify them
4051 > modifiedBuildIds := ms.addBuildIdToLoadedSearchAttribute(existingBuildIds, stamp) mutable_state_impl.go
4052 > modifiedUsedDeploymentVersions := ms.addUsedDeploymentVersionToLoadedSearchAttribute(existingUsedDeploymentVersions, usedVersion)
4053 > modifiedDeployment := ms.GetWorkerDeploymentSA()
4054 > modifiedVersion := ms.GetWorkerDeploymentVersionSA()
4055 > modifiedBehavior := ""
4056 > if b := ms.GetWorkflowVersioningBehaviorSA(); b != enumspb.VERSIONING_BEHAVIOR_UNSPECIFIED {
4057 modifiedBehavior = b.String()
4058 }
4059
4060 // check equality
4061 > if slices.Equal(existingBuildIds, modifiedBuildIds) && mutable_state_impl.go
4062 > slices.Equal(existingUsedDeploymentVersions, modifiedUsedDeploymentVersions) &&
4063 > existingDeployment == modifiedDeployment &&
4064 > existingVersion == modifiedVersion &&
4065 > existingBehavior == modifiedBehavior {
4066 > return false, nil mutable_state_impl.go
4067 > }
4068
4069 // save build ids if changed
4070 > if !slices.Equal(existingBuildIds, modifiedBuildIds) { mutable_state_impl.go
4071 > err = ms.saveBuildIds(modifiedBuildIds, maxSearchAttributeValueSize)
4072 > if err != nil {
4073 return false, err // if err != nil, nothing will be written
4074 }
4076
4077 // save used deployment versions if changed
4078 > if !slices.Equal(existingUsedDeploymentVersions, modifiedUsedDeploymentVersions) { mutable_state_impl.go
4079 err = ms.saveUsedDeploymentVersions(modifiedUsedDeploymentVersions, maxSearchAttributeValueSize)
4080 if err != nil {
4084
4085 // save deployment search attributes if changed
4086 > if existingDeployment != modifiedDeployment || mutable_state_impl.go
4087 > existingVersion != modifiedVersion ||
4088 > existingBehavior != modifiedBehavior {
4089 err = ms.saveDeploymentSearchAttributes(modifiedDeployment, modifiedVersion, modifiedBehavior, maxSearchAttributeValueSize)
4090 if err != nil {
4098
4099 // CheckResettable check if workflow can be reset
4100 > func (ms *MutableStateImpl) CheckResettable() error { mutable_state_impl.go
4101 > if len(ms.GetPendingChildExecutionInfos()) > 0 {
4102 return serviceerror.NewInvalidArgument("it is not allowed resetting to a point that workflow has pending child workflow.")
4103 }
4104 > if len(ms.GetPendingRequestCancelExternalInfos()) > 0 { mutable_state_impl.go
4105 return serviceerror.NewInvalidArgument("it is not allowed resetting to a point that workflow has pending request cancel.")
4106 }
4107 > if len(ms.GetPendingSignalExternalInfos()) > 0 { mutable_state_impl.go
4108 return serviceerror.NewInvalidArgument("it is not allowed resetting to a point that workflow has pending signals to send.")
4109 }
4110 > return nil mutable_state_impl.go
4111 }
4112
4115 request *workflowservice.RespondWorkflowTaskCompletedRequest,
4116 limits historyi.WorkflowTaskCompletionLimits,
4117 > ) (*historypb.HistoryEvent, error) { mutable_state_impl.go
4118 > opTag := tag.WorkflowActionWorkflowTaskCompleted
4119 > if err := ms.checkMutability(opTag); err != nil {
4120 return nil, err
4121 }
4122 > return ms.workflowTaskManager.AddWorkflowTaskCompletedEvent(workflowTask, request, limits) mutable_state_impl.go
4123 }
4124
4189 command *commandpb.ScheduleActivityTaskCommandAttributes,
4190 bypassTaskGeneration bool,
4191 > ) (*historypb.HistoryEvent, *persistencespb.ActivityInfo, error) { mutable_state_impl.go
4192 > opTag := tag.WorkflowActionActivityTaskScheduled
4193 > if err := ms.checkMutability(opTag); err != nil {
4194 return nil, nil, err
4195 }
4196
4197 > _, ok := ms.GetActivityByActivityID(command.GetActivityId()) mutable_state_impl.go
4198 > if ok {
4199 ms.logger.Warn(mutableStateInvalidHistoryActionMsg, opTag,
4200 tag.WorkflowEventID(ms.GetNextEventID()),
4203 }
4204
4205 > event, batchID := ms.hBuilder.AddActivityTaskScheduledEvent(workflowTaskCompletedEventID, command, ms.namespaceEntry.Name()) mutable_state_impl.go
4206 > ai, err := ms.ApplyActivityTaskScheduledEvent(batchID, event)
4207 > // TODO merge active & passive task generation
4208 > if !bypassTaskGeneration {
4209 > if err := ms.taskGenerator.GenerateActivityTasks( mutable_state_impl.go
4210 > event.GetEventId(),
4211 > ); err != nil {
4212 return nil, nil, err
4213 }
4214 }
4215
4216 > return event, ai, err mutable_state_impl.go
4217 }
4218
4220 batchID int64,
4221 event *historypb.HistoryEvent,
4222 > ) (*persistencespb.ActivityInfo, error) { mutable_state_impl.go
4223 >
4224 > attributes := event.GetActivityTaskScheduledEventAttributes()
4225 >
4226 > scheduledEventID := event.GetEventId()
4227 > scheduleToCloseTimeout := attributes.GetScheduleToCloseTimeout()
4228 >
4229 > ai := &persistencespb.ActivityInfo{
4230 > Version: event.GetVersion(),
4231 > ScheduledEventId: scheduledEventID,
4232 > ScheduledEventBatchId: batchID,
4233 > ScheduledTime: event.GetEventTime(),
4234 > FirstScheduledTime: event.GetEventTime(),
4235 > StartedEventId: common.EmptyEventID,
4236 > StartVersion: common.EmptyVersion,
4237 > StartedTime: nil,
4238 > ActivityId: attributes.ActivityId,
4239 > ScheduleToStartTimeout: attributes.GetScheduleToStartTimeout(),
4240 > ScheduleToCloseTimeout: scheduleToCloseTimeout,
4241 > StartToCloseTimeout: attributes.GetStartToCloseTimeout(),
4242 > HeartbeatTimeout: attributes.GetHeartbeatTimeout(),
4243 > CancelRequested: false,
4244 > CancelRequestId: common.EmptyEventID,
4245 > LastHeartbeatUpdateTime: nil,
4246 > TimerTaskStatus: TimerTaskStatusNone,
4247 > TaskQueue: attributes.TaskQueue.GetName(),
4248 > HasRetryPolicy: attributes.RetryPolicy != nil,
4249 > Attempt: 1,
4250 > ActivityType: attributes.GetActivityType(),
4251 > Priority: attributes.Priority,
4252 > }
4253 >
4254 > if attributes.UseWorkflowBuildId {
4255 if ms.GetAssignedBuildId() != "" {
4256 // only set when using new versioning
4264 }
4265
4266 > if ai.HasRetryPolicy { mutable_state_impl.go
4267 ai.RetryInitialInterval = attributes.RetryPolicy.GetInitialInterval()
4268 ai.RetryBackoffCoefficient = attributes.RetryPolicy.GetBackoffCoefficient()
4279 }
4280
4281 > ms.addPendingActivityInfo(ai) mutable_state_impl.go
4282 > ms.writeEventToCache(event)
4283 > return ai, nil
4284 }
4285
4286 > func (ms *MutableStateImpl) addPendingActivityInfo(ai *persistencespb.ActivityInfo) { mutable_state_impl.go
4287 > ms.pendingActivityInfoIDs[ai.ScheduledEventId] = ai
4288 > ms.pendingActivityIDToEventID[ai.ActivityId] = ai.ScheduledEventId
4289 > ms.updateActivityInfos[ai.ScheduledEventId] = ai
4290 > ms.activityInfosUserDataUpdated[ai.ScheduledEventId] = struct{}{}
4291 > ms.approximateSize += ai.Size() + int64SizeBytes
4292 > ms.executionInfo.ActivityCount++
4293 > }
4294
4295 func (ms *MutableStateImpl) addStartedEventForTransientActivity(
4296 scheduledEventID int64,
4297 versioningStamp *commonpb.WorkerVersionStamp,
4298 > ) error { mutable_state_impl.go
4299 > ai, ok := ms.GetActivityInfo(scheduledEventID)
4300 > if !ok || ai.StartedEventId != common.TransientEventID {
4301 > return nil mutable_state_impl.go
4302 > }
4303
4304 if versioningStamp == nil {
4346 workerControlTaskQueue string,
4347 startedClock *clockspb.VectorClock,
4348 > ) (*historypb.HistoryEvent, error) { mutable_state_impl.go
4349 > opTag := tag.WorkflowActionActivityTaskStarted
4350 > err := ms.checkMutability(opTag)
4351 > if err != nil {
4352 return nil, err
4353 }
4354
4355 > var redirectCounter int64 mutable_state_impl.go
4356 > buildId := worker_versioning.BuildIdIfUsingVersioning(versioningStamp)
4357 > if buildId != "" {
4358 // note that if versioningStamp.BuildId is present we know it's not an old versioning worker because matching
4359 // does not pass build ID for old versioning workers to Record*TaskStart.
4369 }
4370
4371 > if deployment != nil { mutable_state_impl.go
4372 ai.LastWorkerDeploymentVersion = worker_versioning.WorkerDeploymentVersionToStringV31(worker_versioning.DeploymentVersionFromDeployment(deployment))
4373 ai.LastDeploymentVersion = worker_versioning.ExternalWorkerDeploymentVersionFromDeployment(deployment)
4374 }
4375
4376 > ai.WorkerControlTaskQueue = workerControlTaskQueue mutable_state_impl.go
4377 > ai.StartedClock = startedClock
4378 >
4379 > if !ai.HasRetryPolicy {
4380 > event := ms.hBuilder.AddActivityTaskStartedEvent( mutable_state_impl.go
4381 > scheduledEventID,
4382 > ai.Attempt,
4383 > requestID,
4384 > identity,
4385 > ai.RetryLastFailure,
4386 > versioningStamp,
4387 > redirectCounter,
4388 > )
4389 > if err := ms.ApplyActivityTaskStartedEvent(event); err != nil {
4390 return nil, err
4391 }
4392 > return event, nil mutable_state_impl.go
4393 }
4394
4418 func (ms *MutableStateImpl) ApplyActivityTaskStartedEvent(
4419 event *historypb.HistoryEvent,
4420 > ) error { mutable_state_impl.go
4421 > attributes := event.GetActivityTaskStartedEventAttributes()
4422 > scheduledEventID := attributes.GetScheduledEventId()
4423 > ai, ok := ms.GetActivityInfo(scheduledEventID)
4424 > if !ok {
4425 ms.logError(
4426 fmt.Sprintf("unable to find activity event id: %v in mutable state", scheduledEventID),
4430 }
4431
4432 > ms.approximateSize -= ai.Size() mutable_state_impl.go
4433 >
4434 > ai.Version = event.GetVersion()
4435 > ai.StartedEventId = event.GetEventId()
4436 > ai.StartVersion = event.GetVersion()
4437 > ai.RequestId = attributes.GetRequestId()
4438 > ai.StartedTime = event.GetEventTime()
4439 > ms.updateActivityInfos[ai.ScheduledEventId] = ai
4440 > ms.activityInfosUserDataUpdated[ai.ScheduledEventId] = struct{}{}
4441 > ms.approximateSize += ai.Size()
4442 >
4443 > err := ms.applyActivityBuildIdRedirect(ai, worker_versioning.BuildIdIfUsingVersioning(attributes.GetWorkerVersion()), attributes.GetBuildIdRedirectCounter())
4444 > return err
4445 }
4446
4447 > func (ms *MutableStateImpl) applyActivityBuildIdRedirect(activityInfo *persistencespb.ActivityInfo, buildId string, redirectCounter int64) error { mutable_state_impl.go
4448 > if buildId == "" {
4449 > return nil // not versioned
4450 > }
4451
4452 if useWf := activityInfo.GetUseWorkflowBuildIdInfo(); useWf != nil {
4617 scheduledEventID int64,
4618 _ string,
4619 > ) (*historypb.HistoryEvent, *persistencespb.ActivityInfo, error) { mutable_state_impl.go
4620 > opTag := tag.WorkflowActionActivityTaskCancelRequested
4621 > if err := ms.checkMutability(opTag); err != nil {
4622 return nil, nil, err
4623 }
4624
4625 > ai, ok := ms.GetActivityInfo(scheduledEventID) mutable_state_impl.go
4626 > if !ok {
4627 // It is possible both started and completed events are buffered for this activity
4628 if !ms.hBuilder.HasActivityFinishEvent(scheduledEventID) {
4638
4639 // Check for duplicate cancellation
4640 > if ok && ai.CancelRequested { mutable_state_impl.go
4641 ms.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
4642 tag.WorkflowEventID(ms.GetNextEventID()),
4649
4650 // At this point we know this is a valid activity cancellation request
4651 > actCancelReqEvent := ms.hBuilder.AddActivityTaskCancelRequestedEvent(workflowTaskCompletedEventID, scheduledEventID) mutable_state_impl.go
4652 >
4653 > if err := ms.ApplyActivityTaskCancelRequestedEvent(actCancelReqEvent); err != nil {
4654 return nil, nil, err
4655 }
4656
4657 > return actCancelReqEvent, ai, nil mutable_state_impl.go
4658 }
4659
4739 func (ms *MutableStateImpl) ApplyActivityTaskCancelRequestedEvent(
4740 event *historypb.HistoryEvent,
4741 > ) error { mutable_state_impl.go
4742 > attributes := event.GetActivityTaskCancelRequestedEventAttributes()
4743 > scheduledEventID := attributes.GetScheduledEventId()
4744 > ai, ok := ms.GetActivityInfo(scheduledEventID)
4745 > if !ok {
4746 // This will only be called on active cluster if activity info is found in mutable state
4747 // Passive side logic should always have activity info in mutable state if this is called, as the only
4751 }
4752
4753 > ms.approximateSize -= ai.Size() mutable_state_impl.go
4754 >
4755 > ai.Version = event.GetVersion()
4756 >
4757 > // - We have the activity dispatched to worker.
4758 > // - The activity might not be heartbeat'ing, but the activity can still call RecordActivityHeartBeat()
4759 > // to see cancellation while reporting progress of the activity.
4760 > ai.CancelRequested = true
4761 >
4762 > ai.CancelRequestId = event.GetEventId()
4763 > ms.updateActivityInfos[ai.ScheduledEventId] = ai
4764 > ms.activityInfosUserDataUpdated[ai.ScheduledEventId] = struct{}{}
4765 > ms.approximateSize += ai.Size()
4766 > return nil
4767 }
4768
4773 details *commonpb.Payloads,
4774 identity string,
4775 > ) (*historypb.HistoryEvent, error) { mutable_state_impl.go
4776 > opTag := tag.WorkflowActionActivityTaskCanceled
4777 > if err := ms.checkMutability(opTag); err != nil {
4778 return nil, err
4779 }
4780
4781 > ai, ok := ms.GetActivityInfo(scheduledEventID) mutable_state_impl.go
4782 > if !ok || ai.StartedEventId != startedEventID {
4783 ms.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
4784 tag.WorkflowEventID(ms.GetNextEventID()),
4789
4790 // Verify cancel request as well.
4791 > if !ai.CancelRequested { mutable_state_impl.go
4792 ms.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
4793 tag.WorkflowEventID(ms.GetNextEventID()),
4799 }
4800
4801 > if err := ms.addStartedEventForTransientActivity(scheduledEventID, nil); err != nil { mutable_state_impl.go
4802 return nil, err
4803 }
4804 > event := ms.hBuilder.AddActivityTaskCanceledEvent( mutable_state_impl.go
4805 > scheduledEventID,
4806 > startedEventID,
4807 > latestCancelRequestedEventID,
4808 > details,
4809 > identity,
4810 > )
4811 > if err := ms.ApplyActivityTaskCanceledEvent(event); err != nil {
4812 return nil, err
4813 }
4814
4815 > return event, nil mutable_state_impl.go
4816 }
4817
4818 func (ms *MutableStateImpl) ApplyActivityTaskCanceledEvent(
4819 event *historypb.HistoryEvent,
4820 > ) error { mutable_state_impl.go
4821 > attributes := event.GetActivityTaskCanceledEventAttributes()
4822 > scheduledEventID := attributes.GetScheduledEventId()
4823 >
4824 > return ms.DeleteActivity(scheduledEventID)
4825 > }
4826
4827 func (ms *MutableStateImpl) AddCompletedWorkflowEvent(
6305 newExecutionStartTime time.Time,
6306 namespaceRetention time.Duration,
6307 > ) *workflowpb.ResetPoints { mutable_state_impl.go
6308 > if resetPoints.GetPoints() == nil {
6309 > return resetPoints
6310 > }
6311 newPoints := make([]*workflowpb.ResetPointInfo, 0, len(resetPoints.Points))
6312 // For continue-as-new, new execution start time is the same as previous execution close time,
7043 }
7044
7045 > func (ms *MutableStateImpl) RemoveReportedProblemsSearchAttribute() error { mutable_state_impl.go
7046 > if ms.executionInfo.SearchAttributes == nil {
7047 return nil
7048 }
7049
7050 > temporalReportedProblems := ms.executionInfo.SearchAttributes[sadefs.TemporalReportedProblems] mutable_state_impl.go
7051 > if temporalReportedProblems == nil {
7052 > return nil
7053 > }
7054
7055 // Log the removal of the search attribute
7140 }
7141
7142 > func (ms *MutableStateImpl) AddExternalPayloadSize(size int64) { mutable_state_impl.go
7143 > if ms.executionInfo.ExecutionStats == nil {
7144 ms.executionInfo.ExecutionStats = &persistencespb.ExecutionStats{}
7145 }
7146 > ms.executionInfo.ExecutionStats.ExternalPayloadSize += size mutable_state_impl.go
7147 }
7148
7151 }
7152
7153 > func (ms *MutableStateImpl) AddExternalPayloadCount(count int64) { mutable_state_impl.go
7154 > if ms.executionInfo.ExecutionStats == nil {
7155 ms.executionInfo.ExecutionStats = &persistencespb.ExecutionStats{}
7156 }
7157 > ms.executionInfo.ExecutionStats.ExternalPayloadCount += count mutable_state_impl.go
7158 }
7159
7254 func (ms *MutableStateImpl) AddTasks(
7255 newTasks ...tasks.Task,
7257 > now := ms.Now()
7258 > for _, task := range newTasks {
7259 > if chasmTask, ok := task.(*tasks.ChasmTask); ok &&
7260 > chasmTask.GetCategory() == tasks.CategoryVisibility &&
7261 > ms.stateInDB == enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED {
7262 softassert.Fail(ms.logger, "CHASM visibility task added on already-closed execution")
7263 }
7264
7265 > category := task.GetCategory() mutable_state_impl.go
7266 > // Drop tasks scheduled too far in the future. VisibilityTime hasn't been
7267 > // shifted to wall-clock yet (the conversion runs below), so both sides are
7268 > // virtual here; the difference is frame-invariant (skip cancels). Keep
7269 > // `now` from ms.Now() so both stay in the same frame.
7270 > if category.Type() == tasks.CategoryTypeScheduled &&
7271 > task.GetVisibilityTime().Sub(now) > maxScheduledTaskDuration {
7272 ms.logger.Info("Dropped long duration scheduled task.", tasks.Tags(task)...)
7273 continue
7279 // vs. real distinction. The CategoryTypeScheduled drop-check above runs first so it
7280 // compares virtual-vs-virtual (now is also virtual).
7281 > if category.Type() == tasks.CategoryTypeScheduled { mutable_state_impl.go
7282 > task.SetVisibilityTime(ms.ToRealTime(task.GetVisibilityTime())) mutable_state_impl.go
7283 > }
7284
7285 > if chasmPureTask, ok := task.(*tasks.ChasmTaskPure); ok { mutable_state_impl.go
7286 ms.chasmPureTasks = append(ms.chasmPureTasks, chasmPureTask)
7287 maxPureTasks := ms.config.ChasmMaxInMemoryPureTasks()
7296 }
7297
7298 > ms.InsertTasks[category] = append(ms.InsertTasks[category], task) mutable_state_impl.go
7299 }
7300 }
7360 }
7361
7362 > func (ms *MutableStateImpl) RemoveSpeculativeWorkflowTaskTimeoutTask() { mutable_state_impl.go
7363 > if ms.speculativeWorkflowTaskTimeoutTask != nil {
7364 // Cancelling task prevents it from being submitted to scheduler in memoryScheduledQueue.
7365 ms.speculativeWorkflowTaskTimeoutTask.Cancel()
7368 }
7369
7370 > func (ms *MutableStateImpl) SetWorkflowTaskScheduleToStartTimeoutTask(task *tasks.WorkflowTaskTimeoutTask) { mutable_state_impl.go
7371 > ms.wftScheduleToStartTimeoutTask = task
7372 > }
7373
7374 > func (ms *MutableStateImpl) SetWorkflowTaskStartToCloseTimeoutTask(task *tasks.WorkflowTaskTimeoutTask) { mutable_state_impl.go
7375 > ms.wftStartToCloseTimeoutTask = task
7376 > }
7377
7378 > func (ms *MutableStateImpl) GetWorkflowTaskScheduleToStartTimeoutTask() *tasks.WorkflowTaskTimeoutTask { mutable_state_impl.go
7379 > return ms.wftScheduleToStartTimeoutTask
7380 > }
7381
7382 > func (ms *MutableStateImpl) GetWorkflowTaskStartToCloseTimeoutTask() *tasks.WorkflowTaskTimeoutTask { mutable_state_impl.go
7383 > return ms.wftStartToCloseTimeoutTask
7384 > }
7385
7386 > func (ms *MutableStateImpl) GetWorkflowStateStatus() (enumsspb.WorkflowExecutionState, enumspb.WorkflowExecutionStatus) { mutable_state_impl.go
7387 > return ms.executionState.State, ms.executionState.Status
7388 > }
7389
7390 func (ms *MutableStateImpl) UpdateWorkflowStateStatus(
7391 state enumsspb.WorkflowExecutionState,
7392 status enumspb.WorkflowExecutionStatus,
7393 > ) (bool, error) { mutable_state_impl.go
7394 > if state == ms.executionState.State && status == ms.executionState.Status {
7395 > return false, nil mutable_state_impl.go
7396 > }
7397 > if state != enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE && mutable_state_impl.go
7398 > ms.executionState.State != enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE {
7399 > // Suppress and Revive workflows are cluster local operations. mutable_state_impl.go
7400 > ms.executionStateUpdated = true
7401 > ms.visibilityUpdated = true // workflow status & state change triggers visibility change as well
7402 > }
7403 > return true, setStateStatus(ms.executionState, state, status) mutable_state_impl.go
7404 }
7405
7407 // However, certain in-memory changes (e.g. speculative workflow task) won't be cleared before releasing
7408 // the lock and have to be excluded from the check.
7409 > func (ms *MutableStateImpl) IsDirty() bool { mutable_state_impl.go
7410 > return ms.hBuilder.IsDirty() ||
7411 > len(ms.InsertTasks) > 0 ||
7412 > (ms.stateMachineNode != nil && ms.stateMachineNode.Dirty()) ||
7413 > ms.chasmTree.IsDirty()
7414 > }
7415
7416 // isStateDirty is used upon closing transaction to determine if application data has been updated, and
7417 // mutable state should move to a new versioned transition.
7418 > func (ms *MutableStateImpl) isStateDirty() bool { mutable_state_impl.go
7419 > // TODO: we need to track more workflow state changes
7420 > // e.g. changes to executionInfo.CancelRequested
7421 > // They are mostly covered by history builder check today.
7422 > return ms.hBuilder.IsDirty() ||
7423 > len(ms.activityInfosUserDataUpdated) > 0 ||
7424 > len(ms.deleteActivityInfos) > 0 ||
7425 > len(ms.timerInfosUserDataUpdated) > 0 ||
7426 > len(ms.deleteTimerInfos) > 0 ||
7427 > len(ms.updateChildExecutionInfos) > 0 ||
7428 > len(ms.deleteChildExecutionInfos) > 0 ||
7429 > len(ms.updateRequestCancelInfos) > 0 ||
7430 > len(ms.deleteRequestCancelInfos) > 0 ||
7431 > len(ms.updateSignalInfos) > 0 ||
7432 > len(ms.deleteSignalInfos) > 0 ||
7433 > len(ms.updateSignalRequestedIDs) > 0 ||
7434 > len(ms.deleteSignalRequestedIDs) > 0 ||
7435 > len(ms.updateInfoUpdated) > 0 ||
7436 > ms.visibilityUpdated ||
7437 > ms.executionStateUpdated ||
7438 > ms.workflowTaskUpdated ||
7439 > (ms.stateMachineNode != nil && ms.stateMachineNode.Dirty()) ||
7440 > ms.chasmTree.IsStateDirty() ||
7441 > ms.isResetStateUpdated ||
7442 > ms.timeSkippingInfoUpdated
7443 > }
7444
7445 func (ms *MutableStateImpl) IsTransitionHistoryEnabled() bool {
7449 func (ms *MutableStateImpl) StartTransaction(
7450 namespaceEntry *namespace.Namespace,
7451 > ) (bool, error) { mutable_state_impl.go
7452 > if ms.IsDirty() {
7453 ms.logger.Error("MutableState encountered dirty transaction",
7454 tag.WorkflowNamespaceID(ms.executionInfo.NamespaceId),
7461 }
7462
7463 > ms.transitionHistoryEnabled = ms.config.EnableTransitionHistory(namespaceEntry.Name().String()) mutable_state_impl.go
7464 >
7465 > namespaceEntry, err := ms.startTransactionHandleNamespaceMigration(namespaceEntry)
7466 > if err != nil {
7467 return false, err
7468 }
7469 > ms.namespaceEntry = namespaceEntry mutable_state_impl.go
7470 > if err := ms.UpdateCurrentVersion(namespaceEntry.FailoverVersion(ms.executionInfo.WorkflowId), false); err != nil {
7471 return false, err
7472 }
7473
7474 > flushBeforeReady, err := ms.startTransactionHandleWorkflowTaskFailover() mutable_state_impl.go
7475 > if err != nil {
7476 return false, err
7477 }
7478
7479 > return flushBeforeReady, nil mutable_state_impl.go
7480 }
7481
7483 ctx context.Context,
7484 transactionPolicy historyi.TransactionPolicy,
7485 > ) (*persistence.WorkflowMutation, []*persistence.WorkflowEvents, error) { mutable_state_impl.go
7486 > result, err := ms.closeTransaction(ctx, transactionPolicy)
7487 > if err != nil {
7488 return nil, nil, err
7489 }
7490
7491 > if result.skipPersistence { mutable_state_impl.go
7492 if err := ms.cleanupTransaction(); err != nil {
7493 return nil, nil, err
7496 }
7497
7498 > workflowMutation := &persistence.WorkflowMutation{ mutable_state_impl.go
7499 > ExecutionInfo: ms.executionInfo,
7500 > ExecutionState: ms.executionState,
7501 > NextEventID: ms.hBuilder.NextEventID(),
7502 >
7503 > UpsertActivityInfos: ms.updateActivityInfos,
7504 > DeleteActivityInfos: ms.deleteActivityInfos,
7505 > UpsertTimerInfos: ms.updateTimerInfos,
7506 > DeleteTimerInfos: ms.deleteTimerInfos,
7507 > UpsertChildExecutionInfos: ms.updateChildExecutionInfos,
7508 > DeleteChildExecutionInfos: ms.deleteChildExecutionInfos,
7509 > UpsertRequestCancelInfos: ms.updateRequestCancelInfos,
7510 > DeleteRequestCancelInfos: ms.deleteRequestCancelInfos,
7511 > UpsertSignalInfos: ms.updateSignalInfos,
7512 > DeleteSignalInfos: ms.deleteSignalInfos,
7513 > UpsertSignalRequestedIDs: ms.updateSignalRequestedIDs,
7514 > DeleteSignalRequestedIDs: ms.deleteSignalRequestedIDs,
7515 > UpsertChasmNodes: result.chasmNodesMutation.UpdatedNodes,
7516 > DeleteChasmNodes: result.chasmNodesMutation.DeletedNodes,
7517 > NewBufferedEvents: result.bufferEvents,
7518 > ClearBufferedEvents: result.clearBuffer,
7519 >
7520 > Tasks: ms.InsertTasks,
7521 > BestEffortDeleteTasks: ms.BestEffortDeleteTasks,
7522 >
7523 > Condition: ms.nextEventIDInDB,
7524 > DBRecordVersion: ms.dbRecordVersion,
7525 > Checksum: result.checksum,
7526 > }
7527 >
7528 > ms.checksum = result.checksum
7529 > if err := ms.cleanupTransaction(); err != nil {
7530 return nil, nil, err
7531 }
7532 > return workflowMutation, result.workflowEventsSeq, nil mutable_state_impl.go
7533 }
7534
7536 ctx context.Context,
7537 transactionPolicy historyi.TransactionPolicy,
7538 > ) (*persistence.WorkflowSnapshot, []*persistence.WorkflowEvents, error) { mutable_state_impl.go
7539 > result, err := ms.closeTransaction(ctx, transactionPolicy)
7540 > if err != nil {
7541 return nil, nil, err
7542 }
7543
7544 > if len(result.bufferEvents) > 0 { mutable_state_impl.go
7545 // TODO do we need the functionality to generate snapshot with buffered events?
7546 return nil, nil, softassert.UnexpectedInternalErr(
7551 }
7552
7553 > workflowSnapshot := &persistence.WorkflowSnapshot{ mutable_state_impl.go
7554 > ExecutionInfo: ms.executionInfo,
7555 > ExecutionState: ms.executionState,
7556 > NextEventID: ms.hBuilder.NextEventID(),
7557 >
7558 > ActivityInfos: ms.pendingActivityInfoIDs,
7559 > TimerInfos: ms.pendingTimerInfoIDs,
7560 > ChildExecutionInfos: ms.pendingChildExecutionInfoIDs,
7561 > RequestCancelInfos: ms.pendingRequestCancelInfoIDs,
7562 > SignalInfos: ms.pendingSignalInfoIDs,
7563 > SignalRequestedIDs: ms.pendingSignalRequestedIDs,
7564 > ChasmNodes: ms.chasmTree.Snapshot(nil).Nodes,
7565 >
7566 > Tasks: ms.InsertTasks,
7567 >
7568 > Condition: ms.nextEventIDInDB,
7569 > DBRecordVersion: ms.dbRecordVersion,
7570 > Checksum: result.checksum,
7571 > }
7572 >
7573 > ms.checksum = result.checksum
7574 > if err := ms.cleanupTransaction(); err != nil {
7575 return nil, nil, err
7576 }
7577 > return workflowSnapshot, result.workflowEventsSeq, nil mutable_state_impl.go
7578 }
7579
7599 func (ms *MutableStateImpl) updateSearchAttributes(
7600 updatedPayloadMap map[string]*commonpb.Payload,
7602 > ms.executionInfo.SearchAttributes = payload.MergeMapOfPayload(
7603 > ms.executionInfo.SearchAttributes,
7604 > updatedPayloadMap,
7605 > )
7606 > ms.visibilityUpdated = true
7607 > }
7608
7609 func (ms *MutableStateImpl) updateMemo(
7628 func (ms *MutableStateImpl) SetContextMetadata(
7629 ctx context.Context,
7631 > switch ms.chasmTree.ArchetypeID() {
7632 > case chasm.WorkflowArchetypeID, chasm.UnspecifiedArchetypeID: mutable_state_impl.go
7633 > // Set workflow type
7634 > if wfType := ms.GetWorkflowType(); wfType != nil && wfType.GetName() != "" {
7635 > contextutil.ContextMetadataSet(ctx, contextutil.MetadataKeyWorkflowType, wfType.GetName()) mutable_state_impl.go
7636 > }
7637
7638 // Set workflow task queue
7639 > if ms.executionInfo != nil && ms.executionInfo.TaskQueue != "" { mutable_state_impl.go
7640 > contextutil.ContextMetadataSet(ctx, contextutil.MetadataKeyWorkflowTaskQueue, ms.executionInfo.TaskQueue) mutable_state_impl.go
7641 > }
7642
7643 > for _, activityID := range contextutil.ContextMetadataGetMarkedActivityIDs(ctx) { mutable_state_impl.go
7644 if ai, ok := ms.GetActivityByActivityID(activityID); ok {
7645 contextutil.ContextMetadataSet(ctx, contextutil.ActivityTypeKey(ai.ScheduledEventId), ai.ActivityType.GetName())
7660 ctx context.Context,
7661 transactionPolicy historyi.TransactionPolicy,
7662 > ) (closeTransactionResult, error) { mutable_state_impl.go
7663 > ms.SetContextMetadata(ctx)
7664 >
7665 > if err := ms.closeTransactionWithPolicyCheck(
7666 > transactionPolicy,
7667 > ); err != nil {
7668 return closeTransactionResult{}, err
7669 }
7670
7671 > if err := ms.closeTransactionHandleWorkflowTask( mutable_state_impl.go
7672 > transactionPolicy,
7673 > ); err != nil {
7674 return closeTransactionResult{}, err
7675 }
7681 // and need to reconsider the sequence of time skipping close trx handling in this function
7682 // when supporting chasm.
7683 > regenTimerTasksForWorkflowTimeSkipping := ms.closeTransactionHandleWorkflowTimeSkipping(ctx, transactionPolicy) mutable_state_impl.go
7684 >
7685 > // Save if the state is dirty before closeTransactionPrepareEvents since it flushes the buffer
7686 > // events, and therefore change the dirty state.
7687 > isStateDirty := ms.isStateDirty()
7688 >
7689 > // closeTransactionPrepareEvents must be called after closeTransactionHandleWorkflowTask because
7690 > // the latter might fail the workflow task and buffered events must be flushed afterwards.
7691 > // We need to save the value of ms.isStateDirty() before calling closeTransactionPrepareEvents
7692 > // because flushing the buffered events might change the dirty state.
7693 > workflowEventsSeq, eventBatches, bufferEvents, clearBuffer, err := ms.closeTransactionPrepareEvents(transactionPolicy)
7694 > if err != nil {
7695 return closeTransactionResult{}, err
7696 }
7699 // cluster — standby (passive) replays events that were already stamped by
7700 // the active side, and we must not overwrite those principals.
7701 > if transactionPolicy == historyi.TransactionPolicyActive { mutable_state_impl.go
7702 > principal := headers.GetPrincipal(ctx) mutable_state_impl.go
7703 > for _, we := range workflowEventsSeq {
7704 > for _, event := range we.Events { mutable_state_impl.go
7705 > // Skip events that already have a principal. Those are previously
7706 > // buffered events (e.g., signals) that were stamped when originally
7707 > // created and are now being flushed into history by a different caller
7708 > // (e.g., the worker completing a workflow task).
7709 > if event.Principal == nil {
7710 > event.Principal = principal
7711 > }
7712 }
7713 }
7714 > for _, event := range bufferEvents { mutable_state_impl.go
7715 event.Principal = principal
7716 }
7719 // CloseTransaction() on chasmTree may update execution state & status,
7720 // so must be called before closeTransactionUpdateTransitionHistory().
7721 > chasmNodesMutation, err := ms.chasmTree.CloseTransaction() mutable_state_impl.go
7722 > if err != nil {
7723 return closeTransactionResult{}, err
7724 }
7725
7726 > if ms.closeTransactionShouldSkipPersistence(isStateDirty, chasmNodesMutation) { mutable_state_impl.go
7727 return closeTransactionResult{
7728 skipPersistence: true,
7730 }
7731
7732 > for nodePath := range chasmNodesMutation.DeletedNodes { mutable_state_impl.go
7733 ms.approximateSize -= ms.chasmNodeSizes[nodePath]
7734 delete(ms.chasmNodeSizes, nodePath)
7735 }
7736 > for nodePath, node := range chasmNodesMutation.UpdatedNodes { mutable_state_impl.go
7737 newSize := len(nodePath) + node.Size()
7738 ms.approximateSize += newSize - ms.chasmNodeSizes[nodePath]
7740 }
7741
7742 > if isStateDirty { mutable_state_impl.go
7743 > if err := ms.closeTransactionUpdateTransitionHistory( mutable_state_impl.go
7744 > transactionPolicy,
7745 > ); err != nil {
7746 return closeTransactionResult{}, err
7747 }
7748 > ms.closeTransactionHandleUnknownVersionedTransition() mutable_state_impl.go
7749 > ms.closeTransactionUpdateLastRunningClock(transactionPolicy, workflowEventsSeq)
7750 }
7751
7752 // todo@TimeSkipping, we can move update versioned transition to inside closeTransactionHandleWorkflowTimeSkipping
7753 > ms.closeTransactionTrackLastUpdateVersionedTransition( mutable_state_impl.go
7754 > transactionPolicy,
7755 > )
7756 >
7757 > ms.closeTransactionTrackTombstones(transactionPolicy, chasmNodesMutation)
7758 >
7759 > // generate tasks
7760 > if err := ms.closeTransactionPrepareTasks(
7761 > transactionPolicy,
7762 > eventBatches,
7763 > clearBuffer,
7764 > regenTimerTasksForWorkflowTimeSkipping,
7765 > ); err != nil {
7766 return closeTransactionResult{}, err
7767 }
7768
7769 > ms.executionInfo.StateTransitionCount += 1 mutable_state_impl.go
7770 > ms.executionInfo.LastUpdateTime = timestamppb.New(ms.timeSource.Now())
7771 >
7772 > // We generate checksum here based on the assumption that the returned
7773 > // snapshot object is considered immutable. As of this writing, the only
7774 > // code that modifies the returned object lives inside Context.resetWorkflowExecution.
7775 > // Currently, the updates done inside Context.resetWorkflowExecution don't
7776 > // impact the checksum calculation.
7777 > checksum := ms.generateChecksum()
7778 >
7779 > if ms.dbRecordVersion == 0 {
7780 > // noop, existing behavior mutable_state_impl.go
7781 > } else { mutable_state_impl.go
7782 > ms.dbRecordVersion += 1 mutable_state_impl.go
7783 > }
7784
7785 > return closeTransactionResult{ mutable_state_impl.go
7786 > workflowEventsSeq: workflowEventsSeq,
7787 > bufferEvents: bufferEvents,
7788 > clearBuffer: clearBuffer,
7789 > checksum: checksum,
7790 > chasmNodesMutation: chasmNodesMutation,
7791 > }, nil
7792 }
7793
7794 > func (ms *MutableStateImpl) closeTransactionShouldSkipPersistence(isStateDirty bool, chasmNodesMutation chasm.NodesMutation) bool { mutable_state_impl.go
7795 > return !ms.IsWorkflow() && !isStateDirty && chasmNodesMutation.IsEmpty()
7796 > }
7797
7798 func (ms *MutableStateImpl) closeTransactionHandleWorkflowTask(
7799 transactionPolicy historyi.TransactionPolicy,
7800 > ) error { mutable_state_impl.go
7801 > if err := ms.closeTransactionHandleBufferedEventsLimit(
7802 > transactionPolicy,
7803 > ); err != nil {
7804 return err
7805 }
7806
7807 > if err := ms.closeTransactionHandleWorkflowTaskScheduling( mutable_state_impl.go
7808 > transactionPolicy,
7809 > ); err != nil {
7810 return err
7811 }
7812
7813 > return ms.closeTransactionHandleSpeculativeWorkflowTask(transactionPolicy) mutable_state_impl.go
7814 }
7815
7816 func (ms *MutableStateImpl) closeTransactionHandleWorkflowTaskScheduling(
7817 transactionPolicy historyi.TransactionPolicy,
7818 > ) error { mutable_state_impl.go
7819 > if transactionPolicy == historyi.TransactionPolicyPassive ||
7820 > !ms.IsWorkflowExecutionRunning() {
7821 return nil
7822 }
7823
7824 > for _, t := range ms.currentTransactionAddedStateMachineEventTypes { mutable_state_impl.go
7825 def, ok := ms.shard.StateMachineRegistry().EventDefinition(t)
7826 if !ok {
7840 }
7841
7842 > return nil mutable_state_impl.go
7843 }
7844
7845 func (ms *MutableStateImpl) closeTransactionHandleSpeculativeWorkflowTask(
7846 transactionPolicy historyi.TransactionPolicy,
7847 > ) error { mutable_state_impl.go
7848 > if transactionPolicy == historyi.TransactionPolicyPassive ||
7849 > !ms.IsWorkflowExecutionRunning() {
7850 return nil
7851 }
7854 // because prepareEventsAndReplicationTasks will move internal buffered events to the history,
7855 // and WT related events (WTScheduled, in particular) need to go first.
7856 > return ms.workflowTaskManager.convertSpeculativeWorkflowTaskToNormal() mutable_state_impl.go
7857 }
7858
7859 func (ms *MutableStateImpl) closeTransactionUpdateTransitionHistory(
7860 transactionPolicy historyi.TransactionPolicy,
7861 > ) error { mutable_state_impl.go
7862 > if transactionPolicy != historyi.TransactionPolicyActive {
7863 // TODO: replication/standby logic will need a different way for updating transition history
7864 // when not syncing mutable state
7866 }
7867
7868 > if !ms.transitionHistoryEnabled { mutable_state_impl.go
7869 return nil
7870 }
7871
7872 // handle disable then re-enable of transition history
7873 > if len(ms.executionInfo.TransitionHistory) == 0 && len(ms.executionInfo.PreviousTransitionHistory) != 0 { mutable_state_impl.go
7874 ms.executionInfo.TransitionHistory = ms.executionInfo.PreviousTransitionHistory
7875 ms.executionInfo.PreviousTransitionHistory = nil
7876 }
7877
7878 > ms.executionInfo.TransitionHistory = UpdatedTransitionHistory( mutable_state_impl.go
7879 > ms.executionInfo.TransitionHistory,
7880 > ms.GetCurrentVersion(),
7881 > )
7882 >
7883 > return nil
7884 }
7885
7886 func (ms *MutableStateImpl) closeTransactionTrackLastUpdateVersionedTransition(
7887 transactionPolicy historyi.TransactionPolicy,
7889 > if transactionPolicy != historyi.TransactionPolicyActive {
7890 // TODO: replication/standby logic will need a different way for updating LastUpdatedVersionedTransition
7891 // when reapplying history, especially when history replication tasks got batched.
7893 }
7894
7895 > if !ms.transitionHistoryEnabled { mutable_state_impl.go
7896 // transition history is not enabled
7897 return
7898 }
7899 // transaction closed without any state change
7900 > if len(ms.executionInfo.TransitionHistory) == 0 { mutable_state_impl.go
7901 return
7902 }
7903
7904 > currentVersionedTransition := ms.CurrentVersionedTransition() mutable_state_impl.go
7905 > for activityId := range ms.activityInfosUserDataUpdated {
7906 > ms.updateActivityInfos[activityId].LastUpdateVersionedTransition = currentVersionedTransition mutable_state_impl.go
7907 > }
7908 > for timerId := range ms.timerInfosUserDataUpdated { mutable_state_impl.go
7909 ms.updateTimerInfos[timerId].LastUpdateVersionedTransition = currentVersionedTransition
7910 }
7911 > for _, childInfo := range ms.updateChildExecutionInfos { mutable_state_impl.go
7912 childInfo.LastUpdateVersionedTransition = currentVersionedTransition
7913 }
7914 > for _, cancelInfo := range ms.updateRequestCancelInfos { mutable_state_impl.go
7915 cancelInfo.LastUpdateVersionedTransition = currentVersionedTransition
7916 }
7917 > for _, signalInfo := range ms.updateSignalInfos { mutable_state_impl.go
7918 signalInfo.LastUpdateVersionedTransition = currentVersionedTransition
7919 }
7922 // signal requestedID.
7923 // Deletion of signalRequestID is not replicated today, so we can even drop the check on deleteSignalRequestedIDs
7924 > if len(ms.updateSignalRequestedIDs) != 0 || len(ms.deleteSignalRequestedIDs) != 0 { mutable_state_impl.go
7925 ms.executionInfo.SignalRequestIdsLastUpdateVersionedTransition = currentVersionedTransition
7926 }
7927
7928 > for updateID := range ms.updateInfoUpdated { mutable_state_impl.go
7929 ms.executionInfo.UpdateInfos[updateID].LastUpdateVersionedTransition = currentVersionedTransition
7930 }
7931
7932 > if ms.workflowTaskUpdated { mutable_state_impl.go
7933 > ms.executionInfo.WorkflowTaskLastUpdateVersionedTransition = currentVersionedTransition mutable_state_impl.go
7934 > }
7935
7936 > if ms.visibilityUpdated { mutable_state_impl.go
7937 > ms.executionInfo.VisibilityLastUpdateVersionedTransition = currentVersionedTransition mutable_state_impl.go
7938 > }
7939
7940 > if ms.executionStateUpdated { mutable_state_impl.go
7941 > ms.executionState.LastUpdateVersionedTransition = currentVersionedTransition mutable_state_impl.go
7942 > }
7943
7944 > if ms.timeSkippingInfoUpdated && ms.executionInfo.TimeSkippingInfo != nil { mutable_state_impl.go
7945 ms.executionInfo.TimeSkippingInfo.LastUpdateVersionedTransition = currentVersionedTransition
7946 }
7950 }
7951
7952 > func (ms *MutableStateImpl) closeTransactionHandleUnknownVersionedTransition() { mutable_state_impl.go
7953 > if len(ms.executionInfo.TransitionHistory) != 0 {
7954 > if transitionhistory.Compare( mutable_state_impl.go
7955 > ms.versionedTransitionInDB,
7956 > ms.CurrentVersionedTransition(),
7957 > ) != 0 {
7958 > // versioned transition updated in the transaction
7959 > return
7960 > }
7961 }
7962
8017 transactionPolicy historyi.TransactionPolicy,
8018 workflowEventsSeq []*persistence.WorkflowEvents,
8020 > if transactionPolicy != historyi.TransactionPolicyActive {
8021 return
8022 }
8024 // Events can only be generated while mutable state is running,
8025 // so we can update LastRunningClock blindly.
8026 > if len(workflowEventsSeq) > 0 { mutable_state_impl.go
8027 > lastEvents := workflowEventsSeq[len(workflowEventsSeq)-1].Events mutable_state_impl.go
8028 > lastEvent := lastEvents[len(lastEvents)-1]
8029 > ms.executionInfo.LastRunningClock = lastEvent.GetTaskId()
8030 > return
8031 > }
8032
8033 > if !ms.IsWorkflowExecutionRunning() && !ms.IsCurrentWorkflowGuaranteed() { mutable_state_impl.go
8034 // If workflow currently is not running and also not running at the beginning of the transaction,
8035 // then don't update the lastRunningClock
8038 }
8039
8040 > ms.executionInfo.LastRunningClock = ms.shard.CurrentVectorClock().GetClock() mutable_state_impl.go
8041 }
8042
8044 transactionPolicy historyi.TransactionPolicy,
8045 chasmNodesMutation chasm.NodesMutation,
8047 > if transactionPolicy != historyi.TransactionPolicyActive {
8048 // Passive/Replication logic will update tombstone list when applying mutable state
8049 // snapshot or mutation.
8051 }
8052
8053 > if !ms.transitionHistoryEnabled { mutable_state_impl.go
8054 // transition history is not enabled
8055 return
8056 }
8057
8058 > if len(ms.executionInfo.TransitionHistory) == 0 { mutable_state_impl.go
8059 // in an unknown state
8060 return
8061 }
8062
8063 > var tombstones []*persistencespb.StateMachineTombstone mutable_state_impl.go
8064 > if ms.stateMachineNode != nil {
8065 > opLog, err := ms.stateMachineNode.OpLog()
8066 > if err != nil {
8067 panic(fmt.Sprintf("Failed to get HSM operation log: %v", err))
8068 }
8069
8070 > for _, op := range opLog { mutable_state_impl.go
8071 if deleteOp, ok := op.(hsm.DeleteOperation); ok {
8072 path := deleteOp.Path()
8095 }
8096
8097 > for scheduledEventID := range ms.deleteActivityInfos { mutable_state_impl.go
8098 > tombstones = append(tombstones, &persistencespb.StateMachineTombstone{ mutable_state_impl.go
8099 > StateMachineKey: &persistencespb.StateMachineTombstone_ActivityScheduledEventId{
8100 > ActivityScheduledEventId: scheduledEventID,
8101 > },
8102 > })
8103 > }
8104 > for timerID := range ms.deleteTimerInfos { mutable_state_impl.go
8105 tombstones = append(tombstones, &persistencespb.StateMachineTombstone{
8106 StateMachineKey: &persistencespb.StateMachineTombstone_TimerId{
8109 })
8110 }
8111 > for initiatedEventId := range ms.deleteChildExecutionInfos { mutable_state_impl.go
8112 tombstones = append(tombstones, &persistencespb.StateMachineTombstone{
8113 StateMachineKey: &persistencespb.StateMachineTombstone_ChildExecutionInitiatedEventId{
8116 })
8117 }
8118 > for initiatedEventId := range ms.deleteRequestCancelInfos { mutable_state_impl.go
8119 tombstones = append(tombstones, &persistencespb.StateMachineTombstone{
8120 StateMachineKey: &persistencespb.StateMachineTombstone_RequestCancelInitiatedEventId{
8123 })
8124 }
8125 > for initiatedEventId := range ms.deleteSignalInfos { mutable_state_impl.go
8126 tombstones = append(tombstones, &persistencespb.StateMachineTombstone{
8127 StateMachineKey: &persistencespb.StateMachineTombstone_SignalExternalInitiatedEventId{
8130 })
8131 }
8132 > for chasmNodePath := range chasmNodesMutation.DeletedNodes { mutable_state_impl.go
8133 tombstones = append(tombstones, &persistencespb.StateMachineTombstone{
8134 StateMachineKey: &persistencespb.StateMachineTombstone_ChasmNodePath{
8142 // which is not supported by today's DB schema.
8143 // TODO: we don't delete updateInfo today. Track them here when we do.
8144 > currentVersionedTransition := ms.CurrentVersionedTransition() mutable_state_impl.go
8145 >
8146 > tombstoneBatch := &persistencespb.StateMachineTombstoneBatch{
8147 > VersionedTransition: currentVersionedTransition,
8148 > StateMachineTombstones: tombstones,
8149 > }
8150 > // As an optimization, we only track the first empty tombstone batch. So we can know the start point of the tombstone batch
8151 > if len(tombstones) > 0 || len(ms.executionInfo.SubStateMachineTombstoneBatches) == 0 {
8152 > ms.executionInfo.SubStateMachineTombstoneBatches = append(ms.executionInfo.SubStateMachineTombstoneBatches, tombstoneBatch)
8153 > }
8154
8155 > ms.totalTombstones += len(tombstones) mutable_state_impl.go
8156 > ms.capTombstoneCount()
8157 }
8158
8159 // capTombstoneCount limits the total number of tombstones stored in the mutable state.
8160 // This method should be called whenever tombstone batch list is updated or synced.
8161 > func (ms *MutableStateImpl) capTombstoneCount() { mutable_state_impl.go
8162 > tombstoneCountLimit := ms.config.MutableStateTombstoneCountLimit()
8163 > for ms.totalTombstones > tombstoneCountLimit &&
8164 > len(ms.executionInfo.SubStateMachineTombstoneBatches) > 0 {
8165 ms.totalTombstones -= len(ms.executionInfo.SubStateMachineTombstoneBatches[0].StateMachineTombstones)
8166 ms.executionInfo.SubStateMachineTombstoneBatches = ms.executionInfo.SubStateMachineTombstoneBatches[1:]
8173 clearBufferEvents bool,
8174 regenerateTimerTasksForTimeSkipping bool,
8175 > ) error { mutable_state_impl.go
8176 > if err := ms.closeTransactionHandleWorkflowResetTask(
8177 > transactionPolicy,
8178 > ); err != nil {
8179 return err
8180 }
8181
8182 > if err := ms.taskGenerator.GenerateDirtySubStateMachineTasks(ms.shard.StateMachineRegistry()); err != nil { mutable_state_impl.go
8183 return err
8184 }
8185
8186 > ms.closeTransactionCollapseVisibilityTasks() mutable_state_impl.go
8187 >
8188 > if err := ms.closeTransactionGenerateChasmRetentionTask(transactionPolicy); err != nil {
8189 return err
8190 }
8195 // regardless of how many activity & user timer created
8196 // so the calculation must be at the very end
8197 > if err := ms.closeTransactionHandleActivityUserTimerTasks(transactionPolicy); err != nil { mutable_state_impl.go
8198 return err
8199 }
8200 > if regenerateTimerTasksForTimeSkipping { mutable_state_impl.go
8201 if err := ms.closeTransactionRegenTimerTasksForWorkflowTimeSkipping(transactionPolicy); err != nil {
8202 return err
8204 }
8205
8206 > return ms.closeTransactionPrepareReplicationTasks(transactionPolicy, eventBatches, clearBufferEvents) mutable_state_impl.go
8207 }
8208
8209 func (ms *MutableStateImpl) closeTransactionGenerateChasmRetentionTask(
8210 transactionPolicy historyi.TransactionPolicy,
8211 > ) error { mutable_state_impl.go
8212 >
8213 > if ms.IsWorkflow() ||
8214 > ms.executionState.State != enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED ||
8215 > ms.stateInDB == enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED {
8216 > return nil mutable_state_impl.go
8217 > }
8218
8219 // Generate retention timer for chasm executions if it's currentely completed
8234 eventBatches [][]*historypb.HistoryEvent,
8235 clearBufferEvents bool,
8236 > ) error { mutable_state_impl.go
8237 > var replicationTasks []tasks.Task
8238 > if ms.config.ReplicationMultipleBatches() {
8239 task, err := ms.eventsToReplicationTask(transactionPolicy, eventBatches)
8240 if err != nil {
8242 }
8243 replicationTasks = append(replicationTasks, task...)
8244 > } else { mutable_state_impl.go
8245 > for _, historyEvents := range eventBatches {
8246 > task, err := ms.eventsToReplicationTask(transactionPolicy, [][]*historypb.HistoryEvent{historyEvents}) mutable_state_impl.go
8247 > if err != nil {
8248 return err
8249 }
8250 > replicationTasks = append(replicationTasks, task...) mutable_state_impl.go
8251 }
8252 }
8253 > replicationTasks = append(replicationTasks, ms.syncActivityToReplicationTask(transactionPolicy)...) mutable_state_impl.go
8254 > replicationTasks = append(replicationTasks, ms.dirtyHSMToReplicationTask(transactionPolicy, eventBatches, clearBufferEvents)...)
8255 >
8256 > archetypeID := ms.ChasmTree().ArchetypeID()
8257 > isWorkflow := archetypeID == chasm.WorkflowArchetypeID
8258 > if !isWorkflow && len(replicationTasks) != 0 {
8259 return softassert.UnexpectedInternalErr(ms.logger, "chasm execution generated workflow replication tasks", nil)
8260 }
8261
8262 > if ms.transitionHistoryEnabled { mutable_state_impl.go
8263 > switch transactionPolicy { mutable_state_impl.go
8264 > case historyi.TransactionPolicyActive: mutable_state_impl.go
8265 > if ms.generateReplicationTask() {
8266 now := time.Now().UTC()
8267 workflowKey := definition.NewWorkflowKey(
8336 }
8337
8338 > if transactionPolicy == historyi.TransactionPolicyPassive && mutable_state_impl.go
8339 > len(ms.InsertTasks[tasks.CategoryReplication]) > 0 {
8340 return softassert.UnexpectedInternalErr(
8341 ms.logger,
8345 }
8346
8347 > return nil mutable_state_impl.go
8348 }
8349
8350 > func (ms *MutableStateImpl) cleanupTransaction() error { mutable_state_impl.go
8351 > ms.updateActivityInfos = make(map[int64]*persistencespb.ActivityInfo)
8352 > ms.deleteActivityInfos = make(map[int64]struct{})
8353 > ms.syncActivityTasks = make(map[int64]struct{})
8354 >
8355 > ms.updateTimerInfos = make(map[string]*persistencespb.TimerInfo)
8356 > ms.deleteTimerInfos = make(map[string]struct{})
8357 >
8358 > ms.updateChildExecutionInfos = make(map[int64]*persistencespb.ChildExecutionInfo)
8359 > ms.deleteChildExecutionInfos = make(map[int64]struct{})
8360 >
8361 > ms.updateRequestCancelInfos = make(map[int64]*persistencespb.RequestCancelInfo)
8362 > ms.deleteRequestCancelInfos = make(map[int64]struct{})
8363 >
8364 > ms.updateSignalInfos = make(map[int64]*persistencespb.SignalInfo)
8365 > ms.deleteSignalInfos = make(map[int64]struct{})
8366 >
8367 > ms.updateSignalRequestedIDs = make(map[string]struct{})
8368 > ms.deleteSignalRequestedIDs = make(map[string]struct{})
8369 >
8370 > ms.visibilityUpdated = false
8371 > ms.executionStateUpdated = false
8372 > ms.workflowTaskUpdated = false
8373 > ms.isResetStateUpdated = false
8374 > ms.timeSkippingInfoUpdated = false
8375 > ms.updateInfoUpdated = make(map[string]struct{})
8376 > ms.timerInfosUserDataUpdated = make(map[string]struct{})
8377 > ms.activityInfosUserDataUpdated = make(map[int64]struct{})
8378 > ms.reapplyEventsCandidate = nil
8379 > ms.subStateMachineDeleted = false
8380 > ms.replayEventBatchID = common.EmptyEventID
8381 >
8382 > ms.stateInDB = ms.executionState.State
8383 > ms.nextEventIDInDB = ms.GetNextEventID()
8384 > if len(ms.executionInfo.TransitionHistory) != 0 {
8385 > ms.versionedTransitionInDB = ms.CurrentVersionedTransition() mutable_state_impl.go
8386 > } else { mutable_state_impl.go
8387 ms.versionedTransitionInDB = nil
8388 }
8389 // ms.dbRecordVersion remains the same
8390
8391 > ms.hBuilder = historybuilder.New( mutable_state_impl.go
8392 > ms.timeSource,
8393 > ms.shard.GenerateTaskIDs,
8394 > ms.GetCurrentVersion(),
8395 > ms.nextEventIDInDB,
8396 > ms.bufferEventsInDB,
8397 > ms.metricsHandler,
8398 > ms.config.MaximumEventBatchSizeInBytes,
8399 > )
8400 >
8401 > ms.InsertTasks = make(map[tasks.Category][]tasks.Task)
8402 > ms.BestEffortDeleteTasks = make(map[tasks.Category][]tasks.Key)
8403 >
8404 > // Clear outputs for the next transaction.
8405 > ms.stateMachineNode.ClearTransactionState()
8406 > // Clear out transient state machine state.
8407 > ms.currentTransactionAddedStateMachineEventTypes = nil
8408 >
8409 > return nil
8410 }
8411
8412 func (ms *MutableStateImpl) closeTransactionPrepareEvents(
8413 transactionPolicy historyi.TransactionPolicy,
8414 > ) ([]*persistence.WorkflowEvents, [][]*historypb.HistoryEvent, []*historypb.HistoryEvent, bool, error) { mutable_state_impl.go
8415 > currentBranchToken, err := ms.GetCurrentBranchToken()
8416 > if err != nil {
8417 return nil, nil, nil, false, err
8418 }
8419
8420 > historyMutation, err := ms.hBuilder.Finish(!ms.HasStartedWorkflowTask()) mutable_state_impl.go
8421 > if err != nil {
8422 return nil, nil, nil, false, err
8423 }
8424
8425 // TODO @wxing1292 need more refactoring to make the logic clean
8426 > ms.bufferEventsInDB = historyMutation.MemBufferBatch mutable_state_impl.go
8427 > newBufferBatch := historyMutation.DBBufferBatch
8428 > clearBuffer := historyMutation.DBClearBuffer
8429 > newEventsBatches := historyMutation.DBEventsBatches
8430 > ms.updatePendingEventIDs(historyMutation.ScheduledIDToStartedID, historyMutation.RequestIDToEventID)
8431 >
8432 > workflowEventsSeq := make([]*persistence.WorkflowEvents, len(newEventsBatches))
8433 > historyNodeTxnIDs, err := ms.shard.GenerateTaskIDs(len(newEventsBatches))
8434 > if err != nil {
8435 return nil, nil, nil, false, err
8436 }
8437 > for index, eventBatch := range newEventsBatches { mutable_state_impl.go
8438 > workflowEventsSeq[index] = &persistence.WorkflowEvents{ mutable_state_impl.go
8439 > NamespaceID: ms.executionInfo.NamespaceId,
8440 > WorkflowID: ms.executionInfo.WorkflowId,
8441 > RunID: ms.executionState.RunId,
8442 > BranchToken: currentBranchToken,
8443 > PrevTxnID: ms.executionInfo.LastFirstEventTxnId,
8444 > TxnID: historyNodeTxnIDs[index],
8445 > Events: eventBatch,
8446 > }
8447 > ms.executionInfo.LastFirstEventId = eventBatch[0].GetEventId()
8448 > ms.executionInfo.LastFirstEventTxnId = historyNodeTxnIDs[index]
8449 >
8450 > // Calculate and add the external payload size and count for this batch
8451 > if ms.config.ExternalPayloadsEnabled(ms.GetNamespaceEntry().Name().String()) {
8452 > externalPayloadSize, externalPayloadCount, err := CalculateExternalPayloadSize(eventBatch, ms.metricsHandler)
8453 > if err != nil {
8454 return nil, nil, nil, false, err
8455 }
8456 > ms.AddExternalPayloadSize(externalPayloadSize) mutable_state_impl.go
8457 > ms.AddExternalPayloadCount(externalPayloadCount)
8458 }
8459 }
8460
8461 > if err := ms.validateNoEventsAfterWorkflowFinish( mutable_state_impl.go
8462 > transactionPolicy,
8463 > workflowEventsSeq,
8464 > ); err != nil {
8465 return nil, nil, nil, false, err
8466 }
8467
8468 > if len(workflowEventsSeq) > 0 { mutable_state_impl.go
8469 > lastEvents := workflowEventsSeq[len(workflowEventsSeq)-1].Events mutable_state_impl.go
8470 > lastEvent := lastEvents[len(lastEvents)-1]
8471 > if err := ms.updateWithLastWriteEvent(
8472 > lastEvent,
8473 > transactionPolicy,
8474 > ); err != nil {
8475 return nil, nil, nil, false, err
8476 }
8477 }
8478
8479 > return workflowEventsSeq, newEventsBatches, newBufferBatch, clearBuffer, nil mutable_state_impl.go
8480 }
8481
8483 transactionPolicy historyi.TransactionPolicy,
8484 eventBatches [][]*historypb.HistoryEvent,
8485 > ) ([]tasks.Task, error) { mutable_state_impl.go
8486 > switch transactionPolicy {
8487 > case historyi.TransactionPolicyActive: mutable_state_impl.go
8488 > if ms.generateReplicationTask() {
8489 return ms.taskGenerator.GenerateHistoryReplicationTasks(eventBatches)
8490 }
8491 > return nil, nil mutable_state_impl.go
8492 case historyi.TransactionPolicyPassive:
8493 return nil, nil
8499 func (ms *MutableStateImpl) syncActivityToReplicationTask(
8500 transactionPolicy historyi.TransactionPolicy,
8501 > ) []tasks.Task { mutable_state_impl.go
8502 > now := time.Now().UTC()
8503 > switch transactionPolicy {
8504 > case historyi.TransactionPolicyActive: mutable_state_impl.go
8505 > if ms.generateReplicationTask() {
8506 var activityIDs map[int64]struct{}
8507 if ms.disablingTransitionHistory() {
8525 )
8526 }
8527 > return nil mutable_state_impl.go
8528 case historyi.TransactionPolicyPassive:
8529 return emptyTasks
8537 eventBatches [][]*historypb.HistoryEvent,
8538 clearBufferEvents bool,
8539 > ) []tasks.Task { mutable_state_impl.go
8540 > switch transactionPolicy {
8541 > case historyi.TransactionPolicyActive: mutable_state_impl.go
8542 > if !ms.generateReplicationTask() {
8543 > return emptyTasks mutable_state_impl.go
8544 > }
8545
8546 // Skip if there are no HSM children (no outbound tasks to generate)
8578 scheduledIDToStartedID map[int64]int64,
8579 requestIDToEventID map[string]int64,
8580 > ) error { mutable_state_impl.go
8581 > for scheduledEventID, startedEventID := range scheduledIDToStartedID {
8582 > if activityInfo, ok := ms.GetActivityInfo(scheduledEventID); ok { mutable_state_impl.go
8583 > activityInfo.StartedEventId = startedEventID mutable_state_impl.go
8584 > ms.updateActivityInfos[activityInfo.ScheduledEventId] = activityInfo
8585 > ms.activityInfosUserDataUpdated[activityInfo.ScheduledEventId] = struct{}{}
8586 > continue
8587 }
8588 if childInfo, ok := ms.GetChildExecutionInfo(scheduledEventID); ok {
8592 }
8593 }
8594 > if len(requestIDToEventID) > 0 { mutable_state_impl.go
8595 var wf *chasmworkflow.Workflow
8596 var chasmCtx chasm.MutableContext
8621 lastEvent *historypb.HistoryEvent,
8622 transactionPolicy historyi.TransactionPolicy,
8623 > ) error { mutable_state_impl.go
8624 > if transactionPolicy == historyi.TransactionPolicyPassive {
8625 // already handled in mutable state.
8626 return nil
8627 }
8628
8629 > currentVersionHistory, err := versionhistory.GetCurrentVersionHistory(ms.executionInfo.VersionHistories) mutable_state_impl.go
8630 > if err != nil {
8631 return err
8632 }
8633 > if err := versionhistory.AddOrUpdateVersionHistoryItem(currentVersionHistory, versionhistory.NewVersionHistoryItem( mutable_state_impl.go
8634 > lastEvent.GetEventId(), lastEvent.GetVersion(),
8635 > )); err != nil {
8636 return err
8637 }
8638
8639 > return nil mutable_state_impl.go
8640 }
8641
8646 transactionPolicy historyi.TransactionPolicy,
8647 workflowEventSeq []*persistence.WorkflowEvents,
8648 > ) error { mutable_state_impl.go
8649 > if transactionPolicy == historyi.TransactionPolicyPassive ||
8650 > len(workflowEventSeq) == 0 {
8651 > return nil mutable_state_impl.go
8652 > }
8653
8654 // only do check if workflow is finished
8655 > if ms.executionState.State != enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED { mutable_state_impl.go
8656 > return nil mutable_state_impl.go
8657 > }
8658
8659 // workflow close
8685 func (ms *MutableStateImpl) startTransactionHandleNamespaceMigration(
8686 namespaceEntry *namespace.Namespace,
8687 > ) (*namespace.Namespace, error) { mutable_state_impl.go
8688 > // NOTE:
8689 > // the main idea here is to guarantee that buffered events & namespace migration works
8690 > // e.g. handle buffered events during version 0 => version > 0 by postponing namespace migration
8691 > // * flush buffered events as if namespace is still local
8692 > // * use updated namespace for actual call
8693 >
8694 > lastWriteVersion, err := ms.GetLastWriteVersion()
8695 > if err != nil {
8696 return nil, err
8697 }
8698
8699 // local namespace -> global namespace && with started workflow task
8700 > if lastWriteVersion == common.EmptyVersion && namespaceEntry.FailoverVersion(ms.executionInfo.WorkflowId) > common.EmptyVersion && ms.HasStartedWorkflowTask() { mutable_state_impl.go
8701 localNamespaceMutation := namespace.WithPretendLocalNamespace(
8702 ms.clusterMetadata.GetCurrentClusterName(),
8704 return namespaceEntry.Clone(localNamespaceMutation), nil
8705 }
8706 > return namespaceEntry, nil mutable_state_impl.go
8707 }
8708
8709 > func (ms *MutableStateImpl) startTransactionHandleWorkflowTaskFailover() (bool, error) { mutable_state_impl.go
8710 > if !ms.IsWorkflowExecutionRunning() {
8711 return false, nil
8712 }
8717
8718 // Handling mutable state turn from standby to active, while having a workflow task on the fly
8719 > workflowTask := ms.GetStartedWorkflowTask() mutable_state_impl.go
8720 > currentVersion := ms.GetCurrentVersion()
8721 > if workflowTask == nil || workflowTask.Version >= currentVersion {
8722 > // no pending workflow tasks, no buffered events
8723 > // or workflow task has higher / equal version
8724 > return false, nil
8725 > }
8726
8727 lastEventVersion, err := ms.GetLastEventVersion()
8805 func (ms *MutableStateImpl) closeTransactionWithPolicyCheck(
8806 transactionPolicy historyi.TransactionPolicy,
8807 > ) error { mutable_state_impl.go
8808 > switch transactionPolicy {
8809 > case historyi.TransactionPolicyActive: mutable_state_impl.go
8810 > // Cannot use ms.namespaceEntry.ActiveClusterName() because currentVersion may be updated during this transaction in
8811 > // passive cluster. For example: if passive cluster sees conflict and decided to terminate this workflow. The
8812 > // currentVersion on mutable state would be updated to point to last write version which is current (passive) cluster.
8813 > activeCluster := ms.clusterMetadata.ClusterNameForFailoverVersion(ms.namespaceEntry.IsGlobalNamespace(), ms.GetCurrentVersion())
8814 > currentCluster := ms.clusterMetadata.GetCurrentClusterName()
8815 >
8816 > if activeCluster != currentCluster {
8817 namespaceID := ms.GetExecutionInfo().NamespaceId
8818 return serviceerror.NewNamespaceNotActive(namespaceID, currentCluster, activeCluster)
8819 }
8820 > return nil mutable_state_impl.go
8821 case historyi.TransactionPolicyPassive:
8822 return nil
8826 }
8827
8828 > func (ms *MutableStateImpl) BufferSizeAcceptable() bool { mutable_state_impl.go
8829 > if ms.hBuilder.NumBufferedEvents() > ms.config.MaximumBufferedEventsBatch() {
8830 return false
8831 }
8832
8833 > if ms.hBuilder.SizeInBytesOfBufferedEvents() > ms.config.MaximumBufferedEventsSizeInBytes() { mutable_state_impl.go
8834 return false
8835 }
8836 > return true mutable_state_impl.go
8837 }
8838
8839 func (ms *MutableStateImpl) closeTransactionHandleBufferedEventsLimit(
8840 transactionPolicy historyi.TransactionPolicy,
8841 > ) error { mutable_state_impl.go
8842 > if transactionPolicy == historyi.TransactionPolicyPassive ||
8843 > !ms.IsWorkflowExecutionRunning() {
8844 return nil
8845 }
8846
8847 > if ms.BufferSizeAcceptable() { mutable_state_impl.go
8848 > return nil mutable_state_impl.go
8849 > }
8850
8851 // Handling buffered events size issue
8870 func (ms *MutableStateImpl) closeTransactionHandleWorkflowResetTask(
8871 transactionPolicy historyi.TransactionPolicy,
8872 > ) error { mutable_state_impl.go
8873 > if transactionPolicy == historyi.TransactionPolicyPassive ||
8874 > !ms.IsWorkflowExecutionRunning() {
8875 return nil
8876 }
8877
8878 > namespaceEntry, err := ms.shard.GetNamespaceRegistry().GetNamespaceByID(namespace.ID(ms.executionInfo.NamespaceId)) mutable_state_impl.go
8879 > if err != nil {
8880 return err
8881 }
8882 > if _, pt := FindAutoResetPoint( mutable_state_impl.go
8883 > ms.timeSource,
8884 > namespaceEntry.VerifyBinaryChecksum,
8885 > ms.GetExecutionInfo().AutoResetPoints,
8886 > ); pt != nil {
8887 if err := ms.taskGenerator.GenerateWorkflowResetTasks(); err != nil {
8888 return err
8897 )
8898 }
8899 > return nil mutable_state_impl.go
8900 }
8901
8902 func (ms *MutableStateImpl) closeTransactionHandleActivityUserTimerTasks(
8903 transactionPolicy historyi.TransactionPolicy,
8904 > ) error { mutable_state_impl.go
8905 > switch transactionPolicy {
8906 > case historyi.TransactionPolicyActive: mutable_state_impl.go
8907 > if !ms.IsWorkflowExecutionRunning() {
8908 return nil
8909 }
8910 > if err := ms.taskGenerator.GenerateActivityTimerTasks(); err != nil { mutable_state_impl.go
8911 return err
8912 }
8913 > return ms.taskGenerator.GenerateUserTimerTasks() mutable_state_impl.go
8914 case historyi.TransactionPolicyPassive:
8915 return nil
8923 // Any other task type is preserved in order.
8924 // Eg: [START, UPSERT, TP1, CLOSE, TP2, TP3] -> [TP1, CLOSE, TP2, TP3]
8925 > func (ms *MutableStateImpl) closeTransactionCollapseVisibilityTasks() { mutable_state_impl.go
8926 > visTasks := ms.InsertTasks[tasks.CategoryVisibility]
8927 > if len(visTasks) < 2 {
8928 > return mutable_state_impl.go
8929 > }
8930 > var visTaskToKeep tasks.Task mutable_state_impl.go
8931 > lastIndex := -1
8932 > for i, task := range visTasks {
8933 > switch task.GetType() {
8934 case enumsspb.TASK_TYPE_VISIBILITY_START_EXECUTION,
8935 enumsspb.TASK_TYPE_VISIBILITY_UPSERT_EXECUTION,
8936 enumsspb.TASK_TYPE_VISIBILITY_CLOSE_EXECUTION,
8937 > enumsspb.TASK_TYPE_VISIBILITY_DELETE_EXECUTION: mutable_state_impl.go
8938 > if visTaskToKeep == nil || task.GetType() >= visTaskToKeep.GetType() {
8939 > visTaskToKeep = task
8940 > }
8941 > lastIndex = i
8942 }
8943 }
8944 > if visTaskToKeep == nil { mutable_state_impl.go
8945 return
8946 }
8947 > collapsedVisTasks := make([]tasks.Task, 0, len(visTasks)) mutable_state_impl.go
8948 > for i, task := range visTasks {
8949 > switch task.GetType() {
8950 case enumsspb.TASK_TYPE_VISIBILITY_START_EXECUTION,
8951 enumsspb.TASK_TYPE_VISIBILITY_UPSERT_EXECUTION,
8952 enumsspb.TASK_TYPE_VISIBILITY_CLOSE_EXECUTION,
8953 > enumsspb.TASK_TYPE_VISIBILITY_DELETE_EXECUTION: mutable_state_impl.go
8954 > if i == lastIndex {
8955 > collapsedVisTasks = append(collapsedVisTasks, visTaskToKeep)
8956 > }
8957 default:
8958 collapsedVisTasks = append(collapsedVisTasks, task)
8959 }
8960 }
8961 > ms.InsertTasks[tasks.CategoryVisibility] = collapsedVisTasks mutable_state_impl.go
8962 }
8963
8964 > func (ms *MutableStateImpl) generateReplicationTask() bool { mutable_state_impl.go
8965 > return len(ms.namespaceEntry.ClusterNames(ms.GetWorkflowKey().WorkflowID)) > 1
8966 > }
8967
8968 func (ms *MutableStateImpl) checkMutability(
8969 actionTag tag.ZapTag,
8970 > ) error { mutable_state_impl.go
8971 > if !ms.IsWorkflowExecutionRunning() {
8972 ms.logWarn(
8973 mutableStateInvalidHistoryActionMsg,
8979 return ErrWorkflowFinished
8980 }
8981 > return nil mutable_state_impl.go
8982 }
8983
8984 > func (ms *MutableStateImpl) generateChecksum() *persistencespb.Checksum { mutable_state_impl.go
8985 > if !ms.shouldGenerateChecksum() {
8986 > return nil
8987 > }
8988 csum, err := generateMutableStateChecksum(ms)
8989 if err != nil {
8994 }
8995
8996 > func (ms *MutableStateImpl) shouldGenerateChecksum() bool { mutable_state_impl.go
8997 > if ms.namespaceEntry == nil {
8998 return false
8999 }
9000 > return rand.Intn(100) < ms.config.MutableStateChecksumGenProbability(ms.namespaceEntry.Name().String()) mutable_state_impl.go
9001 }
9002
9073 }
9074
9075 > func (ms *MutableStateImpl) CurrentVersionedTransition() *persistencespb.VersionedTransition { mutable_state_impl.go
9076 > return transitionhistory.LastVersionedTransition(ms.executionInfo.TransitionHistory)
9077 > }
9078
9079 func (ms *MutableStateImpl) ApplyMutation(
9586 }
9587
9588 > func (ms *MutableStateImpl) initVersionedTransitionInDB() { mutable_state_impl.go
9589 > if len(ms.executionInfo.TransitionHistory) != 0 {
9590 > ms.versionedTransitionInDB = ms.CurrentVersionedTransition() mutable_state_impl.go
9591 > }
9592 }
9593
9603 //
9604 // Note: Deployment objects are immutable, never change their fields.
9605 > func (ms *MutableStateImpl) GetEffectiveDeployment() *deploymentpb.Deployment { mutable_state_impl.go
9606 > return GetEffectiveDeployment(ms.GetExecutionInfo().GetVersioningInfo())
9607 > }
9608
9609 > func (ms *MutableStateImpl) GetWorkerDeploymentSA() string { mutable_state_impl.go
9610 > versioningInfo := ms.GetExecutionInfo().GetVersioningInfo()
9611 > if override := versioningInfo.GetVersioningOverride(); override != nil {
9612 if v := worker_versioning.GetOverrideTargetDeploymentVersion(override); v != nil {
9613 return v.GetDeploymentName()
9614 }
9615 }
9616 > if v := versioningInfo.GetDeploymentVersion(); v != nil { mutable_state_impl.go
9617 return v.GetDeploymentName()
9618 }
9619 > return ms.GetExecutionInfo().GetWorkerDeploymentName() mutable_state_impl.go
9620 }
9621
9622 > func (ms *MutableStateImpl) GetWorkerDeploymentVersionSA() string { mutable_state_impl.go
9623 > versioningInfo := ms.GetExecutionInfo().GetVersioningInfo()
9624 > if override := versioningInfo.GetVersioningOverride(); override != nil {
9625 if v := worker_versioning.GetOverrideTargetDeploymentVersion(override); v != nil {
9626 return worker_versioning.ExternalWorkerDeploymentVersionToString(v)
9627 }
9628 }
9629 > if v := versioningInfo.GetDeploymentVersion(); v != nil { mutable_state_impl.go
9630 return worker_versioning.ExternalWorkerDeploymentVersionToString(v)
9631 }
9632 //nolint:staticcheck // SA1019: worker versioning v0.31
9633 > return worker_versioning.ExternalWorkerDeploymentVersionToString(worker_versioning.ExternalWorkerDeploymentVersionFromStringV31(versioningInfo.GetVersion())) mutable_state_impl.go
9634 }
9635
9636 > func (ms *MutableStateImpl) GetWorkflowVersioningBehaviorSA() enumspb.VersioningBehavior { mutable_state_impl.go
9637 > if override := ms.executionInfo.GetVersioningInfo().GetVersioningOverride(); override != nil {
9638 if override.GetAutoUpgrade() {
9639 return enumspb.VERSIONING_BEHAVIOR_AUTO_UPGRADE
9644 return override.GetBehavior()
9645 }
9646 > return ms.executionInfo.GetVersioningInfo().GetBehavior() mutable_state_impl.go
9647 }
9648
9649 > func (ms *MutableStateImpl) GetDeploymentTransition() *workflowpb.DeploymentTransition { mutable_state_impl.go
9650 > vi := ms.GetExecutionInfo().GetVersioningInfo()
9651 > if t := vi.GetVersionTransition(); t != nil {
9652 //nolint:staticcheck // SA1019: worker versioning v0.30
9653 ret := &workflowpb.DeploymentTransition{}
9662 }
9663 //nolint:staticcheck // SA1019: worker versioning v0.30
9664 > return ms.GetExecutionInfo().GetVersioningInfo().GetDeploymentTransition() mutable_state_impl.go
9665 }
9666
9672 // 3. Behavior: this is returned when there is no override (most common case). Behavior is
9673 // set based on the worker-sent deployment in the latest WFT completion.
9674 > func (ms *MutableStateImpl) GetEffectiveVersioningBehavior() enumspb.VersioningBehavior { mutable_state_impl.go
9675 > return GetEffectiveVersioningBehavior(ms.GetExecutionInfo().GetVersioningInfo())
9676 > }
9677
9678 // StartDeploymentTransition starts a transition to the given deployment which must be
9843 }
9844
9845 > func (ms *MutableStateImpl) GetReapplyCandidateEvents() []*historypb.HistoryEvent { mutable_state_impl.go
9846 > return ms.reapplyEventsCandidate
9847 > }
9848
9849 func (ms *MutableStateImpl) IsSubStateMachineDeleted() bool {
9923 }
9924
9925 > func (ms *MutableStateImpl) ToRealTime(virtualTime time.Time) time.Time { mutable_state_impl.go
9926 > if virtualTime.IsZero() {
9927 return virtualTime
9928 }
9929 > return virtualTime.Add(-ms.accumulatedSkippedDuration()) mutable_state_impl.go
9930 }
go.temporal.io/server/service/history/workflow/workflow_task_state_machine.go 490 covered LOC · 84 ranges

Open complete file

53 ms *MutableStateImpl,
54 metricsHandler metrics.Handler,
55 > ) *workflowTaskStateMachine { workflow_task_state_machine.go
56 > return &workflowTaskStateMachine{
57 > ms: ms,
58 > metricsHandler: metricsHandler,
59 > }
60 > }
61
62 func (m *workflowTaskStateMachine) ApplyWorkflowTaskScheduledEvent(
69 originalScheduledTimestamp *timestamppb.Timestamp,
70 workflowTaskType enumsspb.WorkflowTaskType,
71 > ) (*historyi.WorkflowTaskInfo, error) { workflow_task_state_machine.go
72 >
73 > // set workflow state to running, since workflow task is scheduled
74 > // NOTE: for zombie workflow, should not change the state
75 > state, _ := m.ms.GetWorkflowStateStatus()
76 > if state != enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE {
77 > if _, err := m.ms.UpdateWorkflowStateStatus(
78 > enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING,
79 > enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING,
80 > ); err != nil {
81 return nil, err
82 }
83 }
84
85 > workflowTask := &historyi.WorkflowTaskInfo{ workflow_task_state_machine.go
86 > Version: version,
87 > ScheduledEventID: scheduledEventID,
88 > StartedEventID: common.EmptyEventID,
89 > RequestID: emptyUUID,
90 > WorkflowTaskTimeout: startToCloseTimeout.AsDuration(),
91 > TaskQueue: taskQueue,
92 > Attempt: attempt,
93 > AttemptsSinceLastSuccess: m.ms.executionInfo.WorkflowTaskAttemptsSinceLastSuccess,
94 > ScheduledTime: scheduledTime.AsTime(),
95 > StartedTime: time.Time{},
96 > OriginalScheduledTime: originalScheduledTimestamp.AsTime(),
97 > Type: workflowTaskType,
98 > SuggestContinueAsNew: false, // reset, will be recomputed on workflow task started
99 > SuggestContinueAsNewReasons: nil, // reset, will be recomputed on workflow task started
100 > HistorySizeBytes: 0, // reset, will be recomputed on workflow task started
101 > Stamp: m.ms.GetExecutionInfo().GetWorkflowTaskStamp(),
102 > }
103 >
104 > m.retainWorkflowTaskBuildIdInfo(workflowTask)
105 > m.UpdateWorkflowTask(workflowTask)
106 > return workflowTask, nil
107 }
108
111 // - BuildIdRedirectCounter so add the right BuildIdRedirectCounter to the WFT started event that will be
112 // created at WFT completion time
113 > func (m *workflowTaskStateMachine) retainWorkflowTaskBuildIdInfo(workflowTask *historyi.WorkflowTaskInfo) { workflow_task_state_machine.go
114 > if workflowTask.Attempt > 1 {
115 workflowTask.BuildId = m.ms.executionInfo.WorkflowTaskBuildId
116 workflowTask.BuildIdRedirectCounter = m.ms.executionInfo.BuildIdRedirectCounter
179 redirectCounter int64,
180 suggestContinueAsNewReasons []enumspb.SuggestContinueAsNewReason,
181 > ) (*historyi.WorkflowTaskInfo, error) { workflow_task_state_machine.go
182 > // When this function is called from ApplyEvents, workflowTask is nil.
183 > // It is safe to look up the workflow task as it does not have to deal with transient workflow task case.
184 > if workflowTask == nil {
185 workflowTask = m.GetWorkflowTaskByID(scheduledEventID)
186 if workflowTask == nil {
202 }
203
204 > workflowTask = &historyi.WorkflowTaskInfo{ workflow_task_state_machine.go
205 > Version: version,
206 > ScheduledEventID: scheduledEventID,
207 > StartedEventID: startedEventID,
208 > RequestID: requestID,
209 > WorkflowTaskTimeout: workflowTask.WorkflowTaskTimeout,
210 > Attempt: workflowTask.Attempt,
211 > AttemptsSinceLastSuccess: workflowTask.AttemptsSinceLastSuccess,
212 > StartedTime: startedTime,
213 > ScheduledTime: workflowTask.ScheduledTime,
214 > TaskQueue: workflowTask.TaskQueue,
215 > OriginalScheduledTime: workflowTask.OriginalScheduledTime,
216 > Type: workflowTask.Type,
217 > SuggestContinueAsNew: suggestContinueAsNew,
218 > SuggestContinueAsNewReasons: suggestContinueAsNewReasons,
219 > HistorySizeBytes: historySizeBytes,
220 > BuildIdRedirectCounter: redirectCounter,
221 > Stamp: m.ms.GetExecutionInfo().GetWorkflowTaskStamp(),
222 > }
223 >
224 > if buildId := worker_versioning.BuildIdIfUsingVersioning(versioningStamp); buildId != "" {
225 if redirectCounter == 0 {
226 // this is the initial build ID, it should normally be persisted after scheduling the wf task,
308 originalScheduledTimestamp *timestamppb.Timestamp,
309 workflowTaskType enumsspb.WorkflowTaskType,
310 > ) (*historyi.WorkflowTaskInfo, error) { workflow_task_state_machine.go
311 > opTag := tag.WorkflowActionWorkflowTaskScheduled
312 > if m.HasPendingWorkflowTask() {
313 m.ms.logger.Warn(mutableStateInvalidHistoryActionMsg, opTag,
314 tag.WorkflowEventID(m.ms.GetNextEventID()),
322 // and
323 // - is not speculative.
324 > createWorkflowTaskScheduledEvent := !m.ms.IsTransientWorkflowTask() && workflowTaskType != enumsspb.WORKFLOW_TASK_TYPE_SPECULATIVE workflow_task_state_machine.go
325 >
326 > // If while scheduling a workflow task and new events has come, then this workflow task cannot be a transient/speculative.
327 > // Flush any buffered events before creating the workflow task, otherwise it will result in invalid IDs for
328 > // transient/speculative workflow task and will cause in timeout processing to not work for transient workflow tasks.
329 > if m.ms.HasBufferedEvents() {
330 > m.ms.executionInfo.WorkflowTaskAttempt = 1 workflow_task_state_machine.go
331 > workflowTaskType = enumsspb.WORKFLOW_TASK_TYPE_NORMAL
332 > createWorkflowTaskScheduledEvent = true
333 > m.ms.updatePendingEventIDs(m.ms.hBuilder.FlushBufferToCurrentBatch())
334 > }
335 > if m.ms.IsTransientWorkflowTask() { workflow_task_state_machine.go
336 // TODO: ideally this should be the version of the last started workflow task.
337 // but we are using the last event version here instead since there's no other
351 }
352
353 > scheduleTime := m.ms.timeSource.Now().UTC() workflow_task_state_machine.go
354 > attempt := m.ms.executionInfo.WorkflowTaskAttempt
355 > // TaskQueue should already be set from workflow execution started event.
356 > taskQueue := m.ms.CurrentTaskQueue()
357 > // DefaultWorkflowTaskTimeout should already be set from workflow execution started event.
358 > startToCloseTimeout := m.getStartToCloseTimeout(m.ms.executionInfo.DefaultWorkflowTaskTimeout, attempt)
359 >
360 > var scheduledEvent *historypb.HistoryEvent
361 > var scheduledEventID int64
362 >
363 > if createWorkflowTaskScheduledEvent {
364 > scheduledEvent = m.ms.hBuilder.AddWorkflowTaskScheduledEvent( workflow_task_state_machine.go
365 > taskQueue,
366 > startToCloseTimeout,
367 > attempt,
368 > scheduleTime,
369 > )
370 > scheduledEventID = scheduledEvent.GetEventId()
372 // WorkflowTaskScheduledEvent will be created later.
373 scheduledEventID = m.ms.GetNextEventID()
374 }
375
376 > workflowTask, err := m.ApplyWorkflowTaskScheduledEvent( workflow_task_state_machine.go
377 > m.ms.GetCurrentVersion(),
378 > scheduledEventID,
379 > taskQueue,
380 > startToCloseTimeout,
381 > attempt,
382 > timestamppb.New(scheduleTime),
383 > originalScheduledTimestamp,
384 > workflowTaskType,
385 > )
386 > if err != nil {
387 return nil, err
388 }
389
390 // TODO merge active & passive task generation
391 > if !bypassTaskGeneration { workflow_task_state_machine.go
392 > if workflowTask.Type == enumsspb.WORKFLOW_TASK_TYPE_SPECULATIVE { workflow_task_state_machine.go
393 err = m.ms.taskGenerator.GenerateScheduleSpeculativeWorkflowTaskTasks(workflowTask)
395 > err = m.ms.taskGenerator.GenerateScheduleWorkflowTaskTasks(scheduledEventID) workflow_task_state_machine.go
396 > }
397 > if err != nil { workflow_task_state_machine.go
398 return nil, err
399 }
400 }
401
402 > return workflowTask, nil workflow_task_state_machine.go
403 }
404
408 bypassTaskGeneration bool,
409 workflowTaskType enumsspb.WorkflowTaskType,
410 > ) (*historyi.WorkflowTaskInfo, error) { workflow_task_state_machine.go
411 > return m.AddWorkflowTaskScheduledEventAsHeartbeat(bypassTaskGeneration, timestamppb.New(m.ms.timeSource.Now()), workflowTaskType)
412 > }
413
414 // AddFirstWorkflowTaskScheduled adds the first workflow task scheduled event unless it should be delayed as indicated
462 targetDeploymentVersion *deploymentpb.WorkerDeploymentVersion,
463 targetRevisionNumber int64,
464 > ) (*historypb.HistoryEvent, *historyi.WorkflowTaskInfo, error) { workflow_task_state_machine.go
465 > opTag := tag.WorkflowActionWorkflowTaskStarted
466 > workflowTask := m.GetWorkflowTaskByID(scheduledEventID)
467 > if workflowTask == nil || workflowTask.StartedEventID != common.EmptyEventID {
468 m.ms.logger.Warn(mutableStateInvalidHistoryActionMsg, opTag,
469 tag.WorkflowEventID(m.ms.GetNextEventID()),
473 }
474
475 > m.ms.RemoveSpeculativeWorkflowTaskTimeoutTask() workflow_task_state_machine.go
476 >
477 > scheduledEventID = workflowTask.ScheduledEventID
478 > startedEventID := scheduledEventID + 1
479 > startTime := m.ms.timeSource.Now()
480 >
481 > // The history size computed here might not include this workflow task scheduled or started
482 > // events. That's okay, it doesn't have to be 100% accurate. It just has to be kept
483 > // consistent between the started event in history and the event that was sent to the SDK
484 > // that resulted in the successful completion.
485 > historySizeBytes, suggestContinueAsNewReasons := m.getHistorySizeInfo()
486 > suggestContinueAsNew := len(suggestContinueAsNewReasons) > 0
487 > if updateReg != nil && updateReg.SuggestContinueAsNew() {
488 suggestContinueAsNew = cmp.Or(suggestContinueAsNew, true)
489 suggestContinueAsNewReasons = append(suggestContinueAsNewReasons, enumspb.SUGGEST_CONTINUE_AS_NEW_REASON_TOO_MANY_UPDATES)
490 }
491
492 > if m.ms.config.EnableSendTargetVersionChanged(m.ms.namespaceEntry.Name().String()) && workflow_task_state_machine.go
493 > m.ms.GetEffectiveVersioningBehavior() != enumspb.VERSIONING_BEHAVIOR_UNSPECIFIED {
494
495 // effectiveDeploymentVersion may be nil if the workflow is on an unversioned build;
542 }
543 // emit metric
544 > if m.targetWorkerDeploymentVersionChangedForStartedEvent() { workflow_task_state_machine.go
545 metrics.WorkflowTargetVersionChangedCount.With(m.metricsHandler.WithTags(
546 metrics.NamespaceTag(m.ms.namespaceEntry.Name().String()),
548 )).Record(1)
549 }
550 > if suggestContinueAsNew { workflow_task_state_machine.go
551 metrics.WorkflowSuggestContinueAsNewCount.With(m.metricsHandler.WithTags(
552 metrics.NamespaceTag(m.ms.namespaceEntry.Name().String()),
561 }
562
563 > workflowTask, scheduledEventCreatedForRedirect, redirectCounter, err := m.processBuildIdRedirectInfo(versioningStamp, workflowTask, taskQueue, redirectInfo, skipVersioningCheck) workflow_task_state_machine.go
564 > if err != nil {
565 return nil, nil, err
566 }
567
568 > workflowTaskScheduledEventCreated := scheduledEventCreatedForRedirect || workflow_task_state_machine.go
569 > (!m.ms.IsTransientWorkflowTask() && workflowTask.Type != enumsspb.WORKFLOW_TASK_TYPE_SPECULATIVE)
570 >
571 > // If new events came since transient/speculative WT was scheduled or failover happened during lifetime of transient/speculative WT,
572 > // transient/speculative WT needs to be converted to normal WT, i.e. WorkflowTaskScheduledEvent needs to be created now.
573 > if !workflowTaskScheduledEventCreated &&
574 > (workflowTask.ScheduledEventID != m.ms.GetNextEventID() || workflowTask.Version != m.ms.GetCurrentVersion()) {
575
576 workflowTask.Attempt = 1
590 // Create WorkflowTaskStartedEvent only if WorkflowTaskScheduledEvent was created.
591 // (it wasn't created for transient/speculative WT).
592 > var startedEvent *historypb.HistoryEvent workflow_task_state_machine.go
593 > if workflowTaskScheduledEventCreated {
594 > startedEvent = m.ms.hBuilder.AddWorkflowTaskStartedEvent( workflow_task_state_machine.go
595 > scheduledEventID,
596 > requestID,
597 > identity,
598 > startTime,
599 > suggestContinueAsNew,
600 > historySizeBytes,
601 > versioningStamp,
602 > redirectCounter,
603 > suggestContinueAsNewReasons,
604 > m.targetWorkerDeploymentVersionChangedForStartedEvent(),
605 > )
606 > m.ms.hBuilder.FlushAndCreateNewBatch()
607 > startedEventID = startedEvent.GetEventId()
608 > }
609
610 > workflowTask, err = m.ApplyWorkflowTaskStartedEvent( workflow_task_state_machine.go
611 > workflowTask,
612 > m.ms.GetCurrentVersion(),
613 > scheduledEventID,
614 > startedEventID,
615 > requestID,
616 > startTime,
617 > suggestContinueAsNew,
618 > historySizeBytes,
619 > versioningStamp,
620 > redirectCounter,
621 > suggestContinueAsNewReasons,
622 > )
623 > if err != nil {
624 return nil, nil, err
625 }
626
627 > m.emitWorkflowTaskAttemptStats(workflowTask.Attempt) workflow_task_state_machine.go
628 >
629 > // TODO merge active & passive task generation
630 > if err = m.ms.taskGenerator.GenerateStartWorkflowTaskTasks(
631 > scheduledEventID,
632 > ); err != nil {
633 return nil, nil, err
634 }
635
636 > return startedEvent, workflowTask, nil workflow_task_state_machine.go
637 }
638
648 redirectInfo *taskqueuespb.BuildIdRedirectInfo,
649 skipVersioningCheck bool,
650 > ) (newWorkflowTask *historyi.WorkflowTaskInfo, converted bool, redirectCounter int64, err error) { workflow_task_state_machine.go
651 > buildId := worker_versioning.BuildIdIfUsingVersioning(versioningStamp)
652 > if buildId == "" && (m.ms.GetAssignedBuildId() == "" || // unversioned workflow
653 > skipVersioningCheck || // resetter may add WFT started events without stamps, it sets skipVersioningCheck=true
654 > (taskQueue.GetKind() == enumspb.TASK_QUEUE_KIND_STICKY && m.ms.executionInfo.GetStickyTaskQueue() == taskQueue.GetName())) {
655 > // build ID is expected to be empty for sticky queues until old versioning is removed [cleanup-old-wv]
656 > return workflowTask, false, 0, nil
657 > }
658
659 redirectCounter, err = m.ms.validateBuildIdRedirectInfo(versioningStamp, redirectInfo)
685 }
686
687 > func (m *workflowTaskStateMachine) skipWorkflowTaskCompletedEvent(workflowTaskType enumsspb.WorkflowTaskType, request *workflowservice.RespondWorkflowTaskCompletedRequest) bool { workflow_task_state_machine.go
688 > if workflowTaskType != enumsspb.WORKFLOW_TASK_TYPE_SPECULATIVE {
689 > // Only Speculative WT can skip WorkflowTaskCompletedEvent. workflow_task_state_machine.go
690 > return false
691 > }
692
693 if len(request.GetCommands()) != 0 {
763 request *workflowservice.RespondWorkflowTaskCompletedRequest,
764 limits historyi.WorkflowTaskCompletionLimits,
765 > ) (*historypb.HistoryEvent, error) { workflow_task_state_machine.go
766 >
767 > m.ms.RemoveSpeculativeWorkflowTaskTimeoutTask()
768 >
769 > // Capture if WorkflowTaskScheduled and WorkflowTaskStarted events were created
770 > // before calling m.beforeAddWorkflowTaskCompletedEvent() because it will delete workflow task info from mutable state.
771 > workflowTaskScheduledStartedEventsCreated := !m.ms.IsTransientWorkflowTask() && workflowTask.Type != enumsspb.WORKFLOW_TASK_TYPE_SPECULATIVE
772 > m.beforeAddWorkflowTaskCompletedEvent()
773 >
774 > if m.skipWorkflowTaskCompletedEvent(workflowTask.Type, request) {
775 return nil, nil
776 }
777
778 > if !workflowTaskScheduledStartedEventsCreated { workflow_task_state_machine.go
779 // Create corresponding WorkflowTaskScheduled and WorkflowTaskStarted events for transient/speculative workflow tasks.
780 scheduledEvent := m.ms.hBuilder.AddWorkflowTaskScheduledEvent(
810 }
811
812 > deploymentName := request.GetDeploymentOptions().GetDeploymentName() workflow_task_state_machine.go
813 > if deploymentName == "" {
814 > //nolint:staticcheck // SA1019 deprecated Deployment will clean up later
815 > deploymentName = request.GetDeployment().GetSeriesName()
816 > }
817
818 > vb := request.VersioningBehavior workflow_task_state_machine.go
819 > if request.DeploymentOptions != nil && request.DeploymentOptions.GetWorkerVersioningMode() != enumspb.WORKER_VERSIONING_MODE_VERSIONED {
820 // SDK has a bug that reports behavior if user has specified a default behavior without enabling versioning.
821 // Until that is fixed, we should adjust this value so the workflow works correctly.
824
825 //nolint:staticcheck // SA1019 deprecated Deployment will clean up later
826 > wftDeployment := worker_versioning.DeploymentOrVersion(request.Deployment, worker_versioning.DeploymentVersionFromOptions(request.DeploymentOptions)) workflow_task_state_machine.go
827 >
828 > // Now write the completed event
829 > event := m.ms.hBuilder.AddWorkflowTaskCompletedEvent(
830 > workflowTask.ScheduledEventID,
831 > workflowTask.StartedEventID,
832 > request.Identity,
833 > request.BinaryChecksum,
834 > request.WorkerVersionStamp,
835 > request.SdkMetadata,
836 > request.MeteringMetadata,
837 > deploymentName,
838 > wftDeployment,
839 > vb,
840 > )
841 >
842 > override := m.ms.GetExecutionInfo().GetVersioningInfo().GetVersioningOverride()
843 > // Capture the pending one-time target before afterAddWorkflowTaskCompletedEvent,
844 > // which clears the override when this WFT completes on the target version.
845 > var oneTimeTarget *deploymentpb.WorkerDeploymentVersion
846 > if oneTime := override.GetOneTime(); oneTime != nil {
847 oneTimeTarget = oneTime.GetTargetDeploymentVersion()
848 }
849
850 > wftScheduleToClose := event.GetEventTime().AsTime().Sub(workflowTask.ScheduledTime) workflow_task_state_machine.go
851 > err := m.afterAddWorkflowTaskCompletedEvent(event, limits, wftScheduleToClose)
852 > if err != nil {
853 return nil, err
854 }
855 // afterAddWorkflowTaskCompletedEvent clears the one-time override. Emit fulfillment
856 // telemetry only on this live completion path, not when applying rebuilt history.
857 > if oneTimeTarget != nil && wftCompletedOnTargetVersion(wftDeployment, oneTimeTarget) { workflow_task_state_machine.go
858 metrics.WorkerDeploymentVersioningOneTimeOverrideCounter.With(m.metricsHandler).Record(1)
859 m.ms.logger.Info("One-time versioning override fulfilled",
865 }
866
867 > metrics.WorkflowTasksCompleted.With(m.metricsHandler).Record(1, workflow_task_state_machine.go
868 > metrics.NamespaceTag(m.ms.GetNamespaceEntry().Name().String()),
869 > metrics.VersioningBehaviorTag(vb),
870 > metrics.FirstAttemptTag(workflowTask.Attempt),
871 > )
872 >
873 > numConsecutiveWorkflowTaskProblemsToTriggerSearchAttribute := m.ms.config.NumConsecutiveWorkflowTaskProblemsToTriggerSearchAttribute(m.ms.GetNamespaceEntry().Name().String())
874 > if numConsecutiveWorkflowTaskProblemsToTriggerSearchAttribute > 0 {
875 > if err := m.ms.RemoveReportedProblemsSearchAttribute(); err != nil {
876 return nil, err
877 }
878 }
879
880 > return event, nil workflow_task_state_machine.go
881 }
882
883 > func (m *workflowTaskStateMachine) targetWorkerDeploymentVersionChangedForStartedEvent() bool { workflow_task_state_machine.go
884 > return m.ms.config.EnableSendTargetVersionChanged(m.ms.namespaceEntry.Name().String()) &&
885 > m.ms.GetEffectiveVersioningBehavior() == enumspb.VERSIONING_BEHAVIOR_PINNED &&
886 > m.ms.executionInfo.GetLastNotifiedTargetVersion() != nil
887 > }
888
889 func (m *workflowTaskStateMachine) AddWorkflowTaskFailedEvent(
1023 }
1024
1025 > func (m *workflowTaskStateMachine) recordTimeoutTasksForDeletion(workflowTask *historyi.WorkflowTaskInfo) { workflow_task_state_machine.go
1026 > // Record persisted workflow task timeout tasks for deletion after successful persistence update.
1027 > if task := workflowTask.ScheduleToStartTimeoutTask; task != nil {
1028 key := task.GetKey()
1029 if key.FireTime.Sub(workflowTask.ScheduledTime) < maxWorkflowTaskTimeoutToDelete {
1096
1097 // deleteWorkflowTask deletes a workflow task.
1098 > func (m *workflowTaskStateMachine) deleteWorkflowTask() { workflow_task_state_machine.go
1099 > // Get current workflow task info before deleting it, to capture timeout tasks for deletion
1100 > currentWorkflowTask := m.getWorkflowTaskInfo()
1101 > m.recordTimeoutTasksForDeletion(currentWorkflowTask)
1102 >
1103 > // Clear in-memory timeout tasks
1104 > m.ms.SetWorkflowTaskScheduleToStartTimeoutTask(nil)
1105 > m.ms.SetWorkflowTaskStartToCloseTimeoutTask(nil)
1106 >
1107 > resetWorkflowTaskInfo := &historyi.WorkflowTaskInfo{
1108 > Version: common.EmptyVersion,
1109 > ScheduledEventID: common.EmptyEventID,
1110 > StartedEventID: common.EmptyEventID,
1111 > RequestID: emptyUUID,
1112 > WorkflowTaskTimeout: time.Duration(0),
1113 > Attempt: 1,
1114 > StartedTime: time.Unix(0, 0).UTC(),
1115 > ScheduledTime: time.Unix(0, 0).UTC(),
1116 >
1117 > TaskQueue: nil,
1118 > // Keep the last original scheduled Timestamp, so that AddWorkflowTaskScheduledEventAsHeartbeat can continue with it.
1119 > OriginalScheduledTime: currentWorkflowTask.OriginalScheduledTime,
1120 > Type: enumsspb.WORKFLOW_TASK_TYPE_UNSPECIFIED,
1121 > SuggestContinueAsNew: false,
1122 > SuggestContinueAsNewReasons: nil,
1123 > HistorySizeBytes: 0,
1124 > }
1125 > m.UpdateWorkflowTask(resetWorkflowTaskInfo)
1126 > }
1127
1128 // UpdateWorkflowTask updates a workflow task.
1129 func (m *workflowTaskStateMachine) UpdateWorkflowTask(
1130 workflowTask *historyi.WorkflowTaskInfo,
1132 > if m.HasStartedWorkflowTask() && workflowTask.StartedEventID == common.EmptyEventID {
1133 > // reset the flag whenever started workflow task closes, there could be three cases: workflow_task_state_machine.go
1134 > // 1. workflow task completed:
1135 > // a. workflow task contains close workflow command, the fact that workflow task
1136 > // completes successfully means workflow will also close and the value of the
1137 > // flag doesn't matter.
1138 > // b. workflow task doesn't contain close workflow command, then by definition,
1139 > // workflow is not trying to close, so unset the flag.
1140 > // 2. workflow task timedout: we don't know if workflow is trying to close or not,
1141 > // reset the flag to be safe. It's possible that workflow task is trying to signal
1142 > // itself within a local activity when this flag is set, which may result in timeout.
1143 > // reset the flag will allow the workflow to proceed.
1144 > // 3. workflow failed: always reset the flag here. If failure is due to unhandled command,
1145 > // AddWorkflowTaskFailedEvent will set the flag.
1146 > m.ms.workflowCloseAttempted = false
1147 > }
1148
1149 > m.ms.executionInfo.WorkflowTaskVersion = workflowTask.Version workflow_task_state_machine.go
1150 > m.ms.executionInfo.WorkflowTaskScheduledEventId = workflowTask.ScheduledEventID
1151 > m.ms.executionInfo.WorkflowTaskStartedEventId = workflowTask.StartedEventID
1152 > m.ms.executionInfo.WorkflowTaskRequestId = workflowTask.RequestID
1153 > m.ms.executionInfo.WorkflowTaskTimeout = durationpb.New(workflowTask.WorkflowTaskTimeout)
1154 > m.ms.executionInfo.WorkflowTaskAttempt = workflowTask.Attempt
1155 > m.ms.executionInfo.WorkflowTaskAttemptsSinceLastSuccess = workflowTask.AttemptsSinceLastSuccess
1156 > if !workflowTask.StartedTime.IsZero() {
1157 > m.ms.executionInfo.WorkflowTaskStartedTime = timestamppb.New(workflowTask.StartedTime) workflow_task_state_machine.go
1158 > }
1159 > if !workflowTask.ScheduledTime.IsZero() { workflow_task_state_machine.go
1160 > m.ms.executionInfo.WorkflowTaskScheduledTime = timestamppb.New(workflowTask.ScheduledTime)
1161 > }
1162 > m.ms.executionInfo.WorkflowTaskOriginalScheduledTime = timestamppb.New(workflowTask.OriginalScheduledTime)
1163 > m.ms.executionInfo.WorkflowTaskType = workflowTask.Type
1164 > m.ms.executionInfo.WorkflowTaskSuggestContinueAsNew = workflowTask.SuggestContinueAsNew
1165 > m.ms.executionInfo.WorkflowTaskSuggestContinueAsNewReasons = workflowTask.SuggestContinueAsNewReasons
1166 > m.ms.executionInfo.WorkflowTaskHistorySizeBytes = workflowTask.HistorySizeBytes
1167 > m.ms.executionInfo.WorkflowTaskBuildId = workflowTask.BuildId
1168 > m.ms.executionInfo.WorkflowTaskBuildIdRedirectCounter = workflowTask.BuildIdRedirectCounter
1169 >
1170 > m.ms.workflowTaskUpdated = true
1171 >
1172 > // NOTE:
1173 > // - do not update executionInfo.TaskQueue!
1174 >
1175 > m.ms.logger.Debug("Workflow task updated",
1176 > tag.WorkflowScheduledEventID(workflowTask.ScheduledEventID),
1177 > tag.WorkflowStartedEventID(workflowTask.StartedEventID),
1178 > tag.WorkflowTaskRequestId(workflowTask.RequestID),
1179 > tag.WorkflowTaskTimeout(workflowTask.WorkflowTaskTimeout),
1180 > tag.Attempt(workflowTask.Attempt),
1181 > tag.WorkflowStartedTimestamp(workflowTask.StartedTime),
1182 > tag.WorkflowTaskType(workflowTask.Type.String()))
1183 }
1184
1185 > func (m *workflowTaskStateMachine) HasPendingWorkflowTask() bool { workflow_task_state_machine.go
1186 > return m.ms.executionInfo.WorkflowTaskScheduledEventId != common.EmptyEventID
1187 > }
1188
1189 func (m *workflowTaskStateMachine) GetPendingWorkflowTask() *historyi.WorkflowTaskInfo {
1196 }
1197
1198 > func (m *workflowTaskStateMachine) HasStartedWorkflowTask() bool { workflow_task_state_machine.go
1199 > return m.ms.executionInfo.WorkflowTaskScheduledEventId != common.EmptyEventID &&
1200 > m.ms.executionInfo.WorkflowTaskStartedEventId != common.EmptyEventID
1201 > }
1202
1203 > func (m *workflowTaskStateMachine) GetStartedWorkflowTask() *historyi.WorkflowTaskInfo { workflow_task_state_machine.go
1204 > if !m.HasStartedWorkflowTask() {
1205 > return nil workflow_task_state_machine.go
1206 > }
1207
1208 > workflowTask := m.getWorkflowTaskInfo() workflow_task_state_machine.go
1209 > return workflowTask
1210 }
1211
1215
1216 // GetWorkflowTaskByID returns details about the current workflow task by scheduled event ID.
1217 > func (m *workflowTaskStateMachine) GetWorkflowTaskByID(scheduledEventID int64) *historyi.WorkflowTaskInfo { workflow_task_state_machine.go
1218 > workflowTask := m.getWorkflowTaskInfo()
1219 > if scheduledEventID == workflowTask.ScheduledEventID {
1220 > return workflowTask
1221 > }
1222
1223 return nil
1284 }
1285
1286 > func (m *workflowTaskStateMachine) getWorkflowTaskInfo() *historyi.WorkflowTaskInfo { workflow_task_state_machine.go
1287 > wft := &historyi.WorkflowTaskInfo{
1288 > Version: m.ms.executionInfo.WorkflowTaskVersion,
1289 > ScheduledEventID: m.ms.executionInfo.WorkflowTaskScheduledEventId,
1290 > StartedEventID: m.ms.executionInfo.WorkflowTaskStartedEventId,
1291 > RequestID: m.ms.executionInfo.WorkflowTaskRequestId,
1292 > WorkflowTaskTimeout: m.ms.executionInfo.WorkflowTaskTimeout.AsDuration(),
1293 > Attempt: m.ms.executionInfo.WorkflowTaskAttempt,
1294 > AttemptsSinceLastSuccess: m.ms.executionInfo.WorkflowTaskAttemptsSinceLastSuccess,
1295 > StartedTime: m.ms.executionInfo.WorkflowTaskStartedTime.AsTime(),
1296 > ScheduledTime: m.ms.executionInfo.WorkflowTaskScheduledTime.AsTime(),
1297 > TaskQueue: m.ms.CurrentTaskQueue(),
1298 > OriginalScheduledTime: m.ms.executionInfo.WorkflowTaskOriginalScheduledTime.AsTime(),
1299 > Type: m.ms.executionInfo.WorkflowTaskType,
1300 > SuggestContinueAsNew: m.ms.executionInfo.WorkflowTaskSuggestContinueAsNew,
1301 > SuggestContinueAsNewReasons: m.ms.executionInfo.WorkflowTaskSuggestContinueAsNewReasons,
1302 > HistorySizeBytes: m.ms.executionInfo.WorkflowTaskHistorySizeBytes,
1303 > BuildId: m.ms.executionInfo.WorkflowTaskBuildId,
1304 > BuildIdRedirectCounter: m.ms.executionInfo.WorkflowTaskBuildIdRedirectCounter,
1305 > ScheduleToStartTimeoutTask: m.ms.GetWorkflowTaskScheduleToStartTimeoutTask(),
1306 > StartToCloseTimeoutTask: m.ms.GetWorkflowTaskStartToCloseTimeoutTask(),
1307 > Stamp: m.ms.executionInfo.WorkflowTaskStamp,
1308 > }
1309 >
1310 > return wft
1311 > }
1312
1313 > func (m *workflowTaskStateMachine) beforeAddWorkflowTaskCompletedEvent() { workflow_task_state_machine.go
1314 > // Make sure to delete workflow task before adding events. Otherwise they are buffered rather than getting appended.
1315 > m.deleteWorkflowTask()
1316 > }
1317
1318 func (m *workflowTaskStateMachine) afterAddWorkflowTaskCompletedEvent(
1320 limits historyi.WorkflowTaskCompletionLimits,
1321 wftScheduleToClose time.Duration,
1323 > attrs := event.GetWorkflowTaskCompletedEventAttributes()
1324 > m.ms.executionInfo.LastCompletedWorkflowTaskStartedEventId = attrs.GetStartedEventId()
1325 > m.ms.executionInfo.MostRecentWorkerVersionStamp = attrs.GetWorkerVersion()
1326 > m.ms.executionInfo.WorkerDeploymentName = attrs.GetWorkerDeploymentName()
1327 >
1328 > //nolint:staticcheck // SA1019 deprecated Deployment will clean up later
1329 > wftDeployment := attrs.GetDeployment()
1330 > if v := attrs.GetWorkerDeploymentVersion(); v != "" { //nolint:staticcheck // SA1019: worker versioning v0.31
1331 dv, _ := worker_versioning.WorkerDeploymentVersionFromStringV31(v)
1332 wftDeployment = worker_versioning.DeploymentFromDeploymentVersion(dv)
1333 }
1334 > if v := attrs.GetDeploymentVersion(); v != nil { workflow_task_state_machine.go
1335 wftDeployment = worker_versioning.DeploymentFromExternalDeploymentVersion(v)
1336 }
1337 > wftBehavior := attrs.GetVersioningBehavior() workflow_task_state_machine.go
1338 > versioningInfo := m.ms.GetExecutionInfo().GetVersioningInfo()
1339 > transition := m.ms.GetDeploymentTransition()
1340 >
1341 > var completedTransition bool
1342 > if transition != nil {
1343 // It's possible that the completed WFT is not yet from the current transition because when
1344 // the transition started, the current wft was already started. In this case, we allow the
1353
1354 // Deployment and behavior before applying the data came from the completed wft.
1355 > wfDeploymentBefore := m.ms.GetEffectiveDeployment() workflow_task_state_machine.go
1356 > wfBehaviorBefore := m.ms.GetEffectiveVersioningBehavior()
1357 >
1358 > // Change deployment and behavior based on completed wft.
1359 > if wftBehavior == enumspb.VERSIONING_BEHAVIOR_UNSPECIFIED {
1360 > if versioningInfo != nil {
1361 versioningInfo.Behavior = wftBehavior
1362 // Deployment Version is not set for unversioned workers.
1380 versioningInfo.DeploymentVersion = worker_versioning.ExternalWorkerDeploymentVersionFromDeployment(wftDeployment)
1381 }
1382 > if oneTime := versioningInfo.GetVersioningOverride().GetOneTime(); oneTime != nil && workflow_task_state_machine.go
1383 > wftCompletedOnTargetVersion(wftDeployment, oneTime.GetTargetDeploymentVersion()) {
1384 // Clear before computing effective deployment/behavior so the worker-reported base state takes effect.
1385 versioningInfo.VersioningOverride = nil
1387
1388 // Deployment and behavior after applying the data came from the completed wft.
1389 > wfDeploymentAfter := m.ms.GetEffectiveDeployment() workflow_task_state_machine.go
1390 > wfBehaviorAfter := m.ms.GetEffectiveVersioningBehavior()
1391 > // We reschedule activities if a transition was completed because during the transition
1392 > // ATs might have been dropped. Note that it is possible that transition completes and still
1393 > // `wfDeploymentBefore == wfDeploymentAfter`. Example: wf was on deployment1, started
1394 > // transition to deployment2, before completing the transition it changed the transition to
1395 > // deployment1 (maybe user rolled back current deployment), now the transition completes.
1396 > if completedTransition ||
1397 > // It is possible that this WFT is changing workflow's deployment even if there was no
1398 > // ongoing transition in the MS. That is possible when the wft is speculative. We still
1399 > // want to reschedule the activities so they are queued with the up-to-date directive.
1400 > !wfDeploymentBefore.Equal(wfDeploymentAfter) ||
1401 > // If effective behavior changes we also want to reschedule the pending activities, so
1402 > // they go to the right matching queues.
1403 > wfBehaviorBefore != wfBehaviorAfter {
1404 if err := m.ms.reschedulePendingActivities(wftScheduleToClose); err != nil {
1405 return err
1408
1409 //nolint:staticcheck // SA1019: worker versioning v2
1410 > buildId := attrs.GetWorkerVersion().GetBuildId() workflow_task_state_machine.go
1411 > if wftDeployment != nil {
1412 buildId = wftDeployment.GetBuildId()
1413 }
1414 > addedResetPoint := m.ms.addResetPointFromCompletion( workflow_task_state_machine.go
1415 > attrs.GetBinaryChecksum(),
1416 > buildId,
1417 > event.GetEventId(),
1418 > limits.MaxResetPoints,
1419 > )
1420 >
1421 > // For v3 versioned workflows (ms.GetEffectiveVersioningBehavior() != UNSPECIFIED), this will update the reachability
1422 > // search attribute based on the execution_info.deployment and/or override deployment if one exists. We must update the
1423 > // search attribute here because the reachability deployment may have just been changed by CompleteDeploymentTransition.
1424 > // This is also useful for unversioned workers.
1425 > // For v1 and v2 versioned workflows the search attributes should be already up-to-date based on the task started events.
1426 > //nolint:staticcheck // SA1019
1427 > if err := m.ms.updateBuildIdsAndDeploymentSearchAttributes(attrs.GetWorkerVersion(), worker_versioning.ExternalWorkerDeploymentVersionFromDeployment(wftDeployment), limits.MaxSearchAttributeValueSize); err != nil {
1428 return err
1429 }
1430 > if addedResetPoint && len(attrs.GetBinaryChecksum()) > 0 { workflow_task_state_machine.go
1431 if err := m.ms.updateBinaryChecksumSearchAttribute(); err != nil {
1432 return err
1433 }
1434 }
1435 > return nil workflow_task_state_machine.go
1436 }
1437
1449 func (m *workflowTaskStateMachine) emitWorkflowTaskAttemptStats(
1450 attempt int32,
1452 > namespaceName := m.ms.GetNamespaceEntry().Name().String()
1453 > metrics.WorkflowTaskAttempt.With(m.ms.metricsHandler).
1454 > Record(int64(attempt), metrics.NamespaceTag(namespaceName))
1455 > if attempt >= int32(m.ms.shard.GetConfig().WorkflowTaskCriticalAttempts()) {
1456 m.ms.shard.GetThrottledLogger().Warn("Critical attempts processing workflow task",
1457 tag.WorkflowNamespace(namespaceName),
1466 defaultTimeout *durationpb.Duration,
1467 attempt int32,
1468 > ) *durationpb.Duration { workflow_task_state_machine.go
1469 > // This util function is only for calculating active workflow task timeout.
1470 > // Transient workflow task in passive cluster won't call this function and
1471 > // always use default timeout as it will either be completely overwritten by
1472 > // a replicated workflow schedule event from active cluster, or if used, it's
1473 > // attempt will be reset to 1.
1474 > // Check ApplyTransientWorkflowTaskScheduled for details.
1475 >
1476 > if defaultTimeout == nil {
1477 defaultTimeout = durationpb.New(0)
1478 }
1479
1480 > if attempt <= workflowTaskRetryBackoffMinAttempts { workflow_task_state_machine.go
1481 > return defaultTimeout
1482 > }
1483
1484 policy := backoff.NewExponentialRetryPolicy(workflowTaskRetryInitialInterval).
1489 }
1490
1491 > func (m *workflowTaskStateMachine) getHistorySizeInfo() (int64, []enumspb.SuggestContinueAsNewReason) { workflow_task_state_machine.go
1492 > var reasons []enumspb.SuggestContinueAsNewReason
1493 > stats := m.ms.GetExecutionInfo().ExecutionStats
1494 > if stats == nil {
1495 return 0, reasons
1496 }
1498 // include the workflow task started event that we're currently writing. That's okay, it
1499 // doesn't have to be 100% accurate.
1500 > historySize := stats.HistorySize workflow_task_state_machine.go
1501 > // This is called right before AddWorkflowTaskStartedEvent, so at this point, nextEventID
1502 > // is the ID of the workflow task started event.
1503 > historyCount := m.ms.GetNextEventID()
1504 > config := m.ms.shard.GetConfig()
1505 > namespaceName := m.ms.GetNamespaceEntry().Name().String()
1506 > sizeLimit := int64(config.HistorySizeSuggestContinueAsNew(namespaceName))
1507 > countLimit := int64(config.HistoryCountSuggestContinueAsNew(namespaceName))
1508 > if historySize >= sizeLimit {
1509 reasons = append(reasons, enumspb.SUGGEST_CONTINUE_AS_NEW_REASON_HISTORY_SIZE_TOO_LARGE)
1510 }
1511 > if historyCount >= countLimit { workflow_task_state_machine.go
1512 reasons = append(reasons, enumspb.SUGGEST_CONTINUE_AS_NEW_REASON_TOO_MANY_HISTORY_EVENTS)
1513 }
1514 > return historySize, reasons workflow_task_state_machine.go
1515 }
1516
1517 > func (m *workflowTaskStateMachine) convertSpeculativeWorkflowTaskToNormal() error { workflow_task_state_machine.go
1518 > if m.ms.executionInfo.WorkflowTaskType != enumsspb.WORKFLOW_TASK_TYPE_SPECULATIVE {
1519 > return nil workflow_task_state_machine.go
1520 > }
1521
1522 // Workflow task can't be persisted as Speculative, because when it is completed,
go.temporal.io/server/service/history/configs/config.go 392 covered LOC · 1 range

Open complete file

445 dc *dynamicconfig.Collection,
446 numberOfShards int32,
447 > ) *Config { config.go
448 > cfg := &Config{
449 > NumberOfShards: numberOfShards,
450 >
451 > EnableReplicationStream: dynamicconfig.EnableReplicationStream.Get(dc),
452 > EmitReplicationLifecycleEvents: dynamicconfig.EmitReplicationLifecycleEvents.Get(dc),
453 > EnableCloseInboundReplicationStreamOnShutdown: dynamicconfig.EnableCloseInboundReplicationStreamOnShutdown.Get(dc),
454 > EnableSeparateReplicationEnableFlag: dynamicconfig.EnableSeparateReplicationEnableFlag.Get(dc),
455 > HistoryReplicationDLQV2: dynamicconfig.EnableHistoryReplicationDLQV2.Get(dc),
456 >
457 > RPS: dynamicconfig.HistoryRPS.Get(dc),
458 > NamespaceRPS: dynamicconfig.HistoryNamespaceRPS.Get(dc),
459 > OperatorRPSRatio: dynamicconfig.OperatorRPSRatio.Get(dc),
460 > MaxIDLengthLimit: dynamicconfig.MaxIDLengthLimit.Get(dc),
461 > PersistenceMaxQPS: dynamicconfig.HistoryPersistenceMaxQPS.Get(dc),
462 > PersistenceGlobalMaxQPS: dynamicconfig.HistoryPersistenceGlobalMaxQPS.Get(dc),
463 > PersistenceNamespaceMaxQPS: dynamicconfig.HistoryPersistenceNamespaceMaxQPS.Get(dc),
464 > PersistenceGlobalNamespaceMaxQPS: dynamicconfig.HistoryPersistenceGlobalNamespaceMaxQPS.Get(dc),
465 > PersistencePerShardNamespaceMaxQPS: dynamicconfig.HistoryPersistencePerShardNamespaceMaxQPS.Get(dc),
466 > PersistenceDynamicRateLimitingParams: dynamicconfig.HistoryPersistenceDynamicRateLimitingParams.Get(dc),
467 > PersistenceQPSBurstRatio: dynamicconfig.PersistenceQPSBurstRatio.Get(dc),
468 > AlignMembershipChange: dynamicconfig.HistoryAlignMembershipChange.Get(dc),
469 > ShutdownDrainDuration: dynamicconfig.HistoryShutdownDrainDuration.Get(dc),
470 > StartupMembershipJoinDelay: dynamicconfig.HistoryStartupMembershipJoinDelay.Get(dc),
471 > AllowResetWithPendingChildren: dynamicconfig.AllowResetWithPendingChildren.Get(dc),
472 > MaxAutoResetPoints: dynamicconfig.HistoryMaxAutoResetPoints.Get(dc),
473 > DefaultWorkflowTaskTimeout: dynamicconfig.DefaultWorkflowTaskTimeout.Get(dc),
474 >
475 > MaxLocalParentWorkflowVerificationDuration: dynamicconfig.MaxLocalParentWorkflowVerificationDuration.Get(dc),
476 >
477 > VisibilityPersistenceMaxReadQPS: dynamicconfig.VisibilityPersistenceMaxReadQPS.Get(dc),
478 > VisibilityPersistenceMaxWriteQPS: dynamicconfig.VisibilityPersistenceMaxWriteQPS.Get(dc),
479 > VisibilityPersistenceSlowQueryThreshold: dynamicconfig.VisibilityPersistenceSlowQueryThreshold.Get(dc),
480 > EnableReadFromSecondaryVisibility: dynamicconfig.EnableReadFromSecondaryVisibility.Get(dc),
481 > VisibilityEnableShadowReadMode: dynamicconfig.VisibilityEnableShadowReadMode.Get(dc),
482 > SecondaryVisibilityWritingMode: dynamicconfig.SecondaryVisibilityWritingMode.Get(dc),
483 > VisibilityDisableOrderByClause: dynamicconfig.VisibilityDisableOrderByClause.Get(dc),
484 > VisibilityEnableManualPagination: dynamicconfig.VisibilityEnableManualPagination.Get(dc),
485 > VisibilityEnableUnifiedQueryConverter: dynamicconfig.VisibilityEnableUnifiedQueryConverter.Get(dc),
486 > VisibilityAllowList: dynamicconfig.VisibilityAllowList.Get(dc),
487 > SuppressErrorSetSystemSearchAttribute: dynamicconfig.SuppressErrorSetSystemSearchAttribute.Get(dc),
488 >
489 > EmitShardLagLog: dynamicconfig.EmitShardLagLog.Get(dc),
490 > EnableDataLossMetrics: dynamicconfig.EnableDataLossMetrics.Get(dc),
491 > // HistoryCacheLimitSizeBased should not change during runtime.
492 > HistoryCacheLimitSizeBased: dynamicconfig.HistoryCacheSizeBasedLimit.Get(dc)(),
493 > HistoryHostLevelCacheMaxSize: dynamicconfig.HistoryCacheHostLevelMaxSize.Get(dc),
494 > HistoryHostLevelCacheMaxSizeBytes: dynamicconfig.HistoryCacheHostLevelMaxSizeBytes.Get(dc),
495 > HistoryCacheTTL: dynamicconfig.HistoryCacheTTL.Get(dc),
496 > HistoryCacheNonUserContextLockTimeout: dynamicconfig.HistoryCacheNonUserContextLockTimeout.Get(dc),
497 > HistoryCacheBackgroundEvict: dynamicconfig.HistoryCacheBackgroundEvict.Get(dc),
498 > EnableWorkflowExecutionTimeoutTimer: dynamicconfig.EnableWorkflowExecutionTimeoutTimer.Get(dc),
499 > EnableUpdateWorkflowModeIgnoreCurrent: dynamicconfig.EnableUpdateWorkflowModeIgnoreCurrent.Get(dc),
500 > EnableTransitionHistory: dynamicconfig.EnableTransitionHistory.Get(dc),
501 > MaxCallbacksPerWorkflow: dynamicconfig.MaxCallbacksPerWorkflow.Get(dc),
502 > MaxCallbacksPerExecution: callback.MaxPerExecution.Get(dc),
503 > MaxCallbacksPerUpdateID: dynamicconfig.MaxCallbacksPerUpdateID.Get(dc),
504 > EnableChasm: dynamicconfig.EnableChasm.Get(dc),
505 > EnableChasmNexusWorkflowOperations: nexusoperation.EnableChasmWorkflowOperations.Get(dc),
506 > ChasmMaxInMemoryPureTasks: dynamicconfig.ChasmMaxInMemoryPureTasks.Get(dc),
507 >
508 > EnableCHASMSchedulerCreation: dynamicconfig.EnableCHASMSchedulerCreation.Get(dc),
509 > EnableCHASMSchedulerMigration: dynamicconfig.EnableCHASMSchedulerMigration.Get(dc),
510 >
511 > EnableCHASMCallbacks: dynamicconfig.EnableCHASMCallbacks.Get(dc),
512 > EnableCHASMSignalBacklinks: dynamicconfig.EnableCHASMSignalBacklinks.Get(dc),
513 > ExternalPayloadsEnabled: dynamicconfig.ExternalPayloadsEnabled.Get(dc),
514 > EnableWorkflowUpdateCallbacks: dynamicconfig.EnableWorkflowUpdateCallbacks.Get(dc),
515 >
516 > EventsShardLevelCacheMaxSizeBytes: dynamicconfig.EventsCacheMaxSizeBytes.Get(dc), // 512KB
517 > EventsHostLevelCacheMaxSizeBytes: dynamicconfig.EventsHostLevelCacheMaxSizeBytes.Get(dc), // 256MB
518 > EventsCacheTTL: dynamicconfig.EventsCacheTTL.Get(dc),
519 > EnableHostLevelEventsCache: dynamicconfig.EnableHostLevelEventsCache.Get(dc),
520 >
521 > RangeSizeBits: 20, // 20 bits for sequencer, 2^20 sequence number for any range
522 >
523 > AcquireShardInterval: dynamicconfig.AcquireShardInterval.Get(dc),
524 > AcquireShardConcurrency: dynamicconfig.AcquireShardConcurrency.Get(dc),
525 > ShardIOConcurrency: dynamicconfig.ShardIOConcurrency.Get(dc),
526 > ShardIOTimeout: dynamicconfig.ShardIOTimeout.Get(dc),
527 > ShardLingerOwnershipCheckQPS: dynamicconfig.ShardLingerOwnershipCheckQPS.Get(dc),
528 > ShardLingerTimeLimit: dynamicconfig.ShardLingerTimeLimit.Get(dc),
529 > ShardFinalizerTimeout: dynamicconfig.ShardFinalizerTimeout.Get(dc),
530 >
531 > HistoryClientOwnershipCachingEnabled: dynamicconfig.HistoryClientOwnershipCachingEnabled.Get(dc),
532 >
533 > StandbyClusterDelay: dynamicconfig.StandbyClusterDelay.Get(dc),
534 > StandbyTaskMissingEventsResendDelay: dynamicconfig.StandbyTaskMissingEventsResendDelay.Get(dc),
535 > StandbyTaskMissingEventsDiscardDelay: dynamicconfig.StandbyTaskMissingEventsDiscardDelay.Get(dc),
536 > ChasmStandbyTaskDiscardDelay: dynamicconfig.ChasmStandbyTaskDiscardDelay.Get(dc),
537 >
538 > QueuePendingTaskCriticalCount: dynamicconfig.QueuePendingTaskCriticalCount.Get(dc),
539 > QueueReaderStuckCriticalAttempts: dynamicconfig.QueueReaderStuckCriticalAttempts.Get(dc),
540 > QueueCriticalSlicesCount: dynamicconfig.QueueCriticalSlicesCount.Get(dc),
541 > QueuePendingTaskMaxCount: dynamicconfig.QueuePendingTaskMaxCount.Get(dc),
542 > QueueMaxPredicateSize: dynamicconfig.QueueMaxPredicateSize.Get(dc),
543 > QueueShrinkPredicateMaxPendingKeys: dynamicconfig.QueueShrinkPredicateMaxPendingKeys.Get(dc),
544 > QueueMoveGroupTaskCountBase: dynamicconfig.QueueMoveGroupTaskCountBase.Get(dc),
545 > QueueMoveGroupTaskCountMultiplier: dynamicconfig.QueueMoveGroupTaskCountMultiplier.Get(dc),
546 >
547 > TaskDLQEnabled: dynamicconfig.HistoryTaskDLQEnabled.Get(dc),
548 > TaskDLQUnexpectedErrorAttempts: dynamicconfig.HistoryTaskDLQUnexpectedErrorAttempts.Get(dc),
549 > TaskDLQInternalErrors: dynamicconfig.HistoryTaskDLQInternalErrors.Get(dc),
550 > TaskDLQErrorPattern: dynamicconfig.HistoryTaskDLQErrorPattern.Get(dc),
551 >
552 > TaskSchedulerEnableRateLimiter: dynamicconfig.TaskSchedulerEnableRateLimiter.Get(dc),
553 > TaskSchedulerEnableRateLimiterShadowMode: dynamicconfig.TaskSchedulerEnableRateLimiterShadowMode.Get(dc),
554 > TaskSchedulerRateLimiterStartupDelay: dynamicconfig.TaskSchedulerRateLimiterStartupDelay.Get(dc),
555 > TaskSchedulerGlobalMaxQPS: dynamicconfig.TaskSchedulerGlobalMaxQPS.Get(dc),
556 > TaskSchedulerMaxQPS: dynamicconfig.TaskSchedulerMaxQPS.Get(dc),
557 > TaskSchedulerNamespaceMaxQPS: dynamicconfig.TaskSchedulerNamespaceMaxQPS.Get(dc),
558 > TaskSchedulerGlobalNamespaceMaxQPS: dynamicconfig.TaskSchedulerGlobalNamespaceMaxQPS.Get(dc),
559 > TaskSchedulerInactiveChannelDeletionDelay: dynamicconfig.TaskSchedulerInactiveChannelDeletionDelay.Get(dc),
560 > TaskSchedulerEnableExecutionQueueScheduler: dynamicconfig.TaskSchedulerEnableExecutionQueueScheduler.Get(dc),
561 > TaskSchedulerExecutionQueueSchedulerMaxQueues: dynamicconfig.TaskSchedulerExecutionQueueSchedulerMaxQueues.Get(dc),
562 > TaskSchedulerExecutionQueueSchedulerQueueTTL: dynamicconfig.TaskSchedulerExecutionQueueSchedulerQueueTTL.Get(dc),
563 > TaskSchedulerExecutionQueueSchedulerQueueConcurrency: dynamicconfig.TaskSchedulerExecutionQueueSchedulerQueueConcurrency.Get(dc),
564 >
565 > TimerTaskBatchSize: dynamicconfig.TimerTaskBatchSize.Get(dc),
566 > TimerProcessorSchedulerWorkerCount: dynamicconfig.TimerProcessorSchedulerWorkerCount.Subscribe(dc),
567 > TimerProcessorSchedulerActiveRoundRobinWeights: dynamicconfig.TimerProcessorSchedulerActiveRoundRobinWeights.WithDefault(ConvertWeightsToDynamicConfigValue(DefaultActiveTaskPriorityWeight)).Get(dc),
568 > TimerProcessorSchedulerStandbyRoundRobinWeights: dynamicconfig.TimerProcessorSchedulerStandbyRoundRobinWeights.WithDefault(ConvertWeightsToDynamicConfigValue(DefaultStandbyTaskPriorityWeight)).Get(dc),
569 > TimerProcessorUpdateAckInterval: dynamicconfig.TimerProcessorUpdateAckInterval.Get(dc),
570 > TimerProcessorUpdateAckIntervalJitterCoefficient: dynamicconfig.TimerProcessorUpdateAckIntervalJitterCoefficient.Get(dc),
571 > TimerProcessorMaxPollRPS: dynamicconfig.TimerProcessorMaxPollRPS.Get(dc),
572 > TimerProcessorMaxPollHostRPS: dynamicconfig.TimerProcessorMaxPollHostRPS.Get(dc),
573 > TimerProcessorMaxPollInterval: dynamicconfig.TimerProcessorMaxPollInterval.Get(dc),
574 > TimerProcessorMaxPollIntervalJitterCoefficient: dynamicconfig.TimerProcessorMaxPollIntervalJitterCoefficient.Get(dc),
575 > TimerProcessorPollBackoffInterval: dynamicconfig.TimerProcessorPollBackoffInterval.Get(dc),
576 > TimerProcessorMaxTimeShift: dynamicconfig.TimerProcessorMaxTimeShift.Get(dc),
577 > TransferQueueMaxReaderCount: dynamicconfig.TransferQueueMaxReaderCount.Get(dc),
578 > RetentionTimerJitterDuration: dynamicconfig.RetentionTimerJitterDuration.Get(dc),
579 >
580 > MemoryTimerProcessorSchedulerWorkerCount: dynamicconfig.MemoryTimerProcessorSchedulerWorkerCount.Subscribe(dc),
581 >
582 > TransferTaskBatchSize: dynamicconfig.TransferTaskBatchSize.Get(dc),
583 > TransferProcessorSchedulerWorkerCount: dynamicconfig.TransferProcessorSchedulerWorkerCount.Subscribe(dc),
584 > TransferProcessorSchedulerActiveRoundRobinWeights: dynamicconfig.TransferProcessorSchedulerActiveRoundRobinWeights.WithDefault(ConvertWeightsToDynamicConfigValue(DefaultActiveTaskPriorityWeight)).Get(dc),
585 > TransferProcessorSchedulerStandbyRoundRobinWeights: dynamicconfig.TransferProcessorSchedulerStandbyRoundRobinWeights.WithDefault(ConvertWeightsToDynamicConfigValue(DefaultStandbyTaskPriorityWeight)).Get(dc),
586 > TransferProcessorMaxPollRPS: dynamicconfig.TransferProcessorMaxPollRPS.Get(dc),
587 > TransferProcessorMaxPollHostRPS: dynamicconfig.TransferProcessorMaxPollHostRPS.Get(dc),
588 > TransferProcessorMaxPollInterval: dynamicconfig.TransferProcessorMaxPollInterval.Get(dc),
589 > TransferProcessorMaxPollIntervalJitterCoefficient: dynamicconfig.TransferProcessorMaxPollIntervalJitterCoefficient.Get(dc),
590 > TransferProcessorUpdateAckInterval: dynamicconfig.TransferProcessorUpdateAckInterval.Get(dc),
591 > TransferProcessorUpdateAckIntervalJitterCoefficient: dynamicconfig.TransferProcessorUpdateAckIntervalJitterCoefficient.Get(dc),
592 > TransferProcessorPollBackoffInterval: dynamicconfig.TransferProcessorPollBackoffInterval.Get(dc),
593 > TransferProcessorEnsureCloseBeforeDelete: dynamicconfig.TransferProcessorEnsureCloseBeforeDelete.Get(dc),
594 > TimerQueueMaxReaderCount: dynamicconfig.TimerQueueMaxReaderCount.Get(dc),
595 >
596 > OutboundTaskBatchSize: dynamicconfig.OutboundTaskBatchSize.Get(dc),
597 > OutboundProcessorMaxPollRPS: dynamicconfig.OutboundProcessorMaxPollRPS.Get(dc),
598 > OutboundProcessorMaxPollHostRPS: dynamicconfig.OutboundProcessorMaxPollHostRPS.Get(dc),
599 > OutboundProcessorMaxPollInterval: dynamicconfig.OutboundProcessorMaxPollInterval.Get(dc),
600 > OutboundProcessorMaxPollIntervalJitterCoefficient: dynamicconfig.OutboundProcessorMaxPollIntervalJitterCoefficient.Get(dc),
601 > OutboundProcessorUpdateAckInterval: dynamicconfig.OutboundProcessorUpdateAckInterval.Get(dc),
602 > OutboundProcessorUpdateAckIntervalJitterCoefficient: dynamicconfig.OutboundProcessorUpdateAckIntervalJitterCoefficient.Get(dc),
603 > OutboundProcessorPollBackoffInterval: dynamicconfig.OutboundProcessorPollBackoffInterval.Get(dc),
604 > OutboundQueuePendingTaskCriticalCount: dynamicconfig.OutboundQueuePendingTaskCriticalCount.Get(dc),
605 > OutboundQueuePendingTaskMaxCount: dynamicconfig.OutboundQueuePendingTaskMaxCount.Get(dc),
606 > OutboundQueueMaxPredicateSize: dynamicconfig.OutboundQueueMaxPredicateSize.Get(dc),
607 > OutboundQueueMaxReaderCount: dynamicconfig.OutboundQueueMaxReaderCount.Get(dc),
608 > OutboundQueueGroupLimiterBufferSize: dynamicconfig.OutboundQueueGroupLimiterBufferSize.Get(dc),
609 > OutboundQueueGroupLimiterConcurrency: dynamicconfig.OutboundQueueGroupLimiterConcurrency.Get(dc),
610 > OutboundQueueHostSchedulerMaxTaskRPS: dynamicconfig.OutboundQueueHostSchedulerMaxTaskRPS.Get(dc),
611 > OutboundQueueCircuitBreakerSettings: dynamicconfig.OutboundQueueCircuitBreakerSettings.Subscribe(dc),
612 > OutboundStandbyTaskMissingEventsDestinationDownErr: dynamicconfig.OutboundStandbyTaskMissingEventsDestinationDownErr.Get(dc),
613 > OutboundStandbyTaskMissingEventsDiscardDelay: dynamicconfig.OutboundStandbyTaskMissingEventsDiscardDelay.Get(dc),
614 >
615 > ReplicatorProcessorMaxPollInterval: dynamicconfig.ReplicatorProcessorMaxPollInterval.Get(dc),
616 > ReplicatorProcessorMaxPollIntervalJitterCoefficient: dynamicconfig.ReplicatorProcessorMaxPollIntervalJitterCoefficient.Get(dc),
617 > ReplicatorProcessorFetchTasksBatchSize: dynamicconfig.ReplicatorTaskBatchSize.Get(dc),
618 > ReplicatorProcessorMaxSkipTaskCount: dynamicconfig.ReplicatorMaxSkipTaskCount.Get(dc),
619 > ReplicationTaskProcessorHostQPS: dynamicconfig.ReplicationTaskProcessorHostQPS.Get(dc),
620 > ReplicationTaskProcessorShardQPS: dynamicconfig.ReplicationTaskProcessorShardQPS.Get(dc),
621 > ReplicationEnableDLQMetrics: dynamicconfig.ReplicationEnableDLQMetrics.Get(dc),
622 > ReplicationEnableUpdateWithNewTaskMerge: dynamicconfig.ReplicationEnableUpdateWithNewTaskMerge.Get(dc),
623 > ReplicationStreamSyncStatusDuration: dynamicconfig.ReplicationStreamSyncStatusDuration.Get(dc),
624 > ReplicationProcessorSchedulerQueueSize: dynamicconfig.ReplicationProcessorSchedulerQueueSize.Get(dc),
625 > ReplicationProcessorSchedulerWorkerCount: dynamicconfig.ReplicationProcessorSchedulerWorkerCount.Subscribe(dc),
626 > ReplicationLowPriorityProcessorSchedulerWorkerCount: dynamicconfig.ReplicationLowPriorityProcessorSchedulerWorkerCount.Subscribe(dc),
627 > ReplicationLowPriorityTaskParallelism: dynamicconfig.ReplicationLowPriorityTaskParallelism.Get(dc),
628 > EnableReplicationTaskBatching: dynamicconfig.EnableReplicationTaskBatching.Get(dc),
629 > EnableReplicationTaskTieredProcessing: dynamicconfig.EnableReplicationTaskTieredProcessing.Get(dc),
630 > ReplicationStreamSenderHighPriorityQPS: dynamicconfig.ReplicationStreamSenderHighPriorityQPS.Get(dc),
631 > ReplicationStreamSenderLowPriorityQPS: dynamicconfig.ReplicationStreamSenderLowPriorityQPS.Get(dc),
632 > ReplicationStreamEventLoopRetryMaxAttempts: dynamicconfig.ReplicationStreamEventLoopRetryMaxAttempts.Get(dc),
633 > ReplicationReceiverMaxOutstandingTaskCount: dynamicconfig.ReplicationReceiverMaxOutstandingTaskCount.Get(dc),
634 > ReplicationReceiverSlowSubmissionLatencyThreshold: dynamicconfig.ReplicationReceiverSlowSubmissionLatencyThreshold.Get(dc),
635 > ReplicationReceiverSlowSubmissionWindow: dynamicconfig.ReplicationReceiverSlowSubmissionWindow.Get(dc),
636 > EnableReplicationReceiverSlowSubmissionFlowControl: dynamicconfig.EnableReplicationReceiverSlowSubmissionFlowControl.Get(dc),
637 > ReplicationResendMaxBatchCount: dynamicconfig.ReplicationResendMaxBatchCount.Get(dc),
638 > ReplicationProgressCacheMaxSize: dynamicconfig.ReplicationProgressCacheMaxSize.Get(dc),
639 > ReplicationProgressCacheTTL: dynamicconfig.ReplicationProgressCacheTTL.Get(dc),
640 > ReplicationEnableRateLimit: dynamicconfig.ReplicationEnableRateLimit.Get(dc),
641 > ReplicationEnableRateLimitShadowMode: dynamicconfig.ReplicationEnableRateLimitShadowMode.Get(dc),
642 > ReplicationStreamSendEmptyTaskDuration: dynamicconfig.ReplicationStreamSendEmptyTaskDuration.Get(dc),
643 > ReplicationStreamReceiverLivenessMultiplier: dynamicconfig.ReplicationStreamReceiverLivenessMultiplier.Get(dc),
644 > ReplicationStreamSenderLivenessMultiplier: dynamicconfig.ReplicationStreamSenderLivenessMultiplier.Get(dc),
645 > EnableHistoryReplicationRateLimiter: dynamicconfig.EnableHistoryReplicationRateLimiter.Get(dc),
646 >
647 > MaximumBufferedEventsBatch: dynamicconfig.MaximumBufferedEventsBatch.Get(dc),
648 > MaximumBufferedEventsSizeInBytes: dynamicconfig.MaximumBufferedEventsSizeInBytes.Get(dc),
649 > MaximumSignalsPerExecution: dynamicconfig.MaximumSignalsPerExecution.Get(dc),
650 > MaximumEventBatchSizeInBytes: dynamicconfig.MaximumEventBatchSizeInBytes.Get(dc),
651 > ShardUpdateMinInterval: dynamicconfig.ShardUpdateMinInterval.Get(dc),
652 > ShardFirstUpdateInterval: dynamicconfig.ShardFirstUpdateInterval.Get(dc),
653 > ShardUpdateMinTasksCompleted: dynamicconfig.ShardUpdateMinTasksCompleted.Get(dc),
654 > ShardSyncMinInterval: dynamicconfig.ShardSyncMinInterval.Get(dc),
655 > ShardSyncTimerJitterCoefficient: dynamicconfig.TransferProcessorMaxPollIntervalJitterCoefficient.Get(dc),
656 >
657 > // history client: client/history/client.go set the client timeout 30s
658 > // TODO: Return this value to the client: go.temporal.io/server/issues/294
659 > LongPollExpirationInterval: dynamicconfig.HistoryLongPollExpirationInterval.Get(dc),
660 > EnableParentClosePolicy: dynamicconfig.EnableParentClosePolicy.Get(dc),
661 > NumParentClosePolicySystemWorkflows: dynamicconfig.NumParentClosePolicySystemWorkflows.Get(dc),
662 > EnableParentClosePolicyWorker: dynamicconfig.EnableParentClosePolicyWorker.Get(dc),
663 > ParentClosePolicyThreshold: dynamicconfig.ParentClosePolicyThreshold.Get(dc),
664 >
665 > BlobSizeLimitError: dynamicconfig.BlobSizeLimitError.Get(dc),
666 > BlobSizeLimitWarn: dynamicconfig.BlobSizeLimitWarn.Get(dc),
667 > MemoSizeLimitError: dynamicconfig.MemoSizeLimitError.Get(dc),
668 > MemoSizeLimitWarn: dynamicconfig.MemoSizeLimitWarn.Get(dc),
669 > NumPendingChildExecutionsLimit: dynamicconfig.NumPendingChildExecutionsLimitError.Get(dc),
670 > NumPendingActivitiesLimit: dynamicconfig.NumPendingActivitiesLimitError.Get(dc),
671 > NumPendingSignalsLimit: dynamicconfig.NumPendingSignalsLimitError.Get(dc),
672 > NumPendingCancelsRequestLimit: dynamicconfig.NumPendingCancelRequestsLimitError.Get(dc),
673 > HistorySizeLimitError: dynamicconfig.HistorySizeLimitError.Get(dc),
674 > HistorySizeLimitWarn: dynamicconfig.HistorySizeLimitWarn.Get(dc),
675 > HistorySizeSuggestContinueAsNew: dynamicconfig.HistorySizeSuggestContinueAsNew.Get(dc),
676 > HistoryCountLimitError: dynamicconfig.HistoryCountLimitError.Get(dc),
677 > HistoryCountLimitWarn: dynamicconfig.HistoryCountLimitWarn.Get(dc),
678 > HistoryCountSuggestContinueAsNew: dynamicconfig.HistoryCountSuggestContinueAsNew.Get(dc),
679 > HistoryMaxPageSize: dynamicconfig.HistoryMaxPageSize.Get(dc),
680 > MutableStateActivityFailureSizeLimitError: dynamicconfig.MutableStateActivityFailureSizeLimitError.Get(dc),
681 > MutableStateActivityFailureSizeLimitWarn: dynamicconfig.MutableStateActivityFailureSizeLimitWarn.Get(dc),
682 > MutableStateSizeLimitError: dynamicconfig.MutableStateSizeLimitError.Get(dc),
683 > MutableStateSizeLimitWarn: dynamicconfig.MutableStateSizeLimitWarn.Get(dc),
684 > MutableStateTombstoneCountLimit: dynamicconfig.MutableStateTombstoneCountLimit.Get(dc),
685 >
686 > ThrottledLogRPS: dynamicconfig.HistoryThrottledLogRPS.Get(dc),
687 > EnableStickyQuery: dynamicconfig.EnableStickyQuery.Get(dc),
688 >
689 > DefaultActivityRetryPolicy: dynamicconfig.DefaultActivityRetryPolicy.Get(dc),
690 > DefaultWorkflowRetryPolicy: dynamicconfig.DefaultWorkflowRetryPolicy.Get(dc),
691 > WorkflowTaskHeartbeatTimeout: dynamicconfig.WorkflowTaskHeartbeatTimeout.Get(dc),
692 > WorkflowTaskCriticalAttempts: dynamicconfig.WorkflowTaskCriticalAttempts.Get(dc),
693 > WorkflowTaskRetryMaxInterval: dynamicconfig.WorkflowTaskRetryMaxInterval.Get(dc),
694 > EnableWorkflowTaskStampIncrementOnFailure: dynamicconfig.EnableWorkflowTaskStampIncrementOnFailure.Get(dc),
695 > DiscardSpeculativeWorkflowTaskMaximumEventsCount: dynamicconfig.DiscardSpeculativeWorkflowTaskMaximumEventsCount.Get(dc),
696 > EnableDropRepeatedWorkflowTaskFailures: dynamicconfig.EnableDropRepeatedWorkflowTaskFailures.Get(dc),
697 > SendTransientOrSpeculativeWorkflowTaskEvents: dynamicconfig.SendTransientOrSpeculativeWorkflowTaskEvents.Get(dc),
698 >
699 > ReplicationTaskApplyTimeout: dynamicconfig.ReplicationTaskApplyTimeout.Get(dc),
700 > ReplicationTaskFetcherParallelism: dynamicconfig.ReplicationTaskFetcherParallelism.Get(dc),
701 > ReplicationTaskFetcherAggregationInterval: dynamicconfig.ReplicationTaskFetcherAggregationInterval.Get(dc),
702 > ReplicationTaskFetcherTimerJitterCoefficient: dynamicconfig.ReplicationTaskFetcherTimerJitterCoefficient.Get(dc),
703 > ReplicationTaskFetcherErrorRetryWait: dynamicconfig.ReplicationTaskFetcherErrorRetryWait.Get(dc),
704 >
705 > ReplicationTaskProcessorErrorRetryWait: dynamicconfig.ReplicationTaskProcessorErrorRetryWait.Get(dc),
706 > ReplicationTaskProcessorErrorRetryBackoffCoefficient: dynamicconfig.ReplicationTaskProcessorErrorRetryBackoffCoefficient.Get(dc),
707 > ReplicationTaskProcessorErrorRetryMaxInterval: dynamicconfig.ReplicationTaskProcessorErrorRetryMaxInterval.Get(dc),
708 > ReplicationTaskProcessorErrorRetryMaxAttempts: dynamicconfig.ReplicationTaskProcessorErrorRetryMaxAttempts.Get(dc),
709 > ReplicationTaskProcessorErrorRetryExpiration: dynamicconfig.ReplicationTaskProcessorErrorRetryExpiration.Get(dc),
710 > ReplicationTaskProcessorNoTaskRetryWait: dynamicconfig.ReplicationTaskProcessorNoTaskInitialWait.Get(dc),
711 > ReplicationTaskProcessorCleanupInterval: dynamicconfig.ReplicationTaskProcessorCleanupInterval.Get(dc),
712 > ReplicationTaskProcessorCleanupJitterCoefficient: dynamicconfig.ReplicationTaskProcessorCleanupJitterCoefficient.Get(dc),
713 > ReplicationMultipleBatches: dynamicconfig.ReplicationMultipleBatches.Get(dc),
714 >
715 > ReplicationStreamSenderErrorRetryWait: dynamicconfig.ReplicationStreamSenderErrorRetryWait.Get(dc),
716 > ReplicationStreamSenderErrorRetryBackoffCoefficient: dynamicconfig.ReplicationStreamSenderErrorRetryBackoffCoefficient.Get(dc),
717 > ReplicationStreamSenderErrorRetryMaxInterval: dynamicconfig.ReplicationStreamSenderErrorRetryMaxInterval.Get(dc),
718 > ReplicationStreamSenderErrorRetryMaxAttempts: dynamicconfig.ReplicationStreamSenderErrorRetryMaxAttempts.Get(dc),
719 > ReplicationStreamSenderErrorRetryExpiration: dynamicconfig.ReplicationStreamSenderErrorRetryExpiration.Get(dc),
720 >
721 > ReplicationExecutableTaskErrorRetryWait: dynamicconfig.ReplicationExecutableTaskErrorRetryWait.Get(dc),
722 > ReplicationExecutableTaskErrorRetryBackoffCoefficient: dynamicconfig.ReplicationExecutableTaskErrorRetryBackoffCoefficient.Get(dc),
723 > ReplicationExecutableTaskErrorRetryMaxInterval: dynamicconfig.ReplicationExecutableTaskErrorRetryMaxInterval.Get(dc),
724 > ReplicationExecutableTaskErrorRetryMaxAttempts: dynamicconfig.ReplicationExecutableTaskErrorRetryMaxAttempts.Get(dc),
725 > ReplicationExecutableTaskErrorRetryExpiration: dynamicconfig.ReplicationExecutableTaskErrorRetryExpiration.Get(dc),
726 >
727 > MaxBufferedQueryCount: dynamicconfig.MaxBufferedQueryCount.Get(dc),
728 > MutableStateChecksumGenProbability: dynamicconfig.MutableStateChecksumGenProbability.Get(dc),
729 > MutableStateChecksumVerifyProbability: dynamicconfig.MutableStateChecksumVerifyProbability.Get(dc),
730 > MutableStateChecksumInvalidateBefore: dynamicconfig.MutableStateChecksumInvalidateBefore.Get(dc),
731 >
732 > StandbyTaskReReplicationContextTimeout: dynamicconfig.StandbyTaskReReplicationContextTimeout.Get(dc),
733 >
734 > SkipReapplicationByNamespaceID: dynamicconfig.SkipReapplicationByNamespaceID.Get(dc),
735 >
736 > // ===== Visibility related =====
737 > VisibilityTaskBatchSize: dynamicconfig.VisibilityTaskBatchSize.Get(dc),
738 > VisibilityProcessorMaxPollRPS: dynamicconfig.VisibilityProcessorMaxPollRPS.Get(dc),
739 > VisibilityProcessorMaxPollHostRPS: dynamicconfig.VisibilityProcessorMaxPollHostRPS.Get(dc),
740 > VisibilityProcessorSchedulerWorkerCount: dynamicconfig.VisibilityProcessorSchedulerWorkerCount.Subscribe(dc),
741 > VisibilityProcessorSchedulerActiveRoundRobinWeights: dynamicconfig.VisibilityProcessorSchedulerActiveRoundRobinWeights.WithDefault(ConvertWeightsToDynamicConfigValue(DefaultActiveTaskPriorityWeight)).Get(dc),
742 > VisibilityProcessorSchedulerStandbyRoundRobinWeights: dynamicconfig.VisibilityProcessorSchedulerStandbyRoundRobinWeights.WithDefault(ConvertWeightsToDynamicConfigValue(DefaultStandbyTaskPriorityWeight)).Get(dc),
743 > VisibilityProcessorMaxPollInterval: dynamicconfig.VisibilityProcessorMaxPollInterval.Get(dc),
744 > VisibilityProcessorMaxPollIntervalJitterCoefficient: dynamicconfig.VisibilityProcessorMaxPollIntervalJitterCoefficient.Get(dc),
745 > VisibilityProcessorUpdateAckInterval: dynamicconfig.VisibilityProcessorUpdateAckInterval.Get(dc),
746 > VisibilityProcessorUpdateAckIntervalJitterCoefficient: dynamicconfig.VisibilityProcessorUpdateAckIntervalJitterCoefficient.Get(dc),
747 > VisibilityProcessorPollBackoffInterval: dynamicconfig.VisibilityProcessorPollBackoffInterval.Get(dc),
748 > VisibilityProcessorEnsureCloseBeforeDelete: dynamicconfig.VisibilityProcessorEnsureCloseBeforeDelete.Get(dc),
749 > VisibilityProcessorEnableCloseWorkflowCleanup: dynamicconfig.VisibilityProcessorEnableCloseWorkflowCleanup.Get(dc),
750 > VisibilityProcessorRelocateAttributesMinBlobSize: dynamicconfig.VisibilityProcessorRelocateAttributesMinBlobSize.Get(dc),
751 > VisibilityQueueMaxReaderCount: dynamicconfig.VisibilityQueueMaxReaderCount.Get(dc),
752 >
753 > DisableFetchRelocatableAttributesFromVisibility: dynamicconfig.DisableFetchRelocatableAttributesFromVisibility.Get(dc),
754 >
755 > SearchAttributesNumberOfKeysLimit: dynamicconfig.SearchAttributesNumberOfKeysLimit.Get(dc),
756 > SearchAttributesSizeOfValueLimit: dynamicconfig.SearchAttributesSizeOfValueLimit.Get(dc),
757 > SearchAttributesTotalSizeLimit: dynamicconfig.SearchAttributesTotalSizeLimit.Get(dc),
758 > IndexerConcurrency: dynamicconfig.WorkerIndexerConcurrency.Get(dc),
759 > ESProcessorNumOfWorkers: dynamicconfig.WorkerESProcessorNumOfWorkers.Get(dc),
760 > // Should not be greater than number of visibility task queue workers VisibilityProcessorSchedulerWorkerCount (default 512)
761 > // Otherwise, visibility queue processors won't be able to fill up bulk with documents (even under heavy load) and bulk will flush due to interval, not number of actions.
762 > ESProcessorBulkActions: dynamicconfig.WorkerESProcessorBulkActions.Get(dc),
763 > // 16MB - just a sanity check. With ES document size ~1Kb it should never be reached.
764 > ESProcessorBulkSize: dynamicconfig.WorkerESProcessorBulkSize.Get(dc),
765 > // Bulk processor will flush every this interval regardless of last flush due to bulk actions.
766 > ESProcessorFlushInterval: dynamicconfig.WorkerESProcessorFlushInterval.Get(dc),
767 > ESProcessorAckTimeout: dynamicconfig.WorkerESProcessorAckTimeout.Get(dc),
768 >
769 > EnableCrossNamespaceCommands: dynamicconfig.EnableCrossNamespaceCommands.Get(dc),
770 > EnableActivityEagerExecution: dynamicconfig.EnableActivityEagerExecution.Get(dc),
771 > EnableActivityRetryStampIncrement: dynamicconfig.EnableActivityRetryStampIncrement.Get(dc),
772 > EnableCancelActivityWorkerCommand: dynamicconfig.EnableCancelActivityWorkerCommand.Get(dc),
773 > EnableEagerWorkflowStart: dynamicconfig.EnableEagerWorkflowStart.Get(dc),
774 > NamespaceCacheRefreshInterval: dynamicconfig.NamespaceCacheRefreshInterval.Get(dc),
775 >
776 > // Archival related
777 > ArchivalTaskBatchSize: dynamicconfig.ArchivalTaskBatchSize.Get(dc),
778 > ArchivalProcessorMaxPollRPS: dynamicconfig.ArchivalProcessorMaxPollRPS.Get(dc),
779 > ArchivalProcessorMaxPollHostRPS: dynamicconfig.ArchivalProcessorMaxPollHostRPS.Get(dc),
780 > ArchivalProcessorSchedulerWorkerCount: dynamicconfig.ArchivalProcessorSchedulerWorkerCount.Subscribe(dc),
781 > ArchivalProcessorMaxPollInterval: dynamicconfig.ArchivalProcessorMaxPollInterval.Get(dc),
782 > ArchivalProcessorMaxPollIntervalJitterCoefficient: dynamicconfig.ArchivalProcessorMaxPollIntervalJitterCoefficient.Get(dc),
783 > ArchivalProcessorUpdateAckInterval: dynamicconfig.ArchivalProcessorUpdateAckInterval.Get(dc),
784 > ArchivalProcessorUpdateAckIntervalJitterCoefficient: dynamicconfig.ArchivalProcessorUpdateAckIntervalJitterCoefficient.Get(dc),
785 > ArchivalProcessorPollBackoffInterval: dynamicconfig.ArchivalProcessorPollBackoffInterval.Get(dc),
786 > ArchivalProcessorArchiveDelay: dynamicconfig.ArchivalProcessorArchiveDelay.Get(dc),
787 > ArchivalBackendMaxRPS: dynamicconfig.ArchivalBackendMaxRPS.Get(dc),
788 > ArchivalQueueMaxReaderCount: dynamicconfig.ArchivalQueueMaxReaderCount.Get(dc),
789 >
790 > // workflow update related
791 > WorkflowExecutionMaxInFlightUpdates: dynamicconfig.WorkflowExecutionMaxInFlightUpdates.Get(dc),
792 > WorkflowExecutionMaxInFlightUpdatePayloads: dynamicconfig.WorkflowExecutionMaxInFlightUpdatePayloads.Get(dc),
793 > WorkflowExecutionMaxTotalUpdates: dynamicconfig.WorkflowExecutionMaxTotalUpdates.Get(dc),
794 > WorkflowExecutionMaxTotalUpdatesSuggestContinueAsNewThreshold: dynamicconfig.WorkflowExecutionMaxTotalUpdatesSuggestContinueAsNewThreshold.Get(dc),
795 > EnableUpdateWithStartRetryOnClosedWorkflowAbort: dynamicconfig.EnableUpdateWithStartRetryOnClosedWorkflowAbort.Get(dc),
796 > EnableUpdateWithStartRetryableErrorOnClosedWorkflowAbort: dynamicconfig.EnableUpdateWithStartRetryableErrorOnClosedWorkflowAbort.Get(dc),
797 >
798 > SendRawHistoryBetweenInternalServices: dynamicconfig.SendRawHistoryBetweenInternalServices.Get(dc),
799 > SendRawHistoryBytesToMatchingService: dynamicconfig.SendRawHistoryBytesToMatchingService.Get(dc),
800 > SendRawWorkflowHistory: dynamicconfig.SendRawWorkflowHistory.Get(dc),
801 > WorkflowIdReuseMinimalInterval: dynamicconfig.WorkflowIdReuseMinimalInterval.Get(dc),
802 > EnableWorkflowIdReuseStartTimeValidation: dynamicconfig.EnableWorkflowIdReuseStartTimeValidation.Get(dc),
803 > BusinessIDReuseRate: dynamicconfig.BusinessIDReuseRate.Get(dc),
804 > BusinessIDReuseBurstRatio: dynamicconfig.BusinessIDReuseBurstRatio.Get(dc),
805 > BusinessIDReuseLimiterCacheSize: dynamicconfig.BusinessIDReuseLimiterCacheSize.Get(dc),
806 > BusinessIDReuseLimiterCacheTTL: dynamicconfig.BusinessIDReuseLimiterCacheTTL.Get(dc),
807 >
808 > HealthPersistenceLatencyFailure: dynamicconfig.HealthPersistenceLatencyFailure.Get(dc),
809 > HealthPersistenceLatencyPercentiles: dynamicconfig.PersistenceHealthSignalPercentileLatencySettings.Get(dc),
810 > HealthPersistenceErrorRatio: dynamicconfig.HealthPersistenceErrorRatio.Get(dc),
811 > HealthRPCLatencyFailure: dynamicconfig.HealthRPCLatencyFailure.Get(dc),
812 > HealthRPCLatencyPercentiles: dynamicconfig.HistoryHealthSignalPercentileLatencySettings.Get(dc),
813 > HealthRPCErrorRatio: dynamicconfig.HealthRPCErrorRatio.Get(dc),
814 > HealthHistoryInitializationTime: dynamicconfig.HealthHistoryInitializationTime.Get(dc),
815 >
816 > BreakdownMetricsByTaskQueue: dynamicconfig.MetricsBreakdownByTaskQueue.Get(dc),
817 >
818 > LogAllReqErrors: dynamicconfig.LogAllReqErrors.Get(dc),
819 >
820 > NumConsecutiveWorkflowTaskProblemsToTriggerSearchAttribute: dynamicconfig.NumConsecutiveWorkflowTaskProblemsToTriggerSearchAttribute.Get(dc),
821 >
822 > // Worker-Versioning related
823 > UseRevisionNumberForWorkerVersioning: dynamicconfig.UseRevisionNumberForWorkerVersioning.Get(dc),
824 > EnableSuggestCaNOnNewTargetVersion: dynamicconfig.EnableSuggestCaNOnNewTargetVersion.Get(dc),
825 > EnableSendTargetVersionChanged: dynamicconfig.EnableSendTargetVersionChanged.Get(dc),
826 > VersionMembershipCacheTTL: dynamicconfig.VersionMembershipCacheTTL.Get(dc),
827 > VersionMembershipCacheMaxSize: dynamicconfig.VersionMembershipCacheMaxSize.Get(dc),
828 > EnableVersionReactivationSignals: dynamicconfig.EnableVersionReactivationSignals.Get(dc),
829 > RoutingInfoCacheTTL: dynamicconfig.RoutingInfoCacheTTL.Get(dc),
830 > RoutingInfoCacheMaxSize: dynamicconfig.RoutingInfoCacheMaxSize.Get(dc),
831 >
832 > // Workflow task completion pagination
833 > EnableWorkflowTaskCompletionPagination: dynamicconfig.EnableWorkflowTaskCompletionPagination.Get(dc),
834 > WorkflowTaskCompletionBufferSizeLimit: dynamicconfig.WorkflowTaskCompletionBufferSizeLimit.Get(dc),
835 > }
836 >
837 > return cfg
838 > }
839
840 // GetShardID return the corresponding shard ID for a given namespaceID and workflowID pair
go.temporal.io/server/common/dynamicconfig/setting_gen.go 316 covered LOC · 70 ranges

Open complete file

26 type GlobalBoolConstrainedDefaultSetting = GlobalTypedConstrainedDefaultSetting[bool]
27
28 > func NewGlobalBoolSetting(key string, def bool, description string) GlobalBoolSetting { setting_gen.go
29 > return NewGlobalTypedSettingWithConverter[bool](key, convertBool, def, description)
30 > }
31
32 func NewGlobalBoolSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[bool], description string) GlobalBoolConstrainedDefaultSetting {
36 type BoolPropertyFn = TypedPropertyFn[bool]
37
38 > func GetBoolPropertyFn(value bool) BoolPropertyFn { setting_gen.go
39 > return GetTypedPropertyFn(value)
40 > }
41
42 type NamespaceBoolSetting = NamespaceTypedSetting[bool]
43 type NamespaceBoolConstrainedDefaultSetting = NamespaceTypedConstrainedDefaultSetting[bool]
44
45 > func NewNamespaceBoolSetting(key string, def bool, description string) NamespaceBoolSetting { setting_gen.go
46 > return NewNamespaceTypedSettingWithConverter[bool](key, convertBool, def, description)
47 > }
48
49 func NewNamespaceBoolSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[bool], description string) NamespaceBoolConstrainedDefaultSetting {
53 type BoolPropertyFnWithNamespaceFilter = TypedPropertyFnWithNamespaceFilter[bool]
54
55 > func GetBoolPropertyFnFilteredByNamespace(value bool) BoolPropertyFnWithNamespaceFilter { setting_gen.go
56 > return GetTypedPropertyFnFilteredByNamespace(value)
57 > }
58
59 type NamespaceIDBoolSetting = NamespaceIDTypedSetting[bool]
60 type NamespaceIDBoolConstrainedDefaultSetting = NamespaceIDTypedConstrainedDefaultSetting[bool]
61
62 > func NewNamespaceIDBoolSetting(key string, def bool, description string) NamespaceIDBoolSetting { setting_gen.go
63 > return NewNamespaceIDTypedSettingWithConverter[bool](key, convertBool, def, description)
64 > }
65
66 func NewNamespaceIDBoolSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[bool], description string) NamespaceIDBoolConstrainedDefaultSetting {
77 type TaskQueueBoolConstrainedDefaultSetting = TaskQueueTypedConstrainedDefaultSetting[bool]
78
79 > func NewTaskQueueBoolSetting(key string, def bool, description string) TaskQueueBoolSetting { setting_gen.go
80 > return NewTaskQueueTypedSettingWithConverter[bool](key, convertBool, def, description)
81 > }
82
83 func NewTaskQueueBoolSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[bool], description string) TaskQueueBoolConstrainedDefaultSetting {
128 type DestinationBoolConstrainedDefaultSetting = DestinationTypedConstrainedDefaultSetting[bool]
129
130 > func NewDestinationBoolSetting(key string, def bool, description string) DestinationBoolSetting { setting_gen.go
131 > return NewDestinationTypedSettingWithConverter[bool](key, convertBool, def, description)
132 > }
133
134 func NewDestinationBoolSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[bool], description string) DestinationBoolConstrainedDefaultSetting {
162 type GlobalIntConstrainedDefaultSetting = GlobalTypedConstrainedDefaultSetting[int]
163
164 > func NewGlobalIntSetting(key string, def int, description string) GlobalIntSetting { setting_gen.go
165 > return NewGlobalTypedSettingWithConverter[int](key, convertInt, def, description)
166 > }
167
168 func NewGlobalIntSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[int], description string) GlobalIntConstrainedDefaultSetting {
179 type NamespaceIntConstrainedDefaultSetting = NamespaceTypedConstrainedDefaultSetting[int]
180
181 > func NewNamespaceIntSetting(key string, def int, description string) NamespaceIntSetting { setting_gen.go
182 > return NewNamespaceTypedSettingWithConverter[int](key, convertInt, def, description)
183 > }
184
185 func NewNamespaceIntSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[int], description string) NamespaceIntConstrainedDefaultSetting {
189 type IntPropertyFnWithNamespaceFilter = TypedPropertyFnWithNamespaceFilter[int]
190
191 > func GetIntPropertyFnFilteredByNamespace(value int) IntPropertyFnWithNamespaceFilter { setting_gen.go
192 > return GetTypedPropertyFnFilteredByNamespace(value)
193 > }
194
195 type NamespaceIDIntSetting = NamespaceIDTypedSetting[int]
213 type TaskQueueIntConstrainedDefaultSetting = TaskQueueTypedConstrainedDefaultSetting[int]
214
215 > func NewTaskQueueIntSetting(key string, def int, description string) TaskQueueIntSetting { setting_gen.go
216 > return NewTaskQueueTypedSettingWithConverter[int](key, convertInt, def, description)
217 > }
218
219 > func NewTaskQueueIntSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[int], description string) TaskQueueIntConstrainedDefaultSetting { setting_gen.go
220 > return NewTaskQueueTypedSettingWithConstrainedDefault[int](key, convertInt, cdef, description)
221 > }
222
223 type IntPropertyFnWithTaskQueueFilter = TypedPropertyFnWithTaskQueueFilter[int]
230 type ShardIDIntConstrainedDefaultSetting = ShardIDTypedConstrainedDefaultSetting[int]
231
232 > func NewShardIDIntSetting(key string, def int, description string) ShardIDIntSetting { setting_gen.go
233 > return NewShardIDTypedSettingWithConverter[int](key, convertInt, def, description)
234 > }
235
236 func NewShardIDIntSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[int], description string) ShardIDIntConstrainedDefaultSetting {
264 type DestinationIntConstrainedDefaultSetting = DestinationTypedConstrainedDefaultSetting[int]
265
266 > func NewDestinationIntSetting(key string, def int, description string) DestinationIntSetting { setting_gen.go
267 > return NewDestinationTypedSettingWithConverter[int](key, convertInt, def, description)
268 > }
269
270 func NewDestinationIntSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[int], description string) DestinationIntConstrainedDefaultSetting {
298 type GlobalFloatConstrainedDefaultSetting = GlobalTypedConstrainedDefaultSetting[float64]
299
300 > func NewGlobalFloatSetting(key string, def float64, description string) GlobalFloatSetting { setting_gen.go
301 > return NewGlobalTypedSettingWithConverter[float64](key, convertFloat, def, description)
302 > }
303
304 func NewGlobalFloatSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[float64], description string) GlobalFloatConstrainedDefaultSetting {
315 type NamespaceFloatConstrainedDefaultSetting = NamespaceTypedConstrainedDefaultSetting[float64]
316
317 > func NewNamespaceFloatSetting(key string, def float64, description string) NamespaceFloatSetting { setting_gen.go
318 > return NewNamespaceTypedSettingWithConverter[float64](key, convertFloat, def, description)
319 > }
320
321 func NewNamespaceFloatSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[float64], description string) NamespaceFloatConstrainedDefaultSetting {
349 type TaskQueueFloatConstrainedDefaultSetting = TaskQueueTypedConstrainedDefaultSetting[float64]
350
351 > func NewTaskQueueFloatSetting(key string, def float64, description string) TaskQueueFloatSetting { setting_gen.go
352 > return NewTaskQueueTypedSettingWithConverter[float64](key, convertFloat, def, description)
353 > }
354
355 func NewTaskQueueFloatSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[float64], description string) TaskQueueFloatConstrainedDefaultSetting {
366 type ShardIDFloatConstrainedDefaultSetting = ShardIDTypedConstrainedDefaultSetting[float64]
367
368 > func NewShardIDFloatSetting(key string, def float64, description string) ShardIDFloatSetting { setting_gen.go
369 > return NewShardIDTypedSettingWithConverter[float64](key, convertFloat, def, description)
370 > }
371
372 func NewShardIDFloatSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[float64], description string) ShardIDFloatConstrainedDefaultSetting {
400 type DestinationFloatConstrainedDefaultSetting = DestinationTypedConstrainedDefaultSetting[float64]
401
402 > func NewDestinationFloatSetting(key string, def float64, description string) DestinationFloatSetting { setting_gen.go
403 > return NewDestinationTypedSettingWithConverter[float64](key, convertFloat, def, description)
404 > }
405
406 func NewDestinationFloatSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[float64], description string) DestinationFloatConstrainedDefaultSetting {
434 type GlobalStringConstrainedDefaultSetting = GlobalTypedConstrainedDefaultSetting[string]
435
436 > func NewGlobalStringSetting(key string, def string, description string) GlobalStringSetting { setting_gen.go
437 > return NewGlobalTypedSettingWithConverter[string](key, convertString, def, description)
438 > }
439
440 func NewGlobalStringSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[string], description string) GlobalStringConstrainedDefaultSetting {
570 type GlobalDurationConstrainedDefaultSetting = GlobalTypedConstrainedDefaultSetting[time.Duration]
571
572 > func NewGlobalDurationSetting(key string, def time.Duration, description string) GlobalDurationSetting { setting_gen.go
573 > return NewGlobalTypedSettingWithConverter[time.Duration](key, convertDuration, def, description)
574 > }
575
576 func NewGlobalDurationSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[time.Duration], description string) GlobalDurationConstrainedDefaultSetting {
580 type DurationPropertyFn = TypedPropertyFn[time.Duration]
581
582 > func GetDurationPropertyFn(value time.Duration) DurationPropertyFn { setting_gen.go
583 > return GetTypedPropertyFn(value)
584 > }
585
586 type NamespaceDurationSetting = NamespaceTypedSetting[time.Duration]
587 type NamespaceDurationConstrainedDefaultSetting = NamespaceTypedConstrainedDefaultSetting[time.Duration]
588
589 > func NewNamespaceDurationSetting(key string, def time.Duration, description string) NamespaceDurationSetting { setting_gen.go
590 > return NewNamespaceTypedSettingWithConverter[time.Duration](key, convertDuration, def, description)
591 > }
592
593 func NewNamespaceDurationSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[time.Duration], description string) NamespaceDurationConstrainedDefaultSetting {
604 type NamespaceIDDurationConstrainedDefaultSetting = NamespaceIDTypedConstrainedDefaultSetting[time.Duration]
605
606 > func NewNamespaceIDDurationSetting(key string, def time.Duration, description string) NamespaceIDDurationSetting { setting_gen.go
607 > return NewNamespaceIDTypedSettingWithConverter[time.Duration](key, convertDuration, def, description)
608 > }
609
610 func NewNamespaceIDDurationSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[time.Duration], description string) NamespaceIDDurationConstrainedDefaultSetting {
621 type TaskQueueDurationConstrainedDefaultSetting = TaskQueueTypedConstrainedDefaultSetting[time.Duration]
622
623 > func NewTaskQueueDurationSetting(key string, def time.Duration, description string) TaskQueueDurationSetting { setting_gen.go
624 > return NewTaskQueueTypedSettingWithConverter[time.Duration](key, convertDuration, def, description)
625 > }
626
627 > func NewTaskQueueDurationSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[time.Duration], description string) TaskQueueDurationConstrainedDefaultSetting { setting_gen.go
628 > return NewTaskQueueTypedSettingWithConstrainedDefault[time.Duration](key, convertDuration, cdef, description)
629 > }
630
631 type DurationPropertyFnWithTaskQueueFilter = TypedPropertyFnWithTaskQueueFilter[time.Duration]
638 type ShardIDDurationConstrainedDefaultSetting = ShardIDTypedConstrainedDefaultSetting[time.Duration]
639
640 > func NewShardIDDurationSetting(key string, def time.Duration, description string) ShardIDDurationSetting { setting_gen.go
641 > return NewShardIDTypedSettingWithConverter[time.Duration](key, convertDuration, def, description)
642 > }
643
644 func NewShardIDDurationSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[time.Duration], description string) ShardIDDurationConstrainedDefaultSetting {
655 type TaskTypeDurationConstrainedDefaultSetting = TaskTypeTypedConstrainedDefaultSetting[time.Duration]
656
657 > func NewTaskTypeDurationSetting(key string, def time.Duration, description string) TaskTypeDurationSetting { setting_gen.go
658 > return NewTaskTypeTypedSettingWithConverter[time.Duration](key, convertDuration, def, description)
659 > }
660
661 func NewTaskTypeDurationSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[time.Duration], description string) TaskTypeDurationConstrainedDefaultSetting {
672 type DestinationDurationConstrainedDefaultSetting = DestinationTypedConstrainedDefaultSetting[time.Duration]
673
674 > func NewDestinationDurationSetting(key string, def time.Duration, description string) DestinationDurationSetting { setting_gen.go
675 > return NewDestinationTypedSettingWithConverter[time.Duration](key, convertDuration, def, description)
676 > }
677
678 func NewDestinationDurationSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[time.Duration], description string) DestinationDurationConstrainedDefaultSetting {
689 type ChasmTaskTypeDurationConstrainedDefaultSetting = ChasmTaskTypeTypedConstrainedDefaultSetting[time.Duration]
690
691 > func NewChasmTaskTypeDurationSetting(key string, def time.Duration, description string) ChasmTaskTypeDurationSetting { setting_gen.go
692 > return NewChasmTaskTypeTypedSettingWithConverter[time.Duration](key, convertDuration, def, description)
693 > }
694
695 func NewChasmTaskTypeDurationSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[time.Duration], description string) ChasmTaskTypeDurationConstrainedDefaultSetting {
723 type NamespaceMapConstrainedDefaultSetting = NamespaceTypedConstrainedDefaultSetting[map[string]any]
724
725 > func NewNamespaceMapSetting(key string, def map[string]any, description string) NamespaceMapSetting { setting_gen.go
726 > return NewNamespaceTypedSettingWithConverter[map[string]any](key, convertMap, def, description)
727 > }
728
729 func NewNamespaceMapSettingWithConstrainedDefault(key string, cdef []TypedConstrainedValue[map[string]any], description string) NamespaceMapConstrainedDefaultSetting {
845 // values. The value from dynamic config will be _merged_ over a deep copy of 'def'. Be very careful
846 // when using non-empty maps or slices as defaults, the result may not be what you want.
847 > func NewGlobalTypedSetting[T any](key string, def T, description string) GlobalTypedSetting[T] { setting_gen.go
848 > // Warn on any shared structure used with ConvertStructure, even though we handle it by deep copying.
849 > warnDefaultSharedStructure(key, def)
850 > // If even deep copy won't even work, we should panic early. Do that by calling deep copy once here.
851 > _ = deepCopyForMapstructure(def)
852 >
853 > s := GlobalTypedSetting[T]{
854 > key: MakeKey(key),
855 > def: def,
856 > convert: ConvertStructure[T](def),
857 > description: description,
858 > }
859 > register(s)
860 > return s
861 > }
862
863 // NewGlobalTypedSettingWithConverter creates a setting with a custom converter function.
864 > func NewGlobalTypedSettingWithConverter[T any](key string, convert func(any) (T, error), def T, description string) GlobalTypedSetting[T] { setting_gen.go
865 > s := GlobalTypedSetting[T]{
866 > key: MakeKey(key),
867 > def: def,
868 > convert: convert,
869 > description: description,
870 > }
871 > register(s)
872 > return s
873 > }
874
875 // NewGlobalTypedSettingWithConstrainedDefault creates a setting with a compound default value.
885 }
886
887 > func (s GlobalTypedSetting[T]) Key() Key { return s.key } setting_gen.go
888 func (s GlobalTypedSetting[T]) Precedence() Precedence { return PrecedenceGlobal }
889 func (s GlobalTypedSetting[T]) Validate(v any) error {
907 type TypedPropertyFn[T any] func() T
908
909 > func (s GlobalTypedSetting[T]) Get(c *Collection) TypedPropertyFn[T] { setting_gen.go
910 > return func() T {
911 > prec := []Constraints{{}} setting_gen.go
912 > return matchAndConvert(
913 > c,
914 > s.key,
915 > s.def,
916 > s.convert,
917 > prec,
918 > )
919 > }
920 }
921
935 type TypedSubscribable[T any] func(callback func(T)) (v T, cancel func())
936
937 > func (s GlobalTypedSetting[T]) Subscribe(c *Collection) TypedSubscribable[T] { setting_gen.go
938 > return func(callback func(T)) (T, func()) {
939 prec := []Constraints{{}}
940 return subscribe(c, s.key, s.def, s.convert, prec, callback)
969 }
970
971 > func GetTypedPropertyFn[T any](value T) TypedPropertyFn[T] { setting_gen.go
972 > return func() T {
973 return value
974 }
981 // values. The value from dynamic config will be _merged_ over a deep copy of 'def'. Be very careful
982 // when using non-empty maps or slices as defaults, the result may not be what you want.
983 > func NewNamespaceTypedSetting[T any](key string, def T, description string) NamespaceTypedSetting[T] { setting_gen.go
984 > // Warn on any shared structure used with ConvertStructure, even though we handle it by deep copying.
985 > warnDefaultSharedStructure(key, def)
986 > // If even deep copy won't even work, we should panic early. Do that by calling deep copy once here.
987 > _ = deepCopyForMapstructure(def)
988 >
989 > s := NamespaceTypedSetting[T]{
990 > key: MakeKey(key),
991 > def: def,
992 > convert: ConvertStructure[T](def),
993 > description: description,
994 > }
995 > register(s)
996 > return s
997 > }
998
999 // NewNamespaceTypedSettingWithConverter creates a setting with a custom converter function.
1000 > func NewNamespaceTypedSettingWithConverter[T any](key string, convert func(any) (T, error), def T, description string) NamespaceTypedSetting[T] { setting_gen.go
1001 > s := NamespaceTypedSetting[T]{
1002 > key: MakeKey(key),
1003 > def: def,
1004 > convert: convert,
1005 > description: description,
1006 > }
1007 > register(s)
1008 > return s
1009 > }
1010
1011 // NewNamespaceTypedSettingWithConstrainedDefault creates a setting with a compound default value.
1021 }
1022
1023 > func (s NamespaceTypedSetting[T]) Key() Key { return s.key } setting_gen.go
1024 func (s NamespaceTypedSetting[T]) Precedence() Precedence { return PrecedenceNamespace }
1025 func (s NamespaceTypedSetting[T]) Validate(v any) error {
1035 }
1036
1037 > func (s NamespaceTypedSetting[T]) WithDefault(v T) NamespaceTypedSetting[T] { setting_gen.go
1038 > newS := s
1039 > newS.def = v
1040 > return newS
1041 > }
1042
1043 type TypedPropertyFnWithNamespaceFilter[T any] func(namespace string) T
1044
1045 > func (s NamespaceTypedSetting[T]) Get(c *Collection) TypedPropertyFnWithNamespaceFilter[T] { setting_gen.go
1046 > return func(namespace string) T {
1047 > prec := []Constraints{{Namespace: namespace}, {}} setting_gen.go
1048 > return matchAndConvert(
1049 > c,
1050 > s.key,
1051 > s.def,
1052 > s.convert,
1053 > prec,
1054 > )
1055 > }
1056 }
1057
1105 }
1106
1107 > func GetTypedPropertyFnFilteredByNamespace[T any](value T) TypedPropertyFnWithNamespaceFilter[T] { setting_gen.go
1108 > return func(namespace string) T {
1109 > return value setting_gen.go
1110 > }
1111 }
1112
1134
1135 // NewNamespaceIDTypedSettingWithConverter creates a setting with a custom converter function.
1136 > func NewNamespaceIDTypedSettingWithConverter[T any](key string, convert func(any) (T, error), def T, description string) NamespaceIDTypedSetting[T] { setting_gen.go
1137 > s := NamespaceIDTypedSetting[T]{
1138 > key: MakeKey(key),
1139 > def: def,
1140 > convert: convert,
1141 > description: description,
1142 > }
1143 > register(s)
1144 > return s
1145 > }
1146
1147 // NewNamespaceIDTypedSettingWithConstrainedDefault creates a setting with a compound default value.
1157 }
1158
1159 > func (s NamespaceIDTypedSetting[T]) Key() Key { return s.key } setting_gen.go
1160 func (s NamespaceIDTypedSetting[T]) Precedence() Precedence { return PrecedenceNamespaceID }
1161 func (s NamespaceIDTypedSetting[T]) Validate(v any) error {
1179 type TypedPropertyFnWithNamespaceIDFilter[T any] func(namespaceID namespace.ID) T
1180
1181 > func (s NamespaceIDTypedSetting[T]) Get(c *Collection) TypedPropertyFnWithNamespaceIDFilter[T] { setting_gen.go
1182 > return func(namespaceID namespace.ID) T {
1183 prec := []Constraints{{NamespaceID: namespaceID.String()}, {}}
1184 return matchAndConvert(
1253 // values. The value from dynamic config will be _merged_ over a deep copy of 'def'. Be very careful
1254 // when using non-empty maps or slices as defaults, the result may not be what you want.
1255 > func NewTaskQueueTypedSetting[T any](key string, def T, description string) TaskQueueTypedSetting[T] { setting_gen.go
1256 > // Warn on any shared structure used with ConvertStructure, even though we handle it by deep copying.
1257 > warnDefaultSharedStructure(key, def)
1258 > // If even deep copy won't even work, we should panic early. Do that by calling deep copy once here.
1259 > _ = deepCopyForMapstructure(def)
1260 >
1261 > s := TaskQueueTypedSetting[T]{
1262 > key: MakeKey(key),
1263 > def: def,
1264 > convert: ConvertStructure[T](def),
1265 > description: description,
1266 > }
1267 > register(s)
1268 > return s
1269 > }
1270
1271 // NewTaskQueueTypedSettingWithConverter creates a setting with a custom converter function.
1272 > func NewTaskQueueTypedSettingWithConverter[T any](key string, convert func(any) (T, error), def T, description string) TaskQueueTypedSetting[T] { setting_gen.go
1273 > s := TaskQueueTypedSetting[T]{
1274 > key: MakeKey(key),
1275 > def: def,
1276 > convert: convert,
1277 > description: description,
1278 > }
1279 > register(s)
1280 > return s
1281 > }
1282
1283 // NewTaskQueueTypedSettingWithConstrainedDefault creates a setting with a compound default value.
1284 > func NewTaskQueueTypedSettingWithConstrainedDefault[T any](key string, convert func(any) (T, error), cdef []TypedConstrainedValue[T], description string) TaskQueueTypedConstrainedDefaultSetting[T] { setting_gen.go
1285 > s := TaskQueueTypedConstrainedDefaultSetting[T]{
1286 > key: MakeKey(key),
1287 > cdef: cdef,
1288 > convert: convert,
1289 > description: description,
1290 > }
1291 > register(s)
1292 > return s
1293 > }
1294
1295 > func (s TaskQueueTypedSetting[T]) Key() Key { return s.key } setting_gen.go
1296 func (s TaskQueueTypedSetting[T]) Precedence() Precedence { return PrecedenceTaskQueue }
1297 func (s TaskQueueTypedSetting[T]) Validate(v any) error {
1300 }
1301
1302 > func (s TaskQueueTypedConstrainedDefaultSetting[T]) Key() Key { return s.key } setting_gen.go
1303 func (s TaskQueueTypedConstrainedDefaultSetting[T]) Precedence() Precedence { return PrecedenceTaskQueue }
1304 func (s TaskQueueTypedConstrainedDefaultSetting[T]) Validate(v any) error {
1315 type TypedPropertyFnWithTaskQueueFilter[T any] func(namespace string, taskQueue string, taskQueueType enumspb.TaskQueueType) T
1316
1317 > func (s TaskQueueTypedSetting[T]) Get(c *Collection) TypedPropertyFnWithTaskQueueFilter[T] { setting_gen.go
1318 > return func(namespace string, taskQueue string, taskQueueType enumspb.TaskQueueType) T {
1319 > prec := []Constraints{ setting_gen.go
1320 > {Namespace: namespace, TaskQueueName: taskQueue, TaskQueueType: taskQueueType},
1321 > {Namespace: namespace, TaskQueueName: taskQueue},
1322 > {TaskQueueName: taskQueue},
1323 > {Namespace: namespace},
1324 > {},
1325 > }
1326 > return matchAndConvert(
1327 > c,
1328 > s.key,
1329 > s.def,
1330 > s.convert,
1331 > prec,
1332 > )
1333 > }
1334 }
1335
1430
1431 // NewShardIDTypedSettingWithConverter creates a setting with a custom converter function.
1432 > func NewShardIDTypedSettingWithConverter[T any](key string, convert func(any) (T, error), def T, description string) ShardIDTypedSetting[T] { setting_gen.go
1433 > s := ShardIDTypedSetting[T]{
1434 > key: MakeKey(key),
1435 > def: def,
1436 > convert: convert,
1437 > description: description,
1438 > }
1439 > register(s)
1440 > return s
1441 > }
1442
1443 // NewShardIDTypedSettingWithConstrainedDefault creates a setting with a compound default value.
1453 }
1454
1455 > func (s ShardIDTypedSetting[T]) Key() Key { return s.key } setting_gen.go
1456 func (s ShardIDTypedSetting[T]) Precedence() Precedence { return PrecedenceShardID }
1457 func (s ShardIDTypedSetting[T]) Validate(v any) error {
1475 type TypedPropertyFnWithShardIDFilter[T any] func(shardID int32) T
1476
1477 > func (s ShardIDTypedSetting[T]) Get(c *Collection) TypedPropertyFnWithShardIDFilter[T] { setting_gen.go
1478 > return func(shardID int32) T {
1479 prec := []Constraints{{ShardID: shardID}, {}}
1480 return matchAndConvert(
1566
1567 // NewTaskTypeTypedSettingWithConverter creates a setting with a custom converter function.
1568 > func NewTaskTypeTypedSettingWithConverter[T any](key string, convert func(any) (T, error), def T, description string) TaskTypeTypedSetting[T] { setting_gen.go
1569 > s := TaskTypeTypedSetting[T]{
1570 > key: MakeKey(key),
1571 > def: def,
1572 > convert: convert,
1573 > description: description,
1574 > }
1575 > register(s)
1576 > return s
1577 > }
1578
1579 // NewTaskTypeTypedSettingWithConstrainedDefault creates a setting with a compound default value.
1589 }
1590
1591 > func (s TaskTypeTypedSetting[T]) Key() Key { return s.key } setting_gen.go
1592 func (s TaskTypeTypedSetting[T]) Precedence() Precedence { return PrecedenceTaskType }
1593 func (s TaskTypeTypedSetting[T]) Validate(v any) error {
1611 type TypedPropertyFnWithTaskTypeFilter[T any] func(taskType enumsspb.TaskType) T
1612
1613 > func (s TaskTypeTypedSetting[T]) Get(c *Collection) TypedPropertyFnWithTaskTypeFilter[T] { setting_gen.go
1614 > return func(taskType enumsspb.TaskType) T {
1615 prec := []Constraints{{TaskType: taskType}, {}}
1616 return matchAndConvert(
1685 // values. The value from dynamic config will be _merged_ over a deep copy of 'def'. Be very careful
1686 // when using non-empty maps or slices as defaults, the result may not be what you want.
1687 > func NewDestinationTypedSetting[T any](key string, def T, description string) DestinationTypedSetting[T] { setting_gen.go
1688 > // Warn on any shared structure used with ConvertStructure, even though we handle it by deep copying.
1689 > warnDefaultSharedStructure(key, def)
1690 > // If even deep copy won't even work, we should panic early. Do that by calling deep copy once here.
1691 > _ = deepCopyForMapstructure(def)
1692 >
1693 > s := DestinationTypedSetting[T]{
1694 > key: MakeKey(key),
1695 > def: def,
1696 > convert: ConvertStructure[T](def),
1697 > description: description,
1698 > }
1699 > register(s)
1700 > return s
1701 > }
1702
1703 // NewDestinationTypedSettingWithConverter creates a setting with a custom converter function.
1704 > func NewDestinationTypedSettingWithConverter[T any](key string, convert func(any) (T, error), def T, description string) DestinationTypedSetting[T] { setting_gen.go
1705 > s := DestinationTypedSetting[T]{
1706 > key: MakeKey(key),
1707 > def: def,
1708 > convert: convert,
1709 > description: description,
1710 > }
1711 > register(s)
1712 > return s
1713 > }
1714
1715 // NewDestinationTypedSettingWithConstrainedDefault creates a setting with a compound default value.
1725 }
1726
1727 > func (s DestinationTypedSetting[T]) Key() Key { return s.key } setting_gen.go
1728 func (s DestinationTypedSetting[T]) Precedence() Precedence { return PrecedenceDestination }
1729 func (s DestinationTypedSetting[T]) Validate(v any) error {
1747 type TypedPropertyFnWithDestinationFilter[T any] func(namespace string, destination string) T
1748
1749 > func (s DestinationTypedSetting[T]) Get(c *Collection) TypedPropertyFnWithDestinationFilter[T] { setting_gen.go
1750 > return func(namespace string, destination string) T {
1751 prec := []Constraints{
1752 {Namespace: namespace, Destination: destination},
1785 type TypedSubscribableWithDestinationFilter[T any] func(namespace string, destination string, callback func(T)) (v T, cancel func())
1786
1787 > func (s DestinationTypedSetting[T]) Subscribe(c *Collection) TypedSubscribableWithDestinationFilter[T] { setting_gen.go
1788 > return func(namespace string, destination string, callback func(T)) (T, func()) {
1789 prec := []Constraints{
1790 {Namespace: namespace, Destination: destination},
1858
1859 // NewChasmTaskTypeTypedSettingWithConverter creates a setting with a custom converter function.
1860 > func NewChasmTaskTypeTypedSettingWithConverter[T any](key string, convert func(any) (T, error), def T, description string) ChasmTaskTypeTypedSetting[T] { setting_gen.go
1861 > s := ChasmTaskTypeTypedSetting[T]{
1862 > key: MakeKey(key),
1863 > def: def,
1864 > convert: convert,
1865 > description: description,
1866 > }
1867 > register(s)
1868 > return s
1869 > }
1870
1871 // NewChasmTaskTypeTypedSettingWithConstrainedDefault creates a setting with a compound default value.
1881 }
1882
1883 > func (s ChasmTaskTypeTypedSetting[T]) Key() Key { return s.key } setting_gen.go
1884 func (s ChasmTaskTypeTypedSetting[T]) Precedence() Precedence { return PrecedenceChasmTaskType }
1885 func (s ChasmTaskTypeTypedSetting[T]) Validate(v any) error {
1903 type TypedPropertyFnWithChasmTaskTypeFilter[T any] func(chasmTaskType string) T
1904
1905 > func (s ChasmTaskTypeTypedSetting[T]) Get(c *Collection) TypedPropertyFnWithChasmTaskTypeFilter[T] { setting_gen.go
1906 > return func(chasmTaskType string) T {
1907 prec := []Constraints{{ChasmTaskType: chasmTaskType}, {}}
1908 return matchAndConvert(
go.temporal.io/server/service/history/shard/context_impl.go 281 covered LOC · 79 ranges

Open complete file

210 }
211
212 > func (s *ContextImpl) GetShardID() int32 { context_impl.go
213 > // constant from initialization, no need for locks
214 > return s.shardID
215 > }
216
217 func (s *ContextImpl) GetRangeID() int64 {
222 }
223
224 > func (s *ContextImpl) GetOwner() string { context_impl.go
225 > // constant from initialization, no need for locks
226 > return s.owner
227 > }
228
229 > func (s *ContextImpl) GetExecutionManager() persistence.ExecutionManager { context_impl.go
230 > // constant from initialization, no need for locks
231 > return s.executionManager
232 > }
233
234 func (s *ContextImpl) GetPingChecks() []pingable.Check {
265 func (s *ContextImpl) GetEngine(
266 ctx context.Context,
267 > ) (historyi.Engine, error) { context_impl.go
268 > return s.engineFuture.Get(ctx)
269 > }
270
271 func (s *ContextImpl) AssertOwnership(
313 }
314
315 > func (s *ContextImpl) CurrentVectorClock() *clockspb.VectorClock { context_impl.go
316 > s.rLock()
317 > defer s.rUnlock()
318 >
319 > nextTaskKey := s.taskKeyManager.peekTaskKey(tasks.CategoryTransfer)
320 > return vclock.NewVectorClock(s.clusterMetadata.GetClusterID(), s.shardID, nextTaskKey.TaskID)
321 > }
322
323 func (s *ContextImpl) GenerateTaskID() (int64, error) {
328 }
329
330 > func (s *ContextImpl) GetFinalizer() *finalizer.Finalizer { context_impl.go
331 > return s.finalizer
332 > }
333
334 > func (s *ContextImpl) GenerateTaskIDs(number int) ([]int64, error) { context_impl.go
335 > s.wLock()
336 > defer s.wUnlock()
337 >
338 > result := []int64{}
339 > for range number {
340 > id, err := s.generateTaskIDLocked() context_impl.go
341 > if err != nil {
342 return nil, err
343 }
344 > result = append(result, id) context_impl.go
345 }
346 > return result, nil context_impl.go
347 }
348
596 ctx context.Context,
597 request *persistence.UpdateWorkflowExecutionRequest,
598 > ) (*persistence.UpdateWorkflowExecutionResponse, error) { context_impl.go
599 > // do not try to get namespace cache within shard lock
600 > namespaceID := namespace.ID(request.UpdateWorkflowMutation.ExecutionInfo.NamespaceId)
601 > namespaceEntry, err := s.GetNamespaceRegistry().GetNamespaceByID(namespaceID)
602 > if err != nil {
603 return nil, err
604 }
605
606 > if err := s.ioSemaphoreAcquire(ctx); err != nil { context_impl.go
607 return nil, err
608 }
609 > defer s.ioSemaphoreRelease() context_impl.go
610 >
611 > s.wLock()
612 >
613 > // timeout check should be done within the shard lock, in case of shard lock contention
614 > ctx, cancel, err := s.newDetachedContext(ctx)
615 > if err != nil {
616 s.wUnlock()
617 return nil, err
618 }
619 > defer cancel() context_impl.go
620 >
621 > if err := s.errorByState(); err != nil {
622 s.wUnlock()
623 return nil, err
624 }
625
626 > if err := s.errorByNamespaceStateLocked(namespaceEntry.Name(), request.UpdateWorkflowMutation.ExecutionInfo.WorkflowId); err != nil { context_impl.go
627 s.wUnlock()
628 return nil, err
629 }
630
631 > taskMaps := make([]map[tasks.Category][]tasks.Task, 0, 2) context_impl.go
632 > taskMaps = append(taskMaps, request.UpdateWorkflowMutation.Tasks)
633 > if request.NewWorkflowSnapshot != nil {
634 taskMaps = append(taskMaps, request.NewWorkflowSnapshot.Tasks)
635 }
636 > requestCompletionFn, err := s.taskKeyManager.setAndTrackTaskKeys(taskMaps...) context_impl.go
637 > if err != nil {
638 s.wUnlock()
639 return nil, err
640 }
641 > s.updateCloseTaskIDs(request.UpdateWorkflowMutation.ExecutionInfo, request.UpdateWorkflowMutation.Tasks) context_impl.go
642 > if request.NewWorkflowSnapshot != nil {
643 s.updateCloseTaskIDs(request.NewWorkflowSnapshot.ExecutionInfo, request.NewWorkflowSnapshot.Tasks)
644 }
645
646 > request.RangeID = s.getRangeIDLocked() context_impl.go
647 > s.wUnlock()
648 >
649 > resp, err := s.executionManager.UpdateWorkflowExecution(ctx, request)
650 > requestCompletionFn(err)
651 > if err = s.handleWriteError(request.RangeID, err); err != nil {
652 return nil, err
653 }
654 > return resp, nil context_impl.go
655 }
656
657 > func (s *ContextImpl) updateCloseTaskIDs(executionInfo *persistencespb.WorkflowExecutionInfo, tasksByCategory map[tasks.Category][]tasks.Task) { context_impl.go
658 > for _, t := range tasksByCategory[tasks.CategoryTransfer] {
659 > if t.GetType() == enumsspb.TASK_TYPE_TRANSFER_CLOSE_EXECUTION { context_impl.go
660 executionInfo.CloseTransferTaskId = t.GetTaskID()
661 break
662 }
663 }
664 > for _, t := range tasksByCategory[tasks.CategoryVisibility] { context_impl.go
665 if t.GetType() == enumsspb.TASK_TYPE_VISIBILITY_CLOSE_EXECUTION ||
666 t.GetType() == enumsspb.TASK_TYPE_CHASM {
807 ctx context.Context,
808 request *persistence.GetWorkflowExecutionRequest,
809 > ) (*persistence.GetWorkflowExecutionResponse, error) { context_impl.go
810 > if err := s.errorByState(); err != nil {
811 return nil, err
812 }
813
814 > resp, err := s.executionManager.GetWorkflowExecution(ctx, request) context_impl.go
815 > if err = s.handleReadError(err); err != nil {
816 // also return resp, for RebuildMutableState API
817 return resp, err
818 }
819 > return resp, nil context_impl.go
820 }
821
1100 }
1101
1102 > func (s *ContextImpl) GetConfig() *configs.Config { context_impl.go
1103 > // constant from initialization, no need for locks
1104 > return s.config
1105 > }
1106
1107 > func (s *ContextImpl) GetEventsCache() events.Cache { context_impl.go
1108 > // constant from initialization (except for tests), no need for locks
1109 > return s.eventsCache
1110 > }
1111
1112 > func (s *ContextImpl) GetLogger() log.Logger { context_impl.go
1113 > // constant from initialization, no need for locks
1114 > return s.contextTaggedLogger
1115 > }
1116
1117 > func (s *ContextImpl) GetThrottledLogger() log.Logger { context_impl.go
1118 > // constant from initialization, no need for locks
1119 > return s.throttledLogger
1120 > }
1121
1122 > func (s *ContextImpl) getRangeIDLocked() int64 { context_impl.go
1123 > return s.shardInfo.GetRangeId()
1124 > }
1125
1126 > func (s *ContextImpl) errorByState() error { context_impl.go
1127 > s.stateLock.Lock()
1128 > defer s.stateLock.Unlock()
1129 >
1130 > switch s.state {
1131 case contextStateInitialized, contextStateAcquiring:
1132 return ErrShardStatusUnknown
1133 > case contextStateAcquired: context_impl.go
1134 > return nil
1135 case contextStateStopping, contextStateStopped:
1136 return s.newShardClosedErrorWithShardID()
1143 namespaceName namespace.Name,
1144 workflowID string,
1145 > ) error { context_impl.go
1146 > if s.handoverTracker.IsInHandover(namespaceName, workflowID) {
1147 return consts.ErrNamespaceHandover
1148 }
1149 > return nil context_impl.go
1150 }
1151
1152 > func (s *ContextImpl) generateTaskIDLocked() (int64, error) { context_impl.go
1153 > taskKey, err := s.taskKeyManager.generateTaskKey(tasks.CategoryTransfer)
1154 > if err != nil {
1155 return -1, err
1156 }
1157 > return taskKey.TaskID, nil context_impl.go
1158 }
1159
1365 }
1366
1367 > func (s *ContextImpl) handleReadError(err error) error { context_impl.go
1368 > switch err.(type) {
1369 > case nil: context_impl.go
1370 > return nil
1371
1372 case *persistence.ShardOwnershipLostError:
1384 requestRangeID int64,
1385 err error,
1386 > ) error { context_impl.go
1387 > s.wLock()
1388 > defer s.wUnlock()
1389 >
1390 > return s.handleWriteErrorLocked(requestRangeID, err)
1391 > }
1392
1393 func (s *ContextImpl) handleWriteErrorLocked(
1394 requestRangeID int64,
1395 err error,
1396 > ) error { context_impl.go
1397 >
1398 > if requestRangeID != s.getRangeIDLocked() {
1399 return err
1400 }
1401
1402 > if valid := s.IsValid(); !valid { context_impl.go
1403 return err
1404 }
1405 > switch err.(type) { context_impl.go
1406 > case nil: context_impl.go
1407 > // Persistence success: update max read level
1408 > return nil
1409
1410 case *persistence.AppendHistoryTimeoutError:
1469
1470 // FinishStop should only be called by the controller.
1471 > func (s *ContextImpl) FinishStop() { context_impl.go
1472 > // After this returns, engineFuture.Set may not be called anymore, so if we don't get see
1473 > // an Engine here, we won't ever have one.
1474 > _ = s.transition(contextRequestFinishStop{})
1475 >
1476 > // Use a context that we know is cancelled so that this doesn't block.
1477 > engine, _ := s.engineFuture.Get(s.lifecycleCtx)
1478 >
1479 > // Stop the engine if it was running (outside the lock but before returning).
1480 > if engine != nil {
1481 > s.contextTaggedLogger.Info("", tag.LifeCycleStopping, tag.ComponentShardEngine) context_impl.go
1482 > engine.Stop()
1483 > s.contextTaggedLogger.Info("", tag.LifeCycleStopped, tag.ComponentShardEngine)
1484 > }
1485
1486 // Run finalizer to cleanup any of the shard's associated resources that are registered.
1487 > if s.finalizer != nil { context_impl.go
1488 s.finalizer.Run(s.config.ShardFinalizerTimeout())
1489 }
1490 }
1491
1492 > func (s *ContextImpl) IsValid() bool { context_impl.go
1493 > s.stateLock.Lock()
1494 > defer s.stateLock.Unlock()
1495 > return s.state < contextStateStopping
1496 > }
1497
1498 func (s *ContextImpl) GetLifecycleContext() context.Context {
1506 }
1507
1508 > func (s *ContextImpl) wLock() { context_impl.go
1509 > handler := s.metricsHandler.WithTags(metrics.OperationTag(metrics.ShardInfoScope))
1510 > metrics.LockRequests.With(handler).Record(1)
1511 > startTime := time.Now().UTC()
1512 > defer func() { metrics.LockLatency.With(handler).Record(time.Since(startTime)) }()
1513
1514 > s.rwLock.Lock() context_impl.go
1515 }
1516
1517 > func (s *ContextImpl) rLock() { context_impl.go
1518 > handler := s.metricsHandler.WithTags(metrics.OperationTag(metrics.ShardInfoScope))
1519 > metrics.LockRequests.With(handler).Record(1)
1520 > startTime := time.Now().UTC()
1521 > defer func() { metrics.LockLatency.With(handler).Record(time.Since(startTime)) }()
1522
1523 > s.rwLock.RLock() context_impl.go
1524 }
1525
1526 > func (s *ContextImpl) wUnlock() { context_impl.go
1527 > s.rwLock.Unlock()
1528 > }
1529
1530 > func (s *ContextImpl) rUnlock() { context_impl.go
1531 > s.rwLock.RUnlock()
1532 > }
1533
1534 func (s *ContextImpl) ioSemaphoreAcquire(
1535 ctx context.Context,
1536 > ) (retErr error) { context_impl.go
1537 > priority := locks.PriorityHigh
1538 > callerInfo := headers.GetCallerInfo(ctx)
1539 > if callerInfo.CallerType == headers.CallerTypePreemptable {
1540 priority = locks.PriorityLow
1541 }
1542
1543 > handler := s.metricsHandler.WithTags(metrics.OperationTag(metrics.ShardInfoScope), metrics.PriorityTag(priority)) context_impl.go
1544 > metrics.SemaphoreRequests.With(handler).Record(1)
1545 > startTime := time.Now().UTC()
1546 > defer func() {
1547 > metrics.SemaphoreLatency.With(handler).Record(time.Since(startTime))
1548 > if retErr != nil {
1549 metrics.SemaphoreFailures.With(handler).Record(1)
1550 }
1551 }()
1552
1553 > return s.ioSemaphore.Acquire(ctx, priority, 1) context_impl.go
1554 }
1555
1556 > func (s *ContextImpl) ioSemaphoreRelease() { context_impl.go
1557 > s.ioSemaphore.Release(1)
1558 > }
1559
1560 > func (s *ContextImpl) transition(request contextRequest) error { context_impl.go
1561 > /* State transitions:
1562 >
1563 > The normal pattern:
1564 > Initialized
1565 > controller calls start()
1566 > Acquiring
1567 > acquireShard gets the shard
1568 > Acquired
1569 >
1570 > If we get a transient error from persistence:
1571 > Acquired
1572 > transient error: handleErrorLocked calls transition(contextRequestLost)
1573 > Acquiring
1574 > acquireShard gets the shard
1575 > Acquired
1576 >
1577 > If we get shard ownership lost:
1578 > Acquired
1579 > ShardOwnershipLostError: handleErrorLocked calls transition(contextRequestStop)
1580 > Stopping
1581 > controller removes from map and calls FinishStop()
1582 > Stopped
1583 >
1584 > Stopping can be triggered internally (if we get a ShardOwnershipLostError, or fail to acquire the rangeid
1585 > lock after several minutes) or externally (from controller, e.g. controller shutting down or admin force-
1586 > unload shard). If it's triggered internally, we transition to Stopping, then make an asynchronous callback
1587 > to controller, which will remove us from the map and call FinishStop(), which will transition to Stopped and
1588 > stop the engine. If it's triggered externally, we'll skip over Stopping and go straight to Stopped.
1589 >
1590 > If we transition externally to Stopped, and the acquireShard goroutine is still running, we can't kill it,
1591 > but we should make sure that it can't do anything: the context it uses for persistence ops will be
1592 > canceled, and if it tries to transition states, it will fail.
1593 >
1594 > Invariants:
1595 > - Once state is Stopping, it can only go to Stopped.
1596 > - Once state is Stopped, it can't go anywhere else.
1597 > - At the start of acquireShard, state must be Acquiring.
1598 > - By the end of acquireShard, state must not be Acquiring: either acquireShard set it to Acquired, or the
1599 > controller set it to Stopped.
1600 > - If state is Acquiring, acquireShard should be running in the background.
1601 > - Only acquireShard can use contextRequestAcquired (i.e. transition from Acquiring to Acquired).
1602 > - Once state has reached Acquired at least once, and not reached Stopped, engineFuture must be set.
1603 > - Only the controller may call start() and FinishStop().
1604 > - The controller must call FinishStop() for every ContextImpl it creates.
1605 >
1606 > */
1607 >
1608 > s.stateLock.Lock()
1609 > defer s.stateLock.Unlock()
1610 >
1611 > setStateAcquiring := func() {
1612 s.state = contextStateAcquiring
1613 s.contextTaggedLogger.Info("", tag.LifeCycleStarted, tag.ComponentShardContext)
1615 }
1616
1617 > setStateStopping := func(request contextRequestStop) { context_impl.go
1618 s.state = contextStateStopping
1619 s.stopReason = request.reason
1627 }
1628
1629 > setStateStopped := func() { context_impl.go
1630 > s.state = contextStateStopped context_impl.go
1631 > s.contextTaggedLogger.Info("", tag.LifeCycleStopped, tag.ComponentShardContext)
1632 > // Do this again in case we skipped the stopping state, which could happen
1633 > // when calling CloseShardByID or the controller is shutting down.
1634 > s.lifecycleCancel()
1635 > }
1636
1637 > switch s.state { context_impl.go
1638 case contextStateInitialized:
1639 switch request := request.(type) {
1681 return nil
1682 }
1683 > case contextStateAcquired: context_impl.go
1684 > switch request := request.(type) {
1685 case contextRequestAcquire:
1686 return nil // nothing to do, already acquired
1691 setStateStopping(request)
1692 return nil
1693 > case contextRequestFinishStop: context_impl.go
1694 > setStateStopped()
1695 > return nil
1696 }
1697 case contextStateStopping:
2212 }
2213
2214 > func (s *ContextImpl) GetMetricsHandler() metrics.Handler { context_impl.go
2215 > return s.metricsHandler
2216 > }
2217
2218 > func (s *ContextImpl) GetTimeSource() cclock.TimeSource { context_impl.go
2219 > return s.timeSource
2220 > }
2221
2222 > func (s *ContextImpl) GetNamespaceRegistry() namespace.Registry { context_impl.go
2223 > return s.namespaceRegistry
2224 > }
2225
2226 func (s *ContextImpl) GetSearchAttributesProvider() searchattribute.Provider {
2228 }
2229
2230 > func (s *ContextImpl) GetSearchAttributesMapperProvider() searchattribute.MapperProvider { context_impl.go
2231 > return s.saMapperProvider
2232 > }
2233
2234 > func (s *ContextImpl) GetClusterMetadata() cluster.Metadata { context_impl.go
2235 > return s.clusterMetadata
2236 > }
2237
2238 > func (s *ContextImpl) GetArchivalMetadata() archiver.ArchivalMetadata { context_impl.go
2239 > return s.archivalMetadata
2240 > }
2241
2242 > func (s *ContextImpl) StateMachineRegistry() *hsm.Registry { context_impl.go
2243 > return s.stateMachineRegistry
2244 > }
2245
2246 > func (s *ContextImpl) ChasmRegistry() *chasm.Registry { context_impl.go
2247 > return s.chasmRegistry
2248 > }
2249
2250 func (s *ContextImpl) ChasmWorkflowRegistry() *chasmworkflow.Registry {
2252 }
2253
2254 > func (s *ContextImpl) EndpointRegistry() chasm.EndpointRegistry { context_impl.go
2255 > return s.endpointRegistry
2256 > }
2257
2258 func (s *ContextImpl) BusinessIDReuseRateLimiter(namespaceID namespace.ID, businessID string, archetypeID chasm.ArchetypeID) quotas.RateLimiter {
2303 func (s *ContextImpl) newDetachedContext(
2304 ctx context.Context,
2305 > ) (context.Context, context.CancelFunc, error) { context_impl.go
2306 > if err := ctx.Err(); err != nil {
2307 return nil, nil, err
2308 }
2309
2310 > detachedContext := rpc.CopyContextValues(s.lifecycleCtx, ctx) context_impl.go
2311 >
2312 > var cancel context.CancelFunc
2313 > deadline, ok := ctx.Deadline()
2314 > if ok {
2315 timeout := max(deadline.Sub(s.GetTimeSource().Now()), minContextTimeout)
2316 detachedContext, cancel = context.WithTimeout(detachedContext, timeout)
2317 > } else { context_impl.go
2318 > cancel = func() {} context_impl.go
2319 }
2320
2321 > return detachedContext, cancel, nil context_impl.go
2322 }
2323
go.temporal.io/server/service/history/api/respondworkflowtaskcompleted/api.go 272 covered LOC · 56 ranges

Open complete file

81 matchingClient matchingservice.MatchingServiceClient,
82 versionCache worker_versioning.VersionMembershipAndReactivationStatusCache,
83 > ) *WorkflowTaskCompletedHandler { api.go
84 > return &WorkflowTaskCompletedHandler{
85 > config: shardContext.GetConfig(),
86 > shardContext: shardContext,
87 > workflowConsistencyChecker: workflowConsistencyChecker,
88 > timeSource: shardContext.GetTimeSource(),
89 > namespaceRegistry: shardContext.GetNamespaceRegistry(),
90 > eventNotifier: eventNotifier,
91 > tokenSerializer: tokenSerializer,
92 > metricsHandler: shardContext.GetMetricsHandler(),
93 > logger: shardContext.GetLogger(),
94 > throttledLogger: shardContext.GetThrottledLogger(),
95 > commandAttrValidator: api.NewCommandAttrValidator(
96 > shardContext.GetNamespaceRegistry(),
97 > shardContext.GetConfig(),
98 > searchAttributesValidator,
99 > ),
100 > searchAttributesMapperProvider: shardContext.GetSearchAttributesMapperProvider(),
101 > searchAttributesValidator: searchAttributesValidator,
102 > persistenceVisibilityMgr: visibilityManager,
103 > commandHandlerRegistry: commandHandlerRegistry,
104 > chasmWorkflowRegistry: chasmWorkflowRegistry,
105 > matchingClient: matchingClient,
106 > versionCache: versionCache,
107 > }
108 > }
109
110 //nolint:revive // cyclomatic complexity
112 ctx context.Context,
113 req *historyservice.RespondWorkflowTaskCompletedRequest,
114 > ) (_ *historyservice.RespondWorkflowTaskCompletedResponse, retError error) { api.go
115 > // By default, retError is passed to workflow lease release method in deferred function.
116 > // If error is passed, then workflow context and mutable state are cleared.
117 > // If no changes to mutable state are made or changes already persisted (in memory version corresponds to the database),
118 > // then the lease is released without an error, i.e. workflow context and mutable state are NOT cleared.
119 > releaseLeaseWithError := true
120 >
121 > request := req.CompleteRequest
122 > token, err0 := handler.tokenSerializer.Deserialize(request.TaskToken)
123 > if err0 != nil {
124 return nil, consts.ErrDeserializingToken
125 }
126
127 > namespaceEntry, err := api.GetActiveNamespace(handler.shardContext, namespace.ID(req.GetNamespaceId()), token.WorkflowId) api.go
128 > if err != nil {
129 return nil, err
130 }
131
132 > workflowLease, err := handler.workflowConsistencyChecker.GetWorkflowLeaseWithConsistencyCheck( api.go
133 > ctx,
134 > token.Clock,
135 > func(mutableState historyi.MutableState) bool {
136 > workflowTask := mutableState.GetWorkflowTaskByID(token.GetScheduledEventId()) api.go
137 > if workflowTask == nil && token.GetScheduledEventId() >= mutableState.GetNextEventID() {
138 metrics.StaleMutableStateCounter.With(handler.metricsHandler).Record(
139 1,
141 return false
142 }
143 > return true api.go
144 },
145 definition.NewWorkflowKey(
150 locks.PriorityHigh,
151 )
152 > if err != nil { api.go
153 return nil, err
154 }
155 > weContext := workflowLease.GetContext() api.go
156 > ms := workflowLease.GetMutableState()
157 > currentWorkflowTask := ms.GetWorkflowTaskByID(token.GetScheduledEventId())
158 >
159 > if len(request.Commands) == 0 {
160 // Context metadata is automatically set during mutable state transaction close. For RespondWorkflowTaskCompleted
161 // with no commands (e.g., workflow task heartbeat or only readonly messages like `update.Rejection`), the transaction
164 }
165
166 > defer func() { api.go
167 > var errForRelease error
168 > if releaseLeaseWithError {
169 > // If the workflow context needs to be cleared, operation error passed to Release func (default). api.go
170 > // Otherwise, leave it nil here to avoid clearing the workflow context (but still return error to the caller).
171 > errForRelease = retError
172 > }
173 > if retError != nil && currentWorkflowTask != nil && currentWorkflowTask.Type == enumsspb.WORKFLOW_TASK_TYPE_SPECULATIVE && ms.IsStickyTaskQueueSet() { api.go
174 // If, while completing WFT, error is occurred and returned to the worker then worker will clear its cache.
175 // New WFT will also be created on sticky task queue and sent to worker.
197 }
198
199 > workflowLease.GetReleaseFn()(errForRelease) api.go
200 }()
201
202 > if !ms.IsWorkflowExecutionRunning() || api.go
203 > currentWorkflowTask == nil ||
204 > currentWorkflowTask.StartedEventID == common.EmptyEventID ||
205 > (token.StartedEventId != common.EmptyEventID && token.StartedEventId != currentWorkflowTask.StartedEventID) ||
206 > (token.StartedTime != nil && !currentWorkflowTask.StartedTime.IsZero() && !token.StartedTime.AsTime().Equal(currentWorkflowTask.StartedTime)) ||
207 > currentWorkflowTask.Attempt != token.Attempt ||
208 > (token.Version != common.EmptyVersion && token.Version != currentWorkflowTask.Version) {
209 // Mutable state wasn't changed yet and doesn't have to be cleared.
210 releaseLeaseWithError = false
213
214 // We don't accept the request to create a new workflow task if the workflow is paused.
215 > if ms.IsWorkflowExecutionStatusPaused() && request.GetForceCreateNewWorkflowTask() { api.go
216 // Mutable state wasn't changed yet and doesn't have to be cleared.
217 releaseLeaseWithError = false
219 }
220
221 > behavior := request.GetVersioningBehavior() api.go
222 > deployment := worker_versioning.DeploymentFromDeploymentVersion(worker_versioning.DeploymentVersionFromOptions(request.GetDeploymentOptions()))
223 > //nolint:staticcheck // SA1019 deprecated Deployment will clean up later
224 > if behavior != enumspb.VERSIONING_BEHAVIOR_UNSPECIFIED && request.GetDeployment() == nil &&
225 > (request.GetDeploymentOptions() == nil || request.GetDeploymentOptions().GetWorkerVersioningMode() != enumspb.WORKER_VERSIONING_MODE_VERSIONED) {
226 // Mutable state wasn't changed yet and doesn't have to be cleared.
227 releaseLeaseWithError = false
229 }
230
231 > assignedBuildId := ms.GetAssignedBuildId() api.go
232 > wftCompletedBuildId := request.GetWorkerVersionStamp().GetBuildId()
233 > if assignedBuildId != "" && !ms.IsStickyTaskQueueSet() {
234 // Worker versioning is used, make sure the task was completed by the right build ID, unless we're using a
235 // sticky queue in which case Matching will not send the build ID until old versioning is cleaned up
243 }
244
245 > var effects effect.Buffer api.go
246 > defer func() {
247 > // `effects` are canceled immediately on WFT failure or persistence errors.
248 > // This `defer` handles rare cases where an error is returned but the cancellation didn't happen.
249 > if retError != nil {
250 cancelled := effects.Cancel(ctx)
251 if cancelled {
261 // TODO(carlydf): change condition when deprecating versionstamp
262 // It's an error if the workflow has used versioning in the past but this task has no versioning info.
263 > if ms.GetMostRecentWorkerVersionStamp().GetUseVersioning() && api.go
264 > //nolint:staticcheck // SA1019 deprecated stamp will clean up later
265 > !request.GetWorkerVersionStamp().GetUseVersioning() &&
266 > request.GetDeploymentOptions().GetWorkerVersioningMode() != enumspb.WORKER_VERSIONING_MODE_VERSIONED &&
267 > // This check is not needed for V3 versioning
268 > ms.GetEffectiveVersioningBehavior() == enumspb.VERSIONING_BEHAVIOR_UNSPECIFIED {
269 // Mutable state wasn't changed yet and doesn't have to be cleared.
270 releaseLeaseWithError = false
272 }
273
274 > nsName := namespaceEntry.Name().String() api.go
275 >
276 > // When pagination is enabled, buffer intermediate pages and merge them into the final page
277 > // before continuing through the normal workflow task completion path.
278 > paginationResp, mergedCommands, err := handler.applyTaskCompletionPagination(weContext, token, request, nsName)
279 > // In case of a buffer overflow fall through and fail the workflow task below
280 > paginationOverflow := errors.Is(err, workflow.ErrTaskCompletionBufferSizeExceeded)
281 > if !paginationOverflow && (paginationResp != nil || err != nil) {
282 releaseLeaseWithError = false
283 return paginationResp, err
286 // `commands` is the effective list of commands to execute including ones from
287 // paginated requests. `request.Commands` is left unchanged.
288 > commands := request.Commands api.go
289 > if len(mergedCommands) > 0 {
290 commands = append(mergedCommands, request.Commands...)
291 }
292
293 > limits := historyi.WorkflowTaskCompletionLimits{ api.go
294 > MaxResetPoints: handler.config.MaxAutoResetPoints(nsName),
295 > MaxSearchAttributeValueSize: handler.config.SearchAttributesSizeOfValueLimit(nsName),
296 > }
297 > // TODO: this metric is inaccurate, it should only be emitted if a new binary checksum (or build ID) is added in this completion.
298 > if ms.GetExecutionInfo().AutoResetPoints != nil && limits.MaxResetPoints == len(ms.GetExecutionInfo().AutoResetPoints.Points) {
299 metrics.AutoResetPointsLimitExceededCounter.With(handler.metricsHandler).Record(
300 1,
302 }
303
304 > var wtHeartbeatTimedOut bool api.go
305 > var completedEvent *historypb.HistoryEvent
306 >
307 > // SDKs set ForceCreateNewWorkflowTask flag to true when they are doing WT heartbeats.
308 > // In a mean time, there might be pending commands and messages on the worker side.
309 > // If those commands/messages are sent on the heartbeat WT it means that WF is making progress.
310 > // WT heartbeat timeout is applicable only when WF doesn't make any progress and does heartbeats only.
311 > checkWTHeartbeatTimeout := request.GetForceCreateNewWorkflowTask() && len(commands) == 0 && len(request.Messages) == 0
312 >
313 > if checkWTHeartbeatTimeout {
314 // WorkflowTaskHeartbeatTimeout is a total duration for which workflow is allowed to send continuous heartbeats.
315 // Default is 30 minutes.
336 }
337 // WT wasn't timed out (due to too many heartbeats), therefore WTCompleted event should be created.
338 > if !wtHeartbeatTimedOut { api.go
339 > completedEvent, err = ms.AddWorkflowTaskCompletedEvent(currentWorkflowTask, request, limits) api.go
340 > if err != nil {
341 return nil, err
342 }
345 // See workflowTaskStateMachine.skipWorkflowTaskCompletedEvent for more details.
346
347 > if request.StickyAttributes == nil || request.StickyAttributes.WorkerTaskQueue == nil { api.go
348 > metrics.CompleteWorkflowTaskWithStickyDisabledCounter.With(handler.metricsHandler).Record( api.go
349 > 1,
350 > metrics.OperationTag(metrics.HistoryRespondWorkflowTaskCompletedScope))
351 > ms.ClearStickyTaskQueue()
352 > } else { api.go
353 metrics.CompleteWorkflowTaskWithStickyEnabledCounter.With(handler.metricsHandler).Record(
354 1,
365 }
366
367 > var ( api.go
368 > wtFailedCause *workflowTaskFailedCause
369 > activityNotStartedCancelled bool
370 > newMutableState historyi.MutableState
371 > responseMutations []workflowTaskResponseMutation
372 > )
373 > updateRegistry := weContext.UpdateRegistry(ctx)
374 > // hasBufferedEventsOrMessages indicates if there are any buffered events
375 > // or admitted updates which should generate a new workflow task.
376 >
377 > // TODO: HasOutgoingMessages call (=check for admitted updates) is comment out
378 > // because non-durable admitted updates can't block WF from closing,
379 > // because everytime WFT is failing, WF context is cleared together with update registry
380 > // and admitted updates are lost. Uncomment this check when durable admitted is implemented
381 > // or updates stay in the registry after WFT is failed.
382 > hasBufferedEventsOrMessages := ms.HasBufferedEvents() // || updateRegistry.HasOutgoingMessages(false)
383 > if paginationOverflow {
384 // Per-workflow completion buffer overflowed: terminate the workflow
385 wtFailedCause = newWorkflowTaskFailedCause(
388 "workflow task completion buffer size exceeds the per-workflow limit"),
389 true)
390 > } else if err := namespaceEntry.VerifyBinaryChecksum(request.GetBinaryChecksum()); err != nil { //nolint:staticcheck // SA1019 deprecated stamp will clean up later api.go
391 wtFailedCause = newWorkflowTaskFailedCause(
392 enumspb.WORKFLOW_TASK_FAILED_CAUSE_BAD_BINARY,
396 request.GetBinaryChecksum()),
397 false)
398 > } else { api.go
399 > namespace := namespaceEntry.Name() api.go
400 > workflowSizeChecker := newWorkflowSizeChecker(
401 > workflowSizeLimits{
402 > blobSizeLimitWarn: handler.config.BlobSizeLimitWarn(namespace.String()),
403 > blobSizeLimitError: handler.config.BlobSizeLimitError(namespace.String()),
404 > memoSizeLimitWarn: handler.config.MemoSizeLimitWarn(namespace.String()),
405 > memoSizeLimitError: handler.config.MemoSizeLimitError(namespace.String()),
406 > numPendingChildExecutionsLimit: handler.config.NumPendingChildExecutionsLimit(namespace.String()),
407 > numPendingActivitiesLimit: handler.config.NumPendingActivitiesLimit(namespace.String()),
408 > numPendingSignalsLimit: handler.config.NumPendingSignalsLimit(namespace.String()),
409 > numPendingCancelsRequestLimit: handler.config.NumPendingCancelsRequestLimit(namespace.String()),
410 > },
411 > ms,
412 > handler.searchAttributesValidator,
413 > handler.metricsHandler.WithTags(
414 > metrics.OperationTag(metrics.HistoryRespondWorkflowTaskCompletedScope),
415 > metrics.NamespaceTag(namespace.String()),
416 > ),
417 > handler.throttledLogger,
418 > )
419 >
420 > workflowTaskHandler := newWorkflowTaskCompletedHandler(
421 > request.GetIdentity(),
422 > request.GetWorkerControlTaskQueue(),
423 > completedEvent.GetEventId(), // If completedEvent is nil, then GetEventId() returns 0 and this value shouldn't be used in workflowTaskHandler.
424 > ms,
425 > updateRegistry,
426 > &effects,
427 > handler.commandAttrValidator,
428 > workflowSizeChecker,
429 > handler.logger,
430 > handler.namespaceRegistry,
431 > handler.metricsHandler,
432 > handler.config,
433 > handler.shardContext,
434 > handler.searchAttributesMapperProvider,
435 > hasBufferedEventsOrMessages,
436 > handler.commandHandlerRegistry,
437 > handler.chasmWorkflowRegistry,
438 > handler.matchingClient,
439 > handler.versionCache,
440 > )
441 >
442 > if responseMutations, err = workflowTaskHandler.handleCommands(
443 > ctx,
444 > commands,
445 > collection.NewIndexedTakeList(
446 > request.Messages,
447 > func(msg *protocolpb.Message) string { return msg.Id },
448 ),
449 ); err != nil {
455 // If worker ignored the update request (old SDK or SDK bug), then server rejects this update.
456 // Otherwise, this update will be delivered (and new WT created) again and again.
457 > workflowTaskHandler.rejectUnprocessedUpdates( api.go
458 > ctx,
459 > currentWorkflowTask.ScheduledEventID,
460 > request.GetForceCreateNewWorkflowTask(),
461 > weContext.GetWorkflowKey(),
462 > request.GetIdentity(),
463 > )
464 >
465 > // If the Workflow completed itself, but there are still accepted
466 > // (but not completed) Updates, they need to be aborted.
467 > // Reason is always "WorkflowCompleted" because accepted Updates
468 > // are not moving to continuing runs (if any).
469 > if !ms.IsWorkflowExecutionRunning() {
470 updateRegistry.AbortAccepted(update.AbortReasonWorkflowCompleted, &effects)
471 }
473 // set the vars used by following logic
474 // further refactor should also clean up the vars used below
475 > wtFailedCause = workflowTaskHandler.workflowTaskFailedCause api.go
476 >
477 > // failMessage is not used by workflowTaskHandlerCallbacks
478 > activityNotStartedCancelled = workflowTaskHandler.activityNotStartedCancelled
479 > // continueAsNewTimerTasks is not used by workflowTaskHandlerCallbacks
480 >
481 > newMutableState = workflowTaskHandler.newMutableState
482 >
483 > hasBufferedEventsOrMessages = workflowTaskHandler.hasBufferedEventsOrMessages
484 }
485
486 > wtFailedShouldCreateNewTask := false api.go
487 > if wtFailedCause != nil {
488 effects.Cancel(ctx)
489
539 }
540
541 > newWorkflowTaskType := enumsspb.WORKFLOW_TASK_TYPE_UNSPECIFIED api.go
542 > // Do not schedule a new workflow task if the workflow is paused. Accepting the in-flight
543 > // WT completion is intentional (see HistoryBuilder buffering of WORKFLOW_EXECUTION_PAUSED),
544 > // but scheduling a follow-up WT would call ApplyWorkflowTaskScheduledEvent, which resets
545 > // Status to RUNNING while leaving executionInfo.PauseInfo set — desyncing pause state.
546 > // Mirrors the gate in closeTransactionHandleWorkflowTaskScheduling.
547 > if ms.IsWorkflowExecutionRunning() && !ms.IsWorkflowExecutionStatusPaused() {
548 > if request.GetForceCreateNewWorkflowTask() || // Heartbeat WT is always of Normal type. api.go
549 > wtFailedShouldCreateNewTask ||
550 > hasBufferedEventsOrMessages ||
551 > activityNotStartedCancelled ||
552 > // If the workflow has an ongoing transition to another deployment version, we should ensure
553 > // it has a pending wft so it does not remain in the transition phase for long.
554 > ms.GetDeploymentTransition() != nil {
555
556 newWorkflowTaskType = enumsspb.WORKFLOW_TASK_TYPE_NORMAL
557
558 > } else if updateRegistry.HasOutgoingMessages(true) { api.go
559 // There shouldn't be any sent updates in the registry because
560 // all sent but not processed updates were rejected by server.
565 }
566
567 > bypassTaskGeneration := request.GetReturnNewWorkflowTask() && wtFailedCause == nil api.go
568 > // TODO (alex-update): All current SDKs always set ReturnNewWorkflowTask to true
569 > // which means that server always bypass task generation if WFT didn't fail.
570 > // ReturnNewWorkflowTask flag needs to be removed.
571 >
572 > if newWorkflowTaskType == enumsspb.WORKFLOW_TASK_TYPE_SPECULATIVE && !bypassTaskGeneration {
573 // If task generation can't be bypassed (i.e. WFT has failed),
574 // WFT must be created as Normal because speculative WFT by nature skips task generation.
576 }
577
578 > var newWorkflowTask *historyi.WorkflowTaskInfo api.go
579 >
580 > // Speculative workflow task will be created after mutable state is persisted.
581 > if newWorkflowTaskType == enumsspb.WORKFLOW_TASK_TYPE_NORMAL {
582 versioningStamp := request.WorkerVersionStamp
583 if versioningStamp.GetUseVersioning() {
640 }
641
642 > var updateErr error api.go
643 > if newMutableState != nil {
644 newWorkflowExecutionInfo := newMutableState.GetExecutionInfo()
645 newWorkflowExecutionState := newMutableState.GetExecutionState()
661 newMutableState,
662 )
663 > } else { api.go
664 > // If completedEvent is not nil (which means that this WT wasn't speculative)
665 > // OR new WT is normal, then mutable state needs to be persisted.
666 > // Otherwise, (both current and new WT are speculative) mutable state is updated in memory only but not persisted.
667 > if completedEvent != nil || newWorkflowTaskType == enumsspb.WORKFLOW_TASK_TYPE_NORMAL {
668 > updateErr = weContext.UpdateWorkflowExecutionAsActive(ctx, handler.shardContext) api.go
669 > }
670 }
671
672 > if updateErr != nil { api.go
673 effects.Cancel(ctx)
674 if persistence.IsConflictErr(updateErr) {
712 // If mutable state was persisted successfully (or persistence was skipped),
713 // then effects needs to be applied immediately to keep registry and mutable state in sync.
714 > effects.Apply(ctx) api.go
715 >
716 > if !ms.IsWorkflowExecutionRunning() {
717 // NOTE: It is important to call this *after* applying effects to be sure there are no
718 // Updates in ProvisionallyCompleted state.
736
737 // Create speculative workflow task after mutable state is persisted.
738 > if newWorkflowTaskType == enumsspb.WORKFLOW_TASK_TYPE_SPECULATIVE { api.go
739 newWorkflowTask, err = ms.AddWorkflowTaskScheduledEvent(bypassTaskGeneration, newWorkflowTaskType)
740 if err != nil {
765 }
766
767 > handler.handleBufferedQueries(ms, req.GetCompleteRequest().GetQueryResults(), newWorkflowTask != nil, namespaceEntry) api.go
768 >
769 > if wtHeartbeatTimedOut {
770 // Mutable state was already persisted and doesn't need to be cleared although error is returned to the worker.
771 releaseLeaseWithError = false
773 }
774
775 > if wtFailedCause != nil { api.go
776 // Mutable state was already persisted and doesn't need to be cleared although error is returned to the worker.
777 releaseLeaseWithError = false
779 }
780
781 > resp := &historyservice.RespondWorkflowTaskCompletedResponse{} api.go
782 > //nolint:staticcheck
783 > if newWorkflowTask != nil && bypassTaskGeneration {
784 resp.StartedResponse, err = recordworkflowtaskstarted.CreateRecordWorkflowTaskStartedResponse(
785 ctx,
806 // SDK needs to know where to roll back its history event pointer, i.e. after what event all other events needs to be dropped.
807 // SDK uses WorkflowTaskStartedEventID to do that.
808 > if completedEvent == nil { api.go
809 resp.ResetHistoryEventId = ms.GetExecutionInfo().LastCompletedWorkflowTaskStartedEventId
810 }
811
812 > for _, mutation := range responseMutations { api.go
813 if err := mutation(resp); err != nil {
814 return nil, err
816 }
817
818 > return resp, nil api.go
819 }
820
829 request *workflowservice.RespondWorkflowTaskCompletedRequest,
830 nsName string,
831 > ) (resp *historyservice.RespondWorkflowTaskCompletedResponse, mergedCommands []*commandpb.Command, err error) { api.go
832 > if !handler.config.EnableWorkflowTaskCompletionPagination(nsName) {
833 > if request.GetIntermediatePage() || request.GetPageNumber() > 0 { api.go
834 return nil, nil, serviceerror.NewFailedPreconditionf(
835 "workflow task completion pagination is disabled for this namespace %s",
837 )
838 }
839 > return nil, nil, nil api.go
840 }
841
1020 createNewWorkflowTask bool,
1021 namespaceEntry *namespace.Namespace,
1022 > ) { api.go
1023 > queryRegistry := ms.GetQueryRegistry()
1024 > if !queryRegistry.HasBufferedQuery() {
1025 > return api.go
1026 > }
1027
1028 namespaceName := namespaceEntry.Name()
go.temporal.io/server/service/history/workflow/context.go 263 covered LOC · 77 ranges

Open complete file

88 throttledLogger log.ThrottledLogger,
89 metricsHandler metrics.Handler,
90 > ) *ContextImpl { context.go
91 > tags := func() []tag.Tag {
92 > return []tag.Tag{ context.go
93 > tag.WorkflowNamespaceID(workflowKey.NamespaceID),
94 > tag.WorkflowID(workflowKey.WorkflowID),
95 > tag.WorkflowRunID(workflowKey.RunID),
96 > }
97 > }
98 > contextImpl := &ContextImpl{ context.go
99 > workflowKey: workflowKey,
100 > archetypeID: archetypeID,
101 > logger: log.NewLazyLogger(logger, tags),
102 > throttledLogger: log.NewLazyLogger(throttledLogger, tags),
103 > metricsHandler: metricsHandler.WithTags(metrics.OperationTag(metrics.WorkflowContextScope)),
104 > config: config,
105 > lock: locks.NewPrioritySemaphore(1),
106 > }
107 > softassert.That(
108 > contextImpl.throttledLogger,
109 > contextImpl.archetypeID != chasm.UnspecifiedArchetypeID,
110 > "Creating execution context with unspecified archetype ID",
111 > )
112 >
113 > return contextImpl
114 }
115
117 ctx context.Context,
118 lockPriority locks.Priority,
119 > ) error { context.go
120 > return c.lock.Acquire(ctx, lockPriority, 1)
121 > }
122
123 > func (c *ContextImpl) Unlock() { context.go
124 > c.lock.Release(1)
125 > }
126
127 > func (c *ContextImpl) IsDirty() bool { context.go
128 > if c.MutableState == nil {
129 return false
130 }
131 > return c.MutableState.IsDirty() context.go
132 }
133
177 // task is no longer in flight (timed out, failed, completed, or the workflow
178 // closed) and its buffer can never be consumed
179 > func (c *ContextImpl) reconcileTaskCompletionBuffer() { context.go
180 > if c.taskCompletionBuffer == nil || c.MutableState == nil {
181 > return context.go
182 > }
183 if c.startedWorkflowTaskIdentity() != c.taskCompletionBuffer.identity {
184 c.clearTaskCompletionBuffer()
319 }
320
321 > func (c *ContextImpl) GetWorkflowKey() definition.WorkflowKey { context.go
322 > return c.workflowKey
323 > }
324
325 > func (c *ContextImpl) GetNamespace(shardContext historyi.ShardContext) namespace.Name { context.go
326 > namespaceEntry, err := shardContext.GetNamespaceRegistry().GetNamespaceByID(
327 > namespace.ID(c.workflowKey.NamespaceID),
328 > )
329 > if err != nil {
330 return ""
331 }
332 > return namespaceEntry.Name() context.go
333 }
334
341 }
342
343 > func (c *ContextImpl) LoadMutableState(ctx context.Context, shardContext historyi.ShardContext) (historyi.MutableState, error) { context.go
344 > namespaceEntry, err := shardContext.GetNamespaceRegistry().GetNamespaceByID(
345 > namespace.ID(c.workflowKey.NamespaceID),
346 > )
347 > if err != nil {
348 return nil, err
349 }
350
351 > if c.MutableState == nil { context.go
352 > response, err := getWorkflowExecution(ctx, shardContext, &persistence.GetWorkflowExecutionRequest{ context.go
353 > ShardID: shardContext.GetShardID(),
354 > NamespaceID: c.workflowKey.NamespaceID,
355 > WorkflowID: c.workflowKey.WorkflowID,
356 > RunID: c.workflowKey.RunID,
357 > ArchetypeID: c.archetypeID,
358 > })
359 > if err != nil {
360 return nil, err
361 }
362
363 > mutableState, err := NewMutableStateFromDB( context.go
364 > shardContext,
365 > shardContext.GetEventsCache(),
366 > c.logger,
367 > namespaceEntry,
368 > response.State,
369 > response.DBRecordVersion,
370 > )
371 > if err != nil {
372 return nil, err
373 }
378 // returned by NewMutableStateFromDB().
379 // Thus causing NPE (e.g. when calling c.Clear()) or other unexpected behavior.
380 > c.MutableState = mutableState context.go
381 }
382
383 > mutableStateArchetypeID := c.MutableState.ChasmTree().ArchetypeID() context.go
384 > if c.archetypeID != chasm.UnspecifiedArchetypeID && c.archetypeID != mutableStateArchetypeID {
385 chasmRegistry := shardContext.ChasmRegistry()
386 contextArchetype, ok := chasmRegistry.ComponentFqnByID(c.archetypeID)
405 )
406 }
407 > c.archetypeID = mutableStateArchetypeID context.go
408 >
409 > flushBeforeReady, err := c.MutableState.StartTransaction(namespaceEntry)
410 > if err != nil {
411 return nil, err
412 }
413 > if !flushBeforeReady { context.go
414 > return c.MutableState, nil
415 > }
416
417 if err = c.UpdateWorkflowExecutionAsActive(
631 ctx context.Context,
632 shardContext historyi.ShardContext,
633 > ) error { context.go
634 >
635 > // We only perform this check on active cluster for the namespace
636 > historySizeForceTerminate, err := c.enforceHistorySizeCheck(ctx, shardContext)
637 > if err != nil {
638 return err
639 }
640 > historyCountForceTerminate := false context.go
641 > if !historySizeForceTerminate {
642 > historyCountForceTerminate, err = c.enforceHistoryCountCheck(ctx, shardContext)
643 > if err != nil {
644 return err
645 }
646 }
647 > msForceTerminate := false context.go
648 > if !historySizeForceTerminate && !historyCountForceTerminate {
649 > msForceTerminate, err = c.enforceMutableStateSizeCheck(ctx, shardContext)
650 > if err != nil {
651 return err
652 }
653 }
654
655 > updateMode, err := c.updateWorkflowMode() context.go
656 > if err != nil {
657 return err
658 }
659
660 > err = c.UpdateWorkflowExecutionWithNew( context.go
661 > ctx,
662 > shardContext,
663 > updateMode,
664 > nil,
665 > nil,
666 > historyi.TransactionPolicyActive,
667 > nil,
668 > )
669 > if err != nil {
670 return err
671 }
674 // Retrying the operation will give appropriate semantics operation should expect in the case of workflow
675 // execution being closed.
676 > if historySizeForceTerminate { context.go
677 return consts.ErrHistorySizeExceedsLimit
678 }
679 > if historyCountForceTerminate { context.go
680 return consts.ErrHistoryCountExceedsLimit
681 }
682 > if msForceTerminate { context.go
683 return consts.ErrMutableStateSizeExceedsLimit
684 }
685
686 > return nil context.go
687 }
688
752 updateWorkflowTransactionPolicy historyi.TransactionPolicy,
753 newWorkflowTransactionPolicy *historyi.TransactionPolicy,
754 > ) (retError error) { context.go
755 >
756 > defer func() {
757 > if retError != nil {
758 c.Clear()
759 }
760 }()
761
762 > if newContext != nil && newMutableState != nil && newWorkflowTransactionPolicy != nil { context.go
763 if *newWorkflowTransactionPolicy == historyi.TransactionPolicyActive {
764 execInfo := newMutableState.GetExecutionInfo()
784 // reconcileTaskCompletionBuffer drops an orphaned buffer for the pagination of
785 // RespondWorkflowTaskCompleted requests.
786 > c.reconcileTaskCompletionBuffer() context.go
787 >
788 > updateWorkflow, updateWorkflowEventsSeq, err := c.MutableState.CloseTransactionAsMutation(
789 > ctx,
790 > updateWorkflowTransactionPolicy,
791 > )
792 > if err != nil {
793 return err
794 }
795
796 > var newWorkflow *persistence.WorkflowSnapshot context.go
797 > var newWorkflowEventsSeq []*persistence.WorkflowEvents
798 > if newContext != nil && newMutableState != nil && newWorkflowTransactionPolicy != nil {
799 defer func() {
800 if retError != nil {
812 }
813
814 > if updateWorkflow == nil { context.go
815 if newWorkflow != nil || len(newWorkflowEventsSeq) != 0 {
816 return serviceerror.NewInternal("current workflow mutation skipped with new workflow snapshot")
819 }
820
821 > if err := c.mergeUpdateWithNewReplicationTasks( context.go
822 > updateWorkflow,
823 > newWorkflow,
824 > ); err != nil {
825 return err
826 }
827
828 > eventsToReapply := updateWorkflowEventsSeq context.go
829 > if len(updateWorkflowEventsSeq) == 0 {
830 > if reapplyCandidateEvents := c.MutableState.GetReapplyCandidateEvents(); len(reapplyCandidateEvents) != 0 { context.go
831 eventsToReapply = []*persistence.WorkflowEvents{
832 {
840 }
841
842 > if err := c.updateWorkflowExecutionEventReapply( context.go
843 > ctx,
844 > shardContext,
845 > updateMode,
846 > eventsToReapply,
847 > // The new run is created by applying events so the history builder in newMutableState contains the events be re-applied.
848 > // So we can use newWorkflowEventsSeq directly to reapply events.
849 > newWorkflowEventsSeq,
850 > ); err != nil {
851 return err
852 }
853
854 > if _, _, err := NewTransaction(shardContext).UpdateWorkflowExecution( context.go
855 > ctx,
856 > updateMode,
857 > c.archetypeID,
858 > c.MutableState.GetCurrentVersion(),
859 > updateWorkflow,
860 > updateWorkflowEventsSeq,
861 > MutableStateFailoverVersion(newMutableState),
862 > newWorkflow,
863 > newWorkflowEventsSeq,
864 > c.MutableState.IsWorkflow(),
865 > ); err != nil {
866 return err
867 }
868
869 > emitStateTransitionCount(c.metricsHandler, shardContext.GetClusterMetadata(), c.MutableState) context.go
870 > emitStateTransitionCount(c.metricsHandler, shardContext.GetClusterMetadata(), newMutableState)
871 >
872 > // finally emit session stats
873 > emitWorkflowHistoryStats(
874 > c.metricsHandler,
875 > c.GetNamespace(shardContext),
876 > c.MutableState.GetExecutionState().State,
877 > int(c.MutableState.GetExecutionInfo().ExecutionStats.HistorySize),
878 > int(c.MutableState.GetNextEventID()-1),
879 > )
880 >
881 > return nil
882 }
883
926 currentWorkflowMutation *persistence.WorkflowMutation,
927 newWorkflowSnapshot *persistence.WorkflowSnapshot,
928 > ) error { context.go
929 >
930 > if newWorkflowSnapshot == nil {
931 > return nil context.go
932 > }
933
934 if currentWorkflowMutation.ExecutionState.Status != enumspb.WORKFLOW_EXECUTION_STATUS_CONTINUED_AS_NEW &&
1043 eventBatch1 []*persistence.WorkflowEvents,
1044 eventBatch2 []*persistence.WorkflowEvents,
1045 > ) error { context.go
1046 > if updateMode == persistence.UpdateWorkflowModeIgnoreCurrent {
1047 if len(eventBatch1) != 0 || len(eventBatch2) != 0 {
1048 return serviceerror.NewInternal("encountered events reapplication without knowing if workflow is current. Events generated for a close workflow?")
1051 }
1052
1053 > if updateMode != persistence.UpdateWorkflowModeBypassCurrent { context.go
1054 > return nil context.go
1055 > }
1056
1057 var eventBatches []*persistence.WorkflowEvents
1079 }
1080
1081 > func (c *ContextImpl) updateWorkflowMode() (persistence.UpdateWorkflowMode, error) { context.go
1082 > if !c.config.EnableUpdateWorkflowModeIgnoreCurrent() {
1083 return persistence.UpdateWorkflowModeUpdateCurrent, nil
1084 }
1085
1086 > if c.MutableState.IsCurrentWorkflowGuaranteed() { context.go
1087 > return persistence.UpdateWorkflowModeUpdateCurrent, nil context.go
1088 > }
1089
1090 guaranteed, err := c.MutableState.IsNonCurrentWorkflowGuaranteed()
1216 }
1217
1218 > func (c *ContextImpl) UpdateRegistry(ctx context.Context) update.Registry { context.go
1219 > if c.updateRegistry != nil && c.updateRegistry.FailoverVersion() != c.MutableState.GetCurrentVersion() {
1220 c.updateRegistry.Clear()
1221 c.updateRegistry = nil
1222 }
1223
1224 > if c.updateRegistry == nil { context.go
1225 > nsName := c.MutableState.GetNamespaceEntry().Name().String()
1226 >
1227 > c.updateRegistry = update.NewRegistry(
1228 > c.MutableState,
1229 > update.WithNamespace(nsName),
1230 > update.WithLogger(c.logger),
1231 > update.WithMetrics(c.metricsHandler),
1232 > update.WithTracerProvider(trace.SpanFromContext(ctx).TracerProvider()),
1233 > update.WithInFlightLimit(
1234 > func() int {
1235 return c.config.WorkflowExecutionMaxInFlightUpdates(nsName)
1236 },
1253 )
1254 }
1255 > return c.updateRegistry context.go
1256 }
1257
1260 ctx context.Context,
1261 shardContext historyi.ShardContext,
1262 > ) (bool, error) { context.go
1263 > // Hard terminate workflow if still running and breached history size limit
1264 > if c.maxHistorySizeExceeded(shardContext) {
1265 if err := c.forceTerminateWorkflow(ctx, shardContext, common.FailureReasonHistorySizeExceedsLimit); err != nil {
1266 return false, err
1269 return true, nil
1270 }
1271 > return false, nil context.go
1272 }
1273
1274 // Returns true if the workflow is running and history size should trigger a forced termination
1275 // Prints a log message if history size is over the error or warn limits
1276 > func (c *ContextImpl) maxHistorySizeExceeded(shardContext historyi.ShardContext) bool { context.go
1277 > namespaceName := c.GetNamespace(shardContext).String()
1278 > historySizeLimitWarn := c.config.HistorySizeLimitWarn(namespaceName)
1279 > historySizeLimitError := c.config.HistorySizeLimitError(namespaceName)
1280 > historySize := int(c.MutableState.GetExecutionInfo().ExecutionStats.HistorySize)
1281 >
1282 > if historySize > historySizeLimitError && c.MutableState.IsWorkflowExecutionRunning() {
1283 c.logger.Warn("history size exceeds error limit.",
1284 tag.WorkflowHistorySize(historySize))
1287 }
1288
1289 > if historySize > historySizeLimitWarn { context.go
1290 c.throttledLogger.Warn("history size exceeds warn limit.",
1291 tag.WorkflowHistorySize(historySize))
1292 }
1293
1294 > return false context.go
1295 }
1296
1298 ctx context.Context,
1299 shardContext historyi.ShardContext,
1300 > ) (bool, error) { context.go
1301 > // Hard terminate workflow if still running and breached history count limit
1302 > if c.maxHistoryCountExceeded(shardContext) {
1303 if err := c.forceTerminateWorkflow(ctx, shardContext, common.FailureReasonHistoryCountExceedsLimit); err != nil {
1304 return false, err
1307 return true, nil
1308 }
1309 > return false, nil context.go
1310 }
1311
1312 // Returns true if the workflow is running and history event count should trigger a forced termination
1313 // Prints a log message if history event count is over the error or warn limits
1314 > func (c *ContextImpl) maxHistoryCountExceeded(shardContext historyi.ShardContext) bool { context.go
1315 > namespaceName := c.GetNamespace(shardContext).String()
1316 > historyCountLimitWarn := c.config.HistoryCountLimitWarn(namespaceName)
1317 > historyCountLimitError := c.config.HistoryCountLimitError(namespaceName)
1318 > historyCount := int(c.MutableState.GetNextEventID() - 1)
1319 >
1320 > if historyCount > historyCountLimitError && c.MutableState.IsWorkflowExecutionRunning() {
1321 c.logger.Warn("history count exceeds error limit.",
1322 tag.WorkflowEventCount(historyCount))
1325 }
1326
1327 > if historyCount > historyCountLimitWarn { context.go
1328 c.throttledLogger.Warn("history count exceeds warn limit.",
1329 tag.WorkflowEventCount(historyCount))
1330 }
1331
1332 > return false context.go
1333 }
1334
1335 // Returns true if execution is forced terminated
1336 // TODO: ideally this check should be after closing mutable state tx, but that would require a large refactor
1337 > func (c *ContextImpl) enforceMutableStateSizeCheck(ctx context.Context, shardContext historyi.ShardContext) (bool, error) { context.go
1338 > if c.maxMutableStateSizeExceeded(shardContext.ChasmRegistry()) {
1339 if err := c.forceTerminateWorkflow(ctx, shardContext, common.FailureReasonMutableStateSizeExceedsLimit); err != nil {
1340 return false, err
1343 return true, nil
1344 }
1345 > return false, nil context.go
1346 }
1347
1348 // Returns true if the workflow is running and mutable state size should trigger a forced termination
1349 // Prints a log message if mutable state size is over the error or warn limits
1350 > func (c *ContextImpl) maxMutableStateSizeExceeded(chasmRegistry *chasm.Registry) bool { context.go
1351 > mutableStateSizeLimitError := c.config.MutableStateSizeLimitError()
1352 > mutableStateSizeLimitWarn := c.config.MutableStateSizeLimitWarn()
1353 >
1354 > mutableStateSize := c.MutableState.GetApproximatePersistedSize()
1355 > metricsHandler := c.metricsHandler
1356 > if archetypeTag, ok := getArchetypeMetricTag(chasmRegistry, c.MutableState.ChasmTree().ArchetypeID()); ok {
1357 > metricsHandler = metricsHandler.WithTags(archetypeTag)
1358 > }
1359 > metrics.PersistedMutableStateSize.With(metricsHandler).Record(int64(mutableStateSize))
1360 >
1361 > if mutableStateSize > mutableStateSizeLimitError {
1362 c.logger.Warn("mutable state size exceeds error limit.",
1363 tag.WorkflowMutableStateSize(mutableStateSize))
1366 }
1367
1368 > if mutableStateSize > mutableStateSizeLimitWarn { context.go
1369 c.throttledLogger.Warn("mutable state size exceeds warn limit.",
1370 tag.WorkflowMutableStateSize(mutableStateSize))
1371 }
1372
1373 > return false context.go
1374 }
1375
1418 // CacheSize estimates the in-memory size of the object for cache limits. For proto objects, it uses proto.Size()
1419 // which returns the serialized size. Note: In-memory size will be slightly larger than the serialized size.
1420 > func (c *ContextImpl) CacheSize() int { context.go
1421 > if !c.config.HistoryCacheLimitSizeBased {
1422 > return 1 context.go
1423 > }
1424 size := len(c.workflowKey.WorkflowID) + len(c.workflowKey.RunID) + len(c.workflowKey.NamespaceID)
1425 if c.MutableState != nil {
1436 clusterMetadata cluster.Metadata,
1437 mutableState historyi.MutableState,
1438 > ) { context.go
1439 > if mutableState == nil {
1440 > return context.go
1441 > }
1442 > namespaceEntry := mutableState.GetNamespaceEntry() context.go
1443 > metrics.StateTransitionCount.With(metricsHandler).Record(
1444 > mutableState.GetExecutionInfo().StateTransitionCount,
1445 > metrics.NamespaceTag(namespaceEntry.Name().String()),
1446 > metrics.NamespaceStateTag(namespaceState(clusterMetadata, new(mutableState.GetCurrentVersion()))),
1447 > )
1448 }
1449
1451 clusterMetadata cluster.Metadata,
1452 mutableStateCurrentVersion *int64,
1453 > ) string { context.go
1454 >
1455 > if mutableStateCurrentVersion == nil {
1456 > return metrics.UnknownNamespaceStateTagValue context.go
1457 > }
1458
1459 // default value, need to special handle
1460 > if *mutableStateCurrentVersion == 0 { context.go
1461 > return metrics.ActiveNamespaceStateTagValue context.go
1462 > }
1463
1464 if clusterMetadata.IsVersionFromSameCluster(
1473 func MutableStateFailoverVersion(
1474 mutableState historyi.MutableState,
1475 > ) *int64 { context.go
1476 > if mutableState == nil {
1477 > return nil context.go
1478 > }
1479 return new(mutableState.GetCurrentVersion())
1480 }
go.temporal.io/server/api/persistence/v1/executions.pb.go 197 covered LOC · 57 ranges

Open complete file

83 }
84
85 > func (x *ShardInfo) GetShardId() int32 { executions.pb.go
86 > if x != nil {
87 > return x.ShardId
88 > }
89 return 0
90 }
91
92 > func (x *ShardInfo) GetRangeId() int64 { executions.pb.go
93 > if x != nil {
94 > return x.RangeId
95 > }
96 return 0
97 }
98
99 > func (x *ShardInfo) GetOwner() string { executions.pb.go
100 > if x != nil {
101 > return x.Owner
102 > }
103 return ""
104 }
393 func (*WorkflowExecutionInfo) ProtoMessage() {}
394
395 > func (x *WorkflowExecutionInfo) ProtoReflect() protoreflect.Message { executions.pb.go
396 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[1]
397 > if x != nil {
398 > ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) executions.pb.go
399 > if ms.LoadMessageInfo() == nil {
400 > ms.StoreMessageInfo(mi)
401 > }
402 > return ms
403 }
404 > return mi.MessageOf(x) executions.pb.go
405 }
406
634 }
635
636 > func (x *WorkflowExecutionInfo) GetWorkflowTaskStamp() int32 { executions.pb.go
637 > if x != nil {
638 > return x.WorkflowTaskStamp
639 > }
640 return 0
641 }
942 }
943
944 > func (x *WorkflowExecutionInfo) GetUpdateInfos() map[string]*UpdateInfo { executions.pb.go
945 > if x != nil {
946 > return x.UpdateInfos
947 > }
948 return nil
949 }
1040 }
1041
1042 > func (x *WorkflowExecutionInfo) GetVersioningInfo() *v12.WorkflowExecutionVersioningInfo { executions.pb.go
1043 > if x != nil {
1044 > return x.VersioningInfo
1045 > }
1046 return nil
1047 }
1075 }
1076
1077 > func (x *WorkflowExecutionInfo) GetWorkerDeploymentName() string { executions.pb.go
1078 > if x != nil {
1079 > return x.WorkerDeploymentName
1080 > }
1081 return ""
1082 }
1142 }
1143
1144 > func (x *WorkflowExecutionInfo) GetTimeSkippingInfo() *TimeSkippingInfo { executions.pb.go
1145 > if x != nil {
1146 > return x.TimeSkippingInfo
1147 > }
1148 return nil
1149 }
1199 func (*TimeSkippingInfo) ProtoMessage() {}
1200
1201 > func (x *TimeSkippingInfo) ProtoReflect() protoreflect.Message { executions.pb.go
1202 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[2]
1203 > if x != nil {
1204 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
1205 if ms.LoadMessageInfo() == nil {
1208 return ms
1209 }
1210 > return mi.MessageOf(x) executions.pb.go
1211 }
1212
1216 }
1217
1218 > func (x *TimeSkippingInfo) GetConfig() *v13.TimeSkippingConfig { executions.pb.go
1219 > if x != nil {
1220 return x.Config
1221 }
1222 > return nil executions.pb.go
1223 }
1224
1225 > func (x *TimeSkippingInfo) GetAccumulatedSkippedDuration() *durationpb.Duration { executions.pb.go
1226 > if x != nil {
1227 return x.AccumulatedSkippedDuration
1228 }
1229 > return nil executions.pb.go
1230 }
1231
1333 func (*LastNotifiedTargetVersion) ProtoMessage() {}
1334
1335 > func (x *LastNotifiedTargetVersion) ProtoReflect() protoreflect.Message { executions.pb.go
1336 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[4]
1337 > if x != nil {
1338 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
1339 if ms.LoadMessageInfo() == nil {
1342 return ms
1343 }
1344 > return mi.MessageOf(x) executions.pb.go
1345 }
1346
1390 func (*ExecutionStats) ProtoMessage() {}
1391
1392 > func (x *ExecutionStats) ProtoReflect() protoreflect.Message { executions.pb.go
1393 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[5]
1394 > if x != nil {
1395 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
1396 if ms.LoadMessageInfo() == nil {
1399 return ms
1400 }
1401 > return mi.MessageOf(x) executions.pb.go
1402 }
1403
1463 func (*WorkflowExecutionState) ProtoMessage() {}
1464
1465 > func (x *WorkflowExecutionState) ProtoReflect() protoreflect.Message { executions.pb.go
1466 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[6]
1467 > if x != nil {
1468 > ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) executions.pb.go
1469 > if ms.LoadMessageInfo() == nil {
1470 > ms.StoreMessageInfo(mi)
1471 > }
1472 > return ms
1473 }
1474 > return mi.MessageOf(x) executions.pb.go
1475 }
1476
1487 }
1488
1489 > func (x *WorkflowExecutionState) GetRunId() string { executions.pb.go
1490 > if x != nil {
1491 > return x.RunId executions.pb.go
1492 > }
1493 return ""
1494 }
1495
1496 > func (x *WorkflowExecutionState) GetState() v1.WorkflowExecutionState { executions.pb.go
1497 > if x != nil {
1498 > return x.State executions.pb.go
1499 > }
1500 return v1.WorkflowExecutionState(0)
1501 }
1502
1503 > func (x *WorkflowExecutionState) GetStatus() v11.WorkflowExecutionStatus { executions.pb.go
1504 > if x != nil {
1505 > return x.Status executions.pb.go
1506 > }
1507 return v11.WorkflowExecutionStatus(0)
1508 }
1557 func (*RequestIDInfo) ProtoMessage() {}
1558
1559 > func (x *RequestIDInfo) ProtoReflect() protoreflect.Message { executions.pb.go
1560 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[7]
1561 > if x != nil {
1562 > ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) executions.pb.go
1563 > if ms.LoadMessageInfo() == nil {
1564 > ms.StoreMessageInfo(mi)
1565 > }
1566 > return ms
1567 }
1568 > return mi.MessageOf(x) executions.pb.go
1569 }
1570
2889 func (*ActivityInfo) ProtoMessage() {}
2890
2891 > func (x *ActivityInfo) ProtoReflect() protoreflect.Message { executions.pb.go
2892 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[17]
2893 > if x != nil {
2894 > ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) executions.pb.go
2895 > if ms.LoadMessageInfo() == nil {
2896 > ms.StoreMessageInfo(mi)
2897 > }
2898 > return ms
2899 }
2900 > return mi.MessageOf(x) executions.pb.go
2901 }
2902
3310 func (*TimerInfo) ProtoMessage() {}
3311
3312 > func (x *TimerInfo) ProtoReflect() protoreflect.Message { executions.pb.go
3313 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[18]
3314 > if x != nil {
3315 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
3316 if ms.LoadMessageInfo() == nil {
3319 return ms
3320 }
3321 > return mi.MessageOf(x) executions.pb.go
3322 }
3323
3403 func (*ChildExecutionInfo) ProtoMessage() {}
3404
3405 > func (x *ChildExecutionInfo) ProtoReflect() protoreflect.Message { executions.pb.go
3406 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[19]
3407 > if x != nil {
3408 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
3409 if ms.LoadMessageInfo() == nil {
3412 return ms
3413 }
3414 > return mi.MessageOf(x) executions.pb.go
3415 }
3416
3543 func (*RequestCancelInfo) ProtoMessage() {}
3544
3545 > func (x *RequestCancelInfo) ProtoReflect() protoreflect.Message { executions.pb.go
3546 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[20]
3547 > if x != nil {
3548 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
3549 if ms.LoadMessageInfo() == nil {
3552 return ms
3553 }
3554 > return mi.MessageOf(x) executions.pb.go
3555 }
3556
3620 func (*SignalInfo) ProtoMessage() {}
3621
3622 > func (x *SignalInfo) ProtoReflect() protoreflect.Message { executions.pb.go
3623 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[21]
3624 > if x != nil {
3625 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
3626 if ms.LoadMessageInfo() == nil {
3629 return ms
3630 }
3631 > return mi.MessageOf(x) executions.pb.go
3632 }
3633
3695 func (*Checksum) ProtoMessage() {}
3696
3697 > func (x *Checksum) ProtoReflect() protoreflect.Message { executions.pb.go
3698 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[22]
3699 > if x != nil {
3700 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
3701 if ms.LoadMessageInfo() == nil {
3704 return ms
3705 }
3706 > return mi.MessageOf(x) executions.pb.go
3707 }
3708
3726 }
3727
3728 > func (x *Checksum) GetValue() []byte { executions.pb.go
3729 > if x != nil {
3730 return x.Value
3731 }
3732 > return nil executions.pb.go
3733 }
3734
4336 func (*ResetChildInfo) ProtoMessage() {}
4337
4338 > func (x *ResetChildInfo) ProtoReflect() protoreflect.Message { executions.pb.go
4339 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[28]
4340 > if x != nil {
4341 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
4342 if ms.LoadMessageInfo() == nil {
4345 return ms
4346 }
4347 > return mi.MessageOf(x) executions.pb.go
4348 }
4349
4387 func (*WorkflowPauseInfo) ProtoMessage() {}
4388
4389 > func (x *WorkflowPauseInfo) ProtoReflect() protoreflect.Message { executions.pb.go
4390 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[29]
4391 > if x != nil {
4392 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
4393 if ms.LoadMessageInfo() == nil {
4396 return ms
4397 }
4398 > return mi.MessageOf(x) executions.pb.go
4399 }
4400
4503 func (*ActivityInfo_UseWorkflowBuildIdInfo) ProtoMessage() {}
4504
4505 > func (x *ActivityInfo_UseWorkflowBuildIdInfo) ProtoReflect() protoreflect.Message { executions.pb.go
4506 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[39]
4507 > if x != nil {
4508 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
4509 if ms.LoadMessageInfo() == nil {
4512 return ms
4513 }
4514 > return mi.MessageOf(x) executions.pb.go
4515 }
4516
4561 func (*ActivityInfo_PauseInfo) ProtoMessage() {}
4562
4563 > func (x *ActivityInfo_PauseInfo) ProtoReflect() protoreflect.Message { executions.pb.go
4564 > mi := &file_temporal_server_api_persistence_v1_executions_proto_msgTypes[40]
4565 > if x != nil {
4566 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
4567 if ms.LoadMessageInfo() == nil {
4570 return ms
4571 }
4572 > return mi.MessageOf(x) executions.pb.go
4573 }
4574
5706 }
5707
5708 > func init() { file_temporal_server_api_persistence_v1_executions_proto_init() } executions.pb.go
5709 > func file_temporal_server_api_persistence_v1_executions_proto_init() {
5710 > if File_temporal_server_api_persistence_v1_executions_proto != nil {
5711 > return
5712 > }
5713 > file_temporal_server_api_persistence_v1_chasm_proto_init()
5714 > file_temporal_server_api_persistence_v1_hsm_proto_init()
5715 > file_temporal_server_api_persistence_v1_queues_proto_init()
5716 > file_temporal_server_api_persistence_v1_update_proto_init()
5717 > file_temporal_server_api_persistence_v1_executions_proto_msgTypes[1].OneofWrappers = []any{
5718 > (*WorkflowExecutionInfo_LastWorkflowTaskFailureCause)(nil),
5719 > (*WorkflowExecutionInfo_LastWorkflowTaskTimedOutType)(nil),
5720 > }
5721 > file_temporal_server_api_persistence_v1_executions_proto_msgTypes[8].OneofWrappers = []any{
5722 > (*TransferTaskInfo_CloseExecutionTaskDetails_)(nil),
5723 > (*TransferTaskInfo_ChasmTaskInfo)(nil),
5724 > }
5725 > file_temporal_server_api_persistence_v1_executions_proto_msgTypes[10].OneofWrappers = []any{
5726 > (*VisibilityTaskInfo_ChasmTaskInfo)(nil),
5727 > }
5728 > file_temporal_server_api_persistence_v1_executions_proto_msgTypes[11].OneofWrappers = []any{
5729 > (*TimerTaskInfo_ChasmTaskInfo)(nil),
5730 > }
5731 > file_temporal_server_api_persistence_v1_executions_proto_msgTypes[13].OneofWrappers = []any{
5732 > (*OutboundTaskInfo_StateMachineInfo)(nil),
5733 > (*OutboundTaskInfo_ChasmTaskInfo)(nil),
5734 > (*OutboundTaskInfo_WorkerCommandsTask)(nil),
5735 > }
5736 > file_temporal_server_api_persistence_v1_executions_proto_msgTypes[17].OneofWrappers = []any{
5737 > (*ActivityInfo_UseWorkflowBuildIdInfo_)(nil),
5738 > (*ActivityInfo_LastIndependentlyAssignedBuildId)(nil),
5739 > }
5740 > file_temporal_server_api_persistence_v1_executions_proto_msgTypes[23].OneofWrappers = []any{
5741 > (*Callback_Nexus_)(nil),
5742 > (*Callback_Hsm)(nil),
5743 > }
5744 > file_temporal_server_api_persistence_v1_executions_proto_msgTypes[40].OneofWrappers = []any{
5745 > (*ActivityInfo_PauseInfo_Manual_)(nil),
5746 > (*ActivityInfo_PauseInfo_RuleId)(nil),
5747 > }
5748 > file_temporal_server_api_persistence_v1_executions_proto_msgTypes[46].OneofWrappers = []any{
5749 > (*CallbackInfo_Trigger_WorkflowClosed)(nil),
5750 > }
5751 > type x struct{}
5752 > out := protoimpl.TypeBuilder{
5753 > File: protoimpl.DescBuilder{
5754 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
5755 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_executions_proto_rawDesc), len(file_temporal_server_api_persistence_v1_executions_proto_rawDesc)),
5756 > NumEnums: 0,
5757 > NumMessages: 47,
5758 > NumExtensions: 0,
5759 > NumServices: 0,
5760 > },
5761 > GoTypes: file_temporal_server_api_persistence_v1_executions_proto_goTypes,
5762 > DependencyIndexes: file_temporal_server_api_persistence_v1_executions_proto_depIdxs,
5763 > MessageInfos: file_temporal_server_api_persistence_v1_executions_proto_msgTypes,
5764 > }.Build()
5765 > File_temporal_server_api_persistence_v1_executions_proto = out.File
5766 > file_temporal_server_api_persistence_v1_executions_proto_goTypes = nil
5767 > file_temporal_server_api_persistence_v1_executions_proto_depIdxs = nil
5768 }
go.temporal.io/server/service/history/workflow/transaction_impl.go 191 covered LOC · 34 ranges

Open complete file

40 func NewTransaction(
41 shardContext historyi.ShardContext,
42 > ) *TransactionImpl { transaction_impl.go
43 > return &TransactionImpl{
44 > shard: shardContext,
45 > logger: shardContext.GetLogger(),
46 > }
47 > }
48
49 func (t *TransactionImpl) CreateWorkflowExecution(
172 newWorkflowEventsSeq []*persistence.WorkflowEvents,
173 isWorkflow bool,
174 > ) (int64, int64, error) { transaction_impl.go
175 >
176 > engine, err := t.shard.GetEngine(ctx)
177 > if err != nil {
178 return 0, 0, err
179 }
180 > resp, err := updateWorkflowExecution( transaction_impl.go
181 > ctx,
182 > t.shard,
183 > currentWorkflowFailoverVersion,
184 > newWorkflowFailoverVersion,
185 > &persistence.UpdateWorkflowExecutionRequest{
186 > ShardID: t.shard.GetShardID(),
187 > // RangeID , this is set by shard context
188 > Mode: updateMode,
189 > ArchetypeID: archetypeID,
190 > UpdateWorkflowMutation: *currentWorkflowMutation,
191 > UpdateWorkflowEvents: currentWorkflowEventsSeq,
192 > NewWorkflowSnapshot: newWorkflowSnapshot,
193 > NewWorkflowEvents: newWorkflowEventsSeq,
194 > },
195 > isWorkflow,
196 > )
197 > if persistence.OperationPossiblySucceeded(err) {
198 > NotifyOnExecutionMutation(engine, currentWorkflowMutation) transaction_impl.go
199 > NotifyOnExecutionSnapshot(engine, newWorkflowSnapshot)
200 > }
201 > if err != nil { transaction_impl.go
202 return 0, 0, err
203 }
204
205 > if err := NotifyNewHistoryMutationEvent(engine, currentWorkflowMutation); err != nil { transaction_impl.go
206 t.logger.Error("unable to notify workflow mutation", tag.Error(err))
207 }
208 > if err := NotifyNewHistorySnapshotEvent(engine, newWorkflowSnapshot); err != nil { transaction_impl.go
209 t.logger.Error("unable to notify workflow creation", tag.Error(err))
210 }
211 > updateHistorySizeDiff := int64(resp.UpdateMutableStateStats.HistoryStatistics.SizeDiff) transaction_impl.go
212 > newHistorySizeDiff := int64(0)
213 > if resp.NewMutableStateStats != nil {
214 newHistorySizeDiff = int64(resp.NewMutableStateStats.HistoryStatistics.SizeDiff)
215 }
216 > return updateHistorySizeDiff, newHistorySizeDiff, nil transaction_impl.go
217 }
218
474 shardContext historyi.ShardContext,
475 request *persistence.GetWorkflowExecutionRequest,
476 > ) (*persistence.GetWorkflowExecutionResponse, error) { transaction_impl.go
477 >
478 > resp, err := shardContext.GetWorkflowExecution(ctx, request)
479 > if err != nil {
480 switch err.(type) {
481 case *serviceerror.NotFound:
495 }
496
497 > if namespaceEntry, err := shardContext.GetNamespaceRegistry().GetNamespaceByID( transaction_impl.go
498 > namespace.ID(resp.State.ExecutionInfo.NamespaceId),
499 > ); err == nil {
500 > emitGetMetrics(
501 > shardContext,
502 > namespaceEntry,
503 > request.ArchetypeID,
504 > &resp.MutableStateStats,
505 > )
506 > }
507 > return resp, nil
508 }
509
515 request *persistence.UpdateWorkflowExecutionRequest,
516 isWorkflow bool,
517 > ) (*persistence.UpdateWorkflowExecutionResponse, error) { transaction_impl.go
518 >
519 > resp, err := shardContext.UpdateWorkflowExecution(ctx, request)
520 > if err != nil {
521 shardContext.GetLogger().Error(
522 "Update workflow execution operation failed.",
530 }
531
532 > if namespaceEntry, err := shardContext.GetNamespaceRegistry().GetNamespaceByID( transaction_impl.go
533 > namespace.ID(request.UpdateWorkflowMutation.ExecutionInfo.NamespaceId),
534 > ); err == nil {
535 > emitMutationMetrics(
536 > shardContext,
537 > namespaceEntry,
538 > request.ArchetypeID,
539 > &resp.UpdateMutableStateStats,
540 > resp.NewMutableStateStats,
541 > )
542 >
543 > emitCompletionMetrics(
544 > shardContext,
545 > namespaceEntry,
546 > mutationToCompletionMetric(
547 > namespaceState(shardContext.GetClusterMetadata(), &updateWorkflowFailoverVersion),
548 > &request.UpdateWorkflowMutation,
549 > request.UpdateWorkflowEvents,
550 > isWorkflow,
551 > ),
552 > snapshotToCompletionMetric(
553 > namespaceState(shardContext.GetClusterMetadata(), newWorkflowFailoverVersion),
554 > request.NewWorkflowSnapshot,
555 > request.NewWorkflowEvents,
556 > isWorkflow,
557 > ),
558 > )
559 > }
560
561 > return resp, nil transaction_impl.go
562 }
563
586 engine historyi.Engine,
587 workflowSnapshot *persistence.WorkflowSnapshot,
589 > if workflowSnapshot == nil {
590 > return transaction_impl.go
591 > }
592 engine.NotifyNewTasks(workflowSnapshot.Tasks)
593 if len(workflowSnapshot.ChasmNodes) > 0 {
603 engine historyi.Engine,
604 workflowMutation *persistence.WorkflowMutation,
606 > if workflowMutation == nil {
607 return
608 }
609 > engine.NotifyNewTasks(workflowMutation.Tasks) transaction_impl.go
610 > if len(workflowMutation.UpsertChasmNodes) > 0 ||
611 > len(workflowMutation.DeleteChasmNodes) > 0 {
612 engine.NotifyChasmExecution(chasm.ExecutionKey{
613 NamespaceID: workflowMutation.ExecutionInfo.NamespaceId,
621 engine historyi.Engine,
622 workflowSnapshot *persistence.WorkflowSnapshot,
623 > ) error { transaction_impl.go
624 >
625 > if workflowSnapshot == nil {
626 > return nil transaction_impl.go
627 > }
628
629 executionInfo := workflowSnapshot.ExecutionInfo
661 engine historyi.Engine,
662 workflowMutation *persistence.WorkflowMutation,
663 > ) error { transaction_impl.go
664 >
665 > if workflowMutation == nil {
666 return nil
667 }
668
669 > executionInfo := workflowMutation.ExecutionInfo transaction_impl.go
670 > executionState := workflowMutation.ExecutionState
671 >
672 > namespaceID := executionInfo.NamespaceId
673 > workflowID := executionInfo.WorkflowId
674 > runID := executionState.RunId
675 > workflowState := executionState.State
676 > workflowStatus := executionState.Status
677 > lastFirstEventID := executionInfo.LastFirstEventId
678 > lastFirstEventTxnID := executionInfo.LastFirstEventTxnId
679 > lastWorkflowTaskStartEventID := executionInfo.LastCompletedWorkflowTaskStartedEventId
680 > nextEventID := workflowMutation.NextEventID
681 >
682 > engine.NotifyNewHistoryEvent(events.NewNotification(
683 > namespaceID,
684 > &commonpb.WorkflowExecution{
685 > WorkflowId: workflowID,
686 > RunId: runID,
687 > },
688 > lastFirstEventID,
689 > lastFirstEventTxnID,
690 > nextEventID,
691 > lastWorkflowTaskStartEventID,
692 > workflowState,
693 > workflowStatus,
694 > executionInfo.VersionHistories,
695 > executionInfo.TransitionHistory,
696 > ))
697 > return nil
698 }
699
703 archetypeID chasm.ArchetypeID,
704 stats ...*persistence.MutableStateStatistics,
706 > metricsHandler := shardContext.GetMetricsHandler()
707 > chasmRegistry := shardContext.ChasmRegistry()
708 > namespaceName := namespace.Name()
709 > for _, stat := range stats {
710 > emitMutableStateStatus(
711 > metricsHandler.WithTags(metrics.OperationTag(metrics.SessionStatsScope), metrics.NamespaceTag(namespaceName.String())),
712 > chasmRegistry,
713 > archetypeID,
714 > stat,
715 > )
716 > }
717 }
718
722 archetypeID chasm.ArchetypeID,
723 stats ...*persistence.MutableStateStatistics,
725 > metricsHandler := shardContext.GetMetricsHandler()
726 > chasmRegistry := shardContext.ChasmRegistry()
727 > namespaceName := namespace.Name()
728 > for _, stat := range stats {
729 > emitMutableStateStatus(
730 > metricsHandler.WithTags(metrics.OperationTag(metrics.ExecutionStatsScope), metrics.NamespaceTag(namespaceName.String())),
731 > chasmRegistry,
732 > archetypeID,
733 > stat,
734 > )
735 > }
736 }
737
738 // wroteEvents reports whether the run wrote any history events in this transaction.
739 > func wroteEvents(eventsSeq []*persistence.WorkflowEvents) bool { transaction_impl.go
740 > for _, batch := range eventsSeq {
741 > if len(batch.Events) > 0 { transaction_impl.go
742 > return true
743 > }
744 }
745 > return false transaction_impl.go
746 }
747
751 eventsSeq []*persistence.WorkflowEvents,
752 isWorkflow bool,
753 > ) completionMetric { transaction_impl.go
754 > if workflowSnapshot == nil {
755 > return completionMetric{shouldRecord: false} transaction_impl.go
756 > }
757
758 return completionMetric{
774 eventsSeq []*persistence.WorkflowEvents,
775 isWorkflow bool,
776 > ) completionMetric { transaction_impl.go
777 > if workflowMutation == nil {
778 return completionMetric{shouldRecord: false}
779 }
780
781 > return completionMetric{ transaction_impl.go
782 > shouldRecord: wroteEvents(eventsSeq),
783 > isWorkflow: isWorkflow,
784 > taskQueue: workflowMutation.ExecutionInfo.TaskQueue,
785 > namespaceState: namespaceState,
786 > workflowTypeName: workflowMutation.ExecutionInfo.WorkflowTypeName,
787 > status: workflowMutation.ExecutionState.Status,
788 > startTime: workflowMutation.ExecutionState.StartTime,
789 > closeTime: workflowMutation.ExecutionInfo.CloseTime,
790 > }
791 }
792
795 namespace *namespace.Namespace,
796 completionMetrics ...completionMetric,
798 > metricsHandler := shardContext.GetMetricsHandler()
799 > namespaceName := namespace.Name()
800 >
801 > for _, completionMetric := range completionMetrics {
802 > if !completionMetric.shouldRecord {
803 > continue transaction_impl.go
804 }
805
806 > emitWorkflowCompletionStats( transaction_impl.go
807 > metricsHandler,
808 > namespaceName,
809 > completionMetric,
810 > shardContext.GetConfig(),
811 > )
812 }
813 }
go.temporal.io/server/service/history/historybuilder/event_store.go 183 covered LOC · 58 ranges

Open complete file

49 }
50
51 > func (b *EventStore) IsDirty() bool { event_store.go
52 > return len(b.memEventsBatches) > 0 ||
53 > len(b.memLatestBatch) > 0 ||
54 > len(b.memBufferBatch) > 0 ||
55 > len(b.scheduledIDToStartedID) > 0
56 > }
57
58 > func (b *EventStore) AllocateEventID() int64 { event_store.go
59 > result := b.nextEventID
60 > b.nextEventID++
61 > return result
62 > }
63
64 > func (b *EventStore) NextEventID() int64 { event_store.go
65 > return b.nextEventID
66 > }
67
68 func (b *EventStore) LastEventVersion() (int64, bool) {
85 func (b *EventStore) add(
86 event *historypb.HistoryEvent,
87 > ) (*historypb.HistoryEvent, int64) { event_store.go
88 > b.assertMutable()
89 > if b.workflowFinished {
90 panic("history builder unable to add new event after workflow finish")
91 }
92 > if b.finishEvent(event.GetEventType()) { event_store.go
93 b.workflowFinished = true
94 }
95
96 > batchID := common.EmptyEventID event_store.go
97 > if b.bufferEvent(event.GetEventType()) {
98 > event.EventId = common.BufferedEventID event_store.go
99 > b.memBufferBatch = append(b.memBufferBatch, event)
100 > } else { event_store.go
101 > event.EventId = b.AllocateEventID() event_store.go
102 > b.appendToLatestBatch(event)
103 > batchID = b.memLatestBatch[0].EventId
104 > }
105 > return event, batchID event_store.go
106 }
107
118 // first if the additional event would push the current batch over
119 // maxEventBatchSizeInBytes. A value of <= 0 disables the check.
120 > func (b *EventStore) appendToLatestBatch(event *historypb.HistoryEvent) { event_store.go
121 > eventSize := proto.Size(event)
122 > if limit := b.maxEventBatchSizeInBytes(); limit > 0 {
123 if len(b.memLatestBatch) > 0 && b.memLatestBatchSize+eventSize > limit {
124 b.FlushAndCreateNewBatch()
128 // limit is disabled. Otherwise, enabling maxEventBatchSizeInBytes mid-flight
129 // would start counting from that point and undercount the current batch.
130 > b.memLatestBatchSize += eventSize event_store.go
131 > b.memLatestBatch = append(b.memLatestBatch, event)
132 }
133
134 > func (b *EventStore) HasBufferEvents() bool { event_store.go
135 > return len(b.dbBufferBatch) > 0 || len(b.memBufferBatch) > 0
136 > }
137
138 // HasAnyBufferedEvent returns true if there is at least one buffered event that matches the provided filter.
144 }
145
146 > func (b *EventStore) NumBufferedEvents() int { event_store.go
147 > return len(b.dbBufferBatch) + len(b.memBufferBatch)
148 > }
149
150 > func (b *EventStore) SizeInBytesOfBufferedEvents() int { event_store.go
151 > size := 0
152 > for _, ev := range b.dbBufferBatch {
153 size += proto.Size(ev)
154 }
155 > for _, ev := range b.memBufferBatch { event_store.go
156 size += proto.Size(ev)
157 }
158 > return size event_store.go
159 }
160
161 > func (b *EventStore) FlushBufferToCurrentBatch() (map[int64]int64, map[string]int64) { event_store.go
162 > if len(b.dbBufferBatch) == 0 && len(b.memBufferBatch) == 0 {
163 > return b.scheduledIDToStartedID, b.requestIDToEventID event_store.go
164 > }
165
166 > b.assertMutable() event_store.go
167 >
168 > if b.workflowFinished {
169 // in case this case happen
170 // 1. request cancel activity
176 }
177
178 > b.dbClearBuffer = b.dbClearBuffer || len(b.dbBufferBatch) > 0 event_store.go
179 > bufferBatch := append(b.dbBufferBatch, b.memBufferBatch...)
180 > b.dbBufferBatch = nil
181 > b.memBufferBatch = nil
182 >
183 > // 0th reorder events in case casandra reorder the buffered events
184 > // TODO eventually remove this ordering
185 > bufferBatch = b.reorderBuffer(bufferBatch)
186 >
187 > // 1st assign event ID
188 > for _, event := range bufferBatch {
189 > event.EventId = b.AllocateEventID()
190 > }
191
192 // 2nd wire event ID, e.g. activity, child workflow
193 > b.wireEventIDs(bufferBatch) event_store.go
194 >
195 > for _, event := range bufferBatch {
196 > b.appendToLatestBatch(event)
197 > }
198
199 > return b.scheduledIDToStartedID, b.requestIDToEventID event_store.go
200 }
201
202 > func (b *EventStore) FlushAndCreateNewBatch() { event_store.go
203 > b.assertNotSealed()
204 > if len(b.memLatestBatch) == 0 {
205 > return event_store.go
206 > }
207
208 > b.memEventsBatches = append(b.memEventsBatches, b.memLatestBatch) event_store.go
209 > b.memLatestBatch = nil
210 > b.memLatestBatchSize = 0
211 }
212
213 func (b *EventStore) Finish(
214 flushBufferEvent bool,
215 > ) (*HistoryMutation, error) { event_store.go
216 > defer func() {
217 > b.state = HistoryBuilderStateSealed
218 > }()
219
220 > if flushBufferEvent { event_store.go
221 > _, _ = b.FlushBufferToCurrentBatch() event_store.go
222 > }
223 > b.FlushAndCreateNewBatch() event_store.go
224 >
225 > dbEventsBatches := b.memEventsBatches
226 > dbClearBuffer := b.dbClearBuffer
227 > dbBufferBatch := b.memBufferBatch
228 > memBufferBatch := b.dbBufferBatch
229 > memBufferBatch = append(memBufferBatch, dbBufferBatch...)
230 > scheduledIDToStartedID := b.scheduledIDToStartedID
231 > requestIDToEventID := b.requestIDToEventID
232 >
233 > b.memEventsBatches = nil
234 > b.memBufferBatch = nil
235 > b.memLatestBatch = nil
236 > b.memLatestBatchSize = 0
237 > b.dbClearBuffer = false
238 > b.dbBufferBatch = nil
239 > b.scheduledIDToStartedID = nil
240 >
241 > if err := b.assignTaskIDs(dbEventsBatches); err != nil {
242 return nil, err
243 }
244
245 > return &HistoryMutation{ event_store.go
246 > DBEventsBatches: dbEventsBatches,
247 > DBClearBuffer: dbClearBuffer,
248 > DBBufferBatch: dbBufferBatch,
249 > MemBufferBatch: memBufferBatch,
250 > ScheduledIDToStartedID: scheduledIDToStartedID,
251 > RequestIDToEventID: requestIDToEventID,
252 > }, nil
253 }
254
255 func (b *EventStore) assignTaskIDs(
256 dbEventsBatches [][]*historypb.HistoryEvent,
257 > ) error { event_store.go
258 > b.assertNotSealed()
259 >
260 > if b.state == HistoryBuilderStateImmutable {
261 return nil
262 }
263
264 > taskIDCount := 0 event_store.go
265 > for i := range dbEventsBatches {
266 > taskIDCount += len(dbEventsBatches[i]) event_store.go
267 > }
268 > taskIDs, err := b.taskIDGenerator(taskIDCount) event_store.go
269 > if err != nil {
270 return err
271 }
272
273 > taskIDPointer := 0 event_store.go
274 > height := len(dbEventsBatches)
275 > for i := range height {
276 > width := len(dbEventsBatches[i]) event_store.go
277 > for j := range width {
278 > dbEventsBatches[i][j].TaskId = taskIDs[taskIDPointer]
279 > taskIDPointer++
280 > }
281 }
282 > return nil event_store.go
283 }
284
285 > func (b *EventStore) assertMutable() { event_store.go
286 > if b.state != HistoryBuilderStateMutable {
287 panic("history builder is mutated while not in mutable state")
288 }
289 }
290
291 > func (b *EventStore) assertNotSealed() { event_store.go
292 > if b.state == HistoryBuilderStateSealed {
293 panic("history builder is in sealed state")
294 }
297 func (b *EventStore) bufferEvent(
298 eventType enumspb.EventType,
299 > ) bool { event_store.go
300 > switch eventType {
301 case // do not buffer for workflow state change
302 enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_STARTED,
306 enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_TERMINATED,
307 enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CONTINUED_AS_NEW,
308 > enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CANCELED: event_store.go
309 > return false
310
311 case // workflow task event should not be buffered
314 enumspb.EVENT_TYPE_WORKFLOW_TASK_COMPLETED,
315 enumspb.EVENT_TYPE_WORKFLOW_TASK_FAILED,
316 > enumspb.EVENT_TYPE_WORKFLOW_TASK_TIMED_OUT: event_store.go
317 > return false
318
319 case // events generated directly from commands should not be buffered
332 enumspb.EVENT_TYPE_WORKFLOW_PROPERTIES_MODIFIED,
333 enumspb.EVENT_TYPE_NEXUS_OPERATION_SCHEDULED,
334 > enumspb.EVENT_TYPE_NEXUS_OPERATION_CANCEL_REQUESTED: event_store.go
335 > // do not buffer event if event is directly generated from a corresponding command
336 > return false
337
338 case // events generated directly from messages should not be buffered
355 return true
356
357 > default: event_store.go
358 > return true
359 }
360 }
362 func (b *EventStore) finishEvent(
363 eventType enumspb.EventType,
364 > ) bool { event_store.go
365 > switch eventType {
366 case
367 enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED,
373 return true
374
375 > default: event_store.go
376 > return false
377 }
378 }
381 func (b *EventStore) wireEventIDs(
382 bufferEvents []*historypb.HistoryEvent,
383 > ) { event_store.go
384 > for _, event := range bufferEvents {
385 > switch event.GetEventType() {
386 > case enumspb.EVENT_TYPE_ACTIVITY_TASK_STARTED: event_store.go
387 > attributes := event.GetActivityTaskStartedEventAttributes()
388 > scheduledEventID := attributes.GetScheduledEventId()
389 > b.scheduledIDToStartedID[scheduledEventID] = event.GetEventId()
390 case enumspb.EVENT_TYPE_ACTIVITY_TASK_COMPLETED:
391 attributes := event.GetActivityTaskCompletedEventAttributes()
403 attributes.StartedEventId = startedEventID
404 }
405 > case enumspb.EVENT_TYPE_ACTIVITY_TASK_CANCELED: event_store.go
406 > attributes := event.GetActivityTaskCanceledEventAttributes()
407 > if startedEventID, ok := b.scheduledIDToStartedID[attributes.GetScheduledEventId()]; ok {
408 attributes.StartedEventId = startedEventID
409 }
461 func (b *EventStore) reorderBuffer(
462 bufferEvents []*historypb.HistoryEvent,
463 > ) []*historypb.HistoryEvent { event_store.go
464 > b.emitOutOfOrderBufferedEvents(bufferEvents)
465 > reorderBuffer := make([]*historypb.HistoryEvent, 0, len(bufferEvents))
466 > reorderEvents := make([]*historypb.HistoryEvent, 0, len(bufferEvents))
467 > for _, event := range bufferEvents {
468 > switch event.GetEventType() {
469 case enumspb.EVENT_TYPE_ACTIVITY_TASK_COMPLETED,
470 enumspb.EVENT_TYPE_ACTIVITY_TASK_FAILED,
481 enumspb.EVENT_TYPE_NEXUS_OPERATION_FAILED,
482 enumspb.EVENT_TYPE_NEXUS_OPERATION_CANCELED,
483 > enumspb.EVENT_TYPE_NEXUS_OPERATION_TIMED_OUT: event_store.go
484 > reorderBuffer = append(reorderBuffer, event)
485 > default: event_store.go
486 > reorderEvents = append(reorderEvents, event)
487 }
488 }
489
490 > return append(reorderEvents, reorderBuffer...) event_store.go
491 }
492
493 > func (b *EventStore) emitOutOfOrderBufferedEvents(bufferedEvents []*historypb.HistoryEvent) { event_store.go
494 >
495 > if b.metricsHandler == nil {
496 return
497 }
498
499 > completedActivities := make(map[int64]enumspb.EventType) event_store.go
500 > completedChildWorkflows := make(map[int64]enumspb.EventType)
501 > completedNexusOperations := make(map[int64]enumspb.EventType)
502 > for _, event := range bufferedEvents {
503 > switch event.GetEventType() {
504 // Activity.
505 > case enumspb.EVENT_TYPE_ACTIVITY_TASK_STARTED: event_store.go
506 > if completeEventType, seenCompleted := completedActivities[event.GetActivityTaskStartedEventAttributes().GetScheduledEventId()]; seenCompleted {
507 metrics.OutOfOrderBufferedEventsCounter.With(b.metricsHandler).Record(1, metrics.OperationTag(completeEventType.String()))
508 }
513 case enumspb.EVENT_TYPE_ACTIVITY_TASK_TIMED_OUT:
514 completedActivities[event.GetActivityTaskTimedOutEventAttributes().GetScheduledEventId()] = event.GetEventType()
515 > case enumspb.EVENT_TYPE_ACTIVITY_TASK_CANCELED: event_store.go
516 > completedActivities[event.GetActivityTaskCanceledEventAttributes().GetScheduledEventId()] = event.GetEventType()
517
518 // Child Workflow.
go.temporal.io/server/service/history/historybuilder/event_factory.go 175 covered LOC · 11 ranges

Open complete file

36 firstRunID string,
37 originalRunID string,
38 > ) *historypb.HistoryEvent { event_factory.go
39 > event := b.createHistoryEvent(enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_STARTED, startTime)
40 > req := request.StartRequest
41 >
42 > // Versioning override might be set on the workflow service request if a user passes it to
43 > // StartWorkflow options, or it might be set on the history service request if a workflow is
44 > // continuing-as-new and inheriting a Pinned override. Use whichever of the two is non-nil.
45 > nonNilVersioningOverride := req.GetVersioningOverride() // From user.
46 > if nonNilVersioningOverride == nil {
47 > nonNilVersioningOverride = request.GetVersioningOverride() // From server during continue-as-new.
48 > }
49
50 > attributes := &historypb.WorkflowExecutionStartedEventAttributes{ event_factory.go
51 > WorkflowType: req.WorkflowType,
52 > TaskQueue: req.TaskQueue,
53 > Header: req.Header,
54 > Input: req.Input,
55 > WorkflowRunTimeout: req.WorkflowRunTimeout,
56 > WorkflowExecutionTimeout: req.WorkflowExecutionTimeout,
57 > WorkflowTaskTimeout: req.WorkflowTaskTimeout,
58 > ContinuedExecutionRunId: prevRunID,
59 > PrevAutoResetPoints: resetPoints,
60 > Identity: req.Identity,
61 > RetryPolicy: req.RetryPolicy,
62 > Attempt: request.GetAttempt(),
63 > WorkflowExecutionExpirationTime: request.WorkflowExecutionExpirationTime,
64 > CronSchedule: req.CronSchedule,
65 > LastCompletionResult: request.LastCompletionResult,
66 > ContinuedFailure: request.GetContinuedFailure(),
67 > Initiator: request.ContinueAsNewInitiator,
68 > FirstWorkflowTaskBackoff: request.FirstWorkflowTaskBackoff,
69 > FirstExecutionRunId: firstRunID,
70 > OriginalExecutionRunId: originalRunID,
71 > // Filter nil values here rather than in the API layer because not all
72 > // creation paths go through the frontend (e.g. continue-as-new, child workflows, replication).
73 > Memo: payload.FilterNilMemo(req.Memo),
74 > SearchAttributes: payload.FilterNilSearchAttributes(req.SearchAttributes),
75 > WorkflowId: req.WorkflowId,
76 > SourceVersionStamp: request.SourceVersionStamp,
77 > CompletionCallbacks: req.CompletionCallbacks,
78 > RootWorkflowExecution: request.RootExecutionInfo.GetExecution(),
79 > InheritedBuildId: request.InheritedBuildId,
80 > VersioningOverride: worker_versioning.ConvertOverrideToV32(nonNilVersioningOverride),
81 > Priority: req.GetPriority(),
82 > InheritedPinnedVersion: request.InheritedPinnedVersion,
83 > // We expect the API handler to unset RequestEagerExecution if eager execution cannot be accepted.
84 > EagerExecutionAccepted: req.GetRequestEagerExecution(),
85 > InheritedAutoUpgradeInfo: request.InheritedAutoUpgradeInfo,
86 > DeclinedTargetVersionUpgrade: request.DeclinedTargetVersionUpgrade,
87 > TimeSkippingConfig: req.GetTimeSkippingConfig(),
88 > TimeSkippingStatePropagation: request.GetTimeSkippingStatePropagation(),
89 > }
90 >
91 > parentInfo := request.ParentExecutionInfo
92 > if parentInfo != nil {
93 attributes.ParentWorkflowNamespaceId = parentInfo.NamespaceId
94 attributes.ParentWorkflowNamespace = parentInfo.Namespace
98 }
99
100 > event.Attributes = &historypb.HistoryEvent_WorkflowExecutionStartedEventAttributes{ event_factory.go
101 > WorkflowExecutionStartedEventAttributes: attributes,
102 > }
103 > return event
104 }
105
109 attempt int32,
110 scheduleTime time.Time,
111 > ) *historypb.HistoryEvent { event_factory.go
112 > event := b.createHistoryEvent(enumspb.EVENT_TYPE_WORKFLOW_TASK_SCHEDULED, scheduleTime)
113 > event.Attributes = &historypb.HistoryEvent_WorkflowTaskScheduledEventAttributes{
114 > WorkflowTaskScheduledEventAttributes: &historypb.WorkflowTaskScheduledEventAttributes{
115 > TaskQueue: taskQueue,
116 > StartToCloseTimeout: startToCloseTimeout,
117 > Attempt: attempt,
118 > },
119 > }
120 >
121 > return event
122 > }
123
124 func (b *EventFactory) CreateWorkflowTaskStartedEvent(
133 suggestContinueAsNewReasons []enumspb.SuggestContinueAsNewReason,
134 targetWorkerDeploymentVersionChanged bool,
135 > ) *historypb.HistoryEvent { event_factory.go
136 > event := b.createHistoryEvent(enumspb.EVENT_TYPE_WORKFLOW_TASK_STARTED, startTime)
137 > event.Attributes = &historypb.HistoryEvent_WorkflowTaskStartedEventAttributes{
138 > WorkflowTaskStartedEventAttributes: &historypb.WorkflowTaskStartedEventAttributes{
139 > ScheduledEventId: scheduledEventID,
140 > Identity: identity,
141 > RequestId: requestID,
142 > SuggestContinueAsNew: suggestContinueAsNew,
143 > SuggestContinueAsNewReasons: suggestContinueAsNewReasons,
144 > HistorySizeBytes: historySizeBytes,
145 > WorkerVersion: versioningStamp,
146 > BuildIdRedirectCounter: buildIdRedirectCounter,
147 >
148 > TargetWorkerDeploymentVersionChanged: targetWorkerDeploymentVersionChanged,
149 > },
150 > }
151 > return event
152 > }
153
154 func (b *EventFactory) CreateWorkflowTaskCompletedEvent(
163 deployment *deploymentpb.Deployment,
164 behavior enumspb.VersioningBehavior,
165 > ) *historypb.HistoryEvent { event_factory.go
166 > event := b.createHistoryEvent(enumspb.EVENT_TYPE_WORKFLOW_TASK_COMPLETED, b.timeSource.Now())
167 > event.Attributes = &historypb.HistoryEvent_WorkflowTaskCompletedEventAttributes{
168 > WorkflowTaskCompletedEventAttributes: &historypb.WorkflowTaskCompletedEventAttributes{
169 > ScheduledEventId: scheduledEventID,
170 > StartedEventId: startedEventID,
171 > Identity: identity,
172 > BinaryChecksum: checksum,
173 > WorkerVersion: workerVersionStamp,
174 > SdkMetadata: sdkMetadata,
175 > MeteringMetadata: meteringMetadata,
176 > WorkerDeploymentName: deploymentName,
177 > DeploymentVersion: worker_versioning.ExternalWorkerDeploymentVersionFromDeployment(deployment),
178 > VersioningBehavior: behavior,
179 > },
180 > }
181 >
182 > return event
183 > }
184
185 func (b *EventFactory) CreateWorkflowTaskTimedOutEvent(
231 workflowTaskCompletedEventID int64,
232 command *commandpb.ScheduleActivityTaskCommandAttributes,
233 > ) *historypb.HistoryEvent { event_factory.go
234 > event := b.createHistoryEvent(enumspb.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED, b.timeSource.Now())
235 > event.Attributes = &historypb.HistoryEvent_ActivityTaskScheduledEventAttributes{
236 > ActivityTaskScheduledEventAttributes: &historypb.ActivityTaskScheduledEventAttributes{
237 > WorkflowTaskCompletedEventId: workflowTaskCompletedEventID,
238 > ActivityId: command.ActivityId,
239 > ActivityType: command.ActivityType,
240 > TaskQueue: command.TaskQueue,
241 > Header: command.Header,
242 > Input: command.Input,
243 > ScheduleToCloseTimeout: command.ScheduleToCloseTimeout,
244 > ScheduleToStartTimeout: command.ScheduleToStartTimeout,
245 > StartToCloseTimeout: command.StartToCloseTimeout,
246 > HeartbeatTimeout: command.HeartbeatTimeout,
247 > RetryPolicy: command.RetryPolicy,
248 > UseWorkflowBuildId: command.UseWorkflowBuildId,
249 > Priority: command.Priority,
250 > },
251 > }
252 > return event
253 > }
254
255 func (b *EventFactory) CreateActivityTaskStartedEvent(
261 versioningStamp *commonpb.WorkerVersionStamp,
262 redirectCounter int64,
263 > ) *historypb.HistoryEvent { event_factory.go
264 > event := b.createHistoryEvent(enumspb.EVENT_TYPE_ACTIVITY_TASK_STARTED, b.timeSource.Now())
265 > event.Attributes = &historypb.HistoryEvent_ActivityTaskStartedEventAttributes{
266 > ActivityTaskStartedEventAttributes: &historypb.ActivityTaskStartedEventAttributes{
267 > ScheduledEventId: scheduledEventID,
268 > Attempt: attempt,
269 > Identity: identity,
270 > RequestId: requestID,
271 > LastFailure: lastFailure,
272 > WorkerVersion: versioningStamp,
273 > BuildIdRedirectCounter: redirectCounter,
274 > },
275 > }
276 > return event
277 > }
278
279 func (b *EventFactory) CreateActivityTaskCompletedEvent(
535 workflowTaskCompletedEventID int64,
536 scheduledEventID int64,
537 > ) *historypb.HistoryEvent { event_factory.go
538 > event := b.createHistoryEvent(enumspb.EVENT_TYPE_ACTIVITY_TASK_CANCEL_REQUESTED, b.timeSource.Now())
539 > event.Attributes = &historypb.HistoryEvent_ActivityTaskCancelRequestedEventAttributes{
540 > ActivityTaskCancelRequestedEventAttributes: &historypb.ActivityTaskCancelRequestedEventAttributes{
541 > WorkflowTaskCompletedEventId: workflowTaskCompletedEventID,
542 > ScheduledEventId: scheduledEventID,
543 > },
544 > }
545 > return event
546 > }
547
548 func (b *EventFactory) CreateActivityTaskCanceledEvent(
552 details *commonpb.Payloads,
553 identity string,
554 > ) *historypb.HistoryEvent { event_factory.go
555 > event := b.createHistoryEvent(enumspb.EVENT_TYPE_ACTIVITY_TASK_CANCELED, b.timeSource.Now())
556 > event.Attributes = &historypb.HistoryEvent_ActivityTaskCanceledEventAttributes{
557 > ActivityTaskCanceledEventAttributes: &historypb.ActivityTaskCanceledEventAttributes{
558 > ScheduledEventId: scheduledEventID,
559 > StartedEventId: startedEventID,
560 > LatestCancelRequestedEventId: latestCancelRequestedEventID,
561 > Details: details,
562 > Identity: identity,
563 > },
564 > }
565 > return event
566 > }
567
568 func (b *EventFactory) CreateTimerCanceledEvent(
1086 eventType enumspb.EventType,
1087 time time.Time,
1088 > ) *historypb.HistoryEvent { event_factory.go
1089 > historyEvent := &historypb.HistoryEvent{}
1090 > historyEvent.EventTime = timestamppb.New(time.UTC())
1091 > historyEvent.EventType = eventType
1092 > historyEvent.Version = b.version
1093 > historyEvent.TaskId = common.EmptyEventTaskID
1094 >
1095 > return historyEvent
1096 > }
1097
1098 // CreateWorkflowExecutionTimeSkippingTransitionedEvent creates a workflow execution time skipping transitioned event.
go.temporal.io/server/common/metrics/tally_metrics_handler.go 153 covered LOC · 44 ranges

Open complete file

37 }
38
39 > func newSharedScopeCache(maxSize int) *sharedScopeCache { tally_metrics_handler.go
40 > return &sharedScopeCache{
41 > maxSize: maxSize,
42 > scopes: make(map[string]tally.Scope),
43 > handlers: make(map[string]*tallyMetricsHandler),
44 > }
45 > }
46
47 > func (c *sharedScopeCache) loadOrStoreScope(key string, create func() tally.Scope) tally.Scope { tally_metrics_handler.go
48 > c.mu.RLock()
49 > if s, ok := c.scopes[key]; ok {
50 > c.mu.RUnlock() tally_metrics_handler.go
51 > return s
52 > }
53 > c.mu.RUnlock() tally_metrics_handler.go
54 >
55 > s := create()
56 >
57 > c.mu.Lock()
58 > defer c.mu.Unlock()
59 > // Double-check: another goroutine may have inserted while we were creating.
60 > if existing, ok := c.scopes[key]; ok {
61 return existing
62 }
63 > if len(c.scopes) >= c.maxSize { tally_metrics_handler.go
64 clear(c.scopes)
65 }
66 > c.scopes[key] = s tally_metrics_handler.go
67 > return s
68 }
69
70 > func (c *sharedScopeCache) loadOrStoreHandler(key string, create func() *tallyMetricsHandler) *tallyMetricsHandler { tally_metrics_handler.go
71 > c.mu.RLock()
72 > if h, ok := c.handlers[key]; ok {
73 > c.mu.RUnlock() tally_metrics_handler.go
74 > return h
75 > }
76 > c.mu.RUnlock() tally_metrics_handler.go
77 >
78 > h := create()
79 >
80 > c.mu.Lock()
81 > defer c.mu.Unlock()
82 > // Double-check: another goroutine may have inserted while we were creating.
83 > if existing, ok := c.handlers[key]; ok {
84 return existing
85 }
86 > if len(c.handlers) >= c.maxSize { tally_metrics_handler.go
87 clear(c.handlers)
88 }
89 > c.handlers[key] = h tally_metrics_handler.go
90 > return h
91 }
92
109 var _ Handler = (*tallyMetricsHandler)(nil)
110
111 > func NewTallyMetricsHandler(cfg ClientConfig, scope tally.Scope) *tallyMetricsHandler { tally_metrics_handler.go
112 > perUnitBuckets := make(map[MetricUnit]tally.Buckets)
113 >
114 > for unit, boundariesList := range cfg.PerUnitHistogramBoundaries {
115 perUnitBuckets[MetricUnit(unit)] = tally.ValueBuckets(boundariesList)
116 }
117
118 > maxSize := cfg.TagsCacheMaxSize tally_metrics_handler.go
119 > if maxSize <= 0 {
120 > maxSize = defaultTagsCacheMaxSize tally_metrics_handler.go
121 > }
122
123 > return &tallyMetricsHandler{ tally_metrics_handler.go
124 > scope: scope,
125 > perUnitBuckets: perUnitBuckets,
126 > excludeTags: configExcludeTags(cfg),
127 > cache: newSharedScopeCache(maxSize),
128 > scopeKey: "",
129 > }
130 }
131
132 // tagsCacheKey builds a compact string key from a tag slice for use as a
133 // map lookup key.
134 > func tagsCacheKey(tags []Tag) string { tally_metrics_handler.go
135 > size := 0
136 > for i := range tags {
137 > size += len(tags[i].Key) + len(tags[i].Value) + 2*binary.MaxVarintLen64
138 > }
139 > var sb strings.Builder
140 > sb.Grow(size)
141 > for _, t := range tags {
142 > appendCacheKeyPart(&sb, t.Key)
143 > appendCacheKeyPart(&sb, t.Value)
144 > }
145 > return sb.String()
146 }
147
148 > func appendCacheKeyPart(sb *strings.Builder, value string) { tally_metrics_handler.go
149 > var lenBuf [binary.MaxVarintLen64]byte
150 > n := binary.PutUvarint(lenBuf[:], uint64(len(value)))
151 > _, _ = sb.Write(lenBuf[:n])
152 > sb.WriteString(value)
153 > }
154
155 // WithTags creates a new MetricProvider with provided []Tag
156 // Tags are merged with registered Tags from the source MetricsHandler.
157 // Handlers are cached by tag combination so repeated calls avoid allocations.
158 > func (tmh *tallyMetricsHandler) WithTags(tags ...Tag) Handler { tally_metrics_handler.go
159 > if len(tags) == 0 {
160 return tmh
161 }
162 > normalizedKey := tagsCacheKey(normalizeTagsForCaching(tags, tmh.excludeTags)) tally_metrics_handler.go
163 > key := tmh.scopeKey + normalizedKey
164 > return tmh.cache.loadOrStoreHandler(key, func() *tallyMetricsHandler {
165 > return &tallyMetricsHandler{
166 > scope: tmh.scope.Tagged(tagsToMap(tags, tmh.excludeTags)),
167 > perUnitBuckets: tmh.perUnitBuckets,
168 > excludeTags: tmh.excludeTags,
169 > cache: tmh.cache,
170 > scopeKey: key,
171 > }
172 > })
173 }
174
178 // excludeTags before cache key computation so that different raw values which
179 // map to the same excluded placeholder share a single cache entry.
180 > func (tmh *tallyMetricsHandler) cachedTaggedScope(tags []Tag) tally.Scope { tally_metrics_handler.go
181 > if len(tags) == 0 {
182 > return tmh.scope tally_metrics_handler.go
183 > }
184 > key := tmh.scopeKey + tagsCacheKey(normalizeTagsForCaching(tags, tmh.excludeTags)) tally_metrics_handler.go
185 > return tmh.cache.loadOrStoreScope(key, func() tally.Scope {
186 > return tmh.scope.Tagged(tagsToMap(tags, tmh.excludeTags))
187 > })
188 }
189
190 // normalizeTag applies excludeTags substitution to a single tag.
191 // Returns the (possibly modified) tag and whether it was normalized.
192 > func normalizeTag(t Tag, excl excludeTags) (Tag, bool) { tally_metrics_handler.go
193 > if vals, ok := excl[t.Key]; ok {
194 if _, ok := vals[t.Value]; !ok {
195 return Tag{Key: t.Key, Value: tagExcludedValue}, true
196 }
197 }
198 > return t, false tally_metrics_handler.go
199 }
200
202 // canonical tag values for cache key computation. Returns the original slice
203 // unchanged if no tags need normalization (zero-alloc fast path).
204 > func normalizeTagsForCaching(tags []Tag, excl excludeTags) []Tag { tally_metrics_handler.go
205 > if len(excl) == 0 {
206 > return tags tally_metrics_handler.go
207 > }
208 var normalized []Tag
209 for i, t := range tags {
223
224 // Counter obtains a counter for the given name.
225 > func (tmh *tallyMetricsHandler) Counter(counter string) CounterIface { tally_metrics_handler.go
226 > if v, ok := tmh.counters.Load(counter); ok {
227 > return v.(CounterIface) //nolint:revive // type-safe: only CounterIface is stored tally_metrics_handler.go
228 > }
229 > c := CounterFunc(func(i int64, t ...Tag) { tally_metrics_handler.go
230 > tmh.cachedTaggedScope(t).Counter(counter).Inc(i)
231 > })
232 > actual, _ := tmh.counters.LoadOrStore(counter, c)
233 > return actual.(CounterIface) //nolint:revive // type-safe: only CounterIface is stored
234 }
235
236 // Gauge obtains a gauge for the given name.
237 > func (tmh *tallyMetricsHandler) Gauge(gauge string) GaugeIface { tally_metrics_handler.go
238 > if v, ok := tmh.gauges.Load(gauge); ok {
239 > return v.(GaugeIface) //nolint:revive // type-safe: only GaugeIface is stored tally_metrics_handler.go
240 > }
241 > g := GaugeFunc(func(f float64, t ...Tag) { tally_metrics_handler.go
242 > tmh.cachedTaggedScope(t).Gauge(gauge).Update(f)
243 > })
244 > actual, _ := tmh.gauges.LoadOrStore(gauge, g)
245 > return actual.(GaugeIface) //nolint:revive // type-safe: only GaugeIface is stored
246 }
247
248 // Timer obtains a timer for the given name.
249 > func (tmh *tallyMetricsHandler) Timer(timer string) TimerIface { tally_metrics_handler.go
250 > if v, ok := tmh.timers.Load(timer); ok {
251 > return v.(TimerIface) //nolint:revive // type-safe: only TimerIface is stored tally_metrics_handler.go
252 > }
253 > ti := TimerFunc(func(d time.Duration, t ...Tag) { tally_metrics_handler.go
254 > tmh.cachedTaggedScope(t).Timer(timer).Record(d)
255 > })
256 > actual, _ := tmh.timers.LoadOrStore(timer, ti)
257 > return actual.(TimerIface) //nolint:revive // type-safe: only TimerIface is stored
258 }
259
260 // Histogram obtains a histogram for the given name.
261 > func (tmh *tallyMetricsHandler) Histogram(histogram string, unit MetricUnit) HistogramIface { tally_metrics_handler.go
262 > key := histogramCacheKey{name: histogram, unit: unit}
263 > if v, ok := tmh.histograms.Load(key); ok {
264 > return v.(HistogramIface) //nolint:revive // type-safe: only HistogramIface is stored tally_metrics_handler.go
265 > }
266 > h := HistogramFunc(func(i int64, t ...Tag) { tally_metrics_handler.go
267 > tmh.cachedTaggedScope(t).Histogram(histogram, tmh.perUnitBuckets[unit]).RecordValue(float64(i)) tally_metrics_handler.go
268 > })
269 > actual, _ := tmh.histograms.LoadOrStore(key, h) tally_metrics_handler.go
270 > return actual.(HistogramIface) //nolint:revive // type-safe: only HistogramIface is stored
271 }
272
273 func (*tallyMetricsHandler) Stop(log.Logger) {}
274
275 > func (*tallyMetricsHandler) Close() error { tally_metrics_handler.go
276 > return nil
277 > }
278
279 > func (tmh *tallyMetricsHandler) StartBatch(_ string) BatchHandler { tally_metrics_handler.go
280 > return tmh
281 > }
282
283 > func tagsToMap(t1 []Tag, e excludeTags) map[string]string { tally_metrics_handler.go
284 > if len(t1) == 0 {
285 return nil
286 }
287
288 > m := make(map[string]string, len(t1)) tally_metrics_handler.go
289 > for i := range t1 {
290 > nt, _ := normalizeTag(t1[i], e)
291 > m[nt.Key] = nt.Value
292 > }
293 > return m
294 }
go.temporal.io/server/service/history/workflow/timer_sequence.go 152 covered LOC · 47 ranges

Open complete file

61 func NewTimerSequence(
62 mutableState historyi.MutableState,
63 > ) *timerSequenceImpl { timer_sequence.go
64 > return &timerSequenceImpl{
65 > mutableState: mutableState,
66 > }
67 > }
68
69 > func (t *timerSequenceImpl) CreateNextUserTimer() (bool, error) { timer_sequence.go
70 >
71 > sequenceIDs := t.LoadAndSortUserTimers()
72 > if len(sequenceIDs) == 0 {
73 > return false, nil timer_sequence.go
74 > }
75
76 firstTimerTask := sequenceIDs[0]
107 }
108
109 > func (t *timerSequenceImpl) CreateNextActivityTimer() (bool, error) { timer_sequence.go
110 >
111 > sequenceIDs := t.LoadAndSortActivityTimers()
112 > if len(sequenceIDs) == 0 {
113 > return false, nil timer_sequence.go
114 > }
115
116 > firstTimerTask := sequenceIDs[0] timer_sequence.go
117 >
118 > // activity timer after workflow timeout, skip
119 > execInfo := t.mutableState.GetExecutionInfo()
120 > workflowRunExpirationTime := timestamp.TimeValue(execInfo.WorkflowRunExpirationTime)
121 > if !workflowRunExpirationTime.IsZero() && firstTimerTask.Timestamp.After(workflowRunExpirationTime) {
122 return false, nil
123 }
124
125 // timer has already been created
126 > if firstTimerTask.TimerCreated { timer_sequence.go
127 > return false, nil timer_sequence.go
128 > }
129
130 > activityInfo, ok := t.mutableState.GetActivityInfo(firstTimerTask.EventID) timer_sequence.go
131 > if !ok {
132 return false, serviceerror.NewInternalf("unable to load activity info %v", firstTimerTask.EventID)
133 }
134 // mark timer task mask as indication that timer task is generated
135 > activityInfo.TimerTaskStatus |= timerTypeToTimerMask(firstTimerTask.TimerType) timer_sequence.go
136 > var err error
137 > var timerTaskStamp *time.Time
138 > if firstTimerTask.TimerType == enumspb.TIMEOUT_TYPE_HEARTBEAT {
139 timerTaskStamp = &firstTimerTask.Timestamp
140 }
141 > err = t.mutableState.UpdateActivityTaskStatusWithTimerHeartbeat(activityInfo.ScheduledEventId, activityInfo.TimerTaskStatus, timerTaskStamp) timer_sequence.go
142 >
143 > if err != nil {
144 return false, err
145 }
146 > t.mutableState.AddTasks(&tasks.ActivityTimeoutTask{ timer_sequence.go
147 > // TaskID is set by shard
148 > WorkflowKey: t.mutableState.GetWorkflowKey(),
149 > VisibilityTimestamp: firstTimerTask.Timestamp,
150 > TimeoutType: firstTimerTask.TimerType,
151 > EventID: firstTimerTask.EventID,
152 > Attempt: firstTimerTask.Attempt,
153 > Stamp: activityInfo.Stamp,
154 > })
155 > return true, nil
156 }
157
158 > func (t *timerSequenceImpl) LoadAndSortUserTimers() []TimerSequenceID { timer_sequence.go
159 >
160 > pendingTimers := t.mutableState.GetPendingTimerInfos()
161 > timers := make(TimerSequenceIDs, 0, len(pendingTimers))
162 >
163 > for _, timerInfo := range pendingTimers {
164
165 if sequenceID := t.getUserTimerTimeout(
170 }
171
172 > sort.Sort(timers) timer_sequence.go
173 > return timers
174 }
175
176 > func (t *timerSequenceImpl) LoadAndSortActivityTimers() []TimerSequenceID { timer_sequence.go
177 > // there can be 4 timer per activity
178 > // see TimerType
179 > pendingActivities := t.mutableState.GetPendingActivityInfos()
180 > activityTimers := make(TimerSequenceIDs, 0, len(pendingActivities)*4)
181 >
182 > for _, activityInfo := range pendingActivities {
183 > // skip activities that are paused timer_sequence.go
184 > if activityInfo.Paused {
185 continue
186 }
187 > if sequenceID := t.getActivityScheduleToCloseTimeout( timer_sequence.go
188 > activityInfo,
189 > ); sequenceID != nil {
190 > activityTimers = append(activityTimers, *sequenceID) timer_sequence.go
191 > }
192
193 > if sequenceID := t.getActivityScheduleToStartTimeout( timer_sequence.go
194 > activityInfo,
195 > ); sequenceID != nil {
196 activityTimers = append(activityTimers, *sequenceID)
197 }
198
199 > if sequenceID := t.getActivityStartToCloseTimeout( timer_sequence.go
200 > activityInfo,
201 > ); sequenceID != nil {
202 > activityTimers = append(activityTimers, *sequenceID) timer_sequence.go
203 > }
204
205 > if sequenceID := t.getActivityHeartbeatTimeout( timer_sequence.go
206 > activityInfo,
207 > ); sequenceID != nil {
208 activityTimers = append(activityTimers, *sequenceID)
209 }
210 }
211
212 > sort.Sort(activityTimers) timer_sequence.go
213 > return activityTimers
214 }
215
231 func (t *timerSequenceImpl) getActivityScheduleToStartTimeout(
232 activityInfo *persistencespb.ActivityInfo,
233 > ) *TimerSequenceID { timer_sequence.go
234 >
235 > // activity is not scheduled yet, probably due to retry & backoff
236 > if activityInfo.ScheduledEventId == common.EmptyEventID {
237 return nil
238 }
239
240 // activity is already started
241 > if activityInfo.StartedEventId != common.EmptyEventID { timer_sequence.go
242 > return nil timer_sequence.go
243 > }
244
245 scheduleToStartDuration := timestamp.DurationValue(activityInfo.ScheduleToStartTimeout)
261 func (t *timerSequenceImpl) getActivityScheduleToCloseTimeout(
262 activityInfo *persistencespb.ActivityInfo,
263 > ) *TimerSequenceID { timer_sequence.go
264 >
265 > // activity is not scheduled yet, probably due to retry & backoff
266 > if activityInfo.ScheduledEventId == common.EmptyEventID {
267 return nil
268 }
269
270 > scheduleToCloseDuration := timestamp.DurationValue(activityInfo.ScheduleToCloseTimeout) timer_sequence.go
271 > if scheduleToCloseDuration == 0 {
272 return nil
273 }
274
275 > var timeoutTime time.Time timer_sequence.go
276 > // for backward compatibility. FirstScheduledTime can be null if mutable state was
277 > // restored from the version before this field was introduce
278 > if activityInfo.FirstScheduledTime != nil {
279 > timeoutTime = timestamp.TimeValue(activityInfo.FirstScheduledTime).Add(scheduleToCloseDuration) timer_sequence.go
280 > } else { timer_sequence.go
281 timeoutTime = timestamp.TimeValue(activityInfo.ScheduledTime).Add(scheduleToCloseDuration)
282 }
283
284 > return &TimerSequenceID{ timer_sequence.go
285 > EventID: activityInfo.ScheduledEventId,
286 > Timestamp: timeoutTime,
287 > TimerType: enumspb.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE,
288 > TimerCreated: (activityInfo.TimerTaskStatus & TimerTaskStatusCreatedScheduleToClose) > 0,
289 > Attempt: activityInfo.Attempt,
290 > }
291 }
292
293 func (t *timerSequenceImpl) getActivityStartToCloseTimeout(
294 activityInfo *persistencespb.ActivityInfo,
295 > ) *TimerSequenceID { timer_sequence.go
296 >
297 > // activity is not scheduled yet, probably due to retry & backoff
298 > if activityInfo.ScheduledEventId == common.EmptyEventID {
299 return nil
300 }
301
302 // activity is not started yet
303 > if activityInfo.StartedEventId == common.EmptyEventID { timer_sequence.go
304 return nil
305 }
306
307 > startToCloseDuration := timestamp.DurationValue(activityInfo.StartToCloseTimeout) timer_sequence.go
308 > if startToCloseDuration == 0 {
309 return nil
310 }
311
312 > timeoutTime := timestamp.TimeValue(activityInfo.StartedTime).Add(startToCloseDuration) timer_sequence.go
313 >
314 > return &TimerSequenceID{
315 > EventID: activityInfo.ScheduledEventId,
316 > Timestamp: timeoutTime,
317 > TimerType: enumspb.TIMEOUT_TYPE_START_TO_CLOSE,
318 > TimerCreated: (activityInfo.TimerTaskStatus & TimerTaskStatusCreatedStartToClose) > 0,
319 > Attempt: activityInfo.Attempt,
320 > }
321 }
322
323 func (t *timerSequenceImpl) getActivityHeartbeatTimeout(
324 activityInfo *persistencespb.ActivityInfo,
325 > ) *TimerSequenceID { timer_sequence.go
326 >
327 > // activity is not scheduled yet, probably due to retry & backoff
328 > if activityInfo.ScheduledEventId == common.EmptyEventID {
329 return nil
330 }
331
332 // activity is not started yet
333 > if activityInfo.StartedEventId == common.EmptyEventID { timer_sequence.go
334 return nil
335 }
336
337 // not heartbeat timeout configured
338 > heartbeatDuration := timestamp.DurationValue(activityInfo.HeartbeatTimeout) timer_sequence.go
339 > if heartbeatDuration == 0 {
340 > return nil timer_sequence.go
341 > }
342
343 // use the latest time as last heartbeat time
364 func timerTypeToTimerMask(
365 timerType enumspb.TimeoutType,
366 > ) int32 { timer_sequence.go
367 >
368 > switch timerType {
369 > case enumspb.TIMEOUT_TYPE_START_TO_CLOSE: timer_sequence.go
370 > return TimerTaskStatusCreatedStartToClose
371 case enumspb.TIMEOUT_TYPE_SCHEDULE_TO_START:
372 return TimerTaskStatusCreatedScheduleToStart
381
382 // Len implements sort.Interface
383 > func (s TimerSequenceIDs) Len() int { timer_sequence.go
384 > return len(s)
385 > }
386
387 // Swap implements sort.Interface.
389 this int,
390 that int,
391 > ) { timer_sequence.go
392 > s[this], s[that] = s[that], s[this]
393 > }
394
395 // Less implements sort.Interface
397 this int,
398 that int,
399 > ) bool { timer_sequence.go
400 >
401 > thisSequenceID := s[this]
402 > thatSequenceID := s[that]
403 >
404 > // order: timeout time, event ID, timeout type
405 >
406 > if thisSequenceID.Timestamp.Before(thatSequenceID.Timestamp) {
407 > return true timer_sequence.go
408 > } else if thisSequenceID.Timestamp.After(thatSequenceID.Timestamp) { timer_sequence.go
409 return false
410 }
go.temporal.io/server/common/cache/lru.go 135 covered LOC · 40 ranges

Open complete file

126 }
127
128 > func (entry *entryImpl) Size() int { lru.go
129 > return entry.size
130 > }
131
132 func (entry *entryImpl) CreateTime() time.Time {
135
136 // New creates a new cache with the given options
137 > func New(maxSize int, opts *Options) StoppableCache { lru.go
138 > return NewWithMetrics(maxSize, opts, metrics.NoopMetricsHandler)
139 > }
140
141 // NewWithMetrics creates a new cache that will emit capacity and ttl metrics.
142 // handler should be tagged with metrics.CacheTypeTag.
143 > func NewWithMetrics(maxSize int, opts *Options, handler metrics.Handler) StoppableCache { lru.go
144 > if opts == nil {
145 opts = &Options{}
146 }
147
148 > backgroundEvict := opts.BackgroundEvict lru.go
149 > if backgroundEvict == nil {
150 > backgroundEvict = func() dynamicconfig.CacheBackgroundEvictSettings { lru.go
151 > return dynamicconfig.CacheBackgroundEvictSettings{
152 > Enabled: false,
153 > }
154 > }
155 }
156
157 > timeSource := opts.TimeSource lru.go
158 > if timeSource == nil {
159 > timeSource = clock.NewRealTimeSource() lru.go
160 > }
161
162 > metrics.CacheSize.With(handler).Record(float64(maxSize)) lru.go
163 > metrics.CacheTtl.With(handler).Record(opts.TTL)
164 > c := &lru{
165 > byAccess: list.New(),
166 > byKey: make(map[any]*list.Element),
167 > ttl: opts.TTL,
168 > maxSize: maxSize,
169 > currSize: 0,
170 > pin: opts.Pin,
171 > onPut: opts.OnPut,
172 > onEvict: opts.OnEvict,
173 > timeSource: timeSource,
174 > metricsHandler: handler,
175 > backgroundEvict: backgroundEvict,
176 > }
177 > if c.backgroundEvict().Enabled {
178 c.loops.Go(c.bgEvictLoop)
179 }
180 > return c lru.go
181 }
182
188
189 // Get retrieves the value stored under the given key
190 > func (c *lru) Get(key any) any { lru.go
191 > if c.maxSize == 0 { //
192 return nil
193 }
194 > c.mut.Lock() lru.go
195 > defer c.mut.Unlock()
196 >
197 > element := c.byKey[key]
198 > if element == nil {
199 > return nil lru.go
200 > }
201
202 > entry := element.Value.(*entryImpl) lru.go
203 >
204 > if c.isEntryExpired(entry, c.timeSource.Now().UTC()) {
205 // Entry has expired
206 c.deleteInternal(element)
208 }
209
210 > metrics.CacheEntryAgeOnGet.With(c.metricsHandler).Record(c.timeSource.Now().UTC().Sub(entry.createTime)) lru.go
211 >
212 > c.updateEntryRefCount(entry)
213 > c.byAccess.MoveToFront(element)
214 > return entry.value
215 }
216
217 // Put puts a new value associated with a given key, returning the existing value (if present)
218 > func (c *lru) Put(key any, value any) any { lru.go
219 > if c.pin {
220 panic("Cannot use Put API in Pin mode. Use Delete and PutIfNotExist if necessary")
221 }
222 > val, _ := c.putInternal(key, value, true) lru.go
223 > return val
224 }
225
226 // PutIfNotExist puts a value associated with a given key if it does not exist
227 > func (c *lru) PutIfNotExist(key any, value any) (any, error) { lru.go
228 > existing, err := c.putInternal(key, value, false)
229 > if err != nil {
230 return nil, err
231 }
232
233 > if existing == nil { lru.go
234 > // This is a new value lru.go
235 > return value, err
236 > }
237
238 return existing, err
254
255 // Release decrements the ref count of a pinned element.
256 > func (c *lru) Release(key any) { lru.go
257 > if c.maxSize == 0 || !c.pin {
258 return
259 }
260 > c.mut.Lock() lru.go
261 > defer c.mut.Unlock()
262 >
263 > elt, ok := c.byKey[key]
264 > if !ok {
265 return
266 }
267 > entry := elt.Value.(*entryImpl) lru.go
268 > entry.refCount--
269 > if entry.refCount == 0 {
270 > c.pinnedSize -= entry.Size() lru.go
271 > metrics.CachePinnedUsage.With(c.metricsHandler).Record(float64(c.pinnedSize))
272 > }
273 // Entry size might have changed. Recalculate size and evict entries if necessary.
274 > newEntrySize := getSize(entry.value) lru.go
275 > c.currSize = c.calculateNewCacheSize(newEntrySize, entry.Size())
276 > entry.size = newEntrySize
277 > if c.currSize > c.maxSize {
278 c.tryEvictUntilCacheSizeUnderLimit()
279 }
280 > metrics.CacheUsage.With(c.metricsHandler).Record(float64(c.currSize)) lru.go
281 }
282
294 // Put puts a new value associated with a given key, returning the existing value (if present)
295 // allowUpdate flag is used to control overwrite behavior if the value exists.
296 > func (c *lru) putInternal(key any, value any, allowUpdate bool) (any, error) { lru.go
297 > if c.maxSize == 0 {
298 return nil, nil
299 }
300 > newEntrySize := getSize(value) lru.go
301 > if newEntrySize > c.maxSize {
302 return nil, ErrCacheItemTooLarge
303 }
304
305 > c.mut.Lock() lru.go
306 > defer c.mut.Unlock()
307 >
308 > elt := c.byKey[key]
309 > // If the entry exists, check if it has expired or update the value
310 > if elt != nil {
311 existingEntry := elt.Value.(*entryImpl)
312 if !c.isEntryExpired(existingEntry, c.timeSource.Now().UTC()) {
347 }
348
349 > c.tryEvictUntilEnoughSpaceWithSkipEntry(newEntrySize, nil) lru.go
350 >
351 > // check if the new entry can fit in the cache
352 > newCacheSize := c.calculateNewCacheSize(newEntrySize, emptyEntrySize)
353 > if newCacheSize > c.maxSize {
354 return nil, ErrCacheFull
355 }
356
357 > entry := &entryImpl{ lru.go
358 > key: key,
359 > value: value,
360 > size: newEntrySize,
361 > }
362 > c.updateEntryTTL(entry)
363 > c.updateEntryRefCount(entry)
364 > element := c.byAccess.PushFront(entry)
365 > c.byKey[key] = element
366 > c.currSize = newCacheSize
367 > metrics.CacheUsage.With(c.metricsHandler).Record(float64(c.currSize))
368 >
369 > if c.onPut != nil {
370 > c.onPut(value) lru.go
371 > }
372
373 > return nil, nil lru.go
374 }
375
376 > func (c *lru) calculateNewCacheSize(newEntrySize int, existingEntrySize int) int { lru.go
377 > return c.currSize - existingEntrySize + newEntrySize
378 > }
379
380 func (c *lru) deleteInternal(element *list.Element) {
397 // tryEvictUntilEnoughSpaceWithSkipEntry try to evict entries until there is enough space for the new entry without
398 // evicting the existing entry. the existing entry is skipped because it is being updated.
399 > func (c *lru) tryEvictUntilEnoughSpaceWithSkipEntry(newEntrySize int, existingEntry *entryImpl) { lru.go
400 > element := c.byAccess.Back()
401 > existingEntrySize := 0
402 > if existingEntry != nil {
403 existingEntrySize = existingEntry.Size()
404 }
405
406 > for c.calculateNewCacheSize(newEntrySize, existingEntrySize) > c.maxSize && element != nil { lru.go
407 entry := element.Value.(*entryImpl)
408 if existingEntry != nil && entry.key == existingEntry.key {
426 }
427
428 > func (c *lru) isEntryExpired(entry *entryImpl, currentTime time.Time) bool { lru.go
429 > return entry.refCount == 0 && !entry.createTime.IsZero() && currentTime.After(entry.createTime.Add(c.ttl))
430 > }
431
432 > func (c *lru) updateEntryTTL(entry *entryImpl) { lru.go
433 > if c.ttl != 0 {
434 > entry.createTime = c.timeSource.Now().UTC() lru.go
435 > }
436 }
437
438 > func (c *lru) updateEntryRefCount(entry *entryImpl) { lru.go
439 > if c.pin {
440 > entry.refCount++ lru.go
441 > if entry.refCount == 1 {
442 > c.pinnedSize += entry.Size()
443 > metrics.CachePinnedUsage.With(c.metricsHandler).Record(float64(c.pinnedSize))
444 > }
445 }
446 }
go.temporal.io/server/common/resourcetest/test_resource.go 132 covered LOC · 13 ranges

Open complete file

95
96 // NewTest returns a new test resource instance
97 > func NewTest(controller *gomock.Controller, serviceName primitives.ServiceName) *Test { test_resource.go
98 > logger := log.NewTestLogger()
99 >
100 > frontendClient := workflowservicemock.NewMockWorkflowServiceClient(controller)
101 > matchingClient := matchingservicemock.NewMockMatchingServiceClient(controller)
102 > historyClient := historyservicemock.NewMockHistoryServiceClient(controller)
103 > remoteFrontendClient := workflowservicemock.NewMockWorkflowServiceClient(controller)
104 > remoteAdminClient := adminservicemock.NewMockAdminServiceClient(controller)
105 > clusterMetadataManager := persistence.NewMockClusterMetadataManager(controller)
106 > clientBean := client.NewMockBean(controller)
107 > clientBean.EXPECT().GetFrontendClient().Return(frontendClient).AnyTimes()
108 > clientBean.EXPECT().GetMatchingClient(gomock.Any()).Return(matchingClient, nil).AnyTimes()
109 > clientBean.EXPECT().GetHistoryClient().Return(historyClient).AnyTimes()
110 > clientBean.EXPECT().GetRemoteAdminClient(gomock.Any()).Return(remoteAdminClient, nil).AnyTimes()
111 > clientBean.EXPECT().GetRemoteFrontendClient(gomock.Any()).Return(nil, remoteFrontendClient, nil).AnyTimes()
112 > clientFactory := client.NewMockFactory(controller)
113 >
114 > metadataMgr := persistence.NewMockMetadataManager(controller)
115 > taskMgr := persistence.NewMockTaskManager(controller)
116 > shardMgr := persistence.NewMockShardManager(controller)
117 > executionMgr := persistence.NewMockExecutionManager(controller)
118 > executionMgr.EXPECT().GetHistoryBranchUtil().Return(persistence.NewHistoryBranchUtil(serialization.NewSerializer())).AnyTimes()
119 > namespaceReplicationQueue := persistence.NewMockNamespaceReplicationQueue(controller)
120 > nexusEndpointMgr := persistence.NewMockNexusEndpointManager(controller)
121 >
122 > membershipMonitor := membership.NewMockMonitor(controller)
123 > hostInfoProvider := membership.NewMockHostInfoProvider(controller)
124 > frontendServiceResolver := membership.NewMockServiceResolver(controller)
125 > matchingServiceResolver := membership.NewMockServiceResolver(controller)
126 > historyServiceResolver := membership.NewMockServiceResolver(controller)
127 > workerServiceResolver := membership.NewMockServiceResolver(controller)
128 > membershipMonitor.EXPECT().GetResolver(primitives.FrontendService).Return(frontendServiceResolver, nil).AnyTimes()
129 > membershipMonitor.EXPECT().GetResolver(primitives.InternalFrontendService).Return(nil, membership.ErrUnknownService).AnyTimes()
130 > membershipMonitor.EXPECT().GetResolver(primitives.MatchingService).Return(matchingServiceResolver, nil).AnyTimes()
131 > membershipMonitor.EXPECT().GetResolver(primitives.HistoryService).Return(historyServiceResolver, nil).AnyTimes()
132 > membershipMonitor.EXPECT().GetResolver(primitives.WorkerService).Return(workerServiceResolver, nil).AnyTimes()
133 > membershipMonitor.EXPECT().WaitUntilInitialized(gomock.Any()).Return(nil).AnyTimes()
134 >
135 > scope := tally.NewTestScope("test", nil)
136 > metricsHandler := metrics.NewTallyMetricsHandler(metrics.ClientConfig{}, scope).WithTags(
137 > metrics.ServiceNameTag(serviceName),
138 > )
139 >
140 > return &Test{
141 > MetricsScope: scope,
142 > ClusterMetadata: cluster.NewMockMetadata(controller),
143 > SearchAttributesProvider: searchattribute.NewMockProvider(controller),
144 > SearchAttributesManager: searchattribute.NewMockManager(controller),
145 > SearchAttributesMapperProvider: searchattribute.NewMockMapperProvider(controller),
146 >
147 > // other common resources
148 >
149 > NamespaceCache: namespace.NewMockRegistry(controller),
150 > TimeSource: clock.NewRealTimeSource(),
151 > PayloadSerializer: serialization.NewSerializer(),
152 > MetricsHandler: metricsHandler,
153 > ArchivalMetadata: archiver.NewMetadataMock(controller),
154 > ArchiverProvider: provider.NewMockArchiverProvider(controller),
155 >
156 > // membership infos
157 >
158 > MembershipMonitor: membershipMonitor,
159 > HostInfoProvider: hostInfoProvider,
160 > FrontendServiceResolver: frontendServiceResolver,
161 > MatchingServiceResolver: matchingServiceResolver,
162 > HistoryServiceResolver: historyServiceResolver,
163 > WorkerServiceResolver: workerServiceResolver,
164 >
165 > // internal services clients
166 >
167 > SDKClientFactory: sdk.NewMockClientFactory(controller),
168 > FrontendClient: frontendClient,
169 > MatchingClient: matchingClient,
170 > HistoryClient: historyClient,
171 > RemoteAdminClient: remoteAdminClient,
172 > RemoteFrontendClient: remoteFrontendClient,
173 > ClientBean: clientBean,
174 > ClientFactory: clientFactory,
175 > ESClient: esclient.NewMockClient(controller),
176 > VisibilityManager: manager.NewMockVisibilityManager(controller),
177 >
178 > // persistence clients
179 >
180 > MetadataMgr: metadataMgr,
181 > ClusterMetadataMgr: clusterMetadataManager,
182 > TaskMgr: taskMgr,
183 > NamespaceReplicationQueue: namespaceReplicationQueue,
184 > ShardMgr: shardMgr,
185 > ExecutionMgr: executionMgr,
186 > NexusEndpointManager: nexusEndpointMgr,
187 >
188 > // logger
189 >
190 > Logger: logger,
191 > }
192 > }
193
194 // Start for testing
218
219 // GetClusterMetadata for testing
220 > func (t *Test) GetClusterMetadata() cluster.Metadata { test_resource.go
221 > return t.ClusterMetadata
222 > }
223
224 // GetClusterMetadata for testing
230
231 // GetNamespaceRegistry for testing
232 > func (t *Test) GetNamespaceRegistry() namespace.Registry { test_resource.go
233 > return t.NamespaceCache
234 > }
235
236 // GetTimeSource for testing
240
241 // GetPayloadSerializer for testing
242 > func (t *Test) GetPayloadSerializer() serialization.Serializer { test_resource.go
243 > return t.PayloadSerializer
244 > }
245
246 // GetMetricsHandler for testing
250
251 // GetArchivalMetadata for testing
252 > func (t *Test) GetArchivalMetadata() archiver.ArchivalMetadata { test_resource.go
253 > return t.ArchivalMetadata
254 > }
255
256 // GetArchiverProvider for testing
267
268 // GetHostInfoProvider for testing
269 > func (t *Test) GetHostInfoProvider() membership.HostInfoProvider { test_resource.go
270 > return t.HostInfoProvider
271 > }
272
273 // GetFrontendServiceResolver for testing
319
320 // GetHistoryClient for testing
321 > func (t *Test) GetHistoryClient() historyservice.HistoryServiceClient { test_resource.go
322 > return t.HistoryClient
323 > }
324
325 // GetRemoteAdminClient for testing
338
339 // GetClientBean for testing
340 > func (t *Test) GetClientBean() client.Bean { test_resource.go
341 > return t.ClientBean
342 > }
343
344 // GetClientFactory for testing
371
372 // GetShardManager for testing
373 > func (t *Test) GetShardManager() persistence.ShardManager { test_resource.go
374 > return t.ShardMgr
375 > }
376
377 // GetExecutionManager for testing
383
384 // GetLogger for testing
385 > func (t *Test) GetLogger() log.Logger { test_resource.go
386 > return t.Logger
387 > }
388
389 // GetThrottledLogger for testing
390 > func (t *Test) GetThrottledLogger() log.Logger { test_resource.go
391 > return t.Logger
392 > }
393
394 // GetGRPCListener for testing
397 }
398
399 > func (t *Test) GetSearchAttributesProvider() searchattribute.Provider { test_resource.go
400 > return t.SearchAttributesProvider
401 > }
402
403 func (t *Test) GetSearchAttributesManager() searchattribute.Manager {
405 }
406
407 > func (t *Test) GetSearchAttributesMapperProvider() searchattribute.MapperProvider { test_resource.go
408 > return t.SearchAttributesMapperProvider
409 > }
go.temporal.io/server/service/history/workflow/task_generator.go 131 covered LOC · 25 ranges

Open complete file

115 archivalMetadata archiver.ArchivalMetadata,
116 logger log.Logger,
117 > ) *TaskGeneratorImpl { task_generator.go
118 > return &TaskGeneratorImpl{
119 > namespaceRegistry: namespaceRegistry,
120 > mutableState: mutableState,
121 > config: config,
122 > archivalMetadata: archivalMetadata,
123 > logger: logger,
124 > }
125 > }
126
127 func (r *TaskGeneratorImpl) GenerateWorkflowStartTasks(
128 startEvent *historypb.HistoryEvent,
129 > ) (int32, error) { task_generator.go
130 >
131 > executionInfo := r.mutableState.GetExecutionInfo()
132 > executionTimeoutTimerTaskStatus := executionInfo.WorkflowExecutionTimerTaskStatus
133 > if !r.mutableState.IsWorkflowExecutionRunning() {
134 return executionTimeoutTimerTaskStatus, nil
135 }
136
137 > workflowExecutionTimeoutTimerEnabled := r.config.EnableWorkflowExecutionTimeoutTimer() task_generator.go
138 > if !workflowExecutionTimeoutTimerEnabled {
139 // when the feature is disabled, reset this field so that it won't be carried over to the next run
140 // and new runs can always have the run timeout timer always generated.
155 // into the situation where execution timeout is set but no timeout timer task is generated.
156
157 > isFirstRun := executionInfo.FirstExecutionRunId == r.mutableState.GetExecutionState().RunId task_generator.go
158 > workflowExecutionExpirationTime := timestamp.TimeValue(
159 > executionInfo.WorkflowExecutionExpirationTime,
160 > )
161 > if workflowExecutionTimeoutTimerEnabled &&
162 > !isFirstRun &&
163 > !workflowExecutionExpirationTime.IsZero() &&
164 > executionInfo.WorkflowExecutionTimerTaskStatus == TimerTaskStatusNone {
165 r.mutableState.AddTasks(&tasks.WorkflowExecutionTimeoutTask{
166 // TaskID is set by shard
173 }
174
175 > workflowRunExpirationTime := timestamp.TimeValue( task_generator.go
176 > executionInfo.WorkflowRunExpirationTime,
177 > )
178 > if workflowRunExpirationTime.IsZero() {
179 return executionTimeoutTimerTaskStatus, nil
180 }
181 > if executionTimeoutTimerTaskStatus == TimerTaskStatusNone || task_generator.go
182 > workflowRunExpirationTime.Before(workflowExecutionExpirationTime) {
183 > r.mutableState.AddTasks(&tasks.WorkflowRunTimeoutTask{ task_generator.go
184 > // TaskID is set by shard
185 > WorkflowKey: r.mutableState.GetWorkflowKey(),
186 > VisibilityTimestamp: workflowRunExpirationTime,
187 > Version: startEvent.GetVersion(),
188 > })
189 > }
190
191 > return executionTimeoutTimerTaskStatus, nil task_generator.go
192 }
193
295 func (r *TaskGeneratorImpl) GenerateDirtySubStateMachineTasks(
296 stateMachineRegistry *hsm.Registry,
297 > ) error { task_generator.go
298 > tree := r.mutableState.HSM()
299 > opLog, err := tree.OpLog()
300 > if err != nil {
301 return err
302 }
303
304 > for _, op := range opLog { task_generator.go
305 switch transitionOp := op.(type) {
306 case hsm.DeleteOperation:
329 }
330
331 > AddNextStateMachineTimerTask(r.mutableState) task_generator.go
332 >
333 > return nil
334 }
335
408 func (r *TaskGeneratorImpl) GenerateRecordWorkflowStartedTasks(
409 startEvent *historypb.HistoryEvent,
410 > ) error { task_generator.go
411 >
412 > startVersion := startEvent.GetVersion()
413 >
414 > r.mutableState.AddTasks(&tasks.StartExecutionVisibilityTask{
415 > // TaskID, VisibilityTimestamp is set by shard
416 > WorkflowKey: r.mutableState.GetWorkflowKey(),
417 > Version: startVersion,
418 > })
419 > return nil
420 > }
421
422 func (r *TaskGeneratorImpl) GenerateScheduleWorkflowTaskTasks(
423 workflowTaskScheduledEventID int64,
424 > ) error { task_generator.go
425 > workflowTask := r.mutableState.GetWorkflowTaskByID(workflowTaskScheduledEventID)
426 > if workflowTask == nil {
427 return serviceerror.NewInternalf("it could be a bug, cannot get pending workflow task: %v", workflowTaskScheduledEventID)
428 }
429 > if workflowTask.Type == enumsspb.WORKFLOW_TASK_TYPE_SPECULATIVE { task_generator.go
430 return serviceerror.NewInternalf("it could be a bug, GenerateScheduleSpeculativeWorkflowTaskTasks must be called for speculative workflow task: %v", workflowTaskScheduledEventID)
431 }
432
433 > if r.mutableState.IsStickyTaskQueueSet() { task_generator.go
434 scheduleToStartTimeout := timestamp.DurationValue(r.mutableState.GetExecutionInfo().StickyScheduleToStartTimeout)
435 wttt := &tasks.WorkflowTaskTimeoutTask{
447 }
448
449 > r.mutableState.AddTasks(&tasks.WorkflowTask{ task_generator.go
450 > // TaskID, VisibilityTimestamp is set by shard
451 > WorkflowKey: r.mutableState.GetWorkflowKey(),
452 > // Store current task queue to the transfer task.
453 > // If current task queue becomes sticky in between when this transfer task is created and processed,
454 > // it can't be used at process time, because timeout timer was not created for it,
455 > // because it used to be non-sticky when this transfer task was created here.
456 > // In short, task queue that was "current" when transfer task was created must be used when task is processed.
457 > TaskQueue: workflowTask.TaskQueue.GetName(),
458 > ScheduledEventID: workflowTask.ScheduledEventID,
459 > Version: workflowTask.Version,
460 > Stamp: workflowTask.Stamp,
461 > })
462 >
463 > return nil
464 }
465
517 func (r *TaskGeneratorImpl) GenerateStartWorkflowTaskTasks(
518 workflowTaskScheduledEventID int64,
519 > ) error { task_generator.go
520 > workflowTask := r.mutableState.GetWorkflowTaskByID(
521 > workflowTaskScheduledEventID,
522 > )
523 > if workflowTask == nil {
524 return serviceerror.NewInternalf("it could be a bug, cannot get pending workflow task: %v", workflowTaskScheduledEventID)
525 }
526
527 > isSpeculative := workflowTask.Type == enumsspb.WORKFLOW_TASK_TYPE_SPECULATIVE task_generator.go
528 > wttt := &tasks.WorkflowTaskTimeoutTask{
529 > // TaskID is set by shard
530 > WorkflowKey: r.mutableState.GetWorkflowKey(),
531 > VisibilityTimestamp: workflowTask.StartedTime.Add(workflowTask.WorkflowTaskTimeout),
532 > TimeoutType: enumspb.TIMEOUT_TYPE_START_TO_CLOSE,
533 > EventID: workflowTask.ScheduledEventID,
534 > ScheduleAttempt: workflowTask.Attempt,
535 > Version: workflowTask.Version,
536 > Stamp: workflowTask.Stamp,
537 > InMemory: isSpeculative,
538 > }
539 >
540 > if isSpeculative {
541 // If WT is speculative, create task in in-memory task queue.
542 return r.mutableState.SetSpeculativeWorkflowTaskTimeoutTask(wttt)
543 }
544 > r.mutableState.AddTasks(wttt) task_generator.go
545 > r.mutableState.SetWorkflowTaskStartToCloseTimeoutTask(wttt)
546 >
547 > return nil
548 }
549
550 func (r *TaskGeneratorImpl) GenerateActivityTasks(
551 activityScheduledEventID int64,
552 > ) error { task_generator.go
553 > activityInfo, ok := r.mutableState.GetActivityInfo(activityScheduledEventID)
554 > if !ok {
555 return serviceerror.NewInternalf("it could be a bug, cannot get pending activity: %v", activityScheduledEventID)
556 }
557
558 > r.mutableState.AddTasks(&tasks.ActivityTask{ task_generator.go
559 > // TaskID, VisibilityTimestamp is set by shard
560 > WorkflowKey: r.mutableState.GetWorkflowKey(),
561 > TaskQueue: activityInfo.TaskQueue,
562 > ScheduledEventID: activityInfo.ScheduledEventId,
563 > Version: activityInfo.Version,
564 > Stamp: activityInfo.Stamp,
565 > })
566 >
567 > return nil
568 }
569
703 }
704
705 > func (r *TaskGeneratorImpl) GenerateUpsertVisibilityTask() error { task_generator.go
706 > r.mutableState.AddTasks(&tasks.UpsertExecutionVisibilityTask{
707 > // TaskID, VisibilityTimestamp is set by shard
708 > WorkflowKey: r.mutableState.GetWorkflowKey(),
709 > })
710 > return nil
711 > }
712
713 func (r *TaskGeneratorImpl) GenerateWorkflowResetTasks() error {
724 }
725
726 > func (r *TaskGeneratorImpl) GenerateActivityTimerTasks() error { task_generator.go
727 > _, err := r.getTimerSequence().CreateNextActivityTimer()
728 > return err
729 > }
730
731 > func (r *TaskGeneratorImpl) GenerateUserTimerTasks() error { task_generator.go
732 > _, err := r.getTimerSequence().CreateNextUserTimer()
733 > return err
734 > }
735
736 func (r *TaskGeneratorImpl) GenerateHistoryReplicationTasks(
893 }
894
895 > func (r *TaskGeneratorImpl) getTimerSequence() TimerSequence { task_generator.go
896 > return NewTimerSequence(r.mutableState)
897 > }
898
899 func (r *TaskGeneratorImpl) getTargetNamespaceID(
go.temporal.io/server/service/history/workflow/cache/cache.go 126 covered LOC · 33 ranges

Open complete file

95 logger log.Logger,
96 handler metrics.Handler,
97 > ) Cache { cache.go
98 > maxSize := config.HistoryHostLevelCacheMaxSize()
99 > if config.HistoryCacheLimitSizeBased {
100 maxSize = config.HistoryHostLevelCacheMaxSizeBytes()
101 }
102 > opts := &cache.Options{ cache.go
103 > TTL: config.HistoryCacheTTL(),
104 > Pin: true,
105 > BackgroundEvict: config.HistoryCacheBackgroundEvict,
106 > OnPut: func(val any) {
107 > //revive:disable-next-line:unchecked-type-assertion cache.go
108 > item := val.(*cacheItem)
109 > if item.finalizer == nil {
110 > return // should only happen in unit tests cache.go
111 > }
112 wfKey := item.wfContext.GetWorkflowKey()
113 err := item.finalizer.Register(wfKey.String(), func(ctx context.Context) error {
141 }
142
143 > taggedHandler := handler.WithTags(metrics.CacheTypeTag(metrics.MutableStateCacheTypeTagValue)) cache.go
144 > c := cache.NewWithMetrics(maxSize, opts, taggedHandler)
145 > return &cacheImpl{
146 > Cache: c,
147 > nonUserContextLockTimeout: config.HistoryCacheNonUserContextLockTimeout(),
148 > }
149 }
150
159 execution *commonpb.WorkflowExecution,
160 lockPriority locks.Priority,
161 > ) (historyi.WorkflowContext, historyi.ReleaseWorkflowContextFunc, error) { cache.go
162 > return c.GetOrCreateChasmExecution(
163 > ctx,
164 > shardContext,
165 > namespaceID,
166 > execution,
167 > chasm.WorkflowArchetypeID,
168 > lockPriority,
169 > )
170 > }
171
172 func (c *cacheImpl) GetOrCreateCurrentExecution(
221 archetypeID chasm.ArchetypeID,
222 lockPriority locks.Priority,
223 > ) (historyi.WorkflowContext, historyi.ReleaseWorkflowContextFunc, error) { cache.go
224 >
225 > if err := c.validateWorkflowExecutionInfo(ctx, shardContext, namespaceID, execution, archetypeID, lockPriority); err != nil {
226 return nil, nil, err
227 }
228
229 > handler := shardContext.GetMetricsHandler().WithTags( cache.go
230 > metrics.OperationTag(metrics.HistoryCacheGetOrCreateScope),
231 > metrics.CacheTypeTag(metrics.MutableStateCacheTypeTagValue),
232 > metrics.NamespaceIDTag(namespaceID.String()),
233 > )
234 > metrics.CacheRequests.With(handler).Record(1)
235 > start := time.Now()
236 > defer func() { metrics.CacheLatency.With(handler).Record(time.Since(start)) }()
237
238 > weCtx, weReleaseFunc, err := c.getOrCreateWorkflowExecutionInternal( cache.go
239 > ctx,
240 > shardContext,
241 > namespaceID,
242 > execution,
243 > archetypeID,
244 > handler,
245 > false,
246 > lockPriority,
247 > )
248 >
249 > metrics.ContextCounterAdd(ctx, metrics.HistoryWorkflowExecutionCacheLatency.Name(),
250 > time.Since(start).Nanoseconds())
251 >
252 > return weCtx, weReleaseFunc, err
253 }
254
262 forceClearContext bool,
263 lockPriority locks.Priority,
264 > ) (historyi.WorkflowContext, historyi.ReleaseWorkflowContextFunc, error) { cache.go
265 >
266 > if !softassert.That(
267 > shardContext.GetLogger(),
268 > archetypeID != chasm.UnspecifiedArchetypeID,
269 > "Creating execution cache key with unspecified archetype ID",
270 > ) {
271 archetypeID = chasm.WorkflowArchetypeID
272 }
273
274 > cacheKey := Key{ cache.go
275 > WorkflowKey: definition.NewWorkflowKey(namespaceID.String(), execution.GetWorkflowId(), execution.GetRunId()),
276 > ArchetypeID: archetypeID,
277 > ShardUUID: shardContext.GetOwner(),
278 > }
279 > item, cacheHit := c.Get(cacheKey).(*cacheItem)
280 > var workflowCtx historyi.WorkflowContext
281 > if cacheHit {
282 > workflowCtx = item.wfContext cache.go
283 > } else { cache.go
284 > metrics.CacheMissCounter.With(handler).Record(1) cache.go
285 > workflowCtx = workflow.NewContext(
286 > shardContext.GetConfig(),
287 > cacheKey.WorkflowKey,
288 > archetypeID,
289 > shardContext.GetLogger(),
290 > shardContext.GetThrottledLogger(),
291 > shardContext.GetMetricsHandler(),
292 > )
293 >
294 > var err error
295 > value := &cacheItem{shardId: shardContext.GetShardID(), wfContext: workflowCtx, finalizer: shardContext.GetFinalizer()}
296 > existing, err := c.PutIfNotExist(cacheKey, value)
297 > if err != nil {
298 metrics.CacheFailures.With(handler).Record(1)
299 return nil, nil, err
300 }
301 //nolint:revive
302 > workflowCtx = existing.(*cacheItem).wfContext cache.go
303 }
304
305 > if err := c.lockWorkflowExecution(ctx, workflowCtx, cacheKey, lockPriority); err != nil { cache.go
306 metrics.CacheFailures.With(handler).Record(1)
307 metrics.AcquireLockFailedCounter.With(handler).Record(1)
311 // TODO This will create a closure on every request.
312 // Consider revisiting this if it causes too much GC activity
313 > releaseFunc := c.makeReleaseFunc(cacheKey, shardContext, workflowCtx, forceClearContext, handler, time.Now()) cache.go
314 >
315 > return workflowCtx, releaseFunc, nil
316 }
317
321 cacheKey Key,
322 lockPriority locks.Priority,
323 > ) error { cache.go
324 > // skip if there is no deadline
325 > if deadline, ok := ctx.Deadline(); ok {
326 var cancel context.CancelFunc
327 if headers.GetCallerInfo(ctx).CallerType != headers.CallerTypeAPI {
340 }
341
342 > if err := workflowCtx.Lock(ctx, lockPriority); err != nil { cache.go
343 // ctx is done before lock can be acquired
344 c.Release(cacheKey)
345 return consts.ErrResourceExhaustedBusyWorkflow
346 }
347 > return nil cache.go
348 }
349
355 handler metrics.Handler,
356 acquireTime time.Time,
357 > ) func(error) { cache.go
358 >
359 > status := cacheNotReleased
360 > return func(err error) {
361 > if atomic.CompareAndSwapInt32(&status, cacheNotReleased, cacheReleased) {
362 > defer func() {
363 > metrics.HistoryWorkflowExecutionCacheLockHoldDuration.With(handler).Record(time.Since(acquireTime))
364 > }()
365 > if rec := recover(); rec != nil {
366 wfContext.Clear()
367 wfContext.Unlock()
368 c.Release(cacheKey)
369 panic(rec)
370 > } else { cache.go
371 > if err != nil || forceClearContext {
372 // TODO see issue #668, there are certain type or errors which can bypass the clear
373 wfContext.Clear()
374 wfContext.Unlock()
375 c.Release(cacheKey)
376 > } else { cache.go
377 > isDirty := wfContext.IsDirty() cache.go
378 > if isDirty {
379 wfContext.Clear()
380 softassert.Fail(shardContext.GetLogger(), "Cache encountered dirty mutable state transaction",
385 )
386 }
387 > wfContext.Unlock() cache.go
388 > c.Release(cacheKey)
389 > if isDirty {
390 panic("Cache encountered dirty mutable state transaction")
391 }
403 archetypeID chasm.ArchetypeID,
404 lockPriority locks.Priority,
405 > ) error { cache.go
406 >
407 > if err := c.validateWorkflowID(execution.GetWorkflowId()); err != nil {
408 return err
409 }
410
411 // RunID is not provided, lets try to retrieve the RunID for current active execution
412 > if execution.GetRunId() == "" { cache.go
413 runID, err := GetCurrentRunID(
414 ctx,
425
426 execution.RunId = runID
427 > } else if uuid.Validate(execution.GetRunId()) != nil { // immediately return if invalid runID cache.go
428 return serviceerror.NewInvalidArgument("RunId is not valid UUID.")
429 }
430 > return nil cache.go
431 }
432
433 func (c *cacheImpl) validateWorkflowID(
434 workflowID string,
435 > ) error { cache.go
436 > if workflowID == "" {
437 return serviceerror.NewInvalidArgument("Can't load workflow execution. WorkflowId not set.")
438 }
439 > return nil cache.go
440 }
441
477 }
478
479 > func (c *cacheItem) CacheSize() int { cache.go
480 > if sg, ok := c.wfContext.(cache.SizeGetter); ok {
481 > return sg.CacheSize() cache.go
482 > }
483 return 0
484 }
go.temporal.io/server/service/history/historybuilder/history_builder.go 114 covered LOC · 14 ranges

Open complete file

66 metricsHandler metrics.Handler,
67 maxEventBatchSizeInBytes dynamicconfig.IntPropertyFn,
68 > ) *HistoryBuilder { history_builder.go
69 > return &HistoryBuilder{
70 > EventStore: EventStore{
71 > state: HistoryBuilderStateMutable,
72 > timeSource: timeSource,
73 > taskIDGenerator: taskIDGenerator,
74 >
75 > version: version,
76 > nextEventID: nextEventID,
77 >
78 > workflowFinished: false,
79 >
80 > dbBufferBatch: dbBufferBatch,
81 > dbClearBuffer: false,
82 > memEventsBatches: nil,
83 > memLatestBatch: nil,
84 > memBufferBatch: nil,
85 > scheduledIDToStartedID: make(map[int64]int64),
86 > requestIDToEventID: make(map[string]int64),
87 >
88 > maxEventBatchSizeInBytes: maxEventBatchSizeInBytes,
89 >
90 > metricsHandler: metricsHandler,
91 > },
92 > EventFactory: EventFactory{timeSource: timeSource, version: version},
93 > }
94 > }
95
96 func (b *HistoryBuilder) SetTimeSource(timeSource clock.TimeSource) {
153 }
154
155 > func (b *HistoryBuilder) IsDirty() bool { history_builder.go
156 > return b.EventStore.IsDirty()
157 > }
158
159 // AddWorkflowExecutionStartedEvent
168 firstInChainRunID string,
169 originalRunID string,
170 > ) *historypb.HistoryEvent { history_builder.go
171 > event := b.CreateWorkflowExecutionStartedEvent(
172 > startTime,
173 > request,
174 > resetPoints,
175 > prevRunID,
176 > firstInChainRunID,
177 > originalRunID,
178 > )
179 > if request.StartRequest.GetUserMetadata() != nil {
180 event.UserMetadata = request.StartRequest.GetUserMetadata()
181 }
182 > if len(request.StartRequest.GetLinks()) > 0 { history_builder.go
183 event.Links = request.StartRequest.GetLinks()
184 }
185 > event, _ = b.add(event) history_builder.go
186 > return event
187 }
188
192 attempt int32,
193 scheduleTime time.Time,
194 > ) *historypb.HistoryEvent { history_builder.go
195 > event := b.CreateWorkflowTaskScheduledEvent(taskQueue, startToCloseTimeout, attempt, scheduleTime)
196 > event, _ = b.add(event)
197 > return event
198 > }
199
200 func (b *HistoryBuilder) AddWorkflowTaskStartedEvent(
209 suggestContinueAsNewReasons []enumspb.SuggestContinueAsNewReason,
210 targetWorkerDeploymentVersionChanged bool,
211 > ) *historypb.HistoryEvent { history_builder.go
212 > event := b.CreateWorkflowTaskStartedEvent(
213 > scheduledEventID,
214 > requestID,
215 > identity,
216 > startTime,
217 > suggestContinueAsNew,
218 > historySizeBytes,
219 > versioningStamp,
220 > buildIdRedirectCounter,
221 > suggestContinueAsNewReasons,
222 > targetWorkerDeploymentVersionChanged,
223 > )
224 > event, _ = b.add(event)
225 > return event
226 > }
227
228 func (b *HistoryBuilder) AddWorkflowTaskCompletedEvent(
237 deployment *deploymentpb.Deployment,
238 behavior enumspb.VersioningBehavior,
239 > ) *historypb.HistoryEvent { history_builder.go
240 > event := b.CreateWorkflowTaskCompletedEvent(
241 > scheduledEventID,
242 > startedEventID,
243 > identity,
244 > checksum,
245 > workerVersionStamp,
246 > sdkMetadata,
247 > meteringMetadata,
248 > deploymentName,
249 > deployment,
250 > behavior,
251 > )
252 > event, _ = b.add(event)
253 > return event
254 > }
255
256 func (b *HistoryBuilder) AddWorkflowTaskTimedOutEvent(
318 command *commandpb.ScheduleActivityTaskCommandAttributes,
319 ns namespace.Name,
320 > ) (*historypb.HistoryEvent, int64) { history_builder.go
321 > event := b.CreateActivityTaskScheduledEvent(workflowTaskCompletedEventID, command)
322 > event, batchID := b.add(event)
323 >
324 > if payloadSize := command.Input.Size(); payloadSize > 0 {
325 > b.metricsHandler.Counter(metrics.ActivityPayloadSize.Name()).Record( history_builder.go
326 > int64(payloadSize),
327 > metrics.OperationTag(metrics.HistoryRecordActivityTaskStartedScope),
328 > metrics.NamespaceTag(ns.String()))
329 > }
330
331 > return event, batchID history_builder.go
332 }
333
351 versioningStamp *commonpb.WorkerVersionStamp,
352 redirectCounter int64,
353 > ) *historypb.HistoryEvent { history_builder.go
354 > event := b.CreateActivityTaskStartedEvent(scheduledEventID, attempt, requestID, identity, lastFailure, versioningStamp, redirectCounter)
355 > event, _ = b.add(event)
356 > return event
357 > }
358
359 func (b *HistoryBuilder) AddActivityTaskCompletedEvent(
555 workflowTaskCompletedEventID int64,
556 scheduledEventID int64,
557 > ) *historypb.HistoryEvent { history_builder.go
558 > event := b.CreateActivityTaskCancelRequestedEvent(workflowTaskCompletedEventID, scheduledEventID)
559 >
560 > event, _ = b.add(event)
561 > return event
562 > }
563
564 func (b *HistoryBuilder) AddActivityTaskCanceledEvent(
568 details *commonpb.Payloads,
569 identity string,
570 > ) *historypb.HistoryEvent { history_builder.go
571 > event := b.CreateActivityTaskCanceledEvent(
572 > scheduledEventID,
573 > startedEventID,
574 > latestCancelRequestedEventID,
575 > details,
576 > identity,
577 > )
578 >
579 > event, _ = b.add(event)
580 > return event
581 > }
582
583 func (b *HistoryBuilder) AddTimerCanceledEvent(
go.temporal.io/server/chasm/search_attribute.go 111 covered LOC · 16 ranges

Open complete file

136 }
137
138 > func newSearchAttributeFieldBool(index int) SearchAttributeFieldBool { search_attribute.go
139 > return SearchAttributeFieldBool{
140 > field: resolveFieldName(enumspb.INDEXED_VALUE_TYPE_BOOL, index),
141 > }
142 > }
143
144 // SearchAttributeFieldDateTime is a search attribute field for a datetime value.
147 }
148
149 > func newSearchAttributeFieldDateTime(index int) SearchAttributeFieldDateTime { search_attribute.go
150 > return SearchAttributeFieldDateTime{
151 > field: resolveFieldName(enumspb.INDEXED_VALUE_TYPE_DATETIME, index),
152 > }
153 > }
154
155 // SearchAttributeFieldInt is a search attribute field for an integer value.
158 }
159
160 > func newSearchAttributeFieldInt(index int) SearchAttributeFieldInt { search_attribute.go
161 > return SearchAttributeFieldInt{
162 > field: resolveFieldName(enumspb.INDEXED_VALUE_TYPE_INT, index),
163 > }
164 > }
165
166 // SearchAttributeFieldDouble is a search attribute field for a double value.
169 }
170
171 > func newSearchAttributeFieldDouble(index int) SearchAttributeFieldDouble { search_attribute.go
172 > return SearchAttributeFieldDouble{
173 > field: resolveFieldName(enumspb.INDEXED_VALUE_TYPE_DOUBLE, index),
174 > }
175 > }
176
177 // SearchAttributeFieldKeyword is a search attribute field for a keyword value.
180 }
181
182 > func newSearchAttributeFieldKeyword(index int) SearchAttributeFieldKeyword { search_attribute.go
183 > return SearchAttributeFieldKeyword{
184 > field: resolveFieldName(enumspb.INDEXED_VALUE_TYPE_KEYWORD, index),
185 > }
186 > }
187
188 > func newSearchAttributeFieldLowCardinalityKeyword(index int) SearchAttributeFieldKeyword { search_attribute.go
189 > return SearchAttributeFieldKeyword{
190 > field: fmt.Sprintf("%s%s%02d", sadefs.ReservedPrefix, "LowCardinalityKeyword", index),
191 > }
192 > }
193
194 // SearchAttributeFieldKeywordList is a search attribute field for a keyword list value.
197 }
198
199 > func newSearchAttributeFieldKeywordList(index int) SearchAttributeFieldKeywordList { search_attribute.go
200 > return SearchAttributeFieldKeywordList{
201 > field: resolveFieldName(enumspb.INDEXED_VALUE_TYPE_KEYWORD_LIST, index),
202 > }
203 > }
204
205 // SearchAttributeFieldText is a search attribute field for a text value.
214 }
215
216 > func resolveFieldName(valueType enumspb.IndexedValueType, index int) string { search_attribute.go
217 > // Columns are named like TemporalBool01, TemporalDatetime01, TemporalDouble01, TemporalInt01.
218 > return fmt.Sprintf("%s%s%02d", sadefs.ReservedPrefix, valueType.String(), index)
219 > }
220
221 func (s searchAttributeDefinition) definition() searchAttributeDefinition {
229
230 // NewSearchAttributeBool creates a new boolean search attribute given a predefined chasm field
231 > func NewSearchAttributeBool(alias string, boolField SearchAttributeFieldBool) SearchAttributeBool { search_attribute.go
232 > return SearchAttributeBool{
233 > searchAttributeDefinition: searchAttributeDefinition{
234 > alias: alias,
235 > field: boolField.field,
236 > valueType: enumspb.INDEXED_VALUE_TYPE_BOOL,
237 > },
238 > }
239 > }
240
241 > func newSearchAttributeBoolByField(field string) SearchAttributeBool { search_attribute.go
242 > return SearchAttributeBool{
243 > searchAttributeDefinition: searchAttributeDefinition{
244 > alias: field,
245 > field: field,
246 > valueType: enumspb.INDEXED_VALUE_TYPE_BOOL,
247 > },
248 > }
249 > }
250
251 // Value sets the boolean value of the search attribute.
266
267 // NewSearchAttributeDateTime creates a new date time search attribute given a predefined chasm field
268 > func NewSearchAttributeDateTime(alias string, datetimeField SearchAttributeFieldDateTime) SearchAttributeDateTime { search_attribute.go
269 > return SearchAttributeDateTime{
270 > searchAttributeDefinition: searchAttributeDefinition{
271 > alias: alias,
272 > field: datetimeField.field,
273 > valueType: enumspb.INDEXED_VALUE_TYPE_DATETIME,
274 > },
275 > }
276 > }
277
278 > func newSearchAttributeDateTimeByField(field string) SearchAttributeDateTime { search_attribute.go
279 > return SearchAttributeDateTime{
280 > searchAttributeDefinition: searchAttributeDefinition{
281 > alias: field,
282 > field: field,
283 > valueType: enumspb.INDEXED_VALUE_TYPE_DATETIME,
284 > },
285 > }
286 > }
287
288 // Value sets the date time value of the search attribute.
303
304 // NewSearchAttributeInt creates a new integer search attribute given a predefined chasm field
305 > func NewSearchAttributeInt(alias string, intField SearchAttributeFieldInt) SearchAttributeInt { search_attribute.go
306 > return SearchAttributeInt{
307 > searchAttributeDefinition: searchAttributeDefinition{
308 > alias: alias,
309 > field: intField.field,
310 > valueType: enumspb.INDEXED_VALUE_TYPE_INT,
311 > },
312 > }
313 > }
314
315 // Value sets the integer value of the search attribute.
367
368 // NewSearchAttributeKeyword creates a new keyword search attribute given a predefined chasm field
369 > func NewSearchAttributeKeyword(alias string, keywordField SearchAttributeFieldKeyword) SearchAttributeKeyword { search_attribute.go
370 > return SearchAttributeKeyword{
371 > searchAttributeDefinition: searchAttributeDefinition{
372 > alias: alias,
373 > field: keywordField.field,
374 > valueType: enumspb.INDEXED_VALUE_TYPE_KEYWORD,
375 > },
376 > }
377 > }
378
379 > func newSearchAttributeKeywordByField(field string) SearchAttributeKeyword { search_attribute.go
380 > return SearchAttributeKeyword{
381 > searchAttributeDefinition: searchAttributeDefinition{
382 > alias: field,
383 > field: field,
384 > valueType: enumspb.INDEXED_VALUE_TYPE_KEYWORD,
385 > },
386 > }
387 > }
388
389 // Value sets the string value of the search attribute.
414 }
415
416 > func newSearchAttributeKeywordListByField(field string) SearchAttributeKeywordList { search_attribute.go
417 > return SearchAttributeKeywordList{
418 > searchAttributeDefinition: searchAttributeDefinition{
419 > alias: field,
420 > field: field,
421 > valueType: enumspb.INDEXED_VALUE_TYPE_KEYWORD_LIST,
422 > },
423 > }
424 > }
425
426 // Value sets the string list value of the search attribute.
go.temporal.io/server/service/history/api/respondworkflowtaskcompleted/workflow_task_completed_handler.go 110 covered LOC · 29 ranges

Open complete file

128 matchingClient matchingservice.MatchingServiceClient,
129 versionCache worker_versioning.VersionMembershipAndReactivationStatusCache,
130 > ) *workflowTaskCompletedHandler { workflow_task_completed_handler.go
131 > return &workflowTaskCompletedHandler{
132 > identity: identity,
133 > workerControlTaskQueue: workerControlTaskQueue,
134 > workflowTaskCompletedID: workflowTaskCompletedID,
135 >
136 > // internal state
137 > hasBufferedEventsOrMessages: hasBufferedEventsOrMessages,
138 > workflowTaskFailedCause: nil,
139 > activityNotStartedCancelled: false,
140 > newMutableState: nil,
141 > stopProcessing: false,
142 > mutableState: mutableState,
143 > effects: effects,
144 > initiatedChildExecutionsInBatch: make(map[string]struct{}),
145 > updateRegistry: updateRegistry,
146 >
147 > // validation
148 > attrValidator: attrValidator,
149 > sizeLimitChecker: sizeLimitChecker,
150 > searchAttributesMapperProvider: searchAttributesMapperProvider,
151 >
152 > logger: logger,
153 > namespaceRegistry: namespaceRegistry,
154 > metricsHandler: metricsHandler.WithTags(
155 > metrics.OperationTag(metrics.HistoryRespondWorkflowTaskCompletedScope),
156 > metrics.NamespaceTag(mutableState.GetNamespaceEntry().Name().String()),
157 > ),
158 > config: config,
159 > shard: shard,
160 > tokenSerializer: tasktoken.NewSerializer(),
161 > commandHandlerRegistry: commandHandlerRegistry,
162 > chasmWorkflowRegistry: chasmWorkflowRegistry,
163 > matchingClient: matchingClient,
164 > versionCache: versionCache,
165 > }
166 > }
167
168 func (handler *workflowTaskCompletedHandler) handleCommands(
170 commands []*commandpb.Command,
171 msgs *collection.IndexedTakeList[string, *protocolpb.Message],
172 > ) ([]workflowTaskResponseMutation, error) { workflow_task_completed_handler.go
173 > if err := handler.attrValidator.ValidateCommandSequence(
174 > commands,
175 > ); err != nil {
176 return nil, err
177 }
178
179 > var mutations []workflowTaskResponseMutation workflow_task_completed_handler.go
180 > var postActions []commandPostAction
181 > for _, command := range commands {
182 > response, err := handler.handleCommand(ctx, command, msgs) workflow_task_completed_handler.go
183 > if err != nil || handler.stopProcessing {
184 return nil, err
185 }
186 > if response != nil { workflow_task_completed_handler.go
187 if response.workflowTaskResponseMutation != nil {
188 mutations = append(mutations, response.workflowTaskResponseMutation)
200 // However, PROTOCOL_MESSAGE command is not required by server. If it is not present,
201 // update.Acceptance and update.Respond messages will be processed after all commands in order they are in request.
202 > for _, msg := range msgs.TakeRemaining() { workflow_task_completed_handler.go
203 err := handler.handleMessage(ctx, msg)
204 if err != nil || handler.stopProcessing {
207 }
208
209 > for _, postAction := range postActions { workflow_task_completed_handler.go
210 mutation, err := postAction(ctx)
211 if err != nil || handler.stopProcessing {
230 wfKey definition.WorkflowKey,
231 workerIdentity string,
233 >
234 > // If server decided to fail WT (instead of completing), don't reject updates.
235 > // New WT will be created, and it will deliver these updates again to the worker.
236 > // Worker will do full history replay, and updates should be delivered again.
237 > if handler.workflowTaskFailedCause != nil {
238 return
239 }
240
241 // If WT is a heartbeat WT, then it doesn't have to have messages.
242 > if wtHeartbeat { workflow_task_completed_handler.go
243 return
244 }
247 // then it might skip processing some updates. In this case, it doesn't indicate old SDK or bug.
248 // All unprocessed updates will be aborted later though.
249 > if !handler.mutableState.IsWorkflowExecutionRunning() { workflow_task_completed_handler.go
250 return
251 }
252
253 > rejectedUpdateIDs := handler.updateRegistry.RejectUnprocessed( workflow_task_completed_handler.go
254 > ctx,
255 > handler.effects)
256 >
257 > if len(rejectedUpdateIDs) > 0 {
258 handler.logger.Warn(
259 "Workflow task completed w/o processing updates.",
277 command *commandpb.Command,
278 msgs *collection.IndexedTakeList[string, *protocolpb.Message],
279 > ) (*handleCommandResponse, error) { workflow_task_completed_handler.go
280 >
281 > metrics.CommandCounter.With(handler.metricsHandler).
282 > Record(1, metrics.CommandTypeTag(command.GetCommandType().String()))
283 > var response *handleCommandResponse
284 > var historyEvent *historypb.HistoryEvent
285 > var err error
286 >
287 > // TODO: ideally history events should not be exposed here. We should be passing the command
288 > // all the way down but it requires a bigger refactor of the mutable state interface.
289 > switch command.GetCommandType() {
290 case enumspb.COMMAND_TYPE_SCHEDULE_ACTIVITY_TASK:
291 historyEvent, response, err = handler.handleCommandScheduleActivity(ctx, command.GetScheduleActivityTaskCommandAttributes())
303 historyEvent, err = handler.handleCommandStartTimer(ctx, command.GetStartTimerCommandAttributes())
304
305 > case enumspb.COMMAND_TYPE_REQUEST_CANCEL_ACTIVITY_TASK: workflow_task_completed_handler.go
306 > historyEvent, err = handler.handleCommandRequestCancelActivity(ctx, command.GetRequestCancelActivityTaskCommandAttributes())
307
308 case enumspb.COMMAND_TYPE_CANCEL_TIMER:
671 _ context.Context,
672 attr *commandpb.RequestCancelActivityTaskCommandAttributes,
673 > ) (*historypb.HistoryEvent, error) { workflow_task_completed_handler.go
674 > if err := handler.validateCommandAttr(
675 > func() (enumspb.WorkflowTaskFailedCause, error) {
676 > return handler.attrValidator.ValidateActivityCancelAttributes(attr)
677 > },
678 ); err != nil || handler.stopProcessing {
679 return nil, err
680 }
681
682 > scheduledEventID := attr.GetScheduledEventId() workflow_task_completed_handler.go
683 > actCancelReqEvent, ai, err := handler.mutableState.AddActivityTaskCancelRequestedEvent(
684 > handler.workflowTaskCompletedID,
685 > scheduledEventID,
686 > handler.identity,
687 > )
688 > if err != nil {
689 return nil, handler.failWorkflowTaskOnInvalidArgument(enumspb.WORKFLOW_TASK_FAILED_CAUSE_BAD_REQUEST_CANCEL_ACTIVITY_ATTRIBUTES, err)
690 }
691 > if ai != nil { workflow_task_completed_handler.go
692 > // If ai is nil, the activity has already been canceled/completed/timedout. The cancel request
693 > // will be recorded in the history, but no further action will be taken.
694 > if ai.StartedEventId == common.EmptyEventID {
695 // We haven't started the activity yet, we can cancel the activity right away and
696 // schedule a workflow task to ensure the workflow makes progress.
706 }
707 handler.activityNotStartedCancelled = true
708 > } else if ai.WorkerControlTaskQueue != "" { workflow_task_completed_handler.go
709 if ai.StartedClock == nil {
710 // StartedClock is nil when the activity is not currently running on a worker
752 }
753 }
754 > return actCancelReqEvent, nil workflow_task_completed_handler.go
755 }
756
757 // flushWorkerCommandsTasks creates WorkerCommandsTasks for all collected worker commands,
758 // batched by control queue.
759 > func (handler *workflowTaskCompletedHandler) flushWorkerCommandsTasks() error { workflow_task_completed_handler.go
760 > for controlQueue, commands := range handler.pendingWorkerCommandsByControlQueue {
761 if err := handler.mutableState.AddWorkerCommandsTasks(
762 commands,
1548 func (handler *workflowTaskCompletedHandler) validateCommandAttr(
1549 validationFn commandAttrValidationFn,
1551 >
1552 > return handler.failWorkflowTaskOnInvalidArgument(validationFn())
1553 > }
1554
1555 func (handler *workflowTaskCompletedHandler) failWorkflowTaskOnInvalidArgument(
1556 wtFailedCause enumspb.WorkflowTaskFailedCause,
1557 err error,
1559 > var invalidArgument *serviceerror.InvalidArgument
1560 > if errors.As(err, &invalidArgument) {
1561 return handler.failWorkflowTask(wtFailedCause, err)
1562 }
1564 }
1565
go.temporal.io/server/common/log/zap_logger.go 109 covered LOC · 30 ranges

Open complete file

58 // NewTestLogger returns a logger for tests
59 // Deprecated: Use testlogger.TestLogger instead.
60 > func NewTestLogger() *zapLogger { zap_logger.go
61 > format := os.Getenv(TestLogFormatEnvVar)
62 > if format == "" {
63 > format = "console"
64 > }
65
66 > logger := BuildZapLogger(Config{ zap_logger.go
67 > Level: os.Getenv(TestLogLevelEnvVar),
68 > Format: format,
69 > Development: true,
70 > })
71 >
72 > // Don't include stack traces for warnings during tests. Only include them for logs with level error and above.
73 > logger = logger.WithOptions(zap.AddStacktrace(zap.ErrorLevel))
74 >
75 > return NewZapLogger(logger)
76 }
77
82
83 // NewZapLogger returns a new zap based logger from zap.Logger
84 > func NewZapLogger(zl *zap.Logger) *zapLogger { zap_logger.go
85 > return &zapLogger{
86 > zl: zl,
87 > skip: skipForZapLogger,
88 > baseZl: zl,
89 > }
90 > }
91
92 // BuildZapLogger builds and returns a new zap.Logger for this logging configuration
93 > func BuildZapLogger(cfg Config) *zap.Logger { zap_logger.go
94 > return buildZapLogger(cfg, true)
95 > }
96
97 > func caller(skip int) string { zap_logger.go
98 > _, path, line, ok := runtime.Caller(skip)
99 > if !ok {
100 return ""
101 }
102 > return path + ":" + strconv.Itoa(line) zap_logger.go
103 }
104
105 > func (l *zapLogger) buildFieldsWithCallAt(tags []tag.Tag) []zap.Field { zap_logger.go
106 > fields := make([]zap.Field, len(tags)+1)
107 > l.fillFields(tags, fields)
108 > fields[len(fields)-1] = zap.String(tag.LoggingCallAtKey, caller(l.skip))
109 > return fields
110 > }
111
112 // fillFields fill fields parameter with fields read from tags. Optimized for performance.
113 > func (l *zapLogger) fillFields(tags []tag.Tag, fields []zap.Field) { zap_logger.go
114 > for i, t := range tags {
115 > if zt, ok := t.(tag.ZapTag); ok { zap_logger.go
116 > fields[i] = zt.Field()
117 > } else {
118 fields[i] = zap.Any(t.Key(), t.Value())
119 }
121 }
122
123 > func setDefaultMsg(msg string) string { zap_logger.go
124 > if msg == "" {
125 > return defaultMsgForEmpty zap_logger.go
126 > }
127 > return msg zap_logger.go
128 }
129
130 > func (l *zapLogger) Debug(msg string, tags ...tag.Tag) { zap_logger.go
131 > if l.zl.Core().Enabled(zap.DebugLevel) {
132 msg = setDefaultMsg(msg)
133 fields := l.buildFieldsWithCallAt(tags)
136 }
137
138 > func (l *zapLogger) Info(msg string, tags ...tag.Tag) { zap_logger.go
139 > if l.zl.Core().Enabled(zap.InfoLevel) {
140 > msg = setDefaultMsg(msg)
141 > fields := l.buildFieldsWithCallAt(tags)
142 > l.zl.Info(msg, fields...)
143 > }
144 }
145
191 //
192 // by deduping "foo" against any existing "foo" tags *only in the former*
193 > func (l *zapLogger) With(tags ...tag.Tag) Logger { zap_logger.go
194 > cloneTags := mergeTags(l.tags, tags)
195 > if l.baseZl == nil {
196 l.baseZl = l.zl
197 }
198 > return l.cloneWithTags(cloneTags) zap_logger.go
199 }
200
201 > func (l *zapLogger) cloneWithTags(tags []tag.Tag) Logger { zap_logger.go
202 > fields := make([]zap.Field, len(tags))
203 > l.fillFields(tags, fields)
204 > zl := l.baseZl.With(fields...)
205 > return &zapLogger{
206 > zl: zl,
207 > skip: l.skip,
208 > baseZl: l.baseZl,
209 > tags: tags,
210 > }
211 > }
212
213 func (l *zapLogger) Skip(extraSkip int) Logger {
219 }
220
221 > func mergeTags(oldTags, newTags []tag.Tag) (outTags []tag.Tag) { zap_logger.go
222 > // Even if oldTags empty, we don't just return newTags because we need to de-dupe it.
223 > outTags = slices.Clone(oldTags)
224 > for _, t := range newTags {
225 > if i := slices.IndexFunc(outTags, func(ti tag.Tag) bool {
226 > return ti.Key() == t.Key() zap_logger.go
227 > }); i >= 0 {
228 > outTags[i] = t zap_logger.go
229 > } else { zap_logger.go
230 > outTags = append(outTags, t)
231 > }
232 }
233 > return outTags zap_logger.go
234 }
235
236 > func buildZapLogger(cfg Config, disableCaller bool) *zap.Logger { zap_logger.go
237 > encodeConfig := DefaultZapEncoderConfig
238 > if disableCaller {
239 > encodeConfig.CallerKey = zapcore.OmitKey
240 > encodeConfig.EncodeCaller = nil
241 > }
242
243 > outputPath := "stderr" zap_logger.go
244 > if len(cfg.OutputFile) > 0 {
245 outputPath = cfg.OutputFile
246 }
247 > if cfg.Stdout { zap_logger.go
248 outputPath = "stdout"
249 }
250 > encoding := "json" zap_logger.go
251 > if cfg.Format == "console" {
252 > encoding = "console" zap_logger.go
253 > }
254 > config := zap.Config{ zap_logger.go
255 > Level: zap.NewAtomicLevelAt(ParseZapLevel(cfg.Level)),
256 > Development: cfg.Development,
257 > Sampling: nil,
258 > Encoding: encoding,
259 > EncoderConfig: encodeConfig,
260 > OutputPaths: []string{outputPath},
261 > ErrorOutputPaths: []string{outputPath},
262 > DisableCaller: disableCaller,
263 > }
264 > logger, _ := config.Build()
265 > return logger
266 }
267
297 }
298
299 > func ParseZapLevel(level string) zapcore.Level { zap_logger.go
300 > switch strings.ToLower(level) {
301 case "debug":
302 return zap.DebugLevel
313 case "fatal":
314 return zap.FatalLevel
315 > default: zap_logger.go
316 > return zap.InfoLevel
317 }
318 }
go.temporal.io/server/service/history/shard/context_testutil.go 106 covered LOC · 9 ranges

Open complete file

56 shardInfo *persistencespb.ShardInfo,
57 config *configs.Config,
58 > ) *ContextTest { context_testutil.go
59 > resourceTest := resourcetest.NewTest(ctrl, primitives.HistoryService)
60 > eventsCache := events.NewMockCache(ctrl)
61 > shard := newTestContext(
62 > resourceTest,
63 > eventsCache,
64 > ContextConfigOverrides{
65 > ShardInfo: shardInfo,
66 > Config: config,
67 > },
68 > )
69 > return &ContextTest{
70 > Resource: resourceTest,
71 > ContextImpl: shard,
72 > MockEventsCache: eventsCache,
73 > }
74 > }
75
76 type ContextConfigOverrides struct {
107 }
108
109 > func newTestContext(t *resourcetest.Test, eventsCache events.Cache, config ContextConfigOverrides) *ContextImpl { context_testutil.go
110 > hostInfoProvider := t.GetHostInfoProvider()
111 > lifecycleCtx, lifecycleCancel := context.WithCancel(context.Background())
112 > if config.ShardInfo.QueueStates == nil {
113 > config.ShardInfo.QueueStates = make(map[int32]*persistencespb.QueueState) context_testutil.go
114 > }
115 > registry := config.Registry context_testutil.go
116 > if registry == nil {
117 > registry = t.GetNamespaceRegistry()
118 > }
119 > clusterMetadata := config.ClusterMetadata
120 > if clusterMetadata == nil {
121 > clusterMetadata = t.GetClusterMetadata()
122 > }
123 > executionManager := config.ExecutionManager
124 > if executionManager == nil {
125 > executionManager = t.ExecutionMgr
126 > }
127 > taskCategoryRegistry := tasks.NewDefaultTaskCategoryRegistry()
128 > taskCategoryRegistry.AddCategory(tasks.CategoryArchival)
129 >
130 > ctx := &ContextImpl{
131 > shardID: config.ShardInfo.GetShardId(),
132 > owner: config.ShardInfo.GetOwner(),
133 > stringRepr: fmt.Sprintf("Shard(%d)", config.ShardInfo.GetShardId()),
134 > executionManager: executionManager,
135 > metricsHandler: t.MetricsHandler,
136 > eventsCache: eventsCache,
137 > config: config.Config,
138 > contextTaggedLogger: t.GetLogger(),
139 > throttledLogger: t.GetThrottledLogger(),
140 > lifecycleCtx: lifecycleCtx,
141 > lifecycleCancel: lifecycleCancel,
142 > queueMetricEmitter: sync.Once{},
143 >
144 > state: contextStateAcquired,
145 > engineFuture: future.NewFuture[historyi.Engine](),
146 > shardInfo: config.ShardInfo,
147 > remoteClusterInfos: make(map[string]*remoteClusterInfo),
148 >
149 > clusterMetadata: clusterMetadata,
150 > timeSource: t.TimeSource,
151 > namespaceRegistry: registry,
152 > stateMachineRegistry: hsm.NewRegistry(),
153 > chasmRegistry: chasm.NewRegistry(t.GetLogger()),
154 > businessIDRateLimiters: cache.New(
155 > config.Config.BusinessIDReuseLimiterCacheSize(),
156 > &cache.Options{TTL: config.Config.BusinessIDReuseLimiterCacheTTL()},
157 > ),
158 > persistenceShardManager: t.GetShardManager(),
159 > clientBean: t.GetClientBean(),
160 > saProvider: t.GetSearchAttributesProvider(),
161 > saMapperProvider: t.GetSearchAttributesMapperProvider(),
162 > historyClient: t.GetHistoryClient(),
163 > payloadSerializer: t.GetPayloadSerializer(),
164 > archivalMetadata: t.GetArchivalMetadata(),
165 > hostInfoProvider: hostInfoProvider,
166 > taskCategoryRegistry: taskCategoryRegistry,
167 > ioSemaphore: locks.NewPrioritySemaphore(1),
168 > }
169 > ctx.taskKeyManager = newTaskKeyManager(
170 > ctx.taskCategoryRegistry,
171 > ctx.timeSource,
172 > config.Config,
173 > ctx.GetLogger(),
174 > func() error {
175 return ctx.renewRangeLocked(false)
176 },
177 )
178 > ctx.taskKeyManager.setRangeID(config.ShardInfo.RangeId) context_testutil.go
179 > ctx.handoverTracker = NewDefaultHandoverTrackerFactory()(HandoverTrackerParams{
180 > ClusterMetadata: clusterMetadata,
181 > GetMaxReplicationTaskID: ctx.getMaxReplicationTaskID,
182 > ErrorByStateFn: ctx.errorByState,
183 > NotifyReplicationFn: ctx.notifyReplicationQueueProcessor,
184 > NamespaceRegistry: registry,
185 > Logger: ctx.contextTaggedLogger,
186 > })
187 > return ctx
188 }
189
190 // SetEngineForTest sets s.engine. Only used by tests.
191 > func (s *ContextTest) SetEngineForTesting(engine historyi.Engine) { context_testutil.go
192 > s.engineFuture.Set(engine, nil)
193 > }
194
195 // SetEventsCacheForTesting sets s.eventsCache. Only used by tests.
196 > func (s *ContextTest) SetEventsCacheForTesting(c events.Cache) { context_testutil.go
197 > // for testing only, will only be called immediately after initialization
198 > s.eventsCache = c
199 > }
200
201 // SetLoggers sets both s.throttledLogger and s.contextTaggedLogger. Only used by tests.
216
217 // SetStateMachineRegistry sets the state machine registry on this shard.
218 > func (s *ContextTest) SetStateMachineRegistry(reg *hsm.Registry) { context_testutil.go
219 > s.stateMachineRegistry = reg
220 > }
221
222 func (s *ContextTest) SetChasmRegistry(reg *chasm.Registry) {
235 // should call that, but integration tests need to do it also to clean up any
236 // background acquireShard goroutines that may exist.
237 > func (s *ContextTest) StopForTest() { context_testutil.go
238 > s.FinishStop()
239 > }
240
241 func (s *StubContext) GetEngine(_ context.Context) (historyi.Engine, error) {
go.temporal.io/server/service/history/workflow/metrics.go 98 covered LOC · 20 ranges

Open complete file

22 historySize int,
23 historyCount int,
24 > ) { metrics.go
25 > handler := metricsHandler.WithTags(metrics.NamespaceTag(namespace.String()))
26 > executionScope := handler.WithTags(metrics.OperationTag(metrics.ExecutionStatsScope))
27 > metrics.HistorySize.With(executionScope).Record(int64(historySize))
28 > metrics.HistoryCount.With(executionScope).Record(int64(historyCount))
29 >
30 > if state == enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED {
31 completionScope := handler.WithTags(metrics.OperationTag(metrics.WorkflowCompletionStatsScope))
32 metrics.HistorySize.With(completionScope).Record(int64(historySize))
40 archetypeID chasm.ArchetypeID,
41 stats *persistence.MutableStateStatistics,
42 > ) { metrics.go
43 > if stats == nil {
44 > return metrics.go
45 > }
46
47 > mutableStateMetricsHandler := metricsHandler metrics.go
48 > if archetypeTag, ok := getArchetypeMetricTag(chasmRegistry, archetypeID); ok {
49 > mutableStateMetricsHandler = mutableStateMetricsHandler.WithTags(archetypeTag)
50 > }
51
52 > batchHandler := mutableStateMetricsHandler.StartBatch("mutable_state_status") metrics.go
53 > defer batchHandler.Close()
54 > metrics.MutableStateSize.With(batchHandler).Record(int64(stats.TotalSize))
55 > metrics.ExecutionInfoSize.With(batchHandler).Record(int64(stats.ExecutionInfoSize))
56 > metrics.ExecutionStateSize.With(batchHandler).Record(int64(stats.ExecutionStateSize))
57 > metrics.ActivityInfoSize.With(batchHandler).Record(int64(stats.ActivityInfoSize))
58 > metrics.ActivityInfoCount.With(batchHandler).Record(int64(stats.ActivityInfoCount))
59 > metrics.TotalActivityCount.With(batchHandler).Record(stats.TotalActivityCount)
60 > metrics.TimerInfoSize.With(batchHandler).Record(int64(stats.TimerInfoSize))
61 > metrics.TimerInfoCount.With(batchHandler).Record(int64(stats.TimerInfoCount))
62 > metrics.TotalUserTimerCount.With(batchHandler).Record(stats.TotalUserTimerCount)
63 > metrics.ChildInfoSize.With(batchHandler).Record(int64(stats.ChildInfoSize))
64 > metrics.ChildInfoCount.With(batchHandler).Record(int64(stats.ChildInfoCount))
65 > metrics.TotalChildExecutionCount.With(batchHandler).Record(stats.TotalChildExecutionCount)
66 > metrics.RequestCancelInfoSize.With(batchHandler).Record(int64(stats.RequestCancelInfoSize))
67 > metrics.RequestCancelInfoCount.With(batchHandler).Record(int64(stats.RequestCancelInfoCount))
68 > metrics.TotalRequestCancelExternalCount.With(batchHandler).Record(stats.TotalRequestCancelExternalCount)
69 > metrics.SignalInfoSize.With(batchHandler).Record(int64(stats.SignalInfoSize))
70 > metrics.SignalInfoCount.With(batchHandler).Record(int64(stats.SignalInfoCount))
71 > metrics.TotalSignalExternalCount.With(batchHandler).Record(stats.TotalSignalExternalCount)
72 > metrics.SignalRequestIDSize.With(batchHandler).Record(int64(stats.SignalRequestIDSize))
73 > metrics.SignalRequestIDCount.With(batchHandler).Record(int64(stats.SignalRequestIDCount))
74 > metrics.TotalSignalCount.With(batchHandler).Record(stats.TotalSignalCount)
75 > metrics.BufferedEventsSize.With(batchHandler).Record(int64(stats.BufferedEventsSize))
76 > metrics.BufferedEventsCount.With(batchHandler).Record(int64(stats.BufferedEventsCount))
77 > metrics.ChasmTotalSize.With(batchHandler).Record(int64(stats.ChasmTotalSize))
78 >
79 > if stats.HistoryStatistics != nil {
80 > metrics.HistorySize.With(metricsHandler).Record(int64(stats.HistoryStatistics.SizeDiff)) metrics.go
81 > metrics.HistoryCount.With(metricsHandler).Record(int64(stats.HistoryStatistics.CountDiff))
82 > }
83
84 > for category, taskCount := range stats.TaskCountByCategory { metrics.go
85 metrics.TaskCount.With(batchHandler).Record(int64(taskCount), metrics.TaskCategoryTag(category))
86 }
90 chasmRegistry *chasm.Registry,
91 archetypeID chasm.ArchetypeID,
92 > ) (metrics.Tag, bool) { metrics.go
93 > switch archetypeID {
94 case chasm.UnspecifiedArchetypeID:
95 return metrics.ArchetypeTag(""), true
96 > case chasm.WorkflowArchetypeID: metrics.go
97 > return metrics.ArchetypeTag(chasm.WorkflowComponentName), true
98 }
99
109 completion completionMetric,
110 config *configs.Config,
111 > ) { metrics.go
112 > // Only emit metrics for Workflows, not other Chasm archetypes
113 > if !completion.isWorkflow {
114 return
115 }
116
117 > handler := GetPerTaskQueueFamilyScope(metricsHandler, namespace, completion.taskQueue, config, metrics.go
118 > metrics.OperationTag(metrics.WorkflowCompletionStatsScope),
119 > metrics.NamespaceStateTag(completion.namespaceState),
120 > metrics.WorkflowTypeTag(completion.workflowTypeName),
121 > )
122 >
123 > closed := true
124 > switch completion.status {
125 case enumspb.WORKFLOW_EXECUTION_STATUS_COMPLETED:
126 metrics.WorkflowSuccessCount.With(handler).Record(1)
135 case enumspb.WORKFLOW_EXECUTION_STATUS_CONTINUED_AS_NEW:
136 metrics.WorkflowContinuedAsNewCount.With(handler).Record(1)
137 > case enumspb.WORKFLOW_EXECUTION_STATUS_UNSPECIFIED, enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING: metrics.go
138 > closed = false
139 }
140 > if closed && completion.startTime != nil && completion.closeTime != nil { metrics.go
141 startTime := completion.startTime.AsTime()
142 closeTime := completion.closeTime.AsTime()
153 config *configs.Config,
154 tags ...metrics.Tag,
155 > ) metrics.Handler { metrics.go
156 > return metrics.GetPerTaskQueueFamilyScope(handler,
157 > namespaceName.String(),
158 > tqid.UnsafeTaskQueueFamily(namespaceName.String(), taskQueueFamily),
159 > config.BreakdownMetricsByTaskQueue(namespaceName.String(), taskQueueFamily, enumspb.TASK_QUEUE_TYPE_WORKFLOW),
160 > tags...,
161 > )
162 > }
163
164 type ActivityExecutionStatus int
191 completion ActivityCompletionMetrics,
192 tags ...metrics.Tag,
193 > ) { metrics.go
194 > metricsHandler := GetPerTaskQueueFamilyScope(
195 > shard.GetMetricsHandler(),
196 > namespaceName,
197 > taskQueue,
198 > shard.GetConfig(),
199 > tags...,
200 > )
201 >
202 > now := shard.GetTimeSource().Now()
203 > if completion.Status != ActivityStatusTimeout &&
204 > !completion.AttemptStartedTime.IsZero() &&
205 > !completion.AttemptStartedTime.After(now) {
206 > latency := now.Sub(completion.AttemptStartedTime) metrics.go
207 > // ActivityE2ELatency is deprecated due to its inaccurate naming. It captures the attempt duration instead of an end-to-end duration as its name suggests. For now record both metrics
208 > metrics.ActivityE2ELatency.With(metricsHandler).Record(latency)
209 > metrics.ActivityStartToCloseLatency.With(metricsHandler).Record(latency)
210 > }
211
212 // Record true end-to-end duration only for terminal states (includes retries and backoffs)
213 > if completion.Closed && !completion.FirstScheduledTime.IsZero() { metrics.go
214 > scheduleToCloseLatency := now.Sub(completion.FirstScheduledTime) metrics.go
215 > metrics.ActivityScheduleToCloseLatency.With(metricsHandler).Record(scheduleToCloseLatency)
216 > }
217
218 > switch completion.Status { metrics.go
219 case ActivityStatusFailed:
220 metrics.ActivityTaskFail.With(metricsHandler).Record(1)
222 metrics.ActivityFail.With(metricsHandler).Record(1)
223 }
224 > case ActivityStatusCanceled: metrics.go
225 > metrics.ActivityCancel.With(metricsHandler).Record(1)
226 case ActivityStatusSucceeded:
227 metrics.ActivitySuccess.With(metricsHandler).Record(1)
go.temporal.io/server/api/historyservice/v1/request_response.pb.go 85 covered LOC · 11 ranges

Open complete file

244 }
245
246 > func (x *StartWorkflowExecutionRequest) GetStartRequest() *v1.StartWorkflowExecutionRequest { request_response.pb.go
247 > if x != nil {
248 > return x.StartRequest
249 > }
250 return nil
251 }
252
253 > func (x *StartWorkflowExecutionRequest) GetParentExecutionInfo() *v11.ParentExecutionInfo { request_response.pb.go
254 > if x != nil {
255 > return x.ParentExecutionInfo
256 > }
257 return nil
258 }
259
260 > func (x *StartWorkflowExecutionRequest) GetAttempt() int32 { request_response.pb.go
261 > if x != nil {
262 > return x.Attempt
263 > }
264 return 0
265 }
279 }
280
281 > func (x *StartWorkflowExecutionRequest) GetContinuedFailure() *v13.Failure { request_response.pb.go
282 > if x != nil {
283 > return x.ContinuedFailure
284 > }
285 return nil
286 }
321 }
322
323 > func (x *StartWorkflowExecutionRequest) GetVersioningOverride() *v15.VersioningOverride { request_response.pb.go
324 > if x != nil {
325 > return x.VersioningOverride
326 > }
327 return nil
328 }
356 }
357
358 > func (x *StartWorkflowExecutionRequest) GetTimeSkippingStatePropagation() *v14.TimeSkippingStatePropagation { request_response.pb.go
359 > if x != nil {
360 > return x.TimeSkippingStatePropagation
361 > }
362 return nil
363 }
2069 }
2070
2071 > func (x *RespondWorkflowTaskCompletedRequest) GetNamespaceId() string { request_response.pb.go
2072 > if x != nil {
2073 > return x.NamespaceId
2074 > }
2075 return ""
2076 }
2077
2078 > func (x *RespondWorkflowTaskCompletedRequest) GetCompleteRequest() *v1.RespondWorkflowTaskCompletedRequest { request_response.pb.go
2079 > if x != nil {
2080 > return x.CompleteRequest
2081 > }
2082 return nil
2083 }
2400 }
2401
2402 > func (x *RecordActivityTaskHeartbeatRequest) GetNamespaceId() string { request_response.pb.go
2403 > if x != nil {
2404 > return x.NamespaceId
2405 > }
2406 return ""
2407 }
2688 }
2689
2690 > func (x *RespondActivityTaskCanceledRequest) GetNamespaceId() string { request_response.pb.go
2691 > if x != nil {
2692 > return x.NamespaceId
2693 > }
2694 return ""
2695 }
11956 }
11957
11958 > func init() { file_temporal_server_api_historyservice_v1_request_response_proto_init() } request_response.pb.go
11959 > func file_temporal_server_api_historyservice_v1_request_response_proto_init() {
11960 > if File_temporal_server_api_historyservice_v1_request_response_proto != nil {
11961 > return
11962 > }
11963 > file_temporal_server_api_historyservice_v1_request_response_proto_msgTypes[107].OneofWrappers = []any{
11964 > (*StreamWorkflowReplicationMessagesRequest_SyncReplicationState)(nil),
11965 > }
11966 > file_temporal_server_api_historyservice_v1_request_response_proto_msgTypes[108].OneofWrappers = []any{
11967 > (*StreamWorkflowReplicationMessagesResponse_Messages)(nil),
11968 > }
11969 > file_temporal_server_api_historyservice_v1_request_response_proto_msgTypes[134].OneofWrappers = []any{
11970 > (*CompleteNexusOperationChasmRequest_Success)(nil),
11971 > (*CompleteNexusOperationChasmRequest_Failure)(nil),
11972 > }
11973 > file_temporal_server_api_historyservice_v1_request_response_proto_msgTypes[136].OneofWrappers = []any{
11974 > (*CompleteNexusOperationRequest_Success)(nil),
11975 > (*CompleteNexusOperationRequest_Failure)(nil),
11976 > }
11977 > file_temporal_server_api_historyservice_v1_request_response_proto_msgTypes[162].OneofWrappers = []any{
11978 > (*ExecuteMultiOperationRequest_Operation_StartWorkflow)(nil),
11979 > (*ExecuteMultiOperationRequest_Operation_UpdateWorkflow)(nil),
11980 > }
11981 > file_temporal_server_api_historyservice_v1_request_response_proto_msgTypes[163].OneofWrappers = []any{
11982 > (*ExecuteMultiOperationResponse_Response_StartWorkflow)(nil),
11983 > (*ExecuteMultiOperationResponse_Response_UpdateWorkflow)(nil),
11984 > }
11985 > type x struct{}
11986 > out := protoimpl.TypeBuilder{
11987 > File: protoimpl.DescBuilder{
11988 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
11989 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_historyservice_v1_request_response_proto_rawDesc), len(file_temporal_server_api_historyservice_v1_request_response_proto_rawDesc)),
11990 > NumEnums: 0,
11991 > NumMessages: 171,
11992 > NumExtensions: 1,
11993 > NumServices: 0,
11994 > },
11995 > GoTypes: file_temporal_server_api_historyservice_v1_request_response_proto_goTypes,
11996 > DependencyIndexes: file_temporal_server_api_historyservice_v1_request_response_proto_depIdxs,
11997 > MessageInfos: file_temporal_server_api_historyservice_v1_request_response_proto_msgTypes,
11998 > ExtensionInfos: file_temporal_server_api_historyservice_v1_request_response_proto_extTypes,
11999 > }.Build()
12000 > File_temporal_server_api_historyservice_v1_request_response_proto = out.File
12001 > file_temporal_server_api_historyservice_v1_request_response_proto_goTypes = nil
12002 > file_temporal_server_api_historyservice_v1_request_response_proto_depIdxs = nil
12003 }
go.temporal.io/server/api/persistence/v1/predicates.pb.go 82 covered LOC · 22 ranges

Open complete file

57 func (*Predicate) ProtoMessage() {}
58
59 > func (x *Predicate) ProtoReflect() protoreflect.Message { predicates.pb.go
60 > mi := &file_temporal_server_api_persistence_v1_predicates_proto_msgTypes[0]
61 > if x != nil {
62 > ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
63 > if ms.LoadMessageInfo() == nil {
64 > ms.StoreMessageInfo(mi)
65 > }
66 > return ms
67 }
68 return mi.MessageOf(x)
261 func (*UniversalPredicateAttributes) ProtoMessage() {}
262
263 > func (x *UniversalPredicateAttributes) ProtoReflect() protoreflect.Message { predicates.pb.go
264 > mi := &file_temporal_server_api_persistence_v1_predicates_proto_msgTypes[1]
265 > if x != nil {
266 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
267 if ms.LoadMessageInfo() == nil {
297 func (*EmptyPredicateAttributes) ProtoMessage() {}
298
299 > func (x *EmptyPredicateAttributes) ProtoReflect() protoreflect.Message { predicates.pb.go
300 > mi := &file_temporal_server_api_persistence_v1_predicates_proto_msgTypes[2]
301 > if x != nil {
302 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
303 if ms.LoadMessageInfo() == nil {
334 func (*AndPredicateAttributes) ProtoMessage() {}
335
336 > func (x *AndPredicateAttributes) ProtoReflect() protoreflect.Message { predicates.pb.go
337 > mi := &file_temporal_server_api_persistence_v1_predicates_proto_msgTypes[3]
338 > if x != nil {
339 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
340 if ms.LoadMessageInfo() == nil {
378 func (*OrPredicateAttributes) ProtoMessage() {}
379
380 > func (x *OrPredicateAttributes) ProtoReflect() protoreflect.Message { predicates.pb.go
381 > mi := &file_temporal_server_api_persistence_v1_predicates_proto_msgTypes[4]
382 > if x != nil {
383 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
384 if ms.LoadMessageInfo() == nil {
422 func (*NotPredicateAttributes) ProtoMessage() {}
423
424 > func (x *NotPredicateAttributes) ProtoReflect() protoreflect.Message { predicates.pb.go
425 > mi := &file_temporal_server_api_persistence_v1_predicates_proto_msgTypes[5]
426 > if x != nil {
427 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
428 if ms.LoadMessageInfo() == nil {
466 func (*NamespaceIdPredicateAttributes) ProtoMessage() {}
467
468 > func (x *NamespaceIdPredicateAttributes) ProtoReflect() protoreflect.Message { predicates.pb.go
469 > mi := &file_temporal_server_api_persistence_v1_predicates_proto_msgTypes[6]
470 > if x != nil {
471 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
472 if ms.LoadMessageInfo() == nil {
510 func (*TaskTypePredicateAttributes) ProtoMessage() {}
511
512 > func (x *TaskTypePredicateAttributes) ProtoReflect() protoreflect.Message { predicates.pb.go
513 > mi := &file_temporal_server_api_persistence_v1_predicates_proto_msgTypes[7]
514 > if x != nil {
515 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
516 if ms.LoadMessageInfo() == nil {
554 func (*DestinationPredicateAttributes) ProtoMessage() {}
555
556 > func (x *DestinationPredicateAttributes) ProtoReflect() protoreflect.Message { predicates.pb.go
557 > mi := &file_temporal_server_api_persistence_v1_predicates_proto_msgTypes[8]
558 > if x != nil {
559 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
560 if ms.LoadMessageInfo() == nil {
598 func (*OutboundTaskGroupPredicateAttributes) ProtoMessage() {}
599
600 > func (x *OutboundTaskGroupPredicateAttributes) ProtoReflect() protoreflect.Message { predicates.pb.go
601 > mi := &file_temporal_server_api_persistence_v1_predicates_proto_msgTypes[9]
602 > if x != nil {
603 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
604 if ms.LoadMessageInfo() == nil {
642 func (*OutboundTaskPredicateAttributes) ProtoMessage() {}
643
644 > func (x *OutboundTaskPredicateAttributes) ProtoReflect() protoreflect.Message { predicates.pb.go
645 > mi := &file_temporal_server_api_persistence_v1_predicates_proto_msgTypes[10]
646 > if x != nil {
647 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
648 if ms.LoadMessageInfo() == nil {
828 }
829
830 > func init() { file_temporal_server_api_persistence_v1_predicates_proto_init() } predicates.pb.go
831 > func file_temporal_server_api_persistence_v1_predicates_proto_init() {
832 > if File_temporal_server_api_persistence_v1_predicates_proto != nil {
833 > return
834 > }
835 > file_temporal_server_api_persistence_v1_predicates_proto_msgTypes[0].OneofWrappers = []any{
836 > (*Predicate_UniversalPredicateAttributes)(nil),
837 > (*Predicate_EmptyPredicateAttributes)(nil),
838 > (*Predicate_AndPredicateAttributes)(nil),
839 > (*Predicate_OrPredicateAttributes)(nil),
840 > (*Predicate_NotPredicateAttributes)(nil),
841 > (*Predicate_NamespaceIdPredicateAttributes)(nil),
842 > (*Predicate_TaskTypePredicateAttributes)(nil),
843 > (*Predicate_DestinationPredicateAttributes)(nil),
844 > (*Predicate_OutboundTaskGroupPredicateAttributes)(nil),
845 > (*Predicate_OutboundTaskPredicateAttributes)(nil),
846 > }
847 > type x struct{}
848 > out := protoimpl.TypeBuilder{
849 > File: protoimpl.DescBuilder{
850 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
851 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_predicates_proto_rawDesc), len(file_temporal_server_api_persistence_v1_predicates_proto_rawDesc)),
852 > NumEnums: 0,
853 > NumMessages: 12,
854 > NumExtensions: 0,
855 > NumServices: 0,
856 > },
857 > GoTypes: file_temporal_server_api_persistence_v1_predicates_proto_goTypes,
858 > DependencyIndexes: file_temporal_server_api_persistence_v1_predicates_proto_depIdxs,
859 > MessageInfos: file_temporal_server_api_persistence_v1_predicates_proto_msgTypes,
860 > }.Build()
861 > File_temporal_server_api_persistence_v1_predicates_proto = out.File
862 > file_temporal_server_api_persistence_v1_predicates_proto_goTypes = nil
863 > file_temporal_server_api_persistence_v1_predicates_proto_depIdxs = nil
864 }
go.temporal.io/server/api/persistence/v1/hsm.pb.go 79 covered LOC · 24 ranges

Open complete file

147 func (*StateMachineMap) ProtoMessage() {}
148
149 > func (x *StateMachineMap) ProtoReflect() protoreflect.Message { hsm.pb.go
150 > mi := &file_temporal_server_api_persistence_v1_hsm_proto_msgTypes[1]
151 > if x != nil {
152 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
153 if ms.LoadMessageInfo() == nil {
156 return ms
157 }
158 > return mi.MessageOf(x) hsm.pb.go
159 }
160
272 func (*StateMachineRef) ProtoMessage() {}
273
274 > func (x *StateMachineRef) ProtoReflect() protoreflect.Message { hsm.pb.go
275 > mi := &file_temporal_server_api_persistence_v1_hsm_proto_msgTypes[3]
276 > if x != nil {
277 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
278 if ms.LoadMessageInfo() == nil {
281 return ms
282 }
283 > return mi.MessageOf(x) hsm.pb.go
284 }
285
349 func (*StateMachineTaskInfo) ProtoMessage() {}
350
351 > func (x *StateMachineTaskInfo) ProtoReflect() protoreflect.Message { hsm.pb.go
352 > mi := &file_temporal_server_api_persistence_v1_hsm_proto_msgTypes[4]
353 > if x != nil {
354 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
355 if ms.LoadMessageInfo() == nil {
358 return ms
359 }
360 > return mi.MessageOf(x) hsm.pb.go
361 }
362
416 func (*StateMachineTimerGroup) ProtoMessage() {}
417
418 > func (x *StateMachineTimerGroup) ProtoReflect() protoreflect.Message { hsm.pb.go
419 > mi := &file_temporal_server_api_persistence_v1_hsm_proto_msgTypes[5]
420 > if x != nil {
421 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
422 if ms.LoadMessageInfo() == nil {
425 return ms
426 }
427 > return mi.MessageOf(x) hsm.pb.go
428 }
429
478 func (*VersionedTransition) ProtoMessage() {}
479
480 > func (x *VersionedTransition) ProtoReflect() protoreflect.Message { hsm.pb.go
481 > mi := &file_temporal_server_api_persistence_v1_hsm_proto_msgTypes[6]
482 > if x != nil {
483 > ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) hsm.pb.go
484 > if ms.LoadMessageInfo() == nil {
485 > ms.StoreMessageInfo(mi)
486 > }
487 > return ms
488 }
489 > return mi.MessageOf(x) hsm.pb.go
490 }
491
495 }
496
497 > func (x *VersionedTransition) GetNamespaceFailoverVersion() int64 { hsm.pb.go
498 > if x != nil {
499 > return x.NamespaceFailoverVersion hsm.pb.go
500 > }
501 > return 0 hsm.pb.go
502 }
503
504 > func (x *VersionedTransition) GetTransitionCount() int64 { hsm.pb.go
505 > if x != nil {
506 > return x.TransitionCount hsm.pb.go
507 > }
508 > return 0 hsm.pb.go
509 }
510
531 func (*StateMachineTombstoneBatch) ProtoMessage() {}
532
533 > func (x *StateMachineTombstoneBatch) ProtoReflect() protoreflect.Message { hsm.pb.go
534 > mi := &file_temporal_server_api_persistence_v1_hsm_proto_msgTypes[7]
535 > if x != nil {
536 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
537 if ms.LoadMessageInfo() == nil {
540 return ms
541 }
542 > return mi.MessageOf(x) hsm.pb.go
543 }
544
592 func (*StateMachineTombstone) ProtoMessage() {}
593
594 > func (x *StateMachineTombstone) ProtoReflect() protoreflect.Message { hsm.pb.go
595 > mi := &file_temporal_server_api_persistence_v1_hsm_proto_msgTypes[8]
596 > if x != nil {
597 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
598 if ms.LoadMessageInfo() == nil {
601 return ms
602 }
603 > return mi.MessageOf(x) hsm.pb.go
604 }
605
763 func (*StateMachinePath) ProtoMessage() {}
764
765 > func (x *StateMachinePath) ProtoReflect() protoreflect.Message { hsm.pb.go
766 > mi := &file_temporal_server_api_persistence_v1_hsm_proto_msgTypes[9]
767 > if x != nil {
768 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
769 if ms.LoadMessageInfo() == nil {
772 return ms
773 }
774 > return mi.MessageOf(x) hsm.pb.go
775 }
776
895 }
896
897 > func init() { file_temporal_server_api_persistence_v1_hsm_proto_init() } hsm.pb.go
898 > func file_temporal_server_api_persistence_v1_hsm_proto_init() {
899 > if File_temporal_server_api_persistence_v1_hsm_proto != nil {
900 > return
901 > }
902 > file_temporal_server_api_persistence_v1_hsm_proto_msgTypes[8].OneofWrappers = []any{
903 > (*StateMachineTombstone_ActivityScheduledEventId)(nil),
904 > (*StateMachineTombstone_TimerId)(nil),
905 > (*StateMachineTombstone_ChildExecutionInitiatedEventId)(nil),
906 > (*StateMachineTombstone_RequestCancelInitiatedEventId)(nil),
907 > (*StateMachineTombstone_SignalExternalInitiatedEventId)(nil),
908 > (*StateMachineTombstone_UpdateId)(nil),
909 > (*StateMachineTombstone_StateMachinePath)(nil),
910 > (*StateMachineTombstone_ChasmNodePath)(nil),
911 > }
912 > type x struct{}
913 > out := protoimpl.TypeBuilder{
914 > File: protoimpl.DescBuilder{
915 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
916 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_hsm_proto_rawDesc), len(file_temporal_server_api_persistence_v1_hsm_proto_rawDesc)),
917 > NumEnums: 0,
918 > NumMessages: 12,
919 > NumExtensions: 0,
920 > NumServices: 0,
921 > },
922 > GoTypes: file_temporal_server_api_persistence_v1_hsm_proto_goTypes,
923 > DependencyIndexes: file_temporal_server_api_persistence_v1_hsm_proto_depIdxs,
924 > MessageInfos: file_temporal_server_api_persistence_v1_hsm_proto_msgTypes,
925 > }.Build()
926 > File_temporal_server_api_persistence_v1_hsm_proto = out.File
927 > file_temporal_server_api_persistence_v1_hsm_proto_goTypes = nil
928 > file_temporal_server_api_persistence_v1_hsm_proto_depIdxs = nil
929 }
go.temporal.io/server/common/log/tag/tags.go 78 covered LOC · 26 ranges

Open complete file

58
59 // Timestamp returns tag for Timestamp
60 > func Timestamp(timestamp time.Time) ZapTag { tags.go
61 > return NewTimeTag("timestamp", timestamp)
62 > }
63
64 // RequestID returns tag for RequestID
70
71 // WorkflowAction returns tag for WorkflowAction
72 > func workflowAction(action string) ZapTag { tags.go
73 > return NewStringTag("wf-action", action)
74 > }
75
76 // WorkflowListFilterType returns tag for WorkflowListFilterType
77 > func workflowListFilterType(listFilterType string) ZapTag { tags.go
78 > return NewStringTag("wf-list-filter-type", listFilterType)
79 > }
80
81 // general
108 // WorkflowID returns tag for WorkflowID
109 // TODO: Rename to BusinessID.
110 > func WorkflowID(workflowID string) ZapTag { tags.go
111 > return NewStringTag(WorkflowIDKey, workflowID)
112 > }
113
114 // WorkflowType returns tag for WorkflowType
124 // WorkflowRunID returns tag for WorkflowRunID
125 // TODO: Rename to RunID
126 > func WorkflowRunID(runID string) ZapTag { tags.go
127 > return NewStringTag(WorkflowRunIDKey, runID)
128 > }
129
130 // WorkflowNewRunID returns tag for WorkflowNewRunID
169
170 // WorkflowTaskTimeout returns tag for WorkflowTaskTimeoutSeconds
171 > func WorkflowTaskTimeout(s time.Duration) ZapTag { tags.go
172 > return NewDurationTag("workflow-task-timeout", s)
173 > }
174
175 // QueryID returns tag for QueryID
187 // WorkflowNamespaceID returns tag for WorkflowNamespaceID
188 // TODO: Rename to NamespaceID
189 > func WorkflowNamespaceID(namespaceID string) ZapTag { tags.go
190 > return NewStringTag("wf-namespace-id", namespaceID)
191 > }
192
193 // WorkflowNamespace returns tag for WorkflowNamespace
194 > func WorkflowNamespace(namespace string) ZapTag { tags.go
195 > return NewStringTag("wf-namespace", namespace)
196 > }
197
198 // WorkflowNamespaceIDs returns tag for WorkflowNamespaceIDs
209
210 // WorkflowScheduledEventID returns tag for WorkflowScheduledEventID
211 > func WorkflowScheduledEventID(scheduledEventID int64) ZapTag { tags.go
212 > return NewInt64("wf-scheduled-event-id", scheduledEventID)
213 > }
214
215 // WorkflowStartedEventID returns tag for WorkflowStartedEventID
216 > func WorkflowStartedEventID(startedEventID int64) ZapTag { tags.go
217 > return NewInt64("wf-started-event-id", startedEventID)
218 > }
219
220 // WorkflowStartedTimestamp returns tag for WorkflowStartedTimestamp
221 > func WorkflowStartedTimestamp(t time.Time) ZapTag { tags.go
222 > return NewTimeTag("wf-started-timestamp", t)
223 > }
224
225 // WorkflowInitiatedID returns tag for WorkflowInitiatedID
376
377 // Component returns tag for Component
378 > func component(component string) ZapTag { tags.go
379 > return NewStringTag("component", component)
380 > }
381
382 // Lifecycle returns tag for Lifecycle
383 > func lifecycle(lifecycle string) ZapTag { tags.go
384 > return NewStringTag("lifecycle", lifecycle)
385 > }
386
387 // StoreOperation returns tag for StoreOperation
388 > func storeOperation(storeOperation string) ZapTag { tags.go
389 > return NewStringTag("store-operation", storeOperation)
390 > }
391
392 // OperationResult returns tag for OperationResult
393 > func operationResult(operationResult string) ZapTag { tags.go
394 > return NewStringTag("operation-result", operationResult)
395 > }
396
397 // ErrorType returns tag for ErrorType
401
402 // errorType returns tag for ErrorType given a string
403 > func errorType(errorType string) ZapTag { tags.go
404 > return NewStringTag("error-type", errorType)
405 > }
406
407 // Shardupdate returns tag for Shardupdate
408 > func shardupdate(shardupdate string) ZapTag { tags.go
409 > return NewStringTag("shard-update", shardupdate)
410 > }
411
412 // scope returns a tag for scope
413 // Pre-defined scope tags are in values.go.
414 > func scope(scope string) ZapTag { tags.go
415 > return NewStringTag("scope", scope)
416 > }
417
418 // general
489
490 // CursorTimestamp returns tag for CursorTimestamp
491 > func CursorTimestamp(timestamp time.Time) ZapTag { tags.go
492 > return NewTimeTag("cursor-timestamp", timestamp)
493 > }
494
495 // MetricScope returns tag for MetricScope
524
525 // Number returns tag for Number
526 > func Number(n int64) ZapTag { tags.go
527 > return NewInt64("number", n)
528 > }
529
530 // NextNumber returns tag for NextNumber
531 > func NextNumber(n int64) ZapTag { tags.go
532 > return NewInt64("next-number", n)
533 > }
534
535 // ServerName returns tag for ServerName
620
621 // TaskID returns tag for TaskID
622 > func TaskID(taskID int64) ZapTag { tags.go
623 > return NewInt64("queue-task-id", taskID)
624 > }
625
626 // TaskKey returns tag for TaskKey
634 }
635
636 > func TaskType(taskType enumsspb.TaskType) ZapTag { tags.go
637 > return NewStringTag("queue-task-type", taskType.String())
638 > }
639
640 func TaskCategoryID(taskCategoryID int) ZapTag {
674
675 // Attempt returns tag for Attempt
676 > func Attempt(attempt int32) ZapTag { tags.go
677 > return NewInt32("attempt", attempt)
678 > }
679
680 // UnexpectedErrorAttempts returns tag for UnexpectedErrorAttempts
683 }
684
685 > func WorkflowTaskType(wtType string) ZapTag { tags.go
686 > return NewStringTag("wt-type", wtType)
687 > }
688
689 // AttemptCount returns tag for AttemptCount
934
935 // WorkflowTaskRequestId returns a tag for workflow task RequestId
936 > func WorkflowTaskRequestId(s string) ZapTag { tags.go
937 > return NewStringTag("workflow-task-request-id", s)
938 > }
939
940 // AckLevel returns tag for ack level
go.temporal.io/server/service/history/events/notifier.go 72 covered LOC · 14 ranges

Open complete file

81 versionHistories *historyspb.VersionHistories,
82 transitionHistory []*persistencespb.VersionedTransition,
83 > ) *Notification { notifier.go
84 >
85 > return &Notification{
86 > ID: definition.NewWorkflowKey(
87 > namespaceID,
88 > workflowExecution.GetWorkflowId(),
89 > workflowExecution.GetRunId(),
90 > ),
91 > LastFirstEventID: lastFirstEventID,
92 > LastFirstEventTxnID: lastFirstEventTxnID,
93 > NextEventID: nextEventID,
94 > PreviousStartedEventID: previousStartedEventID,
95 > WorkflowState: workflowState,
96 > WorkflowStatus: workflowStatus,
97 > VersionHistories: versionhistory.CopyVersionHistories(versionHistories),
98 > TransitionHistory: transitionhistory.CopyVersionedTransitions(transitionHistory),
99 > }
100 > }
101
102 func NewNotifier(
104 metricsHandler metrics.Handler,
105 workflowIDToShardID func(namespace.ID, string) int32,
106 > ) *NotifierImpl { notifier.go
107 >
108 > hashFn := func(key any) uint32 {
109 > notification, ok := key.(Notification) notifier.go
110 > if !ok {
111 > return 0
112 > }
113 return uint32(workflowIDToShardID(namespace.ID(notification.ID.NamespaceID), notification.ID.WorkflowID))
114 }
115 > return &NotifierImpl{ notifier.go
116 > timeSource: timeSource,
117 > metricsHandler: metricsHandler.WithTags(metrics.OperationTag(metrics.HistoryEventNotificationScope)),
118 > status: common.DaemonStatusInitialized,
119 > closeChan: make(chan bool),
120 > eventsChan: make(chan *Notification, eventsChanSize),
121 >
122 > workflowIDToShardID: workflowIDToShardID,
123 >
124 > eventsPubsubs: collection.NewShardedConcurrentTxMap(1024, hashFn),
125 > }
126 }
127
178 }
179
180 > func (notifier *NotifierImpl) dispatchHistoryEventNotification(event *Notification) { notifier.go
181 > identifier := event.ID
182 >
183 > startTime := time.Now().UTC()
184 > defer func() {
185 > metrics.HistoryEventNotificationFanoutLatency.With(notifier.metricsHandler).Record(time.Since(startTime))
186 > }()
187 > _, _, _ = notifier.eventsPubsubs.GetAndDo(identifier, func(key any, value any) error {
188 subscribers := value.(map[string]chan *Notification)
189
200 }
201
202 > func (notifier *NotifierImpl) enqueueHistoryEventNotification(event *Notification) { notifier.go
203 > // set the Timestamp just before enqueuing the event
204 > event.Timestamp = notifier.timeSource.Now()
205 > select {
206 > case notifier.eventsChan <- event:
207 default:
208 // in case the channel is already filled with message
212 }
213
214 > func (notifier *NotifierImpl) dequeueHistoryEventNotifications() { notifier.go
215 > for {
216 > // send out metrics about the current number of messages in flight
217 > metrics.HistoryEventNotificationInFlightMessageGauge.With(notifier.metricsHandler).Record(float64(len(notifier.eventsChan)))
218 > select {
219 > case event := <-notifier.eventsChan: notifier.go
220 > // send out metrics about message processing delay
221 > timeelapsed := time.Since(event.Timestamp)
222 > metrics.HistoryEventNotificationQueueingLatency.With(notifier.metricsHandler).Record(timeelapsed)
223 >
224 > notifier.dispatchHistoryEventNotification(event)
225 > case <-notifier.closeChan: notifier.go
226 > // shutdown
227 > return
228 }
229 }
230 }
231
232 > func (notifier *NotifierImpl) Start() { notifier.go
233 > if !atomic.CompareAndSwapInt32(&notifier.status, common.DaemonStatusInitialized, common.DaemonStatusStarted) {
234 return
235 }
236 > go notifier.dequeueHistoryEventNotifications() notifier.go
237 }
238
239 > func (notifier *NotifierImpl) Stop() { notifier.go
240 > if !atomic.CompareAndSwapInt32(&notifier.status, common.DaemonStatusStarted, common.DaemonStatusStopped) {
241 return
242 }
243 > close(notifier.closeChan) notifier.go
244 }
245
246 > func (notifier *NotifierImpl) NotifyNewHistoryEvent(event *Notification) { notifier.go
247 > notifier.enqueueHistoryEventNotification(event)
248 > }
go.temporal.io/server/service/history/api/respondactivitytaskcanceled/api.go 66 covered LOC · 13 ranges

Open complete file

24 shard historyi.ShardContext,
25 workflowConsistencyChecker api.WorkflowConsistencyChecker,
26 > ) (resp *historyservice.RespondActivityTaskCanceledResponse, retError error) { api.go
27 > request := req.CancelRequest
28 > tokenSerializer := tasktoken.NewSerializer()
29 > token, err0 := tokenSerializer.Deserialize(request.TaskToken)
30 > if err0 != nil {
31 return nil, consts.ErrDeserializingToken
32 }
33
34 > namespaceEntry, err := api.GetActiveNamespace(shard, namespace.ID(req.GetNamespaceId()), token.WorkflowId) api.go
35 > if err != nil {
36 return nil, err
37 }
38 > namespaceName := namespaceEntry.Name() api.go
39 > if err := api.SetActivityTaskRunID(ctx, token, workflowConsistencyChecker); err != nil {
40 return nil, err
41 }
42
43 > var attemptStartedTime time.Time api.go
44 > var firstScheduledTime time.Time
45 > var taskQueue string
46 > var workflowTypeName string
47 > var versioningBehavior enumspb.VersioningBehavior
48 > err = api.GetAndUpdateWorkflowWithNew(
49 > ctx,
50 > token.Clock,
51 > definition.NewWorkflowKey(
52 > token.NamespaceId,
53 > token.WorkflowId,
54 > token.RunId,
55 > ),
56 > func(workflowLease api.WorkflowLease) (*api.UpdateWorkflowAction, error) {
57 > mutableState := workflowLease.GetMutableState()
58 > workflowTypeName = mutableState.GetWorkflowType().GetName()
59 > if !mutableState.IsWorkflowExecutionRunning() {
60 return nil, consts.ErrWorkflowCompleted
61 }
62
63 > scheduledEventID := token.GetScheduledEventId() api.go
64 > if scheduledEventID == common.EmptyEventID { // client call CompleteActivityById, so get scheduledEventID by activityID
65 scheduledEventID, err0 = api.GetActivityScheduledEventID(token.GetActivityId(), mutableState)
66 if err0 != nil {
68 }
69 }
70 > ai, isRunning := mutableState.GetActivityInfo(scheduledEventID) api.go
71 >
72 > // First check to see if cache needs to be refreshed as we could potentially have stale workflow execution in
73 > // some extreme cassandra failure cases.
74 > if !isRunning && scheduledEventID >= mutableState.GetNextEventID() {
75 metrics.StaleMutableStateCounter.With(shard.GetMetricsHandler()).Record(
76 1,
79 }
80
81 > if !isRunning || api.IsActivityTaskNotFoundForToken(token, ai, nil) { api.go
82 return nil, consts.ErrActivityTaskNotFound
83 }
84
85 // sanity check if activity is requested to be cancelled
86 > if !ai.CancelRequested { api.go
87 return nil, consts.ErrActivityTaskNotCancelRequested
88 }
89
90 > if _, err := mutableState.AddActivityTaskCanceledEvent( api.go
91 > scheduledEventID,
92 > ai.StartedEventId,
93 > ai.CancelRequestId,
94 > request.Details,
95 > request.Identity); err != nil {
96 // Unable to add ActivityTaskCanceled event to history
97 return nil, err
98 }
99
100 > attemptStartedTime = timestamp.TimeValue(ai.StartedTime) api.go
101 > firstScheduledTime = timestamp.TimeValue(ai.FirstScheduledTime)
102 > taskQueue = ai.TaskQueue
103 > versioningBehavior = mutableState.GetEffectiveVersioningBehavior()
104 > return &api.UpdateWorkflowAction{
105 > Noop: false,
106 > CreateWorkflowTask: true,
107 > }, nil
108 },
109 nil,
112 )
113
114 > if err == nil { api.go
115 > workflow.RecordActivityCompletionMetrics( api.go
116 > shard,
117 > namespaceName,
118 > taskQueue,
119 > workflow.ActivityCompletionMetrics{
120 > Status: workflow.ActivityStatusCanceled,
121 > AttemptStartedTime: attemptStartedTime,
122 > FirstScheduledTime: firstScheduledTime,
123 > Closed: true,
124 > },
125 > metrics.OperationTag(metrics.HistoryRespondActivityTaskCanceledScope),
126 > metrics.WorkflowTypeTag(workflowTypeName),
127 > metrics.ActivityTypeTag(token.ActivityType),
128 > metrics.VersioningBehaviorTag(versioningBehavior))
129 > }
130 > return &historyservice.RespondActivityTaskCanceledResponse{}, err api.go
131 }
go.temporal.io/server/service/history/shard/task_key_generator.go 66 covered LOC · 15 ranges

Open complete file

39 logger log.Logger,
40 renewRangeIDFn renewRangeIDFn,
41 > ) *taskKeyGenerator { task_key_generator.go
42 > return &taskKeyGenerator{
43 > nextTaskID: taskIDUninitialized,
44 > exclusiveMaxTaskID: taskIDUninitialized,
45 > rangeSizeBits: rangeSizeBits,
46 > timeSource: timeSource,
47 > logger: logger,
48 > renewRangeIDFn: renewRangeIDFn,
49 > }
50 > }
51
52 func (a *taskKeyGenerator) setTaskKeys(
53 taskMaps ...map[tasks.Category][]tasks.Task,
54 > ) error { task_key_generator.go
55 > now := a.timeSource.Now()
56 > // TODO: Truncation here is just to make sure task scheduled time has the same precision as the old logic.
57 > // Remove this truncation once we validate the rest of the code can worker correctly with higher precision.
58 > a.setTaskMinScheduledTime(now.Truncate(common.ScheduledTaskMinPrecision))
59 >
60 > for _, taskMap := range taskMaps {
61 > for category, tasksByCategory := range taskMap {
62 > isScheduledTask := category.Type() == tasks.CategoryTypeScheduled task_key_generator.go
63 > for _, task := range tasksByCategory {
64 > id, err := a.generateTaskID()
65 > if err != nil {
66 return err
67 }
68 > task.SetTaskID(id) task_key_generator.go
69 >
70 > taskScheduledTime := now
71 > if isScheduledTask {
72 // Persistence might loss precision when saving to DB.
73 // Make the task scheduled time to have the same precision as DB here,
94 }
95 }
96 > task.SetVisibilityTime(taskScheduledTime) task_key_generator.go
97 >
98 > a.logger.Debug("Assigning new task key",
99 > tag.WorkflowNamespaceID(task.GetNamespaceID()),
100 > tag.WorkflowID(task.GetWorkflowID()),
101 > tag.WorkflowRunID(task.GetRunID()),
102 > tag.TaskType(task.GetType()),
103 > tag.TaskID(id),
104 > tag.Timestamp(task.GetVisibilityTime()),
105 > tag.CursorTimestamp(a.taskMinScheduledTime),
106 > )
107 }
108 }
109 }
110
111 > return nil task_key_generator.go
112 }
113
114 func (a *taskKeyGenerator) peekTaskKey(
115 category tasks.Category,
116 > ) tasks.Key { task_key_generator.go
117 > switch category.Type() {
118 > case tasks.CategoryTypeImmediate: task_key_generator.go
119 > return tasks.NewImmediateKey(a.nextTaskID)
120 case tasks.CategoryTypeScheduled:
121 return tasks.NewKey(
130 func (a *taskKeyGenerator) generateTaskKey(
131 category tasks.Category,
132 > ) (tasks.Key, error) { task_key_generator.go
133 > id, err := a.generateTaskID()
134 > if err != nil {
135 return tasks.Key{}, err
136 }
137
138 > switch category.Type() { task_key_generator.go
139 > case tasks.CategoryTypeImmediate:
140 > return tasks.NewImmediateKey(id), nil
141 case tasks.CategoryTypeScheduled:
142 return tasks.NewKey(
149 }
150
151 > func (a *taskKeyGenerator) setRangeID(rangeID int64) { task_key_generator.go
152 > a.nextTaskID = rangeID << a.rangeSizeBits
153 > a.exclusiveMaxTaskID = (rangeID + 1) << a.rangeSizeBits
154 >
155 > a.logger.Info("Task key range updated",
156 > tag.Number(a.nextTaskID),
157 > tag.NextNumber(a.exclusiveMaxTaskID),
158 > )
159 > }
160
161 func (a *taskKeyGenerator) setTaskMinScheduledTime(
162 taskMinScheduledTime time.Time,
164 > a.taskMinScheduledTime = util.MaxTime(a.taskMinScheduledTime, taskMinScheduledTime)
165 > }
166
167 > func (a *taskKeyGenerator) generateTaskID() (int64, error) { task_key_generator.go
168 > if a.nextTaskID == taskIDUninitialized {
169 a.logger.Panic("Range id is not initialized before generating task id")
170 }
171
172 > if a.nextTaskID == a.exclusiveMaxTaskID { task_key_generator.go
173 if err := a.renewRangeIDFn(); err != nil {
174 return taskIDUninitialized, err
180 }
181
182 > taskID := a.nextTaskID task_key_generator.go
183 > a.nextTaskID++
184 > return taskID, nil
185 }
go.temporal.io/server/common/persistence/data_interfaces_mock.go 65 covered LOC · 13 ranges

Open complete file

67
68 // NewMockShardManager creates a new mock instance.
69 > func NewMockShardManager(ctrl *gomock.Controller) *MockShardManager { data_interfaces_mock.go
70 > mock := &MockShardManager{ctrl: ctrl}
71 > mock.recorder = &MockShardManagerMockRecorder{mock}
72 > return mock
73 > }
74
75 // EXPECT returns an object that allows the caller to indicate expected use.
160
161 // NewMockExecutionManager creates a new mock instance.
162 > func NewMockExecutionManager(ctrl *gomock.Controller) *MockExecutionManager { data_interfaces_mock.go
163 > mock := &MockExecutionManager{ctrl: ctrl}
164 > mock.recorder = &MockExecutionManagerMockRecorder{mock}
165 > return mock
166 > }
167
168 // EXPECT returns an object that allows the caller to indicate expected use.
169 > func (m *MockExecutionManager) EXPECT() *MockExecutionManagerMockRecorder { data_interfaces_mock.go
170 > return m.recorder
171 > }
172
173 // AddHistoryTasks mocks base method.
373
374 // GetHistoryBranchUtil mocks base method.
375 > func (m *MockExecutionManager) GetHistoryBranchUtil() HistoryBranchUtil { data_interfaces_mock.go
376 > m.ctrl.T.Helper()
377 > ret := m.ctrl.Call(m, "GetHistoryBranchUtil")
378 > ret0, _ := ret[0].(HistoryBranchUtil)
379 > return ret0
380 > }
381
382 // GetHistoryBranchUtil indicates an expected call of GetHistoryBranchUtil.
383 > func (mr *MockExecutionManagerMockRecorder) GetHistoryBranchUtil() *gomock.Call { data_interfaces_mock.go
384 > mr.mock.ctrl.T.Helper()
385 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHistoryBranchUtil", reflect.TypeOf((*MockExecutionManager)(nil).GetHistoryBranchUtil))
386 > }
387
388 // GetHistoryTasks mocks base method.
431
432 // GetWorkflowExecution mocks base method.
433 > func (m *MockExecutionManager) GetWorkflowExecution(ctx context.Context, request *GetWorkflowExecutionRequest) (*GetWorkflowExecutionResponse, error) { data_interfaces_mock.go
434 > m.ctrl.T.Helper()
435 > ret := m.ctrl.Call(m, "GetWorkflowExecution", ctx, request)
436 > ret0, _ := ret[0].(*GetWorkflowExecutionResponse)
437 > ret1, _ := ret[1].(error)
438 > return ret0, ret1
439 > }
440
441 // GetWorkflowExecution indicates an expected call of GetWorkflowExecution.
442 > func (mr *MockExecutionManagerMockRecorder) GetWorkflowExecution(ctx, request any) *gomock.Call { data_interfaces_mock.go
443 > mr.mock.ctrl.T.Helper()
444 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetWorkflowExecution", reflect.TypeOf((*MockExecutionManager)(nil).GetWorkflowExecution), ctx, request)
445 > }
446
447 // IsReplicationDLQEmpty mocks base method.
608
609 // UpdateWorkflowExecution mocks base method.
610 > func (m *MockExecutionManager) UpdateWorkflowExecution(ctx context.Context, request *UpdateWorkflowExecutionRequest) (*UpdateWorkflowExecutionResponse, error) { data_interfaces_mock.go
611 > m.ctrl.T.Helper()
612 > ret := m.ctrl.Call(m, "UpdateWorkflowExecution", ctx, request)
613 > ret0, _ := ret[0].(*UpdateWorkflowExecutionResponse)
614 > ret1, _ := ret[1].(error)
615 > return ret0, ret1
616 > }
617
618 // UpdateWorkflowExecution indicates an expected call of UpdateWorkflowExecution.
619 > func (mr *MockExecutionManagerMockRecorder) UpdateWorkflowExecution(ctx, request any) *gomock.Call { data_interfaces_mock.go
620 > mr.mock.ctrl.T.Helper()
621 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateWorkflowExecution", reflect.TypeOf((*MockExecutionManager)(nil).UpdateWorkflowExecution), ctx, request)
622 > }
623
624 // MockTaskManager is a mock of TaskManager interface.
635
636 // NewMockTaskManager creates a new mock instance.
637 > func NewMockTaskManager(ctrl *gomock.Controller) *MockTaskManager { data_interfaces_mock.go
638 > mock := &MockTaskManager{ctrl: ctrl}
639 > mock.recorder = &MockTaskManagerMockRecorder{mock}
640 > return mock
641 > }
642
643 // EXPECT returns an object that allows the caller to indicate expected use.
878
879 // NewMockMetadataManager creates a new mock instance.
880 > func NewMockMetadataManager(ctrl *gomock.Controller) *MockMetadataManager { data_interfaces_mock.go
881 > mock := &MockMetadataManager{ctrl: ctrl}
882 > mock.recorder = &MockMetadataManagerMockRecorder{mock}
883 > return mock
884 > }
885
886 // EXPECT returns an object that allows the caller to indicate expected use.
1073
1074 // NewMockClusterMetadataManager creates a new mock instance.
1075 > func NewMockClusterMetadataManager(ctrl *gomock.Controller) *MockClusterMetadataManager { data_interfaces_mock.go
1076 > mock := &MockClusterMetadataManager{ctrl: ctrl}
1077 > mock.recorder = &MockClusterMetadataManagerMockRecorder{mock}
1078 > return mock
1079 > }
1080
1081 // EXPECT returns an object that allows the caller to indicate expected use.
1240
1241 // NewMockNexusEndpointManager creates a new mock instance.
1242 > func NewMockNexusEndpointManager(ctrl *gomock.Controller) *MockNexusEndpointManager { data_interfaces_mock.go
1243 > mock := &MockNexusEndpointManager{ctrl: ctrl}
1244 > mock.recorder = &MockNexusEndpointManagerMockRecorder{mock}
1245 > return mock
1246 > }
1247
1248 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/service/history/shard/task_request_tracker.go 58 covered LOC · 16 ranges

Open complete file

24 )
25
26 > func newTaskRequestTracker(registry tasks.TaskCategoryRegistry) *taskRequestTracker { task_request_tracker.go
27 > outstandingTaskKeys := make(map[tasks.Category]map[tasks.Key]struct{})
28 > for _, category := range registry.GetCategories() {
29 > outstandingTaskKeys[category] = make(map[tasks.Key]struct{})
30 > }
31 > return &taskRequestTracker{
32 > pendingTaskKeys: outstandingTaskKeys,
33 > }
34 }
35
36 func (t *taskRequestTracker) track(
37 taskMaps ...map[tasks.Category][]tasks.Task,
38 > ) taskRequestCompletionFn { task_request_tracker.go
39 > minKeyByCategory := make(map[tasks.Category]tasks.Key)
40 > for _, taskMap := range taskMaps {
41 > for category, tasksPerCategory := range taskMap {
42 > minKey := tasks.MaximumKey task_request_tracker.go
43 > for _, task := range tasksPerCategory {
44 > if task.GetKey().CompareTo(minKey) < 0 {
45 > minKey = task.GetKey()
46 > }
47 }
48 > if minKey.CompareTo(tasks.MaximumKey) == 0 { task_request_tracker.go
49 continue
50 }
51
52 > if _, ok := minKeyByCategory[category]; !ok { task_request_tracker.go
53 > minKeyByCategory[category] = minKey
54 > } else {
55 minKeyByCategory[category] = tasks.MinKey(minKeyByCategory[category], minKey)
56 }
58 }
59
60 > t.Lock() task_request_tracker.go
61 > defer t.Unlock()
62 >
63 > t.inflightRequestCount++
64 >
65 > for category, minKey := range minKeyByCategory {
66 > t.pendingTaskKeys[category][minKey] = struct{}{} task_request_tracker.go
67 > }
68
69 > return func(writeErr error) { task_request_tracker.go
70 > t.Lock() task_request_tracker.go
71 > defer t.Unlock()
72 >
73 > // Task key is not pending only when we get a definitive result from persistence.
74 > // This result can be either a success or a error that guarantees the task with that key
75 > // will not be persisted.
76 > if writeErr == nil || !persistence.OperationPossiblySucceeded(writeErr) {
77 > // we can only remove the task from the pending task list if we are sure it was inserted task_request_tracker.go
78 > // or the insertion is guaranteed to have failed
79 > for category, minKey := range minKeyByCategory {
80 > delete(t.pendingTaskKeys[category], minKey) task_request_tracker.go
81 > }
82 }
83
84 // While task key might still be pending, the request is completed and no longer inflight
85 > t.inflightRequestCount-- task_request_tracker.go
86 > if t.inflightRequestCount == 0 {
87 > t.closeWaitChannelsLocked() task_request_tracker.go
88 > }
89 }
90 }
130 }
131
132 > func (t *taskRequestTracker) clear() { task_request_tracker.go
133 > t.Lock()
134 > defer t.Unlock()
135 >
136 > for category := range t.pendingTaskKeys {
137 > t.pendingTaskKeys[category] = make(map[tasks.Key]struct{})
138 > }
139 > t.inflightRequestCount = 0
140 > t.closeWaitChannelsLocked()
141 }
142
143 > func (t *taskRequestTracker) closeWaitChannelsLocked() { task_request_tracker.go
144 > for _, waitCh := range t.waitChannels {
145 close(waitCh)
146 }
147 > t.waitChannels = nil task_request_tracker.go
148 }
go.temporal.io/server/service/history/workflow/update/registry.go 54 covered LOC · 19 ranges

Open complete file

108 // WithInFlightLimit provides an optional limit to the number of incomplete
109 // Updates that a Registry instance will allow.
110 > func WithInFlightLimit(f func() int) Option { registry.go
111 > return func(r *registry) {
112 > r.maxInFlightUpdateCount = f
113 > }
114 }
115
116 // WithInFlightSizeLimit provides an optional limit to the total payload size of incomplete
117 // Updates that a Registry instance will allow.
118 > func WithInFlightSizeLimit(f func() int) Option { registry.go
119 > return func(r *registry) {
120 > r.maxInFlightUpdateSize = f
121 > }
122 }
123
124 // WithTotalLimit provides an optional limit to the total number of Updates for workflow run.
125 > func WithTotalLimit(f func() int) Option { registry.go
126 > return func(r *registry) {
127 > r.maxTotal = f
128 > }
129 }
130
131 // WithTotalLimitSuggestCAN provides an optional threshold for suggesting ContinueAsNew
132 // when the total number of Updates reaches a certain percentage of the total limit.
133 > func WithTotalLimitSuggestCAN(f func() float64) Option { registry.go
134 > return func(r *registry) {
135 > r.maxTotalSuggestContinueAsNewThreshold = f
136 > }
137 }
138
139 // WithNamespace sets the namespace name to be used in Registry metrics and logs.
140 > func WithNamespace(ns string) Option { registry.go
141 > return func(r *registry) {
142 > r.instrumentation.namespace = ns
143 > }
144 }
145
146 // WithLogger sets the log.Logger to be used by Registry and its Updates.
147 > func WithLogger(l log.Logger) Option { registry.go
148 > return func(r *registry) {
149 > r.instrumentation.log = l
150 > }
151 }
152
153 // WithMetrics sets the metrics.Handler to be used by Registry and its Updates.
154 > func WithMetrics(m metrics.Handler) Option { registry.go
155 > return func(r *registry) {
156 > r.instrumentation.metrics = m
157 > }
158 }
159
160 // WithTracerProvider sets the trace.TracerProvider (and by extension the
161 // trace.Tracer) to be used by Registry and its Updates.
162 > func WithTracerProvider(t trace.TracerProvider) Option { registry.go
163 > return func(r *registry) {
164 > r.instrumentation.tracer = t.Tracer(telemetry.ComponentUpdateRegistry)
165 > }
166 }
167
169 store UpdateStore,
170 opts ...Option,
171 > ) Registry { registry.go
172 > r := &registry{
173 > updates: make(map[string]*Update),
174 > store: store,
175 > instrumentation: noopInstrumentation,
176 > failoverVersion: store.GetCurrentVersion(),
177 > maxTotal: func() int { return 0 }, // ie disabled
178 maxInFlightUpdateSize: func() int { return 0 }, // ie disabled
179 maxInFlightUpdateCount: func() int { return 0 }, // ie disabled
180 maxTotalSuggestContinueAsNewThreshold: func() float64 { return 0 }, // ie disabled
181 }
182 > r.maxTotalSuggestContinueAsNew = func() int { registry.go
183 return int(math.Ceil(float64(r.maxTotal()) * r.maxTotalSuggestContinueAsNewThreshold()))
184 }
185 > for _, opt := range opts { registry.go
186 > opt(r) registry.go
187 > }
188
189 > r.store.VisitUpdates(func(updID string, updInfo *persistencespb.UpdateInfo) { registry.go
190 if updInfo.GetAdmission() != nil {
191 // An Update entry in the Registry may have a request payload: we use this to write the payload to an
298 _ context.Context,
299 effects effect.Controller,
300 > ) []string { registry.go
301 > var updatesToReject []*Update
302 > for _, upd := range r.updates {
303 if upd.isSent() {
304 updatesToReject = append(updatesToReject, upd)
306 }
307
308 > var rejectedUpdateIDs []string registry.go
309 > for _, upd := range updatesToReject {
310 if err := upd.reject(unprocessedUpdateFailure, effects); err != nil {
311 return nil
313 rejectedUpdateIDs = append(rejectedUpdateIDs, upd.id)
314 }
315 > return rejectedUpdateIDs registry.go
316 }
317
318 > func (r *registry) HasOutgoingMessages(includeAlreadySent bool) bool { registry.go
319 > for _, upd := range r.updates {
320 if upd.needToSend(includeAlreadySent) {
321 return true
322 }
323 }
324 > return false registry.go
325 }
326
go.temporal.io/server/common/metrics/tags.go 50 covered LOC · 24 ranges

Open complete file

101 // dual emit the metric with the all tag. If a blank namespace is provided then
102 // this converts that to an unknown namespace.
103 > func NamespaceTag(value string) Tag { tags.go
104 > if len(value) == 0 {
105 value = unknownValue
106 }
107 > return Tag{Key: namespace, Value: value} tags.go
108 }
109
110 // NamespaceIDTag returns a new namespace ID tag.
111 > func NamespaceIDTag(value string) Tag { tags.go
112 > if len(value) == 0 {
113 value = unknownValue
114 }
115 > return Tag{Key: namespaceID, Value: value} tags.go
116 }
117
124
125 // NamespaceStateTag returns a new namespace state tag.
126 > func NamespaceStateTag(value string) Tag { tags.go
127 > if len(value) == 0 {
128 value = unknownValue
129 }
130 > return Tag{Key: namespaceState, Value: value} tags.go
131 }
132
177 // - `tqid.PerTaskQueueScope`
178 // - `tqid.PerTaskQueuePartitionScope`
179 > func UnsafeTaskQueueTag(value string) Tag { tags.go
180 > if len(value) == 0 {
181 value = unknownValue
182 }
183 > return Tag{Key: taskQueue, Value: value} tags.go
184 }
185
213
214 // WorkflowTypeTag returns a new workflow type tag.
215 > func WorkflowTypeTag(value string) Tag { tags.go
216 > if len(value) == 0 {
217 value = unknownValue
218 }
219 > return Tag{Key: workflowType, Value: value} tags.go
220 }
221
222 // ActivityTypeTag returns a new activity type tag.
223 > func ActivityTypeTag(value string) Tag { tags.go
224 > if len(value) == 0 {
225 > value = unknownValue tags.go
226 > }
227 > return Tag{Key: activityType, Value: value} tags.go
228 }
229
234
235 // CommandTypeTag returns a new command type tag.
236 > func CommandTypeTag(value string) Tag { tags.go
237 > if len(value) == 0 {
238 value = unknownValue
239 }
240 > return Tag{Key: commandType, Value: value} tags.go
241 }
242
257 }
258
259 > func FirstAttemptTag(attempt int32) Tag { tags.go
260 > value := falseValue
261 > if attempt == 1 {
262 > value = trueValue
263 > }
264 > return Tag{Key: isFirstAttempt, Value: value}
265 }
266
286 }
287
288 > func ArchetypeTag(value string) Tag { tags.go
289 > if len(value) == 0 {
290 value = unknownValue
291 }
292 > return Tag{Key: ArchetypeTagName, Value: value} tags.go
293 }
294
447 }
448
449 > func ServiceNameTag(value primitives.ServiceName) Tag { tags.go
450 > return Tag{Key: serviceName, Value: string(value)}
451 > }
452
453 func ActionType(value string) Tag {
455 }
456
457 > func OperationTag(value string) Tag { tags.go
458 > return Tag{Key: OperationTagName, Value: value}
459 > }
460
461 > func StringTag(key string, value string) Tag { tags.go
462 > return Tag{Key: key, Value: value}
463 > }
464
465 > func CacheTypeTag(value string) Tag { tags.go
466 > return Tag{Key: CacheTypeTagName, Value: value}
467 > }
468
469 > func PriorityTag(value locks.Priority) Tag { tags.go
470 > return Tag{Key: PriorityTagName, Value: strconv.Itoa(int(value))}
471 > }
472
473 // ReasonString is just a string but the special type is defined here to remind callers of ReasonTag to limit the
496 }
497
498 > func VersioningBehaviorTag(behavior enumspb.VersioningBehavior) Tag { tags.go
499 > return Tag{Key: versioningBehavior, Value: behavior.String()}
500 > }
501
502 func ContinueAsNewVersioningBehaviorTag(canBehavior enumspb.ContinueAsNewVersioningBehavior) Tag {
go.temporal.io/server/service/history/api/recordactivitytaskheartbeat/api.go 50 covered LOC · 11 ranges

Open complete file

20 shard historyi.ShardContext,
21 workflowConsistencyChecker api.WorkflowConsistencyChecker,
22 > ) (resp *historyservice.RecordActivityTaskHeartbeatResponse, retError error) { api.go
23 > request := req.HeartbeatRequest
24 > tokenSerializer := tasktoken.NewSerializer()
25 > token, err0 := tokenSerializer.Deserialize(request.TaskToken)
26 > if err0 != nil {
27 return nil, consts.ErrDeserializingToken
28 }
29
30 > _, err := api.GetActiveNamespace(shard, namespace.ID(req.GetNamespaceId()), token.WorkflowId) api.go
31 > if err != nil {
32 return nil, err
33 }
34 > if err := api.SetActivityTaskRunID(ctx, token, workflowConsistencyChecker); err != nil { api.go
35 return nil, err
36 }
37
38 > var cancelRequested bool api.go
39 > var activityPaused bool
40 > var activityReset bool
41 > err = api.GetAndUpdateWorkflowWithNew(
42 > ctx,
43 > token.Clock,
44 > definition.NewWorkflowKey(
45 > token.NamespaceId,
46 > token.WorkflowId,
47 > token.RunId,
48 > ),
49 > func(workflowLease api.WorkflowLease) (*api.UpdateWorkflowAction, error) {
50 > mutableState := workflowLease.GetMutableState()
51 > if !mutableState.IsWorkflowExecutionRunning() {
52 return nil, consts.ErrWorkflowCompleted
53 }
54
55 > scheduledEventID := token.GetScheduledEventId() api.go
56 > if scheduledEventID == common.EmptyEventID { // client call RecordActivityHeartbeatByID, so get scheduledEventID by activityID
57 scheduledEventID, err0 = api.GetActivityScheduledEventID(token.GetActivityId(), mutableState)
58 if err0 != nil {
60 }
61 }
62 > ai, isRunning := mutableState.GetActivityInfo(scheduledEventID) api.go
63 >
64 > // First check to see if cache needs to be refreshed as we could potentially have stale workflow execution in
65 > // some extreme cassandra failure cases.
66 > if !isRunning && scheduledEventID >= mutableState.GetNextEventID() {
67 metrics.StaleMutableStateCounter.With(shard.GetMetricsHandler()).Record(
68 1,
71 }
72
73 > if !isRunning || api.IsActivityTaskNotFoundForToken(token, ai, nil) { api.go
74 return nil, consts.ErrActivityTaskNotFound
75 }
76
77 // update worker identity if available
78 > if req.HeartbeatRequest.Identity != "" { api.go
79 > ai.RetryLastWorkerIdentity = req.HeartbeatRequest.Identity
80 > }
81
82 > cancelRequested = ai.CancelRequested api.go
83 > activityPaused = ai.Paused
84 > activityReset = ai.ActivityReset
85 >
86 > // Save progress and last HB reported time.
87 > mutableState.UpdateActivityProgress(ai, request)
88 >
89 > return &api.UpdateWorkflowAction{
90 > Noop: false,
91 > CreateWorkflowTask: false,
92 > }, nil
93 },
94 nil,
96 workflowConsistencyChecker,
97 )
98 > if err != nil { api.go
99 return nil, err
100 }
101
102 > return &historyservice.RecordActivityTaskHeartbeatResponse{ api.go
103 > CancelRequested: cancelRequested,
104 > ActivityPaused: activityPaused,
105 > ActivityReset: activityReset,
106 > }, nil
107 }
go.temporal.io/server/common/namespace/namespace.go 49 covered LOC · 19 ranges

Open complete file

81 resolver ReplicationResolver,
82 mutations ...Mutation,
83 > ) (*Namespace, error) { namespace.go
84 > if resolver == nil {
85 return nil, serviceerror.NewInvalidArgument("replicationResolver must be provided")
86 }
87 > ns := &Namespace{ namespace.go
88 > info: detail.Info,
89 > config: detail.Config,
90 > configVersion: detail.ConfigVersion,
91 > customSearchAttributesMapper: CustomSearchAttributesMapper{
92 > fieldToAlias: detail.Config.CustomSearchAttributeAliases,
93 > aliasToField: util.InverseMap(detail.Config.CustomSearchAttributeAliases),
94 > },
95 > replicationResolver: resolver,
96 > }
97 >
98 > for _, m := range mutations {
99 > m.apply(ns) namespace.go
100 > }
101
102 > return ns, nil namespace.go
103 }
104
147 // namespace's configured bad binary checksums. The returned error (if any) will
148 // be unwrappable as BadBinaryError.
149 > func (ns *Namespace) VerifyBinaryChecksum(cksum string) error { namespace.go
150 > badBinMap := ns.config.GetBadBinaries().GetBinaries()
151 > if badBinMap == nil {
152 return nil
153 }
154 > if info, ok := badBinMap[cksum]; ok { namespace.go
155 return BadBinaryError{cksum: cksum, info: info}
156 }
157 > return nil namespace.go
158 }
159
160 // ID observes this namespace's permanent unique identifier in string form.
161 > func (ns *Namespace) ID() ID { namespace.go
162 > if ns.info == nil {
163 return ID("")
164 }
165 > return ID(ns.info.Id) namespace.go
166 }
167
168 // Name observes this namespace's configured name.
169 > func (ns *Namespace) Name() Name { namespace.go
170 > if ns.info == nil {
171 return Name("")
172 }
173 > return Name(ns.info.Name) namespace.go
174 }
175
191 // ActiveClusterName observes the name of the cluster that is currently active
192 // for this namespace.
193 > func (ns *Namespace) ActiveClusterName(routingKey RoutingKey) string { namespace.go
194 > return ns.replicationResolver.ActiveClusterName(routingKey)
195 > }
196
197 // ClusterNames observes the names of the clusters to which this namespace is
198 // replicated.
199 > func (ns *Namespace) ClusterNames(businessID string) []string { namespace.go
200 > return ns.replicationResolver.ClusterNames(businessID)
201 > }
202
203 // IsOnCluster returns true is namespace is registered on cluster otherwise false.
212
213 // FailoverVersion return the namespace failover version
214 > func (ns *Namespace) FailoverVersion(businessID string) int64 { namespace.go
215 > return ns.replicationResolver.FailoverVersion(businessID)
216 > }
217
218 // IsGlobalNamespace returns whether the namespace is a global namespace.
219 // Being a global namespace doesn't necessarily mean that there are multiple registered clusters for it, only that it
220 // has a failover version. To determine whether operations should be replicated for a namespace, see ReplicationPolicy.
221 > func (ns *Namespace) IsGlobalNamespace() bool { namespace.go
222 > return ns.replicationResolver.IsGlobalNamespace()
223 > }
224
225 // FailoverNotificationVersion return the global notification version of when failover happened
284
285 // Retention returns retention duration for this namespace.
286 > func (ns *Namespace) Retention() time.Duration { namespace.go
287 > if ns.config.Retention == nil {
288 return 0
289 }
290
291 > return ns.config.Retention.AsDuration() namespace.go
292 }
293
337 }
338
339 > func (id ID) String() string { namespace.go
340 > return string(id)
341 > }
342
343 func (id ID) IsEmpty() bool {
345 }
346
347 > func (n Name) String() string { namespace.go
348 > return string(n)
349 > }
350
351 func (n Name) IsEmpty() bool {
go.temporal.io/server/common/metrics/defs.go 47 covered LOC · 9 ranges

Open complete file

20 )
21
22 > func NewTimerDef(name string, opts ...Option) timerDefinition { defs.go
23 > // This line cannot be combined with others!
24 > // This ensures the stack trace has information of the caller.
25 > def := newMetricDefinition(name, opts...)
26 > globalRegistry.register(def)
27 > return timerDefinition{def}
28 > }
29
30 > func NewBytesHistogramDef(name string, opts ...Option) histogramDefinition { defs.go
31 > // This line cannot be combined with others!
32 > // This ensures the stack trace has information of the caller.
33 > def := newMetricDefinition(name, append(opts, WithUnit(Bytes))...)
34 > globalRegistry.register(def)
35 > return histogramDefinition{def}
36 > }
37
38 > func NewDimensionlessHistogramDef(name string, opts ...Option) histogramDefinition { defs.go
39 > // This line cannot be combined with others!
40 > // This ensures the stack trace has information of the caller.
41 > def := newMetricDefinition(name, append(opts, WithUnit(Dimensionless))...)
42 > globalRegistry.register(def)
43 > return histogramDefinition{def}
44 > }
45
46 > func NewCounterDef(name string, opts ...Option) counterDefinition { defs.go
47 > // This line cannot be combined with others!
48 > // This ensures the stack trace has information of the caller.
49 > def := newMetricDefinition(name, opts...)
50 > globalRegistry.register(def)
51 > return counterDefinition{def}
52 > }
53
54 > func NewGaugeDef(name string, opts ...Option) gaugeDefinition { defs.go
55 > // This line cannot be combined with others!
56 > // This ensures the stack trace has information of the caller.
57 > def := newMetricDefinition(name, opts...)
58 > globalRegistry.register(def)
59 > return gaugeDefinition{def}
60 > }
61
62 > func (d histogramDefinition) With(handler Handler) HistogramIface { defs.go
63 > return handler.Histogram(d.name, d.unit)
64 > }
65
66 > func (d counterDefinition) With(handler Handler) CounterIface { defs.go
67 > return handler.Counter(d.name)
68 > }
69
70 > func (d gaugeDefinition) With(handler Handler) GaugeIface { defs.go
71 > return handler.Gauge(d.name)
72 > }
73
74 > func (d timerDefinition) With(handler Handler) TimerIface { defs.go
75 > return handler.Timer(d.name)
76 > }
go.temporal.io/server/api/token/v1/message.pb.go 46 covered LOC · 7 ranges

Open complete file

258 }
259
260 > func (x *Task) Reset() { message.pb.go
261 > *x = Task{}
262 > mi := &file_temporal_server_api_token_v1_message_proto_msgTypes[2]
263 > ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
264 > ms.StoreMessageInfo(mi)
265 > }
266
267 func (x *Task) String() string {
271 func (*Task) ProtoMessage() {}
272
273 > func (x *Task) ProtoReflect() protoreflect.Message { message.pb.go
274 > mi := &file_temporal_server_api_token_v1_message_proto_msgTypes[2]
275 > if x != nil {
276 > ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
277 > if ms.LoadMessageInfo() == nil {
278 > ms.StoreMessageInfo(mi)
279 > }
280 > return ms
281 }
282 return mi.MessageOf(x)
309 }
310
311 > func (x *Task) GetScheduledEventId() int64 { message.pb.go
312 > if x != nil {
313 > return x.ScheduledEventId
314 > }
315 return 0
316 }
358 }
359
360 > func (x *Task) GetVersion() int64 { message.pb.go
361 > if x != nil {
362 > return x.Version
363 > }
364 return 0
365 }
372 }
373
374 > func (x *Task) GetStartVersion() int64 { message.pb.go
375 > if x != nil {
376 > return x.StartVersion
377 > }
378 return 0
379 }
785 }
786
787 > func init() { file_temporal_server_api_token_v1_message_proto_init() } message.pb.go
788 > func file_temporal_server_api_token_v1_message_proto_init() {
789 > if File_temporal_server_api_token_v1_message_proto != nil {
790 return
791 }
792 > type x struct{} message.pb.go
793 > out := protoimpl.TypeBuilder{
794 > File: protoimpl.DescBuilder{
795 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
796 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_token_v1_message_proto_rawDesc), len(file_temporal_server_api_token_v1_message_proto_rawDesc)),
797 > NumEnums: 0,
798 > NumMessages: 7,
799 > NumExtensions: 0,
800 > NumServices: 0,
801 > },
802 > GoTypes: file_temporal_server_api_token_v1_message_proto_goTypes,
803 > DependencyIndexes: file_temporal_server_api_token_v1_message_proto_depIdxs,
804 > MessageInfos: file_temporal_server_api_token_v1_message_proto_msgTypes,
805 > }.Build()
806 > File_temporal_server_api_token_v1_message_proto = out.File
807 > file_temporal_server_api_token_v1_message_proto_goTypes = nil
808 > file_temporal_server_api_token_v1_message_proto_depIdxs = nil
809 }
go.temporal.io/server/common/cluster/metadata_mock.go 46 covered LOC · 10 ranges

Open complete file

30
31 // NewMockMetadata creates a new mock instance.
32 > func NewMockMetadata(ctrl *gomock.Controller) *MockMetadata { metadata_mock.go
33 > mock := &MockMetadata{ctrl: ctrl}
34 > mock.recorder = &MockMetadataMockRecorder{mock}
35 > return mock
36 > }
37
38 // EXPECT returns an object that allows the caller to indicate expected use.
39 > func (m *MockMetadata) EXPECT() *MockMetadataMockRecorder { metadata_mock.go
40 > return m.recorder
41 > }
42
43 // ClusterNameForFailoverVersion mocks base method.
44 > func (m *MockMetadata) ClusterNameForFailoverVersion(isGlobalNamespace bool, failoverVersion int64) string { metadata_mock.go
45 > m.ctrl.T.Helper()
46 > ret := m.ctrl.Call(m, "ClusterNameForFailoverVersion", isGlobalNamespace, failoverVersion)
47 > ret0, _ := ret[0].(string)
48 > return ret0
49 > }
50
51 // ClusterNameForFailoverVersion indicates an expected call of ClusterNameForFailoverVersion.
52 > func (mr *MockMetadataMockRecorder) ClusterNameForFailoverVersion(isGlobalNamespace, failoverVersion any) *gomock.Call { metadata_mock.go
53 > mr.mock.ctrl.T.Helper()
54 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClusterNameForFailoverVersion", reflect.TypeOf((*MockMetadata)(nil).ClusterNameForFailoverVersion), isGlobalNamespace, failoverVersion)
55 > }
56
57 // GetAllClusterInfo mocks base method.
64
65 // GetAllClusterInfo indicates an expected call of GetAllClusterInfo.
66 > func (mr *MockMetadataMockRecorder) GetAllClusterInfo() *gomock.Call { metadata_mock.go
67 > mr.mock.ctrl.T.Helper()
68 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllClusterInfo", reflect.TypeOf((*MockMetadata)(nil).GetAllClusterInfo))
69 > }
70
71 // GetClusterID mocks base method.
72 > func (m *MockMetadata) GetClusterID() int64 { metadata_mock.go
73 > m.ctrl.T.Helper()
74 > ret := m.ctrl.Call(m, "GetClusterID")
75 > ret0, _ := ret[0].(int64)
76 > return ret0
77 > }
78
79 // GetClusterID indicates an expected call of GetClusterID.
80 > func (mr *MockMetadataMockRecorder) GetClusterID() *gomock.Call { metadata_mock.go
81 > mr.mock.ctrl.T.Helper()
82 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetClusterID", reflect.TypeOf((*MockMetadata)(nil).GetClusterID))
83 > }
84
85 // GetCurrentClusterName mocks base method.
86 > func (m *MockMetadata) GetCurrentClusterName() string { metadata_mock.go
87 > m.ctrl.T.Helper()
88 > ret := m.ctrl.Call(m, "GetCurrentClusterName")
89 > ret0, _ := ret[0].(string)
90 > return ret0
91 > }
92
93 // GetCurrentClusterName indicates an expected call of GetCurrentClusterName.
94 > func (mr *MockMetadataMockRecorder) GetCurrentClusterName() *gomock.Call { metadata_mock.go
95 > mr.mock.ctrl.T.Helper()
96 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentClusterName", reflect.TypeOf((*MockMetadata)(nil).GetCurrentClusterName))
97 > }
98
99 // GetFailoverVersionIncrement mocks base method.
162
163 // IsGlobalNamespaceEnabled indicates an expected call of IsGlobalNamespaceEnabled.
164 > func (mr *MockMetadataMockRecorder) IsGlobalNamespaceEnabled() *gomock.Call { metadata_mock.go
165 > mr.mock.ctrl.T.Helper()
166 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsGlobalNamespaceEnabled", reflect.TypeOf((*MockMetadata)(nil).IsGlobalNamespaceEnabled))
167 > }
168
169 // IsMasterCluster mocks base method.
go.temporal.io/server/common/dynamicconfig/collection.go 46 covered LOC · 10 ranges

Open complete file

111 // NewCollection creates a new collection. For subscriptions to work, you must call Start/Stop.
112 // Get will work without Start/Stop.
113 > func NewCollection(client Client, logger log.Logger) *Collection { collection.go
114 > // Do this at the first convenient place we have a logger:
115 > logSharedStructureWarnings(logger)
116 >
117 > return &Collection{
118 > client: client,
119 > logger: logger,
120 > errCount: -1,
121 > subscriptions: make(map[Key]map[int]any),
122 > convertCache: new(sync.Map),
123 > indexCache: new(sync.Map),
124 > }
125 > }
126
127 func (c *Collection) Start() {
212 cvs []ConstrainedValue,
213 precedence []Constraints,
214 > ) (*ConstrainedValue, error) { collection.go
215 > if len(cvs) == 0 {
216 > return nil, errKeyNotPresent collection.go
217 > } else if len(cvs) > constraintsCacheThreshold && len(cvs) <= math.MaxInt32 { collection.go
218 return findMatchWithCache(cache, cvs, precedence)
219 }
279 convert func(value any) (T, error),
280 precedence []Constraints,
281 > ) T { collection.go
282 > cvs := c.client.GetValue(key)
283 > v, _ := matchAndConvertCvs(c, key, def, convert, precedence, cvs)
284 > return v
285 > }
286
287 func matchAndConvertCvs[T any](
292 precedence []Constraints,
293 cvs []ConstrainedValue,
294 > ) (T, any) { collection.go
295 > cvp, err := findMatch(c.indexCache, cvs, precedence)
296 > if err != nil {
297 > // couldn't find a constrained match, use default collection.go
298 > return def, usingDefaultValue
299 > }
300
301 typedVal, err := convertWithCache(c, key, convert, cvp)
676 // treat the fields independently), or the zero value of its type (if you want to treat the fields
677 // as a group and default unset fields to zero).
678 > func ConvertStructure[T any](def T) func(v any) (T, error) { collection.go
679 > return func(v any) (T, error) {
680 > // if we already have the right type, no conversion is necessary
681 > if typedV, ok := v.(T); ok {
682 return typedV, nil
683 }
685 // Deep-copy the default and decode over it. This allows using e.g. a struct with some
686 // default fields filled in and a config that only set some fields.
687 > out := deepCopyForMapstructure(def) collection.go
688 >
689 > dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
690 > Result: &out,
691 > DecodeHook: mapstructure.ComposeDecodeHookFunc(
692 > mapstructureHookDuration,
693 > mapstructureHookTimestamp,
694 > mapstructureHookProtoEnum,
695 > mapstructureHookGeneric,
696 > ),
697 > })
698 > if err != nil {
699 return out, err
700 }
701 > err = dec.Decode(v) collection.go
702 > return out, err
703 }
704 }
go.temporal.io/server/api/history/v1/message.pb.go 44 covered LOC · 12 ranges

Open complete file

92 func (*VersionHistoryItem) ProtoMessage() {}
93
94 > func (x *VersionHistoryItem) ProtoReflect() protoreflect.Message { message.pb.go
95 > mi := &file_temporal_server_api_history_v1_message_proto_msgTypes[1]
96 > if x != nil {
97 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
98 if ms.LoadMessageInfo() == nil {
101 return ms
102 }
103 > return mi.MessageOf(x) message.pb.go
104 }
105
109 }
110
111 > func (x *VersionHistoryItem) GetEventId() int64 { message.pb.go
112 > if x != nil {
113 > return x.EventId message.pb.go
114 > }
115 return 0
116 }
145 func (*VersionHistory) ProtoMessage() {}
146
147 > func (x *VersionHistory) ProtoReflect() protoreflect.Message { message.pb.go
148 > mi := &file_temporal_server_api_history_v1_message_proto_msgTypes[2]
149 > if x != nil {
150 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
151 if ms.LoadMessageInfo() == nil {
154 return ms
155 }
156 > return mi.MessageOf(x) message.pb.go
157 }
158
162 }
163
164 > func (x *VersionHistory) GetBranchToken() []byte { message.pb.go
165 > if x != nil {
166 > return x.BranchToken
167 > }
168 return nil
169 }
198 func (*VersionHistories) ProtoMessage() {}
199
200 > func (x *VersionHistories) ProtoReflect() protoreflect.Message { message.pb.go
201 > mi := &file_temporal_server_api_history_v1_message_proto_msgTypes[3]
202 > if x != nil {
203 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
204 if ms.LoadMessageInfo() == nil {
207 return ms
208 }
209 > return mi.MessageOf(x) message.pb.go
210 }
211
215 }
216
217 > func (x *VersionHistories) GetCurrentVersionHistoryIndex() int32 { message.pb.go
218 > if x != nil {
219 > return x.CurrentVersionHistoryIndex
220 > }
221 return 0
222 }
498 }
499
500 > func init() { file_temporal_server_api_history_v1_message_proto_init() } message.pb.go
501 > func file_temporal_server_api_history_v1_message_proto_init() {
502 > if File_temporal_server_api_history_v1_message_proto != nil {
503 return
504 }
505 > type x struct{} message.pb.go
506 > out := protoimpl.TypeBuilder{
507 > File: protoimpl.DescBuilder{
508 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
509 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_history_v1_message_proto_rawDesc), len(file_temporal_server_api_history_v1_message_proto_rawDesc)),
510 > NumEnums: 0,
511 > NumMessages: 8,
512 > NumExtensions: 0,
513 > NumServices: 0,
514 > },
515 > GoTypes: file_temporal_server_api_history_v1_message_proto_goTypes,
516 > DependencyIndexes: file_temporal_server_api_history_v1_message_proto_depIdxs,
517 > MessageInfos: file_temporal_server_api_history_v1_message_proto_msgTypes,
518 > }.Build()
519 > File_temporal_server_api_history_v1_message_proto = out.File
520 > file_temporal_server_api_history_v1_message_proto_goTypes = nil
521 > file_temporal_server_api_history_v1_message_proto_depIdxs = nil
522 }
go.temporal.io/server/common/worker_versioning/worker_versioning.go 44 covered LOC · 23 ranges

Open complete file

114
115 // IsUnversionedOrAssignedBuildIdSearchAttribute returns the value is "unversioned" or "assigned:<bld>"
116 > func IsUnversionedOrAssignedBuildIdSearchAttribute(buildId string) bool { worker_versioning.go
117 > return buildId == UnversionedSearchAttribute ||
118 > strings.HasPrefix(buildId, buildIdSearchAttributePrefixAssigned+BuildIdSearchAttributeDelimiter)
119 > }
120
121 // VersionedBuildIdSearchAttribute returns the search attribute value for a versioned build ID
181 // BuildIdIfUsingVersioning returns the given WorkerVersionStamp if it is using versioning,
182 // otherwise returns nil.
183 > func BuildIdIfUsingVersioning(stamp *commonpb.WorkerVersionStamp) string { worker_versioning.go
184 > if stamp.GetUseVersioning() {
185 return stamp.GetBuildId()
186 }
187 > return "" worker_versioning.go
188 }
189
232 }
233
234 > func DeploymentVersionFromOptions(options *deploymentpb.WorkerDeploymentOptions) *deploymentspb.WorkerDeploymentVersion { worker_versioning.go
235 > if options.GetWorkerVersioningMode() == enumspb.WORKER_VERSIONING_MODE_VERSIONED {
236 return &deploymentspb.WorkerDeploymentVersion{
237 DeploymentName: options.GetDeploymentName(),
239 }
240 }
241 > return nil worker_versioning.go
242 }
243
244 // DeploymentOrVersion Temporary helper function to return a Deployment based on passed Deployment
245 // or WorkerDeploymentVersion objects, if `v` is not nil, it'll take precedence.
246 > func DeploymentOrVersion(d *deploymentpb.Deployment, v *deploymentspb.WorkerDeploymentVersion) *deploymentpb.Deployment { worker_versioning.go
247 > if v != nil {
248 return DeploymentIfValid(DeploymentFromDeploymentVersion(v))
249 }
250 > return DeploymentIfValid(d) worker_versioning.go
251 }
252
253 // DeploymentIfValid returns the deployment back if is both of its fields have value.
254 > func DeploymentIfValid(d *deploymentpb.Deployment) *deploymentpb.Deployment { worker_versioning.go
255 > if d.GetSeriesName() != "" && d.GetBuildId() != "" {
256 return d
257 }
258 > return nil worker_versioning.go
259 }
260
490 // ExternalWorkerDeploymentVersionFromDeployment Temporary helper function to convert Deployment to
491 // WorkerDeploymentVersion proto until we update code to use the new proto in all places.
492 > func ExternalWorkerDeploymentVersionFromDeployment(deployment *deploymentpb.Deployment) *deploymentpb.WorkerDeploymentVersion { worker_versioning.go
493 > if deployment == nil {
494 > return nil worker_versioning.go
495 > }
496 return &deploymentpb.WorkerDeploymentVersion{
497 BuildId: deployment.GetBuildId(),
526 // DeploymentFromDeploymentVersion Temporary helper function to convert WorkerDeploymentVersion to
527 // Deployment proto until we update code to use the new proto in all places.
528 > func DeploymentFromDeploymentVersion(dv *deploymentspb.WorkerDeploymentVersion) *deploymentpb.Deployment { worker_versioning.go
529 > if dv == nil {
530 > return nil worker_versioning.go
531 > }
532 return &deploymentpb.Deployment{
533 BuildId: dv.GetBuildId(),
1148 // ConvertOverrideToV32 reads from deprecated fields and returns a new object with ONLY the equivalent non-deprecated v0.32
1149 // fields. Should be used to replace any passed in override that is stored in persistence.
1150 > func ConvertOverrideToV32(override *workflowpb.VersioningOverride) *workflowpb.VersioningOverride { worker_versioning.go
1151 > if override == nil {
1152 > return nil worker_versioning.go
1153 > }
1154 ret := &workflowpb.VersioningOverride{
1155 Override: override.GetOverride(),
1201 }
1202
1203 > func ExternalWorkerDeploymentVersionToString(v *deploymentpb.WorkerDeploymentVersion) string { worker_versioning.go
1204 > if v == nil {
1205 > return "" worker_versioning.go
1206 > }
1207 return v.GetDeploymentName() + WorkerDeploymentVersionDelimiter + v.GetBuildId()
1208 }
1215 }
1216
1217 > func ExternalWorkerDeploymentVersionFromStringV31(s string) *deploymentpb.WorkerDeploymentVersion { worker_versioning.go
1218 > if s == "" { // unset ramp is no longer supported in v32, so all empty version strings will be treated as unversioned.
1219 > s = UnversionedVersionId worker_versioning.go
1220 > }
1221 > v, _ := WorkerDeploymentVersionFromStringV31(s) worker_versioning.go
1222 > if v == nil {
1223 > return nil worker_versioning.go
1224 > }
1225 return &deploymentpb.WorkerDeploymentVersion{
1226 BuildId: v.BuildId,
1229 }
1230
1231 > func WorkerDeploymentVersionFromStringV31(s string) (*deploymentspb.WorkerDeploymentVersion, error) { worker_versioning.go
1232 > if s == UnversionedVersionId {
1233 > return nil, nil worker_versioning.go
1234 > }
1235 before, after, found := strings.Cut(s, WorkerDeploymentVersionIDDelimiterV31)
1236 // Also try parsing via the v32 delimiter in case user is using an old CLI/SDK but passing new version strings.
go.temporal.io/server/service/history/hsm/tree.go 44 covered LOC · 13 ranges

Open complete file

204 children map[string]*persistencespb.StateMachineMap,
205 backend NodeBackend,
206 > ) (*Node, error) { tree.go
207 > def, ok := registry.Machine(t)
208 > if !ok {
209 return nil, fmt.Errorf("%w: state machine for type: %v", ErrNotRegistered, t)
210 }
211 > serialized, err := def.Serialize(data) tree.go
212 > if err != nil {
213 return nil, err
214 }
215 > return &Node{ tree.go
216 > definition: def,
217 > registry: registry,
218 > persistence: &persistencespb.StateMachineNode{
219 > Children: children,
220 > Data: serialized,
221 > InitialVersionedTransition: &persistencespb.VersionedTransition{},
222 > LastUpdateVersionedTransition: &persistencespb.VersionedTransition{},
223 > TransitionCount: 0,
224 > },
225 > cache: &cachedMachine{
226 > dataLoaded: true,
227 > data: data,
228 > children: make(map[Key]*Node),
229 > },
230 > backend: backend,
231 > opLog: make(OperationLog, 0),
232 > }, nil
233 }
234
235 // Dirty returns true if any of the tree's state machines have transitioned.
236 > func (n *Node) Dirty() bool { tree.go
237 > if n.cache.dirty {
238 return true
239 }
240 > for _, child := range n.cache.children { tree.go
241 if child.Dirty() {
242 return true
243 }
244 }
245 > return false tree.go
246 }
247
262 // deleted. For details on compaction rules, see OperationLog.compact().
263 // This method must be called on the root node only.
264 > func (n *Node) OpLog() (OperationLog, error) { tree.go
265 > if n.Parent != nil {
266 return nil, fmt.Errorf("can only be called from root node")
267 }
268
269 > compacted := n.opLog.compact() tree.go
270 > return compacted, nil
271 }
272
274 // This should be called at the end of every transaction where the transitions are performed to avoid emitting duplicate
275 // transition outputs.
276 > func (n *Node) ClearTransactionState() { tree.go
277 > n.root().opLog = nil
278 >
279 > n.cache.dirty = false
280 > for _, child := range n.cache.children {
281 child.ClearTransactionState()
282 }
705 }
706
707 > func (n *Node) root() *Node { tree.go
708 > root := n
709 > for root.Parent != nil {
710 root = root.Parent
711 }
712 > return root tree.go
713 }
714
727 // - If the target of the operation is deleted, only its DeleteOperation is kept
728 // - Otherwise, the operation is included
729 > func (ol OperationLog) compact() OperationLog { tree.go
730 > if len(ol) == 0 {
731 > return ol tree.go
732 > }
733
734 root := newOpNode(Key{})
go.temporal.io/server/api/matchingservice/v1/request_response.pb.go 43 covered LOC · 1 range

Open complete file

6833 }
6834
6835 > func init() { file_temporal_server_api_matchingservice_v1_request_response_proto_init() } request_response.pb.go
6836 > func file_temporal_server_api_matchingservice_v1_request_response_proto_init() {
6837 > if File_temporal_server_api_matchingservice_v1_request_response_proto != nil {
6838 > return
6839 > }
6840 > file_temporal_server_api_matchingservice_v1_request_response_proto_msgTypes[27].OneofWrappers = []any{
6841 > (*UpdateWorkerBuildIdCompatibilityRequest_ApplyPublicRequest_)(nil),
6842 > (*UpdateWorkerBuildIdCompatibilityRequest_RemoveBuildIds_)(nil),
6843 > (*UpdateWorkerBuildIdCompatibilityRequest_PersistUnknownBuildId)(nil),
6844 > }
6845 > file_temporal_server_api_matchingservice_v1_request_response_proto_msgTypes[29].OneofWrappers = []any{
6846 > (*GetWorkerVersioningRulesRequest_Request)(nil),
6847 > }
6848 > file_temporal_server_api_matchingservice_v1_request_response_proto_msgTypes[31].OneofWrappers = []any{
6849 > (*UpdateWorkerVersioningRulesRequest_Request)(nil),
6850 > }
6851 > file_temporal_server_api_matchingservice_v1_request_response_proto_msgTypes[37].OneofWrappers = []any{
6852 > (*SyncDeploymentUserDataRequest_UpdateVersionData)(nil),
6853 > (*SyncDeploymentUserDataRequest_ForgetVersion)(nil),
6854 > }
6855 > file_temporal_server_api_matchingservice_v1_request_response_proto_msgTypes[56].OneofWrappers = []any{
6856 > (*DispatchNexusTaskResponse_HandlerError)(nil),
6857 > (*DispatchNexusTaskResponse_Response)(nil),
6858 > (*DispatchNexusTaskResponse_RequestTimeout)(nil),
6859 > (*DispatchNexusTaskResponse_Failure)(nil),
6860 > }
6861 > type x struct{}
6862 > out := protoimpl.TypeBuilder{
6863 > File: protoimpl.DescBuilder{
6864 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
6865 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_matchingservice_v1_request_response_proto_rawDesc), len(file_temporal_server_api_matchingservice_v1_request_response_proto_rawDesc)),
6866 > NumEnums: 0,
6867 > NumMessages: 97,
6868 > NumExtensions: 0,
6869 > NumServices: 0,
6870 > },
6871 > GoTypes: file_temporal_server_api_matchingservice_v1_request_response_proto_goTypes,
6872 > DependencyIndexes: file_temporal_server_api_matchingservice_v1_request_response_proto_depIdxs,
6873 > MessageInfos: file_temporal_server_api_matchingservice_v1_request_response_proto_msgTypes,
6874 > }.Build()
6875 > File_temporal_server_api_matchingservice_v1_request_response_proto = out.File
6876 > file_temporal_server_api_matchingservice_v1_request_response_proto_goTypes = nil
6877 > file_temporal_server_api_matchingservice_v1_request_response_proto_depIdxs = nil
6878 }
go.temporal.io/server/service/history/history_engine.go 42 covered LOC · 10 ranges

Open complete file

364
365 // Stop the service.
366 > func (e *historyEngineImpl) Stop() { history_engine.go
367 > if !atomic.CompareAndSwapInt32(
368 > &e.status,
369 > common.DaemonStatusStarted,
370 > common.DaemonStatusStopped,
371 > ) {
372 > return history_engine.go
373 > }
374
375 e.logger.Info("", tag.LifeCycleStopping)
579 ctx context.Context,
580 req *historyservice.RespondWorkflowTaskCompletedRequest,
581 > ) (*historyservice.RespondWorkflowTaskCompletedResponse, error) { history_engine.go
582 > h := respondworkflowtaskcompleted.NewWorkflowTaskCompletedHandler(
583 > e.shardContext,
584 > e.tokenSerializer,
585 > e.eventNotifier,
586 > e.commandHandlerRegistry,
587 > e.chasmWorkflowRegistry,
588 > e.searchAttributesValidator,
589 > e.persistenceVisibilityMgr,
590 > e.workflowConsistencyChecker,
591 > e.matchingClient,
592 > e.versionCache,
593 > )
594 > return h.Invoke(ctx, req)
595 > }
596
597 // RespondWorkflowTaskFailed fails a workflow task
623 ctx context.Context,
624 req *historyservice.RespondActivityTaskCanceledRequest,
625 > ) (*historyservice.RespondActivityTaskCanceledResponse, error) { history_engine.go
626 > return respondactivitytaskcanceled.Invoke(ctx, req, e.shardContext, e.workflowConsistencyChecker)
627 > }
628
629 // RecordActivityTaskHeartbeat records an hearbeat for a task.
634 ctx context.Context,
635 req *historyservice.RecordActivityTaskHeartbeatRequest,
636 > ) (*historyservice.RecordActivityTaskHeartbeatResponse, error) { history_engine.go
637 > return recordactivitytaskheartbeat.Invoke(ctx, req, e.shardContext, e.workflowConsistencyChecker)
638 > }
639
640 // RequestCancelWorkflowExecution records request cancellation event for workflow execution
874 func (e *historyEngineImpl) NotifyNewHistoryEvent(
875 notification *events.Notification,
876 > ) { history_engine.go
877 >
878 > e.eventNotifier.NotifyNewHistoryEvent(notification)
879 > }
880
881 func (e *historyEngineImpl) NotifyChasmExecution(executionKey chasm.ExecutionKey, componentRef []byte) {
887 func (e *historyEngineImpl) NotifyNewTasks(
888 newTasks map[tasks.Category][]tasks.Task,
889 > ) { history_engine.go
890 > for category, tasksByCategory := range newTasks {
891 > // TODO: make replicatorProcessor part of queueProcessors list history_engine.go
892 > // and get rid of the special case here.
893 > if category == tasks.CategoryReplication {
894 if e.replicationAckMgr != nil {
895 e.replicationAckMgr.NotifyNewTasks(tasksByCategory)
898 }
899
900 > if len(tasksByCategory) > 0 { history_engine.go
901 > proc, ok := e.queueProcessors[category]
902 > if !ok {
903 // On shard reload it sends fake tasks to wake up the queue processors. Only log if there are "real"
904 // tasks that can't be processed.
908 continue
909 }
910 > proc.NotifyNewTasks(tasksByCategory) history_engine.go
911 }
912 }
go.temporal.io/server/api/persistence/v1/chasm.pb.go 41 covered LOC · 5 ranges

Open complete file

50 func (*ChasmNode) ProtoMessage() {}
51
52 > func (x *ChasmNode) ProtoReflect() protoreflect.Message { chasm.pb.go
53 > mi := &file_temporal_server_api_persistence_v1_chasm_proto_msgTypes[0]
54 > if x != nil {
55 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
56 if ms.LoadMessageInfo() == nil {
59 return ms
60 }
61 > return mi.MessageOf(x) chasm.pb.go
62 }
63
571 func (*ChasmTaskInfo) ProtoMessage() {}
572
573 > func (x *ChasmTaskInfo) ProtoReflect() protoreflect.Message { chasm.pb.go
574 > mi := &file_temporal_server_api_persistence_v1_chasm_proto_msgTypes[8]
575 > if x != nil {
576 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
577 if ms.LoadMessageInfo() == nil {
580 return ms
581 }
582 > return mi.MessageOf(x) chasm.pb.go
583 }
584
1180 }
1181
1182 > func init() { file_temporal_server_api_persistence_v1_chasm_proto_init() } chasm.pb.go
1183 > func file_temporal_server_api_persistence_v1_chasm_proto_init() {
1184 > if File_temporal_server_api_persistence_v1_chasm_proto != nil {
1185 > return
1186 > }
1187 > file_temporal_server_api_persistence_v1_hsm_proto_init()
1188 > file_temporal_server_api_persistence_v1_chasm_proto_msgTypes[1].OneofWrappers = []any{
1189 > (*ChasmNodeMetadata_ComponentAttributes)(nil),
1190 > (*ChasmNodeMetadata_DataAttributes)(nil),
1191 > (*ChasmNodeMetadata_CollectionAttributes)(nil),
1192 > (*ChasmNodeMetadata_PointerAttributes)(nil),
1193 > }
1194 > file_temporal_server_api_persistence_v1_chasm_proto_msgTypes[10].OneofWrappers = []any{
1195 > (*ChasmNexusCompletion_Success)(nil),
1196 > (*ChasmNexusCompletion_Failure)(nil),
1197 > }
1198 > type x struct{}
1199 > out := protoimpl.TypeBuilder{
1200 > File: protoimpl.DescBuilder{
1201 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
1202 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_chasm_proto_rawDesc), len(file_temporal_server_api_persistence_v1_chasm_proto_rawDesc)),
1203 > NumEnums: 0,
1204 > NumMessages: 15,
1205 > NumExtensions: 0,
1206 > NumServices: 0,
1207 > },
1208 > GoTypes: file_temporal_server_api_persistence_v1_chasm_proto_goTypes,
1209 > DependencyIndexes: file_temporal_server_api_persistence_v1_chasm_proto_depIdxs,
1210 > MessageInfos: file_temporal_server_api_persistence_v1_chasm_proto_msgTypes,
1211 > }.Build()
1212 > File_temporal_server_api_persistence_v1_chasm_proto = out.File
1213 > file_temporal_server_api_persistence_v1_chasm_proto_goTypes = nil
1214 > file_temporal_server_api_persistence_v1_chasm_proto_depIdxs = nil
1215 }
go.temporal.io/server/common/locks/priority_semaphore_impl.go 41 covered LOC · 11 ranges

Open complete file

67 // maximum combined weight for concurrent access, capable of handling multiple priority levels.
68 // Most of the logic is taken directly from golang's semaphore.Weighted.
69 > func NewPrioritySemaphore(n int) *PrioritySemaphoreImpl { priority_semaphore_impl.go
70 > waitLists := make([]*list.List, NumPriorities)
71 > for i := range waitLists {
72 > waitLists[i] = list.New()
73 > }
74 > return &PrioritySemaphoreImpl{
75 > size: n,
76 > waitLists: waitLists,
77 > }
78 }
79
81 // are available or ctx is done. On success, returns nil. On failure, returns
82 // ctx.Err() and leaves the semaphore unchanged.
83 > func (s *PrioritySemaphoreImpl) Acquire(ctx context.Context, priority Priority, n int) error { priority_semaphore_impl.go
84 > if priority >= NumPriorities {
85 // nolint:forbidigo
86 panic(fmt.Sprintf("semaphore: invalid priority %v, priority must be less than %v", priority, NumPriorities))
87 }
88
89 > done := ctx.Done() priority_semaphore_impl.go
90 >
91 > s.mu.Lock()
92 > select {
93 case <-done:
94 // ctx becoming done has "happened before" acquiring the semaphore,
98 s.mu.Unlock()
99 return ctx.Err()
101 }
102 // Check if acquisition can proceed without waiting
103 > if s.size-s.cur >= n && s.noWaiters(priority) { priority_semaphore_impl.go
104 > // Since we hold s.mu and haven't synchronized since checking done, if priority_semaphore_impl.go
105 > // ctx becomes done before we return here, it becoming done must have
106 > // "happened concurrently" with this call - it cannot "happen before"
107 > // we return in this branch. So, we're ok to always acquire here.
108 > s.cur += n
109 > s.mu.Unlock()
110 > return nil
111 > }
112
113 if n > s.size {
173 }
174
175 > func (s *PrioritySemaphoreImpl) Release(n int) { priority_semaphore_impl.go
176 > s.mu.Lock()
177 > defer s.mu.Unlock()
178 > s.cur -= n
179 > if s.cur < 0 {
180 s.mu.Unlock()
181 panic("semaphore: released more than held")
182 }
183 > s.notifyWaiters() priority_semaphore_impl.go
184 }
185
186 > func (s *PrioritySemaphoreImpl) notifyWaiters() { priority_semaphore_impl.go
187 > for _, l := range s.waitLists {
188 > for {
189 > next := l.Front()
190 > if next == nil {
191 > break // No more waiters blocked.
192 }
193
219
220 // noWaiters returns if there is no waiter that has priority higher or equal to lowestPriority.
221 > func (s *PrioritySemaphoreImpl) noWaiters(lowestPriority Priority) bool { priority_semaphore_impl.go
222 > for _, l := range s.waitLists[:lowestPriority+1] {
223 > if l.Len() > 0 {
224 return false
225 }
226 }
227 > return true priority_semaphore_impl.go
228 }
go.temporal.io/server/service/history/api/consistency_checker.go 40 covered LOC · 11 ranges

Open complete file

84 shardContext historyi.ShardContext,
85 workflowCache wcache.Cache,
86 > ) *WorkflowConsistencyCheckerImpl { consistency_checker.go
87 > return &WorkflowConsistencyCheckerImpl{
88 > shardContext: shardContext,
89 > workflowCache: workflowCache,
90 > }
91 > }
92
93 func (c *WorkflowConsistencyCheckerImpl) GetWorkflowCache() wcache.Cache {
117 workflowKey definition.WorkflowKey,
118 lockPriority locks.Priority,
119 > ) (WorkflowLease, error) { consistency_checker.go
120 > return c.getWorkflowLeaseImpl(ctx, reqClock, nil, workflowKey, chasm.WorkflowArchetypeID, lockPriority)
121 > }
122
123 // The code below should be used when custom workflow state validation is required.
130 workflowKey definition.WorkflowKey,
131 lockPriority locks.Priority,
132 > ) (WorkflowLease, error) { consistency_checker.go
133 > return c.getWorkflowLeaseImpl(ctx, reqClock, consistencyPredicate, workflowKey, chasm.WorkflowArchetypeID, lockPriority)
134 > }
135
136 func (c *WorkflowConsistencyCheckerImpl) GetCurrentChasmRunID(
180 archetypeID chasm.ArchetypeID,
181 lockPriority locks.Priority,
182 > ) (WorkflowLease, error) { consistency_checker.go
183 > if err := c.clockConsistencyCheck(reqClock); err != nil {
184 return nil, err
185 }
186
187 > if len(workflowKey.RunID) != 0 { consistency_checker.go
188 > return c.getWorkflowLease(ctx, consistencyPredicate, workflowKey, archetypeID, lockPriority) consistency_checker.go
189 > }
190
191 return c.getCurrentWorkflowLease(
201 func (c *WorkflowConsistencyCheckerImpl) clockConsistencyCheck(
202 reqClock *clockspb.VectorClock,
203 > ) error { consistency_checker.go
204 > if reqClock == nil {
205 > return nil
206 > }
207 currentClock := c.shardContext.CurrentVectorClock()
208 if !vclock.Comparable(reqClock, currentClock) {
279 archetypeID chasm.ArchetypeID,
280 lockPriority locks.Priority,
281 > ) (WorkflowLease, error) { consistency_checker.go
282 >
283 > wfContext, release, err := c.workflowCache.GetOrCreateChasmExecution(
284 > ctx,
285 > c.shardContext,
286 > namespace.ID(workflowKey.NamespaceID),
287 > &commonpb.WorkflowExecution{
288 > WorkflowId: workflowKey.WorkflowID,
289 > RunId: workflowKey.RunID,
290 > },
291 > archetypeID,
292 > lockPriority,
293 > )
294 > if err != nil {
295 return nil, err
296 }
297
298 > mutableState, err := wfContext.LoadMutableState(ctx, c.shardContext) consistency_checker.go
299 > if err != nil {
300 release(err)
301 return nil, err
303
304 // if consistencyPredicate is nil we assume it is not needed
305 > if consistencyPredicate == nil || consistencyPredicate(mutableState) { consistency_checker.go
306 > return NewWorkflowLease(wfContext, release, mutableState), nil consistency_checker.go
307 > }
308 wfContext.Clear()
309
go.temporal.io/server/common/persistence/versionhistory/version_history.go 39 covered LOC · 14 ranges

Open complete file

8
9 // NewVersionHistory create a new instance of VersionHistory.
10 > func NewVersionHistory(branchToken []byte, items []*historyspb.VersionHistoryItem) *historyspb.VersionHistory { version_history.go
11 > return &historyspb.VersionHistory{
12 > BranchToken: branchToken,
13 > Items: items,
14 > }
15 > }
16
17 // CopyVersionHistory copies VersionHistory.
18 > func CopyVersionHistory(v *historyspb.VersionHistory) *historyspb.VersionHistory { version_history.go
19 > token := make([]byte, len(v.BranchToken))
20 > copy(token, v.BranchToken)
21 >
22 > items := CopyVersionHistoryItems(v.Items)
23 >
24 > return NewVersionHistory(token, items)
25 > }
26
27 > func CopyVersionHistoryItems(items []*historyspb.VersionHistoryItem) []*historyspb.VersionHistoryItem { version_history.go
28 > var result []*historyspb.VersionHistoryItem
29 > for _, item := range items {
30 > result = append(result, CopyVersionHistoryItem(item)) version_history.go
31 > }
32 > return result version_history.go
33 }
34
58
59 // SetVersionHistoryBranchToken sets the branch token.
60 > func SetVersionHistoryBranchToken(v *historyspb.VersionHistory, branchToken []byte) { version_history.go
61 > v.BranchToken = make([]byte, len(branchToken))
62 > copy(v.BranchToken, branchToken)
63 > }
64
65 // AddOrUpdateVersionHistoryItem updates the VersionHistory with new VersionHistoryItem.
66 > func AddOrUpdateVersionHistoryItem(v *historyspb.VersionHistory, item *historyspb.VersionHistoryItem) error { version_history.go
67 > if len(v.Items) == 0 {
68 > v.Items = []*historyspb.VersionHistoryItem{CopyVersionHistoryItem(item)} version_history.go
69 > return nil
70 > }
71
72 > lastItem := v.Items[len(v.Items)-1] version_history.go
73 > if item.Version < lastItem.Version {
74 return serviceerror.NewInternalf("cannot update version history with a lower version %v. Last version: %v", item.Version, lastItem.Version)
75 }
76
77 > if item.GetEventId() <= lastItem.GetEventId() { version_history.go
78 return serviceerror.NewInternalf("cannot add version history with a lower event id %v. Last event id: %v", item.GetEventId(), lastItem.GetEventId())
79 }
80
81 > if item.Version > lastItem.Version { version_history.go
82 // Add a new history
83 v.Items = append(v.Items, CopyVersionHistoryItem(item))
84 > } else { version_history.go
85 > // item.Version == lastItem.Version && item.EventID > lastItem.EventID version_history.go
86 > // Update event ID
87 > lastItem.EventId = item.GetEventId()
88 > }
89 > return nil version_history.go
90 }
91
go.temporal.io/server/common/backoff/retrypolicy.go 38 covered LOC · 7 ranges

Open complete file

80
81 // NewExponentialRetryPolicy returns an instance of ExponentialRetryPolicy using the provided initialInterval
82 > func NewExponentialRetryPolicy(initialInterval time.Duration) *ExponentialRetryPolicy { retrypolicy.go
83 > p := &ExponentialRetryPolicy{
84 > initialInterval: initialInterval,
85 > backoffCoefficient: defaultBackoffCoefficient,
86 > maximumInterval: defaultMaximumInterval,
87 > expirationInterval: defaultExpirationInterval,
88 > maximumAttempts: defaultMaximumAttempts,
89 > }
90 >
91 > return p
92 > }
93
94 // NewRetrier is used for creating a new instance of Retrier
113 // All retries are computed using the following formula:
114 // initialInterval * math.Pow(backoffCoefficient, currentAttempt)
115 > func (p *ExponentialRetryPolicy) WithBackoffCoefficient(backoffCoefficient float64) *ExponentialRetryPolicy { retrypolicy.go
116 > p.backoffCoefficient = backoffCoefficient
117 > return p
118 > }
119
120 // WithMaximumInterval sets the maximum interval for each retry.
121 // This does *not* cause the policy to stop retrying when the interval between retries reaches the supplied duration.
122 // That is what WithExpirationInterval does. Instead, this prevents the interval from exceeding maximumInterval.
123 > func (p *ExponentialRetryPolicy) WithMaximumInterval(maximumInterval time.Duration) *ExponentialRetryPolicy { retrypolicy.go
124 > p.maximumInterval = maximumInterval
125 > return p
126 > }
127
128 // WithExpirationInterval sets the absolute expiration interval for all retries
129 > func (p *ExponentialRetryPolicy) WithExpirationInterval(expirationInterval time.Duration) *ExponentialRetryPolicy { retrypolicy.go
130 > p.expirationInterval = expirationInterval
131 > return p
132 > }
133
134 // WithMaximumAttempts sets the maximum number of retry attempts
135 > func (p *ExponentialRetryPolicy) WithMaximumAttempts(maximumAttempts int) *ExponentialRetryPolicy { retrypolicy.go
136 > p.maximumAttempts = maximumAttempts
137 > return p
138 > }
139
140 // ComputeNextDelay returns the next delay interval. This is used by Retrier to delay calling the operation again
267 var _ RetryPolicy = (*ConstantDelayRetryPolicy)(nil)
268
269 > func NewConstantDelayRetryPolicy(delay time.Duration) *ConstantDelayRetryPolicy { retrypolicy.go
270 > return &ConstantDelayRetryPolicy{
271 > maximumAttempts: defaultMaximumAttempts,
272 > jitterPct: defaultJitterPct,
273 > delay: delay,
274 > }
275 > }
276
277 > func (p *ConstantDelayRetryPolicy) WithMaximumAttempts(maximumAttempts int) *ConstantDelayRetryPolicy { retrypolicy.go
278 > p.maximumAttempts = maximumAttempts
279 > return p
280 > }
281
282 func (p *ConstantDelayRetryPolicy) WithJitter(jitterPct float64) *ConstantDelayRetryPolicy {
go.temporal.io/server/service/history/events/cache.go 37 covered LOC · 10 ranges

Open complete file

60 logger log.Logger,
61 disabled bool,
62 > ) Cache { cache.go
63 > return newEventsCache(executionManager, handler, logger, config.EventsHostLevelCacheMaxSizeBytes(), config.EventsCacheTTL(), disabled)
64 > }
65
66 func NewShardLevelEventsCache(
81 ttl time.Duration,
82 disabled bool,
83 > ) *CacheImpl { cache.go
84 > opts := &cache.Options{}
85 > opts.TTL = ttl
86 >
87 > taggedMetricHandler := metricsHandler.WithTags(metrics.CacheTypeTag(metrics.EventsCacheTypeTagValue))
88 > return &CacheImpl{
89 > Cache: cache.NewWithMetrics(maxSize, opts, taggedMetricHandler),
90 > executionManager: executionManager,
91 > metricsHandler: taggedMetricHandler,
92 > logger: logger,
93 > disabled: disabled,
94 > }
95 > }
96
97 > func (e *CacheImpl) validateKey(key EventKey) bool { cache.go
98 > if len(key.NamespaceID) == 0 || len(key.WorkflowID) == 0 || len(key.RunID) == 0 || key.EventID < common.FirstEventID {
99 // This is definitely a bug, but just warn and don't crash so we can find anywhere this happens.
100 e.logger.Warn("one or more ids is invalid in event cache",
105 return false
106 }
107 > return true cache.go
108 }
109
144 }
145
146 > func (e *CacheImpl) PutEvent(key EventKey, event *historypb.HistoryEvent) { cache.go
147 > handler := e.metricsHandler.WithTags(metrics.OperationTag(metrics.EventsCachePutEventScope), metrics.NamespaceIDTag(key.NamespaceID.String()))
148 > metrics.CacheRequests.With(handler).Record(1)
149 > startTime := time.Now().UTC()
150 > defer func() { metrics.CacheLatency.With(handler).Record(time.Since(startTime)) }()
151
152 > if !e.validateKey(key) { cache.go
153 return
154 }
155 > e.put(key, event) cache.go
156 }
157
213 }
214
215 > func (e *CacheImpl) put(key EventKey, event *historypb.HistoryEvent) any { cache.go
216 > return e.Put(key, newHistoryEventCacheItem(event))
217 > }
218
219 var _ cache.SizeGetter = (*historyEventCacheItemImpl)(nil)
221 func newHistoryEventCacheItem(
222 event *historypb.HistoryEvent,
223 > ) *historyEventCacheItemImpl { cache.go
224 > return &historyEventCacheItemImpl{
225 > event: event,
226 > }
227 > }
228
229 > func (h *historyEventCacheItemImpl) CacheSize() int { cache.go
230 > return h.event.Size()
231 > }
go.temporal.io/server/api/adminservice/v1/request_response.pb.go 36 covered LOC · 1 range

Open complete file

6623 }
6624
6625 > func init() { file_temporal_server_api_adminservice_v1_request_response_proto_init() } request_response.pb.go
6626 > func file_temporal_server_api_adminservice_v1_request_response_proto_init() {
6627 > if File_temporal_server_api_adminservice_v1_request_response_proto != nil {
6628 > return
6629 > }
6630 > file_temporal_server_api_adminservice_v1_request_response_proto_msgTypes[59].OneofWrappers = []any{
6631 > (*StreamWorkflowReplicationMessagesRequest_SyncReplicationState)(nil),
6632 > }
6633 > file_temporal_server_api_adminservice_v1_request_response_proto_msgTypes[60].OneofWrappers = []any{
6634 > (*StreamWorkflowReplicationMessagesResponse_Messages)(nil),
6635 > }
6636 > file_temporal_server_api_adminservice_v1_request_response_proto_msgTypes[61].OneofWrappers = []any{
6637 > (*GetNamespaceRequest_Namespace)(nil),
6638 > (*GetNamespaceRequest_Id)(nil),
6639 > }
6640 > file_temporal_server_api_adminservice_v1_request_response_proto_msgTypes[90].OneofWrappers = []any{
6641 > (*StartAdminBatchOperationRequest_RefreshTasksOperation)(nil),
6642 > }
6643 > type x struct{}
6644 > out := protoimpl.TypeBuilder{
6645 > File: protoimpl.DescBuilder{
6646 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
6647 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_adminservice_v1_request_response_proto_rawDesc), len(file_temporal_server_api_adminservice_v1_request_response_proto_rawDesc)),
6648 > NumEnums: 1,
6649 > NumMessages: 105,
6650 > NumExtensions: 0,
6651 > NumServices: 0,
6652 > },
6653 > GoTypes: file_temporal_server_api_adminservice_v1_request_response_proto_goTypes,
6654 > DependencyIndexes: file_temporal_server_api_adminservice_v1_request_response_proto_depIdxs,
6655 > EnumInfos: file_temporal_server_api_adminservice_v1_request_response_proto_enumTypes,
6656 > MessageInfos: file_temporal_server_api_adminservice_v1_request_response_proto_msgTypes,
6657 > }.Build()
6658 > File_temporal_server_api_adminservice_v1_request_response_proto = out.File
6659 > file_temporal_server_api_adminservice_v1_request_response_proto_goTypes = nil
6660 > file_temporal_server_api_adminservice_v1_request_response_proto_depIdxs = nil
6661 }
go.temporal.io/server/api/replication/v1/message.pb.go 36 covered LOC · 2 ranges

Open complete file

2441 }
2442
2443 > func init() { file_temporal_server_api_replication_v1_message_proto_init() } message.pb.go
2444 > func file_temporal_server_api_replication_v1_message_proto_init() {
2445 > if File_temporal_server_api_replication_v1_message_proto != nil {
2446 return
2447 }
2448 > file_temporal_server_api_replication_v1_message_proto_msgTypes[0].OneofWrappers = []any{ message.pb.go
2449 > (*ReplicationTask_NamespaceTaskAttributes)(nil),
2450 > (*ReplicationTask_SyncShardStatusTaskAttributes)(nil),
2451 > (*ReplicationTask_SyncActivityTaskAttributes)(nil),
2452 > (*ReplicationTask_HistoryTaskAttributes)(nil),
2453 > (*ReplicationTask_SyncWorkflowStateTaskAttributes)(nil),
2454 > (*ReplicationTask_TaskQueueUserDataAttributes)(nil),
2455 > (*ReplicationTask_SyncHsmAttributes)(nil),
2456 > (*ReplicationTask_BackfillHistoryTaskAttributes)(nil),
2457 > (*ReplicationTask_VerifyVersionedTransitionTaskAttributes)(nil),
2458 > (*ReplicationTask_SyncVersionedTransitionTaskAttributes)(nil),
2459 > }
2460 > file_temporal_server_api_replication_v1_message_proto_msgTypes[21].OneofWrappers = []any{
2461 > (*VersionedTransitionArtifact_SyncWorkflowStateMutationAttributes)(nil),
2462 > (*VersionedTransitionArtifact_SyncWorkflowStateSnapshotAttributes)(nil),
2463 > }
2464 > type x struct{}
2465 > out := protoimpl.TypeBuilder{
2466 > File: protoimpl.DescBuilder{
2467 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
2468 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_replication_v1_message_proto_rawDesc), len(file_temporal_server_api_replication_v1_message_proto_rawDesc)),
2469 > NumEnums: 0,
2470 > NumMessages: 23,
2471 > NumExtensions: 0,
2472 > NumServices: 0,
2473 > },
2474 > GoTypes: file_temporal_server_api_replication_v1_message_proto_goTypes,
2475 > DependencyIndexes: file_temporal_server_api_replication_v1_message_proto_depIdxs,
2476 > MessageInfos: file_temporal_server_api_replication_v1_message_proto_msgTypes,
2477 > }.Build()
2478 > File_temporal_server_api_replication_v1_message_proto = out.File
2479 > file_temporal_server_api_replication_v1_message_proto_goTypes = nil
2480 > file_temporal_server_api_replication_v1_message_proto_depIdxs = nil
2481 }
go.temporal.io/server/common/log/tag/zap_tag.go 36 covered LOC · 8 ranges

Open complete file

26 }
27
28 > func (t ZapTag) Field() zap.Field { zap_tag.go
29 > return t.field
30 > }
31
32 > func (t ZapTag) Key() string { zap_tag.go
33 > return t.field.Key
34 > }
35
36 func (t ZapTag) Value() any {
44 }
45
46 > func NewStringTag(key string, value string) ZapTag { zap_tag.go
47 > return ZapTag{
48 > field: zap.String(key, value),
49 > }
50 > }
51
52 func NewStringsTag(key string, value []string) ZapTag {
82 }
83
84 > func NewInt64(key string, value int64) ZapTag { zap_tag.go
85 > return ZapTag{
86 > field: zap.Int64(key, value),
87 > }
88 > }
89
90 func NewInt(key string, value int) ZapTag {
94 }
95
96 > func NewInt32(key string, value int32) ZapTag { zap_tag.go
97 > return ZapTag{
98 > field: zap.Int32(key, value),
99 > }
100 > }
101
102 func NewUInt32(key string, value uint32) ZapTag {
118 }
119
120 > func NewBoolTag(key string, value bool) ZapTag { zap_tag.go
121 > return ZapTag{
122 > field: zap.Bool(key, value),
123 > }
124 > }
125
126 func NewErrorTag(key string, value error) ZapTag {
130 }
131
132 > func NewDurationTag(key string, value time.Duration) ZapTag { zap_tag.go
133 > return ZapTag{
134 > field: zap.Duration(key, value),
135 > }
136 > }
137
138 func NewDurationPtrTag(key string, value *durationpb.Duration) ZapTag {
142 }
143
144 > func NewTimeTag(key string, value time.Time) ZapTag { zap_tag.go
145 > return ZapTag{
146 > field: zap.Time(key, value),
147 > }
148 > }
149
150 func NewTimePtrTag(key string, value *timestamppb.Timestamp) ZapTag {
go.temporal.io/server/common/namespace/testconstructors.go 36 covered LOC · 8 ranges

Open complete file

13 config *persistencespb.NamespaceConfig,
14 targetCluster string,
15 > ) *Namespace { testconstructors.go
16 > detail := &persistencespb.NamespaceDetail{
17 > Info: ensureInfo(info),
18 > Config: ensureConfig(config),
19 > ReplicationConfig: &persistencespb.NamespaceReplicationConfig{
20 > ActiveClusterName: targetCluster,
21 > Clusters: []string{targetCluster},
22 > },
23 > FailoverVersion: common.EmptyVersion,
24 > }
25 > factory := NewDefaultReplicationResolverFactory()
26 > resolver := factory(detail)
27 > ns, _ := FromPersistentState(detail, resolver, WithGlobalFlag(false))
28 > return ns
29 > }
30
31 // NewNamespaceForTest returns an entry with test data
55 repConfig *persistencespb.NamespaceReplicationConfig,
56 failoverVersion int64,
57 > ) *Namespace { testconstructors.go
58 > detail := &persistencespb.NamespaceDetail{
59 > Info: ensureInfo(info),
60 > Config: ensureConfig(config),
61 > ReplicationConfig: ensureRepConfig(repConfig),
62 > FailoverVersion: failoverVersion,
63 > }
64 > factory := NewDefaultReplicationResolverFactory()
65 > resolver := factory(detail)
66 > ns, _ := FromPersistentState(detail, resolver, WithGlobalFlag(true))
67 > return ns
68 > }
69
70 > func ensureInfo(proto *persistencespb.NamespaceInfo) *persistencespb.NamespaceInfo { testconstructors.go
71 > if proto == nil {
72 return &persistencespb.NamespaceInfo{}
73 }
74 > return proto testconstructors.go
75 }
76
77 > func ensureConfig(proto *persistencespb.NamespaceConfig) *persistencespb.NamespaceConfig { testconstructors.go
78 > if proto == nil {
79 return &persistencespb.NamespaceConfig{}
80 }
81 > return proto testconstructors.go
82 }
83
84 > func ensureRepConfig(proto *persistencespb.NamespaceReplicationConfig) *persistencespb.NamespaceReplicationConfig { testconstructors.go
85 > if proto == nil {
86 return &persistencespb.NamespaceReplicationConfig{}
87 }
88 > return proto testconstructors.go
89 }
go.temporal.io/server/api/persistence/v1/update.pb.go 35 covered LOC · 3 ranges

Open complete file

222 func (*UpdateInfo) ProtoMessage() {}
223
224 > func (x *UpdateInfo) ProtoReflect() protoreflect.Message { update.pb.go
225 > mi := &file_temporal_server_api_persistence_v1_update_proto_msgTypes[3]
226 > if x != nil {
227 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
228 if ms.LoadMessageInfo() == nil {
231 return ms
232 }
233 > return mi.MessageOf(x) update.pb.go
234 }
235
422 }
423
424 > func init() { file_temporal_server_api_persistence_v1_update_proto_init() } update.pb.go
425 > func file_temporal_server_api_persistence_v1_update_proto_init() {
426 > if File_temporal_server_api_persistence_v1_update_proto != nil {
427 > return
428 > }
429 > file_temporal_server_api_persistence_v1_hsm_proto_init()
430 > file_temporal_server_api_persistence_v1_update_proto_msgTypes[0].OneofWrappers = []any{
431 > (*UpdateAdmissionInfo_HistoryPointer_)(nil),
432 > }
433 > file_temporal_server_api_persistence_v1_update_proto_msgTypes[3].OneofWrappers = []any{
434 > (*UpdateInfo_Acceptance)(nil),
435 > (*UpdateInfo_Completion)(nil),
436 > (*UpdateInfo_Admission)(nil),
437 > }
438 > type x struct{}
439 > out := protoimpl.TypeBuilder{
440 > File: protoimpl.DescBuilder{
441 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
442 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_update_proto_rawDesc), len(file_temporal_server_api_persistence_v1_update_proto_rawDesc)),
443 > NumEnums: 0,
444 > NumMessages: 5,
445 > NumExtensions: 0,
446 > NumServices: 0,
447 > },
448 > GoTypes: file_temporal_server_api_persistence_v1_update_proto_goTypes,
449 > DependencyIndexes: file_temporal_server_api_persistence_v1_update_proto_depIdxs,
450 > MessageInfos: file_temporal_server_api_persistence_v1_update_proto_msgTypes,
451 > }.Build()
452 > File_temporal_server_api_persistence_v1_update_proto = out.File
453 > file_temporal_server_api_persistence_v1_update_proto_goTypes = nil
454 > file_temporal_server_api_persistence_v1_update_proto_depIdxs = nil
455 }
go.temporal.io/server/common/searchattribute/sadefs/encode_value.go 34 covered LOC · 13 ranges

Open complete file

13
14 // EncodeValue encodes search attribute value and IndexedValueType to Payload.
15 > func EncodeValue(val any, t enumspb.IndexedValueType) (*commonpb.Payload, error) { encode_value.go
16 > valPayload, err := payload.Encode(val)
17 > if err != nil {
18 return nil, err
19 }
20
21 > SetMetadataType(valPayload, t) encode_value.go
22 > return valPayload, nil
23 }
24
42 t enumspb.IndexedValueType,
43 allowList bool,
44 > ) (any, error) { encode_value.go
45 > if t == enumspb.INDEXED_VALUE_TYPE_UNSPECIFIED {
46 t = GetMetadataType(value)
47 }
48 > if t == enumspb.INDEXED_VALUE_TYPE_UNSPECIFIED { encode_value.go
49 return nil, fmt.Errorf("%w: %v", ErrInvalidType, t)
50 }
51
52 > switch t { encode_value.go
53 case enumspb.INDEXED_VALUE_TYPE_BOOL:
54 return decodeValueTyped[bool](value, allowList)
63 case enumspb.INDEXED_VALUE_TYPE_TEXT:
64 return validateStrings(decodeValueTyped[string](value, allowList))
65 > case enumspb.INDEXED_VALUE_TYPE_KEYWORD_LIST: encode_value.go
66 > return validateStrings(decodeValueTyped[[]string](value, false))
67 default:
68 return nil, fmt.Errorf("%w: %v", ErrInvalidType, t)
70 }
71
72 > func validateStrings(anyValue any, err error) (any, error) { encode_value.go
73 > if err != nil {
74 return anyValue, err
75 }
76
77 // validate strings
78 > switch value := anyValue.(type) { encode_value.go
79 case string:
80 if !utf8.ValidString(value) {
81 return nil, fmt.Errorf("%w: %s", ErrInvalidString, value)
82 }
83 > case []string: encode_value.go
84 > for _, item := range value {
85 > if !utf8.ValidString(item) {
86 return nil, fmt.Errorf("%w: %s", ErrInvalidString, item)
87 }
88 }
89 }
90 > return anyValue, err encode_value.go
91 }
92
96 //
97 //nolint:revive // allowList is a control flag
98 > func decodeValueTyped[T any](value *commonpb.Payload, allowList bool) (any, error) { encode_value.go
99 > // At first, it tries to decode to pointer of actual type (i.e. `*string` for `string`).
100 > // This is to ensure that `nil` values are decoded back as `nil` using `NilPayloadConverter`.
101 > // If value is not `nil` but some value of expected type, the code relies on the fact that
102 > // search attributes are always encoded with `JsonPayloadConverter`, which uses standard
103 > // `json.Unmarshal` function, which works fine with pointer types when decoding values.
104 > // If decoding to pointer type fails, it tries to decode to array of the same type because
105 > // search attributes support polymorphism: field of specific type may also have an array of that type.
106 > // If resulting slice has zero length, it gets substitute with `nil` to treat nils and empty slices equally.
107 > // If allowList is true, it returns the list as it is. If allowList is false and the list has
108 > // only one element, then return it. Otherwise, return an error.
109 > // If search attribute value is `nil`, it means that search attribute needs to be removed from the document.
110 > var val *T
111 > if err := payload.Decode(value, &val); err == nil {
112 > if val == nil { encode_value.go
113 return nil, nil
114 }
115 > return *val, nil encode_value.go
116 }
117 var listVal []T
go.temporal.io/server/api/persistence/v1/history_tree.pb.go 32 covered LOC · 5 ranges

Open complete file

122 func (*HistoryBranch) ProtoMessage() {}
123
124 > func (x *HistoryBranch) ProtoReflect() protoreflect.Message { history_tree.pb.go
125 > mi := &file_temporal_server_api_persistence_v1_history_tree_proto_msgTypes[1]
126 > if x != nil {
127 > ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
128 > if ms.LoadMessageInfo() == nil {
129 > ms.StoreMessageInfo(mi)
130 > }
131 > return ms
132 }
133 return mi.MessageOf(x)
186 func (*HistoryBranchRange) ProtoMessage() {}
187
188 > func (x *HistoryBranchRange) ProtoReflect() protoreflect.Message { history_tree.pb.go
189 > mi := &file_temporal_server_api_persistence_v1_history_tree_proto_msgTypes[2]
190 > if x != nil {
191 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
192 if ms.LoadMessageInfo() == nil {
274 }
275
276 > func init() { file_temporal_server_api_persistence_v1_history_tree_proto_init() } history_tree.pb.go
277 > func file_temporal_server_api_persistence_v1_history_tree_proto_init() {
278 > if File_temporal_server_api_persistence_v1_history_tree_proto != nil {
279 return
280 }
281 > type x struct{} history_tree.pb.go
282 > out := protoimpl.TypeBuilder{
283 > File: protoimpl.DescBuilder{
284 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
285 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_history_tree_proto_rawDesc), len(file_temporal_server_api_persistence_v1_history_tree_proto_rawDesc)),
286 > NumEnums: 0,
287 > NumMessages: 3,
288 > NumExtensions: 0,
289 > NumServices: 0,
290 > },
291 > GoTypes: file_temporal_server_api_persistence_v1_history_tree_proto_goTypes,
292 > DependencyIndexes: file_temporal_server_api_persistence_v1_history_tree_proto_depIdxs,
293 > MessageInfos: file_temporal_server_api_persistence_v1_history_tree_proto_msgTypes,
294 > }.Build()
295 > File_temporal_server_api_persistence_v1_history_tree_proto = out.File
296 > file_temporal_server_api_persistence_v1_history_tree_proto_goTypes = nil
297 > file_temporal_server_api_persistence_v1_history_tree_proto_depIdxs = nil
298 }
go.temporal.io/server/api/persistence/v1/workflow_mutable_state.pb.go 32 covered LOC · 4 ranges

Open complete file

55 func (*WorkflowMutableState) ProtoMessage() {}
56
57 > func (x *WorkflowMutableState) ProtoReflect() protoreflect.Message { workflow_mutable_state.pb.go
58 > mi := &file_temporal_server_api_persistence_v1_workflow_mutable_state_proto_msgTypes[0]
59 > if x != nil {
60 > ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) workflow_mutable_state.pb.go
61 > if ms.LoadMessageInfo() == nil {
62 > ms.StoreMessageInfo(mi)
63 > }
64 > return ms
65 }
66 return mi.MessageOf(x)
532 }
533
534 > func init() { file_temporal_server_api_persistence_v1_workflow_mutable_state_proto_init() } workflow_mutable_state.pb.go
535 > func file_temporal_server_api_persistence_v1_workflow_mutable_state_proto_init() {
536 > if File_temporal_server_api_persistence_v1_workflow_mutable_state_proto != nil {
537 return
538 }
539 > file_temporal_server_api_persistence_v1_chasm_proto_init() workflow_mutable_state.pb.go
540 > file_temporal_server_api_persistence_v1_executions_proto_init()
541 > file_temporal_server_api_persistence_v1_hsm_proto_init()
542 > file_temporal_server_api_persistence_v1_update_proto_init()
543 > type x struct{}
544 > out := protoimpl.TypeBuilder{
545 > File: protoimpl.DescBuilder{
546 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
547 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_workflow_mutable_state_proto_rawDesc), len(file_temporal_server_api_persistence_v1_workflow_mutable_state_proto_rawDesc)),
548 > NumEnums: 0,
549 > NumMessages: 16,
550 > NumExtensions: 0,
551 > NumServices: 0,
552 > },
553 > GoTypes: file_temporal_server_api_persistence_v1_workflow_mutable_state_proto_goTypes,
554 > DependencyIndexes: file_temporal_server_api_persistence_v1_workflow_mutable_state_proto_depIdxs,
555 > MessageInfos: file_temporal_server_api_persistence_v1_workflow_mutable_state_proto_msgTypes,
556 > }.Build()
557 > File_temporal_server_api_persistence_v1_workflow_mutable_state_proto = out.File
558 > file_temporal_server_api_persistence_v1_workflow_mutable_state_proto_goTypes = nil
559 > file_temporal_server_api_persistence_v1_workflow_mutable_state_proto_depIdxs = nil
560 }
go.temporal.io/server/service/history/api/update_workflow_util.go 32 covered LOC · 13 ranges

Open complete file

20 shard historyi.ShardContext,
21 workflowConsistencyChecker WorkflowConsistencyChecker,
22 > ) (retError error) { update_workflow_util.go
23 > workflowLease, err := workflowConsistencyChecker.GetWorkflowLease(
24 > ctx,
25 > reqClock,
26 > workflowKey,
27 > locks.PriorityHigh,
28 > )
29 > if err != nil {
30 return err
31 }
32 > defer func() { workflowLease.GetReleaseFn()(retError) }() update_workflow_util.go
33
34 > return UpdateWorkflowWithNew(shard, ctx, workflowLease, action, newWorkflowFn) update_workflow_util.go
35 }
36
66 action UpdateWorkflowActionFunc,
67 newWorkflowFn func() (historyi.WorkflowContext, historyi.MutableState, error),
68 > ) (retError error) { update_workflow_util.go
69 >
70 > // conduct caller action
71 > postActions, err := action(workflowLease)
72 > if err != nil {
73 return err
74 }
75 > if postActions.Noop { update_workflow_util.go
76 return nil
77 }
78
79 > mutableState := workflowLease.GetMutableState() update_workflow_util.go
80 > if postActions.CreateWorkflowTask {
81 > // Create a transfer task to schedule a workflow task only if the workflow is not paused and there is no pending workflow task. update_workflow_util.go
82 > if !mutableState.HasPendingWorkflowTask() && !mutableState.IsWorkflowExecutionStatusPaused() {
83 > if _, err := mutableState.AddWorkflowTaskScheduledEvent( update_workflow_util.go
84 > false,
85 > enumsspb.WORKFLOW_TASK_TYPE_NORMAL,
86 > ); err != nil {
87 return err
88 }
90 }
91
92 > var updateErr error update_workflow_util.go
93 > if newWorkflowFn != nil {
94 newContext, newMutableState, err := newWorkflowFn()
95 if err != nil {
110 newMutableState,
111 )
112 > } else { update_workflow_util.go
113 > updateErr = workflowLease.GetContext().UpdateWorkflowExecutionAsActive(ctx, shardContext)
114 > }
115
116 > if updateErr != nil { update_workflow_util.go
117 return updateErr
118 }
119
120 > if postActions.AbortUpdates { update_workflow_util.go
121 workflowLease.GetContext().UpdateRegistry(ctx).Abort(update.AbortReasonWorkflowCompleted)
122 }
123
124 > return nil update_workflow_util.go
125 }
go.temporal.io/server/common/dynamicconfig/deepcopy.go 31 covered LOC · 6 ranges

Open complete file

9 // deepCopyForMapstructure does a simple deep copy of T. Fancy cases (anything other than plain old data)
10 // is not handled and will panic.
11 > func deepCopyForMapstructure[T any](t T) T { deepcopy.go
12 > // nolint:revive // this will be triggered from a static initializer before it can be triggered from production code
13 > return deepCopyValue(reflect.ValueOf(t)).Interface().(T)
14 > }
15
16 > func deepCopyValue(v reflect.Value) reflect.Value { deepcopy.go
17 > switch v.Kind() {
18 case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
19 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
20 > reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.String: deepcopy.go
21 > nv := reflect.New(v.Type()).Elem()
22 > nv.Set(v)
23 > return nv
24 case reflect.Array:
25 nv := reflect.New(v.Type()).Elem()
42 }
43 return deepCopyValue(v.Elem()).Addr()
44 > case reflect.Slice: deepcopy.go
45 > if v.IsNil() {
46 > return v
47 > }
48 nv := reflect.MakeSlice(v.Type(), v.Len(), v.Len())
49 for i := range v.Len() {
51 }
52 return nv
53 > case reflect.Struct: deepcopy.go
54 > // Special case for time.Time: it has unexported fields so we can't copy it field by
55 > // field, but we can copy zero values (which is all we need for default values).
56 > if v.Type() == reflect.TypeFor[time.Time]() {
57 > if v.Interface().(time.Time).IsZero() {
58 > return reflect.ValueOf(time.Time{})
59 > }
60 // nolint:forbidigo // this will be triggered from a static initializer before it can be triggered from production code
61 panic(fmt.Sprintf("Can't deep copy non-zero time.Time: %v", v.Interface()))
62 }
63 > nv := reflect.New(v.Type()).Elem() deepcopy.go
64 > for i := range v.Type().NumField() {
65 > nv.Field(i).Set(deepCopyValue(v.Field(i)))
66 > }
67 > return nv
68 > case reflect.Interface, reflect.Func, reflect.Chan:
69 > // only nil values of any other reference types allowed!
70 > if v.IsNil() {
71 > return v
72 > }
73 fallthrough
74 default:
go.temporal.io/server/common/util.go 31 covered LOC · 6 ranges

Open complete file

161
162 // CreatePersistenceClientRetryPolicy creates a retry policy for calls to persistence
163 > func CreatePersistenceClientRetryPolicy() backoff.RetryPolicy { util.go
164 > return backoff.NewExponentialRetryPolicy(persistenceClientRetryInitialInterval).
165 > WithMaximumAttempts(persistenceClientRetryMaxAttempts)
166 > }
167
168 // CreateFrontendClientRetryPolicy creates a retry policy for calls to frontend service
249
250 // CreateTaskReschedulePolicy creates a retry policy for rescheduling task with errors not equal to ErrTaskRetry
251 > func CreateTaskReschedulePolicy() backoff.RetryPolicy { util.go
252 > return backoff.NewExponentialRetryPolicy(taskRescheduleInitialInterval).
253 > WithBackoffCoefficient(taskRescheduleBackoffCoefficient).
254 > WithMaximumInterval(taskRescheduleMaxInterval).
255 > WithExpirationInterval(backoff.NoInterval)
256 > }
257
258 // CreateDependencyTaskNotCompletedReschedulePolicy creates a retry policy for rescheduling task with
259 // ErrDependencyTaskNotCompleted
260 > func CreateDependencyTaskNotCompletedReschedulePolicy() backoff.RetryPolicy { util.go
261 > return backoff.NewExponentialRetryPolicy(dependencyTaskNotCompletedRescheduleInitialInterval).
262 > WithBackoffCoefficient(dependencyTaskNotCompletedRescheduleBackoffCoefficient).
263 > WithMaximumInterval(dependencyTaskNotCompletedRescheduleMaxInterval).
264 > WithExpirationInterval(backoff.NoInterval)
265 > }
266
267 // CreateTaskNotReadyReschedulePolicy creates a retry policy for rescheduling task with ErrTaskRetry
268 > func CreateTaskNotReadyReschedulePolicy() backoff.RetryPolicy { util.go
269 > return backoff.NewExponentialRetryPolicy(taskNotReadyRescheduleInitialInterval).
270 > WithBackoffCoefficient(taskNotReadyRescheduleBackoffCoefficient).
271 > WithMaximumInterval(taskNotReadyRescheduleMaxInterval).
272 > WithExpirationInterval(backoff.NoInterval)
273 > }
274
275 // CreateTaskResourceExhaustedReschedulePolicy creates a retry policy for rescheduling task with resource exhausted error
276 > func CreateTaskResourceExhaustedReschedulePolicy() backoff.RetryPolicy { util.go
277 > return backoff.NewExponentialRetryPolicy(taskResourceExhaustedRescheduleInitialInterval).
278 > WithBackoffCoefficient(taskResourceExhaustedRescheduleBackoffCoefficient).
279 > WithMaximumInterval(taskResourceExhaustedRescheduleMaxInterval).
280 > WithExpirationInterval(backoff.NoInterval)
281 > }
282
283 // CreateSdkClientFactoryRetryPolicy creates a retry policy to handle SdkClientFactory NewClient when frontend service is not ready
688
689 // CloneProto is a generic typed version of proto.Clone from proto.
690 > func CloneProto[T proto.Message](v T) T { util.go
691 > return proto.Clone(v).(T)
692 > }
693
694 func CloneProtoMap[K comparable, T proto.Message](src map[K]T) map[K]T {
go.temporal.io/server/service/history/shard/task_key_manager.go 31 covered LOC · 6 ranges

Open complete file

28 logger log.Logger,
29 renewRangeIDFn renewRangeIDFn,
30 > ) *taskKeyManager { task_key_manager.go
31 > return &taskKeyManager{
32 > generator: newTaskKeyGenerator(
33 > config.RangeSizeBits,
34 > timeSource,
35 > logger,
36 > renewRangeIDFn,
37 > ),
38 > tracker: newTaskRequestTracker(taskCategoryRegistry),
39 > timeSource: timeSource,
40 > logger: logger,
41 > config: config,
42 > }
43 > }
44
45 func (m *taskKeyManager) setAndTrackTaskKeys(
46 taskMaps ...map[tasks.Category][]tasks.Task,
47 > ) (taskRequestCompletionFn, error) { task_key_manager.go
48 >
49 > if err := m.generator.setTaskKeys(taskMaps...); err != nil {
50 return nil, err
51 }
52
53 > return m.tracker.track(taskMaps...), nil task_key_manager.go
54 }
55
56 func (m *taskKeyManager) peekTaskKey(
57 category tasks.Category,
58 > ) tasks.Key { task_key_manager.go
59 > return m.generator.peekTaskKey(category)
60 > }
61
62 func (m *taskKeyManager) generateTaskKey(
63 category tasks.Category,
64 > ) (tasks.Key, error) { task_key_manager.go
65 > return m.generator.generateTaskKey(category)
66 > }
67
68 func (m *taskKeyManager) drainTaskRequests() {
72 func (m *taskKeyManager) setRangeID(
73 rangeID int64,
75 > m.generator.setRangeID(rangeID)
76 >
77 > // rangeID update means all pending add tasks requests either already succeeded
78 > // are guaranteed to fail, so we can clear pending requests in the tracker
79 > m.tracker.clear()
80 > }
81
82 func (m *taskKeyManager) setTaskMinScheduledTime(
go.temporal.io/server/api/enums/v1/task.pb.go 30 covered LOC · 6 ranges

Open complete file

217 }
218
219 > func (x TaskType) String() string { task.pb.go
220 > switch x {
221 case TASK_TYPE_UNSPECIFIED:
222 return "Unspecified"
225 case TASK_TYPE_REPLICATION_SYNC_ACTIVITY:
226 return "ReplicationSyncActivity"
227 > case TASK_TYPE_TRANSFER_WORKFLOW_TASK: task.pb.go
228 > return "TransferWorkflowTask"
229 case TASK_TYPE_TRANSFER_ACTIVITY_TASK:
230 return "TransferActivityTask"
303 }
304
305 > func (TaskType) Descriptor() protoreflect.EnumDescriptor { task.pb.go
306 > return file_temporal_server_api_enums_v1_task_proto_enumTypes[1].Descriptor()
307 > }
308
309 func (TaskType) Type() protoreflect.EnumType {
361 }
362
363 > func (TaskPriority) Descriptor() protoreflect.EnumDescriptor { task.pb.go
364 > return file_temporal_server_api_enums_v1_task_proto_enumTypes[2].Descriptor()
365 > }
366
367 func (TaskPriority) Type() protoreflect.EnumType {
456 }
457
458 > func init() { file_temporal_server_api_enums_v1_task_proto_init() } task.pb.go
459 > func file_temporal_server_api_enums_v1_task_proto_init() {
460 > if File_temporal_server_api_enums_v1_task_proto != nil {
461 return
462 }
463 > type x struct{} task.pb.go
464 > out := protoimpl.TypeBuilder{
465 > File: protoimpl.DescBuilder{
466 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
467 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_enums_v1_task_proto_rawDesc), len(file_temporal_server_api_enums_v1_task_proto_rawDesc)),
468 > NumEnums: 3,
469 > NumMessages: 0,
470 > NumExtensions: 0,
471 > NumServices: 0,
472 > },
473 > GoTypes: file_temporal_server_api_enums_v1_task_proto_goTypes,
474 > DependencyIndexes: file_temporal_server_api_enums_v1_task_proto_depIdxs,
475 > EnumInfos: file_temporal_server_api_enums_v1_task_proto_enumTypes,
476 > }.Build()
477 > File_temporal_server_api_enums_v1_task_proto = out.File
478 > file_temporal_server_api_enums_v1_task_proto_goTypes = nil
479 > file_temporal_server_api_enums_v1_task_proto_depIdxs = nil
480 }
go.temporal.io/server/api/workflow/v1/message.pb.go 30 covered LOC · 8 ranges

Open complete file

102 }
103
104 > func (x *ParentExecutionInfo) GetClock() *v11.VectorClock { message.pb.go
105 > if x != nil {
106 return x.Clock
107 }
108 > return nil message.pb.go
109 }
110
160 }
161
162 > func (x *RootExecutionInfo) GetExecution() *v1.WorkflowExecution { message.pb.go
163 > if x != nil {
164 return x.Execution
165 }
166 > return nil message.pb.go
167 }
168
189 func (*BaseExecutionInfo) ProtoMessage() {}
190
191 > func (x *BaseExecutionInfo) ProtoReflect() protoreflect.Message { message.pb.go
192 > mi := &file_temporal_server_api_workflow_v1_message_proto_msgTypes[2]
193 > if x != nil {
194 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
195 if ms.LoadMessageInfo() == nil {
198 return ms
199 }
200 > return mi.MessageOf(x) message.pb.go
201 }
202
278 }
279
280 > func init() { file_temporal_server_api_workflow_v1_message_proto_init() } message.pb.go
281 > func file_temporal_server_api_workflow_v1_message_proto_init() {
282 > if File_temporal_server_api_workflow_v1_message_proto != nil {
283 return
284 }
285 > type x struct{} message.pb.go
286 > out := protoimpl.TypeBuilder{
287 > File: protoimpl.DescBuilder{
288 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
289 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_workflow_v1_message_proto_rawDesc), len(file_temporal_server_api_workflow_v1_message_proto_rawDesc)),
290 > NumEnums: 0,
291 > NumMessages: 3,
292 > NumExtensions: 0,
293 > NumServices: 0,
294 > },
295 > GoTypes: file_temporal_server_api_workflow_v1_message_proto_goTypes,
296 > DependencyIndexes: file_temporal_server_api_workflow_v1_message_proto_depIdxs,
297 > MessageInfos: file_temporal_server_api_workflow_v1_message_proto_msgTypes,
298 > }.Build()
299 > File_temporal_server_api_workflow_v1_message_proto = out.File
300 > file_temporal_server_api_workflow_v1_message_proto_goTypes = nil
301 > file_temporal_server_api_workflow_v1_message_proto_depIdxs = nil
302 }
go.temporal.io/server/common/persistence/sql/sqlplugin/mysql/execution_maps.go 30 covered LOC · 5 ranges

Open complete file

53 )
54
55 > func stringMap(a []string, f func(string) string) []string { execution_maps.go
56 > b := make([]string, len(a))
57 > for i, v := range a {
58 > b[i] = f(v)
59 > }
60 > return b
61 }
62
63 > func makeDeleteMapQry(tableName string) string { execution_maps.go
64 > return fmt.Sprintf(deleteMapQryTemplate, tableName)
65 > }
66
67 > func makeSetKeyInMapQry(tableName string, nonPrimaryKeyColumns []string, mapKeyName string) string { execution_maps.go
68 > return fmt.Sprintf(setKeyInMapQryTemplate,
69 > tableName,
70 > strings.Join(nonPrimaryKeyColumns, ","),
71 > strings.Join(stringMap(nonPrimaryKeyColumns, func(x string) string {
72 > return ":" + x
73 > }), ","),
74 > strings.Join(stringMap(nonPrimaryKeyColumns, func(x string) string {
75 > return x + "=VALUES(" + x + ")"
76 > }), ","),
77 mapKeyName)
78 }
79
80 > func makeDeleteKeyInMapQry(tableName string, mapKeyName string) string { execution_maps.go
81 > return fmt.Sprintf(deleteKeyInMapQryTemplate,
82 > tableName,
83 > mapKeyName)
84 > }
85
86 > func makeGetMapQryTemplate(tableName string, nonPrimaryKeyColumns []string, mapKeyName string) string { execution_maps.go
87 > return fmt.Sprintf(getMapQryTemplate,
88 > tableName,
89 > mapKeyName,
90 > strings.Join(nonPrimaryKeyColumns, ","))
91 > }
92
93 var (
go.temporal.io/server/common/persistence/sql/sqlplugin/postgresql/execution_maps.go 30 covered LOC · 6 ranges

Open complete file

86 )
87
88 > func stringMap(a []string, f func(string) string) []string { execution_maps.go
89 > b := make([]string, len(a))
90 > for i, v := range a {
91 > b[i] = f(v)
92 > }
93 > return b
94 }
95
96 > func makeDeleteMapQry(tableName string) string { execution_maps.go
97 > return fmt.Sprintf(deleteMapQueryTemplate, tableName)
98 > }
99
100 > func makeSetKeyInMapQry(tableName string, nonPrimaryKeyColumns []string, mapKeyName string) string { execution_maps.go
101 > return fmt.Sprintf(setKeyInMapQueryTemplate,
102 > tableName,
103 > strings.Join(nonPrimaryKeyColumns, ","),
104 > strings.Join(stringMap(nonPrimaryKeyColumns, func(x string) string {
105 > return ":" + x
106 > }), ","),
107 mapKeyName,
108 > strings.Join(stringMap(nonPrimaryKeyColumns, func(x string) string { execution_maps.go
109 > return "excluded." + x
110 > }), ","))
111 }
112
113 > func makeDeleteKeyInMapQry(tableName string, mapKeyName string) string { execution_maps.go
114 > return fmt.Sprintf(deleteKeyInMapQueryTemplate,
115 > tableName,
116 > mapKeyName)
117 > }
118
119 > func makeGetMapQryTemplate(tableName string, nonPrimaryKeyColumns []string, mapKeyName string) string { execution_maps.go
120 > return fmt.Sprintf(getMapQueryTemplate,
121 > tableName,
122 > mapKeyName,
123 > strings.Join(nonPrimaryKeyColumns, ","))
124 > }
125
126 var (
go.temporal.io/server/common/persistence/sql/sqlplugin/sqlite/execution_maps.go 30 covered LOC · 5 ranges

Open complete file

52 )
53
54 > func stringMap(a []string, f func(string) string) []string { execution_maps.go
55 > b := make([]string, len(a))
56 > for i, v := range a {
57 > b[i] = f(v)
58 > }
59 > return b
60 }
61
62 > func makeDeleteMapQry(tableName string) string { execution_maps.go
63 > return fmt.Sprintf(deleteMapQryTemplate, tableName)
64 > }
65
66 > func makeSetKeyInMapQry(tableName string, nonPrimaryKeyColumns []string, mapKeyName string) string { execution_maps.go
67 > return fmt.Sprintf(setKeyInMapQryTemplate,
68 > tableName,
69 > strings.Join(nonPrimaryKeyColumns, ","),
70 > strings.Join(stringMap(nonPrimaryKeyColumns, func(x string) string {
71 > return ":" + x
72 > }), ","),
73 > strings.Join(stringMap(nonPrimaryKeyColumns, func(x string) string {
74 > return x + "=" + x
75 > }), ","),
76 mapKeyName)
77 }
78
79 > func makeDeleteKeyInMapQry(tableName string, mapKeyName string) string { execution_maps.go
80 > return fmt.Sprintf(deleteKeyInMapQryTemplate,
81 > tableName,
82 > mapKeyName)
83 > }
84
85 > func makeGetMapQryTemplate(tableName string, nonPrimaryKeyColumns []string, mapKeyName string) string { execution_maps.go
86 > return fmt.Sprintf(getMapQryTemplate,
87 > tableName,
88 > mapKeyName,
89 > strings.Join(nonPrimaryKeyColumns, ","))
90 > }
91
92 var (
go.temporal.io/server/common/searchattribute/sadefs/constants.go 30 covered LOC · 9 ranges

Open complete file

261 }
262
263 > dbCustomSearchAttributeFieldNameRE = func() map[enumspb.IndexedValueType]*regexp.Regexp { constants.go
264 > res := map[enumspb.IndexedValueType]*regexp.Regexp{}
265 > for t := range defaultNumDBCustomSearchAttributes {
266 > res[t] = regexp.MustCompile(fmt.Sprintf(`^%s(0[1-9]|[1-9][0-9])$`, t.String()))
267 > }
268 > return res
269 }()
270 )
271
272 // System returns a clone of the system search attributes map.
273 > func System() map[string]enumspb.IndexedValueType { constants.go
274 > return maps.Clone(system)
275 > }
276
277 // Predefined returns a clone of the predefined search attributes map.
278 > func Predefined() map[string]enumspb.IndexedValueType { constants.go
279 > return maps.Clone(predefined)
280 > }
281
282 // PredefinedWhiteList returns a clone of the predefined whitelist search attributes map.
283 > func PredefinedWhiteList() map[string]enumspb.IndexedValueType { constants.go
284 > return maps.Clone(predefinedWhiteList)
285 > }
286
287 // Reserved returns a clone of the reserved field names map.
343 // GetSqlDbColName maps system and reserved search attributes to column names for SQL tables.
344 // If the input is not a system or reserved search attribute, then it returns the input.
345 > func GetSqlDbColName(name string) string { constants.go
346 > if fieldName, ok := sqlDbSystemNameToColName[name]; ok {
347 > return fieldName constants.go
348 > }
349 return name
350 }
352 func GetDBIndexSearchAttributes(
353 override map[enumspb.IndexedValueType]int,
354 > ) *persistencespb.IndexSearchAttributes { constants.go
355 > csa := map[string]enumspb.IndexedValueType{}
356 > for saType, defaultNumAttrs := range defaultNumDBCustomSearchAttributes {
357 > numAttrs := defaultNumAttrs
358 > if value, ok := override[saType]; ok {
359 numAttrs = value
360 }
361 > for i := range numAttrs { constants.go
362 > csa[fmt.Sprintf("%s%02d", saType.String(), i+1)] = saType
363 > }
364 }
365 > return &persistencespb.IndexSearchAttributes{ constants.go
366 > CustomSearchAttributes: csa,
367 > }
368 }
369
go.temporal.io/server/api/enums/v1/workflow_task_type.pb.go 29 covered LOC · 6 ranges

Open complete file

72 }
73
74 > func (WorkflowTaskType) Descriptor() protoreflect.EnumDescriptor { workflow_task_type.pb.go
75 > return file_temporal_server_api_enums_v1_workflow_task_type_proto_enumTypes[0].Descriptor()
76 > }
77
78 func (WorkflowTaskType) Type() protoreflect.EnumType {
124 }
125
126 > func init() { file_temporal_server_api_enums_v1_workflow_task_type_proto_init() } workflow_task_type.pb.go
127 > func file_temporal_server_api_enums_v1_workflow_task_type_proto_init() {
128 > if File_temporal_server_api_enums_v1_workflow_task_type_proto != nil {
129 return
130 }
131 > type x struct{} workflow_task_type.pb.go
132 > out := protoimpl.TypeBuilder{
133 > File: protoimpl.DescBuilder{
134 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
135 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_enums_v1_workflow_task_type_proto_rawDesc), len(file_temporal_server_api_enums_v1_workflow_task_type_proto_rawDesc)),
136 > NumEnums: 1,
137 > NumMessages: 0,
138 > NumExtensions: 0,
139 > NumServices: 0,
140 > },
141 > GoTypes: file_temporal_server_api_enums_v1_workflow_task_type_proto_goTypes,
142 > DependencyIndexes: file_temporal_server_api_enums_v1_workflow_task_type_proto_depIdxs,
143 > EnumInfos: file_temporal_server_api_enums_v1_workflow_task_type_proto_enumTypes,
144 > }.Build()
145 > File_temporal_server_api_enums_v1_workflow_task_type_proto = out.File
146 > file_temporal_server_api_enums_v1_workflow_task_type_proto_goTypes = nil
147 > file_temporal_server_api_enums_v1_workflow_task_type_proto_depIdxs = nil
148 }
go.temporal.io/server/api/taskqueue/v1/message.pb.go 29 covered LOC · 2 ranges

Open complete file

1330 }
1331
1332 > func init() { file_temporal_server_api_taskqueue_v1_message_proto_init() } message.pb.go
1333 > func file_temporal_server_api_taskqueue_v1_message_proto_init() {
1334 > if File_temporal_server_api_taskqueue_v1_message_proto != nil {
1335 return
1336 }
1337 > file_temporal_server_api_taskqueue_v1_message_proto_msgTypes[0].OneofWrappers = []any{ message.pb.go
1338 > (*TaskVersionDirective_UseAssignmentRules)(nil),
1339 > (*TaskVersionDirective_AssignedBuildId)(nil),
1340 > }
1341 > file_temporal_server_api_taskqueue_v1_message_proto_msgTypes[5].OneofWrappers = []any{
1342 > (*TaskQueuePartition_NormalPartitionId)(nil),
1343 > (*TaskQueuePartition_StickyName)(nil),
1344 > (*TaskQueuePartition_WorkerCommands)(nil),
1345 > }
1346 > type x struct{}
1347 > out := protoimpl.TypeBuilder{
1348 > File: protoimpl.DescBuilder{
1349 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
1350 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_taskqueue_v1_message_proto_rawDesc), len(file_temporal_server_api_taskqueue_v1_message_proto_rawDesc)),
1351 > NumEnums: 0,
1352 > NumMessages: 16,
1353 > NumExtensions: 0,
1354 > NumServices: 0,
1355 > },
1356 > GoTypes: file_temporal_server_api_taskqueue_v1_message_proto_goTypes,
1357 > DependencyIndexes: file_temporal_server_api_taskqueue_v1_message_proto_depIdxs,
1358 > MessageInfos: file_temporal_server_api_taskqueue_v1_message_proto_msgTypes,
1359 > }.Build()
1360 > File_temporal_server_api_taskqueue_v1_message_proto = out.File
1361 > file_temporal_server_api_taskqueue_v1_message_proto_goTypes = nil
1362 > file_temporal_server_api_taskqueue_v1_message_proto_depIdxs = nil
1363 }
go.temporal.io/server/common/future/future_impl.go 29 covered LOC · 6 ranges

Open complete file

29 )
30
31 > func NewFuture[T any]() *FutureImpl[T] { future_impl.go
32 > var value T
33 > return &FutureImpl[T]{
34 > status: pending,
35 > readyCh: make(chan struct{}),
36 >
37 > value: value,
38 > err: nil,
39 > }
40 > }
41
42 func (f *FutureImpl[T]) Get(
43 ctx context.Context,
44 > ) (T, error) { future_impl.go
45 > if f.Ready() {
46 > return f.value, f.err future_impl.go
47 > }
48
49 select {
67 value T,
68 err error,
69 > ) { future_impl.go
70 > // cannot directly set status to `ready`, to prevent data race in case multiple `Get` occurs
71 > // instead set status to `setting` to prevent concurrent completion of this future
72 > if !atomic.CompareAndSwapInt32(
73 > &f.status,
74 > pending,
75 > setting,
76 > ) {
77 panic("future has already been completed")
78 }
79
80 > f.value = value future_impl.go
81 > f.err = err
82 > atomic.CompareAndSwapInt32(&f.status, setting, ready)
83 > close(f.readyCh)
84 }
85
104 }
105
106 > func (f *FutureImpl[T]) Ready() bool { future_impl.go
107 > return atomic.LoadInt32(&f.status) == ready
108 > }
go.temporal.io/server/common/namespace/replication_resolver.go 29 covered LOC · 8 ranges

Open complete file

49 }
50
51 > func NewDefaultReplicationResolverFactory() ReplicationResolverFactory { replication_resolver.go
52 > return func(detail *persistencespb.NamespaceDetail) ReplicationResolver {
53 > // By convention, a namespace with non-zero failover version is a global namespace
54 > // This can be overridden by WithGlobalFlag mutation if needed
55 > isGlobal := detail.FailoverVersion != 0
56 > return &defaultReplicationResolver{
57 > replicationConfig: detail.ReplicationConfig,
58 > isGlobalNamespace: isGlobal,
59 > failoverVersion: detail.FailoverVersion,
60 > failoverNotificationVersion: detail.FailoverNotificationVersion,
61 > }
62 > }
63 }
64
65 > func (r *defaultReplicationResolver) ActiveClusterName(_ RoutingKey) string { replication_resolver.go
66 > if r.replicationConfig == nil {
67 return ""
68 }
69 > return r.replicationConfig.ActiveClusterName replication_resolver.go
70 }
71
79 }
80
81 > func (r *defaultReplicationResolver) ClusterNames(businessID string) []string { replication_resolver.go
82 > if r.replicationConfig == nil {
83 return nil
84 }
85 // copy slice to preserve immutability
86 > out := make([]string, len(r.replicationConfig.Clusters)) replication_resolver.go
87 > copy(out, r.replicationConfig.Clusters)
88 > return out
89 }
90
96 }
97
98 > func (r *defaultReplicationResolver) IsGlobalNamespace() bool { replication_resolver.go
99 > return r.isGlobalNamespace
100 > }
101
102 > func (r *defaultReplicationResolver) FailoverVersion(businessID string) int64 { replication_resolver.go
103 > return r.failoverVersion
104 > }
105
106 func (r *defaultReplicationResolver) FailoverNotificationVersion() int64 {
112 }
113
114 > func (r *defaultReplicationResolver) SetGlobalFlag(isGlobal bool) { replication_resolver.go
115 > r.isGlobalNamespace = isGlobal
116 > }
117
118 func (r *defaultReplicationResolver) SetActiveCluster(clusterName string) {
go.temporal.io/server/common/payload/payload.go 29 covered LOC · 13 ranges

Open complete file

30 }
31
32 > func Encode(value any) (*commonpb.Payload, error) { payload.go
33 > return defaultDataConverter.ToPayload(value)
34 > }
35
36 > func Decode(p *commonpb.Payload, valuePtr any) error { payload.go
37 > return defaultDataConverter.FromPayload(p, valuePtr)
38 > }
39
40 func ToString(p *commonpb.Payload) string {
67 dst map[string]*commonpb.Payload,
68 src map[string]*commonpb.Payload,
69 > ) map[string]*commonpb.Payload { payload.go
70 > if src == nil {
71 return maps.Clone(dst)
72 }
73 > res := util.CloneMapNonNil(dst) payload.go
74 > for k, v := range src {
75 > if isNilPayload(v) { payload.go
76 delete(res, k)
77 > } else { payload.go
78 > res[k] = v payload.go
79 > }
80 }
81 > return res payload.go
82 }
83
88 // - payload's data is "null" (json encoded value for nil objects)
89 // - payload's data is "[]" (empty slice for backwards compatibility)
90 > func isNilPayload(p *commonpb.Payload) bool { payload.go
91 > return p == nil ||
92 > bytes.Equal(p.Data, nilPayload.Data) ||
93 > bytes.Equal(p.Data, nilSlicePayload.Data) ||
94 > bytes.Equal(p.Data, emptySlicePayload.Data)
95 > }
96
97 // FilterNilSearchAttributes returns a new SearchAttributes with nil/empty payload values filtered out.
99 // This is used to filter out nil search attributes from workflow start and continue-as-new events.
100 // Reuses MergeMapOfPayload which already handles nil payload filtering.
101 > func FilterNilSearchAttributes(sa *commonpb.SearchAttributes) *commonpb.SearchAttributes { payload.go
102 > if sa == nil || len(sa.GetIndexedFields()) == 0 {
103 > return nil payload.go
104 > }
105
106 filtered := MergeMapOfPayload(nil, sa.GetIndexedFields())
115 // This is used to filter out nil memo fields from workflow start, continue-as-new, and modify-properties events.
116 // Reuses MergeMapOfPayload which already handles nil payload filtering.
117 > func FilterNilMemo(memo *commonpb.Memo) *commonpb.Memo { payload.go
118 > if memo == nil || len(memo.GetFields()) == 0 {
119 > return nil payload.go
120 > }
121
122 filtered := MergeMapOfPayload(nil, memo.GetFields())
go.temporal.io/server/api/clock/v1/message.pb.go 28 covered LOC · 5 ranges

Open complete file

45 func (*VectorClock) ProtoMessage() {}
46
47 > func (x *VectorClock) ProtoReflect() protoreflect.Message { message.pb.go
48 > mi := &file_temporal_server_api_clock_v1_message_proto_msgTypes[0]
49 > if x != nil {
50 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
51 if ms.LoadMessageInfo() == nil {
54 return ms
55 }
56 > return mi.MessageOf(x) message.pb.go
57 }
58
69 }
70
71 > func (x *VectorClock) GetClock() int64 { message.pb.go
72 > if x != nil {
73 > return x.Clock
74 > }
75 return 0
76 }
193 }
194
195 > func init() { file_temporal_server_api_clock_v1_message_proto_init() } message.pb.go
196 > func file_temporal_server_api_clock_v1_message_proto_init() {
197 > if File_temporal_server_api_clock_v1_message_proto != nil {
198 return
199 }
200 > type x struct{} message.pb.go
201 > out := protoimpl.TypeBuilder{
202 > File: protoimpl.DescBuilder{
203 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
204 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_clock_v1_message_proto_rawDesc), len(file_temporal_server_api_clock_v1_message_proto_rawDesc)),
205 > NumEnums: 0,
206 > NumMessages: 2,
207 > NumExtensions: 0,
208 > NumServices: 0,
209 > },
210 > GoTypes: file_temporal_server_api_clock_v1_message_proto_goTypes,
211 > DependencyIndexes: file_temporal_server_api_clock_v1_message_proto_depIdxs,
212 > MessageInfos: file_temporal_server_api_clock_v1_message_proto_msgTypes,
213 > }.Build()
214 > File_temporal_server_api_clock_v1_message_proto = out.File
215 > file_temporal_server_api_clock_v1_message_proto_goTypes = nil
216 > file_temporal_server_api_clock_v1_message_proto_depIdxs = nil
217 }
go.temporal.io/server/client/client_bean_mock.go 28 covered LOC · 7 ranges

Open complete file

34
35 // NewMockBean creates a new mock instance.
36 > func NewMockBean(ctrl *gomock.Controller) *MockBean { client_bean_mock.go
37 > mock := &MockBean{ctrl: ctrl}
38 > mock.recorder = &MockBeanMockRecorder{mock}
39 > return mock
40 > }
41
42 // EXPECT returns an object that allows the caller to indicate expected use.
43 > func (m *MockBean) EXPECT() *MockBeanMockRecorder { client_bean_mock.go
44 > return m.recorder
45 > }
46
47 // Close mocks base method.
66
67 // GetFrontendClient indicates an expected call of GetFrontendClient.
68 > func (mr *MockBeanMockRecorder) GetFrontendClient() *gomock.Call { client_bean_mock.go
69 > mr.mock.ctrl.T.Helper()
70 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFrontendClient", reflect.TypeOf((*MockBean)(nil).GetFrontendClient))
71 > }
72
73 // GetHistoryClient mocks base method.
80
81 // GetHistoryClient indicates an expected call of GetHistoryClient.
82 > func (mr *MockBeanMockRecorder) GetHistoryClient() *gomock.Call { client_bean_mock.go
83 > mr.mock.ctrl.T.Helper()
84 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHistoryClient", reflect.TypeOf((*MockBean)(nil).GetHistoryClient))
85 > }
86
87 // GetMatchingClient mocks base method.
95
96 // GetMatchingClient indicates an expected call of GetMatchingClient.
97 > func (mr *MockBeanMockRecorder) GetMatchingClient(namespaceIDToName any) *gomock.Call { client_bean_mock.go
98 > mr.mock.ctrl.T.Helper()
99 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMatchingClient", reflect.TypeOf((*MockBean)(nil).GetMatchingClient), namespaceIDToName)
100 > }
101
102 // GetRemoteAdminClient mocks base method.
110
111 // GetRemoteAdminClient indicates an expected call of GetRemoteAdminClient.
112 > func (mr *MockBeanMockRecorder) GetRemoteAdminClient(arg0 any) *gomock.Call { client_bean_mock.go
113 > mr.mock.ctrl.T.Helper()
114 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRemoteAdminClient", reflect.TypeOf((*MockBean)(nil).GetRemoteAdminClient), arg0)
115 > }
116
117 // GetRemoteFrontendClient mocks base method.
126
127 // GetRemoteFrontendClient indicates an expected call of GetRemoteFrontendClient.
128 > func (mr *MockBeanMockRecorder) GetRemoteFrontendClient(arg0 any) *gomock.Call { client_bean_mock.go
129 > mr.mock.ctrl.T.Helper()
130 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRemoteFrontendClient", reflect.TypeOf((*MockBean)(nil).GetRemoteFrontendClient), arg0)
131 > }
go.temporal.io/server/service/history/workflow/timeskipping.go 28 covered LOC · 7 ranges

Open complete file

181 }
182
183 > func accumulatedSkippedDuration(source *persistencespb.WorkflowExecutionInfo) time.Duration { timeskipping.go
184 > return source.GetTimeSkippingInfo().GetAccumulatedSkippedDuration().AsDuration()
185 > }
186
187 // =============================================================================
201 }
202
203 > func (ms *MutableStateImpl) accumulatedSkippedDuration() time.Duration { timeskipping.go
204 > return accumulatedSkippedDuration(ms.executionInfo)
205 > }
206
207 // =============================================================================
306 // and if the workflow is at the correct state and status to skip time.
307 // And if there is a time point to skip to is not the scope of this method.
308 > func (ms *MutableStateImpl) isWorkflowSkippable() bool { timeskipping.go
309 > noSkippingReason := ""
310 > defer func() {
311 > if noSkippingReason != "" {
312 > ms.logger.Debug(fmt.Sprintf("time skipping skipped for: %s", noSkippingReason),
313 > tag.WorkflowID(ms.GetExecutionInfo().WorkflowId),
314 > tag.WorkflowRunID(ms.GetExecutionState().RunId),
315 > )
316 > }
317 }()
318
319 // (1) gate by time skipping configuration
320 > tsc := ms.GetExecutionInfo().GetTimeSkippingInfo().GetConfig() timeskipping.go
321 > if tsc == nil || !tsc.Enabled {
322 > noSkippingReason = "time skipping is not enabled"
323 > return false
324 > }
325
326 // (2) gate by workflow state and status
433 ctx context.Context,
434 transactionPolicy historyi.TransactionPolicy,
435 > ) (needRegenTasks bool) { timeskipping.go
436 > if !ms.IsWorkflow() {
437 return false
438 }
439 > switch transactionPolicy { timeskipping.go
440 > case historyi.TransactionPolicyActive: timeskipping.go
441 > // 1. gate: only a running, time-skipping-enabled, idle workflow may skip time
442 > if !ms.isWorkflowSkippable() {
443 > return false
444 > }
445 // 2. find the next skip target; if there is none, time skipping is not needed
446 transition := ms.findNextSkipTarget()
go.temporal.io/server/api/persistence/v1/queues.pb.go 27 covered LOC · 3 ranges

Open complete file

98 func (*QueueState) ProtoMessage() {}
99
100 > func (x *QueueState) ProtoReflect() protoreflect.Message { queues.pb.go
101 > mi := &file_temporal_server_api_persistence_v1_queues_proto_msgTypes[1]
102 > if x != nil {
103 ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
104 if ms.LoadMessageInfo() == nil {
107 return ms
108 }
109 > return mi.MessageOf(x) queues.pb.go
110 }
111
616 }
617
618 > func init() { file_temporal_server_api_persistence_v1_queues_proto_init() } queues.pb.go
619 > func file_temporal_server_api_persistence_v1_queues_proto_init() {
620 > if File_temporal_server_api_persistence_v1_queues_proto != nil {
621 > return
622 > }
623 > file_temporal_server_api_persistence_v1_predicates_proto_init()
624 > type x struct{}
625 > out := protoimpl.TypeBuilder{
626 > File: protoimpl.DescBuilder{
627 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
628 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_queues_proto_rawDesc), len(file_temporal_server_api_persistence_v1_queues_proto_rawDesc)),
629 > NumEnums: 0,
630 > NumMessages: 12,
631 > NumExtensions: 0,
632 > NumServices: 0,
633 > },
634 > GoTypes: file_temporal_server_api_persistence_v1_queues_proto_goTypes,
635 > DependencyIndexes: file_temporal_server_api_persistence_v1_queues_proto_depIdxs,
636 > MessageInfos: file_temporal_server_api_persistence_v1_queues_proto_msgTypes,
637 > }.Build()
638 > File_temporal_server_api_persistence_v1_queues_proto = out.File
639 > file_temporal_server_api_persistence_v1_queues_proto_goTypes = nil
640 > file_temporal_server_api_persistence_v1_queues_proto_depIdxs = nil
641 }
go.temporal.io/server/api/enums/v1/common.pb.go 26 covered LOC · 4 ranges

Open complete file

120 }
121
122 > func (ChecksumFlavor) Descriptor() protoreflect.EnumDescriptor { common.pb.go
123 > return file_temporal_server_api_enums_v1_common_proto_enumTypes[1].Descriptor()
124 > }
125
126 func (ChecksumFlavor) Type() protoreflect.EnumType {
201 }
202
203 > func (CallbackState) Descriptor() protoreflect.EnumDescriptor { common.pb.go
204 > return file_temporal_server_api_enums_v1_common_proto_enumTypes[2].Descriptor()
205 > }
206
207 func (CallbackState) Type() protoreflect.EnumType {
264 }
265
266 > func init() { file_temporal_server_api_enums_v1_common_proto_init() } common.pb.go
267 > func file_temporal_server_api_enums_v1_common_proto_init() {
268 > if File_temporal_server_api_enums_v1_common_proto != nil {
269 return
270 }
271 > type x struct{} common.pb.go
272 > out := protoimpl.TypeBuilder{
273 > File: protoimpl.DescBuilder{
274 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
275 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_enums_v1_common_proto_rawDesc), len(file_temporal_server_api_enums_v1_common_proto_rawDesc)),
276 > NumEnums: 3,
277 > NumMessages: 0,
278 > NumExtensions: 0,
279 > NumServices: 0,
280 > },
281 > GoTypes: file_temporal_server_api_enums_v1_common_proto_goTypes,
282 > DependencyIndexes: file_temporal_server_api_enums_v1_common_proto_depIdxs,
283 > EnumInfos: file_temporal_server_api_enums_v1_common_proto_enumTypes,
284 > }.Build()
285 > File_temporal_server_api_enums_v1_common_proto = out.File
286 > file_temporal_server_api_enums_v1_common_proto_goTypes = nil
287 > file_temporal_server_api_enums_v1_common_proto_depIdxs = nil
288 }
go.temporal.io/server/api/enums/v1/workflow.pb.go 26 covered LOC · 4 ranges

Open complete file

86 }
87
88 > func (WorkflowExecutionState) Descriptor() protoreflect.EnumDescriptor { workflow.pb.go
89 > return file_temporal_server_api_enums_v1_workflow_proto_enumTypes[0].Descriptor()
90 > }
91
92 func (WorkflowExecutionState) Type() protoreflect.EnumType {
150 }
151
152 > func (WorkflowBackoffType) Descriptor() protoreflect.EnumDescriptor { workflow.pb.go
153 > return file_temporal_server_api_enums_v1_workflow_proto_enumTypes[1].Descriptor()
154 > }
155
156 func (WorkflowBackoffType) Type() protoreflect.EnumType {
275 }
276
277 > func init() { file_temporal_server_api_enums_v1_workflow_proto_init() } workflow.pb.go
278 > func file_temporal_server_api_enums_v1_workflow_proto_init() {
279 > if File_temporal_server_api_enums_v1_workflow_proto != nil {
280 return
281 }
282 > type x struct{} workflow.pb.go
283 > out := protoimpl.TypeBuilder{
284 > File: protoimpl.DescBuilder{
285 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
286 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_enums_v1_workflow_proto_rawDesc), len(file_temporal_server_api_enums_v1_workflow_proto_rawDesc)),
287 > NumEnums: 3,
288 > NumMessages: 0,
289 > NumExtensions: 0,
290 > NumServices: 0,
291 > },
292 > GoTypes: file_temporal_server_api_enums_v1_workflow_proto_goTypes,
293 > DependencyIndexes: file_temporal_server_api_enums_v1_workflow_proto_depIdxs,
294 > EnumInfos: file_temporal_server_api_enums_v1_workflow_proto_enumTypes,
295 > }.Build()
296 > File_temporal_server_api_enums_v1_workflow_proto = out.File
297 > file_temporal_server_api_enums_v1_workflow_proto_goTypes = nil
298 > file_temporal_server_api_enums_v1_workflow_proto_depIdxs = nil
299 }
go.temporal.io/server/chasm/lib/scheduler/gen/schedulerpb/v1/message.pb.go 26 covered LOC · 1 range

Open complete file

843 }
844
845 > func init() { file_temporal_server_chasm_lib_scheduler_proto_v1_message_proto_init() } message.pb.go
846 > func file_temporal_server_chasm_lib_scheduler_proto_v1_message_proto_init() {
847 > if File_temporal_server_chasm_lib_scheduler_proto_v1_message_proto != nil {
848 > return
849 > }
850 > file_temporal_server_chasm_lib_scheduler_proto_v1_message_proto_msgTypes[4].OneofWrappers = []any{
851 > (*BackfillerState_BackfillRequest)(nil),
852 > (*BackfillerState_TriggerRequest)(nil),
853 > }
854 > type x struct{}
855 > out := protoimpl.TypeBuilder{
856 > File: protoimpl.DescBuilder{
857 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
858 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_scheduler_proto_v1_message_proto_rawDesc), len(file_temporal_server_chasm_lib_scheduler_proto_v1_message_proto_rawDesc)),
859 > NumEnums: 0,
860 > NumMessages: 12,
861 > NumExtensions: 0,
862 > NumServices: 0,
863 > },
864 > GoTypes: file_temporal_server_chasm_lib_scheduler_proto_v1_message_proto_goTypes,
865 > DependencyIndexes: file_temporal_server_chasm_lib_scheduler_proto_v1_message_proto_depIdxs,
866 > MessageInfos: file_temporal_server_chasm_lib_scheduler_proto_v1_message_proto_msgTypes,
867 > }.Build()
868 > File_temporal_server_chasm_lib_scheduler_proto_v1_message_proto = out.File
869 > file_temporal_server_chasm_lib_scheduler_proto_v1_message_proto_goTypes = nil
870 > file_temporal_server_chasm_lib_scheduler_proto_v1_message_proto_depIdxs = nil
871 }
go.temporal.io/server/common/membership/interfaces_mock.go 26 covered LOC · 6 ranges

Open complete file

32
33 // NewMockMonitor creates a new mock instance.
34 > func NewMockMonitor(ctrl *gomock.Controller) *MockMonitor { interfaces_mock.go
35 > mock := &MockMonitor{ctrl: ctrl}
36 > mock.recorder = &MockMonitorMockRecorder{mock}
37 > return mock
38 > }
39
40 // EXPECT returns an object that allows the caller to indicate expected use.
41 > func (m *MockMonitor) EXPECT() *MockMonitorMockRecorder { interfaces_mock.go
42 > return m.recorder
43 > }
44
45 // ApproximateMaxPropagationTime mocks base method.
111
112 // GetResolver indicates an expected call of GetResolver.
113 > func (mr *MockMonitorMockRecorder) GetResolver(service any) *gomock.Call { interfaces_mock.go
114 > mr.mock.ctrl.T.Helper()
115 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetResolver", reflect.TypeOf((*MockMonitor)(nil).GetResolver), service)
116 > }
117
118 // SetDraining mocks base method.
151
152 // WaitUntilInitialized indicates an expected call of WaitUntilInitialized.
153 > func (mr *MockMonitorMockRecorder) WaitUntilInitialized(arg0 any) *gomock.Call { interfaces_mock.go
154 > mr.mock.ctrl.T.Helper()
155 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitUntilInitialized", reflect.TypeOf((*MockMonitor)(nil).WaitUntilInitialized), arg0)
156 > }
157
158 // MockServiceResolver is a mock of ServiceResolver interface.
169
170 // NewMockServiceResolver creates a new mock instance.
171 > func NewMockServiceResolver(ctrl *gomock.Controller) *MockServiceResolver { interfaces_mock.go
172 > mock := &MockServiceResolver{ctrl: ctrl}
173 > mock.recorder = &MockServiceResolverMockRecorder{mock}
174 > return mock
175 > }
176
177 // EXPECT returns an object that allows the caller to indicate expected use.
318
319 // NewMockHostInfoProvider creates a new mock instance.
320 > func NewMockHostInfoProvider(ctrl *gomock.Controller) *MockHostInfoProvider { interfaces_mock.go
321 > mock := &MockHostInfoProvider{ctrl: ctrl}
322 > mock.recorder = &MockHostInfoProviderMockRecorder{mock}
323 > return mock
324 > }
325
326 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/service/history/queues/queue_mock.go 26 covered LOC · 6 ranges

Open complete file

30
31 // NewMockQueue creates a new mock instance.
32 > func NewMockQueue(ctrl *gomock.Controller) *MockQueue { queue_mock.go
33 > mock := &MockQueue{ctrl: ctrl}
34 > mock.recorder = &MockQueueMockRecorder{mock}
35 > return mock
36 > }
37
38 // EXPECT returns an object that allows the caller to indicate expected use.
39 > func (m *MockQueue) EXPECT() *MockQueueMockRecorder { queue_mock.go
40 > return m.recorder
41 > }
42
43 // Category mocks base method.
44 > func (m *MockQueue) Category() tasks.Category { queue_mock.go
45 > m.ctrl.T.Helper()
46 > ret := m.ctrl.Call(m, "Category")
47 > ret0, _ := ret[0].(tasks.Category)
48 > return ret0
49 > }
50
51 // Category indicates an expected call of Category.
52 > func (mr *MockQueueMockRecorder) Category() *gomock.Call { queue_mock.go
53 > mr.mock.ctrl.T.Helper()
54 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Category", reflect.TypeOf((*MockQueue)(nil).Category))
55 > }
56
57 // FailoverNamespace mocks base method.
68
69 // NotifyNewTasks mocks base method.
70 > func (m *MockQueue) NotifyNewTasks(arg0 []tasks.Task) { queue_mock.go
71 > m.ctrl.T.Helper()
72 > m.ctrl.Call(m, "NotifyNewTasks", arg0)
73 > }
74
75 // NotifyNewTasks indicates an expected call of NotifyNewTasks.
76 > func (mr *MockQueueMockRecorder) NotifyNewTasks(arg0 any) *gomock.Call { queue_mock.go
77 > mr.mock.ctrl.T.Helper()
78 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NotifyNewTasks", reflect.TypeOf((*MockQueue)(nil).NotifyNewTasks), arg0)
79 > }
80
81 // Start mocks base method.
go.temporal.io/server/chasm/lib/activity/gen/activitypb/v1/activity_state.pb.go 25 covered LOC · 2 ranges

Open complete file

1382 }
1383
1384 > func init() { file_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto_init() } activity_state.pb.go
1385 > func file_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto_init() {
1386 > if File_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto != nil {
1387 return
1388 }
1389 > file_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto_msgTypes[7].OneofWrappers = []any{ activity_state.pb.go
1390 > (*ActivityOutcome_Successful_)(nil),
1391 > (*ActivityOutcome_Failed_)(nil),
1392 > }
1393 > type x struct{}
1394 > out := protoimpl.TypeBuilder{
1395 > File: protoimpl.DescBuilder{
1396 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
1397 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto_rawDesc), len(file_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto_rawDesc)),
1398 > NumEnums: 2,
1399 > NumMessages: 11,
1400 > NumExtensions: 0,
1401 > NumServices: 0,
1402 > },
1403 > GoTypes: file_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto_goTypes,
1404 > DependencyIndexes: file_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto_depIdxs,
1405 > EnumInfos: file_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto_enumTypes,
1406 > MessageInfos: file_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto_msgTypes,
1407 > }.Build()
1408 > File_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto = out.File
1409 > file_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto_goTypes = nil
1410 > file_temporal_server_chasm_lib_activity_proto_v1_activity_state_proto_depIdxs = nil
1411 }
go.temporal.io/server/chasm/lib/nexusoperation/gen/nexusoperationpb/v1/operation.pb.go 25 covered LOC · 2 ranges

Open complete file

998 }
999
1000 > func init() { file_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto_init() } operation.pb.go
1001 > func file_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto_init() {
1002 > if File_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto != nil {
1003 return
1004 }
1005 > file_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto_msgTypes[2].OneofWrappers = []any{ operation.pb.go
1006 > (*OperationOutcome_Successful_)(nil),
1007 > (*OperationOutcome_Failed_)(nil),
1008 > }
1009 > type x struct{}
1010 > out := protoimpl.TypeBuilder{
1011 > File: protoimpl.DescBuilder{
1012 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
1013 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto_rawDesc), len(file_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto_rawDesc)),
1014 > NumEnums: 2,
1015 > NumMessages: 8,
1016 > NumExtensions: 0,
1017 > NumServices: 0,
1018 > },
1019 > GoTypes: file_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto_goTypes,
1020 > DependencyIndexes: file_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto_depIdxs,
1021 > EnumInfos: file_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto_enumTypes,
1022 > MessageInfos: file_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto_msgTypes,
1023 > }.Build()
1024 > File_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto = out.File
1025 > file_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto_goTypes = nil
1026 > file_temporal_server_chasm_lib_nexusoperation_proto_v1_operation_proto_depIdxs = nil
1027 }
go.temporal.io/server/common/routing/route.go 25 covered LOC · 8 ranges

Open complete file

36
37 // NewRoute returns a new [Route] instance with the given components.
38 > func NewRoute[T any](components ...Component[T]) Route[T] { route.go
39 > return Route[T]{components: components}
40 > }
41
42 // RouteBuilder is a builder for the [Route] interface.
46
47 // NewBuilder creates a new [RouteBuilder] instance, which can be used to define a new [Route] via a fluent API.
48 > func NewBuilder[T any]() *RouteBuilder[T] { route.go
49 > return &RouteBuilder[T]{}
50 > }
51
52 // With adds a series of [Component] instances to the [Route].
53 > func (r *RouteBuilder[T]) With(c ...Component[T]) *RouteBuilder[T] { route.go
54 > r.components = append(r.components, c...)
55 > return r
56 > }
57
58 // Constant adds a [Constant] component to the [Route].
59 > func (r *RouteBuilder[T]) Constant(values ...string) *RouteBuilder[T] { route.go
60 > return r.With(Constant[T](values...))
61 > }
62
63 // StringVariable adds a [StringVariable] component to the [Route].
64 > func (r *RouteBuilder[T]) StringVariable(name string, getter func(*T) *string) *RouteBuilder[T] { route.go
65 > return r.With(StringVariable[T](name, getter))
66 > }
67
68 // Build returns a read-only [Route].
69 > func (r *RouteBuilder[T]) Build() Route[T] { route.go
70 > return NewRoute[T](r.components...)
71 > }
72
73 // Representation returns the [github.com/gorilla/mux] compatible string representation of the route for usage in a
111 // Constant returns a [Component] that represents a series of constant HTTP path components in a Route.
112 // They will be joined via strings when used to construct a path or path representation.
113 > func Constant[T any](values ...string) constant[T] { route.go
114 > return values
115 > }
116
117 type constant[T any] []string
128
129 // StringVariable returns a [Component] that represents a string variable in a Route.
130 > func StringVariable[T any](name string, getter func(*T) *string) stringVariable[T] { route.go
131 > return stringVariable[T]{name, getter}
132 > }
133
134 type stringVariable[T any] struct {
go.temporal.io/server/service/history/api/command_attr_validator.go 25 covered LOC · 9 ranges

Open complete file

42 config *configs.Config,
43 searchAttributesValidator *searchattribute.Validator,
44 > ) *CommandAttrValidator { command_attr_validator.go
45 > return &CommandAttrValidator{
46 > namespaceRegistry: namespaceRegistry,
47 > config: config,
48 > maxIDLengthLimit: config.MaxIDLengthLimit(),
49 > searchAttributesValidator: searchAttributesValidator,
50 > getDefaultActivityRetrySettings: config.DefaultActivityRetryPolicy,
51 > getDefaultWorkflowRetrySettings: config.DefaultWorkflowRetryPolicy,
52 > enableCrossNamespaceCommands: config.EnableCrossNamespaceCommands,
53 > }
54 > }
55
56 func (v *CommandAttrValidator) ValidateProtocolMessageAttributes(
165 func (v *CommandAttrValidator) ValidateActivityCancelAttributes(
166 attributes *commandpb.RequestCancelActivityTaskCommandAttributes,
167 > ) (enumspb.WorkflowTaskFailedCause, error) { command_attr_validator.go
168 >
169 > const failedCause = enumspb.WORKFLOW_TASK_FAILED_CAUSE_BAD_REQUEST_CANCEL_ACTIVITY_ATTRIBUTES
170 > if attributes == nil {
171 return failedCause, serviceerror.NewInvalidArgument("RequestCancelActivityTaskCommandAttributes is not set on RequestCancelActivityTaskCommand.")
172 }
173 > if attributes.GetScheduledEventId() <= 0 { command_attr_validator.go
174 return failedCause, serviceerror.NewInvalidArgument("ScheduledEventId is not set on RequestCancelActivityTaskCommand.")
175 }
176 > return enumspb.WORKFLOW_TASK_FAILED_CAUSE_UNSPECIFIED, nil command_attr_validator.go
177 }
178
637 func (v *CommandAttrValidator) ValidateCommandSequence(
638 commands []*commandpb.Command,
639 > ) error { command_attr_validator.go
640 > closeCommand := enumspb.COMMAND_TYPE_UNSPECIFIED
641 >
642 > for _, command := range commands {
643 > if closeCommand != enumspb.COMMAND_TYPE_UNSPECIFIED { command_attr_validator.go
644 return serviceerror.NewInvalidArgumentf(
645 "invalid command sequence: [%v], command %s must be the last command.",
649
650 // nolint:exhaustive
651 > switch command.GetCommandType() { command_attr_validator.go
652 case enumspb.COMMAND_TYPE_SCHEDULE_ACTIVITY_TASK,
653 enumspb.COMMAND_TYPE_REQUEST_CANCEL_ACTIVITY_TASK,
662 enumspb.COMMAND_TYPE_PROTOCOL_MESSAGE,
663 enumspb.COMMAND_TYPE_SCHEDULE_NEXUS_OPERATION,
664 > enumspb.COMMAND_TYPE_REQUEST_CANCEL_NEXUS_OPERATION: command_attr_validator.go
665 // noop
666 case enumspb.COMMAND_TYPE_CONTINUE_AS_NEW_WORKFLOW_EXECUTION,
go.temporal.io/server/api/persistence/v1/namespaces.pb.go 24 covered LOC · 3 ranges

Open complete file

264 }
265
266 > func (x *NamespaceConfig) GetBadBinaries() *v11.BadBinaries { namespaces.pb.go
267 > if x != nil {
268 > return x.BadBinaries
269 > }
270 return nil
271 }
536 }
537
538 > func init() { file_temporal_server_api_persistence_v1_namespaces_proto_init() } namespaces.pb.go
539 > func file_temporal_server_api_persistence_v1_namespaces_proto_init() {
540 > if File_temporal_server_api_persistence_v1_namespaces_proto != nil {
541 return
542 }
543 > type x struct{} namespaces.pb.go
544 > out := protoimpl.TypeBuilder{
545 > File: protoimpl.DescBuilder{
546 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
547 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_namespaces_proto_rawDesc), len(file_temporal_server_api_persistence_v1_namespaces_proto_rawDesc)),
548 > NumEnums: 0,
549 > NumMessages: 8,
550 > NumExtensions: 0,
551 > NumServices: 0,
552 > },
553 > GoTypes: file_temporal_server_api_persistence_v1_namespaces_proto_goTypes,
554 > DependencyIndexes: file_temporal_server_api_persistence_v1_namespaces_proto_depIdxs,
555 > MessageInfos: file_temporal_server_api_persistence_v1_namespaces_proto_msgTypes,
556 > }.Build()
557 > File_temporal_server_api_persistence_v1_namespaces_proto = out.File
558 > file_temporal_server_api_persistence_v1_namespaces_proto_goTypes = nil
559 > file_temporal_server_api_persistence_v1_namespaces_proto_depIdxs = nil
560 }
go.temporal.io/server/api/persistence/v1/nexus.pb.go 24 covered LOC · 2 ranges

Open complete file

481 }
482
483 > func init() { file_temporal_server_api_persistence_v1_nexus_proto_init() } nexus.pb.go
484 > func file_temporal_server_api_persistence_v1_nexus_proto_init() {
485 > if File_temporal_server_api_persistence_v1_nexus_proto != nil {
486 return
487 }
488 > file_temporal_server_api_persistence_v1_nexus_proto_msgTypes[1].OneofWrappers = []any{ nexus.pb.go
489 > (*NexusEndpointTarget_Worker_)(nil),
490 > (*NexusEndpointTarget_External_)(nil),
491 > }
492 > type x struct{}
493 > out := protoimpl.TypeBuilder{
494 > File: protoimpl.DescBuilder{
495 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
496 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_nexus_proto_rawDesc), len(file_temporal_server_api_persistence_v1_nexus_proto_rawDesc)),
497 > NumEnums: 0,
498 > NumMessages: 6,
499 > NumExtensions: 0,
500 > NumServices: 0,
501 > },
502 > GoTypes: file_temporal_server_api_persistence_v1_nexus_proto_goTypes,
503 > DependencyIndexes: file_temporal_server_api_persistence_v1_nexus_proto_depIdxs,
504 > MessageInfos: file_temporal_server_api_persistence_v1_nexus_proto_msgTypes,
505 > }.Build()
506 > File_temporal_server_api_persistence_v1_nexus_proto = out.File
507 > file_temporal_server_api_persistence_v1_nexus_proto_goTypes = nil
508 > file_temporal_server_api_persistence_v1_nexus_proto_depIdxs = nil
509 }
go.temporal.io/server/api/schedule/v1/message.pb.go 24 covered LOC · 2 ranges

Open complete file

1224 }
1225
1226 > func init() { file_temporal_server_api_schedule_v1_message_proto_init() } message.pb.go
1227 > func file_temporal_server_api_schedule_v1_message_proto_init() {
1228 > if File_temporal_server_api_schedule_v1_message_proto != nil {
1229 return
1230 }
1231 > file_temporal_server_api_schedule_v1_message_proto_msgTypes[7].OneofWrappers = []any{ message.pb.go
1232 > (*WatchWorkflowResponse_Result)(nil),
1233 > (*WatchWorkflowResponse_Failure)(nil),
1234 > }
1235 > type x struct{}
1236 > out := protoimpl.TypeBuilder{
1237 > File: protoimpl.DescBuilder{
1238 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
1239 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_schedule_v1_message_proto_rawDesc), len(file_temporal_server_api_schedule_v1_message_proto_rawDesc)),
1240 > NumEnums: 0,
1241 > NumMessages: 13,
1242 > NumExtensions: 0,
1243 > NumServices: 0,
1244 > },
1245 > GoTypes: file_temporal_server_api_schedule_v1_message_proto_goTypes,
1246 > DependencyIndexes: file_temporal_server_api_schedule_v1_message_proto_depIdxs,
1247 > MessageInfos: file_temporal_server_api_schedule_v1_message_proto_msgTypes,
1248 > }.Build()
1249 > File_temporal_server_api_schedule_v1_message_proto = out.File
1250 > file_temporal_server_api_schedule_v1_message_proto_goTypes = nil
1251 > file_temporal_server_api_schedule_v1_message_proto_depIdxs = nil
1252 }
go.temporal.io/server/chasm/lib/callback/gen/callbackpb/v1/message.pb.go 24 covered LOC · 2 ranges

Open complete file

462 }
463
464 > func init() { file_temporal_server_chasm_lib_callback_proto_v1_message_proto_init() } message.pb.go
465 > func file_temporal_server_chasm_lib_callback_proto_v1_message_proto_init() {
466 > if File_temporal_server_chasm_lib_callback_proto_v1_message_proto != nil {
467 return
468 }
469 > file_temporal_server_chasm_lib_callback_proto_v1_message_proto_msgTypes[1].OneofWrappers = []any{ message.pb.go
470 > (*Callback_Nexus_)(nil),
471 > }
472 > type x struct{}
473 > out := protoimpl.TypeBuilder{
474 > File: protoimpl.DescBuilder{
475 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
476 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_callback_proto_v1_message_proto_rawDesc), len(file_temporal_server_chasm_lib_callback_proto_v1_message_proto_rawDesc)),
477 > NumEnums: 1,
478 > NumMessages: 5,
479 > NumExtensions: 0,
480 > NumServices: 0,
481 > },
482 > GoTypes: file_temporal_server_chasm_lib_callback_proto_v1_message_proto_goTypes,
483 > DependencyIndexes: file_temporal_server_chasm_lib_callback_proto_v1_message_proto_depIdxs,
484 > EnumInfos: file_temporal_server_chasm_lib_callback_proto_v1_message_proto_enumTypes,
485 > MessageInfos: file_temporal_server_chasm_lib_callback_proto_v1_message_proto_msgTypes,
486 > }.Build()
487 > File_temporal_server_chasm_lib_callback_proto_v1_message_proto = out.File
488 > file_temporal_server_chasm_lib_callback_proto_v1_message_proto_goTypes = nil
489 > file_temporal_server_chasm_lib_callback_proto_v1_message_proto_depIdxs = nil
490 }
go.temporal.io/server/api/enums/v1/nexus.pb.go 23 covered LOC · 3 ranges

Open complete file

102 }
103
104 > func (NexusOperationState) Descriptor() protoreflect.EnumDescriptor { nexus.pb.go
105 > return file_temporal_server_api_enums_v1_nexus_proto_enumTypes[0].Descriptor()
106 > }
107
108 func (NexusOperationState) Type() protoreflect.EnumType {
158 }
159
160 > func init() { file_temporal_server_api_enums_v1_nexus_proto_init() } nexus.pb.go
161 > func file_temporal_server_api_enums_v1_nexus_proto_init() {
162 > if File_temporal_server_api_enums_v1_nexus_proto != nil {
163 return
164 }
165 > type x struct{} nexus.pb.go
166 > out := protoimpl.TypeBuilder{
167 > File: protoimpl.DescBuilder{
168 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
169 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_enums_v1_nexus_proto_rawDesc), len(file_temporal_server_api_enums_v1_nexus_proto_rawDesc)),
170 > NumEnums: 1,
171 > NumMessages: 0,
172 > NumExtensions: 0,
173 > NumServices: 0,
174 > },
175 > GoTypes: file_temporal_server_api_enums_v1_nexus_proto_goTypes,
176 > DependencyIndexes: file_temporal_server_api_enums_v1_nexus_proto_depIdxs,
177 > EnumInfos: file_temporal_server_api_enums_v1_nexus_proto_enumTypes,
178 > }.Build()
179 > File_temporal_server_api_enums_v1_nexus_proto = out.File
180 > file_temporal_server_api_enums_v1_nexus_proto_goTypes = nil
181 > file_temporal_server_api_enums_v1_nexus_proto_depIdxs = nil
182 }
go.temporal.io/server/api/enums/v1/predicate.pb.go 23 covered LOC · 3 ranges

Open complete file

111 }
112
113 > func (PredicateType) Descriptor() protoreflect.EnumDescriptor { predicate.pb.go
114 > return file_temporal_server_api_enums_v1_predicate_proto_enumTypes[0].Descriptor()
115 > }
116
117 func (PredicateType) Type() protoreflect.EnumType {
170 }
171
172 > func init() { file_temporal_server_api_enums_v1_predicate_proto_init() } predicate.pb.go
173 > func file_temporal_server_api_enums_v1_predicate_proto_init() {
174 > if File_temporal_server_api_enums_v1_predicate_proto != nil {
175 return
176 }
177 > type x struct{} predicate.pb.go
178 > out := protoimpl.TypeBuilder{
179 > File: protoimpl.DescBuilder{
180 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
181 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_enums_v1_predicate_proto_rawDesc), len(file_temporal_server_api_enums_v1_predicate_proto_rawDesc)),
182 > NumEnums: 1,
183 > NumMessages: 0,
184 > NumExtensions: 0,
185 > NumServices: 0,
186 > },
187 > GoTypes: file_temporal_server_api_enums_v1_predicate_proto_goTypes,
188 > DependencyIndexes: file_temporal_server_api_enums_v1_predicate_proto_depIdxs,
189 > EnumInfos: file_temporal_server_api_enums_v1_predicate_proto_enumTypes,
190 > }.Build()
191 > File_temporal_server_api_enums_v1_predicate_proto = out.File
192 > file_temporal_server_api_enums_v1_predicate_proto_goTypes = nil
193 > file_temporal_server_api_enums_v1_predicate_proto_depIdxs = nil
194 }
go.temporal.io/server/chasm/lib/scheduler/gen/schedulerpb/v1/request_response.pb.go 23 covered LOC · 1 range

Open complete file

1021 }
1022
1023 > func init() { file_temporal_server_chasm_lib_scheduler_proto_v1_request_response_proto_init() } request_response.pb.go
1024 > func file_temporal_server_chasm_lib_scheduler_proto_v1_request_response_proto_init() {
1025 > if File_temporal_server_chasm_lib_scheduler_proto_v1_request_response_proto != nil {
1026 > return
1027 > }
1028 > file_temporal_server_chasm_lib_scheduler_proto_v1_message_proto_init()
1029 > type x struct{}
1030 > out := protoimpl.TypeBuilder{
1031 > File: protoimpl.DescBuilder{
1032 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
1033 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_scheduler_proto_v1_request_response_proto_rawDesc), len(file_temporal_server_chasm_lib_scheduler_proto_v1_request_response_proto_rawDesc)),
1034 > NumEnums: 0,
1035 > NumMessages: 18,
1036 > NumExtensions: 0,
1037 > NumServices: 0,
1038 > },
1039 > GoTypes: file_temporal_server_chasm_lib_scheduler_proto_v1_request_response_proto_goTypes,
1040 > DependencyIndexes: file_temporal_server_chasm_lib_scheduler_proto_v1_request_response_proto_depIdxs,
1041 > MessageInfos: file_temporal_server_chasm_lib_scheduler_proto_v1_request_response_proto_msgTypes,
1042 > }.Build()
1043 > File_temporal_server_chasm_lib_scheduler_proto_v1_request_response_proto = out.File
1044 > file_temporal_server_chasm_lib_scheduler_proto_v1_request_response_proto_goTypes = nil
1045 > file_temporal_server_chasm_lib_scheduler_proto_v1_request_response_proto_depIdxs = nil
1046 }
go.temporal.io/server/common/dynamicconfig/shared_structure.go 23 covered LOC · 6 ranges

Open complete file

17 )
18
19 > func warnDefaultSharedStructure(key string, def any) { shared_structure.go
20 > if path := hasSharedStructure(reflect.ValueOf(def), "root"); path != "" {
21 sharedStructureWarnings.Store(key, path)
22 }
23 }
24
25 > func logSharedStructureWarnings(logger log.Logger) { shared_structure.go
26 > // If you see this warning, it means that a default value used in New*TypedSetting has a
27 > // non-nil slice or map in it. That can lead to confusing behavior since the value from
28 > // dynamic config will be merged over the default value (e.g. the slice will be appended
29 > // to, not replaced). If that behavior is desired, you can avoid this warning by using
30 > // New*TypedSettingWithConverter and referring to dynamicconfig.ConvertStructure
31 > // explicitly. Otherwise use nil slices and maps, including at the top level
32 > // (so `[]string(nil)` instead of `[]string{}`).
33 > logSharedStructureWarningsOnce.Do(func() {
34 > sharedStructureWarnings.Range(func(key, path any) bool {
35 softassert.Fail(logger,
36 "default value contains shared structure",
42 }
43
44 > func hasSharedStructure(v reflect.Value, path string) string { shared_structure.go
45 > // nolint:exhaustive // deliberately not exhaustive
46 > switch v.Kind() {
47 > case reflect.Map, reflect.Slice, reflect.Pointer:
48 > if !v.IsNil() {
49 return path
50 }
51 > case reflect.Interface: shared_structure.go
52 > if !v.IsNil() {
53 return hasSharedStructure(v.Elem(), path)
54 }
55 > case reflect.Struct: shared_structure.go
56 > for i := range v.NumField() {
57 > if p := hasSharedStructure(v.Field(i), path+"."+v.Type().Field(i).Name); p != "" {
58 return p
59 }
go.temporal.io/server/common/namespace/registry_mock.go 23 covered LOC · 5 ranges

Open complete file

30
31 // NewMockRegistry creates a new mock instance.
32 > func NewMockRegistry(ctrl *gomock.Controller) *MockRegistry { registry_mock.go
33 > mock := &MockRegistry{ctrl: ctrl}
34 > mock.recorder = &MockRegistryMockRecorder{mock}
35 > return mock
36 > }
37
38 // EXPECT returns an object that allows the caller to indicate expected use.
39 > func (m *MockRegistry) EXPECT() *MockRegistryMockRecorder { registry_mock.go
40 > return m.recorder
41 > }
42
43 // GetAllNamespaces mocks base method.
80
81 // GetNamespace indicates an expected call of GetNamespace.
82 > func (mr *MockRegistryMockRecorder) GetNamespace(name any) *gomock.Call { registry_mock.go
83 > mr.mock.ctrl.T.Helper()
84 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNamespace", reflect.TypeOf((*MockRegistry)(nil).GetNamespace), name)
85 > }
86
87 // GetNamespaceByID mocks base method.
88 > func (m *MockRegistry) GetNamespaceByID(id ID) (*Namespace, error) { registry_mock.go
89 > m.ctrl.T.Helper()
90 > ret := m.ctrl.Call(m, "GetNamespaceByID", id)
91 > ret0, _ := ret[0].(*Namespace)
92 > ret1, _ := ret[1].(error)
93 > return ret0, ret1
94 > }
95
96 // GetNamespaceByID indicates an expected call of GetNamespaceByID.
97 > func (mr *MockRegistryMockRecorder) GetNamespaceByID(id any) *gomock.Call { registry_mock.go
98 > mr.mock.ctrl.T.Helper()
99 > return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNamespaceByID", reflect.TypeOf((*MockRegistry)(nil).GetNamespaceByID), id)
100 > }
101
102 // GetNamespaceByIDWithOptions mocks base method.
go.temporal.io/server/api/common/v1/api_category.pb.go 22 covered LOC · 2 ranges

Open complete file

204 }
205
206 > func init() { file_temporal_server_api_common_v1_api_category_proto_init() } api_category.pb.go
207 > func file_temporal_server_api_common_v1_api_category_proto_init() {
208 > if File_temporal_server_api_common_v1_api_category_proto != nil {
209 return
210 }
211 > type x struct{} api_category.pb.go
212 > out := protoimpl.TypeBuilder{
213 > File: protoimpl.DescBuilder{
214 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
215 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_common_v1_api_category_proto_rawDesc), len(file_temporal_server_api_common_v1_api_category_proto_rawDesc)),
216 > NumEnums: 1,
217 > NumMessages: 1,
218 > NumExtensions: 1,
219 > NumServices: 0,
220 > },
221 > GoTypes: file_temporal_server_api_common_v1_api_category_proto_goTypes,
222 > DependencyIndexes: file_temporal_server_api_common_v1_api_category_proto_depIdxs,
223 > EnumInfos: file_temporal_server_api_common_v1_api_category_proto_enumTypes,
224 > MessageInfos: file_temporal_server_api_common_v1_api_category_proto_msgTypes,
225 > ExtensionInfos: file_temporal_server_api_common_v1_api_category_proto_extTypes,
226 > }.Build()
227 > File_temporal_server_api_common_v1_api_category_proto = out.File
228 > file_temporal_server_api_common_v1_api_category_proto_goTypes = nil
229 > file_temporal_server_api_common_v1_api_category_proto_depIdxs = nil
230 }
go.temporal.io/server/chasm/lib/activity/gen/activitypb/v1/request_response.pb.go 22 covered LOC · 1 range

Open complete file

1057 }
1058
1059 > func init() { file_temporal_server_chasm_lib_activity_proto_v1_request_response_proto_init() } request_response.pb.go
1060 > func file_temporal_server_chasm_lib_activity_proto_v1_request_response_proto_init() {
1061 > if File_temporal_server_chasm_lib_activity_proto_v1_request_response_proto != nil {
1062 > return
1063 > }
1064 > type x struct{}
1065 > out := protoimpl.TypeBuilder{
1066 > File: protoimpl.DescBuilder{
1067 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
1068 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_activity_proto_v1_request_response_proto_rawDesc), len(file_temporal_server_chasm_lib_activity_proto_v1_request_response_proto_rawDesc)),
1069 > NumEnums: 0,
1070 > NumMessages: 20,
1071 > NumExtensions: 0,
1072 > NumServices: 0,
1073 > },
1074 > GoTypes: file_temporal_server_chasm_lib_activity_proto_v1_request_response_proto_goTypes,
1075 > DependencyIndexes: file_temporal_server_chasm_lib_activity_proto_v1_request_response_proto_depIdxs,
1076 > MessageInfos: file_temporal_server_chasm_lib_activity_proto_v1_request_response_proto_msgTypes,
1077 > }.Build()
1078 > File_temporal_server_chasm_lib_activity_proto_v1_request_response_proto = out.File
1079 > file_temporal_server_chasm_lib_activity_proto_v1_request_response_proto_goTypes = nil
1080 > file_temporal_server_chasm_lib_activity_proto_v1_request_response_proto_depIdxs = nil
1081 }
go.temporal.io/server/chasm/lib/nexusoperation/gen/nexusoperationpb/v1/request_response.pb.go 22 covered LOC · 1 range

Open complete file

672 }
673
674 > func init() { file_temporal_server_chasm_lib_nexusoperation_proto_v1_request_response_proto_init() } request_response.pb.go
675 > func file_temporal_server_chasm_lib_nexusoperation_proto_v1_request_response_proto_init() {
676 > if File_temporal_server_chasm_lib_nexusoperation_proto_v1_request_response_proto != nil {
677 > return
678 > }
679 > type x struct{}
680 > out := protoimpl.TypeBuilder{
681 > File: protoimpl.DescBuilder{
682 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
683 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_nexusoperation_proto_v1_request_response_proto_rawDesc), len(file_temporal_server_chasm_lib_nexusoperation_proto_v1_request_response_proto_rawDesc)),
684 > NumEnums: 0,
685 > NumMessages: 12,
686 > NumExtensions: 0,
687 > NumServices: 0,
688 > },
689 > GoTypes: file_temporal_server_chasm_lib_nexusoperation_proto_v1_request_response_proto_goTypes,
690 > DependencyIndexes: file_temporal_server_chasm_lib_nexusoperation_proto_v1_request_response_proto_depIdxs,
691 > MessageInfos: file_temporal_server_chasm_lib_nexusoperation_proto_v1_request_response_proto_msgTypes,
692 > }.Build()
693 > File_temporal_server_chasm_lib_nexusoperation_proto_v1_request_response_proto = out.File
694 > file_temporal_server_chasm_lib_nexusoperation_proto_v1_request_response_proto_goTypes = nil
695 > file_temporal_server_chasm_lib_nexusoperation_proto_v1_request_response_proto_depIdxs = nil
696 }
go.temporal.io/server/chasm/lib/tests/gen/testspb/v1/request_response.pb.go 22 covered LOC · 1 range

Open complete file

157 }
158
159 > func init() { file_temporal_server_chasm_lib_tests_proto_v1_request_response_proto_init() } request_response.pb.go
160 > func file_temporal_server_chasm_lib_tests_proto_v1_request_response_proto_init() {
161 > if File_temporal_server_chasm_lib_tests_proto_v1_request_response_proto != nil {
162 > return
163 > }
164 > type x struct{}
165 > out := protoimpl.TypeBuilder{
166 > File: protoimpl.DescBuilder{
167 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
168 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_tests_proto_v1_request_response_proto_rawDesc), len(file_temporal_server_chasm_lib_tests_proto_v1_request_response_proto_rawDesc)),
169 > NumEnums: 0,
170 > NumMessages: 2,
171 > NumExtensions: 0,
172 > NumServices: 0,
173 > },
174 > GoTypes: file_temporal_server_chasm_lib_tests_proto_v1_request_response_proto_goTypes,
175 > DependencyIndexes: file_temporal_server_chasm_lib_tests_proto_v1_request_response_proto_depIdxs,
176 > MessageInfos: file_temporal_server_chasm_lib_tests_proto_v1_request_response_proto_msgTypes,
177 > }.Build()
178 > File_temporal_server_chasm_lib_tests_proto_v1_request_response_proto = out.File
179 > file_temporal_server_chasm_lib_tests_proto_v1_request_response_proto_goTypes = nil
180 > file_temporal_server_chasm_lib_tests_proto_v1_request_response_proto_depIdxs = nil
181 }
go.temporal.io/server/api/persistence/v1/task_queues.pb.go 21 covered LOC · 2 ranges

Open complete file

899 }
900
901 > func init() { file_temporal_server_api_persistence_v1_task_queues_proto_init() } task_queues.pb.go
902 > func file_temporal_server_api_persistence_v1_task_queues_proto_init() {
903 > if File_temporal_server_api_persistence_v1_task_queues_proto != nil {
904 return
905 }
906 > type x struct{} task_queues.pb.go
907 > out := protoimpl.TypeBuilder{
908 > File: protoimpl.DescBuilder{
909 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
910 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_task_queues_proto_rawDesc), len(file_temporal_server_api_persistence_v1_task_queues_proto_rawDesc)),
911 > NumEnums: 1,
912 > NumMessages: 13,
913 > NumExtensions: 0,
914 > NumServices: 0,
915 > },
916 > GoTypes: file_temporal_server_api_persistence_v1_task_queues_proto_goTypes,
917 > DependencyIndexes: file_temporal_server_api_persistence_v1_task_queues_proto_depIdxs,
918 > EnumInfos: file_temporal_server_api_persistence_v1_task_queues_proto_enumTypes,
919 > MessageInfos: file_temporal_server_api_persistence_v1_task_queues_proto_msgTypes,
920 > }.Build()
921 > File_temporal_server_api_persistence_v1_task_queues_proto = out.File
922 > file_temporal_server_api_persistence_v1_task_queues_proto_goTypes = nil
923 > file_temporal_server_api_persistence_v1_task_queues_proto_depIdxs = nil
924 }
go.temporal.io/server/api/routing/v1/extension.pb.go 21 covered LOC · 2 ranges

Open complete file

144 }
145
146 > func init() { file_temporal_server_api_routing_v1_extension_proto_init() } extension.pb.go
147 > func file_temporal_server_api_routing_v1_extension_proto_init() {
148 > if File_temporal_server_api_routing_v1_extension_proto != nil {
149 return
150 }
151 > type x struct{} extension.pb.go
152 > out := protoimpl.TypeBuilder{
153 > File: protoimpl.DescBuilder{
154 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
155 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_routing_v1_extension_proto_rawDesc), len(file_temporal_server_api_routing_v1_extension_proto_rawDesc)),
156 > NumEnums: 0,
157 > NumMessages: 1,
158 > NumExtensions: 1,
159 > NumServices: 0,
160 > },
161 > GoTypes: file_temporal_server_api_routing_v1_extension_proto_goTypes,
162 > DependencyIndexes: file_temporal_server_api_routing_v1_extension_proto_depIdxs,
163 > MessageInfos: file_temporal_server_api_routing_v1_extension_proto_msgTypes,
164 > ExtensionInfos: file_temporal_server_api_routing_v1_extension_proto_extTypes,
165 > }.Build()
166 > File_temporal_server_api_routing_v1_extension_proto = out.File
167 > file_temporal_server_api_routing_v1_extension_proto_goTypes = nil
168 > file_temporal_server_api_routing_v1_extension_proto_depIdxs = nil
169 }
go.temporal.io/server/chasm/lib/activity/gen/activitypb/v1/tasks.pb.go 21 covered LOC · 2 ranges

Open complete file

495 }
496
497 > func init() { file_temporal_server_chasm_lib_activity_proto_v1_tasks_proto_init() } tasks.pb.go
498 > func file_temporal_server_chasm_lib_activity_proto_v1_tasks_proto_init() {
499 > if File_temporal_server_chasm_lib_activity_proto_v1_tasks_proto != nil {
500 return
501 }
502 > type x struct{} tasks.pb.go
503 > out := protoimpl.TypeBuilder{
504 > File: protoimpl.DescBuilder{
505 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
506 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_activity_proto_v1_tasks_proto_rawDesc), len(file_temporal_server_chasm_lib_activity_proto_v1_tasks_proto_rawDesc)),
507 > NumEnums: 2,
508 > NumMessages: 5,
509 > NumExtensions: 0,
510 > NumServices: 0,
511 > },
512 > GoTypes: file_temporal_server_chasm_lib_activity_proto_v1_tasks_proto_goTypes,
513 > DependencyIndexes: file_temporal_server_chasm_lib_activity_proto_v1_tasks_proto_depIdxs,
514 > EnumInfos: file_temporal_server_chasm_lib_activity_proto_v1_tasks_proto_enumTypes,
515 > MessageInfos: file_temporal_server_chasm_lib_activity_proto_v1_tasks_proto_msgTypes,
516 > }.Build()
517 > File_temporal_server_chasm_lib_activity_proto_v1_tasks_proto = out.File
518 > file_temporal_server_chasm_lib_activity_proto_v1_tasks_proto_goTypes = nil
519 > file_temporal_server_chasm_lib_activity_proto_v1_tasks_proto_depIdxs = nil
520 }
go.temporal.io/server/common/persistence/versionhistory/version_histories.go 21 covered LOC · 8 ranges

Open complete file

7
8 // NewVersionHistories create a new instance of VersionHistories.
9 > func NewVersionHistories(versionHistory *historyspb.VersionHistory) *historyspb.VersionHistories { version_histories.go
10 > if versionHistory == nil {
11 panic("version history cannot be null")
12 }
13
14 > return &historyspb.VersionHistories{ version_histories.go
15 > CurrentVersionHistoryIndex: 0,
16 > Histories: []*historyspb.VersionHistory{versionHistory},
17 > }
18 }
19
20 // Copy VersionHistories.
21 > func CopyVersionHistories(h *historyspb.VersionHistories) *historyspb.VersionHistories { version_histories.go
22 > var histories []*historyspb.VersionHistory
23 > for _, history := range h.Histories {
24 > histories = append(histories, CopyVersionHistory(history)) version_histories.go
25 > }
26
27 > return &historyspb.VersionHistories{ version_histories.go
28 > CurrentVersionHistoryIndex: h.CurrentVersionHistoryIndex,
29 > Histories: histories,
30 > }
31 }
32
33 // GetVersionHistory gets the VersionHistory according to index provided.
34 > func GetVersionHistory(h *historyspb.VersionHistories, index int32) (*historyspb.VersionHistory, error) { version_histories.go
35 > if index < 0 || index >= int32(len(h.Histories)) {
36 return nil, serviceerror.NewInternal("version histories index is out of range.")
37 }
38
39 > return h.Histories[index], nil version_histories.go
40 }
41
179
180 // GetCurrentVersionHistory gets the current VersionHistory.
181 > func GetCurrentVersionHistory(h *historyspb.VersionHistories) (*historyspb.VersionHistory, error) { version_histories.go
182 > return GetVersionHistory(h, h.GetCurrentVersionHistoryIndex())
183 > }
184
185 // IsCurrentVersionHistoryEmpty checks if the current VersionHistory is empty.
go.temporal.io/server/api/adminservice/v1/service.pb.go 20 covered LOC · 2 ranges

Open complete file

273 }
274
275 > func init() { file_temporal_server_api_adminservice_v1_service_proto_init() } service.pb.go
276 > func file_temporal_server_api_adminservice_v1_service_proto_init() {
277 > if File_temporal_server_api_adminservice_v1_service_proto != nil {
278 return
279 }
280 > file_temporal_server_api_adminservice_v1_request_response_proto_init() service.pb.go
281 > type x struct{}
282 > out := protoimpl.TypeBuilder{
283 > File: protoimpl.DescBuilder{
284 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
285 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_adminservice_v1_service_proto_rawDesc), len(file_temporal_server_api_adminservice_v1_service_proto_rawDesc)),
286 > NumEnums: 0,
287 > NumMessages: 0,
288 > NumExtensions: 0,
289 > NumServices: 1,
290 > },
291 > GoTypes: file_temporal_server_api_adminservice_v1_service_proto_goTypes,
292 > DependencyIndexes: file_temporal_server_api_adminservice_v1_service_proto_depIdxs,
293 > }.Build()
294 > File_temporal_server_api_adminservice_v1_service_proto = out.File
295 > file_temporal_server_api_adminservice_v1_service_proto_goTypes = nil
296 > file_temporal_server_api_adminservice_v1_service_proto_depIdxs = nil
297 }
go.temporal.io/server/api/archiver/v1/message.pb.go 20 covered LOC · 2 ranges

Open complete file

431 }
432
433 > func init() { file_temporal_server_api_archiver_v1_message_proto_init() } message.pb.go
434 > func file_temporal_server_api_archiver_v1_message_proto_init() {
435 > if File_temporal_server_api_archiver_v1_message_proto != nil {
436 return
437 }
438 > type x struct{} message.pb.go
439 > out := protoimpl.TypeBuilder{
440 > File: protoimpl.DescBuilder{
441 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
442 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_archiver_v1_message_proto_rawDesc), len(file_temporal_server_api_archiver_v1_message_proto_rawDesc)),
443 > NumEnums: 0,
444 > NumMessages: 4,
445 > NumExtensions: 0,
446 > NumServices: 0,
447 > },
448 > GoTypes: file_temporal_server_api_archiver_v1_message_proto_goTypes,
449 > DependencyIndexes: file_temporal_server_api_archiver_v1_message_proto_depIdxs,
450 > MessageInfos: file_temporal_server_api_archiver_v1_message_proto_msgTypes,
451 > }.Build()
452 > File_temporal_server_api_archiver_v1_message_proto = out.File
453 > file_temporal_server_api_archiver_v1_message_proto_goTypes = nil
454 > file_temporal_server_api_archiver_v1_message_proto_depIdxs = nil
455 }
go.temporal.io/server/api/chasm/v1/message.pb.go 20 covered LOC · 2 ranges

Open complete file

206 }
207
208 > func init() { file_temporal_server_api_chasm_v1_message_proto_init() } message.pb.go
209 > func file_temporal_server_api_chasm_v1_message_proto_init() {
210 > if File_temporal_server_api_chasm_v1_message_proto != nil {
211 return
212 }
213 > type x struct{} message.pb.go
214 > out := protoimpl.TypeBuilder{
215 > File: protoimpl.DescBuilder{
216 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
217 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_chasm_v1_message_proto_rawDesc), len(file_temporal_server_api_chasm_v1_message_proto_rawDesc)),
218 > NumEnums: 0,
219 > NumMessages: 1,
220 > NumExtensions: 0,
221 > NumServices: 0,
222 > },
223 > GoTypes: file_temporal_server_api_chasm_v1_message_proto_goTypes,
224 > DependencyIndexes: file_temporal_server_api_chasm_v1_message_proto_depIdxs,
225 > MessageInfos: file_temporal_server_api_chasm_v1_message_proto_msgTypes,
226 > }.Build()
227 > File_temporal_server_api_chasm_v1_message_proto = out.File
228 > file_temporal_server_api_chasm_v1_message_proto_goTypes = nil
229 > file_temporal_server_api_chasm_v1_message_proto_depIdxs = nil
230 }
go.temporal.io/server/api/checksum/v1/message.pb.go 20 covered LOC · 2 ranges

Open complete file

334 }
335
336 > func init() { file_temporal_server_api_checksum_v1_message_proto_init() } message.pb.go
337 > func file_temporal_server_api_checksum_v1_message_proto_init() {
338 > if File_temporal_server_api_checksum_v1_message_proto != nil {
339 return
340 }
341 > type x struct{} message.pb.go
342 > out := protoimpl.TypeBuilder{
343 > File: protoimpl.DescBuilder{
344 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
345 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_checksum_v1_message_proto_rawDesc), len(file_temporal_server_api_checksum_v1_message_proto_rawDesc)),
346 > NumEnums: 0,
347 > NumMessages: 1,
348 > NumExtensions: 0,
349 > NumServices: 0,
350 > },
351 > GoTypes: file_temporal_server_api_checksum_v1_message_proto_goTypes,
352 > DependencyIndexes: file_temporal_server_api_checksum_v1_message_proto_depIdxs,
353 > MessageInfos: file_temporal_server_api_checksum_v1_message_proto_msgTypes,
354 > }.Build()
355 > File_temporal_server_api_checksum_v1_message_proto = out.File
356 > file_temporal_server_api_checksum_v1_message_proto_goTypes = nil
357 > file_temporal_server_api_checksum_v1_message_proto_depIdxs = nil
358 }
go.temporal.io/server/api/cluster/v1/message.pb.go 20 covered LOC · 2 ranges

Open complete file

342 }
343
344 > func init() { file_temporal_server_api_cluster_v1_message_proto_init() } message.pb.go
345 > func file_temporal_server_api_cluster_v1_message_proto_init() {
346 > if File_temporal_server_api_cluster_v1_message_proto != nil {
347 return
348 }
349 > type x struct{} message.pb.go
350 > out := protoimpl.TypeBuilder{
351 > File: protoimpl.DescBuilder{
352 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
353 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_cluster_v1_message_proto_rawDesc), len(file_temporal_server_api_cluster_v1_message_proto_rawDesc)),
354 > NumEnums: 0,
355 > NumMessages: 4,
356 > NumExtensions: 0,
357 > NumServices: 0,
358 > },
359 > GoTypes: file_temporal_server_api_cluster_v1_message_proto_goTypes,
360 > DependencyIndexes: file_temporal_server_api_cluster_v1_message_proto_depIdxs,
361 > MessageInfos: file_temporal_server_api_cluster_v1_message_proto_msgTypes,
362 > }.Build()
363 > File_temporal_server_api_cluster_v1_message_proto = out.File
364 > file_temporal_server_api_cluster_v1_message_proto_goTypes = nil
365 > file_temporal_server_api_cluster_v1_message_proto_depIdxs = nil
366 }
go.temporal.io/server/api/common/v1/dlq.pb.go 20 covered LOC · 2 ranges

Open complete file

295 }
296
297 > func init() { file_temporal_server_api_common_v1_dlq_proto_init() } dlq.pb.go
298 > func file_temporal_server_api_common_v1_dlq_proto_init() {
299 > if File_temporal_server_api_common_v1_dlq_proto != nil {
300 return
301 }
302 > type x struct{} dlq.pb.go
303 > out := protoimpl.TypeBuilder{
304 > File: protoimpl.DescBuilder{
305 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
306 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_common_v1_dlq_proto_rawDesc), len(file_temporal_server_api_common_v1_dlq_proto_rawDesc)),
307 > NumEnums: 0,
308 > NumMessages: 4,
309 > NumExtensions: 0,
310 > NumServices: 0,
311 > },
312 > GoTypes: file_temporal_server_api_common_v1_dlq_proto_goTypes,
313 > DependencyIndexes: file_temporal_server_api_common_v1_dlq_proto_depIdxs,
314 > MessageInfos: file_temporal_server_api_common_v1_dlq_proto_msgTypes,
315 > }.Build()
316 > File_temporal_server_api_common_v1_dlq_proto = out.File
317 > file_temporal_server_api_common_v1_dlq_proto_goTypes = nil
318 > file_temporal_server_api_common_v1_dlq_proto_depIdxs = nil
319 }
go.temporal.io/server/api/contextpropagation/v1/message.pb.go 20 covered LOC · 2 ranges

Open complete file

109 }
110
111 > func init() { file_temporal_server_api_contextpropagation_v1_message_proto_init() } message.pb.go
112 > func file_temporal_server_api_contextpropagation_v1_message_proto_init() {
113 > if File_temporal_server_api_contextpropagation_v1_message_proto != nil {
114 return
115 }
116 > type x struct{} message.pb.go
117 > out := protoimpl.TypeBuilder{
118 > File: protoimpl.DescBuilder{
119 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
120 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_contextpropagation_v1_message_proto_rawDesc), len(file_temporal_server_api_contextpropagation_v1_message_proto_rawDesc)),
121 > NumEnums: 0,
122 > NumMessages: 2,
123 > NumExtensions: 0,
124 > NumServices: 0,
125 > },
126 > GoTypes: file_temporal_server_api_contextpropagation_v1_message_proto_goTypes,
127 > DependencyIndexes: file_temporal_server_api_contextpropagation_v1_message_proto_depIdxs,
128 > MessageInfos: file_temporal_server_api_contextpropagation_v1_message_proto_msgTypes,
129 > }.Build()
130 > File_temporal_server_api_contextpropagation_v1_message_proto = out.File
131 > file_temporal_server_api_contextpropagation_v1_message_proto_goTypes = nil
132 > file_temporal_server_api_contextpropagation_v1_message_proto_depIdxs = nil
133 }
go.temporal.io/server/api/deployment/v1/message.pb.go 20 covered LOC · 2 ranges

Open complete file

4626 }
4627
4628 > func init() { file_temporal_server_api_deployment_v1_message_proto_init() } message.pb.go
4629 > func file_temporal_server_api_deployment_v1_message_proto_init() {
4630 > if File_temporal_server_api_deployment_v1_message_proto != nil {
4631 return
4632 }
4633 > type x struct{} message.pb.go
4634 > out := protoimpl.TypeBuilder{
4635 > File: protoimpl.DescBuilder{
4636 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
4637 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_deployment_v1_message_proto_rawDesc), len(file_temporal_server_api_deployment_v1_message_proto_rawDesc)),
4638 > NumEnums: 0,
4639 > NumMessages: 75,
4640 > NumExtensions: 0,
4641 > NumServices: 0,
4642 > },
4643 > GoTypes: file_temporal_server_api_deployment_v1_message_proto_goTypes,
4644 > DependencyIndexes: file_temporal_server_api_deployment_v1_message_proto_depIdxs,
4645 > MessageInfos: file_temporal_server_api_deployment_v1_message_proto_msgTypes,
4646 > }.Build()
4647 > File_temporal_server_api_deployment_v1_message_proto = out.File
4648 > file_temporal_server_api_deployment_v1_message_proto_goTypes = nil
4649 > file_temporal_server_api_deployment_v1_message_proto_depIdxs = nil
4650 }
go.temporal.io/server/api/enums/v1/cluster.pb.go 20 covered LOC · 2 ranges

Open complete file

209 }
210
211 > func init() { file_temporal_server_api_enums_v1_cluster_proto_init() } cluster.pb.go
212 > func file_temporal_server_api_enums_v1_cluster_proto_init() {
213 > if File_temporal_server_api_enums_v1_cluster_proto != nil {
214 return
215 }
216 > type x struct{} cluster.pb.go
217 > out := protoimpl.TypeBuilder{
218 > File: protoimpl.DescBuilder{
219 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
220 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_enums_v1_cluster_proto_rawDesc), len(file_temporal_server_api_enums_v1_cluster_proto_rawDesc)),
221 > NumEnums: 2,
222 > NumMessages: 0,
223 > NumExtensions: 0,
224 > NumServices: 0,
225 > },
226 > GoTypes: file_temporal_server_api_enums_v1_cluster_proto_goTypes,
227 > DependencyIndexes: file_temporal_server_api_enums_v1_cluster_proto_depIdxs,
228 > EnumInfos: file_temporal_server_api_enums_v1_cluster_proto_enumTypes,
229 > }.Build()
230 > File_temporal_server_api_enums_v1_cluster_proto = out.File
231 > file_temporal_server_api_enums_v1_cluster_proto_goTypes = nil
232 > file_temporal_server_api_enums_v1_cluster_proto_depIdxs = nil
233 }
go.temporal.io/server/api/enums/v1/dlq.pb.go 20 covered LOC · 2 ranges

Open complete file

187 }
188
189 > func init() { file_temporal_server_api_enums_v1_dlq_proto_init() } dlq.pb.go
190 > func file_temporal_server_api_enums_v1_dlq_proto_init() {
191 > if File_temporal_server_api_enums_v1_dlq_proto != nil {
192 return
193 }
194 > type x struct{} dlq.pb.go
195 > out := protoimpl.TypeBuilder{
196 > File: protoimpl.DescBuilder{
197 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
198 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_enums_v1_dlq_proto_rawDesc), len(file_temporal_server_api_enums_v1_dlq_proto_rawDesc)),
199 > NumEnums: 2,
200 > NumMessages: 0,
201 > NumExtensions: 0,
202 > NumServices: 0,
203 > },
204 > GoTypes: file_temporal_server_api_enums_v1_dlq_proto_goTypes,
205 > DependencyIndexes: file_temporal_server_api_enums_v1_dlq_proto_depIdxs,
206 > EnumInfos: file_temporal_server_api_enums_v1_dlq_proto_enumTypes,
207 > }.Build()
208 > File_temporal_server_api_enums_v1_dlq_proto = out.File
209 > file_temporal_server_api_enums_v1_dlq_proto_goTypes = nil
210 > file_temporal_server_api_enums_v1_dlq_proto_depIdxs = nil
211 }
go.temporal.io/server/api/enums/v1/fairness_state.pb.go 20 covered LOC · 2 ranges

Open complete file

123 }
124
125 > func init() { file_temporal_server_api_enums_v1_fairness_state_proto_init() } fairness_state.pb.go
126 > func file_temporal_server_api_enums_v1_fairness_state_proto_init() {
127 > if File_temporal_server_api_enums_v1_fairness_state_proto != nil {
128 return
129 }
130 > type x struct{} fairness_state.pb.go
131 > out := protoimpl.TypeBuilder{
132 > File: protoimpl.DescBuilder{
133 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
134 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_enums_v1_fairness_state_proto_rawDesc), len(file_temporal_server_api_enums_v1_fairness_state_proto_rawDesc)),
135 > NumEnums: 1,
136 > NumMessages: 0,
137 > NumExtensions: 0,
138 > NumServices: 0,
139 > },
140 > GoTypes: file_temporal_server_api_enums_v1_fairness_state_proto_goTypes,
141 > DependencyIndexes: file_temporal_server_api_enums_v1_fairness_state_proto_depIdxs,
142 > EnumInfos: file_temporal_server_api_enums_v1_fairness_state_proto_enumTypes,
143 > }.Build()
144 > File_temporal_server_api_enums_v1_fairness_state_proto = out.File
145 > file_temporal_server_api_enums_v1_fairness_state_proto_goTypes = nil
146 > file_temporal_server_api_enums_v1_fairness_state_proto_depIdxs = nil
147 }
go.temporal.io/server/api/enums/v1/replication.pb.go 20 covered LOC · 2 ranges

Open complete file

314 }
315
316 > func init() { file_temporal_server_api_enums_v1_replication_proto_init() } replication.pb.go
317 > func file_temporal_server_api_enums_v1_replication_proto_init() {
318 > if File_temporal_server_api_enums_v1_replication_proto != nil {
319 return
320 }
321 > type x struct{} replication.pb.go
322 > out := protoimpl.TypeBuilder{
323 > File: protoimpl.DescBuilder{
324 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
325 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_enums_v1_replication_proto_rawDesc), len(file_temporal_server_api_enums_v1_replication_proto_rawDesc)),
326 > NumEnums: 3,
327 > NumMessages: 0,
328 > NumExtensions: 0,
329 > NumServices: 0,
330 > },
331 > GoTypes: file_temporal_server_api_enums_v1_replication_proto_goTypes,
332 > DependencyIndexes: file_temporal_server_api_enums_v1_replication_proto_depIdxs,
333 > EnumInfos: file_temporal_server_api_enums_v1_replication_proto_enumTypes,
334 > }.Build()
335 > File_temporal_server_api_enums_v1_replication_proto = out.File
336 > file_temporal_server_api_enums_v1_replication_proto_goTypes = nil
337 > file_temporal_server_api_enums_v1_replication_proto_depIdxs = nil
338 }
go.temporal.io/server/api/errordetails/v1/message.pb.go 20 covered LOC · 2 ranges

Open complete file

625 }
626
627 > func init() { file_temporal_server_api_errordetails_v1_message_proto_init() } message.pb.go
628 > func file_temporal_server_api_errordetails_v1_message_proto_init() {
629 > if File_temporal_server_api_errordetails_v1_message_proto != nil {
630 return
631 }
632 > type x struct{} message.pb.go
633 > out := protoimpl.TypeBuilder{
634 > File: protoimpl.DescBuilder{
635 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
636 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_errordetails_v1_message_proto_rawDesc), len(file_temporal_server_api_errordetails_v1_message_proto_rawDesc)),
637 > NumEnums: 0,
638 > NumMessages: 10,
639 > NumExtensions: 0,
640 > NumServices: 0,
641 > },
642 > GoTypes: file_temporal_server_api_errordetails_v1_message_proto_goTypes,
643 > DependencyIndexes: file_temporal_server_api_errordetails_v1_message_proto_depIdxs,
644 > MessageInfos: file_temporal_server_api_errordetails_v1_message_proto_msgTypes,
645 > }.Build()
646 > File_temporal_server_api_errordetails_v1_message_proto = out.File
647 > file_temporal_server_api_errordetails_v1_message_proto_goTypes = nil
648 > file_temporal_server_api_errordetails_v1_message_proto_depIdxs = nil
649 }
go.temporal.io/server/api/health/v1/message.pb.go 20 covered LOC · 2 ranges

Open complete file

300 }
301
302 > func init() { file_temporal_server_api_health_v1_message_proto_init() } message.pb.go
303 > func file_temporal_server_api_health_v1_message_proto_init() {
304 > if File_temporal_server_api_health_v1_message_proto != nil {
305 return
306 }
307 > type x struct{} message.pb.go
308 > out := protoimpl.TypeBuilder{
309 > File: protoimpl.DescBuilder{
310 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
311 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_health_v1_message_proto_rawDesc), len(file_temporal_server_api_health_v1_message_proto_rawDesc)),
312 > NumEnums: 0,
313 > NumMessages: 3,
314 > NumExtensions: 0,
315 > NumServices: 0,
316 > },
317 > GoTypes: file_temporal_server_api_health_v1_message_proto_goTypes,
318 > DependencyIndexes: file_temporal_server_api_health_v1_message_proto_depIdxs,
319 > MessageInfos: file_temporal_server_api_health_v1_message_proto_msgTypes,
320 > }.Build()
321 > File_temporal_server_api_health_v1_message_proto = out.File
322 > file_temporal_server_api_health_v1_message_proto_goTypes = nil
323 > file_temporal_server_api_health_v1_message_proto_depIdxs = nil
324 }
go.temporal.io/server/api/historyservice/v1/service.pb.go 20 covered LOC · 2 ranges

Open complete file

428 }
429
430 > func init() { file_temporal_server_api_historyservice_v1_service_proto_init() } service.pb.go
431 > func file_temporal_server_api_historyservice_v1_service_proto_init() {
432 > if File_temporal_server_api_historyservice_v1_service_proto != nil {
433 return
434 }
435 > file_temporal_server_api_historyservice_v1_request_response_proto_init() service.pb.go
436 > type x struct{}
437 > out := protoimpl.TypeBuilder{
438 > File: protoimpl.DescBuilder{
439 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
440 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_historyservice_v1_service_proto_rawDesc), len(file_temporal_server_api_historyservice_v1_service_proto_rawDesc)),
441 > NumEnums: 0,
442 > NumMessages: 0,
443 > NumExtensions: 0,
444 > NumServices: 1,
445 > },
446 > GoTypes: file_temporal_server_api_historyservice_v1_service_proto_goTypes,
447 > DependencyIndexes: file_temporal_server_api_historyservice_v1_service_proto_depIdxs,
448 > }.Build()
449 > File_temporal_server_api_historyservice_v1_service_proto = out.File
450 > file_temporal_server_api_historyservice_v1_service_proto_goTypes = nil
451 > file_temporal_server_api_historyservice_v1_service_proto_depIdxs = nil
452 }
go.temporal.io/server/api/matchingservice/v1/service.pb.go 20 covered LOC · 2 ranges

Open complete file

250 }
251
252 > func init() { file_temporal_server_api_matchingservice_v1_service_proto_init() } service.pb.go
253 > func file_temporal_server_api_matchingservice_v1_service_proto_init() {
254 > if File_temporal_server_api_matchingservice_v1_service_proto != nil {
255 return
256 }
257 > file_temporal_server_api_matchingservice_v1_request_response_proto_init() service.pb.go
258 > type x struct{}
259 > out := protoimpl.TypeBuilder{
260 > File: protoimpl.DescBuilder{
261 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
262 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_matchingservice_v1_service_proto_rawDesc), len(file_temporal_server_api_matchingservice_v1_service_proto_rawDesc)),
263 > NumEnums: 0,
264 > NumMessages: 0,
265 > NumExtensions: 0,
266 > NumServices: 1,
267 > },
268 > GoTypes: file_temporal_server_api_matchingservice_v1_service_proto_goTypes,
269 > DependencyIndexes: file_temporal_server_api_matchingservice_v1_service_proto_depIdxs,
270 > }.Build()
271 > File_temporal_server_api_matchingservice_v1_service_proto = out.File
272 > file_temporal_server_api_matchingservice_v1_service_proto_goTypes = nil
273 > file_temporal_server_api_matchingservice_v1_service_proto_depIdxs = nil
274 }
go.temporal.io/server/api/metrics/v1/message.pb.go 20 covered LOC · 2 ranges

Open complete file

104 }
105
106 > func init() { file_temporal_server_api_metrics_v1_message_proto_init() } message.pb.go
107 > func file_temporal_server_api_metrics_v1_message_proto_init() {
108 > if File_temporal_server_api_metrics_v1_message_proto != nil {
109 return
110 }
111 > type x struct{} message.pb.go
112 > out := protoimpl.TypeBuilder{
113 > File: protoimpl.DescBuilder{
114 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
115 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_metrics_v1_message_proto_rawDesc), len(file_temporal_server_api_metrics_v1_message_proto_rawDesc)),
116 > NumEnums: 0,
117 > NumMessages: 2,
118 > NumExtensions: 0,
119 > NumServices: 0,
120 > },
121 > GoTypes: file_temporal_server_api_metrics_v1_message_proto_goTypes,
122 > DependencyIndexes: file_temporal_server_api_metrics_v1_message_proto_depIdxs,
123 > MessageInfos: file_temporal_server_api_metrics_v1_message_proto_msgTypes,
124 > }.Build()
125 > File_temporal_server_api_metrics_v1_message_proto = out.File
126 > file_temporal_server_api_metrics_v1_message_proto_goTypes = nil
127 > file_temporal_server_api_metrics_v1_message_proto_depIdxs = nil
128 }
go.temporal.io/server/api/namespace/v1/message.pb.go 20 covered LOC · 2 ranges

Open complete file

114 }
115
116 > func init() { file_temporal_server_api_namespace_v1_message_proto_init() } message.pb.go
117 > func file_temporal_server_api_namespace_v1_message_proto_init() {
118 > if File_temporal_server_api_namespace_v1_message_proto != nil {
119 return
120 }
121 > type x struct{} message.pb.go
122 > out := protoimpl.TypeBuilder{
123 > File: protoimpl.DescBuilder{
124 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
125 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_namespace_v1_message_proto_rawDesc), len(file_temporal_server_api_namespace_v1_message_proto_rawDesc)),
126 > NumEnums: 0,
127 > NumMessages: 1,
128 > NumExtensions: 0,
129 > NumServices: 0,
130 > },
131 > GoTypes: file_temporal_server_api_namespace_v1_message_proto_goTypes,
132 > DependencyIndexes: file_temporal_server_api_namespace_v1_message_proto_depIdxs,
133 > MessageInfos: file_temporal_server_api_namespace_v1_message_proto_msgTypes,
134 > }.Build()
135 > File_temporal_server_api_namespace_v1_message_proto = out.File
136 > file_temporal_server_api_namespace_v1_message_proto_goTypes = nil
137 > file_temporal_server_api_namespace_v1_message_proto_depIdxs = nil
138 }
go.temporal.io/server/api/persistence/v1/chasm_visibility.pb.go 20 covered LOC · 2 ranges

Open complete file

146 }
147
148 > func init() { file_temporal_server_api_persistence_v1_chasm_visibility_proto_init() } chasm_visibility.pb.go
149 > func file_temporal_server_api_persistence_v1_chasm_visibility_proto_init() {
150 > if File_temporal_server_api_persistence_v1_chasm_visibility_proto != nil {
151 return
152 }
153 > type x struct{} chasm_visibility.pb.go
154 > out := protoimpl.TypeBuilder{
155 > File: protoimpl.DescBuilder{
156 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
157 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_chasm_visibility_proto_rawDesc), len(file_temporal_server_api_persistence_v1_chasm_visibility_proto_rawDesc)),
158 > NumEnums: 0,
159 > NumMessages: 2,
160 > NumExtensions: 0,
161 > NumServices: 0,
162 > },
163 > GoTypes: file_temporal_server_api_persistence_v1_chasm_visibility_proto_goTypes,
164 > DependencyIndexes: file_temporal_server_api_persistence_v1_chasm_visibility_proto_depIdxs,
165 > MessageInfos: file_temporal_server_api_persistence_v1_chasm_visibility_proto_msgTypes,
166 > }.Build()
167 > File_temporal_server_api_persistence_v1_chasm_visibility_proto = out.File
168 > file_temporal_server_api_persistence_v1_chasm_visibility_proto_goTypes = nil
169 > file_temporal_server_api_persistence_v1_chasm_visibility_proto_depIdxs = nil
170 }
go.temporal.io/server/api/persistence/v1/cluster_metadata.pb.go 20 covered LOC · 2 ranges

Open complete file

289 }
290
291 > func init() { file_temporal_server_api_persistence_v1_cluster_metadata_proto_init() } cluster_metadata.pb.go
292 > func file_temporal_server_api_persistence_v1_cluster_metadata_proto_init() {
293 > if File_temporal_server_api_persistence_v1_cluster_metadata_proto != nil {
294 return
295 }
296 > type x struct{} cluster_metadata.pb.go
297 > out := protoimpl.TypeBuilder{
298 > File: protoimpl.DescBuilder{
299 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
300 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_cluster_metadata_proto_rawDesc), len(file_temporal_server_api_persistence_v1_cluster_metadata_proto_rawDesc)),
301 > NumEnums: 0,
302 > NumMessages: 5,
303 > NumExtensions: 0,
304 > NumServices: 0,
305 > },
306 > GoTypes: file_temporal_server_api_persistence_v1_cluster_metadata_proto_goTypes,
307 > DependencyIndexes: file_temporal_server_api_persistence_v1_cluster_metadata_proto_depIdxs,
308 > MessageInfos: file_temporal_server_api_persistence_v1_cluster_metadata_proto_msgTypes,
309 > }.Build()
310 > File_temporal_server_api_persistence_v1_cluster_metadata_proto = out.File
311 > file_temporal_server_api_persistence_v1_cluster_metadata_proto_goTypes = nil
312 > file_temporal_server_api_persistence_v1_cluster_metadata_proto_depIdxs = nil
313 }
go.temporal.io/server/api/persistence/v1/queue_metadata.pb.go 20 covered LOC · 2 ranges

Open complete file

105 }
106
107 > func init() { file_temporal_server_api_persistence_v1_queue_metadata_proto_init() } queue_metadata.pb.go
108 > func file_temporal_server_api_persistence_v1_queue_metadata_proto_init() {
109 > if File_temporal_server_api_persistence_v1_queue_metadata_proto != nil {
110 return
111 }
112 > type x struct{} queue_metadata.pb.go
113 > out := protoimpl.TypeBuilder{
114 > File: protoimpl.DescBuilder{
115 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
116 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_queue_metadata_proto_rawDesc), len(file_temporal_server_api_persistence_v1_queue_metadata_proto_rawDesc)),
117 > NumEnums: 0,
118 > NumMessages: 2,
119 > NumExtensions: 0,
120 > NumServices: 0,
121 > },
122 > GoTypes: file_temporal_server_api_persistence_v1_queue_metadata_proto_goTypes,
123 > DependencyIndexes: file_temporal_server_api_persistence_v1_queue_metadata_proto_depIdxs,
124 > MessageInfos: file_temporal_server_api_persistence_v1_queue_metadata_proto_msgTypes,
125 > }.Build()
126 > File_temporal_server_api_persistence_v1_queue_metadata_proto = out.File
127 > file_temporal_server_api_persistence_v1_queue_metadata_proto_goTypes = nil
128 > file_temporal_server_api_persistence_v1_queue_metadata_proto_depIdxs = nil
129 }
go.temporal.io/server/api/persistence/v1/tasks.pb.go 20 covered LOC · 2 ranges

Open complete file

846 }
847
848 > func init() { file_temporal_server_api_persistence_v1_tasks_proto_init() } tasks.pb.go
849 > func file_temporal_server_api_persistence_v1_tasks_proto_init() {
850 > if File_temporal_server_api_persistence_v1_tasks_proto != nil {
851 return
852 }
853 > type x struct{} tasks.pb.go
854 > out := protoimpl.TypeBuilder{
855 > File: protoimpl.DescBuilder{
856 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
857 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_persistence_v1_tasks_proto_rawDesc), len(file_temporal_server_api_persistence_v1_tasks_proto_rawDesc)),
858 > NumEnums: 0,
859 > NumMessages: 8,
860 > NumExtensions: 0,
861 > NumServices: 0,
862 > },
863 > GoTypes: file_temporal_server_api_persistence_v1_tasks_proto_goTypes,
864 > DependencyIndexes: file_temporal_server_api_persistence_v1_tasks_proto_depIdxs,
865 > MessageInfos: file_temporal_server_api_persistence_v1_tasks_proto_msgTypes,
866 > }.Build()
867 > File_temporal_server_api_persistence_v1_tasks_proto = out.File
868 > file_temporal_server_api_persistence_v1_tasks_proto_goTypes = nil
869 > file_temporal_server_api_persistence_v1_tasks_proto_depIdxs = nil
870 }
go.temporal.io/server/api/visibilityservice/v1/request_response.pb.go 20 covered LOC · 2 ranges

Open complete file

402 }
403
404 > func init() { file_temporal_server_api_visibilityservice_v1_request_response_proto_init() } request_response.pb.go
405 > func file_temporal_server_api_visibilityservice_v1_request_response_proto_init() {
406 > if File_temporal_server_api_visibilityservice_v1_request_response_proto != nil {
407 return
408 }
409 > type x struct{} request_response.pb.go
410 > out := protoimpl.TypeBuilder{
411 > File: protoimpl.DescBuilder{
412 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
413 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_api_visibilityservice_v1_request_response_proto_rawDesc), len(file_temporal_server_api_visibilityservice_v1_request_response_proto_rawDesc)),
414 > NumEnums: 0,
415 > NumMessages: 5,
416 > NumExtensions: 0,
417 > NumServices: 0,
418 > },
419 > GoTypes: file_temporal_server_api_visibilityservice_v1_request_response_proto_goTypes,
420 > DependencyIndexes: file_temporal_server_api_visibilityservice_v1_request_response_proto_depIdxs,
421 > MessageInfos: file_temporal_server_api_visibilityservice_v1_request_response_proto_msgTypes,
422 > }.Build()
423 > File_temporal_server_api_visibilityservice_v1_request_response_proto = out.File
424 > file_temporal_server_api_visibilityservice_v1_request_response_proto_goTypes = nil
425 > file_temporal_server_api_visibilityservice_v1_request_response_proto_depIdxs = nil
426 }
go.temporal.io/server/chasm/lib/activity/gen/activitypb/v1/service.pb.go 20 covered LOC · 2 ranges

Open complete file

91 }
92
93 > func init() { file_temporal_server_chasm_lib_activity_proto_v1_service_proto_init() } service.pb.go
94 > func file_temporal_server_chasm_lib_activity_proto_v1_service_proto_init() {
95 > if File_temporal_server_chasm_lib_activity_proto_v1_service_proto != nil {
96 return
97 }
98 > file_temporal_server_chasm_lib_activity_proto_v1_request_response_proto_init() service.pb.go
99 > type x struct{}
100 > out := protoimpl.TypeBuilder{
101 > File: protoimpl.DescBuilder{
102 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
103 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_activity_proto_v1_service_proto_rawDesc), len(file_temporal_server_chasm_lib_activity_proto_v1_service_proto_rawDesc)),
104 > NumEnums: 0,
105 > NumMessages: 0,
106 > NumExtensions: 0,
107 > NumServices: 1,
108 > },
109 > GoTypes: file_temporal_server_chasm_lib_activity_proto_v1_service_proto_goTypes,
110 > DependencyIndexes: file_temporal_server_chasm_lib_activity_proto_v1_service_proto_depIdxs,
111 > }.Build()
112 > File_temporal_server_chasm_lib_activity_proto_v1_service_proto = out.File
113 > file_temporal_server_chasm_lib_activity_proto_v1_service_proto_goTypes = nil
114 > file_temporal_server_chasm_lib_activity_proto_v1_service_proto_depIdxs = nil
115 }
go.temporal.io/server/chasm/lib/callback/gen/callbackpb/v1/tasks.pb.go 20 covered LOC · 2 ranges

Open complete file

148 }
149
150 > func init() { file_temporal_server_chasm_lib_callback_proto_v1_tasks_proto_init() } tasks.pb.go
151 > func file_temporal_server_chasm_lib_callback_proto_v1_tasks_proto_init() {
152 > if File_temporal_server_chasm_lib_callback_proto_v1_tasks_proto != nil {
153 return
154 }
155 > type x struct{} tasks.pb.go
156 > out := protoimpl.TypeBuilder{
157 > File: protoimpl.DescBuilder{
158 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
159 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_callback_proto_v1_tasks_proto_rawDesc), len(file_temporal_server_chasm_lib_callback_proto_v1_tasks_proto_rawDesc)),
160 > NumEnums: 0,
161 > NumMessages: 2,
162 > NumExtensions: 0,
163 > NumServices: 0,
164 > },
165 > GoTypes: file_temporal_server_chasm_lib_callback_proto_v1_tasks_proto_goTypes,
166 > DependencyIndexes: file_temporal_server_chasm_lib_callback_proto_v1_tasks_proto_depIdxs,
167 > MessageInfos: file_temporal_server_chasm_lib_callback_proto_v1_tasks_proto_msgTypes,
168 > }.Build()
169 > File_temporal_server_chasm_lib_callback_proto_v1_tasks_proto = out.File
170 > file_temporal_server_chasm_lib_callback_proto_v1_tasks_proto_goTypes = nil
171 > file_temporal_server_chasm_lib_callback_proto_v1_tasks_proto_depIdxs = nil
172 }
go.temporal.io/server/chasm/lib/nexusoperation/gen/nexusoperationpb/v1/service.pb.go 20 covered LOC · 2 ranges

Open complete file

71 }
72
73 > func init() { file_temporal_server_chasm_lib_nexusoperation_proto_v1_service_proto_init() } service.pb.go
74 > func file_temporal_server_chasm_lib_nexusoperation_proto_v1_service_proto_init() {
75 > if File_temporal_server_chasm_lib_nexusoperation_proto_v1_service_proto != nil {
76 return
77 }
78 > file_temporal_server_chasm_lib_nexusoperation_proto_v1_request_response_proto_init() service.pb.go
79 > type x struct{}
80 > out := protoimpl.TypeBuilder{
81 > File: protoimpl.DescBuilder{
82 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
83 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_nexusoperation_proto_v1_service_proto_rawDesc), len(file_temporal_server_chasm_lib_nexusoperation_proto_v1_service_proto_rawDesc)),
84 > NumEnums: 0,
85 > NumMessages: 0,
86 > NumExtensions: 0,
87 > NumServices: 1,
88 > },
89 > GoTypes: file_temporal_server_chasm_lib_nexusoperation_proto_v1_service_proto_goTypes,
90 > DependencyIndexes: file_temporal_server_chasm_lib_nexusoperation_proto_v1_service_proto_depIdxs,
91 > }.Build()
92 > File_temporal_server_chasm_lib_nexusoperation_proto_v1_service_proto = out.File
93 > file_temporal_server_chasm_lib_nexusoperation_proto_v1_service_proto_goTypes = nil
94 > file_temporal_server_chasm_lib_nexusoperation_proto_v1_service_proto_depIdxs = nil
95 }
go.temporal.io/server/chasm/lib/nexusoperation/gen/nexusoperationpb/v1/tasks.pb.go 20 covered LOC · 2 ranges

Open complete file

354 }
355
356 > func init() { file_temporal_server_chasm_lib_nexusoperation_proto_v1_tasks_proto_init() } tasks.pb.go
357 > func file_temporal_server_chasm_lib_nexusoperation_proto_v1_tasks_proto_init() {
358 > if File_temporal_server_chasm_lib_nexusoperation_proto_v1_tasks_proto != nil {
359 return
360 }
361 > type x struct{} tasks.pb.go
362 > out := protoimpl.TypeBuilder{
363 > File: protoimpl.DescBuilder{
364 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
365 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_nexusoperation_proto_v1_tasks_proto_rawDesc), len(file_temporal_server_chasm_lib_nexusoperation_proto_v1_tasks_proto_rawDesc)),
366 > NumEnums: 0,
367 > NumMessages: 7,
368 > NumExtensions: 0,
369 > NumServices: 0,
370 > },
371 > GoTypes: file_temporal_server_chasm_lib_nexusoperation_proto_v1_tasks_proto_goTypes,
372 > DependencyIndexes: file_temporal_server_chasm_lib_nexusoperation_proto_v1_tasks_proto_depIdxs,
373 > MessageInfos: file_temporal_server_chasm_lib_nexusoperation_proto_v1_tasks_proto_msgTypes,
374 > }.Build()
375 > File_temporal_server_chasm_lib_nexusoperation_proto_v1_tasks_proto = out.File
376 > file_temporal_server_chasm_lib_nexusoperation_proto_v1_tasks_proto_goTypes = nil
377 > file_temporal_server_chasm_lib_nexusoperation_proto_v1_tasks_proto_depIdxs = nil
378 }
go.temporal.io/server/chasm/lib/scheduler/gen/schedulerpb/v1/service.pb.go 20 covered LOC · 2 ranges

Open complete file

86 }
87
88 > func init() { file_temporal_server_chasm_lib_scheduler_proto_v1_service_proto_init() } service.pb.go
89 > func file_temporal_server_chasm_lib_scheduler_proto_v1_service_proto_init() {
90 > if File_temporal_server_chasm_lib_scheduler_proto_v1_service_proto != nil {
91 return
92 }
93 > file_temporal_server_chasm_lib_scheduler_proto_v1_request_response_proto_init() service.pb.go
94 > type x struct{}
95 > out := protoimpl.TypeBuilder{
96 > File: protoimpl.DescBuilder{
97 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
98 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_scheduler_proto_v1_service_proto_rawDesc), len(file_temporal_server_chasm_lib_scheduler_proto_v1_service_proto_rawDesc)),
99 > NumEnums: 0,
100 > NumMessages: 0,
101 > NumExtensions: 0,
102 > NumServices: 1,
103 > },
104 > GoTypes: file_temporal_server_chasm_lib_scheduler_proto_v1_service_proto_goTypes,
105 > DependencyIndexes: file_temporal_server_chasm_lib_scheduler_proto_v1_service_proto_depIdxs,
106 > }.Build()
107 > File_temporal_server_chasm_lib_scheduler_proto_v1_service_proto = out.File
108 > file_temporal_server_chasm_lib_scheduler_proto_v1_service_proto_goTypes = nil
109 > file_temporal_server_chasm_lib_scheduler_proto_v1_service_proto_depIdxs = nil
110 }
go.temporal.io/server/chasm/lib/scheduler/gen/schedulerpb/v1/tasks.pb.go 20 covered LOC · 2 ranges

Open complete file

343 }
344
345 > func init() { file_temporal_server_chasm_lib_scheduler_proto_v1_tasks_proto_init() } tasks.pb.go
346 > func file_temporal_server_chasm_lib_scheduler_proto_v1_tasks_proto_init() {
347 > if File_temporal_server_chasm_lib_scheduler_proto_v1_tasks_proto != nil {
348 return
349 }
350 > type x struct{} tasks.pb.go
351 > out := protoimpl.TypeBuilder{
352 > File: protoimpl.DescBuilder{
353 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
354 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_scheduler_proto_v1_tasks_proto_rawDesc), len(file_temporal_server_chasm_lib_scheduler_proto_v1_tasks_proto_rawDesc)),
355 > NumEnums: 0,
356 > NumMessages: 7,
357 > NumExtensions: 0,
358 > NumServices: 0,
359 > },
360 > GoTypes: file_temporal_server_chasm_lib_scheduler_proto_v1_tasks_proto_goTypes,
361 > DependencyIndexes: file_temporal_server_chasm_lib_scheduler_proto_v1_tasks_proto_depIdxs,
362 > MessageInfos: file_temporal_server_chasm_lib_scheduler_proto_v1_tasks_proto_msgTypes,
363 > }.Build()
364 > File_temporal_server_chasm_lib_scheduler_proto_v1_tasks_proto = out.File
365 > file_temporal_server_chasm_lib_scheduler_proto_v1_tasks_proto_goTypes = nil
366 > file_temporal_server_chasm_lib_scheduler_proto_v1_tasks_proto_depIdxs = nil
367 }
go.temporal.io/server/chasm/lib/tests/gen/testspb/v1/message.pb.go 20 covered LOC · 2 ranges

Open complete file

242 }
243
244 > func init() { file_temporal_server_chasm_lib_tests_proto_v1_message_proto_init() } message.pb.go
245 > func file_temporal_server_chasm_lib_tests_proto_v1_message_proto_init() {
246 > if File_temporal_server_chasm_lib_tests_proto_v1_message_proto != nil {
247 return
248 }
249 > type x struct{} message.pb.go
250 > out := protoimpl.TypeBuilder{
251 > File: protoimpl.DescBuilder{
252 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
253 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_tests_proto_v1_message_proto_rawDesc), len(file_temporal_server_chasm_lib_tests_proto_v1_message_proto_rawDesc)),
254 > NumEnums: 0,
255 > NumMessages: 4,
256 > NumExtensions: 0,
257 > NumServices: 0,
258 > },
259 > GoTypes: file_temporal_server_chasm_lib_tests_proto_v1_message_proto_goTypes,
260 > DependencyIndexes: file_temporal_server_chasm_lib_tests_proto_v1_message_proto_depIdxs,
261 > MessageInfos: file_temporal_server_chasm_lib_tests_proto_v1_message_proto_msgTypes,
262 > }.Build()
263 > File_temporal_server_chasm_lib_tests_proto_v1_message_proto = out.File
264 > file_temporal_server_chasm_lib_tests_proto_v1_message_proto_goTypes = nil
265 > file_temporal_server_chasm_lib_tests_proto_v1_message_proto_depIdxs = nil
266 }
go.temporal.io/server/chasm/lib/tests/gen/testspb/v1/service.pb.go 20 covered LOC · 2 ranges

Open complete file

46 }
47
48 > func init() { file_temporal_server_chasm_lib_tests_proto_v1_service_proto_init() } service.pb.go
49 > func file_temporal_server_chasm_lib_tests_proto_v1_service_proto_init() {
50 > if File_temporal_server_chasm_lib_tests_proto_v1_service_proto != nil {
51 return
52 }
53 > file_temporal_server_chasm_lib_tests_proto_v1_request_response_proto_init() service.pb.go
54 > type x struct{}
55 > out := protoimpl.TypeBuilder{
56 > File: protoimpl.DescBuilder{
57 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
58 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_tests_proto_v1_service_proto_rawDesc), len(file_temporal_server_chasm_lib_tests_proto_v1_service_proto_rawDesc)),
59 > NumEnums: 0,
60 > NumMessages: 0,
61 > NumExtensions: 0,
62 > NumServices: 1,
63 > },
64 > GoTypes: file_temporal_server_chasm_lib_tests_proto_v1_service_proto_goTypes,
65 > DependencyIndexes: file_temporal_server_chasm_lib_tests_proto_v1_service_proto_depIdxs,
66 > }.Build()
67 > File_temporal_server_chasm_lib_tests_proto_v1_service_proto = out.File
68 > file_temporal_server_chasm_lib_tests_proto_v1_service_proto_goTypes = nil
69 > file_temporal_server_chasm_lib_tests_proto_v1_service_proto_depIdxs = nil
70 }
go.temporal.io/server/chasm/lib/workflow/gen/workflowpb/v1/state.pb.go 20 covered LOC · 2 ranges

Open complete file

211 }
212
213 > func init() { file_temporal_server_chasm_lib_workflow_proto_v1_state_proto_init() } state.pb.go
214 > func file_temporal_server_chasm_lib_workflow_proto_v1_state_proto_init() {
215 > if File_temporal_server_chasm_lib_workflow_proto_v1_state_proto != nil {
216 return
217 }
218 > type x struct{} state.pb.go
219 > out := protoimpl.TypeBuilder{
220 > File: protoimpl.DescBuilder{
221 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
222 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_workflow_proto_v1_state_proto_rawDesc), len(file_temporal_server_chasm_lib_workflow_proto_v1_state_proto_rawDesc)),
223 > NumEnums: 0,
224 > NumMessages: 3,
225 > NumExtensions: 0,
226 > NumServices: 0,
227 > },
228 > GoTypes: file_temporal_server_chasm_lib_workflow_proto_v1_state_proto_goTypes,
229 > DependencyIndexes: file_temporal_server_chasm_lib_workflow_proto_v1_state_proto_depIdxs,
230 > MessageInfos: file_temporal_server_chasm_lib_workflow_proto_v1_state_proto_msgTypes,
231 > }.Build()
232 > File_temporal_server_chasm_lib_workflow_proto_v1_state_proto = out.File
233 > file_temporal_server_chasm_lib_workflow_proto_v1_state_proto_goTypes = nil
234 > file_temporal_server_chasm_lib_workflow_proto_v1_state_proto_depIdxs = nil
235 }
go.temporal.io/server/chasm/lib/workflow/gen/workflowpb/v1/update_state.pb.go 20 covered LOC · 2 ranges

Open complete file

113 }
114
115 > func init() { file_temporal_server_chasm_lib_workflow_proto_v1_update_state_proto_init() } update_state.pb.go
116 > func file_temporal_server_chasm_lib_workflow_proto_v1_update_state_proto_init() {
117 > if File_temporal_server_chasm_lib_workflow_proto_v1_update_state_proto != nil {
118 return
119 }
120 > type x struct{} update_state.pb.go
121 > out := protoimpl.TypeBuilder{
122 > File: protoimpl.DescBuilder{
123 > GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
124 > RawDescriptor: unsafe.Slice(unsafe.StringData(file_temporal_server_chasm_lib_workflow_proto_v1_update_state_proto_rawDesc), len(file_temporal_server_chasm_lib_workflow_proto_v1_update_state_proto_rawDesc)),
125 > NumEnums: 0,
126 > NumMessages: 1,
127 > NumExtensions: 0,
128 > NumServices: 0,
129 > },
130 > GoTypes: file_temporal_server_chasm_lib_workflow_proto_v1_update_state_proto_goTypes,
131 > DependencyIndexes: file_temporal_server_chasm_lib_workflow_proto_v1_update_state_proto_depIdxs,
132 > MessageInfos: file_temporal_server_chasm_lib_workflow_proto_v1_update_state_proto_msgTypes,
133 > }.Build()
134 > File_temporal_server_chasm_lib_workflow_proto_v1_update_state_proto = out.File
135 > file_temporal_server_chasm_lib_workflow_proto_v1_update_state_proto_goTypes = nil
136 > file_temporal_server_chasm_lib_workflow_proto_v1_update_state_proto_depIdxs = nil
137 }
go.temporal.io/server/common/primitives/uuid.go 20 covered LOC · 5 ranges

Open complete file

68
69 // NewUUID generates a new random UUID
70 > func NewUUID() UUID { uuid.go
71 > u, err := guuid.NewV7()
72 > if err != nil {
73 // Should never happen, but this matches the behavior of google/uuid.NewRandom
74 return nil
75 }
76 > return u[:] uuid.go
77 }
78
91 // String returns the 36 byte hexstring representation of this uuid
92 // return empty string if this uuid is nil
93 > func (u UUID) String() string { uuid.go
94 > if len(u) != 16 {
95 return ""
96 }
97 > var buf [36]byte uuid.go
98 > u.encodeHex(buf[:])
99 > return string(buf[:])
100 }
101
140 }
141
142 > func (u UUID) encodeHex(dst []byte) { uuid.go
143 > hex.Encode(dst, u[:4])
144 > dst[8] = '-'
145 > hex.Encode(dst[9:13], u[4:6])
146 > dst[13] = '-'
147 > hex.Encode(dst[14:18], u[6:8])
148 > dst[18] = '-'
149 > hex.Encode(dst[19:23], u[8:10])
150 > dst[23] = '-'
151 > hex.Encode(dst[24:], u[10:])
152 > }
go.temporal.io/server/common/util/wildcard.go 20 covered LOC · 7 ranges

Open complete file

18 // WildCardStringToRegexps converts a given slices of string patterns to a slice of regular expressions matching
19 // wildcards (*) with any substring.
20 > func WildCardStringsToRegexp(patterns []string) (*regexp.Regexp, error) { wildcard.go
21 > var result strings.Builder
22 > result.WriteRune('^')
23 > for i, pattern := range patterns {
24 > result.WriteRune('(')
25 > first := true
26 > for literal := range strings.SplitSeq(pattern, "*") {
27 > if !first {
28 // Replace * with .*
29 result.WriteString(".*")
30 }
31 > result.WriteString(regexp.QuoteMeta(literal)) wildcard.go
32 > first = false
33 }
34 > result.WriteRune(')') wildcard.go
35 > if i < len(patterns)-1 {
36 > result.WriteRune('|') wildcard.go
37 > }
38 }
39 > result.WriteRune('$') wildcard.go
40 > return regexp.Compile(result.String())
41 }
42
43 // MustWildCardStringsToRegexp is like WildCardStringsToRegexp but panics on error.
44 > func MustWildCardStringsToRegexp(patterns []string) *regexp.Regexp { wildcard.go
45 > re, err := WildCardStringsToRegexp(patterns)
46 > if err != nil {
47 panic(err) //nolint:forbidigo // Must* functions conventionally panic on error.
48 }
49 > return re wildcard.go
50 }
go.temporal.io/server/common/collection/concurrent_tx_map.go 19 covered LOC · 4 ranges

Open complete file

55 //
56 // The hash function to use for sharding
57 > func NewShardedConcurrentTxMap(initialCap int, hashfn HashFunc) ConcurrentTxMap { concurrent_tx_map.go
58 > cmap := new(ShardedConcurrentTxMap)
59 > cmap.hashfn = hashfn
60 > cmap.initialCap = max(nShards, initialCap/nShards)
61 > return cmap
62 > }
63
64 // Get returns the value corresponding to the key, if it exist
125 // GetAndDo returns the value corresponding to the key, and apply fn to key value before return value
126 // return (value, value exist or not, error when evaluation fn)
127 > func (cmap *ShardedConcurrentTxMap) GetAndDo(key any, fn ActionFunc) (any, bool, error) { concurrent_tx_map.go
128 > shard := cmap.getShard(key)
129 > var value any
130 > var ok bool
131 > var err error
132 > shard.Lock()
133 > if shard.items != nil {
134 value, ok = shard.items[key]
135 if ok {
222 }
223
224 > func (cmap *ShardedConcurrentTxMap) getShard(key any) *mapShard { concurrent_tx_map.go
225 > shardIdx := cmap.hashfn(key) % nShards
226 > return &cmap.shards[shardIdx]
227 > }
228
229 func (cmap *ShardedConcurrentTxMap) lazyInitShard(shard *mapShard) {
go.temporal.io/server/common/persistence/transitionhistory/transition_history.go 19 covered LOC · 10 ranges

Open complete file

12 func CopyVersionedTransitions(
13 transitions []*persistencespb.VersionedTransition,
14 > ) []*persistencespb.VersionedTransition { transition_history.go
15 > if transitions == nil {
16 return nil
17 }
18 > copied := make([]*persistencespb.VersionedTransition, len(transitions)) transition_history.go
19 > for i, t := range transitions {
20 > copied[i] = CopyVersionedTransition(t)
21 > }
22 > return copied
23 }
24
25 func CopyVersionedTransition(
26 transition *persistencespb.VersionedTransition,
27 > ) *persistencespb.VersionedTransition { transition_history.go
28 > if transition == nil {
29 return nil
30 }
31 > return common.CloneProto(transition) transition_history.go
32 }
33
34 func LastVersionedTransition(
35 transitions []*persistencespb.VersionedTransition,
36 > ) *persistencespb.VersionedTransition { transition_history.go
37 > if len(transitions) == 0 {
38 // transition history is not enabled
39 return nil
40 }
41 > return transitions[len(transitions)-1] transition_history.go
42 }
43
51 func Compare(
52 a, b *persistencespb.VersionedTransition,
53 > ) int { transition_history.go
54 > if a.GetNamespaceFailoverVersion() < b.GetNamespaceFailoverVersion() {
55 return -1
56 }
57 > if a.GetNamespaceFailoverVersion() > b.GetNamespaceFailoverVersion() { transition_history.go
58 return 1
59 }
60
61 > if a.GetTransitionCount() < b.GetTransitionCount() { transition_history.go
62 > return -1 transition_history.go
63 > }
64 if a.GetTransitionCount() > b.GetTransitionCount() {
65 return 1
go.temporal.io/server/service/history/hsm/registry.go 19 covered LOC · 4 ranges

Open complete file

47
48 // NewRegistry creates a new [Registry].
49 > func NewRegistry() *Registry { registry.go
50 > return &Registry{
51 > machines: make(map[string]StateMachineDefinition),
52 > tasks: make(map[string]TaskSerializer),
53 > immediateExecutors: make(map[string]any),
54 > timerExecutors: make(map[string]any),
55 > remoteExecutors: make(map[string]remoteMethodDefinition),
56 > events: make(map[enumspb.EventType]EventDefinition),
57 > }
58 > }
59
60 // RegisterMachine registers a [StateMachineDefinition] by its type.
61 // Returns an [ErrDuplicateRegistration] if the state machine type has already been registered.
62 > func (r *Registry) RegisterMachine(sm StateMachineDefinition) error { registry.go
63 > t := sm.Type()
64 > if existing, ok := r.machines[t]; ok {
65 return fmt.Errorf("%w: state machine already registered for %v - %v", ErrDuplicateRegistration, sm.Type(), existing.Type())
66 }
67 > r.machines[t] = sm registry.go
68 > return nil
69 }
70
71 // Machine returns a [StateMachineDefinition] for a given type and a boolean indicating whether it was found.
72 > func (r *Registry) Machine(t string) (def StateMachineDefinition, ok bool) { registry.go
73 > def, ok = r.machines[t]
74 > return
75 > }
76
77 // RegisterTaskSerializer registers a [TaskSerializer] for a given type.
go.temporal.io/server/service/history/workflow/task_generator_provider.go 19 covered LOC · 4 ranges

Open complete file

23 )
24
25 > func init() { task_generator_provider.go
26 > var defaultProvider TaskGeneratorProvider = new(taskGeneratorProviderImpl)
27 > populateTaskGeneratorProvider(defaultProvider)
28 > }
29
30 > func populateTaskGeneratorProvider(provider TaskGeneratorProvider) { task_generator_provider.go
31 > _taskGeneratorProvider.Store(&provider)
32 > }
33
34 > func GetTaskGeneratorProvider() TaskGeneratorProvider { task_generator_provider.go
35 > return *_taskGeneratorProvider.Load()
36 > }
37
38 func (p *taskGeneratorProviderImpl) NewTaskGenerator(
39 shard historyi.ShardContext,
40 mutableState historyi.MutableState,
41 > ) TaskGenerator { task_generator_provider.go
42 > return NewTaskGenerator(
43 > shard.GetNamespaceRegistry(),
44 > mutableState,
45 > shard.GetConfig(),
46 > shard.GetArchivalMetadata(),
47 > shard.GetLogger(),
48 > )
49 > }
go.temporal.io/server/common/persistence/history_branch_util.go 18 covered LOC · 6 ranges

Open complete file

41 )
42
43 > func NewHistoryBranchUtil(serializer serialization.Serializer) *HistoryBranchUtilImpl { history_branch_util.go
44 > return &HistoryBranchUtilImpl{
45 > serializer: serializer,
46 > }
47 > }
48
49 func (u *HistoryBranchUtilImpl) NewHistoryBranch(
57 _ time.Duration, // executionTimeout
58 _ time.Duration, // retentionDuration
59 > ) ([]byte, error) { history_branch_util.go
60 > var id string
61 > if branchID == nil {
62 > id = primitives.NewUUID().String() history_branch_util.go
63 > } else { history_branch_util.go
64 id = *branchID
65 }
66 > bi := &persistencespb.HistoryBranch{ history_branch_util.go
67 > TreeId: treeID,
68 > BranchId: id,
69 > Ancestors: ancestors,
70 > }
71 > data, err := u.serializer.HistoryBranchToBlob(bi)
72 > if err != nil {
73 return nil, err
74 }
75 > return data.Data, nil history_branch_util.go
76 }
77
go.temporal.io/server/common/util/util.go 18 covered LOC · 8 ranges

Open complete file

20
21 // MaxTime returns the latest of the given time.Time values.
22 > func MaxTime(first time.Time, rest ...time.Time) time.Time { util.go
23 > latest := first
24 > for _, t := range rest {
25 > if t.After(latest) {
26 > latest = t util.go
27 > }
28 }
29 > return latest util.go
30 }
31
51
52 // SliceTail returns the last n elements of s. n may be greater than len(s).
53 > func SliceTail[S ~[]E, E any](s S, n int) S { util.go
54 > if extra := len(s) - n; extra > 0 {
55 return s[extra:]
56 }
57 > return s util.go
58 }
59
60 // CloneMapNonNil is like maps.Clone except it can't return nil, it will return an empty map instead.
61 > func CloneMapNonNil[M ~map[K]V, K comparable, V any](m M) M { util.go
62 > m = maps.Clone(m)
63 > if m == nil {
64 m = make(M)
65 }
66 > return m util.go
67 }
68
69 // InverseMap creates the inverse map, ie., for a key-value map, it builds the value-key map.
70 > func InverseMap[M ~map[K]V, K, V comparable](m M) map[V]K { util.go
71 > if m == nil {
72 > return nil
73 > }
74 invm := make(map[V]K, len(m))
75 for k, v := range m {
go.temporal.io/server/service/history/api/activity_util.go 18 covered LOC · 8 ranges

Open complete file

16 token *tokenspb.Task,
17 workflowConsistencyChecker WorkflowConsistencyChecker,
18 > ) error { activity_util.go
19 > // TODO when the following APIs are deprecated
20 > // remove this function since run ID will always be set
21 > // * RecordActivityTaskHeartbeatById
22 > // * RespondActivityTaskCanceledById
23 > // * RespondActivityTaskFailedById
24 > // * RespondActivityTaskCompletedById
25 >
26 > if len(token.RunId) != 0 {
27 > return nil activity_util.go
28 > }
29
30 runID, err := workflowConsistencyChecker.GetCurrentWorkflowRunID(
60 ai *persistencespb.ActivityInfo,
61 isCompletedByID *bool,
62 > ) bool { activity_util.go
63 > if isCompletedByID == nil || !*isCompletedByID {
64 > if ai.StartedEventId == common.EmptyEventID { activity_util.go
65 return true
66 }
67 }
68 > if token.GetScheduledEventId() != common.EmptyEventID && token.Attempt != ai.Attempt { activity_util.go
69 return true
70 }
71 > if token.GetStartVersion() != common.EmptyVersion && ai.GetStartVersion() != common.EmptyVersion { activity_util.go
72 return token.GetStartVersion() != ai.GetStartVersion()
73 }
74 > if token.GetVersion() != common.EmptyVersion && token.GetVersion() != ai.GetVersion() { activity_util.go
75 // For backward compatibility. We should not check version here because ai.Version is last write version,
76 // but token.Version is generated when task is created. We should use start version instead.
77 return true
78 }
79 > return false activity_util.go
80 }
go.temporal.io/server/service/history/tasks/task_category_registry.go 18 covered LOC · 4 ranges

Open complete file

26 // each entry point that uses it. Essentially, get it from the dependency graph instead of calling this method, unless
27 // you're in a test.
28 > func NewDefaultTaskCategoryRegistry() *MutableTaskCategoryRegistry { task_category_registry.go
29 > return &MutableTaskCategoryRegistry{
30 > categories: map[int]Category{
31 > CategoryTransfer.ID(): CategoryTransfer,
32 > CategoryTimer.ID(): CategoryTimer,
33 > CategoryVisibility.ID(): CategoryVisibility,
34 > CategoryReplication.ID(): CategoryReplication,
35 > CategoryMemoryTimer.ID(): CategoryMemoryTimer,
36 > CategoryOutbound.ID(): CategoryOutbound,
37 > },
38 > }
39 > }
40
41 // AddCategory register a Category with the registry or panics if a Category with the same ID has already been
42 // registered.
43 > func (r *MutableTaskCategoryRegistry) AddCategory(c Category) { task_category_registry.go
44 > if category, ok := r.categories[c.id]; ok {
45 panic(fmt.Sprintf(
46 "category id: %v has already been defined as type %v and name %v",
61
62 // GetCategories returns a deep copy of all registered Category objects from the registry.
63 > func (r *MutableTaskCategoryRegistry) GetCategories() map[int]Category { task_category_registry.go
64 > return maps.Clone(r.categories)
65 > }
go.temporal.io/server/service/history/tasks/workflow_task.go 18 covered LOC · 6 ranges

Open complete file

23 )
24
25 > func (d *WorkflowTask) GetKey() Key { workflow_task.go
26 > return NewImmediateKey(d.TaskID)
27 > }
28
29 func (d *WorkflowTask) GetVersion() int64 {
39 }
40
41 > func (d *WorkflowTask) SetTaskID(id int64) { workflow_task.go
42 > d.TaskID = id
43 > }
44
45 > func (d *WorkflowTask) GetVisibilityTime() time.Time { workflow_task.go
46 > return d.VisibilityTimestamp
47 > }
48
49 > func (d *WorkflowTask) SetVisibilityTime(timestamp time.Time) { workflow_task.go
50 > d.VisibilityTimestamp = timestamp
51 > }
52
53 > func (d *WorkflowTask) GetCategory() Category { workflow_task.go
54 > return CategoryTransfer
55 > }
56
57 > func (d *WorkflowTask) GetType() enumsspb.TaskType { workflow_task.go
58 > return enumsspb.TASK_TYPE_TRANSFER_WORKFLOW_TASK
59 > }
60
61 func (d *WorkflowTask) String() string {
go.temporal.io/server/common/log/lazy_logger.go 17 covered LOC · 4 ranges

Open complete file

19 )
20
21 > func NewLazyLogger(logger Logger, tagFn func() []tag.Tag) *lazyLogger { lazy_logger.go
22 > return &lazyLogger{
23 > logger: logger,
24 > tagFn: tagFn,
25 > }
26 > }
27
28 > func (l *lazyLogger) Debug(msg string, tags ...tag.Tag) { lazy_logger.go
29 > l.once.Do(l.tagLogger)
30 > l.logger.Debug(msg, tags...)
31 > }
32
33 func (l *lazyLogger) Info(msg string, tags ...tag.Tag) {
61 }
62
63 > func (l *lazyLogger) With(tags ...tag.Tag) Logger { lazy_logger.go
64 > l.once.Do(l.tagLogger)
65 > return With(l.logger, tags...)
66 > }
67
68 > func (l *lazyLogger) tagLogger() { lazy_logger.go
69 > l.logger = With(l.logger, l.tagFn()...)
70 > }
go.temporal.io/server/common/persistence/serialization/codec.go 17 covered LOC · 7 ranges

Open complete file

26 // encodingTypeFromEnv returns an EncodingType based on the environment variable `TEMPORAL_TEST_DATA_ENCODING`.
27 // It defaults to "ENCODING_TYPE_PROTO3" codec if the environment variable is not set.
28 > func encodingTypeFromEnv() enumspb.EncodingType { codec.go
29 > codecType := os.Getenv(SerializerDataEncodingEnvVar)
30 > switch strings.ToLower(codecType) {
31 > case "", "proto3": codec.go
32 > return enumspb.ENCODING_TYPE_PROTO3
33 case "json":
34 return enumspb.ENCODING_TYPE_JSON
65 encoding enumspb.EncodingType,
66 options ...EncodeOption,
67 > ) (*commonpb.DataBlob, error) { codec.go
68 > opts := encodeOptions{}
69 > for _, option := range options {
70 option(&opts)
71 }
72
73 > if m == nil { codec.go
74 return &commonpb.DataBlob{
75 Data: nil,
78 }
79
80 > switch encoding { codec.go
81 case enumspb.ENCODING_TYPE_JSON:
82 blob, err := codec.NewJSONPBEncoder().Encode(m)
88 EncodingType: enumspb.ENCODING_TYPE_JSON,
89 }, nil
90 > case enumspb.ENCODING_TYPE_PROTO3: codec.go
91 > data, err := proto.MarshalOptions{Deterministic: opts.deterministic}.Marshal(m)
92 > if err != nil {
93 return nil, NewSerializationError(enumspb.ENCODING_TYPE_PROTO3, err)
94 }
95 > return &commonpb.DataBlob{ codec.go
96 > EncodingType: enumspb.ENCODING_TYPE_PROTO3,
97 > Data: data,
98 > }, nil
99 default:
100 return nil, NewUnknownEncodingTypeError(encoding.String(), enumspb.ENCODING_TYPE_JSON, enumspb.ENCODING_TYPE_PROTO3)
go.temporal.io/server/service/history/workflow/state_transition_history.go 17 covered LOC · 5 ranges

Open complete file

25 history []*persistencespb.VersionedTransition,
26 namespaceFailoverVersion int64,
27 > ) []*persistencespb.VersionedTransition { state_transition_history.go
28 > if len(history) == 0 {
29 > return []*persistencespb.VersionedTransition{ state_transition_history.go
30 > {
31 > NamespaceFailoverVersion: namespaceFailoverVersion,
32 > TransitionCount: 1,
33 > },
34 > }
35 > }
36
37 > lastTransitionCount := history[len(history)-1].TransitionCount state_transition_history.go
38 > if history[len(history)-1].NamespaceFailoverVersion == namespaceFailoverVersion {
39 > history = history[:len(history)-1] state_transition_history.go
40 > }
41 > return append(history, &persistencespb.VersionedTransition{ state_transition_history.go
42 > NamespaceFailoverVersion: namespaceFailoverVersion,
43 > TransitionCount: lastTransitionCount + 1,
44 > })
45 }
go.temporal.io/server/service/history/workflow/test_util.go 17 covered LOC · 5 ranges

Open complete file

24 runID string,
25 logger log.Logger,
26 > ) *MutableStateImpl { test_util.go
27 >
28 > ms := NewMutableState(shard, eventsCache, logger, ns, workflowID, runID, time.Now().UTC())
29 > ms.executionInfo.NamespaceId = string(ns.ID())
30 > ms.executionInfo.WorkflowId = workflowID
31 > ms.executionState.RunId = runID
32 > ms.GetExecutionInfo().ExecutionTime = ms.GetExecutionState().StartTime
33 > _ = ms.SetHistoryTree(nil, nil, runID)
34 >
35 > return ms
36 > }
37
38 // NewMapEventCache is a functional event cache mock that wraps a simple Go map
90 ctx context.Context,
91 mutableState historyi.MutableState,
92 > ) *persistencespb.WorkflowMutableState { test_util.go
93 > if mutableState.HasBufferedEvents() {
94 _, _, _ = mutableState.CloseTransactionAsMutation(ctx, historyi.TransactionPolicyActive)
95 > } else { test_util.go
96 > _, _, _ = mutableState.CloseTransactionAsSnapshot(ctx, historyi.TransactionPolicyActive) test_util.go
97 > }
98 > return mutableState.CloneToProto() test_util.go
99 }
go.temporal.io/server/common/definition/workflow_key.go 16 covered LOC · 4 ranges

Open complete file

19 workflowID string,
20 runID string,
21 > ) WorkflowKey { workflow_key.go
22 > return WorkflowKey{
23 > NamespaceID: namespaceID,
24 > WorkflowID: workflowID,
25 > RunID: runID,
26 > }
27 > }
28
29 > func (k *WorkflowKey) GetNamespaceID() string { workflow_key.go
30 > return k.NamespaceID
31 > }
32
33 > func (k *WorkflowKey) GetWorkflowID() string { workflow_key.go
34 > return k.WorkflowID
35 > }
36
37 > func (k *WorkflowKey) GetRunID() string { workflow_key.go
38 > return k.RunID
39 > }
40
41 func (k *WorkflowKey) String() string {
go.temporal.io/server/common/headers/version_checker.go 16 covered LOC · 3 ranges

Open complete file

76
77 // NewDefaultVersionChecker constructs a new VersionChecker using default versions from const.
78 > func NewDefaultVersionChecker() *versionChecker { version_checker.go
79 > return NewVersionChecker(SupportedClients, ServerVersion)
80 > }
81
82 // NewVersionChecker constructs a new VersionChecker
83 > func NewVersionChecker(supportedClients map[string]string, serverVersion string) *versionChecker { version_checker.go
84 > return &versionChecker{
85 > serverVersion: semver.MustParse(serverVersion),
86 > supportedClients: supportedClients,
87 > supportedClientsRange: mustParseRanges(supportedClients),
88 > }
89 > }
90
91 // GetClientNameAndVersion extracts SDK name and version from context headers
163 }
164
165 > func mustParseRanges(ranges map[string]string) map[string]semver.Range { version_checker.go
166 > out := make(map[string]semver.Range, len(ranges))
167 > for c, r := range ranges {
168 > out[c] = semver.MustParseRange(r)
169 > }
170 > return out
171 }
go.temporal.io/server/service/history/api/workflow_lease.go 16 covered LOC · 4 ranges

Open complete file

45 releaseFn historyi.ReleaseWorkflowContextFunc,
46 mutableState historyi.MutableState,
47 > ) WorkflowLease { workflow_lease.go
48 > return &workflowLease{
49 > context: wfContext,
50 > releaseFn: releaseFn,
51 > mutableState: mutableState,
52 > }
53 > }
54
55 > func (w *workflowLease) GetContext() historyi.WorkflowContext { workflow_lease.go
56 > return w.context
57 > }
58
59 > func (w *workflowLease) GetMutableState() historyi.MutableState { workflow_lease.go
60 > return w.mutableState
61 > }
62
63 > func (w *workflowLease) GetReleaseFn() historyi.ReleaseWorkflowContextFunc { workflow_lease.go
64 > return w.releaseFn
65 > }
go.temporal.io/server/service/history/tasks/key.go 16 covered LOC · 5 ranges

Open complete file

28 )
29
30 > func NewImmediateKey(taskID int64) Key { key.go
31 > return Key{
32 > FireTime: DefaultFireTime,
33 > TaskID: taskID,
34 > }
35 > }
36
37 > func NewKey(fireTime time.Time, taskID int64) Key { key.go
38 > return Key{
39 > FireTime: fireTime,
40 > TaskID: taskID,
41 > }
42 > }
43
44 func ValidateKey(key Key) error {
54 }
55
56 > func (left Key) CompareTo(right Key) int { key.go
57 > if left.FireTime.Before(right.FireTime) {
58 > return -1 key.go
59 > } else if left.FireTime.After(right.FireTime) { key.go
60 return 1
61 }
go.temporal.io/server/chasm/registry.go 15 covered LOC · 1 range

Open complete file

51 }
52
53 > func NewRegistry(logger log.Logger) *Registry { registry.go
54 > return &Registry{
55 > libraries: make(map[string]Library),
56 > rcByFqn: make(map[string]*RegistrableComponent),
57 > rcByID: make(map[uint32]*RegistrableComponent),
58 > rcByGoType: make(map[reflect.Type]*RegistrableComponent),
59 > rtByFqn: make(map[string]*RegistrableTask),
60 > rtByID: make(map[uint32]*RegistrableTask),
61 > rtByGoType: make(map[reflect.Type]*RegistrableTask),
62 > rcContextValues: make(map[any]valueWithFqn),
63 > nexusServices: make(map[string]*nexus.Service),
64 > NexusEndpointProcessor: NewNexusEndpointProcessor(),
65 > logger: logger,
66 > }
67 > }
68
69 func (r *Registry) Register(lib Library) error {
go.temporal.io/server/common/contextutil/metadata.go 15 covered LOC · 6 ranges

Open complete file

99
100 // ContextMetadataGetMarkedActivityIDs returns the marked activity IDs from the context.
101 > func ContextMetadataGetMarkedActivityIDs(ctx context.Context) []string { metadata.go
102 > metadataCtx := getMetadataContext(ctx)
103 > if metadataCtx == nil {
104 > return nil metadata.go
105 > }
106
107 metadataCtx.Lock()
119
120 // getMetadataContext extracts metadata context from golang context.
121 > func getMetadataContext(ctx context.Context) *metadataContext { metadata.go
122 > metadataCtx := ctx.Value(metadataCtxKey)
123 > if metadataCtx == nil {
124 > return nil metadata.go
125 > }
126 mc, ok := metadataCtx.(*metadataContext)
127 if !ok {
147
148 // ContextMetadataSet sets a metadata key-value pair in the context, overwriting any existing value.
149 > func ContextMetadataSet(ctx context.Context, key string, value any) bool { metadata.go
150 > metadataCtx := getMetadataContext(ctx)
151 > if metadataCtx == nil {
152 > return false metadata.go
153 > }
154
155 metadataCtx.Lock()
go.temporal.io/server/common/persistence/visibility/store/sql/query_converter_util_legacy.go 15 covered LOC · 3 ranges

Open complete file

68 }
69
70 > func newColName(name string) *colName { query_converter_util_legacy.go
71 > return &colName{Name: name}
72 > }
73
74 func newSAColName(
77 fieldName string,
78 valueType enumspb.IndexedValueType,
79 > ) *saColName { query_converter_util_legacy.go
80 > return &saColName{
81 > dbColName: newColName(dbColName),
82 > alias: alias,
83 > fieldName: fieldName,
84 > valueType: valueType,
85 > }
86 > }
87
88 func newFuncExpr(name string, exprs ...sqlparser.Expr) *sqlparser.FuncExpr {
105 }
106
107 > func getMaxDatetimeValue() time.Time { query_converter_util_legacy.go
108 > t, _ := time.Parse(time.RFC3339, "9999-12-31T23:59:59Z")
109 > return t
110 > }
111
112 // formatComparisonExprStringForError formats comparison expression after
go.temporal.io/server/common/primitives/timestamp/duration.go 15 covered LOC · 6 ranges

Open complete file

19 )
20
21 > func DurationValue(d *durationpb.Duration) time.Duration { duration.go
22 > if d == nil {
23 return 0
24 }
25 > return d.AsDuration() duration.go
26 }
27
28 > func DurationPtr(td time.Duration) *durationpb.Duration { duration.go
29 > return durationpb.New(td)
30 > }
31
32 func MinDurationPtr(d1 *durationpb.Duration, d2 *durationpb.Duration) *durationpb.Duration {
35 }
36
37 > func DurationFromSeconds(s int64) *durationpb.Duration { duration.go
38 > return durationMultipleOf(s, time.Second)
39 > }
40
41 func DurationFromMinutes(m int64) *durationpb.Duration {
47 }
48
49 > func DurationFromDays(d int32) *durationpb.Duration { duration.go
50 > return durationMultipleOf(int64(d), time.Hour*24)
51 > }
52
53 > func durationMultipleOf(amt int64, mult time.Duration) *durationpb.Duration { duration.go
54 > return DurationPtr(time.Duration(amt) * mult)
55 > }
56
57 // ValidateAndCapProtoDuration validates protobuf durations for two conditions:
go.temporal.io/server/service/history/shard/handover_tracker.go 15 covered LOC · 3 ranges

Open complete file

63
64 // NewDefaultHandoverTrackerFactory returns a factory that creates the default OSS HandoverTracker.
65 > func NewDefaultHandoverTrackerFactory() HandoverTrackerFactory { handover_tracker.go
66 > return func(params HandoverTrackerParams) HandoverTracker {
67 > return &defaultHandoverTracker{ handover_tracker.go
68 > handoverNamespaces: make(map[namespace.Name]*namespaceHandOverInfo),
69 > clusterMetadata: params.ClusterMetadata,
70 > getMaxReplicationTaskID: params.GetMaxReplicationTaskID,
71 > errorByStateFn: params.ErrorByStateFn,
72 > notifyReplicationFn: params.NotifyReplicationFn,
73 > logger: params.Logger,
74 > }
75 > }
76 }
77
113 }
114
115 > func (t *defaultHandoverTracker) IsInHandover(namespaceName namespace.Name, workflowID string) bool { handover_tracker.go
116 > _, ok := t.handoverNamespaces[namespaceName]
117 > return ok
118 > }
119
120 func (t *defaultHandoverTracker) GetHandoverNamespaces() map[string]*historyservice.HandoverNamespaceInfo {
go.temporal.io/server/service/history/workflow/external_payload_size.go 15 covered LOC · 7 ranges

Open complete file

11
12 // CalculateExternalPayloadSize calculates the total size and count of all external payloads in the given history events.
13 > func CalculateExternalPayloadSize(events []*historypb.HistoryEvent, metricsHandler metrics.Handler) (size int64, count int64, err error) { external_payload_size.go
14 > var totalSize int64
15 > var totalCount int64
16 > visitor := func(vpc *proxy.VisitPayloadsContext, payloads []*commonpb.Payload) ([]*commonpb.Payload, error) {
17 > for _, p := range payloads { external_payload_size.go
18 > totalCount += int64(len(p.ExternalPayloads)) external_payload_size.go
19 > for _, extPayload := range p.ExternalPayloads {
20 totalSize += extPayload.SizeBytes
21 metricsHandler.Histogram(metrics.ExternalPayloadUploadSize.Name(), metrics.Bytes).Record(int64(extPayload.SizeBytes))
22 }
23 }
24 > return payloads, nil external_payload_size.go
25 }
26
27 > for _, event := range events { external_payload_size.go
28 > err := proxy.VisitPayloads(context.Background(), event, proxy.VisitPayloadsOptions{ external_payload_size.go
29 > Visitor: visitor,
30 > SkipSearchAttributes: true,
31 > })
32 > if err != nil {
33 return 0, 0, err
34 }
35 }
36 > return totalSize, totalCount, nil external_payload_size.go
37 }
go.temporal.io/server/common/build/build.go 14 covered LOC · 2 ranges

Open complete file

27 )
28
29 > func init() { build.go
30 > buildInfo, ok := debug.ReadBuildInfo()
31 > if !ok {
32 return
33 }
34
35 > InfoData.Available = true build.go
36 > InfoData.GoVersion = buildInfo.GoVersion
37 >
38 > for _, setting := range buildInfo.Settings {
39 > switch setting.Key {
40 > case "GOARCH":
41 > InfoData.GoArch = setting.Value
42 > case "GOOS":
43 > InfoData.GoOs = setting.Value
44 > case "CGO_ENABLED":
45 > InfoData.CgoEnabled = setting.Value == "1"
46 case "vcs.revision":
47 InfoData.GitRevision = setting.Value
go.temporal.io/server/common/dynamicconfig/gradual_change.go 14 covered LOC · 3 ranges

Open complete file

25 // StaticGradualChange returns a GradualChange whose Value always returns def and whose When
26 // always returns a time in the past.
27 > func StaticGradualChange[T any](def T) GradualChange[T] { gradual_change.go
28 > return GradualChange[T]{New: def}
29 > }
30
31 // Value returns the value for the given key at the given time.
56 // of type GradualChange into a GradualChange.
57 // nolint:revive // cognitive-complexity // this looks complicated but each case is fairly simple
58 > func ConvertGradualChange[T any](def T) func(v any) (GradualChange[T], error) { gradual_change.go
59 > changeConverter := ConvertStructure(StaticGradualChange(def))
60 >
61 > // Call this once so that if it's going to panic, it panics at static init time.
62 > _, _ = changeConverter(nil)
63 >
64 > switch reflect.TypeFor[T]() {
65 > case reflect.TypeFor[bool]():
66 > return func(v any) (GradualChange[T], error) {
67 if b, err := convertBool(v); err == nil {
68 var change GradualChange[T]
72 return changeConverter(v)
73 }
74 > case reflect.TypeFor[int](): gradual_change.go
75 > return func(v any) (GradualChange[T], error) {
76 if i, err := convertInt(v); err == nil {
77 var change GradualChange[T]
go.temporal.io/server/service/history/workflow/util.go 14 covered LOC · 6 ranges

Open complete file

130 verifyChecksum func(string) error,
131 autoResetPoints *workflowpb.ResetPoints,
132 > ) (string, *workflowpb.ResetPointInfo) { util.go
133 > if autoResetPoints == nil {
134 return "", nil
135 }
136 > now := timeSource.Now() util.go
137 > for _, p := range autoResetPoints.Points {
138 > if err := verifyChecksum(p.GetBinaryChecksum()); err != nil && p.GetResettable() { util.go
139 expireTime := timestamp.TimeValue(p.GetExpireTime())
140 if !expireTime.IsZero() && now.After(expireTime) {
145 }
146 }
147 > return "", nil util.go
148 }
149
178 //
179 //nolint:revive // cognitive complexity to reduce after old code clean up
180 > func GetEffectiveDeployment(versioningInfo *workflowpb.WorkflowExecutionVersioningInfo) *deploymentpb.Deployment { util.go
181 > if versioningInfo == nil {
182 > return nil
183 > } else if transition := versioningInfo.GetVersionTransition(); transition != nil {
184 if v := transition.GetDeploymentVersion(); v != nil { // v0.32
185 return worker_versioning.DeploymentFromExternalDeploymentVersion(v)
214 // 3. Behavior: this is returned when there is no override (most common case). Behavior is
215 // set based on the worker-sent deployment in the latest WFT completion.
216 > func GetEffectiveVersioningBehavior(versioningInfo *workflowpb.WorkflowExecutionVersioningInfo) enumspb.VersioningBehavior { util.go
217 > if versioningInfo == nil {
218 > return enumspb.VERSIONING_BEHAVIOR_UNSPECIFIED
219 > } else if t := versioningInfo.GetVersionTransition(); t != nil {
220 return enumspb.VERSIONING_BEHAVIOR_AUTO_UPGRADE
221 } else if override := versioningInfo.GetVersioningOverride(); override != nil {
go.temporal.io/server/common/metrics/defs_base.go 13 covered LOC · 2 ranges

Open complete file

10 }
11
12 > func newMetricDefinition(name string, opts ...Option) metricDefinition { defs_base.go
13 > d := metricDefinition{
14 > name: name,
15 > description: "",
16 > unit: "",
17 > }
18 > for _, opt := range opts {
19 > opt.apply(&d)
20 > }
21 > return d
22 }
23
24 > func (md metricDefinition) Name() string { defs_base.go
25 > return md.name
26 > }
27
28 func (md metricDefinition) Unit() MetricUnit {
go.temporal.io/server/service/history/workflow/query_registry.go 13 covered LOC · 2 ranges

Open complete file

25 )
26
27 > func NewQueryRegistry() historyi.QueryRegistry { query_registry.go
28 > return &queryRegistryImpl{
29 > buffered: make(map[string]query),
30 > completed: make(map[string]query),
31 > unblocked: make(map[string]query),
32 > failed: make(map[string]query),
33 > }
34 > }
35
36 > func (r *queryRegistryImpl) HasBufferedQuery() bool { query_registry.go
37 > r.RLock()
38 > defer r.RUnlock()
39 > return len(r.buffered) > 0
40 > }
41
42 func (r *queryRegistryImpl) GetBufferedIDs() []string {
go.temporal.io/server/common/metrics/noop_impl.go 12 covered LOC · 6 ranges

Open complete file

15 )
16
17 > func newNoopMetricsHandler() *noopMetricsHandler { return &noopMetricsHandler{} } noop_impl.go
18
19 // WithTags creates a new MetricProvder with provided []Tag
20 // Tags are merged with registered Tags from the source MetricsHandler
21 > func (n *noopMetricsHandler) WithTags(...Tag) Handler { noop_impl.go
22 > return n
23 > }
24
25 // Counter obtains a counter for the given name.
29
30 // Gauge obtains a gauge for the given name.
31 > func (*noopMetricsHandler) Gauge(string) GaugeIface { noop_impl.go
32 > return NoopGaugeMetricFunc
33 > }
34
35 // Timer obtains a timer for the given name.
36 > func (*noopMetricsHandler) Timer(string) TimerIface { noop_impl.go
37 > return NoopTimerMetricFunc
38 > }
39
40 // Histogram obtains a histogram for the given name.
54
55 var NoopCounterMetricFunc = CounterFunc(func(i int64, t ...Tag) {})
56 > var NoopGaugeMetricFunc = GaugeFunc(func(f float64, t ...Tag) {}) noop_impl.go
57 > var NoopTimerMetricFunc = TimerFunc(func(d time.Duration, t ...Tag) {}) noop_impl.go
58 var NoopHistogramMetricFunc = HistogramFunc(func(i int64, t ...Tag) {})
go.temporal.io/server/common/persistence/visibility/store/elasticsearch/visibility_store.go 12 covered LOC · 3 ranges

Open complete file

101 }
102
103 > defaultSorter = func() []elastic.Sorter { visibility_store.go
104 > ret := make([]elastic.Sorter, 0, len(defaultSorterFields))
105 > for _, item := range defaultSorterFields {
106 > fs := elastic.NewFieldSort(item.name)
107 > if item.desc {
108 > fs.Desc()
109 > }
110 > if item.missing_first {
111 > fs.Missing("_first")
112 > } else {
113 fs.Missing("_last")
114 }
115 > ret = append(ret, fs) visibility_store.go
116 }
117 > return ret visibility_store.go
118 }()
119
go.temporal.io/server/service/history/api/namespace.go 12 covered LOC · 7 ranges

Open complete file

12 namespaceUUID namespace.ID,
13 businessID string,
14 > ) (*namespace.Namespace, error) { namespace.go
15 >
16 > err := ValidateNamespaceUUID(namespaceUUID)
17 > if err != nil {
18 return nil, err
19 }
20
21 > namespaceEntry, err := shard.GetNamespaceRegistry().GetNamespaceByID(namespaceUUID) namespace.go
22 > if err != nil {
23 return nil, err
24 }
25 > if namespaceEntry.ActiveClusterName(namespace.RoutingKey{ID: businessID}) != shard.GetClusterMetadata().GetCurrentClusterName() { namespace.go
26 return nil, serviceerror.NewNamespaceNotActive(
27 namespaceEntry.Name().String(),
29 namespaceEntry.ActiveClusterName(namespace.RoutingKey{ID: businessID}))
30 }
31 > return namespaceEntry, nil namespace.go
32 }
33
52 func ValidateNamespaceUUID(
53 namespaceUUID namespace.ID,
54 > ) error { namespace.go
55 > if namespaceUUID == "" {
56 return serviceerror.NewInvalidArgument("Missing namespace UUID.")
57 > } else if uuid.Validate(namespaceUUID.String()) != nil { namespace.go
58 return serviceerror.NewInvalidArgument("Invalid namespace UUID.")
59 }
60 > return nil namespace.go
61 }
go.temporal.io/server/service/history/tasks/workflow_task_timer.go 12 covered LOC · 5 ranges

Open complete file

40 )
41
42 > func (d *WorkflowTaskTimeoutTask) GetKey() Key { workflow_task_timer.go
43 > return NewKey(d.VisibilityTimestamp, d.TaskID)
44 > }
45
46 func (d *WorkflowTaskTimeoutTask) GetVersion() int64 {
60 }
61
62 > func (d *WorkflowTaskTimeoutTask) GetVisibilityTime() time.Time { workflow_task_timer.go
63 > return d.VisibilityTimestamp
64 > }
65
66 > func (d *WorkflowTaskTimeoutTask) SetVisibilityTime(t time.Time) { workflow_task_timer.go
67 > d.VisibilityTimestamp = t
68 > }
69
70 > func (d *WorkflowTaskTimeoutTask) GetCategory() Category { workflow_task_timer.go
71 > if d.InMemory {
72 return CategoryMemoryTimer
73 }
74 > return CategoryTimer workflow_task_timer.go
75 }
76
go.temporal.io/server/service/history/workflow/noop_chasm_tree.go 12 covered LOC · 4 ranges

Open complete file

18 type noopChasmTree struct{}
19
20 > func (*noopChasmTree) CloseTransaction() (chasm.NodesMutation, error) { noop_chasm_tree.go
21 > return chasm.NodesMutation{}, nil
22 > }
23
24 > func (*noopChasmTree) Snapshot(*persistencespb.VersionedTransition) chasm.NodesSnapshot { noop_chasm_tree.go
25 > return chasm.NodesSnapshot{}
26 > }
27
28 func (*noopChasmTree) PartitionedSnapshot(*persistencespb.VersionedTransition) (chasm.NodesSnapshot, *persistencespb.ChasmLocalState) {
50 }
51
52 > func (*noopChasmTree) IsDirty() bool { noop_chasm_tree.go
53 > return false
54 > }
55
56 func (*noopChasmTree) Terminate(chasm.TerminateComponentRequest) error {
62 }
63
64 > func (*noopChasmTree) ArchetypeID() chasm.ArchetypeID { noop_chasm_tree.go
65 > return chasm.WorkflowArchetypeID
66 > }
67
68 func (*noopChasmTree) EachPureTask(
go.temporal.io/server/common/collection/indexedtakelist.go 11 covered LOC · 4 ranges

Open complete file

21 values []V,
22 indexer func(V) K,
23 > ) *IndexedTakeList[K, V] { indexedtakelist.go
24 > ret := &IndexedTakeList[K, V]{
25 > values: make([]kv[K, V], 0, len(values)),
26 > }
27 > for _, v := range values {
28 ret.values = append(ret.values, kv[K, V]{key: indexer(v), value: v})
29 }
30 > return ret indexedtakelist.go
31 }
32
50
51 // TakeRemaining removes all remaining values from this set and returns them.
52 > func (itl *IndexedTakeList[K, V]) TakeRemaining() []V { indexedtakelist.go
53 > out := make([]V, 0, len(itl.values))
54 > for i := 0; i < len(itl.values); i++ {
55 kv := &itl.values[i]
56 if !kv.removed {
go.temporal.io/server/common/headers/headers.go 11 covered LOC · 4 ranges

Open complete file

45 // GetValues returns header values for passed header names.
46 // It always returns slice of the same size as number of passed header names.
47 > func GetValues(ctx context.Context, headerNames ...string) []string { headers.go
48 > headerValues := make([]string, len(headerNames))
49 >
50 > for i, headerName := range headerNames {
51 > if values := metadata.ValueFromIncomingContext(ctx, headerName); len(values) > 0 {
52 headerValues[i] = values[0]
53 }
54 }
55
56 > return headerValues headers.go
57 }
58
144
145 // GetPrincipal retrieves the principal from the context headers. Returns nil if principal is not set.
146 > func GetPrincipal(ctx context.Context) *commonpb.Principal { headers.go
147 > values := GetValues(ctx, PrincipalTypeHeaderName, PrincipalNameHeaderName)
148 > if values[0] == "" && values[1] == "" {
149 > return nil headers.go
150 > }
151 return &commonpb.Principal{Type: values[0], Name: values[1]}
152 }
go.temporal.io/server/common/metrics/grpc.go 11 covered LOC · 4 ranges

Open complete file

123
124 // getMetricsContext extracts metrics context from golang context.
125 > func getMetricsContext(ctx context.Context) *metricsContext { grpc.go
126 > metricsCtx := ctx.Value(metricsCtxKey)
127 > if metricsCtx == nil {
128 > return nil grpc.go
129 > }
130
131 return metricsCtx.(*metricsContext)
138
139 // ContextCounterAdd adds value to counter within metrics context.
140 > func ContextCounterAdd(ctx context.Context, name string, value int64) bool { grpc.go
141 > metricsCtx := getMetricsContext(ctx)
142 >
143 > if metricsCtx == nil {
144 > return false grpc.go
145 > }
146
147 metricsCtx.Lock()
go.temporal.io/server/service/history/tests/vars.go 11 covered LOC · 1 range

Open complete file

158 )
159
160 > func NewDynamicConfig() *configs.Config { vars.go
161 > dc := dynamicconfig.NewNoopCollection()
162 > config := configs.NewConfig(dc, 1)
163 > config.EnableActivityEagerExecution = dynamicconfig.GetBoolPropertyFnFilteredByNamespace(true)
164 > config.NamespaceCacheRefreshInterval = dynamicconfig.GetDurationPropertyFn(time.Second)
165 > config.ReplicationEnableUpdateWithNewTaskMerge = dynamicconfig.GetBoolPropertyFn(true)
166 > config.EnableWorkflowIdReuseStartTimeValidation = dynamicconfig.GetBoolPropertyFnFilteredByNamespace(true)
167 > config.EnableTransitionHistory = dynamicconfig.GetBoolPropertyFnFilteredByNamespace(true)
168 > config.EnableChasm = dynamicconfig.GetBoolPropertyFnFilteredByNamespace(false)
169 > return config
170 > }
go.temporal.io/server/common/persistence/sql/sqlplugin/postgresql/plugin.go 10 covered LOC · 1 range

Open complete file

36 var _ sqlplugin.Plugin = (*plugin)(nil)
37
38 > func init() { plugin.go
39 > sql.RegisterPlugin(PluginName, &plugin{
40 > driver: &driver.PQDriver{},
41 > queryConverter: &queryConverter{},
42 > })
43 > sql.RegisterPlugin(PluginNamePGX, &plugin{
44 > driver: &driver.PGXDriver{},
45 > queryConverter: &queryConverter{},
46 > })
47 > }
48
49 func (p *plugin) GetVisibilityQueryConverter() sqlplugin.VisibilityQueryConverter {
go.temporal.io/server/common/persistence/sql/sqlplugin/postgresql/visibility.go 10 covered LOC · 1 range

Open complete file

40 )
41
42 > func buildOnDuplicateKeyUpdate(fields ...string) string { visibility.go
43 > items := make([]string, len(fields))
44 > for i, field := range fields {
45 > items[i] = fmt.Sprintf("%s = excluded.%s", field, field)
46 > }
47 > return fmt.Sprintf(
48 > // The WHERE clause ensures that no update occurs if the version is behind the saved version.
49 > "ON CONFLICT (namespace_id, run_id) DO UPDATE SET %s WHERE executions_visibility.%s < EXCLUDED.%s",
50 > strings.Join(items, ", "), sqlplugin.VersionColumnName, sqlplugin.VersionColumnName,
51 > )
52 }
53
go.temporal.io/server/common/persistence/sql/sqlplugin/sqlite/visibility.go 10 covered LOC · 1 range

Open complete file

42 )
43
44 > func buildOnDuplicateKeyUpdate(fields ...string) string { visibility.go
45 > items := make([]string, len(fields))
46 > for i, field := range fields {
47 > items[i] = fmt.Sprintf("%s = excluded.%s", field, field)
48 > }
49 > return fmt.Sprintf(
50 > // The WHERE clause ensures that no update occurs if the version is behind the saved version.
51 > "ON CONFLICT (namespace_id, run_id) DO UPDATE SET %s WHERE executions_visibility.%s < EXCLUDED.%s",
52 > strings.Join(items, ", "), sqlplugin.VersionColumnName, sqlplugin.VersionColumnName,
53 > )
54 }
55
go.temporal.io/server/common/persistence/sql/sqlplugin/visibility.go 10 covered LOC · 2 ranges

Open complete file

219 }
220
221 > func getDbFields() []string { visibility.go
222 > t := reflect.TypeFor[VisibilityRow]()
223 > dbFields := make([]string, t.NumField())
224 > for i := 0; i < t.NumField(); i++ {
225 > f := t.Field(i)
226 > dbFields[i] = f.Tag.Get("db")
227 > if dbFields[i] == "" {
228 > dbFields[i] = strcase.ToSnake(f.Name)
229 > }
230 }
231 > return dbFields visibility.go
232 }
233
go.temporal.io/server/common/persistence/visibility/store/query/util.go 10 covered LOC · 2 ranges

Open complete file

70 }
71
72 > func NewUnsafeSQLString(val string) *UnsafeSQLString { util.go
73 > return &UnsafeSQLString{Val: val}
74 > }
75
76 func NewColName(name string) *ColumnName {
78 }
79
80 > func NewSAColumn(alias string, fieldName string, valueType enumspb.IndexedValueType) *SAColumn { util.go
81 > return &SAColumn{
82 > Alias: alias,
83 > FieldName: fieldName,
84 > ValueType: valueType,
85 > }
86 > }
87
88 func NamespaceDivisionSAColumn() *SAColumn {
go.temporal.io/server/common/searchattribute/search_attribute_mock.go 10 covered LOC · 2 ranges

Open complete file

31
32 // NewMockProvider creates a new mock instance.
33 > func NewMockProvider(ctrl *gomock.Controller) *MockProvider { search_attribute_mock.go
34 > mock := &MockProvider{ctrl: ctrl}
35 > mock.recorder = &MockProviderMockRecorder{mock}
36 > return mock
37 > }
38
39 // EXPECT returns an object that allows the caller to indicate expected use.
70
71 // NewMockManager creates a new mock instance.
72 > func NewMockManager(ctrl *gomock.Controller) *MockManager { search_attribute_mock.go
73 > mock := &MockManager{ctrl: ctrl}
74 > mock.recorder = &MockManagerMockRecorder{mock}
75 > return mock
76 > }
77
78 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/api/persistence/v1/executions.go-helpers.pb.go 9 covered LOC · 3 ranges

Open complete file

54
55 // Size returns the size of the object, in bytes, once serialized
56 > func (val *WorkflowExecutionInfo) Size() int { executions.go-helpers.pb.go
57 > return proto.Size(val)
58 > }
59
60 // Equal returns whether two WorkflowExecutionInfo values are equivalent by recursively
239
240 // Size returns the size of the object, in bytes, once serialized
241 > func (val *WorkflowExecutionState) Size() int { executions.go-helpers.pb.go
242 > return proto.Size(val)
243 > }
244
245 // Equal returns whether two WorkflowExecutionState values are equivalent by recursively
646
647 // Size returns the size of the object, in bytes, once serialized
648 > func (val *ActivityInfo) Size() int { executions.go-helpers.pb.go
649 > return proto.Size(val)
650 > }
651
652 // Equal returns whether two ActivityInfo values are equivalent by recursively
go.temporal.io/server/common/archiver/archival_metadata.go 9 covered LOC · 1 range

Open complete file

127
128 // NewDisabledArchvialConfig returns an ArchivalConfig where archival is disabled for both the cluster and the namespace
129 > func NewDisabledArchvialConfig() ArchivalConfig { archival_metadata.go
130 > return &archivalConfig{
131 > staticClusterState: ArchivalDisabled,
132 > dynamicClusterState: nil,
133 > enableRead: nil,
134 > namespaceDefaultState: enumspb.ARCHIVAL_STATE_DISABLED,
135 > namespaceDefaultURI: "",
136 > }
137 > }
138
139 // NewEnabledArchivalConfig returns an ArchivalConfig where archival is enabled for both the cluster and the namespace
go.temporal.io/server/common/convert/convert.go 9 covered LOC · 4 ranges

Open complete file

60 func StringSetToSlice(
61 inputs map[string]struct{},
62 > ) []string { convert.go
63 > outputs := make([]string, len(inputs))
64 > i := 0
65 > for item := range inputs {
66 outputs[i] = item
67 i++
68 }
69 > return outputs convert.go
70 }
71 func StringSliceToSet(
72 inputs []string,
73 > ) map[string]struct{} { convert.go
74 > outputs := make(map[string]struct{}, len(inputs))
75 > for _, item := range inputs {
76 outputs[item] = struct{}{}
77 }
78 > return outputs convert.go
79 }
go.temporal.io/server/common/dynamicconfig/static_client.go 9 covered LOC · 4 ranges

Open complete file

10 )
11
12 > func (s StaticClient) GetValue(key Key) []ConstrainedValue { static_client.go
13 > if v, ok := s[key]; ok {
14 if cvs, ok := v.([]ConstrainedValue); ok {
15 return cvs
17 return []ConstrainedValue{{Value: v}}
18 }
19 > return nil static_client.go
20 }
21
22 // NewNoopClient returns a Client that has no keys (a Collection using it will always return
23 // default values).
24 > func NewNoopClient() Client { static_client.go
25 > return StaticClient(nil)
26 > }
27
28 // NewNoopCollection creates a new noop collection.
29 > func NewNoopCollection() *Collection { static_client.go
30 > return NewCollection(NewNoopClient(), log.NewNoopLogger())
31 > }
go.temporal.io/server/common/persistence/sql/sqlplugin/util.go 9 covered LOC · 2 ranges

Open complete file

5 )
6
7 > func appendPrefix(prefix string, fields []string) []string { util.go
8 > out := make([]string, len(fields))
9 > for i, field := range fields {
10 > out[i] = prefix + field
11 > }
12 > return out
13 }
14
15 > func BuildNamedPlaceholder(fields ...string) string { util.go
16 > return strings.Join(appendPrefix(":", fields), ", ")
17 > }
go.temporal.io/server/common/testing/testhooks/test_impl.go 9 covered LOC · 2 ranges

Open complete file

89 var keyCounter atomic.Int64
90
91 > func newKey[T any, S any]() Key[T, S] { test_impl.go
92 > var zero S
93 > var s ScopeType
94 > switch any(zero).(type) {
95 > case namespace.ID, namespace.Name:
96 > s = ScopeNamespace
97 > case global:
98 > s = ScopeGlobal
99 default:
100 panic("testhooks: unknown scope type")
101 }
102 > return Key[T, S]{id: keyCounter.Add(1), scopeType: s} test_impl.go
103 }
go.temporal.io/server/service/history/api/respondworkflowtaskcompleted/workflow_size_checker.go 9 covered LOC · 1 range

Open complete file

42 metricsHandler metrics.Handler,
43 logger log.Logger,
44 > ) *workflowSizeChecker { workflow_size_checker.go
45 > return &workflowSizeChecker{
46 > workflowSizeLimits: limits,
47 > mutableState: mutableState,
48 > searchAttributesValidator: searchAttributesValidator,
49 > metricsHandler: metricsHandler,
50 > logger: logger,
51 > }
52 > }
53
54 func (c *workflowSizeChecker) checkIfPayloadSizeExceedsLimit(
go.temporal.io/server/service/history/tasks/activity_task_timer.go 9 covered LOC · 3 ranges

Open complete file

36 }
37
38 > func (a *ActivityTimeoutTask) GetVisibilityTime() time.Time { activity_task_timer.go
39 > return a.VisibilityTimestamp
40 > }
41
42 > func (a *ActivityTimeoutTask) SetVisibilityTime(t time.Time) { activity_task_timer.go
43 > a.VisibilityTimestamp = t
44 > }
45
46 > func (a *ActivityTimeoutTask) GetCategory() Category { activity_task_timer.go
47 > return CategoryTimer
48 > }
49
50 func (a *ActivityTimeoutTask) GetType() enumsspb.TaskType {
go.temporal.io/server/service/history/tasks/category.go 9 covered LOC · 3 ranges

Open complete file

96 }
97
98 > func (c Category) ID() int { category.go
99 > return c.id
100 > }
101
102 > func (c Category) Name() string { category.go
103 > return c.name
104 > }
105
106 > func (c Category) Type() CategoryType { category.go
107 > return c.cType
108 > }
109
110 func (c Category) MarshalText() (text []byte, err error) {
go.temporal.io/server/service/history/tasks/workflow_run_timer.go 9 covered LOC · 3 ranges

Open complete file

40 }
41
42 > func (u *WorkflowRunTimeoutTask) GetVisibilityTime() time.Time { workflow_run_timer.go
43 > return u.VisibilityTimestamp
44 > }
45
46 > func (u *WorkflowRunTimeoutTask) SetVisibilityTime(t time.Time) { workflow_run_timer.go
47 > u.VisibilityTimestamp = t
48 > }
49
50 > func (u *WorkflowRunTimeoutTask) GetCategory() Category { workflow_run_timer.go
51 > return CategoryTimer
52 > }
53
54 func (u *WorkflowRunTimeoutTask) GetType() enumsspb.TaskType {
go.temporal.io/server/service/history/workflow/mutable_state_state_status.go 9 covered LOC · 4 ranges

Open complete file

18 state enumsspb.WorkflowExecutionState,
19 status enumspb.WorkflowExecutionStatus,
21 > switch e.GetState() {
22 case enumsspb.WORKFLOW_EXECUTION_STATE_VOID:
23 // no validation
24 > case enumsspb.WORKFLOW_EXECUTION_STATE_CREATED: mutable_state_state_status.go
25 > switch state {
26 case enumsspb.WORKFLOW_EXECUTION_STATE_CREATED:
27 if status != enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING {
29 }
30
31 > case enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING: mutable_state_state_status.go
32 > if status != enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING && status != enumspb.WORKFLOW_EXECUTION_STATUS_PAUSED {
33 return invalidStateTransitionErr(e.GetState(), state, status)
34 }
go.temporal.io/server/service/history/workflow/state_machine_definition.go 9 covered LOC · 3 ranges

Open complete file

25
26 // Serialize is a noop as Deserialize is not supported.
27 > func (stateMachineDefinition) Serialize(any) ([]byte, error) { state_machine_definition.go
28 > return nil, nil
29 > }
30
31 > func (stateMachineDefinition) Type() string { state_machine_definition.go
32 > return StateMachineType
33 > }
34
35 > func RegisterStateMachine(reg *hsm.Registry) error { state_machine_definition.go
36 > return reg.RegisterMachine(stateMachineDefinition{})
37 > }
go.temporal.io/server/service/history/workflow/state_machine_timers.go 9 covered LOC · 3 ranges

Open complete file

16 // AddNextStateMachineTimerTask generates a state machine timer task if the first deadline doesn't have a task scheduled
17 // yet.
18 > func AddNextStateMachineTimerTask(ms historyi.MutableState) { state_machine_timers.go
19 > // filter out empty timer groups
20 > timers := ms.GetExecutionInfo().StateMachineTimers
21 > timers = slices.DeleteFunc(timers, func(timerGroup *persistencespb.StateMachineTimerGroup) bool {
22 return len(timerGroup.Infos) == 0
23 })
24 > ms.GetExecutionInfo().StateMachineTimers = timers state_machine_timers.go
25 >
26 > if len(timers) == 0 {
28 > }
29
30 timerGroup := timers[0]
go.temporal.io/server/common/archiver/metadata_mock.go 8 covered LOC · 1 range

Open complete file

20 // NewMetadataMock returns a new MetadataMock which uses the provided controller to create a MockArchivalMetadata
21 // instance.
22 > func NewMetadataMock(controller *gomock.Controller) MetadataMock { metadata_mock.go
23 > m := &metadataMock{
24 > MockArchivalMetadata: NewMockArchivalMetadata(controller),
25 > defaultHistoryConfig: NewDisabledArchvialConfig(),
26 > defaultVisibilityConfig: NewDisabledArchvialConfig(),
27 > }
28 > return m
29 > }
30
31 // MetadataMockRecorder is a wrapper around a ArchivalMetadata mock recorder.
go.temporal.io/server/common/headers/caller_info.go 8 covered LOC · 1 range

Open complete file

156 func GetCallerInfo(
157 ctx context.Context,
158 > ) CallerInfo { caller_info.go
159 > values := GetValues(ctx, CallerNameHeaderName, CallerTypeHeaderName, CallOriginHeaderName)
160 > return CallerInfo{
161 > CallerName: values[0],
162 > CallerType: values[1],
163 > CallOrigin: values[2],
164 > }
165 > }
go.temporal.io/server/common/namespace/mutate.go 8 covered LOC · 2 ranges

Open complete file

8 type mutationFunc func(*Namespace)
9
10 > func (f mutationFunc) apply(ns *Namespace) { mutate.go
11 > f(ns)
12 > }
13
14 // WithActiveCluster assigns the active cluster to a Namespace during a Clone
43
44 // WithGlobalFlag sets whether or not this Namespace is global.
45 > func WithGlobalFlag(b bool) Mutation { mutate.go
46 > return mutationFunc(
47 > func(ns *Namespace) {
48 > ns.replicationResolver.SetGlobalFlag(b)
49 > })
50 }
51
go.temporal.io/server/common/persistence/sql/sqlplugin/mysql/visibility.go 8 covered LOC · 1 range

Open complete file

73 )
74
75 > func buildOnDuplicateKeyUpdate(fields ...string) string { visibility.go
76 > items := make([]string, len(fields))
77 > for i, field := range fields {
78 > // This line is to ensure that no update occurs (for any column) if the version is behind the saved version.
79 > items[i] = fmt.Sprintf("%v = IF(%v < VALUES(%v), VALUES(%v), %v)",
80 > field, sqlplugin.VersionColumnName, sqlplugin.VersionColumnName, field, field)
81 > }
82 > return fmt.Sprintf("ON DUPLICATE KEY UPDATE %s", strings.Join(items, ", "))
83 }
84
go.temporal.io/server/common/tasks/priority.go 8 covered LOC · 2 ranges

Open complete file

59 )
60
61 > func (p Priority) String() string { priority.go
62 > s, ok := PriorityName[p]
63 > if ok {
64 > return s
65 > }
66 return strconv.Itoa(int(p))
67 }
77 func getPriority(
78 class, subClass Priority,
79 > ) Priority { priority.go
80 > return class | subClass
81 > }
go.temporal.io/server/common/tasktoken/serializer.go 8 covered LOC · 2 ranges

Open complete file

9
10 // NewSerializer creates a new instance of Serializer
11 > func NewSerializer() *Serializer { serializer.go
12 > return &Serializer{}
13 > }
14
15 func (s *Serializer) Serialize(taskToken *tokenspb.Task) ([]byte, error) {
20 }
21
22 > func (s *Serializer) Deserialize(data []byte) (*tokenspb.Task, error) { serializer.go
23 > taskToken := &tokenspb.Task{}
24 > err := taskToken.Unmarshal(data)
25 > return taskToken, err
26 > }
27
28 func (s *Serializer) SerializeQueryTaskToken(taskToken *tokenspb.QueryTask) ([]byte, error) {
go.temporal.io/server/chasm/statemachine.go 7 covered LOC · 1 range

Open complete file

34 // The apply function is called after verifying the transition is possible but before setting the destination state,
35 // so it can inspect the current (source) state.
36 > func NewTransition[S comparable, SM StateMachine[S], E any](src []S, dst S, apply func(SM, MutableContext, E) error) Transition[S, SM, E] { statemachine.go
37 > return Transition[S, SM, E]{
38 > Sources: src,
39 > Destination: dst,
40 > apply: apply,
41 > }
42 > }
43
44 // Possible returns a boolean indicating whether the transition is possible for the current state.
go.temporal.io/server/common/dynamicconfig/registry.go 7 covered LOC · 3 ranges

Open complete file

17 )
18
19 > func register(s GenericSetting) { registry.go
20 > if globalRegistry.queried.Load() {
21 panic("dynamicconfig.New*Setting must only be called from static initializers")
22 }
23 > if globalRegistry.settings == nil { registry.go
24 > globalRegistry.settings = make(map[Key]GenericSetting)
25 > }
26 > if globalRegistry.settings[s.Key()] != nil {
27 // nolint:forbidigo // only called during static initialization
28 panic(fmt.Sprintf("duplicate registration of dynamic config key: %q", s.Key().String()))
29 }
30 > globalRegistry.settings[s.Key()] = s registry.go
31 }
32
go.temporal.io/server/common/membership/grpc_resolver.go 7 covered LOC · 2 ranges

Open complete file

53 )
54
55 > func init() { grpc_resolver.go
56 > // This must be called in init to avoid race conditions.
57 > resolver.Register(&globalGrpcBuilder)
58 > }
59
60 // Most code should not use this, this is only exposed for code that has to recognize and use a
80 }
81
82 > func (m *grpcBuilder) Scheme() string { grpc_resolver.go
83 > return grpcResolverScheme
84 > }
85
86 func (m *grpcBuilder) getServiceResolver(u *url.URL) (ServiceResolver, error) {
go.temporal.io/server/common/metrics/task_queues.go 7 covered LOC · 3 ranges

Open complete file

17 taskQueueBreakdown bool,
18 tags ...Tag,
19 > ) Handler { task_queues.go
20 > metricTaskQueueName := omitted
21 > if taskQueueBreakdown {
22 > metricTaskQueueName = taskQueueFamily.Name() task_queues.go
23 > }
24
25 > tags = append(tags, NamespaceTag(namespaceName), UnsafeTaskQueueTag(metricTaskQueueName)) task_queues.go
26 > return handler.WithTags(tags...)
27 }
28
go.temporal.io/server/service/history/hsm/sm.go 7 covered LOC · 1 range

Open complete file

41 // NewTransition creates a new [Transition] from the given source states to a destination state for a given event.
42 // The apply function is called after verifying the transition is possible and setting the destination state.
43 > func NewTransition[S comparable, SM StateMachine[S], E any](src []S, dst S, apply func(SM, E) (TransitionOutput, error)) Transition[S, SM, E] { sm.go
44 > return Transition[S, SM, E]{
45 > Sources: src,
46 > Destination: dst,
47 > apply: apply,
48 > }
49 > }
50
51 // Possible returns a boolean indicating whether the transition is possible for the current state.
go.temporal.io/server/service/history/vclock/vclock.go 7 covered LOC · 1 range

Open complete file

10 shardID int32,
11 clock int64,
12 > ) *clockspb.VectorClock { vclock.go
13 > return &clockspb.VectorClock{
14 > ClusterId: clusterID,
15 > ShardId: shardID,
16 > Clock: clock,
17 > }
18 > }
19
20 func Comparable(
go.temporal.io/server/api/token/v1/message.go-helpers.pb.go 6 covered LOC · 2 ranges

Open complete file

81
82 // Marshal an object of type Task to the protobuf v3 wire format
83 > func (val *Task) Marshal() ([]byte, error) { message.go-helpers.pb.go
84 > return proto.Marshal(val)
85 > }
86
87 // Unmarshal an object of type Task from the protobuf v3 wire format
88 > func (val *Task) Unmarshal(buf []byte) error { message.go-helpers.pb.go
89 > return proto.Unmarshal(buf, val)
90 > }
91
92 // Size returns the size of the object, in bytes, once serialized
go.temporal.io/server/common/clock/time_source.go 6 covered LOC · 2 ranges

Open complete file

31
32 // NewRealTimeSource returns a timeSource that uses the real wall timeSource time.
33 > func NewRealTimeSource() RealTimeSource { time_source.go
34 > return RealTimeSource{}
35 > }
36
37 // Now returns the current time, with the location set to UTC.
38 > func (ts RealTimeSource) Now() time.Time { time_source.go
39 > return time.Now().UTC()
40 > }
41
42 // Since returns the time elapsed since t
go.temporal.io/server/common/effect/buffer.go 6 covered LOC · 2 ranges

Open complete file

27 // to this Buffer.
28 // It returns true if any effects were applied.
29 > func (b *Buffer) Apply(ctx context.Context) bool { buffer.go
30 > applied := false
31 > b.cancels = nil
32 > for _, effect := range b.effects {
33 effect(ctx)
34 applied = true
35 }
36 > b.effects = nil buffer.go
37 > return applied
38 }
39
go.temporal.io/server/common/metrics/option.go 6 covered LOC · 2 ranges

Open complete file

10 type WithDescription string
11
12 > func (h WithDescription) apply(m *metricDefinition) { option.go
13 > m.description = string(h)
14 > }
15
16 // WithUnit sets the unit of a metric. See NewBytesHistogramDef for an example.
17 type WithUnit MetricUnit
18
19 > func (h WithUnit) apply(m *metricDefinition) { option.go
20 > m.unit = MetricUnit(h)
21 > }
go.temporal.io/server/common/persistence/data_interfaces.go 6 covered LOC · 3 ranges

Open complete file

1408 // UnixMilliseconds returns t as a Unix time, the number of milliseconds elapsed since January 1, 1970 UTC.
1409 // It should be used for all CQL timestamp.
1410 > func UnixMilliseconds(t time.Time) int64 { data_interfaces.go
1411 > // Handling zero time separately because UnixNano is undefined for zero times.
1412 > if t.IsZero() {
1413 return 0
1414 }
1415
1416 > unixNano := t.UnixNano() data_interfaces.go
1417 > if unixNano < 0 {
1418 // Time is before January 1, 1970 UTC
1419 return 0
1420 }
1421 > return unixNano / int64(time.Millisecond) data_interfaces.go
1422 }
1423
go.temporal.io/server/common/persistence/nosql/nosqlplugin/cassandra/translator/fixed_address_translator.go 6 covered LOC · 2 ranges

Open complete file

15 )
16
17 > func init() { fixed_address_translator.go
18 > RegisterTranslator(fixedTranslatorName, NewFixedAddressTranslatorPlugin())
19 > }
20
21 type FixedAddressTranslatorPlugin struct {
22 }
23
24 > func NewFixedAddressTranslatorPlugin() TranslatorPlugin { fixed_address_translator.go
25 > return &FixedAddressTranslatorPlugin{}
26 > }
27
28 // GetTranslator What gocql driver does is that it will connect to the first node in the list in configuration
go.temporal.io/server/common/persistence/serialization/serializer.go 6 covered LOC · 2 ranges

Open complete file

139 )
140
141 > func NewSerializer() Serializer { serializer.go
142 > return &serializerImpl{encodingType: encodingTypeFromEnv()}
143 > }
144
145 func (t *serializerImpl) EncodingType() enumspb.EncodingType {
423 }
424
425 > func (t *serializerImpl) HistoryBranchToBlob(info *persistencespb.HistoryBranch) (*commonpb.DataBlob, error) { serializer.go
426 > return encodeBlob(info, t.encodingType)
427 > }
428
429 // NOTE: HistoryBranch does not have an encoding type; so we use the serializer's encoding type.
go.temporal.io/server/common/persistence/sql/sqlplugin/sqlite/plugin.go 6 covered LOC · 1 range

Open complete file

43 }
44
45 > func init() { plugin.go
46 > sql.RegisterPlugin(PluginName, &plugin{
47 > queryConverter: &queryConverter{},
48 > connPool: newConnPool(),
49 > })
50 > }
51
52 func (p *plugin) GetVisibilityQueryConverter() sqlplugin.VisibilityQueryConverter {
go.temporal.io/server/common/persistence/versionhistory/version_history_item.go 6 covered LOC · 3 ranges

Open complete file

8
9 // NewVersionHistoryItem create a new instance of VersionHistoryItem.
10 > func NewVersionHistoryItem(eventID int64, version int64) *historyspb.VersionHistoryItem { version_history_item.go
11 > if eventID < 0 || version < 0 {
12 panic(fmt.Sprintf("invalid version history item event ID: %v, version: %v", eventID, version))
13 }
14
15 > return &historyspb.VersionHistoryItem{EventId: eventID, Version: version} version_history_item.go
16 }
17
18 // CopyVersionHistoryItem create a new instance of VersionHistoryItem.
19 > func CopyVersionHistoryItem(item *historyspb.VersionHistoryItem) *historyspb.VersionHistoryItem { version_history_item.go
20 > return NewVersionHistoryItem(item.EventId, item.Version)
21 > }
22
23 // IsEqualVersionHistoryItem checks whether version history items are equal
go.temporal.io/server/common/rpc/context.go 6 covered LOC · 1 range

Open complete file

25
26 // CopyContextValues copies values in source Context to destination Context.
27 > func CopyContextValues(dst context.Context, src context.Context) context.Context { context.go
28 > return &valueCopyCtx{
29 > Context: dst,
30 > valueCtx: src,
31 > }
32 > }
33
34 // ResetContextTimeout creates new context with specified timeout and copies values from source Context.
go.temporal.io/server/common/tqid/task_queue_id.go 6 covered LOC · 2 ranges

Open complete file

140 // UnsafeTaskQueueFamily returns a TaskQueueFamily object without validating the task queue name.
141 // This method should only be used in logs/metrics, not in the server logic (use NewTaskQueueFamily instead).
142 > func UnsafeTaskQueueFamily(namespaceId string, name string) *TaskQueueFamily { task_queue_id.go
143 > return &TaskQueueFamily{namespaceId, name}
144 > }
145
146 // UnsafePartitionFromProto tries parsing proto using PartitionFromProto but if it fails still returns a Partition
228 }
229
230 > func (n *TaskQueueFamily) Name() string { task_queue_id.go
231 > return n.name
232 > }
233
234 func (n *TaskQueueFamily) NamespaceId() string {
go.temporal.io/server/service/history/configs/task.go 6 covered LOC · 1 range

Open complete file

26 func ConvertWeightsToDynamicConfigValue(
27 weights map[tasks.Priority]int,
28 > ) map[string]any { task.go
29 > weightsForDC := make(map[string]any)
30 > for priority, weight := range weights {
31 > weightsForDC[priority.String()] = weight
32 > }
33 > return weightsForDC
34 }
35
go.temporal.io/server/service/history/tasks/start_visibility_task.go 6 covered LOC · 2 ranges

Open complete file

47 }
48
49 > func (t *StartExecutionVisibilityTask) GetCategory() Category { start_visibility_task.go
50 > return CategoryVisibility
51 > }
52
53 > func (t *StartExecutionVisibilityTask) GetType() enumsspb.TaskType { start_visibility_task.go
54 > return enumsspb.TASK_TYPE_VISIBILITY_START_EXECUTION
55 > }
go.temporal.io/server/service/history/tasks/upsert_visibility_task.go 6 covered LOC · 2 ranges

Open complete file

38 }
39
40 > func (t *UpsertExecutionVisibilityTask) GetCategory() Category { upsert_visibility_task.go
41 > return CategoryVisibility
42 > }
43
44 > func (t *UpsertExecutionVisibilityTask) GetType() enumsspb.TaskType { upsert_visibility_task.go
45 > return enumsspb.TASK_TYPE_VISIBILITY_UPSERT_EXECUTION
46 > }
go.temporal.io/server/api/adminservicemock/v1/service_grpc.pb.mock.go 5 covered LOC · 1 range

Open complete file

33
34 // NewMockAdminServiceClient creates a new mock instance.
35 > func NewMockAdminServiceClient(ctrl *gomock.Controller) *MockAdminServiceClient { service_grpc.pb.mock.go
36 > mock := &MockAdminServiceClient{ctrl: ctrl}
37 > mock.recorder = &MockAdminServiceClientMockRecorder{mock}
38 > return mock
39 > }
40
41 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/api/historyservicemock/v1/service_grpc.pb.mock.go 5 covered LOC · 1 range

Open complete file

33
34 // NewMockHistoryServiceClient creates a new mock instance.
35 > func NewMockHistoryServiceClient(ctrl *gomock.Controller) *MockHistoryServiceClient { service_grpc.pb.mock.go
36 > mock := &MockHistoryServiceClient{ctrl: ctrl}
37 > mock.recorder = &MockHistoryServiceClientMockRecorder{mock}
38 > return mock
39 > }
40
41 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/api/matchingservicemock/v1/service_grpc.pb.mock.go 5 covered LOC · 1 range

Open complete file

32
33 // NewMockMatchingServiceClient creates a new mock instance.
34 > func NewMockMatchingServiceClient(ctrl *gomock.Controller) *MockMatchingServiceClient { service_grpc.pb.mock.go
35 > mock := &MockMatchingServiceClient{ctrl: ctrl}
36 > mock.recorder = &MockMatchingServiceClientMockRecorder{mock}
37 > return mock
38 > }
39
40 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/chasm/lib/nexusoperation/config.go 5 covered LOC · 1 range

Open complete file

160 }
161
162 > func (cfg RetryPolicyConfig) build() backoff.RetryPolicy { config.go
163 > return backoff.NewExponentialRetryPolicy(cfg.InitialInterval).
164 > WithMaximumInterval(cfg.MaxInterval).
165 > WithExpirationInterval(backoff.NoInterval)
166 > }
167
168 var defaultRetryPolicyConfig = RetryPolicyConfig{
go.temporal.io/server/chasm/lib/scheduler/util.go 5 covered LOC · 1 range

Open complete file

26
27 // serializeConflictToken serializes a conflict token as a byte slice.
28 > func serializeConflictToken(conflictToken int64) []byte { util.go
29 > token := make([]byte, 8)
30 > binary.LittleEndian.PutUint64(token, uint64(conflictToken))
31 > return token
32 > }
33
34 // newTaggedLogger returns a logger tagged with the Scheduler's attributes.
go.temporal.io/server/chasm/nexus_operation_processor.go 5 covered LOC · 1 range

Open complete file

165
166 // NewNexusEndpointProcessor creates a new NexusEndpointProcessor.
167 > func NewNexusEndpointProcessor() *NexusEndpointProcessor { nexus_operation_processor.go
168 > return &NexusEndpointProcessor{
169 > serviceProcessors: make(map[string]*NexusServiceProcessor),
170 > }
171 > }
172
173 // RegisterServiceProcessor adds a service-level processor to the endpoint keyed by its name.
go.temporal.io/server/client/client_factory_mock.go 5 covered LOC · 1 range

Open complete file

41
42 // NewMockFactory creates a new mock instance.
43 > func NewMockFactory(ctrl *gomock.Controller) *MockFactory { client_factory_mock.go
44 > mock := &MockFactory{ctrl: ctrl}
45 > mock.recorder = &MockFactoryMockRecorder{mock}
46 > return mock
47 > }
48
49 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/common/archiver/archival_metadata_mock.go 5 covered LOC · 1 range

Open complete file

30
31 // NewMockArchivalMetadata creates a new mock instance.
32 > func NewMockArchivalMetadata(ctrl *gomock.Controller) *MockArchivalMetadata { archival_metadata_mock.go
33 > mock := &MockArchivalMetadata{ctrl: ctrl}
34 > mock.recorder = &MockArchivalMetadataMockRecorder{mock}
35 > return mock
36 > }
37
38 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/common/archiver/provider/provider_mock.go 5 covered LOC · 1 range

Open complete file

30
31 // NewMockArchiverProvider creates a new mock instance.
32 > func NewMockArchiverProvider(ctrl *gomock.Controller) *MockArchiverProvider { provider_mock.go
33 > mock := &MockArchiverProvider{ctrl: ctrl}
34 > mock.recorder = &MockArchiverProviderMockRecorder{mock}
35 > return mock
36 > }
37
38 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/common/metrics/registry.go 5 covered LOC · 1 range

Open complete file

43
44 // register adds a metric definition to the list of pending metric definitions. This method is thread-safe.
45 > func (c *registry) register(d metricDefinition) { registry.go
46 > c.Lock()
47 > defer c.Unlock()
48 > c.definitions = append(c.definitions, d)
49 > }
50
51 // buildCatalog builds a catalog from the list of pending metric definitions. It is safe to call this method multiple
go.temporal.io/server/common/payloads/payloads.go 5 covered LOC · 1 range

Open complete file

13 )
14
15 > func EncodeString(str string) *commonpb.Payloads { payloads.go
16 > // Error can be safely ignored here becase string always can be converted.
17 > ps, _ := defaultDataConverter.ToPayloads(str)
18 > return ps
19 > }
20
21 func EncodeInt(i int) *commonpb.Payloads {
go.temporal.io/server/common/persistence/namespace_replication_queue_mock.go 5 covered LOC · 1 range

Open complete file

31
32 // NewMockNamespaceReplicationQueue creates a new mock instance.
33 > func NewMockNamespaceReplicationQueue(ctrl *gomock.Controller) *MockNamespaceReplicationQueue { namespace_replication_queue_mock.go
34 > mock := &MockNamespaceReplicationQueue{ctrl: ctrl}
35 > mock.recorder = &MockNamespaceReplicationQueueMockRecorder{mock}
36 > return mock
37 > }
38
39 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/common/persistence/sql/sqlplugin/mysql/plugin.go 5 covered LOC · 1 range

Open complete file

24 var _ sqlplugin.Plugin = (*plugin)(nil)
25
26 > func init() { plugin.go
27 > sql.RegisterPlugin(PluginName, &plugin{
28 > queryConverter: &queryConverter{},
29 > })
30 > }
31
32 func (p *plugin) GetVisibilityQueryConverter() sqlplugin.VisibilityQueryConverter {
go.temporal.io/server/common/persistence/sql/sqlplugin/sqlite/conn_pool.go 5 covered LOC · 1 range

Open complete file

23 }
24
25 > func newConnPool() *connPool { conn_pool.go
26 > return &connPool{
27 > pool: make(map[string]entry),
28 > }
29 > }
30
31 // Allocate allocates the shared database in the pool or returns already exists instance with the same DSN. If instance
go.temporal.io/server/common/persistence/visibility/manager/visibility_manager_mock.go 5 covered LOC · 1 range

Open complete file

32
33 // NewMockVisibilityManager creates a new mock instance.
34 > func NewMockVisibilityManager(ctrl *gomock.Controller) *MockVisibilityManager { visibility_manager_mock.go
35 > mock := &MockVisibilityManager{ctrl: ctrl}
36 > mock.recorder = &MockVisibilityManagerMockRecorder{mock}
37 > return mock
38 > }
39
40 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/common/persistence/visibility/store/elasticsearch/client/client_mock.go 5 covered LOC · 1 range

Open complete file

32
33 // NewMockClient creates a new mock instance.
34 > func NewMockClient(ctrl *gomock.Controller) *MockClient { client_mock.go
35 > mock := &MockClient{ctrl: ctrl}
36 > mock.recorder = &MockClientMockRecorder{mock}
37 > return mock
38 > }
39
40 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/common/primitives/timestamp/time.go 5 covered LOC · 3 ranges

Open complete file

11 }
12
13 > func TimeValue(t *timestamppb.Timestamp) time.Time { time.go
14 > if t == nil {
15 > return time.Time{} time.go
16 > }
17 > return t.AsTime() time.go
18 }
19
go.temporal.io/server/common/rpc/interceptor/request_error_handler_mock.go 5 covered LOC · 1 range

Open complete file

32
33 // NewMockErrorHandler creates a new mock instance.
34 > func NewMockErrorHandler(ctrl *gomock.Controller) *MockErrorHandler { request_error_handler_mock.go
35 > mock := &MockErrorHandler{ctrl: ctrl}
36 > mock.recorder = &MockErrorHandlerMockRecorder{mock}
37 > return mock
38 > }
39
40 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/common/sdk/factory_mock.go 5 covered LOC · 1 range

Open complete file

31
32 // NewMockClientFactory creates a new mock instance.
33 > func NewMockClientFactory(ctrl *gomock.Controller) *MockClientFactory { factory_mock.go
34 > mock := &MockClientFactory{ctrl: ctrl}
35 > mock.recorder = &MockClientFactoryMockRecorder{mock}
36 > return mock
37 > }
38
39 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/common/searchattribute/mapper_mock.go 5 covered LOC · 1 range

Open complete file

84
85 // NewMockMapperProvider creates a new mock instance.
86 > func NewMockMapperProvider(ctrl *gomock.Controller) *MockMapperProvider { mapper_mock.go
87 > mock := &MockMapperProvider{ctrl: ctrl}
88 > mock.recorder = &MockMapperProviderMockRecorder{mock}
89 > return mock
90 > }
91
92 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/common/searchattribute/sadefs/util.go 5 covered LOC · 3 ranges

Open complete file

20 }
21
22 > func SetMetadataType(p *commonpb.Payload, t enumspb.IndexedValueType) { util.go
23 > if t == enumspb.INDEXED_VALUE_TYPE_UNSPECIFIED {
24 return
25 }
26
27 > _, isValidT := enumspb.IndexedValueType_name[int32(t)] util.go
28 > if !isValidT {
29 // nolint: forbidigo
30 panic(fmt.Sprintf("unknown index value type %v", t))
31 }
32 > p.Metadata[MetadataType] = []byte(t.String()) util.go
33 }
go.temporal.io/server/common/testing/mockapi/workflowservicemock/v1/service_grpc.pb.mock.go 5 covered LOC · 1 range

Open complete file

32
33 // NewMockWorkflowServiceClient creates a new mock instance.
34 > func NewMockWorkflowServiceClient(ctrl *gomock.Controller) *MockWorkflowServiceClient { service_grpc.pb.mock.go
35 > mock := &MockWorkflowServiceClient{ctrl: ctrl}
36 > mock.recorder = &MockWorkflowServiceClientMockRecorder{mock}
37 > return mock
38 > }
39
40 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/service/history/events/events_cache_mock.go 5 covered LOC · 1 range

Open complete file

31
32 // NewMockCache creates a new mock instance.
33 > func NewMockCache(ctrl *gomock.Controller) *MockCache { events_cache_mock.go
34 > mock := &MockCache{ctrl: ctrl}
35 > mock.recorder = &MockCacheMockRecorder{mock}
36 > return mock
37 > }
38
39 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/service/history/ndc/events_reapplier_mock.go 5 covered LOC · 1 range

Open complete file

33
34 // NewMockEventsReapplier creates a new mock instance.
35 > func NewMockEventsReapplier(ctrl *gomock.Controller) *MockEventsReapplier { events_reapplier_mock.go
36 > mock := &MockEventsReapplier{ctrl: ctrl}
37 > mock.recorder = &MockEventsReapplierMockRecorder{mock}
38 > return mock
39 > }
40
41 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/service/history/ndc/workflow_resetter_mock.go 5 covered LOC · 1 range

Open complete file

34
35 // NewMockWorkflowResetter creates a new mock instance.
36 > func NewMockWorkflowResetter(ctrl *gomock.Controller) *MockWorkflowResetter { workflow_resetter_mock.go
37 > mock := &MockWorkflowResetter{ctrl: ctrl}
38 > mock.recorder = &MockWorkflowResetterMockRecorder{mock}
39 > return mock
40 > }
41
42 // EXPECT returns an object that allows the caller to indicate expected use.
go.temporal.io/server/common/cache/size_getter.go 4 covered LOC · 2 ranges

Open complete file

14 )
15
16 > func getSize(value any) int { size_getter.go
17 > if v, ok := value.(SizeGetter); ok {
18 > return v.CacheSize() size_getter.go
19 > }
20 // if the object does not have a CacheSize() method, assume is count limit cache, which size should be 1
21 return 1
go.temporal.io/server/common/log/with_logger.go 4 covered LOC · 2 ranges

Open complete file

14 // With returns Logger instance that prepend every log entry with tags. If logger implements
15 // WithLogger it is used, otherwise every log call will be intercepted.
16 > func With(logger Logger, tags ...tag.Tag) Logger { with_logger.go
17 > if wl, ok := logger.(WithLogger); ok {
18 > return wl.With(tags...) with_logger.go
19 > }
20 return newWithLogger(logger, tags...)
21 }
go.temporal.io/server/common/metrics/config.go 4 covered LOC · 2 ranges

Open complete file

493 }
494
495 > func configExcludeTags(cfg ClientConfig) map[string]map[string]struct{} { config.go
496 > tagsToFilter := make(map[string]map[string]struct{})
497 > for key, val := range cfg.ExcludeTags {
498 exclusions := make(map[string]struct{})
499 for _, val := range val {
502 tagsToFilter[key] = exclusions
503 }
504 > return tagsToFilter config.go
505 }
506
go.temporal.io/server/common/metrics/metrics.go 4 covered LOC · 4 ranges

Open complete file

80 )
81
82 > func (c CounterFunc) Record(v int64, tags ...Tag) { c(v, tags...) } metrics.go
83 > func (c GaugeFunc) Record(v float64, tags ...Tag) { c(v, tags...) } metrics.go
84 > func (c TimerFunc) Record(v time.Duration, tags ...Tag) { c(v, tags...) } metrics.go
85 > func (c HistogramFunc) Record(v int64, tags ...Tag) { c(v, tags...) } metrics.go
go.temporal.io/server/common/persistence/error_type.go 4 covered LOC · 2 ranges

Open complete file

3 import "go.temporal.io/api/serviceerror"
4
5 > func OperationPossiblySucceeded(err error) bool { error_type.go
6 > switch err.(type) {
7 case *CurrentWorkflowConditionFailedError,
8 *WorkflowConditionFailedError,
17 // Persistence failure that means that write was definitely not committed.
18 return false
19 > default: error_type.go
20 > return true
21 }
22 }
go.temporal.io/server/common/persistence/sql/sqlplugin/mysql/typeconv.go 4 covered LOC · 2 ranges

Open complete file

33 }
34
35 > func getMinMySQLDateTime() time.Time { typeconv.go
36 > t, err := time.Parse(time.RFC3339, "1000-01-01T00:00:00Z")
37 > if err != nil {
38 return time.Unix(0, 0).UTC()
39 }
40 > return t.UTC() typeconv.go
41 }
go.temporal.io/server/common/persistence/sql/sqlplugin/postgresql/typeconv.go 4 covered LOC · 2 ranges

Open complete file

35 }
36
37 > func getMinPostgreSQLDateTime() time.Time { typeconv.go
38 > t, err := time.Parse(time.RFC3339, "1000-01-01T00:00:00Z")
39 > if err != nil {
40 return time.Unix(0, 0).UTC()
41 }
42 > return t.UTC() typeconv.go
43 }
go.temporal.io/server/common/persistence/sql/sqlplugin/sqlite/typeconv.go 4 covered LOC · 2 ranges

Open complete file

33 }
34
35 > func getMinSQLiteDateTime() time.Time { typeconv.go
36 > t, err := time.Parse(time.RFC3339, "1000-01-01T00:00:00Z")
37 > if err != nil {
38 return time.Unix(0, 0).UTC()
39 }
40 > return t.UTC() typeconv.go
41 }
go.temporal.io/server/api/persistence/v1/predicates.go-helpers.pb.go 3 covered LOC · 1 range

Open complete file

17
18 // Size returns the size of the object, in bytes, once serialized
19 > func (val *Predicate) Size() int { predicates.go-helpers.pb.go
20 > return proto.Size(val)
21 > }
22
23 // Equal returns whether two Predicate values are equivalent by recursively
go.temporal.io/server/chasm/library.go 3 covered LOC · 1 range

Open complete file

56 // tasks within the CHASM framework.
57 // The format of the returned FQN is: "libName.name"
58 > func FullyQualifiedName(libName, name string) string { library.go
59 > return libName + "." + name
60 > }
go.temporal.io/server/chasm/registrable_component.go 3 covered LOC · 1 range

Open complete file

203 // The generated ID is used to uniquely identify components and tasks within the CHASM framework. The same FQN will
204 // always produce the same ID.
205 > func GenerateTypeID(fqn string) uint32 { registrable_component.go
206 > return farm.Fingerprint32([]byte(fqn))
207 > }
208
209 // hasBusinessIDAlias returns true if the component has a businessID alias configured
go.temporal.io/server/common/dynamicconfig/key.go 3 covered LOC · 1 range

Open complete file

13 )
14
15 > func MakeKey(s string) Key { key.go
16 > return Key{handle: unique.Make(strings.ToLower(s))}
17 > }
18
19 func (k Key) String() string {
go.temporal.io/server/common/log/noop_logger.go 3 covered LOC · 1 range

Open complete file

10
11 // NewNoopLogger return a noopLogger
12 > func NewNoopLogger() *noopLogger { noop_logger.go
13 > return &noopLogger{}
14 > }
15
16 func (n *noopLogger) Debug(string, ...tag.Tag) {}
go.temporal.io/server/common/membership/hostinfo.go 3 covered LOC · 1 range

Open complete file

12
13 // NewHostInfoFromAddress creates a new HostInfo instance from a socket address.
14 > func NewHostInfoFromAddress(address string) HostInfo { hostinfo.go
15 > return hostAddress(address)
16 > }
17
18 // hostAddress is a HostInfo implementation that uses a string as the address and identity.
go.temporal.io/server/common/persistence/nosql/nosqlplugin/cassandra/translator/translator_plugin.go 3 covered LOC · 1 range

Open complete file

22 // RegisterPlugin adds an auth plugin to the plugin registry
23 // it is only safe to use from a package init function
24 > func RegisterTranslator(name string, plugin TranslatorPlugin) { translator_plugin.go
25 > translators[name] = plugin
26 > }
27
28 func LookupTranslator(name string) (TranslatorPlugin, error) {
go.temporal.io/server/common/persistence/persistence_rate_limited_clients.go 3 covered LOC · 1 range

Open complete file

go.temporal.io/server/common/persistence/sql/store.go 3 covered LOC · 2 ranges

Open complete file

19
20 // RegisterPlugin will register a SQL plugin
21 > func RegisterPlugin(pluginName string, plugin sqlplugin.Plugin) { store.go
22 > if _, ok := supportedPlugins[pluginName]; ok {
23 panic("plugin " + pluginName + " already registered")
24 }
25 > supportedPlugins[pluginName] = plugin store.go
26 }
27
go.temporal.io/server/common/softassert/softassert.go 3 covered LOC · 2 ranges

Open complete file

26 // Example:
27 // softassert.That(logger, object.state == "ready", "object is not ready")
28 > func That(logger log.Logger, condition bool, staticMessage string, tags ...tag.Tag) bool { softassert.go
29 > if !condition {
30 // By using the same prefix for all assertions, they can be reliably found in logs.
31 logger.Error("failed assertion: "+staticMessage, append([]tag.Tag{tag.FailedAssertion}, tags...)...)
32 }
33 > return condition softassert.go
34 }
35
go.temporal.io/server/common/testing/protorequire/require.go 3 covered LOC · 1 range

Open complete file

38 }
39
40 > func New(t require.TestingT) ProtoAssertions { require.go
41 > return ProtoAssertions{t}
42 > }
43
44 // ProtoEqual compares two proto messages for equality using proto semantics. Options can be passed to customize
go.temporal.io/server/service/history/queues/errors/errors.go 3 covered LOC · 1 range

Open complete file

39
40 // NewUnprocessableTaskError returns a new UnprocessableTaskError from given message.
41 > func NewUnprocessableTaskError(message string) *UnprocessableTaskError { errors.go
42 > return &UnprocessableTaskError{Message: message}
43 > }
44
45 func (e UnprocessableTaskError) Error() string {
go.temporal.io/server/service/history/tasks/activity_task.go 3 covered LOC · 1 range

Open complete file

50 }
51
52 > func (a *ActivityTask) GetCategory() Category { activity_task.go
53 > return CategoryTransfer
54 > }
55
56 func (a *ActivityTask) GetType() enumsspb.TaskType {
go.temporal.io/server/common/persistence/client/fx.go 2 covered LOC · 1 range

Open complete file

224 }
225
226 > func managerProvider[T persistence.Closeable](newManagerFn func(Factory) (T, error)) func(Factory, fx.Lifecycle) (T, error) { fx.go
227 > return func(f Factory, lc fx.Lifecycle) (T, error) {
228 manager, err := newManagerFn(f) // passing receiver (Factory) as first argument.
229 if err != nil {
go.temporal.io/server/common/aggregate/noop_moving_window_average.go 1 covered LOC · 1 range

Open complete file

7 )
8
9 > func newNoopMovingWindowAverage() *noopMovingWindowAverage { return &noopMovingWindowAverage{} } noop_moving_window_average.go
10
11 func (a *noopMovingWindowAverage) Record(_ int64) {}
go.temporal.io/server/common/persistence/noop_health_signal_aggregator.go 1 covered LOC · 1 range

Open complete file

11 )
12
13 > func newNoopSignalAggregator() *noopSignalAggregator { return &noopSignalAggregator{} } noop_health_signal_aggregator.go
14
15 func (a *noopSignalAggregator) Start() {}