tina4-nodejs 3.13.157 → 3.13.158

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.
@@ -12,6 +12,19 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
12
12
  * Implements the same interface as the file-based queue but uses Apache Kafka
13
13
  * for message storage and delivery.
14
14
  *
15
+ * The queue API is synchronous, but a durable Kafka consumer needs a PERSISTENT
16
+ * connection that holds an in-memory read cursor and commits consumer-group
17
+ * offsets (ADR-0022 decision 8: the correct fix is "a persistent connection held
18
+ * on the backend instance, the way Python, PHP and Ruby already do it"). Node
19
+ * sockets are async, so the connection lives in a worker thread with its own
20
+ * event loop; the main thread drives it synchronously via a SharedArrayBuffer +
21
+ * Atomics.wait. The worker owns the broker socket, the group-coordinator socket,
22
+ * the per-topic read cursor, and the in-flight map (job id -> record offset) so
23
+ * complete()/fail()/reject()/retry() commit exactly the right record. This
24
+ * replaces the previous stateless child-process-per-operation design, which
25
+ * could not keep a cursor, always fetched offset 0, and never committed — so it
26
+ * replayed the whole topic on every call and every restart.
27
+ *
15
28
  * Configure via environment variables:
16
29
  * TINA4_QUEUE_URL — broker list (strips a leading kafka:// if present)
17
30
  * TINA4_KAFKA_BROKERS (override; default: "localhost:9092")
@@ -25,8 +38,7 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
25
38
  * Precedence for brokers: specific TINA4_KAFKA_BROKERS var (if set)
26
39
  * > value derived from TINA4_QUEUE_URL > existing default.
27
40
  */
28
- import net from "node:net";
29
- import { execFileSync } from "node:child_process";
41
+ import { Worker } from "node:worker_threads";
30
42
  import { randomUUID } from "node:crypto";
31
43
  import type { QueueJob } from "../queue.js";
32
44
 
@@ -109,8 +121,6 @@ export function kafkaSecurityConfig(
109
121
  * convention name (`KAFKA_AUTO_OFFSET_RESET`) — the same precedence the TLS/SASL
110
122
  * keys use. A blank value falls through to the default (tina4-nodejs#263).
111
123
  *
112
- * Surfaced on the declared consumer config for parity/introspection; this
113
- * backend reads records over the raw protocol from the earliest retained offset.
114
124
  * Mirrors Python's `KafkaConnector._offset_reset`.
115
125
  */
116
126
  export function kafkaOffsetReset(env: NodeJS.ProcessEnv = process.env): string {
@@ -124,77 +134,585 @@ export interface QueueBackend {
124
134
  clear(queue: string): void;
125
135
  }
126
136
 
127
- // ── Kafka Protocol Constants ─────────────────────────────────
137
+ /**
138
+ * The worker source (plain JS, run via `new Worker(src, { eval: true })`). It
139
+ * owns the sockets, the per-topic read cursor, and the in-flight map, speaks the
140
+ * Kafka wire protocol by hand (Produce v3 + v2 RecordBatch + CRC-32C, Fetch v4,
141
+ * FindCoordinator v1, OffsetFetch v1, OffsetCommit v2 — the lowest non-flexible
142
+ * versions, matching the PHP/Python backends), and answers one request at a time
143
+ * over a SharedArrayBuffer. No backticks / ${} inside so it embeds cleanly.
144
+ */
145
+ const WORKER_SRC = `
146
+ const net = require("node:net");
147
+ const tls = require("node:tls");
148
+ const { parentPort, workerData } = require("node:worker_threads");
149
+
150
+ const brokers = workerData.brokers;
151
+ const groupId = workerData.groupId;
152
+ const security = workerData.security || {};
153
+ const offsetReset = workerData.offsetReset || "earliest";
154
+ const header = new Int32Array(workerData.sab, 0, 2); // [0]=flag, [1]=respLen
155
+ const outBytes = new Uint8Array(workerData.sab, 8);
156
+
157
+ // Lowest versions Kafka 4.x still accepts: it REMOVED Produce v0-v2 / Fetch v0-v3
158
+ // (the old message formats) and answers a removed version by closing the socket,
159
+ // not with an error code. These are named constants so the source invariant test
160
+ // (test/kafkaErrorCodes.test.ts) can assert the floors.
161
+ const PRODUCE_VERSION = 3;
162
+ const FETCH_VERSION = 4;
163
+
164
+ let correlationId = 0;
165
+ let brokerSock = null;
166
+ let coordSock = null;
167
+ const offsets = {}; // topic -> next read offset (in-memory cursor)
168
+ const inFlight = {}; // job id -> { offset, value, attempts, isEnvelope }
169
+
170
+ const COORDINATOR_ERRORS = [14, 15, 16];
171
+
172
+ function parseBroker(list) {
173
+ const first = String(list).split(",")[0].trim();
174
+ const i = first.lastIndexOf(":");
175
+ if (i < 0) return { host: first || "localhost", port: 9092 };
176
+ return { host: first.slice(0, i) || "localhost", port: parseInt(first.slice(i + 1), 10) || 9092 };
177
+ }
178
+
179
+ function connect(host, port) {
180
+ return new Promise(function (resolve, reject) {
181
+ const proto = String(security["security.protocol"] || "PLAINTEXT").toUpperCase();
182
+ const useTls = proto.indexOf("SSL") >= 0;
183
+ let sock;
184
+ const onErr = function (e) { reject(e); };
185
+ if (useTls) {
186
+ const opts = { host: host, port: port, servername: host };
187
+ if (security["ssl.ca.location"]) opts.ca = require("node:fs").readFileSync(security["ssl.ca.location"]);
188
+ sock = tls.connect(opts, function () { sock.removeListener("error", onErr); resolve(sock); });
189
+ } else {
190
+ sock = net.createConnection({ host: host, port: port }, function () { sock.removeListener("error", onErr); resolve(sock); });
191
+ }
192
+ sock.once("error", onErr);
193
+ });
194
+ }
195
+
196
+ // One request/response round trip on a socket: write the framed request, read a
197
+ // 4-byte length then that many bytes, resolve with the payload AFTER the length
198
+ // (so it starts at correlationId). Serialized — one in flight per socket.
199
+ function rpc(sock, reqBuf) {
200
+ return new Promise(function (resolve, reject) {
201
+ let buf = Buffer.alloc(0);
202
+ function onData(chunk) {
203
+ buf = Buffer.concat([buf, chunk]);
204
+ if (buf.length < 4) return;
205
+ const size = buf.readInt32BE(0);
206
+ if (buf.length < 4 + size) return;
207
+ sock.removeListener("data", onData);
208
+ sock.removeListener("error", onErr);
209
+ resolve(buf.subarray(4, 4 + size));
210
+ }
211
+ function onErr(e) {
212
+ sock.removeListener("data", onData);
213
+ reject(e);
214
+ }
215
+ sock.on("data", onData);
216
+ sock.once("error", onErr);
217
+ sock.write(reqBuf);
218
+ });
219
+ }
128
220
 
129
- const API_PRODUCE = 0;
130
- const API_FETCH = 1;
131
- const API_LIST_OFFSETS = 2;
132
- const API_METADATA = 3;
133
- const API_OFFSET_COMMIT = 8;
134
- const API_OFFSET_FETCH = 9;
135
- const API_FIND_COORDINATOR = 10;
136
- const API_JOIN_GROUP = 11;
137
- const API_HEARTBEAT = 12;
138
- const API_LEAVE_GROUP = 13;
139
- const API_SYNC_GROUP = 14;
221
+ // ── encoders ──────────────────────────────────────────────────────────────
222
+ function kstr(s) {
223
+ const b = Buffer.from(s, "utf-8");
224
+ const out = Buffer.alloc(2 + b.length);
225
+ out.writeInt16BE(b.length, 0);
226
+ b.copy(out, 2);
227
+ return out;
228
+ }
229
+ function frame(apiKey, apiVersion, body) {
230
+ correlationId++;
231
+ const client = Buffer.from("tina4-nodejs", "utf-8");
232
+ const head = Buffer.alloc(2 + 2 + 4 + 2 + client.length);
233
+ let p = 0;
234
+ head.writeInt16BE(apiKey, p); p += 2;
235
+ head.writeInt16BE(apiVersion, p); p += 2;
236
+ head.writeInt32BE(correlationId, p); p += 4;
237
+ head.writeInt16BE(client.length, p); p += 2;
238
+ client.copy(head, p);
239
+ const payload = Buffer.concat([head, body]);
240
+ const out = Buffer.alloc(4 + payload.length);
241
+ out.writeInt32BE(payload.length, 0);
242
+ payload.copy(out, 4);
243
+ return out;
244
+ }
245
+
246
+ // ── CRC-32C + varints + v2 RecordBatch (produce) ────────────────────────────
247
+ const CRC32C_TABLE = (function () {
248
+ const t = new Uint32Array(256);
249
+ for (let n = 0; n < 256; n++) {
250
+ let c = n;
251
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
252
+ t[n] = c >>> 0;
253
+ }
254
+ return t;
255
+ })();
256
+ function crc32c(buf) {
257
+ let crc = 0xffffffff;
258
+ for (let i = 0; i < buf.length; i++) crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
259
+ return (crc ^ 0xffffffff) >>> 0;
260
+ }
261
+ function zig(n) { return ((n << 1) ^ (n >> 31)) >>> 0; }
262
+ function varU(u) {
263
+ const b = [];
264
+ let v = u >>> 0;
265
+ for (;;) { if ((v & ~0x7f) === 0) { b.push(v); break; } b.push((v & 0x7f) | 0x80); v >>>= 7; }
266
+ return Buffer.from(b);
267
+ }
268
+ function varint(n) { return varU(zig(n)); }
269
+ function readVarint(buf, pos) {
270
+ let result = 0, shift = 0, b;
271
+ do { b = buf[pos++]; result |= (b & 0x7f) << shift; shift += 7; } while (b & 0x80);
272
+ result = result >>> 0;
273
+ return { value: (result >>> 1) ^ -(result & 1), next: pos };
274
+ }
275
+ function buildRecordBatch(valueBytes) {
276
+ const now = BigInt(Date.now());
277
+ const recBody = Buffer.concat([
278
+ Buffer.from([0]), varint(0), varint(0), varint(-1),
279
+ varint(valueBytes.length), valueBytes, varint(0),
280
+ ]);
281
+ const record = Buffer.concat([varint(recBody.length), recBody]);
282
+ const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
283
+ let c = 0;
284
+ crcBody.writeInt16BE(0, c); c += 2;
285
+ crcBody.writeInt32BE(0, c); c += 4;
286
+ crcBody.writeBigInt64BE(now, c); c += 8;
287
+ crcBody.writeBigInt64BE(now, c); c += 8;
288
+ crcBody.writeBigInt64BE(-1n, c); c += 8;
289
+ crcBody.writeInt16BE(-1, c); c += 2;
290
+ crcBody.writeInt32BE(-1, c); c += 4;
291
+ crcBody.writeInt32BE(1, c); c += 4;
292
+ record.copy(crcBody, c);
293
+ const crc = crc32c(crcBody);
294
+ const batchLength = 4 + 1 + 4 + crcBody.length;
295
+ const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
296
+ let h = 0;
297
+ head.writeBigInt64BE(0n, h); h += 8;
298
+ head.writeInt32BE(batchLength, h); h += 4;
299
+ head.writeInt32BE(-1, h); h += 4;
300
+ head.writeInt8(2, h); h += 1;
301
+ head.writeUInt32BE(crc, h); h += 4;
302
+ return Buffer.concat([head, crcBody]);
303
+ }
304
+
305
+ // ── produce ─────────────────────────────────────────────────────────────────
306
+ function produceRequest(topic, valueBytes) {
307
+ const topicBuf = Buffer.from(topic, "utf-8");
308
+ const batch = buildRecordBatch(valueBytes);
309
+ const body = Buffer.alloc(2 + 2 + 4 + 4 + 2 + topicBuf.length + 4 + 4 + 4 + batch.length);
310
+ let p = 0;
311
+ body.writeInt16BE(-1, p); p += 2; // transactionalId null
312
+ body.writeInt16BE(1, p); p += 2; // acks 1
313
+ body.writeInt32BE(10000, p); p += 4; // timeoutMs
314
+ body.writeInt32BE(1, p); p += 4; // topics
315
+ body.writeInt16BE(topicBuf.length, p); p += 2;
316
+ topicBuf.copy(body, p); p += topicBuf.length;
317
+ body.writeInt32BE(1, p); p += 4; // partitions
318
+ body.writeInt32BE(0, p); p += 4; // partition 0
319
+ body.writeInt32BE(batch.length, p); p += 4;
320
+ batch.copy(body, p);
321
+ return frame(0, PRODUCE_VERSION, body);
322
+ }
323
+ function parseProduce(resp) {
324
+ let pos = 4; // correlationId
325
+ const topicCount = resp.readInt32BE(pos); pos += 4;
326
+ let err = 0;
327
+ for (let t = 0; t < topicCount; t++) {
328
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
329
+ const pc = resp.readInt32BE(pos); pos += 4;
330
+ for (let pi = 0; pi < pc; pi++) {
331
+ pos += 4; err = resp.readInt16BE(pos); pos += 2; pos += 8; pos += 8;
332
+ }
333
+ }
334
+ return err;
335
+ }
336
+ async function produce(topic, valueBytes) {
337
+ const sock = await broker();
338
+ for (let attempt = 1; attempt <= 10; attempt++) {
339
+ const err = parseProduce(await rpc(sock, produceRequest(topic, valueBytes)));
340
+ if (err === 0) return;
341
+ if ((err !== 3 && err !== 5) || attempt === 10) {
342
+ throw new Error("Kafka rejected the produce for topic " + topic + ": error code " + err);
343
+ }
344
+ await sleep(200);
345
+ }
346
+ }
140
347
 
141
- // ── Kafka Backend ────────────────────────────────────────────
348
+ // ── fetch ─────────────────────────────────────────────────────────────────
349
+ function fetchRequest(topic, offset) {
350
+ const topicBuf = Buffer.from(topic, "utf-8");
351
+ const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + 2 + topicBuf.length + 4 + 4 + 8 + 4);
352
+ let p = 0;
353
+ buf.writeInt32BE(-1, p); p += 4; // replicaId
354
+ buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
355
+ buf.writeInt32BE(1, p); p += 4; // minBytes
356
+ buf.writeInt32BE(1048576, p); p += 4; // maxBytes
357
+ buf.writeInt8(0, p); p += 1; // isolation READ_UNCOMMITTED
358
+ buf.writeInt32BE(1, p); p += 4; // topics
359
+ buf.writeInt16BE(topicBuf.length, p); p += 2;
360
+ topicBuf.copy(buf, p); p += topicBuf.length;
361
+ buf.writeInt32BE(1, p); p += 4; // partitions
362
+ buf.writeInt32BE(0, p); p += 4; // partition 0
363
+ buf.writeBigInt64BE(BigInt(offset), p); p += 8;
364
+ buf.writeInt32BE(1048576, p); p += 4;
365
+ return frame(1, FETCH_VERSION, buf);
366
+ }
367
+ // Decode the first record of the partition's record-set: its value string and
368
+ // absolute offset (baseOffset + offsetDelta). null = no usable record.
369
+ function firstRecord(buf, start, end) {
370
+ let pos = start;
371
+ while (pos + 12 <= end) {
372
+ const baseOffset = buf.readBigInt64BE(pos);
373
+ const batchLength = buf.readInt32BE(pos + 8);
374
+ const batchStart = pos + 12;
375
+ const batchEnd = batchStart + batchLength;
376
+ if (batchLength <= 0 || batchEnd > end) break;
377
+ const magic = buf.readInt8(batchStart + 4);
378
+ if (magic !== 2) { pos = batchEnd; continue; }
379
+ let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
380
+ const recordsCount = buf.readInt32BE(r); r += 4;
381
+ for (let i = 0; i < recordsCount && r < batchEnd; i++) {
382
+ const recLen = readVarint(buf, r);
383
+ let rp = recLen.next;
384
+ const recordEnd = rp + recLen.value;
385
+ rp += 1;
386
+ rp = readVarint(buf, rp).next; // timestampDelta
387
+ const offDelta = readVarint(buf, rp); rp = offDelta.next;
388
+ const keyLen = readVarint(buf, rp); rp = keyLen.next;
389
+ if (keyLen.value >= 0) rp += keyLen.value;
390
+ const valLen = readVarint(buf, rp); rp = valLen.next;
391
+ if (valLen.value >= 0) {
392
+ return {
393
+ value: buf.subarray(rp, rp + valLen.value).toString("utf-8"),
394
+ offset: Number(baseOffset) + offDelta.value,
395
+ };
396
+ }
397
+ r = recordEnd;
398
+ }
399
+ pos = batchEnd;
400
+ }
401
+ return null;
402
+ }
403
+ async function fetchAt(topic, offset) {
404
+ const sock = await broker();
405
+ const resp = await rpc(sock, fetchRequest(topic, offset));
406
+ let pos = 4; // correlationId
407
+ pos += 4; // throttleTimeMs
408
+ const topicCount = resp.readInt32BE(pos); pos += 4;
409
+ let rec = null;
410
+ for (let t = 0; t < topicCount; t++) {
411
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
412
+ const pc = resp.readInt32BE(pos); pos += 4;
413
+ for (let pi = 0; pi < pc; pi++) {
414
+ pos += 4;
415
+ const err = resp.readInt16BE(pos); pos += 2;
416
+ pos += 8; pos += 8;
417
+ const aborted = resp.readInt32BE(pos); pos += 4;
418
+ if (aborted > 0) pos += aborted * 16;
419
+ const recSize = resp.readInt32BE(pos); pos += 4;
420
+ if (err !== 0 && err !== 3 && err !== 5) {
421
+ throw new Error("Kafka rejected the fetch for topic " + topic + ": error code " + err);
422
+ }
423
+ if (err === 0 && recSize > 0) {
424
+ const r = firstRecord(resp, pos, pos + recSize);
425
+ if (r !== null) rec = r;
426
+ }
427
+ if (recSize > 0) pos += recSize;
428
+ }
429
+ }
430
+ return rec;
431
+ }
432
+
433
+ // ── coordinator + offsets ───────────────────────────────────────────────────
434
+ function readNullableString(buf, pos) {
435
+ const len = buf.readInt16BE(pos); pos += 2;
436
+ if (len < 0) return { value: null, next: pos };
437
+ return { value: buf.toString("utf-8", pos, pos + len), next: pos + len };
438
+ }
439
+ async function findCoordinator() {
440
+ const sock = await broker();
441
+ for (let attempt = 0; attempt < 30; attempt++) {
442
+ const body = Buffer.concat([kstr(groupId), Buffer.from([0])]); // key_type 0 = group
443
+ const resp = await rpc(sock, frame(10, 1, body));
444
+ let pos = 4; // correlationId
445
+ pos += 4; // throttle
446
+ const err = resp.readInt16BE(pos); pos += 2;
447
+ pos = readNullableString(resp, pos).next; // error_message
448
+ pos += 4; // node_id
449
+ const hostRes = readNullableString(resp, pos); pos = hostRes.next;
450
+ const port = resp.readInt32BE(pos);
451
+ if (err === 0 && hostRes.value) return { host: hostRes.value, port: port };
452
+ if (err !== 14 && err !== 15) {
453
+ throw new Error("Kafka FindCoordinator failed for group " + groupId + ": error code " + err);
454
+ }
455
+ await sleep(300);
456
+ }
457
+ throw new Error("Kafka group coordinator for " + groupId + " did not become available");
458
+ }
459
+ async function coordinator() {
460
+ if (coordSock) return coordSock;
461
+ const c = await findCoordinator();
462
+ coordSock = await connect(c.host, c.port);
463
+ return coordSock;
464
+ }
465
+ function dropCoordinator() {
466
+ if (coordSock) { try { coordSock.destroy(); } catch (e) { /* ignore */ } }
467
+ coordSock = null;
468
+ }
469
+ function offsetCommitRequest(topic, offset) {
470
+ const body = Buffer.concat([
471
+ kstr(groupId),
472
+ int32(-1), // generation_id -1 (simple consumer)
473
+ kstr(""), // member_id ""
474
+ int64(-1n), // retention_time -1
475
+ int32(1), kstr(topic), int32(1), int32(0), int64(BigInt(offset)), int16(-1),
476
+ ]);
477
+ return frame(8, 2, body);
478
+ }
479
+ function parseOffsetCommit(resp) {
480
+ let pos = 4;
481
+ const tc = resp.readInt32BE(pos); pos += 4;
482
+ if (tc === 0) return 16;
483
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
484
+ const pc = resp.readInt32BE(pos); pos += 4;
485
+ if (pc === 0) return 16;
486
+ pos += 4;
487
+ return resp.readInt16BE(pos);
488
+ }
489
+ async function offsetCommit(topic, offset) {
490
+ var err = 0;
491
+ for (var attempt = 0; attempt < 10; attempt++) {
492
+ if (attempt > 0) { dropCoordinator(); await new Promise(function (r) { setTimeout(r, 200 * attempt); }); }
493
+ err = parseOffsetCommit(await rpc(await coordinator(), offsetCommitRequest(topic, offset)));
494
+ if (COORDINATOR_ERRORS.indexOf(err) < 0) break;
495
+ }
496
+ if (err !== 0) throw new Error("Kafka rejected the offset commit for " + topic + ": error code " + err);
497
+ }
498
+ function offsetFetchRequest(topic) {
499
+ const body = Buffer.concat([kstr(groupId), int32(1), kstr(topic), int32(1), int32(0)]);
500
+ return frame(9, 1, body);
501
+ }
502
+ function parseOffsetFetch(resp) {
503
+ let pos = 4;
504
+ const tc = resp.readInt32BE(pos); pos += 4;
505
+ if (tc === 0) return { offset: -1, err: 16 };
506
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
507
+ const pc = resp.readInt32BE(pos); pos += 4;
508
+ if (pc === 0) return { offset: -1, err: 16 };
509
+ pos += 4;
510
+ const offset = Number(resp.readBigInt64BE(pos)); pos += 8;
511
+ pos = readNullableString(resp, pos).next;
512
+ const err = resp.readInt16BE(pos);
513
+ return { offset: offset, err: err };
514
+ }
515
+ async function offsetFetch(topic) {
516
+ var r = { offset: -1, err: 0 };
517
+ for (var attempt = 0; attempt < 10; attempt++) {
518
+ if (attempt > 0) { dropCoordinator(); await new Promise(function (res) { setTimeout(res, 200 * attempt); }); }
519
+ r = parseOffsetFetch(await rpc(await coordinator(), offsetFetchRequest(topic)));
520
+ if (COORDINATOR_ERRORS.indexOf(r.err) < 0) break;
521
+ }
522
+ if (r.err !== 0) throw new Error("Kafka rejected the offset fetch for " + topic + ": error code " + r.err);
523
+ return r.offset < 0 ? 0 : r.offset;
524
+ }
525
+
526
+ function int16(n) { const b = Buffer.alloc(2); b.writeInt16BE(n, 0); return b; }
527
+ function int32(n) { const b = Buffer.alloc(4); b.writeInt32BE(n, 0); return b; }
528
+ function int64(n) { const b = Buffer.alloc(8); b.writeBigInt64BE(BigInt(n), 0); return b; }
529
+ function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
530
+
531
+ async function broker() {
532
+ if (brokerSock) return brokerSock;
533
+ const b = parseBroker(brokers);
534
+ brokerSock = await connect(b.host, b.port);
535
+ return brokerSock;
536
+ }
537
+
538
+ // Resume from the committed offset on the FIRST read of a topic in this worker,
539
+ // then advance the in-memory cursor; the committed offset only moves on a
540
+ // commit, so it lags and a crash before commit replays (at-least-once).
541
+ async function fetchNext(topic) {
542
+ if (!(topic in offsets)) offsets[topic] = await offsetFetch(topic);
543
+ const rec = await fetchAt(topic, offsets[topic]);
544
+ if (rec === null) return null;
545
+ offsets[topic] = rec.offset + 1;
546
+ return rec;
547
+ }
548
+
549
+ function encodeEnvelope(id, payload, attempts) {
550
+ return JSON.stringify({ id: id, payload: payload, status: "pending", createdAt: new Date().toISOString(), attempts: attempts, delayUntil: null });
551
+ }
552
+
553
+ async function handle(req) {
554
+ const op = req.op;
555
+ if (op === "publish") {
556
+ await produce(req.topic, Buffer.from(req.value, "utf-8"));
557
+ return { ok: true };
558
+ }
559
+ if (op === "dequeueRaw") {
560
+ // The value exactly as it sits on the wire (a raw record stays its bare
561
+ // bytes — tina4-nodejs#264), with no id/offset tracking. For wire
562
+ // inspection; the facade consumes through "pop", which normalises + tracks.
563
+ const rec = await fetchNext(req.topic);
564
+ if (rec === null) return { ok: true, message: null };
565
+ let decoded;
566
+ try { decoded = JSON.parse(rec.value); } catch (e) { decoded = rec.value; }
567
+ return { ok: true, message: decoded };
568
+ }
569
+ if (op === "pop") {
570
+ let rec;
571
+ try {
572
+ rec = await fetchNext(req.topic);
573
+ } catch (e) {
574
+ // A malformed/short response runs the parser off the end (a RangeError);
575
+ // anything else is a transport failure. Both name the topic so the cause
576
+ // is findable, and neither reads as an empty queue (ADR: a real failure
577
+ // must never look idle). Wording matches the Python/PHP backends.
578
+ const range = (e instanceof RangeError) || /out of range|bounds/i.test((e && e.message) || "");
579
+ if (range) throw new Error("Kafka fetch for topic " + req.topic + " returned an unreadable response: " + ((e && e.message) || e));
580
+ throw new Error("Kafka fetch for topic " + req.topic + " failed: " + ((e && e.message) || e));
581
+ }
582
+ if (rec === null) return { ok: true, message: null };
583
+ const coordinate = req.topic + ":0:" + rec.offset;
584
+ let decoded;
585
+ try { decoded = JSON.parse(rec.value); } catch (e) { decoded = null; }
586
+ let message;
587
+ let isEnvelope = false;
588
+ if (decoded !== null && typeof decoded === "object" && !Array.isArray(decoded) && "payload" in decoded) {
589
+ message = decoded;
590
+ isEnvelope = true;
591
+ if (!message.id) message.id = coordinate;
592
+ } else {
593
+ message = { id: coordinate, payload: decoded === null ? rec.value : decoded, status: "pending", attempts: 0 };
594
+ }
595
+ // The Job lifecycle (complete/fail/retry) routes by the record's own topic,
596
+ // so it must be carried back (like the file/mongodb backends do).
597
+ message.topic = req.topic;
598
+ inFlight[String(message.id)] = { offset: rec.offset, value: rec.value, attempts: message.attempts || 0, isEnvelope: isEnvelope };
599
+ return { ok: true, message: message };
600
+ }
601
+ if (op === "complete") {
602
+ const rec = inFlight[String(req.id)];
603
+ if (rec) { delete inFlight[String(req.id)]; await offsetCommit(req.topic, rec.offset + 1); }
604
+ return { ok: true };
605
+ }
606
+ if (op === "fail") {
607
+ const rec = inFlight[String(req.id)];
608
+ if (rec) {
609
+ delete inFlight[String(req.id)];
610
+ const attempts = (rec.attempts || 0) + 1;
611
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
612
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
613
+ if (attempts < req.maxRetries) {
614
+ await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
615
+ } else {
616
+ await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: attempts, error: req.error }), "utf-8"));
617
+ }
618
+ await offsetCommit(req.topic, rec.offset + 1);
619
+ }
620
+ return { ok: true };
621
+ }
622
+ if (op === "reject") {
623
+ const rec = inFlight[String(req.id)];
624
+ if (rec) {
625
+ delete inFlight[String(req.id)];
626
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
627
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
628
+ await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: req.maxRetries, error: req.reason }), "utf-8"));
629
+ await offsetCommit(req.topic, rec.offset + 1);
630
+ }
631
+ return { ok: true };
632
+ }
633
+ if (op === "retry") {
634
+ const rec = inFlight[String(req.id)];
635
+ if (rec) {
636
+ delete inFlight[String(req.id)];
637
+ const attempts = (rec.attempts || 0) + 1;
638
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
639
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
640
+ await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
641
+ await offsetCommit(req.topic, rec.offset + 1);
642
+ }
643
+ return { ok: true };
644
+ }
645
+ if (op === "deadLetters") {
646
+ // Read the <topic>.dead_letter topic from the beginning; every record on it
647
+ // is a dead letter by construction. A throwaway cursor that never commits,
648
+ // so it does not disturb the main consume position.
649
+ const dlq = req.topic + ".dead_letter";
650
+ const out = [];
651
+ let off = 0;
652
+ for (;;) {
653
+ const rec = await fetchAt(dlq, off);
654
+ if (rec === null) break;
655
+ off = rec.offset + 1;
656
+ try { out.push(JSON.parse(rec.value)); } catch (e) { /* skip */ }
657
+ if (out.length > 10000) break;
658
+ }
659
+ return { ok: true, deadLetters: out };
660
+ }
661
+ if (op === "close") {
662
+ try { if (brokerSock) brokerSock.destroy(); } catch (e) { /* ignore */ }
663
+ dropCoordinator();
664
+ return { ok: true, closing: true };
665
+ }
666
+ return { ok: false, error: "unknown op " + op };
667
+ }
668
+
669
+ parentPort.on("message", async function (req) {
670
+ let res;
671
+ try { res = await handle(req); }
672
+ catch (e) { res = { ok: false, error: (e && e.message) ? e.message : String(e) }; }
673
+ const bytes = Buffer.from(JSON.stringify(res), "utf-8");
674
+ outBytes.set(bytes.subarray(0, outBytes.length), 0);
675
+ Atomics.store(header, 1, Math.min(bytes.length, outBytes.length));
676
+ Atomics.store(header, 0, 1);
677
+ Atomics.notify(header, 0);
678
+ });
679
+ `;
142
680
 
143
681
  /**
144
- * Kafka queue backend using raw Kafka protocol over TCP.
145
- *
146
- * Uses synchronous-style communication by spawning a child process
147
- * for each operation, similar to the Redis session handler pattern.
682
+ * Kafka queue backend — a persistent worker-thread connection (see the file
683
+ * header). The public API stays synchronous; each call blocks the main thread on
684
+ * Atomics.wait while the worker runs the async socket I/O.
148
685
  */
149
686
  export class KafkaBackend implements QueueBackend {
150
687
  private brokers: string;
151
688
  private groupId: string;
689
+ private worker: Worker | null = null;
690
+ private sab: SharedArrayBuffer | null = null;
691
+ private header: Int32Array | null = null;
692
+ private outBytes: Uint8Array | null = null;
693
+ private static readonly SAB_SIZE = 1 << 20; // 1 MiB (8-byte header + response bytes)
694
+ private static readonly CALL_TIMEOUT_MS = 20000;
152
695
 
153
696
  constructor(config?: KafkaConfig) {
154
- // Base layer: brokers derived from TINA4_QUEUE_URL (strip a leading
155
- // kafka:// scheme if present; otherwise use the value as-is, e.g.
156
- // "localhost:9092").
157
697
  const url = process.env.TINA4_QUEUE_URL;
158
698
  const fromUrl = url ? url.replace(/^kafka:\/\//, "") : undefined;
159
-
160
- // Precedence: explicit config arg > specific TINA4_KAFKA_BROKERS var
161
- // > value from TINA4_QUEUE_URL > existing default.
162
699
  this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
163
700
  this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
164
701
  }
165
702
 
166
- /**
167
- * Resolved connection config — exposed for testing/introspection.
168
- */
703
+ /** Resolved connection config — exposed for testing/introspection. */
169
704
  getConfig(): Required<Omit<KafkaConfig, "visibilityTimeout">> {
170
705
  return { brokers: this.brokers, groupId: this.groupId };
171
706
  }
172
707
 
173
- /**
174
- * Resolved SSL/SASL client config from the environment (PLAINTEXT default).
175
- * Mirrors Python's `KafkaConnector._security_config`.
176
- */
177
708
  securityConfig(): KafkaSecurityConfig {
178
709
  return kafkaSecurityConfig();
179
710
  }
180
711
 
181
- /**
182
- * Full producer config — brokers + client id + the resolved security block.
183
- * The security keys are applied to BOTH producer and consumer (matching
184
- * Python's `_connect_confluent`).
185
- */
186
712
  producerConfig(): KafkaClientConfig {
187
- return {
188
- "bootstrap.servers": this.brokers,
189
- "client.id": "tina4-nodejs",
190
- ...this.securityConfig(),
191
- };
713
+ return { "bootstrap.servers": this.brokers, "client.id": "tina4-nodejs", ...this.securityConfig() };
192
714
  }
193
715
 
194
- /**
195
- * Full consumer config — brokers + client id + group id + the SAME resolved
196
- * security block applied to the producer.
197
- */
198
716
  consumerConfig(): KafkaClientConfig {
199
717
  return {
200
718
  "bootstrap.servers": this.brokers,
@@ -206,469 +724,51 @@ export class KafkaBackend implements QueueBackend {
206
724
  };
207
725
  }
208
726
 
209
- /**
210
- * Parse broker string into host:port.
211
- */
212
- private parseBroker(): { host: string; port: number } {
213
- const parts = this.brokers.split(",")[0].trim().split(":");
214
- return {
215
- host: parts[0] ?? "localhost",
216
- port: parts[1] ? parseInt(parts[1], 10) : 9092,
217
- };
218
- }
219
-
220
- /**
221
- * Execute a Kafka operation synchronously via a child process.
222
- *
223
- * The wire protocol is hand-rolled (Tina4 is zero-dependency — no npm Kafka
224
- * library). Produce uses Produce **v3** carrying a Kafka **v2 RecordBatch**
225
- * (magic byte 2) with a **CRC-32C** (Castagnoli) checksum; Fetch uses Fetch
226
- * **v4** and parses the v2 RecordBatch out of the response. Both formats are
227
- * what a modern KRaft broker (apache/kafka 3.7.0) requires — the old
228
- * Produce-v0 / message-format-v0 / CRC=0 batch is rejected by such brokers.
229
- */
230
- private execSync(operation: string, topic: string, data?: string): string {
231
- // execFileSync imported at top level
232
- const broker = this.parseBroker();
233
-
234
- const script = `
235
- const net = require("node:net");
236
- const host = ${JSON.stringify(broker.host)};
237
- const port = ${broker.port};
238
- const operation = ${JSON.stringify(operation)};
239
- const topic = ${JSON.stringify(topic)};
240
- const groupId = ${JSON.stringify(this.groupId)};
241
- const data = ${JSON.stringify(data ?? "")};
242
- const API_PRODUCE = ${API_PRODUCE};
243
- const API_FETCH = ${API_FETCH};
244
- const PRODUCE_VERSION = 3; // v3+ requires the v2 RecordBatch format
245
- const FETCH_VERSION = 4; // v4 returns v2 RecordBatches + isolation_level
246
- let correlationId = 0;
247
-
248
- // ── CRC-32C (Castagnoli, polynomial 0x1EDC6F41), table-based ──────────
249
- // Node has no built-in CRC-32C; the v2 RecordBatch mandates it over the
250
- // bytes from \`attributes\` to the end of the batch. A wrong CRC makes the
251
- // broker drop the connection, so this must be exact.
252
- const CRC32C_TABLE = (() => {
253
- const table = new Uint32Array(256);
254
- for (let n = 0; n < 256; n++) {
255
- let c = n;
256
- for (let k = 0; k < 8; k++) {
257
- c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
258
- }
259
- table[n] = c >>> 0;
260
- }
261
- return table;
262
- })();
263
- function crc32c(buf) {
264
- let crc = 0xffffffff;
265
- for (let i = 0; i < buf.length; i++) {
266
- crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
267
- }
268
- return (crc ^ 0xffffffff) >>> 0;
269
- }
270
-
271
- // ── Kafka protocol varints (zigzag-encoded signed varints) ────────────
272
- function encodeZigZag(n) {
273
- // 32-bit zigzag: (n << 1) ^ (n >> 31)
274
- return ((n << 1) ^ (n >> 31)) >>> 0;
275
- }
276
- function encodeVarintUnsigned(u) {
277
- const bytes = [];
278
- let v = u >>> 0;
279
- while (true) {
280
- if ((v & ~0x7f) === 0) { bytes.push(v); break; }
281
- bytes.push((v & 0x7f) | 0x80);
282
- v >>>= 7;
283
- }
284
- return Buffer.from(bytes);
285
- }
286
- function encodeVarint(n) {
287
- // signed varint = zigzag then unsigned-varint
288
- return encodeVarintUnsigned(encodeZigZag(n));
289
- }
290
- function decodeVarint(buf, pos) {
291
- // returns { value, next } — signed (zigzag-decoded)
292
- let result = 0, shift = 0, b;
293
- do {
294
- b = buf[pos++];
295
- result |= (b & 0x7f) << shift;
296
- shift += 7;
297
- } while (b & 0x80);
298
- result = result >>> 0;
299
- // zigzag decode
300
- const value = (result >>> 1) ^ -(result & 1);
301
- return { value, next: pos };
302
- }
303
-
304
- // ── v2 RecordBatch builder ────────────────────────────────────────────
305
- function buildRecordBatch(valueBytes) {
306
- const now = BigInt(Date.now());
307
-
308
- // Build the single record body.
309
- // record = attributes:int8(0), timestampDelta:varint(0),
310
- // offsetDelta:varint(0), keyLen:varint(-1 null),
311
- // valueLen:varint(len), value, headerCount:varint(0)
312
- const recBody = Buffer.concat([
313
- Buffer.from([0]), // attributes (int8)
314
- encodeVarint(0), // timestampDelta
315
- encodeVarint(0), // offsetDelta
316
- encodeVarint(-1), // keyLen (-1 = null key)
317
- encodeVarint(valueBytes.length), // valueLen
318
- valueBytes, // value (JSON payload bytes)
319
- encodeVarint(0), // headerCount
320
- ]);
321
- // record length prefix = signed varint of recBody length
322
- const record = Buffer.concat([encodeVarint(recBody.length), recBody]);
323
- const recordsCount = 1;
324
-
325
- // The portion the CRC covers starts at \`attributes\` and runs to end.
326
- // crcBody = attributes:int16(0), lastOffsetDelta:int32(count-1),
327
- // firstTimestamp:int64, maxTimestamp:int64,
328
- // producerId:int64(-1), producerEpoch:int16(-1),
329
- // baseSequence:int32(-1), recordsCount:int32, records
330
- const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
331
- let c = 0;
332
- crcBody.writeInt16BE(0, c); c += 2; // attributes
333
- crcBody.writeInt32BE(recordsCount - 1, c); c += 4; // lastOffsetDelta
334
- crcBody.writeBigInt64BE(now, c); c += 8; // firstTimestamp
335
- crcBody.writeBigInt64BE(now, c); c += 8; // maxTimestamp
336
- crcBody.writeBigInt64BE(-1n, c); c += 8; // producerId
337
- crcBody.writeInt16BE(-1, c); c += 2; // producerEpoch
338
- crcBody.writeInt32BE(-1, c); c += 4; // baseSequence
339
- crcBody.writeInt32BE(recordsCount, c); c += 4; // recordsCount
340
- record.copy(crcBody, c);
341
-
342
- const crc = crc32c(crcBody);
343
-
344
- // Header before the CRC-covered region:
345
- // baseOffset:int64(0), batchLength:int32, partitionLeaderEpoch:int32(-1),
346
- // magic:int8(2), crc:uint32. batchLength counts everything AFTER itself
347
- // (partitionLeaderEpoch through end of records) = 4 + 1 + 4 + crcBody.
348
- const batchLength = 4 + 1 + 4 + crcBody.length;
349
- const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
350
- let h = 0;
351
- head.writeBigInt64BE(0n, h); h += 8; // baseOffset
352
- head.writeInt32BE(batchLength, h); h += 4; // batchLength
353
- head.writeInt32BE(-1, h); h += 4; // partitionLeaderEpoch
354
- head.writeInt8(2, h); h += 1; // magic = 2
355
- head.writeUInt32BE(crc, h); h += 4; // crc (CRC-32C)
356
-
357
- return Buffer.concat([head, crcBody]);
358
- }
359
-
360
- // ── Produce v3 request ─────────────────────────────────────────────────
361
- function buildProduceRequest(topicName, valueBytes) {
362
- correlationId++;
363
- const clientBuf = Buffer.from("tina4", "utf-8");
364
- const topicBuf = Buffer.from(topicName, "utf-8");
365
- const recordBatch = buildRecordBatch(valueBytes);
366
-
367
- const body = Buffer.alloc(
368
- 2 + // transactionalId (-1 null nullable_string)
369
- 2 + // acks
370
- 4 + // timeoutMs
371
- 4 + // topics array count
372
- 2 + topicBuf.length + // topic name
373
- 4 + // partitions array count
374
- 4 + // partition index
375
- 4 + recordBatch.length // recordSetBytes (int32 size) + batch
376
- );
377
- let p = 0;
378
- body.writeInt16BE(-1, p); p += 2; // transactionalId = null
379
- body.writeInt16BE(1, p); p += 2; // acks = 1
380
- body.writeInt32BE(10000, p); p += 4; // timeoutMs
381
- body.writeInt32BE(1, p); p += 4; // topics count
382
- body.writeInt16BE(topicBuf.length, p); p += 2;
383
- topicBuf.copy(body, p); p += topicBuf.length;
384
- body.writeInt32BE(1, p); p += 4; // partitions count
385
- body.writeInt32BE(0, p); p += 4; // partition index 0
386
- body.writeInt32BE(recordBatch.length, p); p += 4; // recordSetBytes size
387
- recordBatch.copy(body, p);
388
-
389
- return frameRequest(API_PRODUCE, PRODUCE_VERSION, clientBuf, body);
390
- }
391
-
392
- // ── Fetch v4 request ────────────────────────────────────────────────────
393
- function buildFetchRequest(topicName, fetchOffset) {
394
- correlationId++;
395
- const clientBuf = Buffer.from("tina4", "utf-8");
396
- const topicBuf = Buffer.from(topicName, "utf-8");
397
-
398
- // Fetch v4 request body (NO logStartOffset — that arrives in v5+):
399
- // replicaId(4), maxWaitMs(4), minBytes(4), maxBytes(4 v3+),
400
- // isolationLevel(1 v4+), topics[count]: name, partitions[count]:
401
- // partition(4), fetchOffset(8), partitionMaxBytes(4).
402
- const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + (2 + topicBuf.length) + 4 + 4 + 8 + 4);
403
- let p = 0;
404
- buf.writeInt32BE(-1, p); p += 4; // replicaId (-1 consumer)
405
- buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
406
- buf.writeInt32BE(1, p); p += 4; // minBytes
407
- buf.writeInt32BE(1048576, p); p += 4; // maxBytes
408
- buf.writeInt8(0, p); p += 1; // isolationLevel = READ_UNCOMMITTED
409
- buf.writeInt32BE(1, p); p += 4; // topics count
410
- buf.writeInt16BE(topicBuf.length, p); p += 2;
411
- topicBuf.copy(buf, p); p += topicBuf.length;
412
- buf.writeInt32BE(1, p); p += 4; // partitions count
413
- buf.writeInt32BE(0, p); p += 4; // partition 0
414
- buf.writeBigInt64BE(BigInt(fetchOffset), p); p += 8; // fetchOffset
415
- buf.writeInt32BE(1048576, p); p += 4; // partitionMaxBytes
416
-
417
- return frameRequest(API_FETCH, FETCH_VERSION, clientBuf, buf);
418
- }
419
-
420
- // Frame a request with header v1: apiKey, apiVersion, correlationId,
421
- // clientId (nullable string) + body.
422
- function frameRequest(apiKey, apiVersion, clientBuf, body) {
423
- const header = Buffer.alloc(2 + 2 + 4 + 2 + clientBuf.length);
424
- let p = 0;
425
- header.writeInt16BE(apiKey, p); p += 2;
426
- header.writeInt16BE(apiVersion, p); p += 2;
427
- header.writeInt32BE(correlationId, p); p += 4;
428
- header.writeInt16BE(clientBuf.length, p); p += 2;
429
- clientBuf.copy(header, p);
430
- const payload = Buffer.concat([header, body]);
431
- const framed = Buffer.alloc(4 + payload.length);
432
- framed.writeInt32BE(payload.length, 0);
433
- payload.copy(framed, 4);
434
- return framed;
435
- }
436
-
437
- // ── Parse a v2 RecordBatch region, return the FIRST record value ───────
438
- // \`buf\` is the whole fetch response; [start, end) bounds the partition's
439
- // record-set bytes (may contain one or more concatenated batches).
440
- function firstRecordValue(buf, start, end) {
441
- let pos = start;
442
- while (pos + 12 <= end) {
443
- // baseOffset(8) + batchLength(4) then batchLength bytes follow.
444
- const batchLength = buf.readInt32BE(pos + 8);
445
- const batchStart = pos + 12; // first byte of partitionLeaderEpoch
446
- const batchEnd = batchStart + batchLength;
447
- if (batchLength <= 0 || batchEnd > end) break;
448
- // partitionLeaderEpoch(4), magic(1), crc(4), attributes(2),
449
- // lastOffsetDelta(4), firstTimestamp(8), maxTimestamp(8),
450
- // producerId(8), producerEpoch(2), baseSequence(4), recordsCount(4)
451
- const magic = buf.readInt8(batchStart + 4);
452
- if (magic !== 2) { pos = batchEnd; continue; }
453
- let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
454
- const recordsCount = buf.readInt32BE(r); r += 4;
455
- for (let i = 0; i < recordsCount && r < batchEnd; i++) {
456
- const recLen = decodeVarint(buf, r); // record length (signed varint)
457
- let rp = recLen.next;
458
- const recordEnd = rp + recLen.value;
459
- rp += 1; // attributes (int8)
460
- const tsDelta = decodeVarint(buf, rp); rp = tsDelta.next;
461
- const offDelta = decodeVarint(buf, rp); rp = offDelta.next;
462
- const keyLen = decodeVarint(buf, rp); rp = keyLen.next;
463
- if (keyLen.value >= 0) rp += keyLen.value;
464
- const valLen = decodeVarint(buf, rp); rp = valLen.next;
465
- if (valLen.value >= 0) {
466
- return buf.subarray(rp, rp + valLen.value).toString("utf-8");
467
- }
468
- r = recordEnd;
469
- }
470
- pos = batchEnd;
471
- }
472
- return null;
473
- }
474
-
475
- let finished = false;
476
- function finish(out, code) {
477
- if (finished) return;
478
- finished = true;
479
- clearTimeout(timer);
480
- try { sock.destroy(); } catch (e) { /* ignore */ }
481
- if (out) process.stdout.write(out);
482
- // Flush stdout before exiting so execFileSync captures it.
483
- process.stdout.write("", () => process.exit(code));
484
- }
485
-
486
- const sock = net.createConnection({ host, port }, () => {
487
- if (operation === "publish") {
488
- const req = buildProduceRequest(topic, Buffer.from(data, "utf-8"));
489
- sock.write(req);
490
- } else if (operation === "get") {
491
- sock.write(buildFetchRequest(topic, 0));
492
- } else {
493
- finish("__UNSUPPORTED__", 0);
494
- }
495
- });
496
-
497
- let buffer = Buffer.alloc(0);
498
- sock.on("data", (chunk) => {
499
- buffer = Buffer.concat([buffer, chunk]);
500
- if (buffer.length < 4) return;
501
- const respSize = buffer.readInt32BE(0);
502
- if (buffer.length < 4 + respSize) return;
503
-
504
- if (operation === "publish") {
505
- // Produce v3 response (after the 4-byte frame size): correlationId(4),
506
- // topics[count]: name, partitions[count]: partition(4), errorCode(2),
507
- // baseOffset(8), logAppendTime(8); then throttleTimeMs(4) at the END.
508
- // Only the per-partition error code matters here.
509
- try {
510
- let pos = 4 + 4; // skip frame size + correlationId
511
- const topicCount = buffer.readInt32BE(pos); pos += 4;
512
- let errCode = 0;
513
- for (let t = 0; t < topicCount; t++) {
514
- const tl = buffer.readInt16BE(pos); pos += 2 + tl;
515
- const pc = buffer.readInt32BE(pos); pos += 4;
516
- for (let pi = 0; pi < pc; pi++) {
517
- pos += 4; // partition index
518
- errCode = buffer.readInt16BE(pos); pos += 2; // error code
519
- pos += 8; // baseOffset
520
- pos += 8; // logAppendTime (v2+)
521
- }
522
- }
523
- if (errCode === 0) {
524
- finish("__PUBLISHED__", 0);
525
- } else {
526
- // Report the CODE, not just "it failed" — the caller decides
527
- // whether it is retriable (3/5, the async topic-creation race)
528
- // or fatal (e.g. 29 TOPIC_AUTHORIZATION_FAILED).
529
- process.stderr.write("Produce error code " + errCode);
530
- finish("__PRODUCEERROR__" + errCode, 0);
531
- }
532
- } catch (e) {
533
- process.stderr.write("produce parse: " + e.message);
534
- finish("__PARSEERROR__produce: " + e.message, 0);
535
- }
536
- return;
537
- } else if (operation === "get") {
538
- // Fetch v4 response (after the 4-byte frame size): correlationId(4),
539
- // throttleTimeMs(4), topics[count]: name, partitions[count]:
540
- // partition(4), errorCode(2), highWatermark(8), lastStableOffset(8),
541
- // abortedTxns[count](producerId(8)+firstOffset(8)),
542
- // recordSetBytes(int32)+batch.
543
- try {
544
- let pos = 4 + 4; // frame size + correlationId
545
- pos += 4; // throttleTimeMs (v1+)
546
- const topicCount = buffer.readInt32BE(pos); pos += 4;
547
- let out = "__EMPTY__";
548
- let fatalCode = 0;
549
- for (let t = 0; t < topicCount; t++) {
550
- const tl = buffer.readInt16BE(pos); pos += 2 + tl;
551
- const pc = buffer.readInt32BE(pos); pos += 4;
552
- for (let pi = 0; pi < pc; pi++) {
553
- pos += 4; // partition index
554
- const errCode = buffer.readInt16BE(pos); pos += 2;
555
- pos += 8; // highWatermark
556
- pos += 8; // lastStableOffset (v4+)
557
- const abortedCount = buffer.readInt32BE(pos); pos += 4;
558
- if (abortedCount > 0) pos += abortedCount * 16; // (-1 => none, skip)
559
- const recSetSize = buffer.readInt32BE(pos); pos += 4;
560
- // 3 = UNKNOWN_TOPIC_OR_PARTITION, 5 = LEADER_NOT_AVAILABLE:
561
- // "nothing to read here yet", which a consumer that starts
562
- // before its producer hits on every cold start. Any OTHER code
563
- // (29 TOPIC_AUTHORIZATION_FAILED, 13 STALE_CONTROLLER_EPOCH, …)
564
- // is a real failure and must NOT be reported as an empty queue.
565
- if (errCode !== 0 && errCode !== 3 && errCode !== 5) {
566
- fatalCode = errCode;
567
- }
568
- if (errCode === 0 && recSetSize > 0) {
569
- const val = firstRecordValue(buffer, pos, pos + recSetSize);
570
- if (val !== null) out = val;
571
- }
572
- pos += recSetSize > 0 ? recSetSize : 0;
573
- }
574
- }
575
- if (fatalCode !== 0) {
576
- process.stderr.write("Fetch error code " + fatalCode);
577
- finish("__FETCHERROR__" + fatalCode, 0);
578
- return;
579
- }
580
- finish(out, 0);
581
- } catch (e) {
582
- // A parse failure is NOT an empty queue either — say so.
583
- process.stderr.write("fetch parse: " + e.message);
584
- finish("__PARSEERROR__fetch: " + e.message, 0);
585
- }
586
- return;
587
- }
588
- });
589
-
590
- // Report the reason on STDOUT and exit 0. Writing it to stderr and
591
- // exiting non-zero LOST it: stderr to a pipe is an async write and
592
- // process.exit() truncates it, so the parent saw an empty stderr and fell
593
- // back to execFileSync's message -- which embeds this entire script.
594
- // stdout is flushed by finish()'s write callback, so it survives.
595
- sock.on("error", (err) => {
596
- finish("__TRANSPORTERROR__" + err.message, 0);
597
- });
598
-
599
- var timer = setTimeout(() => {
600
- finish("__TRANSPORTERROR__timed out after 10s talking to " + host + ":" + port, 0);
601
- }, 10000);
602
- `;
603
-
604
- try {
605
- const result = execFileSync(process.execPath, ["-e", script], {
606
- encoding: "utf-8",
607
- timeout: 15000,
608
- stdio: ["pipe", "pipe", "pipe"],
609
- });
610
- return result;
611
- } catch (err) {
612
- // Reached only when the child itself could not run (spawn failure, killed,
613
- // the outer 15s timeout). The socket-level reasons come back through
614
- // stdout as __TRANSPORTERROR__ instead. Swallowing this to "" made every
615
- // failure indistinguishable from an empty queue.
616
- //
617
- // execFileSync's own message embeds the ENTIRE generated script, so it is
618
- // truncated here -- a 20KB error that buries the cause is barely better
619
- // than no error at all.
620
- const e = err as { stderr?: Buffer | string; message?: string };
621
- const reason = String(e.stderr ?? "").trim() || e.message || "unknown error";
622
- const firstLine = reason.split("\n", 1)[0]!.slice(0, 200);
623
- return "__TRANSPORTERROR__" + firstLine;
624
- }
625
- }
626
-
627
- /**
628
- * Sleep synchronously between produce retries.
629
- *
630
- * `push()` is synchronous (the whole backend drives its socket through a child
631
- * process), so there is no event loop to await on. `Atomics.wait` on a
632
- * SharedArrayBuffer is the stdlib way to block a thread for a fixed time --
633
- * no dependency, no busy-wait burning CPU.
634
- */
635
- private static sleepSync(ms: number): void {
636
- const shared = new Int32Array(new SharedArrayBuffer(4));
637
- Atomics.wait(shared, 0, 0, ms);
727
+ /** Lazily start the persistent worker + its shared buffer. */
728
+ private ensureWorker(): void {
729
+ if (this.worker) return;
730
+ this.sab = new SharedArrayBuffer(KafkaBackend.SAB_SIZE);
731
+ this.header = new Int32Array(this.sab, 0, 2);
732
+ this.outBytes = new Uint8Array(this.sab, 8);
733
+ this.worker = new Worker(WORKER_SRC, {
734
+ eval: true,
735
+ workerData: {
736
+ brokers: this.brokers,
737
+ groupId: this.groupId,
738
+ security: this.securityConfig(),
739
+ offsetReset: kafkaOffsetReset(),
740
+ sab: this.sab,
741
+ },
742
+ });
743
+ // The worker must not keep the parent process alive by itself.
744
+ this.worker.unref();
638
745
  }
639
746
 
640
- /**
641
- * Turn a sentinel from the protocol child into a thrown error, or return.
642
- *
643
- * The wording matches the Python and PHP backends exactly -- the parity rule
644
- * covers user-visible error messages, not just behaviour.
645
- */
646
- private static assertNoError(result: string, operation: string, topic: string): void {
647
- const fatal = /^__(PRODUCEERROR|FETCHERROR)__(\d+)/.exec(result);
648
- if (fatal) {
649
- throw new Error(
650
- `Kafka rejected the ${operation} for topic ${topic}: error code ${fatal[2]}`,
651
- );
747
+ /** One synchronous request to the worker: post, block on Atomics.wait, read. */
748
+ private request(req: Record<string, unknown>): Record<string, unknown> {
749
+ this.ensureWorker();
750
+ const header = this.header!;
751
+ const outBytes = this.outBytes!;
752
+ Atomics.store(header, 0, 0); // pending
753
+ this.worker!.postMessage(req);
754
+ const waited = Atomics.wait(header, 0, 0, KafkaBackend.CALL_TIMEOUT_MS);
755
+ if (waited === "timed-out") {
756
+ throw new Error(`Kafka ${String(req.op)} for topic ${String(req.topic ?? "")} timed out after ${KafkaBackend.CALL_TIMEOUT_MS}ms`);
652
757
  }
653
- if (result.startsWith("__TRANSPORTERROR__")) {
654
- throw new Error(
655
- `Kafka ${operation} for topic ${topic} failed: ` +
656
- result.slice("__TRANSPORTERROR__".length),
657
- );
658
- }
659
- if (result.startsWith("__PARSEERROR__")) {
660
- throw new Error(
661
- `Kafka ${operation} for topic ${topic} returned an unreadable response: ` +
662
- result.slice("__PARSEERROR__".length),
663
- );
758
+ const len = Atomics.load(header, 1);
759
+ const json = Buffer.from(outBytes.buffer, outBytes.byteOffset, len).toString("utf-8");
760
+ const res = JSON.parse(json) as Record<string, unknown>;
761
+ if (res.ok === false) {
762
+ throw new Error(String(res.error ?? "unknown Kafka worker error"));
664
763
  }
764
+ return res;
665
765
  }
666
766
 
667
767
  /**
668
768
  * Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
669
769
  * as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
670
- * consumer reading the topic gets the schema it expects; otherwise the Tina4 job
671
- * envelope. pop() unwraps both shapes (payload ?? the whole record).
770
+ * consumer reading the topic gets the schema it expects; otherwise the Tina4
771
+ * job envelope. pop() unwraps both shapes (payload ?? the whole record).
672
772
  */
673
773
  private static encodeJob(id: string, payload: unknown, raw: boolean): string {
674
774
  if (raw) return JSON.stringify(payload);
@@ -684,59 +784,90 @@ export class KafkaBackend implements QueueBackend {
684
784
 
685
785
  push(queue: string, payload: unknown, _delay?: number, _priority?: number, raw: boolean = false): string {
686
786
  const id = randomUUID();
787
+ const value = KafkaBackend.encodeJob(id, payload, raw);
788
+ this.request({ op: "publish", topic: queue, value });
789
+ return id;
790
+ }
687
791
 
688
- // Topic auto-creation is ASYNCHRONOUS, so a brand-new topic answers
689
- // UNKNOWN_TOPIC_OR_PARTITION (3) or LEADER_NOT_AVAILABLE (5) on the first
690
- // attempt while the controller is still electing a leader. Retry those
691
- // (same 10 attempts / 200ms as the Python and PHP backends) instead of
692
- // failing a cold-start push; every other code throws immediately.
693
- const body = KafkaBackend.encodeJob(id, payload, raw);
694
- let result = "";
695
- for (let attempt = 1; attempt <= 10; attempt++) {
696
- result = this.execSync("publish", queue, body);
697
- if (result.includes("__PUBLISHED__")) {
698
- return id;
699
- }
700
- const retriable = /^__PRODUCEERROR__(3|5)\b/.test(result);
701
- if (!retriable || attempt === 10) {
702
- break;
703
- }
704
- KafkaBackend.sleepSync(200);
705
- }
792
+ pop(queue: string): QueueJob | null {
793
+ const res = this.request({ op: "pop", topic: queue });
794
+ const message = res.message as QueueJob | null;
795
+ return message ?? null;
796
+ }
706
797
 
707
- KafkaBackend.assertNoError(result, "produce", queue);
708
- throw new Error(`Kafka publish failed for topic ${queue}: ${result || "no response"}`);
798
+ /**
799
+ * Read the next record's value exactly as it sits on the wire — a Tina4
800
+ * envelope as produced, a raw record (tina4-nodejs#264) as its bare bytes —
801
+ * with no id/offset tracking. For a foreign consumer's view of the schema;
802
+ * the queue facade consumes through pop(), which also normalises and tracks
803
+ * the offset so complete()/fail() can commit it.
804
+ */
805
+ dequeue(queue: string): unknown {
806
+ const res = this.request({ op: "dequeueRaw", topic: queue });
807
+ return res.message ?? null;
709
808
  }
710
809
 
711
- pop(queue: string): QueueJob | null {
712
- const result = this.execSync("get", queue);
810
+ /** Commit the record's offset so a completed job never replays (ADR-0022 d.4). */
811
+ complete(queue: string, id: string): void {
812
+ this.request({ op: "complete", topic: queue, id });
813
+ }
713
814
 
714
- // A real failure must NOT read as an empty queue: a mis-permissioned
715
- // consumer would otherwise poll an "idle" topic forever.
716
- KafkaBackend.assertNoError(result, "fetch", queue);
815
+ /**
816
+ * Record a failed attempt: re-produce the job with an incremented attempts
817
+ * count while it has retries left, else produce it to the dead-letter topic;
818
+ * commit the original offset either way (ADR-0022 decision 2).
819
+ */
820
+ fail(queue: string, id: string, error: string, maxRetries: number, _retryBackoff?: number): void {
821
+ this.request({ op: "fail", topic: queue, id, error, maxRetries });
822
+ }
717
823
 
718
- if (!result || result === "__EMPTY__" || result === "__UNSUPPORTED__") return null;
824
+ /** Dead-letter the job now, no retry (ADR-0023 reject), then commit the offset. */
825
+ reject(queue: string, id: string, reason: string, maxRetries: number): void {
826
+ this.request({ op: "reject", topic: queue, id, reason, maxRetries });
827
+ }
719
828
 
720
- try {
721
- return JSON.parse(result) as QueueJob;
722
- } catch {
723
- return null;
724
- }
829
+ /** Re-produce the job (manual retry) and commit the original offset. */
830
+ retry(queue: string, id: string, delaySeconds?: number): boolean {
831
+ this.request({ op: "retry", topic: queue, id, delaySeconds: delaySeconds ?? 0 });
832
+ return true;
833
+ }
834
+
835
+ /** Read the dead-letter topic for this queue (every record on it is a dead letter). */
836
+ deadLetters(queue: string, _maxRetries?: number): QueueJob[] {
837
+ const res = this.request({ op: "deadLetters", topic: queue });
838
+ return (res.deadLetters as QueueJob[]) ?? [];
839
+ }
840
+
841
+ /**
842
+ * Refuse rather than silently answer from the local file store. Kafka keeps no
843
+ * queryable registry of failed jobs: a failed record is re-produced to a
844
+ * dead-letter TOPIC and the original offset committed past, and a log cannot be
845
+ * queried by job state. Returning [] would claim nothing has failed.
846
+ */
847
+ failed(_queue: string, _maxRetries?: number): QueueJob[] {
848
+ throw new Error(
849
+ "The kafka queue backend cannot answer failed(): Kafka keeps no queryable " +
850
+ "registry of failed or dead jobs. Consume the dead-letter topic directly " +
851
+ "(deadLetters()), or use the file or mongodb backend.",
852
+ );
853
+ }
854
+
855
+ /** Refuse for the same reason failed() does (no queryable failed registry). */
856
+ retryFailed(_queue: string, _maxRetries?: number): number {
857
+ throw new Error(
858
+ "The kafka queue backend cannot perform retryFailed(): Kafka keeps no " +
859
+ "queryable registry of failed or dead jobs. Consume the dead-letter topic " +
860
+ "directly, or use the file or mongodb backend.",
861
+ );
725
862
  }
726
863
 
727
864
  size(_queue: string): number {
728
- // Kafka doesn't have a simple "queue size" concept — return 0
729
- // Real implementation would need to compare committed offset vs log end offset
865
+ // Kafka has no queue-depth concept; computing one means an admin round-trip
866
+ // per call. ADR-0022 decision 5 records 0 as the documented answer.
730
867
  return 0;
731
868
  }
732
869
 
733
870
  clear(_queue: string): void {
734
- // Not performable on Kafka - throws naming the backend and the operation.
735
- // clear() empties the queue, but a Kafka log cannot delete records on
736
- // demand: a partition is read in offset order and records leave only by
737
- // retention. This used to be a silent no-op, which claimed the queue was
738
- // emptied when it was untouched (ADR-0022 invariant 6). PHP, Python and
739
- // Ruby already refuse by name; this brings the Node backend class in line.
740
871
  throw new Error(
741
872
  "The kafka queue backend cannot perform clear(): Kafka has no notion of " +
742
873
  "job status and cannot delete records on demand. A log is read in " +
@@ -746,13 +877,25 @@ export class KafkaBackend implements QueueBackend {
746
877
  }
747
878
 
748
879
  purge(_queue: string, _status?: string): number {
749
- // Not performable on Kafka - throws naming the backend and the operation.
750
- // purge(status) removes jobs SELECTED BY STATUS; a Kafka log has no notion
751
- // of status to purge by. Refusing by name is the honest answer.
752
880
  throw new Error(
753
881
  "The kafka queue backend cannot perform purge(): Kafka has no notion of " +
754
882
  "job status to purge by. A log is read in offset order and records " +
755
883
  "leave only by retention. Use the file or mongodb backend.",
756
884
  );
757
885
  }
886
+
887
+ /** Stop the worker and release the connection. Idempotent. */
888
+ close(): void {
889
+ if (!this.worker) return;
890
+ try {
891
+ this.request({ op: "close" });
892
+ } catch {
893
+ // best effort — we are tearing the worker down regardless
894
+ }
895
+ void this.worker.terminate();
896
+ this.worker = null;
897
+ this.sab = null;
898
+ this.header = null;
899
+ this.outBytes = null;
900
+ }
758
901
  }