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.
@@ -10303,6 +10303,7 @@ var init_autoCrud = __esm({
10303
10303
  var engine_exports = {};
10304
10304
  __export(engine_exports, {
10305
10305
  Frond: () => Frond,
10306
+ FrondSyntaxError: () => FrondSyntaxError,
10306
10307
  MEMO_CACHE_MAX: () => MEMO_CACHE_MAX,
10307
10308
  TEMPLATE_CACHE_MAX: () => TEMPLATE_CACHE_MAX,
10308
10309
  escapeHtml: () => escapeHtml,
@@ -11435,6 +11436,87 @@ function isEscapableStructured(value) {
11435
11436
  function toOutputString(value) {
11436
11437
  return String(value);
11437
11438
  }
11439
+ function phpDate(dt, fmt) {
11440
+ const pad = (n) => String(n).padStart(2, "0");
11441
+ const hours = dt.getHours();
11442
+ const h12 = hours % 12 || 12;
11443
+ const dow = dt.getDay();
11444
+ const iso2 = dow === 0 ? 7 : dow;
11445
+ let out = "";
11446
+ for (let i = 0; i < fmt.length; i++) {
11447
+ const c = fmt[i];
11448
+ if (c === "\\" && i + 1 < fmt.length) {
11449
+ out += fmt[i + 1];
11450
+ i++;
11451
+ continue;
11452
+ }
11453
+ switch (c) {
11454
+ case "Y":
11455
+ out += String(dt.getFullYear());
11456
+ break;
11457
+ case "y":
11458
+ out += pad(dt.getFullYear() % 100);
11459
+ break;
11460
+ case "m":
11461
+ out += pad(dt.getMonth() + 1);
11462
+ break;
11463
+ case "n":
11464
+ out += String(dt.getMonth() + 1);
11465
+ break;
11466
+ case "d":
11467
+ out += pad(dt.getDate());
11468
+ break;
11469
+ case "j":
11470
+ out += String(dt.getDate());
11471
+ break;
11472
+ case "H":
11473
+ out += pad(hours);
11474
+ break;
11475
+ case "G":
11476
+ out += String(hours);
11477
+ break;
11478
+ case "h":
11479
+ out += pad(h12);
11480
+ break;
11481
+ case "g":
11482
+ out += String(h12);
11483
+ break;
11484
+ case "i":
11485
+ out += pad(dt.getMinutes());
11486
+ break;
11487
+ case "s":
11488
+ out += pad(dt.getSeconds());
11489
+ break;
11490
+ case "A":
11491
+ out += hours < 12 ? "AM" : "PM";
11492
+ break;
11493
+ case "a":
11494
+ out += hours < 12 ? "am" : "pm";
11495
+ break;
11496
+ case "D":
11497
+ out += PHP_DAYS[dow].slice(0, 3);
11498
+ break;
11499
+ case "l":
11500
+ out += PHP_DAYS[dow];
11501
+ break;
11502
+ case "M":
11503
+ out += PHP_MONTHS[dt.getMonth()].slice(0, 3);
11504
+ break;
11505
+ case "F":
11506
+ out += PHP_MONTHS[dt.getMonth()];
11507
+ break;
11508
+ case "N":
11509
+ out += String(iso2);
11510
+ break;
11511
+ case "w":
11512
+ out += String(dow);
11513
+ break;
11514
+ default:
11515
+ out += c;
11516
+ }
11517
+ }
11518
+ return out;
11519
+ }
11438
11520
  function dateFilter(value, fmt) {
11439
11521
  let dt;
11440
11522
  if (value instanceof Date) {
@@ -11447,6 +11529,7 @@ function dateFilter(value, fmt) {
11447
11529
  } else {
11448
11530
  return String(value);
11449
11531
  }
11532
+ if (!fmt.includes("%")) return phpDate(dt, fmt);
11450
11533
  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" }));
11451
11534
  }
11452
11535
  function wordwrap(text, width) {
@@ -11557,7 +11640,7 @@ function _generateFormToken(descriptor = "") {
11557
11640
  function _generateFormTokenValue(descriptor = "") {
11558
11641
  return new SafeString(_buildFormTokenJwt(descriptor));
11559
11642
  }
11560
- 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;
11643
+ 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;
11561
11644
  var init_engine = __esm({
11562
11645
  "../frond/src/engine.ts"() {
11563
11646
  "use strict";
@@ -11754,6 +11837,35 @@ var init_engine = __esm({
11754
11837
  "__defineProperty__",
11755
11838
  "valueOf"
11756
11839
  ]);
11840
+ FrondSyntaxError = class extends Error {
11841
+ constructor(message) {
11842
+ super(message);
11843
+ this.name = "FrondSyntaxError";
11844
+ }
11845
+ };
11846
+ PHP_MONTHS = [
11847
+ "January",
11848
+ "February",
11849
+ "March",
11850
+ "April",
11851
+ "May",
11852
+ "June",
11853
+ "July",
11854
+ "August",
11855
+ "September",
11856
+ "October",
11857
+ "November",
11858
+ "December"
11859
+ ];
11860
+ PHP_DAYS = [
11861
+ "Sunday",
11862
+ "Monday",
11863
+ "Tuesday",
11864
+ "Wednesday",
11865
+ "Thursday",
11866
+ "Friday",
11867
+ "Saturday"
11868
+ ];
11757
11869
  BUILTIN_FILTERS = {
11758
11870
  upper: (v) => String(v).toUpperCase(),
11759
11871
  lower: (v) => String(v).toLowerCase(),
@@ -12277,7 +12389,9 @@ var init_engine = __esm({
12277
12389
  }
12278
12390
  }
12279
12391
  if (depth > 0) {
12280
- pos = contentStart;
12392
+ throw new FrondSyntaxError(
12393
+ `{% block ${name} %} is never closed (missing or malformed {% endblock %})`
12394
+ );
12281
12395
  }
12282
12396
  }
12283
12397
  return blocks;
@@ -12344,9 +12458,9 @@ var init_engine = __esm({
12344
12458
  }
12345
12459
  }
12346
12460
  if (!closeMatch) {
12347
- pieces.push(source.slice(mOpen.index));
12348
- pos = source.length;
12349
- break;
12461
+ throw new FrondSyntaxError(
12462
+ `{% block ${name} %} is never closed (missing or malformed {% endblock %})`
12463
+ );
12350
12464
  }
12351
12465
  const parentContent = source.slice(contentStart, closeMatch.index);
12352
12466
  const blockSource = blocks[name] ?? parentContent;
@@ -14116,6 +14230,41 @@ var init_queryBuilder = __esm({
14116
14230
  }
14117
14231
  return this;
14118
14232
  }
14233
+ /**
14234
+ * Set OFFSET (rows to skip) as its own chainable verb.
14235
+ *
14236
+ * `limit(n, offset)` buries the offset as a second positional arg; this
14237
+ * exposes it on its own, so `.offset(20).limit(10)` reads naturally and
14238
+ * matches the SQL keyword.
14239
+ *
14240
+ * @param count - Number of rows to skip.
14241
+ * @returns this for chaining.
14242
+ */
14243
+ offset(count) {
14244
+ this.offsetVal = count;
14245
+ return this;
14246
+ }
14247
+ /**
14248
+ * Alias for `offset()` -- the Mongo/Eloquent name for the same thing.
14249
+ *
14250
+ * Mirrors the DocStore cursor's `skip` and the `skip` key that `toMongo()`
14251
+ * already emits, so a query reads the same whether it targets SQL or MongoDB.
14252
+ *
14253
+ * @param count - Number of rows to skip.
14254
+ * @returns this for chaining.
14255
+ */
14256
+ skip(count) {
14257
+ return this.offset(count);
14258
+ }
14259
+ /**
14260
+ * Alias for `limit()` -- the Eloquent name; pairs with `skip()`.
14261
+ *
14262
+ * @param count - Maximum rows to return.
14263
+ * @returns this for chaining.
14264
+ */
14265
+ take(count) {
14266
+ return this.limit(count);
14267
+ }
14119
14268
  /**
14120
14269
  * Build and return the SQL string without executing.
14121
14270
  *
@@ -22221,6 +22370,9 @@ function attachCsrfFromEnv() {
22221
22370
  }
22222
22371
  return false;
22223
22372
  }
22373
+ function logPath(req2) {
22374
+ return req2.path ?? (req2.url ?? "/").split("?")[0];
22375
+ }
22224
22376
  function requestLogger() {
22225
22377
  return (req2, res, next) => {
22226
22378
  const start2 = Date.now();
@@ -22229,8 +22381,7 @@ function requestLogger() {
22229
22381
  const duration = Date.now() - start2;
22230
22382
  const status2 = res.raw.statusCode;
22231
22383
  const method = req2.method ?? "?";
22232
- const url = req2.url ?? "/";
22233
- Log.info(`${method} ${url} -> ${status2} (${duration}ms)`);
22384
+ Log.info(`${method} ${logPath(req2)} -> ${status2} (${duration}ms)`);
22234
22385
  });
22235
22386
  next();
22236
22387
  };
@@ -22657,9 +22808,9 @@ var init_middleware = __esm({
22657
22808
  const duration = Date.now() - (req2.startTime ?? Date.now());
22658
22809
  const status2 = res.raw.statusCode;
22659
22810
  const method = req2.method ?? "?";
22660
- const url = req2.url ?? "/";
22811
+ const path10 = logPath(req2);
22661
22812
  const color = status2 >= 400 ? "\x1B[31m" : status2 >= 300 ? "\x1B[33m" : "\x1B[32m";
22662
- console.log(` ${color}${status2}\x1B[0m ${method} ${url} \x1B[90m${duration}ms\x1B[0m`);
22813
+ console.log(` ${color}${status2}\x1B[0m ${method} ${path10} \x1B[90m${duration}ms\x1B[0m`);
22663
22814
  return [req2, res];
22664
22815
  }
22665
22816
  };
@@ -29696,9 +29847,9 @@ function agentLog(projectRoot3, category, message) {
29696
29847
  if (!fs4.existsSync(logDir)) {
29697
29848
  fs4.mkdirSync(logDir, { recursive: true });
29698
29849
  }
29699
- const logPath = path3.join(logDir, "agent.log");
29850
+ const logPath2 = path3.join(logDir, "agent.log");
29700
29851
  const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/\..+/, "Z");
29701
- fs4.appendFileSync(logPath, `${ts} [${category}] ${message}
29852
+ fs4.appendFileSync(logPath2, `${ts} [${category}] ${message}
29702
29853
  `, "utf-8");
29703
29854
  } catch {
29704
29855
  }
@@ -30694,13 +30845,13 @@ function registerDevTools(server) {
30694
30845
  "git_status",
30695
30846
  () => {
30696
30847
  try {
30697
- const { execFileSync: execFileSync7 } = req("node:child_process");
30848
+ const { execFileSync: execFileSync6 } = req("node:child_process");
30698
30849
  const cwd = path3.resolve(process.cwd());
30699
30850
  const run = (args) => {
30700
- return execFileSync7("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
30851
+ return execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
30701
30852
  };
30702
30853
  try {
30703
- execFileSync7("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
30854
+ execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
30704
30855
  } catch {
30705
30856
  return { error: "Not a git repository" };
30706
30857
  }
@@ -34593,6 +34744,753 @@ var init_mongoBackend = __esm({
34593
34744
  }
34594
34745
  });
34595
34746
 
34747
+ // ../core/src/queueBackends/kafkaBackend.ts
34748
+ import { Worker as Worker2 } from "node:worker_threads";
34749
+ import { randomUUID as randomUUID6 } from "node:crypto";
34750
+ function kafkaSecurityConfig(env = process.env) {
34751
+ const mapping = [
34752
+ ["security.protocol", "SECURITY_PROTOCOL"],
34753
+ ["ssl.ca.location", "SSL_CA_LOCATION"],
34754
+ ["sasl.mechanism", "SASL_MECHANISM"],
34755
+ ["sasl.username", "SASL_USERNAME"],
34756
+ ["sasl.password", "SASL_PASSWORD"]
34757
+ ];
34758
+ const config = {};
34759
+ for (const [rdk, suffix] of mapping) {
34760
+ const value = env[`TINA4_KAFKA_${suffix}`] || env[`KAFKA_${suffix}`];
34761
+ if (value) {
34762
+ config[rdk] = value;
34763
+ }
34764
+ }
34765
+ return config;
34766
+ }
34767
+ function kafkaOffsetReset(env = process.env) {
34768
+ return env.TINA4_KAFKA_AUTO_OFFSET_RESET || env.KAFKA_AUTO_OFFSET_RESET || "earliest";
34769
+ }
34770
+ var WORKER_SRC, KafkaBackend;
34771
+ var init_kafkaBackend = __esm({
34772
+ "../core/src/queueBackends/kafkaBackend.ts"() {
34773
+ "use strict";
34774
+ WORKER_SRC = `
34775
+ const net = require("node:net");
34776
+ const tls = require("node:tls");
34777
+ const { parentPort, workerData } = require("node:worker_threads");
34778
+
34779
+ const brokers = workerData.brokers;
34780
+ const groupId = workerData.groupId;
34781
+ const security = workerData.security || {};
34782
+ const offsetReset = workerData.offsetReset || "earliest";
34783
+ const header = new Int32Array(workerData.sab, 0, 2); // [0]=flag, [1]=respLen
34784
+ const outBytes = new Uint8Array(workerData.sab, 8);
34785
+
34786
+ // Lowest versions Kafka 4.x still accepts: it REMOVED Produce v0-v2 / Fetch v0-v3
34787
+ // (the old message formats) and answers a removed version by closing the socket,
34788
+ // not with an error code. These are named constants so the source invariant test
34789
+ // (test/kafkaErrorCodes.test.ts) can assert the floors.
34790
+ const PRODUCE_VERSION = 3;
34791
+ const FETCH_VERSION = 4;
34792
+
34793
+ let correlationId = 0;
34794
+ let brokerSock = null;
34795
+ let coordSock = null;
34796
+ const offsets = {}; // topic -> next read offset (in-memory cursor)
34797
+ const inFlight = {}; // job id -> { offset, value, attempts, isEnvelope }
34798
+
34799
+ const COORDINATOR_ERRORS = [14, 15, 16];
34800
+
34801
+ function parseBroker(list) {
34802
+ const first = String(list).split(",")[0].trim();
34803
+ const i = first.lastIndexOf(":");
34804
+ if (i < 0) return { host: first || "localhost", port: 9092 };
34805
+ return { host: first.slice(0, i) || "localhost", port: parseInt(first.slice(i + 1), 10) || 9092 };
34806
+ }
34807
+
34808
+ function connect(host, port) {
34809
+ return new Promise(function (resolve, reject) {
34810
+ const proto = String(security["security.protocol"] || "PLAINTEXT").toUpperCase();
34811
+ const useTls = proto.indexOf("SSL") >= 0;
34812
+ let sock;
34813
+ const onErr = function (e) { reject(e); };
34814
+ if (useTls) {
34815
+ const opts = { host: host, port: port, servername: host };
34816
+ if (security["ssl.ca.location"]) opts.ca = require("node:fs").readFileSync(security["ssl.ca.location"]);
34817
+ sock = tls.connect(opts, function () { sock.removeListener("error", onErr); resolve(sock); });
34818
+ } else {
34819
+ sock = net.createConnection({ host: host, port: port }, function () { sock.removeListener("error", onErr); resolve(sock); });
34820
+ }
34821
+ sock.once("error", onErr);
34822
+ });
34823
+ }
34824
+
34825
+ // One request/response round trip on a socket: write the framed request, read a
34826
+ // 4-byte length then that many bytes, resolve with the payload AFTER the length
34827
+ // (so it starts at correlationId). Serialized \u2014 one in flight per socket.
34828
+ function rpc(sock, reqBuf) {
34829
+ return new Promise(function (resolve, reject) {
34830
+ let buf = Buffer.alloc(0);
34831
+ function onData(chunk) {
34832
+ buf = Buffer.concat([buf, chunk]);
34833
+ if (buf.length < 4) return;
34834
+ const size = buf.readInt32BE(0);
34835
+ if (buf.length < 4 + size) return;
34836
+ sock.removeListener("data", onData);
34837
+ sock.removeListener("error", onErr);
34838
+ resolve(buf.subarray(4, 4 + size));
34839
+ }
34840
+ function onErr(e) {
34841
+ sock.removeListener("data", onData);
34842
+ reject(e);
34843
+ }
34844
+ sock.on("data", onData);
34845
+ sock.once("error", onErr);
34846
+ sock.write(reqBuf);
34847
+ });
34848
+ }
34849
+
34850
+ // \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
34851
+ function kstr(s) {
34852
+ const b = Buffer.from(s, "utf-8");
34853
+ const out = Buffer.alloc(2 + b.length);
34854
+ out.writeInt16BE(b.length, 0);
34855
+ b.copy(out, 2);
34856
+ return out;
34857
+ }
34858
+ function frame(apiKey, apiVersion, body) {
34859
+ correlationId++;
34860
+ const client = Buffer.from("tina4-nodejs", "utf-8");
34861
+ const head = Buffer.alloc(2 + 2 + 4 + 2 + client.length);
34862
+ let p = 0;
34863
+ head.writeInt16BE(apiKey, p); p += 2;
34864
+ head.writeInt16BE(apiVersion, p); p += 2;
34865
+ head.writeInt32BE(correlationId, p); p += 4;
34866
+ head.writeInt16BE(client.length, p); p += 2;
34867
+ client.copy(head, p);
34868
+ const payload = Buffer.concat([head, body]);
34869
+ const out = Buffer.alloc(4 + payload.length);
34870
+ out.writeInt32BE(payload.length, 0);
34871
+ payload.copy(out, 4);
34872
+ return out;
34873
+ }
34874
+
34875
+ // \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
34876
+ const CRC32C_TABLE = (function () {
34877
+ const t = new Uint32Array(256);
34878
+ for (let n = 0; n < 256; n++) {
34879
+ let c = n;
34880
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
34881
+ t[n] = c >>> 0;
34882
+ }
34883
+ return t;
34884
+ })();
34885
+ function crc32c(buf) {
34886
+ let crc = 0xffffffff;
34887
+ for (let i = 0; i < buf.length; i++) crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
34888
+ return (crc ^ 0xffffffff) >>> 0;
34889
+ }
34890
+ function zig(n) { return ((n << 1) ^ (n >> 31)) >>> 0; }
34891
+ function varU(u) {
34892
+ const b = [];
34893
+ let v = u >>> 0;
34894
+ for (;;) { if ((v & ~0x7f) === 0) { b.push(v); break; } b.push((v & 0x7f) | 0x80); v >>>= 7; }
34895
+ return Buffer.from(b);
34896
+ }
34897
+ function varint(n) { return varU(zig(n)); }
34898
+ function readVarint(buf, pos) {
34899
+ let result = 0, shift = 0, b;
34900
+ do { b = buf[pos++]; result |= (b & 0x7f) << shift; shift += 7; } while (b & 0x80);
34901
+ result = result >>> 0;
34902
+ return { value: (result >>> 1) ^ -(result & 1), next: pos };
34903
+ }
34904
+ function buildRecordBatch(valueBytes) {
34905
+ const now = BigInt(Date.now());
34906
+ const recBody = Buffer.concat([
34907
+ Buffer.from([0]), varint(0), varint(0), varint(-1),
34908
+ varint(valueBytes.length), valueBytes, varint(0),
34909
+ ]);
34910
+ const record = Buffer.concat([varint(recBody.length), recBody]);
34911
+ const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
34912
+ let c = 0;
34913
+ crcBody.writeInt16BE(0, c); c += 2;
34914
+ crcBody.writeInt32BE(0, c); c += 4;
34915
+ crcBody.writeBigInt64BE(now, c); c += 8;
34916
+ crcBody.writeBigInt64BE(now, c); c += 8;
34917
+ crcBody.writeBigInt64BE(-1n, c); c += 8;
34918
+ crcBody.writeInt16BE(-1, c); c += 2;
34919
+ crcBody.writeInt32BE(-1, c); c += 4;
34920
+ crcBody.writeInt32BE(1, c); c += 4;
34921
+ record.copy(crcBody, c);
34922
+ const crc = crc32c(crcBody);
34923
+ const batchLength = 4 + 1 + 4 + crcBody.length;
34924
+ const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
34925
+ let h = 0;
34926
+ head.writeBigInt64BE(0n, h); h += 8;
34927
+ head.writeInt32BE(batchLength, h); h += 4;
34928
+ head.writeInt32BE(-1, h); h += 4;
34929
+ head.writeInt8(2, h); h += 1;
34930
+ head.writeUInt32BE(crc, h); h += 4;
34931
+ return Buffer.concat([head, crcBody]);
34932
+ }
34933
+
34934
+ // \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
34935
+ function produceRequest(topic, valueBytes) {
34936
+ const topicBuf = Buffer.from(topic, "utf-8");
34937
+ const batch = buildRecordBatch(valueBytes);
34938
+ const body = Buffer.alloc(2 + 2 + 4 + 4 + 2 + topicBuf.length + 4 + 4 + 4 + batch.length);
34939
+ let p = 0;
34940
+ body.writeInt16BE(-1, p); p += 2; // transactionalId null
34941
+ body.writeInt16BE(1, p); p += 2; // acks 1
34942
+ body.writeInt32BE(10000, p); p += 4; // timeoutMs
34943
+ body.writeInt32BE(1, p); p += 4; // topics
34944
+ body.writeInt16BE(topicBuf.length, p); p += 2;
34945
+ topicBuf.copy(body, p); p += topicBuf.length;
34946
+ body.writeInt32BE(1, p); p += 4; // partitions
34947
+ body.writeInt32BE(0, p); p += 4; // partition 0
34948
+ body.writeInt32BE(batch.length, p); p += 4;
34949
+ batch.copy(body, p);
34950
+ return frame(0, PRODUCE_VERSION, body);
34951
+ }
34952
+ function parseProduce(resp) {
34953
+ let pos = 4; // correlationId
34954
+ const topicCount = resp.readInt32BE(pos); pos += 4;
34955
+ let err = 0;
34956
+ for (let t = 0; t < topicCount; t++) {
34957
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
34958
+ const pc = resp.readInt32BE(pos); pos += 4;
34959
+ for (let pi = 0; pi < pc; pi++) {
34960
+ pos += 4; err = resp.readInt16BE(pos); pos += 2; pos += 8; pos += 8;
34961
+ }
34962
+ }
34963
+ return err;
34964
+ }
34965
+ async function produce(topic, valueBytes) {
34966
+ const sock = await broker();
34967
+ for (let attempt = 1; attempt <= 10; attempt++) {
34968
+ const err = parseProduce(await rpc(sock, produceRequest(topic, valueBytes)));
34969
+ if (err === 0) return;
34970
+ if ((err !== 3 && err !== 5) || attempt === 10) {
34971
+ throw new Error("Kafka rejected the produce for topic " + topic + ": error code " + err);
34972
+ }
34973
+ await sleep(200);
34974
+ }
34975
+ }
34976
+
34977
+ // \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
34978
+ function fetchRequest(topic, offset) {
34979
+ const topicBuf = Buffer.from(topic, "utf-8");
34980
+ const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + 2 + topicBuf.length + 4 + 4 + 8 + 4);
34981
+ let p = 0;
34982
+ buf.writeInt32BE(-1, p); p += 4; // replicaId
34983
+ buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
34984
+ buf.writeInt32BE(1, p); p += 4; // minBytes
34985
+ buf.writeInt32BE(1048576, p); p += 4; // maxBytes
34986
+ buf.writeInt8(0, p); p += 1; // isolation READ_UNCOMMITTED
34987
+ buf.writeInt32BE(1, p); p += 4; // topics
34988
+ buf.writeInt16BE(topicBuf.length, p); p += 2;
34989
+ topicBuf.copy(buf, p); p += topicBuf.length;
34990
+ buf.writeInt32BE(1, p); p += 4; // partitions
34991
+ buf.writeInt32BE(0, p); p += 4; // partition 0
34992
+ buf.writeBigInt64BE(BigInt(offset), p); p += 8;
34993
+ buf.writeInt32BE(1048576, p); p += 4;
34994
+ return frame(1, FETCH_VERSION, buf);
34995
+ }
34996
+ // Decode the first record of the partition's record-set: its value string and
34997
+ // absolute offset (baseOffset + offsetDelta). null = no usable record.
34998
+ function firstRecord(buf, start, end) {
34999
+ let pos = start;
35000
+ while (pos + 12 <= end) {
35001
+ const baseOffset = buf.readBigInt64BE(pos);
35002
+ const batchLength = buf.readInt32BE(pos + 8);
35003
+ const batchStart = pos + 12;
35004
+ const batchEnd = batchStart + batchLength;
35005
+ if (batchLength <= 0 || batchEnd > end) break;
35006
+ const magic = buf.readInt8(batchStart + 4);
35007
+ if (magic !== 2) { pos = batchEnd; continue; }
35008
+ let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
35009
+ const recordsCount = buf.readInt32BE(r); r += 4;
35010
+ for (let i = 0; i < recordsCount && r < batchEnd; i++) {
35011
+ const recLen = readVarint(buf, r);
35012
+ let rp = recLen.next;
35013
+ const recordEnd = rp + recLen.value;
35014
+ rp += 1;
35015
+ rp = readVarint(buf, rp).next; // timestampDelta
35016
+ const offDelta = readVarint(buf, rp); rp = offDelta.next;
35017
+ const keyLen = readVarint(buf, rp); rp = keyLen.next;
35018
+ if (keyLen.value >= 0) rp += keyLen.value;
35019
+ const valLen = readVarint(buf, rp); rp = valLen.next;
35020
+ if (valLen.value >= 0) {
35021
+ return {
35022
+ value: buf.subarray(rp, rp + valLen.value).toString("utf-8"),
35023
+ offset: Number(baseOffset) + offDelta.value,
35024
+ };
35025
+ }
35026
+ r = recordEnd;
35027
+ }
35028
+ pos = batchEnd;
35029
+ }
35030
+ return null;
35031
+ }
35032
+ async function fetchAt(topic, offset) {
35033
+ const sock = await broker();
35034
+ const resp = await rpc(sock, fetchRequest(topic, offset));
35035
+ let pos = 4; // correlationId
35036
+ pos += 4; // throttleTimeMs
35037
+ const topicCount = resp.readInt32BE(pos); pos += 4;
35038
+ let rec = null;
35039
+ for (let t = 0; t < topicCount; t++) {
35040
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
35041
+ const pc = resp.readInt32BE(pos); pos += 4;
35042
+ for (let pi = 0; pi < pc; pi++) {
35043
+ pos += 4;
35044
+ const err = resp.readInt16BE(pos); pos += 2;
35045
+ pos += 8; pos += 8;
35046
+ const aborted = resp.readInt32BE(pos); pos += 4;
35047
+ if (aborted > 0) pos += aborted * 16;
35048
+ const recSize = resp.readInt32BE(pos); pos += 4;
35049
+ if (err !== 0 && err !== 3 && err !== 5) {
35050
+ throw new Error("Kafka rejected the fetch for topic " + topic + ": error code " + err);
35051
+ }
35052
+ if (err === 0 && recSize > 0) {
35053
+ const r = firstRecord(resp, pos, pos + recSize);
35054
+ if (r !== null) rec = r;
35055
+ }
35056
+ if (recSize > 0) pos += recSize;
35057
+ }
35058
+ }
35059
+ return rec;
35060
+ }
35061
+
35062
+ // \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
35063
+ function readNullableString(buf, pos) {
35064
+ const len = buf.readInt16BE(pos); pos += 2;
35065
+ if (len < 0) return { value: null, next: pos };
35066
+ return { value: buf.toString("utf-8", pos, pos + len), next: pos + len };
35067
+ }
35068
+ async function findCoordinator() {
35069
+ const sock = await broker();
35070
+ for (let attempt = 0; attempt < 30; attempt++) {
35071
+ const body = Buffer.concat([kstr(groupId), Buffer.from([0])]); // key_type 0 = group
35072
+ const resp = await rpc(sock, frame(10, 1, body));
35073
+ let pos = 4; // correlationId
35074
+ pos += 4; // throttle
35075
+ const err = resp.readInt16BE(pos); pos += 2;
35076
+ pos = readNullableString(resp, pos).next; // error_message
35077
+ pos += 4; // node_id
35078
+ const hostRes = readNullableString(resp, pos); pos = hostRes.next;
35079
+ const port = resp.readInt32BE(pos);
35080
+ if (err === 0 && hostRes.value) return { host: hostRes.value, port: port };
35081
+ if (err !== 14 && err !== 15) {
35082
+ throw new Error("Kafka FindCoordinator failed for group " + groupId + ": error code " + err);
35083
+ }
35084
+ await sleep(300);
35085
+ }
35086
+ throw new Error("Kafka group coordinator for " + groupId + " did not become available");
35087
+ }
35088
+ async function coordinator() {
35089
+ if (coordSock) return coordSock;
35090
+ const c = await findCoordinator();
35091
+ coordSock = await connect(c.host, c.port);
35092
+ return coordSock;
35093
+ }
35094
+ function dropCoordinator() {
35095
+ if (coordSock) { try { coordSock.destroy(); } catch (e) { /* ignore */ } }
35096
+ coordSock = null;
35097
+ }
35098
+ function offsetCommitRequest(topic, offset) {
35099
+ const body = Buffer.concat([
35100
+ kstr(groupId),
35101
+ int32(-1), // generation_id -1 (simple consumer)
35102
+ kstr(""), // member_id ""
35103
+ int64(-1n), // retention_time -1
35104
+ int32(1), kstr(topic), int32(1), int32(0), int64(BigInt(offset)), int16(-1),
35105
+ ]);
35106
+ return frame(8, 2, body);
35107
+ }
35108
+ function parseOffsetCommit(resp) {
35109
+ let pos = 4;
35110
+ const tc = resp.readInt32BE(pos); pos += 4;
35111
+ if (tc === 0) return 16;
35112
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
35113
+ const pc = resp.readInt32BE(pos); pos += 4;
35114
+ if (pc === 0) return 16;
35115
+ pos += 4;
35116
+ return resp.readInt16BE(pos);
35117
+ }
35118
+ async function offsetCommit(topic, offset) {
35119
+ var err = 0;
35120
+ for (var attempt = 0; attempt < 10; attempt++) {
35121
+ if (attempt > 0) { dropCoordinator(); await new Promise(function (r) { setTimeout(r, 200 * attempt); }); }
35122
+ err = parseOffsetCommit(await rpc(await coordinator(), offsetCommitRequest(topic, offset)));
35123
+ if (COORDINATOR_ERRORS.indexOf(err) < 0) break;
35124
+ }
35125
+ if (err !== 0) throw new Error("Kafka rejected the offset commit for " + topic + ": error code " + err);
35126
+ }
35127
+ function offsetFetchRequest(topic) {
35128
+ const body = Buffer.concat([kstr(groupId), int32(1), kstr(topic), int32(1), int32(0)]);
35129
+ return frame(9, 1, body);
35130
+ }
35131
+ function parseOffsetFetch(resp) {
35132
+ let pos = 4;
35133
+ const tc = resp.readInt32BE(pos); pos += 4;
35134
+ if (tc === 0) return { offset: -1, err: 16 };
35135
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
35136
+ const pc = resp.readInt32BE(pos); pos += 4;
35137
+ if (pc === 0) return { offset: -1, err: 16 };
35138
+ pos += 4;
35139
+ const offset = Number(resp.readBigInt64BE(pos)); pos += 8;
35140
+ pos = readNullableString(resp, pos).next;
35141
+ const err = resp.readInt16BE(pos);
35142
+ return { offset: offset, err: err };
35143
+ }
35144
+ async function offsetFetch(topic) {
35145
+ var r = { offset: -1, err: 0 };
35146
+ for (var attempt = 0; attempt < 10; attempt++) {
35147
+ if (attempt > 0) { dropCoordinator(); await new Promise(function (res) { setTimeout(res, 200 * attempt); }); }
35148
+ r = parseOffsetFetch(await rpc(await coordinator(), offsetFetchRequest(topic)));
35149
+ if (COORDINATOR_ERRORS.indexOf(r.err) < 0) break;
35150
+ }
35151
+ if (r.err !== 0) throw new Error("Kafka rejected the offset fetch for " + topic + ": error code " + r.err);
35152
+ return r.offset < 0 ? 0 : r.offset;
35153
+ }
35154
+
35155
+ function int16(n) { const b = Buffer.alloc(2); b.writeInt16BE(n, 0); return b; }
35156
+ function int32(n) { const b = Buffer.alloc(4); b.writeInt32BE(n, 0); return b; }
35157
+ function int64(n) { const b = Buffer.alloc(8); b.writeBigInt64BE(BigInt(n), 0); return b; }
35158
+ function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
35159
+
35160
+ async function broker() {
35161
+ if (brokerSock) return brokerSock;
35162
+ const b = parseBroker(brokers);
35163
+ brokerSock = await connect(b.host, b.port);
35164
+ return brokerSock;
35165
+ }
35166
+
35167
+ // Resume from the committed offset on the FIRST read of a topic in this worker,
35168
+ // then advance the in-memory cursor; the committed offset only moves on a
35169
+ // commit, so it lags and a crash before commit replays (at-least-once).
35170
+ async function fetchNext(topic) {
35171
+ if (!(topic in offsets)) offsets[topic] = await offsetFetch(topic);
35172
+ const rec = await fetchAt(topic, offsets[topic]);
35173
+ if (rec === null) return null;
35174
+ offsets[topic] = rec.offset + 1;
35175
+ return rec;
35176
+ }
35177
+
35178
+ function encodeEnvelope(id, payload, attempts) {
35179
+ return JSON.stringify({ id: id, payload: payload, status: "pending", createdAt: new Date().toISOString(), attempts: attempts, delayUntil: null });
35180
+ }
35181
+
35182
+ async function handle(req) {
35183
+ const op = req.op;
35184
+ if (op === "publish") {
35185
+ await produce(req.topic, Buffer.from(req.value, "utf-8"));
35186
+ return { ok: true };
35187
+ }
35188
+ if (op === "dequeueRaw") {
35189
+ // The value exactly as it sits on the wire (a raw record stays its bare
35190
+ // bytes \u2014 tina4-nodejs#264), with no id/offset tracking. For wire
35191
+ // inspection; the facade consumes through "pop", which normalises + tracks.
35192
+ const rec = await fetchNext(req.topic);
35193
+ if (rec === null) return { ok: true, message: null };
35194
+ let decoded;
35195
+ try { decoded = JSON.parse(rec.value); } catch (e) { decoded = rec.value; }
35196
+ return { ok: true, message: decoded };
35197
+ }
35198
+ if (op === "pop") {
35199
+ let rec;
35200
+ try {
35201
+ rec = await fetchNext(req.topic);
35202
+ } catch (e) {
35203
+ // A malformed/short response runs the parser off the end (a RangeError);
35204
+ // anything else is a transport failure. Both name the topic so the cause
35205
+ // is findable, and neither reads as an empty queue (ADR: a real failure
35206
+ // must never look idle). Wording matches the Python/PHP backends.
35207
+ const range = (e instanceof RangeError) || /out of range|bounds/i.test((e && e.message) || "");
35208
+ if (range) throw new Error("Kafka fetch for topic " + req.topic + " returned an unreadable response: " + ((e && e.message) || e));
35209
+ throw new Error("Kafka fetch for topic " + req.topic + " failed: " + ((e && e.message) || e));
35210
+ }
35211
+ if (rec === null) return { ok: true, message: null };
35212
+ const coordinate = req.topic + ":0:" + rec.offset;
35213
+ let decoded;
35214
+ try { decoded = JSON.parse(rec.value); } catch (e) { decoded = null; }
35215
+ let message;
35216
+ let isEnvelope = false;
35217
+ if (decoded !== null && typeof decoded === "object" && !Array.isArray(decoded) && "payload" in decoded) {
35218
+ message = decoded;
35219
+ isEnvelope = true;
35220
+ if (!message.id) message.id = coordinate;
35221
+ } else {
35222
+ message = { id: coordinate, payload: decoded === null ? rec.value : decoded, status: "pending", attempts: 0 };
35223
+ }
35224
+ // The Job lifecycle (complete/fail/retry) routes by the record's own topic,
35225
+ // so it must be carried back (like the file/mongodb backends do).
35226
+ message.topic = req.topic;
35227
+ inFlight[String(message.id)] = { offset: rec.offset, value: rec.value, attempts: message.attempts || 0, isEnvelope: isEnvelope };
35228
+ return { ok: true, message: message };
35229
+ }
35230
+ if (op === "complete") {
35231
+ const rec = inFlight[String(req.id)];
35232
+ if (rec) { delete inFlight[String(req.id)]; await offsetCommit(req.topic, rec.offset + 1); }
35233
+ return { ok: true };
35234
+ }
35235
+ if (op === "fail") {
35236
+ const rec = inFlight[String(req.id)];
35237
+ if (rec) {
35238
+ delete inFlight[String(req.id)];
35239
+ const attempts = (rec.attempts || 0) + 1;
35240
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
35241
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
35242
+ if (attempts < req.maxRetries) {
35243
+ await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
35244
+ } else {
35245
+ await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: attempts, error: req.error }), "utf-8"));
35246
+ }
35247
+ await offsetCommit(req.topic, rec.offset + 1);
35248
+ }
35249
+ return { ok: true };
35250
+ }
35251
+ if (op === "reject") {
35252
+ const rec = inFlight[String(req.id)];
35253
+ if (rec) {
35254
+ delete inFlight[String(req.id)];
35255
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
35256
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
35257
+ await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: req.maxRetries, error: req.reason }), "utf-8"));
35258
+ await offsetCommit(req.topic, rec.offset + 1);
35259
+ }
35260
+ return { ok: true };
35261
+ }
35262
+ if (op === "retry") {
35263
+ const rec = inFlight[String(req.id)];
35264
+ if (rec) {
35265
+ delete inFlight[String(req.id)];
35266
+ const attempts = (rec.attempts || 0) + 1;
35267
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
35268
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
35269
+ await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
35270
+ await offsetCommit(req.topic, rec.offset + 1);
35271
+ }
35272
+ return { ok: true };
35273
+ }
35274
+ if (op === "deadLetters") {
35275
+ // Read the <topic>.dead_letter topic from the beginning; every record on it
35276
+ // is a dead letter by construction. A throwaway cursor that never commits,
35277
+ // so it does not disturb the main consume position.
35278
+ const dlq = req.topic + ".dead_letter";
35279
+ const out = [];
35280
+ let off = 0;
35281
+ for (;;) {
35282
+ const rec = await fetchAt(dlq, off);
35283
+ if (rec === null) break;
35284
+ off = rec.offset + 1;
35285
+ try { out.push(JSON.parse(rec.value)); } catch (e) { /* skip */ }
35286
+ if (out.length > 10000) break;
35287
+ }
35288
+ return { ok: true, deadLetters: out };
35289
+ }
35290
+ if (op === "close") {
35291
+ try { if (brokerSock) brokerSock.destroy(); } catch (e) { /* ignore */ }
35292
+ dropCoordinator();
35293
+ return { ok: true, closing: true };
35294
+ }
35295
+ return { ok: false, error: "unknown op " + op };
35296
+ }
35297
+
35298
+ parentPort.on("message", async function (req) {
35299
+ let res;
35300
+ try { res = await handle(req); }
35301
+ catch (e) { res = { ok: false, error: (e && e.message) ? e.message : String(e) }; }
35302
+ const bytes = Buffer.from(JSON.stringify(res), "utf-8");
35303
+ outBytes.set(bytes.subarray(0, outBytes.length), 0);
35304
+ Atomics.store(header, 1, Math.min(bytes.length, outBytes.length));
35305
+ Atomics.store(header, 0, 1);
35306
+ Atomics.notify(header, 0);
35307
+ });
35308
+ `;
35309
+ KafkaBackend = class _KafkaBackend {
35310
+ brokers;
35311
+ groupId;
35312
+ worker = null;
35313
+ sab = null;
35314
+ header = null;
35315
+ outBytes = null;
35316
+ static SAB_SIZE = 1 << 20;
35317
+ // 1 MiB (8-byte header + response bytes)
35318
+ static CALL_TIMEOUT_MS = 2e4;
35319
+ constructor(config) {
35320
+ const url = process.env.TINA4_QUEUE_URL;
35321
+ const fromUrl = url ? url.replace(/^kafka:\/\//, "") : void 0;
35322
+ this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
35323
+ this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
35324
+ }
35325
+ /** Resolved connection config — exposed for testing/introspection. */
35326
+ getConfig() {
35327
+ return { brokers: this.brokers, groupId: this.groupId };
35328
+ }
35329
+ securityConfig() {
35330
+ return kafkaSecurityConfig();
35331
+ }
35332
+ producerConfig() {
35333
+ return { "bootstrap.servers": this.brokers, "client.id": "tina4-nodejs", ...this.securityConfig() };
35334
+ }
35335
+ consumerConfig() {
35336
+ return {
35337
+ "bootstrap.servers": this.brokers,
35338
+ "client.id": "tina4-nodejs",
35339
+ "group.id": this.groupId,
35340
+ "auto.offset.reset": kafkaOffsetReset(),
35341
+ "enable.auto.commit": false,
35342
+ ...this.securityConfig()
35343
+ };
35344
+ }
35345
+ /** Lazily start the persistent worker + its shared buffer. */
35346
+ ensureWorker() {
35347
+ if (this.worker) return;
35348
+ this.sab = new SharedArrayBuffer(_KafkaBackend.SAB_SIZE);
35349
+ this.header = new Int32Array(this.sab, 0, 2);
35350
+ this.outBytes = new Uint8Array(this.sab, 8);
35351
+ this.worker = new Worker2(WORKER_SRC, {
35352
+ eval: true,
35353
+ workerData: {
35354
+ brokers: this.brokers,
35355
+ groupId: this.groupId,
35356
+ security: this.securityConfig(),
35357
+ offsetReset: kafkaOffsetReset(),
35358
+ sab: this.sab
35359
+ }
35360
+ });
35361
+ this.worker.unref();
35362
+ }
35363
+ /** One synchronous request to the worker: post, block on Atomics.wait, read. */
35364
+ request(req2) {
35365
+ this.ensureWorker();
35366
+ const header = this.header;
35367
+ const outBytes = this.outBytes;
35368
+ Atomics.store(header, 0, 0);
35369
+ this.worker.postMessage(req2);
35370
+ const waited = Atomics.wait(header, 0, 0, _KafkaBackend.CALL_TIMEOUT_MS);
35371
+ if (waited === "timed-out") {
35372
+ throw new Error(`Kafka ${String(req2.op)} for topic ${String(req2.topic ?? "")} timed out after ${_KafkaBackend.CALL_TIMEOUT_MS}ms`);
35373
+ }
35374
+ const len = Atomics.load(header, 1);
35375
+ const json = Buffer.from(outBytes.buffer, outBytes.byteOffset, len).toString("utf-8");
35376
+ const res = JSON.parse(json);
35377
+ if (res.ok === false) {
35378
+ throw new Error(String(res.error ?? "unknown Kafka worker error"));
35379
+ }
35380
+ return res;
35381
+ }
35382
+ /**
35383
+ * Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
35384
+ * as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
35385
+ * consumer reading the topic gets the schema it expects; otherwise the Tina4
35386
+ * job envelope. pop() unwraps both shapes (payload ?? the whole record).
35387
+ */
35388
+ static encodeJob(id, payload, raw) {
35389
+ if (raw) return JSON.stringify(payload);
35390
+ return JSON.stringify({
35391
+ id,
35392
+ payload,
35393
+ status: "pending",
35394
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
35395
+ attempts: 0,
35396
+ delayUntil: null
35397
+ });
35398
+ }
35399
+ push(queue, payload, _delay, _priority, raw = false) {
35400
+ const id = randomUUID6();
35401
+ const value = _KafkaBackend.encodeJob(id, payload, raw);
35402
+ this.request({ op: "publish", topic: queue, value });
35403
+ return id;
35404
+ }
35405
+ pop(queue) {
35406
+ const res = this.request({ op: "pop", topic: queue });
35407
+ const message = res.message;
35408
+ return message ?? null;
35409
+ }
35410
+ /**
35411
+ * Read the next record's value exactly as it sits on the wire — a Tina4
35412
+ * envelope as produced, a raw record (tina4-nodejs#264) as its bare bytes —
35413
+ * with no id/offset tracking. For a foreign consumer's view of the schema;
35414
+ * the queue facade consumes through pop(), which also normalises and tracks
35415
+ * the offset so complete()/fail() can commit it.
35416
+ */
35417
+ dequeue(queue) {
35418
+ const res = this.request({ op: "dequeueRaw", topic: queue });
35419
+ return res.message ?? null;
35420
+ }
35421
+ /** Commit the record's offset so a completed job never replays (ADR-0022 d.4). */
35422
+ complete(queue, id) {
35423
+ this.request({ op: "complete", topic: queue, id });
35424
+ }
35425
+ /**
35426
+ * Record a failed attempt: re-produce the job with an incremented attempts
35427
+ * count while it has retries left, else produce it to the dead-letter topic;
35428
+ * commit the original offset either way (ADR-0022 decision 2).
35429
+ */
35430
+ fail(queue, id, error2, maxRetries, _retryBackoff) {
35431
+ this.request({ op: "fail", topic: queue, id, error: error2, maxRetries });
35432
+ }
35433
+ /** Dead-letter the job now, no retry (ADR-0023 reject), then commit the offset. */
35434
+ reject(queue, id, reason, maxRetries) {
35435
+ this.request({ op: "reject", topic: queue, id, reason, maxRetries });
35436
+ }
35437
+ /** Re-produce the job (manual retry) and commit the original offset. */
35438
+ retry(queue, id, delaySeconds) {
35439
+ this.request({ op: "retry", topic: queue, id, delaySeconds: delaySeconds ?? 0 });
35440
+ return true;
35441
+ }
35442
+ /** Read the dead-letter topic for this queue (every record on it is a dead letter). */
35443
+ deadLetters(queue, _maxRetries) {
35444
+ const res = this.request({ op: "deadLetters", topic: queue });
35445
+ return res.deadLetters ?? [];
35446
+ }
35447
+ /**
35448
+ * Refuse rather than silently answer from the local file store. Kafka keeps no
35449
+ * queryable registry of failed jobs: a failed record is re-produced to a
35450
+ * dead-letter TOPIC and the original offset committed past, and a log cannot be
35451
+ * queried by job state. Returning [] would claim nothing has failed.
35452
+ */
35453
+ failed(_queue, _maxRetries) {
35454
+ throw new Error(
35455
+ "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."
35456
+ );
35457
+ }
35458
+ /** Refuse for the same reason failed() does (no queryable failed registry). */
35459
+ retryFailed(_queue, _maxRetries) {
35460
+ throw new Error(
35461
+ "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."
35462
+ );
35463
+ }
35464
+ size(_queue) {
35465
+ return 0;
35466
+ }
35467
+ clear(_queue) {
35468
+ throw new Error(
35469
+ "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."
35470
+ );
35471
+ }
35472
+ purge(_queue, _status) {
35473
+ throw new Error(
35474
+ "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."
35475
+ );
35476
+ }
35477
+ /** Stop the worker and release the connection. Idempotent. */
35478
+ close() {
35479
+ if (!this.worker) return;
35480
+ try {
35481
+ this.request({ op: "close" });
35482
+ } catch {
35483
+ }
35484
+ void this.worker.terminate();
35485
+ this.worker = null;
35486
+ this.sab = null;
35487
+ this.header = null;
35488
+ this.outBytes = null;
35489
+ }
35490
+ };
35491
+ }
35492
+ });
35493
+
34596
35494
  // ../core/src/job.ts
34597
35495
  function createJob(data, queue) {
34598
35496
  const job = {
@@ -34645,7 +35543,7 @@ var init_job = __esm({
34645
35543
  // ../core/src/queueBackends/liteBackend.ts
34646
35544
  import { mkdirSync as mkdirSync16, readdirSync as readdirSync12, readFileSync as readFileSync16, writeFileSync as writeFileSync12, unlinkSync as unlinkSync8, existsSync as existsSync20 } from "node:fs";
34647
35545
  import { join as join25 } from "node:path";
34648
- import { randomUUID as randomUUID6 } from "node:crypto";
35546
+ import { randomUUID as randomUUID7 } from "node:crypto";
34649
35547
  var LiteBackend;
34650
35548
  var init_liteBackend = __esm({
34651
35549
  "../core/src/queueBackends/liteBackend.ts"() {
@@ -34712,7 +35610,7 @@ var init_liteBackend = __esm({
34712
35610
  );
34713
35611
  }
34714
35612
  const dir = this.ensureDir(queue);
34715
- const id = randomUUID6();
35613
+ const id = randomUUID7();
34716
35614
  const now = (/* @__PURE__ */ new Date()).toISOString();
34717
35615
  const job = {
34718
35616
  id,
@@ -35268,13 +36166,11 @@ function defaultVisibilityTimeout() {
35268
36166
  return Number.isFinite(parsed) ? parsed : 300;
35269
36167
  }
35270
36168
  function unsupportedBrokerMessage(backendName) {
35271
- const broker = backendName === "kafka" ? "Kafka" : "RabbitMQ";
35272
- 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";
35273
36169
  return `Queue backend "${backendName}" is not available in tina4-nodejs.
