@capybara-hq/kernel 0.1.0-rc.137 → 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 (99) hide show
  1. package/dist/admin/extensions.controller.d.ts +5 -2
  2. package/dist/admin/extensions.controller.js +10 -1
  3. package/dist/admin/extensions.schemas.d.ts +4 -0
  4. package/dist/admin/extensions.schemas.js +9 -0
  5. package/dist/admin/health.service.d.ts +1 -1
  6. package/dist/admin/health.service.js +3 -3
  7. package/dist/catalog/catalog-content.d.ts +5 -7
  8. package/dist/catalog/catalog-items.js +1 -1
  9. package/dist/catalog/catalog-scope.service.js +5 -5
  10. package/dist/catalog/catalog.module.js +5 -4
  11. package/dist/catalog/catalog.service.d.ts +7 -1
  12. package/dist/catalog/catalog.service.js +19 -2
  13. package/dist/catalog/effect-work.d.ts +27 -0
  14. package/dist/catalog/effect-work.js +151 -0
  15. package/dist/catalog/jobs.d.ts +4 -1
  16. package/dist/catalog/jobs.js +14 -4
  17. package/dist/catalog/org-catalog.service.d.ts +2 -0
  18. package/dist/catalog/org-catalog.service.js +68 -12
  19. package/dist/catalog/org-intent.d.ts +4 -2
  20. package/dist/catalog/org-intent.js +25 -4
  21. package/dist/catalog/owned-items.d.ts +5 -1
  22. package/dist/catalog/owned-items.js +18 -3
  23. package/dist/catalog/plugin-import.d.ts +4 -2
  24. package/dist/catalog/plugin-import.js +10 -5
  25. package/dist/catalog/plugin-install.d.ts +17 -51
  26. package/dist/catalog/plugin-install.js +209 -235
  27. package/dist/catalog/plugin-upgrade.d.ts +8 -3
  28. package/dist/catalog/plugin-upgrade.js +63 -34
  29. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  30. package/dist/catalog/scope-sync-workers.js +10 -26
  31. package/dist/catalog/scope-sync.d.ts +19 -114
  32. package/dist/catalog/scope-sync.js +220 -239
  33. package/dist/catalog/scope-writer.d.ts +10 -1
  34. package/dist/catalog/scope-writer.js +62 -4
  35. package/dist/catalog/template-connector-ensure.js +1 -1
  36. package/dist/catalog/unshare.js +1 -2
  37. package/dist/config/schema.d.ts +1 -1
  38. package/dist/config/schema.js +7 -4
  39. package/dist/db/kernel-schema.d.ts +21 -5
  40. package/dist/erasure/org-catalog.js +2 -2
  41. package/dist/erasure/org-rules.js +2 -0
  42. package/dist/extensions/admin-ops.d.ts +1 -1
  43. package/dist/extensions/admin-ops.js +1 -1
  44. package/dist/extensions/admin-view.d.ts +4 -1
  45. package/dist/extensions/admin-view.js +27 -11
  46. package/dist/extensions/bootstrap.d.ts +1 -1
  47. package/dist/extensions/bootstrap.js +2 -3
  48. package/dist/extensions/enabled.d.ts +160 -0
  49. package/dist/extensions/enabled.js +7 -0
  50. package/dist/extensions/host.d.ts +1 -0
  51. package/dist/extensions/host.js +5 -2
  52. package/dist/extensions/isolated/authorization.d.ts +8 -0
  53. package/dist/extensions/isolated/authorization.js +56 -11
  54. package/dist/extensions/isolated/broker.js +30 -11
  55. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  56. package/dist/extensions/isolated/engine-binds.js +82 -0
  57. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  58. package/dist/extensions/isolated/engine-policy.js +75 -0
  59. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  60. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  61. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  62. package/dist/extensions/isolated/engine-proxy.js +408 -0
  63. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  64. package/dist/extensions/isolated/engine-vaults.js +93 -0
  65. package/dist/extensions/isolated/lanes.d.ts +11 -3
  66. package/dist/extensions/isolated/lanes.js +43 -16
  67. package/dist/extensions/isolated/postgres-gate.d.ts +1 -0
  68. package/dist/extensions/isolated/postgres-gate.js +6 -6
  69. package/dist/extensions/isolated/revision.d.ts +1 -1
  70. package/dist/extensions/isolated/revision.js +3 -2
  71. package/dist/extensions/isolated/sandbox.d.ts +10 -6
  72. package/dist/extensions/isolated/sandbox.js +101 -117
  73. package/dist/extensions/lifecycle-topics.d.ts +1 -0
  74. package/dist/extensions/lifecycle-topics.js +1 -0
  75. package/dist/extensions/lifecycle.js +23 -2
  76. package/dist/extensions/permission-view.d.ts +6 -1
  77. package/dist/inbox/platform-inbox.service.js +16 -27
  78. package/dist/infra/events/kernel-events.d.ts +4 -0
  79. package/dist/infra/outbox/registry.d.ts +3 -36
  80. package/dist/infra/outbox/registry.js +4 -49
  81. package/dist/infra/queue/queue-names.d.ts +1 -1
  82. package/dist/infra/queue/queue-names.js +1 -1
  83. package/dist/orgs/org-lock.d.ts +3 -1
  84. package/dist/orgs/org-lock.js +3 -1
  85. package/dist/orgs/orgs.service.d.ts +3 -1
  86. package/dist/orgs/orgs.service.js +15 -8
  87. package/dist/overrides.d.ts +0 -3
  88. package/dist/overrides.js +0 -2
  89. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  90. package/dist/platform/ops/org-plugins.ops.js +5 -2
  91. package/dist/platform/ops/plugins.ops.js +11 -10
  92. package/dist/tools/registry.d.ts +1 -1
  93. package/dist/tools/registry.js +6 -2
  94. package/package.json +2 -2
  95. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  96. package/dist/catalog/install-status.d.ts +0 -5
  97. package/dist/catalog/install-status.js +0 -5
  98. package/dist/catalog/scope-jobs.d.ts +0 -59
  99. 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,200 +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 { oweScopeItem, PLUGIN_SCOPE_QUEUE, SCOPE_CHUNK_JOB, SCOPE_ORG_CHUNK, SCOPE_ORG_CHUNK_SIZE, SCOPE_ORG_JOB, scopeChunkJobId, scopeOrgJobId, } from "./scope-jobs.js";
