@selvajs/server 0.2.0-beta.2 → 0.2.0-beta.3
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/dist/compute/__tests__/client-cache.test.js +18 -0
- package/dist/compute/__tests__/client-cache.test.js.map +1 -1
- package/dist/compute/__tests__/definition-byte-cache.test.d.ts +2 -0
- package/dist/compute/__tests__/definition-byte-cache.test.d.ts.map +1 -0
- package/dist/compute/__tests__/definition-byte-cache.test.js +107 -0
- package/dist/compute/__tests__/definition-byte-cache.test.js.map +1 -0
- package/dist/compute/__tests__/solve-cache.test.d.ts +13 -0
- package/dist/compute/__tests__/solve-cache.test.d.ts.map +1 -0
- package/dist/compute/__tests__/solve-cache.test.js +234 -0
- package/dist/compute/__tests__/solve-cache.test.js.map +1 -0
- package/dist/compute/__tests__/solve-pipeline.test.js +267 -2
- package/dist/compute/__tests__/solve-pipeline.test.js.map +1 -1
- package/dist/compute/client-cache.d.ts +12 -0
- package/dist/compute/client-cache.d.ts.map +1 -1
- package/dist/compute/client-cache.js +12 -3
- package/dist/compute/client-cache.js.map +1 -1
- package/dist/compute/definition-byte-cache.d.ts +85 -0
- package/dist/compute/definition-byte-cache.d.ts.map +1 -0
- package/dist/compute/definition-byte-cache.js +110 -0
- package/dist/compute/definition-byte-cache.js.map +1 -0
- package/dist/compute/index.d.ts +7 -2
- package/dist/compute/index.d.ts.map +1 -1
- package/dist/compute/index.js +6 -1
- package/dist/compute/index.js.map +1 -1
- package/dist/compute/limits.d.ts +52 -0
- package/dist/compute/limits.d.ts.map +1 -1
- package/dist/compute/limits.js +33 -1
- package/dist/compute/limits.js.map +1 -1
- package/dist/compute/memory-solve-cache.d.ts +58 -0
- package/dist/compute/memory-solve-cache.d.ts.map +1 -0
- package/dist/compute/memory-solve-cache.js +0 -0
- package/dist/compute/memory-solve-cache.js.map +1 -0
- package/dist/compute/solve-cache-envelope.d.ts +53 -0
- package/dist/compute/solve-cache-envelope.d.ts.map +1 -0
- package/dist/compute/solve-cache-envelope.js +66 -0
- package/dist/compute/solve-cache-envelope.js.map +1 -0
- package/dist/compute/solve-cache-key.d.ts +65 -0
- package/dist/compute/solve-cache-key.d.ts.map +1 -0
- package/dist/compute/solve-cache-key.js +50 -0
- package/dist/compute/solve-cache-key.js.map +1 -0
- package/dist/compute/solve-cache-single-flight.d.ts +35 -0
- package/dist/compute/solve-cache-single-flight.d.ts.map +1 -0
- package/dist/compute/solve-cache-single-flight.js +48 -0
- package/dist/compute/solve-cache-single-flight.js.map +1 -0
- package/dist/compute/solve-pipeline.d.ts +71 -8
- package/dist/compute/solve-pipeline.d.ts.map +1 -1
- package/dist/compute/solve-pipeline.js +178 -8
- package/dist/compute/solve-pipeline.js.map +1 -1
- package/dist/definitions/__tests__/definition-service.test.d.ts +14 -0
- package/dist/definitions/__tests__/definition-service.test.d.ts.map +1 -0
- package/dist/definitions/__tests__/definition-service.test.js +95 -0
- package/dist/definitions/__tests__/definition-service.test.js.map +1 -0
- package/dist/definitions/definition-service.d.ts +1 -1
- package/dist/definitions/definition-service.d.ts.map +1 -1
- package/dist/definitions/definition-service.js +8 -4
- package/dist/definitions/definition-service.js.map +1 -1
- package/package.json +2 -2
- package/src/compute/__tests__/client-cache.test.ts +20 -0
- package/src/compute/__tests__/definition-byte-cache.test.ts +129 -0
- package/src/compute/__tests__/solve-cache.test.ts +268 -0
- package/src/compute/__tests__/solve-pipeline.test.ts +320 -1
- package/src/compute/client-cache.ts +24 -3
- package/src/compute/definition-byte-cache.ts +168 -0
- package/src/compute/index.ts +34 -0
- package/src/compute/limits.ts +79 -1
- package/src/compute/memory-solve-cache.ts +0 -0
- package/src/compute/solve-cache-envelope.ts +98 -0
- package/src/compute/solve-cache-key.ts +85 -0
- package/src/compute/solve-cache-single-flight.ts +59 -0
- package/src/compute/solve-pipeline.ts +279 -15
- package/src/definitions/__tests__/definition-service.test.ts +131 -0
- package/src/definitions/definition-service.ts +8 -4
|
@@ -13,25 +13,69 @@ import { gunzipSync } from 'node:zlib';
|
|
|
13
13
|
import type { GrasshopperClient, InputParam, SolveScheduler } from '@selvajs/compute';
|
|
14
14
|
|
|
15
15
|
// --- Mock @selvajs/compute -------------------------------------------------
|
|
16
|
+
// The factory is hoisted above module top-level, so the RhinoComputeError
|
|
17
|
+
// stand-in is declared INSIDE it. The pipeline classifies shed outcomes with
|
|
18
|
+
// `err instanceof RhinoComputeError && err.code === ErrorCodes.QUEUE_*`, so the
|
|
19
|
+
// mock must export a real class + the code constants. Tests import the mocked
|
|
20
|
+
// `RhinoComputeError` below to construct instances the pipeline recognizes.
|
|
16
21
|
vi.mock('@selvajs/compute', () => {
|
|
22
|
+
class RhinoComputeError extends Error {
|
|
23
|
+
code: string;
|
|
24
|
+
statusCode?: number;
|
|
25
|
+
context?: Record<string, unknown>;
|
|
26
|
+
constructor(
|
|
27
|
+
message: string,
|
|
28
|
+
code: string,
|
|
29
|
+
options?: { statusCode?: number; context?: Record<string, unknown> }
|
|
30
|
+
) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.name = 'RhinoComputeError';
|
|
33
|
+
this.code = code;
|
|
34
|
+
this.statusCode = options?.statusCode;
|
|
35
|
+
this.context = options?.context;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
17
38
|
return {
|
|
18
39
|
TreeBuilder: {
|
|
19
40
|
fromInputParams: (params: unknown[]) => ({ __tree: true, count: params.length })
|
|
20
41
|
},
|
|
21
42
|
// transform-input.ts (imported by the pipeline) calls processInput; return
|
|
22
43
|
// the raw shape as an InputParam so filtering/mapping runs end-to-end.
|
|
23
|
-
processInput: (raw: InputParam) => raw
|
|
44
|
+
processInput: (raw: InputParam) => raw,
|
|
45
|
+
// The L2 key module hashes over stableStringify — a deterministic sorted-key
|
|
46
|
+
// JSON is enough for the tests (real impl sorts recursively).
|
|
47
|
+
stableStringify: (value: unknown) => JSON.stringify(value),
|
|
48
|
+
RhinoComputeError,
|
|
49
|
+
ErrorCodes: { QUEUE_FULL: 'QUEUE_FULL', QUEUE_TIMEOUT: 'QUEUE_TIMEOUT' }
|
|
24
50
|
};
|
|
25
51
|
});
|
|
26
52
|
|
|
53
|
+
// The mocked class, typed loosely for constructing test errors. The `as` cast
|
|
54
|
+
// keeps the 3-arg (message, code, options) signature the pipeline's mock uses.
|
|
55
|
+
import { RhinoComputeError as MockRhinoComputeError } from '@selvajs/compute';
|
|
56
|
+
const makeShedError = (
|
|
57
|
+
message: string,
|
|
58
|
+
code: 'QUEUE_FULL' | 'QUEUE_TIMEOUT' | 'UNKNOWN_ERROR',
|
|
59
|
+
options?: { statusCode?: number; context?: Record<string, unknown> }
|
|
60
|
+
) =>
|
|
61
|
+
new (MockRhinoComputeError as unknown as new (
|
|
62
|
+
m: string,
|
|
63
|
+
c: string,
|
|
64
|
+
o?: { statusCode?: number; context?: Record<string, unknown> }
|
|
65
|
+
) => Error)(message, code, options);
|
|
66
|
+
|
|
27
67
|
import {
|
|
28
68
|
runSolvePipeline,
|
|
29
69
|
COMPUTE_CONTRACT_VERSION,
|
|
30
70
|
COMPUTE_VERSION_HEADER,
|
|
71
|
+
deriveSolveCacheInputKey,
|
|
72
|
+
encodeSolveCacheEntry,
|
|
31
73
|
type SolvePipelineArgs,
|
|
74
|
+
type SolvePipelineCacheHook,
|
|
32
75
|
type PipelineInput,
|
|
33
76
|
type CachedClient
|
|
34
77
|
} from '../index.js';
|
|
78
|
+
import { gzipSync } from 'node:zlib';
|
|
35
79
|
|
|
36
80
|
/**
|
|
37
81
|
* A scripted solve stub. The pipeline only JSON-serializes and reads
|
|
@@ -196,6 +240,33 @@ describe('runSolvePipeline — failure outcomes', () => {
|
|
|
196
240
|
expect(outcome.kind).toBe('client_abort');
|
|
197
241
|
});
|
|
198
242
|
|
|
243
|
+
it('R3: a client disconnect while QUEUED forwards the signal and settles client_abort without a result', async () => {
|
|
244
|
+
// Models the queued-disconnect path the package fix (ISSUES 46) closes: the
|
|
245
|
+
// signal fires while the item waits in the FIFO, the scheduler settles it
|
|
246
|
+
// ABORTED (rejects with AbortError) and never runs compute. The pipeline's
|
|
247
|
+
// job — verified here — is to (a) hand the request signal to scheduler.solve
|
|
248
|
+
// so that prune can happen, and (b) classify the aborted-signal reject as
|
|
249
|
+
// client_abort (→ 499), never leaking a compute result.
|
|
250
|
+
const controller = new AbortController();
|
|
251
|
+
let seenSignal: AbortSignal | undefined;
|
|
252
|
+
const outcome = await runSolvePipeline(
|
|
253
|
+
baseArgs({
|
|
254
|
+
signal: controller.signal,
|
|
255
|
+
client: fakeClient(async (_d, _t, opts) => {
|
|
256
|
+
seenSignal = opts.signal;
|
|
257
|
+
// The disconnect arrives while queued: abort, then settle ABORTED —
|
|
258
|
+
// compute output is never produced (the loader throws, never returns).
|
|
259
|
+
controller.abort();
|
|
260
|
+
const e = new Error('aborted while queued');
|
|
261
|
+
e.name = 'AbortError';
|
|
262
|
+
throw e;
|
|
263
|
+
})
|
|
264
|
+
})
|
|
265
|
+
);
|
|
266
|
+
expect(seenSignal).toBe(controller.signal); // scheduler CAN observe the disconnect
|
|
267
|
+
expect(outcome.kind).toBe('client_abort'); // → 499, not a 500/compute_error
|
|
268
|
+
});
|
|
269
|
+
|
|
199
270
|
it('classifies any other throw as compute_error carrying the original error', async () => {
|
|
200
271
|
const boom = new TypeError('fetch failed');
|
|
201
272
|
const outcome = await runSolvePipeline(
|
|
@@ -219,6 +290,57 @@ describe('runSolvePipeline — failure outcomes', () => {
|
|
|
219
290
|
);
|
|
220
291
|
expect(outcome.kind).toBe('too_large');
|
|
221
292
|
});
|
|
293
|
+
|
|
294
|
+
it('classifies a QUEUE_FULL rejection as shed(queue_full) with a Retry-After hint', async () => {
|
|
295
|
+
const outcome = await runSolvePipeline(
|
|
296
|
+
baseArgs({
|
|
297
|
+
client: fakeClient(async () => {
|
|
298
|
+
throw makeShedError('queue full', 'QUEUE_FULL', {
|
|
299
|
+
statusCode: 503,
|
|
300
|
+
context: { queueDepth: 8, maxQueueDepth: 8 }
|
|
301
|
+
});
|
|
302
|
+
})
|
|
303
|
+
})
|
|
304
|
+
);
|
|
305
|
+
expect(outcome.kind).toBe('shed');
|
|
306
|
+
if (outcome.kind !== 'shed') return;
|
|
307
|
+
expect(outcome.reason).toBe('queue_full');
|
|
308
|
+
expect(outcome.retryAfterSeconds).toBeGreaterThan(0);
|
|
309
|
+
expect(outcome.message).toBeTruthy();
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
it('classifies a QUEUE_TIMEOUT rejection as shed(queue_timeout)', async () => {
|
|
313
|
+
const outcome = await runSolvePipeline(
|
|
314
|
+
baseArgs({
|
|
315
|
+
client: fakeClient(async () => {
|
|
316
|
+
throw makeShedError('queued too long', 'QUEUE_TIMEOUT', {
|
|
317
|
+
statusCode: 503,
|
|
318
|
+
context: { waitedMs: 5000, queueWaitMs: 3000 }
|
|
319
|
+
});
|
|
320
|
+
})
|
|
321
|
+
})
|
|
322
|
+
);
|
|
323
|
+
expect(outcome.kind).toBe('shed');
|
|
324
|
+
if (outcome.kind !== 'shed') return;
|
|
325
|
+
expect(outcome.reason).toBe('queue_timeout');
|
|
326
|
+
expect(outcome.retryAfterSeconds).toBeGreaterThan(0);
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
it('does NOT shed a RhinoComputeError with an unrelated code (stays compute_error)', async () => {
|
|
330
|
+
const boom = makeShedError('server exploded', 'UNKNOWN_ERROR', {
|
|
331
|
+
statusCode: 500
|
|
332
|
+
});
|
|
333
|
+
const outcome = await runSolvePipeline(
|
|
334
|
+
baseArgs({
|
|
335
|
+
client: fakeClient(async () => {
|
|
336
|
+
throw boom;
|
|
337
|
+
})
|
|
338
|
+
})
|
|
339
|
+
);
|
|
340
|
+
expect(outcome.kind).toBe('compute_error');
|
|
341
|
+
if (outcome.kind !== 'compute_error') return;
|
|
342
|
+
expect(outcome.error).toBe(boom);
|
|
343
|
+
});
|
|
222
344
|
});
|
|
223
345
|
|
|
224
346
|
describe('runSolvePipeline — Server-Timing', () => {
|
|
@@ -321,6 +443,51 @@ describe('runSolvePipeline — Server-Timing', () => {
|
|
|
321
443
|
expect(st).not.toContain('rhino_decode');
|
|
322
444
|
});
|
|
323
445
|
|
|
446
|
+
it('emits def_bytes=skipped when the byteRefOutcome shows load() never ran (pointer solve)', async () => {
|
|
447
|
+
const outcome = await runSolvePipeline(
|
|
448
|
+
baseArgs({
|
|
449
|
+
byteRefOutcome: { loaded: false, fromCache: false },
|
|
450
|
+
client: fakeClient(async () => ({ errors: [], warnings: [] }))
|
|
451
|
+
})
|
|
452
|
+
);
|
|
453
|
+
expect(outcome.kind).toBe('ok');
|
|
454
|
+
if (outcome.kind !== 'ok') return;
|
|
455
|
+
expect(outcome.envelope.headers['Server-Timing']).toContain('def_bytes;desc=skipped');
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
it('emits def_bytes=hit when bytes were served from the warm cache', async () => {
|
|
459
|
+
const outcome = await runSolvePipeline(
|
|
460
|
+
baseArgs({
|
|
461
|
+
byteRefOutcome: { loaded: true, fromCache: true },
|
|
462
|
+
client: fakeClient(async () => ({ errors: [], warnings: [] }))
|
|
463
|
+
})
|
|
464
|
+
);
|
|
465
|
+
expect(outcome.kind).toBe('ok');
|
|
466
|
+
if (outcome.kind !== 'ok') return;
|
|
467
|
+
expect(outcome.envelope.headers['Server-Timing']).toContain('def_bytes;desc=hit');
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
it('emits def_bytes=miss when the loader was called', async () => {
|
|
471
|
+
const outcome = await runSolvePipeline(
|
|
472
|
+
baseArgs({
|
|
473
|
+
byteRefOutcome: { loaded: true, fromCache: false },
|
|
474
|
+
client: fakeClient(async () => ({ errors: [], warnings: [] }))
|
|
475
|
+
})
|
|
476
|
+
);
|
|
477
|
+
expect(outcome.kind).toBe('ok');
|
|
478
|
+
if (outcome.kind !== 'ok') return;
|
|
479
|
+
expect(outcome.envelope.headers['Server-Timing']).toContain('def_bytes;desc=miss');
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
it('omits def_bytes entirely for a raw-bytes solve (no byteRefOutcome)', async () => {
|
|
483
|
+
const outcome = await runSolvePipeline(
|
|
484
|
+
baseArgs({ client: fakeClient(async () => ({ errors: [], warnings: [] })) })
|
|
485
|
+
);
|
|
486
|
+
expect(outcome.kind).toBe('ok');
|
|
487
|
+
if (outcome.kind !== 'ok') return;
|
|
488
|
+
expect(outcome.envelope.headers['Server-Timing']).not.toContain('def_bytes');
|
|
489
|
+
});
|
|
490
|
+
|
|
324
491
|
it('never attributes rhino timing to a Selva-cache hit (no compute call of ours)', async () => {
|
|
325
492
|
// Our request was served from the in-process cache while a concurrent
|
|
326
493
|
// request's compute call produced the only rhino timing in the window.
|
|
@@ -339,3 +506,155 @@ describe('runSolvePipeline — Server-Timing', () => {
|
|
|
339
506
|
expect(st).not.toContain('rhino_decode');
|
|
340
507
|
});
|
|
341
508
|
});
|
|
509
|
+
|
|
510
|
+
// ============================================================================
|
|
511
|
+
// L2 durable solve cache hook (Phase 3.4)
|
|
512
|
+
// ============================================================================
|
|
513
|
+
|
|
514
|
+
describe('runSolvePipeline — L2 solve cache', () => {
|
|
515
|
+
const config = { computeServerId: 'srv-1' };
|
|
516
|
+
|
|
517
|
+
/** A hook backed by a Map, recording lookups/stores for assertions. */
|
|
518
|
+
function fakeHook(seed?: Map<string, Uint8Array>) {
|
|
519
|
+
const store = seed ?? new Map<string, Uint8Array>();
|
|
520
|
+
const lookups: string[] = [];
|
|
521
|
+
const stores: string[] = [];
|
|
522
|
+
const hook: SolvePipelineCacheHook = {
|
|
523
|
+
configSubset: config,
|
|
524
|
+
lookup: async (key) => {
|
|
525
|
+
lookups.push(key);
|
|
526
|
+
return store.get(key) ?? null;
|
|
527
|
+
},
|
|
528
|
+
store: (key, entry) => {
|
|
529
|
+
stores.push(key);
|
|
530
|
+
store.set(key, entry);
|
|
531
|
+
}
|
|
532
|
+
};
|
|
533
|
+
return { hook, store, lookups, stores };
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
it('a miss solves, then write-throughs the gzipped envelope and marks l2_cache;dur=0', async () => {
|
|
537
|
+
const result = { values: [{ id: 'out' }], errors: [], warnings: ['w'] };
|
|
538
|
+
let solves = 0;
|
|
539
|
+
const { hook, store, stores } = fakeHook();
|
|
540
|
+
const outcome = await runSolvePipeline(
|
|
541
|
+
baseArgs({
|
|
542
|
+
client: fakeClient(async () => {
|
|
543
|
+
solves += 1;
|
|
544
|
+
return result;
|
|
545
|
+
}),
|
|
546
|
+
acceptEncoding: 'gzip',
|
|
547
|
+
solveCache: hook
|
|
548
|
+
})
|
|
549
|
+
);
|
|
550
|
+
expect(outcome.kind).toBe('ok');
|
|
551
|
+
if (outcome.kind !== 'ok') return;
|
|
552
|
+
expect(solves).toBe(1);
|
|
553
|
+
expect(outcome.envelope.headers['Server-Timing']).toContain('l2_cache;dur=0');
|
|
554
|
+
// Write-through happened — one entry stored under the derived key.
|
|
555
|
+
expect(stores).toHaveLength(1);
|
|
556
|
+
expect(store.size).toBe(1);
|
|
557
|
+
});
|
|
558
|
+
|
|
559
|
+
it('a hit returns the stored envelope WITHOUT solving and marks l2_cache;dur=1', async () => {
|
|
560
|
+
const result = { values: [{ id: 'cached' }], errors: [], warnings: [] };
|
|
561
|
+
const serialized = JSON.stringify(result);
|
|
562
|
+
// Pre-seed the store at the key the pipeline will derive for these inputs.
|
|
563
|
+
const args = baseArgs({ acceptEncoding: 'gzip' });
|
|
564
|
+
const tree = { __tree: true, count: 1 }; // matches the mock TreeBuilder output
|
|
565
|
+
const inputKey = deriveSolveCacheInputKey(tree, config).hash;
|
|
566
|
+
const entry = encodeSolveCacheEntry(
|
|
567
|
+
{ errorCount: 0, warningCount: 0, serializedBytes: serialized.length, inputHash: inputKey },
|
|
568
|
+
new Uint8Array(gzipSync(Buffer.from(serialized)))
|
|
569
|
+
);
|
|
570
|
+
const seed = new Map([[inputKey, entry]]);
|
|
571
|
+
const { hook } = fakeHook(seed);
|
|
572
|
+
|
|
573
|
+
let solves = 0;
|
|
574
|
+
const outcome = await runSolvePipeline({
|
|
575
|
+
...args,
|
|
576
|
+
client: fakeClient(async () => {
|
|
577
|
+
solves += 1;
|
|
578
|
+
return { values: [], errors: [], warnings: [] };
|
|
579
|
+
}),
|
|
580
|
+
solveCache: hook
|
|
581
|
+
});
|
|
582
|
+
expect(outcome.kind).toBe('ok');
|
|
583
|
+
if (outcome.kind !== 'ok') return;
|
|
584
|
+
expect(solves).toBe(0); // never solved — served from L2
|
|
585
|
+
expect(outcome.envelope.encoding).toBe('gzip');
|
|
586
|
+
expect(gunzipSync(outcome.envelope.body as Uint8Array).toString()).toBe(serialized);
|
|
587
|
+
expect(outcome.envelope.headers['Server-Timing']).toContain('l2_cache;dur=1');
|
|
588
|
+
});
|
|
589
|
+
|
|
590
|
+
it('a hit for a non-gzip client gunzips the stored body back to JSON', async () => {
|
|
591
|
+
const result = { values: [{ id: 'x' }], errors: [], warnings: [] };
|
|
592
|
+
const serialized = JSON.stringify(result);
|
|
593
|
+
const tree = { __tree: true, count: 1 };
|
|
594
|
+
const inputKey = deriveSolveCacheInputKey(tree, config).hash;
|
|
595
|
+
const entry = encodeSolveCacheEntry(
|
|
596
|
+
{ errorCount: 0, warningCount: 0, serializedBytes: serialized.length, inputHash: inputKey },
|
|
597
|
+
new Uint8Array(gzipSync(Buffer.from(serialized)))
|
|
598
|
+
);
|
|
599
|
+
const { hook } = fakeHook(new Map([[inputKey, entry]]));
|
|
600
|
+
const outcome = await runSolvePipeline(baseArgs({ acceptEncoding: '', solveCache: hook }));
|
|
601
|
+
expect(outcome.kind).toBe('ok');
|
|
602
|
+
if (outcome.kind !== 'ok') return;
|
|
603
|
+
expect(outcome.envelope.encoding).toBeUndefined();
|
|
604
|
+
expect(outcome.envelope.body).toBe(serialized);
|
|
605
|
+
});
|
|
606
|
+
|
|
607
|
+
it('a stored entry whose inputHash mismatches is ignored (collision defense) and re-solves', async () => {
|
|
608
|
+
// Seed the derived key with an entry carrying a DIFFERENT inputHash — a
|
|
609
|
+
// (hypothetical) storage-key collision must not serve the wrong geometry.
|
|
610
|
+
const tree = { __tree: true, count: 1 };
|
|
611
|
+
const inputKey = deriveSolveCacheInputKey(tree, config).hash;
|
|
612
|
+
const wrong = encodeSolveCacheEntry(
|
|
613
|
+
{ errorCount: 0, warningCount: 0, serializedBytes: 2, inputHash: 'not-the-real-hash' },
|
|
614
|
+
new Uint8Array(gzipSync(Buffer.from('{}')))
|
|
615
|
+
);
|
|
616
|
+
const { hook } = fakeHook(new Map([[inputKey, wrong]]));
|
|
617
|
+
let solves = 0;
|
|
618
|
+
const outcome = await runSolvePipeline(
|
|
619
|
+
baseArgs({
|
|
620
|
+
client: fakeClient(async () => {
|
|
621
|
+
solves += 1;
|
|
622
|
+
return { values: [{ id: 'fresh' }], errors: [], warnings: [] };
|
|
623
|
+
}),
|
|
624
|
+
solveCache: hook
|
|
625
|
+
})
|
|
626
|
+
);
|
|
627
|
+
expect(outcome.kind).toBe('ok');
|
|
628
|
+
if (outcome.kind !== 'ok') return;
|
|
629
|
+
expect(solves).toBe(1); // fell through to a real solve
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
it('omits l2_cache from Server-Timing when no hook is passed', async () => {
|
|
633
|
+
const outcome = await runSolvePipeline(baseArgs());
|
|
634
|
+
expect(outcome.kind).toBe('ok');
|
|
635
|
+
if (outcome.kind !== 'ok') return;
|
|
636
|
+
expect(outcome.envelope.headers['Server-Timing']).not.toContain('l2_cache');
|
|
637
|
+
});
|
|
638
|
+
|
|
639
|
+
it('a lookup that rejects is treated as a miss (best-effort), then solves', async () => {
|
|
640
|
+
let solves = 0;
|
|
641
|
+
const hook: SolvePipelineCacheHook = {
|
|
642
|
+
configSubset: config,
|
|
643
|
+
lookup: async () => {
|
|
644
|
+
throw new Error('backend down');
|
|
645
|
+
},
|
|
646
|
+
store: () => {}
|
|
647
|
+
};
|
|
648
|
+
const outcome = await runSolvePipeline(
|
|
649
|
+
baseArgs({
|
|
650
|
+
client: fakeClient(async () => {
|
|
651
|
+
solves += 1;
|
|
652
|
+
return { values: [], errors: [], warnings: [] };
|
|
653
|
+
}),
|
|
654
|
+
solveCache: hook
|
|
655
|
+
})
|
|
656
|
+
);
|
|
657
|
+
expect(outcome.kind).toBe('ok');
|
|
658
|
+
expect(solves).toBe(1);
|
|
659
|
+
});
|
|
660
|
+
});
|
|
@@ -103,6 +103,18 @@ export interface ClientCacheConfig {
|
|
|
103
103
|
* (`ComputeLimits.computeMaxConcurrentSolves`).
|
|
104
104
|
*/
|
|
105
105
|
maxConcurrentSolves: number;
|
|
106
|
+
/**
|
|
107
|
+
* Backpressure — max solves that may WAIT in the FIFO queue (excludes the
|
|
108
|
+
* in-flight `maxConcurrentSolves`). `0` = unbounded (`ComputeLimits.
|
|
109
|
+
* computeMaxQueueDepth`); a full queue sheds new solves with `QUEUE_FULL`.
|
|
110
|
+
*/
|
|
111
|
+
maxQueueDepth: number;
|
|
112
|
+
/**
|
|
113
|
+
* Backpressure — max ms a solve may sit queued before executing; `0` = no
|
|
114
|
+
* deadline (`ComputeLimits.computeQueueWaitMs`). A too-long wait sheds with
|
|
115
|
+
* `QUEUE_TIMEOUT`.
|
|
116
|
+
*/
|
|
117
|
+
queueWaitMs: number;
|
|
106
118
|
/** Concise cache/timing logs. When false, `onDebugLog` is never invoked. */
|
|
107
119
|
debug: boolean;
|
|
108
120
|
/** VERBOSE lib-level logging (full solve request/response incl. geometry). */
|
|
@@ -208,6 +220,11 @@ export function createClientCache(config: ClientCacheConfig): ClientCache {
|
|
|
208
220
|
// solve on this server through a single slot while the compute VM's
|
|
209
221
|
// other compute.geometry children idle (audit B6) — always pass it.
|
|
210
222
|
maxConcurrent: config.maxConcurrentSolves,
|
|
223
|
+
// Backpressure (audit B7). The scheduler treats undefined as
|
|
224
|
+
// unbounded/no-deadline, so map our `0`-means-off convention to undefined
|
|
225
|
+
// rather than passing 0 (which would shed EVERY queued solve).
|
|
226
|
+
maxQueueDepth: config.maxQueueDepth || undefined,
|
|
227
|
+
queueWaitMs: config.queueWaitMs || undefined,
|
|
211
228
|
timeoutMs: config.maxSolveDurationMs,
|
|
212
229
|
cache: { maxEntries: 20, ttlMs: 5 * 60_000 },
|
|
213
230
|
// Solve large definitions by server cache-key (pointer) instead of
|
|
@@ -241,14 +258,18 @@ export function createClientCache(config: ClientCacheConfig): ClientCache {
|
|
|
241
258
|
: '[Compute/def-cache] n/a — reuse disabled or non-reusable definition'
|
|
242
259
|
);
|
|
243
260
|
}
|
|
244
|
-
// Surface real GH errors when present.
|
|
245
|
-
//
|
|
261
|
+
// Surface real GH errors when present. Whether an errored solve is cached is
|
|
262
|
+
// config-gated by `cacheerroredsolves` (default false → errored solves are
|
|
263
|
+
// re-run each time; true → the error result is cached like any other, per R2).
|
|
246
264
|
if (!result.fromCache) {
|
|
247
265
|
const errs = (result.response as { errors?: unknown[] })?.errors;
|
|
248
266
|
const errCount = Array.isArray(errs) ? errs.length : 0;
|
|
249
267
|
if (errCount > 0) {
|
|
268
|
+
const cacheNote = config.cacheerroredsolves
|
|
269
|
+
? 'cached (cacheerroredsolves on)'
|
|
270
|
+
: 'not cached (cacheerroredsolves off) — re-run until fixed';
|
|
250
271
|
debugLog(
|
|
251
|
-
`[Compute/rhino-cache] ${errCount} GH error(s);
|
|
272
|
+
`[Compute/rhino-cache] ${errCount} GH error(s); ${cacheNote}. First: ${JSON.stringify((errs as unknown[])[0])}`
|
|
252
273
|
);
|
|
253
274
|
}
|
|
254
275
|
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-process cache of `.gh` definition bytes, keyed by immutable **version id**.
|
|
3
|
+
*
|
|
4
|
+
* The solve path used to eagerly `storage.get(fileKey)` on every request — moving
|
|
5
|
+
* multi-MB definition bytes off disk/S3 into memory before the scheduler could
|
|
6
|
+
* decide it didn't need them (the compute server already holds the definition via
|
|
7
|
+
* the pointer/`reuseServerDefinitionCache` fast path). This cache turns that eager
|
|
8
|
+
* read into a lazy `DefinitionRef.load()`: the scheduler calls `load()` ONLY when
|
|
9
|
+
* an upload is unavoidable, and even then a warm entry serves the bytes without
|
|
10
|
+
* touching storage. A pointer-known re-solve therefore moves ZERO definition bytes.
|
|
11
|
+
*
|
|
12
|
+
* Keying discipline (the whole reason this module exists):
|
|
13
|
+
* - The key is the **version id**, an immutable UUID — never a `fileKey`, which
|
|
14
|
+
* a delete-latest-then-reupload can REUSE for different content (see the
|
|
15
|
+
* monotonic-version-number fix). A reused key would serve one version's bytes
|
|
16
|
+
* for another: silent cache poisoning with no diagnostic. Callers pass
|
|
17
|
+
* `version.id`, and the returned `DefinitionRef.key` is that same id, so the
|
|
18
|
+
* scheduler's own result/pointer cache keys on the same immutable identity.
|
|
19
|
+
*
|
|
20
|
+
* Eviction:
|
|
21
|
+
* - LRU by **total byte budget**, not entry count — definitions range from tens
|
|
22
|
+
* of KB to hundreds of MB, so an entry-count cap would either pin gigabytes or
|
|
23
|
+
* evict uselessly. `COMPUTE_DEFINITION_BYTE_CACHE_MB` sets the budget; `0`
|
|
24
|
+
* disables the cache (every `getOrLoad` calls `load` and caches nothing).
|
|
25
|
+
* - No TTL: version ids are immutable, so a cached entry can never go stale.
|
|
26
|
+
* - An entry larger than the whole budget is served but never retained (caching
|
|
27
|
+
* it would immediately evict everything including itself).
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Per-`getOrLoad` outcome, observable AFTER the scheduler has (or hasn't) called
|
|
32
|
+
* `load()`. Lets the solve pipeline emit a `def_bytes` Server-Timing verdict:
|
|
33
|
+
* - `load` never invoked → the scheduler served a pointer-known solve without
|
|
34
|
+
* bytes (`skipped`);
|
|
35
|
+
* - `load` invoked, `fromCache` true → warm byte-cache entry (`hit`);
|
|
36
|
+
* - `load` invoked, `fromCache` false → fell through to the loader (`miss`).
|
|
37
|
+
*/
|
|
38
|
+
export interface ByteRefOutcome {
|
|
39
|
+
/** True once `load()` has been called at least once on this ref. */
|
|
40
|
+
loaded: boolean;
|
|
41
|
+
/** When `loaded`, whether the bytes came from a warm cache entry. */
|
|
42
|
+
fromCache: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A definition reference shaped for `@selvajs/compute`'s `DefinitionRef`. */
|
|
46
|
+
export interface ByteCacheRef {
|
|
47
|
+
/** Immutable identity (a version UUID). Keys the scheduler's caches too. */
|
|
48
|
+
key: string;
|
|
49
|
+
/** Materialize the bytes — served from cache when warm, else via the loader. */
|
|
50
|
+
load: () => Promise<Uint8Array>;
|
|
51
|
+
/** Mutable outcome of this ref's `load()` (see {@link ByteRefOutcome}). */
|
|
52
|
+
outcome: ByteRefOutcome;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Hit/miss/eviction counters for observability (Server-Timing, admin debug). */
|
|
56
|
+
export interface ByteCacheStats {
|
|
57
|
+
/** `load()` served from a warm entry (no loader call). */
|
|
58
|
+
hits: number;
|
|
59
|
+
/** `load()` fell through to the loader (cold key, or caching disabled). */
|
|
60
|
+
misses: number;
|
|
61
|
+
/** Entries dropped by the byte-budget LRU. */
|
|
62
|
+
evictions: number;
|
|
63
|
+
/** Current retained entry count. */
|
|
64
|
+
entries: number;
|
|
65
|
+
/** Current retained bytes. */
|
|
66
|
+
bytes: number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface DefinitionByteCache {
|
|
70
|
+
/**
|
|
71
|
+
* Return a `DefinitionRef` whose `load()` serves `versionId`'s bytes from the
|
|
72
|
+
* cache when warm, otherwise calls `load` (and caches the result). The
|
|
73
|
+
* `DefinitionRef` is cheap to build and moves no bytes until `load()` runs —
|
|
74
|
+
* so handing it to the scheduler for a pointer-known solve costs nothing.
|
|
75
|
+
*/
|
|
76
|
+
getOrLoad(versionId: string, load: () => Promise<Uint8Array>): ByteCacheRef;
|
|
77
|
+
/** Snapshot of the counters (see {@link ByteCacheStats}). */
|
|
78
|
+
stats(): ByteCacheStats;
|
|
79
|
+
/** Drop everything (test seam / eviction on definition delete if ever needed). */
|
|
80
|
+
clear(): void;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface Entry {
|
|
84
|
+
bytes: Uint8Array;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Build a definition-byte cache with a total-byte LRU budget.
|
|
89
|
+
*
|
|
90
|
+
* @param maxBytes total retained-byte budget; `0` (or negative) disables caching
|
|
91
|
+
* entirely — every `load()` calls the loader and nothing is retained.
|
|
92
|
+
*/
|
|
93
|
+
export function createDefinitionByteCache(maxBytes: number): DefinitionByteCache {
|
|
94
|
+
const budget = Math.max(0, Math.floor(maxBytes));
|
|
95
|
+
// Map preserves insertion order → iteration order IS LRU order; re-inserting
|
|
96
|
+
// on access moves an entry to the most-recently-used (last) position.
|
|
97
|
+
const cache = new Map<string, Entry>();
|
|
98
|
+
let retainedBytes = 0;
|
|
99
|
+
const stats = { hits: 0, misses: 0, evictions: 0 };
|
|
100
|
+
|
|
101
|
+
function touch(key: string, entry: Entry): void {
|
|
102
|
+
cache.delete(key);
|
|
103
|
+
cache.set(key, entry);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function evictToFit(): void {
|
|
107
|
+
// Evict least-recently-used (first in insertion order) until within budget.
|
|
108
|
+
while (retainedBytes > budget && cache.size > 0) {
|
|
109
|
+
const oldestKey = cache.keys().next().value as string;
|
|
110
|
+
const oldest = cache.get(oldestKey)!;
|
|
111
|
+
cache.delete(oldestKey);
|
|
112
|
+
retainedBytes -= oldest.bytes.byteLength;
|
|
113
|
+
stats.evictions += 1;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function store(key: string, bytes: Uint8Array): void {
|
|
118
|
+
if (budget === 0) return;
|
|
119
|
+
// An entry bigger than the whole budget is never retained — caching it would
|
|
120
|
+
// evict everything (including itself) on the next `evictToFit`. Serve it
|
|
121
|
+
// through, cache nothing.
|
|
122
|
+
if (bytes.byteLength > budget) return;
|
|
123
|
+
const existing = cache.get(key);
|
|
124
|
+
if (existing) retainedBytes -= existing.bytes.byteLength;
|
|
125
|
+
cache.set(key, { bytes });
|
|
126
|
+
retainedBytes += bytes.byteLength;
|
|
127
|
+
evictToFit();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return {
|
|
131
|
+
getOrLoad(versionId, load) {
|
|
132
|
+
const outcome: ByteRefOutcome = { loaded: false, fromCache: false };
|
|
133
|
+
return {
|
|
134
|
+
key: versionId,
|
|
135
|
+
outcome,
|
|
136
|
+
load: async () => {
|
|
137
|
+
const hit = cache.get(versionId);
|
|
138
|
+
if (hit) {
|
|
139
|
+
touch(versionId, hit);
|
|
140
|
+
stats.hits += 1;
|
|
141
|
+
outcome.loaded = true;
|
|
142
|
+
outcome.fromCache = true;
|
|
143
|
+
return hit.bytes;
|
|
144
|
+
}
|
|
145
|
+
stats.misses += 1;
|
|
146
|
+
outcome.loaded = true;
|
|
147
|
+
outcome.fromCache = false;
|
|
148
|
+
const bytes = await load();
|
|
149
|
+
store(versionId, bytes);
|
|
150
|
+
return bytes;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
},
|
|
154
|
+
stats() {
|
|
155
|
+
return {
|
|
156
|
+
hits: stats.hits,
|
|
157
|
+
misses: stats.misses,
|
|
158
|
+
evictions: stats.evictions,
|
|
159
|
+
entries: cache.size,
|
|
160
|
+
bytes: retainedBytes
|
|
161
|
+
};
|
|
162
|
+
},
|
|
163
|
+
clear() {
|
|
164
|
+
cache.clear();
|
|
165
|
+
retainedBytes = 0;
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
}
|
package/src/compute/index.ts
CHANGED
|
@@ -3,11 +3,44 @@
|
|
|
3
3
|
export {
|
|
4
4
|
resolveComputeLimits,
|
|
5
5
|
readPositiveInt,
|
|
6
|
+
readNonNegativeInt,
|
|
6
7
|
readBool,
|
|
7
8
|
type ComputeLimits,
|
|
8
9
|
type EnvRecord
|
|
9
10
|
} from './limits.js';
|
|
10
11
|
|
|
12
|
+
export {
|
|
13
|
+
createDefinitionByteCache,
|
|
14
|
+
type DefinitionByteCache,
|
|
15
|
+
type ByteCacheRef,
|
|
16
|
+
type ByteCacheStats
|
|
17
|
+
} from './definition-byte-cache.js';
|
|
18
|
+
|
|
19
|
+
export {
|
|
20
|
+
createMemorySolveResultCache,
|
|
21
|
+
type MemorySolveResultCache,
|
|
22
|
+
type SolveCacheStats
|
|
23
|
+
} from './memory-solve-cache.js';
|
|
24
|
+
|
|
25
|
+
export {
|
|
26
|
+
deriveSolveCacheInputKey,
|
|
27
|
+
type SolveCacheConfigSubset,
|
|
28
|
+
type SolveCacheInputKey
|
|
29
|
+
} from './solve-cache-key.js';
|
|
30
|
+
|
|
31
|
+
export {
|
|
32
|
+
encodeSolveCacheEntry,
|
|
33
|
+
decodeSolveCacheEntry,
|
|
34
|
+
gunzipEntryBody,
|
|
35
|
+
type EnvelopeHeader,
|
|
36
|
+
type DecodedSolveCacheEntry
|
|
37
|
+
} from './solve-cache-envelope.js';
|
|
38
|
+
|
|
39
|
+
export {
|
|
40
|
+
createSolveCacheSingleFlight,
|
|
41
|
+
type SolveCacheSingleFlight
|
|
42
|
+
} from './solve-cache-single-flight.js';
|
|
43
|
+
|
|
11
44
|
export {
|
|
12
45
|
createComputeRateLimiter,
|
|
13
46
|
type ComputeRateLimiter,
|
|
@@ -41,6 +74,7 @@ export {
|
|
|
41
74
|
COMPUTE_CONTRACT_VERSION,
|
|
42
75
|
COMPUTE_VERSION_HEADER,
|
|
43
76
|
type SolvePipelineArgs,
|
|
77
|
+
type SolvePipelineCacheHook,
|
|
44
78
|
type SolveOutcome,
|
|
45
79
|
type SolveEnvelope,
|
|
46
80
|
type SolvePhaseMetrics,
|