@capybara-hq/kernel 0.1.0-rc.123 → 0.1.0-rc.124

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/admin.controller.d.ts +2 -2
  3. package/dist/admin/admin.controller.js +1 -1
  4. package/dist/admin/health.service.js +5 -5
  5. package/dist/admin/overview.service.d.ts +2 -2
  6. package/dist/admin/overview.service.js +1 -1
  7. package/dist/agents/agents.module.js +4 -0
  8. package/dist/agents/agents.schemas.js +1 -0
  9. package/dist/agents/models.controller.d.ts +2 -2
  10. package/dist/agents/onboarding-checklist.d.ts +30 -0
  11. package/dist/agents/onboarding-checklist.js +176 -0
  12. package/dist/agents/readiness.controller.d.ts +1 -0
  13. package/dist/agents/readiness.controller.js +12 -2
  14. package/dist/agents/readiness.service.d.ts +5 -2
  15. package/dist/agents/readiness.service.js +14 -3
  16. package/dist/automations/automations.service.js +7 -21
  17. package/dist/automations/events/acceptance.d.ts +2 -0
  18. package/dist/automations/events/acceptance.js +14 -3
  19. package/dist/automations/events/sweep.job.d.ts +3 -36
  20. package/dist/automations/events/sweep.job.js +5 -127
  21. package/dist/automations/fire.d.ts +3 -0
  22. package/dist/automations/fire.js +18 -1
  23. package/dist/automations/grant-rules.d.ts +0 -14
  24. package/dist/automations/grant-rules.js +0 -18
  25. package/dist/automations/scan.job.js +22 -16
  26. package/dist/catalog/catalog.module.d.ts +4 -7
  27. package/dist/catalog/catalog.module.js +4 -10
  28. package/dist/catalog/marketplaces.service.d.ts +1 -1
  29. package/dist/catalog/plugin-import.js +2 -1
  30. package/dist/catalog/plugin-install.d.ts +2 -2
  31. package/dist/catalog/plugin-install.js +2 -2
  32. package/dist/catalog/template-connector-ensure.d.ts +4 -7
  33. package/dist/catalog/template-connector-ensure.js +11 -15
  34. package/dist/channels/supervisor.js +34 -23
  35. package/dist/channels/webhook.d.ts +1 -0
  36. package/dist/channels/webhook.js +10 -5
  37. package/dist/conversations/job-org.d.ts +2 -0
  38. package/dist/conversations/job-org.js +12 -0
  39. package/dist/ctx/create-ctx.js +2 -1
  40. package/dist/db/kernel-schema.d.ts +1 -0
  41. package/dist/dial-in/auth.controller.js +3 -2
  42. package/dist/dial-in/auth.service.js +3 -2
  43. package/dist/dial-in/gateway.d.ts +0 -1
  44. package/dist/dial-in/gateway.js +6 -9
  45. package/dist/extensions/host.d.ts +2 -2
  46. package/dist/extensions/host.js +22 -13
  47. package/dist/extensions/installs.d.ts +1 -0
  48. package/dist/extensions/installs.js +2 -0
  49. package/dist/html/html-document.controller.js +3 -0
  50. package/dist/html/html-document.service.js +2 -0
  51. package/dist/http/plugin-route-access.js +7 -2
  52. package/dist/identity/account-avatar.controller.js +4 -2
  53. package/dist/identity/accounts.js +19 -32
  54. package/dist/identity/api-tokens.d.ts +2 -0
  55. package/dist/identity/api-tokens.js +14 -10
  56. package/dist/identity/audit.js +10 -5
  57. package/dist/identity/binding.d.ts +1 -1
  58. package/dist/identity/binding.js +19 -10
  59. package/dist/lifecycle/kernel-lifecycle.d.ts +1 -8
  60. package/dist/lifecycle/kernel-lifecycle.js +11 -37
  61. package/dist/models/purposes.d.ts +24 -3
  62. package/dist/models/purposes.js +131 -14
  63. package/dist/orgs/directory-sync.js +6 -4
  64. package/dist/orgs/roles.d.ts +1 -1
  65. package/dist/orgs/roles.js +1 -0
  66. package/dist/platform/exclusions.js +5 -0
  67. package/dist/platform/ops/admin.ops.js +1 -1
  68. package/dist/platform/ops/agents.ops.js +1 -1
  69. package/dist/platform/ops/models.ops.js +3 -3
  70. package/dist/push/fanout.d.ts +1 -0
  71. package/dist/push/fanout.js +11 -4
  72. package/dist/push/recipients.d.ts +3 -1
  73. package/dist/push/recipients.js +29 -22
  74. package/dist/runtime/maintenance.d.ts +5 -1
  75. package/dist/runtime/maintenance.js +50 -11
  76. package/dist/runtime/providers.d.ts +12 -9
  77. package/dist/runtime/providers.js +2 -23
  78. package/dist/runtime/run-orphan-check.job.d.ts +1 -0
  79. package/dist/runtime/run-orphan-check.job.js +23 -21
  80. package/dist/runtime/usage-report.d.ts +2 -1
  81. package/dist/runtime/usage-report.js +26 -4
  82. package/dist/sandbox/providers.d.ts +2 -0
  83. package/dist/sandbox/providers.js +2 -0
  84. package/dist/shares/liveness.d.ts +3 -2
  85. package/dist/shares/liveness.js +26 -11
  86. package/dist/shares/share-open.service.js +2 -0
  87. package/dist/skills/usable.d.ts +2 -0
  88. package/dist/skills/usable.js +56 -0
  89. package/dist/tools/builtins/platform.js +17 -12
  90. package/dist/tools/connector-setup.d.ts +5 -1
  91. package/dist/tools/connector-setup.js +14 -0
  92. package/dist/tools/credentials.d.ts +5 -0
  93. package/dist/tools/credentials.js +10 -0
  94. package/dist/tools/oauth/flow.d.ts +1 -0
  95. package/dist/tools/oauth/flow.js +8 -3
  96. package/dist/tools/registry.d.ts +2 -0
  97. package/dist/tools/registry.js +6 -0
  98. package/package.json +3 -3
  99. package/src/migrations/0209_onboarding_checklist.sql +5 -0
  100. package/dist/catalog/template-connector-reconcile.d.ts +0 -44
  101. package/dist/catalog/template-connector-reconcile.js +0 -114