26
30
  import { pluginEffectsWanted, ScopeNoLongerWanted, ScopeStillWanted, wantedByScope, } from "./scope-state.js";
27
- import { TemplateConnectorEnsurer } from "./template-connector-ensure.js";
28
- /**
29
- * The plugin scope sync (plugin and component management spec §5, phase 1): converges every org
30
- * to each platform plugin's scope. In phase 1 "on in an org" is the org's plugin install, so for
31
- * each (item, org) the sync:
32
- * - wanted on (`wantedOn`, or a live install in the org depends on it: rule 9) and no live install
33
- * -> installs it as the kernel itself (actor null, audits `via: "scope"`). An install asks for
34
- * no input (plugin pages spec §5.2.2): its connector templates become connectors, those lacking
35
- * an org credential or OAuth client `needs_config`, and an extension whose effective config is
36
- * not valid in the org is switched on all the same (it gets no call until it is, and the org
37
- * catalog shows the plugin `needs_config`);
38
- * - wanted off and a live install -> uninstalls it (`via: "scope"`; the person who changed the
39
- * scope or the switch confirmed the preview); the connectors the install created stay as the
40
- * org's own (spec §5 rule 8); a dependency install it took along that its own scope still wants
41
- * on stays as a standalone install (the installer's rule), the others are synced again.
42
- * The decision is made outside the org row lock; the installer re-checks the scope under it for a
43
- * `via: "scope"` install or uninstall, so a person's switch committed meanwhile wins.
44
- * The sync writes no switch row: those record people's choices, and `wantedOn` honours them for
45
- * every scope (an org that switched an `all` item off stays off, also across a scope change away
46
- * and back, layering spec §4). Builtin items are left alone: they are on everywhere without an org
47
- * install, and their extension is enabled in every org by `enabled.ts` (required or not). A
48
- * failed install, uninstall or dependency install is logged, audited `plugin.scope_sync_failed`
49
- * (once while the same failure stays open), kept as the pair's open failure
50
- * (`plugin_scope_sync_failures`, the super admin's inbox, until a later sync of the pair does not
51
- * fail) and not retried until the next sync of the item (syncs follow owing transactions, never a
52
- * timer). An error outside those steps (a read, the failure write itself) ends the attempt
53
- * without touching the pair's row, so an older failure stays open.
54
- *
55
- * Jobs (queue {@link PLUGIN_SCOPE_QUEUE}), all owed through the outbox (transactional outbox spec
56
- * §8.1), so none is lost:
57
- * - `scope-item` (`scope-item-<itemId>-x<xact>`, one per owing transaction): owed by every
58
- * transaction that changes what the item's sync converges to: its scope, disabled flag, list,
59
- * owner or platform version, an import's commit that deploys no extension, and the deploy of its
60
- * extension (`oweDeployedExtensionSync`: enabled, a new version of an enabled one, permissions
61
- * approved). It fans out: one `scope-item-chunk` per chunk of orgs (`<item job id>-c<n>`, at
62
- * most {@link SCOPE_ORG_CHUNK} orgs each), all owed in one transaction;
63
- * - `scope-item-chunk`: converges the item in its orgs;
64
- * - `scope-org` (`scope-org-<orgId>`): every item in one org, owed by the org's creation.
65
- * A migration that changes a scope inserts its outbox rows itself. One BullMQ retry policy
66
- * (registry): a chunk or org job whose extension is enabled on the deployment but not loaded on
67
- * this replica yet fails after converging its other pairs, so BullMQ retries it with its backoff
68
- * (on any replica); its last attempt installs anyway and records what fails. Pairs of one org are
69
- * serialized across replicas by a Redis lock per org; the installer's org row lock and its
70
- * one-live-install rule are the backstop.
71
- */
72
- 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";
73
- /**
74
- * A chunk or org job with a pair whose extension this replica has not loaded yet (P3-38): thrown
75
- * after its other pairs converged, so BullMQ retries the job with its backoff.
76
- */
77
- export class ScopeSyncDeferred extends Error {
78
- itemIds;
79
- constructor(itemIds) {
80
- 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`);
81
- this.itemIds = itemIds;
82
- this.name = "ScopeSyncDeferred";
83
- }
31
+ import { oweTemplateConnectors } from "./template-connector-jobs.js";
32
+ class SupersededEffect extends Error {
33
+ }
34
+ class FailedEffect extends Error {
84
35
  }
85
36
  /** How long one org's pairs wait for each other (an install can take a while). */
86
37
  const ORG_LOCK_TTL_MS = 60_000;
87
38
  const ORG_LOCK_WAIT_MS = 10 * 60_000;
88
- /** 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. */
89
40
  export const PLUGIN_SCOPE_CONCURRENCY = 2;
90
- /** `ids` in chunks of `size` (the last one shorter). */
91
- export function chunked(ids, size) {
92
- if (!Number.isInteger(size) || size < 1)
93
- throw new Error(`invalid chunk size ${size}`);
94
- const out = [];
95
- for (let i = 0; i < ids.length; i += size)
96
- out.push(ids.slice(i, i + size));
97
- return out;
98
- }
41
+ export { PLUGIN_EFFECT_QUEUE } from "./effect-work.js";
99
42
  let PluginScopeSync = class PluginScopeSync {
100
43
  kdb;
101
44
  outbox;
102
45
  installer;
103
- templateConnectors;
104
46
  registry;
47
+ config;
105
48
  effective;
49
+ orgLock;
106
50
  locks;
107
51
  log;
108
52
  txHost;
109
- chunkSize;
110
- constructor(kdb, outbox, installer, templateConnectors, registry, effective, locks, log, txHost,
111
- /** Orgs per chunk job (a test seam; default {@link SCOPE_ORG_CHUNK}). */
112
- chunkSize = SCOPE_ORG_CHUNK) {
53
+ constructor(kdb, outbox, installer, registry, config, effective, orgLock, locks, log, txHost) {
113
54
  this.kdb = kdb;
114
55
  this.outbox = outbox;
115
56
  this.installer = installer;
116
- this.templateConnectors = templateConnectors;
117
57
  this.registry = registry;
58
+ this.config = config;
118
59
  this.effective = effective;
60
+ this.orgLock = orgLock;
119
61
  this.locks = locks;
120
62
  this.log = log;
121
63
  this.txHost = txHost;
122
- this.chunkSize = chunkSize;
123
64
  }
124
65
  get db() {
125
66
  return this.kdb.db;
126
67
  }
127
- /**
128
- * Owes the sync of an item in every org in the transaction in context (one job per
129
- * transaction), the transaction that changes what it converges to.
130
- */
131
- async enqueueItem(itemId) {
132
- await oweScopeItem(this.outbox, this.db, itemId);
68
+ async enqueueItem(itemId, previousOrgs = []) {
69
+ await oweEffectWork(this.outbox, this.db, { itemIds: [itemId], previousOrgs });
133
70
  }
134
- /** Owes the sync of every item in an org, in the transaction that creates the org. */
135
71
  async enqueueOrg(orgId) {
136
- await this.outbox.add({
137
- queue: PLUGIN_SCOPE_QUEUE,
138
- name: SCOPE_ORG_JOB,
139
- jobId: scopeOrgJobId(orgId),
140
- data: { kind: "org", orgId },
141
- orgId,
142
- });
72
+ await oweEffectWork(this.outbox, this.db, { orgId });
143
73
  }
144
- /**
145
- * One job: an item job fans out to its chunk jobs; a chunk job converges the item in its orgs,
146
- * an org job every item in the org. A pair deferred because its extension is not loaded here
147
- * fails the job after the others ({@link ScopeSyncDeferred}), unless this is its last attempt.
148
- */
149
- async process(data, run) {
150
- if (data.kind === "item") {
151
- await this.fanOut(data.itemId, run.jobId);
152
- return;
153
- }
154
- const pairs = data.kind === "chunk"
155
- ? data.orgIds.map((orgId) => [data.itemId, orgId])
156
- : (await this.db
157
- .selectFrom("catalog_items")
158
- .select("id")
159
- .where("deleted_at", "is", null)
160
- .where("builtin", "=", false)
161
- .orderBy("id")
162
- .execute()).map((i) => [i.id, data.orgId]);
163
- const deferred = new Set();
164
- for (const [itemId, orgId] of pairs) {
165
- // Stopped between pairs: failed, so BullMQ retries the job (on this or another replica).
166
- // On the job's last attempt nothing retries it: the pairs not reached yet are dropped
167
- // until the next sync of the item or org (a scope change, a deploy, a new org) owes them
168
- if (run.signal?.aborted)
169
- throw new Error("the plugin scope worker stopped; the job is retried");
170
- try {
171
- const r = await this.syncPair(itemId, orgId, run.signal, { finalTry: run.finalAttempt });
172
- if (r === "deferred")
173
- deferred.add(itemId);
174
- }
175
- catch (err) {
176
- this.log.warn("plugin scope sync of a pair failed", { itemId, orgId, err });
177
- }
178
- }
179
- if (deferred.size > 0)
180
- throw new ScopeSyncDeferred([...deferred]);
74
+ async recover() {
75
+ await recoverEffectWork(this.outbox, this.db);
181
76
  }
182
- /**
183
- * Owes one chunk job per {@link chunkSize} live orgs of the item job `jobId`, in one
184
- * transaction (a redelivered item job owes the same ids again: deduped).
185
- */
186
- async fanOut(itemId, jobId) {
187
- const item = await this.db
188
- .selectFrom("catalog_items")
189
- .select("id")
190
- .where("id", "=", itemId)
191
- .where("deleted_at", "is", null)
192
- .executeTakeFirst();
193
- if (!item)
194
- return;
195
- const orgs = await this.db
196
- .selectFrom("orgs")
197
- .select("id")
198
- .where("deleted_at", "is", null)
199
- .orderBy("id")
200
- .execute();
201
- const chunks = chunked(orgs.map((o) => o.id), this.chunkSize);
202
- await this.outbox.addMany(chunks.map((orgIds, n) => ({
203
- queue: PLUGIN_SCOPE_QUEUE,
204
- name: SCOPE_CHUNK_JOB,
205
- jobId: scopeChunkJobId(jobId, n),
206
- data: { kind: "chunk", itemId, orgIds },
207
- })));
77
+ async process(data, jobId, signal) {
78
+ const generation = effectGeneration(jobId, data);
79
+ await this.syncPair(data.itemId, data.orgIds[0], signal, generation);
208
80
  }
209
- /**
210
- * Whether the install of the item's `version` may go ahead on this replica (P3-38): its
211
- * extension is loaded here, or it is not enabled on the deployment (the install reports
212
- * `catalog.not_deployed` as before). Enabled but not loaded here (its deploy owed this sync, and
213
- * this replica's reconcile has not caught up yet) -> false, unless this is the job's last try.
214
- */
215
- 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) {
216
83
  const v = await this.db
217
84
  .selectFrom("catalog_item_versions")
218
85
  .select("manifest")
@@ -222,42 +89,140 @@ let PluginScopeSync = class PluginScopeSync {
222
89
  const m = v?.manifest;
223
90
  if (!m?.extension)
224
91
  return true;
225
- 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))
226
94
  return true;
227
95
  const install = await this.db
228
96
  .selectFrom("extension_installs")
229
- .select("desired_state")
97
+ .select(["desired_state", "sha256"])
230
98
  .where("name", "=", m.name)
231
99
  .executeTakeFirst();
232
- 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.`);
233
124
  }
