/
message.go
97 lines (76 loc) · 1.97 KB
/
message.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
package msgqueue
import (
"bytes"
"errors"
"fmt"
"hash/fnv"
"time"
"github.com/go-msgqueue/msgqueue/internal"
"github.com/vmihailenco/msgpack"
)
// ErrDuplicate is returned when adding duplicate message to the queue.
var ErrDuplicate = errors.New("queue: message with such name already exists")
// Message is used to create and retrieve messages from a queue.
type Message struct {
// SQS/IronMQ message id.
Id string
// Optional name for the message. Messages with the same name
// are processed only once.
Name string
// Delay specifies the duration the queue must wait
// before executing the message.
Delay time.Duration
// Function args passed to the handler.
Args []interface{}
// Text representation of the Args.
Body string
// SQS/IronMQ reservation id that is used to release/delete the message..
ReservationId string
// The number of times the message has been reserved or released.
ReservedCount int
Err error
}
func NewMessage(args ...interface{}) *Message {
return &Message{
Args: args,
}
}
func (m *Message) String() string {
return fmt.Sprintf("Message<Id=%q Name=%q ReservedCount=%d>",
m.Id, m.Name, m.ReservedCount)
}
// SetDelayName sets delay and generates message name from the args.
func (m *Message) SetDelayName(delay time.Duration, args ...interface{}) {
h := hashArgs(append(args, delay, timeSlot(delay)))
m.Name = string(h)
m.Delay = delay + 5*time.Second
}
func (m *Message) EncodeBody(compress bool) (string, error) {
if m.Body != "" {
return m.Body, nil
}
s, err := internal.EncodeArgs(m.Args, compress)
if err != nil {
return "", err
}
m.Body = s
return s, nil
}
func timeSlot(period time.Duration) int64 {
if period <= 0 {
return 0
}
return time.Now().UnixNano() / int64(period)
}
func hashArgs(args []interface{}) []byte {
var buf bytes.Buffer
enc := msgpack.NewEncoder(&buf)
_ = enc.EncodeMulti(args...)
b := buf.Bytes()
if len(b) <= 64 {
return b
}
h := fnv.New128a()
_, _ = h.Write(b)
return h.Sum(nil)
}