mirror of
https://github.com/hanzoai/tasks.git
synced 2026-10-04 02:04:03 +00:00
**What changed?** gogo/protobuf has been replaced with Google's official go compiler. **Why?** gogo/protobuf has been deprecated for some time and the community is moving on, building new tools (like vtproto) atop google's v2 compiler. **How did you test it?** `make test` **Potential risks** 1. The change from embedded gogo-generated-structs to google-generated-pointers-to-structs created a risk of nil pointer exceptions. I've fixed all the ones our tests found but it's possible there are more lurking in the new code. 2. This change may cause our performance to decrease. Certainly encoding/deconding of proto objects will become slower, but the overuse of pointers by the google compiler may negatively affect our overall performance. We'll need to keep an eye on the GC stats 3. This breaks the HTTP API. We will not support [shortand payload encoding](https://github.com/temporalio/proposals/blob/master/api/http-api.md#payload-formatting) in this first pass; that will come once this initial work is in testing. **Breaking changes for developers** - `*time.Time` in proto structs will now be [timestamppb.Timestamp](https://pkg.go.dev/google.golang.org/[email protected]/types/known/timestamppb#section-documentation) - `*time.Duration` will now be [durationpb.Duration](https://pkg.go.dev/google.golang.org/protobuf/types/known/durationpb) - V2-generated structs embed locks, so you cannot dereference them. `go vet` will scream at you about this. If you need a copy, use `proto.Clone`. - If the performance of this sucks then I will either update our code generator to add shallow-clone methods or hand-roll the ones we need - Proto enums will, when formatted to JSON, now be in `SCREAMING_SNAKE_CASE` rather than `PascalCase`. We decided (in discussion with the SDK team) that now was as good a time as any to rip the bandage off. - Proto objects, or objects embedding protos, cannot be compared using `reflect.DeepEqual` or _anything_ that uses it. This includes `testify` and `mock` equality testers! - You will need to use the `common/testing/protorequire`, `common/testing/protoassert`, or `common/testing/protomock` packages instead. I've implemented proto-compatible matchers and assertions there for all cases I've encountered - If you need `reflect.DeepEqual` for any reason you can use `go.temporal.io/api/temporalproto.DeepEqual` instead Note that history loading will not be impacted by the JSON changes: I rewrote history loading to dynamically fix incoming history JSON data (like all our other sdks); you can find this code in [my fork of our go API](https://github.com/tdeebswihart/temporal-api-go/blob/master/internal/temporalhistoryv1/load.go) alongside its tests. **🚨Sharp Edges Introduced🚨** Beware `*timestamppb.Timestamp.AsTime()`. If you need to extract a time value from a proto time (timestamppb) **always** make sure to check whether it's nil first. When the proto object is `nil` `AsTime()` will return a non-zero time at the proto epoch: UTC midnight on January 1, 1970. I've made this mistake multiple times during this transition and each time it's been a pain to debug **Is hotfix candidate?** No.
444 lines
13 KiB
Go
444 lines
13 KiB
Go
// The MIT License
|
|
//
|
|
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
|
|
//
|
|
// Copyright (c) 2020 Uber Technologies, Inc.
|
|
//
|
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
// of this software and associated documentation files (the "Software"), to deal
|
|
// in the Software without restriction, including without limitation the rights
|
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
// copies of the Software, and to permit persons to whom the Software is
|
|
// furnished to do so, subject to the following conditions:
|
|
//
|
|
// The above copyright notice and this permission notice shall be included in
|
|
// all copies or substantial portions of the Software.
|
|
//
|
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
// THE SOFTWARE.
|
|
|
|
//go:generate mockgen -copyright_file ../../../LICENSE -package $GOPACKAGE -source $GOFILE -destination timer_sequence_mock.go
|
|
|
|
package workflow
|
|
|
|
import (
|
|
"fmt"
|
|
"sort"
|
|
"time"
|
|
|
|
enumspb "go.temporal.io/api/enums/v1"
|
|
"go.temporal.io/api/serviceerror"
|
|
|
|
persistencespb "go.temporal.io/server/api/persistence/v1"
|
|
"go.temporal.io/server/common"
|
|
"go.temporal.io/server/common/primitives/timestamp"
|
|
"go.temporal.io/server/service/history/tasks"
|
|
)
|
|
|
|
const (
|
|
// user timer task not created / created
|
|
|
|
TimerTaskStatusNone = iota
|
|
TimerTaskStatusCreated
|
|
)
|
|
|
|
const (
|
|
// activity timer task status
|
|
|
|
TimerTaskStatusCreatedStartToClose = 1 << iota
|
|
TimerTaskStatusCreatedScheduleToStart
|
|
TimerTaskStatusCreatedScheduleToClose
|
|
TimerTaskStatusCreatedHeartbeat
|
|
)
|
|
|
|
type (
|
|
// TimerSequenceID represent a in mem timer
|
|
TimerSequenceID struct {
|
|
EventID int64
|
|
Timestamp time.Time
|
|
TimerType enumspb.TimeoutType
|
|
TimerCreated bool
|
|
Attempt int32
|
|
}
|
|
|
|
TimerSequenceIDs []TimerSequenceID
|
|
|
|
TimerSequence interface {
|
|
CreateNextUserTimer() (bool, error)
|
|
CreateNextActivityTimer() (bool, error)
|
|
|
|
LoadAndSortUserTimers() []TimerSequenceID
|
|
LoadAndSortActivityTimers() []TimerSequenceID
|
|
}
|
|
|
|
timerSequenceImpl struct {
|
|
mutableState MutableState
|
|
}
|
|
)
|
|
|
|
var _ TimerSequence = (*timerSequenceImpl)(nil)
|
|
|
|
func NewTimerSequence(
|
|
mutableState MutableState,
|
|
) *timerSequenceImpl {
|
|
return &timerSequenceImpl{
|
|
mutableState: mutableState,
|
|
}
|
|
}
|
|
|
|
func (t *timerSequenceImpl) CreateNextUserTimer() (bool, error) {
|
|
|
|
sequenceIDs := t.LoadAndSortUserTimers()
|
|
if len(sequenceIDs) == 0 {
|
|
return false, nil
|
|
}
|
|
|
|
firstTimerTask := sequenceIDs[0]
|
|
|
|
// user timer after workflow timeout, skip
|
|
workflowRunExpirationTime := timestamp.TimeValue(t.mutableState.GetExecutionInfo().WorkflowRunExpirationTime)
|
|
if !workflowRunExpirationTime.IsZero() && firstTimerTask.Timestamp.After(workflowRunExpirationTime) {
|
|
return false, nil
|
|
}
|
|
|
|
// timer has already been created
|
|
if firstTimerTask.TimerCreated {
|
|
return false, nil
|
|
}
|
|
|
|
timerInfo, ok := t.mutableState.GetUserTimerInfoByEventID(firstTimerTask.EventID)
|
|
if !ok {
|
|
return false, serviceerror.NewInternal(fmt.Sprintf("unable to load activity info %v", firstTimerTask.EventID))
|
|
}
|
|
// mark timer task mask as indication that timer task is generated
|
|
// here TaskID is misleading attr, should be called timer created flag or something
|
|
timerInfo.TaskStatus = TimerTaskStatusCreated
|
|
if err := t.mutableState.UpdateUserTimer(timerInfo); err != nil {
|
|
return false, err
|
|
}
|
|
t.mutableState.AddTasks(&tasks.UserTimerTask{
|
|
// TaskID is set by shard
|
|
WorkflowKey: t.mutableState.GetWorkflowKey(),
|
|
VisibilityTimestamp: firstTimerTask.Timestamp,
|
|
EventID: firstTimerTask.EventID,
|
|
Version: t.mutableState.GetCurrentVersion(),
|
|
})
|
|
return true, nil
|
|
}
|
|
|
|
func (t *timerSequenceImpl) CreateNextActivityTimer() (bool, error) {
|
|
|
|
sequenceIDs := t.LoadAndSortActivityTimers()
|
|
if len(sequenceIDs) == 0 {
|
|
return false, nil
|
|
}
|
|
|
|
firstTimerTask := sequenceIDs[0]
|
|
|
|
// activity timer after workflow timeout, skip
|
|
workflowRunExpirationTime := timestamp.TimeValue(t.mutableState.GetExecutionInfo().WorkflowRunExpirationTime)
|
|
if !workflowRunExpirationTime.IsZero() && firstTimerTask.Timestamp.After(workflowRunExpirationTime) {
|
|
return false, nil
|
|
}
|
|
|
|
// timer has already been created
|
|
if firstTimerTask.TimerCreated {
|
|
return false, nil
|
|
}
|
|
|
|
activityInfo, ok := t.mutableState.GetActivityInfo(firstTimerTask.EventID)
|
|
if !ok {
|
|
return false, serviceerror.NewInternal(fmt.Sprintf("unable to load activity info %v", firstTimerTask.EventID))
|
|
}
|
|
// mark timer task mask as indication that timer task is generated
|
|
activityInfo.TimerTaskStatus |= timerTypeToTimerMask(firstTimerTask.TimerType)
|
|
|
|
var err error
|
|
if firstTimerTask.TimerType == enumspb.TIMEOUT_TYPE_HEARTBEAT {
|
|
err = t.mutableState.UpdateActivityWithTimerHeartbeat(activityInfo, firstTimerTask.Timestamp)
|
|
} else {
|
|
err = t.mutableState.UpdateActivity(activityInfo)
|
|
}
|
|
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
t.mutableState.AddTasks(&tasks.ActivityTimeoutTask{
|
|
// TaskID is set by shard
|
|
WorkflowKey: t.mutableState.GetWorkflowKey(),
|
|
VisibilityTimestamp: firstTimerTask.Timestamp,
|
|
TimeoutType: firstTimerTask.TimerType,
|
|
EventID: firstTimerTask.EventID,
|
|
Attempt: firstTimerTask.Attempt,
|
|
Version: t.mutableState.GetCurrentVersion(),
|
|
})
|
|
return true, nil
|
|
}
|
|
|
|
func (t *timerSequenceImpl) LoadAndSortUserTimers() []TimerSequenceID {
|
|
|
|
pendingTimers := t.mutableState.GetPendingTimerInfos()
|
|
timers := make(TimerSequenceIDs, 0, len(pendingTimers))
|
|
|
|
for _, timerInfo := range pendingTimers {
|
|
|
|
if sequenceID := t.getUserTimerTimeout(
|
|
timerInfo,
|
|
); sequenceID != nil {
|
|
timers = append(timers, *sequenceID)
|
|
}
|
|
}
|
|
|
|
sort.Sort(timers)
|
|
return timers
|
|
}
|
|
|
|
func (t *timerSequenceImpl) LoadAndSortActivityTimers() []TimerSequenceID {
|
|
// there can be 4 timer per activity
|
|
// see TimerType
|
|
pendingActivities := t.mutableState.GetPendingActivityInfos()
|
|
activityTimers := make(TimerSequenceIDs, 0, len(pendingActivities)*4)
|
|
|
|
for _, activityInfo := range pendingActivities {
|
|
|
|
if sequenceID := t.getActivityScheduleToCloseTimeout(
|
|
activityInfo,
|
|
); sequenceID != nil {
|
|
activityTimers = append(activityTimers, *sequenceID)
|
|
}
|
|
|
|
if sequenceID := t.getActivityScheduleToStartTimeout(
|
|
activityInfo,
|
|
); sequenceID != nil {
|
|
activityTimers = append(activityTimers, *sequenceID)
|
|
}
|
|
|
|
if sequenceID := t.getActivityStartToCloseTimeout(
|
|
activityInfo,
|
|
); sequenceID != nil {
|
|
activityTimers = append(activityTimers, *sequenceID)
|
|
}
|
|
|
|
if sequenceID := t.getActivityHeartbeatTimeout(
|
|
activityInfo,
|
|
); sequenceID != nil {
|
|
activityTimers = append(activityTimers, *sequenceID)
|
|
}
|
|
}
|
|
|
|
sort.Sort(activityTimers)
|
|
return activityTimers
|
|
}
|
|
|
|
func (t *timerSequenceImpl) getUserTimerTimeout(
|
|
timerInfo *persistencespb.TimerInfo,
|
|
) *TimerSequenceID {
|
|
|
|
expiryTime := timerInfo.ExpiryTime
|
|
|
|
return &TimerSequenceID{
|
|
EventID: timerInfo.GetStartedEventId(),
|
|
Timestamp: timestamp.TimeValue(expiryTime),
|
|
TimerType: enumspb.TIMEOUT_TYPE_START_TO_CLOSE,
|
|
TimerCreated: timerInfo.TaskStatus == TimerTaskStatusCreated,
|
|
Attempt: 1,
|
|
}
|
|
}
|
|
|
|
func (t *timerSequenceImpl) getActivityScheduleToStartTimeout(
|
|
activityInfo *persistencespb.ActivityInfo,
|
|
) *TimerSequenceID {
|
|
|
|
// activity is not scheduled yet, probably due to retry & backoff
|
|
if activityInfo.ScheduledEventId == common.EmptyEventID {
|
|
return nil
|
|
}
|
|
|
|
// activity is already started
|
|
if activityInfo.StartedEventId != common.EmptyEventID {
|
|
return nil
|
|
}
|
|
|
|
scheduleToStartDuration := timestamp.DurationValue(activityInfo.ScheduleToStartTimeout)
|
|
if scheduleToStartDuration == 0 {
|
|
return nil
|
|
}
|
|
|
|
timeoutTime := timestamp.TimeValue(activityInfo.ScheduledTime).Add(scheduleToStartDuration)
|
|
|
|
return &TimerSequenceID{
|
|
EventID: activityInfo.ScheduledEventId,
|
|
Timestamp: timeoutTime,
|
|
TimerType: enumspb.TIMEOUT_TYPE_SCHEDULE_TO_START,
|
|
TimerCreated: (activityInfo.TimerTaskStatus & TimerTaskStatusCreatedScheduleToStart) > 0,
|
|
Attempt: activityInfo.Attempt,
|
|
}
|
|
}
|
|
|
|
func (t *timerSequenceImpl) getActivityScheduleToCloseTimeout(
|
|
activityInfo *persistencespb.ActivityInfo,
|
|
) *TimerSequenceID {
|
|
|
|
// activity is not scheduled yet, probably due to retry & backoff
|
|
if activityInfo.ScheduledEventId == common.EmptyEventID {
|
|
return nil
|
|
}
|
|
|
|
scheduleToCloseDuration := timestamp.DurationValue(activityInfo.ScheduleToCloseTimeout)
|
|
if scheduleToCloseDuration == 0 {
|
|
return nil
|
|
}
|
|
|
|
timeoutTime := timestamp.TimeValue(activityInfo.ScheduledTime).Add(scheduleToCloseDuration)
|
|
|
|
return &TimerSequenceID{
|
|
EventID: activityInfo.ScheduledEventId,
|
|
Timestamp: timeoutTime,
|
|
TimerType: enumspb.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE,
|
|
TimerCreated: (activityInfo.TimerTaskStatus & TimerTaskStatusCreatedScheduleToClose) > 0,
|
|
Attempt: activityInfo.Attempt,
|
|
}
|
|
}
|
|
|
|
func (t *timerSequenceImpl) getActivityStartToCloseTimeout(
|
|
activityInfo *persistencespb.ActivityInfo,
|
|
) *TimerSequenceID {
|
|
|
|
// activity is not scheduled yet, probably due to retry & backoff
|
|
if activityInfo.ScheduledEventId == common.EmptyEventID {
|
|
return nil
|
|
}
|
|
|
|
// activity is not started yet
|
|
if activityInfo.StartedEventId == common.EmptyEventID {
|
|
return nil
|
|
}
|
|
|
|
startToCloseDuration := timestamp.DurationValue(activityInfo.StartToCloseTimeout)
|
|
if startToCloseDuration == 0 {
|
|
return nil
|
|
}
|
|
|
|
timeoutTime := timestamp.TimeValue(activityInfo.StartedTime).Add(startToCloseDuration)
|
|
|
|
return &TimerSequenceID{
|
|
EventID: activityInfo.ScheduledEventId,
|
|
Timestamp: timeoutTime,
|
|
TimerType: enumspb.TIMEOUT_TYPE_START_TO_CLOSE,
|
|
TimerCreated: (activityInfo.TimerTaskStatus & TimerTaskStatusCreatedStartToClose) > 0,
|
|
Attempt: activityInfo.Attempt,
|
|
}
|
|
}
|
|
|
|
func (t *timerSequenceImpl) getActivityHeartbeatTimeout(
|
|
activityInfo *persistencespb.ActivityInfo,
|
|
) *TimerSequenceID {
|
|
|
|
// activity is not scheduled yet, probably due to retry & backoff
|
|
if activityInfo.ScheduledEventId == common.EmptyEventID {
|
|
return nil
|
|
}
|
|
|
|
// activity is not started yet
|
|
if activityInfo.StartedEventId == common.EmptyEventID {
|
|
return nil
|
|
}
|
|
|
|
// not heartbeat timeout configured
|
|
heartbeatDuration := timestamp.DurationValue(activityInfo.HeartbeatTimeout)
|
|
if heartbeatDuration == 0 {
|
|
return nil
|
|
}
|
|
|
|
// use the latest time as last heartbeat time
|
|
var lastHeartbeat time.Time
|
|
if activityInfo.StartedTime != nil {
|
|
lastHeartbeat = timestamp.TimeValue(activityInfo.StartedTime)
|
|
}
|
|
|
|
if !timestamp.TimeValue(activityInfo.LastHeartbeatUpdateTime).IsZero() && activityInfo.LastHeartbeatUpdateTime.AsTime().After(lastHeartbeat) {
|
|
lastHeartbeat = timestamp.TimeValue(activityInfo.LastHeartbeatUpdateTime)
|
|
}
|
|
|
|
heartbeatTimeout := lastHeartbeat.Add(heartbeatDuration)
|
|
|
|
return &TimerSequenceID{
|
|
EventID: activityInfo.ScheduledEventId,
|
|
Timestamp: heartbeatTimeout,
|
|
TimerType: enumspb.TIMEOUT_TYPE_HEARTBEAT,
|
|
TimerCreated: (activityInfo.TimerTaskStatus & TimerTaskStatusCreatedHeartbeat) > 0,
|
|
Attempt: activityInfo.Attempt,
|
|
}
|
|
}
|
|
|
|
func timerTypeToTimerMask(
|
|
timerType enumspb.TimeoutType,
|
|
) int32 {
|
|
|
|
switch timerType {
|
|
case enumspb.TIMEOUT_TYPE_START_TO_CLOSE:
|
|
return TimerTaskStatusCreatedStartToClose
|
|
case enumspb.TIMEOUT_TYPE_SCHEDULE_TO_START:
|
|
return TimerTaskStatusCreatedScheduleToStart
|
|
case enumspb.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE:
|
|
return TimerTaskStatusCreatedScheduleToClose
|
|
case enumspb.TIMEOUT_TYPE_HEARTBEAT:
|
|
return TimerTaskStatusCreatedHeartbeat
|
|
default:
|
|
panic("invalid timeout type")
|
|
}
|
|
}
|
|
|
|
// Len implements sort.Interface
|
|
func (s TimerSequenceIDs) Len() int {
|
|
return len(s)
|
|
}
|
|
|
|
// Swap implements sort.Interface.
|
|
func (s TimerSequenceIDs) Swap(
|
|
this int,
|
|
that int,
|
|
) {
|
|
s[this], s[that] = s[that], s[this]
|
|
}
|
|
|
|
// Less implements sort.Interface
|
|
func (s TimerSequenceIDs) Less(
|
|
this int,
|
|
that int,
|
|
) bool {
|
|
|
|
thisSequenceID := s[this]
|
|
thatSequenceID := s[that]
|
|
|
|
// order: timeout time, event ID, timeout type
|
|
|
|
if thisSequenceID.Timestamp.Before(thatSequenceID.Timestamp) {
|
|
return true
|
|
} else if thisSequenceID.Timestamp.After(thatSequenceID.Timestamp) {
|
|
return false
|
|
}
|
|
|
|
// timeout time are the same
|
|
if thisSequenceID.EventID < thatSequenceID.EventID {
|
|
return true
|
|
} else if thisSequenceID.EventID > thatSequenceID.EventID {
|
|
return false
|
|
}
|
|
|
|
// timeout time & event ID are the same
|
|
if thisSequenceID.TimerType < thatSequenceID.TimerType {
|
|
return true
|
|
} else if thisSequenceID.TimerType > thatSequenceID.TimerType {
|
|
return false
|
|
}
|
|
|
|
// thisSequenceID && thatSequenceID are the same
|
|
return true
|
|
}
|