234
125
  /** Converges one (item, org), under the org's sync lock; `signal` ends the wait for it. */
235
- syncPair(itemId, orgId, signal, opts = {}) {
126
+ syncPair(itemId, orgId, signal, generation) {
236
127
  return this.locks.run(`plugin-scope-org-${orgId}`, {
237
128
  ttlMs: ORG_LOCK_TTL_MS,
238
129
  waitMs: ORG_LOCK_WAIT_MS,
239
130
  ...(signal !== undefined && { signal }),
240
- }, () => 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
+ }));
241
149
  }
242
- /**
243
- * {@link syncLocked} plus the pair's open failure (`plugin_scope_sync_failures`, the super
244
- * admin's inbox): an attempt that failed records it, any other attempt clears it. An attempt
245
- * that throws (outside the recorded steps) leaves the row as it was.
246
- */
247
- async syncRecorded(itemId, orgId, finalTry = false) {
248
- const attempt = { failed: false, finalTry };
249
- const result = await this.syncLocked(itemId, orgId, attempt);
250
- // a deferred pair changed nothing: an older failure stays open
251
- 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) {
252
177
  await this.db
253
- .deleteFrom("plugin_scope_sync_failures")
178
+ .deleteFrom("plugin_installs")
254
179
  .where("item_id", "=", itemId)
255
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"))))
256
186
  .execute();
257
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();
258
199
  return result;
259
200
  }
