@capybara-hq/kernel 0.1.0-rc.80 → 0.1.0-rc.82

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.
Files changed (65) hide show
  1. package/bootstrap.json +29 -29
  2. package/dist/admin/outbox-dead.service.js +133 -120
  3. package/dist/background/store.js +78 -67
  4. package/dist/background/tasks.service.d.ts +6 -0
  5. package/dist/background/tasks.service.js +3 -0
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/catalog/plugin-import.js +45 -40
  8. package/dist/catalog/scope-sync-workers.js +3 -0
  9. package/dist/channels/inbound.d.ts +6 -1
  10. package/dist/channels/inbound.js +18 -1
  11. package/dist/client/client-reports.service.js +9 -6
  12. package/dist/config/schema.d.ts +5 -0
  13. package/dist/config/schema.js +6 -0
  14. package/dist/conversations/attachments.service.js +101 -96
  15. package/dist/conversations/events.d.ts +7 -0
  16. package/dist/conversations/events.js +9 -0
  17. package/dist/ctx/bus.js +5 -3
  18. package/dist/ctx/queue.js +4 -2
  19. package/dist/db/pool.d.ts +6 -0
  20. package/dist/db/pool.js +3 -2
  21. package/dist/devices/legacy-cleanup.job.js +73 -70
  22. package/dist/dial-in/gateway.d.ts +8 -0
  23. package/dist/dial-in/gateway.js +22 -2
  24. package/dist/extensions/admin-ops.js +22 -19
  25. package/dist/extensions/lifecycle-hooks.js +3 -1
  26. package/dist/http/app.js +3 -1
  27. package/dist/http/plugin-dispatch.js +8 -0
  28. package/dist/identity/auth.guard.js +13 -3
  29. package/dist/index.d.ts +2 -0
  30. package/dist/index.js +1 -0
  31. package/dist/infra/database/database.module.js +1 -0
  32. package/dist/infra/database/org-scope.d.ts +59 -0
  33. package/dist/infra/database/org-scope.js +68 -0
  34. package/dist/infra/database/rls-role.d.ts +11 -0
  35. package/dist/infra/database/rls-role.js +33 -0
  36. package/dist/infra/database/scoped-dialect.d.ts +18 -0
  37. package/dist/infra/database/scoped-dialect.js +245 -0
  38. package/dist/infra/outbox/outbox.dispatcher.js +98 -90
  39. package/dist/infra/outbox/outbox.service.js +29 -26
  40. package/dist/infra/queue/run-job.d.ts +8 -2
  41. package/dist/infra/queue/run-job.js +16 -3
  42. package/dist/infra/schedule/locked-tick.js +12 -4
  43. package/dist/infra/schedule/scheduled-runs.js +3 -1
  44. package/dist/lifecycle/kernel-lifecycle.d.ts +1 -0
  45. package/dist/lifecycle/kernel-lifecycle.js +16 -1
  46. package/dist/orgs/org.guard.js +4 -0
  47. package/dist/platform/sealed-reveals.js +9 -6
  48. package/dist/runtime/maintenance.js +6 -1
  49. package/dist/runtime/run-execution.d.ts +1 -0
  50. package/dist/runtime/run-execution.js +5 -0
  51. package/dist/runtime/run-orphan-check.job.js +20 -15
  52. package/dist/sandbox/legacy-retirement.js +438 -397
  53. package/dist/sandbox/modes.d.ts +10 -0
  54. package/dist/sandbox/modes.js +23 -0
  55. package/dist/sandbox/operation-reconcile.job.d.ts +14 -1
  56. package/dist/sandbox/operation-reconcile.job.js +35 -3
  57. package/dist/sandbox/permission-config-publication.js +83 -77
  58. package/dist/sandbox/sandbox.service.d.ts +24 -0
  59. package/dist/sandbox/sandbox.service.js +159 -62
  60. package/dist/schedules/store.js +17 -14
  61. package/dist/tools/builtins/sandbox/bash.js +16 -1
  62. package/dist/tools/drift.js +31 -24
  63. package/dist/tools/outputs.js +20 -17
  64. package/package.json +2 -2
  65. package/src/migrations/0182_rls_policies.sql +202 -0
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { asPlatform } from "../infra/database/org-scope.js";
13
14
  import { TransactionHost } from "../infra/database/transaction-host.js";
14
15
  import { Transactional } from "../infra/database/transactional.decorator.js";
15
16
  import { PermissionAuthorityLock } from "./permission-authority-lock.js";
