-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.go
More file actions
119 lines (107 loc) · 2.29 KB
/
queue.go
File metadata and controls
119 lines (107 loc) · 2.29 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
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
package main
import (
"sync"
"time"
"github.com/rs/xid"
)
type Message struct {
ID string
Body string
VisibleAt time.Time
Receipt string
CreatedAt time.Time
Locked bool
}
type Queue struct {
config QueueConfig
mu sync.Mutex
messages []*Message
}
func NewQueue(config QueueConfig) *Queue {
return &Queue{config: config, messages: []*Message{}}
}
func (q *Queue) sendMessage(body string) *Message {
q.mu.Lock()
defer q.mu.Unlock()
msg := &Message{
ID: xid.New().String(),
Body: body,
VisibleAt: time.Now(),
Receipt: xid.New().String(),
CreatedAt: time.Now(),
}
q.messages = append(q.messages, msg)
return msg
}
func (q *Queue) receiveMessages(max int) []*Message {
q.mu.Lock()
defer q.mu.Unlock()
var received []*Message
now := time.Now()
for _, msg := range q.messages {
if len(received) >= max {
break
}
if !msg.Locked && (msg.VisibleAt.Before(now) || msg.VisibleAt.Equal(now)) {
msg.VisibleAt = now.Add(time.Duration(q.config.VisibilityTimeout) * time.Second)
msg.Locked = true
received = append(received, msg)
}
}
return received
}
func (q *Queue) deleteMessage(receipt string) bool {
q.mu.Lock()
defer q.mu.Unlock()
for i, msg := range q.messages {
if msg.Receipt == receipt {
q.messages = append(q.messages[:i], q.messages[i+1:]...)
return true
}
}
return false
}
func (q *Queue) requeueExpiredMessages() {
q.mu.Lock()
defer q.mu.Unlock()
now := time.Now()
for _, msg := range q.messages {
if msg.Locked && now.After(msg.VisibleAt) {
msg.Locked = false
}
}
}
func (q *Queue) purge() {
q.mu.Lock()
defer q.mu.Unlock()
q.messages = []*Message{}
}
func (q *Queue) stats() map[string]any {
q.mu.Lock()
defer q.mu.Unlock()
available := 0
inFlight := 0
now := time.Now()
for _, msg := range q.messages {
if msg.Locked && now.Before(msg.VisibleAt) {
inFlight++
} else {
available++
}
}
return map[string]any{
"messagesAvailable": available,
"messagesInFlight": inFlight,
}
}
func (q *Queue) extendVisibilityTimeout(receipt string, extraSeconds int) bool {
q.mu.Lock()
defer q.mu.Unlock()
for _, msg := range q.messages {
if msg.Receipt == receipt && msg.Locked {
msg.VisibleAt = msg.VisibleAt.Add(time.Duration(extraSeconds) * time.Second)
return true
}
}
return false
}