260
- 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) {
261
226
  const item = await this.db
262
227
  .selectFrom("catalog_items")
263
228
  .select([
@@ -270,7 +235,6 @@ let PluginScopeSync = class PluginScopeSync {
270
235
  "platform_synced_version",
271
236
  ])
272
237
  .where("id", "=", itemId)
273
- .where("deleted_at", "is", null)
274
238
  .executeTakeFirst();
275
239
  const org = await this.db
276
240
  .selectFrom("orgs")
@@ -282,29 +246,24 @@ let PluginScopeSync = class PluginScopeSync {
282
246
  return "unchanged";
283
247
  const live = await this.db
284
248
  .selectFrom("plugin_installs")
285
- .select(["id", "status"])
249
+ .select(["id", "version"])
286
250
  .where("org_id", "=", orgId)
287
251
  .where("item_id", "=", itemId)
288
- .where("status", "in", [...LIVE_INSTALL_STATUSES])
289
252
  .executeTakeFirst();
290
253
  const wanted = await pluginEffectsWanted(this.db, orgId, itemId);
291
254
  if (wanted) {
292
- if (live) {
255
+ if (live?.version != null) {
293
256
  // A platform update may have added dependencies: installed here (rule 9, Task 7)
294
- if (live.status === "installed") {
295
- try {
296
- // a dependency just installed may provide the connector kind of a template the org
297
- // never got a connector from (ruling R27); nothing installed, nothing new to provide
298
- if ((await this.installer.addMissingDependencies(orgId, live.id)) > 0) {
299
- await this.templateConnectors.ensureTemplateConnectorsIn(orgId, undefined, {
300
- via: "scope",
301
- });
302
- }
303
- }
304
- catch (e) {
305
- 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);
306
262
  }
307
263
  }
264
+ catch (e) {
265
+ this.failed(orgId, itemId, "dependencies", e, attempt);
266
+ }
308
267
  return "unchanged";
309
268
  }
310
269
  // A dependency-only install is owned and recorded by the enabling root's effects.
@@ -313,10 +272,11 @@ let PluginScopeSync = class PluginScopeSync {
313
272
  // The platform's version (one per deployment, Task 7); the latest import before the first sync
314
273
  const version = item.platform_synced_version ?? item.latest_version;
315
274
  try {
316
- if (!(await this.extensionReady(itemId, version, attempt.finalTry)))
275
+ if (!(await this.extensionReady(itemId, orgId, version, generation)))
317
276
  return "deferred";
318
- await this.installer.install(orgId, null, itemId, version, {}, { via: "scope" });
319
- 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";
320
280
  }
321
281
  catch (e) {
322
282
  // A person switched it off (or the scope changed) after this decision: the installer's
@@ -328,13 +288,12 @@ let PluginScopeSync = class PluginScopeSync {
328
288
  (e.code === "plugin.already_installed" || e.code === "plugin.install_in_progress")) {
329
289
  return "unchanged";
330
290
  }
331
- await this.failed(orgId, itemId, "install", e, attempt);
291
+ this.failed(orgId, itemId, "install", e, attempt);
332
292
  return "unchanged";
333
293
  }
334
294
  }
335
- // Wanted off: only a settled install is removed (one still installing waits for the next
336
- // enqueue)
337
- if (live?.status !== "installed")
295
+ // Off intent removes applied ownership or the journal of an interrupted legacy attempt.
296
+ if (!live)
338
297
  return "unchanged";
339
298
  const deps = await this.createdDependencies(orgId, live.id);
340
299
  try {
@@ -345,16 +304,21 @@ let PluginScopeSync = class PluginScopeSync {
345
304
  // after this decision: the installer's re-check under the org row lock refused it
346
305
  if (e instanceof ScopeStillWanted)
347
306
  return "unchanged";
348
- await this.failed(orgId, itemId, "uninstall", e, attempt);
307
+ this.failed(orgId, itemId, "uninstall", e, attempt);
349
308
  return "unchanged";
350
309
  }
351
310
  // Dependency installs it took along may be wanted on by their own scope: synced again
352
- for (const dep of deps) {
353
- if (dep !== itemId)
354
- await this.syncRecorded(dep, orgId);
355
- }
311
+ await this.enqueueDependencyEffects(deps.filter((dep) => dep !== itemId), orgId);
356
312
  return "removed";
357
313
  }
314
+ async enqueueDependencyEffects(itemIds, orgId) {
315
+ await oweEffectWork(this.outbox, this.db, {
316
+ itemIds,
317
+ orgId,
318
+ previousOrgs: [orgId],
319
+ includeDependents: false,
320
+ });
321
+ }
358
322
  /** The items of the dependency installs this install (of `orgId`) created. */
359
323
  async createdDependencies(orgId, installId) {
360
324
  // `ref` is text: the child install ids are read first, then their items
@@ -415,41 +379,53 @@ let PluginScopeSync = class PluginScopeSync {
415
379
  return false;
416
380
  return !(await this.effective.get(orgId, m.name)).ok;
417
381
  }
418
- /**
419
- * Logs and audits a failed install or uninstall (`plugin.scope_sync_failed`, actor null) and
420
- * records it as the pair's open failure (the super admin's inbox).
421
- */
422
- async failed(orgId, itemId, op, e, attempt) {
423
- attempt.failed = true;
424
- const code = e instanceof ApiError ? e.code : "internal";
425
- const message = e instanceof Error ? e.message : String(e);
426
- this.log.warn("plugin scope sync failed", { orgId, itemId, op, code, err: e });
427
- 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 };
428
386
  }
429
- async recordFailure(orgId, itemId, op, code, message) {
430
- // The same failure again (the pair's open one: an org whose connector kind stays unavailable,
431
- // synced by every later owing of the item) refreshes its time without another audit row
432
- const open = await this.db
433
- .selectFrom("plugin_scope_sync_failures")
434
- .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")
435
403
  .where("item_id", "=", itemId)
436
404
  .where("org_id", "=", orgId)
437
- .forUpdate()
438
405
  .executeTakeFirst();
439
- if (open?.op !== op || open.code !== code || open.message !== message) {
406
+ if (prior?.error?.operation !== op || prior.error.code !== code) {
440
407
  await audit(this.db, {
441
408
  actorAccountId: null,
442
409
  orgId,
443
410
  action: "plugin.scope_sync_failed",
444
411
  target: itemId,
445
- detail: { via: "scope", op, code, message },
412
+ detail: { via: "scope", op, code, message: error.message },
446
413
  });
447
414
  }
448
- const failure = { op, code, message, failed_at: new Date() };
449
415
  await this.db
450
- .insertInto("plugin_scope_sync_failures")
451
- .values({ item_id: itemId, org_id: orgId, ...failure })
452
- .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) }))
453
429
  .execute();
454
430
  }
455
431
  };
