-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathamqp-queue.ts
More file actions
200 lines (186 loc) · 7.03 KB
/
amqp-queue.ts
File metadata and controls
200 lines (186 loc) · 7.03 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
import type { AMQPMessage } from "./amqp-message.js"
import type { ConsumeParams, MessageCount } from "./amqp-channel.js"
import type { AMQPProperties } from "./amqp-properties.js"
import { AMQPConsumer, AMQPGeneratorConsumer } from "./amqp-consumer.js"
import { AMQPSubscription, AMQPGeneratorSubscription } from "./amqp-subscription.js"
import type { ConsumerDefinition } from "./amqp-subscription.js"
import type { AMQPSession } from "./amqp-session.js"
import { publishConfirmed, publishNoConfirm, type Body } from "./amqp-publisher.js"
/**
* Options for {@link AMQPQueue#subscribe}.
* Combines consumer parameters with channel-level prefetch.
*/
export type QueueSubscribeParams = ConsumeParams & {
/** Per-consumer prefetch limit (sets QoS on the channel before consuming). */
prefetch?: number
/**
* Whether to requeue messages that are nacked due to a callback error.
* Defaults to `true`.
*/
requeueOnNack?: boolean
}
/** Options for {@link AMQPQueue#publish}. */
export type QueuePublishOptions = AMQPProperties & {
/** Wait for broker confirmation. Defaults to `true`. */
confirm?: boolean
}
/**
* High-level queue handle returned by {@link AMQPSession#queue}.
*
* All operations are reconnect-safe: they acquire a session channel on each
* call, so they work transparently after a reconnection. `subscribe` provides
* automatic consumer recovery. `publish` waits for a broker confirm; use
* Pass `{ confirm: false }` to skip the wait.
*/
export class AMQPQueue {
readonly name: string
private readonly session: AMQPSession
private readonly subscriptions = new Set<AMQPSubscription>()
/** @internal */
constructor(session: AMQPSession, name: string) {
this.session = session
this.name = name
}
/**
* Publish a message directly to this queue (via the default exchange).
* @param options - publish properties; set `confirm: false` to skip broker confirmation
* @returns `this` for chaining
*/
async publish(body: Body, options: QueuePublishOptions = {}): Promise<AMQPQueue> {
const { confirm = true, ...properties } = options
if (confirm) {
await publishConfirmed(this.session, "", this.name, body, properties)
} else {
await publishNoConfirm(this.session, "", this.name, body, properties)
}
return this
}
/** Subscribe with a callback. Messages are acked after the callback returns, nacked on error. */
subscribe(callback: (msg: AMQPMessage) => void | Promise<void>): Promise<AMQPSubscription>
/** Subscribe with a callback and custom params. */
subscribe(
params: QueueSubscribeParams,
callback: (msg: AMQPMessage) => void | Promise<void>,
): Promise<AMQPSubscription>
/**
* Subscribe via an async iterator. Messages continue yielding across reconnections.
* @example
* ```ts
* for await (const msg of await q.subscribe()) {
* console.log(msg.bodyString())
* await msg.ack()
* }
* ```
*/
subscribe(params?: QueueSubscribeParams): Promise<AMQPGeneratorSubscription>
async subscribe(
params?: QueueSubscribeParams | ((msg: AMQPMessage) => void | Promise<void>),
callback?: (msg: AMQPMessage) => void | Promise<void>,
): Promise<AMQPSubscription | AMQPGeneratorSubscription> {
if (typeof params === "function") [callback, params] = [params, undefined]
const { prefetch, requeueOnNack = true, ...consumeParams } = params ?? {}
// Force noAck: false when auto-acking so the server tracks delivery tags.
// basicConsume defaults noAck to true, so we must be explicit.
const autoAck = !consumeParams.noAck
if (autoAck) consumeParams.noAck = false
if (autoAck && callback !== undefined) {
const userCallback = callback
callback = async (msg: AMQPMessage) => {
try {
await userCallback(msg)
await msg.ack()
} catch {
await msg.nack(requeueOnNack)
}
}
}
const def: ConsumerDefinition = {
queueName: this.name,
consumeParams,
...(callback !== undefined && { callback }),
...(prefetch !== undefined && { prefetch }),
}
const consumer = await this.openConsumer(def)
const sub = callback ? new AMQPSubscription(consumer, def) : new AMQPGeneratorSubscription(consumer, def)
this.subscriptions.add(sub)
sub.onCancel = () => {
this.subscriptions.delete(sub)
}
return sub
}
/**
* Poll the queue for a single message.
* @param [params.noAck=true] - automatically acknowledge on delivery
*/
async get(params?: { noAck?: boolean }): Promise<AMQPMessage | null> {
const ch = await this.session.getOpsChannel()
return ch.basicGet(this.name, params)
}
/**
* Bind this queue to an exchange.
* @returns `this` for chaining
*/
async bind(exchange: string, routingKey = "", args: Record<string, unknown> = {}): Promise<AMQPQueue> {
const ch = await this.session.getOpsChannel()
await ch.queueBind(this.name, exchange, routingKey, args)
return this
}
/**
* Remove a binding between this queue and an exchange.
* @returns `this` for chaining
*/
async unbind(exchange: string, routingKey = "", args: Record<string, unknown> = {}): Promise<AMQPQueue> {
const ch = await this.session.getOpsChannel()
await ch.queueUnbind(this.name, exchange, routingKey, args)
return this
}
/** Purge all messages from this queue. */
async purge(): Promise<MessageCount> {
const ch = await this.session.getOpsChannel()
return ch.queuePurge(this.name)
}
/**
* Delete this queue.
* @param [params.ifUnused=false] - only delete if the queue has no consumers
* @param [params.ifEmpty=false] - only delete if the queue is empty
*/
async delete(params?: { ifUnused?: boolean; ifEmpty?: boolean }): Promise<MessageCount> {
const ch = await this.session.getOpsChannel()
return ch.queueDelete(this.name, params)
}
/**
* Re-establish all subscriptions after a reconnection.
* @internal Called by the session's reconnect loop.
*/
async recover(): Promise<void> {
for (const sub of this.subscriptions) {
try {
const consumer = await this.openConsumer(sub.def)
sub.setConsumer(consumer)
this.session.logger?.debug(`Recovered consumer for queue: ${this.name}`)
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err))
this.session.logger?.warn(`Failed to recover consumer for queue ${this.name}:`, error.message)
}
}
}
/**
* Cancel all subscriptions without closing the connection.
* @internal Called by the session on stop().
*/
cancelAll(): void {
for (const sub of this.subscriptions) {
sub.cancel().catch(() => {})
}
this.subscriptions.clear()
}
private async openConsumer(def: ConsumerDefinition): Promise<AMQPConsumer | AMQPGeneratorConsumer> {
const ch = await this.session.openChannel()
if (def.prefetch !== undefined) {
await ch.basicQos(def.prefetch)
}
return def.callback
? ch.basicConsume(def.queueName, def.consumeParams, def.callback)
: ch.basicConsume(def.queueName, def.consumeParams)
}
}