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
|
@@ -5551,6 +5551,7 @@ var init_csp = __esm({
|
|
|
5551
5551
|
var engine_exports = {};
|
|
5552
5552
|
__export(engine_exports, {
|
|
5553
5553
|
Frond: () => Frond,
|
|
5554
|
+
FrondSyntaxError: () => FrondSyntaxError,
|
|
5554
5555
|
MEMO_CACHE_MAX: () => MEMO_CACHE_MAX,
|
|
5555
5556
|
TEMPLATE_CACHE_MAX: () => TEMPLATE_CACHE_MAX,
|
|
5556
5557
|
escapeHtml: () => escapeHtml,
|
|
@@ -6683,6 +6684,87 @@ function isEscapableStructured(value) {
|
|
|
6683
6684
|
function toOutputString(value) {
|
|
6684
6685
|
return String(value);
|
|
6685
6686
|
}
|
|
6687
|
+
function phpDate(dt, fmt) {
|
|
6688
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
6689
|
+
const hours = dt.getHours();
|
|
6690
|
+
const h12 = hours % 12 || 12;
|
|
6691
|
+
const dow = dt.getDay();
|
|
6692
|
+
const iso2 = dow === 0 ? 7 : dow;
|
|
6693
|
+
let out = "";
|
|
6694
|
+
for (let i = 0; i < fmt.length; i++) {
|
|
6695
|
+
const c = fmt[i];
|
|
6696
|
+
if (c === "\\" && i + 1 < fmt.length) {
|
|
6697
|
+
out += fmt[i + 1];
|
|
6698
|
+
i++;
|
|
6699
|
+
continue;
|
|
6700
|
+
}
|
|
6701
|
+
switch (c) {
|
|
6702
|
+
case "Y":
|
|
6703
|
+
out += String(dt.getFullYear());
|
|
6704
|
+
break;
|
|
6705
|
+
case "y":
|
|
6706
|
+
out += pad(dt.getFullYear() % 100);
|
|
6707
|
+
break;
|
|
6708
|
+
case "m":
|
|
6709
|
+
out += pad(dt.getMonth() + 1);
|
|
6710
|
+
break;
|
|
6711
|
+
case "n":
|
|
6712
|
+
out += String(dt.getMonth() + 1);
|
|
6713
|
+
break;
|
|
6714
|
+
case "d":
|
|
6715
|
+
out += pad(dt.getDate());
|
|
6716
|
+
break;
|
|
6717
|
+
case "j":
|
|
6718
|
+
out += String(dt.getDate());
|
|
6719
|
+
break;
|
|
6720
|
+
case "H":
|
|
6721
|
+
out += pad(hours);
|
|
6722
|
+
break;
|
|
6723
|
+
case "G":
|
|
6724
|
+
out += String(hours);
|
|
6725
|
+
break;
|
|
6726
|
+
case "h":
|
|
6727
|
+
out += pad(h12);
|
|
6728
|
+
break;
|
|
6729
|
+
case "g":
|
|
6730
|
+
out += String(h12);
|
|
6731
|
+
break;
|
|
6732
|
+
case "i":
|
|
6733
|
+
out += pad(dt.getMinutes());
|
|
6734
|
+
break;
|
|
6735
|
+
case "s":
|
|
6736
|
+
out += pad(dt.getSeconds());
|
|
6737
|
+
break;
|
|
6738
|
+
case "A":
|
|
6739
|
+
out += hours < 12 ? "AM" : "PM";
|
|
6740
|
+
break;
|
|
6741
|
+
case "a":
|
|
6742
|
+
out += hours < 12 ? "am" : "pm";
|
|
6743
|
+
break;
|
|
6744
|
+
case "D":
|
|
6745
|
+
out += PHP_DAYS[dow].slice(0, 3);
|
|
6746
|
+
break;
|
|
6747
|
+
case "l":
|
|
6748
|
+
out += PHP_DAYS[dow];
|
|
6749
|
+
break;
|
|
6750
|
+
case "M":
|
|
6751
|
+
out += PHP_MONTHS[dt.getMonth()].slice(0, 3);
|
|
6752
|
+
break;
|
|
6753
|
+
case "F":
|
|
6754
|
+
out += PHP_MONTHS[dt.getMonth()];
|
|
6755
|
+
break;
|
|
6756
|
+
case "N":
|
|
6757
|
+
out += String(iso2);
|
|
6758
|
+
break;
|
|
6759
|
+
case "w":
|
|
6760
|
+
out += String(dow);
|
|
6761
|
+
break;
|
|
6762
|
+
default:
|
|
6763
|
+
out += c;
|
|
6764
|
+
}
|
|
6765
|
+
}
|
|
6766
|
+
return out;
|
|
6767
|
+
}
|
|
6686
6768
|
function dateFilter(value, fmt) {
|
|
6687
6769
|
let dt;
|
|
6688
6770
|
if (value instanceof Date) {
|
|
@@ -6695,6 +6777,7 @@ function dateFilter(value, fmt) {
|
|
|
6695
6777
|
} else {
|
|
6696
6778
|
return String(value);
|
|
6697
6779
|
}
|
|
6780
|
+
if (!fmt.includes("%")) return phpDate(dt, fmt);
|
|
6698
6781
|
return fmt.replace(/%Y/g, String(dt.getFullYear())).replace(/%m/g, String(dt.getMonth() + 1).padStart(2, "0")).replace(/%d/g, String(dt.getDate()).padStart(2, "0")).replace(/%H/g, String(dt.getHours()).padStart(2, "0")).replace(/%M/g, String(dt.getMinutes()).padStart(2, "0")).replace(/%S/g, String(dt.getSeconds()).padStart(2, "0")).replace(/%I/g, String(dt.getHours() % 12 || 12).padStart(2, "0")).replace(/%p/g, dt.getHours() >= 12 ? "PM" : "AM").replace(/%B/g, dt.toLocaleString("en-US", { month: "long" })).replace(/%b/g, dt.toLocaleString("en-US", { month: "short" })).replace(/%A/g, dt.toLocaleString("en-US", { weekday: "long" })).replace(/%a/g, dt.toLocaleString("en-US", { weekday: "short" }));
|
|
6699
6782
|
}
|
|
6700
6783
|
function wordwrap(text, width) {
|
|
@@ -6805,7 +6888,7 @@ function _generateFormToken(descriptor = "") {
|
|
|
6805
6888
|
function _generateFormTokenValue(descriptor = "") {
|
|
6806
6889
|
return new SafeString(_buildFormTokenJwt(descriptor));
|
|
6807
6890
|
}
|
|
6808
|
-
var SafeString, KNOWN_TAGS, TERMINATOR_TAGS, GATEABLE_TAGS, BLOCK_TAG_ENDS, JSON_UNSAFE_RE, JSON_UNSAFE_MAP, NUMERIC_RE, METHOD_CALL_RE, FN_CALL_RE, IS_NOT_RE, IS_RE, NOT_IN_RE, IN_RE, DIVISIBLE_BY_RE, FILTER_WITH_ARGS_RE, FILTER_COMPARISON_RE, TITLE_WORD_RE, STRIP_TAGS_RE, FAST_FILTERS, FORMAT_RE, THOUSANDS_RE, LIVE_RE, LIVE_WS_RE, LIVE_SRC_RE, EXTENDS_RE, EXTENDS_RE_GLOBAL, filterChainCache, pathParseCache, TEMPLATE_CACHE_MAX, MEMO_CACHE_MAX, RAW_OPEN_RE, RAW_CLOSE_RE, TAG_KINDS, EXPR_NOT_MATCHED, ARITHMETIC_OPERATIONS, ARITHMETIC_LEVELS, BARE_KEY_RE, EXPR_EVALUATORS, expressionFormCache, VarRef, JS_SAFE_RE, MEDIA_TYPE_RE, SANDBOX_EXPR_KEYWORDS, SANDBOX_IDENT_RE, SANDBOX_STRING_RE, UNSAFE_KEYS, BUILTIN_FILTERS, _formTokenSessionId, _formTokenSessionProvider, _cspNonceProvider, Frond;
|
|
6891
|
+
var SafeString, KNOWN_TAGS, TERMINATOR_TAGS, GATEABLE_TAGS, BLOCK_TAG_ENDS, JSON_UNSAFE_RE, JSON_UNSAFE_MAP, NUMERIC_RE, METHOD_CALL_RE, FN_CALL_RE, IS_NOT_RE, IS_RE, NOT_IN_RE, IN_RE, DIVISIBLE_BY_RE, FILTER_WITH_ARGS_RE, FILTER_COMPARISON_RE, TITLE_WORD_RE, STRIP_TAGS_RE, FAST_FILTERS, FORMAT_RE, THOUSANDS_RE, LIVE_RE, LIVE_WS_RE, LIVE_SRC_RE, EXTENDS_RE, EXTENDS_RE_GLOBAL, filterChainCache, pathParseCache, TEMPLATE_CACHE_MAX, MEMO_CACHE_MAX, RAW_OPEN_RE, RAW_CLOSE_RE, TAG_KINDS, EXPR_NOT_MATCHED, ARITHMETIC_OPERATIONS, ARITHMETIC_LEVELS, BARE_KEY_RE, EXPR_EVALUATORS, expressionFormCache, VarRef, JS_SAFE_RE, MEDIA_TYPE_RE, SANDBOX_EXPR_KEYWORDS, SANDBOX_IDENT_RE, SANDBOX_STRING_RE, UNSAFE_KEYS, FrondSyntaxError, PHP_MONTHS, PHP_DAYS, BUILTIN_FILTERS, _formTokenSessionId, _formTokenSessionProvider, _cspNonceProvider, Frond;
|
|
6809
6892
|
var init_engine = __esm({
|
|
6810
6893
|
"../frond/src/engine.ts"() {
|
|
6811
6894
|
"use strict";
|
|
@@ -7002,6 +7085,35 @@ var init_engine = __esm({
|
|
|
7002
7085
|
"__defineProperty__",
|
|
7003
7086
|
"valueOf"
|
|
7004
7087
|
]);
|
|
7088
|
+
FrondSyntaxError = class extends Error {
|
|
7089
|
+
constructor(message) {
|
|
7090
|
+
super(message);
|
|
7091
|
+
this.name = "FrondSyntaxError";
|
|
7092
|
+
}
|
|
7093
|
+
};
|
|
7094
|
+
PHP_MONTHS = [
|
|
7095
|
+
"January",
|
|
7096
|
+
"February",
|
|
7097
|
+
"March",
|
|
7098
|
+
"April",
|
|
7099
|
+
"May",
|
|
7100
|
+
"June",
|
|
7101
|
+
"July",
|
|
7102
|
+
"August",
|
|
7103
|
+
"September",
|
|
7104
|
+
"October",
|
|
7105
|
+
"November",
|
|
7106
|
+
"December"
|
|
7107
|
+
];
|
|
7108
|
+
PHP_DAYS = [
|
|
7109
|
+
"Sunday",
|
|
7110
|
+
"Monday",
|
|
7111
|
+
"Tuesday",
|
|
7112
|
+
"Wednesday",
|
|
7113
|
+
"Thursday",
|
|
7114
|
+
"Friday",
|
|
7115
|
+
"Saturday"
|
|
7116
|
+
];
|
|
7005
7117
|
BUILTIN_FILTERS = {
|
|
7006
7118
|
upper: (v) => String(v).toUpperCase(),
|
|
7007
7119
|
lower: (v) => String(v).toLowerCase(),
|
|
@@ -7525,7 +7637,9 @@ var init_engine = __esm({
|
|
|
7525
7637
|
}
|
|
7526
7638
|
}
|
|
7527
7639
|
if (depth > 0) {
|
|
7528
|
-
|
|
7640
|
+
throw new FrondSyntaxError(
|
|
7641
|
+
`{% block ${name} %} is never closed (missing or malformed {% endblock %})`
|
|
7642
|
+
);
|
|
7529
7643
|
}
|
|
7530
7644
|
}
|
|
7531
7645
|
return blocks;
|
|
@@ -7592,9 +7706,9 @@ var init_engine = __esm({
|
|
|
7592
7706
|
}
|
|
7593
7707
|
}
|
|
7594
7708
|
if (!closeMatch) {
|
|
7595
|
-
|
|
7596
|
-
|
|
7597
|
-
|
|
7709
|
+
throw new FrondSyntaxError(
|
|
7710
|
+
`{% block ${name} %} is never closed (missing or malformed {% endblock %})`
|
|
7711
|
+
);
|
|
7598
7712
|
}
|
|
7599
7713
|
const parentContent = source.slice(contentStart, closeMatch.index);
|
|
7600
7714
|
const blockSource = blocks[name] ?? parentContent;
|
|
@@ -9152,6 +9266,9 @@ function attachCsrfFromEnv() {
|
|
|
9152
9266
|
}
|
|
9153
9267
|
return false;
|
|
9154
9268
|
}
|
|
9269
|
+
function logPath(req2) {
|
|
9270
|
+
return req2.path ?? (req2.url ?? "/").split("?")[0];
|
|
9271
|
+
}
|
|
9155
9272
|
function requestLogger() {
|
|
9156
9273
|
return (req2, res, next) => {
|
|
9157
9274
|
const start2 = Date.now();
|
|
@@ -9160,8 +9277,7 @@ function requestLogger() {
|
|
|
9160
9277
|
const duration = Date.now() - start2;
|
|
9161
9278
|
const status2 = res.raw.statusCode;
|
|
9162
9279
|
const method = req2.method ?? "?";
|
|
9163
|
-
|
|
9164
|
-
Log.info(`${method} ${url} -> ${status2} (${duration}ms)`);
|
|
9280
|
+
Log.info(`${method} ${logPath(req2)} -> ${status2} (${duration}ms)`);
|
|
9165
9281
|
});
|
|
9166
9282
|
next();
|
|
9167
9283
|
};
|
|
@@ -9588,9 +9704,9 @@ var init_middleware = __esm({
|
|
|
9588
9704
|
const duration = Date.now() - (req2.startTime ?? Date.now());
|
|
9589
9705
|
const status2 = res.raw.statusCode;
|
|
9590
9706
|
const method = req2.method ?? "?";
|
|
9591
|
-
const
|
|
9707
|
+
const path10 = logPath(req2);
|
|
9592
9708
|
const color = status2 >= 400 ? "\x1B[31m" : status2 >= 300 ? "\x1B[33m" : "\x1B[32m";
|
|
9593
|
-
console.log(` ${color}${status2}\x1B[0m ${method} ${
|
|
9709
|
+
console.log(` ${color}${status2}\x1B[0m ${method} ${path10} \x1B[90m${duration}ms\x1B[0m`);
|
|
9594
9710
|
return [req2, res];
|
|
9595
9711
|
}
|
|
9596
9712
|
};
|
|
@@ -14959,6 +15075,7 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
|
|
|
14959
15075
|
}
|
|
14960
15076
|
const fields = fieldsOverride || parseFields(flags.fields || "");
|
|
14961
15077
|
const isCreate = name.startsWith("create_") || fieldsOverride !== void 0;
|
|
15078
|
+
const isView = isCreate && fieldsOverride === void 0 && table2.endsWith("_view");
|
|
14962
15079
|
const fileName = `${ts}_${name}.sql`;
|
|
14963
15080
|
const path10 = join15(dir, fileName);
|
|
14964
15081
|
setResolutionField("migration_path", `migrations/${fileName}`);
|
|
@@ -14968,7 +15085,13 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
|
|
|
14968
15085
|
}
|
|
14969
15086
|
let upSql;
|
|
14970
15087
|
let downSql;
|
|
14971
|
-
if (
|
|
15088
|
+
if (isView) {
|
|
15089
|
+
upSql = `-- tina4:edit write the CREATE VIEW statement, then remove the
|
|
15090
|
+
-- tina4:edit lines. For example:
|
|
15091
|
+
-- CREATE VIEW ${table2} AS
|
|
15092
|
+
-- SELECT id, /* columns */ FROM source_table WHERE /* ... */;`;
|
|
15093
|
+
downSql = `DROP VIEW IF EXISTS ${table2};`;
|
|
15094
|
+
} else if (isCreate) {
|
|
14972
15095
|
const colLines = [" id INTEGER PRIMARY KEY AUTOINCREMENT"];
|
|
14973
15096
|
for (const [fname, ftype] of fields) {
|
|
14974
15097
|
const info = FIELD_TYPE_MAP[ftype] || FIELD_TYPE_MAP.string;
|
|
@@ -14994,9 +15117,6 @@ DROP TABLE IF EXISTS ${table2};`;
|
|
|
14994
15117
|
|
|
14995
15118
|
-- UP
|
|
14996
15119
|
${upSql}
|
|
14997
|
-
|
|
14998
|
-
-- DOWN
|
|
14999
|
-
${downSql}
|
|
15000
15120
|
`;
|
|
15001
15121
|
writeFileSafe(path10, content);
|
|
15002
15122
|
const downPath = join15(dir, `${ts}_${name}.down.sql`);
|
|
@@ -15006,7 +15126,7 @@ ${downSql}
|
|
|
15006
15126
|
${downSql}
|
|
15007
15127
|
`;
|
|
15008
15128
|
writeFileSafe(downPath, downContent);
|
|
15009
|
-
if (emitTest && isCreate) emitMigrationTest(name, table2);
|
|
15129
|
+
if (emitTest && isCreate && !isView) emitMigrationTest(name, table2);
|
|
15010
15130
|
}
|
|
15011
15131
|
function generateMiddleware(name, _flags) {
|
|
15012
15132
|
const snake = toSnake(name);
|
|
@@ -15817,9 +15937,11 @@ function emitRouteStubTest(route) {
|
|
|
15817
15937
|
* Routing test for ${route} \u2014 no mocks, real Router + route discovery.
|
|
15818
15938
|
*
|
|
15819
15939
|
* Generated with src/routes/api/${route}/ by \`tina4nodejs generate route
|
|
15820
|
-
* ${route}\` (no --model). The handlers
|
|
15821
|
-
* implement them
|
|
15822
|
-
* register on the REAL Router, and the list handler
|
|
15940
|
+
* ${route}\` (no --model). The handlers start as AI-FILL stubs that throw until
|
|
15941
|
+
* you implement them. This tests what is live on generation: all five routes
|
|
15942
|
+
* register on the REAL Router, and the list handler is wired and callable. It
|
|
15943
|
+
* stays GREEN whether the stub still throws OR you have filled it in \u2014
|
|
15944
|
+
* implementing the handler never turns this test red.
|
|
15823
15945
|
* Run with: npx tsx tests/${route}.test.ts
|
|
15824
15946
|
*/
|
|
15825
15947
|
import { dirname, resolve } from "node:path";
|
|
@@ -15836,9 +15958,15 @@ for (const sig of ["GET /api/${route}", "POST /api/${route}", "GET /api/${route}
|
|
|
15836
15958
|
assert(\`route registered: \${sig}\`, sigs.includes(sig));
|
|
15837
15959
|
}
|
|
15838
15960
|
|
|
15839
|
-
// The
|
|
15840
|
-
|
|
15841
|
-
|
|
15961
|
+
// The list handler is WIRED: a loud AI-FILL stub (throws) on generation. This
|
|
15962
|
+
// stays green whether it still throws OR you have filled it in, so doing the
|
|
15963
|
+
// work never turns the suite red.
|
|
15964
|
+
assert("list handler is callable", typeof listHandler === "function");
|
|
15965
|
+
try {
|
|
15966
|
+
await listHandler({} as never, {} as never);
|
|
15967
|
+
} catch {
|
|
15968
|
+
// still the scaffold stub (throws until filled) \u2014 expected
|
|
15969
|
+
}`;
|
|
15842
15970
|
writeTest(route, standaloneTest(doc, body));
|
|
15843
15971
|
}
|
|
15844
15972
|
function emitMiddlewareTest(name, snake) {
|
|
@@ -15922,8 +16050,14 @@ ServiceRunner.register(service.name, service.handler, { interval: (service as {
|
|
|
15922
16050
|
assert("registers on a real ServiceRunner", ServiceRunner.list().some((s) => s.name === "${snake}"));
|
|
15923
16051
|
ServiceRunner.remove("${snake}");
|
|
15924
16052
|
|
|
15925
|
-
// The
|
|
15926
|
-
|
|
16053
|
+
// The task is WIRED: a loud AI-FILL stub (throws) on generation. This stays
|
|
16054
|
+
// green whether it still throws OR you have filled it in.
|
|
16055
|
+
assert("task is callable", typeof ${camel}Task === "function");
|
|
16056
|
+
try {
|
|
16057
|
+
await ${camel}Task({} as never);
|
|
16058
|
+
} catch {
|
|
16059
|
+
// still the scaffold stub (throws until filled) \u2014 expected
|
|
16060
|
+
}`;
|
|
15927
16061
|
writeTest(snake, standaloneTest(doc, body));
|
|
15928
16062
|
}
|
|
15929
16063
|
function emitQueueTest(topic, slug, pascal) {
|
|
@@ -15945,8 +16079,14 @@ assert("the job is really on the queue", new Queue({ topic: "${topic}" }).size()
|
|
|
15945
16079
|
assert("consumer default export is a daemon", worker.daemon === true);
|
|
15946
16080
|
assert("consumer handler is wired", typeof worker.handler === "function");
|
|
15947
16081
|
|
|
15948
|
-
// The per-job handler is
|
|
15949
|
-
|
|
16082
|
+
// The per-job handler is WIRED: a loud AI-FILL stub (throws) on generation.
|
|
16083
|
+
// This stays green whether it still throws OR you have filled it in.
|
|
16084
|
+
assert("handle is callable", typeof handle${pascal} === "function");
|
|
16085
|
+
try {
|
|
16086
|
+
await handle${pascal}({});
|
|
16087
|
+
} catch {
|
|
16088
|
+
// still the scaffold stub (throws until filled) \u2014 expected
|
|
16089
|
+
}`;
|
|
15950
16090
|
writeTest(slug, standaloneTest(doc, body));
|
|
15951
16091
|
}
|
|
15952
16092
|
function emitValidatorTest(name, snake, pascal) {
|
|
@@ -16008,9 +16148,14 @@ import { ${handler} } from "../src/routes/ws_${base}.js"; // importing register
|
|
|
16008
16148
|
const closed = await ${handler}(null as never, "close", "");
|
|
16009
16149
|
assert("close event handled cleanly", closed === undefined);
|
|
16010
16150
|
|
|
16011
|
-
// The "message" branch is
|
|
16012
|
-
|
|
16013
|
-
|
|
16151
|
+
// The "message" branch is WIRED: a loud AI-FILL stub (throws) on generation.
|
|
16152
|
+
// This stays green whether it still throws OR you have filled it in.
|
|
16153
|
+
try {
|
|
16154
|
+
await ${handler}(null as never, "message", "hi");
|
|
16155
|
+
assert("message branch is callable", true);
|
|
16156
|
+
} catch {
|
|
16157
|
+
assert("message branch is callable", true); // still the scaffold stub
|
|
16158
|
+
}`;
|
|
16014
16159
|
writeTest(`ws_${base}`, standaloneTest(doc, body));
|
|
16015
16160
|
}
|
|
16016
16161
|
function emitListenerTest(event, slug) {
|
|
@@ -16027,9 +16172,15 @@ import { Events } from "tina4-nodejs";
|
|
|
16027
16172
|
import "../src/listeners/${slug}.js"; // importing registers the listener via Events.on()`;
|
|
16028
16173
|
const body = `assert("listener registered on the real event bus", Events.listeners("${event}").length >= 1);
|
|
16029
16174
|
|
|
16030
|
-
//
|
|
16031
|
-
|
|
16032
|
-
|
|
16175
|
+
// Emitting reaches the listener. It starts as a loud AI-FILL stub (a strict emit
|
|
16176
|
+
// re-raises); once you implement it this test STILL passes, so doing the work
|
|
16177
|
+
// never turns the suite red.
|
|
16178
|
+
try {
|
|
16179
|
+
await Events.emit("${event}", { strict: true }, { id: 1 });
|
|
16180
|
+
assert("emitting reaches the listener", true);
|
|
16181
|
+
} catch {
|
|
16182
|
+
assert("emitting reaches the listener", true); // still the scaffold stub
|
|
16183
|
+
}`;
|
|
16033
16184
|
writeTest(slug, standaloneTest(doc, body));
|
|
16034
16185
|
}
|
|
16035
16186
|
function emitAuthTest() {
|
|
@@ -16584,9 +16735,9 @@ function agentLog(projectRoot3, category, message) {
|
|
|
16584
16735
|
if (!fs4.existsSync(logDir)) {
|
|
16585
16736
|
fs4.mkdirSync(logDir, { recursive: true });
|
|
16586
16737
|
}
|
|
16587
|
-
const
|
|
16738
|
+
const logPath2 = path3.join(logDir, "agent.log");
|
|
16588
16739
|
const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/\..+/, "Z");
|
|
16589
|
-
fs4.appendFileSync(
|
|
16740
|
+
fs4.appendFileSync(logPath2, `${ts} [${category}] ${message}
|
|
16590
16741
|
`, "utf-8");
|
|
16591
16742
|
} catch {
|
|
16592
16743
|
}
|
|
@@ -17582,13 +17733,13 @@ function registerDevTools(server) {
|
|
|
17582
17733
|
"git_status",
|
|
17583
17734
|
() => {
|
|
17584
17735
|
try {
|
|
17585
|
-
const { execFileSync:
|
|
17736
|
+
const { execFileSync: execFileSync6 } = req("node:child_process");
|
|
17586
17737
|
const cwd = path3.resolve(process.cwd());
|
|
17587
17738
|
const run = (args) => {
|
|
17588
|
-
return
|
|
17739
|
+
return execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
|
|
17589
17740
|
};
|
|
17590
17741
|
try {
|
|
17591
|
-
|
|
17742
|
+
execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
|
|
17592
17743
|
} catch {
|
|
17593
17744
|
return { error: "Not a git repository" };
|
|
17594
17745
|
}
|
|
@@ -21481,6 +21632,753 @@ var init_mongoBackend = __esm({
|
|
|
21481
21632
|
}
|
|
21482
21633
|
});
|
|
21483
21634
|
|
|
21635
|
+
// ../core/src/queueBackends/kafkaBackend.ts
|
|
21636
|
+
import { Worker as Worker2 } from "node:worker_threads";
|
|
21637
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
21638
|
+
function kafkaSecurityConfig(env = process.env) {
|
|
21639
|
+
const mapping = [
|
|
21640
|
+
["security.protocol", "SECURITY_PROTOCOL"],
|
|
21641
|
+
["ssl.ca.location", "SSL_CA_LOCATION"],
|
|
21642
|
+
["sasl.mechanism", "SASL_MECHANISM"],
|
|
21643
|
+
["sasl.username", "SASL_USERNAME"],
|
|
21644
|
+
["sasl.password", "SASL_PASSWORD"]
|
|
21645
|
+
];
|
|
21646
|
+
const config = {};
|
|
21647
|
+
for (const [rdk, suffix] of mapping) {
|
|
21648
|
+
const value = env[`TINA4_KAFKA_${suffix}`] || env[`KAFKA_${suffix}`];
|
|
21649
|
+
if (value) {
|
|
21650
|
+
config[rdk] = value;
|
|
21651
|
+
}
|
|
21652
|
+
}
|
|
21653
|
+
return config;
|
|
21654
|
+
}
|
|
21655
|
+
function kafkaOffsetReset(env = process.env) {
|
|
21656
|
+
return env.TINA4_KAFKA_AUTO_OFFSET_RESET || env.KAFKA_AUTO_OFFSET_RESET || "earliest";
|
|
21657
|
+
}
|
|
21658
|
+
var WORKER_SRC, KafkaBackend;
|
|
21659
|
+
var init_kafkaBackend = __esm({
|
|
21660
|
+
"../core/src/queueBackends/kafkaBackend.ts"() {
|
|
21661
|
+
"use strict";
|
|
21662
|
+
WORKER_SRC = `
|
|
21663
|
+
const net = require("node:net");
|
|
21664
|
+
const tls = require("node:tls");
|
|
21665
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
21666
|
+
|
|
21667
|
+
const brokers = workerData.brokers;
|
|
21668
|
+
const groupId = workerData.groupId;
|
|
21669
|
+
const security = workerData.security || {};
|
|
21670
|
+
const offsetReset = workerData.offsetReset || "earliest";
|
|
21671
|
+
const header = new Int32Array(workerData.sab, 0, 2); // [0]=flag, [1]=respLen
|
|
21672
|
+
const outBytes = new Uint8Array(workerData.sab, 8);
|
|
21673
|
+
|
|
21674
|
+
// Lowest versions Kafka 4.x still accepts: it REMOVED Produce v0-v2 / Fetch v0-v3
|
|
21675
|
+
// (the old message formats) and answers a removed version by closing the socket,
|
|
21676
|
+
// not with an error code. These are named constants so the source invariant test
|
|
21677
|
+
// (test/kafkaErrorCodes.test.ts) can assert the floors.
|
|
21678
|
+
const PRODUCE_VERSION = 3;
|
|
21679
|
+
const FETCH_VERSION = 4;
|
|
21680
|
+
|
|
21681
|
+
let correlationId = 0;
|
|
21682
|
+
let brokerSock = null;
|
|
21683
|
+
let coordSock = null;
|
|
21684
|
+
const offsets = {}; // topic -> next read offset (in-memory cursor)
|
|
21685
|
+
const inFlight = {}; // job id -> { offset, value, attempts, isEnvelope }
|
|
21686
|
+
|
|
21687
|
+
const COORDINATOR_ERRORS = [14, 15, 16];
|
|
21688
|
+
|
|
21689
|
+
function parseBroker(list) {
|
|
21690
|
+
const first = String(list).split(",")[0].trim();
|
|
21691
|
+
const i = first.lastIndexOf(":");
|
|
21692
|
+
if (i < 0) return { host: first || "localhost", port: 9092 };
|
|
21693
|
+
return { host: first.slice(0, i) || "localhost", port: parseInt(first.slice(i + 1), 10) || 9092 };
|
|
21694
|
+
}
|
|
21695
|
+
|
|
21696
|
+
function connect(host, port) {
|
|
21697
|
+
return new Promise(function (resolve, reject) {
|
|
21698
|
+
const proto = String(security["security.protocol"] || "PLAINTEXT").toUpperCase();
|
|
21699
|
+
const useTls = proto.indexOf("SSL") >= 0;
|
|
21700
|
+
let sock;
|
|
21701
|
+
const onErr = function (e) { reject(e); };
|
|
21702
|
+
if (useTls) {
|
|
21703
|
+
const opts = { host: host, port: port, servername: host };
|
|
21704
|
+
if (security["ssl.ca.location"]) opts.ca = require("node:fs").readFileSync(security["ssl.ca.location"]);
|
|
21705
|
+
sock = tls.connect(opts, function () { sock.removeListener("error", onErr); resolve(sock); });
|
|
21706
|
+
} else {
|
|
21707
|
+
sock = net.createConnection({ host: host, port: port }, function () { sock.removeListener("error", onErr); resolve(sock); });
|
|
21708
|
+
}
|
|
21709
|
+
sock.once("error", onErr);
|
|
21710
|
+
});
|
|
21711
|
+
}
|
|
21712
|
+
|
|
21713
|
+
// One request/response round trip on a socket: write the framed request, read a
|
|
21714
|
+
// 4-byte length then that many bytes, resolve with the payload AFTER the length
|
|
21715
|
+
// (so it starts at correlationId). Serialized \u2014 one in flight per socket.
|
|
21716
|
+
function rpc(sock, reqBuf) {
|
|
21717
|
+
return new Promise(function (resolve, reject) {
|
|
21718
|
+
let buf = Buffer.alloc(0);
|
|
21719
|
+
function onData(chunk) {
|
|
21720
|
+
buf = Buffer.concat([buf, chunk]);
|
|
21721
|
+
if (buf.length < 4) return;
|
|
21722
|
+
const size = buf.readInt32BE(0);
|
|
21723
|
+
if (buf.length < 4 + size) return;
|
|
21724
|
+
sock.removeListener("data", onData);
|
|
21725
|
+
sock.removeListener("error", onErr);
|
|
21726
|
+
resolve(buf.subarray(4, 4 + size));
|
|
21727
|
+
}
|
|
21728
|
+
function onErr(e) {
|
|
21729
|
+
sock.removeListener("data", onData);
|
|
21730
|
+
reject(e);
|
|
21731
|
+
}
|
|
21732
|
+
sock.on("data", onData);
|
|
21733
|
+
sock.once("error", onErr);
|
|
21734
|
+
sock.write(reqBuf);
|
|
21735
|
+
});
|
|
21736
|
+
}
|
|
21737
|
+
|
|
21738
|
+
// \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
|
|
21739
|
+
function kstr(s) {
|
|
21740
|
+
const b = Buffer.from(s, "utf-8");
|
|
21741
|
+
const out = Buffer.alloc(2 + b.length);
|
|
21742
|
+
out.writeInt16BE(b.length, 0);
|
|
21743
|
+
b.copy(out, 2);
|
|
21744
|
+
return out;
|
|
21745
|
+
}
|
|
21746
|
+
function frame(apiKey, apiVersion, body) {
|
|
21747
|
+
correlationId++;
|
|
21748
|
+
const client = Buffer.from("tina4-nodejs", "utf-8");
|
|
21749
|
+
const head = Buffer.alloc(2 + 2 + 4 + 2 + client.length);
|
|
21750
|
+
let p = 0;
|
|
21751
|
+
head.writeInt16BE(apiKey, p); p += 2;
|
|
21752
|
+
head.writeInt16BE(apiVersion, p); p += 2;
|
|
21753
|
+
head.writeInt32BE(correlationId, p); p += 4;
|
|
21754
|
+
head.writeInt16BE(client.length, p); p += 2;
|
|
21755
|
+
client.copy(head, p);
|
|
21756
|
+
const payload = Buffer.concat([head, body]);
|
|
21757
|
+
const out = Buffer.alloc(4 + payload.length);
|
|
21758
|
+
out.writeInt32BE(payload.length, 0);
|
|
21759
|
+
payload.copy(out, 4);
|
|
21760
|
+
return out;
|
|
21761
|
+
}
|
|
21762
|
+
|
|
21763
|
+
// \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
|
|
21764
|
+
const CRC32C_TABLE = (function () {
|
|
21765
|
+
const t = new Uint32Array(256);
|
|
21766
|
+
for (let n = 0; n < 256; n++) {
|
|
21767
|
+
let c = n;
|
|
21768
|
+
for (let k = 0; k < 8; k++) c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
|
|
21769
|
+
t[n] = c >>> 0;
|
|
21770
|
+
}
|
|
21771
|
+
return t;
|
|
21772
|
+
})();
|
|
21773
|
+
function crc32c(buf) {
|
|
21774
|
+
let crc = 0xffffffff;
|
|
21775
|
+
for (let i = 0; i < buf.length; i++) crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
|
|
21776
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
21777
|
+
}
|
|
21778
|
+
function zig(n) { return ((n << 1) ^ (n >> 31)) >>> 0; }
|
|
21779
|
+
function varU(u) {
|
|
21780
|
+
const b = [];
|
|
21781
|
+
let v = u >>> 0;
|
|
21782
|
+
for (;;) { if ((v & ~0x7f) === 0) { b.push(v); break; } b.push((v & 0x7f) | 0x80); v >>>= 7; }
|
|
21783
|
+
return Buffer.from(b);
|
|
21784
|
+
}
|
|
21785
|
+
function varint(n) { return varU(zig(n)); }
|
|
21786
|
+
function readVarint(buf, pos) {
|
|
21787
|
+
let result = 0, shift = 0, b;
|
|
21788
|
+
do { b = buf[pos++]; result |= (b & 0x7f) << shift; shift += 7; } while (b & 0x80);
|
|
21789
|
+
result = result >>> 0;
|
|
21790
|
+
return { value: (result >>> 1) ^ -(result & 1), next: pos };
|
|
21791
|
+
}
|
|
21792
|
+
function buildRecordBatch(valueBytes) {
|
|
21793
|
+
const now = BigInt(Date.now());
|
|
21794
|
+
const recBody = Buffer.concat([
|
|
21795
|
+
Buffer.from([0]), varint(0), varint(0), varint(-1),
|
|
21796
|
+
varint(valueBytes.length), valueBytes, varint(0),
|
|
21797
|
+
]);
|
|
21798
|
+
const record = Buffer.concat([varint(recBody.length), recBody]);
|
|
21799
|
+
const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
|
|
21800
|
+
let c = 0;
|
|
21801
|
+
crcBody.writeInt16BE(0, c); c += 2;
|
|
21802
|
+
crcBody.writeInt32BE(0, c); c += 4;
|
|
21803
|
+
crcBody.writeBigInt64BE(now, c); c += 8;
|
|
21804
|
+
crcBody.writeBigInt64BE(now, c); c += 8;
|
|
21805
|
+
crcBody.writeBigInt64BE(-1n, c); c += 8;
|
|
21806
|
+
crcBody.writeInt16BE(-1, c); c += 2;
|
|
21807
|
+
crcBody.writeInt32BE(-1, c); c += 4;
|
|
21808
|
+
crcBody.writeInt32BE(1, c); c += 4;
|
|
21809
|
+
record.copy(crcBody, c);
|
|
21810
|
+
const crc = crc32c(crcBody);
|
|
21811
|
+
const batchLength = 4 + 1 + 4 + crcBody.length;
|
|
21812
|
+
const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
|
|
21813
|
+
let h = 0;
|
|
21814
|
+
head.writeBigInt64BE(0n, h); h += 8;
|
|
21815
|
+
head.writeInt32BE(batchLength, h); h += 4;
|
|
21816
|
+
head.writeInt32BE(-1, h); h += 4;
|
|
21817
|
+
head.writeInt8(2, h); h += 1;
|
|
21818
|
+
head.writeUInt32BE(crc, h); h += 4;
|
|
21819
|
+
return Buffer.concat([head, crcBody]);
|
|
21820
|
+
}
|
|
21821
|
+
|
|
21822
|
+
// \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
|
|
21823
|
+
function produceRequest(topic, valueBytes) {
|
|
21824
|
+
const topicBuf = Buffer.from(topic, "utf-8");
|
|
21825
|
+
const batch = buildRecordBatch(valueBytes);
|
|
21826
|
+
const body = Buffer.alloc(2 + 2 + 4 + 4 + 2 + topicBuf.length + 4 + 4 + 4 + batch.length);
|
|
21827
|
+
let p = 0;
|
|
21828
|
+
body.writeInt16BE(-1, p); p += 2; // transactionalId null
|
|
21829
|
+
body.writeInt16BE(1, p); p += 2; // acks 1
|
|
21830
|
+
body.writeInt32BE(10000, p); p += 4; // timeoutMs
|
|
21831
|
+
body.writeInt32BE(1, p); p += 4; // topics
|
|
21832
|
+
body.writeInt16BE(topicBuf.length, p); p += 2;
|
|
21833
|
+
topicBuf.copy(body, p); p += topicBuf.length;
|
|
21834
|
+
body.writeInt32BE(1, p); p += 4; // partitions
|
|
21835
|
+
body.writeInt32BE(0, p); p += 4; // partition 0
|
|
21836
|
+
body.writeInt32BE(batch.length, p); p += 4;
|
|
21837
|
+
batch.copy(body, p);
|
|
21838
|
+
return frame(0, PRODUCE_VERSION, body);
|
|
21839
|
+
}
|
|
21840
|
+
function parseProduce(resp) {
|
|
21841
|
+
let pos = 4; // correlationId
|
|
21842
|
+
const topicCount = resp.readInt32BE(pos); pos += 4;
|
|
21843
|
+
let err = 0;
|
|
21844
|
+
for (let t = 0; t < topicCount; t++) {
|
|
21845
|
+
const tl = resp.readInt16BE(pos); pos += 2 + tl;
|
|
21846
|
+
const pc = resp.readInt32BE(pos); pos += 4;
|
|
21847
|
+
for (let pi = 0; pi < pc; pi++) {
|
|
21848
|
+
pos += 4; err = resp.readInt16BE(pos); pos += 2; pos += 8; pos += 8;
|
|
21849
|
+
}
|
|
21850
|
+
}
|
|
21851
|
+
return err;
|
|
21852
|
+
}
|
|
21853
|
+
async function produce(topic, valueBytes) {
|
|
21854
|
+
const sock = await broker();
|
|
21855
|
+
for (let attempt = 1; attempt <= 10; attempt++) {
|
|
21856
|
+
const err = parseProduce(await rpc(sock, produceRequest(topic, valueBytes)));
|
|
21857
|
+
if (err === 0) return;
|
|
21858
|
+
if ((err !== 3 && err !== 5) || attempt === 10) {
|
|
21859
|
+
throw new Error("Kafka rejected the produce for topic " + topic + ": error code " + err);
|
|
21860
|
+
}
|
|
21861
|
+
await sleep(200);
|
|
21862
|
+
}
|
|
21863
|
+
}
|
|
21864
|
+
|
|
21865
|
+
// \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
|
|
21866
|
+
function fetchRequest(topic, offset) {
|
|
21867
|
+
const topicBuf = Buffer.from(topic, "utf-8");
|
|
21868
|
+
const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + 2 + topicBuf.length + 4 + 4 + 8 + 4);
|
|
21869
|
+
let p = 0;
|
|
21870
|
+
buf.writeInt32BE(-1, p); p += 4; // replicaId
|
|
21871
|
+
buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
|
|
21872
|
+
buf.writeInt32BE(1, p); p += 4; // minBytes
|
|
21873
|
+
buf.writeInt32BE(1048576, p); p += 4; // maxBytes
|
|
21874
|
+
buf.writeInt8(0, p); p += 1; // isolation READ_UNCOMMITTED
|
|
21875
|
+
buf.writeInt32BE(1, p); p += 4; // topics
|
|
21876
|
+
buf.writeInt16BE(topicBuf.length, p); p += 2;
|
|
21877
|
+
topicBuf.copy(buf, p); p += topicBuf.length;
|
|
21878
|
+
buf.writeInt32BE(1, p); p += 4; // partitions
|
|
21879
|
+
buf.writeInt32BE(0, p); p += 4; // partition 0
|
|
21880
|
+
buf.writeBigInt64BE(BigInt(offset), p); p += 8;
|
|
21881
|
+
buf.writeInt32BE(1048576, p); p += 4;
|
|
21882
|
+
return frame(1, FETCH_VERSION, buf);
|
|
21883
|
+
}
|
|
21884
|
+
// Decode the first record of the partition's record-set: its value string and
|
|
21885
|
+
// absolute offset (baseOffset + offsetDelta). null = no usable record.
|
|
21886
|
+
function firstRecord(buf, start, end) {
|
|
21887
|
+
let pos = start;
|
|
21888
|
+
while (pos + 12 <= end) {
|
|
21889
|
+
const baseOffset = buf.readBigInt64BE(pos);
|
|
21890
|
+
const batchLength = buf.readInt32BE(pos + 8);
|
|
21891
|
+
const batchStart = pos + 12;
|
|
21892
|
+
const batchEnd = batchStart + batchLength;
|
|
21893
|
+
if (batchLength <= 0 || batchEnd > end) break;
|
|
21894
|
+
const magic = buf.readInt8(batchStart + 4);
|
|
21895
|
+
if (magic !== 2) { pos = batchEnd; continue; }
|
|
21896
|
+
let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
|
|
21897
|
+
const recordsCount = buf.readInt32BE(r); r += 4;
|
|
21898
|
+
for (let i = 0; i < recordsCount && r < batchEnd; i++) {
|
|
21899
|
+
const recLen = readVarint(buf, r);
|
|
21900
|
+
let rp = recLen.next;
|
|
21901
|
+
const recordEnd = rp + recLen.value;
|
|
21902
|
+
rp += 1;
|
|
21903
|
+
rp = readVarint(buf, rp).next; // timestampDelta
|
|
21904
|
+
const offDelta = readVarint(buf, rp); rp = offDelta.next;
|
|
21905
|
+
const keyLen = readVarint(buf, rp); rp = keyLen.next;
|
|
21906
|
+
if (keyLen.value >= 0) rp += keyLen.value;
|
|
21907
|
+
const valLen = readVarint(buf, rp); rp = valLen.next;
|
|
21908
|
+
if (valLen.value >= 0) {
|
|
21909
|
+
return {
|
|
21910
|
+
value: buf.subarray(rp, rp + valLen.value).toString("utf-8"),
|
|
21911
|
+
offset: Number(baseOffset) + offDelta.value,
|
|
21912
|
+
};
|
|
21913
|
+
}
|
|
21914
|
+
r = recordEnd;
|
|
21915
|
+
}
|
|
21916
|
+
pos = batchEnd;
|
|
21917
|
+
}
|
|
21918
|
+
return null;
|
|
21919
|
+
}
|
|
21920
|
+
async function fetchAt(topic, offset) {
|
|
21921
|
+
const sock = await broker();
|
|
21922
|
+
const resp = await rpc(sock, fetchRequest(topic, offset));
|
|
21923
|
+
let pos = 4; // correlationId
|
|
21924
|
+
pos += 4; // throttleTimeMs
|
|
21925
|
+
const topicCount = resp.readInt32BE(pos); pos += 4;
|
|
21926
|
+
let rec = null;
|
|
21927
|
+
for (let t = 0; t < topicCount; t++) {
|
|
21928
|
+
const tl = resp.readInt16BE(pos); pos += 2 + tl;
|
|
21929
|
+
const pc = resp.readInt32BE(pos); pos += 4;
|
|
21930
|
+
for (let pi = 0; pi < pc; pi++) {
|
|
21931
|
+
pos += 4;
|
|
21932
|
+
const err = resp.readInt16BE(pos); pos += 2;
|
|
21933
|
+
pos += 8; pos += 8;
|
|
21934
|
+
const aborted = resp.readInt32BE(pos); pos += 4;
|
|
21935
|
+
if (aborted > 0) pos += aborted * 16;
|
|
21936
|
+
const recSize = resp.readInt32BE(pos); pos += 4;
|
|
21937
|
+
if (err !== 0 && err !== 3 && err !== 5) {
|
|
21938
|
+
throw new Error("Kafka rejected the fetch for topic " + topic + ": error code " + err);
|
|
21939
|
+
}
|
|
21940
|
+
if (err === 0 && recSize > 0) {
|
|
21941
|
+
const r = firstRecord(resp, pos, pos + recSize);
|
|
21942
|
+
if (r !== null) rec = r;
|
|
21943
|
+
}
|
|
21944
|
+
if (recSize > 0) pos += recSize;
|
|
21945
|
+
}
|
|
21946
|
+
}
|
|
21947
|
+
return rec;
|
|
21948
|
+
}
|
|
21949
|
+
|
|
21950
|
+
// \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
|
|
21951
|
+
function readNullableString(buf, pos) {
|
|
21952
|
+
const len = buf.readInt16BE(pos); pos += 2;
|
|
21953
|
+
if (len < 0) return { value: null, next: pos };
|
|
21954
|
+
return { value: buf.toString("utf-8", pos, pos + len), next: pos + len };
|
|
21955
|
+
}
|
|
21956
|
+
async function findCoordinator() {
|
|
21957
|
+
const sock = await broker();
|
|
21958
|
+
for (let attempt = 0; attempt < 30; attempt++) {
|
|
21959
|
+
const body = Buffer.concat([kstr(groupId), Buffer.from([0])]); // key_type 0 = group
|
|
21960
|
+
const resp = await rpc(sock, frame(10, 1, body));
|
|
21961
|
+
let pos = 4; // correlationId
|
|
21962
|
+
pos += 4; // throttle
|
|
21963
|
+
const err = resp.readInt16BE(pos); pos += 2;
|
|
21964
|
+
pos = readNullableString(resp, pos).next; // error_message
|
|
21965
|
+
pos += 4; // node_id
|
|
21966
|
+
const hostRes = readNullableString(resp, pos); pos = hostRes.next;
|
|
21967
|
+
const port = resp.readInt32BE(pos);
|
|
21968
|
+
if (err === 0 && hostRes.value) return { host: hostRes.value, port: port };
|
|
21969
|
+
if (err !== 14 && err !== 15) {
|
|
21970
|
+
throw new Error("Kafka FindCoordinator failed for group " + groupId + ": error code " + err);
|
|
21971
|
+
}
|
|
21972
|
+
await sleep(300);
|
|
21973
|
+
}
|
|
21974
|
+
throw new Error("Kafka group coordinator for " + groupId + " did not become available");
|
|
21975
|
+
}
|
|
21976
|
+
async function coordinator() {
|
|
21977
|
+
if (coordSock) return coordSock;
|
|
21978
|
+
const c = await findCoordinator();
|
|
21979
|
+
coordSock = await connect(c.host, c.port);
|
|
21980
|
+
return coordSock;
|
|
21981
|
+
}
|
|
21982
|
+
function dropCoordinator() {
|
|
21983
|
+
if (coordSock) { try { coordSock.destroy(); } catch (e) { /* ignore */ } }
|
|
21984
|
+
coordSock = null;
|
|
21985
|
+
}
|
|
21986
|
+
function offsetCommitRequest(topic, offset) {
|
|
21987
|
+
const body = Buffer.concat([
|
|
21988
|
+
kstr(groupId),
|
|
21989
|
+
int32(-1), // generation_id -1 (simple consumer)
|
|
21990
|
+
kstr(""), // member_id ""
|
|
21991
|
+
int64(-1n), // retention_time -1
|
|
21992
|
+
int32(1), kstr(topic), int32(1), int32(0), int64(BigInt(offset)), int16(-1),
|
|
21993
|
+
]);
|
|
21994
|
+
return frame(8, 2, body);
|
|
21995
|
+
}
|
|
21996
|
+
function parseOffsetCommit(resp) {
|
|
21997
|
+
let pos = 4;
|
|
21998
|
+
const tc = resp.readInt32BE(pos); pos += 4;
|
|
21999
|
+
if (tc === 0) return 16;
|
|
22000
|
+
const tl = resp.readInt16BE(pos); pos += 2 + tl;
|
|
22001
|
+
const pc = resp.readInt32BE(pos); pos += 4;
|
|
22002
|
+
if (pc === 0) return 16;
|
|
22003
|
+
pos += 4;
|
|
22004
|
+
return resp.readInt16BE(pos);
|
|
22005
|
+
}
|
|
22006
|
+
async function offsetCommit(topic, offset) {
|
|
22007
|
+
var err = 0;
|
|
22008
|
+
for (var attempt = 0; attempt < 10; attempt++) {
|
|
22009
|
+
if (attempt > 0) { dropCoordinator(); await new Promise(function (r) { setTimeout(r, 200 * attempt); }); }
|
|
22010
|
+
err = parseOffsetCommit(await rpc(await coordinator(), offsetCommitRequest(topic, offset)));
|
|
22011
|
+
if (COORDINATOR_ERRORS.indexOf(err) < 0) break;
|
|
22012
|
+
}
|
|
22013
|
+
if (err !== 0) throw new Error("Kafka rejected the offset commit for " + topic + ": error code " + err);
|
|
22014
|
+
}
|
|
22015
|
+
function offsetFetchRequest(topic) {
|
|
22016
|
+
const body = Buffer.concat([kstr(groupId), int32(1), kstr(topic), int32(1), int32(0)]);
|
|
22017
|
+
return frame(9, 1, body);
|
|
22018
|
+
}
|
|
22019
|
+
function parseOffsetFetch(resp) {
|
|
22020
|
+
let pos = 4;
|
|
22021
|
+
const tc = resp.readInt32BE(pos); pos += 4;
|
|
22022
|
+
if (tc === 0) return { offset: -1, err: 16 };
|
|
22023
|
+
const tl = resp.readInt16BE(pos); pos += 2 + tl;
|
|
22024
|
+
const pc = resp.readInt32BE(pos); pos += 4;
|
|
22025
|
+
if (pc === 0) return { offset: -1, err: 16 };
|
|
22026
|
+
pos += 4;
|
|
22027
|
+
const offset = Number(resp.readBigInt64BE(pos)); pos += 8;
|
|
22028
|
+
pos = readNullableString(resp, pos).next;
|
|
22029
|
+
const err = resp.readInt16BE(pos);
|
|
22030
|
+
return { offset: offset, err: err };
|
|
22031
|
+
}
|
|
22032
|
+
async function offsetFetch(topic) {
|
|
22033
|
+
var r = { offset: -1, err: 0 };
|
|
22034
|
+
for (var attempt = 0; attempt < 10; attempt++) {
|
|
22035
|
+
if (attempt > 0) { dropCoordinator(); await new Promise(function (res) { setTimeout(res, 200 * attempt); }); }
|
|
22036
|
+
r = parseOffsetFetch(await rpc(await coordinator(), offsetFetchRequest(topic)));
|
|
22037
|
+
if (COORDINATOR_ERRORS.indexOf(r.err) < 0) break;
|
|
22038
|
+
}
|
|
22039
|
+
if (r.err !== 0) throw new Error("Kafka rejected the offset fetch for " + topic + ": error code " + r.err);
|
|
22040
|
+
return r.offset < 0 ? 0 : r.offset;
|
|
22041
|
+
}
|
|
22042
|
+
|
|
22043
|
+
function int16(n) { const b = Buffer.alloc(2); b.writeInt16BE(n, 0); return b; }
|
|
22044
|
+
function int32(n) { const b = Buffer.alloc(4); b.writeInt32BE(n, 0); return b; }
|
|
22045
|
+
function int64(n) { const b = Buffer.alloc(8); b.writeBigInt64BE(BigInt(n), 0); return b; }
|
|
22046
|
+
function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
|
|
22047
|
+
|
|
22048
|
+
async function broker() {
|
|
22049
|
+
if (brokerSock) return brokerSock;
|
|
22050
|
+
const b = parseBroker(brokers);
|
|
22051
|
+
brokerSock = await connect(b.host, b.port);
|
|
22052
|
+
return brokerSock;
|
|
22053
|
+
}
|
|
22054
|
+
|
|
22055
|
+
// Resume from the committed offset on the FIRST read of a topic in this worker,
|
|
22056
|
+
// then advance the in-memory cursor; the committed offset only moves on a
|
|
22057
|
+
// commit, so it lags and a crash before commit replays (at-least-once).
|
|
22058
|
+
async function fetchNext(topic) {
|
|
22059
|
+
if (!(topic in offsets)) offsets[topic] = await offsetFetch(topic);
|
|
22060
|
+
const rec = await fetchAt(topic, offsets[topic]);
|
|
22061
|
+
if (rec === null) return null;
|
|
22062
|
+
offsets[topic] = rec.offset + 1;
|
|
22063
|
+
return rec;
|
|
22064
|
+
}
|
|
22065
|
+
|
|
22066
|
+
function encodeEnvelope(id, payload, attempts) {
|
|
22067
|
+
return JSON.stringify({ id: id, payload: payload, status: "pending", createdAt: new Date().toISOString(), attempts: attempts, delayUntil: null });
|
|
22068
|
+
}
|
|
22069
|
+
|
|
22070
|
+
async function handle(req) {
|
|
22071
|
+
const op = req.op;
|
|
22072
|
+
if (op === "publish") {
|
|
22073
|
+
await produce(req.topic, Buffer.from(req.value, "utf-8"));
|
|
22074
|
+
return { ok: true };
|
|
22075
|
+
}
|
|
22076
|
+
if (op === "dequeueRaw") {
|
|
22077
|
+
// The value exactly as it sits on the wire (a raw record stays its bare
|
|
22078
|
+
// bytes \u2014 tina4-nodejs#264), with no id/offset tracking. For wire
|
|
22079
|
+
// inspection; the facade consumes through "pop", which normalises + tracks.
|
|
22080
|
+
const rec = await fetchNext(req.topic);
|
|
22081
|
+
if (rec === null) return { ok: true, message: null };
|
|
22082
|
+
let decoded;
|
|
22083
|
+
try { decoded = JSON.parse(rec.value); } catch (e) { decoded = rec.value; }
|
|
22084
|
+
return { ok: true, message: decoded };
|
|
22085
|
+
}
|
|
22086
|
+
if (op === "pop") {
|
|
22087
|
+
let rec;
|
|
22088
|
+
try {
|
|
22089
|
+
rec = await fetchNext(req.topic);
|
|
22090
|
+
} catch (e) {
|
|
22091
|
+
// A malformed/short response runs the parser off the end (a RangeError);
|
|
22092
|
+
// anything else is a transport failure. Both name the topic so the cause
|
|
22093
|
+
// is findable, and neither reads as an empty queue (ADR: a real failure
|
|
22094
|
+
// must never look idle). Wording matches the Python/PHP backends.
|
|
22095
|
+
const range = (e instanceof RangeError) || /out of range|bounds/i.test((e && e.message) || "");
|
|
22096
|
+
if (range) throw new Error("Kafka fetch for topic " + req.topic + " returned an unreadable response: " + ((e && e.message) || e));
|
|
22097
|
+
throw new Error("Kafka fetch for topic " + req.topic + " failed: " + ((e && e.message) || e));
|
|
22098
|
+
}
|
|
22099
|
+
if (rec === null) return { ok: true, message: null };
|
|
22100
|
+
const coordinate = req.topic + ":0:" + rec.offset;
|
|
22101
|
+
let decoded;
|
|
22102
|
+
try { decoded = JSON.parse(rec.value); } catch (e) { decoded = null; }
|
|
22103
|
+
let message;
|
|
22104
|
+
let isEnvelope = false;
|
|
22105
|
+
if (decoded !== null && typeof decoded === "object" && !Array.isArray(decoded) && "payload" in decoded) {
|
|
22106
|
+
message = decoded;
|
|
22107
|
+
isEnvelope = true;
|
|
22108
|
+
if (!message.id) message.id = coordinate;
|
|
22109
|
+
} else {
|
|
22110
|
+
message = { id: coordinate, payload: decoded === null ? rec.value : decoded, status: "pending", attempts: 0 };
|
|
22111
|
+
}
|
|
22112
|
+
// The Job lifecycle (complete/fail/retry) routes by the record's own topic,
|
|
22113
|
+
// so it must be carried back (like the file/mongodb backends do).
|
|
22114
|
+
message.topic = req.topic;
|
|
22115
|
+
inFlight[String(message.id)] = { offset: rec.offset, value: rec.value, attempts: message.attempts || 0, isEnvelope: isEnvelope };
|
|
22116
|
+
return { ok: true, message: message };
|
|
22117
|
+
}
|
|
22118
|
+
if (op === "complete") {
|
|
22119
|
+
const rec = inFlight[String(req.id)];
|
|
22120
|
+
if (rec) { delete inFlight[String(req.id)]; await offsetCommit(req.topic, rec.offset + 1); }
|
|
22121
|
+
return { ok: true };
|
|
22122
|
+
}
|
|
22123
|
+
if (op === "fail") {
|
|
22124
|
+
const rec = inFlight[String(req.id)];
|
|
22125
|
+
if (rec) {
|
|
22126
|
+
delete inFlight[String(req.id)];
|
|
22127
|
+
const attempts = (rec.attempts || 0) + 1;
|
|
22128
|
+
const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
|
|
22129
|
+
const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
|
|
22130
|
+
if (attempts < req.maxRetries) {
|
|
22131
|
+
await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
|
|
22132
|
+
} else {
|
|
22133
|
+
await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: attempts, error: req.error }), "utf-8"));
|
|
22134
|
+
}
|
|
22135
|
+
await offsetCommit(req.topic, rec.offset + 1);
|
|
22136
|
+
}
|
|
22137
|
+
return { ok: true };
|
|
22138
|
+
}
|
|
22139
|
+
if (op === "reject") {
|
|
22140
|
+
const rec = inFlight[String(req.id)];
|
|
22141
|
+
if (rec) {
|
|
22142
|
+
delete inFlight[String(req.id)];
|
|
22143
|
+
const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
|
|
22144
|
+
const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
|
|
22145
|
+
await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: req.maxRetries, error: req.reason }), "utf-8"));
|
|
22146
|
+
await offsetCommit(req.topic, rec.offset + 1);
|
|
22147
|
+
}
|
|
22148
|
+
return { ok: true };
|
|
22149
|
+
}
|
|
22150
|
+
if (op === "retry") {
|
|
22151
|
+
const rec = inFlight[String(req.id)];
|
|
22152
|
+
if (rec) {
|
|
22153
|
+
delete inFlight[String(req.id)];
|
|
22154
|
+
const attempts = (rec.attempts || 0) + 1;
|
|
22155
|
+
const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
|
|
22156
|
+
const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
|
|
22157
|
+
await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
|
|
22158
|
+
await offsetCommit(req.topic, rec.offset + 1);
|
|
22159
|
+
}
|
|
22160
|
+
return { ok: true };
|
|
22161
|
+
}
|
|
22162
|
+
if (op === "deadLetters") {
|
|
22163
|
+
// Read the <topic>.dead_letter topic from the beginning; every record on it
|
|
22164
|
+
// is a dead letter by construction. A throwaway cursor that never commits,
|
|
22165
|
+
// so it does not disturb the main consume position.
|
|
22166
|
+
const dlq = req.topic + ".dead_letter";
|
|
22167
|
+
const out = [];
|
|
22168
|
+
let off = 0;
|
|
22169
|
+
for (;;) {
|
|
22170
|
+
const rec = await fetchAt(dlq, off);
|
|
22171
|
+
if (rec === null) break;
|
|
22172
|
+
off = rec.offset + 1;
|
|
22173
|
+
try { out.push(JSON.parse(rec.value)); } catch (e) { /* skip */ }
|
|
22174
|
+
if (out.length > 10000) break;
|
|
22175
|
+
}
|
|
22176
|
+
return { ok: true, deadLetters: out };
|
|
22177
|
+
}
|
|
22178
|
+
if (op === "close") {
|
|
22179
|
+
try { if (brokerSock) brokerSock.destroy(); } catch (e) { /* ignore */ }
|
|
22180
|
+
dropCoordinator();
|
|
22181
|
+
return { ok: true, closing: true };
|
|
22182
|
+
}
|
|
22183
|
+
return { ok: false, error: "unknown op " + op };
|
|
22184
|
+
}
|
|
22185
|
+
|
|
22186
|
+
parentPort.on("message", async function (req) {
|
|
22187
|
+
let res;
|
|
22188
|
+
try { res = await handle(req); }
|
|
22189
|
+
catch (e) { res = { ok: false, error: (e && e.message) ? e.message : String(e) }; }
|
|
22190
|
+
const bytes = Buffer.from(JSON.stringify(res), "utf-8");
|
|
22191
|
+
outBytes.set(bytes.subarray(0, outBytes.length), 0);
|
|
22192
|
+
Atomics.store(header, 1, Math.min(bytes.length, outBytes.length));
|
|
22193
|
+
Atomics.store(header, 0, 1);
|
|
22194
|
+
Atomics.notify(header, 0);
|
|
22195
|
+
});
|
|
22196
|
+
`;
|
|
22197
|
+
KafkaBackend = class _KafkaBackend {
|
|
22198
|
+
brokers;
|
|
22199
|
+
groupId;
|
|
22200
|
+
worker = null;
|
|
22201
|
+
sab = null;
|
|
22202
|
+
header = null;
|
|
22203
|
+
outBytes = null;
|
|
22204
|
+
static SAB_SIZE = 1 << 20;
|
|
22205
|
+
// 1 MiB (8-byte header + response bytes)
|
|
22206
|
+
static CALL_TIMEOUT_MS = 2e4;
|
|
22207
|
+
constructor(config) {
|
|
22208
|
+
const url = process.env.TINA4_QUEUE_URL;
|
|
22209
|
+
const fromUrl = url ? url.replace(/^kafka:\/\//, "") : void 0;
|
|
22210
|
+
this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
|
|
22211
|
+
this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
|
|
22212
|
+
}
|
|
22213
|
+
/** Resolved connection config — exposed for testing/introspection. */
|
|
22214
|
+
getConfig() {
|
|
22215
|
+
return { brokers: this.brokers, groupId: this.groupId };
|
|
22216
|
+
}
|
|
22217
|
+
securityConfig() {
|
|
22218
|
+
return kafkaSecurityConfig();
|
|
22219
|
+
}
|
|
22220
|
+
producerConfig() {
|
|
22221
|
+
return { "bootstrap.servers": this.brokers, "client.id": "tina4-nodejs", ...this.securityConfig() };
|
|
22222
|
+
}
|
|
22223
|
+
consumerConfig() {
|
|
22224
|
+
return {
|
|
22225
|
+
"bootstrap.servers": this.brokers,
|
|
22226
|
+
"client.id": "tina4-nodejs",
|
|
22227
|
+
"group.id": this.groupId,
|
|
22228
|
+
"auto.offset.reset": kafkaOffsetReset(),
|
|
22229
|
+
"enable.auto.commit": false,
|
|
22230
|
+
...this.securityConfig()
|
|
22231
|
+
};
|
|
22232
|
+
}
|
|
22233
|
+
/** Lazily start the persistent worker + its shared buffer. */
|
|
22234
|
+
ensureWorker() {
|
|
22235
|
+
if (this.worker) return;
|
|
22236
|
+
this.sab = new SharedArrayBuffer(_KafkaBackend.SAB_SIZE);
|
|
22237
|
+
this.header = new Int32Array(this.sab, 0, 2);
|
|
22238
|
+
this.outBytes = new Uint8Array(this.sab, 8);
|
|
22239
|
+
this.worker = new Worker2(WORKER_SRC, {
|
|
22240
|
+
eval: true,
|
|
22241
|
+
workerData: {
|
|
22242
|
+
brokers: this.brokers,
|
|
22243
|
+
groupId: this.groupId,
|
|
22244
|
+
security: this.securityConfig(),
|
|
22245
|
+
offsetReset: kafkaOffsetReset(),
|
|
22246
|
+
sab: this.sab
|
|
22247
|
+
}
|
|
22248
|
+
});
|
|
22249
|
+
this.worker.unref();
|
|
22250
|
+
}
|
|
22251
|
+
/** One synchronous request to the worker: post, block on Atomics.wait, read. */
|
|
22252
|
+
request(req2) {
|
|
22253
|
+
this.ensureWorker();
|
|
22254
|
+
const header = this.header;
|
|
22255
|
+
const outBytes = this.outBytes;
|
|
22256
|
+
Atomics.store(header, 0, 0);
|
|
22257
|
+
this.worker.postMessage(req2);
|
|
22258
|
+
const waited = Atomics.wait(header, 0, 0, _KafkaBackend.CALL_TIMEOUT_MS);
|
|
22259
|
+
if (waited === "timed-out") {
|
|
22260
|
+
throw new Error(`Kafka ${String(req2.op)} for topic ${String(req2.topic ?? "")} timed out after ${_KafkaBackend.CALL_TIMEOUT_MS}ms`);
|
|
22261
|
+
}
|
|
22262
|
+
const len = Atomics.load(header, 1);
|
|
22263
|
+
const json = Buffer.from(outBytes.buffer, outBytes.byteOffset, len).toString("utf-8");
|
|
22264
|
+
const res = JSON.parse(json);
|
|
22265
|
+
if (res.ok === false) {
|
|
22266
|
+
throw new Error(String(res.error ?? "unknown Kafka worker error"));
|
|
22267
|
+
}
|
|
22268
|
+
return res;
|
|
22269
|
+
}
|
|
22270
|
+
/**
|
|
22271
|
+
* Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
|
|
22272
|
+
* as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
|
|
22273
|
+
* consumer reading the topic gets the schema it expects; otherwise the Tina4
|
|
22274
|
+
* job envelope. pop() unwraps both shapes (payload ?? the whole record).
|
|
22275
|
+
*/
|
|
22276
|
+
static encodeJob(id, payload, raw) {
|
|
22277
|
+
if (raw) return JSON.stringify(payload);
|
|
22278
|
+
return JSON.stringify({
|
|
22279
|
+
id,
|
|
22280
|
+
payload,
|
|
22281
|
+
status: "pending",
|
|
22282
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
22283
|
+
attempts: 0,
|
|
22284
|
+
delayUntil: null
|
|
22285
|
+
});
|
|
22286
|
+
}
|
|
22287
|
+
push(queue, payload, _delay, _priority, raw = false) {
|
|
22288
|
+
const id = randomUUID5();
|
|
22289
|
+
const value = _KafkaBackend.encodeJob(id, payload, raw);
|
|
22290
|
+
this.request({ op: "publish", topic: queue, value });
|
|
22291
|
+
return id;
|
|
22292
|
+
}
|
|
22293
|
+
pop(queue) {
|
|
22294
|
+
const res = this.request({ op: "pop", topic: queue });
|
|
22295
|
+
const message = res.message;
|
|
22296
|
+
return message ?? null;
|
|
22297
|
+
}
|
|
22298
|
+
/**
|
|
22299
|
+
* Read the next record's value exactly as it sits on the wire — a Tina4
|
|
22300
|
+
* envelope as produced, a raw record (tina4-nodejs#264) as its bare bytes —
|
|
22301
|
+
* with no id/offset tracking. For a foreign consumer's view of the schema;
|
|
22302
|
+
* the queue facade consumes through pop(), which also normalises and tracks
|
|
22303
|
+
* the offset so complete()/fail() can commit it.
|
|
22304
|
+
*/
|
|
22305
|
+
dequeue(queue) {
|
|
22306
|
+
const res = this.request({ op: "dequeueRaw", topic: queue });
|
|
22307
|
+
return res.message ?? null;
|
|
22308
|
+
}
|
|
22309
|
+
/** Commit the record's offset so a completed job never replays (ADR-0022 d.4). */
|
|
22310
|
+
complete(queue, id) {
|
|
22311
|
+
this.request({ op: "complete", topic: queue, id });
|
|
22312
|
+
}
|
|
22313
|
+
/**
|
|
22314
|
+
* Record a failed attempt: re-produce the job with an incremented attempts
|
|
22315
|
+
* count while it has retries left, else produce it to the dead-letter topic;
|
|
22316
|
+
* commit the original offset either way (ADR-0022 decision 2).
|
|
22317
|
+
*/
|
|
22318
|
+
fail(queue, id, error2, maxRetries, _retryBackoff) {
|
|
22319
|
+
this.request({ op: "fail", topic: queue, id, error: error2, maxRetries });
|
|
22320
|
+
}
|
|
22321
|
+
/** Dead-letter the job now, no retry (ADR-0023 reject), then commit the offset. */
|
|
22322
|
+
reject(queue, id, reason, maxRetries) {
|
|
22323
|
+
this.request({ op: "reject", topic: queue, id, reason, maxRetries });
|
|
22324
|
+
}
|
|
22325
|
+
/** Re-produce the job (manual retry) and commit the original offset. */
|
|
22326
|
+
retry(queue, id, delaySeconds) {
|
|
22327
|
+
this.request({ op: "retry", topic: queue, id, delaySeconds: delaySeconds ?? 0 });
|
|
22328
|
+
return true;
|
|
22329
|
+
}
|
|
22330
|
+
/** Read the dead-letter topic for this queue (every record on it is a dead letter). */
|
|
22331
|
+
deadLetters(queue, _maxRetries) {
|
|
22332
|
+
const res = this.request({ op: "deadLetters", topic: queue });
|
|
22333
|
+
return res.deadLetters ?? [];
|
|
22334
|
+
}
|
|
22335
|
+
/**
|
|
22336
|
+
* Refuse rather than silently answer from the local file store. Kafka keeps no
|
|
22337
|
+
* queryable registry of failed jobs: a failed record is re-produced to a
|
|
22338
|
+
* dead-letter TOPIC and the original offset committed past, and a log cannot be
|
|
22339
|
+
* queried by job state. Returning [] would claim nothing has failed.
|
|
22340
|
+
*/
|
|
22341
|
+
failed(_queue, _maxRetries) {
|
|
22342
|
+
throw new Error(
|
|
22343
|
+
"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."
|
|
22344
|
+
);
|
|
22345
|
+
}
|
|
22346
|
+
/** Refuse for the same reason failed() does (no queryable failed registry). */
|
|
22347
|
+
retryFailed(_queue, _maxRetries) {
|
|
22348
|
+
throw new Error(
|
|
22349
|
+
"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."
|
|
22350
|
+
);
|
|
22351
|
+
}
|
|
22352
|
+
size(_queue) {
|
|
22353
|
+
return 0;
|
|
22354
|
+
}
|
|
22355
|
+
clear(_queue) {
|
|
22356
|
+
throw new Error(
|
|
22357
|
+
"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."
|
|
22358
|
+
);
|
|
22359
|
+
}
|
|
22360
|
+
purge(_queue, _status) {
|
|
22361
|
+
throw new Error(
|
|
22362
|
+
"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."
|
|
22363
|
+
);
|
|
22364
|
+
}
|
|
22365
|
+
/** Stop the worker and release the connection. Idempotent. */
|
|
22366
|
+
close() {
|
|
22367
|
+
if (!this.worker) return;
|
|
22368
|
+
try {
|
|
22369
|
+
this.request({ op: "close" });
|
|
22370
|
+
} catch {
|
|
22371
|
+
}
|
|
22372
|
+
void this.worker.terminate();
|
|
22373
|
+
this.worker = null;
|
|
22374
|
+
this.sab = null;
|
|
22375
|
+
this.header = null;
|
|
22376
|
+
this.outBytes = null;
|
|
22377
|
+
}
|
|
22378
|
+
};
|
|
22379
|
+
}
|
|
22380
|
+
});
|
|
22381
|
+
|
|
21484
22382
|
// ../core/src/job.ts
|
|
21485
22383
|
function createJob(data, queue) {
|
|
21486
22384
|
const job = {
|
|
@@ -21533,7 +22431,7 @@ var init_job = __esm({
|
|
|
21533
22431
|
// ../core/src/queueBackends/liteBackend.ts
|
|
21534
22432
|
import { mkdirSync as mkdirSync11, readdirSync as readdirSync9, readFileSync as readFileSync14, writeFileSync as writeFileSync9, unlinkSync as unlinkSync7, existsSync as existsSync16 } from "node:fs";
|
|
21535
22433
|
import { join as join18 } from "node:path";
|
|
21536
|
-
import { randomUUID as
|
|
22434
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
21537
22435
|
var LiteBackend;
|
|
21538
22436
|
var init_liteBackend = __esm({
|
|
21539
22437
|
"../core/src/queueBackends/liteBackend.ts"() {
|
|
@@ -21600,7 +22498,7 @@ var init_liteBackend = __esm({
|
|
|
21600
22498
|
);
|
|
21601
22499
|
}
|
|
21602
22500
|
const dir = this.ensureDir(queue);
|
|
21603
|
-
const id =
|
|
22501
|
+
const id = randomUUID6();
|
|
21604
22502
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
21605
22503
|
const job = {
|
|
21606
22504
|
id,
|
|
@@ -22156,13 +23054,11 @@ function defaultVisibilityTimeout() {
|
|
|
22156
23054
|
return Number.isFinite(parsed) ? parsed : 300;
|
|
22157
23055
|
}
|
|
22158
23056
|
function unsupportedBrokerMessage(backendName) {
|
|
22159
|
-
const broker = backendName === "kafka" ? "Kafka" : "RabbitMQ";
|
|
22160
|
-
const lost = backendName === "kafka" ? "every pop() re-read offset 0, so the topic could never drain" : "pop() destroyed the message with no acknowledgement, so a consumer that died lost the job";
|
|
22161
23057
|
return `Queue backend "${backendName}" is not available in tina4-nodejs.
|
|
22162
23058
|
|
|
22163
|
-
Reason: the
|
|
23059
|
+
Reason: the RabbitMQ backend runs each operation in a separate child process, so no connection survives between pop() and complete(). Acknowledgement is therefore impossible, and pop() destroyed the message with no acknowledgement, so a consumer that died lost the job. It was losing work silently, so it now refuses instead.
|
|
22164
23060
|
|
|
22165
|
-
Use backend "
|
|
23061
|
+
Use backend "kafka" (now a persistent connection: at-least-once, drains, survives restarts), "mongodb" (at-least-once, real reservation + visibility timeout) or the default "file" backend. tina4-python, tina4-php and tina4-ruby still offer RabbitMQ.
|
|
22166
23062
|
|
|
22167
23063
|
Tracking: ADR-0022 in tina4-documentation/plan/v3/DECISIONS.md, findings in plan/v3/features/048-queue-backends.md.`;
|
|
22168
23064
|
}
|
|
@@ -22171,6 +23067,7 @@ var init_queue = __esm({
|
|
|
22171
23067
|
"../core/src/queue.ts"() {
|
|
22172
23068
|
"use strict";
|
|
22173
23069
|
init_mongoBackend();
|
|
23070
|
+
init_kafkaBackend();
|
|
22174
23071
|
init_liteBackend();
|
|
22175
23072
|
init_job();
|
|
22176
23073
|
init_liteBackend();
|
|
@@ -22191,7 +23088,7 @@ var init_queue = __esm({
|
|
|
22191
23088
|
* - new Queue("mongodb", { path: "data/queue" }) // legacy
|
|
22192
23089
|
* - new Queue() // file backend, default topic
|
|
22193
23090
|
*
|
|
22194
|
-
* Throws on backend "rabbitmq"
|
|
23091
|
+
* Throws on backend "rabbitmq" (ADR-0022); "kafka" is now supported.
|
|
22195
23092
|
*/
|
|
22196
23093
|
constructor(backendOrConfig, config) {
|
|
22197
23094
|
let resolvedConfig = {};
|
|
@@ -22209,8 +23106,10 @@ var init_queue = __esm({
|
|
|
22209
23106
|
this._retryBackoff = resolvedConfig.retryBackoff ?? 0;
|
|
22210
23107
|
this._visibilityTimeout = resolvedConfig.visibilityTimeout ?? defaultVisibilityTimeout();
|
|
22211
23108
|
this.liteBackend = new LiteBackend(this.basePath, this._visibilityTimeout);
|
|
22212
|
-
if (this.backendName === "rabbitmq"
|
|
23109
|
+
if (this.backendName === "rabbitmq") {
|
|
22213
23110
|
throw new Error(unsupportedBrokerMessage(this.backendName));
|
|
23111
|
+
} else if (this.backendName === "kafka") {
|
|
23112
|
+
this.externalBackend = new KafkaBackend({ visibilityTimeout: this._visibilityTimeout });
|
|
22214
23113
|
} else if (this.backendName === "mongodb" || this.backendName === "mongo") {
|
|
22215
23114
|
this.externalBackend = new MongoBackend2({ visibilityTimeout: this._visibilityTimeout });
|
|
22216
23115
|
} else if (!["file", "default", "lite"].includes(this.backendName)) {
|
|
@@ -25278,10 +26177,10 @@ function devGitStatusLabel(code) {
|
|
|
25278
26177
|
async function devGitInfo(root) {
|
|
25279
26178
|
const empty = { branch: "", gitRoot: null, status: /* @__PURE__ */ new Map() };
|
|
25280
26179
|
try {
|
|
25281
|
-
const { execFileSync:
|
|
26180
|
+
const { execFileSync: execFileSync6 } = await import("node:child_process");
|
|
25282
26181
|
const git = (args) => {
|
|
25283
26182
|
try {
|
|
25284
|
-
return
|
|
26183
|
+
return execFileSync6("git", args, { cwd: root, timeout: 3e3, encoding: "utf-8" }).toString();
|
|
25285
26184
|
} catch {
|
|
25286
26185
|
return null;
|
|
25287
26186
|
}
|
|
@@ -27108,9 +28007,9 @@ var init_devAdmin = __esm({
|
|
|
27108
28007
|
return;
|
|
27109
28008
|
}
|
|
27110
28009
|
try {
|
|
27111
|
-
const { execFileSync:
|
|
28010
|
+
const { execFileSync: execFileSync6 } = await import("node:child_process");
|
|
27112
28011
|
const args = ["install", dev ? "--save-dev" : "--save", pkg];
|
|
27113
|
-
const output =
|
|
28012
|
+
const output = execFileSync6("npm", args, {
|
|
27114
28013
|
cwd: resolve12(process.cwd()),
|
|
27115
28014
|
timeout: 12e4,
|
|
27116
28015
|
encoding: "utf-8"
|
|
@@ -27122,15 +28021,15 @@ var init_devAdmin = __esm({
|
|
|
27122
28021
|
};
|
|
27123
28022
|
handleGitStatus = async (_req, res) => {
|
|
27124
28023
|
try {
|
|
27125
|
-
const { execFileSync:
|
|
28024
|
+
const { execFileSync: execFileSync6 } = await import("node:child_process");
|
|
27126
28025
|
const cwd = resolve12(process.cwd());
|
|
27127
28026
|
try {
|
|
27128
|
-
|
|
28027
|
+
execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
|
|
27129
28028
|
} catch {
|
|
27130
28029
|
res.json({ error: "Not a git repository" }, 400);
|
|
27131
28030
|
return;
|
|
27132
28031
|
}
|
|
27133
|
-
const run = (args) =>
|
|
28032
|
+
const run = (args) => execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
|
|
27134
28033
|
res.json({
|
|
27135
28034
|
branch: run(["branch", "--show-current"]),
|
|
27136
28035
|
status: run(["status", "--porcelain"]).split(/\r?\n/).filter((l) => l),
|
|
@@ -27260,8 +28159,8 @@ var init_devAdmin = __esm({
|
|
|
27260
28159
|
return;
|
|
27261
28160
|
}
|
|
27262
28161
|
try {
|
|
27263
|
-
const { execFileSync:
|
|
27264
|
-
const output =
|
|
28162
|
+
const { execFileSync: execFileSync6 } = await import("node:child_process");
|
|
28163
|
+
const output = execFileSync6("npx", ["tina4nodejs", "generate", kind, name], {
|
|
27265
28164
|
cwd: resolve12(process.cwd()),
|
|
27266
28165
|
timeout: 3e4,
|
|
27267
28166
|
encoding: "utf-8"
|
|
@@ -27707,6 +28606,359 @@ var init_background = __esm({
|
|
|
27707
28606
|
}
|
|
27708
28607
|
});
|
|
27709
28608
|
|
|
28609
|
+
// ../core/src/tcp.ts
|
|
28610
|
+
import { createServer as createServer3 } from "node:net";
|
|
28611
|
+
function resolveMaxBacklog(explicit) {
|
|
28612
|
+
if (explicit !== void 0) return explicit > 0 ? explicit : DEFAULT_MAX_BACKLOG;
|
|
28613
|
+
const raw = (process.env.TINA4_TCP_MAX_BACKLOG ?? "").trim();
|
|
28614
|
+
if (raw === "") return DEFAULT_MAX_BACKLOG;
|
|
28615
|
+
const value = Number.parseInt(raw, 10);
|
|
28616
|
+
return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_BACKLOG;
|
|
28617
|
+
}
|
|
28618
|
+
function tcpService(port, options = {}) {
|
|
28619
|
+
const service = new TcpService(port, options);
|
|
28620
|
+
services.set(service.name, service);
|
|
28621
|
+
return service;
|
|
28622
|
+
}
|
|
28623
|
+
function tcp(name = "default") {
|
|
28624
|
+
const service = services.get(name);
|
|
28625
|
+
if (!service) {
|
|
28626
|
+
const known = services.size === 0 ? "(none registered)" : [...services.keys()].join(", ");
|
|
28627
|
+
throw new Error(`no tcp_service named '${name}' is registered; known services: ${known}`);
|
|
28628
|
+
}
|
|
28629
|
+
return service;
|
|
28630
|
+
}
|
|
28631
|
+
function registeredTcpServices() {
|
|
28632
|
+
return [...services.values()];
|
|
28633
|
+
}
|
|
28634
|
+
function clearTcpRegistry() {
|
|
28635
|
+
services.clear();
|
|
28636
|
+
}
|
|
28637
|
+
async function startAllTcpServices(host = "0.0.0.0") {
|
|
28638
|
+
for (const service of registeredTcpServices()) {
|
|
28639
|
+
try {
|
|
28640
|
+
await service.start(host);
|
|
28641
|
+
} catch (error2) {
|
|
28642
|
+
Log.error(`tcp_service '${service.name}' failed to start: ${String(error2)}`);
|
|
28643
|
+
}
|
|
28644
|
+
}
|
|
28645
|
+
}
|
|
28646
|
+
function stopAcceptingAllTcpServices() {
|
|
28647
|
+
for (const service of registeredTcpServices()) {
|
|
28648
|
+
try {
|
|
28649
|
+
service.stopAccepting();
|
|
28650
|
+
} catch (error2) {
|
|
28651
|
+
Log.error(`tcp_service '${service.name}' stop-accepting failed: ${String(error2)}`);
|
|
28652
|
+
}
|
|
28653
|
+
}
|
|
28654
|
+
}
|
|
28655
|
+
async function drainAllTcpServices() {
|
|
28656
|
+
for (const service of registeredTcpServices()) {
|
|
28657
|
+
try {
|
|
28658
|
+
await service.drain();
|
|
28659
|
+
} catch (error2) {
|
|
28660
|
+
Log.error(`tcp_service '${service.name}' drain failed: ${String(error2)}`);
|
|
28661
|
+
}
|
|
28662
|
+
}
|
|
28663
|
+
}
|
|
28664
|
+
var DEFAULT_MAX_BACKLOG, TcpConnection, TcpService, services;
|
|
28665
|
+
var init_tcp = __esm({
|
|
28666
|
+
"../core/src/tcp.ts"() {
|
|
28667
|
+
"use strict";
|
|
28668
|
+
init_logger();
|
|
28669
|
+
DEFAULT_MAX_BACKLOG = 1 << 20;
|
|
28670
|
+
TcpConnection = class {
|
|
28671
|
+
constructor(socket, service) {
|
|
28672
|
+
this.socket = socket;
|
|
28673
|
+
this.service = service;
|
|
28674
|
+
this.remoteAddr = `${socket.remoteAddress ?? ""}:${socket.remotePort ?? 0}`;
|
|
28675
|
+
}
|
|
28676
|
+
socket;
|
|
28677
|
+
service;
|
|
28678
|
+
/** The registry id (the IMEI), or null until identify() is called. */
|
|
28679
|
+
id = null;
|
|
28680
|
+
/** Per-connection mutable state bag — the app's parse buffer, auth flag. */
|
|
28681
|
+
context = {};
|
|
28682
|
+
/** The raw TCP peer address ("127.0.0.1:54321"), never a forwarded header. */
|
|
28683
|
+
remoteAddr;
|
|
28684
|
+
lastActivity = Date.now();
|
|
28685
|
+
lineBuffer = Buffer.alloc(0);
|
|
28686
|
+
closed = false;
|
|
28687
|
+
closeFired = false;
|
|
28688
|
+
get isClosed() {
|
|
28689
|
+
return this.closed;
|
|
28690
|
+
}
|
|
28691
|
+
/**
|
|
28692
|
+
* Register this live connection under an app-chosen id (the IMEI). A second
|
|
28693
|
+
* connection identifying with the same id SUPERSEDES the first in the
|
|
28694
|
+
* registry — exactly a device that dropped and reconnected.
|
|
28695
|
+
*/
|
|
28696
|
+
identify(appId) {
|
|
28697
|
+
this.id = String(appId);
|
|
28698
|
+
this.service._registerId(this.id, this);
|
|
28699
|
+
return this;
|
|
28700
|
+
}
|
|
28701
|
+
/**
|
|
28702
|
+
* Write raw bytes to THIS socket. Returns true when queued/sent, false when
|
|
28703
|
+
* the connection is closed or dropped for backpressure. A stalled reader
|
|
28704
|
+
* (never draining) is bounded: once more than the service's maxBacklog bytes
|
|
28705
|
+
* are outstanding, the connection is dropped rather than buffered without end
|
|
28706
|
+
* (mirrors the WebSocket TINA4_WS_MAX_BACKLOG posture).
|
|
28707
|
+
*/
|
|
28708
|
+
send(data) {
|
|
28709
|
+
if (this.closed) return false;
|
|
28710
|
+
const buffer = typeof data === "string" ? Buffer.from(data) : data;
|
|
28711
|
+
this.socket.write(buffer);
|
|
28712
|
+
if (this.socket.writableLength > this.service.maxBacklog) {
|
|
28713
|
+
Log.warning(
|
|
28714
|
+
`tcp_service '${this.service.name}': dropping a stalled reader \u2014 ${this.socket.writableLength} bytes queued exceeds the ${this.service.maxBacklog}-byte backlog limit`
|
|
28715
|
+
);
|
|
28716
|
+
this.close();
|
|
28717
|
+
return false;
|
|
28718
|
+
}
|
|
28719
|
+
return true;
|
|
28720
|
+
}
|
|
28721
|
+
/**
|
|
28722
|
+
* Close this connection. on_close fires exactly once (from the socket's close
|
|
28723
|
+
* event) and the registry entry is removed.
|
|
28724
|
+
*/
|
|
28725
|
+
close() {
|
|
28726
|
+
if (this.closed) return;
|
|
28727
|
+
this.closed = true;
|
|
28728
|
+
try {
|
|
28729
|
+
this.socket.end(() => this.socket.destroy());
|
|
28730
|
+
} catch {
|
|
28731
|
+
this.socket.destroy();
|
|
28732
|
+
}
|
|
28733
|
+
}
|
|
28734
|
+
/** @internal mark activity for the idle reaper. */
|
|
28735
|
+
_touch() {
|
|
28736
|
+
this.lastActivity = Date.now();
|
|
28737
|
+
}
|
|
28738
|
+
/** @internal fire on_close exactly once (called from the service removal path). */
|
|
28739
|
+
_fireClose() {
|
|
28740
|
+
if (this.closeFired) return;
|
|
28741
|
+
this.closeFired = true;
|
|
28742
|
+
this.closed = true;
|
|
28743
|
+
const handler = this.service._callbacks.onClose;
|
|
28744
|
+
if (!handler) return;
|
|
28745
|
+
try {
|
|
28746
|
+
void Promise.resolve(handler(this)).catch((error2) => {
|
|
28747
|
+
Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error2)}`);
|
|
28748
|
+
});
|
|
28749
|
+
} catch (error2) {
|
|
28750
|
+
Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error2)}`);
|
|
28751
|
+
}
|
|
28752
|
+
}
|
|
28753
|
+
};
|
|
28754
|
+
TcpService = class {
|
|
28755
|
+
name;
|
|
28756
|
+
port;
|
|
28757
|
+
maxBacklog;
|
|
28758
|
+
/** @internal the callback bag, read by TcpConnection. */
|
|
28759
|
+
_callbacks;
|
|
28760
|
+
idleTimeout;
|
|
28761
|
+
maxConnections;
|
|
28762
|
+
connections = /* @__PURE__ */ new Set();
|
|
28763
|
+
byId = /* @__PURE__ */ new Map();
|
|
28764
|
+
server = null;
|
|
28765
|
+
owner = false;
|
|
28766
|
+
boundPortValue = null;
|
|
28767
|
+
reaper = null;
|
|
28768
|
+
constructor(port, options = {}) {
|
|
28769
|
+
this.port = port;
|
|
28770
|
+
this.name = options.name ?? "default";
|
|
28771
|
+
this._callbacks = {
|
|
28772
|
+
onConnect: options.onConnect,
|
|
28773
|
+
onData: options.onData,
|
|
28774
|
+
onClose: options.onClose,
|
|
28775
|
+
onLine: options.onLine
|
|
28776
|
+
};
|
|
28777
|
+
this.idleTimeout = options.idleTimeout ?? 0;
|
|
28778
|
+
this.maxConnections = options.maxConnections ?? null;
|
|
28779
|
+
this.maxBacklog = resolveMaxBacklog(options.maxBacklog);
|
|
28780
|
+
}
|
|
28781
|
+
get isOwner() {
|
|
28782
|
+
return this.owner;
|
|
28783
|
+
}
|
|
28784
|
+
/** The port actually bound (resolves an ephemeral port=0 to the real one). */
|
|
28785
|
+
get boundPort() {
|
|
28786
|
+
return this.boundPortValue ?? this.port;
|
|
28787
|
+
}
|
|
28788
|
+
count() {
|
|
28789
|
+
return this.connections.size;
|
|
28790
|
+
}
|
|
28791
|
+
// ── Registry (D4 — server -> device push) ──────────────────────────────────
|
|
28792
|
+
/** @internal */
|
|
28793
|
+
_registerId(appId, conn) {
|
|
28794
|
+
this.byId.set(appId, conn);
|
|
28795
|
+
}
|
|
28796
|
+
/** The live connection for an app id, or null if unknown or closed. */
|
|
28797
|
+
connection(appId) {
|
|
28798
|
+
const conn = this.byId.get(String(appId));
|
|
28799
|
+
if (!conn || conn.isClosed) return null;
|
|
28800
|
+
return conn;
|
|
28801
|
+
}
|
|
28802
|
+
/**
|
|
28803
|
+
* Write bytes to exactly the connection identified by appId. A send to an
|
|
28804
|
+
* unknown or closed id is a NO-OP that returns false — never a throw.
|
|
28805
|
+
*/
|
|
28806
|
+
sendTo(appId, data) {
|
|
28807
|
+
const conn = this.connection(appId);
|
|
28808
|
+
if (!conn) return false;
|
|
28809
|
+
return conn.send(data);
|
|
28810
|
+
}
|
|
28811
|
+
/** Write bytes to every live connection. Returns how many received it. */
|
|
28812
|
+
broadcast(data) {
|
|
28813
|
+
let delivered = 0;
|
|
28814
|
+
for (const conn of [...this.connections]) {
|
|
28815
|
+
if (conn.send(data)) delivered += 1;
|
|
28816
|
+
}
|
|
28817
|
+
return delivered;
|
|
28818
|
+
}
|
|
28819
|
+
// ── Lifecycle ───────────────────────────────────────────────────────────────
|
|
28820
|
+
/**
|
|
28821
|
+
* Bind the listener on host:port on the event loop. SO_REUSEPORT is OFF, so
|
|
28822
|
+
* under a multi-worker deployment exactly ONE worker wins the bind; a worker
|
|
28823
|
+
* that finds the port already bound skips silently (single-owner, D1).
|
|
28824
|
+
* Resolves true when THIS call bound the port.
|
|
28825
|
+
*/
|
|
28826
|
+
start(host = "0.0.0.0") {
|
|
28827
|
+
if (this.server) return Promise.resolve(this.owner);
|
|
28828
|
+
return new Promise((resolve21) => {
|
|
28829
|
+
const server = createServer3((socket) => this.handleConnection(socket));
|
|
28830
|
+
this.server = server;
|
|
28831
|
+
const onError = (error2) => {
|
|
28832
|
+
if (error2.code === "EADDRINUSE" || error2.code === "EADDRNOTAVAIL") {
|
|
28833
|
+
this.owner = false;
|
|
28834
|
+
this.server = null;
|
|
28835
|
+
Log.info(
|
|
28836
|
+
`tcp_service '${this.name}' port ${this.port} is already bound by another worker \u2014 single-owner, this worker will not bind (${error2.code})`
|
|
28837
|
+
);
|
|
28838
|
+
resolve21(false);
|
|
28839
|
+
return;
|
|
28840
|
+
}
|
|
28841
|
+
Log.error(`tcp_service '${this.name}' failed to start: ${error2.message}`);
|
|
28842
|
+
this.server = null;
|
|
28843
|
+
resolve21(false);
|
|
28844
|
+
};
|
|
28845
|
+
server.once("error", onError);
|
|
28846
|
+
server.listen(this.port, host, () => {
|
|
28847
|
+
server.off("error", onError);
|
|
28848
|
+
server.on("error", (error2) => Log.error(`tcp_service '${this.name}' error: ${String(error2)}`));
|
|
28849
|
+
this.owner = true;
|
|
28850
|
+
const addr = server.address();
|
|
28851
|
+
this.boundPortValue = typeof addr === "object" && addr ? addr.port : this.port;
|
|
28852
|
+
Log.info(`tcp_service '${this.name}' listening on ${host}:${this.boundPortValue}`);
|
|
28853
|
+
this.startReaper();
|
|
28854
|
+
resolve21(true);
|
|
28855
|
+
});
|
|
28856
|
+
});
|
|
28857
|
+
}
|
|
28858
|
+
handleConnection(socket) {
|
|
28859
|
+
if (this.maxConnections !== null && this.connections.size >= this.maxConnections) {
|
|
28860
|
+
socket.destroy();
|
|
28861
|
+
return;
|
|
28862
|
+
}
|
|
28863
|
+
const conn = new TcpConnection(socket, this);
|
|
28864
|
+
this.connections.add(conn);
|
|
28865
|
+
socket.on("data", (chunk) => {
|
|
28866
|
+
socket.pause();
|
|
28867
|
+
void this.dispatch(conn, chunk).finally(() => {
|
|
28868
|
+
if (!conn.isClosed) socket.resume();
|
|
28869
|
+
});
|
|
28870
|
+
});
|
|
28871
|
+
socket.on("close", () => this.remove(conn));
|
|
28872
|
+
socket.on("error", () => {
|
|
28873
|
+
});
|
|
28874
|
+
const onConnect = this._callbacks.onConnect;
|
|
28875
|
+
if (onConnect) {
|
|
28876
|
+
void Promise.resolve(onConnect(conn)).catch((error2) => {
|
|
28877
|
+
Log.error(`tcp_service '${this.name}' onConnect error: ${String(error2)}`);
|
|
28878
|
+
});
|
|
28879
|
+
}
|
|
28880
|
+
}
|
|
28881
|
+
async dispatch(conn, chunk) {
|
|
28882
|
+
conn._touch();
|
|
28883
|
+
const { onData, onLine } = this._callbacks;
|
|
28884
|
+
if (onData) {
|
|
28885
|
+
try {
|
|
28886
|
+
await onData(conn, chunk);
|
|
28887
|
+
} catch (error2) {
|
|
28888
|
+
Log.error(`tcp_service '${this.name}' onData error: ${String(error2)}`);
|
|
28889
|
+
}
|
|
28890
|
+
}
|
|
28891
|
+
if (onLine) {
|
|
28892
|
+
conn.lineBuffer = Buffer.concat([conn.lineBuffer, chunk]);
|
|
28893
|
+
let newline = conn.lineBuffer.indexOf(10);
|
|
28894
|
+
while (newline !== -1) {
|
|
28895
|
+
let line = conn.lineBuffer.subarray(0, newline);
|
|
28896
|
+
conn.lineBuffer = conn.lineBuffer.subarray(newline + 1);
|
|
28897
|
+
if (line.length > 0 && line[line.length - 1] === 13) {
|
|
28898
|
+
line = line.subarray(0, line.length - 1);
|
|
28899
|
+
}
|
|
28900
|
+
try {
|
|
28901
|
+
await onLine(conn, line);
|
|
28902
|
+
} catch (error2) {
|
|
28903
|
+
Log.error(`tcp_service '${this.name}' onLine error: ${String(error2)}`);
|
|
28904
|
+
}
|
|
28905
|
+
newline = conn.lineBuffer.indexOf(10);
|
|
28906
|
+
}
|
|
28907
|
+
}
|
|
28908
|
+
}
|
|
28909
|
+
/** @internal remove a connection and fire on_close exactly once. */
|
|
28910
|
+
remove(conn) {
|
|
28911
|
+
const existed = this.connections.delete(conn);
|
|
28912
|
+
if (conn.id !== null && this.byId.get(conn.id) === conn) {
|
|
28913
|
+
this.byId.delete(conn.id);
|
|
28914
|
+
}
|
|
28915
|
+
if (existed) conn._fireClose();
|
|
28916
|
+
}
|
|
28917
|
+
// ── Idle reaper (D1 consumer shape — default OFF) ───────────────────────────
|
|
28918
|
+
startReaper() {
|
|
28919
|
+
if (this.idleTimeout <= 0 || this.reaper) return;
|
|
28920
|
+
const intervalMs = Math.max(50, Math.min(1e3, this.idleTimeout / 2 * 1e3));
|
|
28921
|
+
this.reaper = setInterval(() => this.reapIdle(), intervalMs);
|
|
28922
|
+
this.reaper.unref();
|
|
28923
|
+
}
|
|
28924
|
+
reapIdle() {
|
|
28925
|
+
const now = Date.now();
|
|
28926
|
+
const limitMs = this.idleTimeout * 1e3;
|
|
28927
|
+
for (const conn of [...this.connections]) {
|
|
28928
|
+
if (now - conn.lastActivity >= limitMs) conn.close();
|
|
28929
|
+
}
|
|
28930
|
+
}
|
|
28931
|
+
/** Stop accepting new connections (close the listener). Live conns stay. */
|
|
28932
|
+
stopAccepting() {
|
|
28933
|
+
if (this.reaper) {
|
|
28934
|
+
clearInterval(this.reaper);
|
|
28935
|
+
this.reaper = null;
|
|
28936
|
+
}
|
|
28937
|
+
if (this.server && this.owner) {
|
|
28938
|
+
this.server.close();
|
|
28939
|
+
}
|
|
28940
|
+
}
|
|
28941
|
+
/** Close every live connection (firing on_close) and release the listener. */
|
|
28942
|
+
async drain() {
|
|
28943
|
+
this.stopAccepting();
|
|
28944
|
+
for (const conn of [...this.connections]) conn.close();
|
|
28945
|
+
if (this.server) {
|
|
28946
|
+
await new Promise((resolve21) => {
|
|
28947
|
+
this.server.close(() => resolve21());
|
|
28948
|
+
this.server.unref();
|
|
28949
|
+
}).catch(() => void 0);
|
|
28950
|
+
this.server = null;
|
|
28951
|
+
}
|
|
28952
|
+
}
|
|
28953
|
+
/** Stop accepting and drain in one call (used by direct callers/tests). */
|
|
28954
|
+
async stop() {
|
|
28955
|
+
await this.drain();
|
|
28956
|
+
}
|
|
28957
|
+
};
|
|
28958
|
+
services = /* @__PURE__ */ new Map();
|
|
28959
|
+
}
|
|
28960
|
+
});
|
|
28961
|
+
|
|
27710
28962
|
// ../core/src/events.ts
|
|
27711
28963
|
var events_exports = {};
|
|
27712
28964
|
__export(events_exports, {
|
|
@@ -29359,6 +30611,12 @@ async function invokeRouteHandler(match, req2, res) {
|
|
|
29359
30611
|
if (args.length === 0) return await match.handler();
|
|
29360
30612
|
return await match.handler(...args);
|
|
29361
30613
|
}
|
|
30614
|
+
function coerceHandlerResult(res, result) {
|
|
30615
|
+
if (res.raw.writableEnded || res.raw.headersSent) return;
|
|
30616
|
+
if (result === void 0 || result === null) return;
|
|
30617
|
+
if (result === res) return;
|
|
30618
|
+
res(result);
|
|
30619
|
+
}
|
|
29362
30620
|
async function renderIfTemplateRoute(match, res, result) {
|
|
29363
30621
|
if (res.raw.writableEnded) return;
|
|
29364
30622
|
if (!match.template) return;
|
|
@@ -29378,7 +30636,9 @@ async function runMatchedRoute(ctx) {
|
|
|
29378
30636
|
handlerSkipped = !proceed || res.raw.writableEnded;
|
|
29379
30637
|
}
|
|
29380
30638
|
if (!handlerSkipped) {
|
|
29381
|
-
|
|
30639
|
+
const result = await invokeRouteHandler(match, req2, res);
|
|
30640
|
+
await renderIfTemplateRoute(match, res, result);
|
|
30641
|
+
coerceHandlerResult(res, result);
|
|
29382
30642
|
}
|
|
29383
30643
|
const afterMiddleware = [...ctx.allGlobalMiddleware, ...routeMiddlewareClasses];
|
|
29384
30644
|
if (afterMiddleware.length > 0) {
|
|
@@ -29915,7 +31175,7 @@ async function startServer(config) {
|
|
|
29915
31175
|
server.on("upgrade", (req2, socket, head) => {
|
|
29916
31176
|
const upPath = (req2.url ?? "/").split("?")[0];
|
|
29917
31177
|
if (isDevMode() && upPath === "/__dev_reload") {
|
|
29918
|
-
if (!devHostAllowed(req2.headers.host)) {
|
|
31178
|
+
if (!devHostAllowed(req2.headers.host) || !devPeerAllowed(socket.remoteAddress)) {
|
|
29919
31179
|
try {
|
|
29920
31180
|
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
29921
31181
|
socket.destroy();
|
|
@@ -29939,6 +31199,7 @@ async function startServer(config) {
|
|
|
29939
31199
|
server.listen(port, host, async () => {
|
|
29940
31200
|
if (!cluster.isWorker) writePidfile(port);
|
|
29941
31201
|
const siblingServers = await startLoopbackSiblings(port, host, dispatch);
|
|
31202
|
+
await startAllTcpServices(host);
|
|
29942
31203
|
const displayHost = host === "0.0.0.0" ? "localhost" : host;
|
|
29943
31204
|
const isDebug = isTruthy(process.env.TINA4_DEBUG);
|
|
29944
31205
|
const logLevel = (process.env.TINA4_LOG_LEVEL ?? "DEBUG").toUpperCase();
|
|
@@ -30029,6 +31290,8 @@ ${reset2}
|
|
|
30029
31290
|
if (wsClosed > 0) {
|
|
30030
31291
|
Log.info(`Closed ${wsClosed} WebSocket connection(s) with 1001 going away`);
|
|
30031
31292
|
}
|
|
31293
|
+
stopAcceptingAllTcpServices();
|
|
31294
|
+
await drainAllTcpServices();
|
|
30032
31295
|
const budgetSeconds = shutdownTimeoutSeconds();
|
|
30033
31296
|
let timer;
|
|
30034
31297
|
const outcome = await Promise.race([
|
|
@@ -30071,6 +31334,8 @@ ${reset2}
|
|
|
30071
31334
|
process.off("SIGTERM", onSigterm);
|
|
30072
31335
|
process.off("SIGINT", onSigint);
|
|
30073
31336
|
stopAllBackgroundTasks();
|
|
31337
|
+
stopAcceptingAllTcpServices();
|
|
31338
|
+
void drainAllTcpServices();
|
|
30074
31339
|
if (aiServer) aiServer.close();
|
|
30075
31340
|
server.close();
|
|
30076
31341
|
for (const sibling of siblingServers) {
|
|
@@ -30199,6 +31464,7 @@ var init_server = __esm({
|
|
|
30199
31464
|
init_feedback();
|
|
30200
31465
|
init_i18n();
|
|
30201
31466
|
init_background();
|
|
31467
|
+
init_tcp();
|
|
30202
31468
|
init_version();
|
|
30203
31469
|
__filename = fileURLToPath7(import.meta.url);
|
|
30204
31470
|
__dirname = dirname12(__filename);
|
|
@@ -30362,7 +31628,7 @@ var init_env = __esm({
|
|
|
30362
31628
|
});
|
|
30363
31629
|
|
|
30364
31630
|
// ../core/src/fakeData.ts
|
|
30365
|
-
import { randomInt, randomUUID as
|
|
31631
|
+
import { randomInt, randomUUID as randomUUID7 } from "node:crypto";
|
|
30366
31632
|
import { existsSync as existsSync24, readdirSync as readdirSync16 } from "node:fs";
|
|
30367
31633
|
import { resolve as resolve16, join as join26 } from "node:path";
|
|
30368
31634
|
function mulberry32(seed) {
|
|
@@ -30815,7 +32081,7 @@ var init_fakeData = __esm({
|
|
|
30815
32081
|
const block = (n) => Array.from({ length: n }, hex).join("");
|
|
30816
32082
|
return `${block(8)}-${block(4)}-${block(4)}-${block(4)}-${block(12)}`;
|
|
30817
32083
|
}
|
|
30818
|
-
return
|
|
32084
|
+
return randomUUID7();
|
|
30819
32085
|
}
|
|
30820
32086
|
url() {
|
|
30821
32087
|
const domain = this.pick(DOMAINS);
|
|
@@ -33088,7 +34354,7 @@ import net4 from "node:net";
|
|
|
33088
34354
|
import tls2 from "node:tls";
|
|
33089
34355
|
import { readFileSync as readFileSync23 } from "node:fs";
|
|
33090
34356
|
import { basename as basename7 } from "node:path";
|
|
33091
|
-
import { randomUUID as
|
|
34357
|
+
import { randomUUID as randomUUID8 } from "node:crypto";
|
|
33092
34358
|
function normaliseEncryption(value, kind) {
|
|
33093
34359
|
const normalised = value.trim().toLowerCase();
|
|
33094
34360
|
if (!MAIL_ENCRYPTION_VALUES.includes(normalised)) {
|
|
@@ -33720,7 +34986,7 @@ var init_messenger = __esm({
|
|
|
33720
34986
|
);
|
|
33721
34987
|
}
|
|
33722
34988
|
const recipients = this.prepareRecipients(options, true);
|
|
33723
|
-
const messageId = `${
|
|
34989
|
+
const messageId = `${randomUUID8()}@${this.host}`;
|
|
33724
34990
|
if (recipients.allRecipients.length === 0) {
|
|
33725
34991
|
return { success: false, message: "No recipients specified", id: null };
|
|
33726
34992
|
}
|
|
@@ -36562,7 +37828,7 @@ var init_aiClient = __esm({
|
|
|
36562
37828
|
|
|
36563
37829
|
// ../core/src/queueBackends/rabbitmqBackend.ts
|
|
36564
37830
|
import { execFileSync as execFileSync5 } from "node:child_process";
|
|
36565
|
-
import { randomUUID as
|
|
37831
|
+
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
36566
37832
|
function parseAmqpUrl(url) {
|
|
36567
37833
|
const config = {};
|
|
36568
37834
|
let rest = url.replace(/^amqps:\/\//, "").replace(/^amqp:\/\//, "");
|
|
@@ -36998,7 +38264,7 @@ var init_rabbitmqBackend = __esm({
|
|
|
36998
38264
|
"The rabbitmq queue backend cannot honour push(raw=true): raw emits the message with no Tina4 envelope, which only a message bus consumed by non-Tina4 systems (Kafka) needs. This backend stores an internal envelope (payload/priority/attempts) that pop(), the retry lifecycle and dead-lettering depend on, so there is nothing to omit. Use the kafka backend for raw external messages."
|
|
36999
38265
|
);
|
|
37000
38266
|
}
|
|
37001
|
-
const id =
|
|
38267
|
+
const id = randomUUID9();
|
|
37002
38268
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
37003
38269
|
const job = {
|
|
37004
38270
|
id,
|
|
@@ -37042,586 +38308,6 @@ var init_rabbitmqBackend = __esm({
|
|
|
37042
38308
|
}
|
|
37043
38309
|
});
|
|
37044
38310
|
|
|
37045
|
-
// ../core/src/queueBackends/kafkaBackend.ts
|
|
37046
|
-
import { execFileSync as execFileSync6 } from "node:child_process";
|
|
37047
|
-
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
37048
|
-
function kafkaSecurityConfig(env = process.env) {
|
|
37049
|
-
const mapping = [
|
|
37050
|
-
["security.protocol", "SECURITY_PROTOCOL"],
|
|
37051
|
-
["ssl.ca.location", "SSL_CA_LOCATION"],
|
|
37052
|
-
["sasl.mechanism", "SASL_MECHANISM"],
|
|
37053
|
-
["sasl.username", "SASL_USERNAME"],
|
|
37054
|
-
["sasl.password", "SASL_PASSWORD"]
|
|
37055
|
-
];
|
|
37056
|
-
const config = {};
|
|
37057
|
-
for (const [rdk, suffix] of mapping) {
|
|
37058
|
-
const value = env[`TINA4_KAFKA_${suffix}`] || env[`KAFKA_${suffix}`];
|
|
37059
|
-
if (value) {
|
|
37060
|
-
config[rdk] = value;
|
|
37061
|
-
}
|
|
37062
|
-
}
|
|
37063
|
-
return config;
|
|
37064
|
-
}
|
|
37065
|
-
function kafkaOffsetReset(env = process.env) {
|
|
37066
|
-
return env.TINA4_KAFKA_AUTO_OFFSET_RESET || env.KAFKA_AUTO_OFFSET_RESET || "earliest";
|
|
37067
|
-
}
|
|
37068
|
-
var API_PRODUCE, API_FETCH, KafkaBackend;
|
|
37069
|
-
var init_kafkaBackend = __esm({
|
|
37070
|
-
"../core/src/queueBackends/kafkaBackend.ts"() {
|
|
37071
|
-
"use strict";
|
|
37072
|
-
API_PRODUCE = 0;
|
|
37073
|
-
API_FETCH = 1;
|
|
37074
|
-
KafkaBackend = class _KafkaBackend {
|
|
37075
|
-
brokers;
|
|
37076
|
-
groupId;
|
|
37077
|
-
constructor(config) {
|
|
37078
|
-
const url = process.env.TINA4_QUEUE_URL;
|
|
37079
|
-
const fromUrl = url ? url.replace(/^kafka:\/\//, "") : void 0;
|
|
37080
|
-
this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
|
|
37081
|
-
this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
|
|
37082
|
-
}
|
|
37083
|
-
/**
|
|
37084
|
-
* Resolved connection config — exposed for testing/introspection.
|
|
37085
|
-
*/
|
|
37086
|
-
getConfig() {
|
|
37087
|
-
return { brokers: this.brokers, groupId: this.groupId };
|
|
37088
|
-
}
|
|
37089
|
-
/**
|
|
37090
|
-
* Resolved SSL/SASL client config from the environment (PLAINTEXT default).
|
|
37091
|
-
* Mirrors Python's `KafkaConnector._security_config`.
|
|
37092
|
-
*/
|
|
37093
|
-
securityConfig() {
|
|
37094
|
-
return kafkaSecurityConfig();
|
|
37095
|
-
}
|
|
37096
|
-
/**
|
|
37097
|
-
* Full producer config — brokers + client id + the resolved security block.
|
|
37098
|
-
* The security keys are applied to BOTH producer and consumer (matching
|
|
37099
|
-
* Python's `_connect_confluent`).
|
|
37100
|
-
*/
|
|
37101
|
-
producerConfig() {
|
|
37102
|
-
return {
|
|
37103
|
-
"bootstrap.servers": this.brokers,
|
|
37104
|
-
"client.id": "tina4-nodejs",
|
|
37105
|
-
...this.securityConfig()
|
|
37106
|
-
};
|
|
37107
|
-
}
|
|
37108
|
-
/**
|
|
37109
|
-
* Full consumer config — brokers + client id + group id + the SAME resolved
|
|
37110
|
-
* security block applied to the producer.
|
|
37111
|
-
*/
|
|
37112
|
-
consumerConfig() {
|
|
37113
|
-
return {
|
|
37114
|
-
"bootstrap.servers": this.brokers,
|
|
37115
|
-
"client.id": "tina4-nodejs",
|
|
37116
|
-
"group.id": this.groupId,
|
|
37117
|
-
"auto.offset.reset": kafkaOffsetReset(),
|
|
37118
|
-
"enable.auto.commit": false,
|
|
37119
|
-
...this.securityConfig()
|
|
37120
|
-
};
|
|
37121
|
-
}
|
|
37122
|
-
/**
|
|
37123
|
-
* Parse broker string into host:port.
|
|
37124
|
-
*/
|
|
37125
|
-
parseBroker() {
|
|
37126
|
-
const parts = this.brokers.split(",")[0].trim().split(":");
|
|
37127
|
-
return {
|
|
37128
|
-
host: parts[0] ?? "localhost",
|
|
37129
|
-
port: parts[1] ? parseInt(parts[1], 10) : 9092
|
|
37130
|
-
};
|
|
37131
|
-
}
|
|
37132
|
-
/**
|
|
37133
|
-
* Execute a Kafka operation synchronously via a child process.
|
|
37134
|
-
*
|
|
37135
|
-
* The wire protocol is hand-rolled (Tina4 is zero-dependency — no npm Kafka
|
|
37136
|
-
* library). Produce uses Produce **v3** carrying a Kafka **v2 RecordBatch**
|
|
37137
|
-
* (magic byte 2) with a **CRC-32C** (Castagnoli) checksum; Fetch uses Fetch
|
|
37138
|
-
* **v4** and parses the v2 RecordBatch out of the response. Both formats are
|
|
37139
|
-
* what a modern KRaft broker (apache/kafka 3.7.0) requires — the old
|
|
37140
|
-
* Produce-v0 / message-format-v0 / CRC=0 batch is rejected by such brokers.
|
|
37141
|
-
*/
|
|
37142
|
-
execSync(operation, topic, data) {
|
|
37143
|
-
const broker = this.parseBroker();
|
|
37144
|
-
const script = `
|
|
37145
|
-
const net = require("node:net");
|
|
37146
|
-
const host = ${JSON.stringify(broker.host)};
|
|
37147
|
-
const port = ${broker.port};
|
|
37148
|
-
const operation = ${JSON.stringify(operation)};
|
|
37149
|
-
const topic = ${JSON.stringify(topic)};
|
|
37150
|
-
const groupId = ${JSON.stringify(this.groupId)};
|
|
37151
|
-
const data = ${JSON.stringify(data ?? "")};
|
|
37152
|
-
const API_PRODUCE = ${API_PRODUCE};
|
|
37153
|
-
const API_FETCH = ${API_FETCH};
|
|
37154
|
-
const PRODUCE_VERSION = 3; // v3+ requires the v2 RecordBatch format
|
|
37155
|
-
const FETCH_VERSION = 4; // v4 returns v2 RecordBatches + isolation_level
|
|
37156
|
-
let correlationId = 0;
|
|
37157
|
-
|
|
37158
|
-
// \u2500\u2500 CRC-32C (Castagnoli, polynomial 0x1EDC6F41), table-based \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
37159
|
-
// Node has no built-in CRC-32C; the v2 RecordBatch mandates it over the
|
|
37160
|
-
// bytes from \`attributes\` to the end of the batch. A wrong CRC makes the
|
|
37161
|
-
// broker drop the connection, so this must be exact.
|
|
37162
|
-
const CRC32C_TABLE = (() => {
|
|
37163
|
-
const table = new Uint32Array(256);
|
|
37164
|
-
for (let n = 0; n < 256; n++) {
|
|
37165
|
-
let c = n;
|
|
37166
|
-
for (let k = 0; k < 8; k++) {
|
|
37167
|
-
c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
|
|
37168
|
-
}
|
|
37169
|
-
table[n] = c >>> 0;
|
|
37170
|
-
}
|
|
37171
|
-
return table;
|
|
37172
|
-
})();
|
|
37173
|
-
function crc32c(buf) {
|
|
37174
|
-
let crc = 0xffffffff;
|
|
37175
|
-
for (let i = 0; i < buf.length; i++) {
|
|
37176
|
-
crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
|
|
37177
|
-
}
|
|
37178
|
-
return (crc ^ 0xffffffff) >>> 0;
|
|
37179
|
-
}
|
|
37180
|
-
|
|
37181
|
-
// \u2500\u2500 Kafka protocol varints (zigzag-encoded signed varints) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
37182
|
-
function encodeZigZag(n) {
|
|
37183
|
-
// 32-bit zigzag: (n << 1) ^ (n >> 31)
|
|
37184
|
-
return ((n << 1) ^ (n >> 31)) >>> 0;
|
|
37185
|
-
}
|
|
37186
|
-
function encodeVarintUnsigned(u) {
|
|
37187
|
-
const bytes = [];
|
|
37188
|
-
let v = u >>> 0;
|
|
37189
|
-
while (true) {
|
|
37190
|
-
if ((v & ~0x7f) === 0) { bytes.push(v); break; }
|
|
37191
|
-
bytes.push((v & 0x7f) | 0x80);
|
|
37192
|
-
v >>>= 7;
|
|
37193
|
-
}
|
|
37194
|
-
return Buffer.from(bytes);
|
|
37195
|
-
}
|
|
37196
|
-
function encodeVarint(n) {
|
|
37197
|
-
// signed varint = zigzag then unsigned-varint
|
|
37198
|
-
return encodeVarintUnsigned(encodeZigZag(n));
|
|
37199
|
-
}
|
|
37200
|
-
function decodeVarint(buf, pos) {
|
|
37201
|
-
// returns { value, next } \u2014 signed (zigzag-decoded)
|
|
37202
|
-
let result = 0, shift = 0, b;
|
|
37203
|
-
do {
|
|
37204
|
-
b = buf[pos++];
|
|
37205
|
-
result |= (b & 0x7f) << shift;
|
|
37206
|
-
shift += 7;
|
|
37207
|
-
} while (b & 0x80);
|
|
37208
|
-
result = result >>> 0;
|
|
37209
|
-
// zigzag decode
|
|
37210
|
-
const value = (result >>> 1) ^ -(result & 1);
|
|
37211
|
-
return { value, next: pos };
|
|
37212
|
-
}
|
|
37213
|
-
|
|
37214
|
-
// \u2500\u2500 v2 RecordBatch builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
37215
|
-
function buildRecordBatch(valueBytes) {
|
|
37216
|
-
const now = BigInt(Date.now());
|
|
37217
|
-
|
|
37218
|
-
// Build the single record body.
|
|
37219
|
-
// record = attributes:int8(0), timestampDelta:varint(0),
|
|
37220
|
-
// offsetDelta:varint(0), keyLen:varint(-1 null),
|
|
37221
|
-
// valueLen:varint(len), value, headerCount:varint(0)
|
|
37222
|
-
const recBody = Buffer.concat([
|
|
37223
|
-
Buffer.from([0]), // attributes (int8)
|
|
37224
|
-
encodeVarint(0), // timestampDelta
|
|
37225
|
-
encodeVarint(0), // offsetDelta
|
|
37226
|
-
encodeVarint(-1), // keyLen (-1 = null key)
|
|
37227
|
-
encodeVarint(valueBytes.length), // valueLen
|
|
37228
|
-
valueBytes, // value (JSON payload bytes)
|
|
37229
|
-
encodeVarint(0), // headerCount
|
|
37230
|
-
]);
|
|
37231
|
-
// record length prefix = signed varint of recBody length
|
|
37232
|
-
const record = Buffer.concat([encodeVarint(recBody.length), recBody]);
|
|
37233
|
-
const recordsCount = 1;
|
|
37234
|
-
|
|
37235
|
-
// The portion the CRC covers starts at \`attributes\` and runs to end.
|
|
37236
|
-
// crcBody = attributes:int16(0), lastOffsetDelta:int32(count-1),
|
|
37237
|
-
// firstTimestamp:int64, maxTimestamp:int64,
|
|
37238
|
-
// producerId:int64(-1), producerEpoch:int16(-1),
|
|
37239
|
-
// baseSequence:int32(-1), recordsCount:int32, records
|
|
37240
|
-
const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
|
|
37241
|
-
let c = 0;
|
|
37242
|
-
crcBody.writeInt16BE(0, c); c += 2; // attributes
|
|
37243
|
-
crcBody.writeInt32BE(recordsCount - 1, c); c += 4; // lastOffsetDelta
|
|
37244
|
-
crcBody.writeBigInt64BE(now, c); c += 8; // firstTimestamp
|
|
37245
|
-
crcBody.writeBigInt64BE(now, c); c += 8; // maxTimestamp
|
|
37246
|
-
crcBody.writeBigInt64BE(-1n, c); c += 8; // producerId
|
|
37247
|
-
crcBody.writeInt16BE(-1, c); c += 2; // producerEpoch
|
|
37248
|
-
crcBody.writeInt32BE(-1, c); c += 4; // baseSequence
|
|
37249
|
-
crcBody.writeInt32BE(recordsCount, c); c += 4; // recordsCount
|
|
37250
|
-
record.copy(crcBody, c);
|
|
37251
|
-
|
|
37252
|
-
const crc = crc32c(crcBody);
|
|
37253
|
-
|
|
37254
|
-
// Header before the CRC-covered region:
|
|
37255
|
-
// baseOffset:int64(0), batchLength:int32, partitionLeaderEpoch:int32(-1),
|
|
37256
|
-
// magic:int8(2), crc:uint32. batchLength counts everything AFTER itself
|
|
37257
|
-
// (partitionLeaderEpoch through end of records) = 4 + 1 + 4 + crcBody.
|
|
37258
|
-
const batchLength = 4 + 1 + 4 + crcBody.length;
|
|
37259
|
-
const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
|
|
37260
|
-
let h = 0;
|
|
37261
|
-
head.writeBigInt64BE(0n, h); h += 8; // baseOffset
|
|
37262
|
-
head.writeInt32BE(batchLength, h); h += 4; // batchLength
|
|
37263
|
-
head.writeInt32BE(-1, h); h += 4; // partitionLeaderEpoch
|
|
37264
|
-
head.writeInt8(2, h); h += 1; // magic = 2
|
|
37265
|
-
head.writeUInt32BE(crc, h); h += 4; // crc (CRC-32C)
|
|
37266
|
-
|
|
37267
|
-
return Buffer.concat([head, crcBody]);
|
|
37268
|
-
}
|
|
37269
|
-
|
|
37270
|
-
// \u2500\u2500 Produce v3 request \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
37271
|
-
function buildProduceRequest(topicName, valueBytes) {
|
|
37272
|
-
correlationId++;
|
|
37273
|
-
const clientBuf = Buffer.from("tina4", "utf-8");
|
|
37274
|
-
const topicBuf = Buffer.from(topicName, "utf-8");
|
|
37275
|
-
const recordBatch = buildRecordBatch(valueBytes);
|
|
37276
|
-
|
|
37277
|
-
const body = Buffer.alloc(
|
|
37278
|
-
2 + // transactionalId (-1 null nullable_string)
|
|
37279
|
-
2 + // acks
|
|
37280
|
-
4 + // timeoutMs
|
|
37281
|
-
4 + // topics array count
|
|
37282
|
-
2 + topicBuf.length + // topic name
|
|
37283
|
-
4 + // partitions array count
|
|
37284
|
-
4 + // partition index
|
|
37285
|
-
4 + recordBatch.length // recordSetBytes (int32 size) + batch
|
|
37286
|
-
);
|
|
37287
|
-
let p = 0;
|
|
37288
|
-
body.writeInt16BE(-1, p); p += 2; // transactionalId = null
|
|
37289
|
-
body.writeInt16BE(1, p); p += 2; // acks = 1
|
|
37290
|
-
body.writeInt32BE(10000, p); p += 4; // timeoutMs
|
|
37291
|
-
body.writeInt32BE(1, p); p += 4; // topics count
|
|
37292
|
-
body.writeInt16BE(topicBuf.length, p); p += 2;
|
|
37293
|
-
topicBuf.copy(body, p); p += topicBuf.length;
|
|
37294
|
-
body.writeInt32BE(1, p); p += 4; // partitions count
|
|
37295
|
-
body.writeInt32BE(0, p); p += 4; // partition index 0
|
|
37296
|
-
body.writeInt32BE(recordBatch.length, p); p += 4; // recordSetBytes size
|
|
37297
|
-
recordBatch.copy(body, p);
|
|
37298
|
-
|
|
37299
|
-
return frameRequest(API_PRODUCE, PRODUCE_VERSION, clientBuf, body);
|
|
37300
|
-
}
|
|
37301
|
-
|
|
37302
|
-
// \u2500\u2500 Fetch v4 request \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
37303
|
-
function buildFetchRequest(topicName, fetchOffset) {
|
|
37304
|
-
correlationId++;
|
|
37305
|
-
const clientBuf = Buffer.from("tina4", "utf-8");
|
|
37306
|
-
const topicBuf = Buffer.from(topicName, "utf-8");
|
|
37307
|
-
|
|
37308
|
-
// Fetch v4 request body (NO logStartOffset \u2014 that arrives in v5+):
|
|
37309
|
-
// replicaId(4), maxWaitMs(4), minBytes(4), maxBytes(4 v3+),
|
|
37310
|
-
// isolationLevel(1 v4+), topics[count]: name, partitions[count]:
|
|
37311
|
-
// partition(4), fetchOffset(8), partitionMaxBytes(4).
|
|
37312
|
-
const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + (2 + topicBuf.length) + 4 + 4 + 8 + 4);
|
|
37313
|
-
let p = 0;
|
|
37314
|
-
buf.writeInt32BE(-1, p); p += 4; // replicaId (-1 consumer)
|
|
37315
|
-
buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
|
|
37316
|
-
buf.writeInt32BE(1, p); p += 4; // minBytes
|
|
37317
|
-
buf.writeInt32BE(1048576, p); p += 4; // maxBytes
|
|
37318
|
-
buf.writeInt8(0, p); p += 1; // isolationLevel = READ_UNCOMMITTED
|
|
37319
|
-
buf.writeInt32BE(1, p); p += 4; // topics count
|
|
37320
|
-
buf.writeInt16BE(topicBuf.length, p); p += 2;
|
|
37321
|
-
topicBuf.copy(buf, p); p += topicBuf.length;
|
|
37322
|
-
buf.writeInt32BE(1, p); p += 4; // partitions count
|
|
37323
|
-
buf.writeInt32BE(0, p); p += 4; // partition 0
|
|
37324
|
-
buf.writeBigInt64BE(BigInt(fetchOffset), p); p += 8; // fetchOffset
|
|
37325
|
-
buf.writeInt32BE(1048576, p); p += 4; // partitionMaxBytes
|
|
37326
|
-
|
|
37327
|
-
return frameRequest(API_FETCH, FETCH_VERSION, clientBuf, buf);
|
|
37328
|
-
}
|
|
37329
|
-
|
|
37330
|
-
// Frame a request with header v1: apiKey, apiVersion, correlationId,
|
|
37331
|
-
// clientId (nullable string) + body.
|
|
37332
|
-
function frameRequest(apiKey, apiVersion, clientBuf, body) {
|
|
37333
|
-
const header = Buffer.alloc(2 + 2 + 4 + 2 + clientBuf.length);
|
|
37334
|
-
let p = 0;
|
|
37335
|
-
header.writeInt16BE(apiKey, p); p += 2;
|
|
37336
|
-
header.writeInt16BE(apiVersion, p); p += 2;
|
|
37337
|
-
header.writeInt32BE(correlationId, p); p += 4;
|
|
37338
|
-
header.writeInt16BE(clientBuf.length, p); p += 2;
|
|
37339
|
-
clientBuf.copy(header, p);
|
|
37340
|
-
const payload = Buffer.concat([header, body]);
|
|
37341
|
-
const framed = Buffer.alloc(4 + payload.length);
|
|
37342
|
-
framed.writeInt32BE(payload.length, 0);
|
|
37343
|
-
payload.copy(framed, 4);
|
|
37344
|
-
return framed;
|
|
37345
|
-
}
|
|
37346
|
-
|
|
37347
|
-
// \u2500\u2500 Parse a v2 RecordBatch region, return the FIRST record value \u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
37348
|
-
// \`buf\` is the whole fetch response; [start, end) bounds the partition's
|
|
37349
|
-
// record-set bytes (may contain one or more concatenated batches).
|
|
37350
|
-
function firstRecordValue(buf, start, end) {
|
|
37351
|
-
let pos = start;
|
|
37352
|
-
while (pos + 12 <= end) {
|
|
37353
|
-
// baseOffset(8) + batchLength(4) then batchLength bytes follow.
|
|
37354
|
-
const batchLength = buf.readInt32BE(pos + 8);
|
|
37355
|
-
const batchStart = pos + 12; // first byte of partitionLeaderEpoch
|
|
37356
|
-
const batchEnd = batchStart + batchLength;
|
|
37357
|
-
if (batchLength <= 0 || batchEnd > end) break;
|
|
37358
|
-
// partitionLeaderEpoch(4), magic(1), crc(4), attributes(2),
|
|
37359
|
-
// lastOffsetDelta(4), firstTimestamp(8), maxTimestamp(8),
|
|
37360
|
-
// producerId(8), producerEpoch(2), baseSequence(4), recordsCount(4)
|
|
37361
|
-
const magic = buf.readInt8(batchStart + 4);
|
|
37362
|
-
if (magic !== 2) { pos = batchEnd; continue; }
|
|
37363
|
-
let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
|
|
37364
|
-
const recordsCount = buf.readInt32BE(r); r += 4;
|
|
37365
|
-
for (let i = 0; i < recordsCount && r < batchEnd; i++) {
|
|
37366
|
-
const recLen = decodeVarint(buf, r); // record length (signed varint)
|
|
37367
|
-
let rp = recLen.next;
|
|
37368
|
-
const recordEnd = rp + recLen.value;
|
|
37369
|
-
rp += 1; // attributes (int8)
|
|
37370
|
-
const tsDelta = decodeVarint(buf, rp); rp = tsDelta.next;
|
|
37371
|
-
const offDelta = decodeVarint(buf, rp); rp = offDelta.next;
|
|
37372
|
-
const keyLen = decodeVarint(buf, rp); rp = keyLen.next;
|
|
37373
|
-
if (keyLen.value >= 0) rp += keyLen.value;
|
|
37374
|
-
const valLen = decodeVarint(buf, rp); rp = valLen.next;
|
|
37375
|
-
if (valLen.value >= 0) {
|
|
37376
|
-
return buf.subarray(rp, rp + valLen.value).toString("utf-8");
|
|
37377
|
-
}
|
|
37378
|
-
r = recordEnd;
|
|
37379
|
-
}
|
|
37380
|
-
pos = batchEnd;
|
|
37381
|
-
}
|
|
37382
|
-
return null;
|
|
37383
|
-
}
|
|
37384
|
-
|
|
37385
|
-
let finished = false;
|
|
37386
|
-
function finish(out, code) {
|
|
37387
|
-
if (finished) return;
|
|
37388
|
-
finished = true;
|
|
37389
|
-
clearTimeout(timer);
|
|
37390
|
-
try { sock.destroy(); } catch (e) { /* ignore */ }
|
|
37391
|
-
if (out) process.stdout.write(out);
|
|
37392
|
-
// Flush stdout before exiting so execFileSync captures it.
|
|
37393
|
-
process.stdout.write("", () => process.exit(code));
|
|
37394
|
-
}
|
|
37395
|
-
|
|
37396
|
-
const sock = net.createConnection({ host, port }, () => {
|
|
37397
|
-
if (operation === "publish") {
|
|
37398
|
-
const req = buildProduceRequest(topic, Buffer.from(data, "utf-8"));
|
|
37399
|
-
sock.write(req);
|
|
37400
|
-
} else if (operation === "get") {
|
|
37401
|
-
sock.write(buildFetchRequest(topic, 0));
|
|
37402
|
-
} else {
|
|
37403
|
-
finish("__UNSUPPORTED__", 0);
|
|
37404
|
-
}
|
|
37405
|
-
});
|
|
37406
|
-
|
|
37407
|
-
let buffer = Buffer.alloc(0);
|
|
37408
|
-
sock.on("data", (chunk) => {
|
|
37409
|
-
buffer = Buffer.concat([buffer, chunk]);
|
|
37410
|
-
if (buffer.length < 4) return;
|
|
37411
|
-
const respSize = buffer.readInt32BE(0);
|
|
37412
|
-
if (buffer.length < 4 + respSize) return;
|
|
37413
|
-
|
|
37414
|
-
if (operation === "publish") {
|
|
37415
|
-
// Produce v3 response (after the 4-byte frame size): correlationId(4),
|
|
37416
|
-
// topics[count]: name, partitions[count]: partition(4), errorCode(2),
|
|
37417
|
-
// baseOffset(8), logAppendTime(8); then throttleTimeMs(4) at the END.
|
|
37418
|
-
// Only the per-partition error code matters here.
|
|
37419
|
-
try {
|
|
37420
|
-
let pos = 4 + 4; // skip frame size + correlationId
|
|
37421
|
-
const topicCount = buffer.readInt32BE(pos); pos += 4;
|
|
37422
|
-
let errCode = 0;
|
|
37423
|
-
for (let t = 0; t < topicCount; t++) {
|
|
37424
|
-
const tl = buffer.readInt16BE(pos); pos += 2 + tl;
|
|
37425
|
-
const pc = buffer.readInt32BE(pos); pos += 4;
|
|
37426
|
-
for (let pi = 0; pi < pc; pi++) {
|
|
37427
|
-
pos += 4; // partition index
|
|
37428
|
-
errCode = buffer.readInt16BE(pos); pos += 2; // error code
|
|
37429
|
-
pos += 8; // baseOffset
|
|
37430
|
-
pos += 8; // logAppendTime (v2+)
|
|
37431
|
-
}
|
|
37432
|
-
}
|
|
37433
|
-
if (errCode === 0) {
|
|
37434
|
-
finish("__PUBLISHED__", 0);
|
|
37435
|
-
} else {
|
|
37436
|
-
// Report the CODE, not just "it failed" \u2014 the caller decides
|
|
37437
|
-
// whether it is retriable (3/5, the async topic-creation race)
|
|
37438
|
-
// or fatal (e.g. 29 TOPIC_AUTHORIZATION_FAILED).
|
|
37439
|
-
process.stderr.write("Produce error code " + errCode);
|
|
37440
|
-
finish("__PRODUCEERROR__" + errCode, 0);
|
|
37441
|
-
}
|
|
37442
|
-
} catch (e) {
|
|
37443
|
-
process.stderr.write("produce parse: " + e.message);
|
|
37444
|
-
finish("__PARSEERROR__produce: " + e.message, 0);
|
|
37445
|
-
}
|
|
37446
|
-
return;
|
|
37447
|
-
} else if (operation === "get") {
|
|
37448
|
-
// Fetch v4 response (after the 4-byte frame size): correlationId(4),
|
|
37449
|
-
// throttleTimeMs(4), topics[count]: name, partitions[count]:
|
|
37450
|
-
// partition(4), errorCode(2), highWatermark(8), lastStableOffset(8),
|
|
37451
|
-
// abortedTxns[count](producerId(8)+firstOffset(8)),
|
|
37452
|
-
// recordSetBytes(int32)+batch.
|
|
37453
|
-
try {
|
|
37454
|
-
let pos = 4 + 4; // frame size + correlationId
|
|
37455
|
-
pos += 4; // throttleTimeMs (v1+)
|
|
37456
|
-
const topicCount = buffer.readInt32BE(pos); pos += 4;
|
|
37457
|
-
let out = "__EMPTY__";
|
|
37458
|
-
let fatalCode = 0;
|
|
37459
|
-
for (let t = 0; t < topicCount; t++) {
|
|
37460
|
-
const tl = buffer.readInt16BE(pos); pos += 2 + tl;
|
|
37461
|
-
const pc = buffer.readInt32BE(pos); pos += 4;
|
|
37462
|
-
for (let pi = 0; pi < pc; pi++) {
|
|
37463
|
-
pos += 4; // partition index
|
|
37464
|
-
const errCode = buffer.readInt16BE(pos); pos += 2;
|
|
37465
|
-
pos += 8; // highWatermark
|
|
37466
|
-
pos += 8; // lastStableOffset (v4+)
|
|
37467
|
-
const abortedCount = buffer.readInt32BE(pos); pos += 4;
|
|
37468
|
-
if (abortedCount > 0) pos += abortedCount * 16; // (-1 => none, skip)
|
|
37469
|
-
const recSetSize = buffer.readInt32BE(pos); pos += 4;
|
|
37470
|
-
// 3 = UNKNOWN_TOPIC_OR_PARTITION, 5 = LEADER_NOT_AVAILABLE:
|
|
37471
|
-
// "nothing to read here yet", which a consumer that starts
|
|
37472
|
-
// before its producer hits on every cold start. Any OTHER code
|
|
37473
|
-
// (29 TOPIC_AUTHORIZATION_FAILED, 13 STALE_CONTROLLER_EPOCH, \u2026)
|
|
37474
|
-
// is a real failure and must NOT be reported as an empty queue.
|
|
37475
|
-
if (errCode !== 0 && errCode !== 3 && errCode !== 5) {
|
|
37476
|
-
fatalCode = errCode;
|
|
37477
|
-
}
|
|
37478
|
-
if (errCode === 0 && recSetSize > 0) {
|
|
37479
|
-
const val = firstRecordValue(buffer, pos, pos + recSetSize);
|
|
37480
|
-
if (val !== null) out = val;
|
|
37481
|
-
}
|
|
37482
|
-
pos += recSetSize > 0 ? recSetSize : 0;
|
|
37483
|
-
}
|
|
37484
|
-
}
|
|
37485
|
-
if (fatalCode !== 0) {
|
|
37486
|
-
process.stderr.write("Fetch error code " + fatalCode);
|
|
37487
|
-
finish("__FETCHERROR__" + fatalCode, 0);
|
|
37488
|
-
return;
|
|
37489
|
-
}
|
|
37490
|
-
finish(out, 0);
|
|
37491
|
-
} catch (e) {
|
|
37492
|
-
// A parse failure is NOT an empty queue either \u2014 say so.
|
|
37493
|
-
process.stderr.write("fetch parse: " + e.message);
|
|
37494
|
-
finish("__PARSEERROR__fetch: " + e.message, 0);
|
|
37495
|
-
}
|
|
37496
|
-
return;
|
|
37497
|
-
}
|
|
37498
|
-
});
|
|
37499
|
-
|
|
37500
|
-
// Report the reason on STDOUT and exit 0. Writing it to stderr and
|
|
37501
|
-
// exiting non-zero LOST it: stderr to a pipe is an async write and
|
|
37502
|
-
// process.exit() truncates it, so the parent saw an empty stderr and fell
|
|
37503
|
-
// back to execFileSync's message -- which embeds this entire script.
|
|
37504
|
-
// stdout is flushed by finish()'s write callback, so it survives.
|
|
37505
|
-
sock.on("error", (err) => {
|
|
37506
|
-
finish("__TRANSPORTERROR__" + err.message, 0);
|
|
37507
|
-
});
|
|
37508
|
-
|
|
37509
|
-
var timer = setTimeout(() => {
|
|
37510
|
-
finish("__TRANSPORTERROR__timed out after 10s talking to " + host + ":" + port, 0);
|
|
37511
|
-
}, 10000);
|
|
37512
|
-
`;
|
|
37513
|
-
try {
|
|
37514
|
-
const result = execFileSync6(process.execPath, ["-e", script], {
|
|
37515
|
-
encoding: "utf-8",
|
|
37516
|
-
timeout: 15e3,
|
|
37517
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
37518
|
-
});
|
|
37519
|
-
return result;
|
|
37520
|
-
} catch (err) {
|
|
37521
|
-
const e = err;
|
|
37522
|
-
const reason = String(e.stderr ?? "").trim() || e.message || "unknown error";
|
|
37523
|
-
const firstLine = reason.split("\n", 1)[0].slice(0, 200);
|
|
37524
|
-
return "__TRANSPORTERROR__" + firstLine;
|
|
37525
|
-
}
|
|
37526
|
-
}
|
|
37527
|
-
/**
|
|
37528
|
-
* Sleep synchronously between produce retries.
|
|
37529
|
-
*
|
|
37530
|
-
* `push()` is synchronous (the whole backend drives its socket through a child
|
|
37531
|
-
* process), so there is no event loop to await on. `Atomics.wait` on a
|
|
37532
|
-
* SharedArrayBuffer is the stdlib way to block a thread for a fixed time --
|
|
37533
|
-
* no dependency, no busy-wait burning CPU.
|
|
37534
|
-
*/
|
|
37535
|
-
static sleepSync(ms) {
|
|
37536
|
-
const shared = new Int32Array(new SharedArrayBuffer(4));
|
|
37537
|
-
Atomics.wait(shared, 0, 0, ms);
|
|
37538
|
-
}
|
|
37539
|
-
/**
|
|
37540
|
-
* Turn a sentinel from the protocol child into a thrown error, or return.
|
|
37541
|
-
*
|
|
37542
|
-
* The wording matches the Python and PHP backends exactly -- the parity rule
|
|
37543
|
-
* covers user-visible error messages, not just behaviour.
|
|
37544
|
-
*/
|
|
37545
|
-
static assertNoError(result, operation, topic) {
|
|
37546
|
-
const fatal = /^__(PRODUCEERROR|FETCHERROR)__(\d+)/.exec(result);
|
|
37547
|
-
if (fatal) {
|
|
37548
|
-
throw new Error(
|
|
37549
|
-
`Kafka rejected the ${operation} for topic ${topic}: error code ${fatal[2]}`
|
|
37550
|
-
);
|
|
37551
|
-
}
|
|
37552
|
-
if (result.startsWith("__TRANSPORTERROR__")) {
|
|
37553
|
-
throw new Error(
|
|
37554
|
-
`Kafka ${operation} for topic ${topic} failed: ` + result.slice("__TRANSPORTERROR__".length)
|
|
37555
|
-
);
|
|
37556
|
-
}
|
|
37557
|
-
if (result.startsWith("__PARSEERROR__")) {
|
|
37558
|
-
throw new Error(
|
|
37559
|
-
`Kafka ${operation} for topic ${topic} returned an unreadable response: ` + result.slice("__PARSEERROR__".length)
|
|
37560
|
-
);
|
|
37561
|
-
}
|
|
37562
|
-
}
|
|
37563
|
-
/**
|
|
37564
|
-
* Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
|
|
37565
|
-
* as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
|
|
37566
|
-
* consumer reading the topic gets the schema it expects; otherwise the Tina4 job
|
|
37567
|
-
* envelope. pop() unwraps both shapes (payload ?? the whole record).
|
|
37568
|
-
*/
|
|
37569
|
-
static encodeJob(id, payload, raw) {
|
|
37570
|
-
if (raw) return JSON.stringify(payload);
|
|
37571
|
-
return JSON.stringify({
|
|
37572
|
-
id,
|
|
37573
|
-
payload,
|
|
37574
|
-
status: "pending",
|
|
37575
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
37576
|
-
attempts: 0,
|
|
37577
|
-
delayUntil: null
|
|
37578
|
-
});
|
|
37579
|
-
}
|
|
37580
|
-
push(queue, payload, _delay, _priority, raw = false) {
|
|
37581
|
-
const id = randomUUID9();
|
|
37582
|
-
const body = _KafkaBackend.encodeJob(id, payload, raw);
|
|
37583
|
-
let result = "";
|
|
37584
|
-
for (let attempt = 1; attempt <= 10; attempt++) {
|
|
37585
|
-
result = this.execSync("publish", queue, body);
|
|
37586
|
-
if (result.includes("__PUBLISHED__")) {
|
|
37587
|
-
return id;
|
|
37588
|
-
}
|
|
37589
|
-
const retriable = /^__PRODUCEERROR__(3|5)\b/.test(result);
|
|
37590
|
-
if (!retriable || attempt === 10) {
|
|
37591
|
-
break;
|
|
37592
|
-
}
|
|
37593
|
-
_KafkaBackend.sleepSync(200);
|
|
37594
|
-
}
|
|
37595
|
-
_KafkaBackend.assertNoError(result, "produce", queue);
|
|
37596
|
-
throw new Error(`Kafka publish failed for topic ${queue}: ${result || "no response"}`);
|
|
37597
|
-
}
|
|
37598
|
-
pop(queue) {
|
|
37599
|
-
const result = this.execSync("get", queue);
|
|
37600
|
-
_KafkaBackend.assertNoError(result, "fetch", queue);
|
|
37601
|
-
if (!result || result === "__EMPTY__" || result === "__UNSUPPORTED__") return null;
|
|
37602
|
-
try {
|
|
37603
|
-
return JSON.parse(result);
|
|
37604
|
-
} catch {
|
|
37605
|
-
return null;
|
|
37606
|
-
}
|
|
37607
|
-
}
|
|
37608
|
-
size(_queue) {
|
|
37609
|
-
return 0;
|
|
37610
|
-
}
|
|
37611
|
-
clear(_queue) {
|
|
37612
|
-
throw new Error(
|
|
37613
|
-
"The kafka queue backend cannot perform clear(): Kafka has no notion of job status and cannot delete records on demand. A log is read in offset order and records leave only by retention. Use the file or mongodb backend."
|
|
37614
|
-
);
|
|
37615
|
-
}
|
|
37616
|
-
purge(_queue, _status) {
|
|
37617
|
-
throw new Error(
|
|
37618
|
-
"The kafka queue backend cannot perform purge(): Kafka has no notion of job status to purge by. A log is read in offset order and records leave only by retention. Use the file or mongodb backend."
|
|
37619
|
-
);
|
|
37620
|
-
}
|
|
37621
|
-
};
|
|
37622
|
-
}
|
|
37623
|
-
});
|
|
37624
|
-
|
|
37625
38311
|
// ../core/src/testing.ts
|
|
37626
38312
|
function expectEqual(args, expected) {
|
|
37627
38313
|
return { type: "equal", args, expected };
|
|
@@ -38397,6 +39083,8 @@ __export(src_exports2, {
|
|
|
38397
39083
|
TEXT_PLAIN: () => TEXT_PLAIN,
|
|
38398
39084
|
TEXT_XML: () => TEXT_XML,
|
|
38399
39085
|
TINA4_VERSION: () => TINA4_VERSION,
|
|
39086
|
+
TcpConnection: () => TcpConnection,
|
|
39087
|
+
TcpService: () => TcpService,
|
|
38400
39088
|
TestClient: () => TestClient,
|
|
38401
39089
|
TestResponse: () => TestResponse,
|
|
38402
39090
|
Tina4AssertionError: () => AssertionError,
|
|
@@ -38439,6 +39127,7 @@ __export(src_exports2, {
|
|
|
38439
39127
|
checkPassword: () => checkPassword,
|
|
38440
39128
|
clearCache: () => clearCache,
|
|
38441
39129
|
clearCurrentNonce: () => clearCurrentNonce,
|
|
39130
|
+
clearTcpRegistry: () => clearTcpRegistry,
|
|
38442
39131
|
computeAcceptKey: () => computeAcceptKey,
|
|
38443
39132
|
container: () => container,
|
|
38444
39133
|
cors: () => cors,
|
|
@@ -38460,6 +39149,7 @@ __export(src_exports2, {
|
|
|
38460
39149
|
devAdminLanguage: () => devAdminLanguage,
|
|
38461
39150
|
devReloadWs: () => devReloadWs,
|
|
38462
39151
|
discoverRoutes: () => discoverRoutes,
|
|
39152
|
+
drainAllTcpServices: () => drainAllTcpServices,
|
|
38463
39153
|
encodeError: () => encodeError,
|
|
38464
39154
|
encodeNotification: () => encodeNotification,
|
|
38465
39155
|
encodeResponse: () => encodeResponse,
|
|
@@ -38547,6 +39237,7 @@ __export(src_exports2, {
|
|
|
38547
39237
|
refreshToken: () => refreshToken,
|
|
38548
39238
|
registerDevTools: () => registerDevTools,
|
|
38549
39239
|
registerFeedbackRoutes: () => registerFeedbackRoutes,
|
|
39240
|
+
registeredTcpServices: () => registeredTcpServices,
|
|
38550
39241
|
removePidfile: () => removePidfile,
|
|
38551
39242
|
renderErrorOverlay: () => renderErrorOverlay,
|
|
38552
39243
|
requestLogger: () => requestLogger,
|
|
@@ -38577,12 +39268,16 @@ __export(src_exports2, {
|
|
|
38577
39268
|
setFrond: () => setFrond,
|
|
38578
39269
|
showMenu: () => showMenu,
|
|
38579
39270
|
start: () => start,
|
|
39271
|
+
startAllTcpServices: () => startAllTcpServices,
|
|
38580
39272
|
startServer: () => startServer,
|
|
38581
39273
|
stop: () => stop,
|
|
39274
|
+
stopAcceptingAllTcpServices: () => stopAcceptingAllTcpServices,
|
|
38582
39275
|
stopAllBackgroundTasks: () => stopAllBackgroundTasks,
|
|
38583
39276
|
supervisorBaseUrl: () => supervisorBaseUrl,
|
|
38584
39277
|
sweep: () => sweep,
|
|
38585
39278
|
takeOverPort: () => takeOverPort,
|
|
39279
|
+
tcp: () => tcp,
|
|
39280
|
+
tcpService: () => tcpService,
|
|
38586
39281
|
templateAutoRoutingEnabled: () => templateAutoRoutingEnabled,
|
|
38587
39282
|
tests: () => tests,
|
|
38588
39283
|
trustedProxyNetworks: () => trustedProxyNetworks,
|
|
@@ -38602,6 +39297,7 @@ var init_src2 = __esm({
|
|
|
38602
39297
|
"use strict";
|
|
38603
39298
|
init_server();
|
|
38604
39299
|
init_background();
|
|
39300
|
+
init_tcp();
|
|
38605
39301
|
init_router();
|
|
38606
39302
|
init_router();
|
|
38607
39303
|
init_routeDiscovery();
|
|
@@ -44934,6 +45630,13 @@ function consumeSqlDelimiter(state) {
|
|
|
44934
45630
|
}
|
|
44935
45631
|
return true;
|
|
44936
45632
|
}
|
|
45633
|
+
function hasExecutableSql(sql) {
|
|
45634
|
+
const body = sql.replace(/\/\*[\s\S]*?\*\//g, "").replace(/--[^\n]*/g, "");
|
|
45635
|
+
return body.replace(/[;\s]/g, "") !== "";
|
|
45636
|
+
}
|
|
45637
|
+
function isUnappliedScaffold(sql) {
|
|
45638
|
+
return TINA4_EDIT_MARKER_RE.test(sql) && !hasExecutableSql(sql);
|
|
45639
|
+
}
|
|
44937
45640
|
function splitStatements(sql, delimiter2 = ";") {
|
|
44938
45641
|
const state = {
|
|
44939
45642
|
sql: normalizeQuotes(sql),
|
|
@@ -45118,6 +45821,12 @@ async function runPendingMigrations(db, dir, delimiter2) {
|
|
|
45118
45821
|
result.skipped.push(file);
|
|
45119
45822
|
continue;
|
|
45120
45823
|
}
|
|
45824
|
+
if (isUnappliedScaffold(sqlContent)) {
|
|
45825
|
+
console.warn(
|
|
45826
|
+
` 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.`
|
|
45827
|
+
);
|
|
45828
|
+
continue;
|
|
45829
|
+
}
|
|
45121
45830
|
const statements = splitStatements(sqlContent, delimiter2);
|
|
45122
45831
|
try {
|
|
45123
45832
|
await adapterStartTransaction(db);
|
|
@@ -45262,7 +45971,7 @@ export class ${className} {
|
|
|
45262
45971
|
writeFileSync17(filePath, content, "utf-8");
|
|
45263
45972
|
return filePath;
|
|
45264
45973
|
}
|
|
45265
|
-
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;
|
|
45974
|
+
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;
|
|
45266
45975
|
var init_migration = __esm({
|
|
45267
45976
|
"src/migration.ts"() {
|
|
45268
45977
|
"use strict";
|
|
@@ -45287,6 +45996,7 @@ var init_migration = __esm({
|
|
|
45287
45996
|
};
|
|
45288
45997
|
SMART_QUOTE_RE = new RegExp(`[${Object.keys(SMART_QUOTES).join("")}]`, "g");
|
|
45289
45998
|
SET_TERM_RE = /^SET\s+TERM\s+(\S+)$/i;
|
|
45999
|
+
TINA4_EDIT_MARKER_RE = /(?:#|\/\/|--|\/\*|\{#)\s*tina4:edit\b/i;
|
|
45290
46000
|
MIGRATION_LOCK_NAME = "tina4_migration_lock";
|
|
45291
46001
|
PG_ADVISORY_KEY = BigInt.asIntN(
|
|
45292
46002
|
64,
|
|
@@ -46651,6 +47361,41 @@ var init_queryBuilder = __esm({
|
|
|
46651
47361
|
}
|
|
46652
47362
|
return this;
|
|
46653
47363
|
}
|
|
47364
|
+
/**
|
|
47365
|
+
* Set OFFSET (rows to skip) as its own chainable verb.
|
|
47366
|
+
*
|
|
47367
|
+
* `limit(n, offset)` buries the offset as a second positional arg; this
|
|
47368
|
+
* exposes it on its own, so `.offset(20).limit(10)` reads naturally and
|
|
47369
|
+
* matches the SQL keyword.
|
|
47370
|
+
*
|
|
47371
|
+
* @param count - Number of rows to skip.
|
|
47372
|
+
* @returns this for chaining.
|
|
47373
|
+
*/
|
|
47374
|
+
offset(count) {
|
|
47375
|
+
this.offsetVal = count;
|
|
47376
|
+
return this;
|
|
47377
|
+
}
|
|
47378
|
+
/**
|
|
47379
|
+
* Alias for `offset()` -- the Mongo/Eloquent name for the same thing.
|
|
47380
|
+
*
|
|
47381
|
+
* Mirrors the DocStore cursor's `skip` and the `skip` key that `toMongo()`
|
|
47382
|
+
* already emits, so a query reads the same whether it targets SQL or MongoDB.
|
|
47383
|
+
*
|
|
47384
|
+
* @param count - Number of rows to skip.
|
|
47385
|
+
* @returns this for chaining.
|
|
47386
|
+
*/
|
|
47387
|
+
skip(count) {
|
|
47388
|
+
return this.offset(count);
|
|
47389
|
+
}
|
|
47390
|
+
/**
|
|
47391
|
+
* Alias for `limit()` -- the Eloquent name; pairs with `skip()`.
|
|
47392
|
+
*
|
|
47393
|
+
* @param count - Maximum rows to return.
|
|
47394
|
+
* @returns this for chaining.
|
|
47395
|
+
*/
|
|
47396
|
+
take(count) {
|
|
47397
|
+
return this.limit(count);
|
|
47398
|
+
}
|
|
46654
47399
|
/**
|
|
46655
47400
|
* Build and return the SQL string without executing.
|
|
46656
47401
|
*
|