-
Notifications
You must be signed in to change notification settings - Fork 23
/
runtimestate.go
328 lines (280 loc) · 10.4 KB
/
runtimestate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package backend
import (
"errors"
"fmt"
"time"
"google.golang.org/protobuf/types/known/timestamppb"
"google.golang.org/protobuf/types/known/wrapperspb"
"github.com/microsoft/durabletask-go/api"
"github.com/microsoft/durabletask-go/internal/helpers"
"github.com/microsoft/durabletask-go/internal/protos"
)
var ErrDuplicateEvent = errors.New("duplicate event")
type OrchestrationRuntimeState struct {
instanceID api.InstanceID
newEvents []*protos.HistoryEvent
oldEvents []*protos.HistoryEvent
pendingTasks []*protos.HistoryEvent
pendingTimers []*protos.HistoryEvent
pendingMessages []OrchestratorMessage
startEvent *protos.ExecutionStartedEvent
completedEvent *protos.ExecutionCompletedEvent
createdTime time.Time
lastUpdatedTime time.Time
completedTime time.Time
continuedAsNew bool
isSuspended bool
CustomStatus *wrapperspb.StringValue
}
type OrchestratorMessage struct {
HistoryEvent *HistoryEvent
TargetInstanceID string
}
func NewOrchestrationRuntimeState(instanceID api.InstanceID, existingHistory []*HistoryEvent) *OrchestrationRuntimeState {
s := &OrchestrationRuntimeState{
instanceID: instanceID,
oldEvents: make([]*HistoryEvent, 0, len(existingHistory)),
newEvents: make([]*HistoryEvent, 0, 10),
}
for _, e := range existingHistory {
s.addEvent(e, false)
}
return s
}
// AddEvent appends a new history event to the orchestration history
func (s *OrchestrationRuntimeState) AddEvent(e *HistoryEvent) error {
return s.addEvent(e, true)
}
func (s *OrchestrationRuntimeState) addEvent(e *HistoryEvent, isNew bool) error {
if startEvent := e.GetExecutionStarted(); startEvent != nil {
if s.startEvent != nil {
return ErrDuplicateEvent
}
s.startEvent = startEvent
s.createdTime = e.Timestamp.AsTime()
} else if completedEvent := e.GetExecutionCompleted(); completedEvent != nil {
if s.completedEvent != nil {
return ErrDuplicateEvent
}
s.completedEvent = completedEvent
s.completedTime = e.Timestamp.AsTime()
} else if e.GetExecutionSuspended() != nil {
s.isSuspended = true
} else if e.GetExecutionResumed() != nil {
s.isSuspended = false
} else {
// TODO: Check for other possible duplicates using task IDs
}
if isNew {
s.newEvents = append(s.newEvents, e)
} else {
s.oldEvents = append(s.oldEvents, e)
}
s.lastUpdatedTime = e.Timestamp.AsTime()
return nil
}
func (s *OrchestrationRuntimeState) IsValid() bool {
if len(s.oldEvents) == 0 && len(s.newEvents) == 0 {
// empty orchestration state
return true
} else if s.startEvent != nil {
// orchestration history has a start event
return true
}
return false
}
// ApplyActions takes a set of actions and updates its internal state, including populating the outbox.
func (s *OrchestrationRuntimeState) ApplyActions(actions []*protos.OrchestratorAction, currentTraceContext *protos.TraceContext) (bool, error) {
for _, action := range actions {
if completedAction := action.GetCompleteOrchestration(); completedAction != nil {
if completedAction.OrchestrationStatus == protos.OrchestrationStatus_ORCHESTRATION_STATUS_CONTINUED_AS_NEW {
newState := NewOrchestrationRuntimeState(s.instanceID, []*protos.HistoryEvent{})
newState.continuedAsNew = true
newState.AddEvent(helpers.NewOrchestratorStartedEvent())
// Duplicate the start event info, updating just the input
newState.AddEvent(
helpers.NewExecutionStartedEvent(
s.startEvent.Name,
string(s.instanceID),
completedAction.Result,
s.startEvent.ParentInstance,
s.startEvent.ParentTraceContext,
),
)
// Unprocessed "carryover" events
for _, e := range completedAction.CarryoverEvents {
newState.AddEvent(e)
}
// Overwrite the current state object with a new one
*s = *newState
// ignore all remaining actions
return true, nil
} else {
s.AddEvent(helpers.NewExecutionCompletedEvent(action.Id, completedAction.OrchestrationStatus, completedAction.Result, completedAction.FailureDetails))
if s.startEvent.GetParentInstance() != nil {
msg := OrchestratorMessage{
HistoryEvent: &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.Now()},
TargetInstanceID: s.startEvent.GetParentInstance().OrchestrationInstance.GetInstanceId(),
}
if completedAction.OrchestrationStatus == protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED {
msg.HistoryEvent.EventType = &protos.HistoryEvent_SubOrchestrationInstanceCompleted{
SubOrchestrationInstanceCompleted: &protos.SubOrchestrationInstanceCompletedEvent{
TaskScheduledId: s.startEvent.ParentInstance.TaskScheduledId,
Result: completedAction.Result,
},
}
} else {
// TODO: What is the expected result for termination?
msg.HistoryEvent.EventType = &protos.HistoryEvent_SubOrchestrationInstanceFailed{
SubOrchestrationInstanceFailed: &protos.SubOrchestrationInstanceFailedEvent{
TaskScheduledId: s.startEvent.ParentInstance.TaskScheduledId,
FailureDetails: completedAction.FailureDetails,
},
}
}
s.pendingMessages = append(s.pendingMessages, msg)
}
}
} else if createtimer := action.GetCreateTimer(); createtimer != nil {
s.AddEvent(helpers.NewTimerCreatedEvent(action.Id, createtimer.FireAt))
s.pendingTimers = append(s.pendingTimers, helpers.NewTimerFiredEvent(action.Id, createtimer.FireAt, currentTraceContext))
} else if scheduleTask := action.GetScheduleTask(); scheduleTask != nil {
scheduledEvent := helpers.NewTaskScheduledEvent(
action.Id,
scheduleTask.Name,
scheduleTask.Version,
scheduleTask.Input,
currentTraceContext,
)
s.AddEvent(scheduledEvent)
s.pendingTasks = append(s.pendingTasks, scheduledEvent)
} else if createSO := action.GetCreateSubOrchestration(); createSO != nil {
// Autogenerate an instance ID for the sub-orchestration if none is provided, using a
// deterministic algorithm based on the parent instance ID to help enable de-duplication.
if createSO.InstanceId == "" {
createSO.InstanceId = fmt.Sprintf("%s:%04x", s.instanceID, action.Id)
}
s.AddEvent(helpers.NewSubOrchestrationCreatedEvent(
action.Id,
createSO.Name,
createSO.Version,
createSO.Input,
createSO.InstanceId,
currentTraceContext))
startEvent := helpers.NewExecutionStartedEvent(
createSO.Name,
createSO.InstanceId,
createSO.Input,
helpers.NewParentInfo(action.Id, s.startEvent.Name, string(s.instanceID)),
currentTraceContext,
)
s.pendingMessages = append(s.pendingMessages, OrchestratorMessage{HistoryEvent: startEvent, TargetInstanceID: createSO.InstanceId})
} else if sendEvent := action.GetSendEvent(); sendEvent != nil {
e := helpers.NewSendEventEvent(action.Id, sendEvent.Instance.InstanceId, sendEvent.Name, sendEvent.Data)
s.AddEvent(e)
s.pendingMessages = append(s.pendingMessages, OrchestratorMessage{HistoryEvent: e, TargetInstanceID: sendEvent.Instance.InstanceId})
} else if terminate := action.GetTerminateOrchestration(); terminate != nil {
// Send a message to terminate the target orchestration
msg := OrchestratorMessage{
TargetInstanceID: terminate.InstanceId,
HistoryEvent: helpers.NewExecutionTerminatedEvent(terminate.Reason, terminate.Recurse),
}
s.pendingMessages = append(s.pendingMessages, msg)
} else {
return false, fmt.Errorf("unknown action type: %v", action)
}
}
return false, nil
}
func (s *OrchestrationRuntimeState) InstanceID() api.InstanceID {
return s.instanceID
}
func (s *OrchestrationRuntimeState) Name() (string, error) {
if s.startEvent == nil {
return "", api.ErrNotStarted
}
return s.startEvent.Name, nil
}
func (s *OrchestrationRuntimeState) Input() (string, error) {
if s.startEvent == nil {
return "", api.ErrNotStarted
}
// REVIEW: Should we distinguish between no input and the empty string?
return s.startEvent.Input.GetValue(), nil
}
func (s *OrchestrationRuntimeState) Output() (string, error) {
if s.completedEvent == nil {
return "", api.ErrNotCompleted
}
// REVIEW: Should we distinguish between no output and the empty string?
return s.completedEvent.Result.GetValue(), nil
}
func (s *OrchestrationRuntimeState) RuntimeStatus() protos.OrchestrationStatus {
if s.startEvent == nil {
return protos.OrchestrationStatus_ORCHESTRATION_STATUS_PENDING
} else if s.isSuspended {
return protos.OrchestrationStatus_ORCHESTRATION_STATUS_SUSPENDED
} else if s.completedEvent != nil {
return s.completedEvent.GetOrchestrationStatus()
}
return protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING
}
func (s *OrchestrationRuntimeState) CreatedTime() (time.Time, error) {
if s.startEvent == nil {
return time.Time{}, api.ErrNotStarted
}
return s.createdTime, nil
}
func (s *OrchestrationRuntimeState) LastUpdatedTime() (time.Time, error) {
if s.startEvent == nil {
return time.Time{}, api.ErrNotStarted
}
return s.lastUpdatedTime, nil
}
func (s *OrchestrationRuntimeState) CompletedTime() (time.Time, error) {
if s.completedEvent == nil {
return time.Time{}, api.ErrNotCompleted
}
return s.completedTime, nil
}
func (s *OrchestrationRuntimeState) IsCompleted() bool {
return s.completedEvent != nil
}
func (s *OrchestrationRuntimeState) OldEvents() []*HistoryEvent {
return s.oldEvents
}
func (s *OrchestrationRuntimeState) NewEvents() []*HistoryEvent {
return s.newEvents
}
func (s *OrchestrationRuntimeState) FailureDetails() (*TaskFailureDetails, error) {
if s.completedEvent == nil {
return nil, api.ErrNotCompleted
} else if s.completedEvent.FailureDetails == nil {
return nil, api.ErrNoFailures
}
return s.completedEvent.FailureDetails, nil
}
func (s *OrchestrationRuntimeState) PendingTimers() []*HistoryEvent {
return s.pendingTimers
}
func (s *OrchestrationRuntimeState) PendingTasks() []*HistoryEvent {
return s.pendingTasks
}
func (s *OrchestrationRuntimeState) PendingMessages() []OrchestratorMessage {
return s.pendingMessages
}
func (s *OrchestrationRuntimeState) ContinuedAsNew() bool {
return s.continuedAsNew
}
func (s *OrchestrationRuntimeState) String() string {
return fmt.Sprintf("%v:%v", s.instanceID, helpers.ToRuntimeStatusString(s.RuntimeStatus()))
}
func (s *OrchestrationRuntimeState) getStartedTime() time.Time {
var startTime time.Time
if len(s.oldEvents) > 0 {
startTime = s.oldEvents[0].Timestamp.AsTime()
} else if len(s.newEvents) > 0 {
startTime = s.newEvents[0].Timestamp.AsTime()
}
return startTime
}