@capybara-hq/kernel 0.1.0-rc.142 → 0.1.0-rc.144
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.
- package/dist/admin/admin-agents.controller.d.ts +3 -5
- package/dist/admin/admin-agents.controller.js +1 -1
- package/dist/admin/admin-connectors.controller.d.ts +3 -5
- package/dist/admin/admin-connectors.controller.js +1 -1
- package/dist/admin/admin-items.schemas.d.ts +6 -6
- package/dist/admin/admin-items.schemas.js +5 -9
- package/dist/admin/admin.controller.d.ts +18 -12
- package/dist/admin/admin.controller.js +29 -15
- package/dist/admin/admin.schemas.d.ts +12 -3
- package/dist/admin/admin.schemas.js +17 -6
- package/dist/agents/admin-agents.d.ts +10 -8
- package/dist/agents/admin-agents.js +13 -9
- package/dist/agents/agents.module.js +3 -0
- package/dist/agents/agents.service.js +1 -1
- package/dist/agents/org-templates.d.ts +3 -1
- package/dist/agents/org-templates.js +7 -3
- package/dist/agents/pending-connector-requests.d.ts +10 -4
- package/dist/agents/pending-connector-requests.js +29 -7
- package/dist/automations/automations.controller.d.ts +9 -5
- package/dist/automations/automations.controller.js +21 -4
- package/dist/automations/automations.schemas.d.ts +19 -0
- package/dist/automations/automations.schemas.js +9 -0
- package/dist/automations/automations.service.d.ts +25 -8
- package/dist/automations/automations.service.js +40 -34
- package/dist/automations/events/acceptance.d.ts +6 -1
- package/dist/automations/events/acceptance.js +30 -11
- package/dist/automations/store.d.ts +17 -0
- package/dist/automations/store.js +35 -0
- package/dist/catalog/admin-catalog.controller.d.ts +64 -2
- package/dist/catalog/admin-catalog.controller.js +17 -0
- package/dist/catalog/catalog-import.module.js +3 -0
- package/dist/catalog/catalog-scope.service.d.ts +3 -1
- package/dist/catalog/catalog-scope.service.js +11 -7
- package/dist/catalog/catalog.module.js +3 -0
- package/dist/catalog/catalog.service.d.ts +3 -1
- package/dist/catalog/catalog.service.js +8 -4
- package/dist/catalog/cli.js +2 -2
- package/dist/catalog/component-promotion.d.ts +3 -1
- package/dist/catalog/component-promotion.js +7 -3
- package/dist/catalog/component-scope.service.d.ts +3 -1
- package/dist/catalog/component-scope.service.js +7 -3
- package/dist/catalog/enable-requests.d.ts +10 -8
- package/dist/catalog/enable-requests.js +40 -21
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/catalog/owned-items.d.ts +3 -1
- package/dist/catalog/owned-items.js +13 -9
- package/dist/catalog/platform-components.d.ts +6 -1
- package/dist/catalog/platform-components.js +9 -3
- package/dist/catalog/plugin-connectors.d.ts +8 -4
- package/dist/catalog/plugin-connectors.js +12 -6
- package/dist/catalog/plugin-import.d.ts +3 -1
- package/dist/catalog/plugin-import.js +14 -5
- package/dist/catalog/plugin-install.d.ts +3 -1
- package/dist/catalog/plugin-install.js +8 -4
- package/dist/catalog/plugin-package.js +2 -1
- package/dist/catalog/plugin-upgrade.d.ts +3 -1
- package/dist/catalog/plugin-upgrade.js +8 -4
- package/dist/catalog/request-hints.d.ts +19 -0
- package/dist/catalog/request-hints.js +34 -0
- package/dist/catalog/request-rules.d.ts +9 -5
- package/dist/catalog/request-rules.js +16 -9
- package/dist/catalog/requests.service.d.ts +3 -1
- package/dist/catalog/requests.service.js +28 -9
- package/dist/catalog/scope-orgs.d.ts +2 -1
- package/dist/catalog/scope-orgs.js +2 -2
- package/dist/catalog/scope-sync.d.ts +3 -1
- package/dist/catalog/scope-sync.js +12 -2
- package/dist/catalog/scope-writer.d.ts +6 -3
- package/dist/catalog/scope-writer.js +28 -10
- package/dist/catalog/unshare.d.ts +3 -2
- package/dist/catalog/unshare.js +4 -4
- package/dist/client/client-access.service.js +29 -1
- package/dist/config/schema.d.ts +12 -0
- package/dist/config/schema.js +56 -0
- package/dist/ctx/create-ctx.d.ts +2 -19
- package/dist/ctx/create-ctx.js +3 -93
- package/dist/ctx/durable-relay.d.ts +2 -5
- package/dist/ctx/durable-relay.js +56 -29
- package/dist/db/extension-handoff-schema.js +5 -0
- package/dist/db/kernel-schema.d.ts +74 -0
- package/dist/db/migrator.js +36 -0
- package/dist/erasure/account-batches.js +2 -0
- package/dist/erasure/account-residual.js +1 -0
- package/dist/erasure/org-catalog.js +8 -3
- package/dist/erasure/org-rules.js +1 -0
- package/dist/evals/evals.schemas.d.ts +15 -5
- package/dist/evals/evals.schemas.js +17 -10
- package/dist/evals/runs.controller.d.ts +4 -12
- package/dist/evals/runs.controller.js +14 -11
- package/dist/evals/runs.service.d.ts +29 -25
- package/dist/evals/runs.service.js +73 -61
- package/dist/evals/trajectory.controller.d.ts +10 -6
- package/dist/evals/trajectory.controller.js +11 -4
- package/dist/evals/trajectory.service.d.ts +17 -9
- package/dist/evals/trajectory.service.js +52 -35
- package/dist/extensions/admin-ops.d.ts +6 -1
- package/dist/extensions/admin-ops.js +21 -7
- package/dist/extensions/blobs.d.ts +2 -0
- package/dist/extensions/blobs.js +11 -0
- package/dist/extensions/deployment-config.d.ts +6 -1
- package/dist/extensions/deployment-config.js +13 -2
- package/dist/extensions/enabled.d.ts +5 -0
- package/dist/extensions/extensions.module.js +3 -0
- package/dist/extensions/grant-epoch.d.ts +108 -0
- package/dist/extensions/grant-epoch.js +214 -0
- package/dist/extensions/host.d.ts +29 -9
- package/dist/extensions/host.js +148 -42
- package/dist/extensions/instance.d.ts +3 -3
- package/dist/extensions/instance.js +1 -1
- package/dist/extensions/isolated/authorization.d.ts +54 -2
- package/dist/extensions/isolated/authorization.js +148 -35
- package/dist/extensions/isolated/child-session.js +0 -1
- package/dist/extensions/isolated/revision.js +1 -1
- package/dist/extensions/org-config.d.ts +3 -1
- package/dist/extensions/org-config.js +13 -4
- package/dist/extensions/org-overrides.d.ts +6 -1
- package/dist/extensions/org-overrides.js +13 -2
- package/dist/extensions/package-digest.job.d.ts +34 -0
- package/dist/extensions/package-digest.job.js +121 -0
- package/dist/extensions/package.js +10 -6
- package/dist/extensions/permission-set.d.ts +14 -78
- package/dist/extensions/permission-set.js +17 -143
- package/dist/extensions/permission-view.d.ts +13 -1
- package/dist/extensions/permission-view.js +20 -0
- package/dist/extensions/registry.js +4 -1
- package/dist/extensions/resolve.d.ts +7 -8
- package/dist/extensions/resolve.js +7 -8
- package/dist/extensions/revision-approvals.d.ts +167 -0
- package/dist/extensions/revision-approvals.js +353 -0
- package/dist/extensions/revision-grants.d.ts +197 -0
- package/dist/extensions/revision-grants.js +584 -0
- package/dist/extensions/state.module.js +12 -1
- package/dist/identity/accounts.d.ts +10 -4
- package/dist/identity/accounts.js +18 -5
- package/dist/inbox/inbox-items.service.d.ts +6 -1
- package/dist/inbox/inbox-items.service.js +29 -10
- package/dist/inbox/inbox.module.js +3 -0
- package/dist/inbox/inbox.service.d.ts +3 -1
- package/dist/inbox/inbox.service.js +9 -2
- package/dist/inbox/org-notices.d.ts +4 -3
- package/dist/inbox/org-notices.js +9 -6
- package/dist/inbox/platform-inbox.service.d.ts +3 -1
- package/dist/inbox/platform-inbox.service.js +11 -3
- package/dist/inbox/platform-notices.d.ts +3 -2
- package/dist/inbox/platform-notices.js +10 -4
- package/dist/infra/config/kernel-config.service.js +4 -1
- package/dist/infra/database/extension-effect-key-lock.js +7 -0
- package/dist/infra/paging/paged-read.d.ts +34 -4
- package/dist/infra/paging/paged-read.js +38 -1
- package/dist/invalidation/audiences.d.ts +32 -0
- package/dist/invalidation/audiences.js +43 -0
- package/dist/invalidation/hints.d.ts +6 -0
- package/dist/invalidation/hints.js +7 -1
- package/dist/invalidation/invalidation-hints.d.ts +12 -1
- package/dist/invalidation/invalidation-hints.js +46 -5
- package/dist/invalidation/invalidation-hints.module.d.ts +2 -0
- package/dist/invalidation/invalidation-hints.module.js +4 -1
- package/dist/invalidation/me-stream.d.ts +1 -11
- package/dist/invalidation/me-stream.js +12 -41
- package/dist/invalidation/org-intent-bridge.d.ts +18 -0
- package/dist/invalidation/org-intent-bridge.js +46 -0
- package/dist/models/enablement.d.ts +3 -1
- package/dist/models/enablement.js +25 -5
- package/dist/orgs/invitations.controller.d.ts +4 -7
- package/dist/orgs/invitations.controller.js +8 -5
- package/dist/orgs/invitations.service.d.ts +17 -3
- package/dist/orgs/invitations.service.js +35 -13
- package/dist/orgs/members.service.d.ts +35 -0
- package/dist/orgs/members.service.js +52 -3
- package/dist/orgs/offboarding.d.ts +3 -1
- package/dist/orgs/offboarding.js +7 -3
- package/dist/orgs/orgs.controller.d.ts +11 -4
- package/dist/orgs/orgs.controller.js +25 -5
- package/dist/orgs/orgs.module.js +3 -0
- package/dist/orgs/orgs.schemas.d.ts +14 -0
- package/dist/orgs/orgs.schemas.js +19 -2
- package/dist/orgs/orgs.service.d.ts +24 -2
- package/dist/orgs/orgs.service.js +47 -4
- package/dist/orgs/security-settings.service.d.ts +14 -6
- package/dist/orgs/security-settings.service.js +18 -13
- package/dist/orgs/settings.controller.d.ts +7 -4
- package/dist/platform/exclusions.js +15 -0
- package/dist/platform/ops/accounts.ops.js +7 -16
- package/dist/platform/ops/admin-items.ops.js +7 -7
- package/dist/platform/ops/automations.ops.js +6 -4
- package/dist/platform/ops/evals.ops.js +30 -15
- package/dist/platform/ops/org-settings.ops.js +2 -2
- package/dist/platform/ops/orgs.ops.js +44 -27
- package/dist/push/delivery.d.ts +3 -1
- package/dist/push/delivery.js +7 -3
- package/dist/push/push-processor.js +8 -1
- package/dist/roles/worker.module.js +3 -0
- package/dist/runtime/step-log.d.ts +1 -1
- package/dist/runtime/step-log.js +5 -4
- package/dist/runtime/stream-limit.d.ts +13 -0
- package/dist/runtime/stream-limit.js +40 -0
- package/dist/runtime/stream.controller.d.ts +2 -0
- package/dist/runtime/stream.controller.js +2 -0
- package/dist/runtime/stream.d.ts +1 -0
- package/dist/runtime/stream.js +15 -6
- package/dist/sandbox/permission-authority.module.js +6 -1
- package/dist/sandbox/permission-transitions.d.ts +3 -1
- package/dist/sandbox/permission-transitions.js +17 -2
- package/dist/setup/kernel-checks.d.ts +3 -3
- package/dist/setup/kernel-checks.js +4 -4
- package/dist/setup/setup-check-registry.d.ts +16 -5
- package/dist/setup/setup-check-registry.js +11 -3
- package/dist/setup/setup-checks.service.d.ts +1 -2
- package/dist/setup/setup-checks.service.js +7 -6
- package/dist/skills/agent-skills.service.d.ts +6 -1
- package/dist/skills/agent-skills.service.js +12 -3
- package/dist/skills/changes.service.d.ts +6 -1
- package/dist/skills/changes.service.js +11 -3
- package/dist/skills/conversation-catalog.d.ts +3 -0
- package/dist/skills/conversation-catalog.js +2 -0
- package/dist/skills/skills.module.js +3 -0
- package/dist/skills/skills.service.d.ts +3 -1
- package/dist/skills/skills.service.js +8 -4
- package/dist/tools/admin-connectors.d.ts +10 -8
- package/dist/tools/admin-connectors.js +12 -10
- package/dist/tools/approvals.service.d.ts +12 -1
- package/dist/tools/approvals.service.js +36 -9
- package/dist/tools/builtins/automations.d.ts +1 -1
- package/dist/tools/builtins/automations.js +1 -1
- package/dist/tools/connectors.service.d.ts +3 -1
- package/dist/tools/connectors.service.js +29 -7
- package/dist/tools/tools.module.js +3 -0
- package/dist/ui/admin-ui.controller.d.ts +3 -1
- package/dist/ui/admin-ui.controller.js +3 -1
- package/dist/ui/ui-stream.d.ts +2 -0
- package/dist/ui/ui-stream.js +20 -6
- package/dist/ui/views.controller.d.ts +4 -2
- package/dist/ui/views.controller.js +4 -2
- package/package.json +3 -3
- package/src/migrations/0234_extension_grant_epoch.sql +141 -0
- package/src/migrations/0235_extension_revision_grants.sql +166 -0
- package/src/migrations/0236_paged_table_idx.sql +33 -0
- package/src/migrations/0237_extension_handoff_health.sql +18 -0
|
@@ -7,7 +7,7 @@ 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 { SDK_VERSION } from "@capybara-hq/plugin-sdk";
|
|
10
|
+
import { extensionPointRefs, SDK_VERSION, staticPermissionDeclarations, } from "@capybara-hq/plugin-sdk";
|
|
11
11
|
import { Inject, Injectable } from "@nestjs/common";
|
|
12
12
|
import { sql } from "kysely";
|
|
13
13
|
import semver from "semver";
|
|
@@ -30,6 +30,8 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
|
30
30
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
31
31
|
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
32
32
|
import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
|
|
33
|
+
import { publishPlatformCapabilities } from "../invalidation/audiences.js";
|
|
34
|
+
import { InvalidationHints } from "../invalidation/invalidation-hints.js";
|
|
33
35
|
import { OrgLock } from "../orgs/org-lock.js";
|
|
34
36
|
import { ExtensionAdmin } from "./admin-view.js";
|
|
35
37
|
import { ExtensionBlobs } from "./blobs.js";
|
|
@@ -57,6 +59,7 @@ let ExtensionAdminOps = class ExtensionAdminOps {
|
|
|
57
59
|
log;
|
|
58
60
|
singleProvider;
|
|
59
61
|
outbox;
|
|
62
|
+
hints;
|
|
60
63
|
constructor(kdb, txHost,
|
|
61
64
|
/** The super admin lock (identity/super-admin.ts): joins the transaction. */
|
|
62
65
|
adminLock,
|
|
@@ -83,7 +86,9 @@ let ExtensionAdminOps = class ExtensionAdminOps {
|
|
|
83
86
|
/** One enabled provider per single-provider extension point (checked in the enable). */
|
|
84
87
|
singleProvider,
|
|
85
88
|
/** The plugin scope sync a deploy owes (`oweDeployedExtensionSync`). */
|
|
86
|
-
outbox
|
|
89
|
+
outbox,
|
|
90
|
+
/** A platform enable, disable or new version publishes `platform-caps` after the commit. */
|
|
91
|
+
hints) {
|
|
87
92
|
this.kdb = kdb;
|
|
88
93
|
this.txHost = txHost;
|
|
89
94
|
this.adminLock = adminLock;
|
|
@@ -99,6 +104,7 @@ let ExtensionAdminOps = class ExtensionAdminOps {
|
|
|
99
104
|
this.log = log;
|
|
100
105
|
this.singleProvider = singleProvider;
|
|
101
106
|
this.outbox = outbox;
|
|
107
|
+
this.hints = hints;
|
|
102
108
|
}
|
|
103
109
|
get db() {
|
|
104
110
|
return this.kdb.db;
|
|
@@ -298,6 +304,7 @@ let ExtensionAdminOps = class ExtensionAdminOps {
|
|
|
298
304
|
.set({ desired_state: "disabled", enabled_at: null })
|
|
299
305
|
.where("name", "=", name)
|
|
300
306
|
.execute();
|
|
307
|
+
publishPlatformCapabilities(this.hints);
|
|
301
308
|
await this.audit(actor, actorTokenId, "extension.disabled", name, row.version, row.sha256, {
|
|
302
309
|
singleProvider: block,
|
|
303
310
|
...ownerDetail(opts.owner),
|
|
@@ -328,7 +335,8 @@ let ExtensionAdminOps = class ExtensionAdminOps {
|
|
|
328
335
|
if (sourceIntent)
|
|
329
336
|
await restoreSourceIntent(db, name, sourceIntent, actor);
|
|
330
337
|
if (leftDisabled !== undefined ||
|
|
331
|
-
target.section.manifest.permissions
|
|
338
|
+
staticPermissionDeclarations(target.section.manifest).permissions.deviceAccess?.siteAccess !==
|
|
339
|
+
true) {
|
|
332
340
|
await revokeSiteGrantsOfExtensionEverywhere(db, name);
|
|
333
341
|
}
|
|
334
342
|
await this.audit(actor, actorTokenId, "extension.installed", name, pkg.version, sha256, {
|
|
@@ -340,9 +348,12 @@ let ExtensionAdminOps = class ExtensionAdminOps {
|
|
|
340
348
|
await oweHostServicesStop(db, this.outbox, { extension: name });
|
|
341
349
|
return { changed: true, state: "disabled", leftDisabled };
|
|
342
350
|
}
|
|
343
|
-
// A new version of an enabled extension is a deploy: it owes its plugin's scope sync
|
|
344
|
-
|
|
351
|
+
// A new version of an enabled extension is a deploy: it owes its plugin's scope sync, and
|
|
352
|
+
// what it offers every org may change (`platform-caps`)
|
|
353
|
+
if (row?.desired_state === "enabled") {
|
|
354
|
+
publishPlatformCapabilities(this.hints);
|
|
345
355
|
await oweDeployedExtensionSync(this.outbox, db, name);
|
|
356
|
+
}
|
|
346
357
|
return { changed: true, state: row?.desired_state ?? "disabled" };
|
|
347
358
|
}
|
|
348
359
|
/**
|
|
@@ -452,6 +463,8 @@ let ExtensionAdminOps = class ExtensionAdminOps {
|
|
|
452
463
|
})
|
|
453
464
|
.where("name", "=", name)
|
|
454
465
|
.execute();
|
|
466
|
+
// switched on or off for the whole platform: every org's members refetch
|
|
467
|
+
publishPlatformCapabilities(this.hints);
|
|
455
468
|
if (state === "disabled") {
|
|
456
469
|
await revokeSiteGrantsOfExtensionEverywhere(db, name);
|
|
457
470
|
// its host services stop on every machine that runs one (local agents spec, call 5)
|
|
@@ -576,7 +589,8 @@ ExtensionAdminOps = __decorate([
|
|
|
576
589
|
__param(11, Inject(ExtensionLifecycle)),
|
|
577
590
|
__param(12, Inject(KERNEL_LOGGER)),
|
|
578
591
|
__param(13, Inject(SingleProviderGuard)),
|
|
579
|
-
__param(14, Inject(OutboxService))
|
|
592
|
+
__param(14, Inject(OutboxService)),
|
|
593
|
+
__param(15, Inject(InvalidationHints))
|
|
580
594
|
], ExtensionAdminOps);
|
|
581
595
|
export { ExtensionAdminOps };
|
|
582
596
|
/**
|
|
@@ -668,7 +682,7 @@ const notFound = (name) => new ApiError("extension.not_found", `Extension ${name
|
|
|
668
682
|
const isDowngrade = (to, from) => semver.valid(to) !== null && semver.valid(from) !== null && semver.lt(to, from);
|
|
669
683
|
/** The extension points a stored package's reviewed manifest provides. */
|
|
670
684
|
function providesOf(section) {
|
|
671
|
-
return section?.manifest?.provides ?? [];
|
|
685
|
+
return extensionPointRefs(section?.manifest?.provides ?? []);
|
|
672
686
|
}
|
|
673
687
|
/** The audit detail of an owner's operation. */
|
|
674
688
|
function ownerDetail(owner) {
|
|
@@ -25,6 +25,8 @@ export declare class ExtensionBlobIntegrityError extends Error {
|
|
|
25
25
|
}
|
|
26
26
|
/** 对象存储里的键(相对 `deployment/`)。 */
|
|
27
27
|
export declare const blobKey: (sha256: string) => string;
|
|
28
|
+
/** The lowercase hex sha512 of a package archive: the digest revision grants are keyed by. */
|
|
29
|
+
export declare const packageSha512: (bytes: Uint8Array) => string;
|
|
28
30
|
export interface ExtensionBlobSource {
|
|
29
31
|
source: "npm" | "file" | "catalog" | "bootstrap";
|
|
30
32
|
ref: string;
|
package/dist/extensions/blobs.js
CHANGED
|
@@ -41,6 +41,8 @@ export class ExtensionBlobIntegrityError extends Error {
|
|
|
41
41
|
}
|
|
42
42
|
/** 对象存储里的键(相对 `deployment/`)。 */
|
|
43
43
|
export const blobKey = (sha256) => `plugins/blobs/${sha256}.tgz`;
|
|
44
|
+
/** The lowercase hex sha512 of a package archive: the digest revision grants are keyed by. */
|
|
45
|
+
export const packageSha512 = (bytes) => createHash("sha512").update(bytes).digest("hex");
|
|
44
46
|
const SHA256_RE = /^[0-9a-f]{64}$/;
|
|
45
47
|
/** How many packages {@link ExtensionBlobs.remember} keeps; the oldest is dropped beyond it. */
|
|
46
48
|
const REMEMBERED_MAX = 8;
|
|
@@ -120,6 +122,13 @@ let ExtensionBlobs = class ExtensionBlobs {
|
|
|
120
122
|
// The row is there: bytes that went missing (an object deleted, a database cleared) are
|
|
121
123
|
// restored where the row says, and so are the client build's files and row
|
|
122
124
|
await this.repair(p.sha256, existing.blob_store, bytes);
|
|
125
|
+
// a row stored before 0235 gets its sha512 now that the bytes are at hand
|
|
126
|
+
await this.db
|
|
127
|
+
.updateTable("extension_packages")
|
|
128
|
+
.set({ sha512: packageSha512(bytes) })
|
|
129
|
+
.where("sha256", "=", p.sha256)
|
|
130
|
+
.where("sha512", "is", null)
|
|
131
|
+
.execute();
|
|
123
132
|
if (client !== undefined) {
|
|
124
133
|
await this.clientBuilds.extract(p.sha256, plugin, client.files, client.section);
|
|
125
134
|
}
|
|
@@ -163,6 +172,8 @@ let ExtensionBlobs = class ExtensionBlobs {
|
|
|
163
172
|
source_ref: src.ref,
|
|
164
173
|
uploaded_by: src.actor,
|
|
165
174
|
display_name: p.displayName === undefined ? null : JSON.stringify(p.displayName),
|
|
175
|
+
// the revision identity grants bind to (plan task 1.2b)
|
|
176
|
+
sha512: packageSha512(bytes),
|
|
166
177
|
})
|
|
167
178
|
.onConflict((oc) => oc.column("sha256").doNothing())
|
|
168
179
|
.returning("sha256")
|
|
@@ -8,6 +8,7 @@ import { SuperAdminLock } from "../identity/super-admin.js";
|
|
|
8
8
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
9
9
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
10
10
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
11
|
+
import { InvalidationHints } from "../invalidation/invalidation-hints.js";
|
|
11
12
|
import type { KernelLogger } from "../log.js";
|
|
12
13
|
import type { PublishBus } from "./admin-view.js";
|
|
13
14
|
import { type ConfigIssue } from "./config-issues.js";
|
|
@@ -116,6 +117,8 @@ export declare class ExtensionDeploymentConfigService {
|
|
|
116
117
|
private readonly bus;
|
|
117
118
|
private readonly log;
|
|
118
119
|
private readonly displayNames;
|
|
120
|
+
/** A saved or cleared config publishes `platform-caps` after it applied here. */
|
|
121
|
+
private readonly hints;
|
|
119
122
|
/** Where each startup-config field comes from (see `extensionConfigSources`); those fields are read-only. */
|
|
120
123
|
private readonly sources;
|
|
121
124
|
constructor(kdb: KernelDb, txHost: TransactionHost,
|
|
@@ -128,7 +131,9 @@ export declare class ExtensionDeploymentConfigService {
|
|
|
128
131
|
/** Applies a saved config on this replica at once (other replicas through the bus). */
|
|
129
132
|
lifecycle: ExtensionLifecycle,
|
|
130
133
|
/** Publishes {@link PLUGIN_DEPLOYMENT_CONFIG_TOPIC} after a save (a failure only warns). */
|
|
131
|
-
bus: PublishBus, log: KernelLogger, options: Pick<KernelAppOptions, "env" | "extensionConfigSources">, displayNames: ExtensionDisplayNames
|
|
134
|
+
bus: PublishBus, log: KernelLogger, options: Pick<KernelAppOptions, "env" | "extensionConfigSources">, displayNames: ExtensionDisplayNames,
|
|
135
|
+
/** A saved or cleared config publishes `platform-caps` after it applied here. */
|
|
136
|
+
hints: Pick<InvalidationHints, "publish">);
|
|
132
137
|
private get db();
|
|
133
138
|
/** The startup config's `extensionConfig` (file / Nacos merged with env). */
|
|
134
139
|
private fileConfig;
|
|
@@ -21,6 +21,8 @@ import { KernelDb } from "../infra/database/kernel-db.js";
|
|
|
21
21
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
22
22
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
23
23
|
import { KERNEL_BUS, KERNEL_LOGGER, KEYRING } from "../infra/tokens.js";
|
|
24
|
+
import { PLATFORM_CAPS_TOPIC } from "../invalidation/hints.js";
|
|
25
|
+
import { InvalidationHints } from "../invalidation/invalidation-hints.js";
|
|
24
26
|
import { KERNEL_APP_OPTIONS } from "../lifecycle/tokens.js";
|
|
25
27
|
import { toIssues } from "./config-issues.js";
|
|
26
28
|
import { checkConfigUi, configMessages, hintedSecretPaths, safeConfigFormSchema, } from "./config-json-schema.js";
|
|
@@ -63,6 +65,7 @@ let ExtensionDeploymentConfigService = class ExtensionDeploymentConfigService {
|
|
|
63
65
|
bus;
|
|
64
66
|
log;
|
|
65
67
|
displayNames;
|
|
68
|
+
hints;
|
|
66
69
|
/** Where each startup-config field comes from (see `extensionConfigSources`); those fields are read-only. */
|
|
67
70
|
sources;
|
|
68
71
|
constructor(kdb, txHost,
|
|
@@ -75,7 +78,9 @@ let ExtensionDeploymentConfigService = class ExtensionDeploymentConfigService {
|
|
|
75
78
|
/** Applies a saved config on this replica at once (other replicas through the bus). */
|
|
76
79
|
lifecycle,
|
|
77
80
|
/** Publishes {@link PLUGIN_DEPLOYMENT_CONFIG_TOPIC} after a save (a failure only warns). */
|
|
78
|
-
bus, log, options, displayNames
|
|
81
|
+
bus, log, options, displayNames,
|
|
82
|
+
/** A saved or cleared config publishes `platform-caps` after it applied here. */
|
|
83
|
+
hints) {
|
|
79
84
|
this.kdb = kdb;
|
|
80
85
|
this.txHost = txHost;
|
|
81
86
|
this.adminLock = adminLock;
|
|
@@ -88,6 +93,7 @@ let ExtensionDeploymentConfigService = class ExtensionDeploymentConfigService {
|
|
|
88
93
|
this.bus = bus;
|
|
89
94
|
this.log = log;
|
|
90
95
|
this.displayNames = displayNames;
|
|
96
|
+
this.hints = hints;
|
|
91
97
|
const env = options.env ?? process.env;
|
|
92
98
|
this.sources =
|
|
93
99
|
options.extensionConfigSources ??
|
|
@@ -194,6 +200,9 @@ let ExtensionDeploymentConfigService = class ExtensionDeploymentConfigService {
|
|
|
194
200
|
err,
|
|
195
201
|
});
|
|
196
202
|
}
|
|
203
|
+
// the config may move whether orgs can call the extension (needs config): every org's
|
|
204
|
+
// members refetch (already after the commit)
|
|
205
|
+
await this.hints.publish([PLATFORM_CAPS_TOPIC], { kind: "capabilities" });
|
|
197
206
|
};
|
|
198
207
|
// Inside a caller's transaction (a Platform write applying the person's sealed values) the
|
|
199
208
|
// save is not committed yet: replicas re-read only after the commit
|
|
@@ -283,6 +292,7 @@ let ExtensionDeploymentConfigService = class ExtensionDeploymentConfigService {
|
|
|
283
292
|
err,
|
|
284
293
|
});
|
|
285
294
|
}
|
|
295
|
+
await this.hints.publish([PLATFORM_CAPS_TOPIC], { kind: "capabilities" });
|
|
286
296
|
});
|
|
287
297
|
}
|
|
288
298
|
/**
|
|
@@ -517,7 +527,8 @@ ExtensionDeploymentConfigService = __decorate([
|
|
|
517
527
|
__param(9, Inject(KERNEL_BUS)),
|
|
518
528
|
__param(10, Inject(KERNEL_LOGGER)),
|
|
519
529
|
__param(11, Inject(KERNEL_APP_OPTIONS)),
|
|
520
|
-
__param(12, Inject(ExtensionDisplayNames))
|
|
530
|
+
__param(12, Inject(ExtensionDisplayNames)),
|
|
531
|
+
__param(13, Inject(InvalidationHints))
|
|
521
532
|
], ExtensionDeploymentConfigService);
|
|
522
533
|
export { ExtensionDeploymentConfigService };
|
|
523
534
|
/** The org level of each top-level key: from the zod schema, else the package's form schema. */
|
|
@@ -106,6 +106,7 @@ export declare function extensionOrgCountsQuery(db: KernelSchemaDb, names: reado
|
|
|
106
106
|
eval_results: import("../db/kernel-schema.js").EvalResultsTable;
|
|
107
107
|
eval_runs: import("../db/kernel-schema.js").EvalRunsTable;
|
|
108
108
|
eval_sets: import("../db/kernel-schema.js").EvalSetsTable;
|
|
109
|
+
extension_admission_refusals: import("../db/kernel-schema.js").ExtensionAdmissionRefusalsTable;
|
|
109
110
|
extension_blobs: import("../db/kernel-schema.js").ExtensionBlobsTable;
|
|
110
111
|
extension_catalog_sources: import("../db/kernel-schema.js").ExtensionCatalogSourcesTable;
|
|
111
112
|
extension_client_builds: import("../db/kernel-schema.js").ExtensionClientBuildsTable;
|
|
@@ -113,6 +114,8 @@ export declare function extensionOrgCountsQuery(db: KernelSchemaDb, names: reado
|
|
|
113
114
|
extension_deployment_configs: import("../db/kernel-schema.js").ExtensionDeploymentConfigsTable;
|
|
114
115
|
extension_effect_cancellations: import("../db/kernel-schema.js").ExtensionEffectCancellationsTable;
|
|
115
116
|
extension_effect_receipts: import("../db/kernel-schema.js").ExtensionEffectReceiptsTable;
|
|
117
|
+
extension_grant_epoch: import("../db/kernel-schema.js").ExtensionGrantEpochTable;
|
|
118
|
+
extension_handoff_tables: import("../db/kernel-schema.js").ExtensionHandoffTablesTable;
|
|
116
119
|
extension_installs: import("../db/kernel-schema.js").ExtensionInstallsTable;
|
|
117
120
|
extension_name_owners: import("../db/kernel-schema.js").ExtensionNameOwnersTable;
|
|
118
121
|
extension_org_configs: import("../db/kernel-schema.js").ExtensionOrgConfigsTable;
|
|
@@ -120,6 +123,8 @@ export declare function extensionOrgCountsQuery(db: KernelSchemaDb, names: reado
|
|
|
120
123
|
extension_packages: import("../db/kernel-schema.js").ExtensionPackagesTable;
|
|
121
124
|
extension_permission_snapshots: import("../db/kernel-schema.js").ExtensionPermissionSnapshotsTable;
|
|
122
125
|
extension_replica_status: import("../db/kernel-schema.js").ExtensionReplicaStatusTable;
|
|
126
|
+
extension_revision_grant_orgs: import("../db/kernel-schema.js").ExtensionRevisionGrantOrgsTable;
|
|
127
|
+
extension_revision_grants: import("../db/kernel-schema.js").ExtensionRevisionGrantsTable;
|
|
123
128
|
file_previewers: import("../db/kernel-schema.js").FilePreviewersTable;
|
|
124
129
|
file_shares: import("../db/kernel-schema.js").FileSharesTable;
|
|
125
130
|
files: import("../db/kernel-schema.js").FilesTable;
|
|
@@ -12,6 +12,7 @@ import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
|
|
|
12
12
|
import { DialInRelayModule } from "../dial-in/relay.module.js";
|
|
13
13
|
import { SuperAdminLockModule } from "../identity/super-admin.js";
|
|
14
14
|
import { InboxItemsModule } from "../inbox/inbox-items.service.js";
|
|
15
|
+
import { InvalidationHintsModule } from "../invalidation/invalidation-hints.module.js";
|
|
15
16
|
import { ModelsModule } from "../models/models.module.js";
|
|
16
17
|
import { OrgNetworkAllowancesModule } from "../orgs/network-allowances.service.js";
|
|
17
18
|
import { OrgLockModule } from "../orgs/org-lock.js";
|
|
@@ -50,6 +51,8 @@ let ExtensionsModule = class ExtensionsModule {
|
|
|
50
51
|
ExtensionsModule = __decorate([
|
|
51
52
|
Module({
|
|
52
53
|
imports: [
|
|
54
|
+
// invalidation hints its writers publish after their commit
|
|
55
|
+
InvalidationHintsModule,
|
|
53
56
|
ExtensionRegistryModule,
|
|
54
57
|
// one provider's candidacy for a point, shared with the conversation access check
|
|
55
58
|
ExtensionPointServingModule,
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The deployment grant epoch as one replica sees it (isolation capacity spec 2026-12-04,
|
|
3
|
+
* "Required change: grant epoch").
|
|
4
|
+
*
|
|
5
|
+
* PostgreSQL advances `extension_grant_epoch.epoch` in the transaction of every committed change to
|
|
6
|
+
* a table the isolated grant check reads (migration 0234). Each replica polls it once per second.
|
|
7
|
+
* A changed epoch makes every cached grant stale; a replica that cannot read the epoch stops
|
|
8
|
+
* trusting its cache after `maxAgeMs` and fences in-flight isolated work at the fence deadline.
|
|
9
|
+
*
|
|
10
|
+
* The user-visible bound is {@link REVOCATION_BOUND_MS} (5 s). The kernel acts by
|
|
11
|
+
* {@link FENCE_DEADLINE_MS} (4 s) so that timer delay and event-loop lag under load
|
|
12
|
+
* ({@link FENCE_SLACK_MS}, 1 s) never push a refusal past the bound. For a revocation that commits
|
|
13
|
+
* after the start `t` of the last read that saw the old epoch (that read's snapshot predates the
|
|
14
|
+
* commit):
|
|
15
|
+
* - admissions: a cached grant is trusted only until `t + maxAgeMs` (3 s by default);
|
|
16
|
+
* - in-flight work: when a later read sees the change, work not revalidated at the new epoch is
|
|
17
|
+
* fenced at `t + 4 s` ({@link GrantEpochOptions.onSettleDeadline}), at once if that time has
|
|
18
|
+
* passed, however slow the reads in between were;
|
|
19
|
+
* - no successful read: the expiry timer fences everything at `t + 4 s` as well.
|
|
20
|
+
*
|
|
21
|
+
* Why a plain per-replica timer and not `@LockedInterval`: a locked interval runs once per tick
|
|
22
|
+
* across all replicas, on a worker, but the epoch guards each replica's own in-memory cache, so
|
|
23
|
+
* every replica (api, worker and gateway alike) must read it itself. The read is a one-row
|
|
24
|
+
* primary-key lookup and writes nothing, so a timer per replica carries no cross-replica state;
|
|
25
|
+
* the source of truth stays in PostgreSQL. It runs only after an isolated grant was requested on
|
|
26
|
+
* this replica and stops when the extension host closes.
|
|
27
|
+
*/
|
|
28
|
+
/** #1373: stale kernel admission or broker access ends at most 5 s after a revocation commits. */
|
|
29
|
+
export declare const REVOCATION_BOUND_MS = 5000;
|
|
30
|
+
/** Room left under the bound for timer delay and event-loop lag on a loaded replica. */
|
|
31
|
+
export declare const FENCE_SLACK_MS = 1000;
|
|
32
|
+
/** When the kernel fences, counted from the last read that saw the old epoch. */
|
|
33
|
+
export declare const FENCE_DEADLINE_MS: number;
|
|
34
|
+
export declare const GRANT_EPOCH_POLL_MS = 1000;
|
|
35
|
+
/** How long one epoch read may take: what remains of the trusted age after a poll interval. */
|
|
36
|
+
export declare function grantEpochReadTimeoutMs(maxAgeMs: number, pollMs?: number): number;
|
|
37
|
+
/**
|
|
38
|
+
* The epoch read on its own one-connection pool, opened at the first read. A blocked read (a lock
|
|
39
|
+
* on the epoch row, a saturated server) is cut off on both sides at the read timeout:
|
|
40
|
+
* `statement_timeout` and `lock_timeout` end it in PostgreSQL and `query_timeout` in the client,
|
|
41
|
+
* so it never holds a kernel pool connection or piles up connections of its own. The row has no
|
|
42
|
+
* org_id: deployment state, outside RLS and org scope.
|
|
43
|
+
*/
|
|
44
|
+
export declare function grantEpochReader(opts: {
|
|
45
|
+
url: string;
|
|
46
|
+
readTimeoutMs: number;
|
|
47
|
+
connectTimeoutMs?: number | undefined;
|
|
48
|
+
onError: (err: Error) => void;
|
|
49
|
+
}): {
|
|
50
|
+
read: () => Promise<string>;
|
|
51
|
+
close: () => Promise<void>;
|
|
52
|
+
};
|
|
53
|
+
export interface GrantEpochOptions {
|
|
54
|
+
/** Reads the current epoch; rejects when PostgreSQL cannot be reached. */
|
|
55
|
+
read: () => Promise<string>;
|
|
56
|
+
/** How long a successful read is trusted (`extensionHost.capacity.grantEpochMaxAgeMs`). */
|
|
57
|
+
maxAgeMs: number;
|
|
58
|
+
/** Called after a read that observed a different epoch than the previous successful read. */
|
|
59
|
+
onChange: (epoch: string) => void;
|
|
60
|
+
/**
|
|
61
|
+
* Called after a change was observed, at {@link FENCE_DEADLINE_MS} counted from the start of the
|
|
62
|
+
* last read that saw the old epoch: in-flight work not revalidated at the new epoch must be fenced.
|
|
63
|
+
*/
|
|
64
|
+
onSettleDeadline: () => void;
|
|
65
|
+
/** Called once when no read has succeeded for {@link FENCE_DEADLINE_MS}. */
|
|
66
|
+
onExpired: () => void;
|
|
67
|
+
onFault?: (err: unknown) => void;
|
|
68
|
+
pollMs?: number;
|
|
69
|
+
now?: () => number;
|
|
70
|
+
}
|
|
71
|
+
export declare class GrantEpoch {
|
|
72
|
+
private readonly options;
|
|
73
|
+
private epoch;
|
|
74
|
+
/** Start time of the last successful read: the snapshot it saw is at least this old. */
|
|
75
|
+
private readAt;
|
|
76
|
+
private reading;
|
|
77
|
+
private pollTimer;
|
|
78
|
+
private expiryTimer;
|
|
79
|
+
private readonly settleTimers;
|
|
80
|
+
private running;
|
|
81
|
+
private readonly now;
|
|
82
|
+
private readonly pollMs;
|
|
83
|
+
private readonly readTimeoutMs;
|
|
84
|
+
/**
|
|
85
|
+
* Timers run in the context the epoch was built in (the host's construction), never in the
|
|
86
|
+
* context of the call that first started polling (its org scope or request log context).
|
|
87
|
+
*/
|
|
88
|
+
private readonly inOwnContext;
|
|
89
|
+
constructor(options: GrantEpochOptions);
|
|
90
|
+
/** Starts polling on this replica; idempotent. */
|
|
91
|
+
start(): void;
|
|
92
|
+
stop(): void;
|
|
93
|
+
/** The epoch when the last successful read is younger than `maxAgeMs`, otherwise undefined. */
|
|
94
|
+
fresh(): string | undefined;
|
|
95
|
+
/** The fresh epoch, reading PostgreSQL first when needed; undefined when that read fails. */
|
|
96
|
+
ensureFresh(): Promise<string | undefined>;
|
|
97
|
+
/** One read at a time; concurrent callers share it. It settles within the read timeout. */
|
|
98
|
+
refresh(): Promise<string | undefined>;
|
|
99
|
+
private readOnce;
|
|
100
|
+
private withTimeout;
|
|
101
|
+
/** Fence everything at the revocation bound unless a later read succeeds first. */
|
|
102
|
+
private armExpiry;
|
|
103
|
+
/** `oldEpochReadAt`: start of the last read that saw the old epoch, before the commit. */
|
|
104
|
+
private armSettleDeadline;
|
|
105
|
+
/** Polls on a fixed cadence; a slow read never delays the next tick (reads are coalesced). */
|
|
106
|
+
private poll;
|
|
107
|
+
private timer;
|
|
108
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import pg from "pg";
|
|
3
|
+
import { KERNEL_APPLICATION_NAME } from "../db/pool.js";
|
|
4
|
+
/**
|
|
5
|
+
* The deployment grant epoch as one replica sees it (isolation capacity spec 2026-12-04,
|
|
6
|
+
* "Required change: grant epoch").
|
|
7
|
+
*
|
|
8
|
+
* PostgreSQL advances `extension_grant_epoch.epoch` in the transaction of every committed change to
|
|
9
|
+
* a table the isolated grant check reads (migration 0234). Each replica polls it once per second.
|
|
10
|
+
* A changed epoch makes every cached grant stale; a replica that cannot read the epoch stops
|
|
11
|
+
* trusting its cache after `maxAgeMs` and fences in-flight isolated work at the fence deadline.
|
|
12
|
+
*
|
|
13
|
+
* The user-visible bound is {@link REVOCATION_BOUND_MS} (5 s). The kernel acts by
|
|
14
|
+
* {@link FENCE_DEADLINE_MS} (4 s) so that timer delay and event-loop lag under load
|
|
15
|
+
* ({@link FENCE_SLACK_MS}, 1 s) never push a refusal past the bound. For a revocation that commits
|
|
16
|
+
* after the start `t` of the last read that saw the old epoch (that read's snapshot predates the
|
|
17
|
+
* commit):
|
|
18
|
+
* - admissions: a cached grant is trusted only until `t + maxAgeMs` (3 s by default);
|
|
19
|
+
* - in-flight work: when a later read sees the change, work not revalidated at the new epoch is
|
|
20
|
+
* fenced at `t + 4 s` ({@link GrantEpochOptions.onSettleDeadline}), at once if that time has
|
|
21
|
+
* passed, however slow the reads in between were;
|
|
22
|
+
* - no successful read: the expiry timer fences everything at `t + 4 s` as well.
|
|
23
|
+
*
|
|
24
|
+
* Why a plain per-replica timer and not `@LockedInterval`: a locked interval runs once per tick
|
|
25
|
+
* across all replicas, on a worker, but the epoch guards each replica's own in-memory cache, so
|
|
26
|
+
* every replica (api, worker and gateway alike) must read it itself. The read is a one-row
|
|
27
|
+
* primary-key lookup and writes nothing, so a timer per replica carries no cross-replica state;
|
|
28
|
+
* the source of truth stays in PostgreSQL. It runs only after an isolated grant was requested on
|
|
29
|
+
* this replica and stops when the extension host closes.
|
|
30
|
+
*/
|
|
31
|
+
/** #1373: stale kernel admission or broker access ends at most 5 s after a revocation commits. */
|
|
32
|
+
export const REVOCATION_BOUND_MS = 5_000;
|
|
33
|
+
/** Room left under the bound for timer delay and event-loop lag on a loaded replica. */
|
|
34
|
+
export const FENCE_SLACK_MS = 1_000;
|
|
35
|
+
/** When the kernel fences, counted from the last read that saw the old epoch. */
|
|
36
|
+
export const FENCE_DEADLINE_MS = REVOCATION_BOUND_MS - FENCE_SLACK_MS;
|
|
37
|
+
export const GRANT_EPOCH_POLL_MS = 1_000;
|
|
38
|
+
/** How long one epoch read may take: what remains of the trusted age after a poll interval. */
|
|
39
|
+
export function grantEpochReadTimeoutMs(maxAgeMs, pollMs = GRANT_EPOCH_POLL_MS) {
|
|
40
|
+
return maxAgeMs - pollMs;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The epoch read on its own one-connection pool, opened at the first read. A blocked read (a lock
|
|
44
|
+
* on the epoch row, a saturated server) is cut off on both sides at the read timeout:
|
|
45
|
+
* `statement_timeout` and `lock_timeout` end it in PostgreSQL and `query_timeout` in the client,
|
|
46
|
+
* so it never holds a kernel pool connection or piles up connections of its own. The row has no
|
|
47
|
+
* org_id: deployment state, outside RLS and org scope.
|
|
48
|
+
*/
|
|
49
|
+
export function grantEpochReader(opts) {
|
|
50
|
+
let pool;
|
|
51
|
+
let closed = false;
|
|
52
|
+
const connectTimeoutMs = Math.min(opts.connectTimeoutMs ?? opts.readTimeoutMs, opts.readTimeoutMs);
|
|
53
|
+
return {
|
|
54
|
+
read: async () => {
|
|
55
|
+
if (closed)
|
|
56
|
+
throw new Error("The grant epoch reader is closed");
|
|
57
|
+
pool ??= (() => {
|
|
58
|
+
const created = new pg.Pool({
|
|
59
|
+
connectionString: opts.url,
|
|
60
|
+
max: 1,
|
|
61
|
+
application_name: `${KERNEL_APPLICATION_NAME}-grant-epoch`,
|
|
62
|
+
connectionTimeoutMillis: connectTimeoutMs,
|
|
63
|
+
statement_timeout: opts.readTimeoutMs,
|
|
64
|
+
lock_timeout: opts.readTimeoutMs,
|
|
65
|
+
query_timeout: opts.readTimeoutMs,
|
|
66
|
+
keepAlive: true,
|
|
67
|
+
});
|
|
68
|
+
created.on("error", opts.onError);
|
|
69
|
+
created.on("connect", (client) => client.on("error", opts.onError));
|
|
70
|
+
return created;
|
|
71
|
+
})();
|
|
72
|
+
const { rows } = await pool.query("SELECT epoch::text AS epoch FROM capybara.extension_grant_epoch WHERE id = 1");
|
|
73
|
+
const epoch = rows[0]?.epoch;
|
|
74
|
+
if (epoch === undefined)
|
|
75
|
+
throw new Error("The grant epoch row is missing");
|
|
76
|
+
return epoch;
|
|
77
|
+
},
|
|
78
|
+
close: async () => {
|
|
79
|
+
closed = true;
|
|
80
|
+
const closing = pool;
|
|
81
|
+
pool = undefined;
|
|
82
|
+
await closing?.end();
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
class EpochReadTimeout extends Error {
|
|
87
|
+
constructor() {
|
|
88
|
+
super("Reading the grant epoch timed out");
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
export class GrantEpoch {
|
|
92
|
+
options;
|
|
93
|
+
epoch;
|
|
94
|
+
/** Start time of the last successful read: the snapshot it saw is at least this old. */
|
|
95
|
+
readAt = Number.NEGATIVE_INFINITY;
|
|
96
|
+
reading;
|
|
97
|
+
pollTimer;
|
|
98
|
+
expiryTimer;
|
|
99
|
+
settleTimers = new Set();
|
|
100
|
+
running = false;
|
|
101
|
+
now;
|
|
102
|
+
pollMs;
|
|
103
|
+
readTimeoutMs;
|
|
104
|
+
/**
|
|
105
|
+
* Timers run in the context the epoch was built in (the host's construction), never in the
|
|
106
|
+
* context of the call that first started polling (its org scope or request log context).
|
|
107
|
+
*/
|
|
108
|
+
inOwnContext = AsyncLocalStorage.snapshot();
|
|
109
|
+
constructor(options) {
|
|
110
|
+
this.options = options;
|
|
111
|
+
this.now = options.now ?? (() => performance.now());
|
|
112
|
+
this.pollMs = options.pollMs ?? GRANT_EPOCH_POLL_MS;
|
|
113
|
+
if (options.maxAgeMs <= this.pollMs || options.maxAgeMs >= FENCE_DEADLINE_MS) {
|
|
114
|
+
throw new RangeError("The grant epoch age must exceed the poll interval and stay below the 4 s fence deadline");
|
|
115
|
+
}
|
|
116
|
+
this.readTimeoutMs = grantEpochReadTimeoutMs(options.maxAgeMs, this.pollMs);
|
|
117
|
+
}
|
|
118
|
+
/** Starts polling on this replica; idempotent. */
|
|
119
|
+
start() {
|
|
120
|
+
if (this.running)
|
|
121
|
+
return;
|
|
122
|
+
this.running = true;
|
|
123
|
+
this.poll();
|
|
124
|
+
}
|
|
125
|
+
stop() {
|
|
126
|
+
this.running = false;
|
|
127
|
+
clearTimeout(this.pollTimer);
|
|
128
|
+
clearTimeout(this.expiryTimer);
|
|
129
|
+
for (const timer of this.settleTimers)
|
|
130
|
+
clearTimeout(timer);
|
|
131
|
+
this.settleTimers.clear();
|
|
132
|
+
this.pollTimer = undefined;
|
|
133
|
+
this.expiryTimer = undefined;
|
|
134
|
+
}
|
|
135
|
+
/** The epoch when the last successful read is younger than `maxAgeMs`, otherwise undefined. */
|
|
136
|
+
fresh() {
|
|
137
|
+
return this.now() - this.readAt < this.options.maxAgeMs ? this.epoch : undefined;
|
|
138
|
+
}
|
|
139
|
+
/** The fresh epoch, reading PostgreSQL first when needed; undefined when that read fails. */
|
|
140
|
+
async ensureFresh() {
|
|
141
|
+
return this.fresh() ?? (await this.refresh());
|
|
142
|
+
}
|
|
143
|
+
/** One read at a time; concurrent callers share it. It settles within the read timeout. */
|
|
144
|
+
refresh() {
|
|
145
|
+
this.reading ??= this.readOnce().finally(() => {
|
|
146
|
+
this.reading = undefined;
|
|
147
|
+
});
|
|
148
|
+
return this.reading;
|
|
149
|
+
}
|
|
150
|
+
async readOnce() {
|
|
151
|
+
const startedAt = this.now();
|
|
152
|
+
let epoch;
|
|
153
|
+
try {
|
|
154
|
+
epoch = await this.withTimeout(this.options.read());
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
this.options.onFault?.(err);
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
const previous = this.epoch;
|
|
161
|
+
const previousReadAt = this.readAt;
|
|
162
|
+
this.epoch = epoch;
|
|
163
|
+
if (startedAt > this.readAt) {
|
|
164
|
+
this.readAt = startedAt;
|
|
165
|
+
this.armExpiry();
|
|
166
|
+
}
|
|
167
|
+
if (previous !== undefined && previous !== epoch) {
|
|
168
|
+
this.options.onChange(epoch);
|
|
169
|
+
this.armSettleDeadline(previousReadAt);
|
|
170
|
+
}
|
|
171
|
+
return this.fresh();
|
|
172
|
+
}
|
|
173
|
+
withTimeout(read) {
|
|
174
|
+
let timer;
|
|
175
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
176
|
+
timer = this.timer(() => reject(new EpochReadTimeout()), this.readTimeoutMs);
|
|
177
|
+
});
|
|
178
|
+
return Promise.race([read, timeout]).finally(() => clearTimeout(timer));
|
|
179
|
+
}
|
|
180
|
+
/** Fence everything at the revocation bound unless a later read succeeds first. */
|
|
181
|
+
armExpiry() {
|
|
182
|
+
if (!this.running)
|
|
183
|
+
return;
|
|
184
|
+
clearTimeout(this.expiryTimer);
|
|
185
|
+
const delay = Math.max(0, this.readAt + FENCE_DEADLINE_MS - this.now());
|
|
186
|
+
this.expiryTimer = this.timer(() => {
|
|
187
|
+
this.expiryTimer = undefined;
|
|
188
|
+
this.options.onExpired();
|
|
189
|
+
}, delay);
|
|
190
|
+
}
|
|
191
|
+
/** `oldEpochReadAt`: start of the last read that saw the old epoch, before the commit. */
|
|
192
|
+
armSettleDeadline(oldEpochReadAt) {
|
|
193
|
+
if (!this.running)
|
|
194
|
+
return;
|
|
195
|
+
const delay = Math.max(0, oldEpochReadAt + FENCE_DEADLINE_MS - this.now());
|
|
196
|
+
const timer = this.timer(() => {
|
|
197
|
+
this.settleTimers.delete(timer);
|
|
198
|
+
this.options.onSettleDeadline();
|
|
199
|
+
}, delay);
|
|
200
|
+
this.settleTimers.add(timer);
|
|
201
|
+
}
|
|
202
|
+
/** Polls on a fixed cadence; a slow read never delays the next tick (reads are coalesced). */
|
|
203
|
+
poll() {
|
|
204
|
+
if (!this.running)
|
|
205
|
+
return;
|
|
206
|
+
this.pollTimer = this.timer(() => this.poll(), this.pollMs);
|
|
207
|
+
void this.refresh();
|
|
208
|
+
}
|
|
209
|
+
timer(run, delay) {
|
|
210
|
+
const timer = setTimeout(() => this.inOwnContext(run), delay);
|
|
211
|
+
timer.unref?.();
|
|
212
|
+
return timer;
|
|
213
|
+
}
|
|
214
|
+
}
|