@arqlet/engine-client 0.3.0 → 0.5.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 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, and `workerRun(worker)`, the worker as an asynchronous `run`;
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
- const response = await fetch(href, {cache: 'no-store'});
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.0",
3
+ "version": "0.5.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.3.0"
74
+ "@arqlet/contracts": "^0.5.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, GraphNeighbourhood, GraphPatch, GraphTrace, Hidden, NeighbourhoodAnswer, Overview, OverviewRequest, Scene, Snapshot, TraceAnswer} 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. */
@@ -11,13 +11,20 @@ export interface SessionResult {
11
11
  unchanged?: boolean;
12
12
  }
13
13
 
14
+ /** The answer of a read-only request (`trace`, `neighbourhood`): its fields beside `ok: true`, or the error. */
15
+ export type ReadAnswer<T> = ({ok: true} & T) | {ok: false; error: string};
16
+
14
17
  /** Provisional: one graph, its current snapshot, and changes applied in order with revision checks. */
15
18
  export interface Session {
16
- /** The current snapshot, or null before the first import. */
19
+ /**
20
+ * The current snapshot, or null before the first import. With a resident session only its state (`revision`,
21
+ * `layoutVersion`, `collapsedIds`); `exportSnapshot()` gives the whole snapshot.
22
+ */
17
23
  readonly snapshot: Snapshot | null;
18
24
  /**
19
25
  * 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 shows (default: all). `options`: layout options.
26
+ * dropped. `limit`: the most nodes the first view selects (default: all, at most `MAX_VIEW_LIMIT`). `options`: layout
27
+ * options.
21
28
  */
22
29
  import(graph: Graph, init?: {limit?: number; options?: Record<string, unknown>}): Promise<SessionResult>;
23
30
  /** Drops the snapshot; changes still under way resolve as stale. */
@@ -32,14 +39,62 @@ export interface Session {
32
39
  collapse(id: string): Promise<SessionResult>;
33
40
  /** Any other change of the protocol (`direction`, `configure`, `add`, …); snapshot and expected versions are added. */
34
41
  apply(request: Omit<EngineRequest, 'snapshot' | 'expectedRevision' | 'expectedLayoutVersion'> & {op: string}): Promise<SessionResult>;
42
+ /**
43
+ * Provisional (path cut-out): the paths between two nodes of the current snapshot, read only. `visible` names the boxes
44
+ * and routes of the current view that carry them; `distance` the hops of every visible node from the path.
45
+ * `edgeKinds`: the paths follow only edges of these kinds (default: every edge).
46
+ */
47
+ trace(from: string, to: string, init?: {mode?: 'shortest' | 'all'; edgeKinds?: string[]}): Promise<ReadAnswer<TraceAnswer>>;
48
+ /**
49
+ * Provisional: the nodes within `hops` edges (default 1) of a node or of each of a list, read only, answered as
50
+ * `trace` (`nodes`, `edges`, `visible`, `distance`) plus the `hops` of every node; `nodes` can go to `reveal`.
51
+ * `direction`: `out` (what it leads to), `in` (what leads to it) or `both` (default); `edgeKinds`: only these kinds.
52
+ */
53
+ neighbourhood(
54
+ nodeId: string | string[],
55
+ init?: {hops?: number; direction?: 'out' | 'in' | 'both'; edgeKinds?: string[]},
56
+ ): Promise<ReadAnswer<NeighbourhoodAnswer>>;
57
+ /**
58
+ * Provisional: changes the graph without a new import (removals first; a removed node takes what it holds and its
59
+ * edges along); the view keeps its state and is laid out as a toggle lays it out (abstracting views) or again from
60
+ * where it was.
61
+ */
62
+ patch(patch: GraphPatch): Promise<SessionResult>;
63
+ /** Provisional: opens the groups that hold `nodeIds`; with `partial` (default true) only as far as needed. */
64
+ reveal(nodeIds: string[], init?: {partial?: boolean}): Promise<SessionResult>;
65
+ /** Provisional: hides nodes by kind or id (with what they hold) and edges by kind, keeping the place of the rest, or
66
+ * (`compact: true`) laying the view out again without them; `hide` replaces what was hidden before, `{}` shows everything. */
67
+ filter(hide?: Hidden): Promise<SessionResult>;
35
68
  /** The scene of the current snapshot, computed once per snapshot. Throws the engine's error. */
36
69
  scene(): Promise<Scene>;
70
+ /** The whole snapshot: the current one, or with `resident` the one the engine keeps (for saving or hand-over). */
71
+ exportSnapshot(): Promise<Snapshot | null>;
72
+ /** Whether the snapshot stays in the engine. */
73
+ readonly resident: boolean;
74
+ /** Ends a resident session in the engine (frees its snapshot); the session is not usable afterwards. */
75
+ close(): Promise<void>;
76
+ }
77
+
78
+ /** A session whose snapshot stays in the engine (`openSession`); requests leave the snapshot out. Provisional. */
79
+ export interface ResidentSession {
80
+ run(request: EngineRequest): EngineResponse | Promise<EngineResponse>;
81
+ close(): unknown;
37
82
  }
38
83
 
39
84
  /** Creates a session on an engine `run`, synchronous (`loadEngine`) or asynchronous (`workerRun`). */
40
85
  export function createSession(
41
- run: Run | ((request: EngineRequest) => Promise<EngineResponse>),
42
- init?: {onChange?: (snapshot: Snapshot) => void},
86
+ run: (Run | ((request: EngineRequest) => Promise<EngineResponse>)) & {
87
+ openSession?: () => ResidentSession | Promise<ResidentSession>;
88
+ },
89
+ init?: {
90
+ onChange?: (snapshot: Snapshot) => void;
91
+ /**
92
+ * Provisional (ADR 0019): keep the snapshot in the engine. Requests carry only the change and answers bring the
93
+ * scene; `snapshot` is then the session's state (revision, layout version, collapsed containers). `'auto'` (default):
94
+ * where the engine can (`openSession`); `true`: always; `false`: never.
95
+ */
96
+ resident?: boolean | 'auto';
97
+ },
43
98
  ): Session;
44
99
 
45
100
  /**
@@ -49,4 +104,61 @@ export function createSession(
49
104
  export function workerRun(
50
105
  worker: Worker,
51
106
  init?: {onPublication?: (requestId: number, message: unknown) => void},
52
- ): (request: EngineRequest) => Promise<EngineResponse>;
107
+ ): ((request: EngineRequest) => Promise<EngineResponse>) & {openSession(): Promise<ResidentSession>};
108
+
109
+ /**
110
+ * Provisional: a backend as an asynchronous run (`${base}/op`), with sessions kept in the backend
111
+ * (`${base}/session`). `fetchImpl` replaces `fetch`.
112
+ */
113
+ export function httpRun(
114
+ base?: string,
115
+ init?: {fetchImpl?: typeof fetch},
116
+ ): ((request: EngineRequest) => Promise<EngineResponse>) & {openSession(): Promise<ResidentSession>};
117
+
118
+ /**
119
+ * An overview request without `op` and `graph` (`OverviewRequest` in `@arqlet/contracts`): `start` without positions
120
+ * continues from the last overview.
121
+ */
122
+ export type OverviewSessionRequest = Omit<OverviewRequest, 'graph'>;
123
+
124
+ /** The answer to an overview request: `overview` (ids, parent, x, y, r, labels, kinds, …) when `ok`. */
125
+ export interface OverviewAnswer {
126
+ ok: boolean;
127
+ overview?: Overview;
128
+ error?: string;
129
+ /** A new `open` overtook it; nothing was applied. */
130
+ stale?: boolean;
131
+ }
132
+
133
+ /** Provisional: an overview of one graph, laid out again as the host asks; the graph stays in the engine where it can. */
134
+ export interface OverviewSession {
135
+ /** Lays out `graph`; replaces the graph the session had. */
136
+ open(graph: Graph, request?: OverviewSessionRequest): Promise<OverviewAnswer>;
137
+ /** Lays out the graph again; `start` without positions continues from the last overview (same cluster options). */
138
+ layOut(request?: OverviewSessionRequest): Promise<OverviewAnswer>;
139
+ /** Provisional: the paths between two nodes of the overview's graph, read only (`GraphTrace`). */
140
+ trace(from: string, to: string, init?: {mode?: 'shortest' | 'all'; edgeKinds?: string[]}): Promise<ReadAnswer<GraphTrace>>;
141
+ /** Provisional: the nodes within `hops` of a node (or of each of a list) of the overview's graph, read only. */
142
+ neighbourhood(
143
+ nodeId: string | string[],
144
+ init?: {hops?: number; direction?: 'out' | 'in' | 'both'; edgeKinds?: string[]},
145
+ ): Promise<ReadAnswer<GraphNeighbourhood>>;
146
+ /** The last overview, or null. */
147
+ readonly overview: OverviewAnswer['overview'] | null;
148
+ /** Whether the graph stays in the engine. */
149
+ readonly resident: boolean;
150
+ /** Ends the session and frees the graph in the engine. */
151
+ close(): Promise<void>;
152
+ }
153
+
154
+ /** Creates an overview session on an engine `run`; `resident` as for `createSession`. */
155
+ export function createOverviewSession(
156
+ run: (Run | ((request: EngineRequest) => Promise<EngineResponse>)) & {
157
+ openSession?: () => ResidentSession | Promise<ResidentSession>;
158
+ },
159
+ init?: {resident?: boolean | 'auto'},
160
+ ): OverviewSession;
161
+
162
+ /** The most nodes an import selects for its view; the default of `Session.import`'s limit. */
163
+ export const MAX_VIEW_LIMIT: number;
164
+
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
- return request => new Promise(resolve => {
24
+ const post = message => new Promise(resolve => {
25
25
  const requestId = ++next;
26
26
  waiting.set(requestId, resolve);
27
- worker.postMessage({requestId, request});
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;
37
+ }
38
+
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;
29
64
  }
30
65
 
31
- /** Creates a session on `run` (synchronous or asynchronous). `onChange(snapshot)` is called after every applied change. */
32
- export function createSession(run, {onChange} = {}) {
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 run({
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 shows (containers beyond it start collapsed); `options` are layout options (`docs/configuration.md`).
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(() => run({op: 'import', graph, limit, ...(options ? {options} : {})}));
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,179 @@ 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
+ /**
179
+ * Provisional: the nodes within `hops` edges (default 1) of `nodeId` (a node id or a list), read only:
180
+ * `{ok, nodes, edges, hops, visible: {nodes, routes}, distance}` as for `trace`; `nodes` can go to `reveal`.
181
+ * `direction`: `out`, `in` or `both` (default); `edgeKinds`: follow only edges of these kinds.
182
+ */
183
+ async neighbourhood(nodeId, {hops, direction, edgeKinds} = {}) {
184
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
185
+ return call({op: 'neighbourhood', snapshot, ...(Array.isArray(nodeId) ? {nodeIds: nodeId} : {nodeId}),
186
+ ...(hops !== undefined ? {hops} : {}), ...(direction ? {direction} : {}), ...(edgeKinds ? {edgeKinds} : {})});
187
+ },
188
+
189
+ /**
190
+ * Provisional: changes the graph without a new import: `{nodes, edges, removeNodes, removeEdges}` (removals first; a
191
+ * removed node takes what it holds and its edges along). The view keeps its state; with a level of detail,
192
+ * communities or groups it is laid out as a toggle lays it out, otherwise again from where it was.
193
+ */
194
+ patch(patch) { return change({op: 'patch', patch}); },
195
+
196
+ /** Provisional: opens the groups that hold `nodeIds`; with `partial` (default) only as far as needed. */
197
+ reveal(nodeIds, {partial = true} = {}) { return change({op: 'reveal', nodeIds, partial}); },
198
+
199
+ /**
200
+ * Provisional: hides nodes by kind or id (each with what it holds) and edges by kind, keeping the place of the rest;
201
+ * with `compact: true` the view is laid out again without them, so the rest closes up. `hide` replaces what was hidden
202
+ * before; `{}` shows everything again.
203
+ */
204
+ filter(hide = {}) { return change({op: 'filter', hide}); },
205
+
111
206
  /** The scene (drawing) of the current snapshot, computed once per snapshot. */
112
207
  async scene() {
113
208
  const current = snapshot;
114
209
  if (!current) throw Error('Nothing imported yet.');
115
210
  const known = scenes.get(current);
116
211
  if (known) return known;
117
- const answer = await run({op: 'scene', snapshot: current});
212
+ const answer = await call({op: 'scene', snapshot: current});
118
213
  if (!answer.ok) throw Error(answer.error);
119
214
  scenes.set(current, answer.scene);
120
215
  return answer.scene;
121
216
  },
217
+
218
+ /** The whole snapshot: the current one, or with `resident` the one the engine keeps (for saving or hand-over). */
219
+ async exportSnapshot() {
220
+ if (!snapshot) return null;
221
+ if (!resident) return snapshot;
222
+ const answer = await (await opened).run({op: 'export'});
223
+ if (!answer.ok) throw Error(answer.error);
224
+ return answer.snapshot;
225
+ },
226
+
227
+ /** Whether the snapshot stays in the engine (see `createSession`). */
228
+ get resident() { return resident; },
229
+
230
+ /** Ends a resident session in the engine (frees its snapshot). The session object is not usable afterwards. */
231
+ async close() {
232
+ generation++;
233
+ snapshot = null;
234
+ if (resident) await (await opened).close();
235
+ },
236
+ };
237
+ }
238
+
239
+ // The options the overview's clusters depend on; a continuation needs the same ones (as the engine's session checks).
240
+ // Defaults as the engine's (`communities` 120, `satellites` 0); `groups` and `hubs` compared as given.
241
+ const clustersOf = options => JSON.stringify([options?.communities ?? 120, options?.satellites ?? 0, options?.groups ?? null, options?.hubs ?? null]);
242
+
243
+ /**
244
+ * Provisional (ADR 0019 for the overview): an overview of one graph, laid out again as the host asks, with the graph kept
245
+ * in the engine where it can keep a session (`run.openSession`). `open(graph, request)` lays out a graph; `layOut(request)`
246
+ * lays it out again (other options, `radii`, `intent`, `configSet`); a `start` without positions (`{settle}` or `{}`)
247
+ * continues from the last overview. Without a resident session the graph and the last positions stay here and are sent
248
+ * along; the answers are the same. A new `open` overtakes what is still under way (`{ok: false, stale: true}`).
249
+ */
250
+ export function createOverviewSession(run, {resident: wanted = 'auto'} = {}) {
251
+ if (wanted === true && !run.openSession) throw Error('This engine has no resident sessions');
252
+ const resident = wanted === true || (wanted === 'auto' && typeof run.openSession === 'function');
253
+ const opened = resident ? Promise.resolve(run.openSession()) : null;
254
+ // `graph` is kept here only without a resident session; `started`: an `open` was asked for (it may still run).
255
+ let graph = null, started = false, last = null, clusters = null, generation = 0, queue = Promise.resolve();
256
+
257
+ const send = async request => {
258
+ if (resident) {
259
+ // On the graph the engine has, only what moves comes back (`positionsOnly`) while the clusters stay; it is put
260
+ // together with the last overview here, so every answer is a whole overview.
261
+ const asked = !request.graph && last ? {...request, positionsOnly: true} : request;
262
+ const answer = await (await opened).run(asked);
263
+ if (answer.ok && answer.overview?.positionsOnly) {
264
+ const {positionsOnly: _moved, ...moved} = answer.overview;
265
+ return {...answer, overview: {...last, ...moved}};
266
+ }
267
+ return answer;
268
+ }
269
+ const sent = {...request, graph: request.graph ?? graph};
270
+ const start = request.start;
271
+ if (start && start.x === undefined) {
272
+ if (!last || request.graph) return {ok: false, error: 'No overview to continue from: lay out without start first.'};
273
+ if (clustersOf(request.options) !== clusters) return {ok: false, error: 'The clusters changed since the last overview; lay out without start.'};
274
+ sent.start = {...start, x: last.x, y: last.y, r: last.r};
275
+ }
276
+ return run(sent);
277
+ };
278
+ // A read of the overview's graph, after the changes before it: the session's graph, or the one kept here.
279
+ const read = request => {
280
+ const mine = generation;
281
+ const result = queue.then(async () => {
282
+ if (!started) return {ok: false, error: 'No graph yet: open one first.'};
283
+ const answer = resident ? await (await opened).run(request) : await run({...request, graph});
284
+ return mine === generation ? answer : {ok: false, stale: true, error: 'A new graph overtook this read.'};
285
+ });
286
+ queue = result.catch(() => {});
287
+ return result;
288
+ };
289
+ const enqueue = (request, fresh) => {
290
+ if (fresh) generation++;
291
+ const mine = generation;
292
+ const result = queue.then(async () => {
293
+ if (mine !== generation) return {ok: false, stale: true, error: 'A new graph overtook this overview.'};
294
+ const answer = await send(request);
295
+ if (mine !== generation) return {ok: false, stale: true, error: 'A new graph overtook this overview.'};
296
+ if (answer.ok) {
297
+ last = answer.overview;
298
+ clusters = clustersOf(request.options);
299
+ if (fresh && !resident) graph = request.graph;
300
+ }
301
+ return answer;
302
+ });
303
+ queue = result.catch(() => {});
304
+ return result;
305
+ };
306
+
307
+ return {
308
+ /** Lays out `graph` with `request` (`options`, `intent`, `configSet`, `radii`, `threads`). */
309
+ open(newGraph, request = {}) {
310
+ started = true;
311
+ return enqueue({...request, op: 'overview', graph: newGraph}, true);
312
+ },
313
+ /** Lays out the graph again; `start` without positions continues from the last overview. */
314
+ layOut(request = {}) {
315
+ if (!started) return Promise.resolve({ok: false, error: 'No graph yet: open one first.'});
316
+ const {graph: _ignored, ...rest} = request;
317
+ return enqueue({...rest, op: 'overview'}, false);
318
+ },
319
+ /**
320
+ * Provisional: the paths between two nodes of the overview's graph (`overviewTrace`: `{ok, found, reversed, length,
321
+ * nodes, edges}`), read only; `mode` and `edgeKinds` as for `trace`. The viewer's `pathOf` maps them to its discs.
322
+ */
323
+ trace(from, to, {mode, edgeKinds} = {}) {
324
+ return read({op: 'overviewTrace', from, to, ...(mode ? {mode} : {}), ...(edgeKinds ? {edgeKinds} : {})});
325
+ },
326
+ /** Provisional: the nodes within `hops` of a node of the overview's graph (`overviewNeighbourhood`), read only. */
327
+ neighbourhood(nodeId, {hops, direction, edgeKinds} = {}) {
328
+ return read({op: 'overviewNeighbourhood', ...(Array.isArray(nodeId) ? {nodeIds: nodeId} : {nodeId}),
329
+ ...(hops !== undefined ? {hops} : {}), ...(direction ? {direction} : {}), ...(edgeKinds ? {edgeKinds} : {})});
330
+ },
331
+ /** The last overview (`{ids, parent, x, y, r, …}`), or null. */
332
+ get overview() { return last; },
333
+ /** Whether the graph stays in the engine. */
334
+ get resident() { return resident; },
335
+ /** Ends the session (frees the graph in the engine). */
336
+ async close() {
337
+ generation++;
338
+ graph = last = null;
339
+ started = false;
340
+ if (resident) await (await opened).close();
341
+ },
122
342
  };
123
343
  }
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
- /** Runs one request synchronously on the engine. */
15
- export type Run = (request: EngineRequest) => EngineResponse;
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
- const {instance}=await WebAssembly.instantiate(bytes,imports);
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
- return input=>{
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=api.lw_run(ptr,encoded.length);
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
- const engine=fetch(wasmUrl,{cache:'no-store'}).then(r=>{if(!r.ok)throw Error(`Engine not available: ${wasmUrl}`);return r.arrayBuffer();})
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{const run=await engine;running=data.requestId;const result=run(data.request);running=null;self.postMessage({requestId:data.requestId,...result});}
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
  };