forked from sensu/sensu-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.go
92 lines (80 loc) · 1.54 KB
/
memory.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
package queue
import (
"context"
"strings"
"sync"
"time"
"github.com/sensu/sensu-go/types"
)
// NewMemoryGetter creates a new MemoryGetter.
func NewMemoryGetter() *MemoryGetter {
return &MemoryGetter{data: make(map[string]*Memory)}
}
// MemoryGetter is a types.QueueGetter.
type MemoryGetter struct {
data map[string]*Memory
}
// GetQueue gets a Memory queue.
func (m *MemoryGetter) GetQueue(path ...string) types.Queue {
key := strings.Join(path, "/")
q, ok := m.data[key]
if !ok {
q = &Memory{}
m.data[key] = q
}
return q
}
// Memory is an implementation of types.Queue in memory, provided
// for testing purposes.
type Memory struct {
data []string
sync.Mutex
}
// Enqueue ...
func (m *Memory) Enqueue(_ context.Context, val string) error {
m.Lock()
defer m.Unlock()
m.data = append(m.data, val)
return nil
}
// MemoryItem is an item from MemoryQueue.
type MemoryItem struct {
value string
q *Memory
}
// Value ...
func (m *MemoryItem) Value() string {
return m.value
}
// Ack ...
func (m *MemoryItem) Ack(context.Context) error {
return nil
}
// Nack ...
func (m *MemoryItem) Nack(context.Context) error {
m.q.Lock()
defer m.q.Unlock()
m.q.data = append(m.q.data, m.value)
return nil
}
// Dequeue ...
func (m *Memory) Dequeue(context.Context) (types.QueueItem, error) {
// cheesy blocking algo
var val string
for {
m.Lock()
if len(m.data) == 0 {
m.Unlock()
time.Sleep(time.Second)
continue
}
val = m.data[0]
m.data = m.data[1:]
m.Unlock()
break
}
return &MemoryItem{
q: m,
value: val,
}, nil
}