tina4-nodejs 3.13.162 → 3.13.163

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.
@@ -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") {
@@ -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;
@@ -21,7 +21,8 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
21
21
  * return a + b;
22
22
  * });
23
23
  *
24
- * runAll();
24
+ * runAll(); // synchronous test functions
25
+ * await runAllAsync(); // async test functions (awaited, with a timeout)
25
26
  *
26
27
  * The builders are named expect* — DESCRIPTORS that record an expectation for the
27
28
  * runner — deliberately distinct from the xUnit assert* on Tina4Test (test.ts),
@@ -104,46 +105,70 @@ export function tests(
104
105
 
105
106
  // ── Runner ─────────────────────────────────────────────────────────
106
107
 
107
- /** Run all registered tests. Returns results summary. */
108
- export function runAll(
109
- options: { quiet?: boolean; failfast?: boolean } = {},
110
- ): TestResults {
108
+ interface RunOptions {
109
+ quiet?: boolean;
110
+ failfast?: boolean;
111
+ }
112
+
113
+ interface AsyncRunOptions extends RunOptions {
114
+ /** Per-call limit in milliseconds for an async test function (default 30000). */
115
+ timeoutMs?: number;
116
+ }
117
+
118
+ /**
119
+ * Run all registered tests synchronously. Returns the results summary.
120
+ *
121
+ * A test function that returns a Promise (an async function) cannot be judged
122
+ * here: its result is not known yet. It is reported as an ERROR naming
123
+ * `runAllAsync()`, never as a pass. Use `await runAllAsync()` for async tests.
124
+ */
125
+ export function runAll(options: RunOptions = {}): TestResults {
111
126
  const { quiet = false, failfast = false } = options;
112
127
  const results: TestResults = { passed: 0, failed: 0, errors: 0, details: [] };
113
128
 
114
129
  for (const entry of registry) {
115
- if (!quiet) {
116
- console.log(`\n ${entry.name}`);
130
+ if (!quiet) console.log(`\n ${entry.name}`);
131
+ for (const assertion of entry.assertions) {
132
+ const label = assertionLabel(assertion, entry.name);
133
+ const ok = record(results, label, quiet, () => judge(assertion, callSync(entry.fn, assertion.args)));
134
+ if (!ok && failfast) {
135
+ printSummary(results, quiet);
136
+ return results;
137
+ }
117
138
  }
139
+ }
140
+
141
+ printSummary(results, quiet);
142
+ return results;
143
+ }
118
144
 
145
+ /**
146
+ * Run all registered tests, awaiting each test function. Resolves to the
147
+ * results summary.
148
+ *
149
+ * An async function is judged on what it resolves to or rejects with. A call
150
+ * that has not settled after `timeoutMs` (default 30000) is reported as an
151
+ * error, so one stuck test cannot hang the run. `timeoutMs: Infinity` turns the
152
+ * timeout off; any other value must be a positive number of milliseconds no
153
+ * larger than 2147483647 (the largest delay a Node timer accepts).
154
+ */
155
+ export async function runAllAsync(options: AsyncRunOptions = {}): Promise<TestResults> {
156
+ const { quiet = false, failfast = false, timeoutMs = 30_000 } = options;
157
+ checkTimeout(timeoutMs);
158
+ const results: TestResults = { passed: 0, failed: 0, errors: 0, details: [] };
159
+
160
+ for (const entry of registry) {
161
+ if (!quiet) console.log(`\n ${entry.name}`);
119
162
  for (const assertion of entry.assertions) {
120
163
  const label = assertionLabel(assertion, entry.name);
121
- try {
122
- runAssertion(entry.fn, assertion);
123
- results.passed++;
124
- results.details.push({ name: label, status: "passed" });
125
- if (!quiet) {
126
- console.log(` \x1b[32m+\x1b[0m ${label}`);
127
- }
128
- } catch (err) {
129
- if (err instanceof TestAssertionError) {
130
- results.failed++;
131
- results.details.push({ name: label, status: "failed", message: err.message });
132
- if (!quiet) {
133
- console.log(` \x1b[31mx\x1b[0m ${label}: ${err.message}`);
134
- }
135
- } else {
136
- results.errors++;
137
- const msg = err instanceof Error ? `${err.constructor.name}: ${err.message}` : String(err);
138
- results.details.push({ name: label, status: "error", message: msg });
139
- if (!quiet) {
140
- console.log(` \x1b[33m!\x1b[0m ${label}: ${msg}`);
141
- }
142
- }
143
- if (failfast) {
144
- printSummary(results, quiet);
145
- return results;
146
- }
164
+ const outcome = await callAsync(entry.fn, assertion.args, timeoutMs);
165
+ const ok = record(results, label, quiet, () => {
166
+ if (outcome instanceof TestRunError) throw outcome;
167
+ judge(assertion, outcome);
168
+ });
169
+ if (!ok && failfast) {
170
+ printSummary(results, quiet);
171
+ return results;
147
172
  }
148
173
  }
149
174
  }
@@ -166,52 +191,139 @@ class TestAssertionError extends Error {
166
191
  }
167
192
  }
168
193
 
169
- function runAssertion(fn: (...args: unknown[]) => unknown, assertion: Assertion): void {
170
- const { type, args } = assertion;
194
+ /** What calling a test function produced: a value, or a thrown error. */
195
+ type Outcome = { threw: false; value: unknown } | { threw: true; error: unknown };
196
+
197
+ /** Raised when a test cannot be judged at all (not a failed assertion). */
198
+ class TestRunError extends Error {
199
+ constructor(message: string) {
200
+ super(message);
201
+ this.name = "TestRunError";
202
+ }
203
+ }
204
+
205
+ function isThenable(value: unknown): value is PromiseLike<unknown> {
206
+ return (
207
+ value !== null &&
208
+ (typeof value === "object" || typeof value === "function") &&
209
+ typeof (value as { then?: unknown }).then === "function"
210
+ );
211
+ }
212
+
213
+ function callSync(fn: (...args: unknown[]) => unknown, args: unknown[]): Outcome {
214
+ let value: unknown;
215
+ try {
216
+ value = fn(...args);
217
+ } catch (error) {
218
+ return { threw: true, error };
219
+ }
220
+ if (isThenable(value)) {
221
+ // Settle it quietly: its rejection must not surface as an unhandled one.
222
+ Promise.resolve(value).then(undefined, () => undefined);
223
+ throw new TestRunError(
224
+ "returned a Promise (async test function): runAll() cannot judge it, use await runAllAsync()",
225
+ );
226
+ }
227
+ return { threw: false, value };
228
+ }
229
+
230
+ /** Largest delay setTimeout honours; a larger one fires after 1 ms. */
231
+ const MAX_TIMER_MS = 2_147_483_647;
232
+
233
+ function checkTimeout(timeoutMs: number): void {
234
+ if (timeoutMs === Infinity) return;
235
+ if (!(timeoutMs > 0 && timeoutMs <= MAX_TIMER_MS)) {
236
+ throw new RangeError(
237
+ `timeoutMs must be Infinity or a number of milliseconds in (0, ${MAX_TIMER_MS}], got ${timeoutMs}`,
238
+ );
239
+ }
240
+ }
241
+
242
+ async function callAsync(
243
+ fn: (...args: unknown[]) => unknown,
244
+ args: unknown[],
245
+ timeoutMs: number,
246
+ ): Promise<Outcome | TestRunError> {
247
+ let timer: ReturnType<typeof setTimeout> | undefined;
248
+ try {
249
+ const value = fn(...args);
250
+ if (!isThenable(value)) return { threw: false, value };
251
+ if (timeoutMs === Infinity) return { threw: false, value: await value };
252
+ const timeout = new Promise<never>((_, reject) => {
253
+ timer = setTimeout(
254
+ () => reject(new TestRunError(`did not settle within ${timeoutMs} ms`)),
255
+ timeoutMs,
256
+ );
257
+ });
258
+ return { threw: false, value: await Promise.race([Promise.resolve(value), timeout]) };
259
+ } catch (error) {
260
+ if (error instanceof TestRunError) return error;
261
+ return { threw: true, error };
262
+ } finally {
263
+ if (timer !== undefined) clearTimeout(timer);
264
+ }
265
+ }
266
+
267
+ /** Record one assertion's result; returns true when it passed. */
268
+ function record(results: TestResults, label: string, quiet: boolean, check: () => void): boolean {
269
+ try {
270
+ check();
271
+ results.passed++;
272
+ results.details.push({ name: label, status: "passed" });
273
+ if (!quiet) console.log(` \x1b[32m+\x1b[0m ${label}`);
274
+ return true;
275
+ } catch (err) {
276
+ if (err instanceof TestAssertionError) {
277
+ results.failed++;
278
+ results.details.push({ name: label, status: "failed", message: err.message });
279
+ if (!quiet) console.log(` \x1b[31mx\x1b[0m ${label}: ${err.message}`);
280
+ } else {
281
+ results.errors++;
282
+ const msg = err instanceof Error ? `${err.constructor.name}: ${err.message}` : String(err);
283
+ results.details.push({ name: label, status: "error", message: msg });
284
+ if (!quiet) console.log(` \x1b[33m!\x1b[0m ${label}: ${msg}`);
285
+ }
286
+ return false;
287
+ }
288
+ }
289
+
290
+ /** Judge an expectRaises assertion: the call must have thrown that class. */
291
+ function judgeRaises(assertion: Assertion, outcome: Outcome): void {
292
+ const ExcClass = assertion.exception!;
293
+ if (!outcome.threw) throw new TestAssertionError(`expected ${ExcClass.name} to be raised`);
294
+ const err = outcome.error;
295
+ if (err instanceof ExcClass) return;
296
+ throw new TestAssertionError(
297
+ `expected ${ExcClass.name}, got ${err instanceof Error ? err.constructor.name : typeof err}: ${err}`,
298
+ );
299
+ }
300
+
301
+ /** Judge one assertion against what the call produced. */
302
+ function judge(assertion: Assertion, outcome: Outcome): void {
303
+ const { type } = assertion;
304
+
305
+ if (type === "raises") return judgeRaises(assertion, outcome);
306
+
307
+ // Any other assertion: an exception from the function is an error, not a failure.
308
+ if (outcome.threw) throw outcome.error;
309
+ const result = outcome.value;
171
310
 
172
311
  switch (type) {
173
312
  case "equal": {
174
- const result = fn(...args);
175
313
  const expected = assertion.expected;
176
314
  if (result !== expected) {
177
315
  throw new TestAssertionError(
178
316
  `expected ${JSON.stringify(expected)}, got ${JSON.stringify(result)}`,
179
317
  );
180
318
  }
181
- break;
182
- }
183
-
184
- case "raises": {
185
- const ExcClass = assertion.exception!;
186
- try {
187
- fn(...args);
188
- } catch (err) {
189
- if (err instanceof ExcClass) {
190
- return; // success
191
- }
192
- throw new TestAssertionError(
193
- `expected ${ExcClass.name}, got ${err instanceof Error ? err.constructor.name : typeof err}: ${err}`,
194
- );
195
- }
196
- throw new TestAssertionError(`expected ${ExcClass.name} to be raised`);
197
- }
198
-
199
- case "true": {
200
- const result = fn(...args);
201
- if (!result) {
202
- throw new TestAssertionError(`expected truthy, got ${JSON.stringify(result)}`);
203
- }
204
- break;
205
- }
206
-
207
- case "false": {
208
- const result = fn(...args);
209
- if (result) {
210
- throw new TestAssertionError(`expected falsy, got ${JSON.stringify(result)}`);
211
- }
212
- break;
319
+ return;
213
320
  }
214
-
321
+ case "true":
322
+ if (!result) throw new TestAssertionError(`expected truthy, got ${JSON.stringify(result)}`);
323
+ return;
324
+ case "false":
325
+ if (result) throw new TestAssertionError(`expected falsy, got ${JSON.stringify(result)}`);
326
+ return;
215
327
  default:
216
328
  throw new Error(`unknown assertion type: ${type}`);
217
329
  }