@@ -214,67 +215,69 @@ let LegacyRetirementStore = class LegacyRetirementStore {
214
215
  * Returns the counts.
215
216
  */
216
217
  async abandonDeleted(limit) {
217
- let resolved = 0, abandoned = 0;
218
- // abandoned obligations that gained a matching recorded destruction
219
- const evidenced = await this.db
220
- .selectFrom("device_retirement_obligations as o")
221
- .innerJoin("device_instance_destructions as x", (j) => j
222
- .onRef("x.device_id", "=", "o.device_id")
223
- .onRef("x.provider", "=", "o.provider")
224
- .onRef("x.instance_generation", "=", "o.instance_generation"))
225
- .select("o.id")
226
- .where("o.state", "=", "abandoned")
227
- .limit(limit)
228
- .execute();
229
- for (const r of evidenced) {
230
- const u = await this.db
231
- .updateTable("device_retirement_obligations")
232
- .set({
233
- state: "resolved",
234
- resolution: "provider-destroyed",
235
- resolved_at: sql `now()`,
236
- abandoned_at: null,
237
- last_error: null,
238
- })
239
- .where("id", "=", r.id)
240
- .where("state", "=", "abandoned")
241
- .executeTakeFirst();
242
- resolved += Number(u.numUpdatedRows);
243
- }
244
- const rows = await this.db
245
- .selectFrom("device_retirement_obligations as o")
246
- .leftJoin("devices as d", "d.id", "o.device_id")
247
- .leftJoin("orgs as g", "g.id", "d.org_id")
248
- .select(["o.id", "o.device_id", "o.provider", "o.instance_generation"])
249
- .where("o.state", "in", ["open", "quarantined"])
250
- .where((eb) => eb.or([
251
- eb("d.id", "is", null),
252
- eb("d.deleted_at", "is not", null),
253
- eb("g.deleted_at", "is not", null),
254
- ]))
255
- // a destroy still owed keeps its instance row (R2-I2)
256
- .where((eb) => eb.not(eb.exists(eb
257
- .selectFrom("device_instances as i")
258
- .select("i.device_id")
259
- .whereRef("i.device_id", "=", "o.device_id"))))
260
- .orderBy("o.created_at")
261
- .limit(limit)
262
- .execute();
263
- for (const r of rows) {
264
- if (await this.destructionRecorded(r.device_id, r.provider, r.instance_generation)) {
265
- await this.resolveDestroyed(r.id);
266
- resolved++;
267
- continue;
218
+ return asPlatform("retirement of legacy launches across every org", async () => {
219
+ let resolved = 0, abandoned = 0;
220
+ // abandoned 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);
268
245
  }
269
- const u = await this.db
270
- .updateTable("device_retirement_obligations")
271
- .set({ state: "abandoned", abandoned_at: sql `now()` })
272
- .where("id", "=", r.id)
273
- .where("state", "in", ["open", "quarantined"])
274
- .executeTakeFirst();
275
- abandoned += Number(u.numUpdatedRows);
276
- }
277
- return { resolved, abandoned };
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 destroy still owed keeps its instance row (R2-I2)
258
+ .where((eb) => eb.not(eb.exists(eb
259
+ .selectFrom("device_instances as i")
260
+ .select("i.device_id")
261
+ .whereRef("i.device_id", "=", "o.device_id"))))
262
+ .orderBy("o.created_at")
263
+ .limit(limit)
264
+ .execute();
265
+ for (const r of rows) {
266
+ if (await this.destructionRecorded(r.device_id, r.provider, r.instance_generation)) {
267
+ await this.resolveDestroyed(r.id);
268
+ resolved++;
269
+ continue;
270
+ }
271
+ const u = await this.db
272
+ .updateTable("device_retirement_obligations")
273
+ .set({ state: "abandoned", abandoned_at: sql `now()` })
274
+ .where("id", "=", r.id)
275
+ .where("state", "in", ["open", "quarantined"])
276
+ .executeTakeFirst();
277
+ abandoned += Number(u.numUpdatedRows);
278
+ }
279
+ return { resolved, abandoned };
280
+ });
278
281
  }
279
282
  async frozen() {
280
283
  const row = await this.db
@@ -313,6 +316,8 @@ let LegacyRetirementStore = class LegacyRetirementStore {
313
316
  * all). The `(status = 'running' OR kill_pending OR sid IS NULL)` conjunct is the partial index's
314
317
  * predicate (0157), stated as is so the planner can use it.
315
318
  */
319
+ // org-filter: a query fragment, not run here: its callers (the retirement sweep's methods)
320
+ // execute it inside their asPlatform
316
321
  legacyCandidates(deviceId) {
317
322
  let q = this.db
318
323
  .selectFrom("background_tasks as t")
@@ -341,20 +346,24 @@ let LegacyRetirementStore = class LegacyRetirementStore {
341
346
  return q;
342
347
  }
343
348
  async scanLegacyTasks(deviceId) {
344
- const rows = await this.legacyCandidates(deviceId)
345
- .orderBy("t.started_at", "asc")
346
- .orderBy("t.id", "asc")
347
- .execute();
348
- let added = 0;
349
- for (const r of rows) {
350
- const deviceId = r.device_id;
351
- const { provider, generation } = legacyKey(r);
352
- if (await this.addMember(deviceId, r.org_id, provider, generation, "legacy-task", r.id))
353
- added++;
354
- }
355
- return added;
349
+ return asPlatform("retirement of legacy launches across every org", async () => {
350
+ const rows = await this.legacyCandidates(deviceId)
351
+ .orderBy("t.started_at", "asc")
352
+ .orderBy("t.id", "asc")
353
+ .execute();
354
+ let added = 0;
355
+ for (const r of rows) {
356
+ const deviceId = r.device_id;
357
+ const { provider, generation } = legacyKey(r);
358
+ if (await this.addMember(deviceId, r.org_id, provider, generation, "legacy-task", r.id))
359
+ added++;
360
+ }
361
+ return added;
362
+ });
356
363
  }
357
364
  /** Revoked managed starts on an incarnation that no longer runs, not members yet. */
365
+ // org-filter: a query fragment, not run here: its callers (the retirement sweep's methods)
366
+ // execute it inside their asPlatform
358
367
  revokedCandidates(deviceId) {
359
368
  let q = this.db
360
369
  .selectFrom("sandbox_operation_intents as o")
@@ -380,78 +389,84 @@ let LegacyRetirementStore = class LegacyRetirementStore {
380
389
  return q;
381
390
  }
382
391
  async scanRevokedStarts(deviceId) {
383
- const rows = await this.revokedCandidates(deviceId).orderBy("o.operation_id").execute();
384
- let added = 0;
385
- for (const r of rows) {
386
- const generation = GENERATION_RE.test(r.instance_generation)
387
- ? r.instance_generation
388
- : "unknown";
389
- if (await this.addMember(r.device_id, r.org_id, r.provider, generation, "revoked-start", r.operation_id))
390
- added++;
391
- }
392
- return added;
392
+ return asPlatform("retirement of legacy launches across every org", async () => {
393
+ const rows = await this.revokedCandidates(deviceId).orderBy("o.operation_id").execute();
394
+ let added = 0;
395
+ for (const r of rows) {
396
+ const generation = GENERATION_RE.test(r.instance_generation)
397
+ ? r.instance_generation
398
+ : "unknown";
399
+ if (await this.addMember(r.device_id, r.org_id, r.provider, generation, "revoked-start", r.operation_id))
400
+ added++;
401
+ }
402
+ return added;
403
+ });
393
404
  }
394
405
  /** The obligation of the incarnation (created when missing), with the member added. */
395
406
  async addMember(deviceId, orgId, provider, generation, kind, refId) {
396
- await this.db
397
- .insertInto("device_retirement_obligations")
398
- .values({
399
- device_id: deviceId,
400
- org_id: orgId,
401
- provider,
402
- instance_generation: generation,
403
- })
404
- .onConflict((oc) => oc.columns(["device_id", "provider", "instance_generation"]).doNothing())
405
- .execute();
406
- const obligation = await this.db
407
- .selectFrom("device_retirement_obligations")
408
- .select(["id", "state", "resolution"])
409
- .where("device_id", "=", deviceId)
410
- .where("provider", "=", provider)
411
- .where("instance_generation", "=", generation)
412
- .forUpdate()
413
- .executeTakeFirstOrThrow();
414
- const r = await this.db
415
- .insertInto("device_retirement_members")
416
- .values({ obligation_id: obligation.id, kind, ref_id: refId })
417
- .onConflict((oc) => oc.columns(["kind", "ref_id", "obligation_id"]).doNothing())
418
- .returning("ref_id")
419
- .executeTakeFirst();
420
- // an exact cancel covers only the refs it stopped, and the incarnation lives on (B-22): a
421
- // member found later (a row of an old replica) reopens the obligation; so does one found on
422
- // an incarnation an old replica resolved by a restart of its computer
423
- if (r !== undefined &&
424
- obligation.state === "resolved" &&
425
- (obligation.resolution === "host-rebooted" || obligation.resolution === "exact-cancelled")) {
407
+ return asPlatform("retirement of legacy launches across every org", async () => {
426
408
  await this.db
427
- .updateTable("device_retirement_obligations")
428
- .set({ state: "open", resolution: null, resolved_at: null })
429
- .where("id", "=", obligation.id)
409
+ .insertInto("device_retirement_obligations")
410
+ .values({
411
+ device_id: deviceId,
412
+ org_id: orgId,
413
+ provider,
414
+ instance_generation: generation,
415
+ })
416
+ .onConflict((oc) => oc.columns(["device_id", "provider", "instance_generation"]).doNothing())
430
417
  .execute();
431
- }
432
- return r !== undefined;
418
+ const obligation = await this.db
419
+ .selectFrom("device_retirement_obligations")
420
+ .select(["id", "state", "resolution"])
421
+ .where("device_id", "=", deviceId)
422
+ .where("provider", "=", provider)
423
+ .where("instance_generation", "=", generation)
424
+ .forUpdate()
425
+ .executeTakeFirstOrThrow();
426
+ const r = await this.db
427
+ .insertInto("device_retirement_members")
428
+ .values({ obligation_id: obligation.id, kind, ref_id: refId })
429
+ .onConflict((oc) => oc.columns(["kind", "ref_id", "obligation_id"]).doNothing())
430
+ .returning("ref_id")
431
+ .executeTakeFirst();
432
+ // an exact cancel covers only the refs it stopped, and the incarnation lives on (B-22): a
433
+ // member found later (a row of an old replica) reopens the obligation; so does one found on
434
+ // an incarnation an old replica resolved by a restart of its computer
435
+ if (r !== undefined &&
436
+ obligation.state === "resolved" &&
437
+ (obligation.resolution === "host-rebooted" || obligation.resolution === "exact-cancelled")) {
438
+ await this.db
439
+ .updateTable("device_retirement_obligations")
440
+ .set({ state: "open", resolution: null, resolved_at: null })
441
+ .where("id", "=", obligation.id)
442
+ .execute();
443
+ }
444
+ return r !== undefined;
445
+ });
433
446
  }
434
447
  /** The device's unresolved obligations (open and quarantined), oldest first. */
435
448
  async unresolved(deviceId) {
436
- const rows = await this.db
437
- .selectFrom("device_retirement_obligations")
438
- .select([
439
- "id",
440
- "device_id",
441
- "org_id",
442
- "provider",
443
- "instance_generation",
444
- "state",
445
- "reason",
446
- "attempts",
447
- "created_at",
448
- ])
449
- .where("device_id", "=", deviceId)
450
- .where("state", "in", ["open", "quarantined"])
451
- .orderBy("created_at", "asc")
452
- .orderBy("id", "asc")
453
- .execute();
454
- return rows.map(toObligation);
449
+ return asPlatform("retirement of legacy launches across every org", async () => {
450
+ const rows = await this.db
451
+ .selectFrom("device_retirement_obligations")
452
+ .select([
453
+ "id",
454
+ "device_id",
455
+ "org_id",
456
+ "provider",
457
+ "instance_generation",
458
+ "state",
459
+ "reason",
460
+ "attempts",
461
+ "created_at",
462
+ ])
463
+ .where("device_id", "=", deviceId)
464
+ .where("state", "in", ["open", "quarantined"])
465
+ .orderBy("created_at", "asc")
466
+ .orderBy("id", "asc")
467
+ .execute();
468
+ return rows.map(toObligation);
469
+ });
455
470
  }
456
471
  /**
457
472
  * Whether the device has an unresolved obligation, or a candidate not enumerated yet (a legacy
@@ -459,76 +474,84 @@ let LegacyRetirementStore = class LegacyRetirementStore {
459
474
  * the device goes to the gate, which enumerates it under the exclusive lease (C1).
460
475
  */
461
476
  async hasUnresolved(deviceId) {
462
- const row = await this.db
463
- .selectFrom("device_retirement_obligations")
464
- .select("id")
465
- .where("device_id", "=", deviceId)
466
- .where("state", "in", ["open", "quarantined"])
467
- .limit(1)
468
- .executeTakeFirst();
469
- if (row !== undefined)
470
- return true;
471
- if ((await this.revokedCandidates(deviceId).limit(1).executeTakeFirst()) !== undefined)
472
- return true;
473
- // an exact-cancelled obligation a member was added to after the cancel (a rolling upgrade)
474
- const late = await this.db
475
- .selectFrom("device_retirement_obligations as o")
476
- .select("o.id")
477
- .where("o.device_id", "=", deviceId)
478
- .where("o.state", "=", "resolved")
479
- .where("o.resolution", "=", "exact-cancelled")
480
- .where(({ exists }) => exists(this.lateMember()))
481
- .limit(1)
482
- .executeTakeFirst();
483
- if (late !== undefined)
484
- return true;
485
- return ((await this.frozen()) &&
486
- (await this.legacyCandidates(deviceId).limit(1).executeTakeFirst()) !== undefined);
477
+ return asPlatform("retirement of legacy launches across every org", async () => {
478
+ const row = await this.db
479
+ .selectFrom("device_retirement_obligations")
480
+ .select("id")
481
+ .where("device_id", "=", deviceId)
482
+ .where("state", "in", ["open", "quarantined"])
483
+ .limit(1)
484
+ .executeTakeFirst();
485
+ if (row !== undefined)
486
+ return true;
487
+ if ((await this.revokedCandidates(deviceId).limit(1).executeTakeFirst()) !== undefined)
488
+ return true;
489
+ // an exact-cancelled obligation a member was added to after the cancel (a rolling upgrade)
490
+ const late = await this.db
491
+ .selectFrom("device_retirement_obligations as o")
492
+ .select("o.id")
493
+ .where("o.device_id", "=", deviceId)
494
+ .where("o.state", "=", "resolved")
495
+ .where("o.resolution", "=", "exact-cancelled")
496
+ .where(({ exists }) => exists(this.lateMember()))
497
+ .limit(1)
498
+ .executeTakeFirst();
499
+ if (late !== undefined)
500
+ return true;
501
+ return ((await this.frozen()) &&
502
+ (await this.legacyCandidates(deviceId).limit(1).executeTakeFirst()) !== undefined);
503
+ });
487
504
  }
488
505
  /**
489
506
  * No trusted way to establish termination: the obligation is quarantined (the device stays
490
507
  * unavailable). A resolved obligation is left as it is.
491
508
  */
492
509
  async quarantine(id, reason) {
493
- await this.db
494
- .updateTable("device_retirement_obligations")
495
- .set((eb) => ({
496
- state: "quarantined",
497
- reason: reason.slice(0, 1000),
498
- attempts: eb("attempts", "+", 1),
499
- last_attempt_at: sql `now()`,
500
- }))
501
- .where("id", "=", id)
502
- .where("state", "in", ["open", "quarantined"])
503
- .execute();
510
+ return asPlatform("retirement of legacy launches across every org", async () => {
511
+ await this.db
512
+ .updateTable("device_retirement_obligations")
513
+ .set((eb) => ({
514
+ state: "quarantined",
515
+ reason: reason.slice(0, 1000),
516
+ attempts: eb("attempts", "+", 1),
517
+ last_attempt_at: sql `now()`,
518
+ }))
519
+ .where("id", "=", id)
520
+ .where("state", "in", ["open", "quarantined"])
521
+ .execute();
522
+ });
504
523
  }
505
524
  /** A failed destroy or verification: the obligation stays as it is, the attempt is recorded. */
506
525
  async noteFailure(id, error) {
507
- const text = error instanceof Error ? error.message : String(error);
508
- await this.db
509
- .updateTable("device_retirement_obligations")
510
- .set((eb) => ({
511
- attempts: eb("attempts", "+", 1),
512
- last_attempt_at: sql `now()`,
513
- last_error: text.slice(0, 1000),
514
- }))
515
- .where("id", "=", id)
516
- .where("state", "in", ["open", "quarantined"])
517
- .execute();
526
+ return asPlatform("retirement of legacy launches across every org", async () => {
527
+ const text = error instanceof Error ? error.message : String(error);
528
+ await this.db
529
+ .updateTable("device_retirement_obligations")
530
+ .set((eb) => ({
531
+ attempts: eb("attempts", "+", 1),
532
+ last_attempt_at: sql `now()`,
533
+ last_error: text.slice(0, 1000),
534
+ }))
535
+ .where("id", "=", id)
536
+ .where("state", "in", ["open", "quarantined"])
537
+ .execute();
538
+ });
518
539
  }
519
540
  /** The provider confirmed the incarnation destroyed: the obligation resolves. */
520
541
  async resolveDestroyed(id) {
521
- await this.db
522
- .updateTable("device_retirement_obligations")
523
- .set({
524
- state: "resolved",
525
- resolution: "provider-destroyed",
526
- resolved_at: sql `now()`,
527
- last_error: null,
528
- })
529
- .where("id", "=", id)
530
- .where("state", "in", ["open", "quarantined"])
531
- .execute();
542
+ return asPlatform("retirement of legacy launches across every org", async () => {
543
+ await this.db
544
+ .updateTable("device_retirement_obligations")
545
+ .set({
546
+ state: "resolved",
547
+ resolution: "provider-destroyed",
548
+ resolved_at: sql `now()`,
549
+ last_error: null,
550
+ })
551
+ .where("id", "=", id)
552
+ .where("state", "in", ["open", "quarantined"])
553
+ .execute();
554
+ });
532
555
  }
533
556
  /**
534
557
  * The provider confirmed the exact cancellation of the revoked managed starts `covered` on the
@@ -539,40 +562,42 @@ let LegacyRetirementStore = class LegacyRetirementStore {
539
562
  * instead. Acknowledging here is what tells a member added later apart ({@link scan}).
540
563
  */
541
564
  async resolveCancelled(id, covered) {
542
- const o = await this.db
543
- .selectFrom("device_retirement_obligations")
544
- .select(["state"])
545
- .where("id", "=", id)
546
- .forUpdate()
547
- .executeTakeFirst();
548
- if (o === undefined || (o.state !== "open" && o.state !== "quarantined"))
549
- return false;
550
- const members = await this.db
551
- .selectFrom("device_retirement_members")
552
- .select(["kind", "ref_id"])
553
- .where("obligation_id", "=", id)
554
- .execute();
555
- const set = new Set(covered);
556
- if (members.length === 0 ||
557
- members.some((m) => m.kind !== "revoked-start" || !set.has(m.ref_id)))
558
- return false;
559
- await this.db
560
- .updateTable("sandbox_operation_intents")
561
- .set({ revoke_acknowledged: true, updated_at: new Date() })
562
- .where("operation_id", "in", [...set])
563
- .where("state", "=", "revoked")
564
- .execute();
565
- await this.db
566
- .updateTable("device_retirement_obligations")
567
- .set({
568
- state: "resolved",
569
- resolution: "exact-cancelled",
570
- resolved_at: sql `now()`,
571
- last_error: null,
572
- })
573
- .where("id", "=", id)
574
- .execute();
575
- return true;
565
+ return asPlatform("retirement of legacy launches across every org", async () => {
566
+ const o = await this.db
567
+ .selectFrom("device_retirement_obligations")
568
+ .select(["state"])
569
+ .where("id", "=", id)
570
+ .forUpdate()
571
+ .executeTakeFirst();
572
+ if (o === undefined || (o.state !== "open" && o.state !== "quarantined"))
573
+ return false;
574
+ const members = await this.db
575
+ .selectFrom("device_retirement_members")
576
+ .select(["kind", "ref_id"])
577
+ .where("obligation_id", "=", id)
578
+ .execute();
579
+ const set = new Set(covered);
580
+ if (members.length === 0 ||
581
+ members.some((m) => m.kind !== "revoked-start" || !set.has(m.ref_id)))
582
+ return false;
583
+ await this.db
584
+ .updateTable("sandbox_operation_intents")
585
+ .set({ revoke_acknowledged: true, updated_at: new Date() })
586
+ .where("operation_id", "in", [...set])
587
+ .where("state", "=", "revoked")
588
+ .execute();
589
+ await this.db
590
+ .updateTable("device_retirement_obligations")
591
+ .set({
592
+ state: "resolved",
593
+ resolution: "exact-cancelled",
594
+ resolved_at: sql `now()`,
595
+ last_error: null,
596
+ })
597
+ .where("id", "=", id)
598
+ .execute();
599
+ return true;
600
+ });
576
601
  }
577
602
  /**
578
603
  * Reopens `exact-cancelled` obligations holding a member nobody stopped: a legacy row, or a
@@ -582,21 +607,25 @@ let LegacyRetirementStore = class LegacyRetirementStore {
582
607
  * reopens it. Returns how many it reopened.
583
608
  */
584
609
  async reopenLateMembers(deviceId) {
585
- let q = this.db
586
- .updateTable("device_retirement_obligations as o")
587
- .set({ state: "open", resolution: null, resolved_at: null })
588
- .where("o.state", "=", "resolved")
589
- .where("o.resolution", "=", "exact-cancelled")
590
- .where(({ exists }) => exists(this.lateMember()));
591
- if (deviceId !== undefined)
592
- q = q.where("o.device_id", "=", deviceId);
593
- const r = await q.executeTakeFirst();
594
- return Number(r.numUpdatedRows);
610
+ return asPlatform("retirement of legacy launches across every org", async () => {
611
+ let q = this.db
612
+ .updateTable("device_retirement_obligations as o")
613
+ .set({ state: "open", resolution: null, resolved_at: null })
614
+ .where("o.state", "=", "resolved")
615
+ .where("o.resolution", "=", "exact-cancelled")
616
+ .where(({ exists }) => exists(this.lateMember()));
617
+ if (deviceId !== undefined)
618
+ q = q.where("o.device_id", "=", deviceId);
619
+ const r = await q.executeTakeFirst();
620
+ return Number(r.numUpdatedRows);
621
+ });
595
622
  }
596
623
  /**
597
624
  * A member of obligation `o` an exact cancel never covered (see {@link reopenLateMembers}),
598
625
  * correlated on `o.id`.
599
626
  */
627
+ // org-filter: a correlated subquery fragment on o.id, run only inside the retirement sweep's
628
+ // asPlatform
600
629
  lateMember() {
601
630
  // fail closed: a revoked start is covered only when its intent exists acknowledged (a missing
602
631
  // intent row proves nothing was stopped)
@@ -657,18 +686,20 @@ let LegacyRetirementStore = class LegacyRetirementStore {
657
686
  * attempted longer ago than the backoff (30 s doubling per attempt, at most an hour).
658
687
  */
659
688
  async due(limit) {
660
- const rows = await this.db
661
- .selectFrom("device_retirement_obligations")
662
- .select("device_id")
663
- .where("state", "in", ["open", "quarantined"])
664
- .where(sql `(last_attempt_at IS NULL OR last_attempt_at <
689
+ return asPlatform("retirement of legacy launches across every org", async () => {
690
+ const rows = await this.db
691
+ .selectFrom("device_retirement_obligations")
692
+ .select("device_id")
693
+ .where("state", "in", ["open", "quarantined"])
694
+ .where(sql `(last_attempt_at IS NULL OR last_attempt_at <
665
695
  now() - LEAST(3600, 30 * power(2, LEAST(attempts, 7))) * interval '1 second')`)
666
- .groupBy("device_id")
667
- .orderBy(sql `min(last_attempt_at) ASC NULLS FIRST`)
668
- .orderBy("device_id")
669
- .limit(limit)
670
- .execute();
671
- return rows.map((r) => r.device_id);
696
+ .groupBy("device_id")
697
+ .orderBy(sql `min(last_attempt_at) ASC NULLS FIRST`)
698
+ .orderBy("device_id")
699
+ .limit(limit)
700
+ .execute();
701
+ return rows.map((r) => r.device_id);
702
+ });
672
703
  }
673
704
  /** Members of resolved obligations whose own records are not settled yet. */
674
705
  async unsettledMembers(limit) {
@@ -708,158 +739,168 @@ let LegacyRetirementStore = class LegacyRetirementStore {
708
739
  * only a replica without the 8.5 code writes them (see {@link LegacyRetirementReport}).
709
740
  */
710
741
  async unfencedWriters(state) {
711
- // the migrator's own bookkeeping (schema `capybara`, `migrate()`): when 0157 was applied
712
- const applied = await sql `SELECT applied_at FROM capybara._migrations
742
+ return asPlatform("retirement of legacy launches across every org", async () => {
743
+ // the migrator's own bookkeeping (schema `capybara`, `migrate()`): when 0157 was applied
744
+ const applied = await sql `SELECT applied_at FROM capybara._migrations
713
745
  WHERE name = ${MARKER_MIGRATION}`.execute(this.db.db);
714
- const since = applied.rows[0]?.applied_at;
715
- if (since === undefined)
716
- return { sinceMigration: 0, afterFreeze: 0, afterEnumeration: 0, recent: 0, latestAt: null };
717
- const after = (at) => sql `CASE WHEN started_at > ${at}::timestamptz THEN 1 END`;
718
- const row = await this.db
719
- .selectFrom("background_tasks")
720
- .select((eb) => [
721
- eb.fn.countAll().as("n"),
722
- eb.fn.count(after(state.frozenAt)).as("after"),
723
- eb.fn.count(after(state.enumeratedAt)).as("afterEnumeration"),
724
- // by the database clock, the one that stamped started_at
725
- eb.fn
726
- .count(sql `CASE WHEN started_at > now() - ${RECENT}::interval THEN 1 END`)
727
- .as("recent"),
728
- eb.fn.max("started_at").as("latest"),
729
- ])
730
- .where("launch_state", "=", "legacy")
731
- .where("legacy_dispatch", "=", "unknown")
732
- .where("started_at", ">", since)
733
- .executeTakeFirstOrThrow();
734
- return {
735
- sinceMigration: Number(row.n),
736
- afterFreeze: Number(row.after),
737
- afterEnumeration: Number(row.afterEnumeration),
738
- recent: Number(row.recent),
739
- latestAt: row.latest ?? null,
740
- };
746
+ const since = applied.rows[0]?.applied_at;
747
+ if (since === undefined)
748
+ return {
749
+ sinceMigration: 0,
750
+ afterFreeze: 0,
751
+ afterEnumeration: 0,
752
+ recent: 0,
753
+ latestAt: null,
754
+ };
755
+ const after = (at) => sql `CASE WHEN started_at > ${at}::timestamptz THEN 1 END`;
756
+ const row = await this.db
757
+ .selectFrom("background_tasks")
758
+ .select((eb) => [
759
+ eb.fn.countAll().as("n"),
760
+ eb.fn.count(after(state.frozenAt)).as("after"),
761
+ eb.fn.count(after(state.enumeratedAt)).as("afterEnumeration"),
762
+ // by the database clock, the one that stamped started_at
763
+ eb.fn
764
+ .count(sql `CASE WHEN started_at > now() - ${RECENT}::interval THEN 1 END`)
765
+ .as("recent"),
766
+ eb.fn.max("started_at").as("latest"),
767
+ ])
768
+ .where("launch_state", "=", "legacy")
769
+ .where("legacy_dispatch", "=", "unknown")
770
+ .where("started_at", ">", since)
771
+ .executeTakeFirstOrThrow();
772
+ return {
773
+ sinceMigration: Number(row.n),
774
+ afterFreeze: Number(row.after),
775
+ afterEnumeration: Number(row.afterEnumeration),
776
+ recent: Number(row.recent),
777
+ latestAt: row.latest ?? null,
778
+ };
779
+ });
741
780
  }
742
781
  /** The release gate's honest view (a quarantined device is unavailable, not retired). */
743
782
  async report() {
744
- const freeze = await this.freezeState();
745
- const frozen = freeze.frozenAt !== null;
746
- const fenced = await this.db
747
- .selectFrom("background_tasks")
748
- .select((eb) => eb.fn.countAll().as("n"))
749
- .where("launch_state", "=", "legacy")
750
- .where("status", "=", "running")
751
- .where("sid", "is", null)
752
- .where("legacy_dispatch", "=", "reserved")
753
- .executeTakeFirstOrThrow();
754
- const unfenced = await this.unfencedWriters(freeze);
755
- const counts = await this.db
756
- .selectFrom("device_retirement_obligations")
757
- .select(["state", (eb) => eb.fn.countAll().as("n")])
758
- .groupBy("state")
759
- .execute();
760
- const n = (s) => Number(counts.find((c) => c.state === s)?.n ?? 0);
761
- const unsettled = await this.db
762
- .selectFrom("device_retirement_members as m")
763
- .innerJoin("device_retirement_obligations as o", "o.id", "m.obligation_id")
764
- .select((eb) => eb.fn.countAll().as("n"))
765
- .where("o.state", "=", "resolved")
766
- .where("m.settled", "=", false)
767
- .executeTakeFirstOrThrow();
768
- const unresolved = await this.db
769
- .selectFrom("device_retirement_obligations")
770
- .select(["device_id", "provider", "instance_generation", "state", "reason"])
771
- .where("state", "in", ["open", "quarantined"])
772
- .orderBy("created_at", "asc")
773
- .execute();
774
- const abandonedRows = await this.db
775
- .selectFrom("device_retirement_obligations")
776
- .select(["device_id", "provider", "instance_generation", "abandoned_at"])
777
- .where("state", "=", "abandoned")
778
- .orderBy("abandoned_at", "asc")
779
- .execute();
780
- const abandonedMembers = await this.db
781
- .selectFrom("device_retirement_members as m")
782
- .innerJoin("device_retirement_obligations as o", "o.id", "m.obligation_id")
783
- .select((eb) => eb.fn.countAll().as("n"))
784
- .where("o.state", "=", "abandoned")
785
- .executeTakeFirstOrThrow();
786
- const cloudCandidates = await this.db
787
- .selectFrom("background_tasks as t")
788
- .innerJoin("devices as d", "d.id", "t.device_id")
789
- .leftJoin("device_instances as i", "i.device_id", "t.device_id")
790
- .select([
791
- "t.device_id",
792
- "t.sandbox_created_at",
793
- "t.legacy_dispatch_generation",
794
- "t.legacy_dispatch_provider",
795
- "i.provider as instance_provider",
796
- "i.created_at as instance_created_at",
797
- "i.prev_handle",
798
- "i.status as instance_status",
799
- "i.handle as instance_handle",
800
- "i.had_instance",
801
- ])
802
- .where("d.deleted_at", "is", null)
803
- .where("t.launch_state", "=", "legacy")
804
- .where(MAY_STILL_RUN)
805
- .where(MAY_HAVE_DISPATCHED)
806
- .orderBy("t.device_id")
807
- .execute();
808
- const cloudUnknown = new Map();
809
- for (const r of cloudCandidates) {
810
- const key = legacyKey(r);
811
- if (key.generation !== "unknown" && key.provider !== "unknown")
812
- continue;
813
- if (cloudUnknown.has(r.device_id))
814
- continue;
815
- const live = r.instance_handle !== null &&
816
- (r.instance_status === "running" ||
817
- r.instance_status === "suspended" ||
818
- r.instance_status === "creating");
819
- const createdAt = r.instance_created_at;
820
- const noInstance = createdAt === null || r.had_instance !== true;
821
- const currentUnconfirmed = createdAt !== null &&
822
- !noInstance &&
823
- !live &&
824
- !(r.instance_provider !== null &&
825
- (await this.destructionRecorded(r.device_id, r.instance_provider, generationOf(createdAt))));
826
- cloudUnknown.set(r.device_id, {
827
- prevHandle: r.prev_handle !== null,
828
- noInstance,
829
- currentUnconfirmed,
830
- });
831
- }
832
- const open = n("open"), quarantined = n("quarantined"), abandoned = n("abandoned"), unsettledMembers = Number(unsettled.n);
833
- const retired = frozen && open === 0 && quarantined === 0 && unsettledMembers === 0;
834
- return {
835
- frozen,
836
- frozenAt: freeze.frozenAt,
837
- freezeEnumeratedAt: freeze.enumeratedAt,
838
- fencedReservations: Number(fenced.n),
839
- unfencedWriters: unfenced,
840
- open,
841
- quarantined,
842
- resolved: n("resolved"),
843
- unsettledMembers,
844
- retired,
845
- cleanRetirement: retired && abandoned === 0,
846
- abandoned,
847
- abandonedMembers: Number(abandonedMembers.n),
848
- abandonedList: abandonedRows.map((r) => ({
849
- deviceId: r.device_id,
850
- provider: r.provider,
851
- instanceGeneration: r.instance_generation,
852
- abandonedAt: r.abandoned_at,
853
- })),
854
- cloudUnknown: [...cloudUnknown].map(([deviceId, flags]) => ({ deviceId, ...flags })),
855
- unresolved: unresolved.map((r) => ({
856
- deviceId: r.device_id,
857
- provider: r.provider,
858
- instanceGeneration: r.instance_generation,
859
- state: r.state,
860
- reason: r.reason,
861
- })),
862
- };
783
+ return asPlatform("retirement of legacy launches across every org", async () => {
784
+ const freeze = await this.freezeState();
785
+ const frozen = freeze.frozenAt !== null;
786
+ const fenced = await this.db
787
+ .selectFrom("background_tasks")
788
+ .select((eb) => eb.fn.countAll().as("n"))
789
+ .where("launch_state", "=", "legacy")
790
+ .where("status", "=", "running")
791
+ .where("sid", "is", null)
792
+ .where("legacy_dispatch", "=", "reserved")
793
+ .executeTakeFirstOrThrow();
794
+ const unfenced = await this.unfencedWriters(freeze);
795
+ const counts = await this.db
796
+ .selectFrom("device_retirement_obligations")
797
+ .select(["state", (eb) => eb.fn.countAll().as("n")])
798
+ .groupBy("state")
799
+ .execute();
800
+ const n = (s) => Number(counts.find((c) => c.state === s)?.n ?? 0);
801
+ const unsettled = await this.db
802
+ .selectFrom("device_retirement_members as m")
803
+ .innerJoin("device_retirement_obligations as o", "o.id", "m.obligation_id")
804
+ .select((eb) => eb.fn.countAll().as("n"))
805
+ .where("o.state", "=", "resolved")
806
+ .where("m.settled", "=", false)
807
+ .executeTakeFirstOrThrow();
808
+ const unresolved = await this.db
809
+ .selectFrom("device_retirement_obligations")
810
+ .select(["device_id", "provider", "instance_generation", "state", "reason"])
811
+ .where("state", "in", ["open", "quarantined"])
812
+ .orderBy("created_at", "asc")
813
+ .execute();
814
+ const abandonedRows = await this.db
815
+ .selectFrom("device_retirement_obligations")
816
+ .select(["device_id", "provider", "instance_generation", "abandoned_at"])
817
+ .where("state", "=", "abandoned")
818
+ .orderBy("abandoned_at", "asc")
819
+ .execute();
820
+ const abandonedMembers = await this.db
821
+ .selectFrom("device_retirement_members as m")
822
+ .innerJoin("device_retirement_obligations as o", "o.id", "m.obligation_id")
823
+ .select((eb) => eb.fn.countAll().as("n"))
824
+ .where("o.state", "=", "abandoned")
825
+ .executeTakeFirstOrThrow();
826
+ const cloudCandidates = await this.db
827
+ .selectFrom("background_tasks as t")
828
+ .innerJoin("devices as d", "d.id", "t.device_id")
829
+ .leftJoin("device_instances as i", "i.device_id", "t.device_id")
830
+ .select([
831
+ "t.device_id",
832
+ "t.sandbox_created_at",
833
+ "t.legacy_dispatch_generation",
834
+ "t.legacy_dispatch_provider",
835
+ "i.provider as instance_provider",
836
+ "i.created_at as instance_created_at",
837
+ "i.prev_handle",
838
+ "i.status as instance_status",
839
+ "i.handle as instance_handle",
840
+ "i.had_instance",
841
+ ])
842
+ .where("d.deleted_at", "is", null)
843
+ .where("t.launch_state", "=", "legacy")
844
+ .where(MAY_STILL_RUN)
845
+ .where(MAY_HAVE_DISPATCHED)
846
+ .orderBy("t.device_id")
847
+ .execute();
848
+ const cloudUnknown = new Map();
849
+ for (const r of cloudCandidates) {
850
+ const key = legacyKey(r);
851
+ if (key.generation !== "unknown" && key.provider !== "unknown")
852
+ continue;
853
+ if (cloudUnknown.has(r.device_id))
854
+ continue;
855
+ const live = r.instance_handle !== null &&
856
+ (r.instance_status === "running" ||
857
+ r.instance_status === "suspended" ||
858
+ r.instance_status === "creating");
859
+ const createdAt = r.instance_created_at;
860
+ const noInstance = createdAt === null || r.had_instance !== true;
861
+ const currentUnconfirmed = createdAt !== null &&
862
+ !noInstance &&
863
+ !live &&
864
+ !(r.instance_provider !== null &&
865
+ (await this.destructionRecorded(r.device_id, r.instance_provider, generationOf(createdAt))));
866
+ cloudUnknown.set(r.device_id, {
867
+ prevHandle: r.prev_handle !== null,
868
+ noInstance,
869
+ currentUnconfirmed,
870
+ });
871
+ }
872
+ const open = n("open"), quarantined = n("quarantined"), abandoned = n("abandoned"), unsettledMembers = Number(unsettled.n);
873
+ const retired = frozen && open === 0 && quarantined === 0 && unsettledMembers === 0;
874
+ return {
875
+ frozen,
876
+ frozenAt: freeze.frozenAt,
877
+ freezeEnumeratedAt: freeze.enumeratedAt,
878
+ fencedReservations: Number(fenced.n),
879
+ unfencedWriters: unfenced,
880
+ open,
881
+ quarantined,
882
+ resolved: n("resolved"),
883
+ unsettledMembers,
884
+ retired,
885
+ cleanRetirement: retired && abandoned === 0,
886
+ abandoned,
887
+ abandonedMembers: Number(abandonedMembers.n),
888
+ abandonedList: abandonedRows.map((r) => ({
889
+ deviceId: r.device_id,
890
+ provider: r.provider,
891
+ instanceGeneration: r.instance_generation,
892
+ abandonedAt: r.abandoned_at,
893
+ })),
894
+ cloudUnknown: [...cloudUnknown].map(([deviceId, flags]) => ({ deviceId, ...flags })),
895
+ unresolved: unresolved.map((r) => ({
896
+ deviceId: r.device_id,
897
+ provider: r.provider,
898
+ instanceGeneration: r.instance_generation,
899
+ state: r.state,
900
+ reason: r.reason,
901
+ })),
902
+ };
903
+ });
863
904
  }
864
905
  };
865
906
  __decorate([