@capybara-hq/kernel 0.1.0-rc.136 → 0.1.0-rc.138

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 (203) hide show
  1. package/dist/admin/audit-log.service.d.ts +96 -12
  2. package/dist/admin/audit-log.service.js +508 -44
  3. package/dist/admin/audit-targets.d.ts +17 -0
  4. package/dist/admin/audit-targets.js +84 -0
  5. package/dist/admin/audit.controller.d.ts +12 -9
  6. package/dist/admin/audit.controller.js +29 -8
  7. package/dist/admin/audit.schemas.d.ts +20 -4
  8. package/dist/admin/audit.schemas.js +42 -17
  9. package/dist/admin/extensions.controller.d.ts +5 -2
  10. package/dist/admin/extensions.controller.js +10 -1
  11. package/dist/admin/extensions.schemas.d.ts +4 -0
  12. package/dist/admin/extensions.schemas.js +9 -0
  13. package/dist/admin/health.service.d.ts +1 -1
  14. package/dist/admin/health.service.js +3 -3
  15. package/dist/agents/templates.js +3 -10
  16. package/dist/app.d.ts +3 -1
  17. package/dist/app.js +1 -0
  18. package/dist/automations/automations.service.js +4 -5
  19. package/dist/catalog/catalog-content.d.ts +6 -8
  20. package/dist/catalog/catalog-content.js +17 -22
  21. package/dist/catalog/catalog-items.d.ts +5 -10
  22. package/dist/catalog/catalog-items.js +27 -51
  23. package/dist/catalog/catalog-scope.service.d.ts +4 -2
  24. package/dist/catalog/catalog-scope.service.js +109 -145
  25. package/dist/catalog/catalog.module.js +7 -4
  26. package/dist/catalog/catalog.service.d.ts +10 -4
  27. package/dist/catalog/catalog.service.js +52 -10
  28. package/dist/catalog/cli.js +17 -0
  29. package/dist/catalog/component-promotion.js +8 -4
  30. package/dist/catalog/component-scope.service.d.ts +3 -1
  31. package/dist/catalog/component-scope.service.js +101 -140
  32. package/dist/catalog/component-state.d.ts +10 -8
  33. package/dist/catalog/component-state.js +42 -30
  34. package/dist/catalog/dependency-edges.d.ts +25 -0
  35. package/dist/catalog/dependency-edges.js +125 -0
  36. package/dist/catalog/effect-work.d.ts +27 -0
  37. package/dist/catalog/effect-work.js +151 -0
  38. package/dist/catalog/jobs.d.ts +4 -1
  39. package/dist/catalog/jobs.js +14 -4
  40. package/dist/catalog/org-catalog.service.d.ts +5 -1
  41. package/dist/catalog/org-catalog.service.js +101 -106
  42. package/dist/catalog/org-intent.d.ts +45 -0
  43. package/dist/catalog/org-intent.js +205 -0
  44. package/dist/catalog/owned-items.d.ts +6 -2
  45. package/dist/catalog/owned-items.js +27 -32
  46. package/dist/catalog/ownership.d.ts +2 -3
  47. package/dist/catalog/ownership.js +10 -28
  48. package/dist/catalog/platform-components.d.ts +3 -1
  49. package/dist/catalog/platform-components.js +9 -1
  50. package/dist/catalog/plugin-import.d.ts +4 -2
  51. package/dist/catalog/plugin-import.js +22 -21
  52. package/dist/catalog/plugin-install.d.ts +19 -54
  53. package/dist/catalog/plugin-install.js +221 -271
  54. package/dist/catalog/plugin-upgrade.d.ts +10 -5
  55. package/dist/catalog/plugin-upgrade.js +80 -67
  56. package/dist/catalog/request-rules.js +20 -8
  57. package/dist/catalog/scope-orgs.js +2 -7
  58. package/dist/catalog/scope-state.d.ts +6 -6
  59. package/dist/catalog/scope-state.js +24 -43
  60. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  61. package/dist/catalog/scope-sync-workers.js +10 -26
  62. package/dist/catalog/scope-sync.d.ts +19 -116
  63. package/dist/catalog/scope-sync.js +228 -275
  64. package/dist/catalog/scope-writer.d.ts +87 -0
  65. package/dist/catalog/scope-writer.js +239 -0
  66. package/dist/catalog/template-connector-ensure.js +1 -1
  67. package/dist/catalog/unshare.js +9 -43
  68. package/dist/channels/connections.service.js +6 -6
  69. package/dist/channels/supervisor.js +3 -7
  70. package/dist/client/client-access.service.js +2 -12
  71. package/dist/config/schema.d.ts +6 -0
  72. package/dist/config/schema.js +32 -1
  73. package/dist/ctx/create-ctx.d.ts +2 -2
  74. package/dist/ctx/create-ctx.js +2 -60
  75. package/dist/ctx/guard-db.d.ts +6 -0
  76. package/dist/ctx/guard-db.js +55 -0
  77. package/dist/db/extension-handoff-schema.d.ts +1 -1
  78. package/dist/db/extension-handoff-schema.js +48 -10
  79. package/dist/db/extension-schema-transfer.js +5 -2
  80. package/dist/db/kernel-schema.d.ts +32 -6
  81. package/dist/device-access/host-services.d.ts +2 -2
  82. package/dist/device-access/host-services.js +5 -6
  83. package/dist/erasure/org-catalog.js +2 -2
  84. package/dist/erasure/org-rules.js +7 -0
  85. package/dist/extensions/admin-ops.d.ts +10 -6
  86. package/dist/extensions/admin-ops.js +53 -9
  87. package/dist/extensions/admin-view.d.ts +4 -1
  88. package/dist/extensions/admin-view.js +27 -14
  89. package/dist/extensions/bootstrap.d.ts +1 -1
  90. package/dist/extensions/bootstrap.js +6 -4
  91. package/dist/extensions/cli.js +1 -0
  92. package/dist/extensions/effective-config.js +1 -4
  93. package/dist/extensions/enabled.d.ts +183 -29
  94. package/dist/extensions/enabled.js +148 -62
  95. package/dist/extensions/host.d.ts +65 -45
  96. package/dist/extensions/host.js +446 -128
  97. package/dist/extensions/installs.d.ts +9 -0
  98. package/dist/extensions/installs.js +23 -0
  99. package/dist/extensions/isolated/admission.d.ts +10 -0
  100. package/dist/extensions/isolated/admission.js +206 -0
  101. package/dist/extensions/isolated/authorization.d.ts +45 -0
  102. package/dist/extensions/isolated/authorization.js +191 -0
  103. package/dist/extensions/isolated/broker.d.ts +15 -0
  104. package/dist/extensions/isolated/broker.js +471 -0
  105. package/dist/extensions/isolated/child-protocol.d.ts +84 -0
  106. package/dist/extensions/isolated/child-protocol.js +21 -0
  107. package/dist/extensions/isolated/child-registration.d.ts +22 -0
  108. package/dist/extensions/isolated/child-registration.js +152 -0
  109. package/dist/extensions/isolated/child-session.d.ts +6 -0
  110. package/dist/extensions/isolated/child-session.js +343 -0
  111. package/dist/extensions/isolated/child-streams.d.ts +4 -0
  112. package/dist/extensions/isolated/child-streams.js +142 -0
  113. package/dist/extensions/isolated/child.d.ts +1 -0
  114. package/dist/extensions/isolated/child.js +10 -0
  115. package/dist/extensions/isolated/configured-package.d.ts +15 -0
  116. package/dist/extensions/isolated/configured-package.js +73 -0
  117. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  118. package/dist/extensions/isolated/engine-binds.js +82 -0
  119. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  120. package/dist/extensions/isolated/engine-policy.js +75 -0
  121. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  122. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  123. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  124. package/dist/extensions/isolated/engine-proxy.js +408 -0
  125. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  126. package/dist/extensions/isolated/engine-vaults.js +93 -0
  127. package/dist/extensions/isolated/lanes.d.ts +108 -0
  128. package/dist/extensions/isolated/lanes.js +726 -0
  129. package/dist/extensions/isolated/postgres-gate.d.ts +15 -0
  130. package/dist/extensions/isolated/postgres-gate.js +255 -0
  131. package/dist/extensions/isolated/revision.d.ts +32 -0
  132. package/dist/extensions/isolated/revision.js +359 -0
  133. package/dist/extensions/isolated/rpc-frame.d.ts +50 -0
  134. package/dist/extensions/isolated/rpc-frame.js +193 -0
  135. package/dist/extensions/isolated/rpc.d.ts +66 -0
  136. package/dist/extensions/isolated/rpc.js +314 -0
  137. package/dist/extensions/isolated/sandbox.d.ts +39 -0
  138. package/dist/extensions/isolated/sandbox.js +356 -0
  139. package/dist/extensions/isolated/tier.d.ts +6 -0
  140. package/dist/extensions/isolated/tier.js +45 -0
  141. package/dist/extensions/ledger.d.ts +1 -1
  142. package/dist/extensions/lifecycle-topics.d.ts +2 -0
  143. package/dist/extensions/lifecycle-topics.js +2 -0
  144. package/dist/extensions/lifecycle.d.ts +3 -1
  145. package/dist/extensions/lifecycle.js +53 -5
  146. package/dist/extensions/locks.d.ts +2 -0
  147. package/dist/extensions/locks.js +7 -0
  148. package/dist/extensions/org-config.d.ts +17 -27
  149. package/dist/extensions/org-config.js +114 -129
  150. package/dist/extensions/permission-view.d.ts +6 -1
  151. package/dist/extensions/plugin-guides.d.ts +5 -10
  152. package/dist/extensions/plugin-guides.js +18 -37
  153. package/dist/extensions/plugin-icons.d.ts +3 -21
  154. package/dist/extensions/plugin-icons.js +9 -44
  155. package/dist/extensions/plugin-items.d.ts +10 -30
  156. package/dist/extensions/plugin-items.js +32 -73
  157. package/dist/extensions/source-intent.d.ts +14 -0
  158. package/dist/extensions/source-intent.js +77 -0
  159. package/dist/inbox/platform-inbox.service.js +16 -27
  160. package/dist/index.d.ts +2 -1
  161. package/dist/index.js +2 -1
  162. package/dist/infra/database/database.module.js +6 -1
  163. package/dist/infra/database/kernel-db.d.ts +3 -1
  164. package/dist/infra/database/kernel-db.js +4 -0
  165. package/dist/infra/events/kernel-events.d.ts +4 -0
  166. package/dist/infra/outbox/registry.d.ts +3 -36
  167. package/dist/infra/outbox/registry.js +4 -49
  168. package/dist/infra/paging/paged-read.d.ts +56 -0
  169. package/dist/infra/paging/paged-read.js +78 -0
  170. package/dist/infra/queue/queue-names.d.ts +1 -1
  171. package/dist/infra/queue/queue-names.js +1 -1
  172. package/dist/kernel.d.ts +3 -2
  173. package/dist/kernel.js +21 -2
  174. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  175. package/dist/lifecycle/kernel-lifecycle.js +22 -12
  176. package/dist/lifecycle/tokens.d.ts +8 -0
  177. package/dist/lifecycle/tokens.js +2 -0
  178. package/dist/orgs/directory-sync.js +1 -4
  179. package/dist/orgs/org-lock.d.ts +3 -1
  180. package/dist/orgs/org-lock.js +3 -1
  181. package/dist/orgs/orgs.service.d.ts +3 -1
  182. package/dist/orgs/orgs.service.js +15 -8
  183. package/dist/overrides.d.ts +0 -3
  184. package/dist/overrides.js +0 -2
  185. package/dist/platform/ops/admin.ops.js +14 -3
  186. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  187. package/dist/platform/ops/org-plugins.ops.js +5 -2
  188. package/dist/platform/ops/orgs.ops.js +13 -3
  189. package/dist/platform/ops/plugins.ops.js +11 -10
  190. package/dist/setup/setup-checks.service.js +3 -2
  191. package/dist/skills/usable.js +41 -30
  192. package/dist/themes/theme-state.js +3 -3
  193. package/dist/tools/registry.d.ts +2 -2
  194. package/dist/tools/registry.js +7 -3
  195. package/package.json +2 -2
  196. package/src/migrations/0228_extension_org_switches.sql +56 -0
  197. package/src/migrations/0229_catalog_dependency_edges.sql +17 -0
  198. package/src/migrations/0230_audit_filter_idx.sql +18 -0
  199. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  200. package/dist/catalog/install-status.d.ts +0 -6
  201. package/dist/catalog/install-status.js +0 -6
  202. package/dist/catalog/scope-jobs.d.ts +0 -59
  203. package/dist/catalog/scope-jobs.js +0 -78
