@mostra/runtime 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 +202 -0
- package/README.md +39 -2
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +236 -0
- package/dist/bin.js.map +1 -0
- package/dist/builder/child/main.d.ts +1 -0
- package/dist/builder/child/main.js +1408 -0
- package/dist/builder/child/main.js.map +1 -0
- package/dist/child-xrHmytks.js +49 -0
- package/dist/child-xrHmytks.js.map +1 -0
- package/dist/deps/child/install.d.ts +1 -0
- package/dist/deps/child/install.js +33 -0
- package/dist/deps/child/install.js.map +1 -0
- package/dist/index.d.ts +221 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/instance-CzBkUyHu.js +15920 -0
- package/dist/instance-CzBkUyHu.js.map +1 -0
- package/dist/types-NjNy7gXX.js +57 -0
- package/dist/types-NjNy7gXX.js.map +1 -0
- package/package.json +87 -3
- package/src/actions/index.ts +622 -0
- package/src/addressing/index.ts +281 -0
- package/src/bin.ts +240 -0
- package/src/builder/child/dev.ts +383 -0
- package/src/builder/child/fields.ts +363 -0
- package/src/builder/child/main.ts +47 -0
- package/src/builder/child/plugins.ts +195 -0
- package/src/builder/child/scan.ts +459 -0
- package/src/builder/child/spa.ts +348 -0
- package/src/builder/coverage.ts +72 -0
- package/src/builder/index.ts +406 -0
- package/src/builder/types.ts +180 -0
- package/src/deps/child/install.ts +30 -0
- package/src/deps/index.ts +918 -0
- package/src/deps/installer.ts +321 -0
- package/src/deps/lock.ts +82 -0
- package/src/deps/scan.ts +266 -0
- package/src/deps/specifier.ts +64 -0
- package/src/deps/warm.ts +57 -0
- package/src/dev/index.ts +518 -0
- package/src/faults.ts +65 -0
- package/src/gate.ts +55 -0
- package/src/gateway/actions.ts +268 -0
- package/src/gateway/browser.ts +650 -0
- package/src/gateway/capabilities.ts +760 -0
- package/src/gateway/controls.ts +91 -0
- package/src/gateway/dev.ts +119 -0
- package/src/gateway/http.ts +229 -0
- package/src/gateway/identity.ts +101 -0
- package/src/gateway/index.ts +1299 -0
- package/src/gateway/integrity.ts +117 -0
- package/src/gateway/listener.ts +217 -0
- package/src/gateway/routes.ts +197 -0
- package/src/gateway/serve.ts +138 -0
- package/src/gc/index.ts +451 -0
- package/src/home/acquire.ts +276 -0
- package/src/home/index.ts +16 -0
- package/src/home/paths.ts +192 -0
- package/src/home/platform.ts +34 -0
- package/src/home/record.ts +76 -0
- package/src/home/settings.ts +113 -0
- package/src/index.ts +30 -0
- package/src/instance/index.ts +979 -0
- package/src/interaction/ephemeral.ts +300 -0
- package/src/interaction/events.ts +355 -0
- package/src/interaction/fields.ts +392 -0
- package/src/interaction/index.ts +1013 -0
- package/src/interaction/outbox.ts +493 -0
- package/src/interaction/policy.ts +26 -0
- package/src/interaction/results.ts +341 -0
- package/src/interaction/runs.ts +313 -0
- package/src/interaction/signals.ts +120 -0
- package/src/interaction/submissions.ts +585 -0
- package/src/interaction/subscriptions.ts +258 -0
- package/src/interaction/viewers.ts +187 -0
- package/src/interaction/wait.ts +201 -0
- package/src/ledger/index.ts +442 -0
- package/src/ledger/migrations.ts +596 -0
- package/src/ledger/requests.ts +105 -0
- package/src/ledger/types.ts +28 -0
- package/src/live/index.ts +573 -0
- package/src/log.ts +316 -0
- package/src/processes/child.ts +67 -0
- package/src/processes/environment.ts +64 -0
- package/src/processes/identity.ts +191 -0
- package/src/processes/index.ts +19 -0
- package/src/processes/manager.ts +543 -0
- package/src/protocol-server/client.ts +94 -0
- package/src/protocol-server/index.ts +91 -0
- package/src/protocol-server/server.ts +518 -0
- package/src/protocol-server/streams.ts +81 -0
- package/src/publish/checks.ts +92 -0
- package/src/publish/digest.ts +87 -0
- package/src/publish/index.ts +23 -0
- package/src/publish/manifest.ts +409 -0
- package/src/publish/methods.ts +96 -0
- package/src/publish/publisher.ts +913 -0
- package/src/publish/source.ts +272 -0
- package/src/publish/tar.ts +110 -0
- package/src/registry/index.ts +481 -0
- package/src/registry/store.ts +136 -0
- package/src/secrets/index.ts +223 -0
- package/src/service/idle.ts +64 -0
- package/src/service/index.ts +3 -0
- package/src/service/unit.ts +250 -0
- package/src/verify/fields.ts +125 -0
- package/src/verify/index.ts +913 -0
- package/src/verify/regression.ts +157 -0
- package/src/verify/runner.ts +230 -0
- package/src/verify/sandbox.ts +407 -0
- package/src/verify/typecheck.ts +371 -0
- package/src/workers/index.ts +17 -0
- package/src/workers/launcher.ts +260 -0
- package/src/workers/pool.ts +708 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host protocol server (HO-02, D59): one dispatcher for stdio and the home socket, the
|
|
3
|
+
* session methods, and the socket client a starter uses to attach.
|
|
4
|
+
*/
|
|
5
|
+
import {
|
|
6
|
+
type ChildProcessStatus,
|
|
7
|
+
createDiagnostic,
|
|
8
|
+
type DeliveryCounts,
|
|
9
|
+
type GatewayStatus,
|
|
10
|
+
type InstanceCheck,
|
|
11
|
+
type InstanceInfo,
|
|
12
|
+
type InstanceStatusResult,
|
|
13
|
+
instanceCheckMethod,
|
|
14
|
+
instanceStatusMethod,
|
|
15
|
+
mostraShutdownMethod,
|
|
16
|
+
RpcError,
|
|
17
|
+
type WorkerStatus,
|
|
18
|
+
} from "@mostra/protocol";
|
|
19
|
+
import { handler, type MethodHandler } from "./server.ts";
|
|
20
|
+
|
|
21
|
+
export { attach, type SocketClient } from "./client.ts";
|
|
22
|
+
export { handler, type MethodHandler, ProtocolServer, type Session } from "./server.ts";
|
|
23
|
+
|
|
24
|
+
/** What the session methods need from the instance. */
|
|
25
|
+
export interface SessionMethodsOptions {
|
|
26
|
+
describe(): InstanceInfo;
|
|
27
|
+
/** When the instance took ownership of its home. */
|
|
28
|
+
readonly startedAt: string;
|
|
29
|
+
socketPath(): string;
|
|
30
|
+
connections(): number;
|
|
31
|
+
processes(): readonly ChildProcessStatus[];
|
|
32
|
+
/** Where the gateway listens, once it has started. */
|
|
33
|
+
gateway?(): GatewayStatus | undefined;
|
|
34
|
+
/** The outbox per host (WP-06). */
|
|
35
|
+
deliveries?(): readonly DeliveryCounts[];
|
|
36
|
+
/** The artifact workers (WP-08). */
|
|
37
|
+
workers?(): readonly WorkerStatus[];
|
|
38
|
+
/** When an idle daemon exits (WP-08); `undefined` while busy or for an instance that never does. */
|
|
39
|
+
idleExitAt?(): string | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* The supervisor's own checks of its home (`instance/check`, D140 item 18), in order; `deep`
|
|
42
|
+
* also hashes every version against its output digest.
|
|
43
|
+
*/
|
|
44
|
+
checks?(deep: boolean): Promise<readonly InstanceCheck[]>;
|
|
45
|
+
/**
|
|
46
|
+
* Stops the instance. Called after the `mostra/shutdown` response is on its way (D87).
|
|
47
|
+
*/
|
|
48
|
+
shutdown(reason: string): void;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The handlers of `instance/status` and `mostra/shutdown`. */
|
|
52
|
+
export function sessionMethods(options: SessionMethodsOptions): MethodHandler[] {
|
|
53
|
+
return [
|
|
54
|
+
handler(instanceStatusMethod, (): InstanceStatusResult => {
|
|
55
|
+
const gateway = options.gateway?.();
|
|
56
|
+
return {
|
|
57
|
+
instance: options.describe(),
|
|
58
|
+
startedAt: options.startedAt,
|
|
59
|
+
socket: options.socketPath(),
|
|
60
|
+
connections: options.connections(),
|
|
61
|
+
processes: [...options.processes()],
|
|
62
|
+
...(gateway ? { gateway } : {}),
|
|
63
|
+
...(options.deliveries ? { deliveries: [...options.deliveries()] } : {}),
|
|
64
|
+
...(options.workers ? { workers: [...options.workers()] } : {}),
|
|
65
|
+
...(() => {
|
|
66
|
+
const at = options.idleExitAt?.();
|
|
67
|
+
return at === undefined ? {} : { idleExitAt: at };
|
|
68
|
+
})(),
|
|
69
|
+
};
|
|
70
|
+
}),
|
|
71
|
+
handler(instanceCheckMethod, async (params) => ({
|
|
72
|
+
checks: [...((await options.checks?.(params.deep === true)) ?? [])],
|
|
73
|
+
})),
|
|
74
|
+
handler(mostraShutdownMethod, (_params, session) => {
|
|
75
|
+
// A host-spawned instance lives as long as its host's stdio; attached clients can't end it
|
|
76
|
+
// (D87). A daemon stops for any attached client: its socket is owner-only.
|
|
77
|
+
if (options.describe().mode === "host" && session.kind !== "stdio") {
|
|
78
|
+
throw new RpcError(
|
|
79
|
+
createDiagnostic("MOSTRA_HOST_SHUTDOWN_REFUSED", {
|
|
80
|
+
message: "This instance was spawned by a host over stdio; only that host can stop it.",
|
|
81
|
+
}),
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
// Answer first: the response is written before the stop begins.
|
|
85
|
+
setImmediate(() =>
|
|
86
|
+
options.shutdown(`mostra/shutdown from ${session.client?.name ?? "a client"}`),
|
|
87
|
+
);
|
|
88
|
+
return {};
|
|
89
|
+
}),
|
|
90
|
+
];
|
|
91
|
+
}
|
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host protocol server (D59, INTERFACES §6, HO-02): one dispatcher for every connection,
|
|
3
|
+
* whether `mostra-runtime host`'s stdio or an attached client's Unix socket. It owns the session
|
|
4
|
+
* rules (initialize first and once, revision negotiation, the home check, port registration on
|
|
5
|
+
* the registering connection) and routes every other method to the handler a module registered.
|
|
6
|
+
*/
|
|
7
|
+
import { chmodSync, mkdirSync, type Stats, statSync, unlinkSync } from "node:fs";
|
|
8
|
+
import { createServer, type Server, type Socket } from "node:net";
|
|
9
|
+
import { dirname } from "node:path";
|
|
10
|
+
import type { Readable, Writable } from "node:stream";
|
|
11
|
+
import {
|
|
12
|
+
CLI_CLIENT_NAME,
|
|
13
|
+
type ClientInfo,
|
|
14
|
+
createDiagnostic,
|
|
15
|
+
type Diagnostic,
|
|
16
|
+
HOST_PROTOCOL_REVISIONS,
|
|
17
|
+
type HomeConfig,
|
|
18
|
+
type InstanceInfo,
|
|
19
|
+
type JsonRpcParams,
|
|
20
|
+
type MethodDefinition,
|
|
21
|
+
type MostraInitializeResult,
|
|
22
|
+
mostraInitializeMethod,
|
|
23
|
+
negotiateRevision,
|
|
24
|
+
parseParams,
|
|
25
|
+
type Revision,
|
|
26
|
+
RpcError,
|
|
27
|
+
RpcPeer,
|
|
28
|
+
} from "@mostra/protocol";
|
|
29
|
+
import type { Log } from "../log.ts";
|
|
30
|
+
import { pump, writeLine } from "./streams.ts";
|
|
31
|
+
|
|
32
|
+
/** How a connection reached the instance. */
|
|
33
|
+
export type ConnectionKind = "stdio" | "socket";
|
|
34
|
+
|
|
35
|
+
/** One connection's session, as handlers see it. */
|
|
36
|
+
export interface Session {
|
|
37
|
+
/** A per-instance sequence number, for logs. */
|
|
38
|
+
readonly id: number;
|
|
39
|
+
readonly kind: ConnectionKind;
|
|
40
|
+
/** The client, once initialized. */
|
|
41
|
+
readonly client: ClientInfo | undefined;
|
|
42
|
+
/** The negotiated revision, once initialized. */
|
|
43
|
+
readonly revision: Revision | undefined;
|
|
44
|
+
/** The ports this connection registered and the instance supports. */
|
|
45
|
+
readonly ports: ReadonlySet<string>;
|
|
46
|
+
/** The notifications the client accepts (D84); the instance sends no others. */
|
|
47
|
+
readonly notifications: ReadonlySet<string>;
|
|
48
|
+
/** Aborts when the connection closes, so long requests (`wait`) end with it. */
|
|
49
|
+
readonly signal: AbortSignal;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A method a module serves. */
|
|
53
|
+
export interface MethodHandler<P = unknown, R = unknown> {
|
|
54
|
+
readonly definition: MethodDefinition<P, R>;
|
|
55
|
+
handle(params: P, session: Session): R | Promise<R>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Builds a handler with its types checked against the method definition. */
|
|
59
|
+
export function handler<P, R>(
|
|
60
|
+
definition: MethodDefinition<P, R>,
|
|
61
|
+
handle: (params: P, session: Session) => R | Promise<R>,
|
|
62
|
+
): MethodHandler {
|
|
63
|
+
return { definition, handle } as unknown as MethodHandler;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Options for {@link ProtocolServer}. */
|
|
67
|
+
export interface ProtocolServerOptions {
|
|
68
|
+
readonly log: Log;
|
|
69
|
+
/** Describes the instance for `mostra/initialize`. */
|
|
70
|
+
describe(): InstanceInfo;
|
|
71
|
+
/** Whether a client's `home.path` names this instance's home (D84). */
|
|
72
|
+
servesHome(path: string): boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Applies a client's home settings (`HomeConfig` without `path`), such as the dependency policy
|
|
75
|
+
* (D95). Runs during `mostra/initialize`, after the home check; a throw refuses the session.
|
|
76
|
+
*/
|
|
77
|
+
configureHome?(home: HomeConfig, client: ClientInfo): void;
|
|
78
|
+
/**
|
|
79
|
+
* Marks the home as configured by a host (D140 item 4): called when a client other than the
|
|
80
|
+
* standalone CLI sends `home` or `ports` in `mostra/initialize`.
|
|
81
|
+
*/
|
|
82
|
+
markHostConfigured?(client: ClientInfo): void;
|
|
83
|
+
/** Every method besides `mostra/initialize`. */
|
|
84
|
+
readonly handlers: readonly MethodHandler[];
|
|
85
|
+
/** The ports this instance calls when a client registers them. */
|
|
86
|
+
readonly supportedPorts: readonly string[];
|
|
87
|
+
/** The revisions this instance speaks. Default: `HOST_PROTOCOL_REVISIONS`. */
|
|
88
|
+
readonly revisions?: readonly Revision[];
|
|
89
|
+
/**
|
|
90
|
+
* Applied to the text of every diagnostic a response carries, so secrets and capability
|
|
91
|
+
* material that reach an error (a bundler message quoting an import, say) never leave the
|
|
92
|
+
* instance (STANDARDS security). Default: the identity.
|
|
93
|
+
*/
|
|
94
|
+
readonly redact?: (text: string) => string;
|
|
95
|
+
/** Runs after a connection initialized, with its registered ports. */
|
|
96
|
+
onInitialized?(session: Session): void;
|
|
97
|
+
/** Runs once when a connection closes. */
|
|
98
|
+
onClosed?(session: Session): void;
|
|
99
|
+
/** The notifications this instance may send, for `capabilities.notifications`. */
|
|
100
|
+
readonly notifications?: readonly string[];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
interface Connection {
|
|
104
|
+
readonly session: MutableSession;
|
|
105
|
+
readonly peer: RpcPeer;
|
|
106
|
+
readonly output: Writable;
|
|
107
|
+
close(): void;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
interface MutableSession {
|
|
111
|
+
id: number;
|
|
112
|
+
kind: ConnectionKind;
|
|
113
|
+
client: ClientInfo | undefined;
|
|
114
|
+
revision: Revision | undefined;
|
|
115
|
+
ports: Set<string>;
|
|
116
|
+
notifications: Set<string>;
|
|
117
|
+
readonly signal: AbortSignal;
|
|
118
|
+
initialized: boolean;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The host protocol server of one instance. */
|
|
122
|
+
export class ProtocolServer {
|
|
123
|
+
readonly #options: ProtocolServerOptions;
|
|
124
|
+
readonly #handlers: ReadonlyMap<string, MethodHandler>;
|
|
125
|
+
readonly #connections = new Set<Connection>();
|
|
126
|
+
#nextId = 1;
|
|
127
|
+
#refusal: Diagnostic | undefined;
|
|
128
|
+
#listener: { server: Server; path: string; stats: Stats } | undefined;
|
|
129
|
+
#healTimer: ReturnType<typeof setInterval> | undefined;
|
|
130
|
+
|
|
131
|
+
constructor(options: ProtocolServerOptions) {
|
|
132
|
+
this.#options = options;
|
|
133
|
+
this.#handlers = new Map(options.handlers.map((entry) => [entry.definition.method, entry]));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** How many connections are open. */
|
|
137
|
+
get connections(): number {
|
|
138
|
+
return this.#connections.size;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The methods this server serves, for `capabilities.methods`. */
|
|
142
|
+
get methods(): readonly string[] {
|
|
143
|
+
return [mostraInitializeMethod.method, ...this.#handlers.keys()];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Serves one stream connection (stdio, or an accepted socket). `onClose` runs once when it
|
|
148
|
+
* ends.
|
|
149
|
+
*/
|
|
150
|
+
serve(kind: ConnectionKind, input: Readable, output: Writable, onClose?: () => void): Session {
|
|
151
|
+
const closed = new AbortController();
|
|
152
|
+
const session: MutableSession = {
|
|
153
|
+
id: this.#nextId++,
|
|
154
|
+
kind,
|
|
155
|
+
client: undefined,
|
|
156
|
+
revision: undefined,
|
|
157
|
+
ports: new Set(),
|
|
158
|
+
notifications: new Set(),
|
|
159
|
+
signal: closed.signal,
|
|
160
|
+
initialized: false,
|
|
161
|
+
};
|
|
162
|
+
const peer = new RpcPeer({
|
|
163
|
+
send: (message) => {
|
|
164
|
+
writeLine(output, message);
|
|
165
|
+
},
|
|
166
|
+
onRequest: (method, params) => this.#dispatch(session, method, params),
|
|
167
|
+
onInternalError: (error, method) =>
|
|
168
|
+
this.#options.log.error("protocol.internal_error", { session: session.id, method, error }),
|
|
169
|
+
});
|
|
170
|
+
const connection: Connection = {
|
|
171
|
+
session,
|
|
172
|
+
peer,
|
|
173
|
+
output,
|
|
174
|
+
close: () => {
|
|
175
|
+
peer.close();
|
|
176
|
+
output.end();
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
this.#connections.add(connection);
|
|
180
|
+
this.#options.log.info("protocol.connected", { session: session.id, kind });
|
|
181
|
+
pump(
|
|
182
|
+
{ input, output },
|
|
183
|
+
() => peer,
|
|
184
|
+
() => {
|
|
185
|
+
peer.close();
|
|
186
|
+
this.#connections.delete(connection);
|
|
187
|
+
closed.abort();
|
|
188
|
+
this.#options.log.info("protocol.disconnected", { session: session.id, kind });
|
|
189
|
+
if (session.initialized) {
|
|
190
|
+
try {
|
|
191
|
+
this.#options.onClosed?.(session);
|
|
192
|
+
} catch (error) {
|
|
193
|
+
this.#options.log.error("protocol.close_hook_failed", { session: session.id, error });
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
onClose?.();
|
|
197
|
+
},
|
|
198
|
+
);
|
|
199
|
+
return session;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Listens on the home's control socket (D81, D82): replaces any leftover socket file (only the
|
|
204
|
+
* lock holder calls this), makes the socket owner-only, and checks every `healMs` (at most
|
|
205
|
+
* 10 s) that the file still exists, re-creating it when it has disappeared.
|
|
206
|
+
*/
|
|
207
|
+
async listen(path: string, healMs = 5000): Promise<void> {
|
|
208
|
+
this.#listener = await this.#bind(path);
|
|
209
|
+
this.#healTimer = setInterval(() => void this.#heal(), Math.min(healMs, 10_000));
|
|
210
|
+
this.#healTimer.unref();
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** The socket the server listens on. */
|
|
214
|
+
get socketPath(): string | undefined {
|
|
215
|
+
return this.#listener?.path;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async #bind(path: string): Promise<{ server: Server; path: string; stats: Stats }> {
|
|
219
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
220
|
+
try {
|
|
221
|
+
unlinkSync(path);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
224
|
+
}
|
|
225
|
+
const server = createServer((socket: Socket) => {
|
|
226
|
+
this.serve("socket", socket, socket);
|
|
227
|
+
});
|
|
228
|
+
await new Promise<void>((resolve, reject) => {
|
|
229
|
+
server.once("error", reject);
|
|
230
|
+
server.listen(path, () => {
|
|
231
|
+
server.off("error", reject);
|
|
232
|
+
resolve();
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
chmodSync(path, 0o600);
|
|
236
|
+
server.on("error", (error) => this.#options.log.error("protocol.listener_error", { error }));
|
|
237
|
+
return { server, path, stats: statSync(path) };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async #heal(): Promise<void> {
|
|
241
|
+
const listener = this.#listener;
|
|
242
|
+
if (!listener) return;
|
|
243
|
+
let current: Stats | undefined;
|
|
244
|
+
try {
|
|
245
|
+
current = statSync(listener.path);
|
|
246
|
+
} catch {
|
|
247
|
+
current = undefined;
|
|
248
|
+
}
|
|
249
|
+
if (current && current.ino === listener.stats.ino && current.dev === listener.stats.dev) return;
|
|
250
|
+
// Close the old listener first: Node removes a Unix socket's file when its server closes, so
|
|
251
|
+
// closing it after binding would remove the new socket.
|
|
252
|
+
listener.server.close();
|
|
253
|
+
try {
|
|
254
|
+
const replacement = await this.#bind(listener.path);
|
|
255
|
+
this.#listener = replacement;
|
|
256
|
+
this.#options.log.warn("protocol.socket_recreated", { path: listener.path });
|
|
257
|
+
} catch (error) {
|
|
258
|
+
this.#options.log.warn("protocol.socket_recreate_failed", { path: listener.path, error });
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Answers every request from now on with `diagnostic`, for an instance that can no longer serve
|
|
264
|
+
* (`MOSTRA_HOME_GONE`).
|
|
265
|
+
*/
|
|
266
|
+
refuse(diagnostic: Diagnostic): void {
|
|
267
|
+
this.#refusal = diagnostic;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Calls a port method on the connection that registered the port most recently (D59: port
|
|
272
|
+
* callbacks reach only the registering connection).
|
|
273
|
+
*/
|
|
274
|
+
callPort(
|
|
275
|
+
port: string,
|
|
276
|
+
method: string,
|
|
277
|
+
params: JsonRpcParams,
|
|
278
|
+
options: { timeoutMs?: number } = {},
|
|
279
|
+
): Promise<unknown> {
|
|
280
|
+
const registrant = [...this.#connections]
|
|
281
|
+
.reverse()
|
|
282
|
+
.find((connection) => connection.session.ports.has(port));
|
|
283
|
+
if (!registrant) return Promise.reject(new Error(`No connection registered the ${port} port.`));
|
|
284
|
+
return registrant.peer.request(method, params, options);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** The names of the clients connected now (initialized sessions). */
|
|
288
|
+
connectedClients(): ReadonlySet<string> {
|
|
289
|
+
return new Set(
|
|
290
|
+
[...this.#connections]
|
|
291
|
+
.filter((connection) => connection.session.initialized)
|
|
292
|
+
.map((connection) => connection.session.client?.name ?? ""),
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* The initialized connections that registered `port`, oldest first, with their clients' names:
|
|
298
|
+
* the hosts a port call can reach (D105).
|
|
299
|
+
*/
|
|
300
|
+
registrants(port: string): { readonly session: number; readonly owner: string }[] {
|
|
301
|
+
return [...this.#connections]
|
|
302
|
+
.filter((connection) => connection.session.initialized && connection.session.ports.has(port))
|
|
303
|
+
.map((connection) => ({
|
|
304
|
+
session: connection.session.id,
|
|
305
|
+
owner: connection.session.client?.name ?? "",
|
|
306
|
+
}));
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Calls a method on one connection (a port call, D59); rejects with `MOSTRA_HOST_CONNECTION_CLOSED`
|
|
311
|
+
* when that connection is gone, and `MOSTRA_HOST_TIMEOUT` past `timeoutMs`.
|
|
312
|
+
*/
|
|
313
|
+
callSession(
|
|
314
|
+
session: number,
|
|
315
|
+
method: string,
|
|
316
|
+
params: JsonRpcParams,
|
|
317
|
+
timeoutMs: number,
|
|
318
|
+
): Promise<unknown> {
|
|
319
|
+
const connection = [...this.#connections].find((entry) => entry.session.id === session);
|
|
320
|
+
if (!connection) {
|
|
321
|
+
return Promise.reject(
|
|
322
|
+
new RpcError(
|
|
323
|
+
createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", {
|
|
324
|
+
message: `The connection that registered for ${method} has closed.`,
|
|
325
|
+
}),
|
|
326
|
+
),
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
return connection.peer.request(method, params, { timeoutMs });
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* When a connection's output is full (its client reads slower than the instance writes), a
|
|
334
|
+
* promise that settles once it drained or closed; `undefined` when it can take more now. Senders
|
|
335
|
+
* of long streams of notifications wait on it, so a slow client never makes the instance buffer
|
|
336
|
+
* without bound.
|
|
337
|
+
*/
|
|
338
|
+
drained(session: number): Promise<void> | undefined {
|
|
339
|
+
const connection = [...this.#connections].find((entry) => entry.session.id === session);
|
|
340
|
+
const output = connection?.output;
|
|
341
|
+
if (!output?.writableNeedDrain) return undefined;
|
|
342
|
+
return new Promise((resolve) => {
|
|
343
|
+
const done = (): void => {
|
|
344
|
+
output.off("drain", done);
|
|
345
|
+
output.off("close", done);
|
|
346
|
+
resolve();
|
|
347
|
+
};
|
|
348
|
+
output.once("drain", done);
|
|
349
|
+
output.once("close", done);
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Sends a notification on one connection, if its client accepted that notification (D84).
|
|
355
|
+
* Returns `false` when the connection is gone or didn't accept it.
|
|
356
|
+
*/
|
|
357
|
+
notify(session: number, method: string, params: JsonRpcParams): boolean {
|
|
358
|
+
const connection = [...this.#connections].find((entry) => entry.session.id === session);
|
|
359
|
+
if (!connection || connection.peer.closed || !connection.session.notifications.has(method)) {
|
|
360
|
+
return false;
|
|
361
|
+
}
|
|
362
|
+
connection.peer.notify(method, params);
|
|
363
|
+
return true;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Stops listening, removes the socket file if it is still this server's, and closes every
|
|
368
|
+
* connection. Responses already sent are flushed first.
|
|
369
|
+
*/
|
|
370
|
+
close(): void {
|
|
371
|
+
if (this.#healTimer) clearInterval(this.#healTimer);
|
|
372
|
+
const listener = this.#listener;
|
|
373
|
+
this.#listener = undefined;
|
|
374
|
+
if (listener) {
|
|
375
|
+
listener.server.close();
|
|
376
|
+
try {
|
|
377
|
+
const current = statSync(listener.path);
|
|
378
|
+
if (current.ino === listener.stats.ino && current.dev === listener.stats.dev)
|
|
379
|
+
unlinkSync(listener.path);
|
|
380
|
+
} catch {
|
|
381
|
+
// Already gone.
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
for (const connection of this.#connections) connection.close();
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async #dispatch(session: MutableSession, method: string, params: unknown): Promise<unknown> {
|
|
388
|
+
try {
|
|
389
|
+
return await this.#route(session, method, params);
|
|
390
|
+
} catch (error) {
|
|
391
|
+
const redact = this.#options.redact;
|
|
392
|
+
if (!redact || !(error instanceof RpcError)) throw error;
|
|
393
|
+
const { diagnostic } = error;
|
|
394
|
+
throw new RpcError(
|
|
395
|
+
{
|
|
396
|
+
...diagnostic,
|
|
397
|
+
message: redact(diagnostic.message),
|
|
398
|
+
...(diagnostic.hint !== undefined ? { hint: redact(diagnostic.hint) } : {}),
|
|
399
|
+
...(diagnostic.fix?.text !== undefined
|
|
400
|
+
? { fix: { ...diagnostic.fix, text: redact(diagnostic.fix.text) } }
|
|
401
|
+
: {}),
|
|
402
|
+
},
|
|
403
|
+
error.code,
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
async #route(session: MutableSession, method: string, params: unknown): Promise<unknown> {
|
|
409
|
+
if (this.#refusal) throw new RpcError(this.#refusal);
|
|
410
|
+
if (method === mostraInitializeMethod.method) return this.#initialize(session, params);
|
|
411
|
+
if (!session.initialized) {
|
|
412
|
+
throw new RpcError(
|
|
413
|
+
createDiagnostic("MOSTRA_HOST_INITIALIZE_ORDER", {
|
|
414
|
+
message: `${method} arrived before mostra/initialize on this connection.`,
|
|
415
|
+
}),
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
const entry = this.#handlers.get(method);
|
|
419
|
+
if (!entry) {
|
|
420
|
+
throw new RpcError(
|
|
421
|
+
createDiagnostic("MOSTRA_HOST_METHOD_UNKNOWN", {
|
|
422
|
+
message: `This instance serves no method ${method}.`,
|
|
423
|
+
}),
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
const parsed = parseParams(entry.definition, params);
|
|
427
|
+
const result = await entry.handle(parsed, session);
|
|
428
|
+
const checked = entry.definition.result.safeParse(result);
|
|
429
|
+
if (!checked.success) {
|
|
430
|
+
this.#options.log.error("protocol.invalid_result", { method, issues: checked.error.issues });
|
|
431
|
+
throw new RpcError(
|
|
432
|
+
createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", {
|
|
433
|
+
message: `${method} failed unexpectedly.`,
|
|
434
|
+
}),
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
return checked.data;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
#initialize(session: MutableSession, raw: unknown): MostraInitializeResult {
|
|
441
|
+
if (session.initialized) {
|
|
442
|
+
throw new RpcError(
|
|
443
|
+
createDiagnostic("MOSTRA_HOST_INITIALIZE_ORDER", {
|
|
444
|
+
message: "This connection is already initialized; mostra/initialize is sent once.",
|
|
445
|
+
}),
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
const params = parseParams(mostraInitializeMethod, raw);
|
|
449
|
+
const negotiation = negotiateRevision(
|
|
450
|
+
params.revisions,
|
|
451
|
+
this.#options.revisions ?? HOST_PROTOCOL_REVISIONS,
|
|
452
|
+
);
|
|
453
|
+
if (!negotiation.ok) throw new RpcError(negotiation.diagnostic);
|
|
454
|
+
const instance = this.#options.describe();
|
|
455
|
+
if (params.home?.path !== undefined && !this.#options.servesHome(params.home.path)) {
|
|
456
|
+
throw new RpcError(
|
|
457
|
+
createDiagnostic("MOSTRA_HOME_MISMATCH", {
|
|
458
|
+
message: `The client expects the home ${params.home.path}; this instance serves ${instance.home}.`,
|
|
459
|
+
}),
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
if (params.home !== undefined) this.#options.configureHome?.(params.home, params.client);
|
|
463
|
+
if (
|
|
464
|
+
(params.home !== undefined || params.ports.length > 0) &&
|
|
465
|
+
params.client.name !== CLI_CLIENT_NAME
|
|
466
|
+
) {
|
|
467
|
+
this.#options.markHostConfigured?.(params.client);
|
|
468
|
+
}
|
|
469
|
+
const supported = new Set(this.#options.supportedPorts);
|
|
470
|
+
const warnings: Diagnostic[] = [];
|
|
471
|
+
for (const port of new Set(params.ports)) {
|
|
472
|
+
if (supported.has(port)) {
|
|
473
|
+
session.ports.add(port);
|
|
474
|
+
} else {
|
|
475
|
+
warnings.push(
|
|
476
|
+
createDiagnostic("MOSTRA_HOST_PORT_UNSUPPORTED", {
|
|
477
|
+
message:
|
|
478
|
+
port === "ai"
|
|
479
|
+
? "The ai port is reserved for a later release (D46); this instance doesn't call it."
|
|
480
|
+
: `This instance doesn't call the ${port} port; the session continues without it.`,
|
|
481
|
+
}),
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
session.initialized = true;
|
|
486
|
+
session.client = params.client;
|
|
487
|
+
session.revision = negotiation.revision;
|
|
488
|
+
const offered = new Set(this.#options.notifications ?? []);
|
|
489
|
+
for (const name of params.capabilities.notifications ?? []) {
|
|
490
|
+
if (offered.has(name)) session.notifications.add(name);
|
|
491
|
+
}
|
|
492
|
+
this.#options.log.info("protocol.initialized", {
|
|
493
|
+
session: session.id,
|
|
494
|
+
client: params.client,
|
|
495
|
+
revision: negotiation.revision,
|
|
496
|
+
ports: [...session.ports],
|
|
497
|
+
});
|
|
498
|
+
// After the answer is on its way: a port call it starts never precedes the response.
|
|
499
|
+
setImmediate(() => {
|
|
500
|
+
if (session.signal.aborted) return;
|
|
501
|
+
try {
|
|
502
|
+
this.#options.onInitialized?.(session);
|
|
503
|
+
} catch (error) {
|
|
504
|
+
this.#options.log.error("protocol.initialized_hook_failed", { session: session.id, error });
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
return {
|
|
508
|
+
revision: negotiation.revision,
|
|
509
|
+
instance,
|
|
510
|
+
capabilities: {
|
|
511
|
+
methods: this.methods,
|
|
512
|
+
notifications: [...(this.#options.notifications ?? [])],
|
|
513
|
+
ports: [...this.#options.supportedPorts],
|
|
514
|
+
},
|
|
515
|
+
warnings,
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Newline-delimited JSON-RPC over byte streams (INTERFACES §6): stdio for `mostra-runtime host`,
|
|
3
|
+
* Unix sockets for attached clients. Both feed the same {@link RpcPeer}.
|
|
4
|
+
*/
|
|
5
|
+
import type { Readable, Writable } from "node:stream";
|
|
6
|
+
import {
|
|
7
|
+
createDiagnostic,
|
|
8
|
+
encodeLine,
|
|
9
|
+
LineSplitter,
|
|
10
|
+
MAX_LINE_LENGTH,
|
|
11
|
+
RpcError,
|
|
12
|
+
type RpcPeer,
|
|
13
|
+
} from "@mostra/protocol";
|
|
14
|
+
|
|
15
|
+
/** A connection's raw ends. */
|
|
16
|
+
export interface StreamEnds {
|
|
17
|
+
readonly input: Readable;
|
|
18
|
+
readonly output: Writable;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Connects `peer` to a stream pair: lines in, encoded messages out. Calls `onEnd` once when the
|
|
23
|
+
* input ends or fails. A line longer than the limit is answered with `MOSTRA_HOST_MALFORMED` and
|
|
24
|
+
* ends the connection, so a client can't make the instance buffer without bound.
|
|
25
|
+
*/
|
|
26
|
+
export function pump(ends: StreamEnds, peer: () => RpcPeer, onEnd: () => void): void {
|
|
27
|
+
const splitter = new LineSplitter();
|
|
28
|
+
let ended = false;
|
|
29
|
+
const end = (): void => {
|
|
30
|
+
if (ended) return;
|
|
31
|
+
ended = true;
|
|
32
|
+
onEnd();
|
|
33
|
+
};
|
|
34
|
+
ends.input.setEncoding("utf8");
|
|
35
|
+
ends.input.on("data", (chunk: string) => {
|
|
36
|
+
let lines: string[];
|
|
37
|
+
try {
|
|
38
|
+
lines = splitter.push(chunk);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
const diagnostic = createDiagnostic("MOSTRA_HOST_MALFORMED", {
|
|
41
|
+
message: (error as Error).message,
|
|
42
|
+
});
|
|
43
|
+
writeLine(ends.output, {
|
|
44
|
+
jsonrpc: "2.0",
|
|
45
|
+
id: null,
|
|
46
|
+
error: new RpcError(diagnostic).toErrorObject(),
|
|
47
|
+
});
|
|
48
|
+
ends.input.destroy();
|
|
49
|
+
end();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
for (const line of lines) peer().receiveLine(line);
|
|
53
|
+
});
|
|
54
|
+
ends.input.on("end", end);
|
|
55
|
+
ends.input.on("close", end);
|
|
56
|
+
ends.input.on("error", end);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Writes one message as a line. Returns false when the stream can't take it any more. A message
|
|
61
|
+
* longer than the line limit would make the reader drop the connection, so it is never written:
|
|
62
|
+
* an answer becomes `MOSTRA_HOST_MESSAGE_TOO_LARGE` for its request, and anything else is dropped
|
|
63
|
+
* (Mostra's own requests and notifications are bounded well below the limit).
|
|
64
|
+
*/
|
|
65
|
+
export function writeLine(output: Writable, message: Parameters<typeof encodeLine>[0]): boolean {
|
|
66
|
+
if (output.destroyed || output.writableEnded) throw new Error("The connection is closed.");
|
|
67
|
+
let line = encodeLine(message);
|
|
68
|
+
if (line.length > MAX_LINE_LENGTH) {
|
|
69
|
+
if (!("id" in message) || "method" in message || message.id === null) return true;
|
|
70
|
+
line = encodeLine({
|
|
71
|
+
jsonrpc: "2.0",
|
|
72
|
+
id: message.id,
|
|
73
|
+
error: new RpcError(
|
|
74
|
+
createDiagnostic("MOSTRA_HOST_MESSAGE_TOO_LARGE", {
|
|
75
|
+
message: `The answer is ${line.length} characters, longer than one protocol message carries (${MAX_LINE_LENGTH}).`,
|
|
76
|
+
}),
|
|
77
|
+
).toErrorObject(),
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
return output.write(line);
|
|
81
|
+
}
|