@capybara-hq/kernel 0.1.0-rc.141 → 0.1.0-rc.142
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/config/schema.d.ts +1 -0
- package/dist/config/schema.js +10 -0
- package/dist/http/api.module.js +6 -0
- package/dist/infra/config/kernel-config.service.js +2 -0
- package/dist/invalidation/hints.d.ts +56 -0
- package/dist/invalidation/hints.js +67 -0
- package/dist/invalidation/invalidation-hints.d.ts +24 -0
- package/dist/invalidation/invalidation-hints.js +59 -0
- package/dist/invalidation/invalidation-hints.module.d.ts +8 -0
- package/dist/invalidation/invalidation-hints.module.js +23 -0
- package/dist/invalidation/me-stream.controller.d.ts +30 -0
- package/dist/invalidation/me-stream.controller.js +100 -0
- package/dist/invalidation/me-stream.d.ts +67 -0
- package/dist/invalidation/me-stream.js +351 -0
- package/dist/invalidation/me-stream.module.d.ts +7 -0
- package/dist/invalidation/me-stream.module.js +22 -0
- package/dist/kernel.module.js +4 -0
- package/dist/platform/exclusions.js +5 -0
- package/package.json +1 -1
package/dist/config/schema.d.ts
CHANGED
|
@@ -175,6 +175,7 @@ export declare const KernelConfigSchema: z.ZodObject<{
|
|
|
175
175
|
stalledIntervalMs: z.ZodDefault<z.ZodNumber>;
|
|
176
176
|
sseHeartbeatMs: z.ZodDefault<z.ZodNumber>;
|
|
177
177
|
sseRecheckMs: z.ZodDefault<z.ZodNumber>;
|
|
178
|
+
meStreamMaxPerAccount: z.ZodDefault<z.ZodNumber>;
|
|
178
179
|
}, z.core.$strict>>;
|
|
179
180
|
tools: z.ZodDefault<z.ZodObject<{
|
|
180
181
|
timeoutMs: z.ZodDefault<z.ZodNumber>;
|
package/dist/config/schema.js
CHANGED
|
@@ -984,6 +984,15 @@ export const KernelConfigSchema = z.strictObject({
|
|
|
984
984
|
.meta(meta({
|
|
985
985
|
description: "How often an open conversation event stream (SSE) re-checks that the viewer may still access the conversation, in milliseconds; the stream closes when access is lost",
|
|
986
986
|
})),
|
|
987
|
+
meStreamMaxPerAccount: z
|
|
988
|
+
.number()
|
|
989
|
+
.int()
|
|
990
|
+
.positive()
|
|
991
|
+
.default(8)
|
|
992
|
+
.meta(meta({
|
|
993
|
+
hot: true,
|
|
994
|
+
description: "Maximum concurrent account invalidation streams (GET /api/v1/orgs/:orgId/me/stream) per account on one replica; a new stream over the limit closes that account's oldest stream on the replica",
|
|
995
|
+
})),
|
|
987
996
|
})
|
|
988
997
|
.default({
|
|
989
998
|
maxSteps: 0,
|
|
@@ -998,6 +1007,7 @@ export const KernelConfigSchema = z.strictObject({
|
|
|
998
1007
|
stalledIntervalMs: 30000,
|
|
999
1008
|
sseHeartbeatMs: 15000,
|
|
1000
1009
|
sseRecheckMs: 60000,
|
|
1010
|
+
meStreamMaxPerAccount: 8,
|
|
1001
1011
|
}),
|
|
1002
1012
|
tools: z
|
|
1003
1013
|
.strictObject({
|
package/dist/http/api.module.js
CHANGED
|
@@ -78,6 +78,8 @@ import { InboxModule } from "../inbox/inbox.module.js";
|
|
|
78
78
|
import { InboxItemsController } from "../inbox/inbox-items.controller.js";
|
|
79
79
|
import { PlatformInboxController } from "../inbox/platform-inbox.controller.js";
|
|
80
80
|
import { PrincipalThrottlerGuard } from "../infra/throttler/principal-throttler.guard.js";
|
|
81
|
+
import { MeStreamController } from "../invalidation/me-stream.controller.js";
|
|
82
|
+
import { MeStreamModule } from "../invalidation/me-stream.module.js";
|
|
81
83
|
import { ModelEnablementController } from "../models/enablement.controller.js";
|
|
82
84
|
import { ModelsModule } from "../models/models.module.js";
|
|
83
85
|
import { ModelPurposesController } from "../models/purposes.controller.js";
|
|
@@ -177,6 +179,8 @@ const CONTROLLERS = [
|
|
|
177
179
|
InboxController,
|
|
178
180
|
InboxItemsController,
|
|
179
181
|
PlatformInboxController,
|
|
182
|
+
// the account invalidation stream (inbox, request and capability hints)
|
|
183
|
+
MeStreamController,
|
|
180
184
|
ConversationStreamController,
|
|
181
185
|
ConnectorContentController,
|
|
182
186
|
ConnectorsController,
|
|
@@ -265,6 +269,8 @@ ApiModule = __decorate([
|
|
|
265
269
|
LibraryReadModule,
|
|
266
270
|
UiModule,
|
|
267
271
|
InboxModule,
|
|
272
|
+
// the account invalidation streams (me/stream): api role only
|
|
273
|
+
MeStreamModule,
|
|
268
274
|
ThemesModule,
|
|
269
275
|
ClientModule,
|
|
270
276
|
SetupModule,
|
|
@@ -25,6 +25,8 @@ const HOT_APPLIERS = {
|
|
|
25
25
|
"log.level": (k, v) => k.log.setLevel(String(v)),
|
|
26
26
|
// The runtime reads the concurrency cap through the config service on every quota request.
|
|
27
27
|
"runtime.orgConcurrency": () => { },
|
|
28
|
+
// MeStreams reads the per-account stream cap at every stream open.
|
|
29
|
+
"runtime.meStreamMaxPerAccount": () => { },
|
|
28
30
|
// Eval org concurrency is read the same way at every quota request.
|
|
29
31
|
"evals.orgConcurrency": () => { },
|
|
30
32
|
// The git gateway reads tools.git.enabled through the config service on every request.
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { type OrgRole } from "../orgs/roles.js";
|
|
3
|
+
/**
|
|
4
|
+
* Account invalidation hints (account invalidation stream spec §3): a content-free "refetch now"
|
|
5
|
+
* nudge. A hint is its kind only: no ids, counts, names or org ids, so it can reveal nothing about
|
|
6
|
+
* an entry or another org. The org is implied by the bus topic and by the stream's own `:orgId`.
|
|
7
|
+
* Extra fields are rejected when the kernel publishes and when a frame is parsed.
|
|
8
|
+
*/
|
|
9
|
+
export declare const HINT_KINDS: readonly ["inbox", "requests", "capabilities", "platform-inbox"];
|
|
10
|
+
export type HintKind = (typeof HINT_KINDS)[number];
|
|
11
|
+
export declare const Hint: z.ZodObject<{
|
|
12
|
+
kind: z.ZodEnum<{
|
|
13
|
+
capabilities: "capabilities";
|
|
14
|
+
inbox: "inbox";
|
|
15
|
+
"platform-inbox": "platform-inbox";
|
|
16
|
+
requests: "requests";
|
|
17
|
+
}>;
|
|
18
|
+
}, z.core.$strict>;
|
|
19
|
+
export type Hint = z.infer<typeof Hint>;
|
|
20
|
+
/** The hint `value` is, or undefined when it is anything else (an extra field, a wrong kind). */
|
|
21
|
+
export declare function parseHint(value: unknown): Hint | undefined;
|
|
22
|
+
/** The roles that have a role topic: guests have none (spec §3). */
|
|
23
|
+
export declare const TOPIC_ROLES: readonly ["member", "admin", "owner"];
|
|
24
|
+
export type TopicRole = (typeof TOPIC_ROLES)[number];
|
|
25
|
+
/** A topic of the account invalidation stream, as built by the builders below. */
|
|
26
|
+
export type InvalidationTopic = string & {
|
|
27
|
+
readonly __invalidationTopic: unique symbol;
|
|
28
|
+
};
|
|
29
|
+
/** The topic of one account's streams: every org stream of that account listens to it. */
|
|
30
|
+
export declare function acctTopic(accountId: string): InvalidationTopic;
|
|
31
|
+
/**
|
|
32
|
+
* The topic of the members of `orgId` at or above `role`: a stream subscribes to every role topic
|
|
33
|
+
* at or below its member's role, so a writer publishes once per role value.
|
|
34
|
+
*/
|
|
35
|
+
export declare function orgRoleTopic(orgId: string, role: TopicRole): InvalidationTopic;
|
|
36
|
+
/** The topic of committed org intent changes (capabilities): every member stream (not guests). */
|
|
37
|
+
export declare function orgCapsTopic(orgId: string): InvalidationTopic;
|
|
38
|
+
/** The topic of super admin streams. */
|
|
39
|
+
export declare const PLATFORM_ADMINS_TOPIC: InvalidationTopic;
|
|
40
|
+
/** The role topics a member with `role` listens to: every one at or below it (guest: none). */
|
|
41
|
+
export declare function roleTopicRoles(role: OrgRole): TopicRole[];
|
|
42
|
+
/**
|
|
43
|
+
* The identity a stream's topics come from, all of it verified by the kernel: the principal's
|
|
44
|
+
* account id, its membership role in the stream's org (read from PG after the org guard) and its
|
|
45
|
+
* super admin flag. Nothing from the request (query, headers, body, `Last-Event-ID`) goes here.
|
|
46
|
+
*/
|
|
47
|
+
export interface StreamIdentity {
|
|
48
|
+
accountId: string;
|
|
49
|
+
orgId: string;
|
|
50
|
+
role: OrgRole;
|
|
51
|
+
superAdmin: boolean;
|
|
52
|
+
}
|
|
53
|
+
/** The topics a stream of `id` subscribes to (spec §5 "Subscriptions"). */
|
|
54
|
+
export declare function streamTopics(id: StreamIdentity): InvalidationTopic[];
|
|
55
|
+
/** The SSE frame of a hint: `event: hint`, data the hint's JSON (its kind only). */
|
|
56
|
+
export declare const hintFrame: (h: Hint) => string;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { ORG_ROLES, roleAtLeast } from "../orgs/roles.js";
|
|
3
|
+
/**
|
|
4
|
+
* Account invalidation hints (account invalidation stream spec §3): a content-free "refetch now"
|
|
5
|
+
* nudge. A hint is its kind only: no ids, counts, names or org ids, so it can reveal nothing about
|
|
6
|
+
* an entry or another org. The org is implied by the bus topic and by the stream's own `:orgId`.
|
|
7
|
+
* Extra fields are rejected when the kernel publishes and when a frame is parsed.
|
|
8
|
+
*/
|
|
9
|
+
export const HINT_KINDS = ["inbox", "requests", "capabilities", "platform-inbox"];
|
|
10
|
+
export const Hint = z.strictObject({ kind: z.enum(HINT_KINDS) });
|
|
11
|
+
/** The hint `value` is, or undefined when it is anything else (an extra field, a wrong kind). */
|
|
12
|
+
export function parseHint(value) {
|
|
13
|
+
const r = Hint.safeParse(value);
|
|
14
|
+
return r.success ? { kind: r.data.kind } : undefined;
|
|
15
|
+
}
|
|
16
|
+
/** The roles that have a role topic: guests have none (spec §3). */
|
|
17
|
+
export const TOPIC_ROLES = ["member", "admin", "owner"];
|
|
18
|
+
/**
|
|
19
|
+
* Ids that go into a topic name: kernel-generated ids, never containing the `.` that separates
|
|
20
|
+
* topic segments, so one id cannot spell another topic.
|
|
21
|
+
*/
|
|
22
|
+
const ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
|
|
23
|
+
function assertId(what, id) {
|
|
24
|
+
if (typeof id !== "string" || !ID_RE.test(id))
|
|
25
|
+
throw new Error(`invalid ${what} for a topic`);
|
|
26
|
+
}
|
|
27
|
+
/** The topic of one account's streams: every org stream of that account listens to it. */
|
|
28
|
+
export function acctTopic(accountId) {
|
|
29
|
+
assertId("account id", accountId);
|
|
30
|
+
return `acct.${accountId}`;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The topic of the members of `orgId` at or above `role`: a stream subscribes to every role topic
|
|
34
|
+
* at or below its member's role, so a writer publishes once per role value.
|
|
35
|
+
*/
|
|
36
|
+
export function orgRoleTopic(orgId, role) {
|
|
37
|
+
assertId("org id", orgId);
|
|
38
|
+
if (!TOPIC_ROLES.includes(role))
|
|
39
|
+
throw new Error("invalid topic role");
|
|
40
|
+
return `org-role.${orgId}.${role}`;
|
|
41
|
+
}
|
|
42
|
+
/** The topic of committed org intent changes (capabilities): every member stream (not guests). */
|
|
43
|
+
export function orgCapsTopic(orgId) {
|
|
44
|
+
assertId("org id", orgId);
|
|
45
|
+
return `org-caps.${orgId}`;
|
|
46
|
+
}
|
|
47
|
+
/** The topic of super admin streams. */
|
|
48
|
+
export const PLATFORM_ADMINS_TOPIC = "platform-admins";
|
|
49
|
+
/** The role topics a member with `role` listens to: every one at or below it (guest: none). */
|
|
50
|
+
export function roleTopicRoles(role) {
|
|
51
|
+
return TOPIC_ROLES.filter((r) => roleAtLeast(role, r));
|
|
52
|
+
}
|
|
53
|
+
/** The topics a stream of `id` subscribes to (spec §5 "Subscriptions"). */
|
|
54
|
+
export function streamTopics(id) {
|
|
55
|
+
if (!ORG_ROLES.includes(id.role))
|
|
56
|
+
throw new Error("invalid org role");
|
|
57
|
+
const topics = [acctTopic(id.accountId)];
|
|
58
|
+
for (const r of roleTopicRoles(id.role))
|
|
59
|
+
topics.push(orgRoleTopic(id.orgId, r));
|
|
60
|
+
if (roleAtLeast(id.role, "member"))
|
|
61
|
+
topics.push(orgCapsTopic(id.orgId));
|
|
62
|
+
if (id.superAdmin)
|
|
63
|
+
topics.push(PLATFORM_ADMINS_TOPIC);
|
|
64
|
+
return topics;
|
|
65
|
+
}
|
|
66
|
+
/** The SSE frame of a hint: `event: hint`, data the hint's JSON (its kind only). */
|
|
67
|
+
export const hintFrame = (h) => `event: hint\ndata: ${JSON.stringify({ kind: h.kind })}\n\n`;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ExtensionContext, Logger } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { Hint, type InvalidationTopic } from "./hints.js";
|
|
3
|
+
/**
|
|
4
|
+
* Publishes account invalidation hints on the kernel bus (account invalidation stream spec §4).
|
|
5
|
+
* A hint is harmless to lose (the web's `live` freshness converges anyway), so it is an
|
|
6
|
+
* after-commit side effect, never an outbox row: {@link publishAfterCommit} is what a writer calls
|
|
7
|
+
* inside its transaction; a rollback publishes nothing. Topics come from the builders in
|
|
8
|
+
* `hints.ts` and the row the writer already holds. A publish failure is logged and swallowed.
|
|
9
|
+
*/
|
|
10
|
+
export declare class InvalidationHints {
|
|
11
|
+
private readonly bus;
|
|
12
|
+
private readonly log;
|
|
13
|
+
constructor(bus: Pick<ExtensionContext["bus"], "publish">, log: Pick<Logger, "warn">);
|
|
14
|
+
/**
|
|
15
|
+
* Publishes `hint` on every topic now. The hint is validated first (kind only: an extra field
|
|
16
|
+
* throws, a programming error); bus failures are logged and never thrown.
|
|
17
|
+
*/
|
|
18
|
+
publish(topics: readonly InvalidationTopic[], hint: Hint): Promise<void>;
|
|
19
|
+
/**
|
|
20
|
+
* Publishes `hint` after the root transaction commits (at once outside a transaction); a
|
|
21
|
+
* rollback drops it. The hint is validated now, so a bad hint fails the caller, not the hook.
|
|
22
|
+
*/
|
|
23
|
+
publishAfterCommit(topics: readonly InvalidationTopic[], hint: Hint): void;
|
|
24
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
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 { afterCommit } from "../infra/database/after-commit.js";
|
|
12
|
+
import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
|
|
13
|
+
import { Hint } from "./hints.js";
|
|
14
|
+
/**
|
|
15
|
+
* Publishes account invalidation hints on the kernel bus (account invalidation stream spec §4).
|
|
16
|
+
* A hint is harmless to lose (the web's `live` freshness converges anyway), so it is an
|
|
17
|
+
* after-commit side effect, never an outbox row: {@link publishAfterCommit} is what a writer calls
|
|
18
|
+
* inside its transaction; a rollback publishes nothing. Topics come from the builders in
|
|
19
|
+
* `hints.ts` and the row the writer already holds. A publish failure is logged and swallowed.
|
|
20
|
+
*/
|
|
21
|
+
let InvalidationHints = class InvalidationHints {
|
|
22
|
+
bus;
|
|
23
|
+
log;
|
|
24
|
+
constructor(bus, log) {
|
|
25
|
+
this.bus = bus;
|
|
26
|
+
this.log = log;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Publishes `hint` on every topic now. The hint is validated first (kind only: an extra field
|
|
30
|
+
* throws, a programming error); bus failures are logged and never thrown.
|
|
31
|
+
*/
|
|
32
|
+
async publish(topics, hint) {
|
|
33
|
+
const h = Hint.parse(hint);
|
|
34
|
+
const unique = [...new Set(topics)];
|
|
35
|
+
await Promise.all(unique.map(async (topic) => {
|
|
36
|
+
try {
|
|
37
|
+
await this.bus.publish(topic, { kind: h.kind });
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
this.log.warn("invalidation hint publish failed", { topic, kind: h.kind, err });
|
|
41
|
+
}
|
|
42
|
+
}));
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Publishes `hint` after the root transaction commits (at once outside a transaction); a
|
|
46
|
+
* rollback drops it. The hint is validated now, so a bad hint fails the caller, not the hook.
|
|
47
|
+
*/
|
|
48
|
+
publishAfterCommit(topics, hint) {
|
|
49
|
+
const h = Hint.parse(hint);
|
|
50
|
+
const list = [...topics];
|
|
51
|
+
afterCommit(() => this.publish(list, h));
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
InvalidationHints = __decorate([
|
|
55
|
+
Injectable(),
|
|
56
|
+
__param(0, Inject(KERNEL_BUS)),
|
|
57
|
+
__param(1, Inject(KERNEL_LOGGER))
|
|
58
|
+
], InvalidationHints);
|
|
59
|
+
export { InvalidationHints };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Account invalidation hints (account invalidation stream spec §4): {@link InvalidationHints}, which
|
|
3
|
+
* writers call after their commit. It needs only the global kernel bus and logger, so any module
|
|
4
|
+
* may import it, whatever role runs it (api requests, worker jobs, the gateway). The topic builders
|
|
5
|
+
* are plain functions in `hints.ts`. The streams that deliver hints are `MeStreamModule`'s.
|
|
6
|
+
*/
|
|
7
|
+
export declare class InvalidationHintsModule {
|
|
8
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
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
|
+
import { Module } from "@nestjs/common";
|
|
8
|
+
import { InvalidationHints } from "./invalidation-hints.js";
|
|
9
|
+
/**
|
|
10
|
+
* Account invalidation hints (account invalidation stream spec §4): {@link InvalidationHints}, which
|
|
11
|
+
* writers call after their commit. It needs only the global kernel bus and logger, so any module
|
|
12
|
+
* may import it, whatever role runs it (api requests, worker jobs, the gateway). The topic builders
|
|
13
|
+
* are plain functions in `hints.ts`. The streams that deliver hints are `MeStreamModule`'s.
|
|
14
|
+
*/
|
|
15
|
+
let InvalidationHintsModule = class InvalidationHintsModule {
|
|
16
|
+
};
|
|
17
|
+
InvalidationHintsModule = __decorate([
|
|
18
|
+
Module({
|
|
19
|
+
providers: [InvalidationHints],
|
|
20
|
+
exports: [InvalidationHints],
|
|
21
|
+
})
|
|
22
|
+
], InvalidationHintsModule);
|
|
23
|
+
export { InvalidationHintsModule };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
2
|
+
import { ApiTokenService } from "../identity/api-tokens.js";
|
|
3
|
+
import { type Principal } from "../identity/principal.js";
|
|
4
|
+
import { SessionService } from "../identity/sessions.js";
|
|
5
|
+
import { type OrgContext } from "../orgs/org.guard.js";
|
|
6
|
+
import { MeStreams } from "./me-stream.js";
|
|
7
|
+
/**
|
|
8
|
+
* The account invalidation stream (account invalidation stream spec §5):
|
|
9
|
+
* - `GET /api/v1/orgs/:orgId/me/stream`: SSE of content-free hints (`event: hint`,
|
|
10
|
+
* `data: {"kind"}` with kind `inbox` | `requests` | `capabilities` | `platform-inbox`) addressed
|
|
11
|
+
* to the caller in this org; any member, a guest included (a guest gets only its account's
|
|
12
|
+
* hints); user principals only (session cookie or personal token). Heartbeat and recheck follow
|
|
13
|
+
* `runtime.sseHeartbeatMs` / `runtime.sseRecheckMs`; a lost membership, a disabled account or a
|
|
14
|
+
* revoked credential ends it with `event: error` (`data: {"code"}`); over
|
|
15
|
+
* `runtime.meStreamMaxPerAccount` on one replica the account's oldest stream ends with
|
|
16
|
+
* `event: closed` (`data: {"reason":"superseded"}`). No replay (`Last-Event-ID` is ignored).
|
|
17
|
+
* A client treats any `event: error` as terminal, whatever its code. A removed or downgraded
|
|
18
|
+
* member may still get kind-only org-topic hints until the next recheck (accepted: hints carry
|
|
19
|
+
* nothing but their kind).
|
|
20
|
+
*
|
|
21
|
+
* The stream's topics come only from the principal, the org guard's verified membership and the
|
|
22
|
+
* recheck's PG read: no query, header or body value is read here.
|
|
23
|
+
*/
|
|
24
|
+
export declare class MeStreamController {
|
|
25
|
+
private readonly streams;
|
|
26
|
+
private readonly sessions;
|
|
27
|
+
private readonly tokens;
|
|
28
|
+
constructor(streams: MeStreams, sessions: SessionService, tokens: ApiTokenService);
|
|
29
|
+
stream(principal: Principal, org: OrgContext, req: FastifyRequest, reply: FastifyReply): Promise<void>;
|
|
30
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
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 { Controller, Get, Inject, Req, Res } from "@nestjs/common";
|
|
11
|
+
import { ApiTokenService } from "../identity/api-tokens.js";
|
|
12
|
+
import { credentialCheck } from "../identity/credential-check.js";
|
|
13
|
+
import { CurrentPrincipal, requireUser } from "../identity/principal.js";
|
|
14
|
+
import { SessionService } from "../identity/sessions.js";
|
|
15
|
+
import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
|
|
16
|
+
import { BEARER_RE } from "../ui/views.controller.js";
|
|
17
|
+
import { MeStreams } from "./me-stream.js";
|
|
18
|
+
/**
|
|
19
|
+
* The account invalidation stream (account invalidation stream spec §5):
|
|
20
|
+
* - `GET /api/v1/orgs/:orgId/me/stream`: SSE of content-free hints (`event: hint`,
|
|
21
|
+
* `data: {"kind"}` with kind `inbox` | `requests` | `capabilities` | `platform-inbox`) addressed
|
|
22
|
+
* to the caller in this org; any member, a guest included (a guest gets only its account's
|
|
23
|
+
* hints); user principals only (session cookie or personal token). Heartbeat and recheck follow
|
|
24
|
+
* `runtime.sseHeartbeatMs` / `runtime.sseRecheckMs`; a lost membership, a disabled account or a
|
|
25
|
+
* revoked credential ends it with `event: error` (`data: {"code"}`); over
|
|
26
|
+
* `runtime.meStreamMaxPerAccount` on one replica the account's oldest stream ends with
|
|
27
|
+
* `event: closed` (`data: {"reason":"superseded"}`). No replay (`Last-Event-ID` is ignored).
|
|
28
|
+
* A client treats any `event: error` as terminal, whatever its code. A removed or downgraded
|
|
29
|
+
* member may still get kind-only org-topic hints until the next recheck (accepted: hints carry
|
|
30
|
+
* nothing but their kind).
|
|
31
|
+
*
|
|
32
|
+
* The stream's topics come only from the principal, the org guard's verified membership and the
|
|
33
|
+
* recheck's PG read: no query, header or body value is read here.
|
|
34
|
+
*/
|
|
35
|
+
let MeStreamController = class MeStreamController {
|
|
36
|
+
streams;
|
|
37
|
+
sessions;
|
|
38
|
+
tokens;
|
|
39
|
+
constructor(streams, sessions, tokens) {
|
|
40
|
+
this.streams = streams;
|
|
41
|
+
this.sessions = sessions;
|
|
42
|
+
this.tokens = tokens;
|
|
43
|
+
}
|
|
44
|
+
async stream(principal, org, req, reply) {
|
|
45
|
+
const p = requireUser(principal);
|
|
46
|
+
const res = reply.raw;
|
|
47
|
+
const handle = await this.streams.open({
|
|
48
|
+
orgId: org.orgId,
|
|
49
|
+
accountId: p.account.id,
|
|
50
|
+
// the bearer re-authenticates the same token the auth guard accepted (never a topic input)
|
|
51
|
+
credential: credentialCheck(p, BEARER_RE.exec(req.headers.authorization ?? "")?.[1], {
|
|
52
|
+
sessions: this.sessions,
|
|
53
|
+
tokens: this.tokens,
|
|
54
|
+
}),
|
|
55
|
+
}, {
|
|
56
|
+
write: (chunk) => {
|
|
57
|
+
res.write(chunk);
|
|
58
|
+
},
|
|
59
|
+
backlog: () => res.writableLength,
|
|
60
|
+
end: () => {
|
|
61
|
+
res.end();
|
|
62
|
+
},
|
|
63
|
+
abort: () => {
|
|
64
|
+
res.destroy();
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
reply.hijack();
|
|
68
|
+
res.on("close", () => handle.close());
|
|
69
|
+
if (res.destroyed || !res.socket || res.socket.destroyed) {
|
|
70
|
+
handle.close();
|
|
71
|
+
res.destroy();
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
res.writeHead(200, {
|
|
75
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
76
|
+
"cache-control": "no-cache",
|
|
77
|
+
"x-accel-buffering": "no",
|
|
78
|
+
connection: "keep-alive",
|
|
79
|
+
});
|
|
80
|
+
res.flushHeaders();
|
|
81
|
+
handle.begin();
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
__decorate([
|
|
85
|
+
Get("stream")
|
|
86
|
+
// the person's own hints: any member, a guest included; requireUser refuses service tokens
|
|
87
|
+
,
|
|
88
|
+
OrgAction("org.read"),
|
|
89
|
+
__param(0, CurrentPrincipal()),
|
|
90
|
+
__param(1, CurrentOrg()),
|
|
91
|
+
__param(2, Req()),
|
|
92
|
+
__param(3, Res())
|
|
93
|
+
], MeStreamController.prototype, "stream", null);
|
|
94
|
+
MeStreamController = __decorate([
|
|
95
|
+
Controller("api/v1/orgs/:orgId/me"),
|
|
96
|
+
__param(0, Inject(MeStreams)),
|
|
97
|
+
__param(1, Inject(SessionService)),
|
|
98
|
+
__param(2, Inject(ApiTokenService))
|
|
99
|
+
], MeStreamController);
|
|
100
|
+
export { MeStreamController };
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { Logger } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { CredentialCheck } from "../identity/credential-check.js";
|
|
3
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
4
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
5
|
+
import { GracefulShutdown } from "../infra/lifecycle/graceful-shutdown.service.js";
|
|
6
|
+
import { type OrgRole } from "../orgs/roles.js";
|
|
7
|
+
import { type SseOutput, type StreamBus, type StreamHandle } from "../runtime/stream.js";
|
|
8
|
+
/** What the recheck reads about the stream's account in its org (one query). */
|
|
9
|
+
export interface MeStreamAccessState {
|
|
10
|
+
/** The account's status; undefined when the account no longer exists. */
|
|
11
|
+
status: "active" | "disabled" | undefined;
|
|
12
|
+
superAdmin: boolean;
|
|
13
|
+
/** The membership role in the org; undefined when not a member or the org is deleted. */
|
|
14
|
+
role: OrgRole | undefined;
|
|
15
|
+
}
|
|
16
|
+
/** Reads the membership, role, account status and super admin flag in one query. */
|
|
17
|
+
export declare class MeStreamAccess {
|
|
18
|
+
private readonly db;
|
|
19
|
+
constructor(db: KernelDb);
|
|
20
|
+
state(orgId: string, accountId: string): Promise<MeStreamAccessState>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* One stream's parameters, all from the authenticated principal and the org guard: the stream's
|
|
24
|
+
* topics are derived from these and the recheck's PG read, never from the request.
|
|
25
|
+
*/
|
|
26
|
+
export interface MeStreamParams {
|
|
27
|
+
orgId: string;
|
|
28
|
+
accountId: string;
|
|
29
|
+
credential: CredentialCheck;
|
|
30
|
+
}
|
|
31
|
+
/** The slow client cap: hints are tiny, so a client this far behind has stopped reading. */
|
|
32
|
+
export declare const ME_STREAM_MAX_BACKLOG_BYTES: number;
|
|
33
|
+
/** The final frame sent to the oldest stream of an account over the per-account cap. */
|
|
34
|
+
export declare const SUPERSEDED_FRAME: string;
|
|
35
|
+
/**
|
|
36
|
+
* The account invalidation streams of this replica (`GET /api/v1/orgs/:orgId/me/stream`, account
|
|
37
|
+
* invalidation stream spec §5): each forwards the hints of its topics as `event: hint` frames.
|
|
38
|
+
* Topics are recomputed on every `runtime.sseRecheckMs` recheck (credential first, then the
|
|
39
|
+
* membership, role, account status and super admin flag); a lost membership, a disabled account or
|
|
40
|
+
* a revoked credential ends the stream with `event: error` (`data: {"code"}`). At most
|
|
41
|
+
* `runtime.meStreamMaxPerAccount` streams per account on this replica: a new one over the cap
|
|
42
|
+
* supersedes the account's oldest (`event: closed`, `data: {"reason":"superseded"}`). No replay:
|
|
43
|
+
* the client refetches on open. Across replicas only through the Redis bus; this process holds
|
|
44
|
+
* only its connections' subscriptions and timers, closed at shutdown.
|
|
45
|
+
*/
|
|
46
|
+
export declare class MeStreams {
|
|
47
|
+
private readonly active;
|
|
48
|
+
/** Each account's streams on this replica, oldest first (replica-local resource accounting). */
|
|
49
|
+
private readonly byAccount;
|
|
50
|
+
private closing;
|
|
51
|
+
private readonly d;
|
|
52
|
+
constructor(bus: StreamBus, access: Pick<MeStreamAccess, "state">, config: Pick<KernelConfigService, "get">, log: Pick<Logger, "warn">, shutdown?: Pick<GracefulShutdown, "signal">);
|
|
53
|
+
/** Checks access and subscribes; a refusal throws before anything was written. */
|
|
54
|
+
open(p: MeStreamParams, out: SseOutput): Promise<StreamHandle>;
|
|
55
|
+
/** Closes every stream of this process (at shutdown) and latches. */
|
|
56
|
+
closeAll(): void;
|
|
57
|
+
get size(): number;
|
|
58
|
+
/** How many streams `accountId` holds on this replica. */
|
|
59
|
+
countOf(accountId: string): number;
|
|
60
|
+
/**
|
|
61
|
+
* Registers `conn` under its account as it begins, superseding the oldest streams over the cap
|
|
62
|
+
* (read now, so a lowered limit applies at the next stream). The list is complete before any victim closes: a
|
|
63
|
+
* victim's close finds itself already gone and never drops the account's entry.
|
|
64
|
+
*/
|
|
65
|
+
private admit;
|
|
66
|
+
private forget;
|
|
67
|
+
}
|
|
@@ -0,0 +1,351 @@
|
|
|
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, Optional } from "@nestjs/common";
|
|
11
|
+
import { ApiError } from "../errors.js";
|
|
12
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
13
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
14
|
+
import { withOrgScope } from "../infra/database/org-scope.js";
|
|
15
|
+
import { GracefulShutdown } from "../infra/lifecycle/graceful-shutdown.service.js";
|
|
16
|
+
import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
|
|
17
|
+
import { ORG_ROLES } from "../orgs/roles.js";
|
|
18
|
+
import { endedStream, } from "../runtime/stream.js";
|
|
19
|
+
import { hintFrame, parseHint, streamTopics } from "./hints.js";
|
|
20
|
+
/** Reads the membership, role, account status and super admin flag in one query. */
|
|
21
|
+
let MeStreamAccess = class MeStreamAccess {
|
|
22
|
+
db;
|
|
23
|
+
constructor(db) {
|
|
24
|
+
this.db = db;
|
|
25
|
+
}
|
|
26
|
+
async state(orgId, accountId) {
|
|
27
|
+
const row = await this.db
|
|
28
|
+
.selectFrom("accounts")
|
|
29
|
+
.leftJoin("memberships", (j) => j.onRef("memberships.account_id", "=", "accounts.id").on("memberships.org_id", "=", orgId))
|
|
30
|
+
.leftJoin("orgs", (j) => j.onRef("orgs.id", "=", "memberships.org_id").on("orgs.deleted_at", "is", null))
|
|
31
|
+
.select([
|
|
32
|
+
"accounts.status",
|
|
33
|
+
"accounts.is_super_admin",
|
|
34
|
+
"memberships.role",
|
|
35
|
+
"orgs.id as live_org_id",
|
|
36
|
+
])
|
|
37
|
+
.where("accounts.id", "=", accountId)
|
|
38
|
+
.executeTakeFirst();
|
|
39
|
+
if (!row)
|
|
40
|
+
return { status: undefined, superAdmin: false, role: undefined };
|
|
41
|
+
return {
|
|
42
|
+
status: row.status,
|
|
43
|
+
superAdmin: row.is_super_admin === true,
|
|
44
|
+
role: row.live_org_id !== null && row.role !== null ? row.role : undefined,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
MeStreamAccess = __decorate([
|
|
49
|
+
Injectable(),
|
|
50
|
+
__param(0, Inject(KernelDb))
|
|
51
|
+
], MeStreamAccess);
|
|
52
|
+
export { MeStreamAccess };
|
|
53
|
+
/** The slow client cap: hints are tiny, so a client this far behind has stopped reading. */
|
|
54
|
+
export const ME_STREAM_MAX_BACKLOG_BYTES = 64 * 1024;
|
|
55
|
+
/** The final frame sent to the oldest stream of an account over the per-account cap. */
|
|
56
|
+
export const SUPERSEDED_FRAME = `event: closed\ndata: ${JSON.stringify({ reason: "superseded" })}\n\n`;
|
|
57
|
+
const roleRank = (r) => ORG_ROLES.indexOf(r);
|
|
58
|
+
async function verdict(d, p) {
|
|
59
|
+
const denied = await p.credential();
|
|
60
|
+
if (denied !== null)
|
|
61
|
+
return { code: denied };
|
|
62
|
+
const s = await withOrgScope(p.orgId, () => d.access.state(p.orgId, p.accountId));
|
|
63
|
+
if (s.status === undefined)
|
|
64
|
+
return { code: "auth.required" };
|
|
65
|
+
if (s.status !== "active")
|
|
66
|
+
return { code: "auth.account_disabled" };
|
|
67
|
+
if (s.role === undefined)
|
|
68
|
+
return { code: "org.not_found" };
|
|
69
|
+
return { role: s.role, superAdmin: s.superAdmin };
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The account invalidation streams of this replica (`GET /api/v1/orgs/:orgId/me/stream`, account
|
|
73
|
+
* invalidation stream spec §5): each forwards the hints of its topics as `event: hint` frames.
|
|
74
|
+
* Topics are recomputed on every `runtime.sseRecheckMs` recheck (credential first, then the
|
|
75
|
+
* membership, role, account status and super admin flag); a lost membership, a disabled account or
|
|
76
|
+
* a revoked credential ends the stream with `event: error` (`data: {"code"}`). At most
|
|
77
|
+
* `runtime.meStreamMaxPerAccount` streams per account on this replica: a new one over the cap
|
|
78
|
+
* supersedes the account's oldest (`event: closed`, `data: {"reason":"superseded"}`). No replay:
|
|
79
|
+
* the client refetches on open. Across replicas only through the Redis bus; this process holds
|
|
80
|
+
* only its connections' subscriptions and timers, closed at shutdown.
|
|
81
|
+
*/
|
|
82
|
+
let MeStreams = class MeStreams {
|
|
83
|
+
active = new Set();
|
|
84
|
+
/** Each account's streams on this replica, oldest first (replica-local resource accounting). */
|
|
85
|
+
byAccount = new Map();
|
|
86
|
+
closing = false;
|
|
87
|
+
d;
|
|
88
|
+
constructor(bus, access, config, log, shutdown) {
|
|
89
|
+
this.d = { bus, access, config, log };
|
|
90
|
+
if (shutdown?.signal.aborted)
|
|
91
|
+
this.closeAll();
|
|
92
|
+
else
|
|
93
|
+
shutdown?.signal.addEventListener("abort", () => this.closeAll(), { once: true });
|
|
94
|
+
}
|
|
95
|
+
/** Checks access and subscribes; a refusal throws before anything was written. */
|
|
96
|
+
async open(p, out) {
|
|
97
|
+
const v = await verdict(this.d, p);
|
|
98
|
+
if ("code" in v)
|
|
99
|
+
throw new ApiError(v.code, "Access denied");
|
|
100
|
+
if (this.closing)
|
|
101
|
+
return endedStream(out);
|
|
102
|
+
const conn = new MeConnection(this.d, p, out, () => this.admit(conn), () => this.forget(conn));
|
|
103
|
+
this.active.add(conn);
|
|
104
|
+
try {
|
|
105
|
+
await conn.apply(v.role, v.superAdmin, false);
|
|
106
|
+
}
|
|
107
|
+
catch (e) {
|
|
108
|
+
conn.close();
|
|
109
|
+
throw e;
|
|
110
|
+
}
|
|
111
|
+
if (this.closing || conn.isClosed) {
|
|
112
|
+
conn.close();
|
|
113
|
+
return endedStream(out);
|
|
114
|
+
}
|
|
115
|
+
// counted against the cap only at begin(), once its subscriptions work and its headers go out:
|
|
116
|
+
// a failed open, or a client already gone (never begun), supersedes nothing
|
|
117
|
+
return conn;
|
|
118
|
+
}
|
|
119
|
+
/** Closes every stream of this process (at shutdown) and latches. */
|
|
120
|
+
closeAll() {
|
|
121
|
+
this.closing = true;
|
|
122
|
+
for (const c of [...this.active])
|
|
123
|
+
c.close();
|
|
124
|
+
}
|
|
125
|
+
get size() {
|
|
126
|
+
return this.active.size;
|
|
127
|
+
}
|
|
128
|
+
/** How many streams `accountId` holds on this replica. */
|
|
129
|
+
countOf(accountId) {
|
|
130
|
+
return this.byAccount.get(accountId)?.length ?? 0;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Registers `conn` under its account as it begins, superseding the oldest streams over the cap
|
|
134
|
+
* (read now, so a lowered limit applies at the next stream). The list is complete before any victim closes: a
|
|
135
|
+
* victim's close finds itself already gone and never drops the account's entry.
|
|
136
|
+
*/
|
|
137
|
+
admit(conn) {
|
|
138
|
+
const list = this.byAccount.get(conn.accountId) ?? [];
|
|
139
|
+
const max = this.d.config.get().runtime.meStreamMaxPerAccount;
|
|
140
|
+
const victims = list.splice(0, Math.max(0, list.length - max + 1));
|
|
141
|
+
list.push(conn);
|
|
142
|
+
this.byAccount.set(conn.accountId, list);
|
|
143
|
+
for (const v of victims)
|
|
144
|
+
v.close("end", SUPERSEDED_FRAME);
|
|
145
|
+
}
|
|
146
|
+
forget(conn) {
|
|
147
|
+
this.active.delete(conn);
|
|
148
|
+
const list = this.byAccount.get(conn.accountId);
|
|
149
|
+
if (!list)
|
|
150
|
+
return;
|
|
151
|
+
const i = list.indexOf(conn);
|
|
152
|
+
if (i >= 0)
|
|
153
|
+
list.splice(i, 1);
|
|
154
|
+
if (list.length === 0)
|
|
155
|
+
this.byAccount.delete(conn.accountId);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
MeStreams = __decorate([
|
|
159
|
+
Injectable(),
|
|
160
|
+
__param(0, Inject(KERNEL_BUS)),
|
|
161
|
+
__param(1, Inject(MeStreamAccess)),
|
|
162
|
+
__param(2, Inject(KernelConfigService)),
|
|
163
|
+
__param(3, Inject(KERNEL_LOGGER)),
|
|
164
|
+
__param(4, Optional()),
|
|
165
|
+
__param(4, Inject(GracefulShutdown))
|
|
166
|
+
], MeStreams);
|
|
167
|
+
export { MeStreams };
|
|
168
|
+
class MeConnection {
|
|
169
|
+
d;
|
|
170
|
+
p;
|
|
171
|
+
out;
|
|
172
|
+
onBegin;
|
|
173
|
+
onClosed;
|
|
174
|
+
closed = false;
|
|
175
|
+
begun = false;
|
|
176
|
+
rechecking = false;
|
|
177
|
+
role;
|
|
178
|
+
superAdmin = false;
|
|
179
|
+
/**
|
|
180
|
+
* The topics subscribed now, each with its own subscription: a topic leaves this map before its
|
|
181
|
+
* unsubscribe is awaited, and a handler delivers only while its own subscription is the current
|
|
182
|
+
* one (a topic dropped and re-added never delivers twice).
|
|
183
|
+
*/
|
|
184
|
+
subs = new Map();
|
|
185
|
+
timers = [];
|
|
186
|
+
constructor(d, p, out,
|
|
187
|
+
/** Counts the stream against the per-account cap; called by `begin()`. */
|
|
188
|
+
onBegin, onClosed) {
|
|
189
|
+
this.d = d;
|
|
190
|
+
this.p = p;
|
|
191
|
+
this.out = out;
|
|
192
|
+
this.onBegin = onBegin;
|
|
193
|
+
this.onClosed = onClosed;
|
|
194
|
+
}
|
|
195
|
+
get accountId() {
|
|
196
|
+
return this.p.accountId;
|
|
197
|
+
}
|
|
198
|
+
get isClosed() {
|
|
199
|
+
return this.closed;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Moves the subscriptions to the topics of (`role`, `superAdmin`): dropped topics stop
|
|
203
|
+
* delivering at once, new ones are subscribed. On an upgrade (`notify`) the client is told to
|
|
204
|
+
* refetch what the new role sees.
|
|
205
|
+
*/
|
|
206
|
+
async apply(role, superAdmin, notify) {
|
|
207
|
+
const before = this.role;
|
|
208
|
+
const wasSuperAdmin = this.superAdmin;
|
|
209
|
+
this.role = role;
|
|
210
|
+
this.superAdmin = superAdmin;
|
|
211
|
+
const want = new Set(streamTopics({ accountId: this.p.accountId, orgId: this.p.orgId, role, superAdmin }));
|
|
212
|
+
for (const [topic, sub] of [...this.subs]) {
|
|
213
|
+
if (want.has(topic))
|
|
214
|
+
continue;
|
|
215
|
+
this.subs.delete(topic);
|
|
216
|
+
void this.release(topic, sub);
|
|
217
|
+
}
|
|
218
|
+
const added = [...want].filter((t) => !this.subs.has(t));
|
|
219
|
+
const fresh = added.map((topic) => {
|
|
220
|
+
const sub = { un: Promise.resolve(undefined) };
|
|
221
|
+
sub.un = this.subscribe(topic, sub);
|
|
222
|
+
this.subs.set(topic, sub);
|
|
223
|
+
return sub.un;
|
|
224
|
+
});
|
|
225
|
+
await Promise.all(fresh);
|
|
226
|
+
if (!notify || this.closed)
|
|
227
|
+
return;
|
|
228
|
+
if (before !== undefined && roleRank(role) > roleRank(before)) {
|
|
229
|
+
this.send({ kind: "capabilities" });
|
|
230
|
+
this.send({ kind: "inbox" });
|
|
231
|
+
}
|
|
232
|
+
if (superAdmin && !wasSuperAdmin)
|
|
233
|
+
this.send({ kind: "platform-inbox" });
|
|
234
|
+
}
|
|
235
|
+
async subscribe(topic, sub) {
|
|
236
|
+
const current = () => this.subs.get(topic) === sub;
|
|
237
|
+
const un = await this.d.bus.subscribe(topic, (m) => {
|
|
238
|
+
// only while this subscription is the topic's current one (a downgrade drops it at once)
|
|
239
|
+
if (!current())
|
|
240
|
+
return;
|
|
241
|
+
const h = parseHint(m);
|
|
242
|
+
if (h === undefined) {
|
|
243
|
+
this.d.log.warn("me stream dropped a malformed hint", { topic });
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
this.send(h);
|
|
247
|
+
});
|
|
248
|
+
if (this.closed || !current()) {
|
|
249
|
+
await un();
|
|
250
|
+
return undefined;
|
|
251
|
+
}
|
|
252
|
+
return un;
|
|
253
|
+
}
|
|
254
|
+
async release(topic, sub) {
|
|
255
|
+
try {
|
|
256
|
+
const un = await sub.un;
|
|
257
|
+
await un?.();
|
|
258
|
+
}
|
|
259
|
+
catch (err) {
|
|
260
|
+
this.d.log.warn("me stream unsubscribe failed", { orgId: this.p.orgId, topic, err });
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
begin() {
|
|
264
|
+
if (this.closed) {
|
|
265
|
+
// closed before the headers went out (shutdown): end the empty stream
|
|
266
|
+
try {
|
|
267
|
+
this.out.end();
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
// the connection is already gone
|
|
271
|
+
}
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
this.begun = true;
|
|
275
|
+
this.onBegin();
|
|
276
|
+
const { sseHeartbeatMs, sseRecheckMs } = this.d.config.get().runtime;
|
|
277
|
+
this.timers.push(setInterval(() => this.write(": ping\n\n"), sseHeartbeatMs), setInterval(() => void this.recheck(), sseRecheckMs));
|
|
278
|
+
}
|
|
279
|
+
close(mode = "end", finalFrame) {
|
|
280
|
+
if (this.closed)
|
|
281
|
+
return;
|
|
282
|
+
this.closed = true;
|
|
283
|
+
for (const t of this.timers)
|
|
284
|
+
clearInterval(t);
|
|
285
|
+
this.timers = [];
|
|
286
|
+
for (const [topic, sub] of [...this.subs])
|
|
287
|
+
void this.release(topic, sub);
|
|
288
|
+
this.subs.clear();
|
|
289
|
+
if (this.begun) {
|
|
290
|
+
try {
|
|
291
|
+
if (finalFrame !== undefined && mode === "end")
|
|
292
|
+
this.out.write(finalFrame);
|
|
293
|
+
if (mode === "abort")
|
|
294
|
+
this.out.abort();
|
|
295
|
+
else
|
|
296
|
+
this.out.end();
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
// the connection is already gone
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
this.onClosed();
|
|
303
|
+
}
|
|
304
|
+
send(h) {
|
|
305
|
+
// hints before begin() (headers not written yet) are dropped: the client refetches on open
|
|
306
|
+
if (!this.begun)
|
|
307
|
+
return;
|
|
308
|
+
this.write(hintFrame(h));
|
|
309
|
+
}
|
|
310
|
+
write(chunk) {
|
|
311
|
+
if (this.closed || !this.begun)
|
|
312
|
+
return;
|
|
313
|
+
try {
|
|
314
|
+
this.out.write(chunk);
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
this.close("abort");
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
if (this.out.backlog() > ME_STREAM_MAX_BACKLOG_BYTES) {
|
|
321
|
+
this.d.log.warn("me stream client too slow; closing", { orgId: this.p.orgId });
|
|
322
|
+
this.close("abort");
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
/** Re-checks access and recomputes the topics; a refusal sends `event: error` and closes. */
|
|
326
|
+
async recheck() {
|
|
327
|
+
if (this.closed || this.rechecking)
|
|
328
|
+
return;
|
|
329
|
+
this.rechecking = true;
|
|
330
|
+
try {
|
|
331
|
+
const v = await verdict(this.d, this.p);
|
|
332
|
+
if (this.closed)
|
|
333
|
+
return;
|
|
334
|
+
if ("code" in v) {
|
|
335
|
+
this.fail(v.code);
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
await this.apply(v.role, v.superAdmin, true);
|
|
339
|
+
}
|
|
340
|
+
catch (err) {
|
|
341
|
+
this.d.log.warn("me stream access re-check failed; closing", { orgId: this.p.orgId, err });
|
|
342
|
+
this.fail("internal");
|
|
343
|
+
}
|
|
344
|
+
finally {
|
|
345
|
+
this.rechecking = false;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
fail(code) {
|
|
349
|
+
this.close("end", `event: error\ndata: ${JSON.stringify({ code })}\n\n`);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This replica's account invalidation streams ({@link MeStreams}, served by `MeStreamController`,
|
|
3
|
+
* listed in `ApiModule`'s controllers). Imported only by `ApiModule`, so a process without the api
|
|
4
|
+
* role holds no stream machinery.
|
|
5
|
+
*/
|
|
6
|
+
export declare class MeStreamModule {
|
|
7
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
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
|
+
import { Module } from "@nestjs/common";
|
|
8
|
+
import { MeStreamAccess, MeStreams } from "./me-stream.js";
|
|
9
|
+
/**
|
|
10
|
+
* This replica's account invalidation streams ({@link MeStreams}, served by `MeStreamController`,
|
|
11
|
+
* listed in `ApiModule`'s controllers). Imported only by `ApiModule`, so a process without the api
|
|
12
|
+
* role holds no stream machinery.
|
|
13
|
+
*/
|
|
14
|
+
let MeStreamModule = class MeStreamModule {
|
|
15
|
+
};
|
|
16
|
+
MeStreamModule = __decorate([
|
|
17
|
+
Module({
|
|
18
|
+
providers: [MeStreamAccess, MeStreams],
|
|
19
|
+
exports: [MeStreams],
|
|
20
|
+
})
|
|
21
|
+
], MeStreamModule);
|
|
22
|
+
export { MeStreamModule };
|
package/dist/kernel.module.js
CHANGED
|
@@ -40,6 +40,7 @@ import { RedisModule } from "./infra/redis/redis.module.js";
|
|
|
40
40
|
import { KernelThrottlerModule } from "./infra/throttler/throttler.module.js";
|
|
41
41
|
import { KERNEL_POOL, REDIS } from "./infra/tokens.js";
|
|
42
42
|
import { ValidationModule } from "./infra/validation/validation.module.js";
|
|
43
|
+
import { InvalidationHintsModule } from "./invalidation/invalidation-hints.module.js";
|
|
43
44
|
import { KernelLifecycle } from "./lifecycle/kernel-lifecycle.js";
|
|
44
45
|
import { KERNEL_APP_OPTIONS } from "./lifecycle/tokens.js";
|
|
45
46
|
import { createConfiguredLogger } from "./log-config.js";
|
|
@@ -142,6 +143,9 @@ let KernelModule = KernelModule_1 = class KernelModule {
|
|
|
142
143
|
TriggerEventsModule,
|
|
143
144
|
// ctx.inbox: personal inbox items extensions post (the host finds it at the time of use)
|
|
144
145
|
InboxItemsModule,
|
|
146
|
+
// account invalidation hints: writers on every role (api requests, worker jobs, gateway
|
|
147
|
+
// events) publish them; the streams that deliver them are the api role's (MeStreamModule)
|
|
148
|
+
InvalidationHintsModule,
|
|
145
149
|
// ctx.agents / ctx.conversations / ctx.people: read-only org facts (found at the time of use)
|
|
146
150
|
PluginReadsModule,
|
|
147
151
|
// ctx.conversations' external methods and the external conversation calls' queue (found at
|
|
@@ -799,6 +799,11 @@ export const PLATFORM_EXCLUSIONS = [
|
|
|
799
799
|
category: "transport",
|
|
800
800
|
reason: "Server-sent event stream of UI invalidations",
|
|
801
801
|
},
|
|
802
|
+
{
|
|
803
|
+
route: "GET /api/v1/orgs/:orgId/me/stream",
|
|
804
|
+
category: "transport",
|
|
805
|
+
reason: "Server-sent event stream of inbox and request invalidations",
|
|
806
|
+
},
|
|
802
807
|
{
|
|
803
808
|
route: "GET /api/v1/admin/ui/contributions",
|
|
804
809
|
category: "internal",
|
package/package.json
CHANGED