@capybara-hq/kernel 0.1.0-rc.132 → 0.1.0-rc.133
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/bootstrap.json +5 -5
- package/dist/admin/admin.module.js +3 -0
- package/dist/admin/admin.schemas.d.ts +4 -0
- package/dist/admin/health.service.d.ts +2 -2
- package/dist/admin/health.service.js +6 -2
- package/dist/admin/setup.service.js +6 -1
- package/dist/agents/agents.controller.js +3 -2
- package/dist/agents/agents.service.d.ts +2 -0
- package/dist/agents/agents.service.js +7 -0
- package/dist/catalog/catalog.service.d.ts +2 -0
- package/dist/catalog/catalog.service.js +28 -5
- package/dist/catalog/marketplace-fetch.d.ts +2 -0
- package/dist/catalog/marketplace-fetch.js +15 -0
- package/dist/catalog/marketplaces.service.d.ts +4 -4
- package/dist/catalog/marketplaces.service.js +3 -2
- package/dist/catalog/owned-items.d.ts +2 -0
- package/dist/catalog/owned-items.js +30 -31
- package/dist/catalog/ownership.js +40 -38
- package/dist/catalog/plugin-import.d.ts +3 -4
- package/dist/catalog/plugin-import.js +50 -1
- package/dist/catalog/plugin-upgrade.d.ts +8 -0
- package/dist/catalog/plugin-upgrade.js +95 -7
- package/dist/catalog/publisher-policy.d.ts +9 -0
- package/dist/catalog/publisher-policy.js +12 -0
- package/dist/catalog/unshare.js +66 -58
- package/dist/client/client-access.service.js +5 -3
- package/dist/config/schema.js +1 -1
- package/dist/conversations/conversations.controller.js +4 -14
- package/dist/conversations/conversations.service.d.ts +14 -0
- package/dist/conversations/conversations.service.js +20 -2
- package/dist/ctx/create-ctx.d.ts +11 -2
- package/dist/ctx/create-ctx.js +121 -52
- package/dist/ctx/queue.js +7 -4
- package/dist/db/extension-rls-predicate.d.ts +1 -0
- package/dist/db/extension-rls-predicate.js +8 -0
- package/dist/db/kernel-schema.d.ts +48 -0
- package/dist/db/migrator.js +6 -13
- package/dist/db/pool.d.ts +2 -2
- package/dist/db/pool.js +2 -2
- package/dist/db/sql-statements.d.ts +3 -0
- package/dist/db/sql-statements.js +15 -5
- package/dist/device-access/device-access.module.js +12 -2
- package/dist/device-access/device-access.service.d.ts +30 -2
- package/dist/device-access/device-access.service.js +38 -4
- package/dist/device-access/host-gate.d.ts +45 -0
- package/dist/device-access/host-gate.js +92 -0
- package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
- package/dist/device-access/host-service-stop-sweep.js +112 -0
- package/dist/device-access/host-service-stop.d.ts +78 -0
- package/dist/device-access/host-service-stop.js +144 -0
- package/dist/device-access/host-services.d.ts +211 -0
- package/dist/device-access/host-services.js +803 -0
- package/dist/device-access/person-handles.d.ts +10 -0
- package/dist/device-access/person-handles.js +25 -0
- package/dist/device-access/service-events.d.ts +199 -0
- package/dist/device-access/service-events.js +704 -0
- package/dist/device-access/token.d.ts +5 -0
- package/dist/device-access/token.js +5 -0
- package/dist/devices/devices.service.js +3 -0
- package/dist/dial-in/access.d.ts +5 -5
- package/dist/dial-in/access.js +19 -12
- package/dist/dial-in/gateway.js +6 -2
- package/dist/dial-in/machines.d.ts +9 -2
- package/dist/dial-in/machines.js +27 -4
- package/dist/erasure/device-cleanup.js +12 -0
- package/dist/erasure/org-catalog.js +2 -2
- package/dist/erasure/org-rules.js +9 -0
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +2 -0
- package/dist/extensions/admin-ops.js +8 -2
- package/dist/extensions/deployed-snapshots.d.ts +4 -1
- package/dist/extensions/deployed-snapshots.js +7 -2
- package/dist/extensions/host.d.ts +7 -2
- package/dist/extensions/host.js +11 -2
- package/dist/extensions/instance.d.ts +3 -0
- package/dist/extensions/instance.js +4 -0
- package/dist/extensions/ledger.d.ts +1 -1
- package/dist/extensions/lifecycle-hooks.js +3 -3
- package/dist/extensions/org-config.js +6 -1
- package/dist/extensions/permission-set.d.ts +7 -0
- package/dist/extensions/permission-set.js +10 -0
- package/dist/extensions/permission-view.d.ts +1 -1
- package/dist/extensions/permission-view.js +10 -1
- package/dist/git/tickets.js +32 -27
- package/dist/http/app.js +5 -3
- package/dist/identity/accounts.d.ts +6 -1
- package/dist/identity/accounts.js +11 -2
- package/dist/identity/api-tokens.js +7 -6
- package/dist/identity/settings.d.ts +9 -1
- package/dist/identity/settings.js +16 -1
- package/dist/inbox/org-notices.js +3 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/infra/database/scoped-dialect.d.ts +3 -2
- package/dist/infra/database/scoped-dialect.js +260 -72
- package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
- package/dist/infra/database/startup-activation-transaction.js +3 -2
- package/dist/infra/outbox/registry.d.ts +28 -0
- package/dist/infra/outbox/registry.js +30 -0
- package/dist/infra/queue/queue-names.d.ts +1 -1
- package/dist/infra/queue/queue-names.js +1 -0
- package/dist/infra/queue/run-job.d.ts +4 -1
- package/dist/infra/queue/run-job.js +10 -2
- package/dist/kernel.module.js +3 -0
- package/dist/orgs/offboarding.js +18 -9
- package/dist/orgs/settings.service.js +3 -0
- package/dist/packages/npm-publish-keys.json +27 -0
- package/dist/packages/official-publisher.d.ts +19 -0
- package/dist/packages/official-publisher.js +152 -0
- package/dist/packages/provenance.d.ts +7 -0
- package/dist/packages/provenance.js +22 -19
- package/dist/packages/sigstore-trusted-root.json +126 -0
- package/dist/platform/ops/admin.ops.js +2 -1
- package/dist/platform/ops/orgs.ops.js +1 -0
- package/dist/roles/worker-role.d.ts +6 -3
- package/dist/roles/worker-role.js +12 -4
- package/dist/roles/worker.module.js +7 -0
- package/dist/runtime/maintenance.d.ts +5 -2
- package/dist/runtime/maintenance.js +18 -4
- package/dist/sandbox/device-reports.d.ts +4 -4
- package/dist/sandbox/device-reports.js +40 -30
- package/dist/sandbox/device-services.d.ts +2 -1
- package/dist/sandbox/device-services.js +5 -1
- package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
- package/dist/sandbox/permission-ceiling-writes.js +21 -0
- package/dist/sandbox/permission-config-publication.js +5 -1
- package/dist/themes/theme-state.js +24 -13
- package/dist/tools/call-scope.d.ts +6 -0
- package/dist/tools/call-scope.js +22 -0
- package/dist/tools/registry.js +20 -2
- package/dist/ui/views.js +36 -8
- package/package.json +9 -4
- package/src/migrations/0222_device_host_services.sql +27 -0
- package/src/migrations/0223_device_service_events.sql +54 -0
- package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
|
@@ -1,12 +1,164 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1
2
|
import { CompiledQuery, PostgresDialect, } from "kysely";
|
|
3
|
+
import pg from "pg";
|
|
2
4
|
import { currentScope, scopeKey, unscopedQueryCheck } from "./org-scope.js";
|
|
3
|
-
const SET_SCOPE = "select set_config('capybara.org_id', $1,
|
|
4
|
-
"set_config('capybara.
|
|
5
|
-
|
|
6
|
-
function
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
5
|
+
const SET_SCOPE = "select pg_catalog.set_config('capybara.org_id', $1, true), " +
|
|
6
|
+
"pg_catalog.set_config('capybara.scope', $2, true), " +
|
|
7
|
+
"pg_catalog.set_config('capybara.rls', $3, true)";
|
|
8
|
+
function scopeValues(scope, mode) {
|
|
9
|
+
return [scope?.kind === "org" ? scope.orgId : "", scope?.kind ?? "", mode];
|
|
10
|
+
}
|
|
11
|
+
const PREPARED_SCOPE = "capybara_set_local_scope";
|
|
12
|
+
/** Set the idle defaults. Each transaction reasserts its settings even after a session reset. */
|
|
13
|
+
function initializeScope(mode, prepare) {
|
|
14
|
+
const initialize = "select pg_catalog.set_config('capybara.org_id', '', false), " +
|
|
15
|
+
"pg_catalog.set_config('capybara.scope', '', false), " +
|
|
16
|
+
`pg_catalog.set_config('capybara.rls', '${mode}', false)`;
|
|
17
|
+
return prepare
|
|
18
|
+
? `${initialize}; prepare ${PREPARED_SCOPE}(text, text, text) as ${SET_SCOPE}`
|
|
19
|
+
: initialize;
|
|
20
|
+
}
|
|
21
|
+
function beginSql(scope, mode, settings) {
|
|
22
|
+
let sql = "begin";
|
|
23
|
+
if (settings.isolationLevel)
|
|
24
|
+
sql += ` isolation level ${settings.isolationLevel}`;
|
|
25
|
+
if (settings.accessMode)
|
|
26
|
+
sql += ` ${settings.accessMode}`;
|
|
27
|
+
const [orgId, kind] = scopeValues(scope, mode);
|
|
28
|
+
if (orgId.includes("\0"))
|
|
29
|
+
throw new Error("An org scope cannot contain a NUL byte");
|
|
30
|
+
return (`${sql}; set local capybara.rls = '${mode}'; set local capybara.scope = '${kind}'; ` +
|
|
31
|
+
`set local capybara.org_id = ${pg.escapeLiteral(orgId)}`);
|
|
32
|
+
}
|
|
33
|
+
const STANDALONE = "/* scope transaction */ ";
|
|
34
|
+
const COMMIT_STANDALONE = CompiledQuery.raw(`${STANDALONE}commit`);
|
|
35
|
+
const ROLLBACK = CompiledQuery.raw("rollback");
|
|
36
|
+
/**
|
|
37
|
+
* Reuse plans for recurring scoped reads. A connection prepares at most 64 statements and
|
|
38
|
+
* remembers at most 128 first sightings; query shapes seen only once never use a prepared slot.
|
|
39
|
+
* PostgreSQL still chooses between custom and generic plans for the bound parameters.
|
|
40
|
+
*/
|
|
41
|
+
class ReadPlans {
|
|
42
|
+
seen = new Set();
|
|
43
|
+
prepared = new Map();
|
|
44
|
+
nameFor(sql, parameters) {
|
|
45
|
+
// Avoid expanding wildcards in persistent prepared result types during rolling migrations.
|
|
46
|
+
if (!parameters.length ||
|
|
47
|
+
sql.length > 4096 ||
|
|
48
|
+
!sql.startsWith("select ") ||
|
|
49
|
+
sql.includes("*") ||
|
|
50
|
+
sql === SET_SCOPE)
|
|
51
|
+
return undefined;
|
|
52
|
+
const name = this.prepared.get(sql);
|
|
53
|
+
if (name || this.prepared.size >= 64)
|
|
54
|
+
return name;
|
|
55
|
+
if (this.seen.delete(sql)) {
|
|
56
|
+
const prepared = `capybara_read_${this.prepared.size}`;
|
|
57
|
+
this.prepared.set(sql, prepared);
|
|
58
|
+
return prepared;
|
|
59
|
+
}
|
|
60
|
+
if (this.seen.size === 128) {
|
|
61
|
+
const oldest = this.seen.values().next().value;
|
|
62
|
+
if (oldest !== undefined)
|
|
63
|
+
this.seen.delete(oldest);
|
|
64
|
+
}
|
|
65
|
+
this.seen.add(sql);
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* PostgreSQL executes the scope prelude and the statement in one implicit transaction when
|
|
71
|
+
* both executions precede the same Sync. The server discards the local settings at Sync,
|
|
72
|
+
* and skips the statement entirely if the prelude fails.
|
|
73
|
+
*/
|
|
74
|
+
function scopedStatement(client, scope, mode, sql, parameters, name) {
|
|
75
|
+
return new Promise((resolve, reject) => {
|
|
76
|
+
const config = { text: sql, values: [...parameters], queryMode: "extended", name };
|
|
77
|
+
const query = new pg.Query(config, (error, results) => {
|
|
78
|
+
if (error) {
|
|
79
|
+
reject(error);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
// The first result is the scope prelude. An empty user statement has no result.
|
|
83
|
+
const result = Array.isArray(results) ? results[1] : undefined;
|
|
84
|
+
resolve((result ?? { rows: [], command: "", rowCount: 0 }));
|
|
85
|
+
});
|
|
86
|
+
const submit = query.submit.bind(query);
|
|
87
|
+
query.submit = (connection) => {
|
|
88
|
+
connection.stream.cork();
|
|
89
|
+
try {
|
|
90
|
+
connection.bind({
|
|
91
|
+
statement: PREPARED_SCOPE,
|
|
92
|
+
values: scopeValues(scope, mode),
|
|
93
|
+
}, true);
|
|
94
|
+
connection.describe({ type: "P" }, true);
|
|
95
|
+
connection.execute(null, true);
|
|
96
|
+
return submit(connection);
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
connection.stream.uncork();
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
// The scoped kernel pool uses node-postgres. Other Kysely-compatible pools use explicit
|
|
103
|
+
// transactions through the driver without passing a node-postgres Query object.
|
|
104
|
+
client.query(query);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
/** Initialize each physical session once, before Kysely can reserve it. */
|
|
108
|
+
function withScopedConnections(pool, mode, scopeStore) {
|
|
109
|
+
const wrapped = new WeakMap();
|
|
110
|
+
const initialize = initializeScope(mode, !!scopeStore);
|
|
111
|
+
return {
|
|
112
|
+
...(pool.Client ? { Client: pool.Client } : {}),
|
|
113
|
+
options: pool.options,
|
|
114
|
+
end: () => pool.end(),
|
|
115
|
+
async connect() {
|
|
116
|
+
const client = await pool.connect();
|
|
117
|
+
const existing = wrapped.get(client);
|
|
118
|
+
if (existing)
|
|
119
|
+
return existing;
|
|
120
|
+
try {
|
|
121
|
+
await client.query(initialize, []);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
// Discard this session so a failed bootstrap cannot leave it checked out or usable.
|
|
125
|
+
client.release(true);
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
const plans = scopeStore ? new ReadPlans() : undefined;
|
|
129
|
+
let discard = false;
|
|
130
|
+
const connection = new Proxy(client, {
|
|
131
|
+
get(target, prop) {
|
|
132
|
+
if (prop === "release")
|
|
133
|
+
return () => target.release(discard);
|
|
134
|
+
if (prop === "query") {
|
|
135
|
+
return (query, parameters = []) => {
|
|
136
|
+
const pgClient = target;
|
|
137
|
+
// Kysely passes a cursor object to this method when streaming.
|
|
138
|
+
if (typeof query !== "string")
|
|
139
|
+
return pgClient.query(query);
|
|
140
|
+
const binding = scopeStore?.getStore();
|
|
141
|
+
const name = plans?.nameFor(query, parameters);
|
|
142
|
+
const result = binding
|
|
143
|
+
? scopedStatement(target, binding.scope, mode, query, parameters, name)
|
|
144
|
+
: name
|
|
145
|
+
? pgClient.query({ text: query, values: [...parameters], name })
|
|
146
|
+
: target.query(query, parameters);
|
|
147
|
+
return result.catch((error) => {
|
|
148
|
+
if (error instanceof pg.DatabaseError && error.code === "26000")
|
|
149
|
+
discard = true;
|
|
150
|
+
throw error;
|
|
151
|
+
});
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
const value = Reflect.get(target, prop);
|
|
155
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
wrapped.set(client, connection);
|
|
159
|
+
return connection;
|
|
160
|
+
},
|
|
161
|
+
};
|
|
10
162
|
}
|
|
11
163
|
/** Tables of the `capybara` schema with an `org_id` column (for the unscoped-query check). */
|
|
12
164
|
const ORG_TABLES_SQL = "select table_name from information_schema.columns " +
|
|
@@ -25,26 +177,23 @@ export const captureUnscopedQueryOrigins = {
|
|
|
25
177
|
};
|
|
26
178
|
const TABLE_REF = /"capybara"\."([a-z0-9_]+)"|\bcapybara\.([a-z0-9_]+)/g;
|
|
27
179
|
/**
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
* three: whatever an earlier holder left on the connection is overwritten before it can be read,
|
|
33
|
-
* and a returned connection carries no scope into its next user. Queries on one checkout run one
|
|
34
|
-
* after another (as pg runs them anyway), so a scope change and the query it precedes are never
|
|
35
|
-
* split by another query of the same transaction.
|
|
180
|
+
* A checkout's tenant and platform values are transaction-local. Explicit transactions start
|
|
181
|
+
* with the caller's scope and reset it only on a scope transition. A standalone scoped query
|
|
182
|
+
* owns a short transaction. Queries on one checkout are serialized, keeping each transition
|
|
183
|
+
* together with the query it applies to.
|
|
36
184
|
*/
|
|
37
185
|
class ScopedConnection {
|
|
38
186
|
inner;
|
|
39
|
-
|
|
187
|
+
mode;
|
|
188
|
+
standaloneScope;
|
|
40
189
|
orgTables;
|
|
41
|
-
/** The scope key now on the connection; undefined when unknown (fresh, or after a commit). */
|
|
42
190
|
applied;
|
|
43
191
|
inTransaction = false;
|
|
44
192
|
tail = Promise.resolve();
|
|
45
|
-
constructor(inner,
|
|
193
|
+
constructor(inner, mode, standaloneScope, orgTables) {
|
|
46
194
|
this.inner = inner;
|
|
47
|
-
this.
|
|
195
|
+
this.mode = mode;
|
|
196
|
+
this.standaloneScope = standaloneScope;
|
|
48
197
|
this.orgTables = orgTables;
|
|
49
198
|
}
|
|
50
199
|
// cancellation (an aborted query) goes to the inner connection, which knows the backend; the
|
|
@@ -66,7 +215,7 @@ class ScopedConnection {
|
|
|
66
215
|
if (this.applied === key)
|
|
67
216
|
return;
|
|
68
217
|
this.applied = undefined;
|
|
69
|
-
await this.inner.executeQuery(
|
|
218
|
+
await this.inner.executeQuery(CompiledQuery.raw(SET_SCOPE, scopeValues(scope, this.mode)));
|
|
70
219
|
this.applied = key;
|
|
71
220
|
}
|
|
72
221
|
async check(scope, query) {
|
|
@@ -84,75 +233,98 @@ class ScopedConnection {
|
|
|
84
233
|
const scope = currentScope();
|
|
85
234
|
return this.serial(async () => {
|
|
86
235
|
await this.check(scope, query);
|
|
87
|
-
|
|
88
|
-
|
|
236
|
+
if (this.inTransaction) {
|
|
237
|
+
await this.ensure(scope);
|
|
238
|
+
return this.inner.executeQuery(query);
|
|
239
|
+
}
|
|
240
|
+
// Extended protocol parses one statement. A raw SQL batch uses an explicit transaction.
|
|
241
|
+
if (this.standaloneScope && (query.parameters.length || !query.sql.includes(";"))) {
|
|
242
|
+
return this.standaloneScope.run({ scope }, () => this.inner.executeQuery(query));
|
|
243
|
+
}
|
|
244
|
+
await this.beginScoped(scope, {}, STANDALONE);
|
|
245
|
+
try {
|
|
246
|
+
const result = await this.inner.executeQuery(query);
|
|
247
|
+
await this.finish(() => this.inner.executeQuery(COMMIT_STANDALONE));
|
|
248
|
+
return result;
|
|
249
|
+
}
|
|
250
|
+
catch (error) {
|
|
251
|
+
await this.finish(() => this.inner.executeQuery(ROLLBACK)).catch(() => { });
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
89
254
|
});
|
|
90
255
|
}
|
|
91
|
-
/**
|
|
92
|
-
* A cursor holds this checkout until it is closed: the scope is set and the stream read inside
|
|
93
|
-
* one serial step, so no query of another scope runs in between.
|
|
94
|
-
*/
|
|
256
|
+
/** Keep the serial lane and the local scope until the cursor is closed. */
|
|
95
257
|
async *streamQuery(query, chunkSize) {
|
|
96
258
|
const scope = currentScope();
|
|
97
|
-
let release = () => { };
|
|
259
|
+
let release = (_completed) => { };
|
|
98
260
|
const held = new Promise((resolve) => {
|
|
99
261
|
release = resolve;
|
|
100
262
|
});
|
|
101
|
-
let
|
|
102
|
-
|
|
103
|
-
|
|
263
|
+
let entered = () => { };
|
|
264
|
+
let rejected = (_error) => { };
|
|
265
|
+
const ready = new Promise((resolve, reject) => {
|
|
266
|
+
entered = resolve;
|
|
267
|
+
rejected = reject;
|
|
104
268
|
});
|
|
105
|
-
|
|
269
|
+
const step = this.serial(async () => {
|
|
270
|
+
const standalone = !this.inTransaction;
|
|
106
271
|
try {
|
|
107
272
|
await this.check(scope, query);
|
|
108
|
-
|
|
273
|
+
if (standalone)
|
|
274
|
+
await this.beginScoped(scope, {}, STANDALONE);
|
|
275
|
+
else if (this.inTransaction)
|
|
276
|
+
await this.ensure(scope);
|
|
109
277
|
}
|
|
110
278
|
catch (error) {
|
|
111
|
-
|
|
279
|
+
rejected(error);
|
|
112
280
|
return;
|
|
113
281
|
}
|
|
114
|
-
|
|
115
|
-
await held;
|
|
282
|
+
entered();
|
|
283
|
+
const completed = await held;
|
|
284
|
+
if (standalone) {
|
|
285
|
+
await this.finish(() => this.inner.executeQuery(completed ? COMMIT_STANDALONE : ROLLBACK));
|
|
286
|
+
}
|
|
116
287
|
});
|
|
288
|
+
let completed = false;
|
|
117
289
|
try {
|
|
118
|
-
await
|
|
290
|
+
await ready;
|
|
119
291
|
yield* this.inner.streamQuery(query, chunkSize);
|
|
292
|
+
completed = true;
|
|
120
293
|
}
|
|
121
294
|
finally {
|
|
122
|
-
release();
|
|
295
|
+
release(completed);
|
|
296
|
+
await step;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
async beginScoped(scope, settings, prefix = "") {
|
|
300
|
+
const sql = prefix + beginSql(scope, this.mode, settings);
|
|
301
|
+
try {
|
|
302
|
+
await this.inner.executeQuery(CompiledQuery.raw(sql));
|
|
303
|
+
}
|
|
304
|
+
catch (error) {
|
|
305
|
+
// Kysely rolls back only a transaction whose begin resolved. A scope-setting error can
|
|
306
|
+
// leave this transaction aborted, so end it before releasing the connection.
|
|
307
|
+
await this.inner.executeQuery(ROLLBACK).catch(() => { });
|
|
308
|
+
throw error;
|
|
123
309
|
}
|
|
310
|
+
this.inTransaction = true;
|
|
311
|
+
this.applied = scopeKey(scope);
|
|
124
312
|
}
|
|
125
|
-
|
|
126
|
-
begin(driver, settings) {
|
|
313
|
+
begin(settings) {
|
|
127
314
|
const scope = currentScope();
|
|
128
|
-
return this.serial(
|
|
129
|
-
|
|
130
|
-
|
|
315
|
+
return this.serial(() => this.beginScoped(scope, settings));
|
|
316
|
+
}
|
|
317
|
+
async finish(fn) {
|
|
318
|
+
try {
|
|
319
|
+
await fn();
|
|
320
|
+
}
|
|
321
|
+
finally {
|
|
322
|
+
this.inTransaction = false;
|
|
131
323
|
this.applied = undefined;
|
|
132
|
-
|
|
133
|
-
await this.ensure(scope);
|
|
134
|
-
}
|
|
135
|
-
catch (error) {
|
|
136
|
-
// Kysely rolls back only a transaction whose begin resolved: end this one here, or the
|
|
137
|
-
// connection would return to the pool inside it (best effort; the error is the caller's)
|
|
138
|
-
await driver.rollbackTransaction(this.inner).catch(() => { });
|
|
139
|
-
this.inTransaction = false;
|
|
140
|
-
this.applied = undefined;
|
|
141
|
-
throw error;
|
|
142
|
-
}
|
|
143
|
-
});
|
|
324
|
+
}
|
|
144
325
|
}
|
|
145
|
-
/** `COMMIT` / `ROLLBACK`: the local values end, the session's (unknown here) apply again. */
|
|
146
326
|
end(fn) {
|
|
147
|
-
return this.serial(
|
|
148
|
-
try {
|
|
149
|
-
await fn();
|
|
150
|
-
}
|
|
151
|
-
finally {
|
|
152
|
-
this.inTransaction = false;
|
|
153
|
-
this.applied = undefined;
|
|
154
|
-
}
|
|
155
|
-
});
|
|
327
|
+
return this.serial(() => this.finish(fn));
|
|
156
328
|
}
|
|
157
329
|
/**
|
|
158
330
|
* A savepoint statement, in order with the queries. A rollback to a savepoint also undoes a
|
|
@@ -177,11 +349,13 @@ class ScopedConnection {
|
|
|
177
349
|
*/
|
|
178
350
|
class ScopedDriver {
|
|
179
351
|
inner;
|
|
180
|
-
|
|
352
|
+
mode;
|
|
353
|
+
standaloneScope;
|
|
181
354
|
tables;
|
|
182
|
-
constructor(inner,
|
|
355
|
+
constructor(inner, mode, standaloneScope) {
|
|
183
356
|
this.inner = inner;
|
|
184
|
-
this.
|
|
357
|
+
this.mode = mode;
|
|
358
|
+
this.standaloneScope = standaloneScope;
|
|
185
359
|
}
|
|
186
360
|
init() {
|
|
187
361
|
return this.inner.init();
|
|
@@ -201,10 +375,10 @@ class ScopedDriver {
|
|
|
201
375
|
};
|
|
202
376
|
async acquireConnection() {
|
|
203
377
|
const inner = await this.inner.acquireConnection();
|
|
204
|
-
return new ScopedConnection(inner, this.
|
|
378
|
+
return new ScopedConnection(inner, this.mode, this.standaloneScope, this.orgTables);
|
|
205
379
|
}
|
|
206
380
|
beginTransaction(conn, settings) {
|
|
207
|
-
return scoped(conn).begin(
|
|
381
|
+
return scoped(conn).begin(settings);
|
|
208
382
|
}
|
|
209
383
|
commitTransaction(conn) {
|
|
210
384
|
const c = scoped(conn);
|
|
@@ -244,14 +418,28 @@ function scoped(conn) {
|
|
|
244
418
|
*/
|
|
245
419
|
export class ScopedPostgresDialect extends PostgresDialect {
|
|
246
420
|
rls;
|
|
247
|
-
|
|
248
|
-
|
|
421
|
+
standaloneScope;
|
|
422
|
+
constructor(config, rls, extendedProtocol = false) {
|
|
423
|
+
const start = rls !== "off" && extendedProtocol
|
|
424
|
+
? new AsyncLocalStorage()
|
|
425
|
+
: undefined;
|
|
426
|
+
const pool = config.pool;
|
|
427
|
+
const mode = rls === "enforce" ? "enforce" : "off";
|
|
428
|
+
super(rls === "off"
|
|
429
|
+
? config
|
|
430
|
+
: {
|
|
431
|
+
...config,
|
|
432
|
+
pool: typeof pool === "function"
|
|
433
|
+
? async (options) => withScopedConnections(await pool(options), mode, start)
|
|
434
|
+
: withScopedConnections(pool, mode, start),
|
|
435
|
+
});
|
|
249
436
|
this.rls = rls;
|
|
437
|
+
this.standaloneScope = start;
|
|
250
438
|
}
|
|
251
439
|
createDriver() {
|
|
252
440
|
const inner = super.createDriver();
|
|
253
441
|
if (this.rls === "off")
|
|
254
442
|
return inner;
|
|
255
|
-
return new ScopedDriver(inner, this.rls === "enforce" ? "enforce" : "off");
|
|
443
|
+
return new ScopedDriver(inner, this.rls === "enforce" ? "enforce" : "off", this.standaloneScope);
|
|
256
444
|
}
|
|
257
445
|
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { type Transaction } from "kysely";
|
|
2
|
+
import { type RlsMode } from "./scoped-dialect.js";
|
|
2
3
|
export interface StartupActivationOptions {
|
|
3
4
|
connectionString: string;
|
|
4
5
|
connectTimeoutMs?: number;
|
|
6
|
+
rls?: RlsMode;
|
|
5
7
|
signal: AbortSignal;
|
|
6
8
|
remainingMs: () => number;
|
|
7
9
|
/**
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
-
import { Kysely
|
|
2
|
+
import { Kysely } from "kysely";
|
|
3
3
|
import pg from "pg";
|
|
4
4
|
import { pgConnectOptions } from "../../db/pool.js";
|
|
5
|
+
import { ScopedPostgresDialect } from "./scoped-dialect.js";
|
|
5
6
|
/** Server-side bound on one statement of the owned startup session. */
|
|
6
7
|
export const STARTUP_STATEMENT_TIMEOUT_MS = 500;
|
|
7
8
|
/** Server-side bound on one lock wait of the owned startup session. */
|
|
@@ -169,7 +170,7 @@ fn, options) {
|
|
|
169
170
|
if (closed)
|
|
170
171
|
original.connection.stream.destroy();
|
|
171
172
|
});
|
|
172
|
-
const db = new Kysely({ dialect: new
|
|
173
|
+
const db = new Kysely({ dialect: new ScopedPostgresDialect({ pool }, options.rls ?? "off") });
|
|
173
174
|
let rollbackConfirmed = false;
|
|
174
175
|
try {
|
|
175
176
|
guard.check();
|
|
@@ -570,6 +570,34 @@ export declare const OUTBOX_JOBS: {
|
|
|
570
570
|
readonly removeOnFail: true;
|
|
571
571
|
};
|
|
572
572
|
};
|
|
573
|
+
readonly "device-host-services-stop": {
|
|
574
|
+
readonly queue: "cap-kernel-maintenance";
|
|
575
|
+
readonly idempotent: "Stops the extension's host services on the devices that started one; stopping a service that is not running is a no-op";
|
|
576
|
+
readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
|
|
577
|
+
readonly opts: {
|
|
578
|
+
readonly attempts: 10;
|
|
579
|
+
readonly backoff: {
|
|
580
|
+
readonly type: "exponential";
|
|
581
|
+
readonly delay: 5000;
|
|
582
|
+
};
|
|
583
|
+
readonly removeOnComplete: true;
|
|
584
|
+
readonly removeOnFail: true;
|
|
585
|
+
};
|
|
586
|
+
};
|
|
587
|
+
readonly "device-service-events": {
|
|
588
|
+
readonly queue: "cap-device-service-events";
|
|
589
|
+
readonly idempotent: "the delivery takes the service's lock and hands on only rows not yet marked delivered, in seq order, marking each once its handler resolved; a repeat finds them delivered (handlers get each event at least once)";
|
|
590
|
+
readonly processedIn: "packages/kernel/src/device-access/service-events.ts";
|
|
591
|
+
readonly opts: {
|
|
592
|
+
readonly attempts: 10;
|
|
593
|
+
readonly backoff: {
|
|
594
|
+
readonly type: "exponential";
|
|
595
|
+
readonly delay: 2000;
|
|
596
|
+
};
|
|
597
|
+
readonly removeOnComplete: true;
|
|
598
|
+
readonly removeOnFail: true;
|
|
599
|
+
};
|
|
600
|
+
};
|
|
573
601
|
readonly "hook-run-lifecycle": {
|
|
574
602
|
readonly queue: "cap-kernel-lifecycle";
|
|
575
603
|
readonly idempotent: "the `run.lifecycle` handler sets a display state keyed by the run and phase (the SDK contract: handlers are idempotent); the job id is deterministic per run, phase and wait";
|
|
@@ -512,6 +512,36 @@ export const OUTBOX_JOBS = {
|
|
|
512
512
|
removeOnFail: true,
|
|
513
513
|
},
|
|
514
514
|
},
|
|
515
|
+
// `device-access/host-service-stop.ts` HOST_SERVICES_STOP_JOB: owed by the transaction that
|
|
516
|
+
// switches an extension off in an org (`OrgExtensionConfigs`) or on the deployment
|
|
517
|
+
// (`ExtensionAdminOps`), under `hostServicesStopJobId` (local agents spec, call 5)
|
|
518
|
+
"device-host-services-stop": {
|
|
519
|
+
queue: "cap-kernel-maintenance",
|
|
520
|
+
idempotent: "Stops the extension's host services on the devices that started one; stopping a service that is not running is a no-op",
|
|
521
|
+
processedIn: "packages/kernel/src/runtime/maintenance.ts",
|
|
522
|
+
opts: {
|
|
523
|
+
attempts: 10,
|
|
524
|
+
backoff: { type: "exponential", delay: 5_000 },
|
|
525
|
+
removeOnComplete: true,
|
|
526
|
+
removeOnFail: true,
|
|
527
|
+
},
|
|
528
|
+
},
|
|
529
|
+
// `device-access/service-events.ts` SERVICE_EVENTS_JOB: owed by the transaction that stores a
|
|
530
|
+
// device service event (`ServiceEvents.record`, local agents spec Part 1), under
|
|
531
|
+
// `serviceEventsJobId` (one per event)
|
|
532
|
+
"device-service-events": {
|
|
533
|
+
queue: "cap-device-service-events",
|
|
534
|
+
idempotent: "the delivery takes the service's lock and hands on only rows not yet marked delivered, in seq order, marking each once its handler resolved; a repeat finds them delivered (handlers get each event at least once)",
|
|
535
|
+
processedIn: "packages/kernel/src/device-access/service-events.ts",
|
|
536
|
+
// 10 attempts from 2 s, doubling (about 17 min in all); removed once done, so the same event
|
|
537
|
+
// reported again owes a job that is not deduped away
|
|
538
|
+
opts: {
|
|
539
|
+
attempts: 10,
|
|
540
|
+
backoff: { type: "exponential", delay: 2_000 },
|
|
541
|
+
removeOnComplete: true,
|
|
542
|
+
removeOnFail: true,
|
|
543
|
+
},
|
|
544
|
+
},
|
|
515
545
|
// `extensions/run-lifecycle-owe.ts` RUN_LIFECYCLE_JOB: owed by the transaction that starts a
|
|
516
546
|
// run, suspends it on a person, resumes it, ends it (finished, failed, aborted) or declines,
|
|
517
547
|
// expires or gives up on directed work, once per phase of a run (and wait) and plugin
|
|
@@ -4,5 +4,5 @@
|
|
|
4
4
|
* (admin/health.service.ts) lists the same names from the feature constants;
|
|
5
5
|
* test/infra/queue-names.test.ts keeps the two equal.
|
|
6
6
|
*/
|
|
7
|
-
export declare const KERNEL_QUEUES: readonly ["cap-kernel-runs", "cap-kernel-subagent-runs", "cap-kernel-channels", "cap-kernel-maintenance", "cap-kernel-tool-watch", "cap-kernel-plugin-scope", "cap-kernel-titles", "cap-kernel-suggestions", "cap-kernel-usage-report", "cap-kernel-evals", "cap-kernel-lifecycle", "cap-push-deliver", "cap-connector-tools", "cap-template-connectors"];
|
|
7
|
+
export declare const KERNEL_QUEUES: readonly ["cap-kernel-runs", "cap-kernel-subagent-runs", "cap-kernel-channels", "cap-kernel-maintenance", "cap-kernel-tool-watch", "cap-kernel-plugin-scope", "cap-kernel-titles", "cap-kernel-suggestions", "cap-kernel-usage-report", "cap-kernel-evals", "cap-kernel-lifecycle", "cap-push-deliver", "cap-connector-tools", "cap-template-connectors", "cap-device-service-events"];
|
|
8
8
|
export type KernelQueueName = (typeof KERNEL_QUEUES)[number];
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type ContextJob } from "../../log-context.js";
|
|
2
|
+
import { type OrgScope } from "../database/org-scope.js";
|
|
2
3
|
/**
|
|
3
4
|
* The wrapper every queue processor runs its job in: a fresh async context (no transaction of
|
|
4
5
|
* whoever enqueued the job or started the worker is visible), `queue` / `jobId` / `runId` in the
|
|
@@ -6,7 +7,8 @@ import { type ContextJob } from "../../log-context.js";
|
|
|
6
7
|
* §5.3, §10) is the job's org when its data carries a string `orgId`; else the platform scope when
|
|
7
8
|
* the queue's work is deployment-wide (`opts.platform`, the reason); else none, never inherited
|
|
8
9
|
* from whoever started the worker (a missing org fails closed once RLS is enforced, and the
|
|
9
|
-
* unscoped-query check reports it).
|
|
10
|
+
* unscoped-query check reports it). An explicit `opts.scope` overrides payload inference, with
|
|
11
|
+
* `null` selecting no scope.
|
|
10
12
|
*
|
|
11
13
|
* ```ts
|
|
12
14
|
* @Processor("cap-kernel-titles")
|
|
@@ -19,4 +21,5 @@ import { type ContextJob } from "../../log-context.js";
|
|
|
19
21
|
*/
|
|
20
22
|
export declare function runJob<T>(queue: string, job: ContextJob, fn: () => Promise<T>, opts?: {
|
|
21
23
|
platform?: string;
|
|
24
|
+
scope?: OrgScope | null;
|
|
22
25
|
}): Promise<T>;
|
|
@@ -8,7 +8,8 @@ import { runOutsideTransaction } from "../database/transaction-host.js";
|
|
|
8
8
|
* §5.3, §10) is the job's org when its data carries a string `orgId`; else the platform scope when
|
|
9
9
|
* the queue's work is deployment-wide (`opts.platform`, the reason); else none, never inherited
|
|
10
10
|
* from whoever started the worker (a missing org fails closed once RLS is enforced, and the
|
|
11
|
-
* unscoped-query check reports it).
|
|
11
|
+
* unscoped-query check reports it). An explicit `opts.scope` overrides payload inference, with
|
|
12
|
+
* `null` selecting no scope.
|
|
12
13
|
*
|
|
13
14
|
* ```ts
|
|
14
15
|
* @Processor("cap-kernel-titles")
|
|
@@ -20,9 +21,16 @@ import { runOutsideTransaction } from "../database/transaction-host.js";
|
|
|
20
21
|
* ```
|
|
21
22
|
*/
|
|
22
23
|
export function runJob(queue, job, fn, opts = {}) {
|
|
23
|
-
const orgId = job.data?.orgId;
|
|
24
24
|
const run = () => withJobContext(queue, job, fn);
|
|
25
25
|
return runOutsideTransaction(() => {
|
|
26
|
+
if (opts.scope !== undefined) {
|
|
27
|
+
if (opts.scope?.kind === "org")
|
|
28
|
+
return withOrgScope(opts.scope.orgId, run);
|
|
29
|
+
if (opts.scope?.kind === "platform")
|
|
30
|
+
return asPlatform(opts.scope.reason, run);
|
|
31
|
+
return withoutOrgScope(run);
|
|
32
|
+
}
|
|
33
|
+
const orgId = job.data?.orgId;
|
|
26
34
|
if (typeof orgId === "string" && orgId !== "")
|
|
27
35
|
return withOrgScope(orgId, run);
|
|
28
36
|
if (opts.platform !== undefined)
|
package/dist/kernel.module.js
CHANGED
|
@@ -14,6 +14,7 @@ import { ClientModule } from "./client/client.module.js";
|
|
|
14
14
|
import { PromptSuggestionsModule } from "./conversations/prompt-suggestions.js";
|
|
15
15
|
import { TitlesModule } from "./conversations/titles.js";
|
|
16
16
|
import { ExtensionDeviceAccessModule } from "./device-access/device-access.module.js";
|
|
17
|
+
import { DeviceServiceEventsModule } from "./device-access/service-events.js";
|
|
17
18
|
import { BootstrapDefaultsService } from "./extensions/bootstrap-defaults.js";
|
|
18
19
|
import { ExtensionsModule } from "./extensions/extensions.module.js";
|
|
19
20
|
import { ApiModule } from "./http/api.module.js";
|
|
@@ -134,6 +135,8 @@ let KernelModule = KernelModule_1 = class KernelModule {
|
|
|
134
135
|
ClientModule,
|
|
135
136
|
// ctx.deviceAccess: extensions' device services (the host finds it at the time of use)
|
|
136
137
|
ExtensionDeviceAccessModule,
|
|
138
|
+
// ctx.devices.serviceEvent: host service events (the host finds it at the time of use)
|
|
139
|
+
DeviceServiceEventsModule,
|
|
137
140
|
// ctx.triggers: the events extensions emit (the host finds it at the time of use)
|
|
138
141
|
TriggerEventsModule,
|
|
139
142
|
// ctx.inbox: personal inbox items extensions post (the host finds it at the time of use)
|