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.
@@ -10302,6 +10302,7 @@ var init_autoCrud = __esm({
10302
10302
  var engine_exports = {};
10303
10303
  __export(engine_exports, {
10304
10304
  Frond: () => Frond,
10305
+ FrondSyntaxError: () => FrondSyntaxError,
10305
10306
  MEMO_CACHE_MAX: () => MEMO_CACHE_MAX,
10306
10307
  TEMPLATE_CACHE_MAX: () => TEMPLATE_CACHE_MAX,
10307
10308
  escapeHtml: () => escapeHtml,
@@ -11434,6 +11435,87 @@ function isEscapableStructured(value) {
11434
11435
  function toOutputString(value) {
11435
11436
  return String(value);
11436
11437
  }
11438
+ function phpDate(dt, fmt) {
11439
+ const pad = (n) => String(n).padStart(2, "0");
11440
+ const hours = dt.getHours();
11441
+ const h12 = hours % 12 || 12;
11442
+ const dow = dt.getDay();
11443
+ const iso2 = dow === 0 ? 7 : dow;
11444
+ let out = "";
11445
+ for (let i = 0; i < fmt.length; i++) {
11446
+ const c = fmt[i];
11447
+ if (c === "\\" && i + 1 < fmt.length) {
11448
+ out += fmt[i + 1];
11449
+ i++;
11450
+ continue;
11451
+ }
11452
+ switch (c) {
11453
+ case "Y":
11454
+ out += String(dt.getFullYear());
11455
+ break;
11456
+ case "y":
11457
+ out += pad(dt.getFullYear() % 100);
11458
+ break;
11459
+ case "m":
11460
+ out += pad(dt.getMonth() + 1);
11461
+ break;
11462
+ case "n":
11463
+ out += String(dt.getMonth() + 1);
11464
+ break;
11465
+ case "d":
11466
+ out += pad(dt.getDate());
11467
+ break;
11468
+ case "j":
11469
+ out += String(dt.getDate());
11470
+ break;
11471
+ case "H":
11472
+ out += pad(hours);
11473
+ break;
11474
+ case "G":
11475
+ out += String(hours);
11476
+ break;
11477
+ case "h":
11478
+ out += pad(h12);
11479
+ break;
11480
+ case "g":
11481
+ out += String(h12);
11482
+ break;
11483
+ case "i":
11484
+ out += pad(dt.getMinutes());
11485
+ break;
11486
+ case "s":
11487
+ out += pad(dt.getSeconds());
11488
+ break;
11489
+ case "A":
11490
+ out += hours < 12 ? "AM" : "PM";
11491
+ break;
11492
+ case "a":
11493
+ out += hours < 12 ? "am" : "pm";
11494
+ break;
11495
+ case "D":
11496
+ out += PHP_DAYS[dow].slice(0, 3);
11497
+ break;
11498
+ case "l":
11499
+ out += PHP_DAYS[dow];
11500
+ break;
11501
+ case "M":
11502
+ out += PHP_MONTHS[dt.getMonth()].slice(0, 3);
11503
+ break;
11504
+ case "F":
11505
+ out += PHP_MONTHS[dt.getMonth()];
11506
+ break;
11507
+ case "N":
11508
+ out += String(iso2);
11509
+ break;
11510
+ case "w":
11511
+ out += String(dow);
11512
+ break;
11513
+ default:
11514
+ out += c;
11515
+ }
11516
+ }
11517
+ return out;
11518
+ }
11437
11519
  function dateFilter(value, fmt) {
11438
11520
  let dt;
11439
11521
  if (value instanceof Date) {
@@ -11446,6 +11528,7 @@ function dateFilter(value, fmt) {
11446
11528
  } else {
11447
11529
  return String(value);
11448
11530
  }
11531
+ if (!fmt.includes("%")) return phpDate(dt, fmt);
11449
11532
  return fmt.replace(/%Y/g, String(dt.getFullYear())).replace(/%m/g, String(dt.getMonth() + 1).padStart(2, "0")).replace(/%d/g, String(dt.getDate()).padStart(2, "0")).replace(/%H/g, String(dt.getHours()).padStart(2, "0")).replace(/%M/g, String(dt.getMinutes()).padStart(2, "0")).replace(/%S/g, String(dt.getSeconds()).padStart(2, "0")).replace(/%I/g, String(dt.getHours() % 12 || 12).padStart(2, "0")).replace(/%p/g, dt.getHours() >= 12 ? "PM" : "AM").replace(/%B/g, dt.toLocaleString("en-US", { month: "long" })).replace(/%b/g, dt.toLocaleString("en-US", { month: "short" })).replace(/%A/g, dt.toLocaleString("en-US", { weekday: "long" })).replace(/%a/g, dt.toLocaleString("en-US", { weekday: "short" }));
11450
11533
  }
11451
11534
  function wordwrap(text, width) {
@@ -11556,7 +11639,7 @@ function _generateFormToken(descriptor = "") {
11556
11639
  function _generateFormTokenValue(descriptor = "") {
11557
11640
  return new SafeString(_buildFormTokenJwt(descriptor));
11558
11641
  }
11559
- var SafeString, KNOWN_TAGS, TERMINATOR_TAGS, GATEABLE_TAGS, BLOCK_TAG_ENDS, JSON_UNSAFE_RE, JSON_UNSAFE_MAP, NUMERIC_RE, METHOD_CALL_RE, FN_CALL_RE, IS_NOT_RE, IS_RE, NOT_IN_RE, IN_RE, DIVISIBLE_BY_RE, FILTER_WITH_ARGS_RE, FILTER_COMPARISON_RE, TITLE_WORD_RE, STRIP_TAGS_RE, FAST_FILTERS, FORMAT_RE, THOUSANDS_RE, LIVE_RE, LIVE_WS_RE, LIVE_SRC_RE, EXTENDS_RE, EXTENDS_RE_GLOBAL, filterChainCache, pathParseCache, TEMPLATE_CACHE_MAX, MEMO_CACHE_MAX, RAW_OPEN_RE, RAW_CLOSE_RE, TAG_KINDS, EXPR_NOT_MATCHED, ARITHMETIC_OPERATIONS, ARITHMETIC_LEVELS, BARE_KEY_RE, EXPR_EVALUATORS, expressionFormCache, VarRef, JS_SAFE_RE, MEDIA_TYPE_RE, SANDBOX_EXPR_KEYWORDS, SANDBOX_IDENT_RE, SANDBOX_STRING_RE, UNSAFE_KEYS, BUILTIN_FILTERS, _formTokenSessionId, _formTokenSessionProvider, _cspNonceProvider, Frond;
11642
+ var SafeString, KNOWN_TAGS, TERMINATOR_TAGS, GATEABLE_TAGS, BLOCK_TAG_ENDS, JSON_UNSAFE_RE, JSON_UNSAFE_MAP, NUMERIC_RE, METHOD_CALL_RE, FN_CALL_RE, IS_NOT_RE, IS_RE, NOT_IN_RE, IN_RE, DIVISIBLE_BY_RE, FILTER_WITH_ARGS_RE, FILTER_COMPARISON_RE, TITLE_WORD_RE, STRIP_TAGS_RE, FAST_FILTERS, FORMAT_RE, THOUSANDS_RE, LIVE_RE, LIVE_WS_RE, LIVE_SRC_RE, EXTENDS_RE, EXTENDS_RE_GLOBAL, filterChainCache, pathParseCache, TEMPLATE_CACHE_MAX, MEMO_CACHE_MAX, RAW_OPEN_RE, RAW_CLOSE_RE, TAG_KINDS, EXPR_NOT_MATCHED, ARITHMETIC_OPERATIONS, ARITHMETIC_LEVELS, BARE_KEY_RE, EXPR_EVALUATORS, expressionFormCache, VarRef, JS_SAFE_RE, MEDIA_TYPE_RE, SANDBOX_EXPR_KEYWORDS, SANDBOX_IDENT_RE, SANDBOX_STRING_RE, UNSAFE_KEYS, FrondSyntaxError, PHP_MONTHS, PHP_DAYS, BUILTIN_FILTERS, _formTokenSessionId, _formTokenSessionProvider, _cspNonceProvider, Frond;
11560
11643
  var init_engine = __esm({
11561
11644
  "../frond/src/engine.ts"() {
11562
11645
  "use strict";
@@ -11753,6 +11836,35 @@ var init_engine = __esm({
11753
11836
  "__defineProperty__",
11754
11837
  "valueOf"
11755
11838
  ]);
11839
+ FrondSyntaxError = class extends Error {
11840
+ constructor(message) {
11841
+ super(message);
11842
+ this.name = "FrondSyntaxError";
11843
+ }
11844
+ };
11845
+ PHP_MONTHS = [
11846
+ "January",
11847
+ "February",
11848
+ "March",
11849
+ "April",
11850
+ "May",
11851
+ "June",
11852
+ "July",
11853
+ "August",
11854
+ "September",
11855
+ "October",
11856
+ "November",
11857
+ "December"
11858
+ ];
11859
+ PHP_DAYS = [
11860
+ "Sunday",
11861
+ "Monday",
11862
+ "Tuesday",
11863
+ "Wednesday",
11864
+ "Thursday",
11865
+ "Friday",
11866
+ "Saturday"
11867
+ ];
11756
11868
  BUILTIN_FILTERS = {
11757
11869
  upper: (v) => String(v).toUpperCase(),
11758
11870
  lower: (v) => String(v).toLowerCase(),
@@ -12276,7 +12388,9 @@ var init_engine = __esm({
12276
12388
  }
12277
12389
  }
12278
12390
  if (depth > 0) {
12279
- pos = contentStart;
12391
+ throw new FrondSyntaxError(
12392
+ `{% block ${name} %} is never closed (missing or malformed {% endblock %})`
12393
+ );
12280
12394
  }
12281
12395
  }
12282
12396
  return blocks;
@@ -12343,9 +12457,9 @@ var init_engine = __esm({
12343
12457
  }
12344
12458
  }
12345
12459
  if (!closeMatch) {
12346
- pieces.push(source.slice(mOpen.index));
12347
- pos = source.length;
12348
- break;
12460
+ throw new FrondSyntaxError(
12461
+ `{% block ${name} %} is never closed (missing or malformed {% endblock %})`
12462
+ );
12349
12463
  }
12350
12464
  const parentContent = source.slice(contentStart, closeMatch.index);
12351
12465
  const blockSource = blocks[name] ?? parentContent;
@@ -14115,6 +14229,41 @@ var init_queryBuilder = __esm({
14115
14229
  }
14116
14230
  return this;
14117
14231
  }
14232
+ /**
14233
+ * Set OFFSET (rows to skip) as its own chainable verb.
14234
+ *
14235
+ * `limit(n, offset)` buries the offset as a second positional arg; this
14236
+ * exposes it on its own, so `.offset(20).limit(10)` reads naturally and
14237
+ * matches the SQL keyword.
14238
+ *
14239
+ * @param count - Number of rows to skip.
14240
+ * @returns this for chaining.
14241
+ */
14242
+ offset(count) {
14243
+ this.offsetVal = count;
14244
+ return this;
14245
+ }
14246
+ /**
14247
+ * Alias for `offset()` -- the Mongo/Eloquent name for the same thing.
14248
+ *
14249
+ * Mirrors the DocStore cursor's `skip` and the `skip` key that `toMongo()`
14250
+ * already emits, so a query reads the same whether it targets SQL or MongoDB.
14251
+ *
14252
+ * @param count - Number of rows to skip.
14253
+ * @returns this for chaining.
14254
+ */
14255
+ skip(count) {
14256
+ return this.offset(count);
14257
+ }
14258
+ /**
14259
+ * Alias for `limit()` -- the Eloquent name; pairs with `skip()`.
14260
+ *
14261
+ * @param count - Maximum rows to return.
14262
+ * @returns this for chaining.
14263
+ */
14264
+ take(count) {
14265
+ return this.limit(count);
14266
+ }
14118
14267
  /**
14119
14268
  * Build and return the SQL string without executing.
14120
14269
  *
@@ -22220,6 +22369,9 @@ function attachCsrfFromEnv() {
22220
22369
  }
22221
22370
  return false;
22222
22371
  }
22372
+ function logPath(req2) {
22373
+ return req2.path ?? (req2.url ?? "/").split("?")[0];
22374
+ }
22223
22375
  function requestLogger() {
22224
22376
  return (req2, res, next) => {
22225
22377
  const start2 = Date.now();
@@ -22228,8 +22380,7 @@ function requestLogger() {
22228
22380
  const duration = Date.now() - start2;
22229
22381
  const status2 = res.raw.statusCode;
22230
22382
  const method = req2.method ?? "?";
22231
- const url = req2.url ?? "/";
22232
- Log.info(`${method} ${url} -> ${status2} (${duration}ms)`);
22383
+ Log.info(`${method} ${logPath(req2)} -> ${status2} (${duration}ms)`);
22233
22384
  });
22234
22385
  next();
22235
22386
  };
@@ -22656,9 +22807,9 @@ var init_middleware = __esm({
22656
22807
  const duration = Date.now() - (req2.startTime ?? Date.now());
22657
22808
  const status2 = res.raw.statusCode;
22658
22809
  const method = req2.method ?? "?";
22659
- const url = req2.url ?? "/";
22810
+ const path10 = logPath(req2);
22660
22811
  const color = status2 >= 400 ? "\x1B[31m" : status2 >= 300 ? "\x1B[33m" : "\x1B[32m";
22661
- console.log(` ${color}${status2}\x1B[0m ${method} ${url} \x1B[90m${duration}ms\x1B[0m`);
22812
+ console.log(` ${color}${status2}\x1B[0m ${method} ${path10} \x1B[90m${duration}ms\x1B[0m`);
22662
22813
  return [req2, res];
22663
22814
  }
22664
22815
  };
@@ -29652,9 +29803,9 @@ function agentLog(projectRoot3, category, message) {
29652
29803
  if (!fs4.existsSync(logDir)) {
29653
29804
  fs4.mkdirSync(logDir, { recursive: true });
29654
29805
  }
29655
- const logPath = path3.join(logDir, "agent.log");
29806
+ const logPath2 = path3.join(logDir, "agent.log");
29656
29807
  const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/\..+/, "Z");
29657
- fs4.appendFileSync(logPath, `${ts} [${category}] ${message}
29808
+ fs4.appendFileSync(logPath2, `${ts} [${category}] ${message}
29658
29809
  `, "utf-8");
29659
29810
  } catch {
29660
29811
  }
@@ -30650,13 +30801,13 @@ function registerDevTools(server) {
30650
30801
  "git_status",
30651
30802
  () => {
30652
30803
  try {
30653
- const { execFileSync: execFileSync7 } = req("node:child_process");
30804
+ const { execFileSync: execFileSync6 } = req("node:child_process");
30654
30805
  const cwd = path3.resolve(process.cwd());
30655
30806
  const run = (args) => {
30656
- return execFileSync7("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
30807
+ return execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
30657
30808
  };
30658
30809
  try {
30659
- execFileSync7("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
30810
+ execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
30660
30811
  } catch {
30661
30812
  return { error: "Not a git repository" };
30662
30813
  }
@@ -34549,6 +34700,753 @@ var init_mongoBackend = __esm({
34549
34700
  }
34550
34701
  });
34551
34702
 
34703
+ // src/queueBackends/kafkaBackend.ts
34704
+ import { Worker as Worker2 } from "node:worker_threads";
34705
+ import { randomUUID as randomUUID6 } from "node:crypto";
34706
+ function kafkaSecurityConfig(env = process.env) {
34707
+ const mapping = [
34708
+ ["security.protocol", "SECURITY_PROTOCOL"],
34709
+ ["ssl.ca.location", "SSL_CA_LOCATION"],
34710
+ ["sasl.mechanism", "SASL_MECHANISM"],
34711
+ ["sasl.username", "SASL_USERNAME"],
34712
+ ["sasl.password", "SASL_PASSWORD"]
34713
+ ];
34714
+ const config = {};
34715
+ for (const [rdk, suffix] of mapping) {
34716
+ const value = env[`TINA4_KAFKA_${suffix}`] || env[`KAFKA_${suffix}`];
34717
+ if (value) {
34718
+ config[rdk] = value;
34719
+ }
34720
+ }
34721
+ return config;
34722
+ }
34723
+ function kafkaOffsetReset(env = process.env) {
34724
+ return env.TINA4_KAFKA_AUTO_OFFSET_RESET || env.KAFKA_AUTO_OFFSET_RESET || "earliest";
34725
+ }
34726
+ var WORKER_SRC, KafkaBackend;
34727
+ var init_kafkaBackend = __esm({
34728
+ "src/queueBackends/kafkaBackend.ts"() {
34729
+ "use strict";
34730
+ WORKER_SRC = `
34731
+ const net = require("node:net");
34732
+ const tls = require("node:tls");
34733
+ const { parentPort, workerData } = require("node:worker_threads");
34734
+
34735
+ const brokers = workerData.brokers;
34736
+ const groupId = workerData.groupId;
34737
+ const security = workerData.security || {};
34738
+ const offsetReset = workerData.offsetReset || "earliest";
34739
+ const header = new Int32Array(workerData.sab, 0, 2); // [0]=flag, [1]=respLen
34740
+ const outBytes = new Uint8Array(workerData.sab, 8);
34741
+
34742
+ // Lowest versions Kafka 4.x still accepts: it REMOVED Produce v0-v2 / Fetch v0-v3
34743
+ // (the old message formats) and answers a removed version by closing the socket,
34744
+ // not with an error code. These are named constants so the source invariant test
34745
+ // (test/kafkaErrorCodes.test.ts) can assert the floors.
34746
+ const PRODUCE_VERSION = 3;
34747
+ const FETCH_VERSION = 4;
34748
+
34749
+ let correlationId = 0;
34750
+ let brokerSock = null;
34751
+ let coordSock = null;
34752
+ const offsets = {}; // topic -> next read offset (in-memory cursor)
34753
+ const inFlight = {}; // job id -> { offset, value, attempts, isEnvelope }
34754
+
34755
+ const COORDINATOR_ERRORS = [14, 15, 16];
34756
+
34757
+ function parseBroker(list) {
34758
+ const first = String(list).split(",")[0].trim();
34759
+ const i = first.lastIndexOf(":");
34760
+ if (i < 0) return { host: first || "localhost", port: 9092 };
34761
+ return { host: first.slice(0, i) || "localhost", port: parseInt(first.slice(i + 1), 10) || 9092 };
34762
+ }
34763
+
34764
+ function connect(host, port) {
34765
+ return new Promise(function (resolve, reject) {
34766
+ const proto = String(security["security.protocol"] || "PLAINTEXT").toUpperCase();
34767
+ const useTls = proto.indexOf("SSL") >= 0;
34768
+ let sock;
34769
+ const onErr = function (e) { reject(e); };
34770
+ if (useTls) {
34771
+ const opts = { host: host, port: port, servername: host };
34772
+ if (security["ssl.ca.location"]) opts.ca = require("node:fs").readFileSync(security["ssl.ca.location"]);
34773
+ sock = tls.connect(opts, function () { sock.removeListener("error", onErr); resolve(sock); });
34774
+ } else {
34775
+ sock = net.createConnection({ host: host, port: port }, function () { sock.removeListener("error", onErr); resolve(sock); });
34776
+ }
34777
+ sock.once("error", onErr);
34778
+ });
34779
+ }
34780
+
34781
+ // One request/response round trip on a socket: write the framed request, read a
34782
+ // 4-byte length then that many bytes, resolve with the payload AFTER the length
34783
+ // (so it starts at correlationId). Serialized \u2014 one in flight per socket.
34784
+ function rpc(sock, reqBuf) {
34785
+ return new Promise(function (resolve, reject) {
34786
+ let buf = Buffer.alloc(0);
34787
+ function onData(chunk) {
34788
+ buf = Buffer.concat([buf, chunk]);
34789
+ if (buf.length < 4) return;
34790
+ const size = buf.readInt32BE(0);
34791
+ if (buf.length < 4 + size) return;
34792
+ sock.removeListener("data", onData);
34793
+ sock.removeListener("error", onErr);
34794
+ resolve(buf.subarray(4, 4 + size));
34795
+ }
34796
+ function onErr(e) {
34797
+ sock.removeListener("data", onData);
34798
+ reject(e);
34799
+ }
34800
+ sock.on("data", onData);
34801
+ sock.once("error", onErr);
34802
+ sock.write(reqBuf);
34803
+ });
34804
+ }
34805
+
34806
+ // \u2500\u2500 encoders \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
34807
+ function kstr(s) {
34808
+ const b = Buffer.from(s, "utf-8");
34809
+ const out = Buffer.alloc(2 + b.length);
34810
+ out.writeInt16BE(b.length, 0);
34811
+ b.copy(out, 2);
34812
+ return out;
34813
+ }
34814
+ function frame(apiKey, apiVersion, body) {
34815
+ correlationId++;
34816
+ const client = Buffer.from("tina4-nodejs", "utf-8");
34817
+ const head = Buffer.alloc(2 + 2 + 4 + 2 + client.length);
34818
+ let p = 0;
34819
+ head.writeInt16BE(apiKey, p); p += 2;
34820
+ head.writeInt16BE(apiVersion, p); p += 2;
34821
+ head.writeInt32BE(correlationId, p); p += 4;
34822
+ head.writeInt16BE(client.length, p); p += 2;
34823
+ client.copy(head, p);
34824
+ const payload = Buffer.concat([head, body]);
34825
+ const out = Buffer.alloc(4 + payload.length);
34826
+ out.writeInt32BE(payload.length, 0);
34827
+ payload.copy(out, 4);
34828
+ return out;
34829
+ }
34830
+
34831
+ // \u2500\u2500 CRC-32C + varints + v2 RecordBatch (produce) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
34832
+ const CRC32C_TABLE = (function () {
34833
+ const t = new Uint32Array(256);
34834
+ for (let n = 0; n < 256; n++) {
34835
+ let c = n;
34836
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
34837
+ t[n] = c >>> 0;
34838
+ }
34839
+ return t;
34840
+ })();
34841
+ function crc32c(buf) {
34842
+ let crc = 0xffffffff;
34843
+ for (let i = 0; i < buf.length; i++) crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
34844
+ return (crc ^ 0xffffffff) >>> 0;
34845
+ }
34846
+ function zig(n) { return ((n << 1) ^ (n >> 31)) >>> 0; }
34847
+ function varU(u) {
34848
+ const b = [];
34849
+ let v = u >>> 0;
34850
+ for (;;) { if ((v & ~0x7f) === 0) { b.push(v); break; } b.push((v & 0x7f) | 0x80); v >>>= 7; }
34851
+ return Buffer.from(b);
34852
+ }
34853
+ function varint(n) { return varU(zig(n)); }
34854
+ function readVarint(buf, pos) {
34855
+ let result = 0, shift = 0, b;
34856
+ do { b = buf[pos++]; result |= (b & 0x7f) << shift; shift += 7; } while (b & 0x80);
34857
+ result = result >>> 0;
34858
+ return { value: (result >>> 1) ^ -(result & 1), next: pos };
34859
+ }
34860
+ function buildRecordBatch(valueBytes) {
34861
+ const now = BigInt(Date.now());
34862
+ const recBody = Buffer.concat([
34863
+ Buffer.from([0]), varint(0), varint(0), varint(-1),
34864
+ varint(valueBytes.length), valueBytes, varint(0),
34865
+ ]);
34866
+ const record = Buffer.concat([varint(recBody.length), recBody]);
34867
+ const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
34868
+ let c = 0;
34869
+ crcBody.writeInt16BE(0, c); c += 2;
34870
+ crcBody.writeInt32BE(0, c); c += 4;
34871
+ crcBody.writeBigInt64BE(now, c); c += 8;
34872
+ crcBody.writeBigInt64BE(now, c); c += 8;
34873
+ crcBody.writeBigInt64BE(-1n, c); c += 8;
34874
+ crcBody.writeInt16BE(-1, c); c += 2;
34875
+ crcBody.writeInt32BE(-1, c); c += 4;
34876
+ crcBody.writeInt32BE(1, c); c += 4;
34877
+ record.copy(crcBody, c);
34878
+ const crc = crc32c(crcBody);
34879
+ const batchLength = 4 + 1 + 4 + crcBody.length;
34880
+ const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
34881
+ let h = 0;
34882
+ head.writeBigInt64BE(0n, h); h += 8;
34883
+ head.writeInt32BE(batchLength, h); h += 4;
34884
+ head.writeInt32BE(-1, h); h += 4;
34885
+ head.writeInt8(2, h); h += 1;
34886
+ head.writeUInt32BE(crc, h); h += 4;
34887
+ return Buffer.concat([head, crcBody]);
34888
+ }
34889
+
34890
+ // \u2500\u2500 produce \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
34891
+ function produceRequest(topic, valueBytes) {
34892
+ const topicBuf = Buffer.from(topic, "utf-8");
34893
+ const batch = buildRecordBatch(valueBytes);
34894
+ const body = Buffer.alloc(2 + 2 + 4 + 4 + 2 + topicBuf.length + 4 + 4 + 4 + batch.length);
34895
+ let p = 0;
34896
+ body.writeInt16BE(-1, p); p += 2; // transactionalId null
34897
+ body.writeInt16BE(1, p); p += 2; // acks 1
34898
+ body.writeInt32BE(10000, p); p += 4; // timeoutMs
34899
+ body.writeInt32BE(1, p); p += 4; // topics
34900
+ body.writeInt16BE(topicBuf.length, p); p += 2;
34901
+ topicBuf.copy(body, p); p += topicBuf.length;
34902
+ body.writeInt32BE(1, p); p += 4; // partitions
34903
+ body.writeInt32BE(0, p); p += 4; // partition 0
34904
+ body.writeInt32BE(batch.length, p); p += 4;
34905
+ batch.copy(body, p);
34906
+ return frame(0, PRODUCE_VERSION, body);
34907
+ }
34908
+ function parseProduce(resp) {
34909
+ let pos = 4; // correlationId
34910
+ const topicCount = resp.readInt32BE(pos); pos += 4;
34911
+ let err = 0;
34912
+ for (let t = 0; t < topicCount; t++) {
34913
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
34914
+ const pc = resp.readInt32BE(pos); pos += 4;
34915
+ for (let pi = 0; pi < pc; pi++) {
34916
+ pos += 4; err = resp.readInt16BE(pos); pos += 2; pos += 8; pos += 8;
34917
+ }
34918
+ }
34919
+ return err;
34920
+ }
34921
+ async function produce(topic, valueBytes) {
34922
+ const sock = await broker();
34923
+ for (let attempt = 1; attempt <= 10; attempt++) {
34924
+ const err = parseProduce(await rpc(sock, produceRequest(topic, valueBytes)));
34925
+ if (err === 0) return;
34926
+ if ((err !== 3 && err !== 5) || attempt === 10) {
34927
+ throw new Error("Kafka rejected the produce for topic " + topic + ": error code " + err);
34928
+ }
34929
+ await sleep(200);
34930
+ }
34931
+ }
34932
+
34933
+ // \u2500\u2500 fetch \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
34934
+ function fetchRequest(topic, offset) {
34935
+ const topicBuf = Buffer.from(topic, "utf-8");
34936
+ const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + 2 + topicBuf.length + 4 + 4 + 8 + 4);
34937
+ let p = 0;
34938
+ buf.writeInt32BE(-1, p); p += 4; // replicaId
34939
+ buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
34940
+ buf.writeInt32BE(1, p); p += 4; // minBytes
34941
+ buf.writeInt32BE(1048576, p); p += 4; // maxBytes
34942
+ buf.writeInt8(0, p); p += 1; // isolation READ_UNCOMMITTED
34943
+ buf.writeInt32BE(1, p); p += 4; // topics
34944
+ buf.writeInt16BE(topicBuf.length, p); p += 2;
34945
+ topicBuf.copy(buf, p); p += topicBuf.length;
34946
+ buf.writeInt32BE(1, p); p += 4; // partitions
34947
+ buf.writeInt32BE(0, p); p += 4; // partition 0
34948
+ buf.writeBigInt64BE(BigInt(offset), p); p += 8;
34949
+ buf.writeInt32BE(1048576, p); p += 4;
34950
+ return frame(1, FETCH_VERSION, buf);
34951
+ }
34952
+ // Decode the first record of the partition's record-set: its value string and
34953
+ // absolute offset (baseOffset + offsetDelta). null = no usable record.
34954
+ function firstRecord(buf, start, end) {
34955
+ let pos = start;
34956
+ while (pos + 12 <= end) {
34957
+ const baseOffset = buf.readBigInt64BE(pos);
34958
+ const batchLength = buf.readInt32BE(pos + 8);
34959
+ const batchStart = pos + 12;
34960
+ const batchEnd = batchStart + batchLength;
34961
+ if (batchLength <= 0 || batchEnd > end) break;
34962
+ const magic = buf.readInt8(batchStart + 4);
34963
+ if (magic !== 2) { pos = batchEnd; continue; }
34964
+ let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
34965
+ const recordsCount = buf.readInt32BE(r); r += 4;
34966
+ for (let i = 0; i < recordsCount && r < batchEnd; i++) {
34967
+ const recLen = readVarint(buf, r);
34968
+ let rp = recLen.next;
34969
+ const recordEnd = rp + recLen.value;
34970
+ rp += 1;
34971
+ rp = readVarint(buf, rp).next; // timestampDelta
34972
+ const offDelta = readVarint(buf, rp); rp = offDelta.next;
34973
+ const keyLen = readVarint(buf, rp); rp = keyLen.next;
34974
+ if (keyLen.value >= 0) rp += keyLen.value;
34975
+ const valLen = readVarint(buf, rp); rp = valLen.next;
34976
+ if (valLen.value >= 0) {
34977
+ return {
34978
+ value: buf.subarray(rp, rp + valLen.value).toString("utf-8"),
34979
+ offset: Number(baseOffset) + offDelta.value,
34980
+ };
34981
+ }
34982
+ r = recordEnd;
34983
+ }
34984
+ pos = batchEnd;
34985
+ }
34986
+ return null;
34987
+ }
34988
+ async function fetchAt(topic, offset) {
34989
+ const sock = await broker();
34990
+ const resp = await rpc(sock, fetchRequest(topic, offset));
34991
+ let pos = 4; // correlationId
34992
+ pos += 4; // throttleTimeMs
34993
+ const topicCount = resp.readInt32BE(pos); pos += 4;
34994
+ let rec = null;
34995
+ for (let t = 0; t < topicCount; t++) {
34996
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
34997
+ const pc = resp.readInt32BE(pos); pos += 4;
34998
+ for (let pi = 0; pi < pc; pi++) {
34999
+ pos += 4;
35000
+ const err = resp.readInt16BE(pos); pos += 2;
35001
+ pos += 8; pos += 8;
35002
+ const aborted = resp.readInt32BE(pos); pos += 4;
35003
+ if (aborted > 0) pos += aborted * 16;
35004
+ const recSize = resp.readInt32BE(pos); pos += 4;
35005
+ if (err !== 0 && err !== 3 && err !== 5) {
35006
+ throw new Error("Kafka rejected the fetch for topic " + topic + ": error code " + err);
35007
+ }
35008
+ if (err === 0 && recSize > 0) {
35009
+ const r = firstRecord(resp, pos, pos + recSize);
35010
+ if (r !== null) rec = r;
35011
+ }
35012
+ if (recSize > 0) pos += recSize;
35013
+ }
35014
+ }
35015
+ return rec;
35016
+ }
35017
+
35018
+ // \u2500\u2500 coordinator + offsets \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
35019
+ function readNullableString(buf, pos) {
35020
+ const len = buf.readInt16BE(pos); pos += 2;
35021
+ if (len < 0) return { value: null, next: pos };
35022
+ return { value: buf.toString("utf-8", pos, pos + len), next: pos + len };
35023
+ }
35024
+ async function findCoordinator() {
35025
+ const sock = await broker();
35026
+ for (let attempt = 0; attempt < 30; attempt++) {
35027
+ const body = Buffer.concat([kstr(groupId), Buffer.from([0])]); // key_type 0 = group
35028
+ const resp = await rpc(sock, frame(10, 1, body));
35029
+ let pos = 4; // correlationId
35030
+ pos += 4; // throttle
35031
+ const err = resp.readInt16BE(pos); pos += 2;
35032
+ pos = readNullableString(resp, pos).next; // error_message
35033
+ pos += 4; // node_id
35034
+ const hostRes = readNullableString(resp, pos); pos = hostRes.next;
35035
+ const port = resp.readInt32BE(pos);
35036
+ if (err === 0 && hostRes.value) return { host: hostRes.value, port: port };
35037
+ if (err !== 14 && err !== 15) {
35038
+ throw new Error("Kafka FindCoordinator failed for group " + groupId + ": error code " + err);
35039
+ }
35040
+ await sleep(300);
35041
+ }
35042
+ throw new Error("Kafka group coordinator for " + groupId + " did not become available");
35043
+ }
35044
+ async function coordinator() {
35045
+ if (coordSock) return coordSock;
35046
+ const c = await findCoordinator();
35047
+ coordSock = await connect(c.host, c.port);
35048
+ return coordSock;
35049
+ }
35050
+ function dropCoordinator() {
35051
+ if (coordSock) { try { coordSock.destroy(); } catch (e) { /* ignore */ } }
35052
+ coordSock = null;
35053
+ }
35054
+ function offsetCommitRequest(topic, offset) {
35055
+ const body = Buffer.concat([
35056
+ kstr(groupId),
35057
+ int32(-1), // generation_id -1 (simple consumer)
35058
+ kstr(""), // member_id ""
35059
+ int64(-1n), // retention_time -1
35060
+ int32(1), kstr(topic), int32(1), int32(0), int64(BigInt(offset)), int16(-1),
35061
+ ]);
35062
+ return frame(8, 2, body);
35063
+ }
35064
+ function parseOffsetCommit(resp) {
35065
+ let pos = 4;
35066
+ const tc = resp.readInt32BE(pos); pos += 4;
35067
+ if (tc === 0) return 16;
35068
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
35069
+ const pc = resp.readInt32BE(pos); pos += 4;
35070
+ if (pc === 0) return 16;
35071
+ pos += 4;
35072
+ return resp.readInt16BE(pos);
35073
+ }
35074
+ async function offsetCommit(topic, offset) {
35075
+ var err = 0;
35076
+ for (var attempt = 0; attempt < 10; attempt++) {
35077
+ if (attempt > 0) { dropCoordinator(); await new Promise(function (r) { setTimeout(r, 200 * attempt); }); }
35078
+ err = parseOffsetCommit(await rpc(await coordinator(), offsetCommitRequest(topic, offset)));
35079
+ if (COORDINATOR_ERRORS.indexOf(err) < 0) break;
35080
+ }
35081
+ if (err !== 0) throw new Error("Kafka rejected the offset commit for " + topic + ": error code " + err);
35082
+ }
35083
+ function offsetFetchRequest(topic) {
35084
+ const body = Buffer.concat([kstr(groupId), int32(1), kstr(topic), int32(1), int32(0)]);
35085
+ return frame(9, 1, body);
35086
+ }
35087
+ function parseOffsetFetch(resp) {
35088
+ let pos = 4;
35089
+ const tc = resp.readInt32BE(pos); pos += 4;
35090
+ if (tc === 0) return { offset: -1, err: 16 };
35091
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
35092
+ const pc = resp.readInt32BE(pos); pos += 4;
35093
+ if (pc === 0) return { offset: -1, err: 16 };
35094
+ pos += 4;
35095
+ const offset = Number(resp.readBigInt64BE(pos)); pos += 8;
35096
+ pos = readNullableString(resp, pos).next;
35097
+ const err = resp.readInt16BE(pos);
35098
+ return { offset: offset, err: err };
35099
+ }
35100
+ async function offsetFetch(topic) {
35101
+ var r = { offset: -1, err: 0 };
35102
+ for (var attempt = 0; attempt < 10; attempt++) {
35103
+ if (attempt > 0) { dropCoordinator(); await new Promise(function (res) { setTimeout(res, 200 * attempt); }); }
35104
+ r = parseOffsetFetch(await rpc(await coordinator(), offsetFetchRequest(topic)));
35105
+ if (COORDINATOR_ERRORS.indexOf(r.err) < 0) break;
35106
+ }
35107
+ if (r.err !== 0) throw new Error("Kafka rejected the offset fetch for " + topic + ": error code " + r.err);
35108
+ return r.offset < 0 ? 0 : r.offset;
35109
+ }
35110
+
35111
+ function int16(n) { const b = Buffer.alloc(2); b.writeInt16BE(n, 0); return b; }
35112
+ function int32(n) { const b = Buffer.alloc(4); b.writeInt32BE(n, 0); return b; }
35113
+ function int64(n) { const b = Buffer.alloc(8); b.writeBigInt64BE(BigInt(n), 0); return b; }
35114
+ function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
35115
+
35116
+ async function broker() {
35117
+ if (brokerSock) return brokerSock;
35118
+ const b = parseBroker(brokers);
35119
+ brokerSock = await connect(b.host, b.port);
35120
+ return brokerSock;
35121
+ }
35122
+
35123
+ // Resume from the committed offset on the FIRST read of a topic in this worker,
35124
+ // then advance the in-memory cursor; the committed offset only moves on a
35125
+ // commit, so it lags and a crash before commit replays (at-least-once).
35126
+ async function fetchNext(topic) {
35127
+ if (!(topic in offsets)) offsets[topic] = await offsetFetch(topic);
35128
+ const rec = await fetchAt(topic, offsets[topic]);
35129
+ if (rec === null) return null;
35130
+ offsets[topic] = rec.offset + 1;
35131
+ return rec;
35132
+ }
35133
+
35134
+ function encodeEnvelope(id, payload, attempts) {
35135
+ return JSON.stringify({ id: id, payload: payload, status: "pending", createdAt: new Date().toISOString(), attempts: attempts, delayUntil: null });
35136
+ }
35137
+
35138
+ async function handle(req) {
35139
+ const op = req.op;
35140
+ if (op === "publish") {
35141
+ await produce(req.topic, Buffer.from(req.value, "utf-8"));
35142
+ return { ok: true };
35143
+ }
35144
+ if (op === "dequeueRaw") {
35145
+ // The value exactly as it sits on the wire (a raw record stays its bare
35146
+ // bytes \u2014 tina4-nodejs#264), with no id/offset tracking. For wire
35147
+ // inspection; the facade consumes through "pop", which normalises + tracks.
35148
+ const rec = await fetchNext(req.topic);
35149
+ if (rec === null) return { ok: true, message: null };
35150
+ let decoded;
35151
+ try { decoded = JSON.parse(rec.value); } catch (e) { decoded = rec.value; }
35152
+ return { ok: true, message: decoded };
35153
+ }
35154
+ if (op === "pop") {
35155
+ let rec;
35156
+ try {
35157
+ rec = await fetchNext(req.topic);
35158
+ } catch (e) {
35159
+ // A malformed/short response runs the parser off the end (a RangeError);
35160
+ // anything else is a transport failure. Both name the topic so the cause
35161
+ // is findable, and neither reads as an empty queue (ADR: a real failure
35162
+ // must never look idle). Wording matches the Python/PHP backends.
35163
+ const range = (e instanceof RangeError) || /out of range|bounds/i.test((e && e.message) || "");
35164
+ if (range) throw new Error("Kafka fetch for topic " + req.topic + " returned an unreadable response: " + ((e && e.message) || e));
35165
+ throw new Error("Kafka fetch for topic " + req.topic + " failed: " + ((e && e.message) || e));
35166
+ }
35167
+ if (rec === null) return { ok: true, message: null };
35168
+ const coordinate = req.topic + ":0:" + rec.offset;
35169
+ let decoded;
35170
+ try { decoded = JSON.parse(rec.value); } catch (e) { decoded = null; }
35171
+ let message;
35172
+ let isEnvelope = false;
35173
+ if (decoded !== null && typeof decoded === "object" && !Array.isArray(decoded) && "payload" in decoded) {
35174
+ message = decoded;
35175
+ isEnvelope = true;
35176
+ if (!message.id) message.id = coordinate;
35177
+ } else {
35178
+ message = { id: coordinate, payload: decoded === null ? rec.value : decoded, status: "pending", attempts: 0 };
35179
+ }
35180
+ // The Job lifecycle (complete/fail/retry) routes by the record's own topic,
35181
+ // so it must be carried back (like the file/mongodb backends do).
35182
+ message.topic = req.topic;
35183
+ inFlight[String(message.id)] = { offset: rec.offset, value: rec.value, attempts: message.attempts || 0, isEnvelope: isEnvelope };
35184
+ return { ok: true, message: message };
35185
+ }
35186
+ if (op === "complete") {
35187
+ const rec = inFlight[String(req.id)];
35188
+ if (rec) { delete inFlight[String(req.id)]; await offsetCommit(req.topic, rec.offset + 1); }
35189
+ return { ok: true };
35190
+ }
35191
+ if (op === "fail") {
35192
+ const rec = inFlight[String(req.id)];
35193
+ if (rec) {
35194
+ delete inFlight[String(req.id)];
35195
+ const attempts = (rec.attempts || 0) + 1;
35196
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
35197
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
35198
+ if (attempts < req.maxRetries) {
35199
+ await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
35200
+ } else {
35201
+ await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: attempts, error: req.error }), "utf-8"));
35202
+ }
35203
+ await offsetCommit(req.topic, rec.offset + 1);
35204
+ }
35205
+ return { ok: true };
35206
+ }
35207
+ if (op === "reject") {
35208
+ const rec = inFlight[String(req.id)];
35209
+ if (rec) {
35210
+ delete inFlight[String(req.id)];
35211
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
35212
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
35213
+ await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: req.maxRetries, error: req.reason }), "utf-8"));
35214
+ await offsetCommit(req.topic, rec.offset + 1);
35215
+ }
35216
+ return { ok: true };
35217
+ }
35218
+ if (op === "retry") {
35219
+ const rec = inFlight[String(req.id)];
35220
+ if (rec) {
35221
+ delete inFlight[String(req.id)];
35222
+ const attempts = (rec.attempts || 0) + 1;
35223
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
35224
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
35225
+ await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
35226
+ await offsetCommit(req.topic, rec.offset + 1);
35227
+ }
35228
+ return { ok: true };
35229
+ }
35230
+ if (op === "deadLetters") {
35231
+ // Read the <topic>.dead_letter topic from the beginning; every record on it
35232
+ // is a dead letter by construction. A throwaway cursor that never commits,
35233
+ // so it does not disturb the main consume position.
35234
+ const dlq = req.topic + ".dead_letter";
35235
+ const out = [];
35236
+ let off = 0;
35237
+ for (;;) {
35238
+ const rec = await fetchAt(dlq, off);
35239
+ if (rec === null) break;
35240
+ off = rec.offset + 1;
35241
+ try { out.push(JSON.parse(rec.value)); } catch (e) { /* skip */ }
35242
+ if (out.length > 10000) break;
35243
+ }
35244
+ return { ok: true, deadLetters: out };
35245
+ }
35246
+ if (op === "close") {
35247
+ try { if (brokerSock) brokerSock.destroy(); } catch (e) { /* ignore */ }
35248
+ dropCoordinator();
35249
+ return { ok: true, closing: true };
35250
+ }
35251
+ return { ok: false, error: "unknown op " + op };
35252
+ }
35253
+
35254
+ parentPort.on("message", async function (req) {
35255
+ let res;
35256
+ try { res = await handle(req); }
35257
+ catch (e) { res = { ok: false, error: (e && e.message) ? e.message : String(e) }; }
35258
+ const bytes = Buffer.from(JSON.stringify(res), "utf-8");
35259
+ outBytes.set(bytes.subarray(0, outBytes.length), 0);
35260
+ Atomics.store(header, 1, Math.min(bytes.length, outBytes.length));
35261
+ Atomics.store(header, 0, 1);
35262
+ Atomics.notify(header, 0);
35263
+ });
35264
+ `;
35265
+ KafkaBackend = class _KafkaBackend {
35266
+ brokers;
35267
+ groupId;
35268
+ worker = null;
35269
+ sab = null;
35270
+ header = null;
35271
+ outBytes = null;
35272
+ static SAB_SIZE = 1 << 20;
35273
+ // 1 MiB (8-byte header + response bytes)
35274
+ static CALL_TIMEOUT_MS = 2e4;
35275
+ constructor(config) {
35276
+ const url = process.env.TINA4_QUEUE_URL;
35277
+ const fromUrl = url ? url.replace(/^kafka:\/\//, "") : void 0;
35278
+ this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
35279
+ this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
35280
+ }
35281
+ /** Resolved connection config — exposed for testing/introspection. */
35282
+ getConfig() {
35283
+ return { brokers: this.brokers, groupId: this.groupId };
35284
+ }
35285
+ securityConfig() {
35286
+ return kafkaSecurityConfig();
35287
+ }
35288
+ producerConfig() {
35289
+ return { "bootstrap.servers": this.brokers, "client.id": "tina4-nodejs", ...this.securityConfig() };
35290
+ }
35291
+ consumerConfig() {
35292
+ return {
35293
+ "bootstrap.servers": this.brokers,
35294
+ "client.id": "tina4-nodejs",
35295
+ "group.id": this.groupId,
35296
+ "auto.offset.reset": kafkaOffsetReset(),
35297
+ "enable.auto.commit": false,
35298
+ ...this.securityConfig()
35299
+ };
35300
+ }
35301
+ /** Lazily start the persistent worker + its shared buffer. */
35302
+ ensureWorker() {
35303
+ if (this.worker) return;
35304
+ this.sab = new SharedArrayBuffer(_KafkaBackend.SAB_SIZE);
35305
+ this.header = new Int32Array(this.sab, 0, 2);
35306
+ this.outBytes = new Uint8Array(this.sab, 8);
35307
+ this.worker = new Worker2(WORKER_SRC, {
35308
+ eval: true,
35309
+ workerData: {
35310
+ brokers: this.brokers,
35311
+ groupId: this.groupId,
35312
+ security: this.securityConfig(),
35313
+ offsetReset: kafkaOffsetReset(),
35314
+ sab: this.sab
35315
+ }
35316
+ });
35317
+ this.worker.unref();
35318
+ }
35319
+ /** One synchronous request to the worker: post, block on Atomics.wait, read. */
35320
+ request(req2) {
35321
+ this.ensureWorker();
35322
+ const header = this.header;
35323
+ const outBytes = this.outBytes;
35324
+ Atomics.store(header, 0, 0);
35325
+ this.worker.postMessage(req2);
35326
+ const waited = Atomics.wait(header, 0, 0, _KafkaBackend.CALL_TIMEOUT_MS);
35327
+ if (waited === "timed-out") {
35328
+ throw new Error(`Kafka ${String(req2.op)} for topic ${String(req2.topic ?? "")} timed out after ${_KafkaBackend.CALL_TIMEOUT_MS}ms`);
35329
+ }
35330
+ const len = Atomics.load(header, 1);
35331
+ const json = Buffer.from(outBytes.buffer, outBytes.byteOffset, len).toString("utf-8");
35332
+ const res = JSON.parse(json);
35333
+ if (res.ok === false) {
35334
+ throw new Error(String(res.error ?? "unknown Kafka worker error"));
35335
+ }
35336
+ return res;
35337
+ }
35338
+ /**
35339
+ * Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
35340
+ * as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
35341
+ * consumer reading the topic gets the schema it expects; otherwise the Tina4
35342
+ * job envelope. pop() unwraps both shapes (payload ?? the whole record).
35343
+ */
35344
+ static encodeJob(id, payload, raw) {
35345
+ if (raw) return JSON.stringify(payload);
35346
+ return JSON.stringify({
35347
+ id,
35348
+ payload,
35349
+ status: "pending",
35350
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
35351
+ attempts: 0,
35352
+ delayUntil: null
35353
+ });
35354
+ }
35355
+ push(queue, payload, _delay, _priority, raw = false) {
35356
+ const id = randomUUID6();
35357
+ const value = _KafkaBackend.encodeJob(id, payload, raw);
35358
+ this.request({ op: "publish", topic: queue, value });
35359
+ return id;
35360
+ }
35361
+ pop(queue) {
35362
+ const res = this.request({ op: "pop", topic: queue });
35363
+ const message = res.message;
35364
+ return message ?? null;
35365
+ }
35366
+ /**
35367
+ * Read the next record's value exactly as it sits on the wire — a Tina4
35368
+ * envelope as produced, a raw record (tina4-nodejs#264) as its bare bytes —
35369
+ * with no id/offset tracking. For a foreign consumer's view of the schema;
35370
+ * the queue facade consumes through pop(), which also normalises and tracks
35371
+ * the offset so complete()/fail() can commit it.
35372
+ */
35373
+ dequeue(queue) {
35374
+ const res = this.request({ op: "dequeueRaw", topic: queue });
35375
+ return res.message ?? null;
35376
+ }
35377
+ /** Commit the record's offset so a completed job never replays (ADR-0022 d.4). */
35378
+ complete(queue, id) {
35379
+ this.request({ op: "complete", topic: queue, id });
35380
+ }
35381
+ /**
35382
+ * Record a failed attempt: re-produce the job with an incremented attempts
35383
+ * count while it has retries left, else produce it to the dead-letter topic;
35384
+ * commit the original offset either way (ADR-0022 decision 2).
35385
+ */
35386
+ fail(queue, id, error2, maxRetries, _retryBackoff) {
35387
+ this.request({ op: "fail", topic: queue, id, error: error2, maxRetries });
35388
+ }
35389
+ /** Dead-letter the job now, no retry (ADR-0023 reject), then commit the offset. */
35390
+ reject(queue, id, reason, maxRetries) {
35391
+ this.request({ op: "reject", topic: queue, id, reason, maxRetries });
35392
+ }
35393
+ /** Re-produce the job (manual retry) and commit the original offset. */
35394
+ retry(queue, id, delaySeconds) {
35395
+ this.request({ op: "retry", topic: queue, id, delaySeconds: delaySeconds ?? 0 });
35396
+ return true;
35397
+ }
35398
+ /** Read the dead-letter topic for this queue (every record on it is a dead letter). */
35399
+ deadLetters(queue, _maxRetries) {
35400
+ const res = this.request({ op: "deadLetters", topic: queue });
35401
+ return res.deadLetters ?? [];
35402
+ }
35403
+ /**
35404
+ * Refuse rather than silently answer from the local file store. Kafka keeps no
35405
+ * queryable registry of failed jobs: a failed record is re-produced to a
35406
+ * dead-letter TOPIC and the original offset committed past, and a log cannot be
35407
+ * queried by job state. Returning [] would claim nothing has failed.
35408
+ */
35409
+ failed(_queue, _maxRetries) {
35410
+ throw new Error(
35411
+ "The kafka queue backend cannot answer failed(): Kafka keeps no queryable registry of failed or dead jobs. Consume the dead-letter topic directly (deadLetters()), or use the file or mongodb backend."
35412
+ );
35413
+ }
35414
+ /** Refuse for the same reason failed() does (no queryable failed registry). */
35415
+ retryFailed(_queue, _maxRetries) {
35416
+ throw new Error(
35417
+ "The kafka queue backend cannot perform retryFailed(): Kafka keeps no queryable registry of failed or dead jobs. Consume the dead-letter topic directly, or use the file or mongodb backend."
35418
+ );
35419
+ }
35420
+ size(_queue) {
35421
+ return 0;
35422
+ }
35423
+ clear(_queue) {
35424
+ throw new Error(
35425
+ "The kafka queue backend cannot perform clear(): Kafka has no notion of job status and cannot delete records on demand. A log is read in offset order and records leave only by retention. Use the file or mongodb backend."
35426
+ );
35427
+ }
35428
+ purge(_queue, _status) {
35429
+ throw new Error(
35430
+ "The kafka queue backend cannot perform purge(): Kafka has no notion of job status to purge by. A log is read in offset order and records leave only by retention. Use the file or mongodb backend."
35431
+ );
35432
+ }
35433
+ /** Stop the worker and release the connection. Idempotent. */
35434
+ close() {
35435
+ if (!this.worker) return;
35436
+ try {
35437
+ this.request({ op: "close" });
35438
+ } catch {
35439
+ }
35440
+ void this.worker.terminate();
35441
+ this.worker = null;
35442
+ this.sab = null;
35443
+ this.header = null;
35444
+ this.outBytes = null;
35445
+ }
35446
+ };
35447
+ }
35448
+ });
35449
+
34552
35450
  // src/job.ts
34553
35451
  function createJob(data, queue) {
34554
35452
  const job = {
@@ -34601,7 +35499,7 @@ var init_job = __esm({
34601
35499
  // src/queueBackends/liteBackend.ts
34602
35500
  import { mkdirSync as mkdirSync15, readdirSync as readdirSync12, readFileSync as readFileSync16, writeFileSync as writeFileSync11, unlinkSync as unlinkSync8, existsSync as existsSync19 } from "node:fs";
34603
35501
  import { join as join23 } from "node:path";
34604
- import { randomUUID as randomUUID6 } from "node:crypto";
35502
+ import { randomUUID as randomUUID7 } from "node:crypto";
34605
35503
  var LiteBackend;
34606
35504
  var init_liteBackend = __esm({
34607
35505
  "src/queueBackends/liteBackend.ts"() {
@@ -34668,7 +35566,7 @@ var init_liteBackend = __esm({
34668
35566
  );
34669
35567
  }
34670
35568
  const dir = this.ensureDir(queue);
34671
- const id = randomUUID6();
35569
+ const id = randomUUID7();
34672
35570
  const now = (/* @__PURE__ */ new Date()).toISOString();
34673
35571
  const job = {
34674
35572
  id,
@@ -35224,13 +36122,11 @@ function defaultVisibilityTimeout() {
35224
36122
  return Number.isFinite(parsed) ? parsed : 300;
35225
36123
  }
35226
36124
  function unsupportedBrokerMessage(backendName) {
35227
- const broker = backendName === "kafka" ? "Kafka" : "RabbitMQ";
35228
- const lost = backendName === "kafka" ? "every pop() re-read offset 0, so the topic could never drain" : "pop() destroyed the message with no acknowledgement, so a consumer that died lost the job";
35229
36125
  return `Queue backend "${backendName}" is not available in tina4-nodejs.
