@capybara-hq/kernel 0.1.0-rc.130 → 0.1.0-rc.132
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/account-erasures.d.ts +37 -0
- package/dist/admin/account-erasures.js +119 -0
- package/dist/admin/admin.controller.d.ts +35 -2
- package/dist/admin/admin.controller.js +75 -18
- package/dist/admin/admin.module.js +10 -0
- package/dist/admin/admin.schemas.d.ts +51 -0
- package/dist/admin/admin.schemas.js +20 -0
- package/dist/admin/erasure-dispositions.d.ts +23 -0
- package/dist/admin/erasure-dispositions.js +76 -0
- package/dist/admin/health.service.d.ts +6 -0
- package/dist/admin/health.service.js +27 -1
- package/dist/admin/usage.service.d.ts +5 -0
- package/dist/admin/usage.service.js +21 -2
- package/dist/agents/agents.service.d.ts +1 -1
- package/dist/catalog/plugin-import.d.ts +3 -1
- package/dist/catalog/plugin-import.js +19 -15
- package/dist/channels/connections.service.d.ts +1 -1
- package/dist/client/client-reports.service.js +12 -0
- package/dist/config/schema.d.ts +9 -1
- package/dist/config/schema.js +51 -1
- package/dist/conversations/conversations.service.d.ts +9 -1
- package/dist/conversations/conversations.service.js +112 -15
- package/dist/conversations/event-log.d.ts +2 -0
- package/dist/conversations/event-log.js +77 -0
- package/dist/conversations/events.d.ts +11 -0
- package/dist/conversations/events.js +13 -1
- package/dist/conversations/prompt-suggestions.js +4 -0
- package/dist/conversations/titles.js +3 -2
- package/dist/ctx/create-ctx.d.ts +3 -2
- package/dist/ctx/create-ctx.js +10 -7
- package/dist/db/extension-db.d.ts +30 -0
- package/dist/db/extension-db.js +91 -0
- package/dist/db/extension-schema-transfer.d.ts +6 -0
- package/dist/db/extension-schema-transfer.js +141 -0
- package/dist/db/kernel-schema.d.ts +73 -12
- package/dist/db/migrator.d.ts +6 -0
- package/dist/db/migrator.js +39 -4
- package/dist/db/pool.d.ts +4 -0
- package/dist/db/pool.js +36 -1
- package/dist/devices/devices.service.d.ts +13 -1
- package/dist/devices/devices.service.js +122 -9
- package/dist/erasure/account-batches.d.ts +9 -0
- package/dist/erasure/account-batches.js +567 -0
- package/dist/erasure/account-files.d.ts +34 -0
- package/dist/erasure/account-files.js +217 -0
- package/dist/erasure/account-residual.d.ts +15 -0
- package/dist/erasure/account-residual.js +149 -0
- package/dist/erasure/account-worker.d.ts +32 -0
- package/dist/erasure/account-worker.js +392 -0
- package/dist/erasure/device-cleanup.d.ts +23 -0
- package/dist/erasure/device-cleanup.js +221 -0
- package/dist/erasure/erasure.module.d.ts +2 -0
- package/dist/{conversations/event-org-backfill.module.js → erasure/erasure.module.js} +6 -10
- package/dist/erasure/external-evidence.d.ts +4 -0
- package/dist/erasure/external-evidence.js +28 -0
- package/dist/erasure/jobs.d.ts +5 -0
- package/dist/erasure/jobs.js +20 -0
- package/dist/erasure/org-batches.d.ts +11 -0
- package/dist/erasure/org-batches.js +159 -0
- package/dist/erasure/org-catalog.d.ts +2 -0
- package/dist/erasure/org-catalog.js +34 -0
- package/dist/erasure/org-rules.d.ts +14 -0
- package/dist/erasure/org-rules.js +227 -0
- package/dist/erasure/org-worker.d.ts +38 -0
- package/dist/erasure/org-worker.js +501 -0
- package/dist/erasure/requests.d.ts +61 -0
- package/dist/erasure/requests.js +180 -0
- package/dist/erasure/sweep.job.d.ts +19 -0
- package/dist/erasure/sweep.job.js +130 -0
- package/dist/erasure/worker.d.ts +17 -0
- package/dist/erasure/worker.js +110 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.js +4 -0
- package/dist/evals/judge.d.ts +5 -0
- package/dist/evals/judge.js +16 -1
- package/dist/evals/run-replay.js +12 -1
- package/dist/evals/step-replay.d.ts +5 -3
- package/dist/evals/step-replay.js +9 -5
- package/dist/evals/worker.d.ts +2 -0
- package/dist/evals/worker.js +60 -16
- package/dist/extensions/admin-ops.d.ts +3 -1
- package/dist/extensions/admin-ops.js +11 -7
- package/dist/extensions/extensions.module.js +3 -0
- package/dist/extensions/host.d.ts +4 -1
- package/dist/extensions/host.js +29 -6
- package/dist/extensions/instance.d.ts +3 -0
- package/dist/extensions/instance.js +3 -1
- package/dist/extensions/migrate-lock.d.ts +4 -1
- package/dist/extensions/migrate-lock.js +19 -2
- package/dist/files/blob-objects.d.ts +7 -3
- package/dist/files/blob-objects.js +39 -22
- package/dist/files/blob-sweep.job.d.ts +11 -0
- package/dist/files/blob-sweep.job.js +67 -6
- package/dist/http/api.module.js +5 -1
- package/dist/identity/accounts.js +3 -0
- package/dist/identity/api-tokens.js +5 -0
- package/dist/identity/auth.guard.d.ts +1 -0
- package/dist/identity/auth.guard.js +1 -0
- package/dist/identity/erasure-admission.d.ts +3 -0
- package/dist/identity/erasure-admission.js +14 -0
- package/dist/identity/external.js +5 -0
- package/dist/identity/sessions.js +5 -0
- package/dist/identity/settings.d.ts +86 -1
- package/dist/identity/settings.js +38 -4
- package/dist/infra/config/kernel-config.service.js +1 -0
- package/dist/infra/metrics/kernel-metrics.d.ts +18 -0
- package/dist/infra/metrics/kernel-metrics.js +54 -0
- package/dist/infra/metrics/operational-metrics.d.ts +31 -0
- package/dist/infra/metrics/operational-metrics.js +188 -0
- package/dist/infra/outbox/registry.d.ts +23 -14
- package/dist/infra/outbox/registry.js +12 -15
- package/dist/infra/throttler/credential-throttler.js +8 -1
- package/dist/infra/throttler/named-throttlers.d.ts +6 -0
- package/dist/infra/throttler/named-throttlers.js +6 -0
- package/dist/infra/throttler/principal-throttler.guard.d.ts +10 -0
- package/dist/infra/throttler/principal-throttler.guard.js +50 -0
- package/dist/infra/throttler/redis-throttler-storage.d.ts +1 -0
- package/dist/infra/throttler/redis-throttler-storage.js +27 -5
- package/dist/infra/throttler/throttler.guard.d.ts +2 -3
- package/dist/infra/throttler/throttler.guard.js +2 -3
- package/dist/infra/throttler/throttler.module.js +3 -2
- package/dist/kernel.js +4 -0
- package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
- package/dist/lifecycle/kernel-lifecycle.js +26 -21
- package/dist/models/budget-admission.d.ts +31 -0
- package/dist/models/budget-admission.js +149 -0
- package/dist/models/budget-counters.d.ts +28 -0
- package/dist/models/budget-counters.js +117 -0
- package/dist/models/budget-policy.d.ts +88 -0
- package/dist/models/budget-policy.js +78 -0
- package/dist/models/embeddings.js +13 -2
- package/dist/models/images.js +12 -2
- package/dist/models/purposes.d.ts +5 -2
- package/dist/models/purposes.js +9 -5
- package/dist/orgs/invitations.service.d.ts +1 -1
- package/dist/orgs/members.service.d.ts +28 -1
- package/dist/orgs/members.service.js +74 -11
- package/dist/orgs/offboarding.js +4 -6
- package/dist/orgs/org-owner.d.ts +2 -0
- package/dist/orgs/org-owner.js +21 -6
- package/dist/orgs/orgs.controller.d.ts +22 -0
- package/dist/orgs/orgs.controller.js +24 -0
- package/dist/orgs/orgs.module.js +4 -0
- package/dist/orgs/orgs.schemas.js +7 -0
- package/dist/orgs/orgs.service.d.ts +5 -1
- package/dist/orgs/orgs.service.js +28 -3
- package/dist/orgs/settings.controller.js +6 -1
- package/dist/orgs/settings.service.d.ts +58 -1
- package/dist/orgs/settings.service.js +74 -9
- package/dist/platform/exclusions.js +20 -1
- package/dist/platform/ops/accounts.ops.js +58 -1
- package/dist/platform/ops/admin.ops.js +13 -5
- package/dist/platform/ops/org-settings.ops.js +11 -4
- package/dist/platform/ops/orgs.ops.js +28 -0
- package/dist/platform/ops/retention.d.ts +16 -0
- package/dist/platform/ops/retention.js +21 -0
- package/dist/retention/jobs.d.ts +21 -0
- package/dist/retention/jobs.js +48 -0
- package/dist/retention/policy.d.ts +70 -0
- package/dist/retention/policy.js +103 -0
- package/dist/retention/purge-batch.d.ts +17 -0
- package/dist/retention/purge-batch.js +355 -0
- package/dist/retention/report-obligations.d.ts +12 -0
- package/dist/retention/report-obligations.js +71 -0
- package/dist/retention/sweep.job.d.ts +17 -0
- package/dist/retention/sweep.job.js +95 -0
- package/dist/retention/worker.d.ts +29 -0
- package/dist/retention/worker.js +306 -0
- package/dist/roles/worker.module.js +12 -8
- package/dist/runtime/maintenance.d.ts +5 -3
- package/dist/runtime/maintenance.js +19 -12
- package/dist/runtime/model-call.d.ts +3 -1
- package/dist/runtime/model-call.js +25 -3
- package/dist/runtime/providers.d.ts +7 -2
- package/dist/runtime/providers.js +76 -10
- package/dist/runtime/quota.d.ts +12 -12
- package/dist/runtime/quota.js +42 -37
- package/dist/runtime/run-finish.js +2 -0
- package/dist/runtime/run-principal.d.ts +9 -0
- package/dist/runtime/run-principal.js +18 -0
- package/dist/runtime/run-worker.js +48 -10
- package/dist/runtime/usage-report-jobs.d.ts +4 -1
- package/dist/runtime/usage-report-jobs.js +36 -13
- package/dist/runtime/usage-report.d.ts +5 -3
- package/dist/runtime/usage-report.js +37 -19
- package/dist/sandbox/review/classifier.d.ts +2 -2
- package/dist/sandbox/review/classifier.js +6 -2
- package/dist/sandbox/sandbox.service.js +18 -7
- package/dist/storage/purge.js +5 -1
- package/dist/storage/storage.service.d.ts +17 -1
- package/dist/storage/storage.service.js +75 -4
- package/dist/tools/builtins/vision/read-image.js +3 -0
- package/dist/tools/builtins/web/extract.js +3 -0
- package/dist/tools/pipeline.js +5 -1
- package/package.json +3 -1
- package/src/migrations/0216_model_budget_counters.sql +24 -0
- package/src/migrations/0217_retention.sql +44 -0
- package/src/migrations/0218_data_erasure.sql +41 -0
- package/src/migrations/0219_event_org_constraint_check.sql +29 -0
- package/src/migrations/0220_require_event_org.sql +18 -0
- package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
- package/dist/conversations/event-org-backfill.d.ts +0 -111
- package/dist/conversations/event-org-backfill.js +0 -264
- package/dist/conversations/event-org-backfill.module.d.ts +0 -3
|
@@ -8,18 +8,22 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
8
8
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
9
|
};
|
|
10
10
|
import { EXTENSION_NAME_RE, narrowerProjectReach } from "@capybara-hq/plugin-sdk";
|
|
11
|
-
import { Inject, Injectable } from "@nestjs/common";
|
|
11
|
+
import { Inject, Injectable, Optional } from "@nestjs/common";
|
|
12
12
|
import { z } from "zod";
|
|
13
13
|
import { applyPlatformAttributionPatch, PLATFORM_ATTRIBUTION_FIELDS, PLATFORM_ATTRIBUTION_PATCH, PLATFORM_ATTRIBUTION_SETTING, readStoredPlatformAttribution, resolvePlatformAttribution, } from "../attribution/platform-attribution.js";
|
|
14
14
|
import { productName } from "../config/product-name.js";
|
|
15
15
|
import { DEVICES_DEFAULT_PROVIDER_PATCH, DEVICES_DEFAULT_PROVIDER_SETTING, readPlatformDefaultProvider, } from "../devices/default-provider-setting.js";
|
|
16
16
|
import { ApiError } from "../errors.js";
|
|
17
|
+
import { CacheService } from "../infra/cache/cache.service.js";
|
|
17
18
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
19
|
+
import { afterCommit } from "../infra/database/after-commit.js";
|
|
18
20
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
19
21
|
import { TransactionHost, withOrderedLocks } from "../infra/database/transaction-host.js";
|
|
20
22
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
21
23
|
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
24
|
+
import { PLATFORM_MODEL_BUDGET_CACHE_KEY, PlatformModelBudgetsSchema, } from "../models/budget-policy.js";
|
|
22
25
|
import { DEFAULT_PRICE_CURRENCY, PriceCurrency } from "../models/price-snapshot.js";
|
|
26
|
+
import { confirmRetentionChange, OFF_RETENTION, PlatformRetentionSchema, platformRetentionRow, StoredPlatformRetentionSchema, } from "../retention/policy.js";
|
|
23
27
|
import { applyDevicesNetworkPatch, applyDevicesOutsideSandboxPatch, configuredDeviceSandbox, DEVICES_ALLOWED_PROFILES_PATCH, DEVICES_ALLOWED_PROFILES_SETTING, DEVICES_NETWORK_PATCH, DEVICES_NETWORK_SETTING, DEVICES_OUTSIDE_SANDBOX_PATCH, DEVICES_OUTSIDE_SANDBOX_SETTING, DEVICES_PROJECT_REACH_PATCH, DEVICES_PROJECT_REACH_SETTING, orgDeviceSandboxOf, readDeviceSandboxSettingsView, readStoredDeviceSandbox, resolveDeviceSandboxSettings, } from "../sandbox/device-sandbox-settings.js";
|
|
24
28
|
import { devicesFollowingDefault, needsFullCeiling, needsOpenNetwork, PermissionCeilingWrites, reachNarrowed, } from "../sandbox/permission-ceiling-writes.js";
|
|
25
29
|
import { EXTERNAL_SHARING_SETTING, ExternalSharingValue, HTML_CDN_ALLOWLIST_DEFAULT, HtmlCdnAllowlistSchema, readExternalSharing, readHtmlCdnAllowlist, readShareMaxExpiry, SHARE_MAX_EXPIRY_DEFAULT, SHARE_MAX_EXPIRY_SETTING, ShareMaxExpiryDays, } from "../shares/settings.js";
|
|
@@ -202,7 +206,9 @@ export const DEPLOYMENT_SETTINGS = z.object({
|
|
|
202
206
|
orgCreation: z.enum(["anyone", "super_admin"]).default("anyone"),
|
|
203
207
|
/** 按组织覆盖运行并发上限(orgId → 上限);未列出的组织用 `runtime.orgConcurrency`。 */
|
|
204
208
|
runConcurrencyOverrides: z.record(z.string().min(1), z.number().int().positive()).default({}),
|
|
205
|
-
|
|
209
|
+
retention: StoredPlatformRetentionSchema.default(OFF_RETENTION),
|
|
210
|
+
modelBudgets: PlatformModelBudgetsSchema.default({}),
|
|
211
|
+
/** The currency of model prices used for cost estimates, without conversion. */
|
|
206
212
|
priceCurrency: PriceCurrency.default(DEFAULT_PRICE_CURRENCY),
|
|
207
213
|
/** 按组织覆盖沙箱 cpu / 内存(orgId → 覆盖,C19);只对之后新建的沙箱生效。组织管理员只读。 */
|
|
208
214
|
sandboxLimitOverrides: z.record(z.string().min(1), SANDBOX_LIMIT_OVERRIDE).default({}),
|
|
@@ -288,6 +294,9 @@ export const DEPLOYMENT_SETTINGS_PATCH = z
|
|
|
288
294
|
runConcurrencyOverrides: z
|
|
289
295
|
.record(z.string().min(1), z.number().int().positive().nullable())
|
|
290
296
|
.optional(),
|
|
297
|
+
retention: PlatformRetentionSchema.partial().optional(),
|
|
298
|
+
confirmRetentionShortening: z.literal(true).optional(),
|
|
299
|
+
modelBudgets: PlatformModelBudgetsSchema.nullable().optional(),
|
|
291
300
|
priceCurrency: PriceCurrency.optional(),
|
|
292
301
|
sandboxLimitOverrides: z
|
|
293
302
|
.record(z.string().min(1), SANDBOX_LIMIT_OVERRIDE.nullable())
|
|
@@ -552,15 +561,17 @@ let SettingsService = class SettingsService {
|
|
|
552
561
|
log;
|
|
553
562
|
config;
|
|
554
563
|
ceilings;
|
|
564
|
+
budgetCache;
|
|
555
565
|
constructor(db, txHost, adminLock, log,
|
|
556
566
|
/** The startup config's `devices.outsideSandbox` / `devices.network.*`, which win over the stored choice. */
|
|
557
|
-
config, ceilings) {
|
|
567
|
+
config, ceilings, budgetCache) {
|
|
558
568
|
this.db = db;
|
|
559
569
|
this.txHost = txHost;
|
|
560
570
|
this.adminLock = adminLock;
|
|
561
571
|
this.log = log;
|
|
562
572
|
this.config = config;
|
|
563
573
|
this.ceilings = ceilings;
|
|
574
|
+
this.budgetCache = budgetCache;
|
|
564
575
|
}
|
|
565
576
|
/** The settings with the platform's device sandbox settings and attribution defaults in effect. */
|
|
566
577
|
async view() {
|
|
@@ -848,6 +859,8 @@ let SettingsService = class SettingsService {
|
|
|
848
859
|
patch.devicesAllowedProfiles !== undefined ||
|
|
849
860
|
patch.devicesProjectReach !== undefined)
|
|
850
861
|
await this.ceilings.lock({}, "platform");
|
|
862
|
+
if (patch.retention !== undefined)
|
|
863
|
+
await platformRetentionRow(this.db.db, "update");
|
|
851
864
|
}
|
|
852
865
|
async write(patch, actorAccountId, actorTokenId, auditDetail, opts) {
|
|
853
866
|
// held since the prelude (`lockFor`); naming them again re-checks the actor
|
|
@@ -855,6 +868,17 @@ let SettingsService = class SettingsService {
|
|
|
855
868
|
// The super admin lock serializes every settings write: the current overrides are read
|
|
856
869
|
// and merged under it, so no concurrent change is lost
|
|
857
870
|
const next = {};
|
|
871
|
+
let retentionAudit = {};
|
|
872
|
+
if (patch.retention !== undefined) {
|
|
873
|
+
const raw = await platformRetentionRow(this.db.db);
|
|
874
|
+
const stored = StoredPlatformRetentionSchema.safeParse(raw?.value);
|
|
875
|
+
const before = stored.success ? stored.data : OFF_RETENTION;
|
|
876
|
+
const after = PlatformRetentionSchema.parse({ ...before, ...patch.retention });
|
|
877
|
+
retentionAudit = confirmRetentionChange(before, after, patch.confirmRetentionShortening === true &&
|
|
878
|
+
!opts.onlyNarrows &&
|
|
879
|
+
actorTokenId === undefined, !stored.success);
|
|
880
|
+
next.retention = after;
|
|
881
|
+
}
|
|
858
882
|
if (patch.orgCreation !== undefined)
|
|
859
883
|
next.orgCreation = patch.orgCreation;
|
|
860
884
|
if (patch.priceCurrency !== undefined)
|
|
@@ -1013,6 +1037,13 @@ let SettingsService = class SettingsService {
|
|
|
1013
1037
|
else
|
|
1014
1038
|
writes.push([DEVICES_DEFAULT_PROVIDER_SETTING, patch.devicesDefaultProvider]);
|
|
1015
1039
|
}
|
|
1040
|
+
if (patch.modelBudgets !== undefined) {
|
|
1041
|
+
afterCommit(() => this.budgetCache?.del(PLATFORM_MODEL_BUDGET_CACHE_KEY));
|
|
1042
|
+
}
|
|
1043
|
+
if (patch.modelBudgets === null)
|
|
1044
|
+
deletes.push("modelBudgets");
|
|
1045
|
+
else if (patch.modelBudgets !== undefined)
|
|
1046
|
+
writes.push(["modelBudgets", patch.modelBudgets]);
|
|
1016
1047
|
if (patch.promptSuggestions === null)
|
|
1017
1048
|
deletes.push(PROMPT_SUGGESTIONS_SETTING);
|
|
1018
1049
|
else if (patch.promptSuggestions !== undefined) {
|
|
@@ -1039,6 +1070,7 @@ let SettingsService = class SettingsService {
|
|
|
1039
1070
|
action: "deployment.settings.updated",
|
|
1040
1071
|
detail: {
|
|
1041
1072
|
...patch,
|
|
1073
|
+
...retentionAudit,
|
|
1042
1074
|
...(deviceSandboxChange !== undefined && { deviceSandboxEffective: deviceSandboxChange }),
|
|
1043
1075
|
...auditDetail,
|
|
1044
1076
|
},
|
|
@@ -1061,6 +1093,8 @@ SettingsService = __decorate([
|
|
|
1061
1093
|
__param(2, Inject(SuperAdminLock)),
|
|
1062
1094
|
__param(3, Inject(KERNEL_LOGGER)),
|
|
1063
1095
|
__param(4, Inject(KernelConfigService)),
|
|
1064
|
-
__param(5, Inject(PermissionCeilingWrites))
|
|
1096
|
+
__param(5, Inject(PermissionCeilingWrites)),
|
|
1097
|
+
__param(6, Optional()),
|
|
1098
|
+
__param(6, Inject(CacheService))
|
|
1065
1099
|
], SettingsService);
|
|
1066
1100
|
export { SettingsService };
|
|
@@ -68,6 +68,7 @@ const HOT_APPLIERS = {
|
|
|
68
68
|
"subagents.maxDepth": () => { },
|
|
69
69
|
"subagents.maxConcurrentPerConversation": () => { },
|
|
70
70
|
"subagents.maxDispatchesPerRun": () => { },
|
|
71
|
+
"runtime.memberRunConcurrency": () => { },
|
|
71
72
|
"subagents.maxTokensPerRun": () => { },
|
|
72
73
|
// The web tools read these limits through the config service on every call.
|
|
73
74
|
"web.search.maxResults": () => { },
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { UsagePurpose } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { type Meter } from "@opentelemetry/api";
|
|
3
|
+
export declare const KERNEL_METER = "capybara.kernel";
|
|
4
|
+
export declare const kernelMeter: () => Meter;
|
|
5
|
+
type Purpose = UsagePurpose | "eval";
|
|
6
|
+
type ModelKind = "chat" | "embedding" | "image_generation";
|
|
7
|
+
type AttemptOutcome = "completed" | "failed" | "aborted";
|
|
8
|
+
type TokenUsage = {
|
|
9
|
+
inputTokens: number;
|
|
10
|
+
outputTokens?: number;
|
|
11
|
+
cacheReadTokens?: number;
|
|
12
|
+
cacheWriteTokens?: number;
|
|
13
|
+
};
|
|
14
|
+
export declare function recordRun(outcome: "started" | "completed" | "failed" | "aborted"): void;
|
|
15
|
+
export declare function recordModelAttempt(kind: ModelKind, purpose: Purpose, elapsedSeconds: number, outcome: AttemptOutcome): void;
|
|
16
|
+
export declare function recordModelTokens(kind: ModelKind, purpose: Purpose, usage: TokenUsage | undefined): void;
|
|
17
|
+
export declare function recordThrottle(policy: "default" | "route" | "credential", outcome: "allowed" | "limited" | "unavailable"): void;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { metrics } from "@opentelemetry/api";
|
|
2
|
+
export const KERNEL_METER = "capybara.kernel";
|
|
3
|
+
export const kernelMeter = () => metrics.getMeter(KERNEL_METER);
|
|
4
|
+
function instruments(meter) {
|
|
5
|
+
return {
|
|
6
|
+
runs: meter.createCounter("capybara.run.transitions", {
|
|
7
|
+
description: "Committed run starts and terminal outcomes",
|
|
8
|
+
unit: "{run}",
|
|
9
|
+
}),
|
|
10
|
+
tokens: meter.createCounter("capybara.model.tokens", {
|
|
11
|
+
description: "Tokens reported by model provider attempts",
|
|
12
|
+
unit: "{token}",
|
|
13
|
+
}),
|
|
14
|
+
duration: meter.createHistogram("capybara.model.attempt.duration", {
|
|
15
|
+
description: "Time spent in one admitted model provider attempt",
|
|
16
|
+
unit: "s",
|
|
17
|
+
}),
|
|
18
|
+
throttles: meter.createCounter("capybara.http.throttle", {
|
|
19
|
+
description: "HTTP throttler decisions by policy",
|
|
20
|
+
unit: "{decision}",
|
|
21
|
+
}),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
let cached;
|
|
25
|
+
function counters() {
|
|
26
|
+
const meter = kernelMeter();
|
|
27
|
+
if (cached?.meter !== meter)
|
|
28
|
+
cached = { meter, instruments: instruments(meter) };
|
|
29
|
+
return cached.instruments;
|
|
30
|
+
}
|
|
31
|
+
export function recordRun(outcome) {
|
|
32
|
+
counters().runs.add(1, { outcome });
|
|
33
|
+
}
|
|
34
|
+
export function recordModelAttempt(kind, purpose, elapsedSeconds, outcome) {
|
|
35
|
+
counters().duration.record(elapsedSeconds, { kind, purpose, outcome });
|
|
36
|
+
}
|
|
37
|
+
export function recordModelTokens(kind, purpose, usage) {
|
|
38
|
+
if (typeof usage !== "object" || usage === null)
|
|
39
|
+
return;
|
|
40
|
+
const counts = {
|
|
41
|
+
input: usage.inputTokens,
|
|
42
|
+
output: usage.outputTokens,
|
|
43
|
+
cache_read: usage.cacheReadTokens,
|
|
44
|
+
cache_write: usage.cacheWriteTokens,
|
|
45
|
+
};
|
|
46
|
+
for (const [token_class, count] of Object.entries(counts)) {
|
|
47
|
+
if (typeof count === "number" && Number.isSafeInteger(count) && count > 0) {
|
|
48
|
+
counters().tokens.add(count, { kind, purpose, token_class });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function recordThrottle(policy, outcome) {
|
|
53
|
+
counters().throttles.add(1, { policy, outcome });
|
|
54
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type OnModuleDestroy, type OnModuleInit } from "@nestjs/common";
|
|
2
|
+
import { DiscoveryService } from "@nestjs/core";
|
|
3
|
+
import type { Redis } from "ioredis";
|
|
4
|
+
import type { KernelLogger } from "../../log.js";
|
|
5
|
+
import { KernelConfigService } from "../config/kernel-config.service.js";
|
|
6
|
+
import { KernelDb } from "../database/kernel-db.js";
|
|
7
|
+
import { TransactionHost } from "../database/transaction-host.js";
|
|
8
|
+
import { LockService } from "../lock/lock.service.js";
|
|
9
|
+
export declare const METRICS_SAMPLE_INTERVAL_MS = 30000;
|
|
10
|
+
export declare const operationalMetricsEnabled: () => boolean;
|
|
11
|
+
/** Each collection uses the most recent successful local read, with no backend calls on export. */
|
|
12
|
+
export declare class OperationalMetricsSampler implements OnModuleInit, OnModuleDestroy {
|
|
13
|
+
private readonly discovery;
|
|
14
|
+
private readonly redis;
|
|
15
|
+
private readonly db;
|
|
16
|
+
readonly txHost: TransactionHost;
|
|
17
|
+
readonly lockService: LockService;
|
|
18
|
+
readonly config: KernelConfigService;
|
|
19
|
+
readonly log: KernelLogger;
|
|
20
|
+
private readonly depths;
|
|
21
|
+
private readonly outbox;
|
|
22
|
+
private detach?;
|
|
23
|
+
constructor(discovery: DiscoveryService, redis: Redis, db: KernelDb, txHost: TransactionHost, lockService: LockService, config: KernelConfigService, log: KernelLogger);
|
|
24
|
+
onModuleInit(): void;
|
|
25
|
+
onModuleDestroy(): void;
|
|
26
|
+
run(signal?: AbortSignal): Promise<void>;
|
|
27
|
+
collectSamples(signal?: AbortSignal): Promise<void>;
|
|
28
|
+
private sample;
|
|
29
|
+
private readQueues;
|
|
30
|
+
private readOutbox;
|
|
31
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
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 { DiscoveryService } from "@nestjs/core";
|
|
12
|
+
import { createNoopMeter } from "@opentelemetry/api";
|
|
13
|
+
import { Queue } from "bullmq";
|
|
14
|
+
import { sql } from "kysely";
|
|
15
|
+
import { waitWithin } from "../close-within.js";
|
|
16
|
+
import { KernelConfigService } from "../config/kernel-config.service.js";
|
|
17
|
+
import { KernelDb } from "../database/kernel-db.js";
|
|
18
|
+
import { asPlatform } from "../database/org-scope.js";
|
|
19
|
+
import { TransactionHost } from "../database/transaction-host.js";
|
|
20
|
+
import { Transactional } from "../database/transactional.decorator.js";
|
|
21
|
+
import { LockService } from "../lock/lock.service.js";
|
|
22
|
+
import { KERNEL_QUEUES } from "../queue/queue-names.js";
|
|
23
|
+
import { LockedInterval } from "../schedule/locked-interval.js";
|
|
24
|
+
import { KERNEL_LOGGER, REDIS } from "../tokens.js";
|
|
25
|
+
import { kernelMeter } from "./kernel-metrics.js";
|
|
26
|
+
export const METRICS_SAMPLE_INTERVAL_MS = 30_000;
|
|
27
|
+
const SAMPLE_FRESH_MS = 90_000;
|
|
28
|
+
const SAMPLE_TIMEOUT_MS = 2_000;
|
|
29
|
+
const QUEUE_STATES = ["waiting", "active", "delayed", "failed"];
|
|
30
|
+
export const operationalMetricsEnabled = () => kernelMeter() !== createNoopMeter();
|
|
31
|
+
function fresh(sample, now) {
|
|
32
|
+
return sample.latest && now - sample.latest.at < SAMPLE_FRESH_MS
|
|
33
|
+
? sample.latest.value
|
|
34
|
+
: undefined;
|
|
35
|
+
}
|
|
36
|
+
/** Each collection uses the most recent successful local read, with no backend calls on export. */
|
|
37
|
+
let OperationalMetricsSampler = class OperationalMetricsSampler {
|
|
38
|
+
discovery;
|
|
39
|
+
redis;
|
|
40
|
+
db;
|
|
41
|
+
txHost;
|
|
42
|
+
lockService;
|
|
43
|
+
config;
|
|
44
|
+
log;
|
|
45
|
+
depths = { latest: undefined, reading: false };
|
|
46
|
+
outbox = { latest: undefined, reading: false };
|
|
47
|
+
detach;
|
|
48
|
+
constructor(discovery, redis, db, txHost, lockService, config, log) {
|
|
49
|
+
this.discovery = discovery;
|
|
50
|
+
this.redis = redis;
|
|
51
|
+
this.db = db;
|
|
52
|
+
this.txHost = txHost;
|
|
53
|
+
this.lockService = lockService;
|
|
54
|
+
this.config = config;
|
|
55
|
+
this.log = log;
|
|
56
|
+
}
|
|
57
|
+
onModuleInit() {
|
|
58
|
+
const meter = kernelMeter();
|
|
59
|
+
const depth = meter.createObservableGauge("capybara.queue.depth", { unit: "{job}" });
|
|
60
|
+
const oldest = meter.createObservableGauge("capybara.outbox.oldest_due.age", { unit: "s" });
|
|
61
|
+
const dead = meter.createObservableGauge("capybara.outbox.dead", { unit: "{row}" });
|
|
62
|
+
const available = meter.createObservableGauge("capybara.operations.sample.fresh", {
|
|
63
|
+
description: "Whether the sampled source has a recent successful measurement",
|
|
64
|
+
unit: "1",
|
|
65
|
+
});
|
|
66
|
+
const observe = (result) => {
|
|
67
|
+
const now = Date.now();
|
|
68
|
+
const queues = fresh(this.depths, now);
|
|
69
|
+
const outbox = fresh(this.outbox, now);
|
|
70
|
+
// Cumulative readers can repeat a previous gauge point even if it is not observed again.
|
|
71
|
+
// Publish validity on every collection so a repeated value never looks like a fresh sample.
|
|
72
|
+
result.observe(available, queues ? 1 : 0, { source: "queue" });
|
|
73
|
+
result.observe(available, outbox ? 1 : 0, { source: "outbox" });
|
|
74
|
+
for (const { queue, counts } of queues ?? []) {
|
|
75
|
+
for (const state of QUEUE_STATES)
|
|
76
|
+
result.observe(depth, counts[state], { queue, state });
|
|
77
|
+
}
|
|
78
|
+
if (outbox) {
|
|
79
|
+
result.observe(oldest, outbox.oldest_due_seconds);
|
|
80
|
+
result.observe(dead, outbox.dead_count);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
const gauges = [depth, oldest, dead, available];
|
|
84
|
+
meter.addBatchObservableCallback(observe, gauges);
|
|
85
|
+
this.detach = () => meter.removeBatchObservableCallback(observe, gauges);
|
|
86
|
+
}
|
|
87
|
+
onModuleDestroy() {
|
|
88
|
+
this.detach?.();
|
|
89
|
+
}
|
|
90
|
+
run(signal) {
|
|
91
|
+
return this.collectSamples(signal);
|
|
92
|
+
}
|
|
93
|
+
async collectSamples(signal) {
|
|
94
|
+
await Promise.all([
|
|
95
|
+
this.sample(this.depths, "queue", () => this.readQueues(), signal),
|
|
96
|
+
this.sample(this.outbox, "outbox", () => this.readOutbox(), signal),
|
|
97
|
+
]);
|
|
98
|
+
}
|
|
99
|
+
async sample(state, source, read, signal) {
|
|
100
|
+
if (state.reading || signal?.aborted)
|
|
101
|
+
return;
|
|
102
|
+
state.reading = true;
|
|
103
|
+
const at = Date.now();
|
|
104
|
+
let value;
|
|
105
|
+
const pending = read()
|
|
106
|
+
.then((sample) => {
|
|
107
|
+
value = sample;
|
|
108
|
+
})
|
|
109
|
+
.finally(() => {
|
|
110
|
+
state.reading = false;
|
|
111
|
+
});
|
|
112
|
+
try {
|
|
113
|
+
if (!(await waitWithin(pending, SAMPLE_TIMEOUT_MS)))
|
|
114
|
+
throw new Error("Sample timed out");
|
|
115
|
+
if (!signal?.aborted && value !== undefined)
|
|
116
|
+
state.latest = { at, value };
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
state.latest = undefined;
|
|
120
|
+
this.log.warn("operational metrics sample unavailable", { source });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
async readQueues() {
|
|
124
|
+
if (this.redis.status !== "ready")
|
|
125
|
+
throw new Error("Redis is unavailable");
|
|
126
|
+
const queues = new Map();
|
|
127
|
+
for (const { instance } of this.discovery.getProviders()) {
|
|
128
|
+
if (instance instanceof Queue)
|
|
129
|
+
queues.set(instance.name, instance);
|
|
130
|
+
}
|
|
131
|
+
return Promise.all(KERNEL_QUEUES.flatMap((name) => {
|
|
132
|
+
const queue = queues.get(name);
|
|
133
|
+
if (!queue)
|
|
134
|
+
return [];
|
|
135
|
+
return [
|
|
136
|
+
(async () => {
|
|
137
|
+
if ((await queue.getBackend().client).status !== "ready") {
|
|
138
|
+
throw new Error("Queue connection is unavailable");
|
|
139
|
+
}
|
|
140
|
+
const counts = await queue.getJobCounts("wait", "prioritized", "active", "delayed", "failed");
|
|
141
|
+
return {
|
|
142
|
+
queue: name,
|
|
143
|
+
counts: {
|
|
144
|
+
waiting: (counts.wait ?? 0) + (counts.prioritized ?? 0),
|
|
145
|
+
active: counts.active ?? 0,
|
|
146
|
+
delayed: counts.delayed ?? 0,
|
|
147
|
+
failed: counts.failed ?? 0,
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
})(),
|
|
151
|
+
];
|
|
152
|
+
}));
|
|
153
|
+
}
|
|
154
|
+
async readOutbox() {
|
|
155
|
+
await sql `SET LOCAL statement_timeout = '1500ms'`.execute(this.db.db);
|
|
156
|
+
// org-filter: deployment-wide outbox lag and dead count without org labels
|
|
157
|
+
return asPlatform("sample outbox health across the deployment", async () => {
|
|
158
|
+
const facts = await sql `
|
|
159
|
+
SELECT
|
|
160
|
+
coalesce(extract(epoch FROM statement_timestamp() -
|
|
161
|
+
min(greatest(next_attempt_at, run_at)) FILTER (
|
|
162
|
+
WHERE dead_at IS NULL AND next_attempt_at <= statement_timestamp()
|
|
163
|
+
AND (run_at IS NULL OR run_at <= statement_timestamp())
|
|
164
|
+
)), 0)::float8 AS oldest_due_seconds,
|
|
165
|
+
count(*) FILTER (WHERE dead_at IS NOT NULL)::float8 AS dead_count
|
|
166
|
+
FROM capybara.outbox
|
|
167
|
+
`.execute(this.db.db);
|
|
168
|
+
return facts.rows[0];
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
__decorate([
|
|
173
|
+
LockedInterval("operational-metrics", () => METRICS_SAMPLE_INTERVAL_MS, { runOnStart: true })
|
|
174
|
+
], OperationalMetricsSampler.prototype, "run", null);
|
|
175
|
+
__decorate([
|
|
176
|
+
Transactional()
|
|
177
|
+
], OperationalMetricsSampler.prototype, "readOutbox", null);
|
|
178
|
+
OperationalMetricsSampler = __decorate([
|
|
179
|
+
Injectable(),
|
|
180
|
+
__param(0, Inject(DiscoveryService)),
|
|
181
|
+
__param(1, Inject(REDIS)),
|
|
182
|
+
__param(2, Inject(KernelDb)),
|
|
183
|
+
__param(3, Inject(TransactionHost)),
|
|
184
|
+
__param(4, Inject(LockService)),
|
|
185
|
+
__param(5, Inject(KernelConfigService)),
|
|
186
|
+
__param(6, Inject(KERNEL_LOGGER))
|
|
187
|
+
], OperationalMetricsSampler);
|
|
188
|
+
export { OperationalMetricsSampler };
|
|
@@ -19,6 +19,29 @@ export interface OutboxJobSpec {
|
|
|
19
19
|
* name without one does not type-check as an `OutboxJobName` (`add` does not check it at runtime).
|
|
20
20
|
*/
|
|
21
21
|
export declare const OUTBOX_JOBS: {
|
|
22
|
+
readonly "data-erasure": {
|
|
23
|
+
readonly queue: "cap-kernel-maintenance";
|
|
24
|
+
readonly idempotent: "Each generation claims the durable request under a row lock. Stale and completed deliveries do nothing.";
|
|
25
|
+
readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
|
|
26
|
+
readonly opts: {
|
|
27
|
+
readonly attempts: 1;
|
|
28
|
+
readonly removeOnComplete: true;
|
|
29
|
+
readonly removeOnFail: true;
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
readonly "retention-batch": {
|
|
33
|
+
readonly queue: "cap-kernel-maintenance";
|
|
34
|
+
readonly idempotent: "Locks the work row and checks the queued generation before committing one batch and its continuation";
|
|
35
|
+
readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
|
|
36
|
+
readonly opts: {
|
|
37
|
+
readonly attempts: 5;
|
|
38
|
+
readonly backoff: {
|
|
39
|
+
readonly type: "exponential";
|
|
40
|
+
readonly delay: 5000;
|
|
41
|
+
};
|
|
42
|
+
readonly removeOnComplete: true;
|
|
43
|
+
};
|
|
44
|
+
};
|
|
22
45
|
readonly "trigger-dispatch": {
|
|
23
46
|
readonly queue: "cap-kernel-maintenance";
|
|
24
47
|
readonly idempotent: "Dispatches one stored event by id; the dispatcher reads the event's state and delivers each automation at most once (deliveries keyed by automation and event)";
|
|
@@ -88,20 +111,6 @@ export declare const OUTBOX_JOBS: {
|
|
|
88
111
|
readonly removeOnFail: true;
|
|
89
112
|
};
|
|
90
113
|
};
|
|
91
|
-
readonly "conversation-events-org-backfill": {
|
|
92
|
-
readonly queue: "cap-kernel-maintenance";
|
|
93
|
-
readonly idempotent: "Locks up to 5,000 NULL org_id rows after its (conversation_id, seq) cursor with FOR UPDATE SKIP LOCKED and fills each from its conversation's org_id; rows already filled are skipped and the next batch is owed atomically under a deterministic cursor job id";
|
|
94
|
-
readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
|
|
95
|
-
readonly opts: {
|
|
96
|
-
readonly attempts: 5;
|
|
97
|
-
readonly backoff: {
|
|
98
|
-
readonly type: "exponential";
|
|
99
|
-
readonly delay: 5000;
|
|
100
|
-
};
|
|
101
|
-
readonly removeOnComplete: true;
|
|
102
|
-
readonly removeOnFail: true;
|
|
103
|
-
};
|
|
104
|
-
};
|
|
105
114
|
readonly "file-release": {
|
|
106
115
|
readonly queue: "cap-kernel-maintenance";
|
|
107
116
|
readonly idempotent: "Re-reads the deleted file under its row lock and releases its blob only while nothing else points at it, or deletes its own staging key; a second run finds nothing to do";
|
|
@@ -21,6 +21,18 @@ const SCOPE_JOB_OPTS = {
|
|
|
21
21
|
* name without one does not type-check as an `OutboxJobName` (`add` does not check it at runtime).
|
|
22
22
|
*/
|
|
23
23
|
export const OUTBOX_JOBS = {
|
|
24
|
+
"data-erasure": {
|
|
25
|
+
queue: "cap-kernel-maintenance",
|
|
26
|
+
idempotent: "Each generation claims the durable request under a row lock. Stale and completed deliveries do nothing.",
|
|
27
|
+
processedIn: "packages/kernel/src/runtime/maintenance.ts",
|
|
28
|
+
opts: { attempts: 1, removeOnComplete: true, removeOnFail: true },
|
|
29
|
+
},
|
|
30
|
+
"retention-batch": {
|
|
31
|
+
queue: "cap-kernel-maintenance",
|
|
32
|
+
idempotent: "Locks the work row and checks the queued generation before committing one batch and its continuation",
|
|
33
|
+
processedIn: "packages/kernel/src/runtime/maintenance.ts",
|
|
34
|
+
opts: { attempts: 5, backoff: { type: "exponential", delay: 5000 }, removeOnComplete: true },
|
|
35
|
+
},
|
|
24
36
|
// `automations/job-ids.ts` TRIGGER_DISPATCH_JOB: owed by the transaction that stores a trigger
|
|
25
37
|
// event (`TriggerEventsService.emit`, collaboration spec §4.2), under `trigger-dispatch-<eventId>`
|
|
26
38
|
"trigger-dispatch": {
|
|
@@ -86,21 +98,6 @@ export const OUTBOX_JOBS = {
|
|
|
86
98
|
removeOnFail: true,
|
|
87
99
|
},
|
|
88
100
|
},
|
|
89
|
-
// `conversations/event-org-backfill.ts` EVENT_ORG_BACKFILL_JOB: batched backfill of
|
|
90
|
-
// `conversation_events.org_id` from `conversations`, owed by the periodic kickoff under
|
|
91
|
-
// `eventOrgBackfillJobId(null)` and chained per 5,000-row batch under `eventOrgBackfillJobId(last)`
|
|
92
|
-
"conversation-events-org-backfill": {
|
|
93
|
-
queue: "cap-kernel-maintenance",
|
|
94
|
-
idempotent: "Locks up to 5,000 NULL org_id rows after its (conversation_id, seq) cursor with FOR UPDATE SKIP LOCKED and fills each from its conversation's org_id; rows already filled are skipped and the next batch is owed atomically under a deterministic cursor job id",
|
|
95
|
-
processedIn: "packages/kernel/src/runtime/maintenance.ts",
|
|
96
|
-
// removed either way, so a later kickoff during a rolling deploy can owe the first batch again
|
|
97
|
-
opts: {
|
|
98
|
-
attempts: 5,
|
|
99
|
-
backoff: { type: "exponential", delay: 5_000 },
|
|
100
|
-
removeOnComplete: true,
|
|
101
|
-
removeOnFail: true,
|
|
102
|
-
},
|
|
103
|
-
},
|
|
104
101
|
// `files/blob-objects.ts` FILE_RELEASE_JOB: owed, deferred, by every discard and draft cleanup
|
|
105
102
|
// of an upload, under `fileReleaseJobId`
|
|
106
103
|
"file-release": {
|
|
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
10
10
|
import { Inject, Injectable } from "@nestjs/common";
|
|
11
11
|
import { getStorageToken } from "@nestjs/throttler";
|
|
12
12
|
import { ApiError } from "../../errors.js";
|
|
13
|
+
import { recordThrottle } from "../metrics/kernel-metrics.js";
|
|
13
14
|
import { NAMED_THROTTLERS, throttlerKey } from "./named-throttlers.js";
|
|
14
15
|
/**
|
|
15
16
|
* The Redis key of one counter. All counters of a credential group share the hash tag
|
|
@@ -44,7 +45,13 @@ let CredentialThrottler = class CredentialThrottler {
|
|
|
44
45
|
*/
|
|
45
46
|
async reserve(names, req, reply) {
|
|
46
47
|
const ts = this.resolve(names);
|
|
47
|
-
const r = await this.redisStorage()
|
|
48
|
+
const r = await this.redisStorage()
|
|
49
|
+
.reserve(ts.map((t) => credentialRedisKey(t, t.getTracker(req))), ts.map((t) => t.limit), ts[0]?.ttl ?? 0)
|
|
50
|
+
.catch((error) => {
|
|
51
|
+
recordThrottle("credential", "unavailable");
|
|
52
|
+
throw error;
|
|
53
|
+
});
|
|
54
|
+
recordThrottle("credential", r.allowed ? "allowed" : "limited");
|
|
48
55
|
if (r.allowed)
|
|
49
56
|
return;
|
|
50
57
|
reply.header("retry-after", String(r.retryAfterSeconds));
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import type { FastifyRequest } from "fastify";
|
|
2
2
|
/** The counting window of every credential throttler, ms (first attempt starts it). */
|
|
3
3
|
export declare const CREDENTIAL_WINDOW_MS = 900000;
|
|
4
|
+
/** Deployment-wide quota shared across the Nest API routes. */
|
|
5
|
+
export declare const API_DEFAULT_THROTTLER: {
|
|
6
|
+
readonly name: "api-default";
|
|
7
|
+
readonly ttl: 60000;
|
|
8
|
+
readonly message: "Too many requests; try again later";
|
|
9
|
+
};
|
|
4
10
|
/** A named throttler: a limit over a tracker, answering 429 `auth.rate_limited` with `message`. */
|
|
5
11
|
export interface NamedThrottler {
|
|
6
12
|
name: string;
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
/** The counting window of every credential throttler, ms (first attempt starts it). */
|
|
3
3
|
export const CREDENTIAL_WINDOW_MS = 900_000;
|
|
4
|
+
/** Deployment-wide quota shared across the Nest API routes. */
|
|
5
|
+
export const API_DEFAULT_THROTTLER = {
|
|
6
|
+
name: "api-default",
|
|
7
|
+
ttl: 60_000,
|
|
8
|
+
message: "Too many requests; try again later",
|
|
9
|
+
};
|
|
4
10
|
const sha256 = (s) => createHash("sha256").update(s).digest("hex");
|
|
5
11
|
/** Logins are normalized the way local accounts are (no format check): case / space variants share a count. */
|
|
6
12
|
const loginHash = (login) => sha256(login.normalize("NFKC").trim().toLowerCase());
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type CanActivate, type ExecutionContext } from "@nestjs/common";
|
|
2
|
+
import { type ThrottlerStorage } from "@nestjs/throttler";
|
|
3
|
+
import { KernelConfigService } from "../config/kernel-config.service.js";
|
|
4
|
+
/** Runs after authentication on Nest API routes. Streaming sessions count at admission. */
|
|
5
|
+
export declare class PrincipalThrottlerGuard implements CanActivate {
|
|
6
|
+
private readonly storage;
|
|
7
|
+
private readonly config;
|
|
8
|
+
constructor(storage: ThrottlerStorage, config: KernelConfigService);
|
|
9
|
+
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
10
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
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 { getStorageToken } from "@nestjs/throttler";
|
|
12
|
+
import { ApiError } from "../../errors.js";
|
|
13
|
+
import { KernelConfigService } from "../config/kernel-config.service.js";
|
|
14
|
+
import { API_DEFAULT_THROTTLER, throttlerKey } from "./named-throttlers.js";
|
|
15
|
+
/** Runs after authentication on Nest API routes. Streaming sessions count at admission. */
|
|
16
|
+
let PrincipalThrottlerGuard = class PrincipalThrottlerGuard {
|
|
17
|
+
storage;
|
|
18
|
+
config;
|
|
19
|
+
constructor(storage, config) {
|
|
20
|
+
this.storage = storage;
|
|
21
|
+
this.config = config;
|
|
22
|
+
}
|
|
23
|
+
async canActivate(context) {
|
|
24
|
+
const http = context.switchToHttp();
|
|
25
|
+
const req = http.getRequest();
|
|
26
|
+
const route = req.routeOptions.url;
|
|
27
|
+
if (route !== "/api" && !route?.startsWith("/api/"))
|
|
28
|
+
return true;
|
|
29
|
+
const p = req.principal;
|
|
30
|
+
const tracker = p?.kind === "user"
|
|
31
|
+
? `account:${p.account.id}`
|
|
32
|
+
: p?.kind === "service"
|
|
33
|
+
? `service:${p.orgId}:${p.tokenId}`
|
|
34
|
+
: `ip:${req.ip}`;
|
|
35
|
+
const { principalRequestsPerMinute, anonymousRequestsPerMinute } = this.config.get().http;
|
|
36
|
+
const { name, ttl, message } = API_DEFAULT_THROTTLER;
|
|
37
|
+
const result = await this.storage.increment(throttlerKey(name, tracker), ttl, p ? principalRequestsPerMinute : anonymousRequestsPerMinute, ttl, name);
|
|
38
|
+
if (result.isBlocked) {
|
|
39
|
+
http.getResponse().header("retry-after", String(result.timeToBlockExpire));
|
|
40
|
+
throw new ApiError("rate_limited", message);
|
|
41
|
+
}
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
PrincipalThrottlerGuard = __decorate([
|
|
46
|
+
Injectable(),
|
|
47
|
+
__param(0, Inject(getStorageToken())),
|
|
48
|
+
__param(1, Inject(KernelConfigService))
|
|
49
|
+
], PrincipalThrottlerGuard);
|
|
50
|
+
export { PrincipalThrottlerGuard };
|
|
@@ -24,6 +24,7 @@ export declare const throttlerRedisKey: (key: string, throttlerName: string) =>
|
|
|
24
24
|
export declare class RedisThrottlerStorage implements ThrottlerStorage {
|
|
25
25
|
private readonly redis;
|
|
26
26
|
private readonly log;
|
|
27
|
+
private readonly lastWarning;
|
|
27
28
|
constructor(redis: Redis, log: KernelLogger);
|
|
28
29
|
/** `ttl` is in milliseconds (the throttler convention); `blockDuration` is unused. */
|
|
29
30
|
increment(key: string, ttl: number, limit: number, _blockDuration: number, throttlerName: string): Promise<ThrottlerStorageRecord>;
|