@shotkit/shotium 0.1.0 → 0.2.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/src/lib/worker.ts DELETED
@@ -1,220 +0,0 @@
1
- import {spawn} from 'node:child_process';
2
- import type {ChildProcess, StdioOptions} from 'node:child_process';
3
- import {EventEmitter} from 'node:events';
4
-
5
- import {FrameReader, encodeRequest} from './protocol.js';
6
- import type {WireRequest} from './request.js';
7
-
8
- export interface WorkerOptions {
9
- id: number;
10
- binary: string;
11
- args?: string[];
12
- }
13
-
14
- // The header frame the worker answers with, followed by the image frame.
15
- export interface ResponseHeader {
16
- ok: boolean;
17
- error?: string;
18
- bytes?: number;
19
- path?: string;
20
- }
21
-
22
- export interface WorkerResult {
23
- header: ResponseHeader;
24
- image: Buffer|null;
25
- }
26
-
27
- interface Pending {
28
- resolve: (result: WorkerResult) => void;
29
- reject: (error: Error) => void;
30
- }
31
-
32
- // One shotium.exe --serve process.
33
- //
34
- // Exactly one request is in flight at a time, and that is not a simplification:
35
- // blink is a process-wide singleton bound to the worker's main thread, so a
36
- // second request could not be rendered concurrently even if the protocol
37
- // allowed it. Concurrency is the pool's job, and it gets it by running more
38
- // processes.
39
- //
40
- // Events:
41
- // ready the process has started
42
- // exit {code, signal} it is gone, for any reason
43
- // crash {code, signal} it is gone while it owed an answer
44
- // stderr {line} a diagnostic line, useful when a render is wrong
45
- class Worker extends EventEmitter {
46
- readonly id: number;
47
- // How many requests this process has answered, either way. The pool reads
48
- // it to tell a worker that was working and then died from one that never
49
- // came up at all.
50
- served = 0;
51
-
52
- private readonly binary: string;
53
- private readonly args: string[];
54
- private process: ChildProcess|null = null;
55
- private pending: Pending|null = null;
56
- private stopping = false;
57
- private reader = new FrameReader();
58
- private header: ResponseHeader|null = null;
59
- private stderr = '';
60
-
61
- constructor(options: WorkerOptions) {
62
- super();
63
- this.id = options.id;
64
- this.binary = options.binary;
65
- this.args = options.args || [];
66
- this.start();
67
- }
68
-
69
- get busy(): boolean {
70
- return this.pending !== null;
71
- }
72
-
73
- get alive(): boolean {
74
- return this.process !== null && this.process.exitCode === null &&
75
- !this.stopping;
76
- }
77
-
78
- private start(): void {
79
- const stdio: StdioOptions = ['pipe', 'pipe', 'pipe'];
80
- const child = spawn(this.binary, ['--serve', ...this.args], {
81
- stdio,
82
- windowsHide: true,
83
- // Detached, which on Windows means DETACHED_PROCESS: no console, and so
84
- // no conhost.exe beside every worker. Four of those cost 40 MB of
85
- // working set for a console nothing writes to -- the worker's output is
86
- // three pipes.
87
- //
88
- // It does not outlive its supervisor despite the name: the worker exits
89
- // when its stdin closes, and stdin closes when this process dies.
90
- detached: true,
91
- });
92
- this.process = child;
93
-
94
- child.stdout?.on('data', (chunk: Buffer) => this.onStdout(chunk));
95
- child.stderr?.on('data', (chunk: Buffer) => this.onStderr(chunk));
96
- child.on('error', (error) => this.onGone(null, null, error));
97
- child.on('exit', (code, signal) => this.onGone(code, signal, null));
98
-
99
- // The process is up as soon as spawn resolves the executable; there is no
100
- // handshake in the protocol, and adding one would only move the failure --
101
- // a binary that cannot start fails the first request just as visibly.
102
- this.emit('ready');
103
- }
104
-
105
- private onStdout(chunk: Buffer): void {
106
- this.reader.push(chunk);
107
- for (;;) {
108
- const frame = this.reader.next();
109
- if (frame === null) {
110
- return;
111
- }
112
- if (this.header === null) {
113
- // Frame one of two: the JSON header.
114
- try {
115
- this.header = JSON.parse(frame.toString('utf8')) as ResponseHeader;
116
- } catch {
117
- this.fail(new Error(
118
- `shotium: worker ${this.id} sent a header that is not JSON`));
119
- return;
120
- }
121
- continue;
122
- }
123
- // Frame two: the image, empty when the header reported a failure or when
124
- // the worker was asked to write the file itself.
125
- const header = this.header;
126
- this.header = null;
127
- this.settle(header, frame);
128
- }
129
- }
130
-
131
- private onStderr(chunk: Buffer): void {
132
- this.stderr += chunk.toString('utf8');
133
- const lines = this.stderr.split(/\r?\n/);
134
- this.stderr = lines.pop() ?? '';
135
- for (const line of lines) {
136
- if (line.length > 0) {
137
- this.emit('stderr', {worker: this.id, line});
138
- }
139
- }
140
- }
141
-
142
- private onGone(
143
- code: number|null, signal: NodeJS.Signals|null,
144
- error: Error|null): void {
145
- const wasOwed = this.pending !== null;
146
- this.process = null;
147
- if (wasOwed) {
148
- // A worker that dies mid-request is indistinguishable from one that never
149
- // answered, which is the point: the retry path does not have to tell a
150
- // crash from a hang.
151
- this.fail(
152
- error ||
153
- new Error(`shotium: worker ${this.id} exited (code ${code}, signal ${
154
- signal}) with a request in flight`));
155
- this.emit('crash', {worker: this.id, code, signal});
156
- } else if (error) {
157
- this.emit('error', error);
158
- }
159
- this.emit('exit', {worker: this.id, code, signal});
160
- }
161
-
162
- private settle(header: ResponseHeader, payload: Buffer): void {
163
- const pending = this.pending;
164
- if (!pending) {
165
- return;
166
- }
167
- this.pending = null;
168
- this.served += 1;
169
- if (header.ok) {
170
- pending.resolve({header, image: header.path ? null : payload});
171
- } else {
172
- pending.reject(new Error(header.error || 'shotium: request failed'));
173
- }
174
- }
175
-
176
- private fail(error: Error): void {
177
- const pending = this.pending;
178
- if (!pending) {
179
- return;
180
- }
181
- this.pending = null;
182
- pending.reject(error);
183
- }
184
-
185
- // Sends one request. Rejects if the worker dies before answering; there is no
186
- // timeout here, because the deadline belongs to whoever owns the retry
187
- // policy.
188
- send(request: WireRequest): Promise<WorkerResult> {
189
- if (this.pending) {
190
- return Promise.reject(
191
- new Error(`shotium: worker ${this.id} is already busy`));
192
- }
193
- if (!this.alive) {
194
- return Promise.reject(new Error(`shotium: worker ${this.id} is not up`));
195
- }
196
- return new Promise<WorkerResult>((resolve, reject) => {
197
- this.pending = {resolve, reject};
198
- this.process?.stdin?.write(encodeRequest(request), (error) => {
199
- if (error) {
200
- this.fail(error);
201
- }
202
- });
203
- });
204
- }
205
-
206
- // Closing stdin is the shutdown message: the worker sees the frame stream end
207
- // on a frame boundary and exits 0. kill() is for when it has stopped
208
- // listening.
209
- stop(): void {
210
- this.stopping = true;
211
- this.process?.stdin?.end();
212
- }
213
-
214
- kill(): void {
215
- this.stopping = true;
216
- this.process?.kill();
217
- }
218
- }
219
-
220
- export {Worker};
package/src/native.ts DELETED
@@ -1,234 +0,0 @@
1
- import fs from 'node:fs';
2
- import {createRequire} from 'node:module';
3
- import path from 'node:path';
4
- import {fileURLToPath} from 'node:url';
5
-
6
- import * as platformPackage from './lib/platform.js';
7
- import {toRequest} from './lib/request.js';
8
- import type {
9
- NativeStartOptions,
10
- PurgeOptions,
11
- ScreenshotOptions,
12
- } from './types.js';
13
-
14
- export type {
15
- NativeStartOptions,
16
- PurgeOptions,
17
- ScreenshotOptions,
18
- } from './types.js';
19
-
20
- // A .node addon is a CommonJS artefact: there is no ESM loader for one.
21
- const require = createRequire(import.meta.url);
22
-
23
- // ESM has no __dirname. This is the same thing, from the module's own URL.
24
- const HERE = path.dirname(fileURLToPath(import.meta.url));
25
-
26
- // The engine handle the addon hands back. It is opaque on purpose: everything
27
- // that can be done with it is a call on the binding below.
28
- type Engine = unknown;
29
-
30
- // What native/binding.cc exports. See shot/shot_api.h for the C ABI under it.
31
- interface NativeBinding {
32
- create(optionsJson: string): Engine;
33
- destroy(engine: Engine): void;
34
- purge(engine: Engine, releaseWorkingSet: boolean): void;
35
- capture(engine: Engine, requestJson: string): Promise<Buffer>;
36
- }
37
-
38
- // shot in this process, instead of in workers beside it.
39
- //
40
- // The difference from `runtime` is not the API, which is the same
41
- // screenshot(options), and not the request format, which is byte for byte the
42
- // same JSON. It is where blink is:
43
- //
44
- // runtime N worker processes, one screenshot each at a time, a crash is a
45
- // retry, memory is N copies of an engine
46
- // native one engine in this process, one screenshot at a time ever, a
47
- // crash takes the program with it, memory is one copy
48
- //
49
- // One at a time is not a limitation of this file. Blink is a process-wide
50
- // singleton -- it is initialised once and there is no path to a second one --
51
- // so an in-process engine is one renderer no matter how it is driven, and
52
- // worker_threads do not change that because they share the process. A caller
53
- // who wants four screenshots at once wants four processes, which is what the
54
- // pool is for.
55
- //
56
- // What it buys is that there is no process to start, nothing to find on disk,
57
- // no pipe, and no supervisor: a program that takes a handful of screenshots
58
- // and exits pays for one engine and talks to it directly.
59
-
60
- // Where the addon and the library beside it live.
61
- //
62
- // The platform package is what ships -- the .node sits next to the shared
63
- // library it is linked against, which is the whole reason the two travel in
64
- // one package rather than two. native/build/Release is where node-gyp puts a
65
- // local build; it exists in a checkout and not in an install, so the two never
66
- // compete in practice. Both paths are relative to this file's build output,
67
- // which is one directory below the package root.
68
- function candidates(): string[] {
69
- const found: string[] = [];
70
- const dir = platformPackage.packageDir();
71
- if (dir) {
72
- found.push(path.join(dir, 'shotium.node'));
73
- }
74
- found.push(
75
- path.join(HERE, '..', 'native', 'build', 'Release', 'shotium.node'));
76
- return found;
77
- }
78
-
79
- let binding: NativeBinding|null = null;
80
- let bindingDir: string|null = null;
81
-
82
- function load(): NativeBinding {
83
- if (binding) {
84
- return binding;
85
- }
86
- const tried = candidates();
87
- for (const candidate of tried) {
88
- if (!fs.existsSync(candidate)) {
89
- continue;
90
- }
91
- // Not wrapped in a try: a .node that is there and will not load is a
92
- // broken installation, and the loader's own message -- a missing
93
- // dependency, an architecture mismatch -- says more than anything that
94
- // could be substituted for it.
95
- binding = require(candidate) as NativeBinding;
96
- bindingDir = path.dirname(candidate);
97
- return binding;
98
- }
99
- const expected = platformPackage.packageName();
100
- throw new Error(
101
- 'shotium: no native engine for this platform.\n' +
102
- ` looked in:\n ${tried.join('\n ')}\n` +
103
- (expected ?
104
- ` It ships in ${expected}, which npm installs as an optional ` +
105
- 'dependency of this package.\n' :
106
- ` There is no build for ${process.platform}-${process.arch}.\n`) +
107
- ' import("@shotkit/shotium") uses worker processes instead and needs ' +
108
- 'no addon.');
109
- }
110
-
111
- /**
112
- * The engine, in this process, and the queue in front of it.
113
- *
114
- * Same options and same output as `runtime`, and a different set of trades.
115
- * There is no worker process, so there is nothing to start, nothing to find on
116
- * disk and no pipe: a screenshot costs about a third less than through the
117
- * pool, and the whole thing is one process instead of five.
118
- *
119
- * What it gives up is what a separate process was providing for free. One
120
- * renderer, because blink is a process-wide singleton and `worker_threads`
121
- * share the process, so requests are serialised however many callers there
122
- * are. And no crash isolation: a renderer that dies takes the host program
123
- * with it, where the pool would have retried.
124
- *
125
- * The queue is not about fairness. Each capture occupies a libuv thread pool
126
- * thread for as long as the render takes, and there are four of those by
127
- * default, shared with fs and dns -- so letting four screenshots go at once
128
- * would stall the host's file reads for a fifth of a second at a time while
129
- * gaining nothing, since the engine serialises them anyway.
130
- */
131
- export class NativeRuntime {
132
- private engine: Engine|null = null;
133
- private tail: Promise<unknown> = Promise.resolve();
134
-
135
- get running(): boolean {
136
- return this.engine !== null;
137
- }
138
-
139
- /**
140
- * Starts the engine. Safe to call twice; the second call is a no-op.
141
- *
142
- * `cacheDir` is the HTTP disk cache and `null` disables it, which is the
143
- * default here. `resourceDir` is where `shotium_data.pak` and
144
- * `shotium_strings.pak` are, and defaults to the directory the addon was
145
- * loaded from, which is where they ship.
146
- */
147
- start(options: NativeStartOptions = {}): this {
148
- if (this.engine) {
149
- return this;
150
- }
151
- const native = load();
152
-
153
- const engineOptions: Record<string, unknown> = {};
154
- if (options.cacheDir !== null && options.cacheDir !== undefined) {
155
- engineOptions.cacheDir = options.cacheDir;
156
- }
157
- if (options.userAgent !== undefined) {
158
- engineOptions.userAgent = options.userAgent;
159
- }
160
- // The packs sit beside the library, and the library cannot find itself on
161
- // Linux -- the path the engine resolves for "this module" goes through
162
- // /proc/self/exe, which names node. Saying it here is cheaper than
163
- // teaching the engine a second way to look. See shot_api.h.
164
- engineOptions.resourceDir = options.resourceDir || bindingDir;
165
-
166
- this.engine = native.create(JSON.stringify(engineOptions));
167
- return this;
168
- }
169
-
170
- /** Stops the engine, after whatever is queued. */
171
- async stop(): Promise<void> {
172
- if (!this.engine) {
173
- return;
174
- }
175
- // After the queue, not before: destroy() waits for a capture in flight
176
- // anyway, and doing it in order means a caller's last screenshot resolves
177
- // rather than racing the shutdown.
178
- const engine = this.engine;
179
- this.engine = null;
180
- await this.tail.catch(() => {});
181
- load().destroy(engine);
182
- }
183
-
184
- /**
185
- * Hands back what the engine is holding but can rebuild.
186
- * `releaseWorkingSet` additionally asks the OS for the pages, which the next
187
- * screenshot pays back in soft faults -- worth it when there may not be a
188
- * next one soon.
189
- *
190
- * The resident worker does this for itself on a timer because it can watch
191
- * its own request stream go quiet. Here the queue belongs to the caller, so
192
- * the caller is the one who knows a batch has ended.
193
- */
194
- purge({releaseWorkingSet = false}: PurgeOptions = {}): void {
195
- if (!this.engine) {
196
- return;
197
- }
198
- load().purge(this.engine, releaseWorkingSet);
199
- }
200
-
201
- /**
202
- * Renders one screenshot. Resolves to the encoded image, or to `null` when
203
- * `path` was given and the engine wrote the file itself.
204
- */
205
- async screenshot(options: ScreenshotOptions): Promise<Buffer|null> {
206
- // Before anything else, and before the queue: a malformed request should
207
- // be a rejection now rather than one that waits its turn.
208
- const request = toRequest(options);
209
- if (!this.engine) {
210
- this.start();
211
- }
212
- const engine = this.engine;
213
- const native = load();
214
-
215
- // Chain onto the tail so that captures run one at a time. The catch keeps
216
- // one failure from poisoning everything queued behind it.
217
- const result = this.tail.catch(() => {}).then(
218
- () => native.capture(engine, JSON.stringify(request)));
219
- this.tail = result.catch(() => {});
220
- const image = await result;
221
- return request.path ? null : image;
222
- }
223
- }
224
-
225
- /** The shared in-process engine, started on first use. */
226
- const native = new NativeRuntime();
227
-
228
- /** One screenshot through the shared in-process engine. */
229
- const screenshot = (options: ScreenshotOptions): Promise<Buffer|null> =>
230
- native.screenshot(options);
231
-
232
- export {native, screenshot};
233
-
234
- export default {NativeRuntime, native, screenshot};