@capybara-hq/kernel 0.1.0-rc.137 → 0.1.0-rc.139

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 (101) hide show
  1. package/bootstrap.json +31 -31
  2. package/dist/admin/extensions.controller.d.ts +5 -2
  3. package/dist/admin/extensions.controller.js +10 -1
  4. package/dist/admin/extensions.schemas.d.ts +4 -0
  5. package/dist/admin/extensions.schemas.js +9 -0
  6. package/dist/admin/health.service.d.ts +1 -1
  7. package/dist/admin/health.service.js +3 -3
  8. package/dist/catalog/catalog-content.d.ts +5 -7
  9. package/dist/catalog/catalog-items.js +1 -1
  10. package/dist/catalog/catalog-scope.service.js +5 -5
  11. package/dist/catalog/catalog.module.js +5 -4
  12. package/dist/catalog/catalog.service.d.ts +7 -1
  13. package/dist/catalog/catalog.service.js +19 -2
  14. package/dist/catalog/effect-work.d.ts +27 -0
  15. package/dist/catalog/effect-work.js +151 -0
  16. package/dist/catalog/jobs.d.ts +4 -1
  17. package/dist/catalog/jobs.js +14 -4
  18. package/dist/catalog/org-catalog.service.d.ts +2 -0
  19. package/dist/catalog/org-catalog.service.js +68 -12
  20. package/dist/catalog/org-intent.d.ts +4 -2
  21. package/dist/catalog/org-intent.js +25 -4
  22. package/dist/catalog/owned-items.d.ts +5 -1
  23. package/dist/catalog/owned-items.js +18 -3
  24. package/dist/catalog/plugin-import.d.ts +4 -2
  25. package/dist/catalog/plugin-import.js +10 -5
  26. package/dist/catalog/plugin-install.d.ts +17 -51
  27. package/dist/catalog/plugin-install.js +209 -235
  28. package/dist/catalog/plugin-upgrade.d.ts +8 -3
  29. package/dist/catalog/plugin-upgrade.js +63 -34
  30. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  31. package/dist/catalog/scope-sync-workers.js +10 -26
  32. package/dist/catalog/scope-sync.d.ts +19 -114
  33. package/dist/catalog/scope-sync.js +220 -239
  34. package/dist/catalog/scope-writer.d.ts +10 -1
  35. package/dist/catalog/scope-writer.js +62 -4
  36. package/dist/catalog/template-connector-ensure.js +1 -1
  37. package/dist/catalog/unshare.js +1 -2
  38. package/dist/config/schema.d.ts +1 -1
  39. package/dist/config/schema.js +7 -4
  40. package/dist/db/kernel-schema.d.ts +18 -17
  41. package/dist/erasure/org-catalog.js +2 -2
  42. package/dist/erasure/org-rules.js +2 -2
  43. package/dist/extensions/admin-ops.d.ts +1 -1
  44. package/dist/extensions/admin-ops.js +1 -1
  45. package/dist/extensions/admin-view.d.ts +4 -1
  46. package/dist/extensions/admin-view.js +27 -11
  47. package/dist/extensions/bootstrap.d.ts +1 -1
  48. package/dist/extensions/bootstrap.js +2 -3
  49. package/dist/extensions/enabled.d.ts +159 -0
  50. package/dist/extensions/enabled.js +7 -0
  51. package/dist/extensions/host.d.ts +1 -0
  52. package/dist/extensions/host.js +5 -2
  53. package/dist/extensions/isolated/authorization.d.ts +8 -0
  54. package/dist/extensions/isolated/authorization.js +56 -11
  55. package/dist/extensions/isolated/broker.js +30 -11
  56. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  57. package/dist/extensions/isolated/engine-binds.js +82 -0
  58. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  59. package/dist/extensions/isolated/engine-policy.js +75 -0
  60. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  61. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  62. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  63. package/dist/extensions/isolated/engine-proxy.js +408 -0
  64. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  65. package/dist/extensions/isolated/engine-vaults.js +93 -0
  66. package/dist/extensions/isolated/lanes.d.ts +11 -3
  67. package/dist/extensions/isolated/lanes.js +43 -16
  68. package/dist/extensions/isolated/postgres-gate.d.ts +1 -0
  69. package/dist/extensions/isolated/postgres-gate.js +6 -6
  70. package/dist/extensions/isolated/revision.d.ts +1 -1
  71. package/dist/extensions/isolated/revision.js +3 -2
  72. package/dist/extensions/isolated/sandbox.d.ts +10 -6
  73. package/dist/extensions/isolated/sandbox.js +101 -117
  74. package/dist/extensions/lifecycle-topics.d.ts +1 -0
  75. package/dist/extensions/lifecycle-topics.js +1 -0
  76. package/dist/extensions/lifecycle.js +23 -2
  77. package/dist/extensions/permission-view.d.ts +6 -1
  78. package/dist/inbox/platform-inbox.service.js +16 -27
  79. package/dist/infra/events/kernel-events.d.ts +4 -0
  80. package/dist/infra/outbox/registry.d.ts +3 -36
  81. package/dist/infra/outbox/registry.js +4 -49
  82. package/dist/infra/queue/queue-names.d.ts +1 -1
  83. package/dist/infra/queue/queue-names.js +1 -1
  84. package/dist/orgs/org-lock.d.ts +3 -1
  85. package/dist/orgs/org-lock.js +3 -1
  86. package/dist/orgs/orgs.service.d.ts +3 -1
  87. package/dist/orgs/orgs.service.js +15 -8
  88. package/dist/overrides.d.ts +0 -3
  89. package/dist/overrides.js +0 -2
  90. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  91. package/dist/platform/ops/org-plugins.ops.js +5 -2
  92. package/dist/platform/ops/plugins.ops.js +11 -10
  93. package/dist/tools/registry.d.ts +1 -1
  94. package/dist/tools/registry.js +6 -2
  95. package/package.json +2 -2
  96. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  97. package/src/migrations/0232_contract_plugin_effect_schema.sql +49 -0
  98. package/dist/catalog/install-status.d.ts +0 -5
  99. package/dist/catalog/install-status.js +0 -5
  100. package/dist/catalog/scope-jobs.d.ts +0 -59
  101. package/dist/catalog/scope-jobs.js +0 -78
