queen-mq 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,367 @@
1
+ /**
2
+ * The binary push body: an alternative to the JSON body of POST /api/v1/push.
3
+ *
4
+ * "QPB1" | u8 flags | [u32 raw_len, when zstd] | body
5
+ * body: u32 groups | per group: u16 len, queue | u16 len, partition | u32 n
6
+ * | n x ([u16 len, transactionId, when flag 4] | u32 len, payload)
7
+ *
8
+ * All integers little-endian. flags: 1 = the body is one zstd frame of raw_len
9
+ * bytes, 2 = answer with the counts only, 4 = every item carries its
10
+ * transaction id (empty = the broker mints it). No trace id. Each payload is
11
+ * one JSON document.
12
+ *
13
+ * With flag 8 (encodePushFrames) a group is the messages as the broker stores
14
+ * them, compressed here once:
15
+ *
16
+ * body: u32 groups | per group: u16 len, queue | u16 len, partition | u32 n | u32 z_len | z
17
+ * z: one zstd frame of n frames: u32 body_len | u8 0 | u8[16] message id
18
+ * | u16 len, transactionId | payload
19
+ *
20
+ * The message id is a version-7 UUID minted by the client; a message without
21
+ * its own transaction id uses the id's text. The broker checks every frame and
22
+ * keeps the compressed bytes as they are, so it does not compress them again.
23
+ *
24
+ * A broker that does not know this body answers 400; a client sends it only
25
+ * when `binaryPush` is set, so by default a push is the JSON request every
26
+ * broker knows.
27
+ *
28
+ * The binary transaction body (encodeTransactionFrames), an alternative to the
29
+ * JSON body of POST /api/v1/transaction, carries the pushes the same way:
30
+ *
31
+ * "QTB1" | u8 flags | u32 len, head | u32 groups | the groups, as with flag 8 above
32
+ *
33
+ * head is the JSON transaction body without its push operations: the acks in
34
+ * `operations`, `requiredLeases`, `kv`, `timers`. flags: 2 = the answer leaves
35
+ * out the pushes' and the acks' results and counts them (`pushed`,
36
+ * `duplicate`, `acked`); the riders' results stay. In the answer the head's
37
+ * operations come first and the groups' messages after them, in the order
38
+ * written; the riders follow, as in the JSON body.
39
+ */
40
+
41
+ import { v7 as uuidv7 } from 'uuid'
42
+ import { zstdCompress } from './zstd.js'
43
+
44
+ export const PUSH_BINARY_CONTENT_TYPE = 'application/x-queen-push'
45
+
46
+ const MAGIC = Uint8Array.of(0x51, 0x50, 0x42, 0x31) // "QPB1"
47
+ const TXN_MAGIC = Uint8Array.of(0x51, 0x54, 0x42, 0x31) // "QTB1"
48
+ const FLAG_ZSTD = 1
49
+ const FLAG_COUNTS = 2
50
+ const FLAG_TXN = 4
51
+ const FLAG_FRAMES = 8
52
+
53
+ const utf8 = new TextEncoder()
54
+ const HEX = '0123456789abcdef'
55
+
56
+ /** A message does not fit the body: a name or transaction id over 65535 bytes. */
57
+ function tooLong(what) {
58
+ const error = new Error(`${what} longer than 65535 bytes`)
59
+ error.tooLong = true
60
+ return error
61
+ }
62
+
63
+ /** A growing byte buffer; strings are encoded straight into it. */
64
+ class Out {
65
+ constructor(size = 1024) {
66
+ this.bytes = new Uint8Array(size)
67
+ this.view = new DataView(this.bytes.buffer)
68
+ this.length = 0
69
+ }
70
+
71
+ need(extra) {
72
+ if (this.length + extra <= this.bytes.length) return
73
+ const grown = new Uint8Array(Math.max(this.bytes.length * 2, this.length + extra))
74
+ grown.set(this.bytes.subarray(0, this.length))
75
+ this.bytes = grown
76
+ this.view = new DataView(grown.buffer)
77
+ }
78
+
79
+ u8(value) {
80
+ this.need(1)
81
+ this.bytes[this.length++] = value
82
+ }
83
+
84
+ u32(value) {
85
+ this.need(4)
86
+ this.view.setUint32(this.length, value, true)
87
+ this.length += 4
88
+ }
89
+
90
+ /** Four bytes to fill in later with `setU32`; returns where they are. */
91
+ reserveU32() {
92
+ const at = this.length
93
+ this.u32(0)
94
+ return at
95
+ }
96
+
97
+ setU32(at, value) {
98
+ this.view.setUint32(at, value, true)
99
+ }
100
+
101
+ raw(bytes) {
102
+ this.need(bytes.length)
103
+ this.bytes.set(bytes, this.length)
104
+ this.length += bytes.length
105
+ }
106
+
107
+ /** `text` as UTF-8, no length in front; returns its length in bytes. */
108
+ text(text) {
109
+ this.need(text.length * 3)
110
+ const { written } = utf8.encodeInto(text, this.bytes.subarray(this.length))
111
+ this.length += written
112
+ return written
113
+ }
114
+
115
+ /** `text` with its u16 length in front. */
116
+ text16(text, what) {
117
+ this.need(2)
118
+ const at = this.length
119
+ this.length += 2
120
+ const written = this.text(text)
121
+ if (written > 0xffff) throw tooLong(what)
122
+ this.view.setUint16(at, written, true)
123
+ }
124
+
125
+ /** `text` with its u32 length in front. */
126
+ text32(text) {
127
+ const at = this.reserveU32()
128
+ this.setU32(at, this.text(text))
129
+ }
130
+
131
+ done() {
132
+ return this.bytes.subarray(0, this.length)
133
+ }
134
+ }
135
+
136
+ function checkBatch(batch) {
137
+ if (batch.transactionIds && batch.transactionIds.length !== batch.payloads.length) {
138
+ throw new Error(`${batch.transactionIds.length} transaction ids for ${batch.payloads.length} payloads`)
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Encode batches as a binary push body.
144
+ *
145
+ * @param {Array<{queue: string, partition: string, payloads: string[], transactionIds?: string[]}>} batches
146
+ * one partition's messages each; a payload is the text of one JSON document,
147
+ * and transactionIds, when given, holds one per payload ('' = the broker
148
+ * mints it)
149
+ * @param {object} [options]
150
+ * @param {boolean} [options.compress=false] the body is zstd-compressed
151
+ * @param {boolean} [options.counts=false] the broker answers
152
+ * `{count, queued, duplicate, error}` instead of one object per message
153
+ * @returns {Promise<Uint8Array>}
154
+ */
155
+ export async function encodePushBinary(batches, { compress = false, counts = false } = {}) {
156
+ const withTxn = batches.some(batch => batch.transactionIds)
157
+ const flags = (counts ? FLAG_COUNTS : 0) | (withTxn ? FLAG_TXN : 0)
158
+ const body = new Out()
159
+ body.u32(batches.length)
160
+ for (const batch of batches) {
161
+ checkBatch(batch)
162
+ body.text16(batch.queue, 'queue name')
163
+ body.text16(batch.partition, 'partition name')
164
+ body.u32(batch.payloads.length)
165
+ for (let i = 0; i < batch.payloads.length; i++) {
166
+ if (withTxn) body.text16(batch.transactionIds ? batch.transactionIds[i] : '', 'transaction id')
167
+ body.text32(batch.payloads[i])
168
+ }
169
+ }
170
+
171
+ const out = new Out(MAGIC.length + 5 + (compress ? 0 : body.length))
172
+ out.raw(MAGIC)
173
+ if (!compress) {
174
+ out.u8(flags)
175
+ out.raw(body.done())
176
+ return out.done()
177
+ }
178
+ out.u8(flags | FLAG_ZSTD)
179
+ out.u32(body.length)
180
+ out.raw(await zstdCompress(body.done()))
181
+ return out.done()
182
+ }
183
+
184
+ /**
185
+ * Encode batches as a binary push body whose groups are the messages framed
186
+ * as the broker stores them and compressed once, here. Same batches as
187
+ * `encodePushBinary`; `counts` asks for the short answer.
188
+ *
189
+ * @returns {Promise<Uint8Array>}
190
+ */
191
+ export async function encodePushFrames(batches, { counts = false } = {}) {
192
+ const out = new Out()
193
+ out.raw(MAGIC)
194
+ out.u8(FLAG_FRAMES | (counts ? FLAG_COUNTS : 0))
195
+ return appendFrameGroups(out, batches)
196
+ }
197
+
198
+ /**
199
+ * Encode a binary transaction body: `head`, the JSON transaction body without
200
+ * its push operations (its text; empty for none), then batches as groups of
201
+ * messages framed as the broker stores them and compressed once, here.
202
+ * `counts`: the broker counts the pushes and the acks in its answer instead of
203
+ * rendering one result for each.
204
+ *
205
+ * @returns {Promise<Uint8Array>}
206
+ */
207
+ export async function encodeTransactionFrames(head, batches, { counts = false } = {}) {
208
+ const out = new Out()
209
+ out.raw(TXN_MAGIC)
210
+ out.u8(counts ? FLAG_COUNTS : 0)
211
+ out.text32(head || '')
212
+ return appendFrameGroups(out, batches)
213
+ }
214
+
215
+ /**
216
+ * Appends `u32 groups | per group: u16 len, queue | u16 len, partition | u32 n
217
+ * | u32 z_len | z` to `out`: each batch's messages framed as the broker stores
218
+ * them, with a version-7 id minted here, as one zstd frame.
219
+ */
220
+ async function appendFrameGroups(out, batches) {
221
+ out.u32(batches.length)
222
+ const frames = new Out()
223
+ for (const batch of batches) {
224
+ checkBatch(batch)
225
+ frames.length = 0
226
+ for (let i = 0; i < batch.payloads.length; i++) {
227
+ const bodyLength = frames.reserveU32()
228
+ frames.u8(0)
229
+ frames.need(16)
230
+ const id = frames.length
231
+ uuidv7(undefined, frames.bytes, id)
232
+ frames.length += 16
233
+ const txn = batch.transactionIds ? batch.transactionIds[i] : ''
234
+ frames.text16(txn || uuidText(frames.bytes, id), 'transaction id')
235
+ frames.text(batch.payloads[i])
236
+ frames.setU32(bodyLength, frames.length - bodyLength - 4)
237
+ }
238
+ out.text16(batch.queue, 'queue name')
239
+ out.text16(batch.partition, 'partition name')
240
+ out.u32(batch.payloads.length)
241
+ const compressed = await zstdCompress(frames.done())
242
+ out.u32(compressed.length)
243
+ out.raw(compressed)
244
+ }
245
+ return out.done()
246
+ }
247
+
248
+ /** The lower-case hyphenated text of the 16 id bytes at `at`. */
249
+ export function uuidText(bytes, at = 0) {
250
+ let text = ''
251
+ for (let i = 0; i < 16; i++) {
252
+ if (i === 4 || i === 6 || i === 8 || i === 10) text += '-'
253
+ const byte = bytes[at + i]
254
+ text += HEX[byte >> 4] + HEX[byte & 0x0f]
255
+ }
256
+ return text
257
+ }
258
+
259
+ /**
260
+ * The items of a JSON push (`{queue, partition, payload, transactionId}`) as a
261
+ * binary push body, or null when one of them cannot travel in it: a trace id,
262
+ * a transaction id that is not a string, a payload JSON does not carry, a name
263
+ * over 65535 bytes. The caller then sends the JSON body, and the broker
264
+ * answers that as it always did. Consecutive items of one partition share a
265
+ * group, so the order of the items is the order on the wire.
266
+ *
267
+ * `compress`: the messages framed and compressed here, kept by the broker as
268
+ * they are.
269
+ */
270
+ export async function binaryPushBody(items, compress) {
271
+ if (items.length === 0) return null
272
+ const batches = []
273
+ for (const item of items) {
274
+ if (!addItem(batches, item)) return null
275
+ }
276
+ try {
277
+ return compress ? await encodePushFrames(batches) : await encodePushBinary(batches)
278
+ } catch (error) {
279
+ // A name too long for the body: the JSON push says so in the broker's words.
280
+ if (error.tooLong) return null
281
+ throw error
282
+ }
283
+ }
284
+
285
+ /**
286
+ * Adds one pushed item to `batches`, in the last one when it is the same
287
+ * partition's. False when the item cannot travel in a binary body.
288
+ */
289
+ function addItem(batches, item) {
290
+ if (!item || typeof item !== 'object' || typeof item.queue !== 'string') return false
291
+ if (item.traceId !== undefined && item.traceId !== null) return false
292
+ const transactionId = item.transactionId ?? ''
293
+ if (typeof transactionId !== 'string') return false
294
+ const partition = item.partition ?? 'Default'
295
+ if (typeof partition !== 'string') return false
296
+ const payload = JSON.stringify(item.payload)
297
+ if (payload === undefined) return false
298
+ let last = batches[batches.length - 1]
299
+ if (!last || last.queue !== item.queue || last.partition !== partition) {
300
+ last = { queue: item.queue, partition, payloads: [], transactionIds: [] }
301
+ batches.push(last)
302
+ }
303
+ last.payloads.push(payload)
304
+ last.transactionIds.push(transactionId)
305
+ return true
306
+ }
307
+
308
+ /**
309
+ * A JSON transaction body (`{operations, requiredLeases, kv, timers}`) as the
310
+ * binary one, when its pushes can travel in it: there is at least one, and
311
+ * none carries a trace id. Everything but the pushes stays in the JSON head;
312
+ * consecutive pushed items of one partition share a group, so the pushes keep
313
+ * their order. Null otherwise: the caller then sends the JSON body.
314
+ *
315
+ * `order` is null when the broker's answer lists the operations as the caller
316
+ * added them (every other operation before every push). Otherwise `order[k]`
317
+ * is the place, among the caller's operations, of the k-th result the broker
318
+ * sends: it lists the head's operations first, then the pushes.
319
+ *
320
+ * @returns {Promise<{body: Uint8Array, order: number[]|null}|null>}
321
+ */
322
+ export async function transactionFrames(request) {
323
+ if (!request || typeof request !== 'object' || !Array.isArray(request.operations)) return null
324
+ const head = { ...request, operations: [] }
325
+ const batches = []
326
+ const headAt = []
327
+ const pushAt = []
328
+ let flat = 0
329
+ for (const operation of request.operations) {
330
+ if (!operation || operation.type !== 'push') {
331
+ head.operations.push(operation)
332
+ headAt.push(flat++)
333
+ continue
334
+ }
335
+ // A push names its items, or is one item itself.
336
+ const items = Array.isArray(operation.items) ? operation.items : [operation]
337
+ for (const item of items) {
338
+ if (!addItem(batches, item)) return null
339
+ pushAt.push(flat++)
340
+ }
341
+ }
342
+ if (batches.length === 0) return null
343
+ let body
344
+ try {
345
+ body = await encodeTransactionFrames(JSON.stringify(head), batches)
346
+ } catch (error) {
347
+ if (error.tooLong) return null
348
+ throw error
349
+ }
350
+ const order = [...headAt, ...pushAt]
351
+ return { body, order: order.every((at, k) => at === k) ? null : order }
352
+ }
353
+
354
+ /**
355
+ * Puts the results of a binary transaction back in the order the caller added
356
+ * its operations in, and gives each its own index again. The riders' results,
357
+ * after the operations', are already in place.
358
+ */
359
+ export function restoreResultOrder(answer, order) {
360
+ if (!order || !answer || !Array.isArray(answer.results) || answer.results.length < order.length) return
361
+ const results = answer.results.slice()
362
+ order.forEach((at, k) => {
363
+ const result = answer.results[k]
364
+ results[at] = result && typeof result === 'object' ? { ...result, index: at } : result
365
+ })
366
+ answer.results = results
367
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * zstd for the binary push body and the framed pop answer.
3
+ *
4
+ * It comes from node:zlib (Node 22.15 and later), loaded on first use through
5
+ * a guarded dynamic import, as HttpClient loads undici: a bundle for a runtime
6
+ * without it still loads, and fails only when a push is compressed or a framed
7
+ * pop holds a compressed record.
8
+ */
9
+
10
+ let loading = null
11
+
12
+ async function load() {
13
+ if (loading === null) {
14
+ loading = import('node:zlib').then(
15
+ (zlib) => (typeof zlib.zstdCompressSync === 'function' && typeof zlib.zstdDecompressSync === 'function' ? zlib : null),
16
+ () => null
17
+ )
18
+ }
19
+ const zlib = await loading
20
+ if (!zlib) {
21
+ throw new Error('zstd is not available in this runtime (node:zlib of Node 22.15 or later): pushCompression and framedPop need it')
22
+ }
23
+ return zlib
24
+ }
25
+
26
+ /**
27
+ * One zstd frame of `raw`, at the fastest level. The frame carries its content
28
+ * size, which the broker asks of a frame it stores as it came.
29
+ */
30
+ export async function zstdCompress(raw) {
31
+ const zlib = await load()
32
+ return zlib.zstdCompressSync(raw, {
33
+ params: { [zlib.constants.ZSTD_c_compressionLevel]: 1 },
34
+ pledgedSrcSize: raw.length
35
+ })
36
+ }
37
+
38
+ export async function zstdDecompress(frame) {
39
+ const zlib = await load()
40
+ return zlib.zstdDecompressSync(frame)
41
+ }
@@ -36,7 +36,23 @@ export const CLIENT_DEFAULTS = {
36
36
  // retries unboundedly (paced by backoff) unless maxAttempts is set here, in
37
37
  // which case it applies to both. baseMs (500) / capMs (30000) size the
38
38
  // exponential backoff used when the server doesn't send Retry-After.
39
- retry429: undefined
39
+ retry429: undefined,
40
+ // The three below need a broker that has the binary push body and the framed
41
+ // pop answer. Off, the client sends and reads the JSON every broker knows.
42
+ //
43
+ // binaryPush: a push goes out as the binary push body (http/pushBinary.js)
44
+ // instead of JSON. Items with a trace id stay JSON.
45
+ binaryPush: false,
46
+ // pushCompression (with binaryPush): the client frames the messages as the
47
+ // broker stores them, mints their ids and zstd-compresses each partition's
48
+ // batch once; the broker keeps those bytes as they are. A transaction that
49
+ // pushes sends its pushes the same way, and the rest of the bundle as JSON
50
+ // in front of them.
51
+ pushCompression: false,
52
+ // framedPop: pops ask for the messages as the stored records (frames=true)
53
+ // and unpack them here (http/popFrames.js). A broker that does not know the
54
+ // parameter answers JSON, which is read as always.
55
+ framedPop: false
40
56
  }
41
57
 
42
58
  export const QUEUE_DEFAULTS = {
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "queen-mq",
3
- "version": "2.1.0",
3
+ "version": "2.3.0",
4
4
  "type": "module",
5
5
  "description": "Partitioned message queue on a replicated broker log — broker client + fluent streaming SDK (windows, joins, gates) in one package",
6
6
  "main": "client-v2/index.js",
7
7
  "scripts": {
8
8
  "test": "npm run test:unit && node test-v2/run.js human",
9
- "test:unit": "node --test test-v2/streams-unit/configHash.test.js test-v2/streams-unit/operators.test.js test-v2/streams-unit/cycle.test.js test-v2/streams-unit/eventTime.test.js test-v2/streams-unit/ack.test.js test-v2/streams-unit/gate.test.js test-v2/http-unit/retry429.test.js test-v2/http-unit/hostHeader.test.js test-v2/http-unit/pushStatus.test.js test-v2/http-unit/renew.test.js test-v2/consumer-unit/handlerError.test.js test-v2/consumer-unit/nackScope.test.js test-v2/consumer-unit/stopOnAbort.test.js test-v2/kv-unit/kvWire.test.js test-v2/kv-unit/timerWire.test.js test-v2/kv-unit/txnWire.test.js test-v2/kv-unit/locksWire.test.js test-v2/buffer-unit/buffer.test.js test-v2/conflation-unit/conflationWire.test.js test-v2/autopilot-unit/autopilotWire.test.js test-v2/ephemeral-unit/ephemeralWire.test.js test-v2/ephemeral-unit/ephemeralBuffer.test.js test-v2/ephemeral-unit/durableSinkPin.test.js test-v2/runner-unit/fatalExit.test.js test-v2/pop-unit/popDefaults.test.js test-v2/admin-unit/removedRoutes.test.js test-v2/consumer-unit/supervision.test.js",
9
+ "test:unit": "node --test test-v2/streams-unit/configHash.test.js test-v2/streams-unit/operators.test.js test-v2/streams-unit/cycle.test.js test-v2/streams-unit/eventTime.test.js test-v2/streams-unit/ack.test.js test-v2/streams-unit/gate.test.js test-v2/http-unit/retry429.test.js test-v2/http-unit/hostHeader.test.js test-v2/http-unit/pushStatus.test.js test-v2/http-unit/renew.test.js test-v2/consumer-unit/handlerError.test.js test-v2/consumer-unit/nackScope.test.js test-v2/consumer-unit/stopOnAbort.test.js test-v2/kv-unit/kvWire.test.js test-v2/kv-unit/timerWire.test.js test-v2/kv-unit/txnWire.test.js test-v2/kv-unit/locksWire.test.js test-v2/buffer-unit/buffer.test.js test-v2/conflation-unit/conflationWire.test.js test-v2/autopilot-unit/autopilotWire.test.js test-v2/ephemeral-unit/ephemeralWire.test.js test-v2/ephemeral-unit/ephemeralBuffer.test.js test-v2/ephemeral-unit/durableSinkPin.test.js test-v2/runner-unit/fatalExit.test.js test-v2/pop-unit/popDefaults.test.js test-v2/admin-unit/removedRoutes.test.js test-v2/consumer-unit/supervision.test.js test-v2/wire-unit/pushBinary.test.js test-v2/wire-unit/popFrames.test.js test-v2/wire-unit/transactionFrames.test.js",
10
10
  "test:unit:e2e": "node --test test-v2/streams-unit/e2e.test.js",
11
11
  "test:integration": "node test-v2/run.js human",
12
12
  "test:streams": "node test-v2/run.js stream",
@@ -0,0 +1,47 @@
1
+ /**
2
+ * A real node:http server for the binary wire forms: it records every request
3
+ * with its body as bytes (kv-unit/_planServer.js reads bodies as text, which a
4
+ * binary push body does not survive) and answers what `answer(hit)` returns:
5
+ * `{ status, contentType, body }`, body a Buffer or a string.
6
+ */
7
+
8
+ import { createServer } from 'node:http'
9
+
10
+ export function withWireServer(answer, run) {
11
+ const hits = []
12
+
13
+ const server = createServer((req, res) => {
14
+ const chunks = []
15
+ req.on('data', chunk => chunks.push(chunk))
16
+ req.on('end', () => {
17
+ const hit = { method: req.method, url: req.url, headers: req.headers, raw: Buffer.concat(chunks) }
18
+ hits.push(hit)
19
+ const { status = 200, contentType = 'application/json', body = '' } = answer(hit) || {}
20
+ if (status === 204) {
21
+ res.writeHead(204)
22
+ res.end()
23
+ return
24
+ }
25
+ res.writeHead(status, { 'Content-Type': contentType })
26
+ res.end(body)
27
+ })
28
+ })
29
+
30
+ return new Promise((resolve, reject) => {
31
+ server.listen(0, '127.0.0.1', () => {
32
+ const { port } = server.address()
33
+ const teardown = () => new Promise(r => server.close(r))
34
+ Promise.resolve()
35
+ .then(() => run(`http://127.0.0.1:${port}`, hits))
36
+ .then(
37
+ async (value) => { await teardown(); resolve(value) },
38
+ async (err) => { await teardown(); reject(err) }
39
+ )
40
+ })
41
+ })
42
+ }
43
+
44
+ export function query(url) {
45
+ const i = url.indexOf('?')
46
+ return new URLSearchParams(i < 0 ? '' : url.slice(i + 1))
47
+ }