@selvajs/ui 5.0.1 → 6.0.0-beta.0
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/components/compute/ComputeApp.svelte +15 -7
- package/dist/components/compute/ComputeApp.svelte.d.ts +1 -1
- package/dist/components/primitives/textarea/textarea.svelte +1 -2
- package/dist/components/viewer/SceneManager.svelte +75 -160
- package/dist/components/viewer/SceneManager.svelte.d.ts +8 -3
- package/dist/components/viewer/Viewer.svelte +20 -3
- package/dist/compute/useSolveSession.svelte.d.ts +12 -0
- package/dist/compute/useSolveSession.svelte.js +76 -0
- package/dist/external/storage.d.ts +1 -15
- package/dist/external/storage.js +4 -54
- package/dist/index.d.ts +4 -3
- package/dist/index.js +7 -4
- package/dist/public.d.ts +4 -3
- package/dist/public.js +9 -5
- package/package.json +5 -3
- package/src/lib/components/compute/ComputeApp.svelte +15 -7
- package/src/lib/components/primitives/textarea/textarea.svelte +1 -2
- package/src/lib/components/viewer/SceneManager.svelte +75 -160
- package/src/lib/components/viewer/Viewer.svelte +20 -3
- package/src/lib/compute/mesh-policy-wiring.test.ts +72 -0
- package/src/lib/compute/useSolveSession.svelte.ts +83 -0
- package/src/lib/external/storage.ts +12 -64
- package/src/lib/index.ts +15 -5
- package/src/lib/public.ts +17 -6
- package/dist/compute/computeThrottle.svelte.d.ts +0 -24
- package/dist/compute/computeThrottle.svelte.js +0 -82
- package/dist/compute/createSolveSession.svelte.d.ts +0 -66
- package/dist/compute/createSolveSession.svelte.js +0 -159
- package/dist/compute/solve-session-core.d.ts +0 -54
- package/dist/compute/solve-session-core.js +0 -87
- package/dist/compute/solveMemo.d.ts +0 -22
- package/dist/compute/solveMemo.js +0 -124
- package/dist/types/solveFn.d.ts +0 -25
- package/dist/types/solveFn.js +0 -1
- package/src/lib/compute/computeThrottle.svelte.ts +0 -109
- package/src/lib/compute/computeThrottle.test.ts +0 -106
- package/src/lib/compute/createSolveSession.svelte.ts +0 -239
- package/src/lib/compute/createSolveSession.test.ts +0 -168
- package/src/lib/compute/solve-session-core.test.ts +0 -153
- package/src/lib/compute/solve-session-core.ts +0 -122
- package/src/lib/compute/solveMemo.test.ts +0 -220
- package/src/lib/compute/solveMemo.ts +0 -140
- package/src/lib/external/storage.test.ts +0 -99
- package/src/lib/types/solveFn.ts +0 -29
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
// Pure, framework-free transition logic for a Solve Session (see CONTEXT.md).
|
|
2
|
-
//
|
|
3
|
-
// This module holds the value/lifecycle state machine with no Svelte runes and no
|
|
4
|
-
// transport: how values are seeded (including client-sourced hydration), when a value
|
|
5
|
-
// change should dispatch a solve vs. defer it, and what a reported solve result does to
|
|
6
|
-
// the flags. The reactive wrapper in createSolveSession.svelte.ts is a thin shell over
|
|
7
|
-
// these functions; everything testable lives here.
|
|
8
|
-
import { getDefaultValue } from '../schema/defaults';
|
|
9
|
-
import { getExternalInputs } from '../external/storage';
|
|
10
|
-
/**
|
|
11
|
-
* Builds the initial `values` map for a schema. Non-client inputs get their declared
|
|
12
|
-
* default (falling back to the paramType default); client-sourced inputs are hydrated
|
|
13
|
-
* from `read` and left absent when no stored value exists so the missing-inputs panel
|
|
14
|
-
* can detect them. Outputs are seeded to null.
|
|
15
|
-
*/
|
|
16
|
-
export function buildInitialValues(schema, scopeKey, read) {
|
|
17
|
-
const clientSet = new Set(getExternalInputs(schema).map((e) => e.paramId));
|
|
18
|
-
const values = {};
|
|
19
|
-
for (const input of schema.inputs) {
|
|
20
|
-
if (clientSet.has(input.id)) {
|
|
21
|
-
const stored = read({ scopeKey, inputId: input.id });
|
|
22
|
-
if (stored !== undefined)
|
|
23
|
-
values[input.id] = stored;
|
|
24
|
-
continue;
|
|
25
|
-
}
|
|
26
|
-
values[input.id] = input.default ?? getDefaultValue(input.paramType);
|
|
27
|
-
}
|
|
28
|
-
for (const output of schema.outputs) {
|
|
29
|
-
values[output.id] = null;
|
|
30
|
-
}
|
|
31
|
-
return values;
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Initial lifecycle flags. Manual-solve schemas (instanceSolve === false) start dirty
|
|
35
|
-
* so the user must explicitly calculate; auto-solve schemas start clean.
|
|
36
|
-
*/
|
|
37
|
-
export function makeInitialFlags(instanceSolve) {
|
|
38
|
-
const manual = instanceSolve === false;
|
|
39
|
-
return { hasPendingChanges: manual, hasNeverSolved: manual };
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Records a single value change and decides whether it should dispatch a solve now.
|
|
43
|
-
* Auto-solve mode dispatches immediately; manual mode defers (records the pending value
|
|
44
|
-
* and raises the dirty flag) and never dispatches.
|
|
45
|
-
*/
|
|
46
|
-
export function applyValueChange(state, id, value, instanceSolve) {
|
|
47
|
-
state.values[id] = value;
|
|
48
|
-
if (instanceSolve === false) {
|
|
49
|
-
state.pendingValues[id] = value;
|
|
50
|
-
state.hasPendingChanges = true;
|
|
51
|
-
return { state, shouldSolve: false };
|
|
52
|
-
}
|
|
53
|
-
return { state, shouldSolve: true };
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Projects the session's live values down to solve INPUTS. Solve outputs are merged
|
|
57
|
-
* into the same values map after each solve (applySolveResult) so widgets like
|
|
58
|
-
* dynamic value lists can read them — but they are not solve inputs, and echoing
|
|
59
|
-
* them back to the driver re-uploads potentially MB-sized payloads (a measured
|
|
60
|
-
* 6.4 MB options list) that no backend reads. Every transport gets this projection
|
|
61
|
-
* for free by going through the session's dispatch.
|
|
62
|
-
*/
|
|
63
|
-
export function pickInputValues(schema, values) {
|
|
64
|
-
if (!schema?.inputs)
|
|
65
|
-
return values;
|
|
66
|
-
const picked = {};
|
|
67
|
-
for (const input of schema.inputs) {
|
|
68
|
-
if (input.id in values)
|
|
69
|
-
picked[input.id] = values[input.id];
|
|
70
|
-
}
|
|
71
|
-
return picked;
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* Merges a reported solve result into the state and clears the post-solve lifecycle
|
|
75
|
-
* flags. Missing result arrays are treated as empty.
|
|
76
|
-
*/
|
|
77
|
-
export function applySolveResult(state, result) {
|
|
78
|
-
state.error = '';
|
|
79
|
-
state.computeErrors = result.errors ?? [];
|
|
80
|
-
state.computeWarnings = result.warnings ?? [];
|
|
81
|
-
state.meshes = result.meshes ?? [];
|
|
82
|
-
Object.assign(state.values, result.outputs);
|
|
83
|
-
state.pendingValues = {};
|
|
84
|
-
state.hasPendingChanges = false;
|
|
85
|
-
state.hasNeverSolved = false;
|
|
86
|
-
return state;
|
|
87
|
-
}
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import type { SolveResult } from '../types/solveFn';
|
|
2
|
-
/**
|
|
3
|
-
* Deterministic string key for a set of input values. Object keys are sorted at every
|
|
4
|
-
* level so two logically-equal inputs (built in different key order) collide, matching
|
|
5
|
-
* the server's stable-input keying intent. Values are plain JSON (numbers, strings,
|
|
6
|
-
* booleans, arrays) — the projected solve inputs never contain functions or cycles.
|
|
7
|
-
*/
|
|
8
|
-
export declare function stableInputKey(values: Record<string, unknown>): string;
|
|
9
|
-
export interface SolveMemo {
|
|
10
|
-
/** Returns a previously stored result for these inputs, or undefined on a miss. */
|
|
11
|
-
get(values: Record<string, unknown>): SolveResult | undefined;
|
|
12
|
-
/** Records a completed solve result under its input key (evicting the LRU tail). */
|
|
13
|
-
set(values: Record<string, unknown>, result: SolveResult): void;
|
|
14
|
-
/** Drops every entry — called when the active definition changes. */
|
|
15
|
-
clear(): void;
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
|
-
* A bounded LRU memo. `max` caps entries (not bytes); solve results can be large, so the
|
|
19
|
-
* default is deliberately small — this targets the tight slider-scrub loop, not a durable
|
|
20
|
-
* cache. Re-reading an entry refreshes its recency (Map insertion-order LRU).
|
|
21
|
-
*/
|
|
22
|
-
export declare function createSolveMemo(max?: number): SolveMemo;
|
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
// Client-side solve result memo (M2). A small LRU keyed on a stable serialization of
|
|
2
|
-
// the solve INPUTS, sitting in front of the request/response driver. Dragging a slider
|
|
3
|
-
// back to a value already solved this session returns instantly without a network
|
|
4
|
-
// round-trip — killing slider-scrub storms before they leave the browser. It pairs with
|
|
5
|
-
// the throttle's latest-wins abort: the memo only serves values that fully solved, so a
|
|
6
|
-
// hit is always a complete result.
|
|
7
|
-
//
|
|
8
|
-
// GPU ownership (audit C1): a SolveResult carries live three.js objects, and the viewer
|
|
9
|
-
// takes ownership of every mesh array it renders — `updateScene` disposes the previous
|
|
10
|
-
// content on the next update. So the memo can neither hand out its own instances (they'd
|
|
11
|
-
// be disposed under it, then re-added dead on the next hit) nor drop entries silently
|
|
12
|
-
// (their GPU buffers would leak). It therefore keeps private copies, serves a fresh clone
|
|
13
|
-
// per hit, and disposes an entry whenever it leaves the map.
|
|
14
|
-
import * as THREE from 'three';
|
|
15
|
-
/**
|
|
16
|
-
* Deterministic string key for a set of input values. Object keys are sorted at every
|
|
17
|
-
* level so two logically-equal inputs (built in different key order) collide, matching
|
|
18
|
-
* the server's stable-input keying intent. Values are plain JSON (numbers, strings,
|
|
19
|
-
* booleans, arrays) — the projected solve inputs never contain functions or cycles.
|
|
20
|
-
*/
|
|
21
|
-
export function stableInputKey(values) {
|
|
22
|
-
return serialize(values);
|
|
23
|
-
}
|
|
24
|
-
function serialize(value) {
|
|
25
|
-
if (value === null || typeof value !== 'object')
|
|
26
|
-
return JSON.stringify(value) ?? 'null';
|
|
27
|
-
if (Array.isArray(value))
|
|
28
|
-
return `[${value.map(serialize).join(',')}]`;
|
|
29
|
-
const obj = value;
|
|
30
|
-
const keys = Object.keys(obj).sort();
|
|
31
|
-
return `{${keys.map((k) => `${JSON.stringify(k)}:${serialize(obj[k])}`).join(',')}}`;
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Deep-clone a solve's scene objects so the caller owns them outright.
|
|
35
|
-
*
|
|
36
|
-
* `Object3D.clone()` copies the transform hierarchy but SHARES `geometry` and `material`
|
|
37
|
-
* by reference — which is exactly the aliasing that makes a naive clone useless here, so
|
|
38
|
-
* geometry is copied explicitly. Materials are deliberately left shared: the viewer's
|
|
39
|
-
* `clearScene` skips disposing anything in its SHARED_MATERIALS set (module-scope
|
|
40
|
-
* singletons reused across solves), and per-mesh materials are cheap to recreate but
|
|
41
|
-
* expensive to re-compile as new shader programs.
|
|
42
|
-
*/
|
|
43
|
-
function cloneSceneObjects(meshes) {
|
|
44
|
-
return meshes.map((root) => {
|
|
45
|
-
const copy = root.clone(true);
|
|
46
|
-
const sources = [];
|
|
47
|
-
root.traverse((child) => sources.push(child));
|
|
48
|
-
let i = 0;
|
|
49
|
-
copy.traverse((child) => {
|
|
50
|
-
const source = sources[i++];
|
|
51
|
-
const target = child;
|
|
52
|
-
if (source.geometry)
|
|
53
|
-
target.geometry = source.geometry.clone();
|
|
54
|
-
});
|
|
55
|
-
return copy;
|
|
56
|
-
});
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Release an entry's GPU buffers. Mirrors `clearScene`'s traversal, minus materials —
|
|
60
|
-
* the memo never owns those (see {@link cloneSceneObjects}), so disposing one here would
|
|
61
|
-
* free a singleton still referenced by live scene content.
|
|
62
|
-
*/
|
|
63
|
-
function disposeSceneObjects(result) {
|
|
64
|
-
result.meshes?.forEach((root) => root.traverse((child) => {
|
|
65
|
-
child.geometry?.dispose();
|
|
66
|
-
}));
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* A bounded LRU memo. `max` caps entries (not bytes); solve results can be large, so the
|
|
70
|
-
* default is deliberately small — this targets the tight slider-scrub loop, not a durable
|
|
71
|
-
* cache. Re-reading an entry refreshes its recency (Map insertion-order LRU).
|
|
72
|
-
*/
|
|
73
|
-
export function createSolveMemo(max = 16) {
|
|
74
|
-
const entries = new Map();
|
|
75
|
-
/** Drop an entry and release its GPU buffers. No-op when the key is absent. */
|
|
76
|
-
function evict(key) {
|
|
77
|
-
const entry = entries.get(key);
|
|
78
|
-
if (entry === undefined)
|
|
79
|
-
return;
|
|
80
|
-
entries.delete(key);
|
|
81
|
-
disposeSceneObjects(entry);
|
|
82
|
-
}
|
|
83
|
-
return {
|
|
84
|
-
get(values) {
|
|
85
|
-
const key = stableInputKey(values);
|
|
86
|
-
const hit = entries.get(key);
|
|
87
|
-
if (hit === undefined)
|
|
88
|
-
return undefined;
|
|
89
|
-
// Refresh recency: re-insert at the tail.
|
|
90
|
-
entries.delete(key);
|
|
91
|
-
entries.set(key, hit);
|
|
92
|
-
// A memo hit skips the transport entirely, so no other log line fires —
|
|
93
|
-
// this line is the only trace it wasn't a fresh solve.
|
|
94
|
-
console.info(`[Compute/memo] HIT — served from client memo (${entries.size}/${max})`);
|
|
95
|
-
// Clone on the way out: the viewer disposes what it renders, so the retained
|
|
96
|
-
// entry must never be the instance handed to it (audit C1).
|
|
97
|
-
if (!hit.meshes?.length)
|
|
98
|
-
return hit;
|
|
99
|
-
return { ...hit, meshes: cloneSceneObjects(hit.meshes) };
|
|
100
|
-
},
|
|
101
|
-
set(values, result) {
|
|
102
|
-
const key = stableInputKey(values);
|
|
103
|
-
// Overwriting a key strands the old value's buffers unless it's disposed first.
|
|
104
|
-
evict(key);
|
|
105
|
-
// Store a private copy for the same reason `get` clones: the caller reports this
|
|
106
|
-
// same object to the viewer, which will dispose it on the next scene update.
|
|
107
|
-
entries.set(key, result.meshes?.length ? { ...result, meshes: cloneSceneObjects(result.meshes) } : result);
|
|
108
|
-
while (entries.size > max) {
|
|
109
|
-
const oldest = entries.keys().next().value;
|
|
110
|
-
if (oldest === undefined)
|
|
111
|
-
break;
|
|
112
|
-
evict(oldest);
|
|
113
|
-
console.info(`[Compute/memo] evicted LRU entry (cap ${max})`);
|
|
114
|
-
}
|
|
115
|
-
},
|
|
116
|
-
clear() {
|
|
117
|
-
if (entries.size > 0) {
|
|
118
|
-
console.info(`[Compute/memo] cleared ${entries.size} entries (definition changed)`);
|
|
119
|
-
}
|
|
120
|
-
entries.forEach(disposeSceneObjects);
|
|
121
|
-
entries.clear();
|
|
122
|
-
}
|
|
123
|
-
};
|
|
124
|
-
}
|
package/dist/types/solveFn.d.ts
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Result returned from a solve operation.
|
|
3
|
-
*
|
|
4
|
-
* @property outputs - Key-value pairs of computed results
|
|
5
|
-
* @property meshes - Optional array of 3D mesh data generated during computation
|
|
6
|
-
* @property errors - Optional array of error messages that occurred
|
|
7
|
-
* @property warnings - Optional array of warning messages from the computation
|
|
8
|
-
*/
|
|
9
|
-
export interface SolveResult {
|
|
10
|
-
outputs: Record<string, unknown>;
|
|
11
|
-
meshes?: any[];
|
|
12
|
-
errors?: string[];
|
|
13
|
-
warnings?: string[];
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* Function type for running a computation with given input values.
|
|
17
|
-
*
|
|
18
|
-
* Implementations should listen to the abort signal and clean up resources
|
|
19
|
-
* when the signal is triggered (e.g., when the user cancels the operation).
|
|
20
|
-
*
|
|
21
|
-
* @param values - Input parameters for the computation
|
|
22
|
-
* @param signal - AbortSignal to cancel ongoing operations
|
|
23
|
-
* @returns Promise resolving to the computation result
|
|
24
|
-
*/
|
|
25
|
-
export type SolveFn = (values: Record<string, unknown>, signal: AbortSignal) => Promise<SolveResult>;
|
package/dist/types/solveFn.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Compute throttle utility for managing async compute requests.
|
|
3
|
-
*
|
|
4
|
-
* - Only one request in-flight at a time
|
|
5
|
-
* - Latest values always win (no queue)
|
|
6
|
-
* - AbortController support to cancel stale requests
|
|
7
|
-
* - Configurable timeout with automatic abort
|
|
8
|
-
*/
|
|
9
|
-
interface ComputeThrottleOptions {
|
|
10
|
-
timeout?: number;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Fallback per-solve abort timeout (ms) when the caller doesn't pass one.
|
|
15
|
-
* Used only by callers without a deployment-specific limit (e.g. plugin-ui
|
|
16
|
-
* over WebSocket); the selva app supplies `MAX_SOLVE_DURATION_MS` from its
|
|
17
|
-
* server config via `ComputeApp`'s `solveTimeoutMs` prop.
|
|
18
|
-
*/
|
|
19
|
-
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Creates a throttled compute handler that keeps only one request in-flight.
|
|
23
|
-
* If a new value arrives while one is running, it overwrites the single pending
|
|
24
|
-
* slot — older pending values are dropped. The pending value runs once the
|
|
25
|
-
* current request finishes (or aborts).
|
|
26
|
-
*/
|
|
27
|
-
export function createComputeThrottle<T>(
|
|
28
|
-
computeFn: (values: T, signal: AbortSignal) => Promise<void>,
|
|
29
|
-
options: ComputeThrottleOptions = {}
|
|
30
|
-
): {
|
|
31
|
-
trigger: (values: T) => void;
|
|
32
|
-
readonly isComputing: boolean;
|
|
33
|
-
readonly hasPending: boolean;
|
|
34
|
-
cancel: () => void;
|
|
35
|
-
} {
|
|
36
|
-
const { timeout = DEFAULT_TIMEOUT_MS } = options;
|
|
37
|
-
|
|
38
|
-
let isComputing = $state(false);
|
|
39
|
-
let pendingValues = $state<T | null>(null);
|
|
40
|
-
let currentAbortController: AbortController | null = null;
|
|
41
|
-
|
|
42
|
-
function abortCurrent() {
|
|
43
|
-
currentAbortController?.abort();
|
|
44
|
-
currentAbortController = null;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
async function executeCompute(values: T) {
|
|
48
|
-
abortCurrent();
|
|
49
|
-
|
|
50
|
-
currentAbortController = new AbortController();
|
|
51
|
-
const { signal } = currentAbortController;
|
|
52
|
-
const timeoutId = setTimeout(() => {
|
|
53
|
-
// Cleared in `finally` on every other path, so firing means a genuine
|
|
54
|
-
// timeout — the only signal for it (the abort itself is swallowed below).
|
|
55
|
-
console.warn(`[Compute/throttle] solve exceeded ${timeout}ms — aborting`);
|
|
56
|
-
currentAbortController?.abort();
|
|
57
|
-
}, timeout);
|
|
58
|
-
|
|
59
|
-
isComputing = true;
|
|
60
|
-
try {
|
|
61
|
-
await computeFn(values, signal);
|
|
62
|
-
} catch (err) {
|
|
63
|
-
// AbortError is expected (timeout or cancel). Non-abort errors must be
|
|
64
|
-
// handled inside computeFn — re-throwing here would produce an unhandled
|
|
65
|
-
// rejection because executeCompute is always called fire-and-forget.
|
|
66
|
-
if (!(err instanceof Error) || (err.name !== 'AbortError' && err.name !== 'TimeoutError')) {
|
|
67
|
-
console.error('[computeThrottle] unhandled error in computeFn:', err);
|
|
68
|
-
}
|
|
69
|
-
} finally {
|
|
70
|
-
clearTimeout(timeoutId);
|
|
71
|
-
isComputing = false;
|
|
72
|
-
currentAbortController = null;
|
|
73
|
-
|
|
74
|
-
if (pendingValues !== null) {
|
|
75
|
-
const next = pendingValues;
|
|
76
|
-
pendingValues = null;
|
|
77
|
-
executeCompute(next);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
function trigger(values: T) {
|
|
83
|
-
if (isComputing) {
|
|
84
|
-
if (pendingValues !== null) {
|
|
85
|
-
// Latest-wins: the previously-queued values are dropped, not solved.
|
|
86
|
-
console.debug('[Compute/throttle] superseded pending solve (latest-wins)');
|
|
87
|
-
}
|
|
88
|
-
pendingValues = values;
|
|
89
|
-
} else {
|
|
90
|
-
executeCompute(values);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function cancel() {
|
|
95
|
-
pendingValues = null;
|
|
96
|
-
abortCurrent();
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
return {
|
|
100
|
-
trigger,
|
|
101
|
-
get isComputing() {
|
|
102
|
-
return isComputing;
|
|
103
|
-
},
|
|
104
|
-
get hasPending() {
|
|
105
|
-
return pendingValues !== null;
|
|
106
|
-
},
|
|
107
|
-
cancel
|
|
108
|
-
};
|
|
109
|
-
}
|
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
-
import { createComputeThrottle } from './computeThrottle.svelte';
|
|
3
|
-
|
|
4
|
-
// Pins the throttle state machine: single-in-flight, latest-pending-wins, abort on
|
|
5
|
-
// re-trigger, timeout -> abort, and cancel clearing the pending slot. These are the
|
|
6
|
-
// non-obvious paths (the finally-block re-entry, the abort cleanup) where bugs hide.
|
|
7
|
-
// `computeThrottle.svelte.ts` is a rune module, so these run under the svelte vitest
|
|
8
|
-
// plugin (see vitest.config.ts).
|
|
9
|
-
|
|
10
|
-
// A controllable computeFn: each call exposes a resolver so the test drives when a
|
|
11
|
-
// solve "finishes", plus records the values and the signal it was given.
|
|
12
|
-
function deferredComputeFn() {
|
|
13
|
-
const calls: { values: unknown; signal: AbortSignal; resolve: () => void }[] = [];
|
|
14
|
-
const fn = (values: unknown, signal: AbortSignal) =>
|
|
15
|
-
new Promise<void>((resolve) => {
|
|
16
|
-
calls.push({ values, signal, resolve });
|
|
17
|
-
});
|
|
18
|
-
return { fn, calls };
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
const tick = () => new Promise((r) => setTimeout(r, 0));
|
|
22
|
-
|
|
23
|
-
describe('createComputeThrottle', () => {
|
|
24
|
-
it('runs immediately when idle and reports isComputing across the call', async () => {
|
|
25
|
-
const { fn, calls } = deferredComputeFn();
|
|
26
|
-
const t = createComputeThrottle<number>(fn);
|
|
27
|
-
|
|
28
|
-
expect(t.isComputing).toBe(false);
|
|
29
|
-
t.trigger(1);
|
|
30
|
-
expect(t.isComputing).toBe(true);
|
|
31
|
-
expect(calls).toHaveLength(1);
|
|
32
|
-
expect(calls[0].values).toBe(1);
|
|
33
|
-
|
|
34
|
-
calls[0].resolve();
|
|
35
|
-
await tick();
|
|
36
|
-
expect(t.isComputing).toBe(false);
|
|
37
|
-
expect(t.hasPending).toBe(false);
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
it('keeps only one in flight; latest pending value wins, intermediates dropped', async () => {
|
|
41
|
-
const { fn, calls } = deferredComputeFn();
|
|
42
|
-
const t = createComputeThrottle<number>(fn);
|
|
43
|
-
|
|
44
|
-
t.trigger(1); // runs
|
|
45
|
-
t.trigger(2); // queued
|
|
46
|
-
t.trigger(3); // overwrites the single pending slot — 2 is dropped
|
|
47
|
-
expect(calls).toHaveLength(1);
|
|
48
|
-
expect(t.hasPending).toBe(true);
|
|
49
|
-
|
|
50
|
-
calls[0].resolve(); // first finishes -> pending (3) runs
|
|
51
|
-
await tick();
|
|
52
|
-
expect(calls).toHaveLength(2);
|
|
53
|
-
expect(calls[1].values).toBe(3); // not 2
|
|
54
|
-
expect(t.hasPending).toBe(false);
|
|
55
|
-
});
|
|
56
|
-
|
|
57
|
-
it('aborts the in-flight request when a new one starts (after the pending re-entry)', async () => {
|
|
58
|
-
const { fn, calls } = deferredComputeFn();
|
|
59
|
-
const t = createComputeThrottle<number>(fn);
|
|
60
|
-
|
|
61
|
-
t.trigger(1);
|
|
62
|
-
t.trigger(2); // pending
|
|
63
|
-
const firstSignal = calls[0].signal;
|
|
64
|
-
|
|
65
|
-
calls[0].resolve(); // finishes -> re-enters executeCompute(2), which aborts the (already-cleared) prior
|
|
66
|
-
await tick();
|
|
67
|
-
// The second run gets a fresh, non-aborted signal.
|
|
68
|
-
expect(calls).toHaveLength(2);
|
|
69
|
-
expect(calls[1].signal.aborted).toBe(false);
|
|
70
|
-
expect(firstSignal).not.toBe(calls[1].signal);
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
it('cancel() clears the pending slot and aborts the in-flight signal', async () => {
|
|
74
|
-
const { fn, calls } = deferredComputeFn();
|
|
75
|
-
const t = createComputeThrottle<number>(fn);
|
|
76
|
-
|
|
77
|
-
t.trigger(1);
|
|
78
|
-
t.trigger(2); // pending
|
|
79
|
-
expect(t.hasPending).toBe(true);
|
|
80
|
-
|
|
81
|
-
t.cancel();
|
|
82
|
-
expect(t.hasPending).toBe(false);
|
|
83
|
-
expect(calls[0].signal.aborted).toBe(true);
|
|
84
|
-
|
|
85
|
-
// Resolving the aborted call must NOT start the (now-cleared) pending one.
|
|
86
|
-
calls[0].resolve();
|
|
87
|
-
await tick();
|
|
88
|
-
expect(calls).toHaveLength(1);
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
describe('timeout', () => {
|
|
92
|
-
beforeEach(() => vi.useFakeTimers());
|
|
93
|
-
afterEach(() => vi.useRealTimers());
|
|
94
|
-
|
|
95
|
-
it('aborts the in-flight request when the timeout elapses', async () => {
|
|
96
|
-
const { fn, calls } = deferredComputeFn();
|
|
97
|
-
const t = createComputeThrottle<number>(fn, { timeout: 1000 });
|
|
98
|
-
|
|
99
|
-
t.trigger(1);
|
|
100
|
-
expect(calls[0].signal.aborted).toBe(false);
|
|
101
|
-
|
|
102
|
-
vi.advanceTimersByTime(1000);
|
|
103
|
-
expect(calls[0].signal.aborted).toBe(true);
|
|
104
|
-
});
|
|
105
|
-
});
|
|
106
|
-
});
|