-
Notifications
You must be signed in to change notification settings - Fork 102
/
message.go
204 lines (164 loc) · 4.51 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package taskq
import (
"context"
"encoding"
"encoding/binary"
"errors"
"fmt"
"time"
"github.com/klauspost/compress/s2"
"github.com/klauspost/compress/zstd"
"github.com/vmihailenco/msgpack/v5"
"github.com/vmihailenco/taskq/v3/internal"
)
// ErrDuplicate is returned when adding duplicate message to the queue.
var ErrDuplicate = errors.New("taskq: message with such name already exists")
// Message is used to create and retrieve messages from a queue.
type Message struct {
Ctx context.Context `msgpack:"-"`
// SQS/IronMQ message id.
ID string `msgpack:"1,omitempty,alias:ID"`
// Optional name for the message. Messages with the same name
// are processed only once.
Name string `msgpack:"-"`
// Delay specifies the duration the queue must wait
// before executing the message.
Delay time.Duration `msgpack:"-"`
// Args passed to the handler.
Args []interface{} `msgpack:"-"`
// Binary representation of the args.
ArgsCompression string `msgpack:"2,omitempty,alias:ArgsCompression"`
ArgsBin []byte `msgpack:"3,alias:ArgsBin"`
// SQS/IronMQ reservation id that is used to release/delete the message.
ReservationID string `msgpack:"-"`
// The number of times the message has been reserved or released.
ReservedCount int `msgpack:"4,omitempty,alias:ReservedCount"`
TaskName string `msgpack:"5,alias:TaskName"`
Err error `msgpack:"-"`
evt *ProcessMessageEvent
marshalBinaryCache []byte
}
func NewMessage(ctx context.Context, args ...interface{}) *Message {
return &Message{
Ctx: ctx,
Args: args,
}
}
func (m *Message) String() string {
return fmt.Sprintf("Message<ID=%q Name=%q ReservedCount=%d>",
m.ID, m.Name, m.ReservedCount)
}
// SetDelay sets the message delay.
func (m *Message) SetDelay(delay time.Duration) {
m.Delay = delay
}
// OnceInPeriod uses the period and the args to generate such a message name
// that message with such args is added to the queue once in a given period.
// If args are not provided then message args are used instead.
func (m *Message) OnceInPeriod(period time.Duration, args ...interface{}) {
m.setNameFromArgs(period, args...)
m.SetDelay(period)
}
func (m *Message) OnceWithDelay(delay time.Duration) {
m.setNameFromArgs(0)
if delay > 0 {
m.SetDelay(delay)
}
}
func (m *Message) OnceWithSchedule(tm time.Time) {
m.OnceWithDelay(time.Until(tm))
}
func (m *Message) setNameFromArgs(period time.Duration, args ...interface{}) {
var b []byte
if len(args) > 0 {
b, _ = msgpack.Marshal(args)
} else {
b, _ = m.MarshalArgs()
}
if period > 0 {
b = appendTimeSlot(b, period)
}
m.Name = internal.BytesToString(b)
}
var zdec, _ = zstd.NewReader(nil)
func (m *Message) decompress() ([]byte, error) {
switch m.ArgsCompression {
case "":
return m.ArgsBin, nil
case "zstd":
return zdec.DecodeAll(m.ArgsBin, nil)
case "s2":
return s2.Decode(nil, m.ArgsBin)
default:
return nil, fmt.Errorf("taskq: unsupported compression=%s", m.ArgsCompression)
}
}
func (m *Message) MarshalArgs() ([]byte, error) {
if m.ArgsBin != nil {
if m.ArgsCompression == "" {
return m.ArgsBin, nil
}
if m.Args == nil {
return m.decompress()
}
}
b, err := msgpack.Marshal(m.Args)
if err != nil {
return nil, err
}
m.ArgsBin = b
return b, nil
}
type messageRaw Message
var _ encoding.BinaryMarshaler = (*Message)(nil)
func (m *Message) MarshalBinary() ([]byte, error) {
if m.TaskName == "" {
return nil, internal.ErrTaskNameRequired
}
if m.marshalBinaryCache != nil {
return m.marshalBinaryCache, nil
}
_, err := m.MarshalArgs()
if err != nil {
return nil, err
}
if m.ArgsCompression == "" && len(m.ArgsBin) >= 512 {
compressed := s2.Encode(nil, m.ArgsBin)
if len(compressed) < len(m.ArgsBin) {
m.ArgsCompression = "s2"
m.ArgsBin = compressed
}
}
b, err := msgpack.Marshal((*messageRaw)(m))
if err != nil {
return nil, err
}
m.marshalBinaryCache = b
return b, nil
}
var _ encoding.BinaryUnmarshaler = (*Message)(nil)
func (m *Message) UnmarshalBinary(b []byte) error {
if err := msgpack.Unmarshal(b, (*messageRaw)(m)); err != nil {
return err
}
b, err := m.decompress()
if err != nil {
return err
}
m.ArgsCompression = ""
m.ArgsBin = b
return nil
}
func appendTimeSlot(b []byte, period time.Duration) []byte {
l := len(b)
b = append(b, make([]byte, 16)...)
binary.LittleEndian.PutUint64(b[l:], uint64(period))
binary.LittleEndian.PutUint64(b[l+8:], uint64(timeSlot(period)))
return b
}
func timeSlot(period time.Duration) int64 {
if period <= 0 {
return 0
}
return time.Now().UnixNano() / int64(period)
}