tina4-nodejs 3.13.157 → 3.13.159
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.
- package/CLAUDE.md +4 -3
- package/package.json +3 -3
- package/packages/cli/dist/bin.js +1384 -639
- package/packages/cli/src/commands/generate.ts +72 -23
- package/packages/core/dist/index.js +1393 -639
- package/packages/core/public/bundled-component-provenance.json +2 -2
- package/packages/core/public/js/frond.js +26 -7
- package/packages/core/public/js/frond.min.js +1 -1
- package/packages/core/src/index.ts +18 -0
- package/packages/core/src/middleware.ts +10 -4
- package/packages/core/src/queue.ts +42 -32
- package/packages/core/src/queueBackends/kafkaBackend.ts +687 -544
- package/packages/core/src/server.ts +41 -4
- package/packages/core/src/tcp.ts +484 -0
- package/packages/frond/dist/index.js +118 -4
- package/packages/frond/src/engine.ts +87 -8
- package/packages/frond/src/index.ts +1 -1
- package/packages/orm/dist/index.js +1386 -641
- package/packages/orm/src/migration.ts +34 -0
- package/packages/orm/src/queryBuilder.ts +38 -0
- package/types/core/src/index.d.ts +2 -0
- package/types/core/src/queue.d.ts +1 -1
- package/types/core/src/queueBackends/kafkaBackend.d.ts +48 -54
- package/types/core/src/tcp.d.ts +165 -0
- package/types/frond/src/engine.d.ts +9 -0
- package/types/frond/src/index.d.ts +1 -1
- package/types/orm/src/migration.d.ts +0 -24
- package/types/orm/src/queryBuilder.d.ts +28 -0
|
@@ -9325,6 +9325,13 @@ function consumeSqlDelimiter(state) {
|
|
|
9325
9325
|
}
|
|
9326
9326
|
return true;
|
|
9327
9327
|
}
|
|
9328
|
+
function hasExecutableSql(sql) {
|
|
9329
|
+
const body = sql.replace(/\/\*[\s\S]*?\*\//g, "").replace(/--[^\n]*/g, "");
|
|
9330
|
+
return body.replace(/[;\s]/g, "") !== "";
|
|
9331
|
+
}
|
|
9332
|
+
function isUnappliedScaffold(sql) {
|
|
9333
|
+
return TINA4_EDIT_MARKER_RE.test(sql) && !hasExecutableSql(sql);
|
|
9334
|
+
}
|
|
9328
9335
|
function splitStatements(sql, delimiter2 = ";") {
|
|
9329
9336
|
const state = {
|
|
9330
9337
|
sql: normalizeQuotes(sql),
|
|
@@ -9509,6 +9516,12 @@ async function runPendingMigrations(db, dir, delimiter2) {
|
|
|
9509
9516
|
result.skipped.push(file);
|
|
9510
9517
|
continue;
|
|
9511
9518
|
}
|
|
9519
|
+
if (isUnappliedScaffold(sqlContent)) {
|
|
9520
|
+
console.warn(
|
|
9521
|
+
` Migration ${file} is still an unedited scaffold (a 'tina4:edit' placeholder with no SQL yet) \u2014 skipped and kept pending. Write the migration and remove the tina4:edit line(s), then run migrate again.`
|
|
9522
|
+
);
|
|
9523
|
+
continue;
|
|
9524
|
+
}
|
|
9512
9525
|
const statements = splitStatements(sqlContent, delimiter2);
|
|
9513
9526
|
try {
|
|
9514
9527
|
await adapterStartTransaction(db);
|
|
@@ -9653,7 +9666,7 @@ export class ${className} {
|
|
|
9653
9666
|
writeFileSync(filePath, content, "utf-8");
|
|
9654
9667
|
return filePath;
|
|
9655
9668
|
}
|
|
9656
|
-
var ALTER_ADD_RE, CREATE_TABLE_RE, MIGRATION_TABLE, SMART_QUOTES, SMART_QUOTE_RE, SET_TERM_RE, MIGRATION_LOCK_NAME, PG_ADVISORY_KEY, delay, Migration;
|
|
9669
|
+
var ALTER_ADD_RE, CREATE_TABLE_RE, MIGRATION_TABLE, SMART_QUOTES, SMART_QUOTE_RE, SET_TERM_RE, TINA4_EDIT_MARKER_RE, MIGRATION_LOCK_NAME, PG_ADVISORY_KEY, delay, Migration;
|
|
9657
9670
|
var init_migration = __esm({
|
|
9658
9671
|
"../orm/src/migration.ts"() {
|
|
9659
9672
|
"use strict";
|
|
@@ -9678,6 +9691,7 @@ var init_migration = __esm({
|
|
|
9678
9691
|
};
|
|
9679
9692
|
SMART_QUOTE_RE = new RegExp(`[${Object.keys(SMART_QUOTES).join("")}]`, "g");
|
|
9680
9693
|
SET_TERM_RE = /^SET\s+TERM\s+(\S+)$/i;
|
|
9694
|
+
TINA4_EDIT_MARKER_RE = /(?:#|\/\/|--|\/\*|\{#)\s*tina4:edit\b/i;
|
|
9681
9695
|
MIGRATION_LOCK_NAME = "tina4_migration_lock";
|
|
9682
9696
|
PG_ADVISORY_KEY = BigInt.asIntN(
|
|
9683
9697
|
64,
|
|
@@ -10302,6 +10316,7 @@ var init_autoCrud = __esm({
|
|
|
10302
10316
|
var engine_exports = {};
|
|
10303
10317
|
__export(engine_exports, {
|
|
10304
10318
|
Frond: () => Frond,
|
|
10319
|
+
FrondSyntaxError: () => FrondSyntaxError,
|
|
10305
10320
|
MEMO_CACHE_MAX: () => MEMO_CACHE_MAX,
|
|
10306
10321
|
TEMPLATE_CACHE_MAX: () => TEMPLATE_CACHE_MAX,
|
|
10307
10322
|
escapeHtml: () => escapeHtml,
|
|
@@ -11434,6 +11449,87 @@ function isEscapableStructured(value) {
|
|
|
11434
11449
|
function toOutputString(value) {
|
|
11435
11450
|
return String(value);
|
|
11436
11451
|
}
|
|
11452
|
+
function phpDate(dt, fmt) {
|
|
11453
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
11454
|
+
const hours = dt.getHours();
|
|
11455
|
+
const h12 = hours % 12 || 12;
|
|
11456
|
+
const dow = dt.getDay();
|
|
11457
|
+
const iso2 = dow === 0 ? 7 : dow;
|
|
11458
|
+
let out = "";
|
|
11459
|
+
for (let i = 0; i < fmt.length; i++) {
|
|
11460
|
+
const c = fmt[i];
|
|
11461
|
+
if (c === "\\" && i + 1 < fmt.length) {
|
|
11462
|
+
out += fmt[i + 1];
|
|
11463
|
+
i++;
|
|
11464
|
+
continue;
|
|
11465
|
+
}
|
|
11466
|
+
switch (c) {
|
|
11467
|
+
case "Y":
|
|
11468
|
+
out += String(dt.getFullYear());
|
|
11469
|
+
break;
|
|
11470
|
+
case "y":
|
|
11471
|
+
out += pad(dt.getFullYear() % 100);
|
|
11472
|
+
break;
|
|
11473
|
+
case "m":
|
|
11474
|
+
out += pad(dt.getMonth() + 1);
|
|
11475
|
+
break;
|
|
11476
|
+
case "n":
|
|
11477
|
+
out += String(dt.getMonth() + 1);
|
|
11478
|
+
break;
|
|
11479
|
+
case "d":
|
|
11480
|
+
out += pad(dt.getDate());
|
|
11481
|
+
break;
|
|
11482
|
+
case "j":
|
|
11483
|
+
out += String(dt.getDate());
|
|
11484
|
+
break;
|
|
11485
|
+
case "H":
|
|
11486
|
+
out += pad(hours);
|
|
11487
|
+
break;
|
|
11488
|
+
case "G":
|
|
11489
|
+
out += String(hours);
|
|
11490
|
+
break;
|
|
11491
|
+
case "h":
|
|
11492
|
+
out += pad(h12);
|
|
11493
|
+
break;
|
|
11494
|
+
case "g":
|
|
11495
|
+
out += String(h12);
|
|
11496
|
+
break;
|
|
11497
|
+
case "i":
|
|
11498
|
+
out += pad(dt.getMinutes());
|
|
11499
|
+
break;
|
|
11500
|
+
case "s":
|
|
11501
|
+
out += pad(dt.getSeconds());
|
|
11502
|
+
break;
|
|
11503
|
+
case "A":
|
|
11504
|
+
out += hours < 12 ? "AM" : "PM";
|
|
11505
|
+
break;
|
|
11506
|
+
case "a":
|
|
11507
|
+
out += hours < 12 ? "am" : "pm";
|
|
11508
|
+
break;
|
|
11509
|
+
case "D":
|
|
11510
|
+
out += PHP_DAYS[dow].slice(0, 3);
|
|
11511
|
+
break;
|
|
11512
|
+
case "l":
|
|
11513
|
+
out += PHP_DAYS[dow];
|
|
11514
|
+
break;
|
|
11515
|
+
case "M":
|
|
11516
|
+
out += PHP_MONTHS[dt.getMonth()].slice(0, 3);
|
|
11517
|
+
break;
|
|
11518
|
+
case "F":
|
|
11519
|
+
out += PHP_MONTHS[dt.getMonth()];
|
|
11520
|
+
break;
|
|
11521
|
+
case "N":
|
|
11522
|
+
out += String(iso2);
|
|
11523
|
+
break;
|
|
11524
|
+
case "w":
|
|
11525
|
+
out += String(dow);
|
|
11526
|
+
break;
|
|
11527
|
+
default:
|
|
11528
|
+
out += c;
|
|
11529
|
+
}
|
|
11530
|
+
}
|
|
11531
|
+
return out;
|
|
11532
|
+
}
|
|
11437
11533
|
function dateFilter(value, fmt) {
|
|
11438
11534
|
let dt;
|
|
11439
11535
|
if (value instanceof Date) {
|
|
@@ -11446,6 +11542,7 @@ function dateFilter(value, fmt) {
|
|
|
11446
11542
|
} else {
|
|
11447
11543
|
return String(value);
|
|
11448
11544
|
}
|
|
11545
|
+
if (!fmt.includes("%")) return phpDate(dt, fmt);
|
|
11449
11546
|
return fmt.replace(/%Y/g, String(dt.getFullYear())).replace(/%m/g, String(dt.getMonth() + 1).padStart(2, "0")).replace(/%d/g, String(dt.getDate()).padStart(2, "0")).replace(/%H/g, String(dt.getHours()).padStart(2, "0")).replace(/%M/g, String(dt.getMinutes()).padStart(2, "0")).replace(/%S/g, String(dt.getSeconds()).padStart(2, "0")).replace(/%I/g, String(dt.getHours() % 12 || 12).padStart(2, "0")).replace(/%p/g, dt.getHours() >= 12 ? "PM" : "AM").replace(/%B/g, dt.toLocaleString("en-US", { month: "long" })).replace(/%b/g, dt.toLocaleString("en-US", { month: "short" })).replace(/%A/g, dt.toLocaleString("en-US", { weekday: "long" })).replace(/%a/g, dt.toLocaleString("en-US", { weekday: "short" }));
|
|
11450
11547
|
}
|
|
11451
11548
|
function wordwrap(text, width) {
|
|
@@ -11556,7 +11653,7 @@ function _generateFormToken(descriptor = "") {
|
|
|
11556
11653
|
function _generateFormTokenValue(descriptor = "") {
|
|
11557
11654
|
return new SafeString(_buildFormTokenJwt(descriptor));
|
|
11558
11655
|
}
|
|
11559
|
-
var SafeString, KNOWN_TAGS, TERMINATOR_TAGS, GATEABLE_TAGS, BLOCK_TAG_ENDS, JSON_UNSAFE_RE, JSON_UNSAFE_MAP, NUMERIC_RE, METHOD_CALL_RE, FN_CALL_RE, IS_NOT_RE, IS_RE, NOT_IN_RE, IN_RE, DIVISIBLE_BY_RE, FILTER_WITH_ARGS_RE, FILTER_COMPARISON_RE, TITLE_WORD_RE, STRIP_TAGS_RE, FAST_FILTERS, FORMAT_RE, THOUSANDS_RE, LIVE_RE, LIVE_WS_RE, LIVE_SRC_RE, EXTENDS_RE, EXTENDS_RE_GLOBAL, filterChainCache, pathParseCache, TEMPLATE_CACHE_MAX, MEMO_CACHE_MAX, RAW_OPEN_RE, RAW_CLOSE_RE, TAG_KINDS, EXPR_NOT_MATCHED, ARITHMETIC_OPERATIONS, ARITHMETIC_LEVELS, BARE_KEY_RE, EXPR_EVALUATORS, expressionFormCache, VarRef, JS_SAFE_RE, MEDIA_TYPE_RE, SANDBOX_EXPR_KEYWORDS, SANDBOX_IDENT_RE, SANDBOX_STRING_RE, UNSAFE_KEYS, BUILTIN_FILTERS, _formTokenSessionId, _formTokenSessionProvider, _cspNonceProvider, Frond;
|
|
11656
|
+
var SafeString, KNOWN_TAGS, TERMINATOR_TAGS, GATEABLE_TAGS, BLOCK_TAG_ENDS, JSON_UNSAFE_RE, JSON_UNSAFE_MAP, NUMERIC_RE, METHOD_CALL_RE, FN_CALL_RE, IS_NOT_RE, IS_RE, NOT_IN_RE, IN_RE, DIVISIBLE_BY_RE, FILTER_WITH_ARGS_RE, FILTER_COMPARISON_RE, TITLE_WORD_RE, STRIP_TAGS_RE, FAST_FILTERS, FORMAT_RE, THOUSANDS_RE, LIVE_RE, LIVE_WS_RE, LIVE_SRC_RE, EXTENDS_RE, EXTENDS_RE_GLOBAL, filterChainCache, pathParseCache, TEMPLATE_CACHE_MAX, MEMO_CACHE_MAX, RAW_OPEN_RE, RAW_CLOSE_RE, TAG_KINDS, EXPR_NOT_MATCHED, ARITHMETIC_OPERATIONS, ARITHMETIC_LEVELS, BARE_KEY_RE, EXPR_EVALUATORS, expressionFormCache, VarRef, JS_SAFE_RE, MEDIA_TYPE_RE, SANDBOX_EXPR_KEYWORDS, SANDBOX_IDENT_RE, SANDBOX_STRING_RE, UNSAFE_KEYS, FrondSyntaxError, PHP_MONTHS, PHP_DAYS, BUILTIN_FILTERS, _formTokenSessionId, _formTokenSessionProvider, _cspNonceProvider, Frond;
|
|
11560
11657
|
var init_engine = __esm({
|
|
11561
11658
|
"../frond/src/engine.ts"() {
|
|
11562
11659
|
"use strict";
|
|
@@ -11753,6 +11850,35 @@ var init_engine = __esm({
|
|
|
11753
11850
|
"__defineProperty__",
|
|
11754
11851
|
"valueOf"
|
|
11755
11852
|
]);
|
|
11853
|
+
FrondSyntaxError = class extends Error {
|
|
11854
|
+
constructor(message) {
|
|
11855
|
+
super(message);
|
|
11856
|
+
this.name = "FrondSyntaxError";
|
|
11857
|
+
}
|
|
11858
|
+
};
|
|
11859
|
+
PHP_MONTHS = [
|
|
11860
|
+
"January",
|
|
11861
|
+
"February",
|
|
11862
|
+
"March",
|
|
11863
|
+
"April",
|
|
11864
|
+
"May",
|
|
11865
|
+
"June",
|
|
11866
|
+
"July",
|
|
11867
|
+
"August",
|
|
11868
|
+
"September",
|
|
11869
|
+
"October",
|
|
11870
|
+
"November",
|
|
11871
|
+
"December"
|
|
11872
|
+
];
|
|
11873
|
+
PHP_DAYS = [
|
|
11874
|
+
"Sunday",
|
|
11875
|
+
"Monday",
|
|
11876
|
+
"Tuesday",
|
|
11877
|
+
"Wednesday",
|
|
11878
|
+
"Thursday",
|
|
11879
|
+
"Friday",
|
|
11880
|
+
"Saturday"
|
|
11881
|
+
];
|
|
11756
11882
|
BUILTIN_FILTERS = {
|
|
11757
11883
|
upper: (v) => String(v).toUpperCase(),
|
|
11758
11884
|
lower: (v) => String(v).toLowerCase(),
|
|
@@ -12276,7 +12402,9 @@ var init_engine = __esm({
|
|
|
12276
12402
|
}
|
|
12277
12403
|
}
|
|
12278
12404
|
if (depth > 0) {
|
|
12279
|
-
|
|
12405
|
+
throw new FrondSyntaxError(
|
|
12406
|
+
`{% block ${name} %} is never closed (missing or malformed {% endblock %})`
|
|
12407
|
+
);
|
|
12280
12408
|
}
|
|
12281
12409
|
}
|
|
12282
12410
|
return blocks;
|
|
@@ -12343,9 +12471,9 @@ var init_engine = __esm({
|
|
|
12343
12471
|
}
|
|
12344
12472
|
}
|
|
12345
12473
|
if (!closeMatch) {
|
|
12346
|
-
|
|
12347
|
-
|
|
12348
|
-
|
|
12474
|
+
throw new FrondSyntaxError(
|
|
12475
|
+
`{% block ${name} %} is never closed (missing or malformed {% endblock %})`
|
|
12476
|
+
);
|
|
12349
12477
|
}
|
|
12350
12478
|
const parentContent = source.slice(contentStart, closeMatch.index);
|
|
12351
12479
|
const blockSource = blocks[name] ?? parentContent;
|
|
@@ -14115,6 +14243,41 @@ var init_queryBuilder = __esm({
|
|
|
14115
14243
|
}
|
|
14116
14244
|
return this;
|
|
14117
14245
|
}
|
|
14246
|
+
/**
|
|
14247
|
+
* Set OFFSET (rows to skip) as its own chainable verb.
|
|
14248
|
+
*
|
|
14249
|
+
* `limit(n, offset)` buries the offset as a second positional arg; this
|
|
14250
|
+
* exposes it on its own, so `.offset(20).limit(10)` reads naturally and
|
|
14251
|
+
* matches the SQL keyword.
|
|
14252
|
+
*
|
|
14253
|
+
* @param count - Number of rows to skip.
|
|
14254
|
+
* @returns this for chaining.
|
|
14255
|
+
*/
|
|
14256
|
+
offset(count) {
|
|
14257
|
+
this.offsetVal = count;
|
|
14258
|
+
return this;
|
|
14259
|
+
}
|
|
14260
|
+
/**
|
|
14261
|
+
* Alias for `offset()` -- the Mongo/Eloquent name for the same thing.
|
|
14262
|
+
*
|
|
14263
|
+
* Mirrors the DocStore cursor's `skip` and the `skip` key that `toMongo()`
|
|
14264
|
+
* already emits, so a query reads the same whether it targets SQL or MongoDB.
|
|
14265
|
+
*
|
|
14266
|
+
* @param count - Number of rows to skip.
|
|
14267
|
+
* @returns this for chaining.
|
|
14268
|
+
*/
|
|
14269
|
+
skip(count) {
|
|
14270
|
+
return this.offset(count);
|
|
14271
|
+
}
|
|
14272
|
+
/**
|
|
14273
|
+
* Alias for `limit()` -- the Eloquent name; pairs with `skip()`.
|
|
14274
|
+
*
|
|
14275
|
+
* @param count - Maximum rows to return.
|
|
14276
|
+
* @returns this for chaining.
|
|
14277
|
+
*/
|
|
14278
|
+
take(count) {
|
|
14279
|
+
return this.limit(count);
|
|
14280
|
+
}
|
|
14118
14281
|
/**
|
|
14119
14282
|
* Build and return the SQL string without executing.
|
|
14120
14283
|
*
|
|
@@ -22220,6 +22383,9 @@ function attachCsrfFromEnv() {
|
|
|
22220
22383
|
}
|
|
22221
22384
|
return false;
|
|
22222
22385
|
}
|
|
22386
|
+
function logPath(req2) {
|
|
22387
|
+
return req2.path ?? (req2.url ?? "/").split("?")[0];
|
|
22388
|
+
}
|
|
22223
22389
|
function requestLogger() {
|
|
22224
22390
|
return (req2, res, next) => {
|
|
22225
22391
|
const start2 = Date.now();
|
|
@@ -22228,8 +22394,7 @@ function requestLogger() {
|
|
|
22228
22394
|
const duration = Date.now() - start2;
|
|
22229
22395
|
const status2 = res.raw.statusCode;
|
|
22230
22396
|
const method = req2.method ?? "?";
|
|
22231
|
-
|
|
22232
|
-
Log.info(`${method} ${url} -> ${status2} (${duration}ms)`);
|
|
22397
|
+
Log.info(`${method} ${logPath(req2)} -> ${status2} (${duration}ms)`);
|
|
22233
22398
|
});
|
|
22234
22399
|
next();
|
|
22235
22400
|
};
|
|
@@ -22656,9 +22821,9 @@ var init_middleware = __esm({
|
|
|
22656
22821
|
const duration = Date.now() - (req2.startTime ?? Date.now());
|
|
22657
22822
|
const status2 = res.raw.statusCode;
|
|
22658
22823
|
const method = req2.method ?? "?";
|
|
22659
|
-
const
|
|
22824
|
+
const path10 = logPath(req2);
|
|
22660
22825
|
const color = status2 >= 400 ? "\x1B[31m" : status2 >= 300 ? "\x1B[33m" : "\x1B[32m";
|
|
22661
|
-
console.log(` ${color}${status2}\x1B[0m ${method} ${
|
|
22826
|
+
console.log(` ${color}${status2}\x1B[0m ${method} ${path10} \x1B[90m${duration}ms\x1B[0m`);
|
|
22662
22827
|
return [req2, res];
|
|
22663
22828
|
}
|
|
22664
22829
|
};
|
|
@@ -28027,6 +28192,7 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
|
|
|
28027
28192
|
}
|
|
28028
28193
|
const fields = fieldsOverride || parseFields(flags.fields || "");
|
|
28029
28194
|
const isCreate = name.startsWith("create_") || fieldsOverride !== void 0;
|
|
28195
|
+
const isView = isCreate && fieldsOverride === void 0 && table2.endsWith("_view");
|
|
28030
28196
|
const fileName = `${ts}_${name}.sql`;
|
|
28031
28197
|
const path10 = join20(dir, fileName);
|
|
28032
28198
|
setResolutionField("migration_path", `migrations/${fileName}`);
|
|
@@ -28036,7 +28202,13 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
|
|
|
28036
28202
|
}
|
|
28037
28203
|
let upSql;
|
|
28038
28204
|
let downSql;
|
|
28039
|
-
if (
|
|
28205
|
+
if (isView) {
|
|
28206
|
+
upSql = `-- tina4:edit write the CREATE VIEW statement, then remove the
|
|
28207
|
+
-- tina4:edit lines. For example:
|
|
28208
|
+
-- CREATE VIEW ${table2} AS
|
|
28209
|
+
-- SELECT id, /* columns */ FROM source_table WHERE /* ... */;`;
|
|
28210
|
+
downSql = `DROP VIEW IF EXISTS ${table2};`;
|
|
28211
|
+
} else if (isCreate) {
|
|
28040
28212
|
const colLines = [" id INTEGER PRIMARY KEY AUTOINCREMENT"];
|
|
28041
28213
|
for (const [fname, ftype] of fields) {
|
|
28042
28214
|
const info = FIELD_TYPE_MAP[ftype] || FIELD_TYPE_MAP.string;
|
|
@@ -28062,9 +28234,6 @@ DROP TABLE IF EXISTS ${table2};`;
|
|
|
28062
28234
|
|
|
28063
28235
|
-- UP
|
|
28064
28236
|
${upSql}
|
|
28065
|
-
|
|
28066
|
-
-- DOWN
|
|
28067
|
-
${downSql}
|
|
28068
28237
|
`;
|
|
28069
28238
|
writeFileSafe(path10, content);
|
|
28070
28239
|
const downPath = join20(dir, `${ts}_${name}.down.sql`);
|
|
@@ -28074,7 +28243,7 @@ ${downSql}
|
|
|
28074
28243
|
${downSql}
|
|
28075
28244
|
`;
|
|
28076
28245
|
writeFileSafe(downPath, downContent);
|
|
28077
|
-
if (emitTest && isCreate) emitMigrationTest(name, table2);
|
|
28246
|
+
if (emitTest && isCreate && !isView) emitMigrationTest(name, table2);
|
|
28078
28247
|
}
|
|
28079
28248
|
function generateMiddleware(name, _flags) {
|
|
28080
28249
|
const snake = toSnake(name);
|
|
@@ -28885,9 +29054,11 @@ function emitRouteStubTest(route) {
|
|
|
28885
29054
|
* Routing test for ${route} \u2014 no mocks, real Router + route discovery.
|
|
28886
29055
|
*
|
|
28887
29056
|
* Generated with src/routes/api/${route}/ by \`tina4nodejs generate route
|
|
28888
|
-
* ${route}\` (no --model). The handlers
|
|
28889
|
-
* implement them
|
|
28890
|
-
* register on the REAL Router, and the list handler
|
|
29057
|
+
* ${route}\` (no --model). The handlers start as AI-FILL stubs that throw until
|
|
29058
|
+
* you implement them. This tests what is live on generation: all five routes
|
|
29059
|
+
* register on the REAL Router, and the list handler is wired and callable. It
|
|
29060
|
+
* stays GREEN whether the stub still throws OR you have filled it in \u2014
|
|
29061
|
+
* implementing the handler never turns this test red.
|
|
28891
29062
|
* Run with: npx tsx tests/${route}.test.ts
|
|
28892
29063
|
*/
|
|
28893
29064
|
import { dirname, resolve } from "node:path";
|
|
@@ -28904,9 +29075,15 @@ for (const sig of ["GET /api/${route}", "POST /api/${route}", "GET /api/${route}
|
|
|
28904
29075
|
assert(\`route registered: \${sig}\`, sigs.includes(sig));
|
|
28905
29076
|
}
|
|
28906
29077
|
|
|
28907
|
-
// The
|
|
28908
|
-
|
|
28909
|
-
|
|
29078
|
+
// The list handler is WIRED: a loud AI-FILL stub (throws) on generation. This
|
|
29079
|
+
// stays green whether it still throws OR you have filled it in, so doing the
|
|
29080
|
+
// work never turns the suite red.
|
|
29081
|
+
assert("list handler is callable", typeof listHandler === "function");
|
|
29082
|
+
try {
|
|
29083
|
+
await listHandler({} as never, {} as never);
|
|
29084
|
+
} catch {
|
|
29085
|
+
// still the scaffold stub (throws until filled) \u2014 expected
|
|
29086
|
+
}`;
|
|
28910
29087
|
writeTest(route, standaloneTest(doc, body));
|
|
28911
29088
|
}
|
|
28912
29089
|
function emitMiddlewareTest(name, snake) {
|
|
@@ -28990,8 +29167,14 @@ ServiceRunner.register(service.name, service.handler, { interval: (service as {
|
|
|
28990
29167
|
assert("registers on a real ServiceRunner", ServiceRunner.list().some((s) => s.name === "${snake}"));
|
|
28991
29168
|
ServiceRunner.remove("${snake}");
|
|
28992
29169
|
|
|
28993
|
-
// The
|
|
28994
|
-
|
|
29170
|
+
// The task is WIRED: a loud AI-FILL stub (throws) on generation. This stays
|
|
29171
|
+
// green whether it still throws OR you have filled it in.
|
|
29172
|
+
assert("task is callable", typeof ${camel}Task === "function");
|
|
29173
|
+
try {
|
|
29174
|
+
await ${camel}Task({} as never);
|
|
29175
|
+
} catch {
|
|
29176
|
+
// still the scaffold stub (throws until filled) \u2014 expected
|
|
29177
|
+
}`;
|
|
28995
29178
|
writeTest(snake, standaloneTest(doc, body));
|
|
28996
29179
|
}
|
|
28997
29180
|
function emitQueueTest(topic, slug, pascal) {
|
|
@@ -29013,8 +29196,14 @@ assert("the job is really on the queue", new Queue({ topic: "${topic}" }).size()
|
|
|
29013
29196
|
assert("consumer default export is a daemon", worker.daemon === true);
|
|
29014
29197
|
assert("consumer handler is wired", typeof worker.handler === "function");
|
|
29015
29198
|
|
|
29016
|
-
// The per-job handler is
|
|
29017
|
-
|
|
29199
|
+
// The per-job handler is WIRED: a loud AI-FILL stub (throws) on generation.
|
|
29200
|
+
// This stays green whether it still throws OR you have filled it in.
|
|
29201
|
+
assert("handle is callable", typeof handle${pascal} === "function");
|
|
29202
|
+
try {
|
|
29203
|
+
await handle${pascal}({});
|
|
29204
|
+
} catch {
|
|
29205
|
+
// still the scaffold stub (throws until filled) \u2014 expected
|
|
29206
|
+
}`;
|
|
29018
29207
|
writeTest(slug, standaloneTest(doc, body));
|
|
29019
29208
|
}
|
|
29020
29209
|
function emitValidatorTest(name, snake, pascal) {
|
|
@@ -29076,9 +29265,14 @@ import { ${handler} } from "../src/routes/ws_${base}.js"; // importing register
|
|
|
29076
29265
|
const closed = await ${handler}(null as never, "close", "");
|
|
29077
29266
|
assert("close event handled cleanly", closed === undefined);
|
|
29078
29267
|
|
|
29079
|
-
// The "message" branch is
|
|
29080
|
-
|
|
29081
|
-
|
|
29268
|
+
// The "message" branch is WIRED: a loud AI-FILL stub (throws) on generation.
|
|
29269
|
+
// This stays green whether it still throws OR you have filled it in.
|
|
29270
|
+
try {
|
|
29271
|
+
await ${handler}(null as never, "message", "hi");
|
|
29272
|
+
assert("message branch is callable", true);
|
|
29273
|
+
} catch {
|
|
29274
|
+
assert("message branch is callable", true); // still the scaffold stub
|
|
29275
|
+
}`;
|
|
29082
29276
|
writeTest(`ws_${base}`, standaloneTest(doc, body));
|
|
29083
29277
|
}
|
|
29084
29278
|
function emitListenerTest(event, slug) {
|
|
@@ -29095,9 +29289,15 @@ import { Events } from "tina4-nodejs";
|
|
|
29095
29289
|
import "../src/listeners/${slug}.js"; // importing registers the listener via Events.on()`;
|
|
29096
29290
|
const body = `assert("listener registered on the real event bus", Events.listeners("${event}").length >= 1);
|
|
29097
29291
|
|
|
29098
|
-
//
|
|
29099
|
-
|
|
29100
|
-
|
|
29292
|
+
// Emitting reaches the listener. It starts as a loud AI-FILL stub (a strict emit
|
|
29293
|
+
// re-raises); once you implement it this test STILL passes, so doing the work
|
|
29294
|
+
// never turns the suite red.
|
|
29295
|
+
try {
|
|
29296
|
+
await Events.emit("${event}", { strict: true }, { id: 1 });
|
|
29297
|
+
assert("emitting reaches the listener", true);
|
|
29298
|
+
} catch {
|
|
29299
|
+
assert("emitting reaches the listener", true); // still the scaffold stub
|
|
29300
|
+
}`;
|
|
29101
29301
|
writeTest(slug, standaloneTest(doc, body));
|
|
29102
29302
|
}
|
|
29103
29303
|
function emitAuthTest() {
|
|
@@ -29652,9 +29852,9 @@ function agentLog(projectRoot3, category, message) {
|
|
|
29652
29852
|
if (!fs4.existsSync(logDir)) {
|
|
29653
29853
|
fs4.mkdirSync(logDir, { recursive: true });
|
|
29654
29854
|
}
|
|
29655
|
-
const
|
|
29855
|
+
const logPath2 = path3.join(logDir, "agent.log");
|
|
29656
29856
|
const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/\..+/, "Z");
|
|
29657
|
-
fs4.appendFileSync(
|
|
29857
|
+
fs4.appendFileSync(logPath2, `${ts} [${category}] ${message}
|
|
29658
29858
|
`, "utf-8");
|
|
29659
29859
|
} catch {
|
|
29660
29860
|
}
|
|
@@ -30650,13 +30850,13 @@ function registerDevTools(server) {
|
|
|
30650
30850
|
"git_status",
|
|
30651
30851
|
() => {
|
|
30652
30852
|
try {
|
|
30653
|
-
const { execFileSync:
|
|
30853
|
+
const { execFileSync: execFileSync6 } = req("node:child_process");
|
|
30654
30854
|
const cwd = path3.resolve(process.cwd());
|
|
30655
30855
|
const run = (args) => {
|
|
30656
|
-
return
|
|
30856
|
+
return execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
|
|
30657
30857
|
};
|
|
30658
30858
|
try {
|
|
30659
|
-
|
|
30859
|
+
execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
|
|
30660
30860
|
} catch {
|
|
30661
30861
|
return { error: "Not a git repository" };
|
|
30662
30862
|
}
|
|
@@ -34549,6 +34749,753 @@ var init_mongoBackend = __esm({
|
|
|
34549
34749
|
}
|
|
34550
34750
|
});
|
|
34551
34751
|
|
|
34752
|
+
// src/queueBackends/kafkaBackend.ts
|
|
34753
|
+
import { Worker as Worker2 } from "node:worker_threads";
|
|
34754
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
34755
|
+
function kafkaSecurityConfig(env = process.env) {
|
|
34756
|
+
const mapping = [
|
|
34757
|
+
["security.protocol", "SECURITY_PROTOCOL"],
|
|
34758
|
+
["ssl.ca.location", "SSL_CA_LOCATION"],
|
|
34759
|
+
["sasl.mechanism", "SASL_MECHANISM"],
|
|
34760
|
+
["sasl.username", "SASL_USERNAME"],
|
|
34761
|
+
["sasl.password", "SASL_PASSWORD"]
|
|
34762
|
+
];
|
|
34763
|
+
const config = {};
|
|
34764
|
+
for (const [rdk, suffix] of mapping) {
|
|
34765
|
+
const value = env[`TINA4_KAFKA_${suffix}`] || env[`KAFKA_${suffix}`];
|
|
34766
|
+
if (value) {
|
|
34767
|
+
config[rdk] = value;
|
|
34768
|
+
}
|
|
34769
|
+
}
|
|
34770
|
+
return config;
|
|
34771
|
+
}
|
|
34772
|
+
function kafkaOffsetReset(env = process.env) {
|
|
34773
|
+
return env.TINA4_KAFKA_AUTO_OFFSET_RESET || env.KAFKA_AUTO_OFFSET_RESET || "earliest";
|
|
34774
|
+
}
|
|
34775
|
+
var WORKER_SRC, KafkaBackend;
|
|
34776
|
+
var init_kafkaBackend = __esm({
|
|
34777
|
+
"src/queueBackends/kafkaBackend.ts"() {
|
|
34778
|
+
"use strict";
|
|
34779
|
+
WORKER_SRC = `
|
|
34780
|
+
const net = require("node:net");
|
|
34781
|
+
const tls = require("node:tls");
|
|
34782
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
34783
|
+
|
|
34784
|
+
const brokers = workerData.brokers;
|
|
34785
|
+
const groupId = workerData.groupId;
|
|
34786
|
+
const security = workerData.security || {};
|
|
34787
|
+
const offsetReset = workerData.offsetReset || "earliest";
|
|
34788
|
+
const header = new Int32Array(workerData.sab, 0, 2); // [0]=flag, [1]=respLen
|
|
34789
|
+
const outBytes = new Uint8Array(workerData.sab, 8);
|
|
34790
|
+
|
|
34791
|
+
// Lowest versions Kafka 4.x still accepts: it REMOVED Produce v0-v2 / Fetch v0-v3
|
|
34792
|
+
// (the old message formats) and answers a removed version by closing the socket,
|
|
34793
|
+
// not with an error code. These are named constants so the source invariant test
|
|
34794
|
+
// (test/kafkaErrorCodes.test.ts) can assert the floors.
|
|
34795
|
+
const PRODUCE_VERSION = 3;
|
|
34796
|
+
const FETCH_VERSION = 4;
|
|
34797
|
+
|
|
34798
|
+
let correlationId = 0;
|
|
34799
|
+
let brokerSock = null;
|
|
34800
|
+
let coordSock = null;
|
|
34801
|
+
const offsets = {}; // topic -> next read offset (in-memory cursor)
|
|
34802
|
+
const inFlight = {}; // job id -> { offset, value, attempts, isEnvelope }
|
|
34803
|
+
|
|
34804
|
+
const COORDINATOR_ERRORS = [14, 15, 16];
|
|
34805
|
+
|
|
34806
|
+
function parseBroker(list) {
|
|
34807
|
+
const first = String(list).split(",")[0].trim();
|
|
34808
|
+
const i = first.lastIndexOf(":");
|
|
34809
|
+
if (i < 0) return { host: first || "localhost", port: 9092 };
|
|
34810
|
+
return { host: first.slice(0, i) || "localhost", port: parseInt(first.slice(i + 1), 10) || 9092 };
|
|
34811
|
+
}
|
|
34812
|
+
|
|
34813
|
+
function connect(host, port) {
|
|
34814
|
+
return new Promise(function (resolve, reject) {
|
|
34815
|
+
const proto = String(security["security.protocol"] || "PLAINTEXT").toUpperCase();
|
|
34816
|
+
const useTls = proto.indexOf("SSL") >= 0;
|
|
34817
|
+
let sock;
|
|
34818
|
+
const onErr = function (e) { reject(e); };
|
|
34819
|
+
if (useTls) {
|
|
34820
|
+
const opts = { host: host, port: port, servername: host };
|
|
34821
|
+
if (security["ssl.ca.location"]) opts.ca = require("node:fs").readFileSync(security["ssl.ca.location"]);
|
|
34822
|
+
sock = tls.connect(opts, function () { sock.removeListener("error", onErr); resolve(sock); });
|
|
34823
|
+
} else {
|
|
34824
|
+
sock = net.createConnection({ host: host, port: port }, function () { sock.removeListener("error", onErr); resolve(sock); });
|
|
34825
|
+
}
|
|
34826
|
+
sock.once("error", onErr);
|
|
34827
|
+
});
|
|
34828
|
+
}
|
|
34829
|
+
|
|
34830
|
+
// One request/response round trip on a socket: write the framed request, read a
|
|
34831
|
+
// 4-byte length then that many bytes, resolve with the payload AFTER the length
|
|
34832
|
+
// (so it starts at correlationId). Serialized \u2014 one in flight per socket.
|
|
34833
|
+
function rpc(sock, reqBuf) {
|
|
34834
|
+
return new Promise(function (resolve, reject) {
|
|
34835
|
+
let buf = Buffer.alloc(0);
|
|
34836
|
+
function onData(chunk) {
|
|
34837
|
+
buf = Buffer.concat([buf, chunk]);
|
|
34838
|
+
if (buf.length < 4) return;
|
|
34839
|
+
const size = buf.readInt32BE(0);
|
|
34840
|
+
if (buf.length < 4 + size) return;
|
|
34841
|
+
sock.removeListener("data", onData);
|
|
34842
|
+
sock.removeListener("error", onErr);
|
|
34843
|
+
resolve(buf.subarray(4, 4 + size));
|
|
34844
|
+
}
|
|
34845
|
+
function onErr(e) {
|
|
34846
|
+
sock.removeListener("data", onData);
|
|
34847
|
+
reject(e);
|
|
34848
|
+
}
|
|
34849
|
+
sock.on("data", onData);
|
|
34850
|
+
sock.once("error", onErr);
|
|
34851
|
+
sock.write(reqBuf);
|
|
34852
|
+
});
|
|
34853
|
+
}
|
|
34854
|
+
|
|
34855
|
+
// \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
|
|
34856
|
+
function kstr(s) {
|
|
34857
|
+
const b = Buffer.from(s, "utf-8");
|
|
34858
|
+
const out = Buffer.alloc(2 + b.length);
|
|
34859
|
+
out.writeInt16BE(b.length, 0);
|
|
34860
|
+
b.copy(out, 2);
|
|
34861
|
+
return out;
|
|
34862
|
+
}
|
|
34863
|
+
function frame(apiKey, apiVersion, body) {
|
|
34864
|
+
correlationId++;
|
|
34865
|
+
const client = Buffer.from("tina4-nodejs", "utf-8");
|
|
34866
|
+
const head = Buffer.alloc(2 + 2 + 4 + 2 + client.length);
|
|
34867
|
+
let p = 0;
|
|
34868
|
+
head.writeInt16BE(apiKey, p); p += 2;
|
|
34869
|
+
head.writeInt16BE(apiVersion, p); p += 2;
|
|
34870
|
+
head.writeInt32BE(correlationId, p); p += 4;
|
|
34871
|
+
head.writeInt16BE(client.length, p); p += 2;
|
|
34872
|
+
client.copy(head, p);
|
|
34873
|
+
const payload = Buffer.concat([head, body]);
|
|
34874
|
+
const out = Buffer.alloc(4 + payload.length);
|
|
34875
|
+
out.writeInt32BE(payload.length, 0);
|
|
34876
|
+
payload.copy(out, 4);
|
|
34877
|
+
return out;
|
|
34878
|
+
}
|
|
34879
|
+
|
|
34880
|
+
// \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
|
|
34881
|
+
const CRC32C_TABLE = (function () {
|
|
34882
|
+
const t = new Uint32Array(256);
|
|
34883
|
+
for (let n = 0; n < 256; n++) {
|
|
34884
|
+
let c = n;
|
|
34885
|
+
for (let k = 0; k < 8; k++) c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
|
|
34886
|
+
t[n] = c >>> 0;
|
|
34887
|
+
}
|
|
34888
|
+
return t;
|
|
34889
|
+
})();
|
|
34890
|
+
function crc32c(buf) {
|
|
34891
|
+
let crc = 0xffffffff;
|
|
34892
|
+
for (let i = 0; i < buf.length; i++) crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
|
|
34893
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
34894
|
+
}
|
|
34895
|
+
function zig(n) { return ((n << 1) ^ (n >> 31)) >>> 0; }
|
|
34896
|
+
function varU(u) {
|
|
34897
|
+
const b = [];
|
|
34898
|
+
let v = u >>> 0;
|
|
34899
|
+
for (;;) { if ((v & ~0x7f) === 0) { b.push(v); break; } b.push((v & 0x7f) | 0x80); v >>>= 7; }
|
|
34900
|
+
return Buffer.from(b);
|
|
34901
|
+
}
|
|
34902
|
+
function varint(n) { return varU(zig(n)); }
|
|
34903
|
+
function readVarint(buf, pos) {
|
|
34904
|
+
let result = 0, shift = 0, b;
|
|
34905
|
+
do { b = buf[pos++]; result |= (b & 0x7f) << shift; shift += 7; } while (b & 0x80);
|
|
34906
|
+
result = result >>> 0;
|
|
34907
|
+
return { value: (result >>> 1) ^ -(result & 1), next: pos };
|
|
34908
|
+
}
|
|
34909
|
+
function buildRecordBatch(valueBytes) {
|
|
34910
|
+
const now = BigInt(Date.now());
|
|
34911
|
+
const recBody = Buffer.concat([
|
|
34912
|
+
Buffer.from([0]), varint(0), varint(0), varint(-1),
|
|
34913
|
+
varint(valueBytes.length), valueBytes, varint(0),
|
|
34914
|
+
]);
|
|
34915
|
+
const record = Buffer.concat([varint(recBody.length), recBody]);
|
|
34916
|
+
const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
|
|
34917
|
+
let c = 0;
|
|
34918
|
+
crcBody.writeInt16BE(0, c); c += 2;
|
|
34919
|
+
crcBody.writeInt32BE(0, c); c += 4;
|
|
34920
|
+
crcBody.writeBigInt64BE(now, c); c += 8;
|
|
34921
|
+
crcBody.writeBigInt64BE(now, c); c += 8;
|
|
34922
|
+
crcBody.writeBigInt64BE(-1n, c); c += 8;
|
|
34923
|
+
crcBody.writeInt16BE(-1, c); c += 2;
|
|
34924
|
+
crcBody.writeInt32BE(-1, c); c += 4;
|
|
34925
|
+
crcBody.writeInt32BE(1, c); c += 4;
|
|
34926
|
+
record.copy(crcBody, c);
|
|
34927
|
+
const crc = crc32c(crcBody);
|
|
34928
|
+
const batchLength = 4 + 1 + 4 + crcBody.length;
|
|
34929
|
+
const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
|
|
34930
|
+
let h = 0;
|
|
34931
|
+
head.writeBigInt64BE(0n, h); h += 8;
|
|
34932
|
+
head.writeInt32BE(batchLength, h); h += 4;
|
|
34933
|
+
head.writeInt32BE(-1, h); h += 4;
|
|
34934
|
+
head.writeInt8(2, h); h += 1;
|
|
34935
|
+
head.writeUInt32BE(crc, h); h += 4;
|
|
34936
|
+
return Buffer.concat([head, crcBody]);
|
|
34937
|
+
}
|
|
34938
|
+
|
|
34939
|
+
// \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
|
|
34940
|
+
function produceRequest(topic, valueBytes) {
|
|
34941
|
+
const topicBuf = Buffer.from(topic, "utf-8");
|
|
34942
|
+
const batch = buildRecordBatch(valueBytes);
|
|
34943
|
+
const body = Buffer.alloc(2 + 2 + 4 + 4 + 2 + topicBuf.length + 4 + 4 + 4 + batch.length);
|
|
34944
|
+
let p = 0;
|
|
34945
|
+
body.writeInt16BE(-1, p); p += 2; // transactionalId null
|
|
34946
|
+
body.writeInt16BE(1, p); p += 2; // acks 1
|
|
34947
|
+
body.writeInt32BE(10000, p); p += 4; // timeoutMs
|
|
34948
|
+
body.writeInt32BE(1, p); p += 4; // topics
|
|
34949
|
+
body.writeInt16BE(topicBuf.length, p); p += 2;
|
|
34950
|
+
topicBuf.copy(body, p); p += topicBuf.length;
|
|
34951
|
+
body.writeInt32BE(1, p); p += 4; // partitions
|
|
34952
|
+
body.writeInt32BE(0, p); p += 4; // partition 0
|
|
34953
|
+
body.writeInt32BE(batch.length, p); p += 4;
|
|
34954
|
+
batch.copy(body, p);
|
|
34955
|
+
return frame(0, PRODUCE_VERSION, body);
|
|
34956
|
+
}
|
|
34957
|
+
function parseProduce(resp) {
|
|
34958
|
+
let pos = 4; // correlationId
|
|
34959
|
+
const topicCount = resp.readInt32BE(pos); pos += 4;
|
|
34960
|
+
let err = 0;
|
|
34961
|
+
for (let t = 0; t < topicCount; t++) {
|
|
34962
|
+
const tl = resp.readInt16BE(pos); pos += 2 + tl;
|
|
34963
|
+
const pc = resp.readInt32BE(pos); pos += 4;
|
|
34964
|
+
for (let pi = 0; pi < pc; pi++) {
|
|
34965
|
+
pos += 4; err = resp.readInt16BE(pos); pos += 2; pos += 8; pos += 8;
|
|
34966
|
+
}
|
|
34967
|
+
}
|
|
34968
|
+
return err;
|
|
34969
|
+
}
|
|
34970
|
+
async function produce(topic, valueBytes) {
|
|
34971
|
+
const sock = await broker();
|
|
34972
|
+
for (let attempt = 1; attempt <= 10; attempt++) {
|
|
34973
|
+
const err = parseProduce(await rpc(sock, produceRequest(topic, valueBytes)));
|
|
34974
|
+
if (err === 0) return;
|
|
34975
|
+
if ((err !== 3 && err !== 5) || attempt === 10) {
|
|
34976
|
+
throw new Error("Kafka rejected the produce for topic " + topic + ": error code " + err);
|
|
34977
|
+
}
|
|
34978
|
+
await sleep(200);
|
|
34979
|
+
}
|
|
34980
|
+
}
|
|
34981
|
+
|
|
34982
|
+
// \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
|
|
34983
|
+
function fetchRequest(topic, offset) {
|
|
34984
|
+
const topicBuf = Buffer.from(topic, "utf-8");
|
|
34985
|
+
const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + 2 + topicBuf.length + 4 + 4 + 8 + 4);
|
|
34986
|
+
let p = 0;
|
|
34987
|
+
buf.writeInt32BE(-1, p); p += 4; // replicaId
|
|
34988
|
+
buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
|
|
34989
|
+
buf.writeInt32BE(1, p); p += 4; // minBytes
|
|
34990
|
+
buf.writeInt32BE(1048576, p); p += 4; // maxBytes
|
|
34991
|
+
buf.writeInt8(0, p); p += 1; // isolation READ_UNCOMMITTED
|
|
34992
|
+
buf.writeInt32BE(1, p); p += 4; // topics
|
|
34993
|
+
buf.writeInt16BE(topicBuf.length, p); p += 2;
|
|
34994
|
+
topicBuf.copy(buf, p); p += topicBuf.length;
|
|
34995
|
+
buf.writeInt32BE(1, p); p += 4; // partitions
|
|
34996
|
+
buf.writeInt32BE(0, p); p += 4; // partition 0
|
|
34997
|
+
buf.writeBigInt64BE(BigInt(offset), p); p += 8;
|
|
34998
|
+
buf.writeInt32BE(1048576, p); p += 4;
|
|
34999
|
+
return frame(1, FETCH_VERSION, buf);
|
|
35000
|
+
}
|
|
35001
|
+
// Decode the first record of the partition's record-set: its value string and
|
|
35002
|
+
// absolute offset (baseOffset + offsetDelta). null = no usable record.
|
|
35003
|
+
function firstRecord(buf, start, end) {
|
|
35004
|
+
let pos = start;
|
|
35005
|
+
while (pos + 12 <= end) {
|
|
35006
|
+
const baseOffset = buf.readBigInt64BE(pos);
|
|
35007
|
+
const batchLength = buf.readInt32BE(pos + 8);
|
|
35008
|
+
const batchStart = pos + 12;
|
|
35009
|
+
const batchEnd = batchStart + batchLength;
|
|
35010
|
+
if (batchLength <= 0 || batchEnd > end) break;
|
|
35011
|
+
const magic = buf.readInt8(batchStart + 4);
|
|
35012
|
+
if (magic !== 2) { pos = batchEnd; continue; }
|
|
35013
|
+
let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
|
|
35014
|
+
const recordsCount = buf.readInt32BE(r); r += 4;
|
|
35015
|
+
for (let i = 0; i < recordsCount && r < batchEnd; i++) {
|
|
35016
|
+
const recLen = readVarint(buf, r);
|
|
35017
|
+
let rp = recLen.next;
|
|
35018
|
+
const recordEnd = rp + recLen.value;
|
|
35019
|
+
rp += 1;
|
|
35020
|
+
rp = readVarint(buf, rp).next; // timestampDelta
|
|
35021
|
+
const offDelta = readVarint(buf, rp); rp = offDelta.next;
|
|
35022
|
+
const keyLen = readVarint(buf, rp); rp = keyLen.next;
|
|
35023
|
+
if (keyLen.value >= 0) rp += keyLen.value;
|
|
35024
|
+
const valLen = readVarint(buf, rp); rp = valLen.next;
|
|
35025
|
+
if (valLen.value >= 0) {
|
|
35026
|
+
return {
|
|
35027
|
+
value: buf.subarray(rp, rp + valLen.value).toString("utf-8"),
|
|
35028
|
+
offset: Number(baseOffset) + offDelta.value,
|
|
35029
|
+
};
|
|
35030
|
+
}
|
|
35031
|
+
r = recordEnd;
|
|
35032
|
+
}
|
|
35033
|
+
pos = batchEnd;
|
|
35034
|
+
}
|
|
35035
|
+
return null;
|
|
35036
|
+
}
|
|
35037
|
+
async function fetchAt(topic, offset) {
|
|
35038
|
+
const sock = await broker();
|
|
35039
|
+
const resp = await rpc(sock, fetchRequest(topic, offset));
|
|
35040
|
+
let pos = 4; // correlationId
|
|
35041
|
+
pos += 4; // throttleTimeMs
|
|
35042
|
+
const topicCount = resp.readInt32BE(pos); pos += 4;
|
|
35043
|
+
let rec = null;
|
|
35044
|
+
for (let t = 0; t < topicCount; t++) {
|
|
35045
|
+
const tl = resp.readInt16BE(pos); pos += 2 + tl;
|
|
35046
|
+
const pc = resp.readInt32BE(pos); pos += 4;
|
|
35047
|
+
for (let pi = 0; pi < pc; pi++) {
|
|
35048
|
+
pos += 4;
|
|
35049
|
+
const err = resp.readInt16BE(pos); pos += 2;
|
|
35050
|
+
pos += 8; pos += 8;
|
|
35051
|
+
const aborted = resp.readInt32BE(pos); pos += 4;
|
|
35052
|
+
if (aborted > 0) pos += aborted * 16;
|
|
35053
|
+
const recSize = resp.readInt32BE(pos); pos += 4;
|
|
35054
|
+
if (err !== 0 && err !== 3 && err !== 5) {
|
|
35055
|
+
throw new Error("Kafka rejected the fetch for topic " + topic + ": error code " + err);
|
|
35056
|
+
}
|
|
35057
|
+
if (err === 0 && recSize > 0) {
|
|
35058
|
+
const r = firstRecord(resp, pos, pos + recSize);
|
|
35059
|
+
if (r !== null) rec = r;
|
|
35060
|
+
}
|
|
35061
|
+
if (recSize > 0) pos += recSize;
|
|
35062
|
+
}
|
|
35063
|
+
}
|
|
35064
|
+
return rec;
|
|
35065
|
+
}
|
|
35066
|
+
|
|
35067
|
+
// \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
|
|
35068
|
+
function readNullableString(buf, pos) {
|
|
35069
|
+
const len = buf.readInt16BE(pos); pos += 2;
|
|
35070
|
+
if (len < 0) return { value: null, next: pos };
|
|
35071
|
+
return { value: buf.toString("utf-8", pos, pos + len), next: pos + len };
|
|
35072
|
+
}
|
|
35073
|
+
async function findCoordinator() {
|
|
35074
|
+
const sock = await broker();
|
|
35075
|
+
for (let attempt = 0; attempt < 30; attempt++) {
|
|
35076
|
+
const body = Buffer.concat([kstr(groupId), Buffer.from([0])]); // key_type 0 = group
|
|
35077
|
+
const resp = await rpc(sock, frame(10, 1, body));
|
|
35078
|
+
let pos = 4; // correlationId
|
|
35079
|
+
pos += 4; // throttle
|
|
35080
|
+
const err = resp.readInt16BE(pos); pos += 2;
|
|
35081
|
+
pos = readNullableString(resp, pos).next; // error_message
|
|
35082
|
+
pos += 4; // node_id
|
|
35083
|
+
const hostRes = readNullableString(resp, pos); pos = hostRes.next;
|
|
35084
|
+
const port = resp.readInt32BE(pos);
|
|
35085
|
+
if (err === 0 && hostRes.value) return { host: hostRes.value, port: port };
|
|
35086
|
+
if (err !== 14 && err !== 15) {
|
|
35087
|
+
throw new Error("Kafka FindCoordinator failed for group " + groupId + ": error code " + err);
|
|
35088
|
+
}
|
|
35089
|
+
await sleep(300);
|
|
35090
|
+
}
|
|
35091
|
+
throw new Error("Kafka group coordinator for " + groupId + " did not become available");
|
|
35092
|
+
}
|
|
35093
|
+
async function coordinator() {
|
|
35094
|
+
if (coordSock) return coordSock;
|
|
35095
|
+
const c = await findCoordinator();
|
|
35096
|
+
coordSock = await connect(c.host, c.port);
|
|
35097
|
+
return coordSock;
|
|
35098
|
+
}
|
|
35099
|
+
function dropCoordinator() {
|
|
35100
|
+
if (coordSock) { try { coordSock.destroy(); } catch (e) { /* ignore */ } }
|
|
35101
|
+
coordSock = null;
|
|
35102
|
+
}
|
|
35103
|
+
function offsetCommitRequest(topic, offset) {
|
|
35104
|
+
const body = Buffer.concat([
|
|
35105
|
+
kstr(groupId),
|
|
35106
|
+
int32(-1), // generation_id -1 (simple consumer)
|
|
35107
|
+
kstr(""), // member_id ""
|
|
35108
|
+
int64(-1n), // retention_time -1
|
|
35109
|
+
int32(1), kstr(topic), int32(1), int32(0), int64(BigInt(offset)), int16(-1),
|
|
35110
|
+
]);
|
|
35111
|
+
return frame(8, 2, body);
|
|
35112
|
+
}
|
|
35113
|
+
function parseOffsetCommit(resp) {
|
|
35114
|
+
let pos = 4;
|
|
35115
|
+
const tc = resp.readInt32BE(pos); pos += 4;
|
|
35116
|
+
if (tc === 0) return 16;
|
|
35117
|
+
const tl = resp.readInt16BE(pos); pos += 2 + tl;
|
|
35118
|
+
const pc = resp.readInt32BE(pos); pos += 4;
|
|
35119
|
+
if (pc === 0) return 16;
|
|
35120
|
+
pos += 4;
|
|
35121
|
+
return resp.readInt16BE(pos);
|
|
35122
|
+
}
|
|
35123
|
+
async function offsetCommit(topic, offset) {
|
|
35124
|
+
var err = 0;
|
|
35125
|
+
for (var attempt = 0; attempt < 10; attempt++) {
|
|
35126
|
+
if (attempt > 0) { dropCoordinator(); await new Promise(function (r) { setTimeout(r, 200 * attempt); }); }
|
|
35127
|
+
err = parseOffsetCommit(await rpc(await coordinator(), offsetCommitRequest(topic, offset)));
|
|
35128
|
+
if (COORDINATOR_ERRORS.indexOf(err) < 0) break;
|
|
35129
|
+
}
|
|
35130
|
+
if (err !== 0) throw new Error("Kafka rejected the offset commit for " + topic + ": error code " + err);
|
|
35131
|
+
}
|
|
35132
|
+
function offsetFetchRequest(topic) {
|
|
35133
|
+
const body = Buffer.concat([kstr(groupId), int32(1), kstr(topic), int32(1), int32(0)]);
|
|
35134
|
+
return frame(9, 1, body);
|
|
35135
|
+
}
|
|
35136
|
+
function parseOffsetFetch(resp) {
|
|
35137
|
+
let pos = 4;
|
|
35138
|
+
const tc = resp.readInt32BE(pos); pos += 4;
|
|
35139
|
+
if (tc === 0) return { offset: -1, err: 16 };
|
|
35140
|
+
const tl = resp.readInt16BE(pos); pos += 2 + tl;
|
|
35141
|
+
const pc = resp.readInt32BE(pos); pos += 4;
|
|
35142
|
+
if (pc === 0) return { offset: -1, err: 16 };
|
|
35143
|
+
pos += 4;
|
|
35144
|
+
const offset = Number(resp.readBigInt64BE(pos)); pos += 8;
|
|
35145
|
+
pos = readNullableString(resp, pos).next;
|
|
35146
|
+
const err = resp.readInt16BE(pos);
|
|
35147
|
+
return { offset: offset, err: err };
|
|
35148
|
+
}
|
|
35149
|
+
async function offsetFetch(topic) {
|
|
35150
|
+
var r = { offset: -1, err: 0 };
|
|
35151
|
+
for (var attempt = 0; attempt < 10; attempt++) {
|
|
35152
|
+
if (attempt > 0) { dropCoordinator(); await new Promise(function (res) { setTimeout(res, 200 * attempt); }); }
|
|
35153
|
+
r = parseOffsetFetch(await rpc(await coordinator(), offsetFetchRequest(topic)));
|
|
35154
|
+
if (COORDINATOR_ERRORS.indexOf(r.err) < 0) break;
|
|
35155
|
+
}
|
|
35156
|
+
if (r.err !== 0) throw new Error("Kafka rejected the offset fetch for " + topic + ": error code " + r.err);
|
|
35157
|
+
return r.offset < 0 ? 0 : r.offset;
|
|
35158
|
+
}
|
|
35159
|
+
|
|
35160
|
+
function int16(n) { const b = Buffer.alloc(2); b.writeInt16BE(n, 0); return b; }
|
|
35161
|
+
function int32(n) { const b = Buffer.alloc(4); b.writeInt32BE(n, 0); return b; }
|
|
35162
|
+
function int64(n) { const b = Buffer.alloc(8); b.writeBigInt64BE(BigInt(n), 0); return b; }
|
|
35163
|
+
function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
|
|
35164
|
+
|
|
35165
|
+
async function broker() {
|
|
35166
|
+
if (brokerSock) return brokerSock;
|
|
35167
|
+
const b = parseBroker(brokers);
|
|
35168
|
+
brokerSock = await connect(b.host, b.port);
|
|
35169
|
+
return brokerSock;
|
|
35170
|
+
}
|
|
35171
|
+
|
|
35172
|
+
// Resume from the committed offset on the FIRST read of a topic in this worker,
|
|
35173
|
+
// then advance the in-memory cursor; the committed offset only moves on a
|
|
35174
|
+
// commit, so it lags and a crash before commit replays (at-least-once).
|
|
35175
|
+
async function fetchNext(topic) {
|
|
35176
|
+
if (!(topic in offsets)) offsets[topic] = await offsetFetch(topic);
|
|
35177
|
+
const rec = await fetchAt(topic, offsets[topic]);
|
|
35178
|
+
if (rec === null) return null;
|
|
35179
|
+
offsets[topic] = rec.offset + 1;
|
|
35180
|
+
return rec;
|
|
35181
|
+
}
|
|
35182
|
+
|
|
35183
|
+
function encodeEnvelope(id, payload, attempts) {
|
|
35184
|
+
return JSON.stringify({ id: id, payload: payload, status: "pending", createdAt: new Date().toISOString(), attempts: attempts, delayUntil: null });
|
|
35185
|
+
}
|
|
35186
|
+
|
|
35187
|
+
async function handle(req) {
|
|
35188
|
+
const op = req.op;
|
|
35189
|
+
if (op === "publish") {
|
|
35190
|
+
await produce(req.topic, Buffer.from(req.value, "utf-8"));
|
|
35191
|
+
return { ok: true };
|
|
35192
|
+
}
|
|
35193
|
+
if (op === "dequeueRaw") {
|
|
35194
|
+
// The value exactly as it sits on the wire (a raw record stays its bare
|
|
35195
|
+
// bytes \u2014 tina4-nodejs#264), with no id/offset tracking. For wire
|
|
35196
|
+
// inspection; the facade consumes through "pop", which normalises + tracks.
|
|
35197
|
+
const rec = await fetchNext(req.topic);
|
|
35198
|
+
if (rec === null) return { ok: true, message: null };
|
|
35199
|
+
let decoded;
|
|
35200
|
+
try { decoded = JSON.parse(rec.value); } catch (e) { decoded = rec.value; }
|
|
35201
|
+
return { ok: true, message: decoded };
|
|
35202
|
+
}
|
|
35203
|
+
if (op === "pop") {
|
|
35204
|
+
let rec;
|
|
35205
|
+
try {
|
|
35206
|
+
rec = await fetchNext(req.topic);
|
|
35207
|
+
} catch (e) {
|
|
35208
|
+
// A malformed/short response runs the parser off the end (a RangeError);
|
|
35209
|
+
// anything else is a transport failure. Both name the topic so the cause
|
|
35210
|
+
// is findable, and neither reads as an empty queue (ADR: a real failure
|
|
35211
|
+
// must never look idle). Wording matches the Python/PHP backends.
|
|
35212
|
+
const range = (e instanceof RangeError) || /out of range|bounds/i.test((e && e.message) || "");
|
|
35213
|
+
if (range) throw new Error("Kafka fetch for topic " + req.topic + " returned an unreadable response: " + ((e && e.message) || e));
|
|
35214
|
+
throw new Error("Kafka fetch for topic " + req.topic + " failed: " + ((e && e.message) || e));
|
|
35215
|
+
}
|
|
35216
|
+
if (rec === null) return { ok: true, message: null };
|
|
35217
|
+
const coordinate = req.topic + ":0:" + rec.offset;
|
|
35218
|
+
let decoded;
|
|
35219
|
+
try { decoded = JSON.parse(rec.value); } catch (e) { decoded = null; }
|
|
35220
|
+
let message;
|
|
35221
|
+
let isEnvelope = false;
|
|
35222
|
+
if (decoded !== null && typeof decoded === "object" && !Array.isArray(decoded) && "payload" in decoded) {
|
|
35223
|
+
message = decoded;
|
|
35224
|
+
isEnvelope = true;
|
|
35225
|
+
if (!message.id) message.id = coordinate;
|
|
35226
|
+
} else {
|
|
35227
|
+
message = { id: coordinate, payload: decoded === null ? rec.value : decoded, status: "pending", attempts: 0 };
|
|
35228
|
+
}
|
|
35229
|
+
// The Job lifecycle (complete/fail/retry) routes by the record's own topic,
|
|
35230
|
+
// so it must be carried back (like the file/mongodb backends do).
|
|
35231
|
+
message.topic = req.topic;
|
|
35232
|
+
inFlight[String(message.id)] = { offset: rec.offset, value: rec.value, attempts: message.attempts || 0, isEnvelope: isEnvelope };
|
|
35233
|
+
return { ok: true, message: message };
|
|
35234
|
+
}
|
|
35235
|
+
if (op === "complete") {
|
|
35236
|
+
const rec = inFlight[String(req.id)];
|
|
35237
|
+
if (rec) { delete inFlight[String(req.id)]; await offsetCommit(req.topic, rec.offset + 1); }
|
|
35238
|
+
return { ok: true };
|
|
35239
|
+
}
|
|
35240
|
+
if (op === "fail") {
|
|
35241
|
+
const rec = inFlight[String(req.id)];
|
|
35242
|
+
if (rec) {
|
|
35243
|
+
delete inFlight[String(req.id)];
|
|
35244
|
+
const attempts = (rec.attempts || 0) + 1;
|
|
35245
|
+
const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
|
|
35246
|
+
const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
|
|
35247
|
+
if (attempts < req.maxRetries) {
|
|
35248
|
+
await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
|
|
35249
|
+
} else {
|
|
35250
|
+
await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: attempts, error: req.error }), "utf-8"));
|
|
35251
|
+
}
|
|
35252
|
+
await offsetCommit(req.topic, rec.offset + 1);
|
|
35253
|
+
}
|
|
35254
|
+
return { ok: true };
|
|
35255
|
+
}
|
|
35256
|
+
if (op === "reject") {
|
|
35257
|
+
const rec = inFlight[String(req.id)];
|
|
35258
|
+
if (rec) {
|
|
35259
|
+
delete inFlight[String(req.id)];
|
|
35260
|
+
const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
|
|
35261
|
+
const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
|
|
35262
|
+
await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: req.maxRetries, error: req.reason }), "utf-8"));
|
|
35263
|
+
await offsetCommit(req.topic, rec.offset + 1);
|
|
35264
|
+
}
|
|
35265
|
+
return { ok: true };
|
|
35266
|
+
}
|
|
35267
|
+
if (op === "retry") {
|
|
35268
|
+
const rec = inFlight[String(req.id)];
|
|
35269
|
+
if (rec) {
|
|
35270
|
+
delete inFlight[String(req.id)];
|
|
35271
|
+
const attempts = (rec.attempts || 0) + 1;
|
|
35272
|
+
const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
|
|
35273
|
+
const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
|
|
35274
|
+
await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
|
|
35275
|
+
await offsetCommit(req.topic, rec.offset + 1);
|
|
35276
|
+
}
|
|
35277
|
+
return { ok: true };
|
|
35278
|
+
}
|
|
35279
|
+
if (op === "deadLetters") {
|
|
35280
|
+
// Read the <topic>.dead_letter topic from the beginning; every record on it
|
|
35281
|
+
// is a dead letter by construction. A throwaway cursor that never commits,
|
|
35282
|
+
// so it does not disturb the main consume position.
|
|
35283
|
+
const dlq = req.topic + ".dead_letter";
|
|
35284
|
+
const out = [];
|
|
35285
|
+
let off = 0;
|
|
35286
|
+
for (;;) {
|
|
35287
|
+
const rec = await fetchAt(dlq, off);
|
|
35288
|
+
if (rec === null) break;
|
|
35289
|
+
off = rec.offset + 1;
|
|
35290
|
+
try { out.push(JSON.parse(rec.value)); } catch (e) { /* skip */ }
|
|
35291
|
+
if (out.length > 10000) break;
|
|
35292
|
+
}
|
|
35293
|
+
return { ok: true, deadLetters: out };
|
|
35294
|
+
}
|
|
35295
|
+
if (op === "close") {
|
|
35296
|
+
try { if (brokerSock) brokerSock.destroy(); } catch (e) { /* ignore */ }
|
|
35297
|
+
dropCoordinator();
|
|
35298
|
+
return { ok: true, closing: true };
|
|
35299
|
+
}
|
|
35300
|
+
return { ok: false, error: "unknown op " + op };
|
|
35301
|
+
}
|
|
35302
|
+
|
|
35303
|
+
parentPort.on("message", async function (req) {
|
|
35304
|
+
let res;
|
|
35305
|
+
try { res = await handle(req); }
|
|
35306
|
+
catch (e) { res = { ok: false, error: (e && e.message) ? e.message : String(e) }; }
|
|
35307
|
+
const bytes = Buffer.from(JSON.stringify(res), "utf-8");
|
|
35308
|
+
outBytes.set(bytes.subarray(0, outBytes.length), 0);
|
|
35309
|
+
Atomics.store(header, 1, Math.min(bytes.length, outBytes.length));
|
|
35310
|
+
Atomics.store(header, 0, 1);
|
|
35311
|
+
Atomics.notify(header, 0);
|
|
35312
|
+
});
|
|
35313
|
+
`;
|
|
35314
|
+
KafkaBackend = class _KafkaBackend {
|
|
35315
|
+
brokers;
|
|
35316
|
+
groupId;
|
|
35317
|
+
worker = null;
|
|
35318
|
+
sab = null;
|
|
35319
|
+
header = null;
|
|
35320
|
+
outBytes = null;
|
|
35321
|
+
static SAB_SIZE = 1 << 20;
|
|
35322
|
+
// 1 MiB (8-byte header + response bytes)
|
|
35323
|
+
static CALL_TIMEOUT_MS = 2e4;
|
|
35324
|
+
constructor(config) {
|
|
35325
|
+
const url = process.env.TINA4_QUEUE_URL;
|
|
35326
|
+
const fromUrl = url ? url.replace(/^kafka:\/\//, "") : void 0;
|
|
35327
|
+
this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
|
|
35328
|
+
this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
|
|
35329
|
+
}
|
|
35330
|
+
/** Resolved connection config — exposed for testing/introspection. */
|
|
35331
|
+
getConfig() {
|
|
35332
|
+
return { brokers: this.brokers, groupId: this.groupId };
|
|
35333
|
+
}
|
|
35334
|
+
securityConfig() {
|
|
35335
|
+
return kafkaSecurityConfig();
|
|
35336
|
+
}
|
|
35337
|
+
producerConfig() {
|
|
35338
|
+
return { "bootstrap.servers": this.brokers, "client.id": "tina4-nodejs", ...this.securityConfig() };
|
|
35339
|
+
}
|
|
35340
|
+
consumerConfig() {
|
|
35341
|
+
return {
|
|
35342
|
+
"bootstrap.servers": this.brokers,
|
|
35343
|
+
"client.id": "tina4-nodejs",
|
|
35344
|
+
"group.id": this.groupId,
|
|
35345
|
+
"auto.offset.reset": kafkaOffsetReset(),
|
|
35346
|
+
"enable.auto.commit": false,
|
|
35347
|
+
...this.securityConfig()
|
|
35348
|
+
};
|
|
35349
|
+
}
|
|
35350
|
+
/** Lazily start the persistent worker + its shared buffer. */
|
|
35351
|
+
ensureWorker() {
|
|
35352
|
+
if (this.worker) return;
|
|
35353
|
+
this.sab = new SharedArrayBuffer(_KafkaBackend.SAB_SIZE);
|
|
35354
|
+
this.header = new Int32Array(this.sab, 0, 2);
|
|
35355
|
+
this.outBytes = new Uint8Array(this.sab, 8);
|
|
35356
|
+
this.worker = new Worker2(WORKER_SRC, {
|
|
35357
|
+
eval: true,
|
|
35358
|
+
workerData: {
|
|
35359
|
+
brokers: this.brokers,
|
|
35360
|
+
groupId: this.groupId,
|
|
35361
|
+
security: this.securityConfig(),
|
|
35362
|
+
offsetReset: kafkaOffsetReset(),
|
|
35363
|
+
sab: this.sab
|
|
35364
|
+
}
|
|
35365
|
+
});
|
|
35366
|
+
this.worker.unref();
|
|
35367
|
+
}
|
|
35368
|
+
/** One synchronous request to the worker: post, block on Atomics.wait, read. */
|
|
35369
|
+
request(req2) {
|
|
35370
|
+
this.ensureWorker();
|
|
35371
|
+
const header = this.header;
|
|
35372
|
+
const outBytes = this.outBytes;
|
|
35373
|
+
Atomics.store(header, 0, 0);
|
|
35374
|
+
this.worker.postMessage(req2);
|
|
35375
|
+
const waited = Atomics.wait(header, 0, 0, _KafkaBackend.CALL_TIMEOUT_MS);
|
|
35376
|
+
if (waited === "timed-out") {
|
|
35377
|
+
throw new Error(`Kafka ${String(req2.op)} for topic ${String(req2.topic ?? "")} timed out after ${_KafkaBackend.CALL_TIMEOUT_MS}ms`);
|
|
35378
|
+
}
|
|
35379
|
+
const len = Atomics.load(header, 1);
|
|
35380
|
+
const json = Buffer.from(outBytes.buffer, outBytes.byteOffset, len).toString("utf-8");
|
|
35381
|
+
const res = JSON.parse(json);
|
|
35382
|
+
if (res.ok === false) {
|
|
35383
|
+
throw new Error(String(res.error ?? "unknown Kafka worker error"));
|
|
35384
|
+
}
|
|
35385
|
+
return res;
|
|
35386
|
+
}
|
|
35387
|
+
/**
|
|
35388
|
+
* Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
|
|
35389
|
+
* as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
|
|
35390
|
+
* consumer reading the topic gets the schema it expects; otherwise the Tina4
|
|
35391
|
+
* job envelope. pop() unwraps both shapes (payload ?? the whole record).
|
|
35392
|
+
*/
|
|
35393
|
+
static encodeJob(id, payload, raw) {
|
|
35394
|
+
if (raw) return JSON.stringify(payload);
|
|
35395
|
+
return JSON.stringify({
|
|
35396
|
+
id,
|
|
35397
|
+
payload,
|
|
35398
|
+
status: "pending",
|
|
35399
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
35400
|
+
attempts: 0,
|
|
35401
|
+
delayUntil: null
|
|
35402
|
+
});
|
|
35403
|
+
}
|
|
35404
|
+
push(queue, payload, _delay, _priority, raw = false) {
|
|
35405
|
+
const id = randomUUID6();
|
|
35406
|
+
const value = _KafkaBackend.encodeJob(id, payload, raw);
|
|
35407
|
+
this.request({ op: "publish", topic: queue, value });
|
|
35408
|
+
return id;
|
|
35409
|
+
}
|
|
35410
|
+
pop(queue) {
|
|
35411
|
+
const res = this.request({ op: "pop", topic: queue });
|
|
35412
|
+
const message = res.message;
|
|
35413
|
+
return message ?? null;
|
|
35414
|
+
}
|
|
35415
|
+
/**
|
|
35416
|
+
* Read the next record's value exactly as it sits on the wire — a Tina4
|
|
35417
|
+
* envelope as produced, a raw record (tina4-nodejs#264) as its bare bytes —
|
|
35418
|
+
* with no id/offset tracking. For a foreign consumer's view of the schema;
|
|
35419
|
+
* the queue facade consumes through pop(), which also normalises and tracks
|
|
35420
|
+
* the offset so complete()/fail() can commit it.
|
|
35421
|
+
*/
|
|
35422
|
+
dequeue(queue) {
|
|
35423
|
+
const res = this.request({ op: "dequeueRaw", topic: queue });
|
|
35424
|
+
return res.message ?? null;
|
|
35425
|
+
}
|
|
35426
|
+
/** Commit the record's offset so a completed job never replays (ADR-0022 d.4). */
|
|
35427
|
+
complete(queue, id) {
|
|
35428
|
+
this.request({ op: "complete", topic: queue, id });
|
|
35429
|
+
}
|
|
35430
|
+
/**
|
|
35431
|
+
* Record a failed attempt: re-produce the job with an incremented attempts
|
|
35432
|
+
* count while it has retries left, else produce it to the dead-letter topic;
|
|
35433
|
+
* commit the original offset either way (ADR-0022 decision 2).
|
|
35434
|
+
*/
|
|
35435
|
+
fail(queue, id, error2, maxRetries, _retryBackoff) {
|
|
35436
|
+
this.request({ op: "fail", topic: queue, id, error: error2, maxRetries });
|
|
35437
|
+
}
|
|
35438
|
+
/** Dead-letter the job now, no retry (ADR-0023 reject), then commit the offset. */
|
|
35439
|
+
reject(queue, id, reason, maxRetries) {
|
|
35440
|
+
this.request({ op: "reject", topic: queue, id, reason, maxRetries });
|
|
35441
|
+
}
|
|
35442
|
+
/** Re-produce the job (manual retry) and commit the original offset. */
|
|
35443
|
+
retry(queue, id, delaySeconds) {
|
|
35444
|
+
this.request({ op: "retry", topic: queue, id, delaySeconds: delaySeconds ?? 0 });
|
|
35445
|
+
return true;
|
|
35446
|
+
}
|
|
35447
|
+
/** Read the dead-letter topic for this queue (every record on it is a dead letter). */
|
|
35448
|
+
deadLetters(queue, _maxRetries) {
|
|
35449
|
+
const res = this.request({ op: "deadLetters", topic: queue });
|
|
35450
|
+
return res.deadLetters ?? [];
|
|
35451
|
+
}
|
|
35452
|
+
/**
|
|
35453
|
+
* Refuse rather than silently answer from the local file store. Kafka keeps no
|
|
35454
|
+
* queryable registry of failed jobs: a failed record is re-produced to a
|
|
35455
|
+
* dead-letter TOPIC and the original offset committed past, and a log cannot be
|
|
35456
|
+
* queried by job state. Returning [] would claim nothing has failed.
|
|
35457
|
+
*/
|
|
35458
|
+
failed(_queue, _maxRetries) {
|
|
35459
|
+
throw new Error(
|
|
35460
|
+
"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."
|
|
35461
|
+
);
|
|
35462
|
+
}
|
|
35463
|
+
/** Refuse for the same reason failed() does (no queryable failed registry). */
|
|
35464
|
+
retryFailed(_queue, _maxRetries) {
|
|
35465
|
+
throw new Error(
|
|
35466
|
+
"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."
|
|
35467
|
+
);
|
|
35468
|
+
}
|
|
35469
|
+
size(_queue) {
|
|
35470
|
+
return 0;
|
|
35471
|
+
}
|
|
35472
|
+
clear(_queue) {
|
|
35473
|
+
throw new Error(
|
|
35474
|
+
"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."
|
|
35475
|
+
);
|
|
35476
|
+
}
|
|
35477
|
+
purge(_queue, _status) {
|
|
35478
|
+
throw new Error(
|
|
35479
|
+
"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."
|
|
35480
|
+
);
|
|
35481
|
+
}
|
|
35482
|
+
/** Stop the worker and release the connection. Idempotent. */
|
|
35483
|
+
close() {
|
|
35484
|
+
if (!this.worker) return;
|
|
35485
|
+
try {
|
|
35486
|
+
this.request({ op: "close" });
|
|
35487
|
+
} catch {
|
|
35488
|
+
}
|
|
35489
|
+
void this.worker.terminate();
|
|
35490
|
+
this.worker = null;
|
|
35491
|
+
this.sab = null;
|
|
35492
|
+
this.header = null;
|
|
35493
|
+
this.outBytes = null;
|
|
35494
|
+
}
|
|
35495
|
+
};
|
|
35496
|
+
}
|
|
35497
|
+
});
|
|
35498
|
+
|
|
34552
35499
|
// src/job.ts
|
|
34553
35500
|
function createJob(data, queue) {
|
|
34554
35501
|
const job = {
|
|
@@ -34601,7 +35548,7 @@ var init_job = __esm({
|
|
|
34601
35548
|
// src/queueBackends/liteBackend.ts
|
|
34602
35549
|
import { mkdirSync as mkdirSync15, readdirSync as readdirSync12, readFileSync as readFileSync16, writeFileSync as writeFileSync11, unlinkSync as unlinkSync8, existsSync as existsSync19 } from "node:fs";
|
|
34603
35550
|
import { join as join23 } from "node:path";
|
|
34604
|
-
import { randomUUID as
|
|
35551
|
+
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
34605
35552
|
var LiteBackend;
|
|
34606
35553
|
var init_liteBackend = __esm({
|
|
34607
35554
|
"src/queueBackends/liteBackend.ts"() {
|
|
@@ -34668,7 +35615,7 @@ var init_liteBackend = __esm({
|
|
|
34668
35615
|
);
|
|
34669
35616
|
}
|
|
34670
35617
|
const dir = this.ensureDir(queue);
|
|
34671
|
-
const id =
|
|
35618
|
+
const id = randomUUID7();
|
|
34672
35619
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
34673
35620
|
const job = {
|
|
34674
35621
|
id,
|
|
@@ -35224,13 +36171,11 @@ function defaultVisibilityTimeout() {
|
|
|
35224
36171
|
return Number.isFinite(parsed) ? parsed : 300;
|
|
35225
36172
|
}
|
|
35226
36173
|
function unsupportedBrokerMessage(backendName) {
|
|
35227
|
-
const broker = backendName === "kafka" ? "Kafka" : "RabbitMQ";
|
|
35228
|
-
const lost = backendName === "kafka" ? "every pop() re-read offset 0, so the topic could never drain" : "pop() destroyed the message with no acknowledgement, so a consumer that died lost the job";
|
|
35229
36174
|
return `Queue backend "${backendName}" is not available in tina4-nodejs.
|
|
35230
36175
|
|
|
35231
|
-
Reason: the
|
|
36176
|
+
Reason: the RabbitMQ backend runs each operation in a separate child process, so no connection survives between pop() and complete(). Acknowledgement is therefore impossible, and pop() destroyed the message with no acknowledgement, so a consumer that died lost the job. It was losing work silently, so it now refuses instead.
|
|
35232
36177
|
|
|
35233
|
-
Use backend "
|
|
36178
|
+
Use backend "kafka" (now a persistent connection: at-least-once, drains, survives restarts), "mongodb" (at-least-once, real reservation + visibility timeout) or the default "file" backend. tina4-python, tina4-php and tina4-ruby still offer RabbitMQ.
|
|
35234
36179
|
|
|
35235
36180
|
Tracking: ADR-0022 in tina4-documentation/plan/v3/DECISIONS.md, findings in plan/v3/features/048-queue-backends.md.`;
|
|
35236
36181
|
}
|
|
@@ -35239,6 +36184,7 @@ var init_queue = __esm({
|
|
|
35239
36184
|
"src/queue.ts"() {
|
|
35240
36185
|
"use strict";
|
|
35241
36186
|
init_mongoBackend();
|
|
36187
|
+
init_kafkaBackend();
|
|
35242
36188
|
init_liteBackend();
|
|
35243
36189
|
init_job();
|
|
35244
36190
|
init_liteBackend();
|
|
@@ -35259,7 +36205,7 @@ var init_queue = __esm({
|
|
|
35259
36205
|
* - new Queue("mongodb", { path: "data/queue" }) // legacy
|
|
35260
36206
|
* - new Queue() // file backend, default topic
|
|
35261
36207
|
*
|
|
35262
|
-
* Throws on backend "rabbitmq"
|
|
36208
|
+
* Throws on backend "rabbitmq" (ADR-0022); "kafka" is now supported.
|
|
35263
36209
|
*/
|
|
35264
36210
|
constructor(backendOrConfig, config) {
|
|
35265
36211
|
let resolvedConfig = {};
|
|
@@ -35277,8 +36223,10 @@ var init_queue = __esm({
|
|
|
35277
36223
|
this._retryBackoff = resolvedConfig.retryBackoff ?? 0;
|
|
35278
36224
|
this._visibilityTimeout = resolvedConfig.visibilityTimeout ?? defaultVisibilityTimeout();
|
|
35279
36225
|
this.liteBackend = new LiteBackend(this.basePath, this._visibilityTimeout);
|
|
35280
|
-
if (this.backendName === "rabbitmq"
|
|
36226
|
+
if (this.backendName === "rabbitmq") {
|
|
35281
36227
|
throw new Error(unsupportedBrokerMessage(this.backendName));
|
|
36228
|
+
} else if (this.backendName === "kafka") {
|
|
36229
|
+
this.externalBackend = new KafkaBackend({ visibilityTimeout: this._visibilityTimeout });
|
|
35282
36230
|
} else if (this.backendName === "mongodb" || this.backendName === "mongo") {
|
|
35283
36231
|
this.externalBackend = new MongoBackend2({ visibilityTimeout: this._visibilityTimeout });
|
|
35284
36232
|
} else if (!["file", "default", "lite"].includes(this.backendName)) {
|
|
@@ -38346,10 +39294,10 @@ function devGitStatusLabel(code) {
|
|
|
38346
39294
|
async function devGitInfo(root) {
|
|
38347
39295
|
const empty = { branch: "", gitRoot: null, status: /* @__PURE__ */ new Map() };
|
|
38348
39296
|
try {
|
|
38349
|
-
const { execFileSync:
|
|
39297
|
+
const { execFileSync: execFileSync6 } = await import("node:child_process");
|
|
38350
39298
|
const git = (args) => {
|
|
38351
39299
|
try {
|
|
38352
|
-
return
|
|
39300
|
+
return execFileSync6("git", args, { cwd: root, timeout: 3e3, encoding: "utf-8" }).toString();
|
|
38353
39301
|
} catch {
|
|
38354
39302
|
return null;
|
|
38355
39303
|
}
|
|
@@ -40176,9 +41124,9 @@ var init_devAdmin = __esm({
|
|
|
40176
41124
|
return;
|
|
40177
41125
|
}
|
|
40178
41126
|
try {
|
|
40179
|
-
const { execFileSync:
|
|
41127
|
+
const { execFileSync: execFileSync6 } = await import("node:child_process");
|
|
40180
41128
|
const args = ["install", dev ? "--save-dev" : "--save", pkg];
|
|
40181
|
-
const output =
|
|
41129
|
+
const output = execFileSync6("npm", args, {
|
|
40182
41130
|
cwd: resolve16(process.cwd()),
|
|
40183
41131
|
timeout: 12e4,
|
|
40184
41132
|
encoding: "utf-8"
|
|
@@ -40190,15 +41138,15 @@ var init_devAdmin = __esm({
|
|
|
40190
41138
|
};
|
|
40191
41139
|
handleGitStatus = async (_req, res) => {
|
|
40192
41140
|
try {
|
|
40193
|
-
const { execFileSync:
|
|
41141
|
+
const { execFileSync: execFileSync6 } = await import("node:child_process");
|
|
40194
41142
|
const cwd = resolve16(process.cwd());
|
|
40195
41143
|
try {
|
|
40196
|
-
|
|
41144
|
+
execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
|
|
40197
41145
|
} catch {
|
|
40198
41146
|
res.json({ error: "Not a git repository" }, 400);
|
|
40199
41147
|
return;
|
|
40200
41148
|
}
|
|
40201
|
-
const run = (args) =>
|
|
41149
|
+
const run = (args) => execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
|
|
40202
41150
|
res.json({
|
|
40203
41151
|
branch: run(["branch", "--show-current"]),
|
|
40204
41152
|
status: run(["status", "--porcelain"]).split(/\r?\n/).filter((l) => l),
|
|
@@ -40328,8 +41276,8 @@ var init_devAdmin = __esm({
|
|
|
40328
41276
|
return;
|
|
40329
41277
|
}
|
|
40330
41278
|
try {
|
|
40331
|
-
const { execFileSync:
|
|
40332
|
-
const output =
|
|
41279
|
+
const { execFileSync: execFileSync6 } = await import("node:child_process");
|
|
41280
|
+
const output = execFileSync6("npx", ["tina4nodejs", "generate", kind, name], {
|
|
40333
41281
|
cwd: resolve16(process.cwd()),
|
|
40334
41282
|
timeout: 3e4,
|
|
40335
41283
|
encoding: "utf-8"
|
|
@@ -40775,6 +41723,359 @@ var init_background = __esm({
|
|
|
40775
41723
|
}
|
|
40776
41724
|
});
|
|
40777
41725
|
|
|
41726
|
+
// src/tcp.ts
|
|
41727
|
+
import { createServer as createServer3 } from "node:net";
|
|
41728
|
+
function resolveMaxBacklog(explicit) {
|
|
41729
|
+
if (explicit !== void 0) return explicit > 0 ? explicit : DEFAULT_MAX_BACKLOG;
|
|
41730
|
+
const raw = (process.env.TINA4_TCP_MAX_BACKLOG ?? "").trim();
|
|
41731
|
+
if (raw === "") return DEFAULT_MAX_BACKLOG;
|
|
41732
|
+
const value = Number.parseInt(raw, 10);
|
|
41733
|
+
return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_BACKLOG;
|
|
41734
|
+
}
|
|
41735
|
+
function tcpService(port, options = {}) {
|
|
41736
|
+
const service = new TcpService(port, options);
|
|
41737
|
+
services.set(service.name, service);
|
|
41738
|
+
return service;
|
|
41739
|
+
}
|
|
41740
|
+
function tcp(name = "default") {
|
|
41741
|
+
const service = services.get(name);
|
|
41742
|
+
if (!service) {
|
|
41743
|
+
const known = services.size === 0 ? "(none registered)" : [...services.keys()].join(", ");
|
|
41744
|
+
throw new Error(`no tcp_service named '${name}' is registered; known services: ${known}`);
|
|
41745
|
+
}
|
|
41746
|
+
return service;
|
|
41747
|
+
}
|
|
41748
|
+
function registeredTcpServices() {
|
|
41749
|
+
return [...services.values()];
|
|
41750
|
+
}
|
|
41751
|
+
function clearTcpRegistry() {
|
|
41752
|
+
services.clear();
|
|
41753
|
+
}
|
|
41754
|
+
async function startAllTcpServices(host = "0.0.0.0") {
|
|
41755
|
+
for (const service of registeredTcpServices()) {
|
|
41756
|
+
try {
|
|
41757
|
+
await service.start(host);
|
|
41758
|
+
} catch (error2) {
|
|
41759
|
+
Log.error(`tcp_service '${service.name}' failed to start: ${String(error2)}`);
|
|
41760
|
+
}
|
|
41761
|
+
}
|
|
41762
|
+
}
|
|
41763
|
+
function stopAcceptingAllTcpServices() {
|
|
41764
|
+
for (const service of registeredTcpServices()) {
|
|
41765
|
+
try {
|
|
41766
|
+
service.stopAccepting();
|
|
41767
|
+
} catch (error2) {
|
|
41768
|
+
Log.error(`tcp_service '${service.name}' stop-accepting failed: ${String(error2)}`);
|
|
41769
|
+
}
|
|
41770
|
+
}
|
|
41771
|
+
}
|
|
41772
|
+
async function drainAllTcpServices() {
|
|
41773
|
+
for (const service of registeredTcpServices()) {
|
|
41774
|
+
try {
|
|
41775
|
+
await service.drain();
|
|
41776
|
+
} catch (error2) {
|
|
41777
|
+
Log.error(`tcp_service '${service.name}' drain failed: ${String(error2)}`);
|
|
41778
|
+
}
|
|
41779
|
+
}
|
|
41780
|
+
}
|
|
41781
|
+
var DEFAULT_MAX_BACKLOG, TcpConnection, TcpService, services;
|
|
41782
|
+
var init_tcp = __esm({
|
|
41783
|
+
"src/tcp.ts"() {
|
|
41784
|
+
"use strict";
|
|
41785
|
+
init_logger();
|
|
41786
|
+
DEFAULT_MAX_BACKLOG = 1 << 20;
|
|
41787
|
+
TcpConnection = class {
|
|
41788
|
+
constructor(socket, service) {
|
|
41789
|
+
this.socket = socket;
|
|
41790
|
+
this.service = service;
|
|
41791
|
+
this.remoteAddr = `${socket.remoteAddress ?? ""}:${socket.remotePort ?? 0}`;
|
|
41792
|
+
}
|
|
41793
|
+
socket;
|
|
41794
|
+
service;
|
|
41795
|
+
/** The registry id (the IMEI), or null until identify() is called. */
|
|
41796
|
+
id = null;
|
|
41797
|
+
/** Per-connection mutable state bag — the app's parse buffer, auth flag. */
|
|
41798
|
+
context = {};
|
|
41799
|
+
/** The raw TCP peer address ("127.0.0.1:54321"), never a forwarded header. */
|
|
41800
|
+
remoteAddr;
|
|
41801
|
+
lastActivity = Date.now();
|
|
41802
|
+
lineBuffer = Buffer.alloc(0);
|
|
41803
|
+
closed = false;
|
|
41804
|
+
closeFired = false;
|
|
41805
|
+
get isClosed() {
|
|
41806
|
+
return this.closed;
|
|
41807
|
+
}
|
|
41808
|
+
/**
|
|
41809
|
+
* Register this live connection under an app-chosen id (the IMEI). A second
|
|
41810
|
+
* connection identifying with the same id SUPERSEDES the first in the
|
|
41811
|
+
* registry — exactly a device that dropped and reconnected.
|
|
41812
|
+
*/
|
|
41813
|
+
identify(appId) {
|
|
41814
|
+
this.id = String(appId);
|
|
41815
|
+
this.service._registerId(this.id, this);
|
|
41816
|
+
return this;
|
|
41817
|
+
}
|
|
41818
|
+
/**
|
|
41819
|
+
* Write raw bytes to THIS socket. Returns true when queued/sent, false when
|
|
41820
|
+
* the connection is closed or dropped for backpressure. A stalled reader
|
|
41821
|
+
* (never draining) is bounded: once more than the service's maxBacklog bytes
|
|
41822
|
+
* are outstanding, the connection is dropped rather than buffered without end
|
|
41823
|
+
* (mirrors the WebSocket TINA4_WS_MAX_BACKLOG posture).
|
|
41824
|
+
*/
|
|
41825
|
+
send(data) {
|
|
41826
|
+
if (this.closed) return false;
|
|
41827
|
+
const buffer = typeof data === "string" ? Buffer.from(data) : data;
|
|
41828
|
+
this.socket.write(buffer);
|
|
41829
|
+
if (this.socket.writableLength > this.service.maxBacklog) {
|
|
41830
|
+
Log.warning(
|
|
41831
|
+
`tcp_service '${this.service.name}': dropping a stalled reader \u2014 ${this.socket.writableLength} bytes queued exceeds the ${this.service.maxBacklog}-byte backlog limit`
|
|
41832
|
+
);
|
|
41833
|
+
this.close();
|
|
41834
|
+
return false;
|
|
41835
|
+
}
|
|
41836
|
+
return true;
|
|
41837
|
+
}
|
|
41838
|
+
/**
|
|
41839
|
+
* Close this connection. on_close fires exactly once (from the socket's close
|
|
41840
|
+
* event) and the registry entry is removed.
|
|
41841
|
+
*/
|
|
41842
|
+
close() {
|
|
41843
|
+
if (this.closed) return;
|
|
41844
|
+
this.closed = true;
|
|
41845
|
+
try {
|
|
41846
|
+
this.socket.end(() => this.socket.destroy());
|
|
41847
|
+
} catch {
|
|
41848
|
+
this.socket.destroy();
|
|
41849
|
+
}
|
|
41850
|
+
}
|
|
41851
|
+
/** @internal mark activity for the idle reaper. */
|
|
41852
|
+
_touch() {
|
|
41853
|
+
this.lastActivity = Date.now();
|
|
41854
|
+
}
|
|
41855
|
+
/** @internal fire on_close exactly once (called from the service removal path). */
|
|
41856
|
+
_fireClose() {
|
|
41857
|
+
if (this.closeFired) return;
|
|
41858
|
+
this.closeFired = true;
|
|
41859
|
+
this.closed = true;
|
|
41860
|
+
const handler = this.service._callbacks.onClose;
|
|
41861
|
+
if (!handler) return;
|
|
41862
|
+
try {
|
|
41863
|
+
void Promise.resolve(handler(this)).catch((error2) => {
|
|
41864
|
+
Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error2)}`);
|
|
41865
|
+
});
|
|
41866
|
+
} catch (error2) {
|
|
41867
|
+
Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error2)}`);
|
|
41868
|
+
}
|
|
41869
|
+
}
|
|
41870
|
+
};
|
|
41871
|
+
TcpService = class {
|
|
41872
|
+
name;
|
|
41873
|
+
port;
|
|
41874
|
+
maxBacklog;
|
|
41875
|
+
/** @internal the callback bag, read by TcpConnection. */
|
|
41876
|
+
_callbacks;
|
|
41877
|
+
idleTimeout;
|
|
41878
|
+
maxConnections;
|
|
41879
|
+
connections = /* @__PURE__ */ new Set();
|
|
41880
|
+
byId = /* @__PURE__ */ new Map();
|
|
41881
|
+
server = null;
|
|
41882
|
+
owner = false;
|
|
41883
|
+
boundPortValue = null;
|
|
41884
|
+
reaper = null;
|
|
41885
|
+
constructor(port, options = {}) {
|
|
41886
|
+
this.port = port;
|
|
41887
|
+
this.name = options.name ?? "default";
|
|
41888
|
+
this._callbacks = {
|
|
41889
|
+
onConnect: options.onConnect,
|
|
41890
|
+
onData: options.onData,
|
|
41891
|
+
onClose: options.onClose,
|
|
41892
|
+
onLine: options.onLine
|
|
41893
|
+
};
|
|
41894
|
+
this.idleTimeout = options.idleTimeout ?? 0;
|
|
41895
|
+
this.maxConnections = options.maxConnections ?? null;
|
|
41896
|
+
this.maxBacklog = resolveMaxBacklog(options.maxBacklog);
|
|
41897
|
+
}
|
|
41898
|
+
get isOwner() {
|
|
41899
|
+
return this.owner;
|
|
41900
|
+
}
|
|
41901
|
+
/** The port actually bound (resolves an ephemeral port=0 to the real one). */
|
|
41902
|
+
get boundPort() {
|
|
41903
|
+
return this.boundPortValue ?? this.port;
|
|
41904
|
+
}
|
|
41905
|
+
count() {
|
|
41906
|
+
return this.connections.size;
|
|
41907
|
+
}
|
|
41908
|
+
// ── Registry (D4 — server -> device push) ──────────────────────────────────
|
|
41909
|
+
/** @internal */
|
|
41910
|
+
_registerId(appId, conn) {
|
|
41911
|
+
this.byId.set(appId, conn);
|
|
41912
|
+
}
|
|
41913
|
+
/** The live connection for an app id, or null if unknown or closed. */
|
|
41914
|
+
connection(appId) {
|
|
41915
|
+
const conn = this.byId.get(String(appId));
|
|
41916
|
+
if (!conn || conn.isClosed) return null;
|
|
41917
|
+
return conn;
|
|
41918
|
+
}
|
|
41919
|
+
/**
|
|
41920
|
+
* Write bytes to exactly the connection identified by appId. A send to an
|
|
41921
|
+
* unknown or closed id is a NO-OP that returns false — never a throw.
|
|
41922
|
+
*/
|
|
41923
|
+
sendTo(appId, data) {
|
|
41924
|
+
const conn = this.connection(appId);
|
|
41925
|
+
if (!conn) return false;
|
|
41926
|
+
return conn.send(data);
|
|
41927
|
+
}
|
|
41928
|
+
/** Write bytes to every live connection. Returns how many received it. */
|
|
41929
|
+
broadcast(data) {
|
|
41930
|
+
let delivered = 0;
|
|
41931
|
+
for (const conn of [...this.connections]) {
|
|
41932
|
+
if (conn.send(data)) delivered += 1;
|
|
41933
|
+
}
|
|
41934
|
+
return delivered;
|
|
41935
|
+
}
|
|
41936
|
+
// ── Lifecycle ───────────────────────────────────────────────────────────────
|
|
41937
|
+
/**
|
|
41938
|
+
* Bind the listener on host:port on the event loop. SO_REUSEPORT is OFF, so
|
|
41939
|
+
* under a multi-worker deployment exactly ONE worker wins the bind; a worker
|
|
41940
|
+
* that finds the port already bound skips silently (single-owner, D1).
|
|
41941
|
+
* Resolves true when THIS call bound the port.
|
|
41942
|
+
*/
|
|
41943
|
+
start(host = "0.0.0.0") {
|
|
41944
|
+
if (this.server) return Promise.resolve(this.owner);
|
|
41945
|
+
return new Promise((resolve21) => {
|
|
41946
|
+
const server = createServer3((socket) => this.handleConnection(socket));
|
|
41947
|
+
this.server = server;
|
|
41948
|
+
const onError = (error2) => {
|
|
41949
|
+
if (error2.code === "EADDRINUSE" || error2.code === "EADDRNOTAVAIL") {
|
|
41950
|
+
this.owner = false;
|
|
41951
|
+
this.server = null;
|
|
41952
|
+
Log.info(
|
|
41953
|
+
`tcp_service '${this.name}' port ${this.port} is already bound by another worker \u2014 single-owner, this worker will not bind (${error2.code})`
|
|
41954
|
+
);
|
|
41955
|
+
resolve21(false);
|
|
41956
|
+
return;
|
|
41957
|
+
}
|
|
41958
|
+
Log.error(`tcp_service '${this.name}' failed to start: ${error2.message}`);
|
|
41959
|
+
this.server = null;
|
|
41960
|
+
resolve21(false);
|
|
41961
|
+
};
|
|
41962
|
+
server.once("error", onError);
|
|
41963
|
+
server.listen(this.port, host, () => {
|
|
41964
|
+
server.off("error", onError);
|
|
41965
|
+
server.on("error", (error2) => Log.error(`tcp_service '${this.name}' error: ${String(error2)}`));
|
|
41966
|
+
this.owner = true;
|
|
41967
|
+
const addr = server.address();
|
|
41968
|
+
this.boundPortValue = typeof addr === "object" && addr ? addr.port : this.port;
|
|
41969
|
+
Log.info(`tcp_service '${this.name}' listening on ${host}:${this.boundPortValue}`);
|
|
41970
|
+
this.startReaper();
|
|
41971
|
+
resolve21(true);
|
|
41972
|
+
});
|
|
41973
|
+
});
|
|
41974
|
+
}
|
|
41975
|
+
handleConnection(socket) {
|
|
41976
|
+
if (this.maxConnections !== null && this.connections.size >= this.maxConnections) {
|
|
41977
|
+
socket.destroy();
|
|
41978
|
+
return;
|
|
41979
|
+
}
|
|
41980
|
+
const conn = new TcpConnection(socket, this);
|
|
41981
|
+
this.connections.add(conn);
|
|
41982
|
+
socket.on("data", (chunk) => {
|
|
41983
|
+
socket.pause();
|
|
41984
|
+
void this.dispatch(conn, chunk).finally(() => {
|
|
41985
|
+
if (!conn.isClosed) socket.resume();
|
|
41986
|
+
});
|
|
41987
|
+
});
|
|
41988
|
+
socket.on("close", () => this.remove(conn));
|
|
41989
|
+
socket.on("error", () => {
|
|
41990
|
+
});
|
|
41991
|
+
const onConnect = this._callbacks.onConnect;
|
|
41992
|
+
if (onConnect) {
|
|
41993
|
+
void Promise.resolve(onConnect(conn)).catch((error2) => {
|
|
41994
|
+
Log.error(`tcp_service '${this.name}' onConnect error: ${String(error2)}`);
|
|
41995
|
+
});
|
|
41996
|
+
}
|
|
41997
|
+
}
|
|
41998
|
+
async dispatch(conn, chunk) {
|
|
41999
|
+
conn._touch();
|
|
42000
|
+
const { onData, onLine } = this._callbacks;
|
|
42001
|
+
if (onData) {
|
|
42002
|
+
try {
|
|
42003
|
+
await onData(conn, chunk);
|
|
42004
|
+
} catch (error2) {
|
|
42005
|
+
Log.error(`tcp_service '${this.name}' onData error: ${String(error2)}`);
|
|
42006
|
+
}
|
|
42007
|
+
}
|
|
42008
|
+
if (onLine) {
|
|
42009
|
+
conn.lineBuffer = Buffer.concat([conn.lineBuffer, chunk]);
|
|
42010
|
+
let newline = conn.lineBuffer.indexOf(10);
|
|
42011
|
+
while (newline !== -1) {
|
|
42012
|
+
let line = conn.lineBuffer.subarray(0, newline);
|
|
42013
|
+
conn.lineBuffer = conn.lineBuffer.subarray(newline + 1);
|
|
42014
|
+
if (line.length > 0 && line[line.length - 1] === 13) {
|
|
42015
|
+
line = line.subarray(0, line.length - 1);
|
|
42016
|
+
}
|
|
42017
|
+
try {
|
|
42018
|
+
await onLine(conn, line);
|
|
42019
|
+
} catch (error2) {
|
|
42020
|
+
Log.error(`tcp_service '${this.name}' onLine error: ${String(error2)}`);
|
|
42021
|
+
}
|
|
42022
|
+
newline = conn.lineBuffer.indexOf(10);
|
|
42023
|
+
}
|
|
42024
|
+
}
|
|
42025
|
+
}
|
|
42026
|
+
/** @internal remove a connection and fire on_close exactly once. */
|
|
42027
|
+
remove(conn) {
|
|
42028
|
+
const existed = this.connections.delete(conn);
|
|
42029
|
+
if (conn.id !== null && this.byId.get(conn.id) === conn) {
|
|
42030
|
+
this.byId.delete(conn.id);
|
|
42031
|
+
}
|
|
42032
|
+
if (existed) conn._fireClose();
|
|
42033
|
+
}
|
|
42034
|
+
// ── Idle reaper (D1 consumer shape — default OFF) ───────────────────────────
|
|
42035
|
+
startReaper() {
|
|
42036
|
+
if (this.idleTimeout <= 0 || this.reaper) return;
|
|
42037
|
+
const intervalMs = Math.max(50, Math.min(1e3, this.idleTimeout / 2 * 1e3));
|
|
42038
|
+
this.reaper = setInterval(() => this.reapIdle(), intervalMs);
|
|
42039
|
+
this.reaper.unref();
|
|
42040
|
+
}
|
|
42041
|
+
reapIdle() {
|
|
42042
|
+
const now = Date.now();
|
|
42043
|
+
const limitMs = this.idleTimeout * 1e3;
|
|
42044
|
+
for (const conn of [...this.connections]) {
|
|
42045
|
+
if (now - conn.lastActivity >= limitMs) conn.close();
|
|
42046
|
+
}
|
|
42047
|
+
}
|
|
42048
|
+
/** Stop accepting new connections (close the listener). Live conns stay. */
|
|
42049
|
+
stopAccepting() {
|
|
42050
|
+
if (this.reaper) {
|
|
42051
|
+
clearInterval(this.reaper);
|
|
42052
|
+
this.reaper = null;
|
|
42053
|
+
}
|
|
42054
|
+
if (this.server && this.owner) {
|
|
42055
|
+
this.server.close();
|
|
42056
|
+
}
|
|
42057
|
+
}
|
|
42058
|
+
/** Close every live connection (firing on_close) and release the listener. */
|
|
42059
|
+
async drain() {
|
|
42060
|
+
this.stopAccepting();
|
|
42061
|
+
for (const conn of [...this.connections]) conn.close();
|
|
42062
|
+
if (this.server) {
|
|
42063
|
+
await new Promise((resolve21) => {
|
|
42064
|
+
this.server.close(() => resolve21());
|
|
42065
|
+
this.server.unref();
|
|
42066
|
+
}).catch(() => void 0);
|
|
42067
|
+
this.server = null;
|
|
42068
|
+
}
|
|
42069
|
+
}
|
|
42070
|
+
/** Stop accepting and drain in one call (used by direct callers/tests). */
|
|
42071
|
+
async stop() {
|
|
42072
|
+
await this.drain();
|
|
42073
|
+
}
|
|
42074
|
+
};
|
|
42075
|
+
services = /* @__PURE__ */ new Map();
|
|
42076
|
+
}
|
|
42077
|
+
});
|
|
42078
|
+
|
|
40778
42079
|
// src/events.ts
|
|
40779
42080
|
var events_exports = {};
|
|
40780
42081
|
__export(events_exports, {
|
|
@@ -42427,6 +43728,12 @@ async function invokeRouteHandler(match, req2, res) {
|
|
|
42427
43728
|
if (args.length === 0) return await match.handler();
|
|
42428
43729
|
return await match.handler(...args);
|
|
42429
43730
|
}
|
|
43731
|
+
function coerceHandlerResult(res, result) {
|
|
43732
|
+
if (res.raw.writableEnded || res.raw.headersSent) return;
|
|
43733
|
+
if (result === void 0 || result === null) return;
|
|
43734
|
+
if (result === res) return;
|
|
43735
|
+
res(result);
|
|
43736
|
+
}
|
|
42430
43737
|
async function renderIfTemplateRoute(match, res, result) {
|
|
42431
43738
|
if (res.raw.writableEnded) return;
|
|
42432
43739
|
if (!match.template) return;
|
|
@@ -42446,7 +43753,9 @@ async function runMatchedRoute(ctx) {
|
|
|
42446
43753
|
handlerSkipped = !proceed || res.raw.writableEnded;
|
|
42447
43754
|
}
|
|
42448
43755
|
if (!handlerSkipped) {
|
|
42449
|
-
|
|
43756
|
+
const result = await invokeRouteHandler(match, req2, res);
|
|
43757
|
+
await renderIfTemplateRoute(match, res, result);
|
|
43758
|
+
coerceHandlerResult(res, result);
|
|
42450
43759
|
}
|
|
42451
43760
|
const afterMiddleware = [...ctx.allGlobalMiddleware, ...routeMiddlewareClasses];
|
|
42452
43761
|
if (afterMiddleware.length > 0) {
|
|
@@ -42983,7 +44292,7 @@ async function startServer(config) {
|
|
|
42983
44292
|
server.on("upgrade", (req2, socket, head) => {
|
|
42984
44293
|
const upPath = (req2.url ?? "/").split("?")[0];
|
|
42985
44294
|
if (isDevMode() && upPath === "/__dev_reload") {
|
|
42986
|
-
if (!devHostAllowed(req2.headers.host)) {
|
|
44295
|
+
if (!devHostAllowed(req2.headers.host) || !devPeerAllowed(socket.remoteAddress)) {
|
|
42987
44296
|
try {
|
|
42988
44297
|
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
42989
44298
|
socket.destroy();
|
|
@@ -43007,6 +44316,7 @@ async function startServer(config) {
|
|
|
43007
44316
|
server.listen(port, host, async () => {
|
|
43008
44317
|
if (!cluster.isWorker) writePidfile(port);
|
|
43009
44318
|
const siblingServers = await startLoopbackSiblings(port, host, dispatch);
|
|
44319
|
+
await startAllTcpServices(host);
|
|
43010
44320
|
const displayHost = host === "0.0.0.0" ? "localhost" : host;
|
|
43011
44321
|
const isDebug = isTruthy(process.env.TINA4_DEBUG);
|
|
43012
44322
|
const logLevel = (process.env.TINA4_LOG_LEVEL ?? "DEBUG").toUpperCase();
|
|
@@ -43097,6 +44407,8 @@ ${reset2}
|
|
|
43097
44407
|
if (wsClosed > 0) {
|
|
43098
44408
|
Log.info(`Closed ${wsClosed} WebSocket connection(s) with 1001 going away`);
|
|
43099
44409
|
}
|
|
44410
|
+
stopAcceptingAllTcpServices();
|
|
44411
|
+
await drainAllTcpServices();
|
|
43100
44412
|
const budgetSeconds = shutdownTimeoutSeconds();
|
|
43101
44413
|
let timer;
|
|
43102
44414
|
const outcome = await Promise.race([
|
|
@@ -43139,6 +44451,8 @@ ${reset2}
|
|
|
43139
44451
|
process.off("SIGTERM", onSigterm);
|
|
43140
44452
|
process.off("SIGINT", onSigint);
|
|
43141
44453
|
stopAllBackgroundTasks();
|
|
44454
|
+
stopAcceptingAllTcpServices();
|
|
44455
|
+
void drainAllTcpServices();
|
|
43142
44456
|
if (aiServer) aiServer.close();
|
|
43143
44457
|
server.close();
|
|
43144
44458
|
for (const sibling of siblingServers) {
|
|
@@ -43267,6 +44581,7 @@ var init_server = __esm({
|
|
|
43267
44581
|
init_feedback();
|
|
43268
44582
|
init_i18n();
|
|
43269
44583
|
init_background();
|
|
44584
|
+
init_tcp();
|
|
43270
44585
|
init_version();
|
|
43271
44586
|
__filename = fileURLToPath8(import.meta.url);
|
|
43272
44587
|
__dirname = dirname15(__filename);
|
|
@@ -45625,7 +46940,7 @@ import net4 from "node:net";
|
|
|
45625
46940
|
import tls2 from "node:tls";
|
|
45626
46941
|
import { readFileSync as readFileSync25 } from "node:fs";
|
|
45627
46942
|
import { basename as basename7 } from "node:path";
|
|
45628
|
-
import { randomUUID as
|
|
46943
|
+
import { randomUUID as randomUUID8 } from "node:crypto";
|
|
45629
46944
|
function normaliseEncryption(value, kind) {
|
|
45630
46945
|
const normalised = value.trim().toLowerCase();
|
|
45631
46946
|
if (!MAIL_ENCRYPTION_VALUES.includes(normalised)) {
|
|
@@ -46257,7 +47572,7 @@ var init_messenger = __esm({
|
|
|
46257
47572
|
);
|
|
46258
47573
|
}
|
|
46259
47574
|
const recipients = this.prepareRecipients(options, true);
|
|
46260
|
-
const messageId = `${
|
|
47575
|
+
const messageId = `${randomUUID8()}@${this.host}`;
|
|
46261
47576
|
if (recipients.allRecipients.length === 0) {
|
|
46262
47577
|
return { success: false, message: "No recipients specified", id: null };
|
|
46263
47578
|
}
|
|
@@ -49099,7 +50414,7 @@ var init_aiClient = __esm({
|
|
|
49099
50414
|
|
|
49100
50415
|
// src/queueBackends/rabbitmqBackend.ts
|
|
49101
50416
|
import { execFileSync as execFileSync5 } from "node:child_process";
|
|
49102
|
-
import { randomUUID as
|
|
50417
|
+
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
49103
50418
|
function parseAmqpUrl(url) {
|
|
49104
50419
|
const config = {};
|
|
49105
50420
|
let rest = url.replace(/^amqps:\/\//, "").replace(/^amqp:\/\//, "");
|
|
@@ -49535,7 +50850,7 @@ var init_rabbitmqBackend = __esm({
|
|
|
49535
50850
|
"The rabbitmq queue backend cannot honour push(raw=true): raw emits the message with no Tina4 envelope, which only a message bus consumed by non-Tina4 systems (Kafka) needs. This backend stores an internal envelope (payload/priority/attempts) that pop(), the retry lifecycle and dead-lettering depend on, so there is nothing to omit. Use the kafka backend for raw external messages."
|
|
49536
50851
|
);
|
|
49537
50852
|
}
|
|
49538
|
-
const id =
|
|
50853
|
+
const id = randomUUID9();
|
|
49539
50854
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
49540
50855
|
const job = {
|
|
49541
50856
|
id,
|
|
@@ -49579,586 +50894,6 @@ var init_rabbitmqBackend = __esm({
|
|
|
49579
50894
|
}
|
|
49580
50895
|
});
|
|
49581
50896
|
|
|
49582
|
-
// src/queueBackends/kafkaBackend.ts
|
|
49583
|
-
import { execFileSync as execFileSync6 } from "node:child_process";
|
|
49584
|
-
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
49585
|
-
function kafkaSecurityConfig(env = process.env) {
|
|
49586
|
-
const mapping = [
|
|
49587
|
-
["security.protocol", "SECURITY_PROTOCOL"],
|
|
49588
|
-
["ssl.ca.location", "SSL_CA_LOCATION"],
|
|
49589
|
-
["sasl.mechanism", "SASL_MECHANISM"],
|
|
49590
|
-
["sasl.username", "SASL_USERNAME"],
|
|
49591
|
-
["sasl.password", "SASL_PASSWORD"]
|
|
49592
|
-
];
|
|
49593
|
-
const config = {};
|
|
49594
|
-
for (const [rdk, suffix] of mapping) {
|
|
49595
|
-
const value = env[`TINA4_KAFKA_${suffix}`] || env[`KAFKA_${suffix}`];
|
|
49596
|
-
if (value) {
|
|
49597
|
-
config[rdk] = value;
|
|
49598
|
-
}
|
|
49599
|
-
}
|
|
49600
|
-
return config;
|
|
49601
|
-
}
|
|
49602
|
-
function kafkaOffsetReset(env = process.env) {
|
|
49603
|
-
return env.TINA4_KAFKA_AUTO_OFFSET_RESET || env.KAFKA_AUTO_OFFSET_RESET || "earliest";
|
|
49604
|
-
}
|
|
49605
|
-
var API_PRODUCE, API_FETCH, KafkaBackend;
|
|
49606
|
-
var init_kafkaBackend = __esm({
|
|
49607
|
-
"src/queueBackends/kafkaBackend.ts"() {
|
|
49608
|
-
"use strict";
|
|
49609
|
-
API_PRODUCE = 0;
|
|
49610
|
-
API_FETCH = 1;
|
|
49611
|
-
KafkaBackend = class _KafkaBackend {
|
|
49612
|
-
brokers;
|
|
49613
|
-
groupId;
|
|
49614
|
-
constructor(config) {
|
|
49615
|
-
const url = process.env.TINA4_QUEUE_URL;
|
|
49616
|
-
const fromUrl = url ? url.replace(/^kafka:\/\//, "") : void 0;
|
|
49617
|
-
this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
|
|
49618
|
-
this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
|
|
49619
|
-
}
|
|
49620
|
-
/**
|
|
49621
|
-
* Resolved connection config — exposed for testing/introspection.
|
|
49622
|
-
*/
|
|
49623
|
-
getConfig() {
|
|
49624
|
-
return { brokers: this.brokers, groupId: this.groupId };
|
|
49625
|
-
}
|
|
49626
|
-
/**
|
|
49627
|
-
* Resolved SSL/SASL client config from the environment (PLAINTEXT default).
|
|
49628
|
-
* Mirrors Python's `KafkaConnector._security_config`.
|
|
49629
|
-
*/
|
|
49630
|
-
securityConfig() {
|
|
49631
|
-
return kafkaSecurityConfig();
|
|
49632
|
-
}
|
|
49633
|
-
/**
|
|
49634
|
-
* Full producer config — brokers + client id + the resolved security block.
|
|
49635
|
-
* The security keys are applied to BOTH producer and consumer (matching
|
|
49636
|
-
* Python's `_connect_confluent`).
|
|
49637
|
-
*/
|
|
49638
|
-
producerConfig() {
|
|
49639
|
-
return {
|
|
49640
|
-
"bootstrap.servers": this.brokers,
|
|
49641
|
-
"client.id": "tina4-nodejs",
|
|
49642
|
-
...this.securityConfig()
|
|
49643
|
-
};
|
|
49644
|
-
}
|
|
49645
|
-
/**
|
|
49646
|
-
* Full consumer config — brokers + client id + group id + the SAME resolved
|
|
49647
|
-
* security block applied to the producer.
|
|
49648
|
-
*/
|
|
49649
|
-
consumerConfig() {
|
|
49650
|
-
return {
|
|
49651
|
-
"bootstrap.servers": this.brokers,
|
|
49652
|
-
"client.id": "tina4-nodejs",
|
|
49653
|
-
"group.id": this.groupId,
|
|
49654
|
-
"auto.offset.reset": kafkaOffsetReset(),
|
|
49655
|
-
"enable.auto.commit": false,
|
|
49656
|
-
...this.securityConfig()
|
|
49657
|
-
};
|
|
49658
|
-
}
|
|
49659
|
-
/**
|
|
49660
|
-
* Parse broker string into host:port.
|
|
49661
|
-
*/
|
|
49662
|
-
parseBroker() {
|
|
49663
|
-
const parts = this.brokers.split(",")[0].trim().split(":");
|
|
49664
|
-
return {
|
|
49665
|
-
host: parts[0] ?? "localhost",
|
|
49666
|
-
port: parts[1] ? parseInt(parts[1], 10) : 9092
|
|
49667
|
-
};
|
|
49668
|
-
}
|
|
49669
|
-
/**
|
|
49670
|
-
* Execute a Kafka operation synchronously via a child process.
|
|
49671
|
-
*
|
|
49672
|
-
* The wire protocol is hand-rolled (Tina4 is zero-dependency — no npm Kafka
|
|
49673
|
-
* library). Produce uses Produce **v3** carrying a Kafka **v2 RecordBatch**
|
|
49674
|
-
* (magic byte 2) with a **CRC-32C** (Castagnoli) checksum; Fetch uses Fetch
|
|
49675
|
-
* **v4** and parses the v2 RecordBatch out of the response. Both formats are
|
|
49676
|
-
* what a modern KRaft broker (apache/kafka 3.7.0) requires — the old
|
|
49677
|
-
* Produce-v0 / message-format-v0 / CRC=0 batch is rejected by such brokers.
|
|
49678
|
-
*/
|
|
49679
|
-
execSync(operation, topic, data) {
|
|
49680
|
-
const broker = this.parseBroker();
|
|
49681
|
-
const script = `
|
|
49682
|
-
const net = require("node:net");
|
|
49683
|
-
const host = ${JSON.stringify(broker.host)};
|
|
49684
|
-
const port = ${broker.port};
|
|
49685
|
-
const operation = ${JSON.stringify(operation)};
|
|
49686
|
-
const topic = ${JSON.stringify(topic)};
|
|
49687
|
-
const groupId = ${JSON.stringify(this.groupId)};
|
|
49688
|
-
const data = ${JSON.stringify(data ?? "")};
|
|
49689
|
-
const API_PRODUCE = ${API_PRODUCE};
|
|
49690
|
-
const API_FETCH = ${API_FETCH};
|
|
49691
|
-
const PRODUCE_VERSION = 3; // v3+ requires the v2 RecordBatch format
|
|
49692
|
-
const FETCH_VERSION = 4; // v4 returns v2 RecordBatches + isolation_level
|
|
49693
|
-
let correlationId = 0;
|
|
49694
|
-
|
|
49695
|
-
// \u2500\u2500 CRC-32C (Castagnoli, polynomial 0x1EDC6F41), table-based \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
49696
|
-
// Node has no built-in CRC-32C; the v2 RecordBatch mandates it over the
|
|
49697
|
-
// bytes from \`attributes\` to the end of the batch. A wrong CRC makes the
|
|
49698
|
-
// broker drop the connection, so this must be exact.
|
|
49699
|
-
const CRC32C_TABLE = (() => {
|
|
49700
|
-
const table = new Uint32Array(256);
|
|
49701
|
-
for (let n = 0; n < 256; n++) {
|
|
49702
|
-
let c = n;
|
|
49703
|
-
for (let k = 0; k < 8; k++) {
|
|
49704
|
-
c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
|
|
49705
|
-
}
|
|
49706
|
-
table[n] = c >>> 0;
|
|
49707
|
-
}
|
|
49708
|
-
return table;
|
|
49709
|
-
})();
|
|
49710
|
-
function crc32c(buf) {
|
|
49711
|
-
let crc = 0xffffffff;
|
|
49712
|
-
for (let i = 0; i < buf.length; i++) {
|
|
49713
|
-
crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
|
|
49714
|
-
}
|
|
49715
|
-
return (crc ^ 0xffffffff) >>> 0;
|
|
49716
|
-
}
|
|
49717
|
-
|
|
49718
|
-
// \u2500\u2500 Kafka protocol varints (zigzag-encoded signed varints) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
49719
|
-
function encodeZigZag(n) {
|
|
49720
|
-
// 32-bit zigzag: (n << 1) ^ (n >> 31)
|
|
49721
|
-
return ((n << 1) ^ (n >> 31)) >>> 0;
|
|
49722
|
-
}
|
|
49723
|
-
function encodeVarintUnsigned(u) {
|
|
49724
|
-
const bytes = [];
|
|
49725
|
-
let v = u >>> 0;
|
|
49726
|
-
while (true) {
|
|
49727
|
-
if ((v & ~0x7f) === 0) { bytes.push(v); break; }
|
|
49728
|
-
bytes.push((v & 0x7f) | 0x80);
|
|
49729
|
-
v >>>= 7;
|
|
49730
|
-
}
|
|
49731
|
-
return Buffer.from(bytes);
|
|
49732
|
-
}
|
|
49733
|
-
function encodeVarint(n) {
|
|
49734
|
-
// signed varint = zigzag then unsigned-varint
|
|
49735
|
-
return encodeVarintUnsigned(encodeZigZag(n));
|
|
49736
|
-
}
|
|
49737
|
-
function decodeVarint(buf, pos) {
|
|
49738
|
-
// returns { value, next } \u2014 signed (zigzag-decoded)
|
|
49739
|
-
let result = 0, shift = 0, b;
|
|
49740
|
-
do {
|
|
49741
|
-
b = buf[pos++];
|
|
49742
|
-
result |= (b & 0x7f) << shift;
|
|
49743
|
-
shift += 7;
|
|
49744
|
-
} while (b & 0x80);
|
|
49745
|
-
result = result >>> 0;
|
|
49746
|
-
// zigzag decode
|
|
49747
|
-
const value = (result >>> 1) ^ -(result & 1);
|
|
49748
|
-
return { value, next: pos };
|
|
49749
|
-
}
|
|
49750
|
-
|
|
49751
|
-
// \u2500\u2500 v2 RecordBatch builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
49752
|
-
function buildRecordBatch(valueBytes) {
|
|
49753
|
-
const now = BigInt(Date.now());
|
|
49754
|
-
|
|
49755
|
-
// Build the single record body.
|
|
49756
|
-
// record = attributes:int8(0), timestampDelta:varint(0),
|
|
49757
|
-
// offsetDelta:varint(0), keyLen:varint(-1 null),
|
|
49758
|
-
// valueLen:varint(len), value, headerCount:varint(0)
|
|
49759
|
-
const recBody = Buffer.concat([
|
|
49760
|
-
Buffer.from([0]), // attributes (int8)
|
|
49761
|
-
encodeVarint(0), // timestampDelta
|
|
49762
|
-
encodeVarint(0), // offsetDelta
|
|
49763
|
-
encodeVarint(-1), // keyLen (-1 = null key)
|
|
49764
|
-
encodeVarint(valueBytes.length), // valueLen
|
|
49765
|
-
valueBytes, // value (JSON payload bytes)
|
|
49766
|
-
encodeVarint(0), // headerCount
|
|
49767
|
-
]);
|
|
49768
|
-
// record length prefix = signed varint of recBody length
|
|
49769
|
-
const record = Buffer.concat([encodeVarint(recBody.length), recBody]);
|
|
49770
|
-
const recordsCount = 1;
|
|
49771
|
-
|
|
49772
|
-
// The portion the CRC covers starts at \`attributes\` and runs to end.
|
|
49773
|
-
// crcBody = attributes:int16(0), lastOffsetDelta:int32(count-1),
|
|
49774
|
-
// firstTimestamp:int64, maxTimestamp:int64,
|
|
49775
|
-
// producerId:int64(-1), producerEpoch:int16(-1),
|
|
49776
|
-
// baseSequence:int32(-1), recordsCount:int32, records
|
|
49777
|
-
const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
|
|
49778
|
-
let c = 0;
|
|
49779
|
-
crcBody.writeInt16BE(0, c); c += 2; // attributes
|
|
49780
|
-
crcBody.writeInt32BE(recordsCount - 1, c); c += 4; // lastOffsetDelta
|
|
49781
|
-
crcBody.writeBigInt64BE(now, c); c += 8; // firstTimestamp
|
|
49782
|
-
crcBody.writeBigInt64BE(now, c); c += 8; // maxTimestamp
|
|
49783
|
-
crcBody.writeBigInt64BE(-1n, c); c += 8; // producerId
|
|
49784
|
-
crcBody.writeInt16BE(-1, c); c += 2; // producerEpoch
|
|
49785
|
-
crcBody.writeInt32BE(-1, c); c += 4; // baseSequence
|
|
49786
|
-
crcBody.writeInt32BE(recordsCount, c); c += 4; // recordsCount
|
|
49787
|
-
record.copy(crcBody, c);
|
|
49788
|
-
|
|
49789
|
-
const crc = crc32c(crcBody);
|
|
49790
|
-
|
|
49791
|
-
// Header before the CRC-covered region:
|
|
49792
|
-
// baseOffset:int64(0), batchLength:int32, partitionLeaderEpoch:int32(-1),
|
|
49793
|
-
// magic:int8(2), crc:uint32. batchLength counts everything AFTER itself
|
|
49794
|
-
// (partitionLeaderEpoch through end of records) = 4 + 1 + 4 + crcBody.
|
|
49795
|
-
const batchLength = 4 + 1 + 4 + crcBody.length;
|
|
49796
|
-
const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
|
|
49797
|
-
let h = 0;
|
|
49798
|
-
head.writeBigInt64BE(0n, h); h += 8; // baseOffset
|
|
49799
|
-
head.writeInt32BE(batchLength, h); h += 4; // batchLength
|
|
49800
|
-
head.writeInt32BE(-1, h); h += 4; // partitionLeaderEpoch
|
|
49801
|
-
head.writeInt8(2, h); h += 1; // magic = 2
|
|
49802
|
-
head.writeUInt32BE(crc, h); h += 4; // crc (CRC-32C)
|
|
49803
|
-
|
|
49804
|
-
return Buffer.concat([head, crcBody]);
|
|
49805
|
-
}
|
|
49806
|
-
|
|
49807
|
-
// \u2500\u2500 Produce v3 request \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
49808
|
-
function buildProduceRequest(topicName, valueBytes) {
|
|
49809
|
-
correlationId++;
|
|
49810
|
-
const clientBuf = Buffer.from("tina4", "utf-8");
|
|
49811
|
-
const topicBuf = Buffer.from(topicName, "utf-8");
|
|
49812
|
-
const recordBatch = buildRecordBatch(valueBytes);
|
|
49813
|
-
|
|
49814
|
-
const body = Buffer.alloc(
|
|
49815
|
-
2 + // transactionalId (-1 null nullable_string)
|
|
49816
|
-
2 + // acks
|
|
49817
|
-
4 + // timeoutMs
|
|
49818
|
-
4 + // topics array count
|
|
49819
|
-
2 + topicBuf.length + // topic name
|
|
49820
|
-
4 + // partitions array count
|
|
49821
|
-
4 + // partition index
|
|
49822
|
-
4 + recordBatch.length // recordSetBytes (int32 size) + batch
|
|
49823
|
-
);
|
|
49824
|
-
let p = 0;
|
|
49825
|
-
body.writeInt16BE(-1, p); p += 2; // transactionalId = null
|
|
49826
|
-
body.writeInt16BE(1, p); p += 2; // acks = 1
|
|
49827
|
-
body.writeInt32BE(10000, p); p += 4; // timeoutMs
|
|
49828
|
-
body.writeInt32BE(1, p); p += 4; // topics count
|
|
49829
|
-
body.writeInt16BE(topicBuf.length, p); p += 2;
|
|
49830
|
-
topicBuf.copy(body, p); p += topicBuf.length;
|
|
49831
|
-
body.writeInt32BE(1, p); p += 4; // partitions count
|
|
49832
|
-
body.writeInt32BE(0, p); p += 4; // partition index 0
|
|
49833
|
-
body.writeInt32BE(recordBatch.length, p); p += 4; // recordSetBytes size
|
|
49834
|
-
recordBatch.copy(body, p);
|
|
49835
|
-
|
|
49836
|
-
return frameRequest(API_PRODUCE, PRODUCE_VERSION, clientBuf, body);
|
|
49837
|
-
}
|
|
49838
|
-
|
|
49839
|
-
// \u2500\u2500 Fetch v4 request \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
49840
|
-
function buildFetchRequest(topicName, fetchOffset) {
|
|
49841
|
-
correlationId++;
|
|
49842
|
-
const clientBuf = Buffer.from("tina4", "utf-8");
|
|
49843
|
-
const topicBuf = Buffer.from(topicName, "utf-8");
|
|
49844
|
-
|
|
49845
|
-
// Fetch v4 request body (NO logStartOffset \u2014 that arrives in v5+):
|
|
49846
|
-
// replicaId(4), maxWaitMs(4), minBytes(4), maxBytes(4 v3+),
|
|
49847
|
-
// isolationLevel(1 v4+), topics[count]: name, partitions[count]:
|
|
49848
|
-
// partition(4), fetchOffset(8), partitionMaxBytes(4).
|
|
49849
|
-
const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + (2 + topicBuf.length) + 4 + 4 + 8 + 4);
|
|
49850
|
-
let p = 0;
|
|
49851
|
-
buf.writeInt32BE(-1, p); p += 4; // replicaId (-1 consumer)
|
|
49852
|
-
buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
|
|
49853
|
-
buf.writeInt32BE(1, p); p += 4; // minBytes
|
|
49854
|
-
buf.writeInt32BE(1048576, p); p += 4; // maxBytes
|
|
49855
|
-
buf.writeInt8(0, p); p += 1; // isolationLevel = READ_UNCOMMITTED
|
|
49856
|
-
buf.writeInt32BE(1, p); p += 4; // topics count
|
|
49857
|
-
buf.writeInt16BE(topicBuf.length, p); p += 2;
|
|
49858
|
-
topicBuf.copy(buf, p); p += topicBuf.length;
|
|
49859
|
-
buf.writeInt32BE(1, p); p += 4; // partitions count
|
|
49860
|
-
buf.writeInt32BE(0, p); p += 4; // partition 0
|
|
49861
|
-
buf.writeBigInt64BE(BigInt(fetchOffset), p); p += 8; // fetchOffset
|
|
49862
|
-
buf.writeInt32BE(1048576, p); p += 4; // partitionMaxBytes
|
|
49863
|
-
|
|
49864
|
-
return frameRequest(API_FETCH, FETCH_VERSION, clientBuf, buf);
|
|
49865
|
-
}
|
|
49866
|
-
|
|
49867
|
-
// Frame a request with header v1: apiKey, apiVersion, correlationId,
|
|
49868
|
-
// clientId (nullable string) + body.
|
|
49869
|
-
function frameRequest(apiKey, apiVersion, clientBuf, body) {
|
|
49870
|
-
const header = Buffer.alloc(2 + 2 + 4 + 2 + clientBuf.length);
|
|
49871
|
-
let p = 0;
|
|
49872
|
-
header.writeInt16BE(apiKey, p); p += 2;
|
|
49873
|
-
header.writeInt16BE(apiVersion, p); p += 2;
|
|
49874
|
-
header.writeInt32BE(correlationId, p); p += 4;
|
|
49875
|
-
header.writeInt16BE(clientBuf.length, p); p += 2;
|
|
49876
|
-
clientBuf.copy(header, p);
|
|
49877
|
-
const payload = Buffer.concat([header, body]);
|
|
49878
|
-
const framed = Buffer.alloc(4 + payload.length);
|
|
49879
|
-
framed.writeInt32BE(payload.length, 0);
|
|
49880
|
-
payload.copy(framed, 4);
|
|
49881
|
-
return framed;
|
|
49882
|
-
}
|
|
49883
|
-
|
|
49884
|
-
// \u2500\u2500 Parse a v2 RecordBatch region, return the FIRST record value \u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
49885
|
-
// \`buf\` is the whole fetch response; [start, end) bounds the partition's
|
|
49886
|
-
// record-set bytes (may contain one or more concatenated batches).
|
|
49887
|
-
function firstRecordValue(buf, start, end) {
|
|
49888
|
-
let pos = start;
|
|
49889
|
-
while (pos + 12 <= end) {
|
|
49890
|
-
// baseOffset(8) + batchLength(4) then batchLength bytes follow.
|
|
49891
|
-
const batchLength = buf.readInt32BE(pos + 8);
|
|
49892
|
-
const batchStart = pos + 12; // first byte of partitionLeaderEpoch
|
|
49893
|
-
const batchEnd = batchStart + batchLength;
|
|
49894
|
-
if (batchLength <= 0 || batchEnd > end) break;
|
|
49895
|
-
// partitionLeaderEpoch(4), magic(1), crc(4), attributes(2),
|
|
49896
|
-
// lastOffsetDelta(4), firstTimestamp(8), maxTimestamp(8),
|
|
49897
|
-
// producerId(8), producerEpoch(2), baseSequence(4), recordsCount(4)
|
|
49898
|
-
const magic = buf.readInt8(batchStart + 4);
|
|
49899
|
-
if (magic !== 2) { pos = batchEnd; continue; }
|
|
49900
|
-
let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
|
|
49901
|
-
const recordsCount = buf.readInt32BE(r); r += 4;
|
|
49902
|
-
for (let i = 0; i < recordsCount && r < batchEnd; i++) {
|
|
49903
|
-
const recLen = decodeVarint(buf, r); // record length (signed varint)
|
|
49904
|
-
let rp = recLen.next;
|
|
49905
|
-
const recordEnd = rp + recLen.value;
|
|
49906
|
-
rp += 1; // attributes (int8)
|
|
49907
|
-
const tsDelta = decodeVarint(buf, rp); rp = tsDelta.next;
|
|
49908
|
-
const offDelta = decodeVarint(buf, rp); rp = offDelta.next;
|
|
49909
|
-
const keyLen = decodeVarint(buf, rp); rp = keyLen.next;
|
|
49910
|
-
if (keyLen.value >= 0) rp += keyLen.value;
|
|
49911
|
-
const valLen = decodeVarint(buf, rp); rp = valLen.next;
|
|
49912
|
-
if (valLen.value >= 0) {
|
|
49913
|
-
return buf.subarray(rp, rp + valLen.value).toString("utf-8");
|
|
49914
|
-
}
|
|
49915
|
-
r = recordEnd;
|
|
49916
|
-
}
|
|
49917
|
-
pos = batchEnd;
|
|
49918
|
-
}
|
|
49919
|
-
return null;
|
|
49920
|
-
}
|
|
49921
|
-
|
|
49922
|
-
let finished = false;
|
|
49923
|
-
function finish(out, code) {
|
|
49924
|
-
if (finished) return;
|
|
49925
|
-
finished = true;
|
|
49926
|
-
clearTimeout(timer);
|
|
49927
|
-
try { sock.destroy(); } catch (e) { /* ignore */ }
|
|
49928
|
-
if (out) process.stdout.write(out);
|
|
49929
|
-
// Flush stdout before exiting so execFileSync captures it.
|
|
49930
|
-
process.stdout.write("", () => process.exit(code));
|
|
49931
|
-
}
|
|
49932
|
-
|
|
49933
|
-
const sock = net.createConnection({ host, port }, () => {
|
|
49934
|
-
if (operation === "publish") {
|
|
49935
|
-
const req = buildProduceRequest(topic, Buffer.from(data, "utf-8"));
|
|
49936
|
-
sock.write(req);
|
|
49937
|
-
} else if (operation === "get") {
|
|
49938
|
-
sock.write(buildFetchRequest(topic, 0));
|
|
49939
|
-
} else {
|
|
49940
|
-
finish("__UNSUPPORTED__", 0);
|
|
49941
|
-
}
|
|
49942
|
-
});
|
|
49943
|
-
|
|
49944
|
-
let buffer = Buffer.alloc(0);
|
|
49945
|
-
sock.on("data", (chunk) => {
|
|
49946
|
-
buffer = Buffer.concat([buffer, chunk]);
|
|
49947
|
-
if (buffer.length < 4) return;
|
|
49948
|
-
const respSize = buffer.readInt32BE(0);
|
|
49949
|
-
if (buffer.length < 4 + respSize) return;
|
|
49950
|
-
|
|
49951
|
-
if (operation === "publish") {
|
|
49952
|
-
// Produce v3 response (after the 4-byte frame size): correlationId(4),
|
|
49953
|
-
// topics[count]: name, partitions[count]: partition(4), errorCode(2),
|
|
49954
|
-
// baseOffset(8), logAppendTime(8); then throttleTimeMs(4) at the END.
|
|
49955
|
-
// Only the per-partition error code matters here.
|
|
49956
|
-
try {
|
|
49957
|
-
let pos = 4 + 4; // skip frame size + correlationId
|
|
49958
|
-
const topicCount = buffer.readInt32BE(pos); pos += 4;
|
|
49959
|
-
let errCode = 0;
|
|
49960
|
-
for (let t = 0; t < topicCount; t++) {
|
|
49961
|
-
const tl = buffer.readInt16BE(pos); pos += 2 + tl;
|
|
49962
|
-
const pc = buffer.readInt32BE(pos); pos += 4;
|
|
49963
|
-
for (let pi = 0; pi < pc; pi++) {
|
|
49964
|
-
pos += 4; // partition index
|
|
49965
|
-
errCode = buffer.readInt16BE(pos); pos += 2; // error code
|
|
49966
|
-
pos += 8; // baseOffset
|
|
49967
|
-
pos += 8; // logAppendTime (v2+)
|
|
49968
|
-
}
|
|
49969
|
-
}
|
|
49970
|
-
if (errCode === 0) {
|
|
49971
|
-
finish("__PUBLISHED__", 0);
|
|
49972
|
-
} else {
|
|
49973
|
-
// Report the CODE, not just "it failed" \u2014 the caller decides
|
|
49974
|
-
// whether it is retriable (3/5, the async topic-creation race)
|
|
49975
|
-
// or fatal (e.g. 29 TOPIC_AUTHORIZATION_FAILED).
|
|
49976
|
-
process.stderr.write("Produce error code " + errCode);
|
|
49977
|
-
finish("__PRODUCEERROR__" + errCode, 0);
|
|
49978
|
-
}
|
|
49979
|
-
} catch (e) {
|
|
49980
|
-
process.stderr.write("produce parse: " + e.message);
|
|
49981
|
-
finish("__PARSEERROR__produce: " + e.message, 0);
|
|
49982
|
-
}
|
|
49983
|
-
return;
|
|
49984
|
-
} else if (operation === "get") {
|
|
49985
|
-
// Fetch v4 response (after the 4-byte frame size): correlationId(4),
|
|
49986
|
-
// throttleTimeMs(4), topics[count]: name, partitions[count]:
|
|
49987
|
-
// partition(4), errorCode(2), highWatermark(8), lastStableOffset(8),
|
|
49988
|
-
// abortedTxns[count](producerId(8)+firstOffset(8)),
|
|
49989
|
-
// recordSetBytes(int32)+batch.
|
|
49990
|
-
try {
|
|
49991
|
-
let pos = 4 + 4; // frame size + correlationId
|
|
49992
|
-
pos += 4; // throttleTimeMs (v1+)
|
|
49993
|
-
const topicCount = buffer.readInt32BE(pos); pos += 4;
|
|
49994
|
-
let out = "__EMPTY__";
|
|
49995
|
-
let fatalCode = 0;
|
|
49996
|
-
for (let t = 0; t < topicCount; t++) {
|
|
49997
|
-
const tl = buffer.readInt16BE(pos); pos += 2 + tl;
|
|
49998
|
-
const pc = buffer.readInt32BE(pos); pos += 4;
|
|
49999
|
-
for (let pi = 0; pi < pc; pi++) {
|
|
50000
|
-
pos += 4; // partition index
|
|
50001
|
-
const errCode = buffer.readInt16BE(pos); pos += 2;
|
|
50002
|
-
pos += 8; // highWatermark
|
|
50003
|
-
pos += 8; // lastStableOffset (v4+)
|
|
50004
|
-
const abortedCount = buffer.readInt32BE(pos); pos += 4;
|
|
50005
|
-
if (abortedCount > 0) pos += abortedCount * 16; // (-1 => none, skip)
|
|
50006
|
-
const recSetSize = buffer.readInt32BE(pos); pos += 4;
|
|
50007
|
-
// 3 = UNKNOWN_TOPIC_OR_PARTITION, 5 = LEADER_NOT_AVAILABLE:
|
|
50008
|
-
// "nothing to read here yet", which a consumer that starts
|
|
50009
|
-
// before its producer hits on every cold start. Any OTHER code
|
|
50010
|
-
// (29 TOPIC_AUTHORIZATION_FAILED, 13 STALE_CONTROLLER_EPOCH, \u2026)
|
|
50011
|
-
// is a real failure and must NOT be reported as an empty queue.
|
|
50012
|
-
if (errCode !== 0 && errCode !== 3 && errCode !== 5) {
|
|
50013
|
-
fatalCode = errCode;
|
|
50014
|
-
}
|
|
50015
|
-
if (errCode === 0 && recSetSize > 0) {
|
|
50016
|
-
const val = firstRecordValue(buffer, pos, pos + recSetSize);
|
|
50017
|
-
if (val !== null) out = val;
|
|
50018
|
-
}
|
|
50019
|
-
pos += recSetSize > 0 ? recSetSize : 0;
|
|
50020
|
-
}
|
|
50021
|
-
}
|
|
50022
|
-
if (fatalCode !== 0) {
|
|
50023
|
-
process.stderr.write("Fetch error code " + fatalCode);
|
|
50024
|
-
finish("__FETCHERROR__" + fatalCode, 0);
|
|
50025
|
-
return;
|
|
50026
|
-
}
|
|
50027
|
-
finish(out, 0);
|
|
50028
|
-
} catch (e) {
|
|
50029
|
-
// A parse failure is NOT an empty queue either \u2014 say so.
|
|
50030
|
-
process.stderr.write("fetch parse: " + e.message);
|
|
50031
|
-
finish("__PARSEERROR__fetch: " + e.message, 0);
|
|
50032
|
-
}
|
|
50033
|
-
return;
|
|
50034
|
-
}
|
|
50035
|
-
});
|
|
50036
|
-
|
|
50037
|
-
// Report the reason on STDOUT and exit 0. Writing it to stderr and
|
|
50038
|
-
// exiting non-zero LOST it: stderr to a pipe is an async write and
|
|
50039
|
-
// process.exit() truncates it, so the parent saw an empty stderr and fell
|
|
50040
|
-
// back to execFileSync's message -- which embeds this entire script.
|
|
50041
|
-
// stdout is flushed by finish()'s write callback, so it survives.
|
|
50042
|
-
sock.on("error", (err) => {
|
|
50043
|
-
finish("__TRANSPORTERROR__" + err.message, 0);
|
|
50044
|
-
});
|
|
50045
|
-
|
|
50046
|
-
var timer = setTimeout(() => {
|
|
50047
|
-
finish("__TRANSPORTERROR__timed out after 10s talking to " + host + ":" + port, 0);
|
|
50048
|
-
}, 10000);
|
|
50049
|
-
`;
|
|
50050
|
-
try {
|
|
50051
|
-
const result = execFileSync6(process.execPath, ["-e", script], {
|
|
50052
|
-
encoding: "utf-8",
|
|
50053
|
-
timeout: 15e3,
|
|
50054
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
50055
|
-
});
|
|
50056
|
-
return result;
|
|
50057
|
-
} catch (err) {
|
|
50058
|
-
const e = err;
|
|
50059
|
-
const reason = String(e.stderr ?? "").trim() || e.message || "unknown error";
|
|
50060
|
-
const firstLine = reason.split("\n", 1)[0].slice(0, 200);
|
|
50061
|
-
return "__TRANSPORTERROR__" + firstLine;
|
|
50062
|
-
}
|
|
50063
|
-
}
|
|
50064
|
-
/**
|
|
50065
|
-
* Sleep synchronously between produce retries.
|
|
50066
|
-
*
|
|
50067
|
-
* `push()` is synchronous (the whole backend drives its socket through a child
|
|
50068
|
-
* process), so there is no event loop to await on. `Atomics.wait` on a
|
|
50069
|
-
* SharedArrayBuffer is the stdlib way to block a thread for a fixed time --
|
|
50070
|
-
* no dependency, no busy-wait burning CPU.
|
|
50071
|
-
*/
|
|
50072
|
-
static sleepSync(ms) {
|
|
50073
|
-
const shared = new Int32Array(new SharedArrayBuffer(4));
|
|
50074
|
-
Atomics.wait(shared, 0, 0, ms);
|
|
50075
|
-
}
|
|
50076
|
-
/**
|
|
50077
|
-
* Turn a sentinel from the protocol child into a thrown error, or return.
|
|
50078
|
-
*
|
|
50079
|
-
* The wording matches the Python and PHP backends exactly -- the parity rule
|
|
50080
|
-
* covers user-visible error messages, not just behaviour.
|
|
50081
|
-
*/
|
|
50082
|
-
static assertNoError(result, operation, topic) {
|
|
50083
|
-
const fatal = /^__(PRODUCEERROR|FETCHERROR)__(\d+)/.exec(result);
|
|
50084
|
-
if (fatal) {
|
|
50085
|
-
throw new Error(
|
|
50086
|
-
`Kafka rejected the ${operation} for topic ${topic}: error code ${fatal[2]}`
|
|
50087
|
-
);
|
|
50088
|
-
}
|
|
50089
|
-
if (result.startsWith("__TRANSPORTERROR__")) {
|
|
50090
|
-
throw new Error(
|
|
50091
|
-
`Kafka ${operation} for topic ${topic} failed: ` + result.slice("__TRANSPORTERROR__".length)
|
|
50092
|
-
);
|
|
50093
|
-
}
|
|
50094
|
-
if (result.startsWith("__PARSEERROR__")) {
|
|
50095
|
-
throw new Error(
|
|
50096
|
-
`Kafka ${operation} for topic ${topic} returned an unreadable response: ` + result.slice("__PARSEERROR__".length)
|
|
50097
|
-
);
|
|
50098
|
-
}
|
|
50099
|
-
}
|
|
50100
|
-
/**
|
|
50101
|
-
* Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
|
|
50102
|
-
* as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
|
|
50103
|
-
* consumer reading the topic gets the schema it expects; otherwise the Tina4 job
|
|
50104
|
-
* envelope. pop() unwraps both shapes (payload ?? the whole record).
|
|
50105
|
-
*/
|
|
50106
|
-
static encodeJob(id, payload, raw) {
|
|
50107
|
-
if (raw) return JSON.stringify(payload);
|
|
50108
|
-
return JSON.stringify({
|
|
50109
|
-
id,
|
|
50110
|
-
payload,
|
|
50111
|
-
status: "pending",
|
|
50112
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
50113
|
-
attempts: 0,
|
|
50114
|
-
delayUntil: null
|
|
50115
|
-
});
|
|
50116
|
-
}
|
|
50117
|
-
push(queue, payload, _delay, _priority, raw = false) {
|
|
50118
|
-
const id = randomUUID9();
|
|
50119
|
-
const body = _KafkaBackend.encodeJob(id, payload, raw);
|
|
50120
|
-
let result = "";
|
|
50121
|
-
for (let attempt = 1; attempt <= 10; attempt++) {
|
|
50122
|
-
result = this.execSync("publish", queue, body);
|
|
50123
|
-
if (result.includes("__PUBLISHED__")) {
|
|
50124
|
-
return id;
|
|
50125
|
-
}
|
|
50126
|
-
const retriable = /^__PRODUCEERROR__(3|5)\b/.test(result);
|
|
50127
|
-
if (!retriable || attempt === 10) {
|
|
50128
|
-
break;
|
|
50129
|
-
}
|
|
50130
|
-
_KafkaBackend.sleepSync(200);
|
|
50131
|
-
}
|
|
50132
|
-
_KafkaBackend.assertNoError(result, "produce", queue);
|
|
50133
|
-
throw new Error(`Kafka publish failed for topic ${queue}: ${result || "no response"}`);
|
|
50134
|
-
}
|
|
50135
|
-
pop(queue) {
|
|
50136
|
-
const result = this.execSync("get", queue);
|
|
50137
|
-
_KafkaBackend.assertNoError(result, "fetch", queue);
|
|
50138
|
-
if (!result || result === "__EMPTY__" || result === "__UNSUPPORTED__") return null;
|
|
50139
|
-
try {
|
|
50140
|
-
return JSON.parse(result);
|
|
50141
|
-
} catch {
|
|
50142
|
-
return null;
|
|
50143
|
-
}
|
|
50144
|
-
}
|
|
50145
|
-
size(_queue) {
|
|
50146
|
-
return 0;
|
|
50147
|
-
}
|
|
50148
|
-
clear(_queue) {
|
|
50149
|
-
throw new Error(
|
|
50150
|
-
"The kafka queue backend cannot perform clear(): Kafka has no notion of job status and cannot delete records on demand. A log is read in offset order and records leave only by retention. Use the file or mongodb backend."
|
|
50151
|
-
);
|
|
50152
|
-
}
|
|
50153
|
-
purge(_queue, _status) {
|
|
50154
|
-
throw new Error(
|
|
50155
|
-
"The kafka queue backend cannot perform purge(): Kafka has no notion of job status to purge by. A log is read in offset order and records leave only by retention. Use the file or mongodb backend."
|
|
50156
|
-
);
|
|
50157
|
-
}
|
|
50158
|
-
};
|
|
50159
|
-
}
|
|
50160
|
-
});
|
|
50161
|
-
|
|
50162
50897
|
// src/testing.ts
|
|
50163
50898
|
function expectEqual(args, expected) {
|
|
50164
50899
|
return { type: "equal", args, expected };
|
|
@@ -50934,6 +51669,8 @@ __export(index_exports, {
|
|
|
50934
51669
|
TEXT_PLAIN: () => TEXT_PLAIN,
|
|
50935
51670
|
TEXT_XML: () => TEXT_XML,
|
|
50936
51671
|
TINA4_VERSION: () => TINA4_VERSION,
|
|
51672
|
+
TcpConnection: () => TcpConnection,
|
|
51673
|
+
TcpService: () => TcpService,
|
|
50937
51674
|
TestClient: () => TestClient,
|
|
50938
51675
|
TestResponse: () => TestResponse,
|
|
50939
51676
|
Tina4AssertionError: () => AssertionError,
|
|
@@ -50976,6 +51713,7 @@ __export(index_exports, {
|
|
|
50976
51713
|
checkPassword: () => checkPassword,
|
|
50977
51714
|
clearCache: () => clearCache,
|
|
50978
51715
|
clearCurrentNonce: () => clearCurrentNonce,
|
|
51716
|
+
clearTcpRegistry: () => clearTcpRegistry,
|
|
50979
51717
|
computeAcceptKey: () => computeAcceptKey,
|
|
50980
51718
|
container: () => container,
|
|
50981
51719
|
cors: () => cors,
|
|
@@ -50997,6 +51735,7 @@ __export(index_exports, {
|
|
|
50997
51735
|
devAdminLanguage: () => devAdminLanguage,
|
|
50998
51736
|
devReloadWs: () => devReloadWs,
|
|
50999
51737
|
discoverRoutes: () => discoverRoutes,
|
|
51738
|
+
drainAllTcpServices: () => drainAllTcpServices,
|
|
51000
51739
|
encodeError: () => encodeError,
|
|
51001
51740
|
encodeNotification: () => encodeNotification,
|
|
51002
51741
|
encodeResponse: () => encodeResponse,
|
|
@@ -51084,6 +51823,7 @@ __export(index_exports, {
|
|
|
51084
51823
|
refreshToken: () => refreshToken,
|
|
51085
51824
|
registerDevTools: () => registerDevTools,
|
|
51086
51825
|
registerFeedbackRoutes: () => registerFeedbackRoutes,
|
|
51826
|
+
registeredTcpServices: () => registeredTcpServices,
|
|
51087
51827
|
removePidfile: () => removePidfile,
|
|
51088
51828
|
renderErrorOverlay: () => renderErrorOverlay,
|
|
51089
51829
|
requestLogger: () => requestLogger,
|
|
@@ -51114,12 +51854,16 @@ __export(index_exports, {
|
|
|
51114
51854
|
setFrond: () => setFrond,
|
|
51115
51855
|
showMenu: () => showMenu,
|
|
51116
51856
|
start: () => start,
|
|
51857
|
+
startAllTcpServices: () => startAllTcpServices,
|
|
51117
51858
|
startServer: () => startServer,
|
|
51118
51859
|
stop: () => stop,
|
|
51860
|
+
stopAcceptingAllTcpServices: () => stopAcceptingAllTcpServices,
|
|
51119
51861
|
stopAllBackgroundTasks: () => stopAllBackgroundTasks,
|
|
51120
51862
|
supervisorBaseUrl: () => supervisorBaseUrl,
|
|
51121
51863
|
sweep: () => sweep,
|
|
51122
51864
|
takeOverPort: () => takeOverPort,
|
|
51865
|
+
tcp: () => tcp,
|
|
51866
|
+
tcpService: () => tcpService,
|
|
51123
51867
|
templateAutoRoutingEnabled: () => templateAutoRoutingEnabled,
|
|
51124
51868
|
tests: () => tests,
|
|
51125
51869
|
trustedProxyNetworks: () => trustedProxyNetworks,
|
|
@@ -51138,6 +51882,7 @@ var init_index = __esm({
|
|
|
51138
51882
|
"src/index.ts"() {
|
|
51139
51883
|
init_server();
|
|
51140
51884
|
init_background();
|
|
51885
|
+
init_tcp();
|
|
51141
51886
|
init_router();
|
|
51142
51887
|
init_router();
|
|
51143
51888
|
init_routeDiscovery();
|
|
@@ -51326,6 +52071,8 @@ export {
|
|
|
51326
52071
|
TEXT_PLAIN,
|
|
51327
52072
|
TEXT_XML,
|
|
51328
52073
|
TINA4_VERSION,
|
|
52074
|
+
TcpConnection,
|
|
52075
|
+
TcpService,
|
|
51329
52076
|
TestClient,
|
|
51330
52077
|
TestResponse,
|
|
51331
52078
|
AssertionError as Tina4AssertionError,
|
|
@@ -51368,6 +52115,7 @@ export {
|
|
|
51368
52115
|
checkPassword,
|
|
51369
52116
|
clearCache,
|
|
51370
52117
|
clearCurrentNonce,
|
|
52118
|
+
clearTcpRegistry,
|
|
51371
52119
|
computeAcceptKey,
|
|
51372
52120
|
container,
|
|
51373
52121
|
cors,
|
|
@@ -51389,6 +52137,7 @@ export {
|
|
|
51389
52137
|
devAdminLanguage,
|
|
51390
52138
|
devReloadWs,
|
|
51391
52139
|
discoverRoutes,
|
|
52140
|
+
drainAllTcpServices,
|
|
51392
52141
|
encodeError,
|
|
51393
52142
|
encodeNotification,
|
|
51394
52143
|
encodeResponse,
|
|
@@ -51476,6 +52225,7 @@ export {
|
|
|
51476
52225
|
refreshToken,
|
|
51477
52226
|
registerDevTools,
|
|
51478
52227
|
registerFeedbackRoutes,
|
|
52228
|
+
registeredTcpServices,
|
|
51479
52229
|
removePidfile,
|
|
51480
52230
|
renderErrorOverlay,
|
|
51481
52231
|
requestLogger,
|
|
@@ -51506,12 +52256,16 @@ export {
|
|
|
51506
52256
|
setFrond,
|
|
51507
52257
|
showMenu,
|
|
51508
52258
|
start,
|
|
52259
|
+
startAllTcpServices,
|
|
51509
52260
|
startServer,
|
|
51510
52261
|
stop,
|
|
52262
|
+
stopAcceptingAllTcpServices,
|
|
51511
52263
|
stopAllBackgroundTasks,
|
|
51512
52264
|
supervisorBaseUrl,
|
|
51513
52265
|
sweep,
|
|
51514
52266
|
takeOverPort,
|
|
52267
|
+
tcp,
|
|
52268
|
+
tcpService,
|
|
51515
52269
|
templateAutoRoutingEnabled,
|
|
51516
52270
|
tests,
|
|
51517
52271
|
trustedProxyNetworks,
|