35274
36170
 
35275
- 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.
36171
+ 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.
35276
36172
 
35277
- 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}.
36173
+ 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.
35278
36174
 
35279
36175
  Tracking: ADR-0022 in tina4-documentation/plan/v3/DECISIONS.md, findings in plan/v3/features/048-queue-backends.md.`;
35280
36176
  }
@@ -35283,6 +36179,7 @@ var init_queue = __esm({
35283
36179
  "../core/src/queue.ts"() {
35284
36180
  "use strict";
35285
36181
  init_mongoBackend();
36182
+ init_kafkaBackend();
35286
36183
  init_liteBackend();
35287
36184
  init_job();
35288
36185
  init_liteBackend();
@@ -35303,7 +36200,7 @@ var init_queue = __esm({
35303
36200
  * - new Queue("mongodb", { path: "data/queue" }) // legacy
35304
36201
  * - new Queue() // file backend, default topic
35305
36202
  *
35306
- * Throws on backend "rabbitmq" or "kafka" (ADR-0022).
36203
+ * Throws on backend "rabbitmq" (ADR-0022); "kafka" is now supported.
35307
36204
  */
35308
36205
  constructor(backendOrConfig, config) {
35309
36206
  let resolvedConfig = {};
@@ -35321,8 +36218,10 @@ var init_queue = __esm({
35321
36218
  this._retryBackoff = resolvedConfig.retryBackoff ?? 0;
35322
36219
  this._visibilityTimeout = resolvedConfig.visibilityTimeout ?? defaultVisibilityTimeout();
35323
36220
  this.liteBackend = new LiteBackend(this.basePath, this._visibilityTimeout);
35324
- if (this.backendName === "rabbitmq" || this.backendName === "kafka") {
36221
+ if (this.backendName === "rabbitmq") {
35325
36222
  throw new Error(unsupportedBrokerMessage(this.backendName));
36223
+ } else if (this.backendName === "kafka") {
36224
+ this.externalBackend = new KafkaBackend({ visibilityTimeout: this._visibilityTimeout });
35326
36225
  } else if (this.backendName === "mongodb" || this.backendName === "mongo") {
35327
36226
  this.externalBackend = new MongoBackend2({ visibilityTimeout: this._visibilityTimeout });
35328
36227
  } else if (!["file", "default", "lite"].includes(this.backendName)) {
@@ -38390,10 +39289,10 @@ function devGitStatusLabel(code) {
38390
39289
  async function devGitInfo(root) {
38391
39290
  const empty = { branch: "", gitRoot: null, status: /* @__PURE__ */ new Map() };
38392
39291
  try {
38393
- const { execFileSync: execFileSync7 } = await import("node:child_process");
39292
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
38394
39293
  const git = (args) => {
38395
39294
  try {
38396
- return execFileSync7("git", args, { cwd: root, timeout: 3e3, encoding: "utf-8" }).toString();
39295
+ return execFileSync6("git", args, { cwd: root, timeout: 3e3, encoding: "utf-8" }).toString();
38397
39296
  } catch {
38398
39297
  return null;
38399
39298
  }
@@ -40220,9 +41119,9 @@ var init_devAdmin = __esm({
40220
41119
  return;
40221
41120
  }
40222
41121
  try {
40223
- const { execFileSync: execFileSync7 } = await import("node:child_process");
41122
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
40224
41123
  const args = ["install", dev ? "--save-dev" : "--save", pkg];
40225
- const output = execFileSync7("npm", args, {
41124
+ const output = execFileSync6("npm", args, {
40226
41125
  cwd: resolve17(process.cwd()),
40227
41126
  timeout: 12e4,
40228
41127
  encoding: "utf-8"
@@ -40234,15 +41133,15 @@ var init_devAdmin = __esm({
40234
41133
  };
40235
41134
  handleGitStatus = async (_req, res) => {
40236
41135
  try {
40237
- const { execFileSync: execFileSync7 } = await import("node:child_process");
41136
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
40238
41137
  const cwd = resolve17(process.cwd());
40239
41138
  try {
40240
- execFileSync7("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
41139
+ execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
40241
41140
  } catch {
40242
41141
  res.json({ error: "Not a git repository" }, 400);
40243
41142
  return;
40244
41143
  }
40245
- const run = (args) => execFileSync7("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
41144
+ const run = (args) => execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
40246
41145
  res.json({
40247
41146
  branch: run(["branch", "--show-current"]),
40248
41147
  status: run(["status", "--porcelain"]).split(/\r?\n/).filter((l) => l),
@@ -40372,8 +41271,8 @@ var init_devAdmin = __esm({
40372
41271
  return;
40373
41272
  }
40374
41273
  try {
40375
- const { execFileSync: execFileSync7 } = await import("node:child_process");
40376
- const output = execFileSync7("npx", ["tina4nodejs", "generate", kind, name], {
41274
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
41275
+ const output = execFileSync6("npx", ["tina4nodejs", "generate", kind, name], {
40377
41276
  cwd: resolve17(process.cwd()),
40378
41277
  timeout: 3e4,
40379
41278
  encoding: "utf-8"
@@ -40819,6 +41718,359 @@ var init_background = __esm({
40819
41718
  }
40820
41719
  });
40821
41720
 
41721
+ // ../core/src/tcp.ts
41722
+ import { createServer as createServer3 } from "node:net";
41723
+ function resolveMaxBacklog(explicit) {
41724
+ if (explicit !== void 0) return explicit > 0 ? explicit : DEFAULT_MAX_BACKLOG;
41725
+ const raw = (process.env.TINA4_TCP_MAX_BACKLOG ?? "").trim();
41726
+ if (raw === "") return DEFAULT_MAX_BACKLOG;
41727
+ const value = Number.parseInt(raw, 10);
41728
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_BACKLOG;
41729
+ }
41730
+ function tcpService(port, options = {}) {
41731
+ const service = new TcpService(port, options);
41732
+ services.set(service.name, service);
41733
+ return service;
41734
+ }
41735
+ function tcp(name = "default") {
41736
+ const service = services.get(name);
41737
+ if (!service) {
41738
+ const known = services.size === 0 ? "(none registered)" : [...services.keys()].join(", ");
41739
+ throw new Error(`no tcp_service named '${name}' is registered; known services: ${known}`);
41740
+ }
41741
+ return service;
41742
+ }
41743
+ function registeredTcpServices() {
41744
+ return [...services.values()];
41745
+ }
41746
+ function clearTcpRegistry() {
41747
+ services.clear();
41748
+ }
41749
+ async function startAllTcpServices(host = "0.0.0.0") {
41750
+ for (const service of registeredTcpServices()) {
41751
+ try {
41752
+ await service.start(host);
41753
+ } catch (error2) {
41754
+ Log.error(`tcp_service '${service.name}' failed to start: ${String(error2)}`);
41755
+ }
41756
+ }
41757
+ }
41758
+ function stopAcceptingAllTcpServices() {
41759
+ for (const service of registeredTcpServices()) {
41760
+ try {
41761
+ service.stopAccepting();
41762
+ } catch (error2) {
41763
+ Log.error(`tcp_service '${service.name}' stop-accepting failed: ${String(error2)}`);
41764
+ }
41765
+ }
41766
+ }
41767
+ async function drainAllTcpServices() {
41768
+ for (const service of registeredTcpServices()) {
41769
+ try {
41770
+ await service.drain();
41771
+ } catch (error2) {
41772
+ Log.error(`tcp_service '${service.name}' drain failed: ${String(error2)}`);
41773
+ }
41774
+ }
41775
+ }
41776
+ var DEFAULT_MAX_BACKLOG, TcpConnection, TcpService, services;
41777
+ var init_tcp = __esm({
41778
+ "../core/src/tcp.ts"() {
41779
+ "use strict";
41780
+ init_logger();
41781
+ DEFAULT_MAX_BACKLOG = 1 << 20;
41782
+ TcpConnection = class {
41783
+ constructor(socket, service) {
41784
+ this.socket = socket;
41785
+ this.service = service;
41786
+ this.remoteAddr = `${socket.remoteAddress ?? ""}:${socket.remotePort ?? 0}`;
41787
+ }
41788
+ socket;
41789
+ service;
41790
+ /** The registry id (the IMEI), or null until identify() is called. */
41791
+ id = null;
41792
+ /** Per-connection mutable state bag — the app's parse buffer, auth flag. */
41793
+ context = {};
41794
+ /** The raw TCP peer address ("127.0.0.1:54321"), never a forwarded header. */
41795
+ remoteAddr;
41796
+ lastActivity = Date.now();
41797
+ lineBuffer = Buffer.alloc(0);
41798
+ closed = false;
41799
+ closeFired = false;
41800
+ get isClosed() {
41801
+ return this.closed;
41802
+ }
41803
+ /**
41804
+ * Register this live connection under an app-chosen id (the IMEI). A second
41805
+ * connection identifying with the same id SUPERSEDES the first in the
41806
+ * registry — exactly a device that dropped and reconnected.
41807
+ */
41808
+ identify(appId) {
41809
+ this.id = String(appId);
41810
+ this.service._registerId(this.id, this);
41811
+ return this;
41812
+ }
41813
+ /**
41814
+ * Write raw bytes to THIS socket. Returns true when queued/sent, false when
41815
+ * the connection is closed or dropped for backpressure. A stalled reader
41816
+ * (never draining) is bounded: once more than the service's maxBacklog bytes
41817
+ * are outstanding, the connection is dropped rather than buffered without end
41818
+ * (mirrors the WebSocket TINA4_WS_MAX_BACKLOG posture).
41819
+ */
41820
+ send(data) {
41821
+ if (this.closed) return false;
41822
+ const buffer = typeof data === "string" ? Buffer.from(data) : data;
41823
+ this.socket.write(buffer);
41824
+ if (this.socket.writableLength > this.service.maxBacklog) {
41825
+ Log.warning(
41826
+ `tcp_service '${this.service.name}': dropping a stalled reader \u2014 ${this.socket.writableLength} bytes queued exceeds the ${this.service.maxBacklog}-byte backlog limit`
41827
+ );
41828
+ this.close();
41829
+ return false;
41830
+ }
41831
+ return true;
41832
+ }
41833
+ /**
41834
+ * Close this connection. on_close fires exactly once (from the socket's close
41835
+ * event) and the registry entry is removed.
41836
+ */
41837
+ close() {
41838
+ if (this.closed) return;
41839
+ this.closed = true;
41840
+ try {
41841
+ this.socket.end(() => this.socket.destroy());
41842
+ } catch {
41843
+ this.socket.destroy();
41844
+ }
41845
+ }
41846
+ /** @internal mark activity for the idle reaper. */
41847
+ _touch() {
41848
+ this.lastActivity = Date.now();
41849
+ }
41850
+ /** @internal fire on_close exactly once (called from the service removal path). */
41851
+ _fireClose() {
41852
+ if (this.closeFired) return;
41853
+ this.closeFired = true;
41854
+ this.closed = true;
41855
+ const handler = this.service._callbacks.onClose;
41856
+ if (!handler) return;
41857
+ try {
41858
+ void Promise.resolve(handler(this)).catch((error2) => {
41859
+ Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error2)}`);
41860
+ });
41861
+ } catch (error2) {
41862
+ Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error2)}`);
41863
+ }
41864
+ }
41865
+ };
41866
+ TcpService = class {
41867
+ name;
41868
+ port;
41869
+ maxBacklog;
41870
+ /** @internal the callback bag, read by TcpConnection. */
41871
+ _callbacks;
41872
+ idleTimeout;
41873
+ maxConnections;
41874
+ connections = /* @__PURE__ */ new Set();
41875
+ byId = /* @__PURE__ */ new Map();
41876
+ server = null;
41877
+ owner = false;
41878
+ boundPortValue = null;
41879
+ reaper = null;
41880
+ constructor(port, options = {}) {
41881
+ this.port = port;
41882
+ this.name = options.name ?? "default";
41883
+ this._callbacks = {
41884
+ onConnect: options.onConnect,
41885
+ onData: options.onData,
41886
+ onClose: options.onClose,
41887
+ onLine: options.onLine
41888
+ };
41889
+ this.idleTimeout = options.idleTimeout ?? 0;
41890
+ this.maxConnections = options.maxConnections ?? null;
41891
+ this.maxBacklog = resolveMaxBacklog(options.maxBacklog);
41892
+ }
41893
+ get isOwner() {
41894
+ return this.owner;
41895
+ }
41896
+ /** The port actually bound (resolves an ephemeral port=0 to the real one). */
41897
+ get boundPort() {
41898
+ return this.boundPortValue ?? this.port;
41899
+ }
41900
+ count() {
41901
+ return this.connections.size;
41902
+ }
41903
+ // ── Registry (D4 — server -> device push) ──────────────────────────────────
41904
+ /** @internal */
41905
+ _registerId(appId, conn) {
41906
+ this.byId.set(appId, conn);
41907
+ }
41908
+ /** The live connection for an app id, or null if unknown or closed. */
41909
+ connection(appId) {
41910
+ const conn = this.byId.get(String(appId));
41911
+ if (!conn || conn.isClosed) return null;
41912
+ return conn;
41913
+ }
41914
+ /**
41915
+ * Write bytes to exactly the connection identified by appId. A send to an
41916
+ * unknown or closed id is a NO-OP that returns false — never a throw.
41917
+ */
41918
+ sendTo(appId, data) {
41919
+ const conn = this.connection(appId);
41920
+ if (!conn) return false;
41921
+ return conn.send(data);
41922
+ }
41923
+ /** Write bytes to every live connection. Returns how many received it. */
41924
+ broadcast(data) {
41925
+ let delivered = 0;
41926
+ for (const conn of [...this.connections]) {
41927
+ if (conn.send(data)) delivered += 1;
41928
+ }
41929
+ return delivered;
41930
+ }
41931
+ // ── Lifecycle ───────────────────────────────────────────────────────────────
41932
+ /**
41933
+ * Bind the listener on host:port on the event loop. SO_REUSEPORT is OFF, so
41934
+ * under a multi-worker deployment exactly ONE worker wins the bind; a worker
41935
+ * that finds the port already bound skips silently (single-owner, D1).
41936
+ * Resolves true when THIS call bound the port.
41937
+ */
41938
+ start(host = "0.0.0.0") {
41939
+ if (this.server) return Promise.resolve(this.owner);
41940
+ return new Promise((resolve29) => {
41941
+ const server = createServer3((socket) => this.handleConnection(socket));
41942
+ this.server = server;
41943
+ const onError = (error2) => {
41944
+ if (error2.code === "EADDRINUSE" || error2.code === "EADDRNOTAVAIL") {
41945
+ this.owner = false;
41946
+ this.server = null;
41947
+ Log.info(
41948
+ `tcp_service '${this.name}' port ${this.port} is already bound by another worker \u2014 single-owner, this worker will not bind (${error2.code})`
41949
+ );
41950
+ resolve29(false);
41951
+ return;
41952
+ }
41953
+ Log.error(`tcp_service '${this.name}' failed to start: ${error2.message}`);
41954
+ this.server = null;
41955
+ resolve29(false);
41956
+ };
41957
+ server.once("error", onError);
41958
+ server.listen(this.port, host, () => {
41959
+ server.off("error", onError);
41960
+ server.on("error", (error2) => Log.error(`tcp_service '${this.name}' error: ${String(error2)}`));
41961
+ this.owner = true;
41962
+ const addr = server.address();
41963
+ this.boundPortValue = typeof addr === "object" && addr ? addr.port : this.port;
41964
+ Log.info(`tcp_service '${this.name}' listening on ${host}:${this.boundPortValue}`);
41965
+ this.startReaper();
41966
+ resolve29(true);
41967
+ });
41968
+ });
41969
+ }
41970
+ handleConnection(socket) {
41971
+ if (this.maxConnections !== null && this.connections.size >= this.maxConnections) {
41972
+ socket.destroy();
41973
+ return;
41974
+ }
41975
+ const conn = new TcpConnection(socket, this);
41976
+ this.connections.add(conn);
41977
+ socket.on("data", (chunk) => {
41978
+ socket.pause();
41979
+ void this.dispatch(conn, chunk).finally(() => {
41980
+ if (!conn.isClosed) socket.resume();
41981
+ });
41982
+ });
41983
+ socket.on("close", () => this.remove(conn));
41984
+ socket.on("error", () => {
41985
+ });
41986
+ const onConnect = this._callbacks.onConnect;
41987
+ if (onConnect) {
41988
+ void Promise.resolve(onConnect(conn)).catch((error2) => {
41989
+ Log.error(`tcp_service '${this.name}' onConnect error: ${String(error2)}`);
41990
+ });
41991
+ }
41992
+ }
41993
+ async dispatch(conn, chunk) {
41994
+ conn._touch();
41995
+ const { onData, onLine } = this._callbacks;
41996
+ if (onData) {
41997
+ try {
41998
+ await onData(conn, chunk);
41999
+ } catch (error2) {
42000
+ Log.error(`tcp_service '${this.name}' onData error: ${String(error2)}`);
42001
+ }
42002
+ }
42003
+ if (onLine) {
42004
+ conn.lineBuffer = Buffer.concat([conn.lineBuffer, chunk]);
42005
+ let newline = conn.lineBuffer.indexOf(10);
42006
+ while (newline !== -1) {
42007
+ let line = conn.lineBuffer.subarray(0, newline);
42008
+ conn.lineBuffer = conn.lineBuffer.subarray(newline + 1);
42009
+ if (line.length > 0 && line[line.length - 1] === 13) {
42010
+ line = line.subarray(0, line.length - 1);
42011
+ }
42012
+ try {
42013
+ await onLine(conn, line);
42014
+ } catch (error2) {
42015
+ Log.error(`tcp_service '${this.name}' onLine error: ${String(error2)}`);
42016
+ }
42017
+ newline = conn.lineBuffer.indexOf(10);
42018
+ }
42019
+ }
42020
+ }
42021
+ /** @internal remove a connection and fire on_close exactly once. */
42022
+ remove(conn) {
42023
+ const existed = this.connections.delete(conn);
42024
+ if (conn.id !== null && this.byId.get(conn.id) === conn) {
42025
+ this.byId.delete(conn.id);
42026
+ }
42027
+ if (existed) conn._fireClose();
42028
+ }
42029
+ // ── Idle reaper (D1 consumer shape — default OFF) ───────────────────────────
42030
+ startReaper() {
42031
+ if (this.idleTimeout <= 0 || this.reaper) return;
42032
+ const intervalMs = Math.max(50, Math.min(1e3, this.idleTimeout / 2 * 1e3));
42033
+ this.reaper = setInterval(() => this.reapIdle(), intervalMs);
42034
+ this.reaper.unref();
42035
+ }
42036
+ reapIdle() {
42037
+ const now = Date.now();
42038
+ const limitMs = this.idleTimeout * 1e3;
42039
+ for (const conn of [...this.connections]) {
42040
+ if (now - conn.lastActivity >= limitMs) conn.close();
42041
+ }
42042
+ }
42043
+ /** Stop accepting new connections (close the listener). Live conns stay. */
42044
+ stopAccepting() {
42045
+ if (this.reaper) {
42046
+ clearInterval(this.reaper);
42047
+ this.reaper = null;
42048
+ }
42049
+ if (this.server && this.owner) {
42050
+ this.server.close();
42051
+ }
42052
+ }
42053
+ /** Close every live connection (firing on_close) and release the listener. */
42054
+ async drain() {
42055
+ this.stopAccepting();
42056
+ for (const conn of [...this.connections]) conn.close();
42057
+ if (this.server) {
42058
+ await new Promise((resolve29) => {
42059
+ this.server.close(() => resolve29());
42060
+ this.server.unref();
42061
+ }).catch(() => void 0);
42062
+ this.server = null;
42063
+ }
42064
+ }
42065
+ /** Stop accepting and drain in one call (used by direct callers/tests). */
42066
+ async stop() {
42067
+ await this.drain();
42068
+ }
42069
+ };
42070
+ services = /* @__PURE__ */ new Map();
42071
+ }
42072
+ });
42073
+
40822
42074
  // ../core/src/events.ts
40823
42075
  var events_exports = {};
40824
42076
  __export(events_exports, {
@@ -43027,7 +44279,7 @@ async function startServer(config) {
43027
44279
  server.on("upgrade", (req2, socket, head) => {
43028
44280
  const upPath = (req2.url ?? "/").split("?")[0];
43029
44281
  if (isDevMode() && upPath === "/__dev_reload") {
43030
- if (!devHostAllowed(req2.headers.host)) {
44282
+ if (!devHostAllowed(req2.headers.host) || !devPeerAllowed(socket.remoteAddress)) {
43031
44283
  try {
43032
44284
  socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
43033
44285
  socket.destroy();
@@ -43051,6 +44303,7 @@ async function startServer(config) {
43051
44303
  server.listen(port, host, async () => {
43052
44304
  if (!cluster.isWorker) writePidfile(port);
43053
44305
  const siblingServers = await startLoopbackSiblings(port, host, dispatch);
44306
+ await startAllTcpServices(host);
43054
44307
  const displayHost = host === "0.0.0.0" ? "localhost" : host;
43055
44308
  const isDebug = isTruthy(process.env.TINA4_DEBUG);
43056
44309
  const logLevel = (process.env.TINA4_LOG_LEVEL ?? "DEBUG").toUpperCase();
@@ -43141,6 +44394,8 @@ ${reset2}
43141
44394
  if (wsClosed > 0) {
43142
44395
  Log.info(`Closed ${wsClosed} WebSocket connection(s) with 1001 going away`);
43143
44396
  }
44397
+ stopAcceptingAllTcpServices();
44398
+ await drainAllTcpServices();
43144
44399
  const budgetSeconds = shutdownTimeoutSeconds();
43145
44400
  let timer;
43146
44401
  const outcome = await Promise.race([
@@ -43183,6 +44438,8 @@ ${reset2}
43183
44438
  process.off("SIGTERM", onSigterm);
43184
44439
  process.off("SIGINT", onSigint);
43185
44440
  stopAllBackgroundTasks();
44441
+ stopAcceptingAllTcpServices();
44442
+ void drainAllTcpServices();
43186
44443
  if (aiServer) aiServer.close();
43187
44444
  server.close();
43188
44445
  for (const sibling of siblingServers) {
@@ -43311,6 +44568,7 @@ var init_server = __esm({
43311
44568
  init_feedback();
43312
44569
  init_i18n();
43313
44570
  init_background();
44571
+ init_tcp();
43314
44572
  init_version();
43315
44573
  __filename = fileURLToPath9(import.meta.url);
43316
44574
  __dirname = dirname16(__filename);
@@ -45669,7 +46927,7 @@ import net4 from "node:net";
45669
46927
  import tls2 from "node:tls";
45670
46928
  import { readFileSync as readFileSync25 } from "node:fs";
45671
46929
  import { basename as basename8 } from "node:path";
45672
- import { randomUUID as randomUUID7 } from "node:crypto";
46930
+ import { randomUUID as randomUUID8 } from "node:crypto";
45673
46931
  function normaliseEncryption(value, kind) {
45674
46932
  const normalised = value.trim().toLowerCase();
45675
46933
  if (!MAIL_ENCRYPTION_VALUES.includes(normalised)) {
@@ -46301,7 +47559,7 @@ var init_messenger = __esm({
46301
47559
  );
46302
47560
  }
46303
47561
  const recipients = this.prepareRecipients(options, true);
46304
- const messageId = `${randomUUID7()}@${this.host}`;
47562
+ const messageId = `${randomUUID8()}@${this.host}`;
46305
47563
  if (recipients.allRecipients.length === 0) {
46306
47564
  return { success: false, message: "No recipients specified", id: null };
46307
47565
  }
@@ -49161,7 +50419,7 @@ var init_aiClient = __esm({
49161
50419
 
49162
50420
  // ../core/src/queueBackends/rabbitmqBackend.ts
49163
50421
  import { execFileSync as execFileSync5 } from "node:child_process";
49164
- import { randomUUID as randomUUID8 } from "node:crypto";
50422
+ import { randomUUID as randomUUID9 } from "node:crypto";
49165
50423
  function parseAmqpUrl(url) {
49166
50424
  const config = {};
49167
50425
  let rest = url.replace(/^amqps:\/\//, "").replace(/^amqp:\/\//, "");
@@ -49597,7 +50855,7 @@ var init_rabbitmqBackend = __esm({
49597
50855
  "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."
49598
50856
  );
49599
50857
  }
49600
- const id = randomUUID8();
50858
+ const id = randomUUID9();
49601
50859
  const now = (/* @__PURE__ */ new Date()).toISOString();
49602
50860
  const job = {
49603
50861
  id,
@@ -49641,586 +50899,6 @@ var init_rabbitmqBackend = __esm({
49641
50899
  }
49642
50900
  });
49643
50901
 
49644
- // ../core/src/queueBackends/kafkaBackend.ts
49645
- import { execFileSync as execFileSync6 } from "node:child_process";
49646
- import { randomUUID as randomUUID9 } from "node:crypto";
49647
- function kafkaSecurityConfig(env = process.env) {
49648
- const mapping = [
49649
- ["security.protocol", "SECURITY_PROTOCOL"],
49650
- ["ssl.ca.location", "SSL_CA_LOCATION"],
49651
- ["sasl.mechanism", "SASL_MECHANISM"],
49652
- ["sasl.username", "SASL_USERNAME"],
49653
- ["sasl.password", "SASL_PASSWORD"]
49654
- ];
49655
- const config = {};
49656
- for (const [rdk, suffix] of mapping) {
49657
- const value = env[`TINA4_KAFKA_${suffix}`] || env[`KAFKA_${suffix}`];
49658
- if (value) {
49659
- config[rdk] = value;
49660
- }
49661
- }
49662
- return config;
49663
- }
49664
- function kafkaOffsetReset(env = process.env) {
49665
- return env.TINA4_KAFKA_AUTO_OFFSET_RESET || env.KAFKA_AUTO_OFFSET_RESET || "earliest";
49666
- }
49667
- var API_PRODUCE, API_FETCH, KafkaBackend;
49668
- var init_kafkaBackend = __esm({
49669
- "../core/src/queueBackends/kafkaBackend.ts"() {
49670
- "use strict";
49671
- API_PRODUCE = 0;
49672
- API_FETCH = 1;
49673
- KafkaBackend = class _KafkaBackend {
49674
- brokers;
49675
- groupId;
49676
- constructor(config) {
49677
- const url = process.env.TINA4_QUEUE_URL;
49678
- const fromUrl = url ? url.replace(/^kafka:\/\//, "") : void 0;
49679
- this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
49680
- this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
49681
- }
49682
- /**
49683
- * Resolved connection config — exposed for testing/introspection.
49684
- */
49685
- getConfig() {
49686
- return { brokers: this.brokers, groupId: this.groupId };
49687
- }
49688
- /**
49689
- * Resolved SSL/SASL client config from the environment (PLAINTEXT default).
49690
- * Mirrors Python's `KafkaConnector._security_config`.
49691
- */
49692
- securityConfig() {
49693
- return kafkaSecurityConfig();
49694
- }
49695
- /**
49696
- * Full producer config — brokers + client id + the resolved security block.
49697
- * The security keys are applied to BOTH producer and consumer (matching
49698
- * Python's `_connect_confluent`).
49699
- */
49700
- producerConfig() {
49701
- return {
49702
- "bootstrap.servers": this.brokers,
49703
- "client.id": "tina4-nodejs",
49704
- ...this.securityConfig()
49705
- };
49706
- }
49707
- /**
49708
- * Full consumer config — brokers + client id + group id + the SAME resolved
49709
- * security block applied to the producer.
49710
- */
49711
- consumerConfig() {
49712
- return {
49713
- "bootstrap.servers": this.brokers,
49714
- "client.id": "tina4-nodejs",
49715
- "group.id": this.groupId,
49716
- "auto.offset.reset": kafkaOffsetReset(),
49717
- "enable.auto.commit": false,
49718
- ...this.securityConfig()
49719
- };
49720
- }
49721
- /**
49722
- * Parse broker string into host:port.
49723
- */
49724
- parseBroker() {
49725
- const parts = this.brokers.split(",")[0].trim().split(":");
49726
- return {
49727
- host: parts[0] ?? "localhost",
49728
- port: parts[1] ? parseInt(parts[1], 10) : 9092
49729
- };
49730
- }
49731
- /**
49732
- * Execute a Kafka operation synchronously via a child process.
49733
- *
49734
- * The wire protocol is hand-rolled (Tina4 is zero-dependency — no npm Kafka
49735
- * library). Produce uses Produce **v3** carrying a Kafka **v2 RecordBatch**
49736
- * (magic byte 2) with a **CRC-32C** (Castagnoli) checksum; Fetch uses Fetch
49737
- * **v4** and parses the v2 RecordBatch out of the response. Both formats are
49738
- * what a modern KRaft broker (apache/kafka 3.7.0) requires — the old
49739
- * Produce-v0 / message-format-v0 / CRC=0 batch is rejected by such brokers.
49740
- */
49741
- execSync(operation, topic, data) {
49742
- const broker = this.parseBroker();
49743
- const script = `
49744
- const net = require("node:net");
49745
- const host = ${JSON.stringify(broker.host)};
49746
- const port = ${broker.port};
49747
- const operation = ${JSON.stringify(operation)};
49748
- const topic = ${JSON.stringify(topic)};
49749
- const groupId = ${JSON.stringify(this.groupId)};
49750
- const data = ${JSON.stringify(data ?? "")};
49751
- const API_PRODUCE = ${API_PRODUCE};
49752
- const API_FETCH = ${API_FETCH};
49753
- const PRODUCE_VERSION = 3; // v3+ requires the v2 RecordBatch format
49754
- const FETCH_VERSION = 4; // v4 returns v2 RecordBatches + isolation_level
49755
- let correlationId = 0;
49756
-
49757
- // \u2500\u2500 CRC-32C (Castagnoli, polynomial 0x1EDC6F41), table-based \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
49758
- // Node has no built-in CRC-32C; the v2 RecordBatch mandates it over the
49759
- // bytes from \`attributes\` to the end of the batch. A wrong CRC makes the
49760
- // broker drop the connection, so this must be exact.
49761
- const CRC32C_TABLE = (() => {
49762
- const table = new Uint32Array(256);
49763
- for (let n = 0; n < 256; n++) {
49764
- let c = n;
49765
- for (let k = 0; k < 8; k++) {
49766
- c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
49767
- }
49768
- table[n] = c >>> 0;
49769
- }
49770
- return table;
49771
- })();
49772
- function crc32c(buf) {
49773
- let crc = 0xffffffff;
49774
- for (let i = 0; i < buf.length; i++) {
49775
- crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
49776
- }
49777
- return (crc ^ 0xffffffff) >>> 0;
49778
- }
49779
-
49780
- // \u2500\u2500 Kafka protocol varints (zigzag-encoded signed varints) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
49781
- function encodeZigZag(n) {
49782
- // 32-bit zigzag: (n << 1) ^ (n >> 31)
49783
- return ((n << 1) ^ (n >> 31)) >>> 0;
49784
- }
49785
- function encodeVarintUnsigned(u) {
49786
- const bytes = [];
49787
- let v = u >>> 0;
49788
- while (true) {
49789
- if ((v & ~0x7f) === 0) { bytes.push(v); break; }
49790
- bytes.push((v & 0x7f) | 0x80);
49791
- v >>>= 7;
49792
- }
49793
- return Buffer.from(bytes);
49794
- }
49795
- function encodeVarint(n) {
49796
- // signed varint = zigzag then unsigned-varint
49797
- return encodeVarintUnsigned(encodeZigZag(n));
49798
- }
49799
- function decodeVarint(buf, pos) {
49800
- // returns { value, next } \u2014 signed (zigzag-decoded)
49801
- let result = 0, shift = 0, b;
49802
- do {
49803
- b = buf[pos++];
49804
- result |= (b & 0x7f) << shift;
49805
- shift += 7;
49806
- } while (b & 0x80);
49807
- result = result >>> 0;
49808
- // zigzag decode
49809
- const value = (result >>> 1) ^ -(result & 1);
49810
- return { value, next: pos };
49811
- }
49812
-
49813
- // \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
49814
- function buildRecordBatch(valueBytes) {
49815
- const now = BigInt(Date.now());
49816
-
49817
- // Build the single record body.
49818
- // record = attributes:int8(0), timestampDelta:varint(0),
49819
- // offsetDelta:varint(0), keyLen:varint(-1 null),
49820
- // valueLen:varint(len), value, headerCount:varint(0)
49821
- const recBody = Buffer.concat([
49822
- Buffer.from([0]), // attributes (int8)
49823
- encodeVarint(0), // timestampDelta
49824
- encodeVarint(0), // offsetDelta
49825
- encodeVarint(-1), // keyLen (-1 = null key)
49826
- encodeVarint(valueBytes.length), // valueLen
49827
- valueBytes, // value (JSON payload bytes)
49828
- encodeVarint(0), // headerCount
49829
- ]);
49830
- // record length prefix = signed varint of recBody length
49831
- const record = Buffer.concat([encodeVarint(recBody.length), recBody]);
49832
- const recordsCount = 1;
49833
-
49834
- // The portion the CRC covers starts at \`attributes\` and runs to end.
49835
- // crcBody = attributes:int16(0), lastOffsetDelta:int32(count-1),
49836
- // firstTimestamp:int64, maxTimestamp:int64,
49837
- // producerId:int64(-1), producerEpoch:int16(-1),
49838
- // baseSequence:int32(-1), recordsCount:int32, records
49839
- const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
49840
- let c = 0;
49841
- crcBody.writeInt16BE(0, c); c += 2; // attributes
49842
- crcBody.writeInt32BE(recordsCount - 1, c); c += 4; // lastOffsetDelta
49843
- crcBody.writeBigInt64BE(now, c); c += 8; // firstTimestamp
49844
- crcBody.writeBigInt64BE(now, c); c += 8; // maxTimestamp
49845
- crcBody.writeBigInt64BE(-1n, c); c += 8; // producerId
49846
- crcBody.writeInt16BE(-1, c); c += 2; // producerEpoch
49847
- crcBody.writeInt32BE(-1, c); c += 4; // baseSequence
49848
- crcBody.writeInt32BE(recordsCount, c); c += 4; // recordsCount
49849
- record.copy(crcBody, c);
49850
-
49851
- const crc = crc32c(crcBody);
49852
-
49853
- // Header before the CRC-covered region:
49854
- // baseOffset:int64(0), batchLength:int32, partitionLeaderEpoch:int32(-1),
49855
- // magic:int8(2), crc:uint32. batchLength counts everything AFTER itself
49856
- // (partitionLeaderEpoch through end of records) = 4 + 1 + 4 + crcBody.
49857
- const batchLength = 4 + 1 + 4 + crcBody.length;
49858
- const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
49859
- let h = 0;
49860
- head.writeBigInt64BE(0n, h); h += 8; // baseOffset
49861
- head.writeInt32BE(batchLength, h); h += 4; // batchLength
49862
- head.writeInt32BE(-1, h); h += 4; // partitionLeaderEpoch
49863
- head.writeInt8(2, h); h += 1; // magic = 2
49864
- head.writeUInt32BE(crc, h); h += 4; // crc (CRC-32C)
49865
-
49866
- return Buffer.concat([head, crcBody]);
49867
- }
49868
-
49869
- // \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
49870
- function buildProduceRequest(topicName, valueBytes) {
49871
- correlationId++;
49872
- const clientBuf = Buffer.from("tina4", "utf-8");
49873
- const topicBuf = Buffer.from(topicName, "utf-8");
49874
- const recordBatch = buildRecordBatch(valueBytes);
49875
-
49876
- const body = Buffer.alloc(
49877
- 2 + // transactionalId (-1 null nullable_string)
49878
- 2 + // acks
49879
- 4 + // timeoutMs
49880
- 4 + // topics array count
49881
- 2 + topicBuf.length + // topic name
49882
- 4 + // partitions array count
49883
- 4 + // partition index
49884
- 4 + recordBatch.length // recordSetBytes (int32 size) + batch
49885
- );
49886
- let p = 0;
49887
- body.writeInt16BE(-1, p); p += 2; // transactionalId = null
49888
- body.writeInt16BE(1, p); p += 2; // acks = 1
49889
- body.writeInt32BE(10000, p); p += 4; // timeoutMs
49890
- body.writeInt32BE(1, p); p += 4; // topics count
49891
- body.writeInt16BE(topicBuf.length, p); p += 2;
49892
- topicBuf.copy(body, p); p += topicBuf.length;
49893
- body.writeInt32BE(1, p); p += 4; // partitions count
49894
- body.writeInt32BE(0, p); p += 4; // partition index 0
49895
- body.writeInt32BE(recordBatch.length, p); p += 4; // recordSetBytes size
49896
- recordBatch.copy(body, p);
49897
-
49898
- return frameRequest(API_PRODUCE, PRODUCE_VERSION, clientBuf, body);
49899
- }
49900
-
49901
- // \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
49902
- function buildFetchRequest(topicName, fetchOffset) {
49903
- correlationId++;
49904
- const clientBuf = Buffer.from("tina4", "utf-8");
49905
- const topicBuf = Buffer.from(topicName, "utf-8");
49906
-
49907
- // Fetch v4 request body (NO logStartOffset \u2014 that arrives in v5+):
49908
- // replicaId(4), maxWaitMs(4), minBytes(4), maxBytes(4 v3+),
49909
- // isolationLevel(1 v4+), topics[count]: name, partitions[count]:
49910
- // partition(4), fetchOffset(8), partitionMaxBytes(4).
49911
- const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + (2 + topicBuf.length) + 4 + 4 + 8 + 4);
49912
- let p = 0;
49913
- buf.writeInt32BE(-1, p); p += 4; // replicaId (-1 consumer)
49914
- buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
49915
- buf.writeInt32BE(1, p); p += 4; // minBytes
49916
- buf.writeInt32BE(1048576, p); p += 4; // maxBytes
49917
- buf.writeInt8(0, p); p += 1; // isolationLevel = READ_UNCOMMITTED
49918
- buf.writeInt32BE(1, p); p += 4; // topics count
49919
- buf.writeInt16BE(topicBuf.length, p); p += 2;
49920
- topicBuf.copy(buf, p); p += topicBuf.length;
49921
- buf.writeInt32BE(1, p); p += 4; // partitions count
49922
- buf.writeInt32BE(0, p); p += 4; // partition 0
49923
- buf.writeBigInt64BE(BigInt(fetchOffset), p); p += 8; // fetchOffset
49924
- buf.writeInt32BE(1048576, p); p += 4; // partitionMaxBytes
49925
-
49926
- return frameRequest(API_FETCH, FETCH_VERSION, clientBuf, buf);
49927
- }
49928
-
49929
- // Frame a request with header v1: apiKey, apiVersion, correlationId,
49930
- // clientId (nullable string) + body.
49931
- function frameRequest(apiKey, apiVersion, clientBuf, body) {
49932
- const header = Buffer.alloc(2 + 2 + 4 + 2 + clientBuf.length);
49933
- let p = 0;
49934
- header.writeInt16BE(apiKey, p); p += 2;
49935
- header.writeInt16BE(apiVersion, p); p += 2;
49936
- header.writeInt32BE(correlationId, p); p += 4;
49937
- header.writeInt16BE(clientBuf.length, p); p += 2;
49938
- clientBuf.copy(header, p);
49939
- const payload = Buffer.concat([header, body]);
49940
- const framed = Buffer.alloc(4 + payload.length);
49941
- framed.writeInt32BE(payload.length, 0);
49942
- payload.copy(framed, 4);
49943
- return framed;
49944
- }
49945
-
49946
- // \u2500\u2500 Parse a v2 RecordBatch region, return the FIRST record value \u2500\u2500\u2500\u2500\u2500\u2500\u2500
49947
- // \`buf\` is the whole fetch response; [start, end) bounds the partition's
49948
- // record-set bytes (may contain one or more concatenated batches).
49949
- function firstRecordValue(buf, start, end) {
49950
- let pos = start;
49951
- while (pos + 12 <= end) {
49952
- // baseOffset(8) + batchLength(4) then batchLength bytes follow.
49953
- const batchLength = buf.readInt32BE(pos + 8);
49954
- const batchStart = pos + 12; // first byte of partitionLeaderEpoch
49955
- const batchEnd = batchStart + batchLength;
49956
- if (batchLength <= 0 || batchEnd > end) break;
49957
- // partitionLeaderEpoch(4), magic(1), crc(4), attributes(2),
49958
- // lastOffsetDelta(4), firstTimestamp(8), maxTimestamp(8),
49959
- // producerId(8), producerEpoch(2), baseSequence(4), recordsCount(4)
49960
- const magic = buf.readInt8(batchStart + 4);
49961
- if (magic !== 2) { pos = batchEnd; continue; }
49962
- let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
49963
- const recordsCount = buf.readInt32BE(r); r += 4;
49964
- for (let i = 0; i < recordsCount && r < batchEnd; i++) {
49965
- const recLen = decodeVarint(buf, r); // record length (signed varint)
49966
- let rp = recLen.next;
49967
- const recordEnd = rp + recLen.value;
49968
- rp += 1; // attributes (int8)
49969
- const tsDelta = decodeVarint(buf, rp); rp = tsDelta.next;
49970
- const offDelta = decodeVarint(buf, rp); rp = offDelta.next;
49971
- const keyLen = decodeVarint(buf, rp); rp = keyLen.next;
49972
- if (keyLen.value >= 0) rp += keyLen.value;
49973
- const valLen = decodeVarint(buf, rp); rp = valLen.next;
49974
- if (valLen.value >= 0) {
49975
- return buf.subarray(rp, rp + valLen.value).toString("utf-8");
49976
- }
49977
- r = recordEnd;
49978
- }
49979
- pos = batchEnd;
49980
- }
49981
- return null;
49982
- }
49983
-
49984
- let finished = false;
49985
- function finish(out, code) {
49986
- if (finished) return;
49987
- finished = true;
49988
- clearTimeout(timer);
49989
- try { sock.destroy(); } catch (e) { /* ignore */ }
49990
- if (out) process.stdout.write(out);
49991
- // Flush stdout before exiting so execFileSync captures it.
49992
- process.stdout.write("", () => process.exit(code));
49993
- }
49994
-
49995
- const sock = net.createConnection({ host, port }, () => {
49996
- if (operation === "publish") {
49997
- const req = buildProduceRequest(topic, Buffer.from(data, "utf-8"));
49998
- sock.write(req);
49999
- } else if (operation === "get") {
50000
- sock.write(buildFetchRequest(topic, 0));
50001
- } else {
50002
- finish("__UNSUPPORTED__", 0);
50003
- }
50004
- });
50005
-
50006
- let buffer = Buffer.alloc(0);
50007
- sock.on("data", (chunk) => {
50008
- buffer = Buffer.concat([buffer, chunk]);
50009
- if (buffer.length < 4) return;
50010
- const respSize = buffer.readInt32BE(0);
50011
- if (buffer.length < 4 + respSize) return;
50012
-
50013
- if (operation === "publish") {
50014
- // Produce v3 response (after the 4-byte frame size): correlationId(4),
50015
- // topics[count]: name, partitions[count]: partition(4), errorCode(2),
50016
- // baseOffset(8), logAppendTime(8); then throttleTimeMs(4) at the END.
50017
- // Only the per-partition error code matters here.
50018
- try {
50019
- let pos = 4 + 4; // skip frame size + correlationId
50020
- const topicCount = buffer.readInt32BE(pos); pos += 4;
50021
- let errCode = 0;
50022
- for (let t = 0; t < topicCount; t++) {
50023
- const tl = buffer.readInt16BE(pos); pos += 2 + tl;
50024
- const pc = buffer.readInt32BE(pos); pos += 4;
50025
- for (let pi = 0; pi < pc; pi++) {
50026
- pos += 4; // partition index
50027
- errCode = buffer.readInt16BE(pos); pos += 2; // error code
50028
- pos += 8; // baseOffset
50029
- pos += 8; // logAppendTime (v2+)
50030
- }
50031
- }
50032
- if (errCode === 0) {
50033
- finish("__PUBLISHED__", 0);
50034
- } else {
50035
- // Report the CODE, not just "it failed" \u2014 the caller decides
50036
- // whether it is retriable (3/5, the async topic-creation race)
50037
- // or fatal (e.g. 29 TOPIC_AUTHORIZATION_FAILED).
50038
- process.stderr.write("Produce error code " + errCode);
50039
- finish("__PRODUCEERROR__" + errCode, 0);
50040
- }
50041
- } catch (e) {
50042
- process.stderr.write("produce parse: " + e.message);
50043
- finish("__PARSEERROR__produce: " + e.message, 0);
50044
- }
50045
- return;
50046
- } else if (operation === "get") {
50047
- // Fetch v4 response (after the 4-byte frame size): correlationId(4),
50048
- // throttleTimeMs(4), topics[count]: name, partitions[count]:
50049
- // partition(4), errorCode(2), highWatermark(8), lastStableOffset(8),
50050
- // abortedTxns[count](producerId(8)+firstOffset(8)),
50051
- // recordSetBytes(int32)+batch.
50052
- try {
50053
- let pos = 4 + 4; // frame size + correlationId
50054
- pos += 4; // throttleTimeMs (v1+)
50055
- const topicCount = buffer.readInt32BE(pos); pos += 4;
50056
- let out = "__EMPTY__";
50057
- let fatalCode = 0;
50058
- for (let t = 0; t < topicCount; t++) {
50059
- const tl = buffer.readInt16BE(pos); pos += 2 + tl;
50060
- const pc = buffer.readInt32BE(pos); pos += 4;
50061
- for (let pi = 0; pi < pc; pi++) {
50062
- pos += 4; // partition index
50063
- const errCode = buffer.readInt16BE(pos); pos += 2;
50064
- pos += 8; // highWatermark
50065
- pos += 8; // lastStableOffset (v4+)
50066
- const abortedCount = buffer.readInt32BE(pos); pos += 4;
50067
- if (abortedCount > 0) pos += abortedCount * 16; // (-1 => none, skip)
50068
- const recSetSize = buffer.readInt32BE(pos); pos += 4;
50069
- // 3 = UNKNOWN_TOPIC_OR_PARTITION, 5 = LEADER_NOT_AVAILABLE:
50070
- // "nothing to read here yet", which a consumer that starts
50071
- // before its producer hits on every cold start. Any OTHER code
50072
- // (29 TOPIC_AUTHORIZATION_FAILED, 13 STALE_CONTROLLER_EPOCH, \u2026)
50073
- // is a real failure and must NOT be reported as an empty queue.
50074
- if (errCode !== 0 && errCode !== 3 && errCode !== 5) {
50075
- fatalCode = errCode;
50076
- }
50077
- if (errCode === 0 && recSetSize > 0) {
50078
- const val = firstRecordValue(buffer, pos, pos + recSetSize);
50079
- if (val !== null) out = val;
50080
- }
50081
- pos += recSetSize > 0 ? recSetSize : 0;
50082
- }
50083
- }
50084
- if (fatalCode !== 0) {
50085
- process.stderr.write("Fetch error code " + fatalCode);
50086
- finish("__FETCHERROR__" + fatalCode, 0);
50087
- return;
50088
- }
50089
- finish(out, 0);
50090
- } catch (e) {
50091
- // A parse failure is NOT an empty queue either \u2014 say so.
50092
- process.stderr.write("fetch parse: " + e.message);
50093
- finish("__PARSEERROR__fetch: " + e.message, 0);
50094
- }
50095
- return;
50096
- }
50097
- });
50098
-
50099
- // Report the reason on STDOUT and exit 0. Writing it to stderr and
50100
- // exiting non-zero LOST it: stderr to a pipe is an async write and
50101
- // process.exit() truncates it, so the parent saw an empty stderr and fell
50102
- // back to execFileSync's message -- which embeds this entire script.
50103
- // stdout is flushed by finish()'s write callback, so it survives.
50104
- sock.on("error", (err) => {
50105
- finish("__TRANSPORTERROR__" + err.message, 0);
50106
- });
50107
-
50108
- var timer = setTimeout(() => {
50109
- finish("__TRANSPORTERROR__timed out after 10s talking to " + host + ":" + port, 0);
50110
- }, 10000);
50111
- `;
50112
- try {
50113
- const result = execFileSync6(process.execPath, ["-e", script], {
50114
- encoding: "utf-8",
50115
- timeout: 15e3,
50116
- stdio: ["pipe", "pipe", "pipe"]
50117
- });
50118
- return result;
50119
- } catch (err) {
50120
- const e = err;
50121
- const reason = String(e.stderr ?? "").trim() || e.message || "unknown error";
50122
- const firstLine = reason.split("\n", 1)[0].slice(0, 200);
50123
- return "__TRANSPORTERROR__" + firstLine;
50124
- }
50125
- }
50126
- /**
50127
- * Sleep synchronously between produce retries.
50128
- *
50129
- * `push()` is synchronous (the whole backend drives its socket through a child
50130
- * process), so there is no event loop to await on. `Atomics.wait` on a
50131
- * SharedArrayBuffer is the stdlib way to block a thread for a fixed time --
50132
- * no dependency, no busy-wait burning CPU.
50133
- */
50134
- static sleepSync(ms) {
50135
- const shared = new Int32Array(new SharedArrayBuffer(4));
50136
- Atomics.wait(shared, 0, 0, ms);
50137
- }
50138
- /**
50139
- * Turn a sentinel from the protocol child into a thrown error, or return.
50140
- *
50141
- * The wording matches the Python and PHP backends exactly -- the parity rule
50142
- * covers user-visible error messages, not just behaviour.
50143
- */
50144
- static assertNoError(result, operation, topic) {
50145
- const fatal = /^__(PRODUCEERROR|FETCHERROR)__(\d+)/.exec(result);
50146
- if (fatal) {
50147
- throw new Error(
50148
- `Kafka rejected the ${operation} for topic ${topic}: error code ${fatal[2]}`
50149
- );
50150
- }
50151
- if (result.startsWith("__TRANSPORTERROR__")) {
50152
- throw new Error(
50153
- `Kafka ${operation} for topic ${topic} failed: ` + result.slice("__TRANSPORTERROR__".length)
50154
- );
50155
- }
50156
- if (result.startsWith("__PARSEERROR__")) {
50157
- throw new Error(
50158
- `Kafka ${operation} for topic ${topic} returned an unreadable response: ` + result.slice("__PARSEERROR__".length)
50159
- );
50160
- }
50161
- }
50162
- /**
50163
- * Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
50164
- * as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
50165
- * consumer reading the topic gets the schema it expects; otherwise the Tina4 job
50166
- * envelope. pop() unwraps both shapes (payload ?? the whole record).
50167
- */
50168
- static encodeJob(id, payload, raw) {
50169
- if (raw) return JSON.stringify(payload);
50170
- return JSON.stringify({
50171
- id,
50172
- payload,
50173
- status: "pending",
50174
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
50175
- attempts: 0,
50176
- delayUntil: null
50177
- });
50178
- }
50179
- push(queue, payload, _delay, _priority, raw = false) {
50180
- const id = randomUUID9();
50181
- const body = _KafkaBackend.encodeJob(id, payload, raw);
50182
- let result = "";
50183
- for (let attempt = 1; attempt <= 10; attempt++) {
50184
- result = this.execSync("publish", queue, body);
50185
- if (result.includes("__PUBLISHED__")) {
50186
- return id;
50187
- }
50188
- const retriable = /^__PRODUCEERROR__(3|5)\b/.test(result);
50189
- if (!retriable || attempt === 10) {
50190
- break;
50191
- }
50192
- _KafkaBackend.sleepSync(200);
50193
- }
50194
- _KafkaBackend.assertNoError(result, "produce", queue);
50195
- throw new Error(`Kafka publish failed for topic ${queue}: ${result || "no response"}`);
50196
- }
50197
- pop(queue) {
50198
- const result = this.execSync("get", queue);
50199
- _KafkaBackend.assertNoError(result, "fetch", queue);
50200
- if (!result || result === "__EMPTY__" || result === "__UNSUPPORTED__") return null;
50201
- try {
50202
- return JSON.parse(result);
50203
- } catch {
50204
- return null;
50205
- }
50206
- }
50207
- size(_queue) {
50208
- return 0;
50209
- }
50210
- clear(_queue) {
50211
- throw new Error(
50212
- "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."
50213
- );
50214
- }
50215
- purge(_queue, _status) {
50216
- throw new Error(
50217
- "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."
50218
- );
50219
- }
50220
- };
50221
- }
50222
- });
50223
-
50224
50902
  // ../core/src/testing.ts
50225
50903
  function expectEqual(args, expected) {
50226
50904
  return { type: "equal", args, expected };
@@ -50996,6 +51674,8 @@ __export(src_exports3, {
50996
51674
  TEXT_PLAIN: () => TEXT_PLAIN,
50997
51675
  TEXT_XML: () => TEXT_XML,
50998
51676
  TINA4_VERSION: () => TINA4_VERSION,
51677
+ TcpConnection: () => TcpConnection,
51678
+ TcpService: () => TcpService,
50999
51679
  TestClient: () => TestClient,
51000
51680
  TestResponse: () => TestResponse,
51001
51681
  Tina4AssertionError: () => AssertionError,
@@ -51038,6 +51718,7 @@ __export(src_exports3, {
51038
51718
  checkPassword: () => checkPassword,
51039
51719
  clearCache: () => clearCache,
51040
51720
  clearCurrentNonce: () => clearCurrentNonce,
51721
+ clearTcpRegistry: () => clearTcpRegistry,
51041
51722
  computeAcceptKey: () => computeAcceptKey,
51042
51723
  container: () => container,
51043
51724
  cors: () => cors,
@@ -51059,6 +51740,7 @@ __export(src_exports3, {
51059
51740
  devAdminLanguage: () => devAdminLanguage,
51060
51741
  devReloadWs: () => devReloadWs,
51061
51742
  discoverRoutes: () => discoverRoutes,
51743
+ drainAllTcpServices: () => drainAllTcpServices,
51062
51744
  encodeError: () => encodeError,
51063
51745
  encodeNotification: () => encodeNotification,
51064
51746
  encodeResponse: () => encodeResponse,
@@ -51146,6 +51828,7 @@ __export(src_exports3, {
51146
51828
  refreshToken: () => refreshToken,
51147
51829
  registerDevTools: () => registerDevTools,
51148
51830
  registerFeedbackRoutes: () => registerFeedbackRoutes,
51831
+ registeredTcpServices: () => registeredTcpServices,
51149
51832
  removePidfile: () => removePidfile,
51150
51833
  renderErrorOverlay: () => renderErrorOverlay,
51151
51834
  requestLogger: () => requestLogger,
@@ -51176,12 +51859,16 @@ __export(src_exports3, {
51176
51859
  setFrond: () => setFrond,
51177
51860
  showMenu: () => showMenu,
51178
51861
  start: () => start,
51862
+ startAllTcpServices: () => startAllTcpServices,
51179
51863
  startServer: () => startServer,
51180
51864
  stop: () => stop,
51865
+ stopAcceptingAllTcpServices: () => stopAcceptingAllTcpServices,
51181
51866
  stopAllBackgroundTasks: () => stopAllBackgroundTasks,
51182
51867
  supervisorBaseUrl: () => supervisorBaseUrl,
51183
51868
  sweep: () => sweep,
51184
51869
  takeOverPort: () => takeOverPort,
51870
+ tcp: () => tcp,
51871
+ tcpService: () => tcpService,
51185
51872
  templateAutoRoutingEnabled: () => templateAutoRoutingEnabled,
51186
51873
  tests: () => tests,
51187
51874
  trustedProxyNetworks: () => trustedProxyNetworks,
@@ -51201,6 +51888,7 @@ var init_src3 = __esm({
51201
51888
  "use strict";
51202
51889
  init_server();
51203
51890
  init_background();
51891
+ init_tcp();
51204
51892
  init_router();
51205
51893
  init_router();
51206
51894
  init_routeDiscovery();