@capybara-hq/kernel 0.1.0-rc.40 → 0.1.0-rc.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bootstrap.json +10 -1
- package/dist/admin/admin.schemas.d.ts +6 -0
- package/dist/admin/org-network.service.d.ts +3 -1
- package/dist/admin/org-network.service.js +10 -2
- package/dist/app.d.ts +4 -0
- package/dist/app.js +2 -0
- package/dist/background/finish.d.ts +9 -1
- package/dist/background/finish.js +57 -4
- package/dist/background/launch.d.ts +23 -0
- package/dist/background/launch.js +55 -1
- package/dist/background/managed-output.d.ts +110 -0
- package/dist/background/managed-output.js +219 -0
- package/dist/background/managed.d.ts +52 -0
- package/dist/background/managed.js +128 -0
- package/dist/background/poll.job.d.ts +35 -1
- package/dist/background/poll.job.js +174 -9
- package/dist/background/render.js +1 -0
- package/dist/background/retire-legacy-tasks.job.d.ts +57 -0
- package/dist/background/retire-legacy-tasks.job.js +149 -0
- package/dist/background/session.d.ts +15 -5
- package/dist/background/session.js +22 -6
- package/dist/background/stop.d.ts +35 -5
- package/dist/background/stop.js +94 -8
- package/dist/background/store.d.ts +110 -3
- package/dist/background/store.js +205 -3
- package/dist/background/tasks.service.d.ts +18 -1
- package/dist/background/tasks.service.js +99 -9
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/cards.js +1 -1
- package/dist/channels/inbound.js +2 -0
- package/dist/channels/phrases.d.ts +4 -0
- package/dist/channels/phrases.js +4 -0
- package/dist/config/load.d.ts +18 -0
- package/dist/config/load.js +39 -1
- package/dist/config/permission-migration.d.ts +26 -0
- package/dist/config/permission-migration.js +64 -0
- package/dist/config/schema.d.ts +1 -1
- package/dist/config/schema.js +11 -10
- package/dist/conversations/conversations.controller.d.ts +1 -1
- package/dist/conversations/conversations.controller.js +1 -1
- package/dist/conversations/conversations.module.js +12 -0
- package/dist/conversations/conversations.service.d.ts +11 -2
- package/dist/conversations/conversations.service.js +97 -27
- package/dist/conversations/event-log.d.ts +1 -1
- package/dist/conversations/event-log.js +10 -2
- package/dist/conversations/events.d.ts +304 -4
- package/dist/conversations/events.js +279 -29
- package/dist/conversations/permission-profile-store.d.ts +50 -0
- package/dist/conversations/permission-profile-store.js +67 -0
- package/dist/conversations/permission-profile-store.module.d.ts +2 -0
- package/dist/conversations/permission-profile-store.module.js +19 -0
- package/dist/conversations/permission-profiles.controller.d.ts +84 -0
- package/dist/conversations/permission-profiles.controller.js +105 -0
- package/dist/conversations/permission-profiles.schemas.d.ts +31 -0
- package/dist/conversations/permission-profiles.schemas.js +23 -0
- package/dist/conversations/permission-profiles.service.d.ts +56 -0
- package/dist/conversations/permission-profiles.service.js +179 -0
- package/dist/db/kernel-schema.d.ts +238 -3
- package/dist/devices/access.js +1 -1
- package/dist/devices/access.module.d.ts +2 -0
- package/dist/devices/access.module.js +19 -0
- package/dist/devices/conversation-devices.d.ts +8 -29
- package/dist/devices/conversation-devices.js +37 -73
- package/dist/devices/device-projects.service.d.ts +26 -28
- package/dist/devices/device-projects.service.js +123 -127
- package/dist/devices/devices.controller.js +3 -1
- package/dist/devices/devices.module.js +11 -9
- package/dist/devices/devices.service.d.ts +116 -8
- package/dist/devices/devices.service.js +252 -20
- package/dist/devices/dto.d.ts +16 -0
- package/dist/devices/dto.js +34 -6
- package/dist/devices/errors.d.ts +8 -0
- package/dist/devices/errors.js +10 -0
- package/dist/devices/project-rules.d.ts +44 -0
- package/dist/devices/project-rules.js +27 -0
- package/dist/devices/working-root.d.ts +6 -0
- package/dist/devices/working-root.js +12 -1
- package/dist/errors.d.ts +31 -0
- package/dist/errors.js +31 -0
- package/dist/evals/reconstruct.d.ts +19 -2
- package/dist/evals/reconstruct.js +40 -2
- package/dist/evals/recorded-permission-context.d.ts +77 -0
- package/dist/evals/recorded-permission-context.js +151 -0
- package/dist/evals/recorded-tools.d.ts +10 -1
- package/dist/evals/recorded-tools.js +27 -3
- package/dist/evals/run-replay.d.ts +8 -2
- package/dist/evals/run-replay.js +18 -2
- package/dist/evals/trajectory.d.ts +1 -1
- package/dist/evals/worker.d.ts +10 -1
- package/dist/evals/worker.js +23 -14
- package/dist/http/api.module.js +2 -0
- package/dist/identity/accounts.d.ts +14 -1
- package/dist/identity/accounts.js +61 -5
- package/dist/identity/identity.module.js +2 -0
- package/dist/identity/settings.d.ts +28 -12
- package/dist/identity/settings.js +89 -33
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/infra/cli/kernel-cli.module.d.ts +2 -2
- package/dist/infra/cli/kernel-cli.module.js +5 -2
- package/dist/infra/cli/permission-cutover.d.ts +59 -0
- package/dist/infra/cli/permission-cutover.js +107 -0
- package/dist/infra/config/kernel-config.service.d.ts +2 -2
- package/dist/infra/config/kernel-config.service.js +31 -11
- package/dist/infra/database/startup-activation-transaction.d.ts +36 -0
- package/dist/infra/database/startup-activation-transaction.js +242 -0
- package/dist/infra/database/transaction-host.d.ts +47 -0
- package/dist/infra/database/transaction-host.js +119 -0
- package/dist/infra/database/xact-lock.d.ts +1 -0
- package/dist/infra/database/xact-lock.js +6 -0
- package/dist/infra/outbox/registry.d.ts +39 -0
- package/dist/infra/outbox/registry.js +18 -0
- package/dist/kernel.module.js +2 -0
- package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
- package/dist/lifecycle/kernel-lifecycle.js +55 -28
- package/dist/local-devices/device-auth.js +1 -1
- package/dist/local-devices/device-policy.service.d.ts +35 -5
- package/dist/local-devices/device-policy.service.js +188 -13
- package/dist/local-devices/instance-bindings.d.ts +82 -0
- package/dist/local-devices/instance-bindings.js +304 -0
- package/dist/local-devices/keys.d.ts +5 -0
- package/dist/local-devices/keys.js +5 -0
- package/dist/local-devices/local-device-gateway.d.ts +19 -4
- package/dist/local-devices/local-device-gateway.js +185 -17
- package/dist/local-devices/local-device-provider.d.ts +42 -7
- package/dist/local-devices/local-device-provider.js +185 -10
- package/dist/local-devices/local-devices.module.d.ts +17 -2
- package/dist/local-devices/local-devices.module.js +49 -8
- package/dist/local-devices/machines.d.ts +35 -12
- package/dist/local-devices/machines.js +203 -8
- package/dist/local-devices/network-grants.js +3 -3
- package/dist/local-devices/network-grants.module.d.ts +2 -0
- package/dist/local-devices/network-grants.module.js +14 -0
- package/dist/local-devices/owner-report.d.ts +79 -0
- package/dist/local-devices/owner-report.js +155 -0
- package/dist/local-devices/owner-reports.d.ts +48 -0
- package/dist/local-devices/owner-reports.js +190 -0
- package/dist/local-devices/policy-summary.d.ts +24 -1
- package/dist/local-devices/policy-summary.js +48 -0
- package/dist/local-devices/relay.d.ts +82 -6
- package/dist/local-devices/relay.js +187 -16
- package/dist/local-devices/targets.d.ts +16 -1
- package/dist/local-devices/targets.js +35 -2
- package/dist/orgs/cloud-network-setting.d.ts +33 -0
- package/dist/orgs/cloud-network-setting.js +47 -0
- package/dist/orgs/offboarding.d.ts +3 -1
- package/dist/orgs/offboarding.js +8 -2
- package/dist/orgs/org-lock.d.ts +10 -4
- package/dist/orgs/org-lock.js +10 -4
- package/dist/orgs/orgs.service.d.ts +3 -1
- package/dist/orgs/orgs.service.js +8 -2
- package/dist/orgs/settings.controller.d.ts +4 -1
- package/dist/orgs/settings.controller.js +3 -3
- package/dist/orgs/settings.service.d.ts +48 -56
- package/dist/orgs/settings.service.js +144 -101
- package/dist/overrides.d.ts +6 -1
- package/dist/overrides.js +2 -0
- package/dist/platform/exclusions.js +20 -0
- package/dist/platform/ops/admin.ops.js +14 -11
- package/dist/platform/ops/agent-skills.ops.js +2 -0
- package/dist/platform/ops/devices.ops.js +10 -2
- package/dist/platform/ops/org-settings.ops.js +6 -6
- package/dist/platform/ops/orgs.ops.js +1 -0
- package/dist/roles/worker.module.js +4 -0
- package/dist/runtime/context/build.d.ts +3 -1
- package/dist/runtime/context/build.js +19 -3
- package/dist/runtime/context/compaction.js +5 -0
- package/dist/runtime/context/device-paths.d.ts +9 -2
- package/dist/runtime/context/device-paths.js +20 -0
- package/dist/runtime/context/permission-profile.d.ts +46 -0
- package/dist/runtime/context/permission-profile.js +194 -0
- package/dist/runtime/maintenance.d.ts +7 -1
- package/dist/runtime/maintenance.js +43 -15
- package/dist/runtime/model-call.d.ts +32 -0
- package/dist/runtime/model-call.js +67 -0
- package/dist/runtime/permission-context-errors.d.ts +39 -0
- package/dist/runtime/permission-context-errors.js +67 -0
- package/dist/runtime/permission-context.service.d.ts +60 -0
- package/dist/runtime/permission-context.service.js +286 -0
- package/dist/runtime/project/knowledge.d.ts +7 -2
- package/dist/runtime/project/knowledge.js +5 -2
- package/dist/runtime/project/knowledge.service.d.ts +17 -2
- package/dist/runtime/project/knowledge.service.js +76 -12
- package/dist/runtime/run-execution.d.ts +4 -1
- package/dist/runtime/run-execution.js +14 -5
- package/dist/runtime/run-steps.d.ts +11 -3
- package/dist/runtime/run-steps.js +27 -4
- package/dist/runtime/runtime.module.js +11 -0
- package/dist/sandbox/attachments-path.d.ts +15 -0
- package/dist/sandbox/attachments-path.js +15 -0
- package/dist/sandbox/cloud-permission-snapshot.d.ts +159 -0
- package/dist/sandbox/cloud-permission-snapshot.js +407 -0
- package/dist/sandbox/cloud-permission-snapshot.module.d.ts +8 -0
- package/dist/sandbox/cloud-permission-snapshot.module.js +34 -0
- package/dist/sandbox/held-operations.d.ts +39 -0
- package/dist/sandbox/held-operations.js +119 -0
- package/dist/sandbox/jobs.d.ts +14 -3
- package/dist/sandbox/jobs.js +20 -2
- package/dist/sandbox/kernel-read.d.ts +55 -0
- package/dist/sandbox/kernel-read.js +57 -0
- package/dist/sandbox/legacy-retirement.d.ts +336 -0
- package/dist/sandbox/legacy-retirement.js +1063 -0
- package/dist/sandbox/legacy-retirement.module.d.ts +8 -0
- package/dist/sandbox/legacy-retirement.module.js +25 -0
- package/dist/sandbox/managed-device-context.d.ts +94 -0
- package/dist/sandbox/managed-device-context.js +308 -0
- package/dist/sandbox/managed-device-context.module.d.ts +6 -0
- package/dist/sandbox/managed-device-context.module.js +33 -0
- package/dist/sandbox/modes.d.ts +56 -8
- package/dist/sandbox/modes.js +92 -8
- package/dist/sandbox/operation-authority-types.d.ts +8 -0
- package/dist/sandbox/operation-authority-types.js +32 -0
- package/dist/sandbox/operation-authority.d.ts +145 -0
- package/dist/sandbox/operation-authority.js +783 -0
- package/dist/sandbox/operation-authority.module.d.ts +2 -0
- package/dist/sandbox/operation-authority.module.js +29 -0
- package/dist/sandbox/operation-intents.d.ts +206 -0
- package/dist/sandbox/operation-intents.js +1252 -0
- package/dist/sandbox/operation-intents.module.d.ts +2 -0
- package/dist/sandbox/operation-intents.module.js +21 -0
- package/dist/sandbox/operation-payloads.d.ts +33 -0
- package/dist/sandbox/operation-payloads.js +332 -0
- package/dist/sandbox/operation-reconcile.job.d.ts +49 -0
- package/dist/sandbox/operation-reconcile.job.js +247 -0
- package/dist/sandbox/permission-authority-epochs.d.ts +18 -0
- package/dist/sandbox/permission-authority-epochs.js +83 -0
- package/dist/sandbox/permission-authority-lock.d.ts +38 -0
- package/dist/sandbox/permission-authority-lock.js +147 -0
- package/dist/sandbox/permission-authority.module.d.ts +9 -0
- package/dist/sandbox/permission-authority.module.js +55 -0
- package/dist/sandbox/permission-availability.d.ts +18 -0
- package/dist/sandbox/permission-availability.js +19 -0
- package/dist/sandbox/permission-call-grants.d.ts +34 -0
- package/dist/sandbox/permission-call-grants.js +349 -0
- package/dist/sandbox/permission-call-grants.module.d.ts +2 -0
- package/dist/sandbox/permission-call-grants.module.js +21 -0
- package/dist/sandbox/permission-call-types.d.ts +82 -0
- package/dist/sandbox/permission-call-types.js +1 -0
- package/dist/sandbox/permission-ceiling-writes.d.ts +47 -0
- package/dist/sandbox/permission-ceiling-writes.js +223 -0
- package/dist/sandbox/permission-config-publication.d.ts +76 -0
- package/dist/sandbox/permission-config-publication.js +339 -0
- package/dist/sandbox/permission-context-types.d.ts +64 -0
- package/dist/sandbox/permission-context-types.js +24 -0
- package/dist/sandbox/permission-facts.d.ts +206 -0
- package/dist/sandbox/permission-facts.js +627 -0
- package/dist/sandbox/permission-facts.module.d.ts +2 -0
- package/dist/sandbox/permission-facts.module.js +20 -0
- package/dist/sandbox/permission-instance-writes.d.ts +90 -0
- package/dist/sandbox/permission-instance-writes.js +305 -0
- package/dist/sandbox/permission-runtime-reports.d.ts +83 -0
- package/dist/sandbox/permission-runtime-reports.js +354 -0
- package/dist/sandbox/permission-transitions.d.ts +31 -0
- package/dist/sandbox/permission-transitions.js +155 -0
- package/dist/sandbox/platform-full-access.d.ts +128 -0
- package/dist/sandbox/platform-full-access.js +210 -0
- package/dist/sandbox/providers.d.ts +22 -0
- package/dist/sandbox/providers.js +10 -2
- package/dist/sandbox/providers.module.d.ts +2 -0
- package/dist/sandbox/providers.module.js +19 -0
- package/dist/sandbox/request-not-sent.d.ts +13 -0
- package/dist/sandbox/request-not-sent.js +13 -0
- package/dist/sandbox/review/classifier.d.ts +2 -0
- package/dist/sandbox/review/classifier.js +8 -0
- package/dist/sandbox/review/permission-candidate.d.ts +12 -0
- package/dist/sandbox/review/permission-candidate.js +129 -0
- package/dist/sandbox/review/review.service.d.ts +4 -1
- package/dist/sandbox/review/review.service.js +19 -5
- package/dist/sandbox/sandbox-file-reader.d.ts +18 -1
- package/dist/sandbox/sandbox-file-reader.js +51 -7
- package/dist/sandbox/sandbox.module.js +26 -6
- package/dist/sandbox/sandbox.service.d.ts +230 -34
- package/dist/sandbox/sandbox.service.js +1368 -199
- package/dist/sandbox/unreachable.js +17 -3
- package/dist/sandbox/use-context.d.ts +17 -0
- package/dist/sandbox/use-context.js +1 -0
- package/dist/skills/invoke.d.ts +27 -4
- package/dist/skills/invoke.js +72 -7
- package/dist/tools/approvals.controller.d.ts +1 -0
- package/dist/tools/approvals.schemas.d.ts +1 -0
- package/dist/tools/approvals.schemas.js +3 -1
- package/dist/tools/approvals.service.d.ts +23 -10
- package/dist/tools/approvals.service.js +104 -26
- package/dist/tools/builtins/builtin-tools.d.ts +16 -2
- package/dist/tools/builtins/builtin-tools.js +38 -10
- package/dist/tools/builtins/sandbox/bash.d.ts +25 -1
- package/dist/tools/builtins/sandbox/bash.js +201 -5
- package/dist/tools/builtins/sandbox/common.d.ts +92 -20
- package/dist/tools/builtins/sandbox/common.js +201 -17
- package/dist/tools/builtins/sandbox/deliver.js +2 -2
- package/dist/tools/builtins/sandbox/edit.js +2 -2
- package/dist/tools/builtins/sandbox/fetch-attachment.js +11 -4
- package/dist/tools/builtins/sandbox/glob.js +2 -2
- package/dist/tools/builtins/sandbox/grep.js +2 -2
- package/dist/tools/builtins/sandbox/read.js +2 -2
- package/dist/tools/builtins/sandbox/task-list.js +7 -1
- package/dist/tools/builtins/sandbox/task-output.d.ts +1 -1
- package/dist/tools/builtins/sandbox/task-output.js +172 -0
- package/dist/tools/builtins/sandbox/task-stop.js +25 -3
- package/dist/tools/builtins/sandbox/write.js +2 -2
- package/dist/tools/builtins/skill-load.js +9 -6
- package/dist/tools/device-op-resolver.d.ts +1 -1
- package/dist/tools/device-op-resolver.js +13 -3
- package/dist/tools/permission-approval-jobs.d.ts +18 -0
- package/dist/tools/permission-approval-jobs.js +92 -0
- package/dist/tools/pipeline.d.ts +17 -2
- package/dist/tools/pipeline.js +300 -19
- package/dist/tools/registry.d.ts +9 -0
- package/dist/tools/tools.module.js +12 -0
- package/package.json +4 -3
- package/src/migrations/0146_permission_authority_epochs.sql +6 -0
- package/src/migrations/0147_conversation_permission_profiles.sql +4 -0
- package/src/migrations/0148_first_message_request_hash.sql +2 -0
- package/src/migrations/0149_sandbox_operation_intents.sql +66 -0
- package/src/migrations/0150_permission_call_grants_and_approvals.sql +36 -0
- package/src/migrations/0151_starting_execution_grants.sql +8 -0
- package/src/migrations/0152_background_launch_identity.sql +66 -0
- package/src/migrations/0153_background_cancel_requester.sql +13 -0
- package/src/migrations/0154_cloud_owner_ceiling.sql +14 -0
- package/src/migrations/0155_device_instance_generations.sql +30 -0
- package/src/migrations/0156_device_owner_report.sql +7 -0
- package/src/migrations/0157_legacy_retirement.sql +116 -0
- package/src/migrations/0158_legacy_freeze_enumerated.sql +5 -0
- package/src/migrations/0159_retirement_exact_cancel.sql +9 -0
- package/dist/sandbox/platform-auto-mode.d.ts +0 -63
- package/dist/sandbox/platform-auto-mode.js +0 -63
|
@@ -0,0 +1,1063 @@
|
|
|
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 { isDeviceBootId } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
12
|
+
import { sql } from "kysely";
|
|
13
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
14
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
15
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
16
|
+
import { PermissionAuthorityLock } from "./permission-authority-lock.js";
|
|
17
|
+
import { isInternalProvider, LOCAL_PROVIDER } from "./providers.js";
|
|
18
|
+
/**
|
|
19
|
+
* Legacy retirement (permission runtime cutover phase 8.5): the durable legacy-launch freeze and
|
|
20
|
+
* the physical no-reuse obligations of old instance incarnations (migration 0157).
|
|
21
|
+
*
|
|
22
|
+
* - **Freeze.** {@link freeze} writes the one freeze row under the platform authority writer (the
|
|
23
|
+
* exclusive platform permission lock). A legacy SID launch calls {@link admitLegacyDispatch}
|
|
24
|
+
* immediately before its dispatch, which takes the shared platform lock and refuses once the
|
|
25
|
+
* row exists; so when the freeze commits, every admission that passed before has committed its
|
|
26
|
+
* `dispatched` mark, and none passes after. A replica without this code is not fenced: it must
|
|
27
|
+
* be stopped or drained before the freeze (the rows it writes still read `unknown`, never
|
|
28
|
+
* "not dispatched", and the periodic re-scan picks them up).
|
|
29
|
+
* - **Obligations.** {@link scan} enumerates, under the freeze, every legacy row whose processes
|
|
30
|
+
* may still exist (running with a SID, a reservation that may have dispatched, a stop in flight,
|
|
31
|
+
* `kill_pending` including terminal rows, a possibly dispatched launch that failed), and every
|
|
32
|
+
* revoked managed background start whose recorded generation no longer runs (the 8.4 handoff).
|
|
33
|
+
* Each becomes a member of the obligation of its device, provider and exact instance
|
|
34
|
+
* generation. A SID, PID or output text is never turned into an execution reference: it only
|
|
35
|
+
* names the row. Obligations live apart from the task rows, so output retention never removes
|
|
36
|
+
* them, and task finish and event semantics stay with the task's own finisher.
|
|
37
|
+
* - **Resolution** is the sandbox service's, under the device's exclusive lifecycle lease
|
|
38
|
+
* (`SandboxService` gate): a cloud incarnation is destroyed whole by its provider (confirmed
|
|
39
|
+
* destruction, the file system kept) or found destroyed by a recorded confirmed destruction; a
|
|
40
|
+
* local one, a replaced cloud one without recorded destruction and an unknown one are
|
|
41
|
+
* quarantined. Nothing here resolves on a new generation, a restart, a local (no-op) destroy, a
|
|
42
|
+
* timeout or a process scan.
|
|
43
|
+
*/
|
|
44
|
+
/** The freeze's single row id. */
|
|
45
|
+
const FREEZE_ID = "platform";
|
|
46
|
+
/** A generation as recorded: the decimal epoch millisecond, or `unknown`. */
|
|
47
|
+
const GENERATION_RE = /^[0-9]{1,16}$/;
|
|
48
|
+
/**
|
|
49
|
+
* The cutover barrier is not in place: legacy admission is still open (no freeze), or the freeze
|
|
50
|
+
* is published but its enumeration never completed. Nothing that depends on closed admission
|
|
51
|
+
* (the cloud snapshot) may run.
|
|
52
|
+
*/
|
|
53
|
+
export class CutoverBarrierError extends Error {
|
|
54
|
+
constructor(message) {
|
|
55
|
+
super(message);
|
|
56
|
+
this.name = "CutoverBarrierError";
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The freeze is published, but its enumeration kept finding new rows for every pass (legacy rows,
|
|
61
|
+
* for example of a replica without the freeze code, or revoked managed starts). The freeze stays published (it
|
|
62
|
+
* is never undone) and is not marked enumerated; stop that replica and run the freeze again.
|
|
63
|
+
*/
|
|
64
|
+
export class LegacyFreezeUnsettledError extends Error {
|
|
65
|
+
constructor(passes, added) {
|
|
66
|
+
super(`The legacy-launch freeze is published, but its enumeration did not settle after ${passes} ` +
|
|
67
|
+
`passes (${added} new members): new legacy or revoked rows kept appearing. Stop every ` +
|
|
68
|
+
"old replica, then run the freeze again");
|
|
69
|
+
this.name = "LegacyFreezeUnsettledError";
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** The passes of the freeze's own enumeration before it is called unsettled. */
|
|
73
|
+
const FREEZE_SCAN_PASSES = 5;
|
|
74
|
+
/** What the report counts as a recent unmarked legacy row (database clock). */
|
|
75
|
+
const RECENT = "15 minutes";
|
|
76
|
+
/** The migration that added the legacy dispatch marker: rows after it without one are unfenced. */
|
|
77
|
+
const MARKER_MIGRATION = "0157_legacy_retirement.sql";
|
|
78
|
+
/**
|
|
79
|
+
* The legacy rows whose processes may still exist: the partial index's predicate (0157) stated as
|
|
80
|
+
* is, then the rows that may have dispatched or still owe a kill.
|
|
81
|
+
*/
|
|
82
|
+
const MAY_STILL_RUN = sql `(t.status = 'running' OR t.kill_pending OR t.sid IS NULL)`;
|
|
83
|
+
const MAY_HAVE_DISPATCHED = sql `(
|
|
84
|
+
(t.status = 'running' AND (t.sid IS NOT NULL OR t.legacy_dispatch <> 'reserved'))
|
|
85
|
+
OR t.kill_pending
|
|
86
|
+
OR (t.sid IS NULL AND t.legacy_dispatch <> 'reserved')
|
|
87
|
+
)`;
|
|
88
|
+
/** Whether `provider` is a cloud provider (one whose whole-instance destroy is confirmed). */
|
|
89
|
+
export const isCloudProvider = (provider) => provider !== "unknown" && !isInternalProvider(provider);
|
|
90
|
+
/** The epoch millisecond of `d` as recorded generation text. */
|
|
91
|
+
const generationOf = (d) => String(d.getTime());
|
|
92
|
+
/**
|
|
93
|
+
* The incarnation a legacy row's obligation is keyed by: the one it started in, else the one its
|
|
94
|
+
* dispatch was admitted for; a historical reservation without either is `unknown`, never the
|
|
95
|
+
* instance current now (I2). Its own provider: local `@local`, else the admitted one, else the
|
|
96
|
+
* instance row's only when it is that incarnation, else `unknown` (M6).
|
|
97
|
+
*/
|
|
98
|
+
function legacyKey(r) {
|
|
99
|
+
const generation = r.sandbox_created_at !== null
|
|
100
|
+
? generationOf(new Date(r.sandbox_created_at))
|
|
101
|
+
: (r.legacy_dispatch_generation ?? "unknown");
|
|
102
|
+
const current = r.instance_created_at !== null && generationOf(r.instance_created_at) === generation;
|
|
103
|
+
const provider = r.source === "local"
|
|
104
|
+
? LOCAL_PROVIDER
|
|
105
|
+
: (r.legacy_dispatch_provider ??
|
|
106
|
+
(current && r.instance_provider ? r.instance_provider : "unknown"));
|
|
107
|
+
return { provider, generation };
|
|
108
|
+
}
|
|
109
|
+
const toObligation = (r) => ({
|
|
110
|
+
id: r.id,
|
|
111
|
+
deviceId: r.device_id,
|
|
112
|
+
orgId: r.org_id,
|
|
113
|
+
provider: r.provider,
|
|
114
|
+
instanceGeneration: r.instance_generation,
|
|
115
|
+
state: r.state,
|
|
116
|
+
reason: r.reason,
|
|
117
|
+
attempts: r.attempts,
|
|
118
|
+
bootId: r.boot_id,
|
|
119
|
+
createdAt: r.created_at,
|
|
120
|
+
});
|
|
121
|
+
let LegacyRetirementStore = class LegacyRetirementStore {
|
|
122
|
+
db;
|
|
123
|
+
txHost;
|
|
124
|
+
locks;
|
|
125
|
+
constructor(db, txHost, locks) {
|
|
126
|
+
this.db = db;
|
|
127
|
+
this.txHost = txHost;
|
|
128
|
+
this.locks = locks;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Publishes the legacy-launch freeze under the platform authority writer, then enumerates every
|
|
132
|
+
* legacy row and revoked start until stable; idempotent. Returns when it was first published.
|
|
133
|
+
* Never undone.
|
|
134
|
+
*/
|
|
135
|
+
async freeze(by) {
|
|
136
|
+
const frozenAt = await this.publishFreeze(by);
|
|
137
|
+
// enumerated before the freeze returns: no use may run between it and the first scan (the
|
|
138
|
+
// gate also scans each device it serves, so a worker that never runs bypasses nothing)
|
|
139
|
+
const scan = await this.scanUntilStable(FREEZE_SCAN_PASSES);
|
|
140
|
+
// A separate write after the scan (whose passes commit member by member): the mark only says
|
|
141
|
+
// a whole enumeration completed stable; an unsettled run clears an earlier mark, so the
|
|
142
|
+
// barrier never trusts an enumeration older than what this run found still moving.
|
|
143
|
+
await this.db
|
|
144
|
+
.updateTable("legacy_launch_freeze")
|
|
145
|
+
.set({ enumerated_at: scan.stable ? sql `now()` : null })
|
|
146
|
+
.where("id", "=", FREEZE_ID)
|
|
147
|
+
.execute();
|
|
148
|
+
if (!scan.stable)
|
|
149
|
+
throw new LegacyFreezeUnsettledError(FREEZE_SCAN_PASSES, scan.added);
|
|
150
|
+
return { frozenAt, added: scan.added, stable: true };
|
|
151
|
+
}
|
|
152
|
+
/** Whether the freeze is published and whether its enumeration completed. */
|
|
153
|
+
async freezeState() {
|
|
154
|
+
const row = await this.db
|
|
155
|
+
.selectFrom("legacy_launch_freeze")
|
|
156
|
+
.select(["frozen_at", "enumerated_at"])
|
|
157
|
+
.where("id", "=", FREEZE_ID)
|
|
158
|
+
.executeTakeFirst();
|
|
159
|
+
return { frozenAt: row?.frozen_at ?? null, enumeratedAt: row?.enumerated_at ?? null };
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The cutover barrier (B-10): legacy admission is closed (the freeze is published), the
|
|
163
|
+
* freeze's own enumeration completed, and no unmarked legacy row (only an old, unfenced replica
|
|
164
|
+
* writes one) started after that enumeration. Throws {@link CutoverBarrierError} otherwise. The
|
|
165
|
+
* freeze is never undone; a later legacy row is still enumerated by the gate before any use.
|
|
166
|
+
*/
|
|
167
|
+
async assertCutoverBarrier() {
|
|
168
|
+
const state = await this.freezeState();
|
|
169
|
+
if (state.frozenAt === null)
|
|
170
|
+
throw new CutoverBarrierError("Legacy admission is still open: publish the legacy-launch freeze first " +
|
|
171
|
+
"(capybara permissions cutover freeze)");
|
|
172
|
+
if (state.enumeratedAt === null)
|
|
173
|
+
throw new CutoverBarrierError("The legacy-launch freeze is published but its enumeration never completed: " +
|
|
174
|
+
"run capybara permissions cutover freeze again");
|
|
175
|
+
const unfenced = await this.unfencedWriters(state);
|
|
176
|
+
if (unfenced.afterEnumeration > 0)
|
|
177
|
+
throw new CutoverBarrierError(`${unfenced.afterEnumeration} unmarked legacy row(s) started after the freeze's ` +
|
|
178
|
+
"enumeration: an old, unfenced replica still runs. Stop it, then run capybara " +
|
|
179
|
+
"permissions cutover freeze again");
|
|
180
|
+
}
|
|
181
|
+
async publishFreeze(by) {
|
|
182
|
+
await this.locks.acquire({}, { kind: "write", level: "platform" });
|
|
183
|
+
await this.db
|
|
184
|
+
.insertInto("legacy_launch_freeze")
|
|
185
|
+
.values({ id: FREEZE_ID, frozen_by: by.slice(0, 200) || "unknown" })
|
|
186
|
+
.onConflict((oc) => oc.column("id").doNothing())
|
|
187
|
+
.execute();
|
|
188
|
+
const row = await this.db
|
|
189
|
+
.selectFrom("legacy_launch_freeze")
|
|
190
|
+
.select("frozen_at")
|
|
191
|
+
.where("id", "=", FREEZE_ID)
|
|
192
|
+
.executeTakeFirstOrThrow();
|
|
193
|
+
return row.frozen_at;
|
|
194
|
+
}
|
|
195
|
+
/** When the freeze was published; null before. */
|
|
196
|
+
async frozenAt() {
|
|
197
|
+
const row = await this.db
|
|
198
|
+
.selectFrom("legacy_launch_freeze")
|
|
199
|
+
.select("frozen_at")
|
|
200
|
+
.where("id", "=", FREEZE_ID)
|
|
201
|
+
.executeTakeFirst();
|
|
202
|
+
return row?.frozen_at ?? null;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* The worker's sweep of obligations whose device is gone (its row missing, `deleted_at` set, or
|
|
206
|
+
* its org soft-deleted), at most `limit` per call:
|
|
207
|
+
* - a cloud one (any provider not kernel-internal) waits while the device's instance row exists:
|
|
208
|
+
* its destroy is still owed (the destroy job or the destruction sweep deletes the row when it
|
|
209
|
+
* is done) and records the destruction then;
|
|
210
|
+
* - one whose exact incarnation has a recorded confirmed destruction resolves
|
|
211
|
+
* `provider-destroyed`, an already `abandoned` cloud one too (provider evidence, not a
|
|
212
|
+
* reopen);
|
|
213
|
+
* - every other one becomes `abandoned`. Device ids are never reused, so no device can acquire
|
|
214
|
+
* that incarnation again, but abandonment is no evidence that its processes ended (they may
|
|
215
|
+
* still run on that computer); its members stay unsettled.
|
|
216
|
+
* Returns the counts.
|
|
217
|
+
*/
|
|
218
|
+
async abandonDeleted(limit) {
|
|
219
|
+
let resolved = 0, abandoned = 0;
|
|
220
|
+
// abandoned cloud obligations that gained a matching recorded destruction
|
|
221
|
+
const evidenced = await this.db
|
|
222
|
+
.selectFrom("device_retirement_obligations as o")
|
|
223
|
+
.innerJoin("device_instance_destructions as x", (j) => j
|
|
224
|
+
.onRef("x.device_id", "=", "o.device_id")
|
|
225
|
+
.onRef("x.provider", "=", "o.provider")
|
|
226
|
+
.onRef("x.instance_generation", "=", "o.instance_generation"))
|
|
227
|
+
.select("o.id")
|
|
228
|
+
.where("o.state", "=", "abandoned")
|
|
229
|
+
.limit(limit)
|
|
230
|
+
.execute();
|
|
231
|
+
for (const r of evidenced) {
|
|
232
|
+
const u = await this.db
|
|
233
|
+
.updateTable("device_retirement_obligations")
|
|
234
|
+
.set({
|
|
235
|
+
state: "resolved",
|
|
236
|
+
resolution: "provider-destroyed",
|
|
237
|
+
resolved_at: sql `now()`,
|
|
238
|
+
abandoned_at: null,
|
|
239
|
+
last_error: null,
|
|
240
|
+
})
|
|
241
|
+
.where("id", "=", r.id)
|
|
242
|
+
.where("state", "=", "abandoned")
|
|
243
|
+
.executeTakeFirst();
|
|
244
|
+
resolved += Number(u.numUpdatedRows);
|
|
245
|
+
}
|
|
246
|
+
const rows = await this.db
|
|
247
|
+
.selectFrom("device_retirement_obligations as o")
|
|
248
|
+
.leftJoin("devices as d", "d.id", "o.device_id")
|
|
249
|
+
.leftJoin("orgs as g", "g.id", "d.org_id")
|
|
250
|
+
.select(["o.id", "o.device_id", "o.provider", "o.instance_generation"])
|
|
251
|
+
.where("o.state", "in", ["open", "quarantined"])
|
|
252
|
+
.where((eb) => eb.or([
|
|
253
|
+
eb("d.id", "is", null),
|
|
254
|
+
eb("d.deleted_at", "is not", null),
|
|
255
|
+
eb("g.deleted_at", "is not", null),
|
|
256
|
+
]))
|
|
257
|
+
// a cloud destroy still owed keeps its instance row (R2-I2)
|
|
258
|
+
.where((eb) => eb.or([
|
|
259
|
+
eb("o.provider", "like", "@%"),
|
|
260
|
+
eb.not(eb.exists(eb
|
|
261
|
+
.selectFrom("device_instances as i")
|
|
262
|
+
.select("i.device_id")
|
|
263
|
+
.whereRef("i.device_id", "=", "o.device_id"))),
|
|
264
|
+
]))
|
|
265
|
+
.orderBy("o.created_at")
|
|
266
|
+
.limit(limit)
|
|
267
|
+
.execute();
|
|
268
|
+
for (const r of rows) {
|
|
269
|
+
if (await this.destructionRecorded(r.device_id, r.provider, r.instance_generation)) {
|
|
270
|
+
await this.resolveDestroyed(r.id);
|
|
271
|
+
resolved++;
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
const u = await this.db
|
|
275
|
+
.updateTable("device_retirement_obligations")
|
|
276
|
+
.set({ state: "abandoned", abandoned_at: sql `now()` })
|
|
277
|
+
.where("id", "=", r.id)
|
|
278
|
+
.where("state", "in", ["open", "quarantined"])
|
|
279
|
+
.executeTakeFirst();
|
|
280
|
+
abandoned += Number(u.numUpdatedRows);
|
|
281
|
+
}
|
|
282
|
+
return { resolved, abandoned };
|
|
283
|
+
}
|
|
284
|
+
async frozen() {
|
|
285
|
+
const row = await this.db
|
|
286
|
+
.selectFrom("legacy_launch_freeze")
|
|
287
|
+
.select("id")
|
|
288
|
+
.where("id", "=", FREEZE_ID)
|
|
289
|
+
.executeTakeFirst();
|
|
290
|
+
return row !== undefined;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* The check every legacy SID launch makes immediately before it dispatches its command: under
|
|
294
|
+
* the shared platform authority lock (so a concurrent {@link freeze} waits for it), refuses once
|
|
295
|
+
* the freeze is published; otherwise marks the reservation `dispatched` in the same transaction.
|
|
296
|
+
*/
|
|
297
|
+
async admitLegacyDispatch(orgId, taskId,
|
|
298
|
+
/** The exact incarnation the launch dispatches into (read under its shared lease). */
|
|
299
|
+
instance) {
|
|
300
|
+
await this.locks.acquire({ orgId }, { kind: "admit" });
|
|
301
|
+
if (await this.frozen())
|
|
302
|
+
return "frozen";
|
|
303
|
+
const r = await this.db
|
|
304
|
+
.updateTable("background_tasks")
|
|
305
|
+
.set({
|
|
306
|
+
legacy_dispatch: "dispatched",
|
|
307
|
+
legacy_dispatch_provider: instance.provider,
|
|
308
|
+
legacy_dispatch_generation: GENERATION_RE.test(instance.generation)
|
|
309
|
+
? instance.generation
|
|
310
|
+
: null,
|
|
311
|
+
})
|
|
312
|
+
.where("id", "=", taskId)
|
|
313
|
+
.where("org_id", "=", orgId)
|
|
314
|
+
.where("status", "=", "running")
|
|
315
|
+
.where("sid", "is", null)
|
|
316
|
+
.where("launch_state", "=", "legacy")
|
|
317
|
+
.executeTakeFirst();
|
|
318
|
+
return Number(r.numUpdatedRows) === 1 ? "admitted" : "gone";
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* One enumeration pass: every legacy row (only once the freeze is published) and every revoked
|
|
322
|
+
* managed start that may still own processes on an incarnation that no longer runs, recorded as
|
|
323
|
+
* members of their obligations. Idempotent; returns how many new members it recorded. The
|
|
324
|
+
* worker repeats it every tick, so a row an old unfenced replica writes later is still found.
|
|
325
|
+
*/
|
|
326
|
+
async scan(deviceId) {
|
|
327
|
+
let added = await this.reopenLateMembers(deviceId);
|
|
328
|
+
if (await this.frozen())
|
|
329
|
+
added += await this.scanLegacyTasks(deviceId);
|
|
330
|
+
added += await this.scanRevokedStarts(deviceId);
|
|
331
|
+
return { added };
|
|
332
|
+
}
|
|
333
|
+
/** Repeats {@link scan} until a pass adds nothing (at most `maxPasses`). */
|
|
334
|
+
async scanUntilStable(maxPasses = 5, deviceId) {
|
|
335
|
+
let added = 0;
|
|
336
|
+
for (let i = 0; i < maxPasses; i++) {
|
|
337
|
+
const pass = await this.scan(deviceId);
|
|
338
|
+
added += pass.added;
|
|
339
|
+
if (pass.added === 0)
|
|
340
|
+
return { added, stable: true };
|
|
341
|
+
}
|
|
342
|
+
return { added, stable: false };
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Legacy rows whose processes may still exist and that are not members yet (one device's, or
|
|
346
|
+
* all). The `(status = 'running' OR kill_pending OR sid IS NULL)` conjunct is the partial index's
|
|
347
|
+
* predicate (0157), stated as is so the planner can use it.
|
|
348
|
+
*/
|
|
349
|
+
legacyCandidates(deviceId) {
|
|
350
|
+
let q = this.db
|
|
351
|
+
.selectFrom("background_tasks as t")
|
|
352
|
+
.leftJoin("devices as d", "d.id", "t.device_id")
|
|
353
|
+
.leftJoin("device_instances as i", "i.device_id", "t.device_id")
|
|
354
|
+
.select([
|
|
355
|
+
"t.id",
|
|
356
|
+
"t.org_id",
|
|
357
|
+
"t.device_id",
|
|
358
|
+
"t.sandbox_created_at",
|
|
359
|
+
"t.legacy_dispatch_generation",
|
|
360
|
+
"t.legacy_dispatch_provider",
|
|
361
|
+
"d.source",
|
|
362
|
+
"i.provider as instance_provider",
|
|
363
|
+
"i.created_at as instance_created_at",
|
|
364
|
+
])
|
|
365
|
+
.where("t.launch_state", "=", "legacy")
|
|
366
|
+
.where("t.device_id", "is not", null)
|
|
367
|
+
.where(MAY_STILL_RUN)
|
|
368
|
+
.where(MAY_HAVE_DISPATCHED)
|
|
369
|
+
.where(({ not, exists, selectFrom }) => not(exists(selectFrom("device_retirement_members as m")
|
|
370
|
+
.select("m.ref_id")
|
|
371
|
+
.where("m.kind", "=", "legacy-task")
|
|
372
|
+
.whereRef("m.ref_id", "=", "t.id"))));
|
|
373
|
+
if (deviceId !== undefined)
|
|
374
|
+
q = q.where("t.device_id", "=", deviceId);
|
|
375
|
+
return q;
|
|
376
|
+
}
|
|
377
|
+
async scanLegacyTasks(deviceId) {
|
|
378
|
+
const rows = await this.legacyCandidates(deviceId)
|
|
379
|
+
.orderBy("t.started_at", "asc")
|
|
380
|
+
.orderBy("t.id", "asc")
|
|
381
|
+
.execute();
|
|
382
|
+
let added = 0;
|
|
383
|
+
for (const r of rows) {
|
|
384
|
+
const deviceId = r.device_id;
|
|
385
|
+
const { provider, generation } = legacyKey(r);
|
|
386
|
+
if (await this.addMember(deviceId, r.org_id, provider, generation, "legacy-task", r.id))
|
|
387
|
+
added++;
|
|
388
|
+
}
|
|
389
|
+
return added;
|
|
390
|
+
}
|
|
391
|
+
/** Revoked managed starts on an incarnation that no longer runs, not members yet. */
|
|
392
|
+
revokedCandidates(deviceId) {
|
|
393
|
+
let q = this.db
|
|
394
|
+
.selectFrom("sandbox_operation_intents as o")
|
|
395
|
+
.select(["o.operation_id", "o.org_id", "o.device_id", "o.provider", "o.instance_generation"])
|
|
396
|
+
.where("o.method", "=", "backgroundStart")
|
|
397
|
+
.where("o.state", "=", "revoked")
|
|
398
|
+
.where("o.revoke_acknowledged", "=", false)
|
|
399
|
+
.where("o.execution_ref", "is not", null)
|
|
400
|
+
// the recorded incarnation is no longer the one running (replaced, destroyed, suspended):
|
|
401
|
+
// the revoke worker cannot reach it there
|
|
402
|
+
.where(({ not, exists, selectFrom }) => not(exists(selectFrom("device_instances as d")
|
|
403
|
+
.select("d.device_id")
|
|
404
|
+
.whereRef("d.device_id", "=", "o.device_id")
|
|
405
|
+
.whereRef("d.provider", "=", "o.provider")
|
|
406
|
+
.where("d.status", "=", "running")
|
|
407
|
+
.where(sql `floor(extract(epoch from d.created_at) * 1000)::bigint::text = o.instance_generation`))))
|
|
408
|
+
.where(({ not, exists, selectFrom }) => not(exists(selectFrom("device_retirement_members as m")
|
|
409
|
+
.select("m.ref_id")
|
|
410
|
+
.where("m.kind", "=", "revoked-start")
|
|
411
|
+
.whereRef("m.ref_id", "=", "o.operation_id"))));
|
|
412
|
+
if (deviceId !== undefined)
|
|
413
|
+
q = q.where("o.device_id", "=", deviceId);
|
|
414
|
+
return q;
|
|
415
|
+
}
|
|
416
|
+
async scanRevokedStarts(deviceId) {
|
|
417
|
+
const rows = await this.revokedCandidates(deviceId).orderBy("o.operation_id").execute();
|
|
418
|
+
let added = 0;
|
|
419
|
+
for (const r of rows) {
|
|
420
|
+
const generation = GENERATION_RE.test(r.instance_generation)
|
|
421
|
+
? r.instance_generation
|
|
422
|
+
: "unknown";
|
|
423
|
+
if (await this.addMember(r.device_id, r.org_id, r.provider, generation, "revoked-start", r.operation_id))
|
|
424
|
+
added++;
|
|
425
|
+
}
|
|
426
|
+
return added;
|
|
427
|
+
}
|
|
428
|
+
/** The obligation of the incarnation (created when missing), with the member added. */
|
|
429
|
+
async addMember(deviceId, orgId, provider, generation, kind, refId) {
|
|
430
|
+
// a local incarnation keeps the boot its machine reported last: only a later boot of that
|
|
431
|
+
// machine proves its processes gone (none reported: never by itself)
|
|
432
|
+
const boot = isCloudProvider(provider) ? null : await this.currentBoot(deviceId);
|
|
433
|
+
await this.db
|
|
434
|
+
.insertInto("device_retirement_obligations")
|
|
435
|
+
.values({
|
|
436
|
+
device_id: deviceId,
|
|
437
|
+
org_id: orgId,
|
|
438
|
+
provider,
|
|
439
|
+
instance_generation: generation,
|
|
440
|
+
boot_machine_id: boot?.machineId ?? null,
|
|
441
|
+
boot_id: boot?.bootId ?? null,
|
|
442
|
+
})
|
|
443
|
+
.onConflict((oc) => oc.columns(["device_id", "provider", "instance_generation"]).doNothing())
|
|
444
|
+
.execute();
|
|
445
|
+
const obligation = await this.db
|
|
446
|
+
.selectFrom("device_retirement_obligations")
|
|
447
|
+
.select(["id", "state", "resolution"])
|
|
448
|
+
.where("device_id", "=", deviceId)
|
|
449
|
+
.where("provider", "=", provider)
|
|
450
|
+
.where("instance_generation", "=", generation)
|
|
451
|
+
.forUpdate()
|
|
452
|
+
.executeTakeFirstOrThrow();
|
|
453
|
+
const r = await this.db
|
|
454
|
+
.insertInto("device_retirement_members")
|
|
455
|
+
.values({ obligation_id: obligation.id, kind, ref_id: refId })
|
|
456
|
+
.onConflict((oc) => oc.columns(["kind", "ref_id", "obligation_id"]).doNothing())
|
|
457
|
+
.returning("ref_id")
|
|
458
|
+
.executeTakeFirst();
|
|
459
|
+
// a restart covers only what ran before it: a member found later (a row of an old replica) on
|
|
460
|
+
// the same local incarnation reopens the obligation against the current boot; an exact
|
|
461
|
+
// cancel covers only the refs it stopped, and the incarnation lives on (B-22)
|
|
462
|
+
if (r !== undefined &&
|
|
463
|
+
obligation.state === "resolved" &&
|
|
464
|
+
(obligation.resolution === "host-rebooted" || obligation.resolution === "exact-cancelled")) {
|
|
465
|
+
// read under the obligation's lock: a hello that resolved it meanwhile is seen (M1); a
|
|
466
|
+
// cloud incarnation has no boot
|
|
467
|
+
const now = isCloudProvider(provider) ? null : await this.currentBoot(deviceId);
|
|
468
|
+
await this.db
|
|
469
|
+
.updateTable("device_retirement_obligations")
|
|
470
|
+
.set({
|
|
471
|
+
state: "open",
|
|
472
|
+
resolution: null,
|
|
473
|
+
resolved_at: null,
|
|
474
|
+
boot_machine_id: now?.machineId ?? null,
|
|
475
|
+
boot_id: now?.bootId ?? null,
|
|
476
|
+
})
|
|
477
|
+
.where("id", "=", obligation.id)
|
|
478
|
+
.execute();
|
|
479
|
+
}
|
|
480
|
+
return r !== undefined;
|
|
481
|
+
}
|
|
482
|
+
/** The device's active machine and the boot it reported last (null: no machine). */
|
|
483
|
+
async currentBoot(deviceId) {
|
|
484
|
+
const m = await this.db
|
|
485
|
+
.selectFrom("device_machines")
|
|
486
|
+
.select(["id", "boot_id"])
|
|
487
|
+
.where("device_id", "=", deviceId)
|
|
488
|
+
.where("revoked_at", "is", null)
|
|
489
|
+
.orderBy("created_at", "desc")
|
|
490
|
+
.orderBy("id", "desc")
|
|
491
|
+
.limit(1)
|
|
492
|
+
.executeTakeFirst();
|
|
493
|
+
return m ? { machineId: m.id, bootId: m.boot_id } : null;
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Records the OS boot identity an authenticated hello of `machineId` reported. The caller is the
|
|
497
|
+
* gateway's hello record, after the connection authenticated with the machine's credential and
|
|
498
|
+
* claimed the device, inside its transaction with the machine row locked. A boot first seen for
|
|
499
|
+
* the machine becomes its current one; the current one again is a reconnect; one seen before a
|
|
500
|
+
* later one (stale, replayed) changes nothing. A new or current boot then settles the device's
|
|
501
|
+
* local obligations recorded under another boot of the computer ({@link settleRebooted}).
|
|
502
|
+
*/
|
|
503
|
+
async recordBoot(machineId, bootId) {
|
|
504
|
+
if (!isDeviceBootId(bootId))
|
|
505
|
+
return "ignored";
|
|
506
|
+
const machine = await this.db
|
|
507
|
+
.selectFrom("device_machines")
|
|
508
|
+
.select(["device_id", "boot_id"])
|
|
509
|
+
.where("id", "=", machineId)
|
|
510
|
+
.where("revoked_at", "is", null)
|
|
511
|
+
.executeTakeFirst();
|
|
512
|
+
if (!machine)
|
|
513
|
+
return "ignored";
|
|
514
|
+
const inserted = await this.db
|
|
515
|
+
.insertInto("device_machine_boots")
|
|
516
|
+
.values({ machine_id: machineId, boot_id: bootId })
|
|
517
|
+
.onConflict((oc) => oc.columns(["machine_id", "boot_id"]).doNothing())
|
|
518
|
+
.returning("seq")
|
|
519
|
+
.executeTakeFirst();
|
|
520
|
+
let report;
|
|
521
|
+
if (inserted !== undefined) {
|
|
522
|
+
await this.db
|
|
523
|
+
.updateTable("device_machines")
|
|
524
|
+
.set({ boot_id: bootId })
|
|
525
|
+
.where("id", "=", machineId)
|
|
526
|
+
.execute();
|
|
527
|
+
report = "new";
|
|
528
|
+
}
|
|
529
|
+
else if (machine.boot_id === bootId)
|
|
530
|
+
report = "current";
|
|
531
|
+
else
|
|
532
|
+
return "stale";
|
|
533
|
+
await this.settleRebooted(machine.device_id);
|
|
534
|
+
return report;
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* A hello without a boot identity: the machine has no current boot any more, so a boot it
|
|
538
|
+
* reported earlier is never taken as the one its later work ran under (M2).
|
|
539
|
+
*/
|
|
540
|
+
async clearBoot(machineId) {
|
|
541
|
+
await this.db
|
|
542
|
+
.updateTable("device_machines")
|
|
543
|
+
.set({ boot_id: null })
|
|
544
|
+
.where("id", "=", machineId)
|
|
545
|
+
.execute();
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Resolves (`host-rebooted`) every unresolved local obligation of the device for which a current
|
|
549
|
+
* (non-revoked) machine of the device has recorded a boot other than the obligation's: the
|
|
550
|
+
* evidence is the OS instance, not the credential, so a re-login on the same computer reporting
|
|
551
|
+
* the same boot changes nothing, and one after a restart (or any later boot) resolves it. A boot
|
|
552
|
+
* that some machine of the device had already reported when the obligation's boot was first
|
|
553
|
+
* seen is an older boot, never evidence (a replay through another credential). An obligation
|
|
554
|
+
* without a recorded boot never resolves here. Returns how many resolved.
|
|
555
|
+
*/
|
|
556
|
+
async settleRebooted(deviceId) {
|
|
557
|
+
const r = await this.db
|
|
558
|
+
.updateTable("device_retirement_obligations as o")
|
|
559
|
+
.set({
|
|
560
|
+
state: "resolved",
|
|
561
|
+
resolution: "host-rebooted",
|
|
562
|
+
resolved_at: sql `now()`,
|
|
563
|
+
last_error: null,
|
|
564
|
+
})
|
|
565
|
+
.where("o.device_id", "=", deviceId)
|
|
566
|
+
.where("o.state", "in", ["open", "quarantined"])
|
|
567
|
+
.where("o.provider", "like", "@%")
|
|
568
|
+
.where("o.boot_id", "is not", null)
|
|
569
|
+
.where(({ exists, selectFrom }) => exists(selectFrom("device_machines as m")
|
|
570
|
+
.select("m.id")
|
|
571
|
+
.whereRef("m.device_id", "=", "o.device_id")
|
|
572
|
+
.where("m.revoked_at", "is", null)
|
|
573
|
+
.where("m.boot_id", "is not", null)
|
|
574
|
+
.whereRef("m.boot_id", "<>", "o.boot_id")
|
|
575
|
+
// not a boot the device's machines had already reported by the obligation's boot
|
|
576
|
+
.where((inner) => inner.not(inner.exists(inner
|
|
577
|
+
.selectFrom("device_machine_boots as seen")
|
|
578
|
+
.innerJoin("device_machines as sm", "sm.id", "seen.machine_id")
|
|
579
|
+
.select("seen.boot_id")
|
|
580
|
+
.whereRef("sm.device_id", "=", "o.device_id")
|
|
581
|
+
.whereRef("seen.boot_id", "=", "m.boot_id")
|
|
582
|
+
.where((e) => e("seen.seq", "<=", e
|
|
583
|
+
.selectFrom("device_machine_boots as ob")
|
|
584
|
+
.innerJoin("device_machines as om", "om.id", "ob.machine_id")
|
|
585
|
+
.select((f) => f.fn.min("ob.seq").as("first"))
|
|
586
|
+
.whereRef("om.device_id", "=", "o.device_id")
|
|
587
|
+
.whereRef("ob.boot_id", "=", "o.boot_id"))))))))
|
|
588
|
+
.executeTakeFirst();
|
|
589
|
+
return Number(r.numUpdatedRows);
|
|
590
|
+
}
|
|
591
|
+
/** The device's unresolved obligations (open and quarantined), oldest first. */
|
|
592
|
+
async unresolved(deviceId) {
|
|
593
|
+
const rows = await this.db
|
|
594
|
+
.selectFrom("device_retirement_obligations")
|
|
595
|
+
.select([
|
|
596
|
+
"id",
|
|
597
|
+
"device_id",
|
|
598
|
+
"org_id",
|
|
599
|
+
"provider",
|
|
600
|
+
"instance_generation",
|
|
601
|
+
"state",
|
|
602
|
+
"reason",
|
|
603
|
+
"attempts",
|
|
604
|
+
"boot_id",
|
|
605
|
+
"created_at",
|
|
606
|
+
])
|
|
607
|
+
.where("device_id", "=", deviceId)
|
|
608
|
+
.where("state", "in", ["open", "quarantined"])
|
|
609
|
+
.orderBy("created_at", "asc")
|
|
610
|
+
.orderBy("id", "asc")
|
|
611
|
+
.execute();
|
|
612
|
+
return rows.map(toObligation);
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Whether the device has an unresolved obligation, or a candidate not enumerated yet (a legacy
|
|
616
|
+
* row once frozen, a revoked start): the shared-path check. A candidate counts as unresolved, so
|
|
617
|
+
* the device goes to the gate, which enumerates it under the exclusive lease (C1).
|
|
618
|
+
*/
|
|
619
|
+
async hasUnresolved(deviceId) {
|
|
620
|
+
const row = await this.db
|
|
621
|
+
.selectFrom("device_retirement_obligations")
|
|
622
|
+
.select("id")
|
|
623
|
+
.where("device_id", "=", deviceId)
|
|
624
|
+
.where("state", "in", ["open", "quarantined"])
|
|
625
|
+
.limit(1)
|
|
626
|
+
.executeTakeFirst();
|
|
627
|
+
if (row !== undefined)
|
|
628
|
+
return true;
|
|
629
|
+
if ((await this.revokedCandidates(deviceId).limit(1).executeTakeFirst()) !== undefined)
|
|
630
|
+
return true;
|
|
631
|
+
// an exact-cancelled obligation a member was added to after the cancel (a rolling upgrade)
|
|
632
|
+
const late = await this.db
|
|
633
|
+
.selectFrom("device_retirement_obligations as o")
|
|
634
|
+
.select("o.id")
|
|
635
|
+
.where("o.device_id", "=", deviceId)
|
|
636
|
+
.where("o.state", "=", "resolved")
|
|
637
|
+
.where("o.resolution", "=", "exact-cancelled")
|
|
638
|
+
.where(({ exists }) => exists(this.lateMember()))
|
|
639
|
+
.limit(1)
|
|
640
|
+
.executeTakeFirst();
|
|
641
|
+
if (late !== undefined)
|
|
642
|
+
return true;
|
|
643
|
+
return ((await this.frozen()) &&
|
|
644
|
+
(await this.legacyCandidates(deviceId).limit(1).executeTakeFirst()) !== undefined);
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* No trusted way to establish termination: the obligation is quarantined (the device stays
|
|
648
|
+
* unavailable). A resolved obligation is left as it is.
|
|
649
|
+
*/
|
|
650
|
+
async quarantine(id, reason) {
|
|
651
|
+
await this.db
|
|
652
|
+
.updateTable("device_retirement_obligations")
|
|
653
|
+
.set((eb) => ({
|
|
654
|
+
state: "quarantined",
|
|
655
|
+
reason: reason.slice(0, 1000),
|
|
656
|
+
attempts: eb("attempts", "+", 1),
|
|
657
|
+
last_attempt_at: sql `now()`,
|
|
658
|
+
}))
|
|
659
|
+
.where("id", "=", id)
|
|
660
|
+
.where("state", "in", ["open", "quarantined"])
|
|
661
|
+
.execute();
|
|
662
|
+
}
|
|
663
|
+
/** A failed destroy or verification: the obligation stays as it is, the attempt is recorded. */
|
|
664
|
+
async noteFailure(id, error) {
|
|
665
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
666
|
+
await this.db
|
|
667
|
+
.updateTable("device_retirement_obligations")
|
|
668
|
+
.set((eb) => ({
|
|
669
|
+
attempts: eb("attempts", "+", 1),
|
|
670
|
+
last_attempt_at: sql `now()`,
|
|
671
|
+
last_error: text.slice(0, 1000),
|
|
672
|
+
}))
|
|
673
|
+
.where("id", "=", id)
|
|
674
|
+
.where("state", "in", ["open", "quarantined"])
|
|
675
|
+
.execute();
|
|
676
|
+
}
|
|
677
|
+
/** The provider confirmed the incarnation destroyed: the obligation resolves. */
|
|
678
|
+
async resolveDestroyed(id) {
|
|
679
|
+
await this.db
|
|
680
|
+
.updateTable("device_retirement_obligations")
|
|
681
|
+
.set({
|
|
682
|
+
state: "resolved",
|
|
683
|
+
resolution: "provider-destroyed",
|
|
684
|
+
resolved_at: sql `now()`,
|
|
685
|
+
last_error: null,
|
|
686
|
+
})
|
|
687
|
+
.where("id", "=", id)
|
|
688
|
+
.where("state", "in", ["open", "quarantined"])
|
|
689
|
+
.execute();
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* The provider confirmed the exact cancellation of the revoked managed starts `covered` on the
|
|
693
|
+
* resumed incarnation (B-22): under the obligation's row lock (the lock {@link addMember} takes
|
|
694
|
+
* before it adds a member), resolves it as `exact-cancelled` and acknowledges those
|
|
695
|
+
* revocations, only while every member is one of them. False (nothing changed) when a member
|
|
696
|
+
* outside `covered` exists, which was never stopped: the caller destroys the incarnation
|
|
697
|
+
* instead. Acknowledging here is what tells a member added later apart ({@link scan}).
|
|
698
|
+
*/
|
|
699
|
+
async resolveCancelled(id, covered) {
|
|
700
|
+
const o = await this.db
|
|
701
|
+
.selectFrom("device_retirement_obligations")
|
|
702
|
+
.select(["state"])
|
|
703
|
+
.where("id", "=", id)
|
|
704
|
+
.forUpdate()
|
|
705
|
+
.executeTakeFirst();
|
|
706
|
+
if (o === undefined || (o.state !== "open" && o.state !== "quarantined"))
|
|
707
|
+
return false;
|
|
708
|
+
const members = await this.db
|
|
709
|
+
.selectFrom("device_retirement_members")
|
|
710
|
+
.select(["kind", "ref_id"])
|
|
711
|
+
.where("obligation_id", "=", id)
|
|
712
|
+
.execute();
|
|
713
|
+
const set = new Set(covered);
|
|
714
|
+
if (members.length === 0 ||
|
|
715
|
+
members.some((m) => m.kind !== "revoked-start" || !set.has(m.ref_id)))
|
|
716
|
+
return false;
|
|
717
|
+
await this.db
|
|
718
|
+
.updateTable("sandbox_operation_intents")
|
|
719
|
+
.set({ revoke_acknowledged: true, updated_at: new Date() })
|
|
720
|
+
.where("operation_id", "in", [...set])
|
|
721
|
+
.where("state", "=", "revoked")
|
|
722
|
+
.execute();
|
|
723
|
+
await this.db
|
|
724
|
+
.updateTable("device_retirement_obligations")
|
|
725
|
+
.set({
|
|
726
|
+
state: "resolved",
|
|
727
|
+
resolution: "exact-cancelled",
|
|
728
|
+
resolved_at: sql `now()`,
|
|
729
|
+
last_error: null,
|
|
730
|
+
})
|
|
731
|
+
.where("id", "=", id)
|
|
732
|
+
.execute();
|
|
733
|
+
return true;
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Reopens `exact-cancelled` obligations holding a member nobody stopped: a legacy row, or a
|
|
737
|
+
* revoked start whose intent is not there acknowledged, a missing intent included (every
|
|
738
|
+
* member the cancel covered was acknowledged with the resolution). A replica without the reopen in {@link addMember} (a
|
|
739
|
+
* rolling upgrade) adds such members to a resolved obligation; the next scan of a new one
|
|
740
|
+
* reopens it. Returns how many it reopened.
|
|
741
|
+
*/
|
|
742
|
+
async reopenLateMembers(deviceId) {
|
|
743
|
+
let q = this.db
|
|
744
|
+
.updateTable("device_retirement_obligations as o")
|
|
745
|
+
.set({ state: "open", resolution: null, resolved_at: null })
|
|
746
|
+
.where("o.state", "=", "resolved")
|
|
747
|
+
.where("o.resolution", "=", "exact-cancelled")
|
|
748
|
+
.where(({ exists }) => exists(this.lateMember()));
|
|
749
|
+
if (deviceId !== undefined)
|
|
750
|
+
q = q.where("o.device_id", "=", deviceId);
|
|
751
|
+
const r = await q.executeTakeFirst();
|
|
752
|
+
return Number(r.numUpdatedRows);
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* A member of obligation `o` an exact cancel never covered (see {@link reopenLateMembers}),
|
|
756
|
+
* correlated on `o.id`.
|
|
757
|
+
*/
|
|
758
|
+
lateMember() {
|
|
759
|
+
// fail closed: a revoked start is covered only when its intent exists acknowledged (a missing
|
|
760
|
+
// intent row proves nothing was stopped)
|
|
761
|
+
return this.db
|
|
762
|
+
.selectFrom("device_retirement_members as lm")
|
|
763
|
+
.select("lm.ref_id")
|
|
764
|
+
.where(sql `lm.obligation_id = o.id`)
|
|
765
|
+
.where((eb) => eb.or([
|
|
766
|
+
eb("lm.kind", "=", "legacy-task"),
|
|
767
|
+
eb.not(eb.exists(eb
|
|
768
|
+
.selectFrom("sandbox_operation_intents as li")
|
|
769
|
+
.select("li.operation_id")
|
|
770
|
+
.whereRef("li.operation_id", "=", "lm.ref_id")
|
|
771
|
+
.where("li.revoke_acknowledged", "=", true))),
|
|
772
|
+
]));
|
|
773
|
+
}
|
|
774
|
+
/** The members of one obligation, oldest first. */
|
|
775
|
+
async membersOf(obligationId) {
|
|
776
|
+
const rows = await this.db
|
|
777
|
+
.selectFrom("device_retirement_members")
|
|
778
|
+
.select(["obligation_id", "kind", "ref_id"])
|
|
779
|
+
.where("obligation_id", "=", obligationId)
|
|
780
|
+
.orderBy("created_at", "asc")
|
|
781
|
+
.orderBy("ref_id", "asc")
|
|
782
|
+
.execute();
|
|
783
|
+
return rows.map((r) => ({ obligationId: r.obligation_id, kind: r.kind, refId: r.ref_id }));
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Records the provider-confirmed destruction of a cloud incarnation. A kernel-internal
|
|
787
|
+
* provider's destroy (a local machine: a no-op) is never evidence and is refused.
|
|
788
|
+
*/
|
|
789
|
+
async recordDestruction(deviceId, provider, generation) {
|
|
790
|
+
if (!isCloudProvider(provider))
|
|
791
|
+
throw new Error(`A ${provider} destroy is not evidence of destruction`);
|
|
792
|
+
if (!GENERATION_RE.test(generation))
|
|
793
|
+
throw new Error(`invalid generation ${generation}`);
|
|
794
|
+
await this.db
|
|
795
|
+
.insertInto("device_instance_destructions")
|
|
796
|
+
.values({ device_id: deviceId, provider, instance_generation: generation })
|
|
797
|
+
.onConflict((oc) => oc.columns(["device_id", "provider", "instance_generation"]).doNothing())
|
|
798
|
+
.execute();
|
|
799
|
+
}
|
|
800
|
+
/** Whether a confirmed destruction of exactly that cloud incarnation was recorded. */
|
|
801
|
+
async destructionRecorded(deviceId, provider, generation) {
|
|
802
|
+
if (!isCloudProvider(provider) || !GENERATION_RE.test(generation))
|
|
803
|
+
return false;
|
|
804
|
+
const row = await this.db
|
|
805
|
+
.selectFrom("device_instance_destructions")
|
|
806
|
+
.select("device_id")
|
|
807
|
+
.where("device_id", "=", deviceId)
|
|
808
|
+
.where("provider", "=", provider)
|
|
809
|
+
.where("instance_generation", "=", generation)
|
|
810
|
+
.executeTakeFirst();
|
|
811
|
+
return row !== undefined;
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* Devices with an unresolved obligation the worker should try now: never attempted, or last
|
|
815
|
+
* attempted longer ago than the backoff (30 s doubling per attempt, at most an hour).
|
|
816
|
+
*/
|
|
817
|
+
async due(limit) {
|
|
818
|
+
const rows = await this.db
|
|
819
|
+
.selectFrom("device_retirement_obligations")
|
|
820
|
+
.select("device_id")
|
|
821
|
+
.where("state", "in", ["open", "quarantined"])
|
|
822
|
+
.where(sql `(last_attempt_at IS NULL OR last_attempt_at <
|
|
823
|
+
now() - LEAST(3600, 30 * power(2, LEAST(attempts, 7))) * interval '1 second')`)
|
|
824
|
+
.groupBy("device_id")
|
|
825
|
+
.orderBy(sql `min(last_attempt_at) ASC NULLS FIRST`)
|
|
826
|
+
.orderBy("device_id")
|
|
827
|
+
.limit(limit)
|
|
828
|
+
.execute();
|
|
829
|
+
return rows.map((r) => r.device_id);
|
|
830
|
+
}
|
|
831
|
+
/** Members of resolved obligations whose own records are not settled yet. */
|
|
832
|
+
async unsettledMembers(limit) {
|
|
833
|
+
const rows = await this.db
|
|
834
|
+
.selectFrom("device_retirement_members as m")
|
|
835
|
+
.innerJoin("device_retirement_obligations as o", "o.id", "m.obligation_id")
|
|
836
|
+
.select(["m.obligation_id", "m.kind", "m.ref_id"])
|
|
837
|
+
.where("o.state", "=", "resolved")
|
|
838
|
+
.where("m.settled", "=", false)
|
|
839
|
+
// a member an exact cancel never covered is not settled (acknowledged unstopped): the next
|
|
840
|
+
// scan reopens its obligation
|
|
841
|
+
.where(({ eb, exists, selectFrom }) => eb.or([
|
|
842
|
+
eb("o.resolution", "is", null),
|
|
843
|
+
eb("o.resolution", "!=", "exact-cancelled"),
|
|
844
|
+
exists(selectFrom("sandbox_operation_intents as ui")
|
|
845
|
+
.select("ui.operation_id")
|
|
846
|
+
.whereRef("ui.operation_id", "=", "m.ref_id")
|
|
847
|
+
.where("ui.revoke_acknowledged", "=", true)),
|
|
848
|
+
]))
|
|
849
|
+
.where(({ eb, and }) => eb.not(and([eb("o.resolution", "=", "exact-cancelled"), eb("m.kind", "=", "legacy-task")])))
|
|
850
|
+
.orderBy("m.created_at", "asc")
|
|
851
|
+
.limit(limit)
|
|
852
|
+
.execute();
|
|
853
|
+
return rows.map((r) => ({ obligationId: r.obligation_id, kind: r.kind, refId: r.ref_id }));
|
|
854
|
+
}
|
|
855
|
+
async markSettled(m) {
|
|
856
|
+
await this.db
|
|
857
|
+
.updateTable("device_retirement_members")
|
|
858
|
+
.set({ settled: true })
|
|
859
|
+
.where("obligation_id", "=", m.obligationId)
|
|
860
|
+
.where("kind", "=", m.kind)
|
|
861
|
+
.where("ref_id", "=", m.refId)
|
|
862
|
+
.execute();
|
|
863
|
+
}
|
|
864
|
+
/**
|
|
865
|
+
* Legacy rows without the dispatch marker started after the marker's migration was applied:
|
|
866
|
+
* only a replica without the 8.5 code writes them (see {@link LegacyRetirementReport}).
|
|
867
|
+
*/
|
|
868
|
+
async unfencedWriters(state) {
|
|
869
|
+
// the migrator's own bookkeeping (schema `capybara`, `migrate()`): when 0157 was applied
|
|
870
|
+
const applied = await sql `SELECT applied_at FROM capybara._migrations
|
|
871
|
+
WHERE name = ${MARKER_MIGRATION}`.execute(this.db.db);
|
|
872
|
+
const since = applied.rows[0]?.applied_at;
|
|
873
|
+
if (since === undefined)
|
|
874
|
+
return { sinceMigration: 0, afterFreeze: 0, afterEnumeration: 0, recent: 0, latestAt: null };
|
|
875
|
+
const after = (at) => sql `CASE WHEN started_at > ${at}::timestamptz THEN 1 END`;
|
|
876
|
+
const row = await this.db
|
|
877
|
+
.selectFrom("background_tasks")
|
|
878
|
+
.select((eb) => [
|
|
879
|
+
eb.fn.countAll().as("n"),
|
|
880
|
+
eb.fn.count(after(state.frozenAt)).as("after"),
|
|
881
|
+
eb.fn.count(after(state.enumeratedAt)).as("afterEnumeration"),
|
|
882
|
+
// by the database clock, the one that stamped started_at
|
|
883
|
+
eb.fn
|
|
884
|
+
.count(sql `CASE WHEN started_at > now() - ${RECENT}::interval THEN 1 END`)
|
|
885
|
+
.as("recent"),
|
|
886
|
+
eb.fn.max("started_at").as("latest"),
|
|
887
|
+
])
|
|
888
|
+
.where("launch_state", "=", "legacy")
|
|
889
|
+
.where("legacy_dispatch", "=", "unknown")
|
|
890
|
+
.where("started_at", ">", since)
|
|
891
|
+
.executeTakeFirstOrThrow();
|
|
892
|
+
return {
|
|
893
|
+
sinceMigration: Number(row.n),
|
|
894
|
+
afterFreeze: Number(row.after),
|
|
895
|
+
afterEnumeration: Number(row.afterEnumeration),
|
|
896
|
+
recent: Number(row.recent),
|
|
897
|
+
latestAt: row.latest ?? null,
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
/** The release gate's honest view (a quarantined device is unavailable, not retired). */
|
|
901
|
+
async report() {
|
|
902
|
+
const freeze = await this.freezeState();
|
|
903
|
+
const frozen = freeze.frozenAt !== null;
|
|
904
|
+
const fenced = await this.db
|
|
905
|
+
.selectFrom("background_tasks")
|
|
906
|
+
.select((eb) => eb.fn.countAll().as("n"))
|
|
907
|
+
.where("launch_state", "=", "legacy")
|
|
908
|
+
.where("status", "=", "running")
|
|
909
|
+
.where("sid", "is", null)
|
|
910
|
+
.where("legacy_dispatch", "=", "reserved")
|
|
911
|
+
.executeTakeFirstOrThrow();
|
|
912
|
+
const unfenced = await this.unfencedWriters(freeze);
|
|
913
|
+
const counts = await this.db
|
|
914
|
+
.selectFrom("device_retirement_obligations")
|
|
915
|
+
.select(["state", (eb) => eb.fn.countAll().as("n")])
|
|
916
|
+
.groupBy("state")
|
|
917
|
+
.execute();
|
|
918
|
+
const n = (s) => Number(counts.find((c) => c.state === s)?.n ?? 0);
|
|
919
|
+
const unsettled = await this.db
|
|
920
|
+
.selectFrom("device_retirement_members as m")
|
|
921
|
+
.innerJoin("device_retirement_obligations as o", "o.id", "m.obligation_id")
|
|
922
|
+
.select((eb) => eb.fn.countAll().as("n"))
|
|
923
|
+
.where("o.state", "=", "resolved")
|
|
924
|
+
.where("m.settled", "=", false)
|
|
925
|
+
.executeTakeFirstOrThrow();
|
|
926
|
+
const unresolved = await this.db
|
|
927
|
+
.selectFrom("device_retirement_obligations")
|
|
928
|
+
.select(["device_id", "provider", "instance_generation", "state", "reason", "boot_id"])
|
|
929
|
+
.where("state", "in", ["open", "quarantined"])
|
|
930
|
+
.orderBy("created_at", "asc")
|
|
931
|
+
.execute();
|
|
932
|
+
const withoutBoot = await this.db
|
|
933
|
+
.selectFrom("background_tasks as t")
|
|
934
|
+
.innerJoin("devices as d", "d.id", "t.device_id")
|
|
935
|
+
.leftJoin("device_machines as m", (j) => j.onRef("m.device_id", "=", "d.id").on("m.revoked_at", "is", null))
|
|
936
|
+
.select(["t.device_id", "m.id as machine_id"])
|
|
937
|
+
.distinct()
|
|
938
|
+
.where("d.source", "=", "local")
|
|
939
|
+
.where("d.deleted_at", "is", null)
|
|
940
|
+
.where("t.launch_state", "=", "legacy")
|
|
941
|
+
.where(MAY_STILL_RUN)
|
|
942
|
+
.where(MAY_HAVE_DISPATCHED)
|
|
943
|
+
.where((eb) => eb.or([eb("m.id", "is", null), eb("m.boot_id", "is", null)]))
|
|
944
|
+
.orderBy("t.device_id")
|
|
945
|
+
.execute();
|
|
946
|
+
const abandonedRows = await this.db
|
|
947
|
+
.selectFrom("device_retirement_obligations")
|
|
948
|
+
.select(["device_id", "provider", "instance_generation", "boot_id", "abandoned_at"])
|
|
949
|
+
.where("state", "=", "abandoned")
|
|
950
|
+
.orderBy("abandoned_at", "asc")
|
|
951
|
+
.execute();
|
|
952
|
+
const abandonedMembers = await this.db
|
|
953
|
+
.selectFrom("device_retirement_members as m")
|
|
954
|
+
.innerJoin("device_retirement_obligations as o", "o.id", "m.obligation_id")
|
|
955
|
+
.select((eb) => eb.fn.countAll().as("n"))
|
|
956
|
+
.where("o.state", "=", "abandoned")
|
|
957
|
+
.executeTakeFirstOrThrow();
|
|
958
|
+
const cloudCandidates = await this.db
|
|
959
|
+
.selectFrom("background_tasks as t")
|
|
960
|
+
.innerJoin("devices as d", "d.id", "t.device_id")
|
|
961
|
+
.leftJoin("device_instances as i", "i.device_id", "t.device_id")
|
|
962
|
+
.select([
|
|
963
|
+
"t.device_id",
|
|
964
|
+
"t.sandbox_created_at",
|
|
965
|
+
"t.legacy_dispatch_generation",
|
|
966
|
+
"t.legacy_dispatch_provider",
|
|
967
|
+
"i.provider as instance_provider",
|
|
968
|
+
"i.created_at as instance_created_at",
|
|
969
|
+
"i.prev_handle",
|
|
970
|
+
"i.status as instance_status",
|
|
971
|
+
"i.handle as instance_handle",
|
|
972
|
+
"i.had_instance",
|
|
973
|
+
])
|
|
974
|
+
.where("d.source", "=", "cloud")
|
|
975
|
+
.where("d.deleted_at", "is", null)
|
|
976
|
+
.where("t.launch_state", "=", "legacy")
|
|
977
|
+
.where(MAY_STILL_RUN)
|
|
978
|
+
.where(MAY_HAVE_DISPATCHED)
|
|
979
|
+
.orderBy("t.device_id")
|
|
980
|
+
.execute();
|
|
981
|
+
const cloudUnknown = new Map();
|
|
982
|
+
for (const r of cloudCandidates) {
|
|
983
|
+
const key = legacyKey({ ...r, source: "cloud" });
|
|
984
|
+
if (key.generation !== "unknown" && key.provider !== "unknown")
|
|
985
|
+
continue;
|
|
986
|
+
if (cloudUnknown.has(r.device_id))
|
|
987
|
+
continue;
|
|
988
|
+
const live = r.instance_handle !== null &&
|
|
989
|
+
(r.instance_status === "running" ||
|
|
990
|
+
r.instance_status === "suspended" ||
|
|
991
|
+
r.instance_status === "creating");
|
|
992
|
+
const createdAt = r.instance_created_at;
|
|
993
|
+
const noInstance = createdAt === null || r.had_instance !== true;
|
|
994
|
+
const currentUnconfirmed = createdAt !== null &&
|
|
995
|
+
!noInstance &&
|
|
996
|
+
!live &&
|
|
997
|
+
!(r.instance_provider !== null &&
|
|
998
|
+
(await this.destructionRecorded(r.device_id, r.instance_provider, generationOf(createdAt))));
|
|
999
|
+
cloudUnknown.set(r.device_id, {
|
|
1000
|
+
prevHandle: r.prev_handle !== null,
|
|
1001
|
+
noInstance,
|
|
1002
|
+
currentUnconfirmed,
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
const open = n("open"), quarantined = n("quarantined"), abandoned = n("abandoned"), unsettledMembers = Number(unsettled.n);
|
|
1006
|
+
const retired = frozen && open === 0 && quarantined === 0 && unsettledMembers === 0;
|
|
1007
|
+
return {
|
|
1008
|
+
frozen,
|
|
1009
|
+
frozenAt: freeze.frozenAt,
|
|
1010
|
+
freezeEnumeratedAt: freeze.enumeratedAt,
|
|
1011
|
+
fencedReservations: Number(fenced.n),
|
|
1012
|
+
unfencedWriters: unfenced,
|
|
1013
|
+
open,
|
|
1014
|
+
quarantined,
|
|
1015
|
+
resolved: n("resolved"),
|
|
1016
|
+
unsettledMembers,
|
|
1017
|
+
retired,
|
|
1018
|
+
cleanRetirement: retired && abandoned === 0,
|
|
1019
|
+
abandoned,
|
|
1020
|
+
abandonedMembers: Number(abandonedMembers.n),
|
|
1021
|
+
abandonedList: abandonedRows.map((r) => ({
|
|
1022
|
+
deviceId: r.device_id,
|
|
1023
|
+
provider: r.provider,
|
|
1024
|
+
instanceGeneration: r.instance_generation,
|
|
1025
|
+
local: isInternalProvider(r.provider),
|
|
1026
|
+
bootKnown: r.boot_id !== null,
|
|
1027
|
+
abandonedAt: r.abandoned_at,
|
|
1028
|
+
})),
|
|
1029
|
+
cloudUnknown: [...cloudUnknown].map(([deviceId, flags]) => ({ deviceId, ...flags })),
|
|
1030
|
+
localWithoutBoot: withoutBoot.map((r) => ({
|
|
1031
|
+
deviceId: r.device_id,
|
|
1032
|
+
machineId: r.machine_id,
|
|
1033
|
+
})),
|
|
1034
|
+
unresolved: unresolved.map((r) => ({
|
|
1035
|
+
deviceId: r.device_id,
|
|
1036
|
+
provider: r.provider,
|
|
1037
|
+
instanceGeneration: r.instance_generation,
|
|
1038
|
+
state: r.state,
|
|
1039
|
+
reason: r.reason,
|
|
1040
|
+
bootKnown: r.boot_id !== null,
|
|
1041
|
+
})),
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
};
|
|
1045
|
+
__decorate([
|
|
1046
|
+
Transactional({ propagation: "requires_new" })
|
|
1047
|
+
], LegacyRetirementStore.prototype, "publishFreeze", null);
|
|
1048
|
+
__decorate([
|
|
1049
|
+
Transactional({ propagation: "requires_new" })
|
|
1050
|
+
], LegacyRetirementStore.prototype, "admitLegacyDispatch", null);
|
|
1051
|
+
__decorate([
|
|
1052
|
+
Transactional({ propagation: "requires_new" })
|
|
1053
|
+
], LegacyRetirementStore.prototype, "addMember", null);
|
|
1054
|
+
__decorate([
|
|
1055
|
+
Transactional({ propagation: "requires_new" })
|
|
1056
|
+
], LegacyRetirementStore.prototype, "resolveCancelled", null);
|
|
1057
|
+
LegacyRetirementStore = __decorate([
|
|
1058
|
+
Injectable(),
|
|
1059
|
+
__param(0, Inject(KernelDb)),
|
|
1060
|
+
__param(1, Inject(TransactionHost)),
|
|
1061
|
+
__param(2, Inject(PermissionAuthorityLock))
|
|
1062
|
+
], LegacyRetirementStore);
|
|
1063
|
+
export { LegacyRetirementStore };
|