@capybara-hq/kernel 0.1.0-rc.85 → 0.1.0-rc.87
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/bootstrap.json +5 -5
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/cards.d.ts +7 -3
- package/dist/channels/cards.js +9 -4
- package/dist/channels/phrases.d.ts +10 -0
- package/dist/channels/phrases.js +10 -0
- package/dist/config/docs.js +1 -1
- package/dist/config/schema.d.ts +3 -0
- package/dist/config/schema.js +18 -12
- package/dist/ctx/create-ctx.d.ts +10 -1
- package/dist/ctx/create-ctx.js +42 -2
- package/dist/device-access/device-access.module.d.ts +7 -0
- package/dist/device-access/device-access.module.js +41 -0
- package/dist/device-access/device-access.service.d.ts +142 -0
- package/dist/device-access/device-access.service.js +464 -0
- package/dist/device-access/token.d.ts +6 -0
- package/dist/device-access/token.js +6 -0
- package/dist/device-access/viewer-routes.d.ts +45 -0
- package/dist/device-access/viewer-routes.js +81 -0
- package/dist/device-access/viewer.d.ts +244 -0
- package/dist/device-access/viewer.js +844 -0
- package/dist/dial-in/access.d.ts +19 -0
- package/dist/dial-in/access.js +23 -0
- package/dist/dial-in/gateway.d.ts +48 -6
- package/dist/dial-in/gateway.js +145 -10
- package/dist/dial-in/keys.d.ts +7 -0
- package/dist/dial-in/keys.js +7 -0
- package/dist/dial-in/routes.d.ts +11 -3
- package/dist/dial-in/routes.js +15 -4
- package/dist/dial-in/streams.d.ts +58 -0
- package/dist/dial-in/streams.js +283 -0
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +2 -0
- package/dist/extensions/host.d.ts +13 -1
- package/dist/extensions/host.js +20 -1
- package/dist/extensions/permission-set.d.ts +15 -1
- package/dist/extensions/permission-set.js +13 -1
- package/dist/extensions/permission-view.d.ts +6 -4
- package/dist/extensions/permission-view.js +6 -1
- package/dist/http/error.filter.js +2 -0
- package/dist/http/gateway-routes.d.ts +8 -4
- package/dist/http/gateway-routes.js +4 -3
- package/dist/infra/lock/lock.service.d.ts +5 -1
- package/dist/infra/lock/lock.service.js +10 -4
- package/dist/infra/throttler/named-throttlers.d.ts +3 -0
- package/dist/infra/throttler/named-throttlers.js +16 -0
- package/dist/kernel.module.js +3 -0
- package/dist/roles/gateway-role.d.ts +13 -6
- package/dist/roles/gateway-role.js +27 -9
- package/dist/roles/gateway.module.d.ts +2 -1
- package/dist/roles/gateway.module.js +13 -3
- package/dist/sandbox/device-services.d.ts +62 -0
- package/dist/sandbox/device-services.js +183 -0
- package/dist/sandbox/leases.d.ts +18 -1
- package/dist/sandbox/leases.js +75 -1
- package/dist/sandbox/network-grants.js +5 -2
- package/dist/sandbox/sandbox.module.d.ts +2 -1
- package/dist/sandbox/sandbox.module.js +5 -2
- package/dist/sandbox/sandbox.service.d.ts +44 -1
- package/dist/sandbox/sandbox.service.js +142 -5
- package/dist/tools/approvals.service.d.ts +45 -20
- package/dist/tools/approvals.service.js +19 -9
- package/dist/tools/call-scope.d.ts +60 -0
- package/dist/tools/call-scope.js +23 -0
- package/dist/tools/network-asks.d.ts +13 -0
- package/dist/tools/network-asks.js +26 -2
- package/dist/tools/pipeline.d.ts +30 -1
- package/dist/tools/pipeline.js +285 -54
- package/dist/tools/questions.service.d.ts +24 -3
- package/dist/tools/questions.service.js +3 -1
- package/package.json +3 -3
package/dist/dial-in/access.d.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
|
+
import { type DeviceStream } from "@capybara-hq/plugin-sdk";
|
|
1
2
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
2
3
|
import { DialInRelay, type DialInRequestOptions } from "./relay.js";
|
|
4
|
+
/** What opens streams on the machine sockets this process holds (`DialInGateway`). */
|
|
5
|
+
export interface DialInStreamOpener {
|
|
6
|
+
openStream(deviceId: string, body: unknown, signal: AbortSignal): Promise<DeviceStream>;
|
|
7
|
+
}
|
|
3
8
|
/**
|
|
4
9
|
* What `ctx.dialIn` is built from (`ctx/create-ctx.ts`): the relay, and the check that a device is
|
|
5
10
|
* served by the calling extension. Kept below the extension host (its module imports nothing but
|
|
@@ -8,6 +13,11 @@ import { DialInRelay, type DialInRequestOptions } from "./relay.js";
|
|
|
8
13
|
export declare class DialInAccess {
|
|
9
14
|
private readonly kdb;
|
|
10
15
|
private readonly relay;
|
|
16
|
+
/**
|
|
17
|
+
* The gateway of this process, when it runs the gateway role: it registers itself at
|
|
18
|
+
* construction (`DialInGateway` sits above this module, so it cannot be injected here).
|
|
19
|
+
*/
|
|
20
|
+
private streams;
|
|
11
21
|
constructor(kdb: KernelDb, relay: Pick<DialInRelay, "request" | "online" | "capacity" | "stop">);
|
|
12
22
|
/**
|
|
13
23
|
* Whether `deviceId` is a live device (in a live org) whose `devices.provider` is `plugin`, and
|
|
@@ -23,4 +33,13 @@ export declare class DialInAccess {
|
|
|
23
33
|
maxFrameBytes: number;
|
|
24
34
|
} | null>;
|
|
25
35
|
stop(deviceId: string, reason: "drain" | "stop"): Promise<void>;
|
|
36
|
+
/** @internal the gateway of this process serves the streams of the sockets it holds. */
|
|
37
|
+
serveStreams(opener: DialInStreamOpener): void;
|
|
38
|
+
/**
|
|
39
|
+
* Opens a stream on the machine's socket, which only the gateway replica holding it can do
|
|
40
|
+
* (`DialInGateway.openStream`). A process without the gateway role throws
|
|
41
|
+
* `DialInStreamElsewhereError` when some replica holds the machine, `DeviceOfflineError` when
|
|
42
|
+
* none does.
|
|
43
|
+
*/
|
|
44
|
+
openStream(deviceId: string, body: unknown, signal: AbortSignal): Promise<DeviceStream>;
|
|
26
45
|
}
|
package/dist/dial-in/access.js
CHANGED
|
@@ -7,6 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
7
7
|
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
8
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
9
|
};
|
|
10
|
+
import { DeviceOfflineError, DialInStreamElsewhereError, } from "@capybara-hq/plugin-sdk";
|
|
10
11
|
import { Inject, Injectable } from "@nestjs/common";
|
|
11
12
|
import { isExtensionEnabled } from "../extensions/enabled.js";
|
|
12
13
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
@@ -19,6 +20,11 @@ import { DialInRelay } from "./relay.js";
|
|
|
19
20
|
let DialInAccess = class DialInAccess {
|
|
20
21
|
kdb;
|
|
21
22
|
relay;
|
|
23
|
+
/**
|
|
24
|
+
* The gateway of this process, when it runs the gateway role: it registers itself at
|
|
25
|
+
* construction (`DialInGateway` sits above this module, so it cannot be injected here).
|
|
26
|
+
*/
|
|
27
|
+
streams;
|
|
22
28
|
constructor(kdb, relay) {
|
|
23
29
|
this.kdb = kdb;
|
|
24
30
|
this.relay = relay;
|
|
@@ -58,6 +64,23 @@ let DialInAccess = class DialInAccess {
|
|
|
58
64
|
stop(deviceId, reason) {
|
|
59
65
|
return this.relay.stop(deviceId, reason);
|
|
60
66
|
}
|
|
67
|
+
/** @internal the gateway of this process serves the streams of the sockets it holds. */
|
|
68
|
+
serveStreams(opener) {
|
|
69
|
+
this.streams = opener;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Opens a stream on the machine's socket, which only the gateway replica holding it can do
|
|
73
|
+
* (`DialInGateway.openStream`). A process without the gateway role throws
|
|
74
|
+
* `DialInStreamElsewhereError` when some replica holds the machine, `DeviceOfflineError` when
|
|
75
|
+
* none does.
|
|
76
|
+
*/
|
|
77
|
+
async openStream(deviceId, body, signal) {
|
|
78
|
+
if (this.streams)
|
|
79
|
+
return this.streams.openStream(deviceId, body, signal);
|
|
80
|
+
if (await this.relay.online(deviceId))
|
|
81
|
+
throw new DialInStreamElsewhereError(deviceId);
|
|
82
|
+
throw new DeviceOfflineError(deviceId);
|
|
83
|
+
}
|
|
61
84
|
};
|
|
62
85
|
DialInAccess = __decorate([
|
|
63
86
|
Injectable(),
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { type ExtensionContext } from "@capybara-hq/plugin-sdk";
|
|
1
|
+
import { type DeviceStream, type ExtensionContext } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import type { WebSocket } from "@fastify/websocket";
|
|
3
3
|
import type { Redis } from "ioredis";
|
|
4
4
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
5
5
|
import { LockService } from "../infra/lock/lock.service.js";
|
|
6
6
|
import type { KernelLogger } from "../log.js";
|
|
7
|
+
import { DialInAccess } from "./access.js";
|
|
7
8
|
import { DialInHandlers, type DialInServing, type DialInUnavailable } from "./handlers.js";
|
|
8
9
|
import { DialInMachines, type MachineIdentity } from "./machines.js";
|
|
9
10
|
/** WebSocket close codes the gateway uses (the program reads 4002 and 4003). */
|
|
@@ -54,6 +55,8 @@ declare class DeviceConnection {
|
|
|
54
55
|
private readonly credential;
|
|
55
56
|
/** The protocol the route admitted (the serving provider's `permissions.dialIn.protocol`). */
|
|
56
57
|
private readonly protocol;
|
|
58
|
+
/** The local port the socket arrived on (the holder address's default port when unset). */
|
|
59
|
+
private readonly localPort;
|
|
57
60
|
readonly token: `${string}-${string}-${string}-${string}-${string}`;
|
|
58
61
|
state: State;
|
|
59
62
|
private lease;
|
|
@@ -79,7 +82,11 @@ declare class DeviceConnection {
|
|
|
79
82
|
private closeReason;
|
|
80
83
|
constructor(gw: DialInGateway, socket: WebSocket, identity: MachineIdentity, credential: string,
|
|
81
84
|
/** The protocol the route admitted (the serving provider's `permissions.dialIn.protocol`). */
|
|
82
|
-
protocol: string
|
|
85
|
+
protocol: string,
|
|
86
|
+
/** The local port the socket arrived on (the holder address's default port when unset). */
|
|
87
|
+
localPort: number | undefined);
|
|
88
|
+
/** This connection's streams (the socket's own state, ended with it). */
|
|
89
|
+
private readonly streams;
|
|
83
90
|
/**
|
|
84
91
|
* The id a connection fences requests and results with (sent to the machine in `ready`).
|
|
85
92
|
* Random and separate from the lease token, which stays internal to the kernel.
|
|
@@ -93,6 +100,15 @@ declare class DeviceConnection {
|
|
|
93
100
|
/** Consecutive failed capacity publications on ping (this socket's own state). */
|
|
94
101
|
private publishFailures;
|
|
95
102
|
private publishCapacity;
|
|
103
|
+
/**
|
|
104
|
+
* Where other replicas hop a device stream to: the holder record `{ token, address }` next to
|
|
105
|
+
* the lease (written at the claim, refreshed with the capacity), read only under that token.
|
|
106
|
+
*/
|
|
107
|
+
private writeAddress;
|
|
108
|
+
/** Whether this connection holds its device and sent `ready` (streams may open). */
|
|
109
|
+
get serving(): boolean;
|
|
110
|
+
/** Opens a stream to the machine on this socket ({@link DialInStreams.openStream}). */
|
|
111
|
+
openStream(body: unknown, signal: AbortSignal): Promise<DeviceStream>;
|
|
96
112
|
get deviceId(): string;
|
|
97
113
|
/**
|
|
98
114
|
* Runs `fn` in the device's org (RLS spec §5.3: per-event work of a long connection enters the
|
|
@@ -175,8 +191,11 @@ export type DialInAdmission = {
|
|
|
175
191
|
* request's deadline plus a margin). A `res` is accepted only for a request taken for the socket's
|
|
176
192
|
* device: it is stored under `capk:device-res:<id>` for the rest of that TTL and published on
|
|
177
193
|
* `device.res.<id>`. An `event` goes to the provider's `onFrame`; the close to its `onClose`.
|
|
178
|
-
* `device.revoked.<deviceId>` closes the connection of that machine only (ruling R16).
|
|
179
|
-
*
|
|
194
|
+
* `device.revoked.<deviceId>` closes the connection of that machine only (ruling R16). Device
|
|
195
|
+
* streams ({@link DialInStreams}) run straight over the socket, so only the holder opens them; it
|
|
196
|
+
* writes its internal address under `capk:device-holder-addr:<deviceId>` next to the lease for
|
|
197
|
+
* the other replicas to hop to. The sockets are this process's own; everything other replicas
|
|
198
|
+
* need is in Redis.
|
|
180
199
|
*/
|
|
181
200
|
export declare class DialInGateway {
|
|
182
201
|
readonly machines: Pick<DialInMachines, "authenticate" | "isDeviceDeleted" | "recordConnect" | "touch">;
|
|
@@ -191,9 +210,32 @@ export declare class DialInGateway {
|
|
|
191
210
|
private stopping;
|
|
192
211
|
/** How often connections are pinged ({@link PING_INTERVAL_MS}; a test seam). */
|
|
193
212
|
pingIntervalMs: number;
|
|
213
|
+
/** How long a machine has to answer a stream open ({@link STREAM_OPEN_TIMEOUT_MS}; test seam). */
|
|
214
|
+
streamOpenTimeoutMs: number;
|
|
194
215
|
/** How often a held connection re-checks its credential ({@link REAUTH_EVERY_MS}; test seam). */
|
|
195
216
|
reauthEveryMs: number;
|
|
196
|
-
constructor(machines: Pick<DialInMachines, "authenticate" | "isDeviceDeleted" | "recordConnect" | "touch">, handlers: Pick<DialInHandlers, "forDevice">, locks: Pick<LockService, "hold">, bus: ExtensionContext["bus"], redis: Redis, config: KernelConfigService, log: Pick<KernelLogger, "info" | "warn">);
|
|
217
|
+
constructor(machines: Pick<DialInMachines, "authenticate" | "isDeviceDeleted" | "recordConnect" | "touch">, handlers: Pick<DialInHandlers, "forDevice">, locks: Pick<LockService, "hold">, bus: ExtensionContext["bus"], redis: Redis, config: KernelConfigService, log: Pick<KernelLogger, "info" | "warn">, access: Pick<DialInAccess, "serveStreams">);
|
|
218
|
+
/**
|
|
219
|
+
* This replica's internal origin for device stream hops: `gateway.internalUrl`, else
|
|
220
|
+
* `http://<hostname>:<http.port>` (with `http.port` 0, the port the connection arrived on).
|
|
221
|
+
*/
|
|
222
|
+
internalAddress(localPort?: number): string;
|
|
223
|
+
/** The connection of `deviceId` this replica holds and serves, if any. */
|
|
224
|
+
private serving;
|
|
225
|
+
/** Whether this replica holds `deviceId`'s machine socket (past `ready`). */
|
|
226
|
+
holdsLocally(deviceId: string): boolean;
|
|
227
|
+
/**
|
|
228
|
+
* The internal address of the gateway replica holding `deviceId`'s machine
|
|
229
|
+
* (`capk:device-holder-addr:<deviceId>`, read under the current lease token), or null when no
|
|
230
|
+
* replica holds it or its holder has not recorded its address yet.
|
|
231
|
+
*/
|
|
232
|
+
holderAddress(deviceId: string): Promise<string | null>;
|
|
233
|
+
/**
|
|
234
|
+
* Opens a stream to `deviceId`'s machine over the socket this replica holds
|
|
235
|
+
* ({@link DialInStreams}). Throws `DialInStreamElsewhereError` when another replica holds it
|
|
236
|
+
* (hop to {@link holderAddress}), `DeviceOfflineError` when none does.
|
|
237
|
+
*/
|
|
238
|
+
openStream(deviceId: string, body: unknown, signal: AbortSignal): Promise<DeviceStream>;
|
|
197
239
|
graceMs(): number;
|
|
198
240
|
leaseTtlMs(): number;
|
|
199
241
|
maxFrameBytes(): number;
|
|
@@ -209,7 +251,7 @@ export declare class DialInGateway {
|
|
|
209
251
|
* so a credential revoked or a provider switched off since the upgrade check never gets a
|
|
210
252
|
* connection.
|
|
211
253
|
*/
|
|
212
|
-
accept(socket: WebSocket, credential: string, protocol: string): Promise<void>;
|
|
254
|
+
accept(socket: WebSocket, credential: string, protocol: string, localPort?: number): Promise<void>;
|
|
213
255
|
/**
|
|
214
256
|
* How many devices this process holds the connection of (replica presence reports it): only
|
|
215
257
|
* sockets past the hello that hold their device's lease, so a socket still claiming or being
|
package/dist/dial-in/gateway.js
CHANGED
|
@@ -8,17 +8,20 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
8
8
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
9
|
};
|
|
10
10
|
import { randomUUID } from "node:crypto";
|
|
11
|
-
import {
|
|
11
|
+
import { hostname } from "node:os";
|
|
12
|
+
import { DeviceOfflineError, DIAL_IN_PROTOCOL_RE, DialInStreamElsewhereError, parseDialInMachineFrame, } from "@capybara-hq/plugin-sdk";
|
|
12
13
|
import { Inject, Injectable } from "@nestjs/common";
|
|
13
14
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
14
15
|
import { asPlatform, withOrgScope, withoutOrgScope } from "../infra/database/org-scope.js";
|
|
15
16
|
import { LockService } from "../infra/lock/lock.service.js";
|
|
16
17
|
import { KERNEL_BUS, KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
|
|
18
|
+
import { DialInAccess } from "./access.js";
|
|
17
19
|
import { storedResult, wireFrameOf } from "./envelope.js";
|
|
18
20
|
import { DialInHandlers } from "./handlers.js";
|
|
19
|
-
import { DEVICE_TAKEN_PREFIX, deviceLeaseKey, deviceReqKey, deviceReqTopic, deviceResKey, deviceResTopic, deviceRevokedTopic, deviceTakenKey, deviceTakeoverTopic, deviceTransportKey, } from "./keys.js";
|
|
21
|
+
import { DEVICE_TAKEN_PREFIX, deviceHolderAddrKey, deviceLeaseKey, deviceReqKey, deviceReqTopic, deviceResKey, deviceResTopic, deviceRevokedTopic, deviceTakenKey, deviceTakeoverTopic, deviceTransportKey, } from "./keys.js";
|
|
20
22
|
import { DialInMachines } from "./machines.js";
|
|
21
23
|
import { LIST_TTL_MARGIN_MS } from "./relay.js";
|
|
24
|
+
import { DialInStreams, isStreamFrame, STREAM_OPEN_TIMEOUT_MS } from "./streams.js";
|
|
22
25
|
/** WebSocket close codes the gateway uses (the program reads 4002 and 4003). */
|
|
23
26
|
export const DEVICE_CLOSE = {
|
|
24
27
|
/** The kernel is shutting down: reconnect (another gateway replica takes over). */
|
|
@@ -108,6 +111,41 @@ redis.call('SET', KEYS[2], ARGV[2], 'PX', ttl)
|
|
|
108
111
|
redis.call('DEL', KEYS[1])
|
|
109
112
|
return 1
|
|
110
113
|
`;
|
|
114
|
+
/**
|
|
115
|
+
* Writes the holder record `ARGV[2]` (`{ token, address }`) under `KEYS[2]` for `ARGV[3]` ms, only
|
|
116
|
+
* while the lease `KEYS[1]` is held by the token `ARGV[1]` (a connection that lost its lease never
|
|
117
|
+
* overwrites its successor's address). Returns 1 when written.
|
|
118
|
+
*/
|
|
119
|
+
const WRITE_ADDR = `
|
|
120
|
+
if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end
|
|
121
|
+
redis.call('SET', KEYS[2], ARGV[2], 'PX', ARGV[3])
|
|
122
|
+
return 1
|
|
123
|
+
`;
|
|
124
|
+
/**
|
|
125
|
+
* Reads the lease `KEYS[1]` and the holder record `KEYS[2]` in one step: the record's address
|
|
126
|
+
* only when its token is the current lease's (an expired lease or a takeover whose holder has not
|
|
127
|
+
* written its address yet answers nothing, never a gone or replaced replica's address).
|
|
128
|
+
*/
|
|
129
|
+
const READ_ADDR = `
|
|
130
|
+
local holder = redis.call('GET', KEYS[1])
|
|
131
|
+
if not holder then return false end
|
|
132
|
+
local raw = redis.call('GET', KEYS[2])
|
|
133
|
+
if not raw then return false end
|
|
134
|
+
local ok, rec = pcall(cjson.decode, raw)
|
|
135
|
+
if not ok or type(rec) ~= 'table' or rec.token ~= holder or type(rec.address) ~= 'string' then
|
|
136
|
+
return false
|
|
137
|
+
end
|
|
138
|
+
return rec.address
|
|
139
|
+
`;
|
|
140
|
+
/**
|
|
141
|
+
* Deletes the holder's address `KEYS[2]` once the lease `KEYS[1]` is free or still the token
|
|
142
|
+
* `ARGV[1]`'s: a successor that already claimed the lease keeps the address it writes.
|
|
143
|
+
*/
|
|
144
|
+
const DELETE_ADDR = `
|
|
145
|
+
local holder = redis.call('GET', KEYS[1])
|
|
146
|
+
if holder and holder ~= ARGV[1] then return 0 end
|
|
147
|
+
return redis.call('DEL', KEYS[2])
|
|
148
|
+
`;
|
|
111
149
|
const errMsg = (e) => (e instanceof Error ? e.message : String(e));
|
|
112
150
|
/** A WebSocket close reason is at most 123 UTF-8 bytes. */
|
|
113
151
|
const closeReason = (text) => {
|
|
@@ -126,6 +164,7 @@ class DeviceConnection {
|
|
|
126
164
|
identity;
|
|
127
165
|
credential;
|
|
128
166
|
protocol;
|
|
167
|
+
localPort;
|
|
129
168
|
token = randomUUID();
|
|
130
169
|
state = "hello";
|
|
131
170
|
lease;
|
|
@@ -151,13 +190,27 @@ class DeviceConnection {
|
|
|
151
190
|
closeReason = "offline";
|
|
152
191
|
constructor(gw, socket, identity, credential,
|
|
153
192
|
/** The protocol the route admitted (the serving provider's `permissions.dialIn.protocol`). */
|
|
154
|
-
protocol
|
|
193
|
+
protocol,
|
|
194
|
+
/** The local port the socket arrived on (the holder address's default port when unset). */
|
|
195
|
+
localPort) {
|
|
155
196
|
this.gw = gw;
|
|
156
197
|
this.socket = socket;
|
|
157
198
|
this.identity = identity;
|
|
158
199
|
this.credential = credential;
|
|
159
200
|
this.protocol = protocol;
|
|
201
|
+
this.localPort = localPort;
|
|
202
|
+
this.streams = new DialInStreams(identity.deviceId, {
|
|
203
|
+
send: (text) => {
|
|
204
|
+
if (this.state === "closed" || this.socket.readyState !== this.socket.OPEN)
|
|
205
|
+
return false;
|
|
206
|
+
this.socket.send(text);
|
|
207
|
+
return true;
|
|
208
|
+
},
|
|
209
|
+
maxFrameBytes: () => this.effectiveCap ?? 0,
|
|
210
|
+
}, () => this.gw.streamOpenTimeoutMs);
|
|
160
211
|
}
|
|
212
|
+
/** This connection's streams (the socket's own state, ended with it). */
|
|
213
|
+
streams;
|
|
161
214
|
/**
|
|
162
215
|
* The id a connection fences requests and results with (sent to the machine in `ready`).
|
|
163
216
|
* Random and separate from the lease token, which stays internal to the kernel.
|
|
@@ -177,11 +230,30 @@ class DeviceConnection {
|
|
|
177
230
|
await this.close(DEVICE_CLOSE.protocol, "Frame capacity changed; reconnect");
|
|
178
231
|
return;
|
|
179
232
|
}
|
|
233
|
+
const ttl = Math.max(this.gw.leaseTtlMs(), this.gw.pingIntervalMs * 3);
|
|
180
234
|
await this.gw.redis.set(deviceTransportKey(this.deviceId, this.token), JSON.stringify({
|
|
181
235
|
connectionId: this.connectionId,
|
|
182
236
|
maxFrameBytes: this.effectiveCap,
|
|
183
237
|
...(this.programRunId !== undefined && { programRunId: this.programRunId }),
|
|
184
|
-
}), "PX",
|
|
238
|
+
}), "PX", ttl);
|
|
239
|
+
await this.writeAddress();
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Where other replicas hop a device stream to: the holder record `{ token, address }` next to
|
|
243
|
+
* the lease (written at the claim, refreshed with the capacity), read only under that token.
|
|
244
|
+
*/
|
|
245
|
+
async writeAddress() {
|
|
246
|
+
await this.gw.redis.eval(WRITE_ADDR, 2, deviceLeaseKey(this.deviceId), deviceHolderAddrKey(this.deviceId), this.token, JSON.stringify({ token: this.token, address: this.gw.internalAddress(this.localPort) }), String(Math.max(this.gw.leaseTtlMs(), this.gw.pingIntervalMs * 3)));
|
|
247
|
+
}
|
|
248
|
+
/** Whether this connection holds its device and sent `ready` (streams may open). */
|
|
249
|
+
get serving() {
|
|
250
|
+
return this.state === "holding" && this.ready;
|
|
251
|
+
}
|
|
252
|
+
/** Opens a stream to the machine on this socket ({@link DialInStreams.openStream}). */
|
|
253
|
+
openStream(body, signal) {
|
|
254
|
+
if (!this.serving)
|
|
255
|
+
return Promise.reject(new DeviceOfflineError(this.deviceId));
|
|
256
|
+
return this.streams.openStream(body, signal);
|
|
185
257
|
}
|
|
186
258
|
get deviceId() {
|
|
187
259
|
return this.identity.deviceId;
|
|
@@ -296,6 +368,11 @@ class DeviceConnection {
|
|
|
296
368
|
this.close(DEVICE_CLOSE.protocol, "hello expected");
|
|
297
369
|
return;
|
|
298
370
|
}
|
|
371
|
+
// stream frames go to this socket's stream table, never through shared state
|
|
372
|
+
if (isStreamFrame(frame)) {
|
|
373
|
+
this.streams.onFrame(frame);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
299
376
|
// results are stored in any state after ready: the program sends those it kept while
|
|
300
377
|
// disconnected right after its ready
|
|
301
378
|
await this.store(frame);
|
|
@@ -481,6 +558,7 @@ class DeviceConnection {
|
|
|
481
558
|
return false;
|
|
482
559
|
}
|
|
483
560
|
lease.lost.addEventListener("abort", onLost, { once: true });
|
|
561
|
+
await this.writeAddress();
|
|
484
562
|
await this.subscribe(deviceReqTopic(env), () => this.drain());
|
|
485
563
|
await this.subscribe(deviceRevokedTopic(env), (p) => {
|
|
486
564
|
const message = p;
|
|
@@ -690,6 +768,7 @@ class DeviceConnection {
|
|
|
690
768
|
this.state = "closed";
|
|
691
769
|
this.ready = false;
|
|
692
770
|
this.ended.abort();
|
|
771
|
+
this.streams.closeAll();
|
|
693
772
|
clearTimeout(this.helloTimer);
|
|
694
773
|
clearTimeout(this.pingTimer);
|
|
695
774
|
const lease = this.lease;
|
|
@@ -701,6 +780,7 @@ class DeviceConnection {
|
|
|
701
780
|
lease.abandon();
|
|
702
781
|
else
|
|
703
782
|
await lease.release();
|
|
783
|
+
await this.gw.redis.eval(DELETE_ADDR, 2, deviceLeaseKey(this.deviceId), deviceHolderAddrKey(this.deviceId), this.token);
|
|
704
784
|
}
|
|
705
785
|
}
|
|
706
786
|
catch (e) {
|
|
@@ -760,8 +840,11 @@ class DeviceConnection {
|
|
|
760
840
|
* request's deadline plus a margin). A `res` is accepted only for a request taken for the socket's
|
|
761
841
|
* device: it is stored under `capk:device-res:<id>` for the rest of that TTL and published on
|
|
762
842
|
* `device.res.<id>`. An `event` goes to the provider's `onFrame`; the close to its `onClose`.
|
|
763
|
-
* `device.revoked.<deviceId>` closes the connection of that machine only (ruling R16).
|
|
764
|
-
*
|
|
843
|
+
* `device.revoked.<deviceId>` closes the connection of that machine only (ruling R16). Device
|
|
844
|
+
* streams ({@link DialInStreams}) run straight over the socket, so only the holder opens them; it
|
|
845
|
+
* writes its internal address under `capk:device-holder-addr:<deviceId>` next to the lease for
|
|
846
|
+
* the other replicas to hop to. The sockets are this process's own; everything other replicas
|
|
847
|
+
* need is in Redis.
|
|
765
848
|
*/
|
|
766
849
|
let DialInGateway = class DialInGateway {
|
|
767
850
|
machines;
|
|
@@ -776,9 +859,11 @@ let DialInGateway = class DialInGateway {
|
|
|
776
859
|
stopping = false;
|
|
777
860
|
/** How often connections are pinged ({@link PING_INTERVAL_MS}; a test seam). */
|
|
778
861
|
pingIntervalMs = PING_INTERVAL_MS;
|
|
862
|
+
/** How long a machine has to answer a stream open ({@link STREAM_OPEN_TIMEOUT_MS}; test seam). */
|
|
863
|
+
streamOpenTimeoutMs = STREAM_OPEN_TIMEOUT_MS;
|
|
779
864
|
/** How often a held connection re-checks its credential ({@link REAUTH_EVERY_MS}; test seam). */
|
|
780
865
|
reauthEveryMs = REAUTH_EVERY_MS;
|
|
781
|
-
constructor(machines, handlers, locks, bus, redis, config, log) {
|
|
866
|
+
constructor(machines, handlers, locks, bus, redis, config, log, access) {
|
|
782
867
|
this.machines = machines;
|
|
783
868
|
this.handlers = handlers;
|
|
784
869
|
this.locks = locks;
|
|
@@ -786,6 +871,55 @@ let DialInGateway = class DialInGateway {
|
|
|
786
871
|
this.redis = redis;
|
|
787
872
|
this.config = config;
|
|
788
873
|
this.log = log;
|
|
874
|
+
// ctx.dialIn.openStream on this process reaches the sockets this gateway holds
|
|
875
|
+
access.serveStreams(this);
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* This replica's internal origin for device stream hops: `gateway.internalUrl`, else
|
|
879
|
+
* `http://<hostname>:<http.port>` (with `http.port` 0, the port the connection arrived on).
|
|
880
|
+
*/
|
|
881
|
+
internalAddress(localPort) {
|
|
882
|
+
const c = this.config.get();
|
|
883
|
+
if (c.gateway.internalUrl !== undefined)
|
|
884
|
+
return c.gateway.internalUrl.replace(/\/+$/, "");
|
|
885
|
+
const port = c.http.port !== 0 ? c.http.port : (localPort ?? 0);
|
|
886
|
+
return `http://${hostname()}:${port}`;
|
|
887
|
+
}
|
|
888
|
+
/** The connection of `deviceId` this replica holds and serves, if any. */
|
|
889
|
+
serving(deviceId) {
|
|
890
|
+
for (const c of this.connections)
|
|
891
|
+
if (c.deviceId === deviceId && c.serving)
|
|
892
|
+
return c;
|
|
893
|
+
return undefined;
|
|
894
|
+
}
|
|
895
|
+
/** Whether this replica holds `deviceId`'s machine socket (past `ready`). */
|
|
896
|
+
holdsLocally(deviceId) {
|
|
897
|
+
return this.serving(deviceId) !== undefined;
|
|
898
|
+
}
|
|
899
|
+
/**
|
|
900
|
+
* The internal address of the gateway replica holding `deviceId`'s machine
|
|
901
|
+
* (`capk:device-holder-addr:<deviceId>`, read under the current lease token), or null when no
|
|
902
|
+
* replica holds it or its holder has not recorded its address yet.
|
|
903
|
+
*/
|
|
904
|
+
async holderAddress(deviceId) {
|
|
905
|
+
const r = await this.redis.eval(READ_ADDR, 2, deviceLeaseKey(deviceId), deviceHolderAddrKey(deviceId));
|
|
906
|
+
return typeof r === "string" ? r : null;
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* Opens a stream to `deviceId`'s machine over the socket this replica holds
|
|
910
|
+
* ({@link DialInStreams}). Throws `DialInStreamElsewhereError` when another replica holds it
|
|
911
|
+
* (hop to {@link holderAddress}), `DeviceOfflineError` when none does.
|
|
912
|
+
*/
|
|
913
|
+
async openStream(deviceId, body, signal) {
|
|
914
|
+
const conn = this.serving(deviceId);
|
|
915
|
+
if (conn !== undefined)
|
|
916
|
+
return conn.openStream(body, signal);
|
|
917
|
+
const holder = await this.redis.get(deviceLeaseKey(deviceId));
|
|
918
|
+
// a connection of this replica still claiming or before ready is not elsewhere
|
|
919
|
+
const mine = [...this.connections].some((c) => c.token === holder);
|
|
920
|
+
if (holder !== null && !mine)
|
|
921
|
+
throw new DialInStreamElsewhereError(deviceId);
|
|
922
|
+
throw new DeviceOfflineError(deviceId);
|
|
789
923
|
}
|
|
790
924
|
graceMs() {
|
|
791
925
|
return this.config.get().devices.dialIn.reconnectGraceSeconds * 1000;
|
|
@@ -819,7 +953,7 @@ let DialInGateway = class DialInGateway {
|
|
|
819
953
|
* so a credential revoked or a provider switched off since the upgrade check never gets a
|
|
820
954
|
* connection.
|
|
821
955
|
*/
|
|
822
|
-
async accept(socket, credential, protocol) {
|
|
956
|
+
async accept(socket, credential, protocol, localPort) {
|
|
823
957
|
socket.pause();
|
|
824
958
|
try {
|
|
825
959
|
if (this.stopping) {
|
|
@@ -843,7 +977,7 @@ let DialInGateway = class DialInGateway {
|
|
|
843
977
|
socket.close(DEVICE_CLOSE.protocol, "the device's provider is unavailable");
|
|
844
978
|
return;
|
|
845
979
|
}
|
|
846
|
-
const conn = new DeviceConnection(this, socket, admission.identity, credential, protocol);
|
|
980
|
+
const conn = new DeviceConnection(this, socket, admission.identity, credential, protocol, localPort);
|
|
847
981
|
this.connections.add(conn);
|
|
848
982
|
conn.start();
|
|
849
983
|
}
|
|
@@ -885,6 +1019,7 @@ DialInGateway = __decorate([
|
|
|
885
1019
|
__param(3, Inject(KERNEL_BUS)),
|
|
886
1020
|
__param(4, Inject(REDIS)),
|
|
887
1021
|
__param(5, Inject(KernelConfigService)),
|
|
888
|
-
__param(6, Inject(KERNEL_LOGGER))
|
|
1022
|
+
__param(6, Inject(KERNEL_LOGGER)),
|
|
1023
|
+
__param(7, Inject(DialInAccess))
|
|
889
1024
|
], DialInGateway);
|
|
890
1025
|
export { DialInGateway };
|
package/dist/dial-in/keys.d.ts
CHANGED
|
@@ -4,6 +4,13 @@
|
|
|
4
4
|
*/
|
|
5
5
|
/** The lease of the replica holding the machine's connection: `capk:device-lease:<deviceId>`. */
|
|
6
6
|
export declare const deviceLeaseKey: (deviceId: string) => string;
|
|
7
|
+
/**
|
|
8
|
+
* The internal address (`gateway.internalUrl`, or `http://<hostname>:<port>`) of the gateway
|
|
9
|
+
* replica holding the machine's connection, as `{ token, address }` with the holder's lease token:
|
|
10
|
+
* `capk:device-holder-addr:<deviceId>`. Written by the holder next to its lease, with a TTL, and
|
|
11
|
+
* read only while the lease still has that token; another replica hops a device stream there.
|
|
12
|
+
*/
|
|
13
|
+
export declare const deviceHolderAddrKey: (deviceId: string) => string;
|
|
7
14
|
/** The list of requests waiting for the machine: `capk:device-req:<deviceId>`. */
|
|
8
15
|
export declare const deviceReqKey: (deviceId: string) => string;
|
|
9
16
|
/** The result of one request: `capk:device-res:<requestId>`. */
|
package/dist/dial-in/keys.js
CHANGED
|
@@ -4,6 +4,13 @@
|
|
|
4
4
|
*/
|
|
5
5
|
/** The lease of the replica holding the machine's connection: `capk:device-lease:<deviceId>`. */
|
|
6
6
|
export const deviceLeaseKey = (deviceId) => `capk:device-lease:${deviceId}`;
|
|
7
|
+
/**
|
|
8
|
+
* The internal address (`gateway.internalUrl`, or `http://<hostname>:<port>`) of the gateway
|
|
9
|
+
* replica holding the machine's connection, as `{ token, address }` with the holder's lease token:
|
|
10
|
+
* `capk:device-holder-addr:<deviceId>`. Written by the holder next to its lease, with a TTL, and
|
|
11
|
+
* read only while the lease still has that token; another replica hops a device stream there.
|
|
12
|
+
*/
|
|
13
|
+
export const deviceHolderAddrKey = (deviceId) => `capk:device-holder-addr:${deviceId}`;
|
|
7
14
|
/** The list of requests waiting for the machine: `capk:device-req:<deviceId>`. */
|
|
8
15
|
export const deviceReqKey = (deviceId) => `capk:device-req:${deviceId}`;
|
|
9
16
|
/** The result of one request: `capk:device-res:<requestId>`. */
|
package/dist/dial-in/routes.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type WebSocket } from "@fastify/websocket";
|
|
2
2
|
import type { FastifyInstance, FastifyRequest } from "fastify";
|
|
3
|
+
import { type DeviceStreamRoutesOptions } from "../device-access/viewer-routes.js";
|
|
3
4
|
import type { DialInAdmission } from "./gateway.js";
|
|
4
5
|
/** The device connection route (environments spec §13.4). */
|
|
5
6
|
export declare const DEVICE_CONNECT_ROUTE = "/device/connect";
|
|
@@ -10,12 +11,17 @@ export interface DeviceRoutesGateway {
|
|
|
10
11
|
/** Who the credential stands for and the provider serving its device; null when unknown. */
|
|
11
12
|
admit(credential: string): Promise<DialInAdmission>;
|
|
12
13
|
/** Serves the upgraded socket (re-checks the credential with the socket paused). */
|
|
13
|
-
accept(socket: WebSocket, credential: string, protocol: string): Promise<void>;
|
|
14
|
+
accept(socket: WebSocket, credential: string, protocol: string, localPort?: number): Promise<void>;
|
|
14
15
|
}
|
|
15
16
|
export interface DeviceRoutesOptions {
|
|
16
17
|
gateway: DeviceRoutesGateway;
|
|
17
18
|
/** `devices.dialIn.maxFrameBytes`: a larger incoming frame closes the socket (1009). */
|
|
18
19
|
maxFrameBytes: number;
|
|
20
|
+
/**
|
|
21
|
+
* The device stream viewer routes (`GET /device/stream`, the hop route), registered in the same
|
|
22
|
+
* WebSocket scope when given (`@fastify/websocket` serves one upgrade listener per server).
|
|
23
|
+
*/
|
|
24
|
+
streams?: DeviceStreamRoutesOptions;
|
|
19
25
|
}
|
|
20
26
|
/**
|
|
21
27
|
* A WebSocket upgrade: `Upgrade` lists `websocket` and `Connection` lists `upgrade` (both
|
|
@@ -30,7 +36,8 @@ export declare function isWebSocketUpgrade(req: FastifyRequest): boolean;
|
|
|
30
36
|
*/
|
|
31
37
|
export declare function protocolMismatchMessage(plugin: string, expected: string, spoken: unknown): string;
|
|
32
38
|
/**
|
|
33
|
-
* Registers `GET /device/connect` (the gateway role only)
|
|
39
|
+
* Registers `GET /device/connect` (the gateway role only), and with `opts.streams` the device
|
|
40
|
+
* stream viewer routes (`device-access/viewer-routes.ts`), in its own encapsulated scope with
|
|
34
41
|
* `@fastify/websocket`: a raw Fastify route outside Nest, so neither the API's `AuthGuard` nor its
|
|
35
42
|
* CSRF check applies. Before the upgrade the route checks the machine credential (401
|
|
36
43
|
* `device.credential_invalid`), then the device's provider: off in the org, not loaded or not a
|
|
@@ -40,7 +47,8 @@ export declare function protocolMismatchMessage(plugin: string, expected: string
|
|
|
40
47
|
* Must be called before Nest `app.init()`, on the root instance.
|
|
41
48
|
*
|
|
42
49
|
* `@fastify/websocket` sends every upgrade request of the server through the Fastify router; the
|
|
43
|
-
* root hooks below keep that from reaching any other route: a WebSocket upgrade to
|
|
50
|
+
* root hooks below keep that from reaching any other route: a WebSocket upgrade to a path not in
|
|
51
|
+
* {@link UPGRADE_ROUTES}
|
|
44
52
|
* is answered 404 and its socket closed once answered (Node would have dropped it without a
|
|
45
53
|
* listener). Other upgrades (`h2c`) reach their route as ordinary requests; their socket, which
|
|
46
54
|
* no HTTP connection owns any more, is closed once answered as well (the upgrade is declined).
|
package/dist/dial-in/routes.js
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
import websocket, {} from "@fastify/websocket";
|
|
2
|
+
import { DEVICE_STREAM_HOP_ROUTE, DEVICE_STREAM_ROUTE, registerDeviceStreamRoutes, } from "../device-access/viewer-routes.js";
|
|
2
3
|
import { errorBody } from "../errors.js";
|
|
3
4
|
/** The device connection route (environments spec §13.4). */
|
|
4
5
|
export const DEVICE_CONNECT_ROUTE = "/device/connect";
|
|
5
6
|
/** The header carrying the dial-in protocol the program speaks (`<name>/<major>`). */
|
|
6
7
|
export const DEVICE_PROTOCOL_HEADER = "x-capybara-device-protocol";
|
|
8
|
+
/** The routes of the gateway role that accept a WebSocket upgrade. */
|
|
9
|
+
const UPGRADE_ROUTES = new Set([
|
|
10
|
+
DEVICE_CONNECT_ROUTE,
|
|
11
|
+
DEVICE_STREAM_ROUTE,
|
|
12
|
+
DEVICE_STREAM_HOP_ROUTE,
|
|
13
|
+
]);
|
|
7
14
|
/** The comma-separated tokens of a header, lowercased. */
|
|
8
15
|
function tokens(v) {
|
|
9
16
|
return [v ?? []]
|
|
@@ -54,7 +61,8 @@ export function protocolMismatchMessage(plugin, expected, spoken) {
|
|
|
54
61
|
return `This device is served by ${plugin}, which speaks ${expected}; ${said}. ${fix}`;
|
|
55
62
|
}
|
|
56
63
|
/**
|
|
57
|
-
* Registers `GET /device/connect` (the gateway role only)
|
|
64
|
+
* Registers `GET /device/connect` (the gateway role only), and with `opts.streams` the device
|
|
65
|
+
* stream viewer routes (`device-access/viewer-routes.ts`), in its own encapsulated scope with
|
|
58
66
|
* `@fastify/websocket`: a raw Fastify route outside Nest, so neither the API's `AuthGuard` nor its
|
|
59
67
|
* CSRF check applies. Before the upgrade the route checks the machine credential (401
|
|
60
68
|
* `device.credential_invalid`), then the device's provider: off in the org, not loaded or not a
|
|
@@ -64,14 +72,15 @@ export function protocolMismatchMessage(plugin, expected, spoken) {
|
|
|
64
72
|
* Must be called before Nest `app.init()`, on the root instance.
|
|
65
73
|
*
|
|
66
74
|
* `@fastify/websocket` sends every upgrade request of the server through the Fastify router; the
|
|
67
|
-
* root hooks below keep that from reaching any other route: a WebSocket upgrade to
|
|
75
|
+
* root hooks below keep that from reaching any other route: a WebSocket upgrade to a path not in
|
|
76
|
+
* {@link UPGRADE_ROUTES}
|
|
68
77
|
* is answered 404 and its socket closed once answered (Node would have dropped it without a
|
|
69
78
|
* listener). Other upgrades (`h2c`) reach their route as ordinary requests; their socket, which
|
|
70
79
|
* no HTTP connection owns any more, is closed once answered as well (the upgrade is declined).
|
|
71
80
|
*/
|
|
72
81
|
export async function registerDeviceConnectRoute(fastify, opts) {
|
|
73
82
|
fastify.addHook("onRequest", async (req, reply) => {
|
|
74
|
-
if (!isWebSocketUpgrade(req) || req.routeOptions.url
|
|
83
|
+
if (!isWebSocketUpgrade(req) || UPGRADE_ROUTES.has(req.routeOptions.url ?? ""))
|
|
75
84
|
return;
|
|
76
85
|
return reply
|
|
77
86
|
.code(404)
|
|
@@ -116,7 +125,9 @@ export async function registerDeviceConnectRoute(fastify, opts) {
|
|
|
116
125
|
socket.close(4400, "not authenticated");
|
|
117
126
|
return;
|
|
118
127
|
}
|
|
119
|
-
void opts.gateway.accept(socket, a.credential, a.protocol);
|
|
128
|
+
void opts.gateway.accept(socket, a.credential, a.protocol, req.socket.localPort);
|
|
120
129
|
});
|
|
130
|
+
if (opts.streams)
|
|
131
|
+
await registerDeviceStreamRoutes(scope, opts.streams);
|
|
121
132
|
});
|
|
122
133
|
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type DeviceStream, type DialInMachineFrame } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
/**
|
|
3
|
+
* The `code` of the error a stream's `send` rejects with when a message does not fit one frame
|
|
4
|
+
* once base64-encoded (the viewer endpoint answers it with 1009).
|
|
5
|
+
*/
|
|
6
|
+
export declare const DEVICE_STREAM_MESSAGE_TOO_BIG = "device.stream_message_too_big";
|
|
7
|
+
/** The stream frames a machine sends ({@link DialInStreams.onFrame}). */
|
|
8
|
+
export type DialInMachineStreamFrame = Extract<DialInMachineFrame, {
|
|
9
|
+
type: "stream-opened" | "stream-data" | "stream-credit" | "stream-close";
|
|
10
|
+
}>;
|
|
11
|
+
/** Whether a machine frame belongs to a stream (routed to {@link DialInStreams.onFrame}). */
|
|
12
|
+
export declare function isStreamFrame(frame: DialInMachineFrame): frame is DialInMachineStreamFrame;
|
|
13
|
+
/** What a connection's stream table needs from its socket. */
|
|
14
|
+
export interface DialInStreamTransport {
|
|
15
|
+
/** Sends one frame's text on the socket; false when the socket is no longer open. */
|
|
16
|
+
send(text: string): boolean;
|
|
17
|
+
/** The connection's negotiated frame capacity in UTF-8 bytes. */
|
|
18
|
+
maxFrameBytes(): number;
|
|
19
|
+
}
|
|
20
|
+
/** The reason every stream of a connection ends with when its socket closes. */
|
|
21
|
+
export declare const STREAM_OFFLINE_REASON = "device-offline";
|
|
22
|
+
/** How long the machine has to answer `stream-open` ({@link DialInStreams.openStream}). */
|
|
23
|
+
export declare const STREAM_OPEN_TIMEOUT_MS = 15000;
|
|
24
|
+
/**
|
|
25
|
+
* The streams of one machine connection on the gateway replica holding its socket (browser use
|
|
26
|
+
* spec §6.1): opened with `stream-open`, carried as `stream-data` frames straight over the socket
|
|
27
|
+
* (never through Redis or PG), each side sending only while it holds credit
|
|
28
|
+
* ({@link DIAL_IN_STREAM_INITIAL_CREDIT} at the open, one more per message the other side
|
|
29
|
+
* consumed). A data frame carries one whole message in base64; a message that does not fit the
|
|
30
|
+
* connection's frame capacity is refused, never split. The table is the connection's own state and
|
|
31
|
+
* lives exactly as long as the socket: its close ends every stream with
|
|
32
|
+
* {@link STREAM_OFFLINE_REASON}.
|
|
33
|
+
*/
|
|
34
|
+
export declare class DialInStreams {
|
|
35
|
+
private readonly deviceId;
|
|
36
|
+
private readonly transport;
|
|
37
|
+
/** How long the machine has to answer an open ({@link STREAM_OPEN_TIMEOUT_MS}). */
|
|
38
|
+
private readonly openTimeoutMs;
|
|
39
|
+
private readonly open;
|
|
40
|
+
/** Streams sent `stream-open` and not answered yet. */
|
|
41
|
+
private readonly opening;
|
|
42
|
+
private ended;
|
|
43
|
+
constructor(deviceId: string, transport: DialInStreamTransport,
|
|
44
|
+
/** How long the machine has to answer an open ({@link STREAM_OPEN_TIMEOUT_MS}). */
|
|
45
|
+
openTimeoutMs?: () => number);
|
|
46
|
+
/**
|
|
47
|
+
* Opens a stream: sends `stream-open` with `body` and resolves once the machine answered
|
|
48
|
+
* `stream-opened` ok. A refusal rejects with the machine's error; `signal` bounds the opening
|
|
49
|
+
* only (an abort sends `stream-close` and rejects with the signal's reason), and so does the
|
|
50
|
+
* kernel's own deadline ({@link STREAM_OPEN_TIMEOUT_MS}: `stream-close` and a clear error); the
|
|
51
|
+
* socket's close rejects with `DeviceOfflineError`.
|
|
52
|
+
*/
|
|
53
|
+
openStream(body: unknown, signal: AbortSignal): Promise<DeviceStream>;
|
|
54
|
+
/** A stream frame from the machine; a frame of a stream that is not open is dropped. */
|
|
55
|
+
onFrame(frame: DialInMachineStreamFrame): void;
|
|
56
|
+
/** The socket closed: every stream ends, every opening fails. */
|
|
57
|
+
closeAll(): void;
|
|
58
|
+
}
|