@capybara-hq/kernel 0.1.0-rc.140 → 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/agents/models.controller.d.ts +9 -2
- package/dist/agents/models.controller.js +35 -4
- package/dist/catalog/catalog-scope.service.js +3 -0
- package/dist/catalog/catalog.module.js +8 -0
- package/dist/catalog/catalog.service.d.ts +2 -2
- package/dist/catalog/catalog.service.js +3 -3
- package/dist/catalog/component-scope.controller.d.ts +2 -1
- package/dist/catalog/component-scope.controller.js +5 -2
- package/dist/catalog/component-scope.service.d.ts +16 -0
- package/dist/catalog/component-scope.service.js +21 -1
- package/dist/catalog/enable-decision.d.ts +34 -0
- package/dist/catalog/enable-decision.js +17 -0
- package/dist/catalog/enable-requests.d.ts +186 -0
- package/dist/catalog/enable-requests.js +767 -0
- package/dist/catalog/enable-targets.d.ts +63 -0
- package/dist/catalog/enable-targets.js +94 -0
- package/dist/catalog/org-catalog.controller.d.ts +11 -3
- package/dist/catalog/org-catalog.controller.js +28 -5
- package/dist/catalog/org-catalog.schemas.d.ts +38 -0
- package/dist/catalog/org-catalog.schemas.js +31 -0
- package/dist/catalog/org-catalog.service.js +1 -1
- package/dist/catalog/org-extension.controller.d.ts +1 -1
- package/dist/catalog/owned-items.js +6 -1
- package/dist/catalog/plugin-install.js +7 -2
- package/dist/catalog/plugin-upgrade.js +3 -0
- package/dist/catalog/request-rules.d.ts +7 -5
- package/dist/catalog/request-rules.js +53 -14
- package/dist/catalog/requests.service.d.ts +137 -4
- package/dist/catalog/requests.service.js +574 -28
- package/dist/catalog/scope-writer.d.ts +20 -3
- package/dist/catalog/scope-writer.js +32 -3
- package/dist/config/schema.d.ts +1 -0
- package/dist/config/schema.js +10 -0
- package/dist/ctx/bus.js +3 -2
- package/dist/db/kernel-schema.d.ts +3 -2
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +7 -0
- package/dist/extensions/admin-ops.js +2 -0
- package/dist/extensions/admin-view.js +2 -1
- package/dist/extensions/host.js +1 -1
- package/dist/extensions/org-config.d.ts +8 -0
- package/dist/extensions/org-config.js +20 -5
- package/dist/extensions/permission-view.d.ts +7 -0
- package/dist/extensions/plugin-guides.d.ts +1 -1
- package/dist/extensions/plugin-guides.js +1 -1
- package/dist/extensions/plugin-items.d.ts +8 -0
- package/dist/extensions/plugin-items.js +8 -0
- package/dist/http/api.module.js +6 -0
- package/dist/infra/config/kernel-config.service.js +2 -0
- package/dist/infra/queue/run-job.js +3 -1
- 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/models/enablement.d.ts +12 -0
- package/dist/models/enablement.js +32 -0
- package/dist/platform/exclusions.js +5 -0
- package/dist/platform/ops/admin.ops.js +2 -2
- package/dist/platform/ops/catalog-admin.ops.js +1 -1
- package/dist/platform/ops/extensions-admin.ops.js +17 -9
- package/dist/platform/ops/extensions.ops.js +6 -3
- package/dist/platform/ops/org-plugins.ops.js +1 -1
- package/dist/platform/ops/plugins.ops.js +1 -1
- package/dist/platform/ops/requests.ops.js +55 -1
- package/dist/platform/ops/unavailable.js +2 -2
- package/dist/tools/builtins/sandbox/common.d.ts +3 -3
- package/dist/tools/builtins/sandbox/common.js +3 -3
- package/dist/tools/connectors.controller.d.ts +8 -1
- package/dist/tools/connectors.controller.js +14 -1
- package/dist/tools/connectors.service.d.ts +7 -0
- package/dist/tools/connectors.service.js +30 -0
- package/package.json +1 -1
- package/src/migrations/0233_enable_request_targets.sql +64 -0
|
@@ -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 };
|