-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathqueue.go
More file actions
92 lines (80 loc) · 1.37 KB
/
queue.go
File metadata and controls
92 lines (80 loc) · 1.37 KB
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
package goq
import (
"errors"
"sync"
)
type QClient interface {
Id() string
Notify(message Message) error
}
type PubSub interface {
Done()
Publish(msg Message) bool
Subscribe(client QClient) error
Unsubscribe(qClient QClient)
SubscriberCount() int
}
type Message struct {
Id string
Payload interface{}
}
type GoQ struct {
pubsub PubSub
maxDepth int
queue chan Message
pauseChan chan bool
once sync.Once
done bool
}
func NewGoQ(queueDepth int, publisher PubSub) *GoQ {
return &GoQ{
maxDepth: queueDepth,
queue: make(chan Message, queueDepth),
pauseChan: make(chan bool, 1),
pubsub: publisher,
}
}
func (q *GoQ) Enqueue(message Message) error {
if q.done {
return errors.New("Queue closed")
}
select {
case q.queue <- message:
return nil
default:
return errors.New("Message rejected, max queue depth reached")
}
}
func (q *GoQ) StartPublishing() {
go func() {
for {
msg, ok := <-q.queue
if ok {
select {
case <-q.pauseChan:
return
default:
q.publishMessage(msg)
}
} else {
q.pubsub.Done()
return
}
}
}()
}
func (q *GoQ) StopPublishing() {
q.once.Do(func() {
close(q.queue)
q.done = true
})
}
func (q *GoQ) publishMessage(msg Message) {
delivered := q.pubsub.Publish(msg)
if !delivered {
q.queue <- msg
}
}
func (q *GoQ) PausePublishing() {
q.pauseChan <- true
}