-
Notifications
You must be signed in to change notification settings - Fork 1
/
aqueue.go
253 lines (231 loc) · 5.96 KB
/
aqueue.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
// Copyright 2020 The AQueue Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package aqueue
import (
"context"
"sync"
"time"
)
var (
errBusy = NewError(StatusCodeBusy, "queue busy")
errClosed = NewError(StatusCodeClosed, "queue closed")
errCancelled = NewError(StatusCodeCancelled, "request cancelled")
errInvalidArgument = NewError(StatusCodeInvalidArgument, "invalid arguments")
)
// PopFunc is a promise that returns value when data is available
type PopFunc func() (interface{}, error)
// PushFunc is promise that returns when data is pushed to the queue
type PushFunc func() error
// CancelFunc is called to cancel an asynchronous operation
type CancelFunc func()
// AQueue is opaque context
type AQueue struct {
lock *sync.Mutex
cond *sync.Cond
val interface{}
hasValue bool
closed bool
}
// NewAQueue returns a new queue instance
func NewAQueue() *AQueue {
ctx := &AQueue{
lock: &sync.Mutex{},
}
ctx.cond = sync.NewCond(ctx.lock)
return ctx
}
// Push adds an element to the queue
func (q *AQueue) Push(val interface{}) error {
pushFunc, _ := q.PushAsync(val)
return pushFunc()
}
// PushWithContext adds element to the queue with context
func (q *AQueue) PushWithContext(ctx context.Context, val interface{}) error {
if ctx == nil {
return errInvalidArgument
}
pushFunc, cancelFunc := q.PushAsync(val)
go func() {
<-ctx.Done()
cancelFunc()
}()
return pushFunc()
}
// PushWithTimeout is a convenience method implementing Push() timeout
func (q *AQueue) PushWithTimeout(ctx context.Context, val interface{}, d time.Duration) error {
if ctx == nil {
return errInvalidArgument
}
// create new context with timeout
newCtx, cancel := context.WithTimeout(ctx, d)
defer cancel()
// initiate asynchronous call
funcPush, funcCancel := q.PushAsync(nil)
// wait for context cancelation in a separate thread
go func() {
<-newCtx.Done()
funcCancel()
}()
// wait for push to complete
return funcPush()
}
// PushAsync initiates an asynchronoush push and returns
// a future and a cancel function
func (q *AQueue) PushAsync(val interface{}) (PushFunc, CancelFunc) {
cancelled := false
return func() error {
q.lock.Lock()
defer q.lock.Unlock()
for {
if cancelled {
return errCancelled
}
if err := q.tryPushUnsync(val); err == nil {
q.cond.Broadcast()
return nil
} else if e, ok := err.(*Error); ok {
if e.StatusCode() == StatusCodeClosed {
return e
}
} else {
panic("unknown error type")
}
q.cond.Wait()
}
}, func() {
q.lock.Lock()
defer q.lock.Unlock()
if !cancelled {
cancelled = true
q.cond.Broadcast()
}
}
}
// TryPush attempts to add an element to the queue without blocking.
func (q *AQueue) TryPush(val interface{}) error {
q.lock.Lock()
defer q.lock.Unlock()
return q.tryPushUnsync(val)
}
func (q *AQueue) tryPushUnsync(val interface{}) error {
// check if queue is closed
if q.closed {
return errClosed
}
// update value or wait
if !q.hasValue {
q.val = val
q.hasValue = true
return nil
}
return errBusy
}
// Pop removes the first element from the queue
func (q *AQueue) Pop() (interface{}, error) {
popFunc, _ := q.PopAsync()
return popFunc()
}
// PopWithContext removes an element from the queue with context
func (q *AQueue) PopWithContext(ctx context.Context) (interface{}, error) {
if ctx == nil {
return nil, errInvalidArgument
}
popFunc, cancelFunc := q.PopAsync()
go func() {
<-ctx.Done()
cancelFunc()
}()
return popFunc()
}
// PopWithTimeout removes an element from the queue with context and timeout
func (q *AQueue) PopWithTimeout(ctx context.Context, d time.Duration) (interface{}, error) {
if ctx == nil {
return nil, errInvalidArgument
}
// create new context with timeout
newCtx, cancel := context.WithTimeout(ctx, d)
defer cancel()
// perform async Pop()
popFunc, cancelFunc := q.PopAsync()
go func() {
<-newCtx.Done()
cancelFunc()
}()
return popFunc()
}
// PopAsync initiates retrieval of the next a value from the queue and
// returns a future and a cancel function
func (q *AQueue) PopAsync() (PopFunc, CancelFunc) {
cancelled := false
return func() (interface{}, error) {
q.lock.Lock()
defer q.lock.Unlock()
for {
if cancelled {
return nil, errCancelled
}
if val, err := q.tryPopUnsync(); err == nil {
q.cond.Broadcast()
return val, nil
} else if e, ok := err.(*Error); ok {
if e.StatusCode() == StatusCodeClosed {
return nil, e
}
} else {
panic("unknown error type")
}
q.cond.Wait()
}
}, func() {
q.lock.Lock()
defer q.lock.Unlock()
if !cancelled {
cancelled = true
q.cond.Broadcast()
}
}
}
// TryPop attempts to remove the last element from the queue without blocking.
func (q *AQueue) TryPop() (interface{}, error) {
q.lock.Lock()
defer q.lock.Unlock()
return q.tryPopUnsync()
}
func (q *AQueue) tryPopUnsync() (interface{}, error) {
// check if que is closed
if q.closed {
return nil, errClosed
}
// update value or wait
if !q.hasValue {
return nil, errBusy
}
val := q.val
q.val = nil
q.hasValue = false
return val, nil
}
// Close closes the queue causing any pending Pop/Push calls to exit with EOF error
// and any subsequent requests to fail as well. Closed queue cannot be reused.
func (q *AQueue) Close() {
q.lock.Lock()
defer q.lock.Unlock()
if q.closed {
return
}
q.val = nil // release any references
q.hasValue = false
q.closed = true
q.cond.Broadcast()
}