@@ -7,11 +7,15 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { Inject, Injectable, Optional } from "@nestjs/common";
10
+ import { randomUUID } from "node:crypto";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { sql } from "kysely";
11
13
  import { ApiError } from "../errors.js";
12
14
  import { EffectiveConfigs } from "../extensions/effective-config.js";
15
+ import { STALE_RECONCILE_PERIODS } from "../extensions/lifecycle-topics.js";
13
16
  import { ExtensionRegistry } from "../extensions/registry.js";
14
17
  import { audit } from "../identity/audit.js";
18
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
19
  import { KernelDb } from "../infra/database/kernel-db.js";
16
20
  import { withOrgScope } from "../infra/database/org-scope.js";
17
21
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -19,201 +23,63 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
19
23
  import { LockService } from "../infra/lock/lock.service.js";
20
24
  import { OutboxService } from "../infra/outbox/outbox.service.js";
21
25
  import { KERNEL_LOGGER } from "../infra/tokens.js";
22
- import { LIVE_INSTALL_STATUSES } from "./install-status.js";
26
+ import { OrgLock } from "../orgs/org-lock.js";
27
+ import { effectGeneration, oweEffectWork, recoverEffectWork, } from "./effect-work.js";
23
28
  import { isUsable } from "./ownership.js";
