relapsesdk 0.0.0-stage → 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/LICENSE +232 -0
- package/README.md +2 -2
- package/dist/channel.d.ts +33 -0
- package/dist/channel.js +39 -0
- package/dist/client.d.ts +28 -0
- package/dist/client.js +57 -0
- package/dist/configuration.d.ts +38 -0
- package/dist/configuration.js +251 -0
- package/dist/discovery.d.ts +12 -0
- package/dist/discovery.js +79 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +9 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +10 -0
- package/dist/internal/json.d.ts +5 -0
- package/dist/internal/json.js +15 -0
- package/dist/internal/operation.d.ts +13 -0
- package/dist/internal/operation.js +52 -0
- package/dist/internal/profile-name.d.ts +1 -0
- package/dist/internal/profile-name.js +4 -0
- package/dist/internal/transport.d.ts +25 -0
- package/dist/internal/transport.js +203 -0
- package/dist/internal/wait-for.d.ts +3 -0
- package/dist/internal/wait-for.js +35 -0
- package/dist/launcher.d.ts +12 -0
- package/dist/launcher.js +34 -0
- package/dist/main-channel.d.ts +74 -0
- package/dist/main-channel.js +233 -0
- package/dist/profiles.d.ts +18 -0
- package/dist/profiles.js +65 -0
- package/examples/channel.mjs +20 -0
- package/examples/consumer.ts +134 -0
- package/examples/execute.mjs +22 -0
- package/package.json +61 -4
- package/src/channel.ts +71 -0
- package/src/client.ts +76 -0
- package/src/configuration.ts +273 -0
- package/src/discovery.ts +80 -0
- package/src/errors.ts +25 -0
- package/src/index.ts +26 -0
- package/src/internal/json.ts +25 -0
- package/src/internal/operation.ts +69 -0
- package/src/internal/profile-name.ts +5 -0
- package/src/internal/transport.ts +213 -0
- package/src/internal/wait-for.ts +40 -0
- package/src/launcher.ts +43 -0
- package/src/main-channel.ts +295 -0
- package/src/profiles.ts +83 -0
- package/tsconfig.json +20 -0
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
|
|
3
|
+
import { EventEmitter } from "node:events";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { basename } from "node:path";
|
|
6
|
+
import type { ChannelConnection } from "./channel.js";
|
|
7
|
+
import { RelapseError } from "./errors.js";
|
|
8
|
+
import { isRecord } from "./internal/json.js";
|
|
9
|
+
import { operation, type Operation, type WaitOptions } from "./internal/operation.js";
|
|
10
|
+
import { Transport, type CloseInfo } from "./internal/transport.js";
|
|
11
|
+
import { waitForEvent } from "./internal/wait-for.js";
|
|
12
|
+
|
|
13
|
+
export interface MainChannelOptions extends WaitOptions {
|
|
14
|
+
socketPath: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ExecuteOptions extends WaitOptions {
|
|
18
|
+
name?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type MainRequest = {
|
|
22
|
+
op: "execute";
|
|
23
|
+
script_id: number;
|
|
24
|
+
session: number;
|
|
25
|
+
source: string;
|
|
26
|
+
name?: string;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export interface MainHello {
|
|
30
|
+
type: "hello";
|
|
31
|
+
pid: number;
|
|
32
|
+
profile: string;
|
|
33
|
+
ready: boolean;
|
|
34
|
+
session: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface MainStatus {
|
|
38
|
+
type: "status";
|
|
39
|
+
ready: boolean;
|
|
40
|
+
session: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface ExecutionResult {
|
|
44
|
+
type: "exec_result";
|
|
45
|
+
script_id: number;
|
|
46
|
+
phase: "submitted" | "error";
|
|
47
|
+
detail?: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface LogEntry {
|
|
51
|
+
type: "log";
|
|
52
|
+
level: string;
|
|
53
|
+
text: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface MainError {
|
|
57
|
+
type: "error";
|
|
58
|
+
detail: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export type MainMessage = MainHello | MainStatus | ExecutionResult | LogEntry | MainError;
|
|
62
|
+
|
|
63
|
+
export interface MainChannelEvents {
|
|
64
|
+
message: [message: MainMessage];
|
|
65
|
+
hello: [message: MainHello];
|
|
66
|
+
status: [message: MainStatus];
|
|
67
|
+
exec_result: [message: ExecutionResult];
|
|
68
|
+
log: [message: LogEntry];
|
|
69
|
+
close: [info: CloseInfo];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export class MainChannel extends EventEmitter<MainChannelEvents> implements ChannelConnection {
|
|
73
|
+
readonly #transport: Transport;
|
|
74
|
+
readonly #opening: Operation<void>;
|
|
75
|
+
readonly #requests = new Map<number, Operation<void>>();
|
|
76
|
+
readonly #pending = new Set<number>();
|
|
77
|
+
#hello: Readonly<MainHello> | undefined;
|
|
78
|
+
#ready = false;
|
|
79
|
+
#session = 0;
|
|
80
|
+
#nextId = 1;
|
|
81
|
+
|
|
82
|
+
private constructor(options: MainChannelOptions, opening: Operation<void>) {
|
|
83
|
+
super();
|
|
84
|
+
this.#opening = opening;
|
|
85
|
+
this.#transport = new Transport(options.socketPath, "@main", {
|
|
86
|
+
message: message => this.#receive(message),
|
|
87
|
+
close: info => this.#closed(info),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Connects to @main and receives its initial hello, which may report ready: false. */
|
|
92
|
+
static async connect(options: MainChannelOptions): Promise<MainChannel> {
|
|
93
|
+
const opening = operation<void>(options, 5000);
|
|
94
|
+
let channel: MainChannel;
|
|
95
|
+
try {
|
|
96
|
+
channel = new MainChannel(options, opening);
|
|
97
|
+
} catch (error) {
|
|
98
|
+
opening.resolve();
|
|
99
|
+
await opening.promise.catch(() => {});
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
await Promise.all([
|
|
104
|
+
channel.#transport.open(options).then(() => channel.#transport.resume()),
|
|
105
|
+
opening.promise,
|
|
106
|
+
]);
|
|
107
|
+
setImmediate(() => channel.#transport.resume());
|
|
108
|
+
return channel;
|
|
109
|
+
} catch (error) {
|
|
110
|
+
channel.close();
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
get socketPath(): string { return this.#transport.socketPath; }
|
|
116
|
+
get name(): "@main" { return "@main"; }
|
|
117
|
+
get connected(): boolean { return this.#transport.connected; }
|
|
118
|
+
get maxMessageBytes(): number { return this.#transport.maxMessageBytes; }
|
|
119
|
+
get hello(): Readonly<MainHello> { return this.#hello!; }
|
|
120
|
+
get ready(): boolean { return this.connected && this.#ready; }
|
|
121
|
+
get session(): number { return this.#session; }
|
|
122
|
+
|
|
123
|
+
/** Validates and writes a request. Execution acknowledgements arrive as exec_result events. */
|
|
124
|
+
async send(value: MainRequest): Promise<void> {
|
|
125
|
+
const request = validateRequest(value);
|
|
126
|
+
if (!this.connected) throw new RelapseError("disconnected", "Main channel is closed.");
|
|
127
|
+
if (!this.ready) throw new RelapseError("not_ready", "Executor is not ready.");
|
|
128
|
+
if (request.session !== this.#session) throw new RelapseError("session_changed", "Request targets a different executor session.");
|
|
129
|
+
if (this.#pending.has(request.script_id)) throw new TypeError("This execution request ID is already pending.");
|
|
130
|
+
if (this.#pending.size >= 16) throw new RelapseError("backpressure", "Too many pending executions.");
|
|
131
|
+
|
|
132
|
+
this.#pending.add(request.script_id);
|
|
133
|
+
this.#nextId = Math.max(this.#nextId, request.script_id + 1);
|
|
134
|
+
try {
|
|
135
|
+
await this.#transport.send(request);
|
|
136
|
+
} catch (error) {
|
|
137
|
+
this.#pending.delete(request.script_id);
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Waits for a future matching event. Check ready before waiting for a readiness transition. */
|
|
143
|
+
waitFor<K extends keyof MainChannelEvents>(
|
|
144
|
+
event: K,
|
|
145
|
+
predicate?: (value: MainChannelEvents[K][0]) => boolean,
|
|
146
|
+
options: WaitOptions = {},
|
|
147
|
+
): Promise<MainChannelEvents[K][0]> {
|
|
148
|
+
return waitForEvent(this, event, this.connected, predicate, options);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Resolves on submission, not script completion. Timeout/abort cannot undo submission. */
|
|
152
|
+
async execute(source: string, options: ExecuteOptions = {}): Promise<void> {
|
|
153
|
+
if (this.#nextId > Number.MAX_SAFE_INTEGER) throw new RangeError("Execution request IDs exhausted.");
|
|
154
|
+
const request = operation<void>(options, 10_000);
|
|
155
|
+
const id = this.#nextId++;
|
|
156
|
+
if (!request.settled) {
|
|
157
|
+
this.#requests.set(id, request);
|
|
158
|
+
this.send({
|
|
159
|
+
op: "execute", script_id: id, session: this.#session,
|
|
160
|
+
source, name: options.name ?? "relapse",
|
|
161
|
+
}).catch(error => request.reject(error));
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
await request.promise;
|
|
165
|
+
} finally {
|
|
166
|
+
this.#requests.delete(id);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async executeFile(path: string, options: ExecuteOptions = {}): Promise<void> {
|
|
171
|
+
const source = await readFile(path, {
|
|
172
|
+
encoding: "utf8",
|
|
173
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
174
|
+
});
|
|
175
|
+
await this.execute(source, { ...options, name: options.name ?? basename(path) });
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
close(): void {
|
|
179
|
+
this.#transport.close();
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
#receive(value: unknown): void {
|
|
183
|
+
let message: MainMessage;
|
|
184
|
+
try {
|
|
185
|
+
message = parseMessage(value);
|
|
186
|
+
if ((!this.#hello && message.type !== "hello") || (this.#hello && message.type === "hello")) {
|
|
187
|
+
throw new TypeError("Expected one initial hello message.");
|
|
188
|
+
}
|
|
189
|
+
} catch (error) {
|
|
190
|
+
this.#transport.close(new RelapseError("protocol_error", "Invalid @main message.", { cause: error }));
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
switch (message.type) {
|
|
195
|
+
case "hello":
|
|
196
|
+
this.#hello = Object.freeze(message);
|
|
197
|
+
this.#ready = message.ready;
|
|
198
|
+
this.#session = message.session;
|
|
199
|
+
this.#transport.pause();
|
|
200
|
+
this.#opening.resolve();
|
|
201
|
+
this.emit("hello", message);
|
|
202
|
+
break;
|
|
203
|
+
case "status":
|
|
204
|
+
if (!message.ready || message.session !== this.#session) {
|
|
205
|
+
for (const pending of this.#requests.values()) {
|
|
206
|
+
pending.reject(new RelapseError("session_changed", "Executor session changed before acknowledgement."));
|
|
207
|
+
}
|
|
208
|
+
this.#requests.clear();
|
|
209
|
+
this.#pending.clear();
|
|
210
|
+
}
|
|
211
|
+
this.#ready = message.ready;
|
|
212
|
+
this.#session = message.session;
|
|
213
|
+
this.emit("status", message);
|
|
214
|
+
break;
|
|
215
|
+
case "exec_result": {
|
|
216
|
+
this.#pending.delete(message.script_id);
|
|
217
|
+
const pending = this.#requests.get(message.script_id);
|
|
218
|
+
this.#requests.delete(message.script_id);
|
|
219
|
+
if (message.phase === "submitted") pending?.resolve();
|
|
220
|
+
else pending?.reject(new RelapseError("execution_failed", message.detail ?? "Execution rejected."));
|
|
221
|
+
this.emit("exec_result", message);
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
case "log":
|
|
225
|
+
this.emit("log", message);
|
|
226
|
+
break;
|
|
227
|
+
case "error":
|
|
228
|
+
this.emit("message", message);
|
|
229
|
+
this.#transport.close(new RelapseError("protocol_error", message.detail));
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
this.emit("message", message);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
#closed(info: CloseInfo): void {
|
|
236
|
+
const error = info.error ?? new RelapseError("disconnected", "Main channel closed.");
|
|
237
|
+
this.#opening.reject(error);
|
|
238
|
+
for (const request of this.#requests.values()) request.reject(error);
|
|
239
|
+
this.#requests.clear();
|
|
240
|
+
this.#pending.clear();
|
|
241
|
+
this.#ready = false;
|
|
242
|
+
this.emit("close", info);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function integer(value: unknown, minimum: number): value is number {
|
|
247
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function validateRequest(value: unknown): MainRequest {
|
|
251
|
+
if (!isRecord(value) || Object.keys(value).some(key =>
|
|
252
|
+
!["op", "script_id", "session", "source", "name"].includes(key))) {
|
|
253
|
+
throw new TypeError("Expected a main-channel execution request with only defined fields.");
|
|
254
|
+
}
|
|
255
|
+
const { op, script_id, session, source, name } = value;
|
|
256
|
+
if (op !== "execute" || !integer(script_id, 1) || !integer(session, 0) || typeof source !== "string" ||
|
|
257
|
+
(name !== undefined && (typeof name !== "string" || Buffer.byteLength(name) > 255))) {
|
|
258
|
+
throw new TypeError("Expected execute, a positive script_id, a session, source text, and an optional name of at most 255 bytes.");
|
|
259
|
+
}
|
|
260
|
+
if (Buffer.from(source).toString("utf8") !== source ||
|
|
261
|
+
(name !== undefined && Buffer.from(name).toString("utf8") !== name)) {
|
|
262
|
+
throw new TypeError("Script source and name must contain valid Unicode.");
|
|
263
|
+
}
|
|
264
|
+
// Copy validated fields so serialization cannot use a caller's toJSON implementation.
|
|
265
|
+
return { op, script_id, session, source, ...(name === undefined ? {} : { name }) };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function parseMessage(value: unknown): MainMessage {
|
|
269
|
+
if (!isRecord(value)) throw new TypeError("Expected an object.");
|
|
270
|
+
switch (value.type) {
|
|
271
|
+
case "hello":
|
|
272
|
+
case "status": {
|
|
273
|
+
const { ready, session } = value;
|
|
274
|
+
if (typeof ready !== "boolean" || !integer(session, ready ? 1 : 0)) break;
|
|
275
|
+
if (value.type === "status") return { type: "status", ready, session };
|
|
276
|
+
if (!integer(value.pid, 1) || typeof value.profile !== "string") break;
|
|
277
|
+
return { type: "hello", ready, session, pid: value.pid, profile: value.profile };
|
|
278
|
+
}
|
|
279
|
+
case "exec_result": {
|
|
280
|
+
const { script_id, phase, detail } = value;
|
|
281
|
+
if (!integer(script_id, 1) || (phase !== "submitted" && phase !== "error") ||
|
|
282
|
+
(detail !== undefined && typeof detail !== "string")) break;
|
|
283
|
+
return { type: "exec_result", script_id, phase, ...(detail === undefined ? {} : { detail }) };
|
|
284
|
+
}
|
|
285
|
+
case "log":
|
|
286
|
+
if (typeof value.level === "string" && typeof value.text === "string") {
|
|
287
|
+
return { type: "log", level: value.level, text: value.text };
|
|
288
|
+
}
|
|
289
|
+
break;
|
|
290
|
+
case "error":
|
|
291
|
+
if (typeof value.detail === "string") return { type: "error", detail: value.detail };
|
|
292
|
+
break;
|
|
293
|
+
}
|
|
294
|
+
throw new TypeError("Invalid main-channel message.");
|
|
295
|
+
}
|
package/src/profiles.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
|
|
3
|
+
import { lstat, mkdir, readdir } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import {
|
|
6
|
+
configDirectory, dataDirectory, profilePath as configurationPath,
|
|
7
|
+
resolve as resolveConfiguration, writeProfile, type ConfigurationOptions,
|
|
8
|
+
} from "./configuration.js";
|
|
9
|
+
import { isValidName } from "./internal/profile-name.js";
|
|
10
|
+
|
|
11
|
+
export { isValidName } from "./internal/profile-name.js";
|
|
12
|
+
|
|
13
|
+
export type ProfileOptions = ConfigurationOptions;
|
|
14
|
+
|
|
15
|
+
export interface ProfileInfo {
|
|
16
|
+
name: string;
|
|
17
|
+
dataDir: string;
|
|
18
|
+
configFile: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface ProfilePaths {
|
|
22
|
+
dataDir: string;
|
|
23
|
+
state: string;
|
|
24
|
+
cookies: string;
|
|
25
|
+
configFile: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function info(name: string, dataDir: string, options: ProfileOptions): ProfileInfo {
|
|
29
|
+
return { name, dataDir, configFile: configurationPath(name, options) };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function paths(name: string, options: ProfileOptions = {}): Promise<ProfilePaths> {
|
|
33
|
+
const configuration = await resolveConfiguration(name, options);
|
|
34
|
+
return {
|
|
35
|
+
dataDir: configuration.dataDir,
|
|
36
|
+
state: join(configuration.dataDir, "state"),
|
|
37
|
+
cookies: join(configuration.dataDir, "state", "app", "data", "sober", "cookies"),
|
|
38
|
+
configFile: configurationPath(name, options),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function get(name: string, options: ProfileOptions = {}): Promise<ProfileInfo> {
|
|
43
|
+
const configFile = configurationPath(name, options);
|
|
44
|
+
const configured = await lstat(configFile);
|
|
45
|
+
if (!configured.isFile()) throw new Error("Profile configuration must be a regular file.");
|
|
46
|
+
const configuration = await resolveConfiguration(name, options);
|
|
47
|
+
return info(name, configuration.dataDir, options);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function list(options: ProfileOptions = {}): Promise<ProfileInfo[]> {
|
|
51
|
+
const root = join(configDirectory(options), "profiles");
|
|
52
|
+
const entries = await readdir(root, { withFileTypes: true }).catch((error: NodeJS.ErrnoException) => {
|
|
53
|
+
if (error.code === "ENOENT") return [];
|
|
54
|
+
throw error;
|
|
55
|
+
});
|
|
56
|
+
const names = entries.filter(entry => entry.isDirectory() && isValidName(entry.name))
|
|
57
|
+
.map(entry => entry.name).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
58
|
+
const result: ProfileInfo[] = [];
|
|
59
|
+
for (const name of names) {
|
|
60
|
+
try {
|
|
61
|
+
result.push(await get(name, options));
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function create(name: string, options: ProfileOptions = {}): Promise<ProfileInfo> {
|
|
70
|
+
const configFile = configurationPath(name, options);
|
|
71
|
+
const root = join(dataDirectory(options), "profiles");
|
|
72
|
+
const dataDir = join(root, name);
|
|
73
|
+
const configured = await lstat(configFile).catch((error: NodeJS.ErrnoException) => {
|
|
74
|
+
if (error.code === "ENOENT") return undefined;
|
|
75
|
+
throw error;
|
|
76
|
+
});
|
|
77
|
+
if (configured) throw new Error("Profile already exists.");
|
|
78
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
79
|
+
if (!(await lstat(root)).isDirectory()) throw new Error("Profiles directory must not be a symlink.");
|
|
80
|
+
await mkdir(dataDir, { mode: 0o700 });
|
|
81
|
+
await writeProfile(name, { dataDir, override: {} }, options);
|
|
82
|
+
return info(name, dataDir, options);
|
|
83
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"module": "NodeNext",
|
|
5
|
+
"moduleResolution": "NodeNext",
|
|
6
|
+
"lib": ["ES2022"],
|
|
7
|
+
"types": ["node"],
|
|
8
|
+
"rootDir": "src",
|
|
9
|
+
"outDir": "dist",
|
|
10
|
+
"declaration": true,
|
|
11
|
+
"strict": true,
|
|
12
|
+
"noUncheckedIndexedAccess": true,
|
|
13
|
+
"exactOptionalPropertyTypes": true,
|
|
14
|
+
"verbatimModuleSyntax": true,
|
|
15
|
+
"forceConsistentCasingInFileNames": true,
|
|
16
|
+
"noUnusedLocals": true,
|
|
17
|
+
"noUnusedParameters": true
|
|
18
|
+
},
|
|
19
|
+
"include": ["src/**/*.ts"]
|
|
20
|
+
}
|