-
Notifications
You must be signed in to change notification settings - Fork 753
/
history_store.go
638 lines (554 loc) · 18.9 KB
/
history_store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// 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.
package persistence
import (
"fmt"
"github.com/pborman/uuid"
commonpb "go.temporal.io/api/common/v1"
enumspb "go.temporal.io/api/enums/v1"
historypb "go.temporal.io/api/history/v1"
"go.temporal.io/api/serviceerror"
persistencespb "go.temporal.io/server/api/persistence/v1"
"go.temporal.io/server/common"
"go.temporal.io/server/common/dynamicconfig"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
"go.temporal.io/server/common/persistence/serialization"
)
type (
// historyManagerImpl implements HistoryManager based on HistoryStore and PayloadSerializer
historyV2ManagerImpl struct {
historySerializer PayloadSerializer
persistence HistoryStore
logger log.Logger
pagingTokenSerializer *jsonHistoryTokenSerializer
transactionSizeLimit dynamicconfig.IntPropertyFn
}
)
const (
defaultLastNodeID = common.FirstEventID - 1
defaultLastTransactionID = int64(0)
// TrimHistoryBranch will only dump metadata, relatively cheap
trimHistoryBranchPageSize = 1000
)
var _ HistoryManager = (*historyV2ManagerImpl)(nil)
// NewHistoryV2ManagerImpl returns new HistoryManager
func NewHistoryV2ManagerImpl(
persistence HistoryStore,
logger log.Logger,
transactionSizeLimit dynamicconfig.IntPropertyFn,
) HistoryManager {
return &historyV2ManagerImpl{
historySerializer: NewPayloadSerializer(),
persistence: persistence,
logger: logger,
pagingTokenSerializer: newJSONHistoryTokenSerializer(),
transactionSizeLimit: transactionSizeLimit,
}
}
func (m *historyV2ManagerImpl) GetName() string {
return m.persistence.GetName()
}
// ForkHistoryBranch forks a new branch from a old branch
func (m *historyV2ManagerImpl) ForkHistoryBranch(
request *ForkHistoryBranchRequest,
) (*ForkHistoryBranchResponse, error) {
if request.ForkNodeID <= 1 {
return nil, &InvalidPersistenceRequestError{
Msg: fmt.Sprintf("ForkNodeID must be > 1"),
}
}
forkBranch, err := serialization.HistoryBranchFromBlob(request.ForkBranchToken, enumspb.ENCODING_TYPE_PROTO3.String())
if err != nil {
return nil, err
}
req := &InternalForkHistoryBranchRequest{
ForkBranchInfo: forkBranch,
ForkNodeID: request.ForkNodeID,
NewBranchID: uuid.New(),
Info: request.Info,
ShardID: request.ShardID,
}
resp, err := m.persistence.ForkHistoryBranch(req)
if err != nil {
return nil, err
}
datablob, err := serialization.HistoryBranchToBlob(resp.NewBranchInfo)
if err != nil {
return nil, err
}
token := datablob.Data
return &ForkHistoryBranchResponse{
NewBranchToken: token,
}, nil
}
// DeleteHistoryBranch removes a branch
func (m *historyV2ManagerImpl) DeleteHistoryBranch(
request *DeleteHistoryBranchRequest,
) error {
branch, err := serialization.HistoryBranchFromBlob(request.BranchToken, enumspb.ENCODING_TYPE_PROTO3.String())
if err != nil {
return err
}
req := &InternalDeleteHistoryBranchRequest{
BranchInfo: branch,
ShardID: request.ShardID,
}
return m.persistence.DeleteHistoryBranch(req)
}
// TrimHistoryBranch trims a branch
func (m *historyV2ManagerImpl) TrimHistoryBranch(
request *TrimHistoryBranchRequest,
) (*TrimHistoryBranchResponse, error) {
shardID := request.ShardID
minNodeID := common.FirstEventID
maxNodeID := request.NodeID + 1
pageSize := trimHistoryBranchPageSize
branch, err := serialization.HistoryBranchFromBlob(request.BranchToken, enumspb.ENCODING_TYPE_PROTO3.String())
if err != nil {
return nil, err
}
treeID := branch.TreeId
branchID := branch.BranchId
branchAncestors := branch.Ancestors
// merge tree ID & branch ID into branch ancestors so the processing logic is simple
beginNodeID := common.FirstEventID
if len(branch.Ancestors) > 0 {
beginNodeID = branch.Ancestors[len(branch.Ancestors)-1].GetEndNodeId()
}
branchAncestors = append(branchAncestors, &persistencespb.HistoryBranchRange{
BranchId: branchID,
BeginNodeId: beginNodeID,
EndNodeId: maxNodeID,
})
var pageToken []byte
transactionIDToNode := map[int64]historyNodeMetadata{}
for doContinue := true; doContinue; doContinue = len(pageToken) > 0 {
token, err := m.deserializeToken(pageToken, minNodeID-1)
if err != nil {
return nil, err
}
nodes, token, err := m.readRawHistoryBranch(
shardID,
treeID,
branchAncestors,
minNodeID,
maxNodeID,
token,
pageSize,
true,
)
if err != nil {
return nil, err
}
branchID := branchAncestors[token.CurrentRangeIndex].BranchId
for _, node := range nodes {
transactionIDToNode[node.TransactionID] = historyNodeMetadata{
branchInfo: &persistencespb.HistoryBranch{
TreeId: treeID,
BranchId: branchID,
Ancestors: branchAncestors[0:token.CurrentRangeIndex],
},
nodeID: node.NodeID,
transactionID: node.TransactionID,
prevTransactionID: node.PrevTransactionID,
}
}
pageToken, err = m.serializeToken(token)
if err != nil {
return nil, err
}
}
nodesToTrim, err := validateNodeChainAndTrim(
request.NodeID,
request.TransactionID,
transactionIDToNode,
)
if err != nil {
m.logger.Debug("unable to trim history branch due to existing history node not fully onboarded", tag.Error(err))
return &TrimHistoryBranchResponse{}, nil
}
for _, node := range nodesToTrim {
if err := m.persistence.DeleteHistoryNodes(&InternalDeleteHistoryNodesRequest{
ShardID: shardID,
BranchInfo: node.branchInfo,
NodeID: node.nodeID,
TransactionID: node.transactionID,
}); err != nil {
return nil, err
}
}
return &TrimHistoryBranchResponse{}, nil
}
// GetHistoryTree returns all branch information of a tree
func (m *historyV2ManagerImpl) GetHistoryTree(
request *GetHistoryTreeRequest,
) (*GetHistoryTreeResponse, error) {
if len(request.TreeID) == 0 {
branch, err := serialization.HistoryBranchFromBlob(request.BranchToken, enumspb.ENCODING_TYPE_PROTO3.String())
if err != nil {
return nil, err
}
request.TreeID = branch.GetTreeId()
}
return m.persistence.GetHistoryTree(request)
}
// AppendHistoryNodes add a node to history node table
func (m *historyV2ManagerImpl) AppendHistoryNodes(
request *AppendHistoryNodesRequest,
) (*AppendHistoryNodesResponse, error) {
branch, err := serialization.HistoryBranchFromBlob(request.BranchToken, enumspb.ENCODING_TYPE_PROTO3.String())
if err != nil {
return nil, err
}
if len(request.Events) == 0 {
return nil, &InvalidPersistenceRequestError{
Msg: fmt.Sprintf("events to be appended cannot be empty"),
}
}
version := request.Events[0].Version
nodeID := request.Events[0].EventId
lastID := nodeID - 1
if nodeID <= 0 {
return nil, &InvalidPersistenceRequestError{
Msg: fmt.Sprintf("eventID cannot be less than 1"),
}
}
for _, e := range request.Events {
if e.Version != version {
return nil, &InvalidPersistenceRequestError{
Msg: fmt.Sprintf("event version must be the same inside a batch"),
}
}
if e.EventId != lastID+1 {
return nil, &InvalidPersistenceRequestError{
Msg: fmt.Sprintf("event ID must be continous"),
}
}
lastID++
}
// nodeID will be the first eventID
blob, err := m.historySerializer.SerializeEvents(request.Events, enumspb.ENCODING_TYPE_PROTO3)
if err != nil {
return nil, err
}
size := len(blob.Data)
sizeLimit := m.transactionSizeLimit()
if size > sizeLimit {
return nil, &TransactionSizeLimitError{
Msg: fmt.Sprintf("transaction size of %v bytes exceeds limit of %v bytes", size, sizeLimit),
}
}
req := &InternalAppendHistoryNodesRequest{
IsNewBranch: request.IsNewBranch,
Info: request.Info,
BranchInfo: branch,
Node: InternalHistoryNode{
NodeID: nodeID,
Events: blob,
PrevTransactionID: request.PrevTransactionID,
TransactionID: request.TransactionID,
},
ShardID: request.ShardID,
}
err = m.persistence.AppendHistoryNodes(req)
return &AppendHistoryNodesResponse{
Size: size,
}, err
}
// ReadHistoryBranchByBatch returns history node data for a branch by batch
// Pagination is implemented here, the actual minNodeID passing to persistence layer is calculated along with token's LastNodeID
func (m *historyV2ManagerImpl) ReadHistoryBranchByBatch(
request *ReadHistoryBranchRequest,
) (*ReadHistoryBranchByBatchResponse, error) {
resp := &ReadHistoryBranchByBatchResponse{}
var err error
_, resp.History, resp.NextPageToken, resp.Size, err = m.readHistoryBranch(true, request)
return resp, err
}
// ReadHistoryBranch returns history node data for a branch
// Pagination is implemented here, the actual minNodeID passing to persistence layer is calculated along with token's LastNodeID
func (m *historyV2ManagerImpl) ReadHistoryBranch(
request *ReadHistoryBranchRequest,
) (*ReadHistoryBranchResponse, error) {
resp := &ReadHistoryBranchResponse{}
var err error
resp.HistoryEvents, _, resp.NextPageToken, resp.Size, err = m.readHistoryBranch(false, request)
return resp, err
}
// ReadRawHistoryBranch returns raw history binary data for a branch
// Pagination is implemented here, the actual minNodeID passing to persistence layer is calculated along with token's LastNodeID
// NOTE: this API should only be used by 3+DC
func (m *historyV2ManagerImpl) ReadRawHistoryBranch(
request *ReadHistoryBranchRequest,
) (*ReadRawHistoryBranchResponse, error) {
dataBlobs, token, dataSize, err := m.readRawHistoryBranchAndFilter(request)
if err != nil {
return nil, err
}
nextPageToken, err := m.serializeToken(token)
if err != nil {
return nil, err
}
return &ReadRawHistoryBranchResponse{
HistoryEventBlobs: dataBlobs,
NextPageToken: nextPageToken,
Size: dataSize,
}, nil
}
func (m *historyV2ManagerImpl) GetAllHistoryTreeBranches(
request *GetAllHistoryTreeBranchesRequest,
) (*GetAllHistoryTreeBranchesResponse, error) {
return m.persistence.GetAllHistoryTreeBranches(request)
}
func (m *historyV2ManagerImpl) readRawHistoryBranch(
shardID int32,
treeID string,
branchAncestors []*persistencespb.HistoryBranchRange,
minNodeID int64,
maxNodeID int64,
token *historyV2PagingToken,
pageSize int,
metadataOnly bool,
) ([]InternalHistoryNode, *historyV2PagingToken, error) {
if token.CurrentRangeIndex == notStartedIndex {
for idx, br := range branchAncestors {
// this range won't contain any nodes needed
if minNodeID >= br.GetEndNodeId() {
continue
}
// similarly, the ranges and the rest won't contain any nodes needed,
if maxNodeID <= br.GetBeginNodeId() {
break
}
if token.CurrentRangeIndex == notStartedIndex {
token.CurrentRangeIndex = idx
}
token.FinalRangeIndex = idx
}
if token.CurrentRangeIndex == notStartedIndex {
return nil, nil, serviceerror.NewDataLoss("branchRange is corrupted")
}
}
currentBranch := branchAncestors[token.CurrentRangeIndex]
// minNodeID remains the same, since caller can read from the middle
// maxNodeID need to be shortened since this branch can contain additional history nodes
maxNodeID = currentBranch.GetEndNodeId()
branchID := currentBranch.GetBranchId()
resp, err := m.persistence.ReadHistoryBranch(&InternalReadHistoryBranchRequest{
ShardID: shardID,
TreeID: treeID,
BranchID: branchID,
MinNodeID: minNodeID,
MaxNodeID: maxNodeID,
NextPageToken: token.StoreToken,
PageSize: pageSize,
MetadataOnly: metadataOnly,
})
if err != nil {
return nil, nil, err
}
token.StoreToken = resp.NextPageToken
return resp.Nodes, token, nil
}
func (m *historyV2ManagerImpl) readRawHistoryBranchAndFilter(
request *ReadHistoryBranchRequest,
) ([]*commonpb.DataBlob, *historyV2PagingToken, int, error) {
shardID := request.ShardID
branchToken := request.BranchToken
minNodeID := request.MinEventID
maxNodeID := request.MaxEventID
branch, err := serialization.HistoryBranchFromBlob(branchToken, enumspb.ENCODING_TYPE_PROTO3.String())
if err != nil {
return nil, nil, 0, err
}
treeID := branch.TreeId
branchID := branch.BranchId
branchAncestors := branch.Ancestors
// merge tree ID & branch ID into branch ancestors so the processing logic is simple
beginNodeID := common.FirstEventID
if len(branch.Ancestors) > 0 {
beginNodeID = branch.Ancestors[len(branch.Ancestors)-1].GetEndNodeId()
}
branchAncestors = append(branchAncestors, &persistencespb.HistoryBranchRange{
BranchId: branchID,
BeginNodeId: beginNodeID,
EndNodeId: maxNodeID,
})
token, err := m.deserializeToken(
request.NextPageToken,
request.MinEventID-1,
)
if err != nil {
return nil, nil, 0, err
}
nodes, token, err := m.readRawHistoryBranch(
shardID,
treeID,
branchAncestors,
minNodeID,
maxNodeID,
token,
request.PageSize,
false,
)
if err != nil {
return nil, nil, 0, err
}
if len(nodes) == 0 && len(request.NextPageToken) == 0 {
return nil, nil, 0, serviceerror.NewNotFound("Workflow execution history not found.")
}
nodes, err = m.filterHistoryNodes(
token.LastNodeID,
token.LastTransactionID,
nodes,
)
if err != nil {
return nil, nil, 0, err
}
var dataBlobs []*commonpb.DataBlob
dataSize := 0
if len(nodes) > 0 {
dataBlobs = make([]*commonpb.DataBlob, len(nodes))
for index, node := range nodes {
dataBlobs[index] = node.Events
dataSize += len(node.Events.Data)
}
lastNode := nodes[len(nodes)-1]
token.LastNodeID = lastNode.NodeID
token.LastTransactionID = lastNode.TransactionID
}
return dataBlobs, token, dataSize, nil
}
func (m *historyV2ManagerImpl) readHistoryBranch(
byBatch bool,
request *ReadHistoryBranchRequest,
) ([]*historypb.HistoryEvent, []*historypb.History, []byte, int, error) {
dataBlobs, token, dataSize, err := m.readRawHistoryBranchAndFilter(request)
if err != nil {
return nil, nil, nil, 0, err
}
historyEvents := make([]*historypb.HistoryEvent, 0, request.PageSize)
historyEventBatches := make([]*historypb.History, 0, request.PageSize)
for _, batch := range dataBlobs {
events, err := m.historySerializer.DeserializeEvents(batch)
if err != nil {
return historyEvents, historyEventBatches, nil, dataSize, err
}
if len(events) == 0 {
m.logger.Error("Empty events in a batch")
return historyEvents, historyEventBatches, nil, dataSize, serviceerror.NewDataLoss(fmt.Sprintf("corrupted history event batch, empty events"))
}
firstEvent := events[0] // first
eventCount := len(events) // length
lastEvent := events[eventCount-1] // last
if firstEvent.GetVersion() != lastEvent.GetVersion() || firstEvent.GetEventId()+int64(eventCount-1) != lastEvent.GetEventId() {
// in a single batch, version should be the same, and ID should be contiguous
m.logger.Error("Corrupted event batch",
tag.FirstEventVersion(firstEvent.GetVersion()), tag.WorkflowFirstEventID(firstEvent.GetEventId()),
tag.LastEventVersion(lastEvent.GetVersion()), tag.WorkflowNextEventID(lastEvent.GetEventId()),
tag.Counter(eventCount))
return historyEvents, historyEventBatches, nil, dataSize, serviceerror.NewDataLoss("corrupted history event batch, wrong version and IDs")
}
if firstEvent.GetEventId() != token.LastEventID+1 {
m.logger.Error("Corrupted non-contiguous event batch",
tag.WorkflowFirstEventID(firstEvent.GetEventId()),
tag.WorkflowNextEventID(lastEvent.GetEventId()),
tag.TokenLastEventID(token.LastEventID),
tag.Counter(eventCount))
return historyEvents, historyEventBatches, nil, dataSize, serviceerror.NewDataLoss("corrupted history event batch, eventID is not contiguous")
}
if byBatch {
historyEventBatches = append(historyEventBatches, &historypb.History{Events: events})
} else {
historyEvents = append(historyEvents, events...)
}
token.LastEventID = lastEvent.GetEventId()
}
nextPageToken, err := m.serializeToken(token)
if err != nil {
return nil, nil, nil, 0, err
}
return historyEvents, historyEventBatches, nextPageToken, dataSize, nil
}
func (m *historyV2ManagerImpl) filterHistoryNodes(
lastNodeID int64,
lastTransactionID int64,
nodes []InternalHistoryNode,
) ([]InternalHistoryNode, error) {
var result []InternalHistoryNode
for _, node := range nodes {
// assuming that business logic layer is correct and transaction ID only increase
// thus, valid event batch will come with increasing transaction ID
// event batches with smaller node ID
// -> should not be possible since records are already sorted
// event batches with same node ID
// -> batch with higher transaction ID is valid
// event batches with larger node ID
// -> batch with lower transaction ID is invalid (happens before)
// -> batch with higher transaction ID is valid
if node.TransactionID < lastTransactionID {
continue
}
switch {
case node.NodeID < lastNodeID:
return nil, serviceerror.NewInternal(fmt.Sprintf("corrupted data, nodeID cannot decrease"))
case node.NodeID == lastNodeID:
return nil, serviceerror.NewInternal(fmt.Sprintf("corrupted data, same nodeID must have smaller txnID"))
default: // row.NodeID > lastNodeID:
// NOTE: when row.nodeID > lastNodeID, we expect the one with largest txnID comes first
lastTransactionID = node.TransactionID
lastNodeID = node.NodeID
result = append(result, node)
}
}
return result, nil
}
func (m *historyV2ManagerImpl) deserializeToken(
token []byte,
defaultLastEventID int64,
) (*historyV2PagingToken, error) {
return m.pagingTokenSerializer.Deserialize(
token,
defaultLastEventID,
defaultLastNodeID,
defaultLastTransactionID,
)
}
func (m *historyV2ManagerImpl) serializeToken(
pagingToken *historyV2PagingToken,
) ([]byte, error) {
if len(pagingToken.StoreToken) == 0 {
if pagingToken.CurrentRangeIndex == pagingToken.FinalRangeIndex {
// this means that we have reached the final page of final branchRange
return nil, nil
}
pagingToken.CurrentRangeIndex++
return m.pagingTokenSerializer.Serialize(pagingToken)
}
return m.pagingTokenSerializer.Serialize(pagingToken)
}
func (m *historyV2ManagerImpl) Close() {
m.persistence.Close()
}