@arqlet/engine-client 0.3.0 → 0.4.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/README.md +2 -1
- package/arqlet.wasm +0 -0
- package/engine.js +2 -1
- package/package.json +2 -2
- package/session.d.ts +93 -6
- package/session.js +177 -9
- package/wasm-client.d.ts +9 -4
- package/wasm-client.js +15 -3
- package/worker.js +22 -2
package/README.md
CHANGED
|
@@ -6,7 +6,8 @@ The Arqlet engine as WebAssembly (`arqlet.wasm`, included) and its JavaScript ac
|
|
|
6
6
|
- `wasm-client.js`: `createEngine(bytes, {onPublish})`, the raw binding;
|
|
7
7
|
- `elk.js`: `createElkLayout(run)`, an `elk.layout(graph)`-style call;
|
|
8
8
|
- `session.js`: `createSession(run)`, a layout session that keeps positions across changes (collapse, expand, …)
|
|
9
|
-
with revision checks,
|
|
9
|
+
with revision checks, `createOverviewSession(run)`, a cluster overview whose graph stays in the engine (later layouts
|
|
10
|
+
send only what changed), and `workerRun(worker)` / `httpRun(base)`, a worker or a backend as an asynchronous `run`;
|
|
10
11
|
- `presets.js`: `presetState` and `applyPreset`.
|
|
11
12
|
|
|
12
13
|
Most users want the [`arqlet`](https://www.npmjs.com/package/arqlet) package, which re-exports these.
|
package/arqlet.wasm
CHANGED
|
Binary file
|
package/engine.js
CHANGED
|
@@ -16,7 +16,8 @@ async function readWasm(url) {
|
|
|
16
16
|
const {readFile} = await import(fs);
|
|
17
17
|
return readFile(href);
|
|
18
18
|
}
|
|
19
|
-
|
|
19
|
+
// The browser's HTTP cache applies, as for any asset.
|
|
20
|
+
const response = await fetch(href);
|
|
20
21
|
if (!response.ok) throw Error(`Engine not available: ${href}`);
|
|
21
22
|
return response.arrayBuffer();
|
|
22
23
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arqlet/engine-client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "The Arqlet graph-layout engine as WebAssembly, with a loader, a worker protocol, an ELK-style layout call and preset sequencing. Provisional.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"graph",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
"access": "public"
|
|
72
72
|
},
|
|
73
73
|
"dependencies": {
|
|
74
|
-
"@arqlet/contracts": "^0.
|
|
74
|
+
"@arqlet/contracts": "^0.4.0"
|
|
75
75
|
},
|
|
76
76
|
"scripts": {
|
|
77
77
|
"test": "node --test"
|
package/session.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {Graph, Scene, Snapshot} from '@arqlet/contracts';
|
|
1
|
+
import type {Graph, Hidden, Overview, OverviewRequest, Scene, Snapshot} from '@arqlet/contracts';
|
|
2
2
|
import type {EngineRequest, EngineResponse, Run} from './wasm-client.js';
|
|
3
3
|
|
|
4
4
|
/** An engine answer as the session reports it. `stale`: an import or reset overtook the change, nothing was applied. */
|
|
@@ -13,11 +13,15 @@ export interface SessionResult {
|
|
|
13
13
|
|
|
14
14
|
/** Provisional: one graph, its current snapshot, and changes applied in order with revision checks. */
|
|
15
15
|
export interface Session {
|
|
16
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* The current snapshot, or null before the first import. With a resident session only its state (`revision`,
|
|
18
|
+
* `layoutVersion`, `collapsedIds`); `exportSnapshot()` gives the whole snapshot.
|
|
19
|
+
*/
|
|
17
20
|
readonly snapshot: Snapshot | null;
|
|
18
21
|
/**
|
|
19
22
|
* Lays out `graph` (nodes with `parentId` are containers) and starts the session on it; changes still under way are
|
|
20
|
-
* dropped. `limit`: the most nodes the first view
|
|
23
|
+
* dropped. `limit`: the most nodes the first view selects (default: all, at most `MAX_VIEW_LIMIT`). `options`: layout
|
|
24
|
+
* options.
|
|
21
25
|
*/
|
|
22
26
|
import(graph: Graph, init?: {limit?: number; options?: Record<string, unknown>}): Promise<SessionResult>;
|
|
23
27
|
/** Drops the snapshot; changes still under way resolve as stale. */
|
|
@@ -32,14 +36,47 @@ export interface Session {
|
|
|
32
36
|
collapse(id: string): Promise<SessionResult>;
|
|
33
37
|
/** Any other change of the protocol (`direction`, `configure`, `add`, …); snapshot and expected versions are added. */
|
|
34
38
|
apply(request: Omit<EngineRequest, 'snapshot' | 'expectedRevision' | 'expectedLayoutVersion'> & {op: string}): Promise<SessionResult>;
|
|
39
|
+
/**
|
|
40
|
+
* Provisional (path cut-out): the paths between two nodes of the current snapshot, read only. `visible` names the boxes
|
|
41
|
+
* and routes of the current view that carry them; `distance` the hops of every visible node from the path.
|
|
42
|
+
* `edgeKinds`: the paths follow only edges of these kinds (default: every edge).
|
|
43
|
+
*/
|
|
44
|
+
trace(from: string, to: string, init?: {mode?: 'shortest' | 'all'; edgeKinds?: string[]}): Promise<EngineResponse>;
|
|
45
|
+
/** Provisional: opens the groups that hold `nodeIds`; with `partial` (default true) only as far as needed. */
|
|
46
|
+
reveal(nodeIds: string[], init?: {partial?: boolean}): Promise<SessionResult>;
|
|
47
|
+
/** Provisional: hides nodes by kind or id (with what they hold) and edges by kind, keeping the place of the rest;
|
|
48
|
+
* `hide` replaces what was hidden before, `{}` shows everything. */
|
|
49
|
+
filter(hide?: Hidden): Promise<SessionResult>;
|
|
35
50
|
/** The scene of the current snapshot, computed once per snapshot. Throws the engine's error. */
|
|
36
51
|
scene(): Promise<Scene>;
|
|
52
|
+
/** The whole snapshot: the current one, or with `resident` the one the engine keeps (for saving or hand-over). */
|
|
53
|
+
exportSnapshot(): Promise<Snapshot | null>;
|
|
54
|
+
/** Whether the snapshot stays in the engine. */
|
|
55
|
+
readonly resident: boolean;
|
|
56
|
+
/** Ends a resident session in the engine (frees its snapshot); the session is not usable afterwards. */
|
|
57
|
+
close(): Promise<void>;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A session whose snapshot stays in the engine (`openSession`); requests leave the snapshot out. Provisional. */
|
|
61
|
+
export interface ResidentSession {
|
|
62
|
+
run(request: EngineRequest): EngineResponse | Promise<EngineResponse>;
|
|
63
|
+
close(): unknown;
|
|
37
64
|
}
|
|
38
65
|
|
|
39
66
|
/** Creates a session on an engine `run`, synchronous (`loadEngine`) or asynchronous (`workerRun`). */
|
|
40
67
|
export function createSession(
|
|
41
|
-
run: Run | ((request: EngineRequest) => Promise<EngineResponse>)
|
|
42
|
-
|
|
68
|
+
run: (Run | ((request: EngineRequest) => Promise<EngineResponse>)) & {
|
|
69
|
+
openSession?: () => ResidentSession | Promise<ResidentSession>;
|
|
70
|
+
},
|
|
71
|
+
init?: {
|
|
72
|
+
onChange?: (snapshot: Snapshot) => void;
|
|
73
|
+
/**
|
|
74
|
+
* Provisional (ADR 0019): keep the snapshot in the engine. Requests carry only the change and answers bring the
|
|
75
|
+
* scene; `snapshot` is then the session's state (revision, layout version, collapsed containers). `'auto'` (default):
|
|
76
|
+
* where the engine can (`openSession`); `true`: always; `false`: never.
|
|
77
|
+
*/
|
|
78
|
+
resident?: boolean | 'auto';
|
|
79
|
+
},
|
|
43
80
|
): Session;
|
|
44
81
|
|
|
45
82
|
/**
|
|
@@ -49,4 +86,54 @@ export function createSession(
|
|
|
49
86
|
export function workerRun(
|
|
50
87
|
worker: Worker,
|
|
51
88
|
init?: {onPublication?: (requestId: number, message: unknown) => void},
|
|
52
|
-
): (request: EngineRequest) => Promise<EngineResponse
|
|
89
|
+
): ((request: EngineRequest) => Promise<EngineResponse>) & {openSession(): Promise<ResidentSession>};
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Provisional: a backend as an asynchronous run (`${base}/op`), with sessions kept in the backend
|
|
93
|
+
* (`${base}/session`). `fetchImpl` replaces `fetch`.
|
|
94
|
+
*/
|
|
95
|
+
export function httpRun(
|
|
96
|
+
base?: string,
|
|
97
|
+
init?: {fetchImpl?: typeof fetch},
|
|
98
|
+
): ((request: EngineRequest) => Promise<EngineResponse>) & {openSession(): Promise<ResidentSession>};
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* An overview request without `op` and `graph` (`OverviewRequest` in `@arqlet/contracts`): `start` without positions
|
|
102
|
+
* continues from the last overview.
|
|
103
|
+
*/
|
|
104
|
+
export type OverviewSessionRequest = Omit<OverviewRequest, 'graph'>;
|
|
105
|
+
|
|
106
|
+
/** The answer to an overview request: `overview` (ids, parent, x, y, r, labels, kinds, …) when `ok`. */
|
|
107
|
+
export interface OverviewAnswer {
|
|
108
|
+
ok: boolean;
|
|
109
|
+
overview?: Overview;
|
|
110
|
+
error?: string;
|
|
111
|
+
/** A new `open` overtook it; nothing was applied. */
|
|
112
|
+
stale?: boolean;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Provisional: an overview of one graph, laid out again as the host asks; the graph stays in the engine where it can. */
|
|
116
|
+
export interface OverviewSession {
|
|
117
|
+
/** Lays out `graph`; replaces the graph the session had. */
|
|
118
|
+
open(graph: Graph, request?: OverviewSessionRequest): Promise<OverviewAnswer>;
|
|
119
|
+
/** Lays out the graph again; `start` without positions continues from the last overview (same cluster options). */
|
|
120
|
+
layOut(request?: OverviewSessionRequest): Promise<OverviewAnswer>;
|
|
121
|
+
/** The last overview, or null. */
|
|
122
|
+
readonly overview: OverviewAnswer['overview'] | null;
|
|
123
|
+
/** Whether the graph stays in the engine. */
|
|
124
|
+
readonly resident: boolean;
|
|
125
|
+
/** Ends the session and frees the graph in the engine. */
|
|
126
|
+
close(): Promise<void>;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Creates an overview session on an engine `run`; `resident` as for `createSession`. */
|
|
130
|
+
export function createOverviewSession(
|
|
131
|
+
run: (Run | ((request: EngineRequest) => Promise<EngineResponse>)) & {
|
|
132
|
+
openSession?: () => ResidentSession | Promise<ResidentSession>;
|
|
133
|
+
},
|
|
134
|
+
init?: {resident?: boolean | 'auto'},
|
|
135
|
+
): OverviewSession;
|
|
136
|
+
|
|
137
|
+
/** The most nodes an import selects for its view; the default of `Session.import`'s limit. */
|
|
138
|
+
export const MAX_VIEW_LIMIT: number;
|
|
139
|
+
|
package/session.js
CHANGED
|
@@ -21,19 +21,76 @@ export function workerRun(worker, {onPublication} = {}) {
|
|
|
21
21
|
const {requestId, ...response} = data;
|
|
22
22
|
pending(response);
|
|
23
23
|
});
|
|
24
|
-
|
|
24
|
+
const post = message => new Promise(resolve => {
|
|
25
25
|
const requestId = ++next;
|
|
26
26
|
waiting.set(requestId, resolve);
|
|
27
|
-
worker.postMessage({requestId,
|
|
27
|
+
worker.postMessage({requestId, ...message});
|
|
28
28
|
});
|
|
29
|
+
const run = request => post({request});
|
|
30
|
+
// Provisional (ADR 0019, step 3): a session kept in the worker; its requests leave the snapshot out.
|
|
31
|
+
run.openSession = async () => {
|
|
32
|
+
const opened = await post({session: 'open'});
|
|
33
|
+
if (!opened.ok) throw Error(opened.error);
|
|
34
|
+
return {run: request => post({session: opened.session, request}), close: () => post({session: opened.session, close: true})};
|
|
35
|
+
};
|
|
36
|
+
return run;
|
|
29
37
|
}
|
|
30
38
|
|
|
31
|
-
/**
|
|
32
|
-
export
|
|
39
|
+
/** The most nodes an import selects for its view (the engine's `MAX_VIEW_LIMIT`); the default of `import`'s limit. */
|
|
40
|
+
export const MAX_VIEW_LIMIT = 10000;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Provisional (ADR 0019): a backend as an asynchronous `run`. Requests go to `${base}/op` (one native computation each);
|
|
44
|
+
* `openSession()` keeps a session in the backend (`${base}/session`), whose requests leave the snapshot out. `fetchImpl`
|
|
45
|
+
* replaces `fetch` (tests, other transports). The playground's backend (`apps/playground/server.py`) answers both.
|
|
46
|
+
*/
|
|
47
|
+
export function httpRun(base = '/api', {fetchImpl = globalThis.fetch} = {}) {
|
|
48
|
+
const post = async (path, body) => {
|
|
49
|
+
const response = await fetchImpl(`${base}/${path}`, {
|
|
50
|
+
method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body),
|
|
51
|
+
});
|
|
52
|
+
try { return await response.json(); } catch { return {ok: false, error: `HTTP ${response.status}`}; }
|
|
53
|
+
};
|
|
54
|
+
const run = request => post('op', request);
|
|
55
|
+
run.openSession = async () => {
|
|
56
|
+
const opened = await post('session', {session: 'open'});
|
|
57
|
+
if (!opened.ok) throw Error(opened.error);
|
|
58
|
+
return {
|
|
59
|
+
run: request => post('session', {session: opened.session, request}),
|
|
60
|
+
close: () => post('session', {session: opened.session, close: true}),
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
return run;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Creates a session on `run` (synchronous or asynchronous). `onChange(snapshot)` is called after every applied change.
|
|
68
|
+
*
|
|
69
|
+
* Where the engine can keep a session (`run.openSession`, which `loadEngine` and `workerRun` provide), the snapshot
|
|
70
|
+
* stays in the engine (ADR 0019): requests carry only the change, answers bring the scene, and `snapshot` is the
|
|
71
|
+
* session's state (`revision`, `layoutVersion`, `collapsedIds`); `exportSnapshot()` gives the whole snapshot. `resident`
|
|
72
|
+
* chooses: `'auto'` (default) where the engine can, `true` always (an error without it), `false` never (every request
|
|
73
|
+
* sends the snapshot, as before 0.4).
|
|
74
|
+
*/
|
|
75
|
+
export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
|
|
33
76
|
let snapshot = null;
|
|
34
77
|
let generation = 0;
|
|
35
78
|
let queue = Promise.resolve();
|
|
36
79
|
const scenes = new WeakMap();
|
|
80
|
+
if (wanted === true && !run.openSession) throw Error('This engine has no resident sessions');
|
|
81
|
+
const resident = wanted === true || (wanted === 'auto' && typeof run.openSession === 'function');
|
|
82
|
+
const opened = resident ? Promise.resolve(run.openSession()) : null;
|
|
83
|
+
// The engine call: with a resident session, the request goes to it and its answer is turned into the shape of an
|
|
84
|
+
// answer with a snapshot (the state), its scene remembered for that state.
|
|
85
|
+
const call = async request => {
|
|
86
|
+
if (!resident) return run(request);
|
|
87
|
+
const {snapshot: _sent, ...rest} = request;
|
|
88
|
+
const answer = await (await opened).run(rest);
|
|
89
|
+
if (!answer.ok || answer.revision === undefined) return answer;
|
|
90
|
+
const state = {revision: answer.revision, layoutVersion: answer.layoutVersion, collapsedIds: answer.collapsedIds};
|
|
91
|
+
if (answer.scene) scenes.set(state, answer.scene);
|
|
92
|
+
return {ok: true, snapshot: state};
|
|
93
|
+
};
|
|
37
94
|
|
|
38
95
|
// Runs `step` after every change before it; its answer counts only if no import or reset came in between.
|
|
39
96
|
const enqueue = step => {
|
|
@@ -55,7 +112,7 @@ export function createSession(run, {onChange} = {}) {
|
|
|
55
112
|
// A change to the current snapshot; called inside a queued step.
|
|
56
113
|
const send = request => {
|
|
57
114
|
if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
|
|
58
|
-
return
|
|
115
|
+
return call({
|
|
59
116
|
...request,
|
|
60
117
|
snapshot,
|
|
61
118
|
expectedRevision: snapshot.revision,
|
|
@@ -76,12 +133,12 @@ export function createSession(run, {onChange} = {}) {
|
|
|
76
133
|
|
|
77
134
|
/**
|
|
78
135
|
* Lays out `graph` (nodes with `parentId` are containers) and starts the session on it. `limit` is the most nodes
|
|
79
|
-
* the first view
|
|
136
|
+
* the first view selects (default: all, at most `MAX_VIEW_LIMIT`; containers beyond it start collapsed); `options` are layout options (`docs/configuration.md`).
|
|
80
137
|
* Any change still under way is dropped.
|
|
81
138
|
*/
|
|
82
|
-
import(graph, {limit = graph.nodes.length, options} = {}) {
|
|
139
|
+
import(graph, {limit = Math.min(graph.nodes.length, MAX_VIEW_LIMIT), options} = {}) {
|
|
83
140
|
generation++;
|
|
84
|
-
return enqueue(() =>
|
|
141
|
+
return enqueue(() => call({op: 'import', graph, limit, ...(options ? {options} : {})}));
|
|
85
142
|
},
|
|
86
143
|
|
|
87
144
|
/** Drops the snapshot; changes still under way resolve as stale. */
|
|
@@ -108,16 +165,127 @@ export function createSession(run, {onChange} = {}) {
|
|
|
108
165
|
*/
|
|
109
166
|
apply(request) { return change(request); },
|
|
110
167
|
|
|
168
|
+
/**
|
|
169
|
+
* Provisional (path cut-out): the paths from `from` to `to` in the current snapshot (read only, nothing changes):
|
|
170
|
+
* `{ok, found, reversed, length, nodes, edges, visible: {nodes, routes}, distance}`. `mode`: `shortest` (default) or
|
|
171
|
+
* `all`. `edgeKinds`: follow only edges of these kinds (default: every edge).
|
|
172
|
+
*/
|
|
173
|
+
async trace(from, to, {mode = 'shortest', edgeKinds} = {}) {
|
|
174
|
+
if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
|
|
175
|
+
return call({op: 'trace', snapshot, from, to, mode, ...(edgeKinds ? {edgeKinds} : {})});
|
|
176
|
+
},
|
|
177
|
+
|
|
178
|
+
/** Provisional: opens the groups that hold `nodeIds`; with `partial` (default) only as far as needed. */
|
|
179
|
+
reveal(nodeIds, {partial = true} = {}) { return change({op: 'reveal', nodeIds, partial}); },
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Provisional: hides nodes by kind or id (each with what it holds) and edges by kind, keeping the place of the rest.
|
|
183
|
+
* `hide` replaces what was hidden before; `{}` shows everything again.
|
|
184
|
+
*/
|
|
185
|
+
filter(hide = {}) { return change({op: 'filter', hide}); },
|
|
186
|
+
|
|
111
187
|
/** The scene (drawing) of the current snapshot, computed once per snapshot. */
|
|
112
188
|
async scene() {
|
|
113
189
|
const current = snapshot;
|
|
114
190
|
if (!current) throw Error('Nothing imported yet.');
|
|
115
191
|
const known = scenes.get(current);
|
|
116
192
|
if (known) return known;
|
|
117
|
-
const answer = await
|
|
193
|
+
const answer = await call({op: 'scene', snapshot: current});
|
|
118
194
|
if (!answer.ok) throw Error(answer.error);
|
|
119
195
|
scenes.set(current, answer.scene);
|
|
120
196
|
return answer.scene;
|
|
121
197
|
},
|
|
198
|
+
|
|
199
|
+
/** The whole snapshot: the current one, or with `resident` the one the engine keeps (for saving or hand-over). */
|
|
200
|
+
async exportSnapshot() {
|
|
201
|
+
if (!snapshot) return null;
|
|
202
|
+
if (!resident) return snapshot;
|
|
203
|
+
const answer = await (await opened).run({op: 'export'});
|
|
204
|
+
if (!answer.ok) throw Error(answer.error);
|
|
205
|
+
return answer.snapshot;
|
|
206
|
+
},
|
|
207
|
+
|
|
208
|
+
/** Whether the snapshot stays in the engine (see `createSession`). */
|
|
209
|
+
get resident() { return resident; },
|
|
210
|
+
|
|
211
|
+
/** Ends a resident session in the engine (frees its snapshot). The session object is not usable afterwards. */
|
|
212
|
+
async close() {
|
|
213
|
+
generation++;
|
|
214
|
+
snapshot = null;
|
|
215
|
+
if (resident) await (await opened).close();
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// The options the overview's clusters depend on; a continuation needs the same ones (as the engine's session checks).
|
|
221
|
+
// Defaults as the engine's (`communities` 120, `satellites` 0); `groups` compared as given.
|
|
222
|
+
const clustersOf = options => JSON.stringify([options?.communities ?? 120, options?.satellites ?? 0, options?.groups ?? null]);
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Provisional (ADR 0019 for the overview): an overview of one graph, laid out again as the host asks, with the graph kept
|
|
226
|
+
* in the engine where it can keep a session (`run.openSession`). `open(graph, request)` lays out a graph; `layOut(request)`
|
|
227
|
+
* lays it out again (other options, `radii`, `intent`, `configSet`); a `start` without positions (`{settle}` or `{}`)
|
|
228
|
+
* continues from the last overview. Without a resident session the graph and the last positions stay here and are sent
|
|
229
|
+
* along; the answers are the same. A new `open` overtakes what is still under way (`{ok: false, stale: true}`).
|
|
230
|
+
*/
|
|
231
|
+
export function createOverviewSession(run, {resident: wanted = 'auto'} = {}) {
|
|
232
|
+
if (wanted === true && !run.openSession) throw Error('This engine has no resident sessions');
|
|
233
|
+
const resident = wanted === true || (wanted === 'auto' && typeof run.openSession === 'function');
|
|
234
|
+
const opened = resident ? Promise.resolve(run.openSession()) : null;
|
|
235
|
+
// `graph` is kept here only without a resident session; `started`: an `open` was asked for (it may still run).
|
|
236
|
+
let graph = null, started = false, last = null, clusters = null, generation = 0, queue = Promise.resolve();
|
|
237
|
+
|
|
238
|
+
const send = async request => {
|
|
239
|
+
if (resident) return (await opened).run(request);
|
|
240
|
+
const sent = {...request, graph: request.graph ?? graph};
|
|
241
|
+
const start = request.start;
|
|
242
|
+
if (start && start.x === undefined) {
|
|
243
|
+
if (!last || request.graph) return {ok: false, error: 'No overview to continue from: lay out without start first.'};
|
|
244
|
+
if (clustersOf(request.options) !== clusters) return {ok: false, error: 'The clusters changed since the last overview; lay out without start.'};
|
|
245
|
+
sent.start = {...start, x: last.x, y: last.y, r: last.r};
|
|
246
|
+
}
|
|
247
|
+
return run(sent);
|
|
248
|
+
};
|
|
249
|
+
const enqueue = (request, fresh) => {
|
|
250
|
+
if (fresh) generation++;
|
|
251
|
+
const mine = generation;
|
|
252
|
+
const result = queue.then(async () => {
|
|
253
|
+
if (mine !== generation) return {ok: false, stale: true, error: 'A new graph overtook this overview.'};
|
|
254
|
+
const answer = await send(request);
|
|
255
|
+
if (mine !== generation) return {ok: false, stale: true, error: 'A new graph overtook this overview.'};
|
|
256
|
+
if (answer.ok) {
|
|
257
|
+
last = answer.overview;
|
|
258
|
+
clusters = clustersOf(request.options);
|
|
259
|
+
if (fresh && !resident) graph = request.graph;
|
|
260
|
+
}
|
|
261
|
+
return answer;
|
|
262
|
+
});
|
|
263
|
+
queue = result.catch(() => {});
|
|
264
|
+
return result;
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
return {
|
|
268
|
+
/** Lays out `graph` with `request` (`options`, `intent`, `configSet`, `radii`, `threads`). */
|
|
269
|
+
open(newGraph, request = {}) {
|
|
270
|
+
started = true;
|
|
271
|
+
return enqueue({...request, op: 'overview', graph: newGraph}, true);
|
|
272
|
+
},
|
|
273
|
+
/** Lays out the graph again; `start` without positions continues from the last overview. */
|
|
274
|
+
layOut(request = {}) {
|
|
275
|
+
if (!started) return Promise.resolve({ok: false, error: 'No graph yet: open one first.'});
|
|
276
|
+
const {graph: _ignored, ...rest} = request;
|
|
277
|
+
return enqueue({...rest, op: 'overview'}, false);
|
|
278
|
+
},
|
|
279
|
+
/** The last overview (`{ids, parent, x, y, r, …}`), or null. */
|
|
280
|
+
get overview() { return last; },
|
|
281
|
+
/** Whether the graph stays in the engine. */
|
|
282
|
+
get resident() { return resident; },
|
|
283
|
+
/** Ends the session (frees the graph in the engine). */
|
|
284
|
+
async close() {
|
|
285
|
+
generation++;
|
|
286
|
+
graph = last = null;
|
|
287
|
+
started = false;
|
|
288
|
+
if (resident) await (await opened).close();
|
|
289
|
+
},
|
|
122
290
|
};
|
|
123
291
|
}
|
package/wasm-client.d.ts
CHANGED
|
@@ -11,13 +11,18 @@ export type EngineResponse =
|
|
|
11
11
|
| ({ok: true} & {[field: string]: any})
|
|
12
12
|
| {ok: false; error: string; [field: string]: unknown};
|
|
13
13
|
|
|
14
|
-
/**
|
|
15
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Runs one request synchronously on the engine. `openSession` (provisional, ADR 0019 step 3) opens a session whose
|
|
16
|
+
* snapshot stays in the engine: its requests leave the snapshot out, and its answers bring the scene.
|
|
17
|
+
*/
|
|
18
|
+
export type Run = ((request: EngineRequest) => EngineResponse) & {
|
|
19
|
+
openSession?: () => {run(request: EngineRequest): EngineResponse; close(): void};
|
|
20
|
+
};
|
|
16
21
|
|
|
17
22
|
export interface CreateEngineOptions {
|
|
18
23
|
/** Receives each progressive publication (JSON text) while the call that produced it is still running. */
|
|
19
24
|
onPublish?: (message: string) => void;
|
|
20
25
|
}
|
|
21
26
|
|
|
22
|
-
/** Instantiates the WASM engine from its bytes. */
|
|
23
|
-
export function createEngine(bytes: BufferSource, options?: CreateEngineOptions): Promise<Run>;
|
|
27
|
+
/** Instantiates the WASM engine from its bytes, or from a module the host compiled already. */
|
|
28
|
+
export function createEngine(bytes: BufferSource | WebAssembly.Module, options?: CreateEngineOptions): Promise<Run>;
|
package/wasm-client.js
CHANGED
|
@@ -10,17 +10,29 @@ export async function createEngine(bytes,{onPublish}={}) {
|
|
|
10
10
|
onPublish(decoder.decode(new Uint8Array(api.memory.buffer,ptr,len)));
|
|
11
11
|
},
|
|
12
12
|
}};
|
|
13
|
-
|
|
13
|
+
// The bytes of the module, or a module the host compiled already (then it is not compiled again).
|
|
14
|
+
const result=await WebAssembly.instantiate(bytes,imports);
|
|
15
|
+
const instance=result instanceof WebAssembly.Instance?result:result.instance;
|
|
14
16
|
api=instance.exports;
|
|
15
|
-
|
|
17
|
+
// Copies a request into the module, runs `call` on it, and reads the answer (both buffers freed afterwards).
|
|
18
|
+
const exchange=(input,call)=>{
|
|
16
19
|
const encoded=new TextEncoder().encode(JSON.stringify(input));
|
|
17
20
|
const ptr=api.lw_alloc(encoded.length);
|
|
18
21
|
let out=0,len=0;
|
|
19
22
|
try {
|
|
20
23
|
new Uint8Array(api.memory.buffer,ptr,encoded.length).set(encoded);
|
|
21
|
-
const result=
|
|
24
|
+
const result=call(ptr,encoded.length);
|
|
22
25
|
out=Number(result & 0xffffffffn);len=Number(result >> 32n);
|
|
23
26
|
return JSON.parse(decoder.decode(new Uint8Array(api.memory.buffer,out,len)));
|
|
24
27
|
} finally {api.lw_free(ptr,encoded.length);if(out)api.lw_free(out,len);}
|
|
25
28
|
};
|
|
29
|
+
const run=input=>exchange(input,(ptr,len)=>api.lw_run(ptr,len));
|
|
30
|
+
// Provisional (ADR 0019, step 3): a session whose snapshot stays in the module; requests leave the snapshot out.
|
|
31
|
+
if(api.lw_session_open){
|
|
32
|
+
run.openSession=()=>{
|
|
33
|
+
const id=api.lw_session_open();
|
|
34
|
+
return {run:input=>exchange(input,(ptr,len)=>api.lw_session_run(id,ptr,len)),close:()=>api.lw_session_close(id)};
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
return run;
|
|
26
38
|
}
|
package/worker.js
CHANGED
|
@@ -3,13 +3,33 @@ import {createEngine} from './wasm-client.js';
|
|
|
3
3
|
const wasmUrl=new URL(self.location.href).searchParams.get('wasm');
|
|
4
4
|
// The request being run. Publications are forwarded while its call is still executing; the final reply follows it.
|
|
5
5
|
let running=null;
|
|
6
|
-
|
|
6
|
+
// The browser's HTTP cache applies: an unchanged engine is not downloaded again for every worker.
|
|
7
|
+
const engine=fetch(wasmUrl).then(r=>{if(!r.ok)throw Error(`Engine not available: ${wasmUrl}`);return r.arrayBuffer();})
|
|
7
8
|
.then(bytes=>createEngine(bytes,{onPublish:text=>{
|
|
8
9
|
if(running===null) return;
|
|
9
10
|
// emittedAt and bytes let the page split the latency into computation, transfer and display.
|
|
10
11
|
self.postMessage({requestId:running,publication:JSON.parse(text).publication,emittedAt:Date.now(),bytes:text.length});
|
|
11
12
|
}}));
|
|
13
|
+
// Provisional (ADR 0019, step 3): sessions kept in this worker, by handle. `{requestId, session: 'open'}` answers
|
|
14
|
+
// `{session: id}`; `{requestId, session: id, request}` runs a request in it; `{requestId, session: id, close: true}` ends it.
|
|
15
|
+
const sessions=new Map();
|
|
16
|
+
let nextSession=0;
|
|
12
17
|
self.onmessage=async({data})=>{
|
|
13
|
-
try{
|
|
18
|
+
try{
|
|
19
|
+
const run=await engine;
|
|
20
|
+
if(data.session==='open'){
|
|
21
|
+
if(!run.openSession)throw Error('This engine has no sessions');
|
|
22
|
+
const id=++nextSession;sessions.set(id,run.openSession());
|
|
23
|
+
self.postMessage({requestId:data.requestId,ok:true,session:id});return;
|
|
24
|
+
}
|
|
25
|
+
if(data.session!==undefined){
|
|
26
|
+
const session=sessions.get(data.session);
|
|
27
|
+
if(!session)throw Error('Unknown session');
|
|
28
|
+
if(data.close){session.close();sessions.delete(data.session);self.postMessage({requestId:data.requestId,ok:true});return;}
|
|
29
|
+
running=data.requestId;const result=session.run(data.request);running=null;
|
|
30
|
+
self.postMessage({requestId:data.requestId,...result});return;
|
|
31
|
+
}
|
|
32
|
+
running=data.requestId;const result=run(data.request);running=null;self.postMessage({requestId:data.requestId,...result});
|
|
33
|
+
}
|
|
14
34
|
catch(e){running=null;self.postMessage({requestId:data.requestId,ok:false,error:e.message});}
|
|
15
35
|
};
|