24
29
  import { PluginInstaller } from "./plugin-install.js";
25
- import { wantedOn } from "./scope.js";
26
- import { oweScopeItem, PLUGIN_SCOPE_QUEUE, SCOPE_CHUNK_JOB, SCOPE_ORG_CHUNK, SCOPE_ORG_CHUNK_SIZE, SCOPE_ORG_JOB, scopeChunkJobId, scopeOrgJobId, } from "./scope-jobs.js";
27
- import { ScopeNoLongerWanted, ScopeStillWanted } from "./scope-state.js";
28
- import { TemplateConnectorEnsurer } from "./template-connector-ensure.js";
29
- /**
30
- * The plugin scope sync (plugin and component management spec §5, phase 1): converges every org
31
- * to each platform plugin's scope. In phase 1 "on in an org" is the org's plugin install, so for
32
- * each (item, org) the sync:
33
- * - wanted on (`wantedOn`, or a live install in the org depends on it: rule 9) and no live install
34
- * -> installs it as the kernel itself (actor null, audits `via: "scope"`). An install asks for
35
- * no input (plugin pages spec §5.2.2): its connector templates become connectors, those lacking
36
- * an org credential or OAuth client `needs_config`, and an extension whose effective config is
37
- * not valid in the org is switched on all the same (it gets no call until it is, and the org
38
- * catalog shows the plugin `needs_config`);
39
- * - wanted off and a live install -> uninstalls it (`via: "scope"`; the person who changed the
40
- * scope or the switch confirmed the preview); the connectors the install created stay as the
41
- * org's own (spec §5 rule 8); a dependency install it took along that its own scope still wants
42
- * on stays as a standalone install (the installer's rule), the others are synced again.
43
- * The decision is made outside the org row lock; the installer re-checks the scope under it for a
44
- * `via: "scope"` install or uninstall, so a person's switch committed meanwhile wins.
45
- * The sync writes no switch row: those record people's choices, and `wantedOn` honours them for
46
- * every scope (an org that switched an `all` item off stays off, also across a scope change away
47
- * and back, layering spec §4). Builtin items are left alone: they are on everywhere without an org
48
- * install, and their extension is enabled in every org by `enabled.ts` (required or not). A
49
- * failed install, uninstall or dependency install is logged, audited `plugin.scope_sync_failed`
50
- * (once while the same failure stays open), kept as the pair's open failure
51
- * (`plugin_scope_sync_failures`, the super admin's inbox, until a later sync of the pair does not
52
- * fail) and not retried until the next sync of the item (syncs follow owing transactions, never a
53
- * timer). An error outside those steps (a read, the failure write itself) ends the attempt
54
- * without touching the pair's row, so an older failure stays open.
55
- *
56
- * Jobs (queue {@link PLUGIN_SCOPE_QUEUE}), all owed through the outbox (transactional outbox spec
57
- * §8.1), so none is lost:
58
- * - `scope-item` (`scope-item-<itemId>-x<xact>`, one per owing transaction): owed by every
59
- * transaction that changes what the item's sync converges to: its scope, disabled flag, list,
60
- * owner or platform version, an import's commit that deploys no extension, and the deploy of its
61
- * extension (`oweDeployedExtensionSync`: enabled, a new version of an enabled one, permissions
62
- * approved). It fans out: one `scope-item-chunk` per chunk of orgs (`<item job id>-c<n>`, at
63
- * most {@link SCOPE_ORG_CHUNK} orgs each), all owed in one transaction;
64
- * - `scope-item-chunk`: converges the item in its orgs;
65
- * - `scope-org` (`scope-org-<orgId>`): every item in one org, owed by the org's creation.
66
- * A migration that changes a scope inserts its outbox rows itself. One BullMQ retry policy
67
- * (registry): a chunk or org job whose extension is enabled on the deployment but not loaded on
68
- * this replica yet fails after converging its other pairs, so BullMQ retries it with its backoff
69
- * (on any replica); its last attempt installs anyway and records what fails. Pairs of one org are
70
- * serialized across replicas by a Redis lock per org; the installer's org row lock and its
71
- * one-live-install rule are the backstop.
72
- */
73
- export { PLUGIN_SCOPE_QUEUE, SCOPE_CHUNK_JOB, SCOPE_ITEM_JOB, SCOPE_ORG_CHUNK, SCOPE_ORG_CHUNK_SIZE, SCOPE_ORG_JOB, scopeChunkJobId, scopeItemJobId, scopeOrgJobId, } from "./scope-jobs.js";
74
- /**
75
- * A chunk or org job with a pair whose extension this replica has not loaded yet (P3-38): thrown
76
- * after its other pairs converged, so BullMQ retries the job with its backoff.
77
- */
78
- export class ScopeSyncDeferred extends Error {
79
- itemIds;
80
- constructor(itemIds) {
81
- super(`the extension of catalog item(s) ${itemIds.join(", ")} is enabled on the deployment but not loaded on this replica yet; the scope sync job is retried`);
82
- this.itemIds = itemIds;
83
- this.name = "ScopeSyncDeferred";
84
- }
30
+ import { pluginEffectsWanted, ScopeNoLongerWanted, ScopeStillWanted, wantedByScope, } from "./scope-state.js";
31
+ import { oweTemplateConnectors } from "./template-connector-jobs.js";
32
+ class SupersededEffect extends Error {
33
+ }
34
+ class FailedEffect extends Error {
85
35
  }
86
36
  /** How long one org's pairs wait for each other (an install can take a while). */
87
37
  const ORG_LOCK_TTL_MS = 60_000;
88
38
  const ORG_LOCK_WAIT_MS = 10 * 60_000;
89
- /** The worker's concurrency (per replica): how many chunk, item and org jobs run at once. */
39
+ /** The maximum number of effect jobs one worker processes at once. */
90
40
  export const PLUGIN_SCOPE_CONCURRENCY = 2;
91
- /** `ids` in chunks of `size` (the last one shorter). */
92
- export function chunked(ids, size) {
93
- if (!Number.isInteger(size) || size < 1)
94
- throw new Error(`invalid chunk size ${size}`);
95
- const out = [];
96
- for (let i = 0; i < ids.length; i += size)
97
- out.push(ids.slice(i, i + size));
98
- return out;
99
- }
41
+ export { PLUGIN_EFFECT_QUEUE } from "./effect-work.js";
100
42
  let PluginScopeSync = class PluginScopeSync {
101
43
  kdb;
102
44
  outbox;
103
45
  installer;
104
- templateConnectors;
105
46
  registry;
47
+ config;
106
48
  effective;
49
+ orgLock;
107
50
  locks;
108
51
  log;
109
52
  txHost;
110
- chunkSize;
111
- constructor(kdb, outbox, installer, templateConnectors, registry, effective, locks, log, txHost,
112
- /** Orgs per chunk job (a test seam; default {@link SCOPE_ORG_CHUNK}). */
113
- chunkSize = SCOPE_ORG_CHUNK) {
53
+ constructor(kdb, outbox, installer, registry, config, effective, orgLock, locks, log, txHost) {
114
54
  this.kdb = kdb;
115
55
  this.outbox = outbox;
116
56
  this.installer = installer;
117
- this.templateConnectors = templateConnectors;
118
57
  this.registry = registry;
58
+ this.config = config;
119
59
  this.effective = effective;
60
+ this.orgLock = orgLock;
120
61
  this.locks = locks;
121
62
  this.log = log;
122
63
  this.txHost = txHost;
123
- this.chunkSize = chunkSize;
124
64
  }
125
65
  get db() {
126
66
  return this.kdb.db;
127
67
  }
128
- /**
129
- * Owes the sync of an item in every org in the transaction in context (one job per
130
- * transaction), the transaction that changes what it converges to.
131
- */
132
- async enqueueItem(itemId) {
133
- await oweScopeItem(this.outbox, this.db, itemId);
68
+ async enqueueItem(itemId, previousOrgs = []) {
69
+ await oweEffectWork(this.outbox, this.db, { itemIds: [itemId], previousOrgs });
134
70
  }
135
- /** Owes the sync of every item in an org, in the transaction that creates the org. */
136
71
  async enqueueOrg(orgId) {
137
- await this.outbox.add({
138
- queue: PLUGIN_SCOPE_QUEUE,
139
- name: SCOPE_ORG_JOB,
140
- jobId: scopeOrgJobId(orgId),
141
- data: { kind: "org", orgId },
142
- orgId,
143
- });
72
+ await oweEffectWork(this.outbox, this.db, { orgId });
144
73
  }
145
- /**
146
- * One job: an item job fans out to its chunk jobs; a chunk job converges the item in its orgs,
147
- * an org job every item in the org. A pair deferred because its extension is not loaded here
148
- * fails the job after the others ({@link ScopeSyncDeferred}), unless this is its last attempt.
149
- */
150
- async process(data, run) {
151
- if (data.kind === "item") {
152
- await this.fanOut(data.itemId, run.jobId);
153
- return;
154
- }
155
- const pairs = data.kind === "chunk"
156
- ? data.orgIds.map((orgId) => [data.itemId, orgId])
157
- : (await this.db
158
- .selectFrom("catalog_items")
159
- .select("id")
160
- .where("deleted_at", "is", null)
161
- .where("builtin", "=", false)
162
- .orderBy("id")
163
- .execute()).map((i) => [i.id, data.orgId]);
164
- const deferred = new Set();
165
- for (const [itemId, orgId] of pairs) {
166
- // Stopped between pairs: failed, so BullMQ retries the job (on this or another replica).
167
- // On the job's last attempt nothing retries it: the pairs not reached yet are dropped
168
- // until the next sync of the item or org (a scope change, a deploy, a new org) owes them
169
- if (run.signal?.aborted)
170
- throw new Error("the plugin scope worker stopped; the job is retried");
171
- try {
172
- const r = await this.syncPair(itemId, orgId, run.signal, { finalTry: run.finalAttempt });
173
- if (r === "deferred")
174
- deferred.add(itemId);
175
- }
176
- catch (err) {
177
- this.log.warn("plugin scope sync of a pair failed", { itemId, orgId, err });
178
- }
179
- }
180
- if (deferred.size > 0)
181
- throw new ScopeSyncDeferred([...deferred]);
74
+ async recover() {
75
+ await recoverEffectWork(this.outbox, this.db);
182
76
  }
183
- /**
184
- * Owes one chunk job per {@link chunkSize} live orgs of the item job `jobId`, in one
185
- * transaction (a redelivered item job owes the same ids again: deduped).
186
- */
187
- async fanOut(itemId, jobId) {
188
- const item = await this.db
189
- .selectFrom("catalog_items")
190
- .select("id")
191
- .where("id", "=", itemId)
192
- .where("deleted_at", "is", null)
193
- .executeTakeFirst();
194
- if (!item)
195
- return;
196
- const orgs = await this.db
197
- .selectFrom("orgs")
198
- .select("id")
199
- .where("deleted_at", "is", null)
200
- .orderBy("id")
201
- .execute();
202
- const chunks = chunked(orgs.map((o) => o.id), this.chunkSize);
203
- await this.outbox.addMany(chunks.map((orgIds, n) => ({
204
- queue: PLUGIN_SCOPE_QUEUE,
205
- name: SCOPE_CHUNK_JOB,
206
- jobId: scopeChunkJobId(jobId, n),
207
- data: { kind: "chunk", itemId, orgIds },
208
- })));
77
+ async process(data, jobId, signal) {
78
+ const generation = effectGeneration(jobId, data);
79
+ await this.syncPair(data.itemId, data.orgIds[0], signal, generation);
209
80
  }
210
- /**
211
- * Whether the install of the item's `version` may go ahead on this replica (P3-38): its
212
- * extension is loaded here, or it is not enabled on the deployment (the install reports
213
- * `catalog.not_deployed` as before). Enabled but not loaded here (its deploy owed this sync, and
214
- * this replica's reconcile has not caught up yet) -> false, unless this is the job's last try.
215
- */
216
- async extensionReady(itemId, version, finalTry) {
81
+ /** Allow another worker to apply the effects while a live replica has the revision. */
82
+ async extensionReady(itemId, orgId, version, generation) {
217
83
  const v = await this.db
218
84
  .selectFrom("catalog_item_versions")
219
85
  .select("manifest")
@@ -223,42 +89,140 @@ let PluginScopeSync = class PluginScopeSync {
223
89
  const m = v?.manifest;
224
90
  if (!m?.extension)
225
91
  return true;
226
- if (this.registry.manifests().some((x) => x.name === m.name))
92
+ // Trusted and isolated instances both activate in the same registry.
93
+ if (this.registry.current(m.name))
227
94
  return true;
228
95
  const install = await this.db
229
96
  .selectFrom("extension_installs")
230
- .select("desired_state")
97
+ .select(["desired_state", "sha256"])
231
98
  .where("name", "=", m.name)
232
99
  .executeTakeFirst();
233
- return install?.desired_state !== "enabled" || finalTry;
100
+ if (install?.desired_state !== "enabled")
101
+ return true;
102
+ const staleSeconds = STALE_RECONCILE_PERIODS * this.config.get().extensionHost.reconcileIntervalSeconds;
103
+ const ready = await this.db
104
+ .selectFrom("extension_replica_status")
105
+ .select("replica_id")
106
+ .where("plugin", "=", m.name)
107
+ .where("sha256", "=", install.sha256)
108
+ .where("state", "=", "loaded")
109
+ .where("heartbeat_at", ">", sql `now() - make_interval(secs => ${staleSeconds})`)
110
+ .executeTakeFirst();
111
+ if (ready && generation !== undefined) {
112
+ const canDefer = await this.db
113
+ .selectFrom("plugin_effect_work")
114
+ .select("generation")
115
+ .where("item_id", "=", itemId)
116
+ .where("org_id", "=", orgId)
117
+ .where("generation", "=", generation)
118
+ .where("generation_started_at", ">", sql `now() - interval '5 minutes'`)
119
+ .executeTakeFirst();
120
+ if (canDefer)
121
+ return false;
122
+ }
123
+ throw new ApiError("catalog.not_deployed", `Extension ${m.name} is not loaded on this worker. Check the extension's deployment status.`);
234
124
  }
235
125
  /** Converges one (item, org), under the org's sync lock; `signal` ends the wait for it. */
236
- syncPair(itemId, orgId, signal, opts = {}) {
126
+ syncPair(itemId, orgId, signal, generation) {
237
127
  return this.locks.run(`plugin-scope-org-${orgId}`, {
238
128
  ttlMs: ORG_LOCK_TTL_MS,
239
129
  waitMs: ORG_LOCK_WAIT_MS,
240
130
  ...(signal !== undefined && { signal }),
241
- }, () => withOrgScope(orgId, () => this.syncRecorded(itemId, orgId, opts.finalTry === true)));
131
+ }, ({ lost }) => withOrgScope(orgId, async () => {
132
+ if (generation !== undefined && !(await this.current(itemId, orgId, generation))) {
133
+ return "unchanged";
134
+ }
135
+ const attempt = {};
136
+ try {
137
+ return await this.apply(itemId, orgId, attempt, lost, generation);
138
+ }
139
+ catch (error) {
140
+ if (error instanceof SupersededEffect)
141
+ return "unchanged";
142
+ if (!(error instanceof FailedEffect) || !attempt.failure)
143
+ throw error;
144
+ lost.throwIfAborted();
145
+ await this.settleFailure(itemId, orgId, attempt.failure, generation);
146
+ return "unchanged";
147
+ }
148
+ }));
242
149
  }
243
- /**
244
- * {@link syncLocked} plus the pair's open failure (`plugin_scope_sync_failures`, the super
245
- * admin's inbox): an attempt that failed records it, any other attempt clears it. An attempt
246
- * that throws (outside the recorded steps) leaves the row as it was.
247
- */
248
- async syncRecorded(itemId, orgId, finalTry = false) {
249
- const attempt = { failed: false, finalTry };
250
- const result = await this.syncLocked(itemId, orgId, attempt);
251
- // a deferred pair changed nothing: an older failure stays open
252
- if (!attempt.failed && result !== "deferred") {
150
+ async apply(itemId, orgId, attempt, lost, generation) {
151
+ if (generation !== undefined && !(await this.current(itemId, orgId, generation))) {
152
+ return "unchanged";
153
+ }
154
+ const org = await this.orgLock.tryLock(orgId);
155
+ if (generation !== undefined && !(await this.current(itemId, orgId, generation))) {
156
+ return "unchanged";
157
+ }
158
+ lost.throwIfAborted();
159
+ const result = org ? await this.syncLocked(itemId, orgId, attempt, generation) : "unchanged";
160
+ lost.throwIfAborted();
161
+ if (attempt.failure)
162
+ throw new FailedEffect();
163
+ if (result === "deferred")
164
+ return result;
165
+ if (!(await this.settleGeneration(itemId, orgId, generation))) {
166
+ throw new SupersededEffect();
167
+ }
168
+ await this.db
169
+ .updateTable("plugin_installs")
170
+ .set({ status: "on", error: null })
171
+ .where("item_id", "=", itemId)
172
+ .where("org_id", "=", orgId)
173
+ .where("version", "is not", null)
174
+ .where("status", "=", "install_failed")
175
+ .execute();
176
+ if (attempt.intentOnly) {
253
177
  await this.db
254
- .deleteFrom("plugin_scope_sync_failures")
178
+ .deleteFrom("plugin_installs")
255
179
  .where("item_id", "=", itemId)
256
180
  .where("org_id", "=", orgId)
181
+ .where("version", "is", null)
182
+ .where((eb) => eb.not(eb.exists(eb
183
+ .selectFrom("plugin_install_components")
184
+ .select("install_id")
185
+ .whereRef("install_id", "=", "plugin_installs.id"))))
257
186
  .execute();
258
187
  }
188
+ await this.db
189
+ .deleteFrom("plugin_effect_work")
190
+ .where("item_id", "=", itemId)
191
+ .where("org_id", "=", orgId)
192
+ .where("state", "=", "settled")
193
+ .where((eb) => eb.exists(eb
194
+ .selectFrom("catalog_items")
195
+ .select("id")
196
+ .where("id", "=", itemId)
197
+ .where("deleted_at", "is not", null)))
198
+ .execute();
259
199
  return result;
260
200
  }
261
- async syncLocked(itemId, orgId, attempt) {
201
+ async current(itemId, orgId, generation) {
202
+ return ((await this.db
203
+ .selectFrom("plugin_effect_work")
204
+ .select("generation")
205
+ .where("item_id", "=", itemId)
206
+ .where("org_id", "=", orgId)
207
+ .where("generation", "=", generation)
208
+ .where("state", "=", "pending")
209
+ .executeTakeFirst()) !== undefined);
210
+ }
211
+ async settleGeneration(itemId, orgId, generation) {
212
+ if (generation === undefined)
213
+ return true;
214
+ const row = await this.db
215
+ .updateTable("plugin_effect_work")
216
+ .set({ state: "settled", updated_at: new Date() })
217
+ .where("item_id", "=", itemId)
218
+ .where("org_id", "=", orgId)
219
+ .where("generation", "=", generation)
220
+ .where("state", "=", "pending")
221
+ .returning("generation")
222
+ .executeTakeFirst();
223
+ return row !== undefined;
224
+ }
225
+ async syncLocked(itemId, orgId, attempt, generation) {
262
226
  const item = await this.db
263
227
  .selectFrom("catalog_items")
264
228
  .select([
@@ -271,7 +235,6 @@ let PluginScopeSync = class PluginScopeSync {
271
235
  "platform_synced_version",
272
236
  ])
273
237
  .where("id", "=", itemId)
274
- .where("deleted_at", "is", null)
275
238
  .executeTakeFirst();
276
239
  const org = await this.db
277
240
  .selectFrom("orgs")
@@ -281,57 +244,39 @@ let PluginScopeSync = class PluginScopeSync {
281
244
  .executeTakeFirst();
282
245
  if (!item || !org || item.builtin)
283
246
  return "unchanged";
284
- const [listed, sw, live] = await Promise.all([
285
- this.db
286
- .selectFrom("catalog_item_scope_orgs")
287
- .select("item_id")
288
- .where("item_id", "=", itemId)
289
- .where("org_id", "=", orgId)
290
- .executeTakeFirst(),
291
- this.db
292
- .selectFrom("catalog_item_org_switches")
293
- .select("enabled")
294
- .where("item_id", "=", itemId)
295
- .where("org_id", "=", orgId)
296
- .executeTakeFirst(),
297
- this.db
298
- .selectFrom("plugin_installs")
299
- .select(["id", "status"])
300
- .where("org_id", "=", orgId)
301
- .where("item_id", "=", itemId)
302
- .where("status", "in", [...LIVE_INSTALL_STATUSES])
303
- .executeTakeFirst(),
304
- ]);
305
- const wanted = wantedOn(item, listed !== undefined, sw?.enabled ?? null) ||
306
- (live !== undefined && (await this.dependedOn(orgId, live.id)));
247
+ const live = await this.db
248
+ .selectFrom("plugin_installs")
249
+ .select(["id", "version"])
250
+ .where("org_id", "=", orgId)
251
+ .where("item_id", "=", itemId)
252
+ .executeTakeFirst();
253
+ const wanted = await pluginEffectsWanted(this.db, orgId, itemId);
307
254
  if (wanted) {
308
- if (live) {
255
+ if (live?.version != null) {
309
256
  // A platform update may have added dependencies: installed here (rule 9, Task 7)
310
- if (live.status === "installed") {
311
- try {
312
- // a dependency just installed may provide the connector kind of a template the org
313
- // never got a connector from (ruling R27); nothing installed, nothing new to provide
314
- if ((await this.installer.addMissingDependencies(orgId, live.id)) > 0) {
315
- await this.templateConnectors.ensureTemplateConnectorsIn(orgId, undefined, {
316
- via: "scope",
317
- });
318
- }
319
- }
320
- catch (e) {
321
- await this.failed(orgId, itemId, "dependencies", e, attempt);
257
+ try {
258
+ // a dependency just installed may provide the connector kind of a template the org
259
+ // never got a connector from (ruling R27); nothing installed, nothing new to provide
260
+ if ((await this.installer.addMissingDependencies(orgId, live.id)) > 0) {
261
+ await oweTemplateConnectors(this.outbox, this.db, orgId);
322
262
  }
323
263
  }
264
+ catch (e) {
265
+ this.failed(orgId, itemId, "dependencies", e, attempt);
266
+ }
324
267
  return "unchanged";
325
268
  }
326
- if (!isUsable(item))
269
+ // A dependency-only install is owned and recorded by the enabling root's effects.
270
+ if (!isUsable(item) || !(await wantedByScope(this.db, orgId, itemId)))
327
271
  return "unchanged";
328
272
  // The platform's version (one per deployment, Task 7); the latest import before the first sync
329
273
  const version = item.platform_synced_version ?? item.latest_version;
330
274
  try {
331
- if (!(await this.extensionReady(itemId, version, attempt.finalTry)))
275
+ if (!(await this.extensionReady(itemId, orgId, version, generation)))
332
276
  return "deferred";
333
- await this.installer.install(orgId, null, itemId, version, {}, { via: "scope" });
334
- return "installed";
277
+ const install = await this.installer.install(orgId, null, itemId, version, {}, { via: "scope" });
278
+ attempt.intentOnly = install === null;
279
+ return install === null ? "unchanged" : "installed";
335
280
  }
336
281
  catch (e) {
337
282
  // A person switched it off (or the scope changed) after this decision: the installer's
@@ -343,13 +288,12 @@ let PluginScopeSync = class PluginScopeSync {
343
288
  (e.code === "plugin.already_installed" || e.code === "plugin.install_in_progress")) {
344
289
  return "unchanged";
345
290
  }
346
- await this.failed(orgId, itemId, "install", e, attempt);
291
+ this.failed(orgId, itemId, "install", e, attempt);
347
292
  return "unchanged";
348
293
  }
349
294
  }
350
- // Wanted off: only a settled install is removed (one still installing waits for the next
351
- // enqueue)
352
- if (live?.status !== "installed")
295
+ // Off intent removes applied ownership or the journal of an interrupted legacy attempt.
296
+ if (!live)
353
297
  return "unchanged";
354
298
  const deps = await this.createdDependencies(orgId, live.id);
355
299
  try {
@@ -360,28 +304,20 @@ let PluginScopeSync = class PluginScopeSync {
360
304
  // after this decision: the installer's re-check under the org row lock refused it
361
305
  if (e instanceof ScopeStillWanted)
362
306
  return "unchanged";
363
- await this.failed(orgId, itemId, "uninstall", e, attempt);
307
+ this.failed(orgId, itemId, "uninstall", e, attempt);
364
308
  return "unchanged";
365
309
  }
366
310
  // Dependency installs it took along may be wanted on by their own scope: synced again
367
- for (const dep of deps) {
368
- if (dep !== itemId)
369
- await this.syncRecorded(dep, orgId);
370
- }
311
+ await this.enqueueDependencyEffects(deps.filter((dep) => dep !== itemId), orgId);
371
312
  return "removed";
372
313
  }
373
- /** Whether a live install of the org depends on this install (spec §5 rule 9). */
374
- async dependedOn(orgId, installId) {
375
- const row = await this.db
376
- .selectFrom("plugin_install_components as c")
377
- .innerJoin("plugin_installs as a", "a.id", "c.install_id")
378
- .select("a.id")
379
- .where("a.org_id", "=", orgId)
380
- .where("a.status", "in", [...LIVE_INSTALL_STATUSES])
381
- .where("c.kind", "=", "plugin")
382
- .where("c.ref", "=", installId)
383
- .executeTakeFirst();
384
- return row !== undefined;
314
+ async enqueueDependencyEffects(itemIds, orgId) {
315
+ await oweEffectWork(this.outbox, this.db, {
316
+ itemIds,
317
+ orgId,
318
+ previousOrgs: [orgId],
319
+ includeDependents: false,
320
+ });
385
321
  }
386
322
  /** The items of the dependency installs this install (of `orgId`) created. */
387
323
  async createdDependencies(orgId, installId) {
@@ -443,41 +379,53 @@ let PluginScopeSync = class PluginScopeSync {
443
379
  return false;
444
380
  return !(await this.effective.get(orgId, m.name)).ok;
445
381
  }
446
- /**
447
- * Logs and audits a failed install or uninstall (`plugin.scope_sync_failed`, actor null) and
448
- * records it as the pair's open failure (the super admin's inbox).
449
- */
450
- async failed(orgId, itemId, op, e, attempt) {
451
- attempt.failed = true;
452
- const code = e instanceof ApiError ? e.code : "internal";
453
- const message = e instanceof Error ? e.message : String(e);
454
- this.log.warn("plugin scope sync failed", { orgId, itemId, op, code, err: e });
455
- await this.recordFailure(orgId, itemId, op, code, message);
382
+ failed(orgId, itemId, op, error, attempt) {
383
+ const code = error instanceof ApiError ? error.code : "internal";
384
+ this.log.warn("plugin effect failed", { orgId, itemId, op, code, err: error });
385
+ attempt.failure = { op, code };
456
386
  }
457
- async recordFailure(orgId, itemId, op, code, message) {
458
- // The same failure again (the pair's open one: an org whose connector kind stays unavailable,
459
- // synced by every later owing of the item) refreshes its time without another audit row
460
- const open = await this.db
461
- .selectFrom("plugin_scope_sync_failures")
462
- .select(["op", "code", "message"])
387
+ async settleFailure(itemId, orgId, failure, generation) {
388
+ if (!(await this.orgLock.tryLock(orgId)))
389
+ return;
390
+ if (!(await this.settleGeneration(itemId, orgId, generation)))
391
+ return;
392
+ const { op, code } = failure;
393
+ const error = {
394
+ generation: generation ?? "0",
395
+ operation: op,
396
+ code,
397
+ message: `Plugin setup could not complete the ${op} operation (${code}). Check the plugin's configuration and dependencies.`,
398
+ attemptedAt: new Date().toISOString(),
399
+ };
400
+ const prior = await this.db
401
+ .selectFrom("plugin_installs")
402
+ .select("error")
463
403
  .where("item_id", "=", itemId)
464
404
  .where("org_id", "=", orgId)
465
- .forUpdate()
466
405
  .executeTakeFirst();
467
- if (open?.op !== op || open.code !== code || open.message !== message) {
406
+ if (prior?.error?.operation !== op || prior.error.code !== code) {
468
407
  await audit(this.db, {
469
408
  actorAccountId: null,
470
409
  orgId,
471
410
  action: "plugin.scope_sync_failed",
472
411
  target: itemId,
473
- detail: { via: "scope", op, code, message },
412
+ detail: { via: "scope", op, code, message: error.message },
474
413
  });
475
414
  }
476
- const failure = { op, code, message, failed_at: new Date() };
477
415
  await this.db
478
- .insertInto("plugin_scope_sync_failures")
479
- .values({ item_id: itemId, org_id: orgId, ...failure })
480
- .onConflict((oc) => oc.columns(["item_id", "org_id"]).doUpdateSet(failure))
416
+ .insertInto("plugin_installs")
417
+ .values({
418
+ id: randomUUID(),
419
+ item_id: itemId,
420
+ org_id: orgId,
421
+ version: null,
422
+ installed_by: null,
423
+ status: "install_failed",
424
+ error: JSON.stringify(error),
425
+ })
426
+ .onConflict((oc) => oc
427
+ .columns(["org_id", "item_id"])
428
+ .doUpdateSet({ status: "install_failed", error: JSON.stringify(error) }))
481
429
  .execute();
482
430
  }
483
431
  };
@@ -489,22 +437,27 @@ __decorate([
489
437
  ], PluginScopeSync.prototype, "enqueueOrg", null);
490
438
  __decorate([
491
439
  Transactional()
492
- ], PluginScopeSync.prototype, "fanOut", null);
440
+ ], PluginScopeSync.prototype, "recover", null);
441
+ __decorate([
442
+ Transactional()
443
+ ], PluginScopeSync.prototype, "apply", null);
493
444
  __decorate([
494
- Transactional({ propagation: "requires_new" })
495
- ], PluginScopeSync.prototype, "recordFailure", null);
445
+ Transactional()
446
+ ], PluginScopeSync.prototype, "enqueueDependencyEffects", null);
447
+ __decorate([
448
+ Transactional()
449
+ ], PluginScopeSync.prototype, "settleFailure", null);
496
450
  PluginScopeSync = __decorate([
497
451
  Injectable(),
498
452
  __param(0, Inject(KernelDb)),
499
453
  __param(1, Inject(OutboxService)),
500
454
  __param(2, Inject(PluginInstaller)),
501
- __param(3, Inject(TemplateConnectorEnsurer)),
502
- __param(4, Inject(ExtensionRegistry)),
455
+ __param(3, Inject(ExtensionRegistry)),
456
+ __param(4, Inject(KernelConfigService)),
503
457
  __param(5, Inject(EffectiveConfigs)),
504
- __param(6, Inject(LockService)),
505
- __param(7, Inject(KERNEL_LOGGER)),
506
- __param(8, Inject(TransactionHost)),
507
- __param(9, Optional()),
508
- __param(9, Inject(SCOPE_ORG_CHUNK_SIZE))
458
+ __param(6, Inject(OrgLock)),
459
+ __param(7, Inject(LockService)),
460
+ __param(8, Inject(KERNEL_LOGGER)),
461
+ __param(9, Inject(TransactionHost))
509
462
  ], PluginScopeSync);
510
463
  export { PluginScopeSync };