forked from reddit/baseplate.go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqsend_mock.go
62 lines (54 loc) · 1.22 KB
/
mqsend_mock.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
package mqsend
import (
"context"
)
// MockMessageQueue is a mocked implementation of MessageQueue.
//
// It's implemented with channels.
type MockMessageQueue struct {
msgs chan []byte
maxSize int
}
// OpenMockMessageQueue creates a MockMessageQueue.
//
// The name from the cfg will be ignored.
func OpenMockMessageQueue(cfg MessageQueueConfig) *MockMessageQueue {
return &MockMessageQueue{
msgs: make(chan []byte, cfg.MaxQueueSize),
maxSize: int(cfg.MaxMessageSize),
}
}
// Close closes the queue.
func (mmq *MockMessageQueue) Close() error {
close(mmq.msgs)
return nil
}
// Send sends a message to the queue.
func (mmq *MockMessageQueue) Send(ctx context.Context, data []byte) error {
if len(data) > mmq.maxSize {
return MessageTooLargeError{
MessageSize: len(data),
MaxSize: mmq.maxSize,
}
}
select {
case mmq.msgs <- data:
return nil
case <-ctx.Done():
if ctx.Err() == context.DeadlineExceeded {
return TimedOutError{
Cause: ctx.Err(),
}
}
return ctx.Err()
}
}
// Receive receives a message from the queue.
func (mmq *MockMessageQueue) Receive(ctx context.Context) ([]byte, error) {
select {
case msg := <-mmq.msgs:
return msg, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}