tina4-nodejs 3.13.162 → 3.13.164

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.
@@ -1102,6 +1102,9 @@ const handleSystem: RouteHandler = async (_req, res) => {
1102
1102
  const mem = process.memoryUsage();
1103
1103
  const heapUsedMb = Math.round(mem.heapUsed / 1048576);
1104
1104
  const rssMb = Math.round(mem.rss / 1048576);
1105
+ // Peak RSS: ru_maxrss, which libuv reports in kilobytes on every platform
1106
+ // (it converts macOS bytes). The current RSS is not the peak.
1107
+ const peakRssMb = Math.round(process.resourceUsage().maxRSS / 1024);
1105
1108
  let dbTableCount: number | undefined;
1106
1109
  let dbConnected = false;
1107
1110
  try {
@@ -1118,12 +1121,14 @@ const handleSystem: RouteHandler = async (_req, res) => {
1118
1121
  architecture: process.arch,
1119
1122
  os: `${process.platform} ${process.arch}`,
1120
1123
  pid: process.pid,
1121
- memory_mb: heapUsedMb,
1124
+ // The dashboard's "Memory": the process's current RSS, as tina4-python
1125
+ // reports it. V8's heapUsed (below) leaves out Buffers and native memory.
1126
+ memory_mb: rssMb,
1122
1127
  db_tables: dbTableCount !== undefined ? dbTableCount : "N/A",
1123
1128
  db_connected: dbConnected,
1124
1129
  memory: {
1125
- current_mb: heapUsedMb,
1126
- peak_mb: rssMb,
1130
+ current_mb: rssMb,
1131
+ peak_mb: peakRssMb,
1127
1132
  limit: "V8 default",
1128
1133
  rss: `${rssMb} MB`,
1129
1134
  heapUsed: `${heapUsedMb} MB`,
@@ -172,7 +172,7 @@ export { MongoSessionHandler } from "./sessionHandlers/mongoHandler.js";
172
172
  export type { MongoSessionConfig } from "./sessionHandlers/mongoHandler.js";
173
173
  export { ValkeySessionHandler } from "./sessionHandlers/valkeyHandler.js";
174
174
  export type { ValkeySessionConfig } from "./sessionHandlers/valkeyHandler.js";
175
- export { tests, expectEqual, expectRaises, expectTrue, expectFalse, runAll, reset } from "./testing.js";
175
+ export { tests, expectEqual, expectRaises, expectTrue, expectFalse, runAll, runAllAsync, reset } from "./testing.js";
176
176
  export { TestClient, TestResponse } from "./testClient.js";
177
177
  export { Tina4Test, AssertionError as Tina4AssertionError } from "./test.js";
178
178
  export type { TestRunResults } from "./test.js";
@@ -85,7 +85,10 @@ export interface McpResourceDefinition {
85
85
  name: string;
86
86
  description: string;
87
87
  mimeType: string;
88
- handler: () => unknown;
88
+ // Like tool handlers, resource handlers may be sync or async — the dispatch
89
+ // (`_handleResourcesRead`) awaits the return value, so a resource that reads
90
+ // the async Database wrapper serialises its rows, not a pending Promise.
91
+ handler: () => unknown | Promise<unknown>;
89
92
  }
90
93
 
91
94
  export interface JsonSchema {
@@ -502,7 +505,7 @@ export class McpServer {
502
505
 
503
506
  registerResource(
504
507
  uri: string,
505
- handler: () => unknown,
508
+ handler: () => unknown | Promise<unknown>,
506
509
  description = "",
507
510
  mimeType = "application/json",
508
511
  ): void {
@@ -640,7 +643,7 @@ export class McpServer {
640
643
  return { resources };
641
644
  }
642
645
 
643
- private _handleResourcesRead(params: Record<string, unknown>): Record<string, unknown> {
646
+ private async _handleResourcesRead(params: Record<string, unknown>): Promise<Record<string, unknown>> {
644
647
  const uri = params.uri as string | undefined;
645
648
  if (!uri) {
646
649
  throw new Error("Missing resource URI");
@@ -651,7 +654,10 @@ export class McpServer {
651
654
  throw new Error(`Unknown resource: ${uri}`);
652
655
  }
653
656
 
654
- const result = resource.handler();
657
+ // Await like `_handleToolsCall`: an async handler's rows, not `{}` from
658
+ // JSON.stringify(Promise), and its rejection becomes a JSON-RPC error
659
+ // rather than an unhandled rejection.
660
+ const result = await resource.handler();
655
661
 
656
662
  let text: string;
657
663
  if (typeof result === "string") {
@@ -177,11 +177,52 @@ function sleepSync(ms: number): void {
177
177
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
178
178
  }
179
179
 
180
+ // Listens on argv host:port and exits 0 once bound, 1 on any error. A child
181
+ // process, because takeOverPort is synchronous and a Node bind is not. The
182
+ // host and port arrive as argv, never interpolated into the code.
183
+ const BIND_PROBE = 'const s = require("node:net").createServer();'
184
+ + 's.on("error", () => process.exit(1));'
185
+ + 's.listen({ host: process.argv[1], port: Number(process.argv[2]) }, () => s.close(() => process.exit(0)));';
186
+
187
+ /** True when a plain TCP listener on `host`:`port` binds right now (the same net.listen the server uses). */
188
+ function bindable(host: string, port: number): boolean {
189
+ try {
190
+ execFileSync(process.execPath, ["-e", BIND_PROBE, host, String(port)], { stdio: "ignore", timeout: 5000 });
191
+ return true;
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+
197
+ /**
198
+ * The result to return before any holder lookup, or null to carry on.
199
+ *
200
+ * Takeover is refused when opted out or outside dev mode. Before a bind, the
201
+ * caller passes the host it will bind: if that bind succeeds, nothing holds the
202
+ * port, so there is nothing to refuse and nothing to say.
203
+ */
204
+ function refusal(port: number, dev: boolean, noTakeover: boolean, host?: string): TakeoverResult | null {
205
+ if (dev && !noTakeover) return null;
206
+ if (host !== undefined && bindable(host, port)) {
207
+ return { status: TAKEOVER_NOTHING, port, killed: [], message: "" };
208
+ }
209
+ if (noTakeover) {
210
+ return { status: TAKEOVER_REFUSED_OPTOUT, port, killed: [], message:
211
+ `Port ${port} is in use and takeover is disabled (TINA4_NO_TAKEOVER/--no-kill) `
212
+ + `-- free it or choose another port.` };
213
+ }
214
+ return { status: TAKEOVER_REFUSED_PROD, port, killed: [], message:
215
+ `Port ${port} is in use; takeover is disabled outside dev mode `
216
+ + `-- free it or choose another port.` };
217
+ }
218
+
180
219
  /**
181
220
  * Reclaim `port` ONLY from an identity-confirmed Tina4 dev server. The single
182
221
  * guarded path for both the CLI (`tina4 serve`) and the runtime bind-failure
183
222
  * fallback. `dev`/`noTakeover` are passed in so this stays pure and directly
184
223
  * testable; callers resolve them from isDev() / noTakeoverOptedOut().
224
+ * Before a bind, the caller passes the `host` it will bind, so a free port is
225
+ * reported as nothing rather than refused as "in use".
185
226
  */
186
227
  export function takeOverPort(
187
228
  port: number,
@@ -189,6 +230,7 @@ export function takeOverPort(
189
230
  noTakeover: boolean,
190
231
  baseDir?: string,
191
232
  grace = 500,
233
+ host?: string,
192
234
  ): TakeoverResult {
193
235
  const make = (status: string, killed: number[] = [], message = ""): TakeoverResult => ({
194
236
  status,
@@ -197,16 +239,8 @@ export function takeOverPort(
197
239
  message,
198
240
  });
199
241
 
200
- if (noTakeover) {
201
- return make(TAKEOVER_REFUSED_OPTOUT, [],
202
- `Port ${port} is in use and takeover is disabled (TINA4_NO_TAKEOVER/--no-kill) `
203
- + `-- free it or choose another port.`);
204
- }
205
- if (!dev) {
206
- return make(TAKEOVER_REFUSED_PROD, [],
207
- `Port ${port} is in use; takeover is disabled outside dev mode `
208
- + `-- free it or choose another port.`);
209
- }
242
+ const early = refusal(port, dev, noTakeover, host);
243
+ if (early !== null) return early;
210
244
  if (inContainer()) return make(TAKEOVER_SKIPPED_CONTAINER);
211
245
 
212
246
  const tokens = portHolders(port);
@@ -160,6 +160,12 @@ const outBytes = new Uint8Array(workerData.sab, 8);
160
160
  // (test/kafkaErrorCodes.test.ts) can assert the floors.
161
161
  const PRODUCE_VERSION = 3;
162
162
  const FETCH_VERSION = 4;
163
+ // How long the broker long-polls an empty partition before answering (ms).
164
+ // Deliberately 1000, not tina4-php / tina4-python's 5000: Node's pop() is
165
+ // synchronous (Atomics.wait on this worker), so the long-poll blocks the whole
166
+ // event loop, not one request. The tombstone-skip deadline caps it further while
167
+ // stepping so a stream of tombstones cannot hold pop() past ~1s.
168
+ const FETCH_MAX_WAIT_MS = 1000;
163
169
 
164
170
  let correlationId = 0;
165
171
  let brokerSock = null;
@@ -346,12 +352,13 @@ async function produce(topic, valueBytes) {
346
352
  }
347
353
 
348
354
  // ── fetch ─────────────────────────────────────────────────────────────────
349
- function fetchRequest(topic, offset) {
355
+ function fetchRequest(topic, offset, maxWaitMs) {
356
+ if (maxWaitMs === undefined) maxWaitMs = FETCH_MAX_WAIT_MS;
350
357
  const topicBuf = Buffer.from(topic, "utf-8");
351
358
  const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + 2 + topicBuf.length + 4 + 4 + 8 + 4);
352
359
  let p = 0;
353
360
  buf.writeInt32BE(-1, p); p += 4; // replicaId
354
- buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
361
+ buf.writeInt32BE(maxWaitMs, p); p += 4; // maxWaitMs (long-poll bound; capped by the tombstone-skip deadline)
355
362
  buf.writeInt32BE(1, p); p += 4; // minBytes
356
363
  buf.writeInt32BE(1048576, p); p += 4; // maxBytes
357
364
  buf.writeInt8(0, p); p += 1; // isolation READ_UNCOMMITTED
@@ -364,8 +371,12 @@ function fetchRequest(topic, offset) {
364
371
  buf.writeInt32BE(1048576, p); p += 4;
365
372
  return frame(1, FETCH_VERSION, buf);
366
373
  }
367
- // Decode the first record of the partition's record-set: its value string and
368
- // absolute offset (baseOffset + offsetDelta). null = no usable record.
374
+ // Decode the FIRST record of the partition's record-set (the cross-framework
375
+ // contract: only a batch's first record is decoded -- the Tina4 producer writes
376
+ // one record per batch). Returns its value and absolute offset (baseOffset +
377
+ // offsetDelta); a tombstone (null value) comes back with value null and its
378
+ // offset so the caller can step past it. null = no usable record at all (empty /
379
+ // old-format / short response).
369
380
  function firstRecord(buf, start, end) {
370
381
  let pos = start;
371
382
  while (pos + 12 <= end) {
@@ -381,8 +392,7 @@ function firstRecord(buf, start, end) {
381
392
  for (let i = 0; i < recordsCount && r < batchEnd; i++) {
382
393
  const recLen = readVarint(buf, r);
383
394
  let rp = recLen.next;
384
- const recordEnd = rp + recLen.value;
385
- rp += 1;
395
+ rp += 1; // record attributes byte
386
396
  rp = readVarint(buf, rp).next; // timestampDelta
387
397
  const offDelta = readVarint(buf, rp); rp = offDelta.next;
388
398
  const keyLen = readVarint(buf, rp); rp = keyLen.next;
@@ -394,15 +404,23 @@ function firstRecord(buf, start, end) {
394
404
  offset: Number(baseOffset) + offDelta.value,
395
405
  };
396
406
  }
397
- r = recordEnd;
407
+ // Tombstone (null value) or empty value: hand back a marker carrying its
408
+ // offset instead of null. Returning null here used to mean "no record", so
409
+ // pop() never advanced and re-fetched the tombstone for ever -- nothing
410
+ // after it was delivered. The caller (fetchPastTombstones) steps the
411
+ // offset on and re-fetches.
412
+ return {
413
+ value: null,
414
+ offset: Number(baseOffset) + offDelta.value,
415
+ };
398
416
  }
399
417
  pos = batchEnd;
400
418
  }
401
419
  return null;
402
420
  }
403
- async function fetchAt(topic, offset) {
421
+ async function fetchAt(topic, offset, maxWaitMs) {
404
422
  const sock = await broker();
405
- const resp = await rpc(sock, fetchRequest(topic, offset));
423
+ const resp = await rpc(sock, fetchRequest(topic, offset, maxWaitMs));
406
424
  let pos = 4; // correlationId
407
425
  pos += 4; // throttleTimeMs
408
426
  const topicCount = resp.readInt32BE(pos); pos += 4;
@@ -538,9 +556,37 @@ async function broker() {
538
556
  // Resume from the committed offset on the FIRST read of a topic in this worker,
539
557
  // then advance the in-memory cursor; the committed offset only moves on a
540
558
  // commit, so it lags and a crash before commit replays (at-least-once).
559
+ // Fetch from the cursor, stepping past tombstones, until a record with a value
560
+ // arrives, the topic is exhausted, or the deadline passes. A tombstone (null
561
+ // value: Debezium deletes, compacted-topic delete markers) carries no job;
562
+ // returning "nothing" without moving the offset re-fetched it for ever, so
563
+ // nothing after it was ever delivered. The 1 s deadline holds while skipping
564
+ // (the same steady-state bound as tina4-php/tina4-python), and the whole loop
565
+ // stays inside this one worker round-trip (ADR-0022) -- well under
566
+ // CALL_TIMEOUT_MS. Nothing is committed here: acknowledging the next record
567
+ // commits past the skipped tombstones, as before.
568
+ async function fetchPastTombstones(topic) {
569
+ const deadline = Date.now() + 1000;
570
+ let maxWaitMs = FETCH_MAX_WAIT_MS;
571
+ while (true) {
572
+ const offset = offsets[topic];
573
+ const rec = await fetchAt(topic, offset, maxWaitMs);
574
+ if (rec === null || rec.value !== null) return rec; // nothing, or a real record
575
+ // Anti-spin: the decoder reads only a batch's first record, so a tombstone
576
+ // sharing a batch with later records comes back at an offset already passed.
577
+ // That must never loop this fetch.
578
+ const next = rec.offset + 1;
579
+ if (next <= offset) return null;
580
+ offsets[topic] = next;
581
+ const remaining = deadline - Date.now();
582
+ if (remaining <= 0) return null;
583
+ maxWaitMs = remaining;
584
+ }
585
+ }
586
+
541
587
  async function fetchNext(topic) {
542
588
  if (!(topic in offsets)) offsets[topic] = await offsetFetch(topic);
543
- const rec = await fetchAt(topic, offsets[topic]);
589
+ const rec = await fetchPastTombstones(topic);
544
590
  if (rec === null) return null;
545
591
  offsets[topic] = rec.offset + 1;
546
592
  return rec;
@@ -160,6 +160,54 @@ function swaggerAdvertised(): boolean {
160
160
  return TRUTHY.includes(raw);
161
161
  }
162
162
 
163
+ /**
164
+ * A connection URL (or any text that may embed one) with every `user:pass@`
165
+ * removed, for a boot log line. Core never imports the ORM statically, so this
166
+ * cannot borrow its redactCredentials(); stripping the whole userinfo is
167
+ * stricter than redaction anyway (the user name goes too).
168
+ */
169
+ function stripUrlCredentials(text: string): string {
170
+ return text.replace(/:\/\/[^/\s]*@/g, "://");
171
+ }
172
+
173
+ /** A dynamic import that failed because the module itself is absent. */
174
+ function isModuleNotFound(err: unknown): boolean {
175
+ const code = (err as { code?: unknown } | null)?.code;
176
+ return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND";
177
+ }
178
+
179
+ /**
180
+ * The database connect error from this boot's initializeOrm(), if it failed
181
+ * to connect. autoMigrateOnStartup() reports it instead of the bare "no adapter
182
+ * configured" that a failed connect leaves behind.
183
+ */
184
+ let bootDbConnectError: string | null = null;
185
+
186
+ /**
187
+ * Say WHY initializeOrm() failed, by the step that failed: only a missing ORM
188
+ * module is "install @tina4/orm"; a refused connection names the database
189
+ * (without credentials) and the error (review of tina4-ruby#172).
190
+ */
191
+ function reportOrmBootFailure(
192
+ stage: "import" | "connect" | "models",
193
+ err: unknown,
194
+ dbConfig: { type?: string; path?: string },
195
+ ): void {
196
+ const message = stripUrlCredentials(err instanceof Error ? err.message : String(err));
197
+ if (stage === "connect") {
198
+ const url = (process.env.TINA4_DATABASE_URL ?? "").trim();
199
+ const target = url ? stripUrlCredentials(url) : `${dbConfig.type ?? "sqlite"} ${dbConfig.path ?? "./data/tina4.db"}`;
200
+ bootDbConnectError = message;
201
+ console.warn(`\n Database could not be reached (${target}): ${message}`);
202
+ } else if (stage === "import" && isModuleNotFound(err)) {
203
+ console.warn(`\n ORM not available (install @tina4/orm to enable): ${message}`);
204
+ } else if (stage === "import") {
205
+ console.warn(`\n ORM failed to load:`, err);
206
+ } else {
207
+ console.warn(`\n ORM model setup failed:`, err);
208
+ }
209
+ }
210
+
163
211
  /**
164
212
  * Apply pending DB migrations on startup — NON-BREAKING.
165
213
  *
@@ -205,9 +253,23 @@ export async function autoMigrateOnStartup(
205
253
  let orm: typeof import("../../orm/src/index.js");
206
254
  try {
207
255
  orm = await import("../../orm/src/index.js");
256
+ } catch (err) {
257
+ Log.debug(`Startup migrations skipped (ORM not available): ${stripUrlCredentials(err instanceof Error ? err.message : String(err))}`);
258
+ return;
259
+ }
260
+ try {
208
261
  orm.getAdapter(); // throws if no adapter configured
209
262
  } catch (err) {
210
- Log.debug(`Startup migrations skipped (no database configured): ${err instanceof Error ? err.message : String(err)}`);
263
+ // Only an unset TINA4_DATABASE_URL is "no database configured". A set but
264
+ // unreachable one must say so, or the operator chases a missing setting
265
+ // that is in fact present (review of tina4-ruby#172).
266
+ const configuredUrl = (process.env.TINA4_DATABASE_URL ?? "").trim();
267
+ const cause = stripUrlCredentials(bootDbConnectError ?? (err instanceof Error ? err.message : String(err)));
268
+ if (configuredUrl) {
269
+ Log.debug(`Startup migrations skipped (database configured but could not connect to ${stripUrlCredentials(configuredUrl)}): ${cause}`);
270
+ } else {
271
+ Log.debug(`Startup migrations skipped (no database configured): ${cause}`);
272
+ }
211
273
  return;
212
274
  }
213
275
 
@@ -2108,9 +2170,14 @@ function wireLocaleGlobal(frondEngine: any, base: string): void {
2108
2170
  if (!existsSync(localeDir)) return;
2109
2171
  try {
2110
2172
  const localeFiles = readdirSync(localeDir).filter((file: string) => file.endsWith(".json"));
2111
- if (localeFiles.length === 0 || frondEngine.globals?.t) return;
2173
+ // The engine's class: Frond is imported dynamically, so take it from the instance.
2174
+ const FrondClass = frondEngine.constructor;
2175
+ // Don't overwrite a user-registered t() (class-level, or on this engine).
2176
+ if (localeFiles.length === 0 || FrondClass.hasGlobal("t") || frondEngine.globals?.t) return;
2112
2177
  const i18nInstance = new I18n(process.env.TINA4_LOCALE ?? "en", localeDir);
2113
- frondEngine.addGlobal("t", (key: string, params?: Record<string, string>) => i18nInstance.t(key, params));
2178
+ // Class-level, so t() reaches every engine (res.render's included) whenever
2179
+ // it was built. Templates call t("key") or t("key", {"name": n}).
2180
+ FrondClass.addGlobal("t", (key: string, params?: Record<string, string>) => i18nInstance.t(key, params));
2114
2181
  } catch {
2115
2182
  // Locale directory unreadable — skip auto-wire.
2116
2183
  }
@@ -2742,13 +2809,20 @@ async function initializeOrm(
2742
2809
  const hasOrmDir = existsSync(ormDir);
2743
2810
  const hasModelsDir = existsSync(modelsDir);
2744
2811
  if (hasOrmDir || hasModelsDir) {
2812
+ // Which step failed decides what the warning says: only a missing ORM
2813
+ // module is "install @tina4/orm"; a refused connection is a database
2814
+ // problem and must name the database (review of tina4-ruby#172).
2815
+ let ormStage: "import" | "connect" | "models" = "import";
2816
+ const dbConfig = config?.database ?? {};
2745
2817
  try {
2746
2818
  const orm = await import("../../orm/src/index.js");
2747
- const dbConfig = config?.database ?? {};
2819
+ ormStage = "connect";
2820
+ bootDbConnectError = null;
2748
2821
  await orm.initDatabase({
2749
2822
  type: dbConfig.type ?? "sqlite",
2750
2823
  path: dbConfig.path ?? "./data/tina4.db",
2751
2824
  });
2825
+ ormStage = "models";
2752
2826
 
2753
2827
  // Discover from src/orm/ (primary) and src/models/ (fallback), merge results
2754
2828
  let models = hasOrmDir ? await orm.discoverModels(ormDir) : [];
@@ -2792,7 +2866,7 @@ async function initializeOrm(
2792
2866
  }
2793
2867
  }
2794
2868
  } catch (err) {
2795
- console.warn(`\n ORM not available (install @tina4/orm to enable):`, err);
2869
+ reportOrmBootFailure(ormStage, err, dbConfig);
2796
2870
  }
2797
2871
 
2798
2872
  // Auto-run pending migrations on startup — AFTER initDatabase()/model sync,