@@ -461,22 +437,27 @@ __decorate([
461
437
  ], PluginScopeSync.prototype, "enqueueOrg", null);
462
438
  __decorate([
463
439
  Transactional()
464
- ], PluginScopeSync.prototype, "fanOut", null);
440
+ ], PluginScopeSync.prototype, "recover", null);
465
441
  __decorate([
466
- Transactional({ propagation: "requires_new" })
467
- ], PluginScopeSync.prototype, "recordFailure", null);
442
+ Transactional()
443
+ ], PluginScopeSync.prototype, "apply", null);
444
+ __decorate([
445
+ Transactional()
446
+ ], PluginScopeSync.prototype, "enqueueDependencyEffects", null);
447
+ __decorate([
448
+ Transactional()
449
+ ], PluginScopeSync.prototype, "settleFailure", null);
468
450
  PluginScopeSync = __decorate([
469
451
  Injectable(),
470
452
  __param(0, Inject(KernelDb)),
471
453
  __param(1, Inject(OutboxService)),
472
454
  __param(2, Inject(PluginInstaller)),
473
- __param(3, Inject(TemplateConnectorEnsurer)),
474
- __param(4, Inject(ExtensionRegistry)),
455
+ __param(3, Inject(ExtensionRegistry)),
456
+ __param(4, Inject(KernelConfigService)),
475
457
  __param(5, Inject(EffectiveConfigs)),
476
- __param(6, Inject(LockService)),
477
- __param(7, Inject(KERNEL_LOGGER)),
478
- __param(8, Inject(TransactionHost)),
479
- __param(9, Optional()),
480
- __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))
481
462
  ], PluginScopeSync);
