-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutex_workflow.go
126 lines (115 loc) · 4.33 KB
/
mutex_workflow.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
package mutex_queue
import (
"fmt"
"slices"
"time"
"go.temporal.io/sdk/workflow"
)
const (
// AcquireLockSignalName signal channel name for lock acquisition
AcquireLockSignalName = "acquire-lock-event"
// RequestLockSignalName channel name for request lock
RequestLockSignalName = "request-lock-event"
)
type queuedMutex struct {
queue []string
unlockTimeout time.Duration
}
func MutexWorkflowWithCancellation(
ctx workflow.Context,
namespace string,
resourceID string,
unlockTimeout time.Duration,
queue []string,
) error {
logger := workflow.GetLogger(ctx)
info := workflow.GetInfo(ctx)
currentWorkflowID := workflow.GetInfo(ctx).WorkflowExecution.ID
if currentWorkflowID == "default-test-workflow-id" {
// unit testing hack, see https://github.com/uber-go/cadence-client/issues/663
_ = workflow.Sleep(ctx, 10*time.Millisecond)
}
logger.Info("started", "currentWorkflowID", currentWorkflowID)
requestLockCh := workflow.GetSignalChannel(ctx, RequestLockSignalName)
completeCh := workflow.NewChannel(ctx)
q := &queuedMutex{
queue: queue,
unlockTimeout: unlockTimeout,
}
done := false
for {
selector := workflow.NewSelector(ctx)
selector.AddReceive(completeCh, func(c workflow.ReceiveChannel, more bool) {
c.Receive(ctx, &done)
})
selector.AddReceive(requestLockCh, func(c workflow.ReceiveChannel, more bool) {
var senderID string
c.Receive(ctx, &senderID)
q.queue = append(q.queue, senderID)
workflow.Go(ctx, q.processSender(ctx, senderID, completeCh))
})
if info.GetContinueAsNewSuggested() {
return workflow.NewContinueAsNewError(ctx, MutexWorkflowWithCancellation, namespace, resourceID, unlockTimeout, queue)
}
if done && requestLockCh.Len() == 0 {
return nil
}
selector.Select(ctx)
}
}
func (q *queuedMutex) processSender(ctx workflow.Context, senderID string, completeCh workflow.Channel) func(workflow.Context) {
return func(ctx workflow.Context) {
var index int
workflow.Await(ctx, func() bool {
index = slices.Index(q.queue, senderID)
isLast := index == len(q.queue)-1
// Block the last element in the queue unless it's the only one left.
return !isLast || len(q.queue) == 1
})
if index == 0 {
unblockSender(ctx, senderID, q.unlockTimeout)
} else {
cancelSender(ctx, senderID)
}
// Remove the unblocked or cancelled sender
index = slices.Index(q.queue, senderID) // reindex is needed since other coroutine could have updated the queue
q.queue = append(q.queue[:index], q.queue[index+1:]...)
// Try to complete if queue is empty
if len(q.queue) == 0 {
completeCh.Send(ctx, true)
}
}
}
func cancelSender(ctx workflow.Context, senderWorkflowID string) {
logger := workflow.GetLogger(ctx)
err := workflow.RequestCancelExternalWorkflow(ctx, senderWorkflowID, "").Get(ctx, nil)
if err != nil {
logger.Info("CancelExternalWorkflow error", "Error", err)
}
}
func unblockSender(ctx workflow.Context, senderWorkflowID string, unlockTimeout time.Duration) {
logger := workflow.GetLogger(ctx)
var releaseLockChannelName string
_ = workflow.SideEffect(ctx, func(ctx workflow.Context) interface{} {
return generateUnlockChannelName(senderWorkflowID)
}).Get(&releaseLockChannelName)
logger.Info("generated release lock channel name", "releaseLockChannelName", releaseLockChannelName)
// Send release lock channel name back to a senderWorkflowID, so that it can
// release the lock using release lock channel name
err := workflow.SignalExternalWorkflow(ctx, senderWorkflowID, "", AcquireLockSignalName, releaseLockChannelName).Get(ctx, nil)
if err != nil {
// .Get(ctx, nil) blocks until the signal is sent.
// If the senderWorkflowID is closed (terminated/canceled/timeouted/completed/etc), this would return error.
// In this case we release the lock immediately instead of failing the mutex workflow.
// Mutex workflow failing would lead to all workflows that have sent requestLock will be waiting.
logger.Info("SignalExternalWorkflow error", "Error", err)
}
logger.Info("signaled external workflow")
var ack string
workflow.GetSignalChannel(ctx, releaseLockChannelName).ReceiveWithTimeout(ctx, unlockTimeout, &ack)
logger.Info("release signal received: " + ack)
}
// generateUnlockChannelName generates release lock channel name
func generateUnlockChannelName(senderWorkflowID string) string {
return fmt.Sprintf("unlock-event-%s", senderWorkflowID)
}