@@ -8,6 +8,8 @@ import { SuperAdminLock } from "../identity/super-admin.js";
8
8
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
9
9
  import { KernelDb } from "../infra/database/kernel-db.js";
10
10
  import { TransactionHost } from "../infra/database/transaction-host.js";
11
+ import { XactLock } from "../infra/database/xact-lock.js";
12
+ import { KernelEvents } from "../infra/events/kernel-events.js";
11
13
  import { LockService } from "../infra/lock/lock.service.js";
12
14
  import { OutboxService } from "../infra/outbox/outbox.service.js";
13
15
  import type { KernelLogger } from "../log.js";
@@ -133,7 +135,7 @@ export interface PlatformUpdatePreview {
133
135
  * The orgs where the scope sync owed with the update will install the plugin (plugin pages spec
134
136
  * §5.2.3): its scope wants it on there and the org has no live install (one that waited for
135
137
  * connector input before installs took none). `failing`: the scope sync's last attempt there
136
- * failed (an open `plugin_scope_sync_failures` row), `lastFailure` its message. Sorted by org
138
+ * failed (an `install_failed` effects row), `lastFailure` its message. Sorted by org
137
139
  * id. Hashed by org id and `failing` only. An owner's preview ({@link
138
140
  * PlatformPluginUpdater.previewForOwner}) drops both for orgs other than the owner.
139
141
  */
