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.
@@ -5551,6 +5551,7 @@ var init_csp = __esm({
5551
5551
  var engine_exports = {};
5552
5552
  __export(engine_exports, {
5553
5553
  Frond: () => Frond,
5554
+ FrondSyntaxError: () => FrondSyntaxError,
5554
5555
  MEMO_CACHE_MAX: () => MEMO_CACHE_MAX,
5555
5556
  TEMPLATE_CACHE_MAX: () => TEMPLATE_CACHE_MAX,
5556
5557
  escapeHtml: () => escapeHtml,
@@ -6683,6 +6684,87 @@ function isEscapableStructured(value) {
6683
6684
  function toOutputString(value) {
6684
6685
  return String(value);
6685
6686
  }
6687
+ function phpDate(dt, fmt) {
6688
+ const pad = (n) => String(n).padStart(2, "0");
6689
+ const hours = dt.getHours();
6690
+ const h12 = hours % 12 || 12;
6691
+ const dow = dt.getDay();
6692
+ const iso2 = dow === 0 ? 7 : dow;
6693
+ let out = "";
6694
+ for (let i = 0; i < fmt.length; i++) {
6695
+ const c = fmt[i];
6696
+ if (c === "\\" && i + 1 < fmt.length) {
6697
+ out += fmt[i + 1];
6698
+ i++;
6699
+ continue;
6700
+ }
6701
+ switch (c) {
6702
+ case "Y":
6703
+ out += String(dt.getFullYear());
6704
+ break;
6705
+ case "y":
6706
+ out += pad(dt.getFullYear() % 100);
6707
+ break;
6708
+ case "m":
6709
+ out += pad(dt.getMonth() + 1);
6710
+ break;
6711
+ case "n":
6712
+ out += String(dt.getMonth() + 1);
6713
+ break;
6714
+ case "d":
6715
+ out += pad(dt.getDate());
6716
+ break;
6717
+ case "j":
6718
+ out += String(dt.getDate());
6719
+ break;
6720
+ case "H":
6721
+ out += pad(hours);
6722
+ break;
6723
+ case "G":
6724
+ out += String(hours);
6725
+ break;
6726
+ case "h":
6727
+ out += pad(h12);
6728
+ break;
6729
+ case "g":
6730
+ out += String(h12);
6731
+ break;
6732
+ case "i":
6733
+ out += pad(dt.getMinutes());
6734
+ break;
6735
+ case "s":
6736
+ out += pad(dt.getSeconds());
6737
+ break;
6738
+ case "A":
6739
+ out += hours < 12 ? "AM" : "PM";
6740
+ break;
6741
+ case "a":
6742
+ out += hours < 12 ? "am" : "pm";
6743
+ break;
6744
+ case "D":
6745
+ out += PHP_DAYS[dow].slice(0, 3);
6746
+ break;
6747
+ case "l":
6748
+ out += PHP_DAYS[dow];
6749
+ break;
6750
+ case "M":
6751
+ out += PHP_MONTHS[dt.getMonth()].slice(0, 3);
6752
+ break;
6753
+ case "F":
6754
+ out += PHP_MONTHS[dt.getMonth()];
6755
+ break;
6756
+ case "N":
6757
+ out += String(iso2);
6758
+ break;
6759
+ case "w":
6760
+ out += String(dow);
6761
+ break;
6762
+ default:
6763
+ out += c;
6764
+ }
6765
+ }
6766
+ return out;
6767
+ }
6686
6768
  function dateFilter(value, fmt) {
6687
6769
  let dt;
6688
6770
  if (value instanceof Date) {
@@ -6695,6 +6777,7 @@ function dateFilter(value, fmt) {
6695
6777
  } else {
6696
6778
  return String(value);
6697
6779
  }
6780
+ if (!fmt.includes("%")) return phpDate(dt, fmt);
6698
6781
  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" }));
6699
6782
  }
6700
6783
  function wordwrap(text, width) {
@@ -6805,7 +6888,7 @@ function _generateFormToken(descriptor = "") {
6805
6888
  function _generateFormTokenValue(descriptor = "") {
6806
6889
  return new SafeString(_buildFormTokenJwt(descriptor));
6807
6890
  }
6808
- 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;
6891
+ 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;
6809
6892
  var init_engine = __esm({
6810
6893
  "../frond/src/engine.ts"() {
6811
6894
  "use strict";
@@ -7002,6 +7085,35 @@ var init_engine = __esm({
7002
7085
  "__defineProperty__",
7003
7086
  "valueOf"
7004
7087
  ]);
7088
+ FrondSyntaxError = class extends Error {
7089
+ constructor(message) {
7090
+ super(message);
7091
+ this.name = "FrondSyntaxError";
7092
+ }
7093
+ };
7094
+ PHP_MONTHS = [
7095
+ "January",
7096
+ "February",
7097
+ "March",
7098
+ "April",
7099
+ "May",
7100
+ "June",
7101
+ "July",
7102
+ "August",
7103
+ "September",
7104
+ "October",
7105
+ "November",
7106
+ "December"
7107
+ ];
7108
+ PHP_DAYS = [
7109
+ "Sunday",
7110
+ "Monday",
7111
+ "Tuesday",
7112
+ "Wednesday",
7113
+ "Thursday",
7114
+ "Friday",
7115
+ "Saturday"
7116
+ ];
7005
7117
  BUILTIN_FILTERS = {
7006
7118
  upper: (v) => String(v).toUpperCase(),
7007
7119
  lower: (v) => String(v).toLowerCase(),
@@ -7525,7 +7637,9 @@ var init_engine = __esm({
7525
7637
  }
7526
7638
  }
7527
7639
  if (depth > 0) {
7528
- pos = contentStart;
7640
+ throw new FrondSyntaxError(
7641
+ `{% block ${name} %} is never closed (missing or malformed {% endblock %})`
7642
+ );
7529
7643
  }
7530
7644
  }
7531
7645
  return blocks;
@@ -7592,9 +7706,9 @@ var init_engine = __esm({
7592
7706
  }
7593
7707
  }
7594
7708
  if (!closeMatch) {
7595
- pieces.push(source.slice(mOpen.index));
7596
- pos = source.length;
7597
- break;
7709
+ throw new FrondSyntaxError(
7710
+ `{% block ${name} %} is never closed (missing or malformed {% endblock %})`
7711
+ );
7598
7712
  }
7599
7713
  const parentContent = source.slice(contentStart, closeMatch.index);
7600
7714
  const blockSource = blocks[name] ?? parentContent;
@@ -9152,6 +9266,9 @@ function attachCsrfFromEnv() {
9152
9266
  }
9153
9267
  return false;
9154
9268
  }
9269
+ function logPath(req2) {
9270
+ return req2.path ?? (req2.url ?? "/").split("?")[0];
9271
+ }
9155
9272
  function requestLogger() {
9156
9273
  return (req2, res, next) => {
9157
9274
  const start2 = Date.now();
@@ -9160,8 +9277,7 @@ function requestLogger() {
9160
9277
  const duration = Date.now() - start2;
9161
9278
  const status2 = res.raw.statusCode;
9162
9279
  const method = req2.method ?? "?";
9163
- const url = req2.url ?? "/";
9164
- Log.info(`${method} ${url} -> ${status2} (${duration}ms)`);
9280
+ Log.info(`${method} ${logPath(req2)} -> ${status2} (${duration}ms)`);
9165
9281
  });
9166
9282
  next();
9167
9283
  };
@@ -9588,9 +9704,9 @@ var init_middleware = __esm({
9588
9704
  const duration = Date.now() - (req2.startTime ?? Date.now());
9589
9705
  const status2 = res.raw.statusCode;
9590
9706
  const method = req2.method ?? "?";
9591
- const url = req2.url ?? "/";
9707
+ const path10 = logPath(req2);
9592
9708
  const color = status2 >= 400 ? "\x1B[31m" : status2 >= 300 ? "\x1B[33m" : "\x1B[32m";
9593
- console.log(` ${color}${status2}\x1B[0m ${method} ${url} \x1B[90m${duration}ms\x1B[0m`);
9709
+ console.log(` ${color}${status2}\x1B[0m ${method} ${path10} \x1B[90m${duration}ms\x1B[0m`);
9594
9710
  return [req2, res];
9595
9711
  }
9596
9712
  };
@@ -16584,9 +16700,9 @@ function agentLog(projectRoot3, category, message) {
16584
16700
  if (!fs4.existsSync(logDir)) {
16585
16701
  fs4.mkdirSync(logDir, { recursive: true });
16586
16702
  }
16587
- const logPath = path3.join(logDir, "agent.log");
16703
+ const logPath2 = path3.join(logDir, "agent.log");
16588
16704
  const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/\..+/, "Z");
16589
- fs4.appendFileSync(logPath, `${ts} [${category}] ${message}
16705
+ fs4.appendFileSync(logPath2, `${ts} [${category}] ${message}
16590
16706
  `, "utf-8");
16591
16707
  } catch {
16592
16708
  }
@@ -17582,13 +17698,13 @@ function registerDevTools(server) {
17582
17698
  "git_status",
17583
17699
  () => {
17584
17700
  try {
17585
- const { execFileSync: execFileSync7 } = req("node:child_process");
17701
+ const { execFileSync: execFileSync6 } = req("node:child_process");
17586
17702
  const cwd = path3.resolve(process.cwd());
17587
17703
  const run = (args) => {
17588
- return execFileSync7("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
17704
+ return execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
17589
17705
  };
17590
17706
  try {
17591
- execFileSync7("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
17707
+ execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
17592
17708
  } catch {
17593
17709
  return { error: "Not a git repository" };
17594
17710
  }
@@ -21481,6 +21597,753 @@ var init_mongoBackend = __esm({
21481
21597
  }
21482
21598
  });
21483
21599
 
21600
+ // ../core/src/queueBackends/kafkaBackend.ts
21601
+ import { Worker as Worker2 } from "node:worker_threads";
21602
+ import { randomUUID as randomUUID5 } from "node:crypto";
21603
+ function kafkaSecurityConfig(env = process.env) {
21604
+ const mapping = [
21605
+ ["security.protocol", "SECURITY_PROTOCOL"],
21606
+ ["ssl.ca.location", "SSL_CA_LOCATION"],
21607
+ ["sasl.mechanism", "SASL_MECHANISM"],
21608
+ ["sasl.username", "SASL_USERNAME"],
21609
+ ["sasl.password", "SASL_PASSWORD"]
21610
+ ];
21611
+ const config = {};
21612
+ for (const [rdk, suffix] of mapping) {
21613
+ const value = env[`TINA4_KAFKA_${suffix}`] || env[`KAFKA_${suffix}`];
21614
+ if (value) {
21615
+ config[rdk] = value;
21616
+ }
21617
+ }
21618
+ return config;
21619
+ }
21620
+ function kafkaOffsetReset(env = process.env) {
21621
+ return env.TINA4_KAFKA_AUTO_OFFSET_RESET || env.KAFKA_AUTO_OFFSET_RESET || "earliest";
21622
+ }
21623
+ var WORKER_SRC, KafkaBackend;
21624
+ var init_kafkaBackend = __esm({
21625
+ "../core/src/queueBackends/kafkaBackend.ts"() {
21626
+ "use strict";
21627
+ WORKER_SRC = `
21628
+ const net = require("node:net");
21629
+ const tls = require("node:tls");
21630
+ const { parentPort, workerData } = require("node:worker_threads");
21631
+
21632
+ const brokers = workerData.brokers;
21633
+ const groupId = workerData.groupId;
21634
+ const security = workerData.security || {};
21635
+ const offsetReset = workerData.offsetReset || "earliest";
21636
+ const header = new Int32Array(workerData.sab, 0, 2); // [0]=flag, [1]=respLen
21637
+ const outBytes = new Uint8Array(workerData.sab, 8);
21638
+
21639
+ // Lowest versions Kafka 4.x still accepts: it REMOVED Produce v0-v2 / Fetch v0-v3
21640
+ // (the old message formats) and answers a removed version by closing the socket,
21641
+ // not with an error code. These are named constants so the source invariant test
21642
+ // (test/kafkaErrorCodes.test.ts) can assert the floors.
21643
+ const PRODUCE_VERSION = 3;
21644
+ const FETCH_VERSION = 4;
21645
+
21646
+ let correlationId = 0;
21647
+ let brokerSock = null;
21648
+ let coordSock = null;
21649
+ const offsets = {}; // topic -> next read offset (in-memory cursor)
21650
+ const inFlight = {}; // job id -> { offset, value, attempts, isEnvelope }
21651
+
21652
+ const COORDINATOR_ERRORS = [14, 15, 16];
21653
+
21654
+ function parseBroker(list) {
21655
+ const first = String(list).split(",")[0].trim();
21656
+ const i = first.lastIndexOf(":");
21657
+ if (i < 0) return { host: first || "localhost", port: 9092 };
21658
+ return { host: first.slice(0, i) || "localhost", port: parseInt(first.slice(i + 1), 10) || 9092 };
21659
+ }
21660
+
21661
+ function connect(host, port) {
21662
+ return new Promise(function (resolve, reject) {
21663
+ const proto = String(security["security.protocol"] || "PLAINTEXT").toUpperCase();
21664
+ const useTls = proto.indexOf("SSL") >= 0;
21665
+ let sock;
21666
+ const onErr = function (e) { reject(e); };
21667
+ if (useTls) {
21668
+ const opts = { host: host, port: port, servername: host };
21669
+ if (security["ssl.ca.location"]) opts.ca = require("node:fs").readFileSync(security["ssl.ca.location"]);
21670
+ sock = tls.connect(opts, function () { sock.removeListener("error", onErr); resolve(sock); });
21671
+ } else {
21672
+ sock = net.createConnection({ host: host, port: port }, function () { sock.removeListener("error", onErr); resolve(sock); });
21673
+ }
21674
+ sock.once("error", onErr);
21675
+ });
21676
+ }
21677
+
21678
+ // One request/response round trip on a socket: write the framed request, read a
21679
+ // 4-byte length then that many bytes, resolve with the payload AFTER the length
21680
+ // (so it starts at correlationId). Serialized \u2014 one in flight per socket.
21681
+ function rpc(sock, reqBuf) {
21682
+ return new Promise(function (resolve, reject) {
21683
+ let buf = Buffer.alloc(0);
21684
+ function onData(chunk) {
21685
+ buf = Buffer.concat([buf, chunk]);
21686
+ if (buf.length < 4) return;
21687
+ const size = buf.readInt32BE(0);
21688
+ if (buf.length < 4 + size) return;
21689
+ sock.removeListener("data", onData);
21690
+ sock.removeListener("error", onErr);
21691
+ resolve(buf.subarray(4, 4 + size));
21692
+ }
21693
+ function onErr(e) {
21694
+ sock.removeListener("data", onData);
21695
+ reject(e);
21696
+ }
21697
+ sock.on("data", onData);
21698
+ sock.once("error", onErr);
21699
+ sock.write(reqBuf);
21700
+ });
21701
+ }
21702
+
21703
+ // \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
21704
+ function kstr(s) {
21705
+ const b = Buffer.from(s, "utf-8");
21706
+ const out = Buffer.alloc(2 + b.length);
21707
+ out.writeInt16BE(b.length, 0);
21708
+ b.copy(out, 2);
21709
+ return out;
21710
+ }
21711
+ function frame(apiKey, apiVersion, body) {
21712
+ correlationId++;
21713
+ const client = Buffer.from("tina4-nodejs", "utf-8");
21714
+ const head = Buffer.alloc(2 + 2 + 4 + 2 + client.length);
21715
+ let p = 0;
21716
+ head.writeInt16BE(apiKey, p); p += 2;
21717
+ head.writeInt16BE(apiVersion, p); p += 2;
21718
+ head.writeInt32BE(correlationId, p); p += 4;
21719
+ head.writeInt16BE(client.length, p); p += 2;
21720
+ client.copy(head, p);
21721
+ const payload = Buffer.concat([head, body]);
21722
+ const out = Buffer.alloc(4 + payload.length);
21723
+ out.writeInt32BE(payload.length, 0);
21724
+ payload.copy(out, 4);
21725
+ return out;
21726
+ }
21727
+
21728
+ // \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
21729
+ const CRC32C_TABLE = (function () {
21730
+ const t = new Uint32Array(256);
21731
+ for (let n = 0; n < 256; n++) {
21732
+ let c = n;
21733
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
21734
+ t[n] = c >>> 0;
21735
+ }
21736
+ return t;
21737
+ })();
21738
+ function crc32c(buf) {
21739
+ let crc = 0xffffffff;
21740
+ for (let i = 0; i < buf.length; i++) crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
21741
+ return (crc ^ 0xffffffff) >>> 0;
21742
+ }
21743
+ function zig(n) { return ((n << 1) ^ (n >> 31)) >>> 0; }
21744
+ function varU(u) {
21745
+ const b = [];
21746
+ let v = u >>> 0;
21747
+ for (;;) { if ((v & ~0x7f) === 0) { b.push(v); break; } b.push((v & 0x7f) | 0x80); v >>>= 7; }
21748
+ return Buffer.from(b);
21749
+ }
21750
+ function varint(n) { return varU(zig(n)); }
21751
+ function readVarint(buf, pos) {
21752
+ let result = 0, shift = 0, b;
21753
+ do { b = buf[pos++]; result |= (b & 0x7f) << shift; shift += 7; } while (b & 0x80);
21754
+ result = result >>> 0;
21755
+ return { value: (result >>> 1) ^ -(result & 1), next: pos };
21756
+ }
21757
+ function buildRecordBatch(valueBytes) {
21758
+ const now = BigInt(Date.now());
21759
+ const recBody = Buffer.concat([
21760
+ Buffer.from([0]), varint(0), varint(0), varint(-1),
21761
+ varint(valueBytes.length), valueBytes, varint(0),
21762
+ ]);
21763
+ const record = Buffer.concat([varint(recBody.length), recBody]);
21764
+ const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
21765
+ let c = 0;
21766
+ crcBody.writeInt16BE(0, c); c += 2;
21767
+ crcBody.writeInt32BE(0, c); c += 4;
21768
+ crcBody.writeBigInt64BE(now, c); c += 8;
21769
+ crcBody.writeBigInt64BE(now, c); c += 8;
21770
+ crcBody.writeBigInt64BE(-1n, c); c += 8;
21771
+ crcBody.writeInt16BE(-1, c); c += 2;
21772
+ crcBody.writeInt32BE(-1, c); c += 4;
21773
+ crcBody.writeInt32BE(1, c); c += 4;
21774
+ record.copy(crcBody, c);
21775
+ const crc = crc32c(crcBody);
21776
+ const batchLength = 4 + 1 + 4 + crcBody.length;
21777
+ const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
21778
+ let h = 0;
21779
+ head.writeBigInt64BE(0n, h); h += 8;
21780
+ head.writeInt32BE(batchLength, h); h += 4;
21781
+ head.writeInt32BE(-1, h); h += 4;
21782
+ head.writeInt8(2, h); h += 1;
21783
+ head.writeUInt32BE(crc, h); h += 4;
21784
+ return Buffer.concat([head, crcBody]);
21785
+ }
21786
+
21787
+ // \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
21788
+ function produceRequest(topic, valueBytes) {
21789
+ const topicBuf = Buffer.from(topic, "utf-8");
21790
+ const batch = buildRecordBatch(valueBytes);
21791
+ const body = Buffer.alloc(2 + 2 + 4 + 4 + 2 + topicBuf.length + 4 + 4 + 4 + batch.length);
21792
+ let p = 0;
21793
+ body.writeInt16BE(-1, p); p += 2; // transactionalId null
21794
+ body.writeInt16BE(1, p); p += 2; // acks 1
21795
+ body.writeInt32BE(10000, p); p += 4; // timeoutMs
21796
+ body.writeInt32BE(1, p); p += 4; // topics
21797
+ body.writeInt16BE(topicBuf.length, p); p += 2;
21798
+ topicBuf.copy(body, p); p += topicBuf.length;
21799
+ body.writeInt32BE(1, p); p += 4; // partitions
21800
+ body.writeInt32BE(0, p); p += 4; // partition 0
21801
+ body.writeInt32BE(batch.length, p); p += 4;
21802
+ batch.copy(body, p);
21803
+ return frame(0, PRODUCE_VERSION, body);
21804
+ }
21805
+ function parseProduce(resp) {
21806
+ let pos = 4; // correlationId
21807
+ const topicCount = resp.readInt32BE(pos); pos += 4;
21808
+ let err = 0;
21809
+ for (let t = 0; t < topicCount; t++) {
21810
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
21811
+ const pc = resp.readInt32BE(pos); pos += 4;
21812
+ for (let pi = 0; pi < pc; pi++) {
21813
+ pos += 4; err = resp.readInt16BE(pos); pos += 2; pos += 8; pos += 8;
21814
+ }
21815
+ }
21816
+ return err;
21817
+ }
21818
+ async function produce(topic, valueBytes) {
21819
+ const sock = await broker();
21820
+ for (let attempt = 1; attempt <= 10; attempt++) {
21821
+ const err = parseProduce(await rpc(sock, produceRequest(topic, valueBytes)));
21822
+ if (err === 0) return;
21823
+ if ((err !== 3 && err !== 5) || attempt === 10) {
21824
+ throw new Error("Kafka rejected the produce for topic " + topic + ": error code " + err);
21825
+ }
21826
+ await sleep(200);
21827
+ }
21828
+ }
21829
+
21830
+ // \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
21831
+ function fetchRequest(topic, offset) {
21832
+ const topicBuf = Buffer.from(topic, "utf-8");
21833
+ const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + 2 + topicBuf.length + 4 + 4 + 8 + 4);
21834
+ let p = 0;
21835
+ buf.writeInt32BE(-1, p); p += 4; // replicaId
21836
+ buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
21837
+ buf.writeInt32BE(1, p); p += 4; // minBytes
21838
+ buf.writeInt32BE(1048576, p); p += 4; // maxBytes
21839
+ buf.writeInt8(0, p); p += 1; // isolation READ_UNCOMMITTED
21840
+ buf.writeInt32BE(1, p); p += 4; // topics
21841
+ buf.writeInt16BE(topicBuf.length, p); p += 2;
21842
+ topicBuf.copy(buf, p); p += topicBuf.length;
21843
+ buf.writeInt32BE(1, p); p += 4; // partitions
21844
+ buf.writeInt32BE(0, p); p += 4; // partition 0
21845
+ buf.writeBigInt64BE(BigInt(offset), p); p += 8;
21846
+ buf.writeInt32BE(1048576, p); p += 4;
21847
+ return frame(1, FETCH_VERSION, buf);
21848
+ }
21849
+ // Decode the first record of the partition's record-set: its value string and
21850
+ // absolute offset (baseOffset + offsetDelta). null = no usable record.
21851
+ function firstRecord(buf, start, end) {
21852
+ let pos = start;
21853
+ while (pos + 12 <= end) {
21854
+ const baseOffset = buf.readBigInt64BE(pos);
21855
+ const batchLength = buf.readInt32BE(pos + 8);
21856
+ const batchStart = pos + 12;
21857
+ const batchEnd = batchStart + batchLength;
21858
+ if (batchLength <= 0 || batchEnd > end) break;
21859
+ const magic = buf.readInt8(batchStart + 4);
21860
+ if (magic !== 2) { pos = batchEnd; continue; }
21861
+ let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
21862
+ const recordsCount = buf.readInt32BE(r); r += 4;
21863
+ for (let i = 0; i < recordsCount && r < batchEnd; i++) {
21864
+ const recLen = readVarint(buf, r);
21865
+ let rp = recLen.next;
21866
+ const recordEnd = rp + recLen.value;
21867
+ rp += 1;
21868
+ rp = readVarint(buf, rp).next; // timestampDelta
21869
+ const offDelta = readVarint(buf, rp); rp = offDelta.next;
21870
+ const keyLen = readVarint(buf, rp); rp = keyLen.next;
21871
+ if (keyLen.value >= 0) rp += keyLen.value;
21872
+ const valLen = readVarint(buf, rp); rp = valLen.next;
21873
+ if (valLen.value >= 0) {
21874
+ return {
21875
+ value: buf.subarray(rp, rp + valLen.value).toString("utf-8"),
21876
+ offset: Number(baseOffset) + offDelta.value,
21877
+ };
21878
+ }
21879
+ r = recordEnd;
21880
+ }
21881
+ pos = batchEnd;
21882
+ }
21883
+ return null;
21884
+ }
21885
+ async function fetchAt(topic, offset) {
21886
+ const sock = await broker();
21887
+ const resp = await rpc(sock, fetchRequest(topic, offset));
21888
+ let pos = 4; // correlationId
21889
+ pos += 4; // throttleTimeMs
21890
+ const topicCount = resp.readInt32BE(pos); pos += 4;
21891
+ let rec = null;
21892
+ for (let t = 0; t < topicCount; t++) {
21893
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
21894
+ const pc = resp.readInt32BE(pos); pos += 4;
21895
+ for (let pi = 0; pi < pc; pi++) {
21896
+ pos += 4;
21897
+ const err = resp.readInt16BE(pos); pos += 2;
21898
+ pos += 8; pos += 8;
21899
+ const aborted = resp.readInt32BE(pos); pos += 4;
21900
+ if (aborted > 0) pos += aborted * 16;
21901
+ const recSize = resp.readInt32BE(pos); pos += 4;
21902
+ if (err !== 0 && err !== 3 && err !== 5) {
21903
+ throw new Error("Kafka rejected the fetch for topic " + topic + ": error code " + err);
21904
+ }
21905
+ if (err === 0 && recSize > 0) {
21906
+ const r = firstRecord(resp, pos, pos + recSize);
21907
+ if (r !== null) rec = r;
21908
+ }
21909
+ if (recSize > 0) pos += recSize;
21910
+ }
21911
+ }
21912
+ return rec;
21913
+ }
21914
+
21915
+ // \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
21916
+ function readNullableString(buf, pos) {
21917
+ const len = buf.readInt16BE(pos); pos += 2;
21918
+ if (len < 0) return { value: null, next: pos };
21919
+ return { value: buf.toString("utf-8", pos, pos + len), next: pos + len };
21920
+ }
21921
+ async function findCoordinator() {
21922
+ const sock = await broker();
21923
+ for (let attempt = 0; attempt < 30; attempt++) {
21924
+ const body = Buffer.concat([kstr(groupId), Buffer.from([0])]); // key_type 0 = group
21925
+ const resp = await rpc(sock, frame(10, 1, body));
21926
+ let pos = 4; // correlationId
21927
+ pos += 4; // throttle
21928
+ const err = resp.readInt16BE(pos); pos += 2;
21929
+ pos = readNullableString(resp, pos).next; // error_message
21930
+ pos += 4; // node_id
21931
+ const hostRes = readNullableString(resp, pos); pos = hostRes.next;
21932
+ const port = resp.readInt32BE(pos);
21933
+ if (err === 0 && hostRes.value) return { host: hostRes.value, port: port };
21934
+ if (err !== 14 && err !== 15) {
21935
+ throw new Error("Kafka FindCoordinator failed for group " + groupId + ": error code " + err);
21936
+ }
21937
+ await sleep(300);
21938
+ }
21939
+ throw new Error("Kafka group coordinator for " + groupId + " did not become available");
21940
+ }
21941
+ async function coordinator() {
21942
+ if (coordSock) return coordSock;
21943
+ const c = await findCoordinator();
21944
+ coordSock = await connect(c.host, c.port);
21945
+ return coordSock;
21946
+ }
21947
+ function dropCoordinator() {
21948
+ if (coordSock) { try { coordSock.destroy(); } catch (e) { /* ignore */ } }
21949
+ coordSock = null;
21950
+ }
21951
+ function offsetCommitRequest(topic, offset) {
21952
+ const body = Buffer.concat([
21953
+ kstr(groupId),
21954
+ int32(-1), // generation_id -1 (simple consumer)
21955
+ kstr(""), // member_id ""
21956
+ int64(-1n), // retention_time -1
21957
+ int32(1), kstr(topic), int32(1), int32(0), int64(BigInt(offset)), int16(-1),
21958
+ ]);
21959
+ return frame(8, 2, body);
21960
+ }
21961
+ function parseOffsetCommit(resp) {
21962
+ let pos = 4;
21963
+ const tc = resp.readInt32BE(pos); pos += 4;
21964
+ if (tc === 0) return 16;
21965
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
21966
+ const pc = resp.readInt32BE(pos); pos += 4;
21967
+ if (pc === 0) return 16;
21968
+ pos += 4;
21969
+ return resp.readInt16BE(pos);
21970
+ }
21971
+ async function offsetCommit(topic, offset) {
21972
+ var err = 0;
21973
+ for (var attempt = 0; attempt < 10; attempt++) {
21974
+ if (attempt > 0) { dropCoordinator(); await new Promise(function (r) { setTimeout(r, 200 * attempt); }); }
21975
+ err = parseOffsetCommit(await rpc(await coordinator(), offsetCommitRequest(topic, offset)));
21976
+ if (COORDINATOR_ERRORS.indexOf(err) < 0) break;
21977
+ }
21978
+ if (err !== 0) throw new Error("Kafka rejected the offset commit for " + topic + ": error code " + err);
21979
+ }
21980
+ function offsetFetchRequest(topic) {
21981
+ const body = Buffer.concat([kstr(groupId), int32(1), kstr(topic), int32(1), int32(0)]);
21982
+ return frame(9, 1, body);
21983
+ }
21984
+ function parseOffsetFetch(resp) {
21985
+ let pos = 4;
21986
+ const tc = resp.readInt32BE(pos); pos += 4;
21987
+ if (tc === 0) return { offset: -1, err: 16 };
21988
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
21989
+ const pc = resp.readInt32BE(pos); pos += 4;
21990
+ if (pc === 0) return { offset: -1, err: 16 };
21991
+ pos += 4;
21992
+ const offset = Number(resp.readBigInt64BE(pos)); pos += 8;
21993
+ pos = readNullableString(resp, pos).next;
21994
+ const err = resp.readInt16BE(pos);
21995
+ return { offset: offset, err: err };
21996
+ }
21997
+ async function offsetFetch(topic) {
21998
+ var r = { offset: -1, err: 0 };
21999
+ for (var attempt = 0; attempt < 10; attempt++) {
22000
+ if (attempt > 0) { dropCoordinator(); await new Promise(function (res) { setTimeout(res, 200 * attempt); }); }
22001
+ r = parseOffsetFetch(await rpc(await coordinator(), offsetFetchRequest(topic)));
22002
+ if (COORDINATOR_ERRORS.indexOf(r.err) < 0) break;
22003
+ }
22004
+ if (r.err !== 0) throw new Error("Kafka rejected the offset fetch for " + topic + ": error code " + r.err);
22005
+ return r.offset < 0 ? 0 : r.offset;
22006
+ }
22007
+
22008
+ function int16(n) { const b = Buffer.alloc(2); b.writeInt16BE(n, 0); return b; }
22009
+ function int32(n) { const b = Buffer.alloc(4); b.writeInt32BE(n, 0); return b; }
22010
+ function int64(n) { const b = Buffer.alloc(8); b.writeBigInt64BE(BigInt(n), 0); return b; }
22011
+ function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
22012
+
22013
+ async function broker() {
22014
+ if (brokerSock) return brokerSock;
22015
+ const b = parseBroker(brokers);
22016
+ brokerSock = await connect(b.host, b.port);
22017
+ return brokerSock;
22018
+ }
22019
+
22020
+ // Resume from the committed offset on the FIRST read of a topic in this worker,
22021
+ // then advance the in-memory cursor; the committed offset only moves on a
22022
+ // commit, so it lags and a crash before commit replays (at-least-once).
22023
+ async function fetchNext(topic) {
22024
+ if (!(topic in offsets)) offsets[topic] = await offsetFetch(topic);
22025
+ const rec = await fetchAt(topic, offsets[topic]);
22026
+ if (rec === null) return null;
22027
+ offsets[topic] = rec.offset + 1;
22028
+ return rec;
22029
+ }
22030
+
22031
+ function encodeEnvelope(id, payload, attempts) {
22032
+ return JSON.stringify({ id: id, payload: payload, status: "pending", createdAt: new Date().toISOString(), attempts: attempts, delayUntil: null });
22033
+ }
22034
+
22035
+ async function handle(req) {
22036
+ const op = req.op;
22037
+ if (op === "publish") {
22038
+ await produce(req.topic, Buffer.from(req.value, "utf-8"));
22039
+ return { ok: true };
22040
+ }
22041
+ if (op === "dequeueRaw") {
22042
+ // The value exactly as it sits on the wire (a raw record stays its bare
22043
+ // bytes \u2014 tina4-nodejs#264), with no id/offset tracking. For wire
22044
+ // inspection; the facade consumes through "pop", which normalises + tracks.
22045
+ const rec = await fetchNext(req.topic);
22046
+ if (rec === null) return { ok: true, message: null };
22047
+ let decoded;
22048
+ try { decoded = JSON.parse(rec.value); } catch (e) { decoded = rec.value; }
22049
+ return { ok: true, message: decoded };
22050
+ }
22051
+ if (op === "pop") {
22052
+ let rec;
22053
+ try {
22054
+ rec = await fetchNext(req.topic);
22055
+ } catch (e) {
22056
+ // A malformed/short response runs the parser off the end (a RangeError);
22057
+ // anything else is a transport failure. Both name the topic so the cause
22058
+ // is findable, and neither reads as an empty queue (ADR: a real failure
22059
+ // must never look idle). Wording matches the Python/PHP backends.
22060
+ const range = (e instanceof RangeError) || /out of range|bounds/i.test((e && e.message) || "");
22061
+ if (range) throw new Error("Kafka fetch for topic " + req.topic + " returned an unreadable response: " + ((e && e.message) || e));
22062
+ throw new Error("Kafka fetch for topic " + req.topic + " failed: " + ((e && e.message) || e));
22063
+ }
22064
+ if (rec === null) return { ok: true, message: null };
22065
+ const coordinate = req.topic + ":0:" + rec.offset;
22066
+ let decoded;
22067
+ try { decoded = JSON.parse(rec.value); } catch (e) { decoded = null; }
22068
+ let message;
22069
+ let isEnvelope = false;
22070
+ if (decoded !== null && typeof decoded === "object" && !Array.isArray(decoded) && "payload" in decoded) {
22071
+ message = decoded;
22072
+ isEnvelope = true;
22073
+ if (!message.id) message.id = coordinate;
22074
+ } else {
22075
+ message = { id: coordinate, payload: decoded === null ? rec.value : decoded, status: "pending", attempts: 0 };
22076
+ }
22077
+ // The Job lifecycle (complete/fail/retry) routes by the record's own topic,
22078
+ // so it must be carried back (like the file/mongodb backends do).
22079
+ message.topic = req.topic;
22080
+ inFlight[String(message.id)] = { offset: rec.offset, value: rec.value, attempts: message.attempts || 0, isEnvelope: isEnvelope };
22081
+ return { ok: true, message: message };
22082
+ }
22083
+ if (op === "complete") {
22084
+ const rec = inFlight[String(req.id)];
22085
+ if (rec) { delete inFlight[String(req.id)]; await offsetCommit(req.topic, rec.offset + 1); }
22086
+ return { ok: true };
22087
+ }
22088
+ if (op === "fail") {
22089
+ const rec = inFlight[String(req.id)];
22090
+ if (rec) {
22091
+ delete inFlight[String(req.id)];
22092
+ const attempts = (rec.attempts || 0) + 1;
22093
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
22094
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
22095
+ if (attempts < req.maxRetries) {
22096
+ await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
22097
+ } else {
22098
+ await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: attempts, error: req.error }), "utf-8"));
22099
+ }
22100
+ await offsetCommit(req.topic, rec.offset + 1);
22101
+ }
22102
+ return { ok: true };
22103
+ }
22104
+ if (op === "reject") {
22105
+ const rec = inFlight[String(req.id)];
22106
+ if (rec) {
22107
+ delete inFlight[String(req.id)];
22108
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
22109
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
22110
+ await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: req.maxRetries, error: req.reason }), "utf-8"));
22111
+ await offsetCommit(req.topic, rec.offset + 1);
22112
+ }
22113
+ return { ok: true };
22114
+ }
22115
+ if (op === "retry") {
22116
+ const rec = inFlight[String(req.id)];
22117
+ if (rec) {
22118
+ delete inFlight[String(req.id)];
22119
+ const attempts = (rec.attempts || 0) + 1;
22120
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
22121
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
22122
+ await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
22123
+ await offsetCommit(req.topic, rec.offset + 1);
22124
+ }
22125
+ return { ok: true };
22126
+ }
22127
+ if (op === "deadLetters") {
22128
+ // Read the <topic>.dead_letter topic from the beginning; every record on it
22129
+ // is a dead letter by construction. A throwaway cursor that never commits,
22130
+ // so it does not disturb the main consume position.
22131
+ const dlq = req.topic + ".dead_letter";
22132
+ const out = [];
22133
+ let off = 0;
22134
+ for (;;) {
22135
+ const rec = await fetchAt(dlq, off);
22136
+ if (rec === null) break;
22137
+ off = rec.offset + 1;
22138
+ try { out.push(JSON.parse(rec.value)); } catch (e) { /* skip */ }
22139
+ if (out.length > 10000) break;
22140
+ }
22141
+ return { ok: true, deadLetters: out };
22142
+ }
22143
+ if (op === "close") {
22144
+ try { if (brokerSock) brokerSock.destroy(); } catch (e) { /* ignore */ }
22145
+ dropCoordinator();
22146
+ return { ok: true, closing: true };
22147
+ }
22148
+ return { ok: false, error: "unknown op " + op };
22149
+ }
22150
+
22151
+ parentPort.on("message", async function (req) {
22152
+ let res;
22153
+ try { res = await handle(req); }
22154
+ catch (e) { res = { ok: false, error: (e && e.message) ? e.message : String(e) }; }
22155
+ const bytes = Buffer.from(JSON.stringify(res), "utf-8");
22156
+ outBytes.set(bytes.subarray(0, outBytes.length), 0);
22157
+ Atomics.store(header, 1, Math.min(bytes.length, outBytes.length));
22158
+ Atomics.store(header, 0, 1);
22159
+ Atomics.notify(header, 0);
22160
+ });
22161
+ `;
22162
+ KafkaBackend = class _KafkaBackend {
22163
+ brokers;
22164
+ groupId;
22165
+ worker = null;
22166
+ sab = null;
22167
+ header = null;
22168
+ outBytes = null;
22169
+ static SAB_SIZE = 1 << 20;
22170
+ // 1 MiB (8-byte header + response bytes)
22171
+ static CALL_TIMEOUT_MS = 2e4;
22172
+ constructor(config) {
22173
+ const url = process.env.TINA4_QUEUE_URL;
22174
+ const fromUrl = url ? url.replace(/^kafka:\/\//, "") : void 0;
22175
+ this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
22176
+ this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
22177
+ }
22178
+ /** Resolved connection config — exposed for testing/introspection. */
22179
+ getConfig() {
22180
+ return { brokers: this.brokers, groupId: this.groupId };
22181
+ }
22182
+ securityConfig() {
22183
+ return kafkaSecurityConfig();
22184
+ }
22185
+ producerConfig() {
22186
+ return { "bootstrap.servers": this.brokers, "client.id": "tina4-nodejs", ...this.securityConfig() };
22187
+ }
22188
+ consumerConfig() {
22189
+ return {
22190
+ "bootstrap.servers": this.brokers,
22191
+ "client.id": "tina4-nodejs",
22192
+ "group.id": this.groupId,
22193
+ "auto.offset.reset": kafkaOffsetReset(),
22194
+ "enable.auto.commit": false,
22195
+ ...this.securityConfig()
22196
+ };
22197
+ }
22198
+ /** Lazily start the persistent worker + its shared buffer. */
22199
+ ensureWorker() {
22200
+ if (this.worker) return;
22201
+ this.sab = new SharedArrayBuffer(_KafkaBackend.SAB_SIZE);
22202
+ this.header = new Int32Array(this.sab, 0, 2);
22203
+ this.outBytes = new Uint8Array(this.sab, 8);
22204
+ this.worker = new Worker2(WORKER_SRC, {
22205
+ eval: true,
22206
+ workerData: {
22207
+ brokers: this.brokers,
22208
+ groupId: this.groupId,
22209
+ security: this.securityConfig(),
22210
+ offsetReset: kafkaOffsetReset(),
22211
+ sab: this.sab
22212
+ }
22213
+ });
22214
+ this.worker.unref();
22215
+ }
22216
+ /** One synchronous request to the worker: post, block on Atomics.wait, read. */
22217
+ request(req2) {
22218
+ this.ensureWorker();
22219
+ const header = this.header;
22220
+ const outBytes = this.outBytes;
22221
+ Atomics.store(header, 0, 0);
22222
+ this.worker.postMessage(req2);
22223
+ const waited = Atomics.wait(header, 0, 0, _KafkaBackend.CALL_TIMEOUT_MS);
22224
+ if (waited === "timed-out") {
22225
+ throw new Error(`Kafka ${String(req2.op)} for topic ${String(req2.topic ?? "")} timed out after ${_KafkaBackend.CALL_TIMEOUT_MS}ms`);
22226
+ }
22227
+ const len = Atomics.load(header, 1);
22228
+ const json = Buffer.from(outBytes.buffer, outBytes.byteOffset, len).toString("utf-8");
22229
+ const res = JSON.parse(json);
22230
+ if (res.ok === false) {
22231
+ throw new Error(String(res.error ?? "unknown Kafka worker error"));
22232
+ }
22233
+ return res;
22234
+ }
22235
+ /**
22236
+ * Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
22237
+ * as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
22238
+ * consumer reading the topic gets the schema it expects; otherwise the Tina4
22239
+ * job envelope. pop() unwraps both shapes (payload ?? the whole record).
22240
+ */
22241
+ static encodeJob(id, payload, raw) {
22242
+ if (raw) return JSON.stringify(payload);
22243
+ return JSON.stringify({
22244
+ id,
22245
+ payload,
22246
+ status: "pending",
22247
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
22248
+ attempts: 0,
22249
+ delayUntil: null
22250
+ });
22251
+ }
22252
+ push(queue, payload, _delay, _priority, raw = false) {
22253
+ const id = randomUUID5();
22254
+ const value = _KafkaBackend.encodeJob(id, payload, raw);
22255
+ this.request({ op: "publish", topic: queue, value });
22256
+ return id;
22257
+ }
22258
+ pop(queue) {
22259
+ const res = this.request({ op: "pop", topic: queue });
22260
+ const message = res.message;
22261
+ return message ?? null;
22262
+ }
22263
+ /**
22264
+ * Read the next record's value exactly as it sits on the wire — a Tina4
22265
+ * envelope as produced, a raw record (tina4-nodejs#264) as its bare bytes —
22266
+ * with no id/offset tracking. For a foreign consumer's view of the schema;
22267
+ * the queue facade consumes through pop(), which also normalises and tracks
22268
+ * the offset so complete()/fail() can commit it.
22269
+ */
22270
+ dequeue(queue) {
22271
+ const res = this.request({ op: "dequeueRaw", topic: queue });
22272
+ return res.message ?? null;
22273
+ }
22274
+ /** Commit the record's offset so a completed job never replays (ADR-0022 d.4). */
22275
+ complete(queue, id) {
22276
+ this.request({ op: "complete", topic: queue, id });
22277
+ }
22278
+ /**
22279
+ * Record a failed attempt: re-produce the job with an incremented attempts
22280
+ * count while it has retries left, else produce it to the dead-letter topic;
22281
+ * commit the original offset either way (ADR-0022 decision 2).
22282
+ */
22283
+ fail(queue, id, error2, maxRetries, _retryBackoff) {
22284
+ this.request({ op: "fail", topic: queue, id, error: error2, maxRetries });
22285
+ }
22286
+ /** Dead-letter the job now, no retry (ADR-0023 reject), then commit the offset. */
22287
+ reject(queue, id, reason, maxRetries) {
22288
+ this.request({ op: "reject", topic: queue, id, reason, maxRetries });
22289
+ }
22290
+ /** Re-produce the job (manual retry) and commit the original offset. */
22291
+ retry(queue, id, delaySeconds) {
22292
+ this.request({ op: "retry", topic: queue, id, delaySeconds: delaySeconds ?? 0 });
22293
+ return true;
22294
+ }
22295
+ /** Read the dead-letter topic for this queue (every record on it is a dead letter). */
22296
+ deadLetters(queue, _maxRetries) {
22297
+ const res = this.request({ op: "deadLetters", topic: queue });
22298
+ return res.deadLetters ?? [];
22299
+ }
22300
+ /**
22301
+ * Refuse rather than silently answer from the local file store. Kafka keeps no
22302
+ * queryable registry of failed jobs: a failed record is re-produced to a
22303
+ * dead-letter TOPIC and the original offset committed past, and a log cannot be
22304
+ * queried by job state. Returning [] would claim nothing has failed.
22305
+ */
22306
+ failed(_queue, _maxRetries) {
22307
+ throw new Error(
22308
+ "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."
22309
+ );
22310
+ }
22311
+ /** Refuse for the same reason failed() does (no queryable failed registry). */
22312
+ retryFailed(_queue, _maxRetries) {
22313
+ throw new Error(
22314
+ "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."
22315
+ );
22316
+ }
22317
+ size(_queue) {
22318
+ return 0;
22319
+ }
22320
+ clear(_queue) {
22321
+ throw new Error(
22322
+ "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."
22323
+ );
22324
+ }
22325
+ purge(_queue, _status) {
22326
+ throw new Error(
22327
+ "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."
22328
+ );
22329
+ }
22330
+ /** Stop the worker and release the connection. Idempotent. */
22331
+ close() {
22332
+ if (!this.worker) return;
22333
+ try {
22334
+ this.request({ op: "close" });
22335
+ } catch {
22336
+ }
22337
+ void this.worker.terminate();
22338
+ this.worker = null;
22339
+ this.sab = null;
22340
+ this.header = null;
22341
+ this.outBytes = null;
22342
+ }
22343
+ };
22344
+ }
22345
+ });
22346
+
21484
22347
  // ../core/src/job.ts
21485
22348
  function createJob(data, queue) {
21486
22349
  const job = {
@@ -21533,7 +22396,7 @@ var init_job = __esm({
21533
22396
  // ../core/src/queueBackends/liteBackend.ts
21534
22397
  import { mkdirSync as mkdirSync11, readdirSync as readdirSync9, readFileSync as readFileSync14, writeFileSync as writeFileSync9, unlinkSync as unlinkSync7, existsSync as existsSync16 } from "node:fs";
21535
22398
  import { join as join18 } from "node:path";
21536
- import { randomUUID as randomUUID5 } from "node:crypto";
22399
+ import { randomUUID as randomUUID6 } from "node:crypto";
21537
22400
  var LiteBackend;
21538
22401
  var init_liteBackend = __esm({
21539
22402
  "../core/src/queueBackends/liteBackend.ts"() {
@@ -21600,7 +22463,7 @@ var init_liteBackend = __esm({
21600
22463
  );
21601
22464
  }
21602
22465
  const dir = this.ensureDir(queue);
21603
- const id = randomUUID5();
22466
+ const id = randomUUID6();
21604
22467
  const now = (/* @__PURE__ */ new Date()).toISOString();
21605
22468
  const job = {
21606
22469
  id,
@@ -22156,13 +23019,11 @@ function defaultVisibilityTimeout() {
22156
23019
  return Number.isFinite(parsed) ? parsed : 300;
22157
23020
  }
22158
23021
  function unsupportedBrokerMessage(backendName) {
22159
- const broker = backendName === "kafka" ? "Kafka" : "RabbitMQ";
22160
- 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";
22161
23022
  return `Queue backend "${backendName}" is not available in tina4-nodejs.
22162
23023
 
22163
- 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.
23024
+ 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.
22164
23025
 
22165
- 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}.
23026
+ 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.
22166
23027
 
22167
23028
  Tracking: ADR-0022 in tina4-documentation/plan/v3/DECISIONS.md, findings in plan/v3/features/048-queue-backends.md.`;
22168
23029
  }
@@ -22171,6 +23032,7 @@ var init_queue = __esm({
22171
23032
  "../core/src/queue.ts"() {
22172
23033
  "use strict";
22173
23034
  init_mongoBackend();
23035
+ init_kafkaBackend();
22174
23036
  init_liteBackend();
22175
23037
  init_job();
22176
23038
  init_liteBackend();
@@ -22191,7 +23053,7 @@ var init_queue = __esm({
22191
23053
  * - new Queue("mongodb", { path: "data/queue" }) // legacy
22192
23054
  * - new Queue() // file backend, default topic
22193
23055
  *
22194
- * Throws on backend "rabbitmq" or "kafka" (ADR-0022).
23056
+ * Throws on backend "rabbitmq" (ADR-0022); "kafka" is now supported.
22195
23057
  */
22196
23058
  constructor(backendOrConfig, config) {
22197
23059
  let resolvedConfig = {};
@@ -22209,8 +23071,10 @@ var init_queue = __esm({
22209
23071
  this._retryBackoff = resolvedConfig.retryBackoff ?? 0;
22210
23072
  this._visibilityTimeout = resolvedConfig.visibilityTimeout ?? defaultVisibilityTimeout();
22211
23073
  this.liteBackend = new LiteBackend(this.basePath, this._visibilityTimeout);
22212
- if (this.backendName === "rabbitmq" || this.backendName === "kafka") {
23074
+ if (this.backendName === "rabbitmq") {
22213
23075
  throw new Error(unsupportedBrokerMessage(this.backendName));
23076
+ } else if (this.backendName === "kafka") {
23077
+ this.externalBackend = new KafkaBackend({ visibilityTimeout: this._visibilityTimeout });
22214
23078
  } else if (this.backendName === "mongodb" || this.backendName === "mongo") {
22215
23079
  this.externalBackend = new MongoBackend2({ visibilityTimeout: this._visibilityTimeout });
22216
23080
  } else if (!["file", "default", "lite"].includes(this.backendName)) {
@@ -25278,10 +26142,10 @@ function devGitStatusLabel(code) {
25278
26142
  async function devGitInfo(root) {
25279
26143
  const empty = { branch: "", gitRoot: null, status: /* @__PURE__ */ new Map() };
25280
26144
  try {
25281
- const { execFileSync: execFileSync7 } = await import("node:child_process");
26145
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
25282
26146
  const git = (args) => {
25283
26147
  try {
25284
- return execFileSync7("git", args, { cwd: root, timeout: 3e3, encoding: "utf-8" }).toString();
26148
+ return execFileSync6("git", args, { cwd: root, timeout: 3e3, encoding: "utf-8" }).toString();
25285
26149
  } catch {
25286
26150
  return null;
25287
26151
  }
@@ -27108,9 +27972,9 @@ var init_devAdmin = __esm({
27108
27972
  return;
27109
27973
  }
27110
27974
  try {
27111
- const { execFileSync: execFileSync7 } = await import("node:child_process");
27975
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
27112
27976
  const args = ["install", dev ? "--save-dev" : "--save", pkg];
27113
- const output = execFileSync7("npm", args, {
27977
+ const output = execFileSync6("npm", args, {
27114
27978
  cwd: resolve12(process.cwd()),
27115
27979
  timeout: 12e4,
27116
27980
  encoding: "utf-8"
@@ -27122,15 +27986,15 @@ var init_devAdmin = __esm({
27122
27986
  };
27123
27987
  handleGitStatus = async (_req, res) => {
27124
27988
  try {
27125
- const { execFileSync: execFileSync7 } = await import("node:child_process");
27989
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
27126
27990
  const cwd = resolve12(process.cwd());
27127
27991
  try {
27128
- execFileSync7("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
27992
+ execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
27129
27993
  } catch {
27130
27994
  res.json({ error: "Not a git repository" }, 400);
27131
27995
  return;
27132
27996
  }
27133
- const run = (args) => execFileSync7("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
27997
+ const run = (args) => execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
27134
27998
  res.json({
27135
27999
  branch: run(["branch", "--show-current"]),
27136
28000
  status: run(["status", "--porcelain"]).split(/\r?\n/).filter((l) => l),
@@ -27260,8 +28124,8 @@ var init_devAdmin = __esm({
27260
28124
  return;
27261
28125
  }
27262
28126
  try {
27263
- const { execFileSync: execFileSync7 } = await import("node:child_process");
27264
- const output = execFileSync7("npx", ["tina4nodejs", "generate", kind, name], {
28127
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
28128
+ const output = execFileSync6("npx", ["tina4nodejs", "generate", kind, name], {
27265
28129
  cwd: resolve12(process.cwd()),
27266
28130
  timeout: 3e4,
27267
28131
  encoding: "utf-8"
@@ -27707,6 +28571,359 @@ var init_background = __esm({
27707
28571
  }
27708
28572
  });
27709
28573
 
28574
+ // ../core/src/tcp.ts
28575
+ import { createServer as createServer3 } from "node:net";
28576
+ function resolveMaxBacklog(explicit) {
28577
+ if (explicit !== void 0) return explicit > 0 ? explicit : DEFAULT_MAX_BACKLOG;
28578
+ const raw = (process.env.TINA4_TCP_MAX_BACKLOG ?? "").trim();
28579
+ if (raw === "") return DEFAULT_MAX_BACKLOG;
28580
+ const value = Number.parseInt(raw, 10);
28581
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_BACKLOG;
28582
+ }
28583
+ function tcpService(port, options = {}) {
28584
+ const service = new TcpService(port, options);
28585
+ services.set(service.name, service);
28586
+ return service;
28587
+ }
28588
+ function tcp(name = "default") {
28589
+ const service = services.get(name);
28590
+ if (!service) {
28591
+ const known = services.size === 0 ? "(none registered)" : [...services.keys()].join(", ");
28592
+ throw new Error(`no tcp_service named '${name}' is registered; known services: ${known}`);
28593
+ }
28594
+ return service;
28595
+ }
28596
+ function registeredTcpServices() {
28597
+ return [...services.values()];
28598
+ }
28599
+ function clearTcpRegistry() {
28600
+ services.clear();
28601
+ }
28602
+ async function startAllTcpServices(host = "0.0.0.0") {
28603
+ for (const service of registeredTcpServices()) {
28604
+ try {
28605
+ await service.start(host);
28606
+ } catch (error2) {
28607
+ Log.error(`tcp_service '${service.name}' failed to start: ${String(error2)}`);
28608
+ }
28609
+ }
28610
+ }
28611
+ function stopAcceptingAllTcpServices() {
28612
+ for (const service of registeredTcpServices()) {
28613
+ try {
28614
+ service.stopAccepting();
28615
+ } catch (error2) {
28616
+ Log.error(`tcp_service '${service.name}' stop-accepting failed: ${String(error2)}`);
28617
+ }
28618
+ }
28619
+ }
28620
+ async function drainAllTcpServices() {
28621
+ for (const service of registeredTcpServices()) {
28622
+ try {
28623
+ await service.drain();
28624
+ } catch (error2) {
28625
+ Log.error(`tcp_service '${service.name}' drain failed: ${String(error2)}`);
28626
+ }
28627
+ }
28628
+ }
28629
+ var DEFAULT_MAX_BACKLOG, TcpConnection, TcpService, services;
28630
+ var init_tcp = __esm({
28631
+ "../core/src/tcp.ts"() {
28632
+ "use strict";
28633
+ init_logger();
28634
+ DEFAULT_MAX_BACKLOG = 1 << 20;
28635
+ TcpConnection = class {
28636
+ constructor(socket, service) {
28637
+ this.socket = socket;
28638
+ this.service = service;
28639
+ this.remoteAddr = `${socket.remoteAddress ?? ""}:${socket.remotePort ?? 0}`;
28640
+ }
28641
+ socket;
28642
+ service;
28643
+ /** The registry id (the IMEI), or null until identify() is called. */
28644
+ id = null;
28645
+ /** Per-connection mutable state bag — the app's parse buffer, auth flag. */
28646
+ context = {};
28647
+ /** The raw TCP peer address ("127.0.0.1:54321"), never a forwarded header. */
28648
+ remoteAddr;
28649
+ lastActivity = Date.now();
28650
+ lineBuffer = Buffer.alloc(0);
28651
+ closed = false;
28652
+ closeFired = false;
28653
+ get isClosed() {
28654
+ return this.closed;
28655
+ }
28656
+ /**
28657
+ * Register this live connection under an app-chosen id (the IMEI). A second
28658
+ * connection identifying with the same id SUPERSEDES the first in the
28659
+ * registry — exactly a device that dropped and reconnected.
28660
+ */
28661
+ identify(appId) {
28662
+ this.id = String(appId);
28663
+ this.service._registerId(this.id, this);
28664
+ return this;
28665
+ }
28666
+ /**
28667
+ * Write raw bytes to THIS socket. Returns true when queued/sent, false when
28668
+ * the connection is closed or dropped for backpressure. A stalled reader
28669
+ * (never draining) is bounded: once more than the service's maxBacklog bytes
28670
+ * are outstanding, the connection is dropped rather than buffered without end
28671
+ * (mirrors the WebSocket TINA4_WS_MAX_BACKLOG posture).
28672
+ */
28673
+ send(data) {
28674
+ if (this.closed) return false;
28675
+ const buffer = typeof data === "string" ? Buffer.from(data) : data;
28676
+ this.socket.write(buffer);
28677
+ if (this.socket.writableLength > this.service.maxBacklog) {
28678
+ Log.warning(
28679
+ `tcp_service '${this.service.name}': dropping a stalled reader \u2014 ${this.socket.writableLength} bytes queued exceeds the ${this.service.maxBacklog}-byte backlog limit`
28680
+ );
28681
+ this.close();
28682
+ return false;
28683
+ }
28684
+ return true;
28685
+ }
28686
+ /**
28687
+ * Close this connection. on_close fires exactly once (from the socket's close
28688
+ * event) and the registry entry is removed.
28689
+ */
28690
+ close() {
28691
+ if (this.closed) return;
28692
+ this.closed = true;
28693
+ try {
28694
+ this.socket.end(() => this.socket.destroy());
28695
+ } catch {
28696
+ this.socket.destroy();
28697
+ }
28698
+ }
28699
+ /** @internal mark activity for the idle reaper. */
28700
+ _touch() {
28701
+ this.lastActivity = Date.now();
28702
+ }
28703
+ /** @internal fire on_close exactly once (called from the service removal path). */
28704
+ _fireClose() {
28705
+ if (this.closeFired) return;
28706
+ this.closeFired = true;
28707
+ this.closed = true;
28708
+ const handler = this.service._callbacks.onClose;
28709
+ if (!handler) return;
28710
+ try {
28711
+ void Promise.resolve(handler(this)).catch((error2) => {
28712
+ Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error2)}`);
28713
+ });
28714
+ } catch (error2) {
28715
+ Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error2)}`);
28716
+ }
28717
+ }
28718
+ };
28719
+ TcpService = class {
28720
+ name;
28721
+ port;
28722
+ maxBacklog;
28723
+ /** @internal the callback bag, read by TcpConnection. */
28724
+ _callbacks;
28725
+ idleTimeout;
28726
+ maxConnections;
28727
+ connections = /* @__PURE__ */ new Set();
28728
+ byId = /* @__PURE__ */ new Map();
28729
+ server = null;
28730
+ owner = false;
28731
+ boundPortValue = null;
28732
+ reaper = null;
28733
+ constructor(port, options = {}) {
28734
+ this.port = port;
28735
+ this.name = options.name ?? "default";
28736
+ this._callbacks = {
28737
+ onConnect: options.onConnect,
28738
+ onData: options.onData,
28739
+ onClose: options.onClose,
28740
+ onLine: options.onLine
28741
+ };
28742
+ this.idleTimeout = options.idleTimeout ?? 0;
28743
+ this.maxConnections = options.maxConnections ?? null;
28744
+ this.maxBacklog = resolveMaxBacklog(options.maxBacklog);
28745
+ }
28746
+ get isOwner() {
28747
+ return this.owner;
28748
+ }
28749
+ /** The port actually bound (resolves an ephemeral port=0 to the real one). */
28750
+ get boundPort() {
28751
+ return this.boundPortValue ?? this.port;
28752
+ }
28753
+ count() {
28754
+ return this.connections.size;
28755
+ }
28756
+ // ── Registry (D4 — server -> device push) ──────────────────────────────────
28757
+ /** @internal */
28758
+ _registerId(appId, conn) {
28759
+ this.byId.set(appId, conn);
28760
+ }
28761
+ /** The live connection for an app id, or null if unknown or closed. */
28762
+ connection(appId) {
28763
+ const conn = this.byId.get(String(appId));
28764
+ if (!conn || conn.isClosed) return null;
28765
+ return conn;
28766
+ }
28767
+ /**
28768
+ * Write bytes to exactly the connection identified by appId. A send to an
28769
+ * unknown or closed id is a NO-OP that returns false — never a throw.
28770
+ */
28771
+ sendTo(appId, data) {
28772
+ const conn = this.connection(appId);
28773
+ if (!conn) return false;
28774
+ return conn.send(data);
28775
+ }
28776
+ /** Write bytes to every live connection. Returns how many received it. */
28777
+ broadcast(data) {
28778
+ let delivered = 0;
28779
+ for (const conn of [...this.connections]) {
28780
+ if (conn.send(data)) delivered += 1;
28781
+ }
28782
+ return delivered;
28783
+ }
28784
+ // ── Lifecycle ───────────────────────────────────────────────────────────────
28785
+ /**
28786
+ * Bind the listener on host:port on the event loop. SO_REUSEPORT is OFF, so
28787
+ * under a multi-worker deployment exactly ONE worker wins the bind; a worker
28788
+ * that finds the port already bound skips silently (single-owner, D1).
28789
+ * Resolves true when THIS call bound the port.
28790
+ */
28791
+ start(host = "0.0.0.0") {
28792
+ if (this.server) return Promise.resolve(this.owner);
28793
+ return new Promise((resolve21) => {
28794
+ const server = createServer3((socket) => this.handleConnection(socket));
28795
+ this.server = server;
28796
+ const onError = (error2) => {
28797
+ if (error2.code === "EADDRINUSE" || error2.code === "EADDRNOTAVAIL") {
28798
+ this.owner = false;
28799
+ this.server = null;
28800
+ Log.info(
28801
+ `tcp_service '${this.name}' port ${this.port} is already bound by another worker \u2014 single-owner, this worker will not bind (${error2.code})`
28802
+ );
28803
+ resolve21(false);
28804
+ return;
28805
+ }
28806
+ Log.error(`tcp_service '${this.name}' failed to start: ${error2.message}`);
28807
+ this.server = null;
28808
+ resolve21(false);
28809
+ };
28810
+ server.once("error", onError);
28811
+ server.listen(this.port, host, () => {
28812
+ server.off("error", onError);
28813
+ server.on("error", (error2) => Log.error(`tcp_service '${this.name}' error: ${String(error2)}`));
28814
+ this.owner = true;
28815
+ const addr = server.address();
28816
+ this.boundPortValue = typeof addr === "object" && addr ? addr.port : this.port;
28817
+ Log.info(`tcp_service '${this.name}' listening on ${host}:${this.boundPortValue}`);
28818
+ this.startReaper();
28819
+ resolve21(true);
28820
+ });
28821
+ });
28822
+ }
28823
+ handleConnection(socket) {
28824
+ if (this.maxConnections !== null && this.connections.size >= this.maxConnections) {
28825
+ socket.destroy();
28826
+ return;
28827
+ }
28828
+ const conn = new TcpConnection(socket, this);
28829
+ this.connections.add(conn);
28830
+ socket.on("data", (chunk) => {
28831
+ socket.pause();
28832
+ void this.dispatch(conn, chunk).finally(() => {
28833
+ if (!conn.isClosed) socket.resume();
28834
+ });
28835
+ });
28836
+ socket.on("close", () => this.remove(conn));
28837
+ socket.on("error", () => {
28838
+ });
28839
+ const onConnect = this._callbacks.onConnect;
28840
+ if (onConnect) {
28841
+ void Promise.resolve(onConnect(conn)).catch((error2) => {
28842
+ Log.error(`tcp_service '${this.name}' onConnect error: ${String(error2)}`);
28843
+ });
28844
+ }
28845
+ }
28846
+ async dispatch(conn, chunk) {
28847
+ conn._touch();
28848
+ const { onData, onLine } = this._callbacks;
28849
+ if (onData) {
28850
+ try {
28851
+ await onData(conn, chunk);
28852
+ } catch (error2) {
28853
+ Log.error(`tcp_service '${this.name}' onData error: ${String(error2)}`);
28854
+ }
28855
+ }
28856
+ if (onLine) {
28857
+ conn.lineBuffer = Buffer.concat([conn.lineBuffer, chunk]);
28858
+ let newline = conn.lineBuffer.indexOf(10);
28859
+ while (newline !== -1) {
28860
+ let line = conn.lineBuffer.subarray(0, newline);
28861
+ conn.lineBuffer = conn.lineBuffer.subarray(newline + 1);
28862
+ if (line.length > 0 && line[line.length - 1] === 13) {
28863
+ line = line.subarray(0, line.length - 1);
28864
+ }
28865
+ try {
28866
+ await onLine(conn, line);
28867
+ } catch (error2) {
28868
+ Log.error(`tcp_service '${this.name}' onLine error: ${String(error2)}`);
28869
+ }
28870
+ newline = conn.lineBuffer.indexOf(10);
28871
+ }
28872
+ }
28873
+ }
28874
+ /** @internal remove a connection and fire on_close exactly once. */
28875
+ remove(conn) {
28876
+ const existed = this.connections.delete(conn);
28877
+ if (conn.id !== null && this.byId.get(conn.id) === conn) {
28878
+ this.byId.delete(conn.id);
28879
+ }
28880
+ if (existed) conn._fireClose();
28881
+ }
28882
+ // ── Idle reaper (D1 consumer shape — default OFF) ───────────────────────────
28883
+ startReaper() {
28884
+ if (this.idleTimeout <= 0 || this.reaper) return;
28885
+ const intervalMs = Math.max(50, Math.min(1e3, this.idleTimeout / 2 * 1e3));
28886
+ this.reaper = setInterval(() => this.reapIdle(), intervalMs);
28887
+ this.reaper.unref();
28888
+ }
28889
+ reapIdle() {
28890
+ const now = Date.now();
28891
+ const limitMs = this.idleTimeout * 1e3;
28892
+ for (const conn of [...this.connections]) {
28893
+ if (now - conn.lastActivity >= limitMs) conn.close();
28894
+ }
28895
+ }
28896
+ /** Stop accepting new connections (close the listener). Live conns stay. */
28897
+ stopAccepting() {
28898
+ if (this.reaper) {
28899
+ clearInterval(this.reaper);
28900
+ this.reaper = null;
28901
+ }
28902
+ if (this.server && this.owner) {
28903
+ this.server.close();
28904
+ }
28905
+ }
28906
+ /** Close every live connection (firing on_close) and release the listener. */
28907
+ async drain() {
28908
+ this.stopAccepting();
28909
+ for (const conn of [...this.connections]) conn.close();
28910
+ if (this.server) {
28911
+ await new Promise((resolve21) => {
28912
+ this.server.close(() => resolve21());
28913
+ this.server.unref();
28914
+ }).catch(() => void 0);
28915
+ this.server = null;
28916
+ }
28917
+ }
28918
+ /** Stop accepting and drain in one call (used by direct callers/tests). */
28919
+ async stop() {
28920
+ await this.drain();
28921
+ }
28922
+ };
28923
+ services = /* @__PURE__ */ new Map();
28924
+ }
28925
+ });
28926
+
27710
28927
  // ../core/src/events.ts
27711
28928
  var events_exports = {};
27712
28929
  __export(events_exports, {
@@ -29915,7 +31132,7 @@ async function startServer(config) {
29915
31132
  server.on("upgrade", (req2, socket, head) => {
29916
31133
  const upPath = (req2.url ?? "/").split("?")[0];
29917
31134
  if (isDevMode() && upPath === "/__dev_reload") {
29918
- if (!devHostAllowed(req2.headers.host)) {
31135
+ if (!devHostAllowed(req2.headers.host) || !devPeerAllowed(socket.remoteAddress)) {
29919
31136
  try {
29920
31137
  socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
29921
31138
  socket.destroy();
@@ -29939,6 +31156,7 @@ async function startServer(config) {
29939
31156
  server.listen(port, host, async () => {
29940
31157
  if (!cluster.isWorker) writePidfile(port);
29941
31158
  const siblingServers = await startLoopbackSiblings(port, host, dispatch);
31159
+ await startAllTcpServices(host);
29942
31160
  const displayHost = host === "0.0.0.0" ? "localhost" : host;
29943
31161
  const isDebug = isTruthy(process.env.TINA4_DEBUG);
29944
31162
  const logLevel = (process.env.TINA4_LOG_LEVEL ?? "DEBUG").toUpperCase();
@@ -30029,6 +31247,8 @@ ${reset2}
30029
31247
  if (wsClosed > 0) {
30030
31248
  Log.info(`Closed ${wsClosed} WebSocket connection(s) with 1001 going away`);
30031
31249
  }
31250
+ stopAcceptingAllTcpServices();
31251
+ await drainAllTcpServices();
30032
31252
  const budgetSeconds = shutdownTimeoutSeconds();
30033
31253
  let timer;
30034
31254
  const outcome = await Promise.race([
@@ -30071,6 +31291,8 @@ ${reset2}
30071
31291
  process.off("SIGTERM", onSigterm);
30072
31292
  process.off("SIGINT", onSigint);
30073
31293
  stopAllBackgroundTasks();
31294
+ stopAcceptingAllTcpServices();
31295
+ void drainAllTcpServices();
30074
31296
  if (aiServer) aiServer.close();
30075
31297
  server.close();
30076
31298
  for (const sibling of siblingServers) {
@@ -30199,6 +31421,7 @@ var init_server = __esm({
30199
31421
  init_feedback();
30200
31422
  init_i18n();
30201
31423
  init_background();
31424
+ init_tcp();
30202
31425
  init_version();
30203
31426
  __filename = fileURLToPath7(import.meta.url);
30204
31427
  __dirname = dirname12(__filename);
@@ -30362,7 +31585,7 @@ var init_env = __esm({
30362
31585
  });
30363
31586
 
30364
31587
  // ../core/src/fakeData.ts
30365
- import { randomInt, randomUUID as randomUUID6 } from "node:crypto";
31588
+ import { randomInt, randomUUID as randomUUID7 } from "node:crypto";
30366
31589
  import { existsSync as existsSync24, readdirSync as readdirSync16 } from "node:fs";
30367
31590
  import { resolve as resolve16, join as join26 } from "node:path";
30368
31591
  function mulberry32(seed) {
@@ -30815,7 +32038,7 @@ var init_fakeData = __esm({
30815
32038
  const block = (n) => Array.from({ length: n }, hex).join("");
30816
32039
  return `${block(8)}-${block(4)}-${block(4)}-${block(4)}-${block(12)}`;
30817
32040
  }
30818
- return randomUUID6();
32041
+ return randomUUID7();
30819
32042
  }
30820
32043
  url() {
30821
32044
  const domain = this.pick(DOMAINS);
@@ -33088,7 +34311,7 @@ import net4 from "node:net";
33088
34311
  import tls2 from "node:tls";
33089
34312
  import { readFileSync as readFileSync23 } from "node:fs";
33090
34313
  import { basename as basename7 } from "node:path";
33091
- import { randomUUID as randomUUID7 } from "node:crypto";
34314
+ import { randomUUID as randomUUID8 } from "node:crypto";
33092
34315
  function normaliseEncryption(value, kind) {
33093
34316
  const normalised = value.trim().toLowerCase();
33094
34317
  if (!MAIL_ENCRYPTION_VALUES.includes(normalised)) {
@@ -33720,7 +34943,7 @@ var init_messenger = __esm({
33720
34943
  );
33721
34944
  }
33722
34945
  const recipients = this.prepareRecipients(options, true);
33723
- const messageId = `${randomUUID7()}@${this.host}`;
34946
+ const messageId = `${randomUUID8()}@${this.host}`;
33724
34947
  if (recipients.allRecipients.length === 0) {
33725
34948
  return { success: false, message: "No recipients specified", id: null };
33726
34949
  }
@@ -36562,7 +37785,7 @@ var init_aiClient = __esm({
36562
37785
 
36563
37786
  // ../core/src/queueBackends/rabbitmqBackend.ts
36564
37787
  import { execFileSync as execFileSync5 } from "node:child_process";
36565
- import { randomUUID as randomUUID8 } from "node:crypto";
37788
+ import { randomUUID as randomUUID9 } from "node:crypto";
36566
37789
  function parseAmqpUrl(url) {
36567
37790
  const config = {};
36568
37791
  let rest = url.replace(/^amqps:\/\//, "").replace(/^amqp:\/\//, "");
@@ -36998,7 +38221,7 @@ var init_rabbitmqBackend = __esm({
36998
38221
  "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."
36999
38222
  );
37000
38223
  }
37001
- const id = randomUUID8();
38224
+ const id = randomUUID9();
37002
38225
  const now = (/* @__PURE__ */ new Date()).toISOString();
37003
38226
  const job = {
37004
38227
  id,
@@ -37042,586 +38265,6 @@ var init_rabbitmqBackend = __esm({
37042
38265
  }
37043
38266
  });
37044
38267
 
37045
- // ../core/src/queueBackends/kafkaBackend.ts
37046
- import { execFileSync as execFileSync6 } from "node:child_process";
37047
- import { randomUUID as randomUUID9 } from "node:crypto";
37048
- function kafkaSecurityConfig(env = process.env) {
37049
- const mapping = [
37050
- ["security.protocol", "SECURITY_PROTOCOL"],
37051
- ["ssl.ca.location", "SSL_CA_LOCATION"],
37052
- ["sasl.mechanism", "SASL_MECHANISM"],
37053
- ["sasl.username", "SASL_USERNAME"],
37054
- ["sasl.password", "SASL_PASSWORD"]
37055
- ];
37056
- const config = {};
37057
- for (const [rdk, suffix] of mapping) {
37058
- const value = env[`TINA4_KAFKA_${suffix}`] || env[`KAFKA_${suffix}`];
37059
- if (value) {
37060
- config[rdk] = value;
37061
- }
37062
- }
37063
- return config;
37064
- }
37065
- function kafkaOffsetReset(env = process.env) {
37066
- return env.TINA4_KAFKA_AUTO_OFFSET_RESET || env.KAFKA_AUTO_OFFSET_RESET || "earliest";
37067
- }
37068
- var API_PRODUCE, API_FETCH, KafkaBackend;
37069
- var init_kafkaBackend = __esm({
37070
- "../core/src/queueBackends/kafkaBackend.ts"() {
37071
- "use strict";
37072
- API_PRODUCE = 0;
37073
- API_FETCH = 1;
37074
- KafkaBackend = class _KafkaBackend {
37075
- brokers;
37076
- groupId;
37077
- constructor(config) {
37078
- const url = process.env.TINA4_QUEUE_URL;
37079
- const fromUrl = url ? url.replace(/^kafka:\/\//, "") : void 0;
37080
- this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
37081
- this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
37082
- }
37083
- /**
37084
- * Resolved connection config — exposed for testing/introspection.
37085
- */
37086
- getConfig() {
37087
- return { brokers: this.brokers, groupId: this.groupId };
37088
- }
37089
- /**
37090
- * Resolved SSL/SASL client config from the environment (PLAINTEXT default).
37091
- * Mirrors Python's `KafkaConnector._security_config`.
37092
- */
37093
- securityConfig() {
37094
- return kafkaSecurityConfig();
37095
- }
37096
- /**
37097
- * Full producer config — brokers + client id + the resolved security block.
37098
- * The security keys are applied to BOTH producer and consumer (matching
37099
- * Python's `_connect_confluent`).
37100
- */
37101
- producerConfig() {
37102
- return {
37103
- "bootstrap.servers": this.brokers,
37104
- "client.id": "tina4-nodejs",
37105
- ...this.securityConfig()
37106
- };
37107
- }
37108
- /**
37109
- * Full consumer config — brokers + client id + group id + the SAME resolved
37110
- * security block applied to the producer.
37111
- */
37112
- consumerConfig() {
37113
- return {
37114
- "bootstrap.servers": this.brokers,
37115
- "client.id": "tina4-nodejs",
37116
- "group.id": this.groupId,
37117
- "auto.offset.reset": kafkaOffsetReset(),
37118
- "enable.auto.commit": false,
37119
- ...this.securityConfig()
37120
- };
37121
- }
37122
- /**
37123
- * Parse broker string into host:port.
37124
- */
37125
- parseBroker() {
37126
- const parts = this.brokers.split(",")[0].trim().split(":");
37127
- return {
37128
- host: parts[0] ?? "localhost",
37129
- port: parts[1] ? parseInt(parts[1], 10) : 9092
37130
- };
37131
- }
37132
- /**
37133
- * Execute a Kafka operation synchronously via a child process.
37134
- *
37135
- * The wire protocol is hand-rolled (Tina4 is zero-dependency — no npm Kafka
37136
- * library). Produce uses Produce **v3** carrying a Kafka **v2 RecordBatch**
37137
- * (magic byte 2) with a **CRC-32C** (Castagnoli) checksum; Fetch uses Fetch
37138
- * **v4** and parses the v2 RecordBatch out of the response. Both formats are
37139
- * what a modern KRaft broker (apache/kafka 3.7.0) requires — the old
37140
- * Produce-v0 / message-format-v0 / CRC=0 batch is rejected by such brokers.
37141
- */
37142
- execSync(operation, topic, data) {
37143
- const broker = this.parseBroker();
37144
- const script = `
37145
- const net = require("node:net");
37146
- const host = ${JSON.stringify(broker.host)};
37147
- const port = ${broker.port};
37148
- const operation = ${JSON.stringify(operation)};
37149
- const topic = ${JSON.stringify(topic)};
37150
- const groupId = ${JSON.stringify(this.groupId)};
37151
- const data = ${JSON.stringify(data ?? "")};
37152
- const API_PRODUCE = ${API_PRODUCE};
37153
- const API_FETCH = ${API_FETCH};
37154
- const PRODUCE_VERSION = 3; // v3+ requires the v2 RecordBatch format
37155
- const FETCH_VERSION = 4; // v4 returns v2 RecordBatches + isolation_level
37156
- let correlationId = 0;
37157
-
37158
- // \u2500\u2500 CRC-32C (Castagnoli, polynomial 0x1EDC6F41), table-based \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
37159
- // Node has no built-in CRC-32C; the v2 RecordBatch mandates it over the
37160
- // bytes from \`attributes\` to the end of the batch. A wrong CRC makes the
37161
- // broker drop the connection, so this must be exact.
37162
- const CRC32C_TABLE = (() => {
37163
- const table = new Uint32Array(256);
37164
- for (let n = 0; n < 256; n++) {
37165
- let c = n;
37166
- for (let k = 0; k < 8; k++) {
37167
- c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
37168
- }
37169
- table[n] = c >>> 0;
37170
- }
37171
- return table;
37172
- })();
37173
- function crc32c(buf) {
37174
- let crc = 0xffffffff;
37175
- for (let i = 0; i < buf.length; i++) {
37176
- crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
37177
- }
37178
- return (crc ^ 0xffffffff) >>> 0;
37179
- }
37180
-
37181
- // \u2500\u2500 Kafka protocol varints (zigzag-encoded signed varints) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
37182
- function encodeZigZag(n) {
37183
- // 32-bit zigzag: (n << 1) ^ (n >> 31)
37184
- return ((n << 1) ^ (n >> 31)) >>> 0;
37185
- }
37186
- function encodeVarintUnsigned(u) {
37187
- const bytes = [];
37188
- let v = u >>> 0;
37189
- while (true) {
37190
- if ((v & ~0x7f) === 0) { bytes.push(v); break; }
37191
- bytes.push((v & 0x7f) | 0x80);
37192
- v >>>= 7;
37193
- }
37194
- return Buffer.from(bytes);
37195
- }
37196
- function encodeVarint(n) {
37197
- // signed varint = zigzag then unsigned-varint
37198
- return encodeVarintUnsigned(encodeZigZag(n));
37199
- }
37200
- function decodeVarint(buf, pos) {
37201
- // returns { value, next } \u2014 signed (zigzag-decoded)
37202
- let result = 0, shift = 0, b;
37203
- do {
37204
- b = buf[pos++];
37205
- result |= (b & 0x7f) << shift;
37206
- shift += 7;
37207
- } while (b & 0x80);
37208
- result = result >>> 0;
37209
- // zigzag decode
37210
- const value = (result >>> 1) ^ -(result & 1);
37211
- return { value, next: pos };
37212
- }
37213
-
37214
- // \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
37215
- function buildRecordBatch(valueBytes) {
37216
- const now = BigInt(Date.now());
37217
-
37218
- // Build the single record body.
37219
- // record = attributes:int8(0), timestampDelta:varint(0),
37220
- // offsetDelta:varint(0), keyLen:varint(-1 null),
37221
- // valueLen:varint(len), value, headerCount:varint(0)
37222
- const recBody = Buffer.concat([
37223
- Buffer.from([0]), // attributes (int8)
37224
- encodeVarint(0), // timestampDelta
37225
- encodeVarint(0), // offsetDelta
37226
- encodeVarint(-1), // keyLen (-1 = null key)
37227
- encodeVarint(valueBytes.length), // valueLen
37228
- valueBytes, // value (JSON payload bytes)
37229
- encodeVarint(0), // headerCount
37230
- ]);
37231
- // record length prefix = signed varint of recBody length
37232
- const record = Buffer.concat([encodeVarint(recBody.length), recBody]);
37233
- const recordsCount = 1;
37234
-
37235
- // The portion the CRC covers starts at \`attributes\` and runs to end.
37236
- // crcBody = attributes:int16(0), lastOffsetDelta:int32(count-1),
37237
- // firstTimestamp:int64, maxTimestamp:int64,
37238
- // producerId:int64(-1), producerEpoch:int16(-1),
37239
- // baseSequence:int32(-1), recordsCount:int32, records
37240
- const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
37241
- let c = 0;
37242
- crcBody.writeInt16BE(0, c); c += 2; // attributes
37243
- crcBody.writeInt32BE(recordsCount - 1, c); c += 4; // lastOffsetDelta
37244
- crcBody.writeBigInt64BE(now, c); c += 8; // firstTimestamp
37245
- crcBody.writeBigInt64BE(now, c); c += 8; // maxTimestamp
37246
- crcBody.writeBigInt64BE(-1n, c); c += 8; // producerId
37247
- crcBody.writeInt16BE(-1, c); c += 2; // producerEpoch
37248
- crcBody.writeInt32BE(-1, c); c += 4; // baseSequence
37249
- crcBody.writeInt32BE(recordsCount, c); c += 4; // recordsCount
37250
- record.copy(crcBody, c);
37251
-
37252
- const crc = crc32c(crcBody);
37253
-
37254
- // Header before the CRC-covered region:
37255
- // baseOffset:int64(0), batchLength:int32, partitionLeaderEpoch:int32(-1),
37256
- // magic:int8(2), crc:uint32. batchLength counts everything AFTER itself
37257
- // (partitionLeaderEpoch through end of records) = 4 + 1 + 4 + crcBody.
37258
- const batchLength = 4 + 1 + 4 + crcBody.length;
37259
- const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
37260
- let h = 0;
37261
- head.writeBigInt64BE(0n, h); h += 8; // baseOffset
37262
- head.writeInt32BE(batchLength, h); h += 4; // batchLength
37263
- head.writeInt32BE(-1, h); h += 4; // partitionLeaderEpoch
37264
- head.writeInt8(2, h); h += 1; // magic = 2
37265
- head.writeUInt32BE(crc, h); h += 4; // crc (CRC-32C)
37266
-
37267
- return Buffer.concat([head, crcBody]);
37268
- }
37269
-
37270
- // \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
37271
- function buildProduceRequest(topicName, valueBytes) {
37272
- correlationId++;
37273
- const clientBuf = Buffer.from("tina4", "utf-8");
37274
- const topicBuf = Buffer.from(topicName, "utf-8");
37275
- const recordBatch = buildRecordBatch(valueBytes);
37276
-
37277
- const body = Buffer.alloc(
37278
- 2 + // transactionalId (-1 null nullable_string)
37279
- 2 + // acks
37280
- 4 + // timeoutMs
37281
- 4 + // topics array count
37282
- 2 + topicBuf.length + // topic name
37283
- 4 + // partitions array count
37284
- 4 + // partition index
37285
- 4 + recordBatch.length // recordSetBytes (int32 size) + batch
37286
- );
37287
- let p = 0;
37288
- body.writeInt16BE(-1, p); p += 2; // transactionalId = null
37289
- body.writeInt16BE(1, p); p += 2; // acks = 1
37290
- body.writeInt32BE(10000, p); p += 4; // timeoutMs
37291
- body.writeInt32BE(1, p); p += 4; // topics count
37292
- body.writeInt16BE(topicBuf.length, p); p += 2;
37293
- topicBuf.copy(body, p); p += topicBuf.length;
37294
- body.writeInt32BE(1, p); p += 4; // partitions count
37295
- body.writeInt32BE(0, p); p += 4; // partition index 0
37296
- body.writeInt32BE(recordBatch.length, p); p += 4; // recordSetBytes size
37297
- recordBatch.copy(body, p);
37298
-
37299
- return frameRequest(API_PRODUCE, PRODUCE_VERSION, clientBuf, body);
37300
- }
37301
-
37302
- // \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
37303
- function buildFetchRequest(topicName, fetchOffset) {
37304
- correlationId++;
37305
- const clientBuf = Buffer.from("tina4", "utf-8");
37306
- const topicBuf = Buffer.from(topicName, "utf-8");
37307
-
37308
- // Fetch v4 request body (NO logStartOffset \u2014 that arrives in v5+):
37309
- // replicaId(4), maxWaitMs(4), minBytes(4), maxBytes(4 v3+),
37310
- // isolationLevel(1 v4+), topics[count]: name, partitions[count]:
37311
- // partition(4), fetchOffset(8), partitionMaxBytes(4).
37312
- const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + (2 + topicBuf.length) + 4 + 4 + 8 + 4);
37313
- let p = 0;
37314
- buf.writeInt32BE(-1, p); p += 4; // replicaId (-1 consumer)
37315
- buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
37316
- buf.writeInt32BE(1, p); p += 4; // minBytes
37317
- buf.writeInt32BE(1048576, p); p += 4; // maxBytes
37318
- buf.writeInt8(0, p); p += 1; // isolationLevel = READ_UNCOMMITTED
37319
- buf.writeInt32BE(1, p); p += 4; // topics count
37320
- buf.writeInt16BE(topicBuf.length, p); p += 2;
37321
- topicBuf.copy(buf, p); p += topicBuf.length;
37322
- buf.writeInt32BE(1, p); p += 4; // partitions count
37323
- buf.writeInt32BE(0, p); p += 4; // partition 0
37324
- buf.writeBigInt64BE(BigInt(fetchOffset), p); p += 8; // fetchOffset
37325
- buf.writeInt32BE(1048576, p); p += 4; // partitionMaxBytes
37326
-
37327
- return frameRequest(API_FETCH, FETCH_VERSION, clientBuf, buf);
37328
- }
37329
-
37330
- // Frame a request with header v1: apiKey, apiVersion, correlationId,
37331
- // clientId (nullable string) + body.
37332
- function frameRequest(apiKey, apiVersion, clientBuf, body) {
37333
- const header = Buffer.alloc(2 + 2 + 4 + 2 + clientBuf.length);
37334
- let p = 0;
37335
- header.writeInt16BE(apiKey, p); p += 2;
37336
- header.writeInt16BE(apiVersion, p); p += 2;
37337
- header.writeInt32BE(correlationId, p); p += 4;
37338
- header.writeInt16BE(clientBuf.length, p); p += 2;
37339
- clientBuf.copy(header, p);
37340
- const payload = Buffer.concat([header, body]);
37341
- const framed = Buffer.alloc(4 + payload.length);
37342
- framed.writeInt32BE(payload.length, 0);
37343
- payload.copy(framed, 4);
37344
- return framed;
37345
- }
37346
-
37347
- // \u2500\u2500 Parse a v2 RecordBatch region, return the FIRST record value \u2500\u2500\u2500\u2500\u2500\u2500\u2500
37348
- // \`buf\` is the whole fetch response; [start, end) bounds the partition's
37349
- // record-set bytes (may contain one or more concatenated batches).
37350
- function firstRecordValue(buf, start, end) {
37351
- let pos = start;
37352
- while (pos + 12 <= end) {
37353
- // baseOffset(8) + batchLength(4) then batchLength bytes follow.
37354
- const batchLength = buf.readInt32BE(pos + 8);
37355
- const batchStart = pos + 12; // first byte of partitionLeaderEpoch
37356
- const batchEnd = batchStart + batchLength;
37357
- if (batchLength <= 0 || batchEnd > end) break;
37358
- // partitionLeaderEpoch(4), magic(1), crc(4), attributes(2),
37359
- // lastOffsetDelta(4), firstTimestamp(8), maxTimestamp(8),
37360
- // producerId(8), producerEpoch(2), baseSequence(4), recordsCount(4)
37361
- const magic = buf.readInt8(batchStart + 4);
37362
- if (magic !== 2) { pos = batchEnd; continue; }
37363
- let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
37364
- const recordsCount = buf.readInt32BE(r); r += 4;
37365
- for (let i = 0; i < recordsCount && r < batchEnd; i++) {
37366
- const recLen = decodeVarint(buf, r); // record length (signed varint)
37367
- let rp = recLen.next;
37368
- const recordEnd = rp + recLen.value;
37369
- rp += 1; // attributes (int8)
37370
- const tsDelta = decodeVarint(buf, rp); rp = tsDelta.next;
37371
- const offDelta = decodeVarint(buf, rp); rp = offDelta.next;
37372
- const keyLen = decodeVarint(buf, rp); rp = keyLen.next;
37373
- if (keyLen.value >= 0) rp += keyLen.value;
37374
- const valLen = decodeVarint(buf, rp); rp = valLen.next;
37375
- if (valLen.value >= 0) {
37376
- return buf.subarray(rp, rp + valLen.value).toString("utf-8");
37377
- }
37378
- r = recordEnd;
37379
- }
37380
- pos = batchEnd;
37381
- }
37382
- return null;
37383
- }
37384
-
37385
- let finished = false;
37386
- function finish(out, code) {
37387
- if (finished) return;
37388
- finished = true;
37389
- clearTimeout(timer);
37390
- try { sock.destroy(); } catch (e) { /* ignore */ }
37391
- if (out) process.stdout.write(out);
37392
- // Flush stdout before exiting so execFileSync captures it.
37393
- process.stdout.write("", () => process.exit(code));
37394
- }
37395
-
37396
- const sock = net.createConnection({ host, port }, () => {
37397
- if (operation === "publish") {
37398
- const req = buildProduceRequest(topic, Buffer.from(data, "utf-8"));
37399
- sock.write(req);
37400
- } else if (operation === "get") {
37401
- sock.write(buildFetchRequest(topic, 0));
37402
- } else {
37403
- finish("__UNSUPPORTED__", 0);
37404
- }
37405
- });
37406
-
37407
- let buffer = Buffer.alloc(0);
37408
- sock.on("data", (chunk) => {
37409
- buffer = Buffer.concat([buffer, chunk]);
37410
- if (buffer.length < 4) return;
37411
- const respSize = buffer.readInt32BE(0);
37412
- if (buffer.length < 4 + respSize) return;
37413
-
37414
- if (operation === "publish") {
37415
- // Produce v3 response (after the 4-byte frame size): correlationId(4),
37416
- // topics[count]: name, partitions[count]: partition(4), errorCode(2),
37417
- // baseOffset(8), logAppendTime(8); then throttleTimeMs(4) at the END.
37418
- // Only the per-partition error code matters here.
37419
- try {
37420
- let pos = 4 + 4; // skip frame size + correlationId
37421
- const topicCount = buffer.readInt32BE(pos); pos += 4;
37422
- let errCode = 0;
37423
- for (let t = 0; t < topicCount; t++) {
37424
- const tl = buffer.readInt16BE(pos); pos += 2 + tl;
37425
- const pc = buffer.readInt32BE(pos); pos += 4;
37426
- for (let pi = 0; pi < pc; pi++) {
37427
- pos += 4; // partition index
37428
- errCode = buffer.readInt16BE(pos); pos += 2; // error code
37429
- pos += 8; // baseOffset
37430
- pos += 8; // logAppendTime (v2+)
37431
- }
37432
- }
37433
- if (errCode === 0) {
37434
- finish("__PUBLISHED__", 0);
37435
- } else {
37436
- // Report the CODE, not just "it failed" \u2014 the caller decides
37437
- // whether it is retriable (3/5, the async topic-creation race)
37438
- // or fatal (e.g. 29 TOPIC_AUTHORIZATION_FAILED).
37439
- process.stderr.write("Produce error code " + errCode);
37440
- finish("__PRODUCEERROR__" + errCode, 0);
37441
- }
37442
- } catch (e) {
37443
- process.stderr.write("produce parse: " + e.message);
37444
- finish("__PARSEERROR__produce: " + e.message, 0);
37445
- }
37446
- return;
37447
- } else if (operation === "get") {
37448
- // Fetch v4 response (after the 4-byte frame size): correlationId(4),
37449
- // throttleTimeMs(4), topics[count]: name, partitions[count]:
37450
- // partition(4), errorCode(2), highWatermark(8), lastStableOffset(8),
37451
- // abortedTxns[count](producerId(8)+firstOffset(8)),
37452
- // recordSetBytes(int32)+batch.
37453
- try {
37454
- let pos = 4 + 4; // frame size + correlationId
37455
- pos += 4; // throttleTimeMs (v1+)
37456
- const topicCount = buffer.readInt32BE(pos); pos += 4;
37457
- let out = "__EMPTY__";
37458
- let fatalCode = 0;
37459
- for (let t = 0; t < topicCount; t++) {
37460
- const tl = buffer.readInt16BE(pos); pos += 2 + tl;
37461
- const pc = buffer.readInt32BE(pos); pos += 4;
37462
- for (let pi = 0; pi < pc; pi++) {
37463
- pos += 4; // partition index
37464
- const errCode = buffer.readInt16BE(pos); pos += 2;
37465
- pos += 8; // highWatermark
37466
- pos += 8; // lastStableOffset (v4+)
37467
- const abortedCount = buffer.readInt32BE(pos); pos += 4;
37468
- if (abortedCount > 0) pos += abortedCount * 16; // (-1 => none, skip)
37469
- const recSetSize = buffer.readInt32BE(pos); pos += 4;
37470
- // 3 = UNKNOWN_TOPIC_OR_PARTITION, 5 = LEADER_NOT_AVAILABLE:
37471
- // "nothing to read here yet", which a consumer that starts
37472
- // before its producer hits on every cold start. Any OTHER code
37473
- // (29 TOPIC_AUTHORIZATION_FAILED, 13 STALE_CONTROLLER_EPOCH, \u2026)
37474
- // is a real failure and must NOT be reported as an empty queue.
37475
- if (errCode !== 0 && errCode !== 3 && errCode !== 5) {
37476
- fatalCode = errCode;
37477
- }
37478
- if (errCode === 0 && recSetSize > 0) {
37479
- const val = firstRecordValue(buffer, pos, pos + recSetSize);
37480
- if (val !== null) out = val;
37481
- }
37482
- pos += recSetSize > 0 ? recSetSize : 0;
37483
- }
37484
- }
37485
- if (fatalCode !== 0) {
37486
- process.stderr.write("Fetch error code " + fatalCode);
37487
- finish("__FETCHERROR__" + fatalCode, 0);
37488
- return;
37489
- }
37490
- finish(out, 0);
37491
- } catch (e) {
37492
- // A parse failure is NOT an empty queue either \u2014 say so.
37493
- process.stderr.write("fetch parse: " + e.message);
37494
- finish("__PARSEERROR__fetch: " + e.message, 0);
37495
- }
37496
- return;
37497
- }
37498
- });
37499
-
37500
- // Report the reason on STDOUT and exit 0. Writing it to stderr and
37501
- // exiting non-zero LOST it: stderr to a pipe is an async write and
37502
- // process.exit() truncates it, so the parent saw an empty stderr and fell
37503
- // back to execFileSync's message -- which embeds this entire script.
37504
- // stdout is flushed by finish()'s write callback, so it survives.
37505
- sock.on("error", (err) => {
37506
- finish("__TRANSPORTERROR__" + err.message, 0);
37507
- });
37508
-
37509
- var timer = setTimeout(() => {
37510
- finish("__TRANSPORTERROR__timed out after 10s talking to " + host + ":" + port, 0);
37511
- }, 10000);
37512
- `;
37513
- try {
37514
- const result = execFileSync6(process.execPath, ["-e", script], {
37515
- encoding: "utf-8",
37516
- timeout: 15e3,
37517
- stdio: ["pipe", "pipe", "pipe"]
37518
- });
37519
- return result;
37520
- } catch (err) {
37521
- const e = err;
37522
- const reason = String(e.stderr ?? "").trim() || e.message || "unknown error";
37523
- const firstLine = reason.split("\n", 1)[0].slice(0, 200);
37524
- return "__TRANSPORTERROR__" + firstLine;
37525
- }
37526
- }
37527
- /**
37528
- * Sleep synchronously between produce retries.
37529
- *
37530
- * `push()` is synchronous (the whole backend drives its socket through a child
37531
- * process), so there is no event loop to await on. `Atomics.wait` on a
37532
- * SharedArrayBuffer is the stdlib way to block a thread for a fixed time --
37533
- * no dependency, no busy-wait burning CPU.
37534
- */
37535
- static sleepSync(ms) {
37536
- const shared = new Int32Array(new SharedArrayBuffer(4));
37537
- Atomics.wait(shared, 0, 0, ms);
37538
- }
37539
- /**
37540
- * Turn a sentinel from the protocol child into a thrown error, or return.
37541
- *
37542
- * The wording matches the Python and PHP backends exactly -- the parity rule
37543
- * covers user-visible error messages, not just behaviour.
37544
- */
37545
- static assertNoError(result, operation, topic) {
37546
- const fatal = /^__(PRODUCEERROR|FETCHERROR)__(\d+)/.exec(result);
37547
- if (fatal) {
37548
- throw new Error(
37549
- `Kafka rejected the ${operation} for topic ${topic}: error code ${fatal[2]}`
37550
- );
37551
- }
37552
- if (result.startsWith("__TRANSPORTERROR__")) {
37553
- throw new Error(
37554
- `Kafka ${operation} for topic ${topic} failed: ` + result.slice("__TRANSPORTERROR__".length)
37555
- );
37556
- }
37557
- if (result.startsWith("__PARSEERROR__")) {
37558
- throw new Error(
37559
- `Kafka ${operation} for topic ${topic} returned an unreadable response: ` + result.slice("__PARSEERROR__".length)
37560
- );
37561
- }
37562
- }
37563
- /**
37564
- * Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
37565
- * as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
37566
- * consumer reading the topic gets the schema it expects; otherwise the Tina4 job
37567
- * envelope. pop() unwraps both shapes (payload ?? the whole record).
37568
- */
37569
- static encodeJob(id, payload, raw) {
37570
- if (raw) return JSON.stringify(payload);
37571
- return JSON.stringify({
37572
- id,
37573
- payload,
37574
- status: "pending",
37575
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
37576
- attempts: 0,
37577
- delayUntil: null
37578
- });
37579
- }
37580
- push(queue, payload, _delay, _priority, raw = false) {
37581
- const id = randomUUID9();
37582
- const body = _KafkaBackend.encodeJob(id, payload, raw);
37583
- let result = "";
37584
- for (let attempt = 1; attempt <= 10; attempt++) {
37585
- result = this.execSync("publish", queue, body);
37586
- if (result.includes("__PUBLISHED__")) {
37587
- return id;
37588
- }
37589
- const retriable = /^__PRODUCEERROR__(3|5)\b/.test(result);
37590
- if (!retriable || attempt === 10) {
37591
- break;
37592
- }
37593
- _KafkaBackend.sleepSync(200);
37594
- }
37595
- _KafkaBackend.assertNoError(result, "produce", queue);
37596
- throw new Error(`Kafka publish failed for topic ${queue}: ${result || "no response"}`);
37597
- }
37598
- pop(queue) {
37599
- const result = this.execSync("get", queue);
37600
- _KafkaBackend.assertNoError(result, "fetch", queue);
37601
- if (!result || result === "__EMPTY__" || result === "__UNSUPPORTED__") return null;
37602
- try {
37603
- return JSON.parse(result);
37604
- } catch {
37605
- return null;
37606
- }
37607
- }
37608
- size(_queue) {
37609
- return 0;
37610
- }
37611
- clear(_queue) {
37612
- throw new Error(
37613
- "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."
37614
- );
37615
- }
37616
- purge(_queue, _status) {
37617
- throw new Error(
37618
- "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."
37619
- );
37620
- }
37621
- };
37622
- }
37623
- });
37624
-
37625
38268
  // ../core/src/testing.ts
37626
38269
  function expectEqual(args, expected) {
37627
38270
  return { type: "equal", args, expected };
@@ -38397,6 +39040,8 @@ __export(src_exports2, {
38397
39040
  TEXT_PLAIN: () => TEXT_PLAIN,
38398
39041
  TEXT_XML: () => TEXT_XML,
38399
39042
  TINA4_VERSION: () => TINA4_VERSION,
39043
+ TcpConnection: () => TcpConnection,
39044
+ TcpService: () => TcpService,
38400
39045
  TestClient: () => TestClient,
38401
39046
  TestResponse: () => TestResponse,
38402
39047
  Tina4AssertionError: () => AssertionError,
@@ -38439,6 +39084,7 @@ __export(src_exports2, {
38439
39084
  checkPassword: () => checkPassword,
38440
39085
  clearCache: () => clearCache,
38441
39086
  clearCurrentNonce: () => clearCurrentNonce,
39087
+ clearTcpRegistry: () => clearTcpRegistry,
38442
39088
  computeAcceptKey: () => computeAcceptKey,
38443
39089
  container: () => container,
38444
39090
  cors: () => cors,
@@ -38460,6 +39106,7 @@ __export(src_exports2, {
38460
39106
  devAdminLanguage: () => devAdminLanguage,
38461
39107
  devReloadWs: () => devReloadWs,
38462
39108
  discoverRoutes: () => discoverRoutes,
39109
+ drainAllTcpServices: () => drainAllTcpServices,
38463
39110
  encodeError: () => encodeError,
38464
39111
  encodeNotification: () => encodeNotification,
38465
39112
  encodeResponse: () => encodeResponse,
@@ -38547,6 +39194,7 @@ __export(src_exports2, {
38547
39194
  refreshToken: () => refreshToken,
38548
39195
  registerDevTools: () => registerDevTools,
38549
39196
  registerFeedbackRoutes: () => registerFeedbackRoutes,
39197
+ registeredTcpServices: () => registeredTcpServices,
38550
39198
  removePidfile: () => removePidfile,
38551
39199
  renderErrorOverlay: () => renderErrorOverlay,
38552
39200
  requestLogger: () => requestLogger,
@@ -38577,12 +39225,16 @@ __export(src_exports2, {
38577
39225
  setFrond: () => setFrond,
38578
39226
  showMenu: () => showMenu,
38579
39227
  start: () => start,
39228
+ startAllTcpServices: () => startAllTcpServices,
38580
39229
  startServer: () => startServer,
38581
39230
  stop: () => stop,
39231
+ stopAcceptingAllTcpServices: () => stopAcceptingAllTcpServices,
38582
39232
  stopAllBackgroundTasks: () => stopAllBackgroundTasks,
38583
39233
  supervisorBaseUrl: () => supervisorBaseUrl,
38584
39234
  sweep: () => sweep,
38585
39235
  takeOverPort: () => takeOverPort,
39236
+ tcp: () => tcp,
39237
+ tcpService: () => tcpService,
38586
39238
  templateAutoRoutingEnabled: () => templateAutoRoutingEnabled,
38587
39239
  tests: () => tests,
38588
39240
  trustedProxyNetworks: () => trustedProxyNetworks,
@@ -38602,6 +39254,7 @@ var init_src2 = __esm({
38602
39254
  "use strict";
38603
39255
  init_server();
38604
39256
  init_background();
39257
+ init_tcp();
38605
39258
  init_router();
38606
39259
  init_router();
38607
39260
  init_routeDiscovery();
@@ -46651,6 +47304,41 @@ var init_queryBuilder = __esm({
46651
47304
  }
46652
47305
  return this;
46653
47306
  }
47307
+ /**
47308
+ * Set OFFSET (rows to skip) as its own chainable verb.
47309
+ *
47310
+ * `limit(n, offset)` buries the offset as a second positional arg; this
47311
+ * exposes it on its own, so `.offset(20).limit(10)` reads naturally and
47312
+ * matches the SQL keyword.
47313
+ *
47314
+ * @param count - Number of rows to skip.
47315
+ * @returns this for chaining.
47316
+ */
47317
+ offset(count) {
47318
+ this.offsetVal = count;
47319
+ return this;
47320
+ }
47321
+ /**
47322
+ * Alias for `offset()` -- the Mongo/Eloquent name for the same thing.
47323
+ *
47324
+ * Mirrors the DocStore cursor's `skip` and the `skip` key that `toMongo()`
47325
+ * already emits, so a query reads the same whether it targets SQL or MongoDB.
47326
+ *
47327
+ * @param count - Number of rows to skip.
47328
+ * @returns this for chaining.
47329
+ */
47330
+ skip(count) {
47331
+ return this.offset(count);
47332
+ }
47333
+ /**
47334
+ * Alias for `limit()` -- the Eloquent name; pairs with `skip()`.
47335
+ *
47336
+ * @param count - Maximum rows to return.
47337
+ * @returns this for chaining.
47338
+ */
47339
+ take(count) {
47340
+ return this.limit(count);
47341
+ }
46654
47342
  /**
46655
47343
  * Build and return the SQL string without executing.
46656
47344
  *