@capybara-hq/kernel 0.1.0-rc.84 → 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/admin/admin.module.js +5 -0
- package/dist/admin/health.service.d.ts +2 -2
- package/dist/admin/health.service.js +10 -2
- package/dist/catalog/admin-catalog.controller.d.ts +2 -1
- package/dist/catalog/admin-catalog.controller.js +2 -1
- package/dist/catalog/catalog-content.d.ts +5 -15
- package/dist/catalog/catalog-content.js +5 -56
- package/dist/catalog/catalog-scope.service.d.ts +3 -3
- package/dist/catalog/catalog-scope.service.js +4 -3
- package/dist/catalog/catalog.module.d.ts +3 -1
- package/dist/catalog/catalog.module.js +14 -1
- package/dist/catalog/component-scope.service.d.ts +6 -1
- package/dist/catalog/component-scope.service.js +16 -2
- package/dist/catalog/job-ids.d.ts +29 -0
- package/dist/catalog/job-ids.js +29 -0
- package/dist/catalog/jobs.d.ts +12 -3
- package/dist/catalog/jobs.js +28 -7
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/catalog/org-catalog.controller.d.ts +2 -30
- package/dist/catalog/org-catalog.controller.js +3 -29
- package/dist/catalog/org-catalog.schemas.d.ts +9 -46
- package/dist/catalog/org-catalog.schemas.js +9 -23
- package/dist/catalog/org-catalog.service.js +14 -23
- package/dist/catalog/plugin-import.d.ts +21 -0
- package/dist/catalog/plugin-import.js +33 -3
- package/dist/catalog/plugin-install.d.ts +69 -76
- package/dist/catalog/plugin-install.js +156 -234
- package/dist/catalog/plugin-upgrade.d.ts +71 -11
- package/dist/catalog/plugin-upgrade.js +222 -43
- package/dist/catalog/scope-sync.d.ts +22 -20
- package/dist/catalog/scope-sync.js +57 -42
- package/dist/catalog/template-connector-ensure.d.ts +100 -0
- package/dist/catalog/template-connector-ensure.js +285 -0
- package/dist/catalog/template-connector-jobs.d.ts +28 -0
- package/dist/catalog/template-connector-jobs.js +54 -0
- package/dist/catalog/template-connector-reconcile.d.ts +44 -0
- package/dist/catalog/template-connector-reconcile.js +114 -0
- package/dist/catalog/template-connectors.processor.d.ts +32 -0
- package/dist/catalog/template-connectors.processor.js +101 -0
- 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/db/kernel-schema.d.ts +2 -1
- 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/org-config.d.ts +6 -1
- package/dist/extensions/org-config.js +15 -2
- 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/git/gateway.js +3 -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/outbox/registry.d.ts +28 -0
- package/dist/infra/outbox/registry.js +33 -0
- package/dist/infra/queue/queue-names.d.ts +1 -1
- package/dist/infra/queue/queue-names.js +2 -0
- 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/lifecycle/kernel-lifecycle.d.ts +8 -1
- package/dist/lifecycle/kernel-lifecycle.js +37 -11
- package/dist/orgs/org-owner.d.ts +7 -0
- package/dist/orgs/org-owner.js +16 -0
- package/dist/platform/operation.d.ts +3 -4
- package/dist/platform/ops/connectors.ops.js +8 -1
- package/dist/platform/ops/org-plugins.ops.d.ts +0 -9
- package/dist/platform/ops/org-plugins.ops.js +18 -235
- package/dist/platform/ops/plugins.ops.d.ts +0 -1
- package/dist/platform/ops/plugins.ops.js +3 -31
- 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/roles/worker-role.d.ts +9 -4
- package/dist/roles/worker-role.js +18 -5
- package/dist/roles/worker.module.d.ts +1 -1
- package/dist/roles/worker.module.js +8 -1
- 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/setup/setup-guides.service.d.ts +9 -1
- package/dist/setup/setup-guides.service.js +38 -8
- package/dist/tools/admin-connectors.d.ts +3 -2
- package/dist/tools/admin-connectors.js +5 -4
- 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/connector-setup.d.ts +28 -0
- package/dist/tools/connector-setup.js +33 -0
- package/dist/tools/connector-tools-jobs.d.ts +35 -0
- package/dist/tools/connector-tools-jobs.js +40 -0
- package/dist/tools/connector-tools.processor.d.ts +32 -0
- package/dist/tools/connector-tools.processor.js +97 -0
- package/dist/tools/connectors.controller.d.ts +1 -0
- package/dist/tools/connectors.schemas.d.ts +1 -0
- package/dist/tools/connectors.schemas.js +5 -0
- package/dist/tools/connectors.service.d.ts +138 -14
- package/dist/tools/connectors.service.js +410 -50
- package/dist/tools/credentials.d.ts +35 -0
- package/dist/tools/credentials.js +89 -1
- package/dist/tools/drift.d.ts +5 -0
- package/dist/tools/drift.js +21 -2
- package/dist/tools/editable-endpoint.d.ts +23 -0
- package/dist/tools/editable-endpoint.js +92 -0
- package/dist/tools/network-asks.d.ts +13 -0
- package/dist/tools/network-asks.js +26 -2
- package/dist/tools/oauth/flow.d.ts +1 -1
- package/dist/tools/oauth/flow.js +3 -2
- package/dist/tools/pipeline.d.ts +30 -1
- package/dist/tools/pipeline.js +299 -59
- package/dist/tools/questions.service.d.ts +24 -3
- package/dist/tools/questions.service.js +3 -1
- package/dist/tools/registry.d.ts +14 -2
- package/dist/tools/registry.js +27 -6
- package/dist/tools/tools.module.js +4 -0
- package/package.json +3 -3
- package/src/migrations/0183_connectors_created_by_nullable.sql +5 -0
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { PluginScopeSyncProcessor } from "../catalog/scope-sync-workers.js";
|
|
2
|
+
import { TemplateConnectorsProcessor } from "../catalog/template-connectors.processor.js";
|
|
2
3
|
import { ChannelsProcessor } from "../channels/channels.module.js";
|
|
3
4
|
import { ChannelOutbound } from "../channels/outbound.js";
|
|
4
5
|
import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
|
|
@@ -15,11 +16,12 @@ import { MaintenanceProcessor } from "../runtime/maintenance.js";
|
|
|
15
16
|
import { PromptSuggestionProcessor, RunsProcessor, SubagentRunsProcessor, TitleProcessor, UsageReportProcessor } from "../runtime/run-processors.js";
|
|
16
17
|
import { RunWorker } from "../runtime/run-worker.js";
|
|
17
18
|
import { UsageReporter } from "../runtime/usage-report.js";
|
|
19
|
+
import { ConnectorToolsProcessor } from "../tools/connector-tools.processor.js";
|
|
18
20
|
/**
|
|
19
21
|
* The worker role's parts, driven by `KernelLifecycle` at fixed points of its start order and stop
|
|
20
22
|
* phases (so they stay ordered after the extension load and before the extension host closes): the
|
|
21
23
|
* queue consumers (runs, sub-agent runs, evals, maintenance, the plugin scope sync, lifecycle
|
|
22
|
-
* hook deliveries, push deliveries, channel deliveries, `usage.report`, titles, prompt suggestions) and the schedulers of the `@LockedCron` / `@LockedInterval` jobs. Provided only by
|
|
24
|
+
* hook deliveries, push deliveries, connector tool listings, template connector ensures, channel deliveries, `usage.report`, titles, prompt suggestions) and the schedulers of the `@LockedCron` / `@LockedInterval` jobs. Provided only by
|
|
23
25
|
* `WorkerModule`, so a process without the worker role has none of them.
|
|
24
26
|
*/
|
|
25
27
|
export declare class WorkerRole {
|
|
@@ -43,13 +45,15 @@ export declare class WorkerRole {
|
|
|
43
45
|
private readonly scopeProcessor;
|
|
44
46
|
private readonly lifecycleProcessor;
|
|
45
47
|
private readonly pushProcessor;
|
|
48
|
+
private readonly connectorToolsProcessor;
|
|
49
|
+
private readonly templateConnectorsProcessor;
|
|
46
50
|
/** The startup config (the roles). */
|
|
47
51
|
private readonly config;
|
|
48
52
|
/** The run worker was started: the runs phase drains it. */
|
|
49
53
|
private runsStarted;
|
|
50
54
|
/** The eval worker was started: the runs phase drains it. */
|
|
51
55
|
private evalsStarted;
|
|
52
|
-
constructor(config: KernelConfigService, log: KernelLogger, intervals: LockedIntervalScheduler, scheduledRuns: ScheduledRuns, runWorker: RunWorker, evalWorker: EvalWorker, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelOutbound: ChannelOutbound, runsProcessor: RunsProcessor, subagentRunsProcessor: SubagentRunsProcessor, usageProcessor: UsageReportProcessor, titleProcessor: TitleProcessor, suggestionProcessor: PromptSuggestionProcessor, channelsProcessor: ChannelsProcessor, evalsProcessor: EvalsProcessor, maintenanceProcessor: MaintenanceProcessor, scopeProcessor: PluginScopeSyncProcessor, lifecycleProcessor: LifecycleHooksProcessor, pushProcessor: PushProcessor);
|
|
56
|
+
constructor(config: KernelConfigService, log: KernelLogger, intervals: LockedIntervalScheduler, scheduledRuns: ScheduledRuns, runWorker: RunWorker, evalWorker: EvalWorker, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelOutbound: ChannelOutbound, runsProcessor: RunsProcessor, subagentRunsProcessor: SubagentRunsProcessor, usageProcessor: UsageReportProcessor, titleProcessor: TitleProcessor, suggestionProcessor: PromptSuggestionProcessor, channelsProcessor: ChannelsProcessor, evalsProcessor: EvalsProcessor, maintenanceProcessor: MaintenanceProcessor, scopeProcessor: PluginScopeSyncProcessor, lifecycleProcessor: LifecycleHooksProcessor, pushProcessor: PushProcessor, connectorToolsProcessor: ConnectorToolsProcessor, templateConnectorsProcessor: TemplateConnectorsProcessor);
|
|
53
57
|
/**
|
|
54
58
|
* Starts the queue consumers (after the extension load), then opens the schedules' start gate:
|
|
55
59
|
* the cron and interval timers were armed at application bootstrap, but every tick before this
|
|
@@ -68,8 +72,9 @@ export declare class WorkerRole {
|
|
|
68
72
|
drainEvals(budgetMs: number): Promise<void> | undefined;
|
|
69
73
|
/**
|
|
70
74
|
* Closes the maintenance queue's worker, the plugin scope sync's (it stops between pairs), the
|
|
71
|
-
* lifecycle hook deliveries' (calls in flight are aborted and retried)
|
|
72
|
-
* (sends in flight finish, each bounded by the send time limit)
|
|
75
|
+
* lifecycle hook deliveries' (calls in flight are aborted and retried), the push deliveries'
|
|
76
|
+
* (sends in flight finish, each bounded by the send time limit) and the connector tool
|
|
77
|
+
* listings' (each bounded by the tool timeout).
|
|
73
78
|
*/
|
|
74
79
|
closeMaintenance(): Promise<void>;
|
|
75
80
|
}
|
|
@@ -9,6 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
9
9
|
};
|
|
10
10
|
import { Inject, Injectable } from "@nestjs/common";
|
|
11
11
|
import { PluginScopeSyncProcessor } from "../catalog/scope-sync-workers.js";
|
|
12
|
+
import { TemplateConnectorsProcessor } from "../catalog/template-connectors.processor.js";
|
|
12
13
|
import { ChannelsProcessor } from "../channels/channels.module.js";
|
|
13
14
|
import { ChannelOutbound } from "../channels/outbound.js";
|
|
14
15
|
import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
|
|
@@ -25,11 +26,12 @@ import { MaintenanceProcessor } from "../runtime/maintenance.js";
|
|
|
25
26
|
import { PromptSuggestionProcessor, RunsProcessor, SubagentRunsProcessor, TitleProcessor, UsageReportProcessor, } from "../runtime/run-processors.js";
|
|
26
27
|
import { RunWorker } from "../runtime/run-worker.js";
|
|
27
28
|
import { UsageReporter } from "../runtime/usage-report.js";
|
|
29
|
+
import { ConnectorToolsProcessor } from "../tools/connector-tools.processor.js";
|
|
28
30
|
/**
|
|
29
31
|
* The worker role's parts, driven by `KernelLifecycle` at fixed points of its start order and stop
|
|
30
32
|
* phases (so they stay ordered after the extension load and before the extension host closes): the
|
|
31
33
|
* queue consumers (runs, sub-agent runs, evals, maintenance, the plugin scope sync, lifecycle
|
|
32
|
-
* hook deliveries, push deliveries, channel deliveries, `usage.report`, titles, prompt suggestions) and the schedulers of the `@LockedCron` / `@LockedInterval` jobs. Provided only by
|
|
34
|
+
* hook deliveries, push deliveries, connector tool listings, template connector ensures, channel deliveries, `usage.report`, titles, prompt suggestions) and the schedulers of the `@LockedCron` / `@LockedInterval` jobs. Provided only by
|
|
33
35
|
* `WorkerModule`, so a process without the worker role has none of them.
|
|
34
36
|
*/
|
|
35
37
|
let WorkerRole = class WorkerRole {
|
|
@@ -53,13 +55,15 @@ let WorkerRole = class WorkerRole {
|
|
|
53
55
|
scopeProcessor;
|
|
54
56
|
lifecycleProcessor;
|
|
55
57
|
pushProcessor;
|
|
58
|
+
connectorToolsProcessor;
|
|
59
|
+
templateConnectorsProcessor;
|
|
56
60
|
/** The startup config (the roles). */
|
|
57
61
|
config;
|
|
58
62
|
/** The run worker was started: the runs phase drains it. */
|
|
59
63
|
runsStarted = false;
|
|
60
64
|
/** The eval worker was started: the runs phase drains it. */
|
|
61
65
|
evalsStarted = false;
|
|
62
|
-
constructor(config, log, intervals, scheduledRuns, runWorker, evalWorker, usageReport, titles, suggestions, channelOutbound, runsProcessor, subagentRunsProcessor, usageProcessor, titleProcessor, suggestionProcessor, channelsProcessor, evalsProcessor, maintenanceProcessor, scopeProcessor, lifecycleProcessor, pushProcessor) {
|
|
66
|
+
constructor(config, log, intervals, scheduledRuns, runWorker, evalWorker, usageReport, titles, suggestions, channelOutbound, runsProcessor, subagentRunsProcessor, usageProcessor, titleProcessor, suggestionProcessor, channelsProcessor, evalsProcessor, maintenanceProcessor, scopeProcessor, lifecycleProcessor, pushProcessor, connectorToolsProcessor, templateConnectorsProcessor) {
|
|
63
67
|
this.log = log;
|
|
64
68
|
this.intervals = intervals;
|
|
65
69
|
this.scheduledRuns = scheduledRuns;
|
|
@@ -80,6 +84,8 @@ let WorkerRole = class WorkerRole {
|
|
|
80
84
|
this.scopeProcessor = scopeProcessor;
|
|
81
85
|
this.lifecycleProcessor = lifecycleProcessor;
|
|
82
86
|
this.pushProcessor = pushProcessor;
|
|
87
|
+
this.connectorToolsProcessor = connectorToolsProcessor;
|
|
88
|
+
this.templateConnectorsProcessor = templateConnectorsProcessor;
|
|
83
89
|
this.config = config.get();
|
|
84
90
|
}
|
|
85
91
|
/**
|
|
@@ -99,6 +105,8 @@ let WorkerRole = class WorkerRole {
|
|
|
99
105
|
this.scopeProcessor.start();
|
|
100
106
|
this.lifecycleProcessor.start();
|
|
101
107
|
this.pushProcessor.start();
|
|
108
|
+
this.connectorToolsProcessor.start();
|
|
109
|
+
this.templateConnectorsProcessor.start();
|
|
102
110
|
this.channelOutbound.startWorker(this.channelsProcessor.worker);
|
|
103
111
|
this.usageReport.startWorker(this.usageProcessor.worker);
|
|
104
112
|
this.titles.startWorker(this.titleProcessor.worker);
|
|
@@ -127,8 +135,9 @@ let WorkerRole = class WorkerRole {
|
|
|
127
135
|
}
|
|
128
136
|
/**
|
|
129
137
|
* Closes the maintenance queue's worker, the plugin scope sync's (it stops between pairs), the
|
|
130
|
-
* lifecycle hook deliveries' (calls in flight are aborted and retried)
|
|
131
|
-
* (sends in flight finish, each bounded by the send time limit)
|
|
138
|
+
* lifecycle hook deliveries' (calls in flight are aborted and retried), the push deliveries'
|
|
139
|
+
* (sends in flight finish, each bounded by the send time limit) and the connector tool
|
|
140
|
+
* listings' (each bounded by the tool timeout).
|
|
132
141
|
*/
|
|
133
142
|
async closeMaintenance() {
|
|
134
143
|
await Promise.all([
|
|
@@ -136,6 +145,8 @@ let WorkerRole = class WorkerRole {
|
|
|
136
145
|
this.scopeProcessor.close(),
|
|
137
146
|
this.lifecycleProcessor.close(),
|
|
138
147
|
this.pushProcessor.close(),
|
|
148
|
+
this.connectorToolsProcessor.close(),
|
|
149
|
+
this.templateConnectorsProcessor.close(),
|
|
139
150
|
]);
|
|
140
151
|
}
|
|
141
152
|
};
|
|
@@ -161,6 +172,8 @@ WorkerRole = __decorate([
|
|
|
161
172
|
__param(17, Inject(MaintenanceProcessor)),
|
|
162
173
|
__param(18, Inject(PluginScopeSyncProcessor)),
|
|
163
174
|
__param(19, Inject(LifecycleHooksProcessor)),
|
|
164
|
-
__param(20, Inject(PushProcessor))
|
|
175
|
+
__param(20, Inject(PushProcessor)),
|
|
176
|
+
__param(21, Inject(ConnectorToolsProcessor)),
|
|
177
|
+
__param(22, Inject(TemplateConnectorsProcessor))
|
|
165
178
|
], WorkerRole);
|
|
166
179
|
export { WorkerRole };
|
|
@@ -5,7 +5,7 @@ import type { KernelConfig } from "../config/schema.js";
|
|
|
5
5
|
* `worker`: the cron scheduler and the `@LockedInterval` scheduler (`KernelScheduleModule`, the one
|
|
6
6
|
* place `ScheduleModule.forRoot` is imported), every fixed-period job (`@LockedCron` /
|
|
7
7
|
* `@LockedInterval`, each once per tick across replicas), every queue consumer (`@Processor`: runs,
|
|
8
|
-
* sub-agent runs, `usage.report`, titles, evals, maintenance, channel deliveries, the plugin scope sync, push deliveries) and
|
|
8
|
+
* sub-agent runs, `usage.report`, titles, evals, maintenance, channel deliveries, the plugin scope sync, push deliveries, connector tool listings) and
|
|
9
9
|
* {@link WorkerRole}, which `KernelLifecycle` drives. A process without the worker role runs no cron
|
|
10
10
|
* and no BullMQ worker (the queues' producers exist on every role).
|
|
11
11
|
*/
|
|
@@ -12,6 +12,7 @@ import { RetireLegacyTasksJob } from "../background/retire-legacy-tasks.job.js";
|
|
|
12
12
|
import { CatalogModule } from "../catalog/catalog.module.js";
|
|
13
13
|
import { CatalogJobs } from "../catalog/jobs.js";
|
|
14
14
|
import { PluginScopeWorkersModule } from "../catalog/scope-sync-workers.js";
|
|
15
|
+
import { TemplateConnectorsWorkersModule } from "../catalog/template-connectors.processor.js";
|
|
15
16
|
import { ChannelsModule, ChannelWorkersModule } from "../channels/channels.module.js";
|
|
16
17
|
import { GatewayCheckJob } from "../channels/supervisor.js";
|
|
17
18
|
import { ClientModule } from "../client/client.module.js";
|
|
@@ -48,6 +49,7 @@ import { ShareObjectsModule } from "../shares/share-objects.js";
|
|
|
48
49
|
import { ShareSweepJob } from "../shares/sweep.job.js";
|
|
49
50
|
import { StoragePurgeJob } from "../storage/purge.js";
|
|
50
51
|
import { StorageModule } from "../storage/storage.module.js";
|
|
52
|
+
import { ConnectorToolsWorkersModule } from "../tools/connector-tools.processor.js";
|
|
51
53
|
import { ToolJobs } from "../tools/jobs.js";
|
|
52
54
|
import { ToolsModule } from "../tools/tools.module.js";
|
|
53
55
|
import { WorkerRole } from "./worker-role.js";
|
|
@@ -56,7 +58,7 @@ import { WorkerRole } from "./worker-role.js";
|
|
|
56
58
|
* `worker`: the cron scheduler and the `@LockedInterval` scheduler (`KernelScheduleModule`, the one
|
|
57
59
|
* place `ScheduleModule.forRoot` is imported), every fixed-period job (`@LockedCron` /
|
|
58
60
|
* `@LockedInterval`, each once per tick across replicas), every queue consumer (`@Processor`: runs,
|
|
59
|
-
* sub-agent runs, `usage.report`, titles, evals, maintenance, channel deliveries, the plugin scope sync, push deliveries) and
|
|
61
|
+
* sub-agent runs, `usage.report`, titles, evals, maintenance, channel deliveries, the plugin scope sync, push deliveries, connector tool listings) and
|
|
60
62
|
* {@link WorkerRole}, which `KernelLifecycle` drives. A process without the worker role runs no cron
|
|
61
63
|
* and no BullMQ worker (the queues' producers exist on every role).
|
|
62
64
|
*/
|
|
@@ -78,6 +80,11 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
|
|
|
78
80
|
LifecycleHookWorkersModule,
|
|
79
81
|
// push deliveries (`cap-push-deliver`) and the daily stale registration prune
|
|
80
82
|
PushWorkersModule,
|
|
83
|
+
// connector tool listings owed after a create or a setup (`cap-connector-tools`)
|
|
84
|
+
ConnectorToolsWorkersModule,
|
|
85
|
+
// template connectors an org never had, owed by installs and extension switch-ons
|
|
86
|
+
// (`cap-template-connectors`)
|
|
87
|
+
TemplateConnectorsWorkersModule,
|
|
81
88
|
// the domains the fixed-period jobs call
|
|
82
89
|
RuntimeModule,
|
|
83
90
|
RunJobsModule,
|
|
@@ -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);
|
|
@@ -34,13 +34,16 @@ function grantedOf(detail) {
|
|
|
34
34
|
const g = detail?.grantedHosts;
|
|
35
35
|
return Array.isArray(g) ? g.filter(exactHost) : [];
|
|
36
36
|
}
|
|
37
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
* `detail.hosts` of a network ask: what it asked about (a command's `{ host, port }` entries, a
|
|
39
|
+
* device service's host names).
|
|
40
|
+
*/
|
|
38
41
|
function askedOf(detail) {
|
|
39
42
|
const hs = detail?.hosts;
|
|
40
43
|
if (!Array.isArray(hs))
|
|
41
44
|
return [];
|
|
42
45
|
return hs.flatMap((h) => {
|
|
43
|
-
const host = h?.host;
|
|
46
|
+
const host = typeof h === "string" ? h : h?.host;
|
|
44
47
|
return typeof host === "string" ? [host] : [];
|
|
45
48
|
});
|
|
46
49
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Sandboxes: the one {@link SandboxService} (a device's file system and instance over the
|
|
3
3
|
* `device-provider@1` provider, with the shared / exclusive leases of {@link SandboxLeases}), the review
|
|
4
|
-
* every command passes in auto mode ({@link CommandReviewService}),
|
|
4
|
+
* every command passes in auto mode ({@link CommandReviewService}), device services
|
|
5
|
+
* ({@link DeviceServices}), and the producer of the
|
|
5
6
|
* one-off `sandbox-destroy-for` jobs (`MaintenanceProcessor` consumes them). The sweeps
|
|
6
7
|
* (`SandboxSweepJobs`) are the worker role's (`WorkerModule`).
|
|
7
8
|
*/
|
|
@@ -16,6 +16,7 @@ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
|
|
|
16
16
|
import { StepLogModule } from "../runtime/step-log.js";
|
|
17
17
|
import { CloudPermissionSnapshotsModule } from "./cloud-permission-snapshot.module.js";
|
|
18
18
|
import { DeviceReportsModule } from "./device-reports.module.js";
|
|
19
|
+
import { DeviceServices } from "./device-services.js";
|
|
19
20
|
import { SandboxJobs } from "./jobs.js";
|
|
20
21
|
import { LegacyRetirementModule } from "./legacy-retirement.module.js";
|
|
21
22
|
import { OperationAuthorityModule } from "./operation-authority.module.js";
|
|
@@ -28,7 +29,8 @@ import { SandboxService } from "./sandbox.service.js";
|
|
|
28
29
|
/**
|
|
29
30
|
* Sandboxes: the one {@link SandboxService} (a device's file system and instance over the
|
|
30
31
|
* `device-provider@1` provider, with the shared / exclusive leases of {@link SandboxLeases}), the review
|
|
31
|
-
* every command passes in auto mode ({@link CommandReviewService}),
|
|
32
|
+
* every command passes in auto mode ({@link CommandReviewService}), device services
|
|
33
|
+
* ({@link DeviceServices}), and the producer of the
|
|
32
34
|
* one-off `sandbox-destroy-for` jobs (`MaintenanceProcessor` consumes them). The sweeps
|
|
33
35
|
* (`SandboxSweepJobs`) are the worker role's (`WorkerModule`).
|
|
34
36
|
*/
|
|
@@ -57,12 +59,13 @@ SandboxModule = __decorate([
|
|
|
57
59
|
StepLogModule,
|
|
58
60
|
QueueModule.registerQueue(MAINTENANCE_QUEUE_NAME),
|
|
59
61
|
],
|
|
60
|
-
providers: [SandboxService, SandboxJobs, CommandReviewService],
|
|
62
|
+
providers: [SandboxService, SandboxJobs, CommandReviewService, DeviceServices],
|
|
61
63
|
exports: [
|
|
62
64
|
SandboxProviderRegistryModule,
|
|
63
65
|
LegacyRetirementModule,
|
|
64
66
|
PermissionAuthorityModule,
|
|
65
67
|
SandboxService,
|
|
68
|
+
DeviceServices,
|
|
66
69
|
OperationIntentsModule,
|
|
67
70
|
OperationAuthorityModule,
|
|
68
71
|
SandboxJobs,
|