Repository navigation
Expand file tree
/
Copy pathqueue.go
More file actions
238 lines (209 loc) · 7.9 KB
/
Copy pathqueue.go
File metadata and controls
238 lines (209 loc) · 7.9 KB
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// Package s3queue implements a distributed message queue on top of S3-compatible
// object storage. It uses conditional writes (IfNoneMatch) to guarantee that
// exactly one consumer can claim each message -- no external coordination needed.
package s3queue
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/smithy-go"
)
// ErrAlreadyClaimed is returned when a consumer tries to claim a message
// that another consumer has already claimed. This is the core mechanism
// that prevents double-processing: the first writer wins.
var ErrAlreadyClaimed = errors.New("message already claimed by another consumer")
// timestampFormat is a fixed-width time format that always produces exactly
// 9 fractional digits. Go's time.RFC3339Nano drops trailing zeros, which
// breaks lexicographic sorting: "...00Z" sorts after "...00.1Z" because
// 'Z' (0x5A) > '.' (0x2E). Fixed-width avoids this.
const timestampFormat = "2006-01-02T15:04:05.000000000Z07:00"
// Queue is a distributed message queue backed by S3-compatible storage.
// Messages flow through three stages represented as key prefixes:
//
// pending/ -> a message waiting to be processed
// claimed/ -> a consumer has taken ownership of the message
// done/ -> the message has been successfully processed
type Queue struct {
client *s3.Client
bucket string
prefix string
}
// Message represents a single item in the queue.
type Message struct {
ID string // unique identifier (e.g. "job-001")
Key string // full S3 object key under pending/
Payload []byte // the message body
}
// New creates a Queue that stores messages in the given bucket under prefix.
// The prefix lets multiple independent queues coexist in one bucket.
func New(client *s3.Client, bucket, prefix string) *Queue {
return &Queue{
client: client,
bucket: bucket,
prefix: prefix,
}
}
// Enqueue adds a new message to the queue. The key is structured as:
//
// {prefix}/pending/{timestamp}-{id}
//
// We use a fixed-width timestamp format (timestampFormat) instead of
// time.RFC3339Nano because RFC 3339 nano drops trailing zeros. That
// breaks lexicographic sorting: "...00Z" sorts after "...00.1Z" because
// 'Z' (0x5A) > '.' (0x2E). The fixed-width format always emits 9
// fractional digits, so lexicographic order matches chronological order.
// Note: ordering is approximate. Clock skew across multiple producers
// can still cause out-of-order delivery.
func (q *Queue) Enqueue(ctx context.Context, id string, payload []byte) error {
key := fmt.Sprintf("%s/pending/%s-%s", q.prefix, time.Now().UTC().Format(timestampFormat), id)
_, err := q.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(q.bucket),
Key: aws.String(key),
Body: bytes.NewReader(payload),
})
return err
}
// List returns all pending messages in approximate chronological order
// by timestamp prefix. S3 lists keys lexicographically, and our fixed-width
// timestamp format ensures that lexicographic order matches chronological
// order. Clock skew across producers may cause minor reordering.
func (q *Queue) List(ctx context.Context) ([]Message, error) {
prefix := fmt.Sprintf("%s/pending/", q.prefix)
resp, err := q.client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
Bucket: aws.String(q.bucket),
Prefix: aws.String(prefix),
})
if err != nil {
return nil, fmt.Errorf("listing pending messages: %w", err)
}
messages := make([]Message, 0, len(resp.Contents))
for _, obj := range resp.Contents {
key := aws.ToString(obj.Key)
id := extractID(key)
messages = append(messages, Message{
ID: id,
Key: key,
})
}
return messages, nil
}
// Claim attempts to take exclusive ownership of a message by writing a
// claim marker using a conditional PUT. The IfNoneMatch="*" header tells
// S3 to reject the write if an object already exists at that key.
//
// This is the heart of the queue's consistency guarantee:
// - Consumer A writes claimed/{id} with IfNoneMatch="*" -> succeeds (200)
// - Consumer B writes claimed/{id} with IfNoneMatch="*" -> fails (412)
//
// No locks, no leases, no coordination service -- just a single
// conditional write.
func (q *Queue) Claim(ctx context.Context, messageKey string, workerID string) error {
messageID := extractID(messageKey)
claimKey := fmt.Sprintf("%s/claimed/%s", q.prefix, messageID)
_, err := q.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(q.bucket),
Key: aws.String(claimKey),
Body: bytes.NewReader([]byte(workerID)),
IfNoneMatch: aws.String("*"),
})
if err != nil {
// A 412 Precondition Failed means another consumer beat us to it.
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
code := apiErr.ErrorCode()
if code == "PreconditionFailed" || code == "ConditionalRequestConflict" {
return ErrAlreadyClaimed
}
}
return fmt.Errorf("claiming message %s: %w", messageID, err)
}
return nil
}
// Ack acknowledges successful processing of a message. It removes the
// message from the pending prefix and writes a marker to done/. The
// claimed/{id} marker is intentionally left in place as a tombstone so
// another consumer can't re-claim a message that was already processed.
func (q *Queue) Ack(ctx context.Context, messageKey string) error {
messageID := extractID(messageKey)
// Delete from pending, the original message.
_, err := q.client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(q.bucket),
Key: aws.String(messageKey),
})
if err != nil {
return fmt.Errorf("deleting pending message %s: %w", messageID, err)
}
// Write a done marker so we can audit what was processed.
doneKey := fmt.Sprintf("%s/done/%s", q.prefix, messageID)
_, err = q.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(q.bucket),
Key: aws.String(doneKey),
Body: bytes.NewReader([]byte("done")),
})
if err != nil {
return fmt.Errorf("writing done marker for %s: %w", messageID, err)
}
return nil
}
// Dequeue is the main consumer loop primitive. It lists pending messages,
// tries to claim the first available one, and returns it. If another consumer
// has already claimed a message, it simply moves on to the next.
//
// Returns (nil, nil) when the queue is empty -- this is not an error,
// it just means there's nothing to do right now.
func (q *Queue) Dequeue(ctx context.Context, workerID string) (*Message, error) {
messages, err := q.List(ctx)
if err != nil {
return nil, err
}
for _, msg := range messages {
// Try to claim this message. If someone else got it first,
// ErrAlreadyClaimed tells us to move on.
err := q.Claim(ctx, msg.Key, workerID)
if errors.Is(err, ErrAlreadyClaimed) {
continue
}
if err != nil {
return nil, err
}
// We own this message. Fetch the payload.
resp, err := q.client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(q.bucket),
Key: aws.String(msg.Key),
})
if err != nil {
return nil, fmt.Errorf("fetching payload for %s: %w", msg.ID, err)
}
defer resp.Body.Close()
payload, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading payload for %s: %w", msg.ID, err)
}
msg.Payload = payload
return &msg, nil
}
// No unclaimed messages in the queue.
return nil, nil
}
// extractID pulls the message ID from a full S3 key.
// Given "queue/pending/2026-02-17T12:00:00.000Z-job-001", returns "job-001".
// Given "queue/claimed/job-001", returns "job-001".
func extractID(key string) string {
// Get everything after the last slash.
parts := strings.Split(key, "/")
filename := parts[len(parts)-1]
// For pending keys like "2026-02-17T12:00:00.000000000Z-job-001",
// strip the fixed-width timestamp prefix. UTC times always contain
// "Z-" at the boundary between the timestamp and the message ID.
if idx := strings.Index(filename, "Z-"); idx != -1 {
return filename[idx+2:]
}
// For claimed/done keys, the filename is already the message ID.
return filename
}