@capybara-hq/kernel 0.1.0-rc.85 → 0.1.0-rc.86
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/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
|
@@ -41,6 +41,9 @@ const LOGIN_MSG = "Too many failed login attempts; try again later";
|
|
|
41
41
|
* `app-auth-token-ip` the same way (the one-time code is 32 random bytes).
|
|
42
42
|
* `POST …/guides/:guideId/checks/:checkId/run` opts in to `setup-check` (setup guides v2 §10.3: each run may call a third party).
|
|
43
43
|
*
|
|
44
|
+
* `device-stream-ip` is not a Nest route limit either: the gateway's raw viewer route
|
|
45
|
+
* `GET /device/stream` reserves it before the upgrade (429 `rate_limited`).
|
|
46
|
+
*
|
|
44
47
|
* `plugin-public-write` is not a Nest route limit: the plugin dispatch counts it for unsafe
|
|
45
48
|
* methods on `public` extension routes (`PluginRouteAccess`).
|
|
46
49
|
*/
|
|
@@ -152,6 +155,19 @@ export const NAMED_THROTTLERS = [
|
|
|
152
155
|
message: "Too many device sign-in polls; try again later",
|
|
153
156
|
getTracker: ip,
|
|
154
157
|
},
|
|
158
|
+
// device stream viewer upgrades per client address (`GET /device/stream`, a raw gateway route
|
|
159
|
+
// reserving through CredentialThrottler before the upgrade): every attempt costs a ticket
|
|
160
|
+
// GETDEL, so an unauthenticated flood is bounded; a panel reconnects a few times a minute
|
|
161
|
+
{
|
|
162
|
+
name: "device-stream-ip",
|
|
163
|
+
group: "device-stream",
|
|
164
|
+
onSuccess: "refund",
|
|
165
|
+
limit: 120,
|
|
166
|
+
ttl: 60_000,
|
|
167
|
+
code: "rate_limited",
|
|
168
|
+
message: "Too many device stream connections; try again later",
|
|
169
|
+
getTracker: ip,
|
|
170
|
+
},
|
|
155
171
|
// native-app sign-in code exchanges per client address (@Throttled like device-token-ip): 60.
|
|
156
172
|
// The code is 32 random bytes and dies at its first try, so this only bounds the load
|
|
157
173
|
{
|
package/dist/kernel.module.js
CHANGED
|
@@ -12,6 +12,7 @@ import { ChannelsModule } from "./channels/channels.module.js";
|
|
|
12
12
|
import { ClientModule } from "./client/client.module.js";
|
|
13
13
|
import { PromptSuggestionsModule } from "./conversations/prompt-suggestions.js";
|
|
14
14
|
import { TitlesModule } from "./conversations/titles.js";
|
|
15
|
+
import { ExtensionDeviceAccessModule } from "./device-access/device-access.module.js";
|
|
15
16
|
import { BootstrapDefaultsService } from "./extensions/bootstrap-defaults.js";
|
|
16
17
|
import { ExtensionsModule } from "./extensions/extensions.module.js";
|
|
17
18
|
import { ApiModule } from "./http/api.module.js";
|
|
@@ -128,6 +129,8 @@ let KernelModule = KernelModule_1 = class KernelModule {
|
|
|
128
129
|
PluginRouteAccessModule,
|
|
129
130
|
// client extensions: the client builds stored with extension packages
|
|
130
131
|
ClientModule,
|
|
132
|
+
// ctx.deviceAccess: extensions' device services (the host finds it at the time of use)
|
|
133
|
+
ExtensionDeviceAccessModule,
|
|
131
134
|
// the Platform tool's operation registry and actor facts
|
|
132
135
|
PlatformModule,
|
|
133
136
|
// its operations (skills, agents, ...), registered at start on every role
|
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import type { ExtensionContext } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import { ChannelSupervisor } from "../channels/supervisor.js";
|
|
3
3
|
import { ChannelWebhooks } from "../channels/webhook.js";
|
|
4
|
+
import { DeviceStreamViewers } from "../device-access/viewer.js";
|
|
4
5
|
import { DialInGateway } from "../dial-in/gateway.js";
|
|
5
6
|
import { ExtensionHost } from "../extensions/host.js";
|
|
6
7
|
import type { GatewayRoutes } from "../http/gateway-routes.js";
|
|
7
8
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
9
|
+
import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
|
|
8
10
|
/**
|
|
9
11
|
* The gateway role's parts, driven by `KernelLifecycle` at fixed points of its start order and
|
|
10
12
|
* stop phases: the channel long-connection supervisor (leader election and share) and the webhook
|
|
11
13
|
* inbound (its raw Fastify route, {@link routes}, and its runtime cache's invalidation), and the
|
|
12
|
-
* device connections ({@link DialInGateway}, `GET /device/connect`)
|
|
14
|
+
* device connections ({@link DialInGateway}, `GET /device/connect`) and the device stream viewers
|
|
15
|
+
* ({@link DeviceStreamViewers}, `GET /device/stream`). Provided
|
|
13
16
|
* only by `GatewayModule`, so a process without the gateway role has none of them.
|
|
14
17
|
*/
|
|
15
18
|
export declare class GatewayRole {
|
|
@@ -19,6 +22,8 @@ export declare class GatewayRole {
|
|
|
19
22
|
private readonly supervisor;
|
|
20
23
|
private readonly webhooks;
|
|
21
24
|
private readonly devices;
|
|
25
|
+
private readonly viewers;
|
|
26
|
+
private readonly throttler;
|
|
22
27
|
/** The supervisor's subscription to extension instance changes. */
|
|
23
28
|
private unwatchPlugins;
|
|
24
29
|
private unwatchWebhooks;
|
|
@@ -26,10 +31,10 @@ export declare class GatewayRole {
|
|
|
26
31
|
private unsubscribeWebhooks;
|
|
27
32
|
/** The supervisor was started: the runs phase stops it. */
|
|
28
33
|
private supervisorStarted;
|
|
29
|
-
constructor(config: KernelConfigService, host: ExtensionHost, bus: Pick<ExtensionContext["bus"], "subscribe">, supervisor: ChannelSupervisor, webhooks: ChannelWebhooks, devices: DialInGateway);
|
|
34
|
+
constructor(config: KernelConfigService, host: ExtensionHost, bus: Pick<ExtensionContext["bus"], "subscribe">, supervisor: ChannelSupervisor, webhooks: ChannelWebhooks, devices: DialInGateway, viewers: DeviceStreamViewers, throttler: CredentialThrottler);
|
|
30
35
|
/**
|
|
31
|
-
* The gateway role's HTTP routes (the channel webhook, the device connection
|
|
32
|
-
* the app is built.
|
|
36
|
+
* The gateway role's HTTP routes (the channel webhook, the device connection, the device stream
|
|
37
|
+
* viewer), registered when the app is built.
|
|
33
38
|
*/
|
|
34
39
|
routes(): GatewayRoutes;
|
|
35
40
|
/**
|
|
@@ -46,8 +51,10 @@ export declare class GatewayRole {
|
|
|
46
51
|
/** Ends the webhook cache's `channel.changed` subscription. */
|
|
47
52
|
unsubscribe(): Promise<void>;
|
|
48
53
|
/**
|
|
49
|
-
* Closes the device
|
|
50
|
-
*
|
|
54
|
+
* Closes the device stream viewers (1001: the panels reconnect with a new ticket), then the
|
|
55
|
+
* device connections (1001) and hands their leases back, before the HTTP server closes (the
|
|
56
|
+
* machines reconnect to another gateway replica). Viewers first, so a viewer of a local device
|
|
57
|
+
* learns of the shutdown rather than of its machine going offline.
|
|
51
58
|
*/
|
|
52
59
|
stopDevices(): Promise<void>;
|
|
53
60
|
/**
|
|
@@ -11,15 +11,19 @@ import { Inject, Injectable } from "@nestjs/common";
|
|
|
11
11
|
import { CHANNEL_CHANGED_TOPIC } from "../channels/connections.service.js";
|
|
12
12
|
import { ChannelSupervisor } from "../channels/supervisor.js";
|
|
13
13
|
import { ChannelWebhooks } from "../channels/webhook.js";
|
|
14
|
+
import { DeviceStreamViewers } from "../device-access/viewer.js";
|
|
15
|
+
import { viewerThrottleOn } from "../device-access/viewer-routes.js";
|
|
14
16
|
import { DialInGateway } from "../dial-in/gateway.js";
|
|
15
17
|
import { ExtensionHost } from "../extensions/host.js";
|
|
16
18
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
19
|
+
import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
|
|
17
20
|
import { KERNEL_BUS } from "../infra/tokens.js";
|
|
18
21
|
/**
|
|
19
22
|
* The gateway role's parts, driven by `KernelLifecycle` at fixed points of its start order and
|
|
20
23
|
* stop phases: the channel long-connection supervisor (leader election and share) and the webhook
|
|
21
24
|
* inbound (its raw Fastify route, {@link routes}, and its runtime cache's invalidation), and the
|
|
22
|
-
* device connections ({@link DialInGateway}, `GET /device/connect`)
|
|
25
|
+
* device connections ({@link DialInGateway}, `GET /device/connect`) and the device stream viewers
|
|
26
|
+
* ({@link DeviceStreamViewers}, `GET /device/stream`). Provided
|
|
23
27
|
* only by `GatewayModule`, so a process without the gateway role has none of them.
|
|
24
28
|
*/
|
|
25
29
|
let GatewayRole = class GatewayRole {
|
|
@@ -29,6 +33,8 @@ let GatewayRole = class GatewayRole {
|
|
|
29
33
|
supervisor;
|
|
30
34
|
webhooks;
|
|
31
35
|
devices;
|
|
36
|
+
viewers;
|
|
37
|
+
throttler;
|
|
32
38
|
/** The supervisor's subscription to extension instance changes. */
|
|
33
39
|
unwatchPlugins;
|
|
34
40
|
unwatchWebhooks;
|
|
@@ -36,17 +42,19 @@ let GatewayRole = class GatewayRole {
|
|
|
36
42
|
unsubscribeWebhooks;
|
|
37
43
|
/** The supervisor was started: the runs phase stops it. */
|
|
38
44
|
supervisorStarted = false;
|
|
39
|
-
constructor(config, host, bus, supervisor, webhooks, devices) {
|
|
45
|
+
constructor(config, host, bus, supervisor, webhooks, devices, viewers, throttler) {
|
|
40
46
|
this.config = config;
|
|
41
47
|
this.host = host;
|
|
42
48
|
this.bus = bus;
|
|
43
49
|
this.supervisor = supervisor;
|
|
44
50
|
this.webhooks = webhooks;
|
|
45
51
|
this.devices = devices;
|
|
52
|
+
this.viewers = viewers;
|
|
53
|
+
this.throttler = throttler;
|
|
46
54
|
}
|
|
47
55
|
/**
|
|
48
|
-
* The gateway role's HTTP routes (the channel webhook, the device connection
|
|
49
|
-
* the app is built.
|
|
56
|
+
* The gateway role's HTTP routes (the channel webhook, the device connection, the device stream
|
|
57
|
+
* viewer), registered when the app is built.
|
|
50
58
|
*/
|
|
51
59
|
routes() {
|
|
52
60
|
const config = this.config.get();
|
|
@@ -56,6 +64,11 @@ let GatewayRole = class GatewayRole {
|
|
|
56
64
|
devices: {
|
|
57
65
|
gateway: this.devices,
|
|
58
66
|
maxFrameBytes: config.devices.dialIn.maxFrameBytes,
|
|
67
|
+
streams: {
|
|
68
|
+
viewers: this.viewers,
|
|
69
|
+
// per-client limit only when the client address is known (ruling R23)
|
|
70
|
+
...(viewerThrottleOn(config.http.trustProxy) && { throttler: this.throttler }),
|
|
71
|
+
},
|
|
59
72
|
},
|
|
60
73
|
};
|
|
61
74
|
}
|
|
@@ -100,11 +113,14 @@ let GatewayRole = class GatewayRole {
|
|
|
100
113
|
return this.unsubscribeWebhooks?.() ?? Promise.resolve();
|
|
101
114
|
}
|
|
102
115
|
/**
|
|
103
|
-
* Closes the device
|
|
104
|
-
*
|
|
116
|
+
* Closes the device stream viewers (1001: the panels reconnect with a new ticket), then the
|
|
117
|
+
* device connections (1001) and hands their leases back, before the HTTP server closes (the
|
|
118
|
+
* machines reconnect to another gateway replica). Viewers first, so a viewer of a local device
|
|
119
|
+
* learns of the shutdown rather than of its machine going offline.
|
|
105
120
|
*/
|
|
106
|
-
stopDevices() {
|
|
107
|
-
|
|
121
|
+
async stopDevices() {
|
|
122
|
+
await this.viewers.stop();
|
|
123
|
+
await this.devices.stop();
|
|
108
124
|
}
|
|
109
125
|
/**
|
|
110
126
|
* The runs phase: the supervisor aborts its connects and hands back its leases (undefined: never
|
|
@@ -121,6 +137,8 @@ GatewayRole = __decorate([
|
|
|
121
137
|
__param(2, Inject(KERNEL_BUS)),
|
|
122
138
|
__param(3, Inject(ChannelSupervisor)),
|
|
123
139
|
__param(4, Inject(ChannelWebhooks)),
|
|
124
|
-
__param(5, Inject(DialInGateway))
|
|
140
|
+
__param(5, Inject(DialInGateway)),
|
|
141
|
+
__param(6, Inject(DeviceStreamViewers)),
|
|
142
|
+
__param(7, Inject(CredentialThrottler))
|
|
125
143
|
], GatewayRole);
|
|
126
144
|
export { GatewayRole };
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* The gateway role (nest kernel spec §2), imported by `KernelModule` only when `roles` includes
|
|
3
3
|
* `gateway`: the channel long-connection supervisor, the webhook inbound (served as a raw Fastify
|
|
4
4
|
* route, `http/gateway-routes.ts`), the device connections ({@link DialInGateway}, `GET
|
|
5
|
-
* /device/connect`)
|
|
5
|
+
* /device/connect`), the device stream viewers ({@link DeviceStreamViewers}, `GET /device/stream`)
|
|
6
|
+
* and {@link GatewayRole}, which `KernelLifecycle` drives. It runs
|
|
6
7
|
* no cron and no queue consumer (those are the worker role's).
|
|
7
8
|
*/
|
|
8
9
|
export declare class GatewayModule {
|
|
@@ -8,23 +8,33 @@ import { Module } from "@nestjs/common";
|
|
|
8
8
|
import { ChannelsModule } from "../channels/channels.module.js";
|
|
9
9
|
import { ChannelSupervisor } from "../channels/supervisor.js";
|
|
10
10
|
import { ChannelWebhooks } from "../channels/webhook.js";
|
|
11
|
+
import { ExtensionDeviceAccessModule } from "../device-access/device-access.module.js";
|
|
12
|
+
import { DeviceStreamViewers } from "../device-access/viewer.js";
|
|
11
13
|
import { DialInModule } from "../dial-in/dial-in.module.js";
|
|
12
14
|
import { DialInGateway } from "../dial-in/gateway.js";
|
|
13
15
|
import { ExtensionsModule } from "../extensions/extensions.module.js";
|
|
16
|
+
import { SandboxModule } from "../sandbox/sandbox.module.js";
|
|
14
17
|
import { GatewayRole } from "./gateway-role.js";
|
|
15
18
|
/**
|
|
16
19
|
* The gateway role (nest kernel spec §2), imported by `KernelModule` only when `roles` includes
|
|
17
20
|
* `gateway`: the channel long-connection supervisor, the webhook inbound (served as a raw Fastify
|
|
18
21
|
* route, `http/gateway-routes.ts`), the device connections ({@link DialInGateway}, `GET
|
|
19
|
-
* /device/connect`)
|
|
22
|
+
* /device/connect`), the device stream viewers ({@link DeviceStreamViewers}, `GET /device/stream`)
|
|
23
|
+
* and {@link GatewayRole}, which `KernelLifecycle` drives. It runs
|
|
20
24
|
* no cron and no queue consumer (those are the worker role's).
|
|
21
25
|
*/
|
|
22
26
|
let GatewayModule = class GatewayModule {
|
|
23
27
|
};
|
|
24
28
|
GatewayModule = __decorate([
|
|
25
29
|
Module({
|
|
26
|
-
imports: [
|
|
27
|
-
|
|
30
|
+
imports: [
|
|
31
|
+
ChannelsModule,
|
|
32
|
+
ExtensionsModule,
|
|
33
|
+
DialInModule,
|
|
34
|
+
SandboxModule,
|
|
35
|
+
ExtensionDeviceAccessModule,
|
|
36
|
+
],
|
|
37
|
+
providers: [ChannelSupervisor, ChannelWebhooks, DialInGateway, DeviceStreamViewers, GatewayRole],
|
|
28
38
|
exports: [GatewayRole],
|
|
29
39
|
})
|
|
30
40
|
], GatewayModule);
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type DeviceServiceSpec, type DeviceServiceStatus } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { SandboxService } from "./sandbox.service.js";
|
|
3
|
+
import type { SandboxUseContext } from "./use-context.js";
|
|
4
|
+
/**
|
|
5
|
+
* Device services (browser use spec §5): one long-lived named process per device, started on an
|
|
6
|
+
* extension's behalf in the device's own sandbox with its own state directory, reached by
|
|
7
|
+
* request over its socket. Starting and requesting are uses of the device like any tool call
|
|
8
|
+
* ({@link SandboxService.withDeviceServices}: a suspended instance is resumed); stopping never
|
|
9
|
+
* starts or resumes one. A provider without the service methods is refused with
|
|
10
|
+
* `DeviceAccessError("capability_missing")` before the device is touched. The command review of a
|
|
11
|
+
* launch and the extension's permission are the caller's (`ctx.deviceAccess`).
|
|
12
|
+
*/
|
|
13
|
+
export declare class DeviceServices {
|
|
14
|
+
private readonly sandbox;
|
|
15
|
+
constructor(sandbox: SandboxService);
|
|
16
|
+
/**
|
|
17
|
+
* Starts the service in the device, or finds it running (the provider keeps a running one).
|
|
18
|
+
* With `ifRunning` it never starts one: a stopped service answers its `stopped` status, and the
|
|
19
|
+
* provider gets only the name ({@link nameOnlySpec}), as with every ifRunning ensure. A spec
|
|
20
|
+
* breaking {@link serviceSpecIssue} is refused before the device is touched.
|
|
21
|
+
*/
|
|
22
|
+
ensure(use: SandboxUseContext, spec: DeviceServiceSpec, signal: AbortSignal, opts?: {
|
|
23
|
+
ifRunning?: boolean;
|
|
24
|
+
}): Promise<DeviceServiceStatus>;
|
|
25
|
+
/**
|
|
26
|
+
* Applies the device's current limits to the service again when it runs (an `ifRunning`
|
|
27
|
+
* ensure; the device's allowlist changed); nothing when the instance or the service is not
|
|
28
|
+
* running, and it never resumes or starts anything. The status, or null without a running
|
|
29
|
+
* instance.
|
|
30
|
+
*/
|
|
31
|
+
refresh(use: SandboxUseContext, name: string, signal: AbortSignal): Promise<DeviceServiceStatus | null>;
|
|
32
|
+
/** One request to the service's socket; resolves its answer (throws when it is not running). */
|
|
33
|
+
request(use: SandboxUseContext, name: string, body: Uint8Array, timeoutMs: number, signal: AbortSignal): Promise<Uint8Array>;
|
|
34
|
+
/**
|
|
35
|
+
* The service's state without starting or resuming anything (the provider's `serviceStatus`);
|
|
36
|
+
* null when the device has no running instance (so no service runs) or the provider cannot
|
|
37
|
+
* tell (it lacks `serviceStatus`).
|
|
38
|
+
*/
|
|
39
|
+
status(use: SandboxUseContext, name: string, signal: AbortSignal): Promise<DeviceServiceStatus | null>;
|
|
40
|
+
/**
|
|
41
|
+
* Stops the service when the device's instance runs; nothing to do otherwise (a suspended or
|
|
42
|
+
* destroyed instance has no running service, and stopping never resumes it).
|
|
43
|
+
*/
|
|
44
|
+
stop(use: SandboxUseContext, name: string, signal: AbortSignal): Promise<void>;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* What every `ifRunning` ensure sends the provider: the service's name and nothing to run (the
|
|
48
|
+
* provider reads only the name there; a restart for a network change runs the spec the service
|
|
49
|
+
* was launched with, never a request's).
|
|
50
|
+
*/
|
|
51
|
+
export declare function nameOnlySpec(name: string): DeviceServiceSpec;
|
|
52
|
+
/**
|
|
53
|
+
* Why a service spec is refused, or null (browser use spec §5): a valid name; `entry` and every
|
|
54
|
+
* `files` key relative inside the state directory (no absolute path, no `.` / `..` / empty
|
|
55
|
+
* segment, no backslash, no NUL); `entry` one of the files; no env variable that changes what
|
|
56
|
+
* runs or that the provider sets (`NODE_*`, `PATH`, `SSL_CERT_FILE`, `SSL_CERT_DIR`,
|
|
57
|
+
* `OPENSSL_CONF`, `OPENSSL_ENGINES`, `LD_*`, `DYLD_*`, `CAPYBARA_*`, proxy variables), no NUL in
|
|
58
|
+
* a value. So the reviewed command is the one that runs.
|
|
59
|
+
*/
|
|
60
|
+
export declare function serviceSpecIssue(spec: DeviceServiceSpec): string | null;
|
|
61
|
+
/** Throws a TypeError naming what breaks {@link serviceSpecIssue}. */
|
|
62
|
+
export declare function assertServiceSpec(spec: DeviceServiceSpec): void;
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { DEVICE_SERVICE_NAME_RE, DeviceAccessError, } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
12
|
+
import { SandboxService } from "./sandbox.service.js";
|
|
13
|
+
/**
|
|
14
|
+
* Device services (browser use spec §5): one long-lived named process per device, started on an
|
|
15
|
+
* extension's behalf in the device's own sandbox with its own state directory, reached by
|
|
16
|
+
* request over its socket. Starting and requesting are uses of the device like any tool call
|
|
17
|
+
* ({@link SandboxService.withDeviceServices}: a suspended instance is resumed); stopping never
|
|
18
|
+
* starts or resumes one. A provider without the service methods is refused with
|
|
19
|
+
* `DeviceAccessError("capability_missing")` before the device is touched. The command review of a
|
|
20
|
+
* launch and the extension's permission are the caller's (`ctx.deviceAccess`).
|
|
21
|
+
*/
|
|
22
|
+
let DeviceServices = class DeviceServices {
|
|
23
|
+
sandbox;
|
|
24
|
+
constructor(sandbox) {
|
|
25
|
+
this.sandbox = sandbox;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Starts the service in the device, or finds it running (the provider keeps a running one).
|
|
29
|
+
* With `ifRunning` it never starts one: a stopped service answers its `stopped` status, and the
|
|
30
|
+
* provider gets only the name ({@link nameOnlySpec}), as with every ifRunning ensure. A spec
|
|
31
|
+
* breaking {@link serviceSpecIssue} is refused before the device is touched.
|
|
32
|
+
*/
|
|
33
|
+
async ensure(use, spec, signal, opts = {}) {
|
|
34
|
+
assertServiceSpec(spec);
|
|
35
|
+
return this.sandbox.withDeviceServices(use, requireServices, (h, p, sig) => opts.ifRunning === true
|
|
36
|
+
? p.ensureService(h, nameOnlySpec(spec.name), sig, {
|
|
37
|
+
ifRunning: true,
|
|
38
|
+
})
|
|
39
|
+
: p.ensureService(h, spec, sig), signal);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Applies the device's current limits to the service again when it runs (an `ifRunning`
|
|
43
|
+
* ensure; the device's allowlist changed); nothing when the instance or the service is not
|
|
44
|
+
* running, and it never resumes or starts anything. The status, or null without a running
|
|
45
|
+
* instance.
|
|
46
|
+
*/
|
|
47
|
+
async refresh(use, name, signal) {
|
|
48
|
+
assertServiceName(name);
|
|
49
|
+
const current = await this.sandbox.currentInstance(use.deviceId);
|
|
50
|
+
if (!current)
|
|
51
|
+
return null;
|
|
52
|
+
const r = await this.sandbox.ifRunning(use.deviceId, { createdAt: current.createdAt }, async (p, h, sig) => {
|
|
53
|
+
requireServices(p);
|
|
54
|
+
return p.ensureService(h, nameOnlySpec(name), sig, {
|
|
55
|
+
ifRunning: true,
|
|
56
|
+
});
|
|
57
|
+
}, signal);
|
|
58
|
+
return r.kind === "ran" ? r.value : null;
|
|
59
|
+
}
|
|
60
|
+
/** One request to the service's socket; resolves its answer (throws when it is not running). */
|
|
61
|
+
async request(use, name, body, timeoutMs, signal) {
|
|
62
|
+
assertServiceName(name);
|
|
63
|
+
return this.sandbox.withDeviceServices(use, requireServices, (h, p, sig) => p.serviceRequest(h, name, body, {
|
|
64
|
+
timeoutMs,
|
|
65
|
+
signal: sig,
|
|
66
|
+
}), signal);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The service's state without starting or resuming anything (the provider's `serviceStatus`);
|
|
70
|
+
* null when the device has no running instance (so no service runs) or the provider cannot
|
|
71
|
+
* tell (it lacks `serviceStatus`).
|
|
72
|
+
*/
|
|
73
|
+
async status(use, name, signal) {
|
|
74
|
+
assertServiceName(name);
|
|
75
|
+
const current = await this.sandbox.currentInstance(use.deviceId);
|
|
76
|
+
if (!current)
|
|
77
|
+
return null;
|
|
78
|
+
const r = await this.sandbox.ifRunning(use.deviceId, { createdAt: current.createdAt }, async (p, h, sig) => {
|
|
79
|
+
requireServices(p);
|
|
80
|
+
return p.serviceStatus ? p.serviceStatus(h, name, sig) : null;
|
|
81
|
+
}, signal);
|
|
82
|
+
return r.kind === "ran" ? r.value : null;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Stops the service when the device's instance runs; nothing to do otherwise (a suspended or
|
|
86
|
+
* destroyed instance has no running service, and stopping never resumes it).
|
|
87
|
+
*/
|
|
88
|
+
async stop(use, name, signal) {
|
|
89
|
+
assertServiceName(name);
|
|
90
|
+
const current = await this.sandbox.currentInstance(use.deviceId);
|
|
91
|
+
if (!current)
|
|
92
|
+
return;
|
|
93
|
+
await this.sandbox.ifRunning(use.deviceId, { createdAt: current.createdAt }, async (p, h, sig) => {
|
|
94
|
+
requireServices(p);
|
|
95
|
+
await p.stopService(h, name, sig);
|
|
96
|
+
}, signal);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
DeviceServices = __decorate([
|
|
100
|
+
Injectable(),
|
|
101
|
+
__param(0, Inject(SandboxService))
|
|
102
|
+
], DeviceServices);
|
|
103
|
+
export { DeviceServices };
|
|
104
|
+
/**
|
|
105
|
+
* What every `ifRunning` ensure sends the provider: the service's name and nothing to run (the
|
|
106
|
+
* provider reads only the name there; a restart for a network change runs the spec the service
|
|
107
|
+
* was launched with, never a request's).
|
|
108
|
+
*/
|
|
109
|
+
export function nameOnlySpec(name) {
|
|
110
|
+
return { name, runtime: "node", entry: "", args: [], files: {} };
|
|
111
|
+
}
|
|
112
|
+
/** Environment variables a service spec may not set: they change what runs, or are the provider's. */
|
|
113
|
+
const RESERVED_ENV = /^(NODE_.*|PATH|SSL_CERT_FILE|SSL_CERT_DIR|OPENSSL_CONF|OPENSSL_ENGINES|LD_.*|DYLD_.*|CAPYBARA_.*|(HTTPS?|NO|ALL|FTP)_PROXY)$/i;
|
|
114
|
+
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
115
|
+
/** Why a service file path is refused, or null: relative, plain segments only. */
|
|
116
|
+
function servicePathIssue(path) {
|
|
117
|
+
if (path === "")
|
|
118
|
+
return "is empty";
|
|
119
|
+
if (path.includes("\0"))
|
|
120
|
+
return "contains NUL";
|
|
121
|
+
if (path.includes("\\"))
|
|
122
|
+
return "contains a backslash";
|
|
123
|
+
if (path.startsWith("/"))
|
|
124
|
+
return "is absolute";
|
|
125
|
+
for (const seg of path.split("/")) {
|
|
126
|
+
if (seg === "")
|
|
127
|
+
return "has an empty segment";
|
|
128
|
+
if (seg === "." || seg === "..")
|
|
129
|
+
return `has a "${seg}" segment`;
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Why a service spec is refused, or null (browser use spec §5): a valid name; `entry` and every
|
|
135
|
+
* `files` key relative inside the state directory (no absolute path, no `.` / `..` / empty
|
|
136
|
+
* segment, no backslash, no NUL); `entry` one of the files; no env variable that changes what
|
|
137
|
+
* runs or that the provider sets (`NODE_*`, `PATH`, `SSL_CERT_FILE`, `SSL_CERT_DIR`,
|
|
138
|
+
* `OPENSSL_CONF`, `OPENSSL_ENGINES`, `LD_*`, `DYLD_*`, `CAPYBARA_*`, proxy variables), no NUL in
|
|
139
|
+
* a value. So the reviewed command is the one that runs.
|
|
140
|
+
*/
|
|
141
|
+
export function serviceSpecIssue(spec) {
|
|
142
|
+
if (typeof spec?.name !== "string" || !DEVICE_SERVICE_NAME_RE.test(spec.name))
|
|
143
|
+
return `the service name ${JSON.stringify(spec?.name)} must be 1 to 32 characters, a lower-case letter then lower-case letters, digits and "-"`;
|
|
144
|
+
if (typeof spec.entry !== "string")
|
|
145
|
+
return "entry must be a string";
|
|
146
|
+
const files = spec.files ?? {};
|
|
147
|
+
for (const key of Object.keys(files)) {
|
|
148
|
+
const why = servicePathIssue(key);
|
|
149
|
+
if (why !== null)
|
|
150
|
+
return `the file path ${JSON.stringify(key)} ${why}`;
|
|
151
|
+
}
|
|
152
|
+
const entryWhy = servicePathIssue(spec.entry);
|
|
153
|
+
if (entryWhy !== null)
|
|
154
|
+
return `the entry ${JSON.stringify(spec.entry)} ${entryWhy}`;
|
|
155
|
+
if (!Object.hasOwn(files, spec.entry))
|
|
156
|
+
return `the entry ${JSON.stringify(spec.entry)} is not one of the files`;
|
|
157
|
+
if (!Array.isArray(spec.args) || spec.args.some((a) => typeof a !== "string" || a.includes("\0")))
|
|
158
|
+
return "args must be strings without NUL";
|
|
159
|
+
for (const [k, v] of Object.entries(spec.env ?? {})) {
|
|
160
|
+
if (!ENV_NAME.test(k))
|
|
161
|
+
return `the env variable name ${JSON.stringify(k)} is not valid`;
|
|
162
|
+
if (RESERVED_ENV.test(k))
|
|
163
|
+
return `the env variable ${k} may not be set: it changes what runs, or the provider sets it`;
|
|
164
|
+
if (typeof v !== "string" || v.includes("\0"))
|
|
165
|
+
return `the env variable ${k} must be a string without NUL`;
|
|
166
|
+
}
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
/** Throws a TypeError naming what breaks {@link serviceSpecIssue}. */
|
|
170
|
+
export function assertServiceSpec(spec) {
|
|
171
|
+
const why = serviceSpecIssue(spec);
|
|
172
|
+
if (why !== null)
|
|
173
|
+
throw new TypeError(`Invalid device service spec: ${why}.`);
|
|
174
|
+
}
|
|
175
|
+
function assertServiceName(name) {
|
|
176
|
+
if (!DEVICE_SERVICE_NAME_RE.test(name))
|
|
177
|
+
throw new Error(`Invalid device service name ${JSON.stringify(name)}: use 1 to 32 characters, a lower-case letter then lower-case letters, digits and "-".`);
|
|
178
|
+
}
|
|
179
|
+
/** Refuses a provider that lacks any of the methods a service needs (`openStream` is optional). */
|
|
180
|
+
function requireServices(p) {
|
|
181
|
+
if (!p.ensureService || !p.stopService || !p.serviceRequest)
|
|
182
|
+
throw new DeviceAccessError("capability_missing", "This device's provider cannot run device services; choose a device on a provider that supports them.");
|
|
183
|
+
}
|
package/dist/sandbox/leases.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Redis } from "ioredis";
|
|
2
2
|
import { ApiError } from "../errors.js";
|
|
3
|
-
import { LockService } from "../infra/lock/lock.service.js";
|
|
3
|
+
import { type LeaseHandle, LockService } from "../infra/lock/lock.service.js";
|
|
4
4
|
import type { KernelLogger } from "../log.js";
|
|
5
5
|
/**
|
|
6
6
|
* Shared and exclusive sandbox leases (sub-agents spec §10.3; environments spec §4.2): the Redis
|
|
@@ -21,6 +21,14 @@ import type { KernelLogger } from "../log.js";
|
|
|
21
21
|
* killed by the next acquirer.
|
|
22
22
|
* - `capk:sandbox-path:<env>:<sha256hex(path)>`: a short per-path lease around the kernel's own
|
|
23
23
|
* read-modify-write of one file.
|
|
24
|
+
* - `capk:sandbox-streams:<env>`: sorted set of stream hold tokens scored by their expiry (an open
|
|
25
|
+
* viewer, {@link SandboxLeases.streamHold}). A hold is not a lease: it takes no slot and never
|
|
26
|
+
* blocks a lease. Idle suspension skips a device with a live hold; every exclusive acquisition
|
|
27
|
+
* deletes the set, and a hold's renewal fails once its token is gone or an intent is pending.
|
|
28
|
+
* That DEL is best effort: when it fails (logged), the device's holds stay until their next
|
|
29
|
+
* renewal fails (a later exclusive acquisition deleting the set, or an intent pending at a
|
|
30
|
+
* renewal), so a viewer may outlive that one lifecycle change. A renewal refused this way is a
|
|
31
|
+
* routine yield, logged at debug (`quietYield`), not a lost lock.
|
|
24
32
|
*
|
|
25
33
|
* The first three keys are a {@link LockService} shared lease (`tryShared` / `tryExclusive`,
|
|
26
34
|
* infra/lock/shared-lease.ts); the holder records and the path leases are this file's. Every key
|
|
@@ -124,6 +132,7 @@ export declare class SandboxLeases {
|
|
|
124
132
|
tryExclusive(env: string, o?: {
|
|
125
133
|
token?: string;
|
|
126
134
|
intent?: boolean;
|
|
135
|
+
unlessStreams?: boolean;
|
|
127
136
|
}): Promise<SandboxLease | null>;
|
|
128
137
|
/**
|
|
129
138
|
* One try at a shared lease (`cap` holders at most); null when it is not granted. `token` is the
|
|
@@ -140,6 +149,14 @@ export declare class SandboxLeases {
|
|
|
140
149
|
* bounds the record.
|
|
141
150
|
*/
|
|
142
151
|
registerHolder(env: string, token: string, ttlMs: number): Promise<void>;
|
|
152
|
+
/**
|
|
153
|
+
* A stream hold on the device (an open viewer): null while an exclusive lease is held or an
|
|
154
|
+
* intent is pending. Renewed every TTL / 3 by LockService's watchdog; `lost` aborts once a
|
|
155
|
+
* renewal fails (an exclusive acquisition ended the device's holds, or an intent is pending).
|
|
156
|
+
*/
|
|
157
|
+
streamHold(env: string): Promise<LeaseHandle | null>;
|
|
158
|
+
/** Live stream holds of the device ({@link streamHold}). */
|
|
159
|
+
streamHolds(env: string): Promise<number>;
|
|
143
160
|
/** Deletes a holder record (after its provider calls). */
|
|
144
161
|
unregisterHolder(env: string, token: string): Promise<void>;
|
|
145
162
|
/**
|
package/dist/sandbox/leases.js
CHANGED
|
@@ -32,6 +32,14 @@ import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
|
|
|
32
32
|
* killed by the next acquirer.
|
|
33
33
|
* - `capk:sandbox-path:<env>:<sha256hex(path)>`: a short per-path lease around the kernel's own
|
|
34
34
|
* read-modify-write of one file.
|
|
35
|
+
* - `capk:sandbox-streams:<env>`: sorted set of stream hold tokens scored by their expiry (an open
|
|
36
|
+
* viewer, {@link SandboxLeases.streamHold}). A hold is not a lease: it takes no slot and never
|
|
37
|
+
* blocks a lease. Idle suspension skips a device with a live hold; every exclusive acquisition
|
|
38
|
+
* deletes the set, and a hold's renewal fails once its token is gone or an intent is pending.
|
|
39
|
+
* That DEL is best effort: when it fails (logged), the device's holds stay until their next
|
|
40
|
+
* renewal fails (a later exclusive acquisition deleting the set, or an intent pending at a
|
|
41
|
+
* renewal), so a viewer may outlive that one lifecycle change. A renewal refused this way is a
|
|
42
|
+
* routine yield, logged at debug (`quietYield`), not a lost lock.
|
|
35
43
|
*
|
|
36
44
|
* The first three keys are a {@link LockService} shared lease (`tryShared` / `tryExclusive`,
|
|
37
45
|
* infra/lock/shared-lease.ts); the holder records and the path leases are this file's. Every key
|
|
@@ -47,6 +55,7 @@ const USERS_PREFIX = "capk:sandbox-users:";
|
|
|
47
55
|
const INTENT_PREFIX = "capk:sandbox-intent:";
|
|
48
56
|
const HOLDERS_PREFIX = "capk:sandbox-holders:";
|
|
49
57
|
const PATH_PREFIX = "capk:sandbox-path:";
|
|
58
|
+
const STREAMS_PREFIX = "capk:sandbox-streams:";
|
|
50
59
|
/** TTL of a path lease (ms); renewed while held. */
|
|
51
60
|
const PATH_LEASE_TTL_MS = 30_000;
|
|
52
61
|
/** Shortest life of an exclusive waiter's intent (ms): outlasts event-loop lag between polls. */
|
|
@@ -77,6 +86,33 @@ const REGISTER = redisClockScript(`local ttl = tonumber(ARGV[2])
|
|
|
77
86
|
redis.call('HSET', KEYS[1], ARGV[1], now + ttl)
|
|
78
87
|
if redis.call('PTTL', KEYS[1]) < ttl then redis.call('PEXPIRE', KEYS[1], ttl) end
|
|
79
88
|
return 1`);
|
|
89
|
+
/**
|
|
90
|
+
* KEYS lock, users, intent, streams; ARGV token, ttl. Adds a stream hold unless an exclusive lease
|
|
91
|
+
* is held or an intent is pending (0). The set is kept for its longest member.
|
|
92
|
+
*/
|
|
93
|
+
const STREAM_HOLD = sharedLeaseReadScript(`if redis.call('EXISTS', KEYS[3]) == 1 then return 0 end
|
|
94
|
+
if cur and cur ~= 'shared' then return 0 end
|
|
95
|
+
redis.call('ZREMRANGEBYSCORE', KEYS[4], '-inf', now)
|
|
96
|
+
redis.call('ZADD', KEYS[4], now + tonumber(ARGV[2]), ARGV[1])
|
|
97
|
+
local last = redis.call('ZRANGE', KEYS[4], -1, -1, 'WITHSCORES')
|
|
98
|
+
redis.call('PEXPIREAT', KEYS[4], tonumber(last[2]))
|
|
99
|
+
return 1`);
|
|
100
|
+
/**
|
|
101
|
+
* KEYS intent, streams; ARGV token, ttl. Renews a stream hold; 0 (lost) once an exclusive
|
|
102
|
+
* acquisition deleted it, it expired, or an intent is pending (the hold then yields).
|
|
103
|
+
*/
|
|
104
|
+
const STREAM_RENEW = redisClockScript(`if redis.call('EXISTS', KEYS[1]) == 1 then
|
|
105
|
+
redis.call('ZREM', KEYS[2], ARGV[1])
|
|
106
|
+
return 0
|
|
107
|
+
end
|
|
108
|
+
local score = redis.call('ZSCORE', KEYS[2], ARGV[1])
|
|
109
|
+
if not score or tonumber(score) <= now then return 0 end
|
|
110
|
+
redis.call('ZADD', KEYS[2], now + tonumber(ARGV[2]), ARGV[1])
|
|
111
|
+
local last = redis.call('ZRANGE', KEYS[2], -1, -1, 'WITHSCORES')
|
|
112
|
+
redis.call('PEXPIREAT', KEYS[2], tonumber(last[2]))
|
|
113
|
+
return 1`);
|
|
114
|
+
/** KEYS streams. The number of live stream holds. */
|
|
115
|
+
const STREAM_COUNT = redisClockScript(`return redis.call('ZCOUNT', KEYS[1], '(' .. now, '+inf')`);
|
|
80
116
|
/**
|
|
81
117
|
* KEYS lock, users, holders. Returns the holder fields without a live lease, leaving them in place
|
|
82
118
|
* (the caller forgets them only once their revocation is owed durably, {@link
|
|
@@ -220,7 +256,19 @@ let SandboxLeases = class SandboxLeases {
|
|
|
220
256
|
*/
|
|
221
257
|
async tryExclusive(env, o = {}) {
|
|
222
258
|
const h = await this.locks.tryExclusive(this.keys(env), o.token ?? randomUUID(), this.ttlMs, o.intent ? this.intentTtlMs : undefined);
|
|
223
|
-
|
|
259
|
+
if (!h)
|
|
260
|
+
return null;
|
|
261
|
+
// `unlessStreams` (the idle sweep): refused while the device has a live stream hold. Counted
|
|
262
|
+
// once the lock is held, when no new hold can be taken (a hold refuses a held lock)
|
|
263
|
+
if (o.unlessStreams && (await this.streamHolds(env)) > 0) {
|
|
264
|
+
await h.release();
|
|
265
|
+
return null;
|
|
266
|
+
}
|
|
267
|
+
// a lifecycle change: every stream hold of the device yields (its next renewal fails)
|
|
268
|
+
await this.redis
|
|
269
|
+
.eval("return redis.call('DEL', KEYS[1])", 1, `${STREAMS_PREFIX}${env}`)
|
|
270
|
+
.catch((err) => this.log.warn("cannot end the device's stream holds", { deviceId: env, err }));
|
|
271
|
+
return this.held(env, h);
|
|
224
272
|
}
|
|
225
273
|
/**
|
|
226
274
|
* One try at a shared lease (`cap` holders at most); null when it is not granted. `token` is the
|
|
@@ -246,6 +294,32 @@ let SandboxLeases = class SandboxLeases {
|
|
|
246
294
|
async registerHolder(env, token, ttlMs) {
|
|
247
295
|
await this.redis.eval(REGISTER, 1, `${HOLDERS_PREFIX}${env}`, token, ttlMs);
|
|
248
296
|
}
|
|
297
|
+
/**
|
|
298
|
+
* A stream hold on the device (an open viewer): null while an exclusive lease is held or an
|
|
299
|
+
* intent is pending. Renewed every TTL / 3 by LockService's watchdog; `lost` aborts once a
|
|
300
|
+
* renewal fails (an exclusive acquisition ended the device's holds, or an intent is pending).
|
|
301
|
+
*/
|
|
302
|
+
async streamHold(env) {
|
|
303
|
+
const k = this.keys(env);
|
|
304
|
+
const streams = `${STREAMS_PREFIX}${env}`;
|
|
305
|
+
const token = randomUUID();
|
|
306
|
+
const sentAt = Date.now();
|
|
307
|
+
const ok = await this.redis.eval(STREAM_HOLD, 4, k.lock, k.users, k.intent, streams, token, this.ttlMs);
|
|
308
|
+
if (ok !== 1)
|
|
309
|
+
return null;
|
|
310
|
+
return this.locks.keepAlive(streams, this.ttlMs, {
|
|
311
|
+
renew: async () => (await this.redis.eval(STREAM_RENEW, 2, k.intent, streams, token, this.ttlMs)) === 1,
|
|
312
|
+
release: async () => {
|
|
313
|
+
await this.redis.eval("return redis.call('ZREM', KEYS[1], ARGV[1])", 1, streams, token);
|
|
314
|
+
},
|
|
315
|
+
// a hold ending for a lifecycle change is routine, not a lost lock
|
|
316
|
+
quietYield: true,
|
|
317
|
+
}, sentAt);
|
|
318
|
+
}
|
|
319
|
+
/** Live stream holds of the device ({@link streamHold}). */
|
|
320
|
+
async streamHolds(env) {
|
|
321
|
+
return Number(await this.redis.eval(STREAM_COUNT, 1, `${STREAMS_PREFIX}${env}`));
|
|
322
|
+
}
|
|
249
323
|
/** Deletes a holder record (after its provider calls). */
|
|
250
324
|
async unregisterHolder(env, token) {
|
|
251
325
|
await this.redis.hdel(`${HOLDERS_PREFIX}${env}`, token);
|