482
463
  export { PluginScopeSync };
@@ -4,6 +4,9 @@ import { PluginInstallLock } from "../extensions/locks.js";
4
4
  import { SuperAdminLock } from "../identity/super-admin.js";
5
5
  import { KernelDb } from "../infra/database/kernel-db.js";
6
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
7
+ import { XactLock } from "../infra/database/xact-lock.js";
8
+ import { KernelEvents } from "../infra/events/kernel-events.js";
9
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
7
10
  import type { ComponentKind } from "./component-state.js";
8
11
  import type { PluginScope } from "./scope.js";
9
12
  export declare const COMPONENT_SCOPE_TABLE: {
@@ -64,9 +67,12 @@ export declare function assertScopePreview<Conflict>(confirmation: ScopeConfirma
64
67
  export declare class ScopeWriter {
65
68
  private readonly kdb;
66
69
  private readonly installLock;
70
+ private readonly xactLock;
71
+ private readonly outbox;
67
72
  private readonly adminLock;
68
73
  readonly txHost: TransactionHost;
69
- constructor(kdb: KernelDb, installLock: PluginInstallLock, adminLock: SuperAdminLock, txHost: TransactionHost);
74
+ private readonly events;
75
+ constructor(kdb: KernelDb, installLock: PluginInstallLock, xactLock: XactLock, outbox: OutboxService, adminLock: SuperAdminLock, txHost: TransactionHost, events: KernelEvents);
70
76
  platformChange<Result, Conflict>(actor: string, confirmation: ScopeConfirmation, prepare: () => Promise<PreparedScopeWrite<Result, Conflict> | undefined>): Promise<Result | undefined>;
71
77
  /** Persist the scope and its named list together after platform confirmation. */
72
78
  replaceScope(change: ScopeListChange): Promise<void>;
@@ -74,5 +80,8 @@ export declare class ScopeWriter {
74
80
  setDisabled(subject: ScopeSubject, disabled: boolean): Promise<void>;
75
81
  /** Store local intent under the caller's transaction and org lock. */
76
82
  setOrgSwitch(subject: ScopeSubject, orgId: string, enabled: boolean, actor: string | null): Promise<void>;
83
+ private oweConnectorTemplate;
84
+ /** Catalog switches can change the intent of extensions brought in through a dependency. */
85
+ refreshIsolatedOrgIntent(orgId?: string): void;
77
86
  }
78
87
  export {};