@@ -247,6 +249,8 @@ export type UpdateTarget = VersionRow;
247
249
  export declare class PlatformPluginUpdater {
248
250
  private readonly kdb;
249
251
  readonly txHost: TransactionHost;
252
+ private readonly xactLock;
253
+ private readonly events;
250
254
  private readonly adminLock;
251
255
  private readonly itemLock;
252
256
  private readonly orgLock;
@@ -267,7 +271,7 @@ export declare class PlatformPluginUpdater {
267
271
  private readonly guides;
268
272
  /** Owes the template connector ensure of the orgs with a deferred connector (ruling R27). */
269
273
  private readonly outbox;
270
- constructor(kdb: KernelDb, txHost: TransactionHost, adminLock: SuperAdminLock, itemLock: CatalogItemLock, orgLock: OrgLock, locks: LockService, storage: StorageService, registry: ExtensionRegistry, ops: ExtensionAdminOps,
274
+ constructor(kdb: KernelDb, txHost: TransactionHost, xactLock: XactLock, events: KernelEvents, adminLock: SuperAdminLock, itemLock: CatalogItemLock, orgLock: OrgLock, locks: LockService, storage: StorageService, registry: ExtensionRegistry, ops: ExtensionAdminOps,
271
275
  /** Reads the target's extension package (its permissions, for `needsApproval`). */
272
276
  blobs: ExtensionBlobs, config: KernelConfigService, platform: PlatformComponents,
273
277
  /** Template dependencies (the deployed connector kinds). */
@@ -417,8 +421,9 @@ export declare class PlatformPluginUpdater {
417
421
  * Builtin or unavailable plugins have no org setup plan.
418
422
  */
419
423
  private scopeInstallsOf;
420
- /** The orgs where the plugin is on: a live install (builtin: every live org). */
421
424
  private pluginOrgs;
425
+ /** Applied org resources that the platform update must move with the catalog version. */
426
+ private appliedPluginOrgs;
422
427
  private liveOrgs;
423
428
  }
424
429
  export {};
@@ -26,10 +26,13 @@ import { audit } from "../identity/audit.js";
26
26
  import { SuperAdminLock } from "../identity/super-admin.js";
27
27
  import { notifySharedUpdate } from "../inbox/org-notices.js";
28
28
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
29
+ import { afterCommit } from "../infra/database/after-commit.js";
29
30
  import { KernelDb } from "../infra/database/kernel-db.js";
30
31
  import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
31
32
  import { TransactionHost } from "../infra/database/transaction-host.js";
32
33
  import { Transactional } from "../infra/database/transactional.decorator.js";
34
+ import { XactLock } from "../infra/database/xact-lock.js";
35
+ import { KernelEvents } from "../infra/events/kernel-events.js";
33
36
  import { LockService } from "../infra/lock/lock.service.js";
34
37
  import { OutboxService } from "../infra/outbox/outbox.service.js";
35
38
  import { KERNEL_LOGGER } from "../infra/tokens.js";
@@ -46,10 +49,10 @@ import { markVersionApplied, versionUsable } from "./catalog-items.js";
46
49
  import { agentsUsing, clashingOrgSkills, clashingPlatformSkills, componentOn, connectorsMadeFrom, connectorTemplatesOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, switchOf, themeIdClashes, } from "./component-state.js";
47
50
  import { credentialKey } from "./credential-key.js";
48
51
  import { refreshCatalogDependencyEdges } from "./dependency-edges.js";
49
- import { LIVE_INSTALL_STATUSES } from "./install-status.js";
52
+ import { EFFECT_CANDIDATES_LOCK } from "./effect-work.js";
50
53
  import { CatalogItemLock } from "./locks.js";
51
54
  import { requireMarketplacePublisher } from "./marketplace-fetch.js";
52
- import { orgPluginEffectIntent } from "./org-intent.js";
55
+ import { orgPluginEffectIntent, orgUsable } from "./org-intent.js";
53
56
  import { isUsable } from "./ownership.js";
54
57
  import { PlanStale, PlatformComponents } from "./platform-components.js";
55
58
  import { catalogSkillNames, PluginInstaller } from "./plugin-install.js";
@@ -128,6 +131,8 @@ const filesDigest = (row) => skillFilesDigest(row.files.map((f) => ({ path: f.pa
128
131
  let PlatformPluginUpdater = class PlatformPluginUpdater {
129
132
  kdb;
130
133
  txHost;
134
+ xactLock;
135
+ events;
131
136
  adminLock;
132
137
  itemLock;
133
138
  orgLock;
@@ -144,7 +149,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
144
149
  log;
145
150
  guides;
146
151
  outbox;
147
- constructor(kdb, txHost, adminLock, itemLock, orgLock, locks, storage, registry, ops,
152
+ constructor(kdb, txHost, xactLock, events, adminLock, itemLock, orgLock, locks, storage, registry, ops,
148
153
  /** Reads the target's extension package (its permissions, for `needsApproval`). */
149
154
  blobs, config, platform,
150
155
  /** Template dependencies (the deployed connector kinds). */
@@ -155,6 +160,8 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
155
160
  outbox) {
156
161
  this.kdb = kdb;
157
162
  this.txHost = txHost;
163
+ this.xactLock = xactLock;
164
+ this.events = events;
158
165
  this.adminLock = adminLock;
159
166
  this.itemLock = itemLock;
160
167
  this.orgLock = orgLock;
@@ -533,6 +540,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
533
540
  if (owner !== undefined && actor === null) {
534
541
  throw new Error("an owner update needs the acting account");
535
542
  }
543
+ await this.xactLock.lock(EFFECT_CANDIDATES_LOCK);
536
544
  // null: the kernel itself (the bootstrap step), no super admin to re-check
537
545
  if (owner === undefined && actor !== null)
538
546
  await this.adminLock.lockAndAuthorize(actor);
@@ -584,9 +592,12 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
584
592
  }
585
593
  // Removals (spec §7.3): kept while agents use it; otherwise soft-deleted
586
594
  const now = sql `now()`;
595
+ let removedConnectorTemplate = false;
587
596
  for (const c of diff.components) {
588
597
  if (c.change !== "removed" || c.id === null || c.kept !== undefined)
589
598
  continue;
599
+ if (c.kind === "connector_template")
600
+ removedConnectorTemplate = true;
590
601
  const table = c.kind === "skill"
591
602
  ? "platform_skills"
592
603
  : c.kind === "agent_template"
@@ -664,9 +675,9 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
664
675
  // current at its commit, PluginInstaller.markInstalled)
665
676
  await t
666
677
  .updateTable("plugin_installs")
667
- .set({ version: diff.to.version, error: null })
678
+ .set({ version: diff.to.version })
668
679
  .where("item_id", "=", itemId)
669
- .where("status", "in", [...LIVE_INSTALL_STATUSES])
680
+ .where("version", "is not", null)
670
681
  .execute();
671
682
  if (owner !== undefined) {
672
683
  // An org's version becomes its latest once applied
@@ -678,6 +689,9 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
678
689
  await markVersionApplied(t, itemId, diff.to.version);
679
690
  }
680
691
  await refreshCatalogDependencyEdges(t);
692
+ if (removedConnectorTemplate) {
693
+ afterCommit(() => this.events.emit("catalog.org-intent-changed", {}));
694
+ }
681
695
  // The orgs using a shared org-owned plugin are told, one notice per plugin (a platform-owned
682
696
  // plugin tells nobody); a plugin never synced before has no version to come from
683
697
  if (diff.from !== null) {
@@ -762,7 +776,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
762
776
  const connectorId = await this.connectors.createDeferredIn(c.orgId, null, ci, {
763
777
  auditDetail: { via: "platform_update" },
764
778
  });
765
- await this.installer.recordTemplateConnectorIn(c.orgId, itemId, connectorId, c.templateId, LIVE_INSTALL_STATUSES);
779
+ await this.installer.recordTemplateConnectorIn(c.orgId, itemId, connectorId, c.templateId);
766
780
  }
767
781
  /**
768
782
  * Computes an update (see the class comment). `target`: the target read from an org's staging
@@ -1089,8 +1103,8 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
1089
1103
  pinnedOrgs: [],
1090
1104
  });
1091
1105
  }
1092
- // The orgs where the plugin is on (a live install; builtin: every org)
1093
- const onOrgs = await this.pluginOrgs(itemId, item.builtin);
1106
+ const onOrgs = await this.pluginOrgs(itemId);
1107
+ const appliedOrgs = item.builtin ? onOrgs : await this.appliedPluginOrgs(itemId);
1094
1108
  if (extension)
1095
1109
  extension = { ...extension, orgs: onOrgs };
1096
1110
  // Rule 10: an added skill must not take a name already used where the plugin is on
@@ -1228,7 +1242,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
1228
1242
  .execute()).map((r) => r.org_id))
1229
1243
  : undefined;
1230
1244
  const ids = [...flipped.keys()].sort();
1231
- for (const orgId of onOrgs) {
1245
+ for (const orgId of appliedOrgs) {
1232
1246
  if (listedOrgs !== undefined && !listedOrgs.has(orgId))
1233
1247
  continue;
1234
1248
  // a template the org already has a live connector from (one a switch-off kept) needs none
@@ -1313,7 +1327,11 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
1313
1327
  }
1314
1328
  }
1315
1329
  }
1316
- const scopeInstalls = await this.scopeInstallsOf(item, onOrgs);
1330
+ const toManifest = to.manifest;
1331
+ const expectsSetup = toManifest.extension !== undefined ||
1332
+ (toManifest.connectorTemplates?.length ?? 0) > 0 ||
1333
+ (toManifest.dependencies?.length ?? 0) > 0;
1334
+ const scopeInstalls = expectsSetup ? await this.scopeInstallsOf(item, appliedOrgs) : [];
1317
1335
  const connectorOrgs = [...byOrg.values()]
1318
1336
  .map((e) => ({
1319
1337
  ...e,
@@ -1589,12 +1607,13 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
1589
1607
  .orderBy("id")
1590
1608
  .execute(),
1591
1609
  this.db
1592
- .selectFrom("plugin_scope_sync_failures")
1593
- .select(["org_id", "message"])
1610
+ .selectFrom("plugin_installs")
1611
+ .select(["org_id", "error"])
1612
+ .where("status", "=", "install_failed")
1594
1613
  .where("item_id", "=", item.id)
1595
1614
  .execute(),
1596
1615
  ]);
1597
- const failed = new Map(failures.map((r) => [r.org_id, r.message]));
1616
+ const failed = new Map(failures.map((r) => [r.org_id, r.error?.message]));
1598
1617
  const on = new Set(onOrgs);
1599
1618
  return orgs
1600
1619
  .filter((o) => !on.has(o.id))
@@ -1607,17 +1626,25 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
1607
1626
  };
1608
1627
  });
1609
1628
  }
1610
- /** The orgs where the plugin is on: a live install (builtin: every live org). */
1611
- async pluginOrgs(itemId, builtin) {
1612
- if (builtin)
1613
- return this.liveOrgs();
1629
+ async pluginOrgs(itemId) {
1630
+ const rows = await this.db
1631
+ .selectFrom("orgs")
1632
+ .select("id")
1633
+ .where("deleted_at", "is", null)
1634
+ .where(({ ref }) => orgUsable(this.db, ref("orgs.id"), itemId))
1635
+ .orderBy("id")
1636
+ .execute();
1637
+ return rows.map((row) => row.id);
1638
+ }
1639
+ /** Applied org resources that the platform update must move with the catalog version. */
1640
+ async appliedPluginOrgs(itemId) {
1614
1641
  const rows = await this.db
1615
1642
  .selectFrom("plugin_installs as a")
1616
1643
  .innerJoin("orgs as o", "o.id", "a.org_id")
1617
1644
  .select("a.org_id")
1618
1645
  .distinct()
1619
1646
  .where("a.item_id", "=", itemId)
1620
- .where("a.status", "in", [...LIVE_INSTALL_STATUSES])
1647
+ .where("a.version", "is not", null)
1621
1648
  .where("o.deleted_at", "is", null)
1622
1649
  .orderBy("a.org_id")
1623
1650
  .execute();
@@ -1649,22 +1676,24 @@ PlatformPluginUpdater = __decorate([
1649
1676
  ,
1650
1677
  __param(0, Inject(KernelDb)),
1651
1678
  __param(1, Inject(TransactionHost)),
1652
- __param(2, Inject(SuperAdminLock)),
1653
- __param(3, Inject(CatalogItemLock)),
1654
- __param(4, Inject(OrgLock)),
1655
- __param(5, Inject(LockService)),
1656
- __param(6, Inject(StorageService)),
1657
- __param(7, Inject(ExtensionRegistry)),
1658
- __param(8, Inject(ExtensionAdminOps)),
1659
- __param(9, Inject(ExtensionBlobs)),
1660
- __param(10, Inject(KernelConfigService)),
1661
- __param(11, Inject(PlatformComponents)),
1662
- __param(12, Inject(PluginInstaller)),
1663
- __param(13, Inject(ConnectorsService)),
1664
- __param(14, Inject(PluginScopeSync)),
1665
- __param(15, Inject(KERNEL_LOGGER)),
1666
- __param(16, Inject(PluginGuides)),
1667
- __param(17, Inject(OutboxService))
1679
+ __param(2, Inject(XactLock)),
1680
+ __param(3, Inject(KernelEvents)),
1681
+ __param(4, Inject(SuperAdminLock)),
1682
+ __param(5, Inject(CatalogItemLock)),
1683
+ __param(6, Inject(OrgLock)),
1684
+ __param(7, Inject(LockService)),
1685
+ __param(8, Inject(StorageService)),
1686
+ __param(9, Inject(ExtensionRegistry)),
1687
+ __param(10, Inject(ExtensionAdminOps)),
1688
+ __param(11, Inject(ExtensionBlobs)),
1689
+ __param(12, Inject(KernelConfigService)),
1690
+ __param(13, Inject(PlatformComponents)),
1691
+ __param(14, Inject(PluginInstaller)),
1692
+ __param(15, Inject(ConnectorsService)),
1693
+ __param(16, Inject(PluginScopeSync)),
1694
+ __param(17, Inject(KERNEL_LOGGER)),
1695
+ __param(18, Inject(PluginGuides)),
1696
+ __param(19, Inject(OutboxService))
1668
1697
  ], PlatformPluginUpdater);
1669
1698
  export { PlatformPluginUpdater };
1670
1699
  /** The preview of a diff (without `guideChanges`, which reads PG). */
@@ -1,24 +1,20 @@
1
1
  import { WorkerHost } from "@nestjs/bullmq";
2
2
  import type { Job, Worker } from "bullmq";
3
3
  import type { KernelLogger } from "../log.js";
4
- import { PluginScopeSync, type ScopeJob } from "./scope-sync.js";
5
- /**
6
- * The consumer of {@link PLUGIN_SCOPE_QUEUE}: {@link PluginScopeSync} runs the `scope-item`,
7
- * `scope-item-chunk` and `scope-org` jobs the outbox delivers (any other name fails the job). A
8
- * chunk or org job with a pair whose extension this replica has not loaded yet throws, so BullMQ
9
- * retries it with the registry's backoff; its last attempt installs anyway.
10
- */
11
- export declare class PluginScopeSyncProcessor extends WorkerHost<Worker<ScopeJob>> {
4
+ import { type EffectJob } from "./effect-work.js";
5
+ import { PluginScopeSync } from "./scope-sync.js";
6
+ /** Runs one generation of effects for one org and item. */
7
+ export declare class PluginScopeSyncProcessor extends WorkerHost<Worker<EffectJob>> {
12
8
  private readonly sync;
13
9
  private readonly log;
14
10
  private readonly stopping;
15
- constructor(sync: PluginScopeSync, log: Pick<KernelLogger, "error" | "warn">);
16
- process(job: Job<ScopeJob>): Promise<void>;
11
+ constructor(sync: PluginScopeSync, log: Pick<KernelLogger, "error">);
12
+ process(job: Job<EffectJob>): Promise<void>;
17
13
  /** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
18
14
  start(): void;
19
15
  /** Stops between pairs and closes the worker. */
20
16
  close(): Promise<void>;
21
- failed(job: Job<ScopeJob> | undefined, err: Error): void;
17
+ failed(job: Job<EffectJob> | undefined, err: Error): void;
22
18
  error(err: Error): void;
23
19
  }
24
20
  /**
@@ -13,13 +13,9 @@ import { configuredProcessor } from "../infra/queue/configured-processor.js";
13
13
  import { runJob } from "../infra/queue/run-job.js";
14
14
  import { KERNEL_LOGGER } from "../infra/tokens.js";
15
15
  import { CatalogModule } from "./catalog.module.js";
16
- import { PLUGIN_SCOPE_CONCURRENCY, PLUGIN_SCOPE_QUEUE, PluginScopeSync, SCOPE_CHUNK_JOB, SCOPE_ITEM_JOB, SCOPE_ORG_JOB, ScopeSyncDeferred, } from "./scope-sync.js";
17
- /**
18
- * The consumer of {@link PLUGIN_SCOPE_QUEUE}: {@link PluginScopeSync} runs the `scope-item`,
19
- * `scope-item-chunk` and `scope-org` jobs the outbox delivers (any other name fails the job). A
20
- * chunk or org job with a pair whose extension this replica has not loaded yet throws, so BullMQ
21
- * retries it with the registry's backoff; its last attempt installs anyway.
22
- */
16
+ import { PLUGIN_EFFECT_JOB, PLUGIN_EFFECT_QUEUE } from "./effect-work.js";
17
+ import { PLUGIN_SCOPE_CONCURRENCY, PluginScopeSync } from "./scope-sync.js";
18
+ /** Runs one generation of effects for one org and item. */
23
19
  let PluginScopeSyncProcessor = class PluginScopeSyncProcessor extends WorkerHost {
24
20
  sync;
25
21
  log;
@@ -30,20 +26,12 @@ let PluginScopeSyncProcessor = class PluginScopeSyncProcessor extends WorkerHost
30
26
  this.log = log;
31
27
  }
32
28
  process(job) {
33
- return runJob(PLUGIN_SCOPE_QUEUE, job, () => {
34
- if (![SCOPE_ITEM_JOB, SCOPE_CHUNK_JOB, SCOPE_ORG_JOB].includes(job.name)) {
35
- throw new Error(`unknown plugin scope job ${job.name}`);
36
- }
29
+ return runJob(PLUGIN_EFFECT_QUEUE, job, () => {
30
+ if (job.name !== PLUGIN_EFFECT_JOB)
31
+ throw new Error(`unknown plugin effect job ${job.name}`);
37
32
  if (job.id === undefined)
38
- throw new Error("a plugin scope job has no id");
39
- return this.sync.process(job.data, {
40
- jobId: job.id,
41
- finalAttempt: job.attemptsMade + 1 >= (job.opts.attempts ?? 1),
42
- signal: this.stopping.signal,
43
- });
44
- }, {
45
- // an item or chunk job spans the orgs of a platform item; an org job carries its orgId
46
- platform: "plugin scope sync of a platform item",
33
+ throw new Error("a plugin effect job has no id");
34
+ return this.sync.process(job.data, job.id, this.stopping.signal);
47
35
  });
48
36
  }
49
37
  /** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
@@ -57,11 +45,7 @@ let PluginScopeSyncProcessor = class PluginScopeSyncProcessor extends WorkerHost
57
45
  }
58
46
  failed(job, err) {
59
47
  const meta = { name: job?.name, jobId: job?.id, attempt: job?.attemptsMade, err };
60
- // waiting for a replica to load an extension is expected: retried with the backoff
61
- if (err instanceof ScopeSyncDeferred)
62
- this.log.warn("plugin scope job deferred", meta);
63
- else
64
- this.log.error("plugin scope job failed", meta);
48
+ this.log.error("plugin effect job failed", meta);
65
49
  }
66
50
  error(err) {
67
51
  this.log.error("plugin scope worker error", { err });
@@ -90,7 +74,7 @@ PluginScopeWorkersModule = __decorate([
90
74
  Module({
91
75
  imports: [CatalogModule],
92
76
  providers: [
93
- configuredProcessor(PluginScopeSyncProcessor, PLUGIN_SCOPE_QUEUE, {
77
+ configuredProcessor(PluginScopeSyncProcessor, PLUGIN_EFFECT_QUEUE, {
94
78
  concurrency: PLUGIN_SCOPE_CONCURRENCY,
95
79
  }),
96
80
  ],
@@ -1,136 +1,45 @@
1
1
  import { EffectiveConfigs } from "../extensions/effective-config.js";
2
2
  import { ExtensionRegistry } from "../extensions/registry.js";
3
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
4
  import { KernelDb } from "../infra/database/kernel-db.js";
4
5
  import { TransactionHost } from "../infra/database/transaction-host.js";
5
6
  import { LockService } from "../infra/lock/lock.service.js";
6
7
  import { OutboxService } from "../infra/outbox/outbox.service.js";
7
8
  import type { KernelLogger } from "../log.js";
9
+ import { OrgLock } from "../orgs/org-lock.js";
10
+ import { type EffectJob } from "./effect-work.js";
8
11
  import { PluginInstaller } from "./plugin-install.js";
9
- import { type ScopeJob } from "./scope-jobs.js";
10
- import { TemplateConnectorEnsurer } from "./template-connector-ensure.js";
11
- /**
12
- * The plugin scope sync (plugin and component management spec §5, phase 1): converges every org
13
- * to each platform plugin's scope. In phase 1 "on in an org" is the org's plugin install, so for
14
- * each (item, org) the sync:
15
- * - wanted on (`wantedOn`, or a live install in the org depends on it: rule 9) and no live install
16
- * -> installs it as the kernel itself (actor null, audits `via: "scope"`). An install asks for
17
- * no input (plugin pages spec §5.2.2): its connector templates become connectors, those lacking
18
- * an org credential or OAuth client `needs_config`, and an extension whose effective config is
19
- * not valid in the org is switched on all the same (it gets no call until it is, and the org
20
- * catalog shows the plugin `needs_config`);
21
- * - wanted off and a live install -> uninstalls it (`via: "scope"`; the person who changed the
22
- * scope or the switch confirmed the preview); the connectors the install created stay as the
23
- * org's own (spec §5 rule 8); a dependency install it took along that its own scope still wants
24
- * on stays as a standalone install (the installer's rule), the others are synced again.
25
- * The decision is made outside the org row lock; the installer re-checks the scope under it for a
26
- * `via: "scope"` install or uninstall, so a person's switch committed meanwhile wins.
27
- * The sync writes no switch row: those record people's choices, and `wantedOn` honours them for
28
- * every scope (an org that switched an `all` item off stays off, also across a scope change away
29
- * and back, layering spec §4). Builtin items are left alone: they are on everywhere without an org
30
- * install, and their extension is enabled in every org by `enabled.ts` (required or not). A
31
- * failed install, uninstall or dependency install is logged, audited `plugin.scope_sync_failed`
32
- * (once while the same failure stays open), kept as the pair's open failure
33
- * (`plugin_scope_sync_failures`, the super admin's inbox, until a later sync of the pair does not
34
- * fail) and not retried until the next sync of the item (syncs follow owing transactions, never a
35
- * timer). An error outside those steps (a read, the failure write itself) ends the attempt
36
- * without touching the pair's row, so an older failure stays open.
37
- *
38
- * Jobs (queue {@link PLUGIN_SCOPE_QUEUE}), all owed through the outbox (transactional outbox spec
39
- * §8.1), so none is lost:
40
- * - `scope-item` (`scope-item-<itemId>-x<xact>`, one per owing transaction): owed by every
41
- * transaction that changes what the item's sync converges to: its scope, disabled flag, list,
42
- * owner or platform version, an import's commit that deploys no extension, and the deploy of its
43
- * extension (`oweDeployedExtensionSync`: enabled, a new version of an enabled one, permissions
44
- * approved). It fans out: one `scope-item-chunk` per chunk of orgs (`<item job id>-c<n>`, at
45
- * most {@link SCOPE_ORG_CHUNK} orgs each), all owed in one transaction;
46
- * - `scope-item-chunk`: converges the item in its orgs;
47
- * - `scope-org` (`scope-org-<orgId>`): every item in one org, owed by the org's creation.
48
- * A migration that changes a scope inserts its outbox rows itself. One BullMQ retry policy
49
- * (registry): a chunk or org job whose extension is enabled on the deployment but not loaded on
50
- * this replica yet fails after converging its other pairs, so BullMQ retries it with its backoff
51
- * (on any replica); its last attempt installs anyway and records what fails. Pairs of one org are
52
- * serialized across replicas by a Redis lock per org; the installer's org row lock and its
53
- * one-live-install rule are the backstop.
54
- */
55
- export { PLUGIN_SCOPE_QUEUE, SCOPE_CHUNK_JOB, SCOPE_ITEM_JOB, SCOPE_ORG_CHUNK, SCOPE_ORG_CHUNK_SIZE, SCOPE_ORG_JOB, type ScopeJob, scopeChunkJobId, scopeItemJobId, scopeOrgJobId, } from "./scope-jobs.js";
56
- /**
57
- * What a sync of one (item, org) did. `deferred`: the plugin's extension is enabled on the
58
- * deployment but not loaded on this replica yet (P3-38); the job fails for a BullMQ retry.
59
- */
12
+ /** What a convergence attempt for one affected pair did. */
60
13
  export type ScopeSyncResult = "installed" | "removed" | "unchanged" | "deferred";
61
- /**
62
- * A chunk or org job with a pair whose extension this replica has not loaded yet (P3-38): thrown
63
- * after its other pairs converged, so BullMQ retries the job with its backoff.
64
- */
65
- export declare class ScopeSyncDeferred extends Error {
66
- readonly itemIds: string[];
67
- constructor(itemIds: string[]);
68
- }
69
- /** How a job runs: its BullMQ id and whether this is its last attempt. */
70
- export interface ScopeJobRun {
71
- /** The job's id (an item job's chunks are named after it). */
72
- jobId: string;
73
- /** The job's last attempt: a pair whose extension is not loaded here is attempted anyway. */
74
- finalAttempt: boolean;
75
- /** Stops between pairs (the worker closing). */
76
- signal?: AbortSignal;
77
- }
78
- /** The worker's concurrency (per replica): how many chunk, item and org jobs run at once. */
14
+ /** The maximum number of effect jobs one worker processes at once. */
79
15
  export declare const PLUGIN_SCOPE_CONCURRENCY = 2;
80
- /** `ids` in chunks of `size` (the last one shorter). */
81
- export declare function chunked<T>(ids: readonly T[], size: number): T[][];
16
+ export { PLUGIN_EFFECT_QUEUE } from "./effect-work.js";
82
17
  export declare class PluginScopeSync {
83
18
  private readonly kdb;
84
19
  private readonly outbox;
85
20
  private readonly installer;
86
- private readonly templateConnectors;
87
21
  private readonly registry;
22
+ private readonly config;
88
23
  private readonly effective;
24
+ private readonly orgLock;
89
25
  private readonly locks;
90
26
  private readonly log;
91
27
  readonly txHost: TransactionHost;
92
- /** Orgs per chunk job (a test seam; default {@link SCOPE_ORG_CHUNK}). */
93
- private readonly chunkSize;
94
- constructor(kdb: KernelDb, outbox: Pick<OutboxService, "add" | "addMany">, installer: PluginInstaller, templateConnectors: Pick<TemplateConnectorEnsurer, "ensureTemplateConnectorsIn">, registry: ExtensionRegistry, effective: Pick<EffectiveConfigs, "get">, locks: LockService, log: KernelLogger, txHost: TransactionHost,
95
- /** Orgs per chunk job (a test seam; default {@link SCOPE_ORG_CHUNK}). */
96
- chunkSize?: number);
28
+ constructor(kdb: KernelDb, outbox: Pick<OutboxService, "add" | "addMany">, installer: PluginInstaller, registry: ExtensionRegistry, config: KernelConfigService, effective: Pick<EffectiveConfigs, "get">, orgLock: OrgLock, locks: LockService, log: KernelLogger, txHost: TransactionHost);
97
29
  private get db();
98
- /**
99
- * Owes the sync of an item in every org in the transaction in context (one job per
100
- * transaction), the transaction that changes what it converges to.
101
- */
102
- enqueueItem(itemId: string): Promise<void>;
103
- /** Owes the sync of every item in an org, in the transaction that creates the org. */
30
+ enqueueItem(itemId: string, previousOrgs?: readonly string[]): Promise<void>;
104
31
  enqueueOrg(orgId: string): Promise<void>;
105
- /**
106
- * One job: an item job fans out to its chunk jobs; a chunk job converges the item in its orgs,
107
- * an org job every item in the org. A pair deferred because its extension is not loaded here
108
- * fails the job after the others ({@link ScopeSyncDeferred}), unless this is its last attempt.
109
- */
110
- process(data: ScopeJob, run: ScopeJobRun): Promise<void>;
111
- /**
112
- * Owes one chunk job per {@link chunkSize} live orgs of the item job `jobId`, in one
113
- * transaction (a redelivered item job owes the same ids again: deduped).
114
- */
115
- private fanOut;
116
- /**
117
- * Whether the install of the item's `version` may go ahead on this replica (P3-38): its
118
- * extension is loaded here, or it is not enabled on the deployment (the install reports
119
- * `catalog.not_deployed` as before). Enabled but not loaded here (its deploy owed this sync, and
120
- * this replica's reconcile has not caught up yet) -> false, unless this is the job's last try.
121
- */
32
+ recover(): Promise<void>;
33
+ process(data: EffectJob, jobId: string, signal?: AbortSignal): Promise<void>;
34
+ /** Allow another worker to apply the effects while a live replica has the revision. */
122
35
  private extensionReady;
123
36
  /** Converges one (item, org), under the org's sync lock; `signal` ends the wait for it. */
124
- syncPair(itemId: string, orgId: string, signal?: AbortSignal, opts?: {
125
- finalTry?: boolean;
126
- }): Promise<ScopeSyncResult>;
127
- /**
128
- * {@link syncLocked} plus the pair's open failure (`plugin_scope_sync_failures`, the super
129
- * admin's inbox): an attempt that failed records it, any other attempt clears it. An attempt
130
- * that throws (outside the recorded steps) leaves the row as it was.
131
- */
132
- private syncRecorded;
37
+ syncPair(itemId: string, orgId: string, signal?: AbortSignal, generation?: string): Promise<ScopeSyncResult>;
38
+ private apply;
39
+ private current;
40
+ private settleGeneration;
133
41
  private syncLocked;
42
+ private enqueueDependencyEffects;
134
43
  /** The items of the dependency installs this install (of `orgId`) created. */
135
44
  private createdDependencies;
136
45
  /**
@@ -143,10 +52,6 @@ export declare class PluginScopeSync {
143
52
  needsConfig(orgId: string, itemId: string, version: string): Promise<boolean>;
144
53
  /** Whether the plugin's extension (manifest `m`), loaded here, has no valid config for the org. */
145
54
  private extensionConfigInvalid;
146
- /**
147
- * Logs and audits a failed install or uninstall (`plugin.scope_sync_failed`, actor null) and
148
- * records it as the pair's open failure (the super admin's inbox).
149
- */
150
55
  private failed;
151
- private recordFailure;
56
+ private settleFailure;
152
57
  }