@@ -1,6 +1,7 @@
1
1
  import { ToolError } from "@capybara-hq/plugin-sdk";
2
2
  import { z } from "zod";
3
3
  import { ToolViewSchema } from "../../conversations/events.js";
4
+ import { asPlatform, withOrgScope } from "../../infra/database/org-scope.js";
4
5
  import { availability, PLATFORM_UNAVAILABLE_OFF, } from "../../platform/availability.js";
5
6
  import { errorRoleOf, errorsFor, nextStepFor, OPERATION_ERROR_NEXT, resolveNext, sentence, toToolError, } from "../../platform/errors.js";
6
7
  import { FILE_CHANGED_TEXT, fileCardDetail, } from "../../platform/file-ref.js";
@@ -312,6 +313,13 @@ const factsCtx = (ctx) => ({
312
313
  conversationId: ctx.conversationId,
313
314
  runId: ctx.runId ?? null,
314
315
  });
316
+ /** Called only after the runtime actor is authorized for the operation. */
317
+ function inOperationScope(op, orgId, run) {
318
+ // org-filter: deployment-wide operation restricted to a verified super admin.
319
+ return "superAdmin" in op.authz
320
+ ? asPlatform(`Run verified super admin operation ${op.id}`, run)
321
+ : withOrgScope(orgId, run);
322
+ }
315
323
  export function platformTool(deps) {
316
324
  const spec = {
317
325
  name: BUILTIN.Platform,
@@ -368,7 +376,7 @@ export function platformTool(deps) {
368
376
  const octx = confirmCtx(ctx, role);
369
377
  let personFields;
370
378
  try {
371
- personFields = await personFieldsOf(op, params, octx);
379
+ personFields = await inOperationScope(op, ctx.orgId, () => personFieldsOf(op, params, octx));
372
380
  }
373
381
  catch (e) {
374
382
  if (e instanceof PersonFieldsRefused)
@@ -376,7 +384,7 @@ export function platformTool(deps) {
376
384
  // a target that cannot be read (gone, not allowed) is the write's own error
377
385
  return deny(toToolError(e, (code) => nextStepFor(op.errors, code, role)).message);
378
386
  }
379
- const failed = await precheckOf(op, params, ctx, role, deps.precheckTimeoutMs ?? PRECHECK_TIMEOUT_MS, deps.log);
387
+ const failed = await inOperationScope(op, ctx.orgId, () => precheckOf(op, params, ctx, role, deps.precheckTimeoutMs ?? PRECHECK_TIMEOUT_MS, deps.log));
380
388
  if (failed !== null) {
381
389
  const next = resolveNext(failed.next, role) ?? nextStepFor(op.errors, failed.code, role);
382
390
  return deny(precheckText(op.id, failed.code, failed.message, next));
@@ -401,10 +409,7 @@ export function platformTool(deps) {
401
409
  }),
402
410
  ...(file !== null && { file }),
403
411
  };
404
- const [cls, summary] = await Promise.all([
405
- classOf(op, params, octx),
406
- summaryOf(op, params, sctx),
407
- ]);
412
+ const [cls, summary] = await inOperationScope(op, ctx.orgId, () => Promise.all([classOf(op, params, octx), summaryOf(op, params, sctx)]));
408
413
  return {
409
414
  key,
410
415
  policy: "ask",
@@ -533,7 +538,7 @@ export function platformTool(deps) {
533
538
  throw new ToolError(FILE_CHANGED_TEXT);
534
539
  octx.file = file;
535
540
  }
536
- const person = await personFieldsOf(op, params, octx);
541
+ const person = await inOperationScope(op, ctx.orgId, () => personFieldsOf(op, params, octx));
537
542
  // what the secure input asked (its stored specs) binds what runs: the run-time plan must
538
543
  // ask exactly those fields, and the sealed values must carry exactly them
539
544
  const secureInputId = ctx.secureInputId;
@@ -567,19 +572,19 @@ export function platformTool(deps) {
567
572
  applied = true;
568
573
  // the person who typed the values is the run's trigger account, the secure input's
569
574
  // `requested_for` (a role escalation is refused before any card, R5)
570
- return sealed.consume(secureInputId, ctx.accountId, async (values) => {
571
- // a throw here rolls the row's delete back: nothing is applied
575
+ return withOrgScope(ctx.orgId, () => sealed.consume(secureInputId, ctx.accountId, async (values) => {
576
+ // Throw before applying so the transaction keeps the submitted values.
572
577
  if (!sameSet(Object.keys(values), shown) || !sameSet(asked, shown)) {
573
578
  throw new PersonFieldsChanged();
574
579
  }
575
- const out = await fn(values);
580
+ const out = await inOperationScope(op, ctx.orgId, () => fn(values));
576
581
  entered = Object.keys(values).sort();
577
582
  return out;
578
- });
583
+ }));
579
584
  },
580
585
  };
581
586
  }
582
- result = await op.run(params, octx);
587
+ result = await inOperationScope(op, ctx.orgId, () => op.run(params, octx));
583
588
  }
584
589
  catch (e) {
585
590
  if (e instanceof SealedInputsExpiredError)
@@ -1,4 +1,6 @@
1
- import type { ConnectorAuth, Credentials } from "./credentials.js";
1
+ import { type Expression, type SqlBool } from "kysely";
2
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
+ import { type ConnectorAuth, type Credentials } from "./credentials.js";
2
4
  /**
3
5
  * The org-level input a connector's auth needs (plugin pages spec §5.2.1): `client`, the OAuth
4
6
  * client of the client-credentials flow or of an authorization-code flow with a manually
@@ -16,6 +18,8 @@ export type ConnectorSetup = "ready" | "needs_config";
16
18
  * (apps/web/src/lib/catalog.ts) applies the same rule.
17
19
  */
18
20
  export declare function setupNeed(auth: ConnectorAuth): SetupNeed | undefined;
21
+ /** The SQL form of {@link setupNeed} for existence queries over the connector table. */
22
+ export declare function connectorReady(db: KernelSchemaDb, orgId: string, id: Expression<string>, auth: Expression<unknown>): Expression<SqlBool>;
19
23
  /**
20
24
  * The setup states of several connectors of `orgId` at once (one query, key presence only), by
21
25
  * connector id.
@@ -1,3 +1,5 @@
1
+ import { sql } from "kysely";
2
+ import { connectorCredentialExists } from "./credentials.js";
1
3
  /**
2
4
  * The org input `auth` needs, undefined when it needs none (no auth, a personal credential, or an
3
5
  * authorization-code flow that registers its client itself). The web's `templateNeed`
@@ -12,6 +14,18 @@ export function setupNeed(auth) {
12
14
  }
13
15
  return undefined;
14
16
  }
17
+ /** The SQL form of {@link setupNeed} for existence queries over the connector table. */
18
+ export function connectorReady(db, orgId, id, auth) {
19
+ const type = sql `${auth}->>'type'`;
20
+ return sql `case
21
+ when ${type} = 'oauth_client'
22
+ or (${type} = 'oauth_code' and ${auth}->>'client' = 'manual')
23
+ then ${connectorCredentialExists(db, orgId, id, "client")}
24
+ when ${type} not in ('none', 'oauth_code') and ${auth}->>'ownership' = 'org'
25
+ then ${connectorCredentialExists(db, orgId, id, "org")}
26
+ else true
27
+ end`;
28
+ }
15
29
  /**
16
30
  * The setup states of several connectors of `orgId` at once (one query, key presence only), by
17
31
  * connector id.
@@ -1,5 +1,6 @@
1
1
  import type { AuthInjection } from "@capybara-hq/plugin-sdk";
2
2
  import type { Redis } from "ioredis";
3
+ import { type Expression, type SqlBool } from "kysely";
3
4
  import { type Keyring } from "../ctx/secrets.js";
4
5
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
5
6
  import { ApiError } from "../errors.js";
@@ -78,6 +79,10 @@ export declare class CredentialMissing extends ApiError {
78
79
  readonly ownership: Ownership;
79
80
  constructor(connectorId: string, ownership: Ownership);
80
81
  }
82
+ /** An indexed presence check for a connector credential, without reading its ciphertext. */
83
+ export declare function connectorCredentialExists(db: KernelSchemaDb, orgId: string, connectorId: Expression<string>, entry: "org" | "client" | {
84
+ accountId: string;
85
+ }): Expression<SqlBool>;
81
86
  /**
82
87
  * 删除某账号在该组织所有连接器上的个人凭据(`credentials:app:<connectorId>:user:<accountId>`,含已删除连接器残留的),
83
88
  * 成员离职时在其事务内调用(不解密,不需要密钥环)。返回删除条数。
@@ -60,6 +60,16 @@ const clientKey = (connectorId) => {
60
60
  const ownerOf = (auth, accountId) => auth.type !== "none" && auth.ownership === "personal"
61
61
  ? { kind: "user", accountId }
62
62
  : { kind: "org" };
63
+ /** An indexed presence check for a connector credential, without reading its ciphertext. */
64
+ export function connectorCredentialExists(db, orgId, connectorId, entry) {
65
+ const suffix = typeof entry === "string" ? entry : `user:${entry.accountId}`;
66
+ return sql `exists (${db
67
+ .selectFrom("secrets")
68
+ .select("key")
69
+ .where("namespace", "=", NAMESPACE)
70
+ .where("org_id", "=", orgId)
71
+ .where("key", "=", sql `'credentials:app:' || ${connectorId} || ':' || ${suffix}::text`)})`;
72
+ }
63
73
  const nonEmpty = z.string().min(1);
64
74
  const secretSchemas = {
65
75
  token: z.strictObject({ token: nonEmpty }),
@@ -68,6 +68,7 @@ export declare class OAuthFlow {
68
68
  error?: string | undefined;
69
69
  iss?: string | undefined;
70
70
  }, binding: string | undefined): Promise<string>;
71
+ private completeCallback;
71
72
  /**
72
73
  * In the org row lock: re-checks that the member may still use connectors and the connector
73
74
  * exists, stores the member's tokens with the audit row; true when the connector has no tool
@@ -14,6 +14,7 @@ import { handoffDonePath } from "../../handoff/handoff-paths.js";
14
14
  import { audit } from "../../identity/audit.js";
15
15
  import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
16
16
  import { KernelDb } from "../../infra/database/kernel-db.js";
17
+ import { withOrgScope } from "../../infra/database/org-scope.js";
17
18
  import { TransactionHost } from "../../infra/database/transaction-host.js";
18
19
  import { Transactional } from "../../infra/database/transactional.decorator.js";
19
20
  import { KERNEL_LOGGER, REDIS } from "../../infra/tokens.js";
@@ -189,9 +190,13 @@ let OAuthFlow = class OAuthFlow {
189
190
  if (query.error !== undefined) {
190
191
  return this.fail(query.error === "access_denied" ? "access_denied" : "provider_error", back);
191
192
  }
192
- if (!query.code)
193
+ const code = query.code;
194
+ if (!code)
193
195
  return this.fail("provider_error", back);
194
- const { orgId, connectorId, accountId } = rec;
196
+ return withOrgScope(rec.orgId, () => this.completeCallback(rec, code));
197
+ }
198
+ async completeCallback(rec, code) {
199
+ const { orgId, connectorId, accountId, returnTo: back } = rec;
195
200
  const app = await this.app(orgId, connectorId);
196
201
  const client = app ? await this.credentials.oauthClient(orgId, connectorId) : null;
197
202
  if (!app || !client || app.auth.type !== "oauth_code") {
@@ -201,7 +206,7 @@ let OAuthFlow = class OAuthFlow {
201
206
  try {
202
207
  tokens = await tokenRequest(client, {
203
208
  grant_type: "authorization_code",
204
- code: query.code,
209
+ code,
205
210
  redirect_uri: rec.redirectUri,
206
211
  code_verifier: rec.verifier,
207
212
  resource: client.resource,
@@ -418,6 +418,8 @@ export declare class ToolRegistry {
418
418
  private get builtins();
419
419
  /** `host.list("connector")` 中 `kind` 匹配的第一个实现;未安装返回 undefined。 */
420
420
  findConnector(kind: string): Connector | undefined;
421
+ /** Kinds implemented by currently loaded extensions, without opening a connector session. */
422
+ loadedConnectorKinds(): string[];
421
423
  /** 同 {@link findConnector},未安装时抛错。 */
422
424
  connector(kind: string): Connector;
423
425
  /**
@@ -170,6 +170,12 @@ let ToolRegistry = class ToolRegistry {
170
170
  }
171
171
  return undefined;
172
172
  }
173
+ /** Kinds implemented by currently loaded extensions, without opening a connector session. */
174
+ loadedConnectorKinds() {
175
+ return [
176
+ ...new Set(this.extensions.list("connector").map(({ impl }) => impl.kind)),
177
+ ];
178
+ }
173
179
  /** 同 {@link findConnector},未安装时抛错。 */
174
180
  connector(kind) {
175
181
  const c = this.findConnector(kind);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.123",
3
+ "version": "0.1.0-rc.124",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  "yaml": "^2.9.1",
67
67
  "yauzl": "3.4.0",
68
68
  "zod": "^4.6.7",
69
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.96"
69
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.97"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -75,7 +75,7 @@
75
75
  "@types/ws": "^8.18.2",
76
76
  "@types/yauzl": "3.4.0",
77
77
  "ws": "^8.22.0",
78
- "@capybara-hq/testing": "0.1.0-rc.52"
78
+ "@capybara-hq/testing": "0.1.0-rc.53"
79
79
  },
80
80
  "scripts": {
81
81
  "build": "tsc -b"
@@ -0,0 +1,5 @@
1
+ ALTER TABLE memberships ADD COLUMN IF NOT EXISTS checklist_dismissed boolean NOT NULL DEFAULT false;
2
+
3
+ CREATE INDEX IF NOT EXISTS invitations_pending_org_expiry_idx
4
+ ON invitations (org_id, expires_at)
5
+ WHERE accepted_at IS NULL AND revoked_at IS NULL;
@@ -1,44 +0,0 @@
1
- import { KernelDb } from "../infra/database/kernel-db.js";
2
- import { LockService } from "../infra/lock/lock.service.js";
3
- import type { KernelLogger } from "../log.js";
4
- import { TemplateConnectorEnsurer } from "./template-connector-ensure.js";
5
- /**
6
- * The `deployment_settings` key the reconciliation writes once it ran through: later starts skip
7
- * it (ruling R23).
8
- */
9
- export declare const TEMPLATE_CONNECTOR_RECONCILE_SETTING = "templateConnectorsReconciled";
10
- /**
11
- * The one-off reconciliation of template connectors (plugin pages spec §7 "Plugins waiting
12
- * today"). Installs made before phase 2 left connector templates that are on without a connector,
13
- * because the install asked for input nobody gave. Since phase 2 every install creates them
14
- * (§5.2.2), so this pass creates each one the org never had, once, through
15
- * {@link TemplateConnectorEnsurer} (the same rule and checks as the queued ensure).
16
- *
17
- * It runs once at startup, after the extensions loaded: a template's connector extension must be
18
- * deployed to plan its connector (ruling R22). It runs under the bootstrap step's Redis lock
19
- * `lock:bootstrap`, taken outside any transaction without waiting. A replica that does not get the
20
- * lock skips the pass (ruling R26); the holder or the next start finishes it. Under the lock it
21
- * re-checks the done mark ({@link TEMPLATE_CONNECTOR_RECONCILE_SETTING}).
22
- *
23
- * A template the create's checks refuse (kind off in the org, planning failed) or whose connector
24
- * extension is not loaded here is logged and skipped, and the mark is still written (rulings R23,
25
- * R25); the queued ensure of a later install or extension switch-on creates it. Any other error,
26
- * the shutdown or a lost lock stops the pass without the mark, and the next start resumes it.
27
- */
28
- export declare class TemplateConnectorReconciler {
29
- private readonly kdb;
30
- private readonly locks;
31
- private readonly ensurer;
32
- private readonly log;
33
- constructor(kdb: KernelDb, locks: LockService, ensurer: TemplateConnectorEnsurer, log: KernelLogger);
34
- private get db();
35
- /**
36
- * Runs the reconciliation unless it is done or another replica holds the lock; returns the
37
- * number of connectors it created. `signal` ends the pass (the shutdown).
38
- */
39
- run(signal?: AbortSignal): Promise<{
40
- created: number;
41
- }>;
42
- private done;
43
- private markDone;
44
- }
@@ -1,114 +0,0 @@
1
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- };
7
- var __param = (this && this.__param) || function (paramIndex, decorator) {
8
- return function (target, key) { decorator(target, key, paramIndex); }
9
- };
10
- import { Inject, Injectable } from "@nestjs/common";
11
- import { BOOTSTRAP_LOCK_KEY, BOOTSTRAP_LOCK_TTL_MS } from "../extensions/bootstrap.js";
12
- import { KernelDb } from "../infra/database/kernel-db.js";
13
- import { LockService } from "../infra/lock/lock.service.js";
14
- import { KERNEL_LOGGER } from "../infra/tokens.js";
15
- import { TemplateConnectorEnsurer } from "./template-connector-ensure.js";
16
- /**
17
- * The `deployment_settings` key the reconciliation writes once it ran through: later starts skip
18
- * it (ruling R23).
19
- */
20
- export const TEMPLATE_CONNECTOR_RECONCILE_SETTING = "templateConnectorsReconciled";
21
- /**
22
- * The one-off reconciliation of template connectors (plugin pages spec §7 "Plugins waiting
23
- * today"). Installs made before phase 2 left connector templates that are on without a connector,
24
- * because the install asked for input nobody gave. Since phase 2 every install creates them
25
- * (§5.2.2), so this pass creates each one the org never had, once, through
26
- * {@link TemplateConnectorEnsurer} (the same rule and checks as the queued ensure).
27
- *
28
- * It runs once at startup, after the extensions loaded: a template's connector extension must be
29
- * deployed to plan its connector (ruling R22). It runs under the bootstrap step's Redis lock
30
- * `lock:bootstrap`, taken outside any transaction without waiting. A replica that does not get the
31
- * lock skips the pass (ruling R26); the holder or the next start finishes it. Under the lock it
32
- * re-checks the done mark ({@link TEMPLATE_CONNECTOR_RECONCILE_SETTING}).
33
- *
34
- * A template the create's checks refuse (kind off in the org, planning failed) or whose connector
35
- * extension is not loaded here is logged and skipped, and the mark is still written (rulings R23,
36
- * R25); the queued ensure of a later install or extension switch-on creates it. Any other error,
37
- * the shutdown or a lost lock stops the pass without the mark, and the next start resumes it.
38
- */
39
- let TemplateConnectorReconciler = class TemplateConnectorReconciler {
40
- kdb;
41
- locks;
42
- ensurer;
43
- log;
44
- constructor(kdb, locks, ensurer, log) {
45
- this.kdb = kdb;
46
- this.locks = locks;
47
- this.ensurer = ensurer;
48
- this.log = log;
49
- }
50
- get db() {
51
- return this.kdb.db;
52
- }
53
- /**
54
- * Runs the reconciliation unless it is done or another replica holds the lock; returns the
55
- * number of connectors it created. `signal` ends the pass (the shutdown).
56
- */
57
- async run(signal) {
58
- if (await this.done())
59
- return { created: 0 };
60
- const handle = await this.locks.acquire(BOOTSTRAP_LOCK_KEY, { ttlMs: BOOTSTRAP_LOCK_TTL_MS });
61
- if (!handle) {
62
- this.log.info("template connector reconciliation skipped: another replica holds the lock");
63
- return { created: 0 };
64
- }
65
- try {
66
- // another replica may have finished it before this one got the lock
67
- if (await this.done())
68
- return { created: 0 };
69
- const stop = signal ? AbortSignal.any([signal, handle.lost]) : handle.lost;
70
- let created = 0;
71
- let skipped = 0;
72
- for (const orgId of await this.ensurer.orgsMissing()) {
73
- stop.throwIfAborted();
74
- const r = await this.ensurer.ensureTemplateConnectorsIn(orgId, undefined, {
75
- signal: stop,
76
- via: "reconcile",
77
- });
78
- created += r.created;
79
- skipped += r.skipped + r.notLoaded;
80
- }
81
- stop.throwIfAborted();
82
- await this.markDone();
83
- this.log.info("template connector reconciliation done", { created, skipped });
84
- return { created };
85
- }
86
- finally {
87
- await handle.release();
88
- }
89
- }
90
- async done() {
91
- const row = await this.db
92
- .selectFrom("deployment_settings")
93
- .select("key")
94
- .where("key", "=", TEMPLATE_CONNECTOR_RECONCILE_SETTING)
95
- .executeTakeFirst();
96
- return row !== undefined;
97
- }
98
- async markDone() {
99
- const value = JSON.stringify({ at: new Date().toISOString() });
100
- await this.db
101
- .insertInto("deployment_settings")
102
- .values({ key: TEMPLATE_CONNECTOR_RECONCILE_SETTING, value })
103
- .onConflict((oc) => oc.column("key").doNothing())
104
- .execute();
105
- }
106
- };
107
- TemplateConnectorReconciler = __decorate([
108
- Injectable(),
109
- __param(0, Inject(KernelDb)),
110
- __param(1, Inject(LockService)),
111
- __param(2, Inject(TemplateConnectorEnsurer)),
112
- __param(3, Inject(KERNEL_LOGGER))
113
- ], TemplateConnectorReconciler);
114
- export { TemplateConnectorReconciler };