This repository has been archived by the owner on Sep 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inorder.go
120 lines (100 loc) · 1.95 KB
/
inorder.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
package inorder
import (
"errors"
"sync"
"time"
)
var (
// ErrTaskTimedOut the task didn't complete within the specified time limit
ErrTaskTimedOut = errors.New("task timed out")
)
// Task is something that we can wait for
type Task interface {
Wait() chan bool
IsDone() bool
}
// Result is the result of a task
type Result struct {
mutex *sync.Mutex
Error error
Task Task
}
func (r *Result) SetError(err error) {
r.mutex.Lock()
r.Error = err
r.mutex.Unlock()
}
func (r *Result) IsDone() (bool, error) {
var err error
r.mutex.Lock()
if r.Error != nil {
err = r.Error
}
r.mutex.Unlock()
if err != nil {
return false, err
}
return r.Task.IsDone(), nil
}
// InOrder maintains the order of enqueued jobs
type InOrder struct {
order []*Result
mutex sync.Mutex
taskDone chan bool
Timeout time.Duration
Done chan *Result
}
// NewInOrder creates a new orderer
func NewInOrder(timeout time.Duration) *InOrder {
in := &InOrder{
Done: make(chan *Result),
taskDone: make(chan bool),
Timeout: timeout,
}
go func() {
var doneList []*Result
for _ = range in.taskDone {
in.mutex.Lock()
doneUntil := -1
for i, res := range in.order {
done, err := res.IsDone()
if done || err != nil {
doneList = append(doneList, res)
} else {
break
}
doneUntil = i
}
if doneUntil >= 0 {
in.order = in.order[doneUntil+1:]
}
in.mutex.Unlock()
// Send off the the done tasks outside of the mutex lock
if len(doneList) > 0 {
for _, res := range doneList {
in.Done <- res
}
doneList = doneList[:0]
}
}
}()
return in
}
// Enqueue a new task
func (in *InOrder) Enqueue(task Task) {
in.mutex.Lock()
result := &Result{
mutex: &sync.Mutex{},
Task: task,
}
in.order = append(in.order, result)
in.mutex.Unlock()
go func() {
select {
case <-result.Task.Wait():
case <-time.After(in.Timeout):
result.Error = ErrTaskTimedOut
}
in.taskDone <- true
}()
}