35230
36126
 
35231
- Reason: the ${broker} backend runs each operation in a separate child process, so no connection survives between pop() and complete(). Acknowledgement is therefore impossible, and ${lost}. It was losing work silently, so it now refuses instead.
36127
+ Reason: the RabbitMQ backend runs each operation in a separate child process, so no connection survives between pop() and complete(). Acknowledgement is therefore impossible, and pop() destroyed the message with no acknowledgement, so a consumer that died lost the job. It was losing work silently, so it now refuses instead.
35232
36128
 
35233
- Use backend "mongodb" (at-least-once, with a real reservation and visibility timeout) or the default "file" backend. tina4-python, tina4-php and tina4-ruby still offer ${broker}.
36129
+ Use backend "kafka" (now a persistent connection: at-least-once, drains, survives restarts), "mongodb" (at-least-once, real reservation + visibility timeout) or the default "file" backend. tina4-python, tina4-php and tina4-ruby still offer RabbitMQ.
35234
36130
 
35235
36131
  Tracking: ADR-0022 in tina4-documentation/plan/v3/DECISIONS.md, findings in plan/v3/features/048-queue-backends.md.`;
35236
36132
  }
@@ -35239,6 +36135,7 @@ var init_queue = __esm({
35239
36135
  "src/queue.ts"() {
35240
36136
  "use strict";
35241
36137
  init_mongoBackend();
36138
+ init_kafkaBackend();
35242
36139
  init_liteBackend();
35243
36140
  init_job();
35244
36141
  init_liteBackend();
@@ -35259,7 +36156,7 @@ var init_queue = __esm({
35259
36156
  * - new Queue("mongodb", { path: "data/queue" }) // legacy
35260
36157
  * - new Queue() // file backend, default topic
35261
36158
  *
35262
- * Throws on backend "rabbitmq" or "kafka" (ADR-0022).
36159
+ * Throws on backend "rabbitmq" (ADR-0022); "kafka" is now supported.
35263
36160
  */
35264
36161
  constructor(backendOrConfig, config) {
35265
36162
  let resolvedConfig = {};
@@ -35277,8 +36174,10 @@ var init_queue = __esm({
35277
36174
  this._retryBackoff = resolvedConfig.retryBackoff ?? 0;
35278
36175
  this._visibilityTimeout = resolvedConfig.visibilityTimeout ?? defaultVisibilityTimeout();
35279
36176
  this.liteBackend = new LiteBackend(this.basePath, this._visibilityTimeout);
35280
- if (this.backendName === "rabbitmq" || this.backendName === "kafka") {
36177
+ if (this.backendName === "rabbitmq") {
35281
36178
  throw new Error(unsupportedBrokerMessage(this.backendName));
36179
+ } else if (this.backendName === "kafka") {
36180
+ this.externalBackend = new KafkaBackend({ visibilityTimeout: this._visibilityTimeout });
35282
36181
  } else if (this.backendName === "mongodb" || this.backendName === "mongo") {
35283
36182
  this.externalBackend = new MongoBackend2({ visibilityTimeout: this._visibilityTimeout });
35284
36183
  } else if (!["file", "default", "lite"].includes(this.backendName)) {
@@ -38346,10 +39245,10 @@ function devGitStatusLabel(code) {
38346
39245
  async function devGitInfo(root) {
38347
39246
  const empty = { branch: "", gitRoot: null, status: /* @__PURE__ */ new Map() };
38348
39247
  try {
38349
- const { execFileSync: execFileSync7 } = await import("node:child_process");
39248
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
38350
39249
  const git = (args) => {
38351
39250
  try {
38352
- return execFileSync7("git", args, { cwd: root, timeout: 3e3, encoding: "utf-8" }).toString();
39251
+ return execFileSync6("git", args, { cwd: root, timeout: 3e3, encoding: "utf-8" }).toString();
38353
39252
  } catch {
38354
39253
  return null;
38355
39254
  }
@@ -40176,9 +41075,9 @@ var init_devAdmin = __esm({
40176
41075
  return;
40177
41076
  }
40178
41077
  try {
40179
- const { execFileSync: execFileSync7 } = await import("node:child_process");
41078
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
40180
41079
  const args = ["install", dev ? "--save-dev" : "--save", pkg];
40181
- const output = execFileSync7("npm", args, {
41080
+ const output = execFileSync6("npm", args, {
40182
41081
  cwd: resolve16(process.cwd()),
40183
41082
  timeout: 12e4,
40184
41083
  encoding: "utf-8"
@@ -40190,15 +41089,15 @@ var init_devAdmin = __esm({
40190
41089
  };
40191
41090
  handleGitStatus = async (_req, res) => {
40192
41091
  try {
40193
- const { execFileSync: execFileSync7 } = await import("node:child_process");
41092
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
40194
41093
  const cwd = resolve16(process.cwd());
40195
41094
  try {
40196
- execFileSync7("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
41095
+ execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
40197
41096
  } catch {
40198
41097
  res.json({ error: "Not a git repository" }, 400);
40199
41098
  return;
40200
41099
  }
40201
- const run = (args) => execFileSync7("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
41100
+ const run = (args) => execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
40202
41101
  res.json({
40203
41102
  branch: run(["branch", "--show-current"]),
40204
41103
  status: run(["status", "--porcelain"]).split(/\r?\n/).filter((l) => l),
@@ -40328,8 +41227,8 @@ var init_devAdmin = __esm({
40328
41227
  return;
40329
41228
  }
40330
41229
  try {
40331
- const { execFileSync: execFileSync7 } = await import("node:child_process");
40332
- const output = execFileSync7("npx", ["tina4nodejs", "generate", kind, name], {
41230
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
41231
+ const output = execFileSync6("npx", ["tina4nodejs", "generate", kind, name], {
40333
41232
  cwd: resolve16(process.cwd()),
40334
41233
  timeout: 3e4,
40335
41234
  encoding: "utf-8"
@@ -40775,6 +41674,359 @@ var init_background = __esm({
40775
41674
  }
40776
41675
  });
40777
41676
 
41677
+ // src/tcp.ts
41678
+ import { createServer as createServer3 } from "node:net";
41679
+ function resolveMaxBacklog(explicit) {
41680
+ if (explicit !== void 0) return explicit > 0 ? explicit : DEFAULT_MAX_BACKLOG;
41681
+ const raw = (process.env.TINA4_TCP_MAX_BACKLOG ?? "").trim();
41682
+ if (raw === "") return DEFAULT_MAX_BACKLOG;
41683
+ const value = Number.parseInt(raw, 10);
41684
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_BACKLOG;
41685
+ }
41686
+ function tcpService(port, options = {}) {
41687
+ const service = new TcpService(port, options);
41688
+ services.set(service.name, service);
41689
+ return service;
41690
+ }
41691
+ function tcp(name = "default") {
41692
+ const service = services.get(name);
41693
+ if (!service) {
41694
+ const known = services.size === 0 ? "(none registered)" : [...services.keys()].join(", ");
41695
+ throw new Error(`no tcp_service named '${name}' is registered; known services: ${known}`);
41696
+ }
41697
+ return service;
41698
+ }
41699
+ function registeredTcpServices() {
41700
+ return [...services.values()];
41701
+ }
41702
+ function clearTcpRegistry() {
41703
+ services.clear();
41704
+ }
41705
+ async function startAllTcpServices(host = "0.0.0.0") {
41706
+ for (const service of registeredTcpServices()) {
41707
+ try {
41708
+ await service.start(host);
41709
+ } catch (error2) {
41710
+ Log.error(`tcp_service '${service.name}' failed to start: ${String(error2)}`);
41711
+ }
41712
+ }
41713
+ }
41714
+ function stopAcceptingAllTcpServices() {
41715
+ for (const service of registeredTcpServices()) {
41716
+ try {
41717
+ service.stopAccepting();
41718
+ } catch (error2) {
41719
+ Log.error(`tcp_service '${service.name}' stop-accepting failed: ${String(error2)}`);
41720
+ }
41721
+ }
41722
+ }
41723
+ async function drainAllTcpServices() {
41724
+ for (const service of registeredTcpServices()) {
41725
+ try {
41726
+ await service.drain();
41727
+ } catch (error2) {
41728
+ Log.error(`tcp_service '${service.name}' drain failed: ${String(error2)}`);
41729
+ }
41730
+ }
41731
+ }
41732
+ var DEFAULT_MAX_BACKLOG, TcpConnection, TcpService, services;
41733
+ var init_tcp = __esm({
41734
+ "src/tcp.ts"() {
41735
+ "use strict";
41736
+ init_logger();
41737
+ DEFAULT_MAX_BACKLOG = 1 << 20;
41738
+ TcpConnection = class {
41739
+ constructor(socket, service) {
41740
+ this.socket = socket;
41741
+ this.service = service;
41742
+ this.remoteAddr = `${socket.remoteAddress ?? ""}:${socket.remotePort ?? 0}`;
41743
+ }
41744
+ socket;
41745
+ service;
41746
+ /** The registry id (the IMEI), or null until identify() is called. */
41747
+ id = null;
41748
+ /** Per-connection mutable state bag — the app's parse buffer, auth flag. */
41749
+ context = {};
41750
+ /** The raw TCP peer address ("127.0.0.1:54321"), never a forwarded header. */
41751
+ remoteAddr;
41752
+ lastActivity = Date.now();
41753
+ lineBuffer = Buffer.alloc(0);
41754
+ closed = false;
41755
+ closeFired = false;
41756
+ get isClosed() {
41757
+ return this.closed;
41758
+ }
41759
+ /**
41760
+ * Register this live connection under an app-chosen id (the IMEI). A second
41761
+ * connection identifying with the same id SUPERSEDES the first in the
41762
+ * registry — exactly a device that dropped and reconnected.
41763
+ */
41764
+ identify(appId) {
41765
+ this.id = String(appId);
41766
+ this.service._registerId(this.id, this);
41767
+ return this;
41768
+ }
41769
+ /**
41770
+ * Write raw bytes to THIS socket. Returns true when queued/sent, false when
41771
+ * the connection is closed or dropped for backpressure. A stalled reader
41772
+ * (never draining) is bounded: once more than the service's maxBacklog bytes
41773
+ * are outstanding, the connection is dropped rather than buffered without end
41774
+ * (mirrors the WebSocket TINA4_WS_MAX_BACKLOG posture).
41775
+ */
41776
+ send(data) {
41777
+ if (this.closed) return false;
41778
+ const buffer = typeof data === "string" ? Buffer.from(data) : data;
41779
+ this.socket.write(buffer);
41780
+ if (this.socket.writableLength > this.service.maxBacklog) {
41781
+ Log.warning(
41782
+ `tcp_service '${this.service.name}': dropping a stalled reader \u2014 ${this.socket.writableLength} bytes queued exceeds the ${this.service.maxBacklog}-byte backlog limit`
41783
+ );
41784
+ this.close();
41785
+ return false;
41786
+ }
41787
+ return true;
41788
+ }
41789
+ /**
41790
+ * Close this connection. on_close fires exactly once (from the socket's close
41791
+ * event) and the registry entry is removed.
41792
+ */
41793
+ close() {
41794
+ if (this.closed) return;
41795
+ this.closed = true;
41796
+ try {
41797
+ this.socket.end(() => this.socket.destroy());
41798
+ } catch {
41799
+ this.socket.destroy();
41800
+ }
41801
+ }
41802
+ /** @internal mark activity for the idle reaper. */
41803
+ _touch() {
41804
+ this.lastActivity = Date.now();
41805
+ }
41806
+ /** @internal fire on_close exactly once (called from the service removal path). */
41807
+ _fireClose() {
41808
+ if (this.closeFired) return;
41809
+ this.closeFired = true;
41810
+ this.closed = true;
41811
+ const handler = this.service._callbacks.onClose;
41812
+ if (!handler) return;
41813
+ try {
41814
+ void Promise.resolve(handler(this)).catch((error2) => {
41815
+ Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error2)}`);
41816
+ });
41817
+ } catch (error2) {
41818
+ Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error2)}`);
41819
+ }
41820
+ }
41821
+ };
41822
+ TcpService = class {
41823
+ name;
41824
+ port;
41825
+ maxBacklog;
41826
+ /** @internal the callback bag, read by TcpConnection. */
41827
+ _callbacks;
41828
+ idleTimeout;
41829
+ maxConnections;
41830
+ connections = /* @__PURE__ */ new Set();
41831
+ byId = /* @__PURE__ */ new Map();
41832
+ server = null;
41833
+ owner = false;
41834
+ boundPortValue = null;
41835
+ reaper = null;
41836
+ constructor(port, options = {}) {
41837
+ this.port = port;
41838
+ this.name = options.name ?? "default";
41839
+ this._callbacks = {
41840
+ onConnect: options.onConnect,
41841
+ onData: options.onData,
41842
+ onClose: options.onClose,
41843
+ onLine: options.onLine
41844
+ };
41845
+ this.idleTimeout = options.idleTimeout ?? 0;
41846
+ this.maxConnections = options.maxConnections ?? null;
41847
+ this.maxBacklog = resolveMaxBacklog(options.maxBacklog);
41848
+ }
41849
+ get isOwner() {
41850
+ return this.owner;
41851
+ }
41852
+ /** The port actually bound (resolves an ephemeral port=0 to the real one). */
41853
+ get boundPort() {
41854
+ return this.boundPortValue ?? this.port;
41855
+ }
41856
+ count() {
41857
+ return this.connections.size;
41858
+ }
41859
+ // ── Registry (D4 — server -> device push) ──────────────────────────────────
41860
+ /** @internal */
41861
+ _registerId(appId, conn) {
41862
+ this.byId.set(appId, conn);
41863
+ }
41864
+ /** The live connection for an app id, or null if unknown or closed. */
41865
+ connection(appId) {
41866
+ const conn = this.byId.get(String(appId));
41867
+ if (!conn || conn.isClosed) return null;
41868
+ return conn;
41869
+ }
41870
+ /**
41871
+ * Write bytes to exactly the connection identified by appId. A send to an
41872
+ * unknown or closed id is a NO-OP that returns false — never a throw.
41873
+ */
41874
+ sendTo(appId, data) {
41875
+ const conn = this.connection(appId);
41876
+ if (!conn) return false;
41877
+ return conn.send(data);
41878
+ }
41879
+ /** Write bytes to every live connection. Returns how many received it. */
41880
+ broadcast(data) {
41881
+ let delivered = 0;
41882
+ for (const conn of [...this.connections]) {
41883
+ if (conn.send(data)) delivered += 1;
41884
+ }
41885
+ return delivered;
41886
+ }
41887
+ // ── Lifecycle ───────────────────────────────────────────────────────────────
41888
+ /**
41889
+ * Bind the listener on host:port on the event loop. SO_REUSEPORT is OFF, so
41890
+ * under a multi-worker deployment exactly ONE worker wins the bind; a worker
41891
+ * that finds the port already bound skips silently (single-owner, D1).
41892
+ * Resolves true when THIS call bound the port.
41893
+ */
41894
+ start(host = "0.0.0.0") {
41895
+ if (this.server) return Promise.resolve(this.owner);
41896
+ return new Promise((resolve21) => {
41897
+ const server = createServer3((socket) => this.handleConnection(socket));
41898
+ this.server = server;
41899
+ const onError = (error2) => {
41900
+ if (error2.code === "EADDRINUSE" || error2.code === "EADDRNOTAVAIL") {
41901
+ this.owner = false;
41902
+ this.server = null;
41903
+ Log.info(
41904
+ `tcp_service '${this.name}' port ${this.port} is already bound by another worker \u2014 single-owner, this worker will not bind (${error2.code})`
41905
+ );
41906
+ resolve21(false);
41907
+ return;
41908
+ }
41909
+ Log.error(`tcp_service '${this.name}' failed to start: ${error2.message}`);
41910
+ this.server = null;
41911
+ resolve21(false);
41912
+ };
41913
+ server.once("error", onError);
41914
+ server.listen(this.port, host, () => {
41915
+ server.off("error", onError);
41916
+ server.on("error", (error2) => Log.error(`tcp_service '${this.name}' error: ${String(error2)}`));
41917
+ this.owner = true;
41918
+ const addr = server.address();
41919
+ this.boundPortValue = typeof addr === "object" && addr ? addr.port : this.port;
41920
+ Log.info(`tcp_service '${this.name}' listening on ${host}:${this.boundPortValue}`);
41921
+ this.startReaper();
41922
+ resolve21(true);
41923
+ });
41924
+ });
41925
+ }
41926
+ handleConnection(socket) {
41927
+ if (this.maxConnections !== null && this.connections.size >= this.maxConnections) {
41928
+ socket.destroy();
41929
+ return;
41930
+ }
41931
+ const conn = new TcpConnection(socket, this);
41932
+ this.connections.add(conn);
41933
+ socket.on("data", (chunk) => {
41934
+ socket.pause();
41935
+ void this.dispatch(conn, chunk).finally(() => {
41936
+ if (!conn.isClosed) socket.resume();
41937
+ });
41938
+ });
41939
+ socket.on("close", () => this.remove(conn));
41940
+ socket.on("error", () => {
41941
+ });
41942
+ const onConnect = this._callbacks.onConnect;
41943
+ if (onConnect) {
41944
+ void Promise.resolve(onConnect(conn)).catch((error2) => {
41945
+ Log.error(`tcp_service '${this.name}' onConnect error: ${String(error2)}`);
41946
+ });
41947
+ }
41948
+ }
41949
+ async dispatch(conn, chunk) {
41950
+ conn._touch();
41951
+ const { onData, onLine } = this._callbacks;
41952
+ if (onData) {
41953
+ try {
41954
+ await onData(conn, chunk);
41955
+ } catch (error2) {
41956
+ Log.error(`tcp_service '${this.name}' onData error: ${String(error2)}`);
41957
+ }
41958
+ }
41959
+ if (onLine) {
41960
+ conn.lineBuffer = Buffer.concat([conn.lineBuffer, chunk]);
41961
+ let newline = conn.lineBuffer.indexOf(10);
41962
+ while (newline !== -1) {
41963
+ let line = conn.lineBuffer.subarray(0, newline);
41964
+ conn.lineBuffer = conn.lineBuffer.subarray(newline + 1);
41965
+ if (line.length > 0 && line[line.length - 1] === 13) {
41966
+ line = line.subarray(0, line.length - 1);
41967
+ }
41968
+ try {
41969
+ await onLine(conn, line);
41970
+ } catch (error2) {
41971
+ Log.error(`tcp_service '${this.name}' onLine error: ${String(error2)}`);
41972
+ }
41973
+ newline = conn.lineBuffer.indexOf(10);
41974
+ }
41975
+ }
41976
+ }
41977
+ /** @internal remove a connection and fire on_close exactly once. */
41978
+ remove(conn) {
41979
+ const existed = this.connections.delete(conn);
41980
+ if (conn.id !== null && this.byId.get(conn.id) === conn) {
41981
+ this.byId.delete(conn.id);
41982
+ }
41983
+ if (existed) conn._fireClose();
41984
+ }
41985
+ // ── Idle reaper (D1 consumer shape — default OFF) ───────────────────────────
41986
+ startReaper() {
41987
+ if (this.idleTimeout <= 0 || this.reaper) return;
41988
+ const intervalMs = Math.max(50, Math.min(1e3, this.idleTimeout / 2 * 1e3));
41989
+ this.reaper = setInterval(() => this.reapIdle(), intervalMs);
41990
+ this.reaper.unref();
41991
+ }
41992
+ reapIdle() {
41993
+ const now = Date.now();
41994
+ const limitMs = this.idleTimeout * 1e3;
41995
+ for (const conn of [...this.connections]) {
41996
+ if (now - conn.lastActivity >= limitMs) conn.close();
41997
+ }
41998
+ }
41999
+ /** Stop accepting new connections (close the listener). Live conns stay. */
42000
+ stopAccepting() {
42001
+ if (this.reaper) {
42002
+ clearInterval(this.reaper);
42003
+ this.reaper = null;
42004
+ }
42005
+ if (this.server && this.owner) {
42006
+ this.server.close();
42007
+ }
42008
+ }
42009
+ /** Close every live connection (firing on_close) and release the listener. */
42010
+ async drain() {
42011
+ this.stopAccepting();
42012
+ for (const conn of [...this.connections]) conn.close();
42013
+ if (this.server) {
42014
+ await new Promise((resolve21) => {
42015
+ this.server.close(() => resolve21());
42016
+ this.server.unref();
42017
+ }).catch(() => void 0);
42018
+ this.server = null;
42019
+ }
42020
+ }
42021
+ /** Stop accepting and drain in one call (used by direct callers/tests). */
42022
+ async stop() {
42023
+ await this.drain();
42024
+ }
42025
+ };
42026
+ services = /* @__PURE__ */ new Map();
42027
+ }
42028
+ });
42029
+
40778
42030
  // src/events.ts
40779
42031
  var events_exports = {};
40780
42032
  __export(events_exports, {
@@ -42983,7 +44235,7 @@ async function startServer(config) {
42983
44235
  server.on("upgrade", (req2, socket, head) => {
42984
44236
  const upPath = (req2.url ?? "/").split("?")[0];
42985
44237
  if (isDevMode() && upPath === "/__dev_reload") {
42986
- if (!devHostAllowed(req2.headers.host)) {
44238
+ if (!devHostAllowed(req2.headers.host) || !devPeerAllowed(socket.remoteAddress)) {
42987
44239
  try {
42988
44240
  socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
42989
44241
  socket.destroy();
@@ -43007,6 +44259,7 @@ async function startServer(config) {
43007
44259
  server.listen(port, host, async () => {
43008
44260
  if (!cluster.isWorker) writePidfile(port);
43009
44261
  const siblingServers = await startLoopbackSiblings(port, host, dispatch);
44262
+ await startAllTcpServices(host);
43010
44263
  const displayHost = host === "0.0.0.0" ? "localhost" : host;
43011
44264
  const isDebug = isTruthy(process.env.TINA4_DEBUG);
43012
44265
  const logLevel = (process.env.TINA4_LOG_LEVEL ?? "DEBUG").toUpperCase();
@@ -43097,6 +44350,8 @@ ${reset2}
43097
44350
  if (wsClosed > 0) {
43098
44351
  Log.info(`Closed ${wsClosed} WebSocket connection(s) with 1001 going away`);
43099
44352
  }
44353
+ stopAcceptingAllTcpServices();
44354
+ await drainAllTcpServices();
43100
44355
  const budgetSeconds = shutdownTimeoutSeconds();
43101
44356
  let timer;
43102
44357
  const outcome = await Promise.race([
@@ -43139,6 +44394,8 @@ ${reset2}
43139
44394
  process.off("SIGTERM", onSigterm);
43140
44395
  process.off("SIGINT", onSigint);
43141
44396
  stopAllBackgroundTasks();
44397
+ stopAcceptingAllTcpServices();
44398
+ void drainAllTcpServices();
43142
44399
  if (aiServer) aiServer.close();
43143
44400
  server.close();
43144
44401
  for (const sibling of siblingServers) {
@@ -43267,6 +44524,7 @@ var init_server = __esm({
43267
44524
  init_feedback();
43268
44525
  init_i18n();
43269
44526
  init_background();
44527
+ init_tcp();
43270
44528
  init_version();
43271
44529
  __filename = fileURLToPath8(import.meta.url);
43272
44530
  __dirname = dirname15(__filename);
@@ -45625,7 +46883,7 @@ import net4 from "node:net";
45625
46883
  import tls2 from "node:tls";
45626
46884
  import { readFileSync as readFileSync25 } from "node:fs";
45627
46885
  import { basename as basename7 } from "node:path";
45628
- import { randomUUID as randomUUID7 } from "node:crypto";
46886
+ import { randomUUID as randomUUID8 } from "node:crypto";
45629
46887
  function normaliseEncryption(value, kind) {
45630
46888
  const normalised = value.trim().toLowerCase();
45631
46889
  if (!MAIL_ENCRYPTION_VALUES.includes(normalised)) {
@@ -46257,7 +47515,7 @@ var init_messenger = __esm({
46257
47515
  );
46258
47516
  }
46259
47517
  const recipients = this.prepareRecipients(options, true);
46260
- const messageId = `${randomUUID7()}@${this.host}`;
47518
+ const messageId = `${randomUUID8()}@${this.host}`;
46261
47519
  if (recipients.allRecipients.length === 0) {
46262
47520
  return { success: false, message: "No recipients specified", id: null };
46263
47521
  }
@@ -49099,7 +50357,7 @@ var init_aiClient = __esm({
49099
50357
 
49100
50358
  // src/queueBackends/rabbitmqBackend.ts
49101
50359
  import { execFileSync as execFileSync5 } from "node:child_process";
49102
- import { randomUUID as randomUUID8 } from "node:crypto";
50360
+ import { randomUUID as randomUUID9 } from "node:crypto";
49103
50361
  function parseAmqpUrl(url) {
49104
50362
  const config = {};
49105
50363
  let rest = url.replace(/^amqps:\/\//, "").replace(/^amqp:\/\//, "");
@@ -49535,7 +50793,7 @@ var init_rabbitmqBackend = __esm({
49535
50793
  "The rabbitmq queue backend cannot honour push(raw=true): raw emits the message with no Tina4 envelope, which only a message bus consumed by non-Tina4 systems (Kafka) needs. This backend stores an internal envelope (payload/priority/attempts) that pop(), the retry lifecycle and dead-lettering depend on, so there is nothing to omit. Use the kafka backend for raw external messages."
49536
50794
  );
49537
50795
  }
49538
- const id = randomUUID8();
50796
+ const id = randomUUID9();
49539
50797
  const now = (/* @__PURE__ */ new Date()).toISOString();
49540
50798
  const job = {
49541
50799
  id,
@@ -49579,586 +50837,6 @@ var init_rabbitmqBackend = __esm({
49579
50837
  }
49580
50838
  });
49581
50839
 
49582
- // src/queueBackends/kafkaBackend.ts
49583
- import { execFileSync as execFileSync6 } from "node:child_process";
49584
- import { randomUUID as randomUUID9 } from "node:crypto";
49585
- function kafkaSecurityConfig(env = process.env) {
49586
- const mapping = [
49587
- ["security.protocol", "SECURITY_PROTOCOL"],
49588
- ["ssl.ca.location", "SSL_CA_LOCATION"],
49589
- ["sasl.mechanism", "SASL_MECHANISM"],
49590
- ["sasl.username", "SASL_USERNAME"],
49591
- ["sasl.password", "SASL_PASSWORD"]
49592
- ];
49593
- const config = {};
49594
- for (const [rdk, suffix] of mapping) {
49595
- const value = env[`TINA4_KAFKA_${suffix}`] || env[`KAFKA_${suffix}`];
49596
- if (value) {
49597
- config[rdk] = value;
49598
- }
49599
- }
49600
- return config;
49601
- }
49602
- function kafkaOffsetReset(env = process.env) {
49603
- return env.TINA4_KAFKA_AUTO_OFFSET_RESET || env.KAFKA_AUTO_OFFSET_RESET || "earliest";
49604
- }
49605
- var API_PRODUCE, API_FETCH, KafkaBackend;
49606
- var init_kafkaBackend = __esm({
49607
- "src/queueBackends/kafkaBackend.ts"() {
49608
- "use strict";
49609
- API_PRODUCE = 0;
49610
- API_FETCH = 1;
49611
- KafkaBackend = class _KafkaBackend {
49612
- brokers;
49613
- groupId;
49614
- constructor(config) {
49615
- const url = process.env.TINA4_QUEUE_URL;
49616
- const fromUrl = url ? url.replace(/^kafka:\/\//, "") : void 0;
49617
- this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
49618
- this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
49619
- }
49620
- /**
49621
- * Resolved connection config — exposed for testing/introspection.
49622
- */
49623
- getConfig() {
49624
- return { brokers: this.brokers, groupId: this.groupId };
49625
- }
49626
- /**
49627
- * Resolved SSL/SASL client config from the environment (PLAINTEXT default).
49628
- * Mirrors Python's `KafkaConnector._security_config`.
49629
- */
49630
- securityConfig() {
49631
- return kafkaSecurityConfig();
49632
- }
49633
- /**
49634
- * Full producer config — brokers + client id + the resolved security block.
49635
- * The security keys are applied to BOTH producer and consumer (matching
49636
- * Python's `_connect_confluent`).
49637
- */
49638
- producerConfig() {
49639
- return {
49640
- "bootstrap.servers": this.brokers,
49641
- "client.id": "tina4-nodejs",
49642
- ...this.securityConfig()
49643
- };
49644
- }
49645
- /**
49646
- * Full consumer config — brokers + client id + group id + the SAME resolved
49647
- * security block applied to the producer.
49648
- */
49649
- consumerConfig() {
49650
- return {
49651
- "bootstrap.servers": this.brokers,
49652
- "client.id": "tina4-nodejs",
49653
- "group.id": this.groupId,
49654
- "auto.offset.reset": kafkaOffsetReset(),
49655
- "enable.auto.commit": false,
49656
- ...this.securityConfig()
49657
- };
49658
- }
49659
- /**
49660
- * Parse broker string into host:port.
49661
- */
49662
- parseBroker() {
49663
- const parts = this.brokers.split(",")[0].trim().split(":");
49664
- return {
49665
- host: parts[0] ?? "localhost",
49666
- port: parts[1] ? parseInt(parts[1], 10) : 9092
49667
- };
49668
- }
49669
- /**
49670
- * Execute a Kafka operation synchronously via a child process.
49671
- *
49672
- * The wire protocol is hand-rolled (Tina4 is zero-dependency — no npm Kafka
49673
- * library). Produce uses Produce **v3** carrying a Kafka **v2 RecordBatch**
49674
- * (magic byte 2) with a **CRC-32C** (Castagnoli) checksum; Fetch uses Fetch
49675
- * **v4** and parses the v2 RecordBatch out of the response. Both formats are
49676
- * what a modern KRaft broker (apache/kafka 3.7.0) requires — the old
49677
- * Produce-v0 / message-format-v0 / CRC=0 batch is rejected by such brokers.
49678
- */
49679
- execSync(operation, topic, data) {
49680
- const broker = this.parseBroker();
49681
- const script = `
49682
- const net = require("node:net");
49683
- const host = ${JSON.stringify(broker.host)};
49684
- const port = ${broker.port};
49685
- const operation = ${JSON.stringify(operation)};
49686
- const topic = ${JSON.stringify(topic)};
49687
- const groupId = ${JSON.stringify(this.groupId)};
49688
- const data = ${JSON.stringify(data ?? "")};
49689
- const API_PRODUCE = ${API_PRODUCE};
49690
- const API_FETCH = ${API_FETCH};
49691
- const PRODUCE_VERSION = 3; // v3+ requires the v2 RecordBatch format
49692
- const FETCH_VERSION = 4; // v4 returns v2 RecordBatches + isolation_level
49693
- let correlationId = 0;
49694
-
49695
- // \u2500\u2500 CRC-32C (Castagnoli, polynomial 0x1EDC6F41), table-based \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
49696
- // Node has no built-in CRC-32C; the v2 RecordBatch mandates it over the
49697
- // bytes from \`attributes\` to the end of the batch. A wrong CRC makes the
49698
- // broker drop the connection, so this must be exact.
49699
- const CRC32C_TABLE = (() => {
49700
- const table = new Uint32Array(256);
49701
- for (let n = 0; n < 256; n++) {
49702
- let c = n;
49703
- for (let k = 0; k < 8; k++) {
49704
- c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
49705
- }
49706
- table[n] = c >>> 0;
49707
- }
49708
- return table;
49709
- })();
49710
- function crc32c(buf) {
49711
- let crc = 0xffffffff;
49712
- for (let i = 0; i < buf.length; i++) {
49713
- crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
49714
- }
49715
- return (crc ^ 0xffffffff) >>> 0;
49716
- }
49717
-
49718
- // \u2500\u2500 Kafka protocol varints (zigzag-encoded signed varints) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
49719
- function encodeZigZag(n) {
49720
- // 32-bit zigzag: (n << 1) ^ (n >> 31)
49721
- return ((n << 1) ^ (n >> 31)) >>> 0;
49722
- }
49723
- function encodeVarintUnsigned(u) {
49724
- const bytes = [];
49725
- let v = u >>> 0;
49726
- while (true) {
49727
- if ((v & ~0x7f) === 0) { bytes.push(v); break; }
49728
- bytes.push((v & 0x7f) | 0x80);
49729
- v >>>= 7;
49730
- }
49731
- return Buffer.from(bytes);
49732
- }
49733
- function encodeVarint(n) {
49734
- // signed varint = zigzag then unsigned-varint
49735
- return encodeVarintUnsigned(encodeZigZag(n));
49736
- }
49737
- function decodeVarint(buf, pos) {
49738
- // returns { value, next } \u2014 signed (zigzag-decoded)
49739
- let result = 0, shift = 0, b;
49740
- do {
49741
- b = buf[pos++];
49742
- result |= (b & 0x7f) << shift;
49743
- shift += 7;
49744
- } while (b & 0x80);
49745
- result = result >>> 0;
49746
- // zigzag decode
49747
- const value = (result >>> 1) ^ -(result & 1);
49748
- return { value, next: pos };
49749
- }
49750
-
49751
- // \u2500\u2500 v2 RecordBatch builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
49752
- function buildRecordBatch(valueBytes) {
49753
- const now = BigInt(Date.now());
49754
-
49755
- // Build the single record body.
49756
- // record = attributes:int8(0), timestampDelta:varint(0),
49757
- // offsetDelta:varint(0), keyLen:varint(-1 null),
49758
- // valueLen:varint(len), value, headerCount:varint(0)
49759
- const recBody = Buffer.concat([
49760
- Buffer.from([0]), // attributes (int8)
49761
- encodeVarint(0), // timestampDelta
49762
- encodeVarint(0), // offsetDelta
49763
- encodeVarint(-1), // keyLen (-1 = null key)
49764
- encodeVarint(valueBytes.length), // valueLen
49765
- valueBytes, // value (JSON payload bytes)
49766
- encodeVarint(0), // headerCount
49767
- ]);
49768
- // record length prefix = signed varint of recBody length
49769
- const record = Buffer.concat([encodeVarint(recBody.length), recBody]);
49770
- const recordsCount = 1;
49771
-
49772
- // The portion the CRC covers starts at \`attributes\` and runs to end.
49773
- // crcBody = attributes:int16(0), lastOffsetDelta:int32(count-1),
49774
- // firstTimestamp:int64, maxTimestamp:int64,
49775
- // producerId:int64(-1), producerEpoch:int16(-1),
49776
- // baseSequence:int32(-1), recordsCount:int32, records
49777
- const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
49778
- let c = 0;
49779
- crcBody.writeInt16BE(0, c); c += 2; // attributes
49780
- crcBody.writeInt32BE(recordsCount - 1, c); c += 4; // lastOffsetDelta
49781
- crcBody.writeBigInt64BE(now, c); c += 8; // firstTimestamp
49782
- crcBody.writeBigInt64BE(now, c); c += 8; // maxTimestamp
49783
- crcBody.writeBigInt64BE(-1n, c); c += 8; // producerId
49784
- crcBody.writeInt16BE(-1, c); c += 2; // producerEpoch
49785
- crcBody.writeInt32BE(-1, c); c += 4; // baseSequence
49786
- crcBody.writeInt32BE(recordsCount, c); c += 4; // recordsCount
49787
- record.copy(crcBody, c);
49788
-
49789
- const crc = crc32c(crcBody);
49790
-
49791
- // Header before the CRC-covered region:
49792
- // baseOffset:int64(0), batchLength:int32, partitionLeaderEpoch:int32(-1),
49793
- // magic:int8(2), crc:uint32. batchLength counts everything AFTER itself
49794
- // (partitionLeaderEpoch through end of records) = 4 + 1 + 4 + crcBody.
49795
- const batchLength = 4 + 1 + 4 + crcBody.length;
49796
- const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
49797
- let h = 0;
49798
- head.writeBigInt64BE(0n, h); h += 8; // baseOffset
49799
- head.writeInt32BE(batchLength, h); h += 4; // batchLength
49800
- head.writeInt32BE(-1, h); h += 4; // partitionLeaderEpoch
49801
- head.writeInt8(2, h); h += 1; // magic = 2
49802
- head.writeUInt32BE(crc, h); h += 4; // crc (CRC-32C)
49803
-
49804
- return Buffer.concat([head, crcBody]);
49805
- }
49806
-
49807
- // \u2500\u2500 Produce v3 request \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
49808
- function buildProduceRequest(topicName, valueBytes) {
49809
- correlationId++;
49810
- const clientBuf = Buffer.from("tina4", "utf-8");
49811
- const topicBuf = Buffer.from(topicName, "utf-8");
49812
- const recordBatch = buildRecordBatch(valueBytes);
49813
-
49814
- const body = Buffer.alloc(
49815
- 2 + // transactionalId (-1 null nullable_string)
49816
- 2 + // acks
49817
- 4 + // timeoutMs
49818
- 4 + // topics array count
49819
- 2 + topicBuf.length + // topic name
49820
- 4 + // partitions array count
49821
- 4 + // partition index
49822
- 4 + recordBatch.length // recordSetBytes (int32 size) + batch
49823
- );
49824
- let p = 0;
49825
- body.writeInt16BE(-1, p); p += 2; // transactionalId = null
49826
- body.writeInt16BE(1, p); p += 2; // acks = 1
49827
- body.writeInt32BE(10000, p); p += 4; // timeoutMs
49828
- body.writeInt32BE(1, p); p += 4; // topics count
49829
- body.writeInt16BE(topicBuf.length, p); p += 2;
49830
- topicBuf.copy(body, p); p += topicBuf.length;
49831
- body.writeInt32BE(1, p); p += 4; // partitions count
49832
- body.writeInt32BE(0, p); p += 4; // partition index 0
49833
- body.writeInt32BE(recordBatch.length, p); p += 4; // recordSetBytes size
49834
- recordBatch.copy(body, p);
49835
-
49836
- return frameRequest(API_PRODUCE, PRODUCE_VERSION, clientBuf, body);
49837
- }
49838
-
49839
- // \u2500\u2500 Fetch v4 request \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
49840
- function buildFetchRequest(topicName, fetchOffset) {
49841
- correlationId++;
49842
- const clientBuf = Buffer.from("tina4", "utf-8");
49843
- const topicBuf = Buffer.from(topicName, "utf-8");
49844
-
49845
- // Fetch v4 request body (NO logStartOffset \u2014 that arrives in v5+):
49846
- // replicaId(4), maxWaitMs(4), minBytes(4), maxBytes(4 v3+),
49847
- // isolationLevel(1 v4+), topics[count]: name, partitions[count]:
49848
- // partition(4), fetchOffset(8), partitionMaxBytes(4).
49849
- const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + (2 + topicBuf.length) + 4 + 4 + 8 + 4);
49850
- let p = 0;
49851
- buf.writeInt32BE(-1, p); p += 4; // replicaId (-1 consumer)
49852
- buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
49853
- buf.writeInt32BE(1, p); p += 4; // minBytes
49854
- buf.writeInt32BE(1048576, p); p += 4; // maxBytes
49855
- buf.writeInt8(0, p); p += 1; // isolationLevel = READ_UNCOMMITTED
49856
- buf.writeInt32BE(1, p); p += 4; // topics count
49857
- buf.writeInt16BE(topicBuf.length, p); p += 2;
49858
- topicBuf.copy(buf, p); p += topicBuf.length;
49859
- buf.writeInt32BE(1, p); p += 4; // partitions count
49860
- buf.writeInt32BE(0, p); p += 4; // partition 0
49861
- buf.writeBigInt64BE(BigInt(fetchOffset), p); p += 8; // fetchOffset
49862
- buf.writeInt32BE(1048576, p); p += 4; // partitionMaxBytes
49863
-
49864
- return frameRequest(API_FETCH, FETCH_VERSION, clientBuf, buf);
49865
- }
49866
-
49867
- // Frame a request with header v1: apiKey, apiVersion, correlationId,
49868
- // clientId (nullable string) + body.
49869
- function frameRequest(apiKey, apiVersion, clientBuf, body) {
49870
- const header = Buffer.alloc(2 + 2 + 4 + 2 + clientBuf.length);
49871
- let p = 0;
49872
- header.writeInt16BE(apiKey, p); p += 2;
49873
- header.writeInt16BE(apiVersion, p); p += 2;
49874
- header.writeInt32BE(correlationId, p); p += 4;
49875
- header.writeInt16BE(clientBuf.length, p); p += 2;
49876
- clientBuf.copy(header, p);
49877
- const payload = Buffer.concat([header, body]);
49878
- const framed = Buffer.alloc(4 + payload.length);
49879
- framed.writeInt32BE(payload.length, 0);
49880
- payload.copy(framed, 4);
49881
- return framed;
49882
- }
49883
-
49884
- // \u2500\u2500 Parse a v2 RecordBatch region, return the FIRST record value \u2500\u2500\u2500\u2500\u2500\u2500\u2500
49885
- // \`buf\` is the whole fetch response; [start, end) bounds the partition's
49886
- // record-set bytes (may contain one or more concatenated batches).
49887
- function firstRecordValue(buf, start, end) {
49888
- let pos = start;
49889
- while (pos + 12 <= end) {
49890
- // baseOffset(8) + batchLength(4) then batchLength bytes follow.
49891
- const batchLength = buf.readInt32BE(pos + 8);
49892
- const batchStart = pos + 12; // first byte of partitionLeaderEpoch
49893
- const batchEnd = batchStart + batchLength;
49894
- if (batchLength <= 0 || batchEnd > end) break;
49895
- // partitionLeaderEpoch(4), magic(1), crc(4), attributes(2),
49896
- // lastOffsetDelta(4), firstTimestamp(8), maxTimestamp(8),
49897
- // producerId(8), producerEpoch(2), baseSequence(4), recordsCount(4)
49898
- const magic = buf.readInt8(batchStart + 4);
49899
- if (magic !== 2) { pos = batchEnd; continue; }
49900
- let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
49901
- const recordsCount = buf.readInt32BE(r); r += 4;
49902
- for (let i = 0; i < recordsCount && r < batchEnd; i++) {
49903
- const recLen = decodeVarint(buf, r); // record length (signed varint)
49904
- let rp = recLen.next;
49905
- const recordEnd = rp + recLen.value;
49906
- rp += 1; // attributes (int8)
49907
- const tsDelta = decodeVarint(buf, rp); rp = tsDelta.next;
49908
- const offDelta = decodeVarint(buf, rp); rp = offDelta.next;
49909
- const keyLen = decodeVarint(buf, rp); rp = keyLen.next;
49910
- if (keyLen.value >= 0) rp += keyLen.value;
49911
- const valLen = decodeVarint(buf, rp); rp = valLen.next;
49912
- if (valLen.value >= 0) {
49913
- return buf.subarray(rp, rp + valLen.value).toString("utf-8");
49914
- }
49915
- r = recordEnd;
49916
- }
49917
- pos = batchEnd;
49918
- }
49919
- return null;
49920
- }
49921
-
49922
- let finished = false;
49923
- function finish(out, code) {
49924
- if (finished) return;
49925
- finished = true;
49926
- clearTimeout(timer);
49927
- try { sock.destroy(); } catch (e) { /* ignore */ }
49928
- if (out) process.stdout.write(out);
49929
- // Flush stdout before exiting so execFileSync captures it.
49930
- process.stdout.write("", () => process.exit(code));
49931
- }
49932
-
49933
- const sock = net.createConnection({ host, port }, () => {
49934
- if (operation === "publish") {
49935
- const req = buildProduceRequest(topic, Buffer.from(data, "utf-8"));
49936
- sock.write(req);
49937
- } else if (operation === "get") {
49938
- sock.write(buildFetchRequest(topic, 0));
49939
- } else {
49940
- finish("__UNSUPPORTED__", 0);
49941
- }
49942
- });
49943
-
49944
- let buffer = Buffer.alloc(0);
49945
- sock.on("data", (chunk) => {
49946
- buffer = Buffer.concat([buffer, chunk]);
49947
- if (buffer.length < 4) return;
49948
- const respSize = buffer.readInt32BE(0);
49949
- if (buffer.length < 4 + respSize) return;
49950
-
49951
- if (operation === "publish") {
49952
- // Produce v3 response (after the 4-byte frame size): correlationId(4),
49953
- // topics[count]: name, partitions[count]: partition(4), errorCode(2),
49954
- // baseOffset(8), logAppendTime(8); then throttleTimeMs(4) at the END.
49955
- // Only the per-partition error code matters here.
49956
- try {
49957
- let pos = 4 + 4; // skip frame size + correlationId
49958
- const topicCount = buffer.readInt32BE(pos); pos += 4;
49959
- let errCode = 0;
49960
- for (let t = 0; t < topicCount; t++) {
49961
- const tl = buffer.readInt16BE(pos); pos += 2 + tl;
49962
- const pc = buffer.readInt32BE(pos); pos += 4;
49963
- for (let pi = 0; pi < pc; pi++) {
49964
- pos += 4; // partition index
49965
- errCode = buffer.readInt16BE(pos); pos += 2; // error code
49966
- pos += 8; // baseOffset
49967
- pos += 8; // logAppendTime (v2+)
49968
- }
49969
- }
49970
- if (errCode === 0) {
49971
- finish("__PUBLISHED__", 0);
49972
- } else {
49973
- // Report the CODE, not just "it failed" \u2014 the caller decides
49974
- // whether it is retriable (3/5, the async topic-creation race)
49975
- // or fatal (e.g. 29 TOPIC_AUTHORIZATION_FAILED).
49976
- process.stderr.write("Produce error code " + errCode);
49977
- finish("__PRODUCEERROR__" + errCode, 0);
49978
- }
49979
- } catch (e) {
49980
- process.stderr.write("produce parse: " + e.message);
49981
- finish("__PARSEERROR__produce: " + e.message, 0);
49982
- }
49983
- return;
49984
- } else if (operation === "get") {
49985
- // Fetch v4 response (after the 4-byte frame size): correlationId(4),
49986
- // throttleTimeMs(4), topics[count]: name, partitions[count]:
49987
- // partition(4), errorCode(2), highWatermark(8), lastStableOffset(8),
49988
- // abortedTxns[count](producerId(8)+firstOffset(8)),
49989
- // recordSetBytes(int32)+batch.
49990
- try {
49991
- let pos = 4 + 4; // frame size + correlationId
49992
- pos += 4; // throttleTimeMs (v1+)
49993
- const topicCount = buffer.readInt32BE(pos); pos += 4;
49994
- let out = "__EMPTY__";
49995
- let fatalCode = 0;
49996
- for (let t = 0; t < topicCount; t++) {
49997
- const tl = buffer.readInt16BE(pos); pos += 2 + tl;
49998
- const pc = buffer.readInt32BE(pos); pos += 4;
49999
- for (let pi = 0; pi < pc; pi++) {
50000
- pos += 4; // partition index
50001
- const errCode = buffer.readInt16BE(pos); pos += 2;
50002
- pos += 8; // highWatermark
50003
- pos += 8; // lastStableOffset (v4+)
50004
- const abortedCount = buffer.readInt32BE(pos); pos += 4;
50005
- if (abortedCount > 0) pos += abortedCount * 16; // (-1 => none, skip)
50006
- const recSetSize = buffer.readInt32BE(pos); pos += 4;
50007
- // 3 = UNKNOWN_TOPIC_OR_PARTITION, 5 = LEADER_NOT_AVAILABLE:
50008
- // "nothing to read here yet", which a consumer that starts
50009
- // before its producer hits on every cold start. Any OTHER code
50010
- // (29 TOPIC_AUTHORIZATION_FAILED, 13 STALE_CONTROLLER_EPOCH, \u2026)
50011
- // is a real failure and must NOT be reported as an empty queue.
50012
- if (errCode !== 0 && errCode !== 3 && errCode !== 5) {
50013
- fatalCode = errCode;
50014
- }
50015
- if (errCode === 0 && recSetSize > 0) {
50016
- const val = firstRecordValue(buffer, pos, pos + recSetSize);
50017
- if (val !== null) out = val;
50018
- }
50019
- pos += recSetSize > 0 ? recSetSize : 0;
50020
- }
50021
- }
50022
- if (fatalCode !== 0) {
50023
- process.stderr.write("Fetch error code " + fatalCode);
50024
- finish("__FETCHERROR__" + fatalCode, 0);
50025
- return;
50026
- }
50027
- finish(out, 0);
50028
- } catch (e) {
50029
- // A parse failure is NOT an empty queue either \u2014 say so.
50030
- process.stderr.write("fetch parse: " + e.message);
50031
- finish("__PARSEERROR__fetch: " + e.message, 0);
50032
- }
50033
- return;
50034
- }
50035
- });
50036
-
50037
- // Report the reason on STDOUT and exit 0. Writing it to stderr and
50038
- // exiting non-zero LOST it: stderr to a pipe is an async write and
50039
- // process.exit() truncates it, so the parent saw an empty stderr and fell
50040
- // back to execFileSync's message -- which embeds this entire script.
50041
- // stdout is flushed by finish()'s write callback, so it survives.
50042
- sock.on("error", (err) => {
50043
- finish("__TRANSPORTERROR__" + err.message, 0);
50044
- });
50045
-
50046
- var timer = setTimeout(() => {
50047
- finish("__TRANSPORTERROR__timed out after 10s talking to " + host + ":" + port, 0);
50048
- }, 10000);
50049
- `;
50050
- try {
50051
- const result = execFileSync6(process.execPath, ["-e", script], {
50052
- encoding: "utf-8",
50053
- timeout: 15e3,
50054
- stdio: ["pipe", "pipe", "pipe"]
50055
- });
50056
- return result;
50057
- } catch (err) {
50058
- const e = err;
50059
- const reason = String(e.stderr ?? "").trim() || e.message || "unknown error";
50060
- const firstLine = reason.split("\n", 1)[0].slice(0, 200);
50061
- return "__TRANSPORTERROR__" + firstLine;
50062
- }
50063
- }
50064
- /**
50065
- * Sleep synchronously between produce retries.
50066
- *
50067
- * `push()` is synchronous (the whole backend drives its socket through a child
50068
- * process), so there is no event loop to await on. `Atomics.wait` on a
50069
- * SharedArrayBuffer is the stdlib way to block a thread for a fixed time --
50070
- * no dependency, no busy-wait burning CPU.
50071
- */
50072
- static sleepSync(ms) {
50073
- const shared = new Int32Array(new SharedArrayBuffer(4));
50074
- Atomics.wait(shared, 0, 0, ms);
50075
- }
50076
- /**
50077
- * Turn a sentinel from the protocol child into a thrown error, or return.
50078
- *
50079
- * The wording matches the Python and PHP backends exactly -- the parity rule
50080
- * covers user-visible error messages, not just behaviour.
50081
- */
50082
- static assertNoError(result, operation, topic) {
50083
- const fatal = /^__(PRODUCEERROR|FETCHERROR)__(\d+)/.exec(result);
50084
- if (fatal) {
50085
- throw new Error(
50086
- `Kafka rejected the ${operation} for topic ${topic}: error code ${fatal[2]}`
50087
- );
50088
- }
50089
- if (result.startsWith("__TRANSPORTERROR__")) {
50090
- throw new Error(
50091
- `Kafka ${operation} for topic ${topic} failed: ` + result.slice("__TRANSPORTERROR__".length)
50092
- );
50093
- }
50094
- if (result.startsWith("__PARSEERROR__")) {
50095
- throw new Error(
50096
- `Kafka ${operation} for topic ${topic} returned an unreadable response: ` + result.slice("__PARSEERROR__".length)
50097
- );
50098
- }
50099
- }
50100
- /**
50101
- * Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
50102
- * as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
50103
- * consumer reading the topic gets the schema it expects; otherwise the Tina4 job
50104
- * envelope. pop() unwraps both shapes (payload ?? the whole record).
50105
- */
50106
- static encodeJob(id, payload, raw) {
50107
- if (raw) return JSON.stringify(payload);
50108
- return JSON.stringify({
50109
- id,
50110
- payload,
50111
- status: "pending",
50112
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
50113
- attempts: 0,
50114
- delayUntil: null
50115
- });
50116
- }
50117
- push(queue, payload, _delay, _priority, raw = false) {
50118
- const id = randomUUID9();
50119
- const body = _KafkaBackend.encodeJob(id, payload, raw);
50120
- let result = "";
50121
- for (let attempt = 1; attempt <= 10; attempt++) {
50122
- result = this.execSync("publish", queue, body);
50123
- if (result.includes("__PUBLISHED__")) {
50124
- return id;
50125
- }
50126
- const retriable = /^__PRODUCEERROR__(3|5)\b/.test(result);
50127
- if (!retriable || attempt === 10) {
50128
- break;
50129
- }
50130
- _KafkaBackend.sleepSync(200);
50131
- }
50132
- _KafkaBackend.assertNoError(result, "produce", queue);
50133
- throw new Error(`Kafka publish failed for topic ${queue}: ${result || "no response"}`);
50134
- }
50135
- pop(queue) {
50136
- const result = this.execSync("get", queue);
50137
- _KafkaBackend.assertNoError(result, "fetch", queue);
50138
- if (!result || result === "__EMPTY__" || result === "__UNSUPPORTED__") return null;
50139
- try {
50140
- return JSON.parse(result);
50141
- } catch {
50142
- return null;
50143
- }
50144
- }
50145
- size(_queue) {
50146
- return 0;
50147
- }
50148
- clear(_queue) {
50149
- throw new Error(
50150
- "The kafka queue backend cannot perform clear(): Kafka has no notion of job status and cannot delete records on demand. A log is read in offset order and records leave only by retention. Use the file or mongodb backend."
50151
- );
50152
- }
50153
- purge(_queue, _status) {
50154
- throw new Error(
50155
- "The kafka queue backend cannot perform purge(): Kafka has no notion of job status to purge by. A log is read in offset order and records leave only by retention. Use the file or mongodb backend."
50156
- );
50157
- }
50158
- };
50159
- }
50160
- });
50161
-
50162
50840
  // src/testing.ts
50163
50841
  function expectEqual(args, expected) {
50164
50842
  return { type: "equal", args, expected };
@@ -50934,6 +51612,8 @@ __export(index_exports, {
50934
51612
  TEXT_PLAIN: () => TEXT_PLAIN,
50935
51613
  TEXT_XML: () => TEXT_XML,
50936
51614
  TINA4_VERSION: () => TINA4_VERSION,
51615
+ TcpConnection: () => TcpConnection,
51616
+ TcpService: () => TcpService,
50937
51617
  TestClient: () => TestClient,
50938
51618
  TestResponse: () => TestResponse,
50939
51619
  Tina4AssertionError: () => AssertionError,
@@ -50976,6 +51656,7 @@ __export(index_exports, {
50976
51656
  checkPassword: () => checkPassword,
50977
51657
  clearCache: () => clearCache,
50978
51658
  clearCurrentNonce: () => clearCurrentNonce,
51659
+ clearTcpRegistry: () => clearTcpRegistry,
50979
51660
  computeAcceptKey: () => computeAcceptKey,
50980
51661
  container: () => container,
50981
51662
  cors: () => cors,
@@ -50997,6 +51678,7 @@ __export(index_exports, {
50997
51678
  devAdminLanguage: () => devAdminLanguage,
50998
51679
  devReloadWs: () => devReloadWs,
50999
51680
  discoverRoutes: () => discoverRoutes,
51681
+ drainAllTcpServices: () => drainAllTcpServices,
51000
51682
  encodeError: () => encodeError,
51001
51683
  encodeNotification: () => encodeNotification,
51002
51684
  encodeResponse: () => encodeResponse,
@@ -51084,6 +51766,7 @@ __export(index_exports, {
51084
51766
  refreshToken: () => refreshToken,
51085
51767
  registerDevTools: () => registerDevTools,
51086
51768
  registerFeedbackRoutes: () => registerFeedbackRoutes,
51769
+ registeredTcpServices: () => registeredTcpServices,
51087
51770
  removePidfile: () => removePidfile,
51088
51771
  renderErrorOverlay: () => renderErrorOverlay,
51089
51772
  requestLogger: () => requestLogger,
@@ -51114,12 +51797,16 @@ __export(index_exports, {
51114
51797
  setFrond: () => setFrond,
51115
51798
  showMenu: () => showMenu,
51116
51799
  start: () => start,
51800
+ startAllTcpServices: () => startAllTcpServices,
51117
51801
  startServer: () => startServer,
51118
51802
  stop: () => stop,
51803
+ stopAcceptingAllTcpServices: () => stopAcceptingAllTcpServices,
51119
51804
  stopAllBackgroundTasks: () => stopAllBackgroundTasks,
51120
51805
  supervisorBaseUrl: () => supervisorBaseUrl,
51121
51806
  sweep: () => sweep,
51122
51807
  takeOverPort: () => takeOverPort,
51808
+ tcp: () => tcp,
51809
+ tcpService: () => tcpService,
51123
51810
  templateAutoRoutingEnabled: () => templateAutoRoutingEnabled,
51124
51811
  tests: () => tests,
51125
51812
  trustedProxyNetworks: () => trustedProxyNetworks,
@@ -51138,6 +51825,7 @@ var init_index = __esm({
51138
51825
  "src/index.ts"() {
51139
51826
  init_server();
51140
51827
  init_background();
51828
+ init_tcp();
51141
51829
  init_router();
51142
51830
  init_router();
51143
51831
  init_routeDiscovery();
@@ -51326,6 +52014,8 @@ export {
51326
52014
  TEXT_PLAIN,
51327
52015
  TEXT_XML,
51328
52016
  TINA4_VERSION,
52017
+ TcpConnection,
52018
+ TcpService,
51329
52019
  TestClient,
51330
52020
  TestResponse,
51331
52021
  AssertionError as Tina4AssertionError,
@@ -51368,6 +52058,7 @@ export {
51368
52058
  checkPassword,
51369
52059
  clearCache,
51370
52060
  clearCurrentNonce,
52061
+ clearTcpRegistry,
51371
52062
  computeAcceptKey,
51372
52063
  container,
51373
52064
  cors,
@@ -51389,6 +52080,7 @@ export {
51389
52080
  devAdminLanguage,
51390
52081
  devReloadWs,
51391
52082
  discoverRoutes,
52083
+ drainAllTcpServices,
51392
52084
  encodeError,
51393
52085
  encodeNotification,
51394
52086
  encodeResponse,
@@ -51476,6 +52168,7 @@ export {
51476
52168
  refreshToken,
51477
52169
  registerDevTools,
51478
52170
  registerFeedbackRoutes,
52171
+ registeredTcpServices,
51479
52172
  removePidfile,
51480
52173
  renderErrorOverlay,
51481
52174
  requestLogger,
@@ -51506,12 +52199,16 @@ export {
51506
52199
  setFrond,
51507
52200
  showMenu,
51508
52201
  start,
52202
+ startAllTcpServices,
51509
52203
  startServer,
51510
52204
  stop,
52205
+ stopAcceptingAllTcpServices,
51511
52206
  stopAllBackgroundTasks,
51512
52207
  supervisorBaseUrl,
51513
52208
  sweep,
51514
52209
  takeOverPort,
52210
+ tcp,
52211
+ tcpService,
51515
52212
  templateAutoRoutingEnabled,
51516
52213
  tests,
51517
52214
  trustedProxyNetworks,