forked from vmihailenco/taskq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
73 lines (57 loc) · 1.67 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
package msgqueue
import (
"errors"
"fmt"
"math/rand"
"time"
"gopkg.in/vmihailenco/msgpack.v2"
)
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
}
func NewMessage(args ...interface{}) *Message {
return &Message{
Args: args,
}
}
func (m *Message) String() string {
return fmt.Sprintf("Message<Id=%q Name=%q>", m.Id, m.Name)
}
// SetDelayName sets delay and generates message name from the args.
func (m *Message) SetDelayName(delay time.Duration, args ...interface{}) {
m.Name = argsName(append(args, timeSlot(delay)))
m.Delay = delay
// Some random delay to better distribute the load.
m.Delay += time.Duration(rand.Intn(5)+1) * time.Second
}
func (m *Message) MarshalArgs() (string, error) {
return encodeArgs(m.Args)
}
func timeSlot(resolution time.Duration) int64 {
resolutionInSeconds := int64(resolution / time.Second)
if resolutionInSeconds <= 0 {
return 0
}
return time.Now().Unix() / resolutionInSeconds
}
func argsName(args []interface{}) string {
b, _ := msgpack.Marshal(args...)
return string(b)
}