@gmitch215/folio 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +482 -2
- package/dist/bake.d.ts +174 -0
- package/dist/bake.js +701 -0
- package/dist/browser-worker.d.ts +9 -0
- package/dist/browser-worker.js +37 -0
- package/dist/browser.d.ts +68 -0
- package/dist/browser.js +274 -0
- package/dist/compiler.d.ts +43 -0
- package/dist/compiler.js +505 -0
- package/dist/coordinator.d.ts +27 -0
- package/dist/coordinator.js +189 -0
- package/dist/extract.d.ts +71 -0
- package/dist/extract.js +1176 -0
- package/dist/frames.d.ts +19 -0
- package/dist/frames.js +111 -0
- package/dist/guards.d.ts +12 -0
- package/dist/guards.js +202 -0
- package/dist/host.d.ts +60 -0
- package/dist/host.js +374 -0
- package/dist/import-order.d.ts +2 -0
- package/dist/import-order.js +114 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/managed.d.ts +86 -0
- package/dist/managed.js +398 -0
- package/dist/memory.d.ts +10 -0
- package/dist/memory.js +89 -0
- package/dist/node.d.ts +124 -0
- package/dist/node.js +831 -0
- package/dist/pages.d.ts +109 -0
- package/dist/pages.js +339 -0
- package/dist/remote.d.ts +86 -0
- package/dist/remote.js +255 -0
- package/dist/tasks.d.ts +107 -0
- package/dist/tasks.js +317 -0
- package/dist/transaction.d.ts +23 -0
- package/dist/transaction.js +93 -0
- package/dist/values.d.ts +3 -0
- package/dist/values.js +25 -0
- package/dist/worker.d.ts +1 -0
- package/dist/worker.js +86 -0
- package/package.json +126 -5
package/dist/remote.js
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/** Portable transport values. References and executable objects do not cross this boundary. */
|
|
2
|
+
export function encodeValue(value, depth = 0) {
|
|
3
|
+
if (depth > 64)
|
|
4
|
+
throw new RangeError('transport value is too deeply nested');
|
|
5
|
+
if (value === undefined)
|
|
6
|
+
return ['u'];
|
|
7
|
+
if (typeof value === 'number') {
|
|
8
|
+
const view = new DataView(new ArrayBuffer(8));
|
|
9
|
+
view.setFloat64(0, value);
|
|
10
|
+
return ['n', view.getBigUint64(0).toString(16).padStart(16, '0')];
|
|
11
|
+
}
|
|
12
|
+
if (typeof value === 'bigint')
|
|
13
|
+
return ['i', value.toString()];
|
|
14
|
+
if (value === null || typeof value === 'boolean' || typeof value === 'string')
|
|
15
|
+
return ['v', value];
|
|
16
|
+
if (Array.isArray(value))
|
|
17
|
+
return ['a', value.map((item) => encodeValue(item, depth + 1))];
|
|
18
|
+
if (value &&
|
|
19
|
+
typeof value === 'object' &&
|
|
20
|
+
(Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null))
|
|
21
|
+
return [
|
|
22
|
+
'o',
|
|
23
|
+
Object.entries(value).map(([key, item]) => [key, encodeValue(item, depth + 1)])
|
|
24
|
+
];
|
|
25
|
+
throw new TypeError('transport accepts values, not object identities or executable objects');
|
|
26
|
+
}
|
|
27
|
+
/** Inverse of `encodeValue`; rejects anything that is not a transport value. */
|
|
28
|
+
export function decodeValue(value, depth = 0) {
|
|
29
|
+
if (depth > 64 || !Array.isArray(value))
|
|
30
|
+
throw new TypeError('invalid transport value');
|
|
31
|
+
const [kind, payload] = value;
|
|
32
|
+
if (kind === 'u' && value.length === 1)
|
|
33
|
+
return undefined;
|
|
34
|
+
if (kind === 'v' &&
|
|
35
|
+
value.length === 2 &&
|
|
36
|
+
(payload === null || ['boolean', 'string'].includes(typeof payload)))
|
|
37
|
+
return payload;
|
|
38
|
+
if (kind === 'n' &&
|
|
39
|
+
value.length === 2 &&
|
|
40
|
+
typeof payload === 'string' &&
|
|
41
|
+
/^[0-9a-f]{16}$/.test(payload)) {
|
|
42
|
+
const view = new DataView(new ArrayBuffer(8));
|
|
43
|
+
view.setBigUint64(0, BigInt(`0x${payload}`));
|
|
44
|
+
return view.getFloat64(0);
|
|
45
|
+
}
|
|
46
|
+
if (kind === 'i' &&
|
|
47
|
+
value.length === 2 &&
|
|
48
|
+
typeof payload === 'string' &&
|
|
49
|
+
/^(0|-?[1-9][0-9]*)$/.test(payload) &&
|
|
50
|
+
payload.length <= 4096)
|
|
51
|
+
return BigInt(payload);
|
|
52
|
+
if (kind === 'a' && value.length === 2 && Array.isArray(payload))
|
|
53
|
+
return payload.map((item) => decodeValue(item, depth + 1));
|
|
54
|
+
if (kind === 'o' && value.length === 2 && Array.isArray(payload)) {
|
|
55
|
+
const result = {};
|
|
56
|
+
for (const pair of payload) {
|
|
57
|
+
if (!Array.isArray(pair) ||
|
|
58
|
+
pair.length !== 2 ||
|
|
59
|
+
typeof pair[0] !== 'string' ||
|
|
60
|
+
Object.hasOwn(result, pair[0]))
|
|
61
|
+
throw new TypeError('invalid transport record');
|
|
62
|
+
Object.defineProperty(result, pair[0], {
|
|
63
|
+
value: decodeValue(pair[1], depth + 1),
|
|
64
|
+
enumerable: true,
|
|
65
|
+
writable: true,
|
|
66
|
+
configurable: true
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
throw new TypeError('invalid transport value');
|
|
72
|
+
}
|
|
73
|
+
/** Lowercase hex text for a byte payload. */
|
|
74
|
+
export function encodeBytes(bytes) {
|
|
75
|
+
let result = '';
|
|
76
|
+
for (const value of bytes)
|
|
77
|
+
result += value.toString(16).padStart(2, '0');
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
/** Inverse of `encodeBytes`; rejects odd lengths and non-hex text. */
|
|
81
|
+
export function decodeBytes(value) {
|
|
82
|
+
if (typeof value !== 'string' || value.length % 2 || !/^[0-9a-f]*$/.test(value))
|
|
83
|
+
throw new TypeError('invalid byte payload');
|
|
84
|
+
return Uint8Array.from({ length: value.length / 2 }, (_, index) => parseInt(value.slice(index * 2, index * 2 + 2), 16));
|
|
85
|
+
}
|
|
86
|
+
/** An error response from the host. */
|
|
87
|
+
export class RemoteError extends Error {
|
|
88
|
+
/** HTTP status of the response. */
|
|
89
|
+
status;
|
|
90
|
+
/** The host's error category. */
|
|
91
|
+
kind;
|
|
92
|
+
constructor(message, status, kind) {
|
|
93
|
+
super(message);
|
|
94
|
+
this.status = status;
|
|
95
|
+
this.kind = kind;
|
|
96
|
+
this.name = 'RemoteError';
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** A failed response can be retried explicitly with the exact original request. */
|
|
100
|
+
export class UncertainDelivery extends Error {
|
|
101
|
+
/** Sequence number of the request whose response was lost. */
|
|
102
|
+
sequence;
|
|
103
|
+
constructor(sequence, options) {
|
|
104
|
+
super('delivery is uncertain; retryPending() retrieves the result without replaying effects', options);
|
|
105
|
+
this.sequence = sequence;
|
|
106
|
+
this.name = 'UncertainDelivery';
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
async function readBounded(response, maximum) {
|
|
110
|
+
const reader = response.body?.getReader();
|
|
111
|
+
if (!reader)
|
|
112
|
+
return '';
|
|
113
|
+
const chunks = [];
|
|
114
|
+
let size = 0;
|
|
115
|
+
try {
|
|
116
|
+
for (;;) {
|
|
117
|
+
const { done, value } = await reader.read();
|
|
118
|
+
if (done)
|
|
119
|
+
break;
|
|
120
|
+
size += value.byteLength;
|
|
121
|
+
if (size > maximum)
|
|
122
|
+
throw new RangeError('response exceeds transport byte limit');
|
|
123
|
+
chunks.push(value);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
await reader.cancel().catch(() => { });
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
reader.releaseLock();
|
|
132
|
+
}
|
|
133
|
+
const bytes = new Uint8Array(size);
|
|
134
|
+
let offset = 0;
|
|
135
|
+
for (const chunk of chunks) {
|
|
136
|
+
bytes.set(chunk, offset);
|
|
137
|
+
offset += chunk.length;
|
|
138
|
+
}
|
|
139
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
140
|
+
}
|
|
141
|
+
/** Connects to a registered artifact. Compilation and shared memory stay at the host. */
|
|
142
|
+
export class RemoteFolio {
|
|
143
|
+
/** Session details from the host: its capability, worker thread ids and sharing capabilities. */
|
|
144
|
+
info;
|
|
145
|
+
#url;
|
|
146
|
+
#request;
|
|
147
|
+
#headers;
|
|
148
|
+
#maximum;
|
|
149
|
+
#sequence = 0;
|
|
150
|
+
#pending;
|
|
151
|
+
#busy = false;
|
|
152
|
+
#closed = false;
|
|
153
|
+
constructor(url, info, options) {
|
|
154
|
+
this.info = info;
|
|
155
|
+
this.#url = new URL(encodeURIComponent(info.capability), `${url.href.replace(/\/$/, '')}/`);
|
|
156
|
+
this.#request = options.fetch ?? fetch;
|
|
157
|
+
this.#headers = new Headers(options.headers);
|
|
158
|
+
this.#headers.set('content-type', 'application/json');
|
|
159
|
+
this.#maximum = options.maximumResponseBytes ?? 2 * 1024 * 1024;
|
|
160
|
+
}
|
|
161
|
+
/** Opens a session on a registered artifact; `workers` asks for a group width within host limits. */
|
|
162
|
+
static async open(url, artifact, options = {}) {
|
|
163
|
+
const headers = new Headers(options.headers);
|
|
164
|
+
headers.set('content-type', 'application/json');
|
|
165
|
+
const response = await (options.fetch ?? fetch)(new Request(url, {
|
|
166
|
+
method: 'POST',
|
|
167
|
+
headers,
|
|
168
|
+
body: JSON.stringify(encodeValue({ artifact, workers: options.workers }))
|
|
169
|
+
}));
|
|
170
|
+
const value = decodeValue(JSON.parse(await readBounded(response, options.maximumResponseBytes ?? 2 * 1024 * 1024)));
|
|
171
|
+
if (!response.ok)
|
|
172
|
+
throw new RemoteError(value.message, response.status, value.kind);
|
|
173
|
+
return new RemoteFolio(new URL(url), value, options);
|
|
174
|
+
}
|
|
175
|
+
async #send() {
|
|
176
|
+
const pending = this.#pending;
|
|
177
|
+
try {
|
|
178
|
+
const response = await this.#request(new Request(this.#url, {
|
|
179
|
+
method: 'POST',
|
|
180
|
+
headers: this.#headers,
|
|
181
|
+
body: pending.body
|
|
182
|
+
}));
|
|
183
|
+
const value = decodeValue(JSON.parse(await readBounded(response, this.#maximum)));
|
|
184
|
+
const accepted = response.headers.get('x-folio-sequence') === String(this.#sequence);
|
|
185
|
+
if (response.ok && !accepted)
|
|
186
|
+
throw new Error('host omitted the accepted sequence');
|
|
187
|
+
this.#pending = undefined;
|
|
188
|
+
if (accepted)
|
|
189
|
+
this.#sequence++;
|
|
190
|
+
if (pending.close && accepted)
|
|
191
|
+
this.#closed = true;
|
|
192
|
+
if (!response.ok)
|
|
193
|
+
throw new RemoteError(value.message, response.status, value.kind);
|
|
194
|
+
return value;
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
if (!this.#pending)
|
|
198
|
+
throw error;
|
|
199
|
+
throw new UncertainDelivery(this.#sequence, { cause: error });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
async #command(command) {
|
|
203
|
+
if (this.#closed)
|
|
204
|
+
throw new Error('remote folio is closed');
|
|
205
|
+
if (this.#busy)
|
|
206
|
+
throw new Error('remote session already has an active request');
|
|
207
|
+
if (this.#pending)
|
|
208
|
+
throw new Error('retry the uncertain request before another operation');
|
|
209
|
+
this.#busy = true;
|
|
210
|
+
try {
|
|
211
|
+
this.#pending = {
|
|
212
|
+
body: JSON.stringify(encodeValue({ sequence: this.#sequence, ...command })),
|
|
213
|
+
close: command.operation === 'close'
|
|
214
|
+
};
|
|
215
|
+
return await this.#send();
|
|
216
|
+
}
|
|
217
|
+
finally {
|
|
218
|
+
this.#busy = false;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/** Resends the exact uncertain request; the host returns its cached result without repeating effects. */
|
|
222
|
+
async retryPending() {
|
|
223
|
+
if (this.#busy || !this.#pending)
|
|
224
|
+
throw new Error('no uncertain request is available');
|
|
225
|
+
this.#busy = true;
|
|
226
|
+
try {
|
|
227
|
+
return await this.#send();
|
|
228
|
+
}
|
|
229
|
+
finally {
|
|
230
|
+
this.#busy = false;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
/** Runs one allowlisted export in order on the host. */
|
|
234
|
+
async run(entry, args = [], options = {}) {
|
|
235
|
+
return this.#command({ operation: 'run', entry, args, options });
|
|
236
|
+
}
|
|
237
|
+
/** Reads bytes from the host's memory, bounded by the host's read limit. */
|
|
238
|
+
async read(offset, length, memory) {
|
|
239
|
+
return decodeBytes(await this.#command({ operation: 'read', offset, length, memory }));
|
|
240
|
+
}
|
|
241
|
+
/** Writes bytes into the host's memory, bounded by the host's write limit. */
|
|
242
|
+
async write(offset, bytes, memory) {
|
|
243
|
+
await this.#command({ operation: 'write', offset, bytes: encodeBytes(bytes), memory });
|
|
244
|
+
}
|
|
245
|
+
/** Ends the session; the host joins its workers before releasing the slot. */
|
|
246
|
+
async close() {
|
|
247
|
+
if (this.#closed)
|
|
248
|
+
return;
|
|
249
|
+
await this.#command({ operation: 'close' });
|
|
250
|
+
}
|
|
251
|
+
/** `await using` support; equivalent to `close()`. */
|
|
252
|
+
[Symbol.asyncDispose]() {
|
|
253
|
+
return this.close();
|
|
254
|
+
}
|
|
255
|
+
}
|
package/dist/tasks.d.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { type MessagePort } from 'node:worker_threads';
|
|
2
|
+
/** Task input and output are copied between threads. Strings and bytes are both accepted. */
|
|
3
|
+
export type TaskInput = string | Uint8Array;
|
|
4
|
+
/** The end of a pool link that a worker passes to `serveTasks`. */
|
|
5
|
+
export interface TaskLink {
|
|
6
|
+
port: MessagePort;
|
|
7
|
+
signal: SharedArrayBuffer;
|
|
8
|
+
}
|
|
9
|
+
/** Timing and size evidence for one joined task. Timestamps are epoch milliseconds. */
|
|
10
|
+
export interface TaskRecord {
|
|
11
|
+
id: string;
|
|
12
|
+
worker: number;
|
|
13
|
+
name: string;
|
|
14
|
+
submitMs: number;
|
|
15
|
+
startMs: number;
|
|
16
|
+
endMs: number;
|
|
17
|
+
waitMs: number;
|
|
18
|
+
cpuMs?: number;
|
|
19
|
+
inputBytes: number;
|
|
20
|
+
outputBytes: number;
|
|
21
|
+
}
|
|
22
|
+
/** Options for `TaskPool`. */
|
|
23
|
+
export interface TaskPoolOptions {
|
|
24
|
+
/**
|
|
25
|
+
* Differential check. Every `every`th task runs again with `run` in the joining thread and the
|
|
26
|
+
* two outputs are compared byte for byte. A difference means the task depended on state the
|
|
27
|
+
* serial program would have shared, and `join` throws `TaskConflictError`.
|
|
28
|
+
*/
|
|
29
|
+
audit?: {
|
|
30
|
+
run(name: string, input: TaskInput): TaskInput;
|
|
31
|
+
every?: number;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** A task function threw in its worker. */
|
|
35
|
+
export declare class TaskError extends Error {
|
|
36
|
+
readonly task: string;
|
|
37
|
+
readonly worker: number;
|
|
38
|
+
constructor(task: string, worker: number, detail: string);
|
|
39
|
+
}
|
|
40
|
+
/** An audited task returned different bytes in its worker than in the joining thread. */
|
|
41
|
+
export declare class TaskConflictError extends Error {
|
|
42
|
+
readonly task: string;
|
|
43
|
+
readonly worker: number;
|
|
44
|
+
readonly offset: number;
|
|
45
|
+
constructor(task: string, worker: number, offset: number);
|
|
46
|
+
}
|
|
47
|
+
/** The joined output of a task, with decoded accessors. */
|
|
48
|
+
export declare class TaskResult {
|
|
49
|
+
readonly bytes: Uint8Array;
|
|
50
|
+
readonly record: TaskRecord;
|
|
51
|
+
constructor(bytes: Uint8Array, record: TaskRecord);
|
|
52
|
+
text(): string;
|
|
53
|
+
json<T = unknown>(): T;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Creates `count` linked channel pairs. Pass the `owner` ends to `new TaskPool` in the thread that
|
|
57
|
+
* submits tasks, which may be a worker, and the `server` ends to `serveTasks` in the workers.
|
|
58
|
+
* Each port must be listed in the `transferList` of the thread it travels to.
|
|
59
|
+
*/
|
|
60
|
+
export declare function createTaskLinks(count: number): {
|
|
61
|
+
owner: TaskLink[];
|
|
62
|
+
server: TaskLink[];
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Runs named functions in private contexts on other threads. The owner submits a task with a name
|
|
66
|
+
* and a copied input, keeps working, and joins the copied output. Nothing is shared between the
|
|
67
|
+
* owner and a worker, so tasks must not depend on each other's state; `audit` checks that.
|
|
68
|
+
* `new TaskPool(count)` creates the channels. The caller starts each worker, hands it
|
|
69
|
+
* `link(index)` and calls `serveTasks` there. `new TaskPool(links)` attaches to owner ends made
|
|
70
|
+
* by `createTaskLinks`, for an owner that runs in a worker.
|
|
71
|
+
*/
|
|
72
|
+
export declare class TaskPool {
|
|
73
|
+
#private;
|
|
74
|
+
constructor(source: number | TaskLink[], options?: TaskPoolOptions);
|
|
75
|
+
/** Number of worker links. */
|
|
76
|
+
get size(): number;
|
|
77
|
+
/** Tasks are spread round robin over the first `width` workers. */
|
|
78
|
+
get width(): number;
|
|
79
|
+
set width(value: number);
|
|
80
|
+
/** The worker end of link `index`. List its port in the worker's `transferList`. */
|
|
81
|
+
link(index: number): TaskLink;
|
|
82
|
+
/** Starts a task and returns a handle for `join`. */
|
|
83
|
+
submit(name: string, input?: TaskInput): string;
|
|
84
|
+
/** Starts a task whose input is a JSON value. */
|
|
85
|
+
submitJson(name: string, value: unknown): string;
|
|
86
|
+
/** Blocks the calling thread until the task finishes. Use it where the caller cannot yield. */
|
|
87
|
+
join(handle: string): TaskResult;
|
|
88
|
+
/** Waits for the task without blocking the event loop. */
|
|
89
|
+
joinAsync(handle: string): Promise<TaskResult>;
|
|
90
|
+
/** Submits every job, then joins them in submission order. */
|
|
91
|
+
run(jobs: [name: string, input?: TaskInput][]): Promise<TaskResult[]>;
|
|
92
|
+
/** Blocking form of `run`. */
|
|
93
|
+
runSync(jobs: [name: string, input?: TaskInput][]): TaskResult[];
|
|
94
|
+
/** Returns the records of tasks joined since the last call and clears them. */
|
|
95
|
+
drain(): TaskRecord[];
|
|
96
|
+
/** Closes the channels. Tasks that were not joined are dropped. */
|
|
97
|
+
close(): void;
|
|
98
|
+
}
|
|
99
|
+
/** Options for `serveTasks`. */
|
|
100
|
+
export interface ServeOptions {
|
|
101
|
+
/** Reads this thread's CPU time in milliseconds. Defaults to `process.threadCpuUsage`. */
|
|
102
|
+
cpu?: () => number | undefined;
|
|
103
|
+
}
|
|
104
|
+
/** Runs on the worker side. Tasks on one link run one at a time, in arrival order. */
|
|
105
|
+
export declare function serveTasks(link: TaskLink, run: (name: string, input: TaskInput) => TaskInput | Promise<TaskInput>, options?: ServeOptions): void;
|
|
106
|
+
/** The largest number of tasks whose intervals overlap at one instant. */
|
|
107
|
+
export declare function peakConcurrency(records: Pick<TaskRecord, 'startMs' | 'endMs'>[]): number;
|
package/dist/tasks.js
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
import { MessageChannel, receiveMessageOnPort } from 'node:worker_threads';
|
|
2
|
+
/** A task function threw in its worker. */
|
|
3
|
+
export class TaskError extends Error {
|
|
4
|
+
task;
|
|
5
|
+
worker;
|
|
6
|
+
constructor(task, worker, detail) {
|
|
7
|
+
super(`task ${task} failed on worker ${worker}: ${detail}`);
|
|
8
|
+
this.name = 'TaskError';
|
|
9
|
+
this.task = task;
|
|
10
|
+
this.worker = worker;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** An audited task returned different bytes in its worker than in the joining thread. */
|
|
14
|
+
export class TaskConflictError extends Error {
|
|
15
|
+
task;
|
|
16
|
+
worker;
|
|
17
|
+
offset;
|
|
18
|
+
constructor(task, worker, offset) {
|
|
19
|
+
super(`task ${task} on worker ${worker} differs from the serial result at byte ${offset}`);
|
|
20
|
+
this.name = 'TaskConflictError';
|
|
21
|
+
this.task = task;
|
|
22
|
+
this.worker = worker;
|
|
23
|
+
this.offset = offset;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** The joined output of a task, with decoded accessors. */
|
|
27
|
+
export class TaskResult {
|
|
28
|
+
bytes;
|
|
29
|
+
record;
|
|
30
|
+
constructor(bytes, record) {
|
|
31
|
+
this.bytes = bytes;
|
|
32
|
+
this.record = record;
|
|
33
|
+
}
|
|
34
|
+
text() {
|
|
35
|
+
return decoder.decode(this.bytes);
|
|
36
|
+
}
|
|
37
|
+
json() {
|
|
38
|
+
return JSON.parse(this.text());
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const encoder = new TextEncoder();
|
|
42
|
+
const decoder = new TextDecoder();
|
|
43
|
+
const now = () => performance.timeOrigin + performance.now();
|
|
44
|
+
function toBytes(value) {
|
|
45
|
+
return typeof value === 'string' ? encoder.encode(value) : value;
|
|
46
|
+
}
|
|
47
|
+
function threadCpuMs() {
|
|
48
|
+
const usage = process.threadCpuUsage?.();
|
|
49
|
+
return usage ? (usage.user + usage.system) / 1000 : undefined;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Creates `count` linked channel pairs. Pass the `owner` ends to `new TaskPool` in the thread that
|
|
53
|
+
* submits tasks, which may be a worker, and the `server` ends to `serveTasks` in the workers.
|
|
54
|
+
* Each port must be listed in the `transferList` of the thread it travels to.
|
|
55
|
+
*/
|
|
56
|
+
export function createTaskLinks(count) {
|
|
57
|
+
if (!Number.isSafeInteger(count) || count < 1)
|
|
58
|
+
throw new RangeError('invalid worker count');
|
|
59
|
+
const owner = [];
|
|
60
|
+
const server = [];
|
|
61
|
+
for (let index = 0; index < count; index++) {
|
|
62
|
+
const channel = new MessageChannel();
|
|
63
|
+
const signal = new SharedArrayBuffer(4);
|
|
64
|
+
owner.push({ port: channel.port1, signal });
|
|
65
|
+
server.push({ port: channel.port2, signal });
|
|
66
|
+
}
|
|
67
|
+
return { owner, server };
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Runs named functions in private contexts on other threads. The owner submits a task with a name
|
|
71
|
+
* and a copied input, keeps working, and joins the copied output. Nothing is shared between the
|
|
72
|
+
* owner and a worker, so tasks must not depend on each other's state; `audit` checks that.
|
|
73
|
+
* `new TaskPool(count)` creates the channels. The caller starts each worker, hands it
|
|
74
|
+
* `link(index)` and calls `serveTasks` there. `new TaskPool(links)` attaches to owner ends made
|
|
75
|
+
* by `createTaskLinks`, for an owner that runs in a worker.
|
|
76
|
+
*/
|
|
77
|
+
export class TaskPool {
|
|
78
|
+
#owner;
|
|
79
|
+
#server;
|
|
80
|
+
#counters;
|
|
81
|
+
#replies = new Map();
|
|
82
|
+
#pending = new Map();
|
|
83
|
+
#audit;
|
|
84
|
+
#log = [];
|
|
85
|
+
#width;
|
|
86
|
+
#next = 0;
|
|
87
|
+
#seq = 0;
|
|
88
|
+
#closed = false;
|
|
89
|
+
constructor(source, options = {}) {
|
|
90
|
+
const every = options.audit?.every ?? 1;
|
|
91
|
+
if (!Number.isSafeInteger(every) || every < 1)
|
|
92
|
+
throw new RangeError('invalid audit interval');
|
|
93
|
+
this.#audit = options.audit && { run: options.audit.run, every };
|
|
94
|
+
if (typeof source === 'number') {
|
|
95
|
+
const links = createTaskLinks(source);
|
|
96
|
+
this.#owner = links.owner;
|
|
97
|
+
this.#server = links.server;
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
if (!source.length)
|
|
101
|
+
throw new RangeError('invalid worker count');
|
|
102
|
+
this.#owner = source;
|
|
103
|
+
}
|
|
104
|
+
this.#counters = this.#owner.map((link) => new Int32Array(link.signal));
|
|
105
|
+
this.#width = this.#owner.length;
|
|
106
|
+
}
|
|
107
|
+
/** Number of worker links. */
|
|
108
|
+
get size() {
|
|
109
|
+
return this.#owner.length;
|
|
110
|
+
}
|
|
111
|
+
/** Tasks are spread round robin over the first `width` workers. */
|
|
112
|
+
get width() {
|
|
113
|
+
return this.#width;
|
|
114
|
+
}
|
|
115
|
+
set width(value) {
|
|
116
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > this.size)
|
|
117
|
+
throw new RangeError('invalid width');
|
|
118
|
+
this.#width = value;
|
|
119
|
+
this.#next = 0;
|
|
120
|
+
}
|
|
121
|
+
/** The worker end of link `index`. List its port in the worker's `transferList`. */
|
|
122
|
+
link(index) {
|
|
123
|
+
if (!this.#server)
|
|
124
|
+
throw new Error('this pool was attached to existing links');
|
|
125
|
+
const link = this.#server[index];
|
|
126
|
+
if (!link)
|
|
127
|
+
throw new RangeError('invalid worker index');
|
|
128
|
+
return link;
|
|
129
|
+
}
|
|
130
|
+
/** Starts a task and returns a handle for `join`. */
|
|
131
|
+
submit(name, input = '') {
|
|
132
|
+
if (this.#closed)
|
|
133
|
+
throw new Error('task pool is closed');
|
|
134
|
+
const worker = this.#next++ % this.#width;
|
|
135
|
+
const seq = this.#seq++;
|
|
136
|
+
const id = `${worker}:${seq}`;
|
|
137
|
+
const submitMs = now();
|
|
138
|
+
const request = { id, name, input, submitMs };
|
|
139
|
+
this.#owner[worker].port.postMessage(request);
|
|
140
|
+
const audited = this.#audit && seq % this.#audit.every === 0 ? input : undefined;
|
|
141
|
+
this.#pending.set(id, {
|
|
142
|
+
id,
|
|
143
|
+
worker,
|
|
144
|
+
name,
|
|
145
|
+
submitMs,
|
|
146
|
+
inputBytes: toBytes(input).length,
|
|
147
|
+
audited
|
|
148
|
+
});
|
|
149
|
+
return id;
|
|
150
|
+
}
|
|
151
|
+
/** Starts a task whose input is a JSON value. */
|
|
152
|
+
submitJson(name, value) {
|
|
153
|
+
return this.submit(name, JSON.stringify(value));
|
|
154
|
+
}
|
|
155
|
+
/** Blocks the calling thread until the task finishes. Use it where the caller cannot yield. */
|
|
156
|
+
join(handle) {
|
|
157
|
+
const pending = this.#claim(handle);
|
|
158
|
+
const counter = this.#counters[pending.worker];
|
|
159
|
+
let waitMs = 0;
|
|
160
|
+
let reply = this.#reply(pending);
|
|
161
|
+
while (!reply) {
|
|
162
|
+
const seen = Atomics.load(counter, 0);
|
|
163
|
+
reply = this.#reply(pending);
|
|
164
|
+
if (reply)
|
|
165
|
+
break;
|
|
166
|
+
const start = now();
|
|
167
|
+
Atomics.wait(counter, 0, seen);
|
|
168
|
+
waitMs += now() - start;
|
|
169
|
+
}
|
|
170
|
+
return this.#finish(pending, reply, waitMs);
|
|
171
|
+
}
|
|
172
|
+
/** Waits for the task without blocking the event loop. */
|
|
173
|
+
async joinAsync(handle) {
|
|
174
|
+
const pending = this.#claim(handle);
|
|
175
|
+
const counter = this.#counters[pending.worker];
|
|
176
|
+
const atomics = Atomics;
|
|
177
|
+
let waitMs = 0;
|
|
178
|
+
let reply = this.#reply(pending);
|
|
179
|
+
while (!reply) {
|
|
180
|
+
const seen = Atomics.load(counter, 0);
|
|
181
|
+
reply = this.#reply(pending);
|
|
182
|
+
if (reply)
|
|
183
|
+
break;
|
|
184
|
+
const start = now();
|
|
185
|
+
const wait = atomics.waitAsync(counter, 0, seen);
|
|
186
|
+
if (wait.async)
|
|
187
|
+
await wait.value;
|
|
188
|
+
waitMs += now() - start;
|
|
189
|
+
}
|
|
190
|
+
return this.#finish(pending, reply, waitMs);
|
|
191
|
+
}
|
|
192
|
+
/** Submits every job, then joins them in submission order. */
|
|
193
|
+
async run(jobs) {
|
|
194
|
+
const handles = jobs.map(([name, input]) => this.submit(name, input));
|
|
195
|
+
const results = [];
|
|
196
|
+
for (const handle of handles)
|
|
197
|
+
results.push(await this.joinAsync(handle));
|
|
198
|
+
return results;
|
|
199
|
+
}
|
|
200
|
+
/** Blocking form of `run`. */
|
|
201
|
+
runSync(jobs) {
|
|
202
|
+
const handles = jobs.map(([name, input]) => this.submit(name, input));
|
|
203
|
+
return handles.map((handle) => this.join(handle));
|
|
204
|
+
}
|
|
205
|
+
/** Returns the records of tasks joined since the last call and clears them. */
|
|
206
|
+
drain() {
|
|
207
|
+
const out = this.#log;
|
|
208
|
+
this.#log = [];
|
|
209
|
+
return out;
|
|
210
|
+
}
|
|
211
|
+
/** Closes the channels. Tasks that were not joined are dropped. */
|
|
212
|
+
close() {
|
|
213
|
+
this.#closed = true;
|
|
214
|
+
this.#replies.clear();
|
|
215
|
+
this.#pending.clear();
|
|
216
|
+
for (const link of this.#owner)
|
|
217
|
+
link.port.close();
|
|
218
|
+
}
|
|
219
|
+
#claim(handle) {
|
|
220
|
+
const pending = this.#pending.get(handle);
|
|
221
|
+
if (!pending)
|
|
222
|
+
throw new Error(`unknown or already joined task ${handle}`);
|
|
223
|
+
this.#pending.delete(handle);
|
|
224
|
+
return pending;
|
|
225
|
+
}
|
|
226
|
+
#reply(pending) {
|
|
227
|
+
const port = this.#owner[pending.worker].port;
|
|
228
|
+
let message;
|
|
229
|
+
while ((message = receiveMessageOnPort(port))) {
|
|
230
|
+
const reply = message.message;
|
|
231
|
+
this.#replies.set(reply.id, reply);
|
|
232
|
+
}
|
|
233
|
+
const reply = this.#replies.get(pending.id);
|
|
234
|
+
if (reply)
|
|
235
|
+
this.#replies.delete(pending.id);
|
|
236
|
+
return reply;
|
|
237
|
+
}
|
|
238
|
+
#finish(pending, reply, waitMs) {
|
|
239
|
+
if (!reply.ok)
|
|
240
|
+
throw new TaskError(pending.name, pending.worker, decoder.decode(reply.output));
|
|
241
|
+
if (pending.audited !== undefined && this.#audit) {
|
|
242
|
+
const local = toBytes(this.#audit.run(pending.name, pending.audited));
|
|
243
|
+
const offset = firstDifference(local, reply.output);
|
|
244
|
+
if (offset >= 0)
|
|
245
|
+
throw new TaskConflictError(pending.name, pending.worker, offset);
|
|
246
|
+
}
|
|
247
|
+
const record = {
|
|
248
|
+
id: pending.id,
|
|
249
|
+
worker: pending.worker,
|
|
250
|
+
name: pending.name,
|
|
251
|
+
submitMs: pending.submitMs,
|
|
252
|
+
startMs: reply.startMs,
|
|
253
|
+
endMs: reply.endMs,
|
|
254
|
+
waitMs,
|
|
255
|
+
cpuMs: reply.cpuMs,
|
|
256
|
+
inputBytes: pending.inputBytes,
|
|
257
|
+
outputBytes: reply.output.length
|
|
258
|
+
};
|
|
259
|
+
this.#log.push(record);
|
|
260
|
+
return new TaskResult(reply.output, record);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function firstDifference(a, b) {
|
|
264
|
+
const shared = Math.min(a.length, b.length);
|
|
265
|
+
for (let index = 0; index < shared; index++)
|
|
266
|
+
if (a[index] !== b[index])
|
|
267
|
+
return index;
|
|
268
|
+
return a.length === b.length ? -1 : shared;
|
|
269
|
+
}
|
|
270
|
+
/** Runs on the worker side. Tasks on one link run one at a time, in arrival order. */
|
|
271
|
+
export function serveTasks(link, run, options = {}) {
|
|
272
|
+
const counter = new Int32Array(link.signal);
|
|
273
|
+
const cpu = options.cpu ?? threadCpuMs;
|
|
274
|
+
let chain = Promise.resolve();
|
|
275
|
+
link.port.on('message', (request) => {
|
|
276
|
+
chain = chain.then(() => execute(request));
|
|
277
|
+
});
|
|
278
|
+
async function execute(request) {
|
|
279
|
+
const cpuStart = cpu();
|
|
280
|
+
const startMs = now();
|
|
281
|
+
let ok = true;
|
|
282
|
+
let output;
|
|
283
|
+
try {
|
|
284
|
+
output = toBytes(await run(request.name, request.input));
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
ok = false;
|
|
288
|
+
output = encoder.encode(String(error?.stack ?? error));
|
|
289
|
+
}
|
|
290
|
+
const cpuEnd = cpu();
|
|
291
|
+
const reply = {
|
|
292
|
+
id: request.id,
|
|
293
|
+
ok,
|
|
294
|
+
output,
|
|
295
|
+
startMs,
|
|
296
|
+
endMs: now(),
|
|
297
|
+
cpuMs: cpuStart === undefined || cpuEnd === undefined ? undefined : cpuEnd - cpuStart
|
|
298
|
+
};
|
|
299
|
+
link.port.postMessage(reply);
|
|
300
|
+
Atomics.add(counter, 0, 1);
|
|
301
|
+
Atomics.notify(counter, 0);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/** The largest number of tasks whose intervals overlap at one instant. */
|
|
305
|
+
export function peakConcurrency(records) {
|
|
306
|
+
const edges = [];
|
|
307
|
+
for (const record of records)
|
|
308
|
+
edges.push([record.startMs, 1], [record.endMs, -1]);
|
|
309
|
+
edges.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
|
|
310
|
+
let open = 0;
|
|
311
|
+
let peak = 0;
|
|
312
|
+
for (const [, delta] of edges) {
|
|
313
|
+
open += delta;
|
|
314
|
+
peak = Math.max(peak, open);
|
|
315
|
+
}
|
|
316
|
+
return peak;
|
|
317
|
+
}
|