@capybara-hq/kernel 0.1.0-rc.132 → 0.1.0-rc.134
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/automations/events/trigger-events.service.d.ts +13 -1
- package/dist/automations/events/trigger-events.service.js +27 -14
- 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.d.ts +1 -0
- package/dist/config/schema.js +8 -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 +15 -2
- package/dist/ctx/create-ctx.js +195 -79
- package/dist/ctx/durable-cancellation.d.ts +3 -0
- package/dist/ctx/durable-cancellation.js +8 -0
- package/dist/ctx/durable-effects.service.d.ts +81 -0
- package/dist/ctx/durable-effects.service.js +316 -0
- package/dist/ctx/durable-envelope.d.ts +24 -0
- package/dist/ctx/durable-envelope.js +80 -0
- package/dist/ctx/durable-failure.d.ts +7 -0
- package/dist/ctx/durable-failure.js +32 -0
- package/dist/ctx/durable-job.d.ts +9 -0
- package/dist/ctx/durable-job.js +2 -0
- package/dist/ctx/durable-keys.d.ts +27 -0
- package/dist/ctx/durable-keys.js +138 -0
- package/dist/ctx/durable-relay.d.ts +29 -0
- package/dist/ctx/durable-relay.js +250 -0
- package/dist/ctx/queue.d.ts +2 -0
- package/dist/ctx/queue.js +25 -15
- package/dist/db/extension-db.js +2 -0
- package/dist/db/extension-handoff-schema.d.ts +6 -0
- package/dist/db/extension-handoff-schema.js +72 -0
- package/dist/db/extension-rls-predicate.d.ts +1 -0
- package/dist/db/extension-rls-predicate.js +8 -0
- package/dist/db/extension-schema-transfer.d.ts +1 -1
- package/dist/db/extension-schema-transfer.js +18 -6
- package/dist/db/kernel-schema.d.ts +64 -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 +10 -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/extensions.module.js +10 -0
- package/dist/extensions/host.d.ts +12 -2
- package/dist/extensions/host.js +44 -22
- package/dist/extensions/instance.d.ts +5 -0
- package/dist/extensions/instance.js +10 -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/extensions/sources.d.ts +1 -0
- package/dist/extensions/sources.js +9 -0
- 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/inbox-items.service.d.ts +5 -0
- package/dist/inbox/inbox-items.service.js +57 -33
- 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/extension-effect-key-lock.d.ts +10 -0
- package/dist/infra/database/extension-effect-key-lock.js +69 -0
- package/dist/infra/database/extension-handoff.d.ts +27 -0
- package/dist/infra/database/extension-handoff.js +113 -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/outbox.dispatcher.d.ts +6 -1
- package/dist/infra/outbox/outbox.dispatcher.js +64 -4
- package/dist/infra/outbox/outbox.module.js +2 -0
- package/dist/infra/outbox/registry.d.ts +40 -0
- package/dist/infra/outbox/registry.js +42 -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.js +1 -0
- package/dist/kernel.module.js +3 -0
- package/dist/orgs/offboarding.js +18 -9
- package/dist/orgs/orgs.service.js +16 -0
- 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 +9 -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
- package/src/migrations/0225_extension_effect_receipts.sql +25 -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();
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ModuleRef } from "@nestjs/core";
|
|
2
2
|
import type { Queue } from "bullmq";
|
|
3
|
+
import { ExtensionRegistry } from "../../extensions/registry.js";
|
|
3
4
|
import type { KernelLogger } from "../../log.js";
|
|
4
5
|
import { KernelDb } from "../database/kernel-db.js";
|
|
5
6
|
import { TransactionHost } from "../database/transaction-host.js";
|
|
@@ -62,11 +63,12 @@ export declare class OutboxDispatcher {
|
|
|
62
63
|
private readonly log;
|
|
63
64
|
private readonly moduleRef;
|
|
64
65
|
private readonly dispatchFails;
|
|
66
|
+
private readonly extensions?;
|
|
65
67
|
/** The owners' queue instances resolved so far (a per-process handle cache). */
|
|
66
68
|
private readonly queues;
|
|
67
69
|
/** Fast-path passes running in this process (bounded by OUTBOX_FAST_PATH_CONCURRENCY). */
|
|
68
70
|
private fastPaths;
|
|
69
|
-
constructor(txHost: TransactionHost, db: KernelDb, log: KernelLogger, moduleRef: Pick<ModuleRef, "get">, dispatchFails?: (queue: KernelQueueName) => boolean);
|
|
71
|
+
constructor(txHost: TransactionHost, db: KernelDb, log: KernelLogger, moduleRef: Pick<ModuleRef, "get">, dispatchFails?: (queue: KernelQueueName) => boolean, extensions?: ExtensionRegistry | undefined);
|
|
70
72
|
/** The queue instance its owner module registered, or undefined when no loaded module has it. */
|
|
71
73
|
private queue;
|
|
72
74
|
/** The kernel queues this process can add to, with their handles. */
|
|
@@ -94,6 +96,9 @@ export declare class OutboxDispatcher {
|
|
|
94
96
|
* bounded by {@link OUTBOX_REDIS_TIMEOUT_MS}.
|
|
95
97
|
*/
|
|
96
98
|
private claimAndSend;
|
|
99
|
+
private sendExtensionJob;
|
|
100
|
+
/** Uses the regular outbox backoff for a worker that applies an owed effect directly. */
|
|
101
|
+
deferDirect(id: string, reason: string): Promise<void>;
|
|
97
102
|
/**
|
|
98
103
|
* Records a failed add on its rows (after the claim transaction, so the attempt is kept whatever
|
|
99
104
|
* that transaction did): one more attempt, the error, the next attempt by {@link OUTBOX_BACKOFF},
|
|
@@ -11,8 +11,13 @@ import { getQueueToken } from "@nestjs/bullmq";
|
|
|
11
11
|
import { Inject, Injectable, Optional } from "@nestjs/common";
|
|
12
12
|
import { ModuleRef } from "@nestjs/core";
|
|
13
13
|
import { sql } from "kysely";
|
|
14
|
+
import { cancelDeletedOrgEffect } from "../../ctx/durable-cancellation.js";
|
|
15
|
+
import { classifyEffectFailure, ExtensionEffectFailure, effectFailureMessage, } from "../../ctx/durable-failure.js";
|
|
16
|
+
import { EXTENSION_EFFECT_REDRIVE_JOB, EXTENSION_QUEUE_EFFECT_JOB, } from "../../ctx/durable-job.js";
|
|
17
|
+
import { isExtensionEnabled } from "../../extensions/enabled.js";
|
|
18
|
+
import { ExtensionRegistry } from "../../extensions/registry.js";
|
|
14
19
|
import { KernelDb } from "../database/kernel-db.js";
|
|
15
|
-
import { asPlatform } from "../database/org-scope.js";
|
|
20
|
+
import { asPlatform, withOrgScope } from "../database/org-scope.js";
|
|
16
21
|
import { TransactionHost } from "../database/transaction-host.js";
|
|
17
22
|
import { Transactional } from "../database/transactional.decorator.js";
|
|
18
23
|
import { QUEUE_JOB_DEFAULTS } from "../queue/queue.module.js";
|
|
@@ -97,16 +102,18 @@ let OutboxDispatcher = class OutboxDispatcher {
|
|
|
97
102
|
log;
|
|
98
103
|
moduleRef;
|
|
99
104
|
dispatchFails;
|
|
105
|
+
extensions;
|
|
100
106
|
/** The owners' queue instances resolved so far (a per-process handle cache). */
|
|
101
107
|
queues = new Map();
|
|
102
108
|
/** Fast-path passes running in this process (bounded by OUTBOX_FAST_PATH_CONCURRENCY). */
|
|
103
109
|
fastPaths = 0;
|
|
104
|
-
constructor(txHost, db, log, moduleRef, dispatchFails = () => false) {
|
|
110
|
+
constructor(txHost, db, log, moduleRef, dispatchFails = () => false, extensions) {
|
|
105
111
|
this.txHost = txHost;
|
|
106
112
|
this.db = db;
|
|
107
113
|
this.log = log;
|
|
108
114
|
this.moduleRef = moduleRef;
|
|
109
115
|
this.dispatchFails = dispatchFails;
|
|
116
|
+
this.extensions = extensions;
|
|
110
117
|
}
|
|
111
118
|
/** The queue instance its owner module registered, or undefined when no loaded module has it. */
|
|
112
119
|
queue(name) {
|
|
@@ -201,8 +208,9 @@ let OutboxDispatcher = class OutboxDispatcher {
|
|
|
201
208
|
// rows of a queue this process cannot reach are left for a process that can
|
|
202
209
|
let query = this.db
|
|
203
210
|
.selectFrom("outbox")
|
|
204
|
-
.select(["id", "queue", "job_name", "job_id", "data", "run_at"])
|
|
211
|
+
.select(["id", "queue", "job_name", "job_id", "data", "run_at", "org_id"])
|
|
205
212
|
.where("dead_at", "is", null)
|
|
213
|
+
.where("job_name", "!=", EXTENSION_EFFECT_REDRIVE_JOB)
|
|
206
214
|
.where("queue", "in", [...queues.keys()]);
|
|
207
215
|
query =
|
|
208
216
|
"ids" in claim
|
|
@@ -213,6 +221,8 @@ let OutboxDispatcher = class OutboxDispatcher {
|
|
|
213
221
|
return { sent: 0, failed: [] };
|
|
214
222
|
const byQueue = new Map();
|
|
215
223
|
for (const row of rows) {
|
|
224
|
+
if (row.job_name === EXTENSION_QUEUE_EFFECT_JOB)
|
|
225
|
+
continue;
|
|
216
226
|
const group = byQueue.get(row.queue);
|
|
217
227
|
if (group)
|
|
218
228
|
group.push(row);
|
|
@@ -260,11 +270,59 @@ let OutboxDispatcher = class OutboxDispatcher {
|
|
|
260
270
|
failed.push({ ids, error: firstError.slice(0, MAX_ERROR_LENGTH) });
|
|
261
271
|
}
|
|
262
272
|
}
|
|
273
|
+
for (const row of rows) {
|
|
274
|
+
if (row.job_name !== EXTENSION_QUEUE_EFFECT_JOB)
|
|
275
|
+
continue;
|
|
276
|
+
try {
|
|
277
|
+
if (this.dispatchFails(row.queue)) {
|
|
278
|
+
throw new Error("outbox dispatch failure (test seam)");
|
|
279
|
+
}
|
|
280
|
+
const left = deadline - Date.now();
|
|
281
|
+
if (left <= 0)
|
|
282
|
+
throw new Error("No time left in the outbox dispatch pass");
|
|
283
|
+
await withTimeout(this.sendExtensionJob(row), left, "add to extension queue");
|
|
284
|
+
delivered.push(row.id);
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
failed.push({ ids: [row.id], error: effectFailureMessage(classifyEffectFailure(error)) });
|
|
288
|
+
}
|
|
289
|
+
}
|
|
263
290
|
if (delivered.length > 0)
|
|
264
291
|
await this.db.deleteFrom("outbox").where("id", "in", delivered).execute();
|
|
265
292
|
return { sent: delivered.length, failed };
|
|
266
293
|
});
|
|
267
294
|
}
|
|
295
|
+
async sendExtensionJob(row) {
|
|
296
|
+
const data = row.data;
|
|
297
|
+
if (!row.org_id || data.orgId !== row.org_id) {
|
|
298
|
+
throw new ExtensionEffectFailure("scope_mismatch", "The queue effect scope differs from the outbox row");
|
|
299
|
+
}
|
|
300
|
+
const org = await this.db
|
|
301
|
+
.selectFrom("orgs")
|
|
302
|
+
.select("id")
|
|
303
|
+
.where("id", "=", row.org_id)
|
|
304
|
+
.where("deleted_at", "is", null)
|
|
305
|
+
.executeTakeFirst();
|
|
306
|
+
if (!org) {
|
|
307
|
+
await cancelDeletedOrgEffect(this.db.db, data.plugin, data.jobId);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (!(await isExtensionEnabled(this.db.db, org.id, data.plugin))) {
|
|
311
|
+
throw new ExtensionEffectFailure("org_disabled", "The extension is disabled in this organization");
|
|
312
|
+
}
|
|
313
|
+
const extension = this.extensions?.current(data.plugin);
|
|
314
|
+
if (!extension)
|
|
315
|
+
throw new ExtensionEffectFailure("extension_unavailable", "The extension is unavailable");
|
|
316
|
+
if (!extension.hasEffectQueue(data.queue)) {
|
|
317
|
+
throw new ExtensionEffectFailure("queue_unavailable", "The extension effect queue is not registered");
|
|
318
|
+
}
|
|
319
|
+
const delay = row.run_at ? Math.max(0, row.run_at.getTime() - Date.now()) : undefined;
|
|
320
|
+
await withOrgScope(org.id, () => extension.enqueueEffect(data.queue, data.data, data.jobId, delay));
|
|
321
|
+
}
|
|
322
|
+
/** Uses the regular outbox backoff for a worker that applies an owed effect directly. */
|
|
323
|
+
async deferDirect(id, reason) {
|
|
324
|
+
await this.recordFailure({ ids: [id], error: reason });
|
|
325
|
+
}
|
|
268
326
|
/**
|
|
269
327
|
* Records a failed add on its rows (after the claim transaction, so the attempt is kept whatever
|
|
270
328
|
* that transaction did): one more attempt, the error, the next attempt by {@link OUTBOX_BACKOFF},
|
|
@@ -316,6 +374,8 @@ OutboxDispatcher = __decorate([
|
|
|
316
374
|
__param(2, Inject(KERNEL_LOGGER)),
|
|
317
375
|
__param(3, Inject(ModuleRef)),
|
|
318
376
|
__param(4, Optional()),
|
|
319
|
-
__param(4, Inject(OUTBOX_DISPATCH_FAILS))
|
|
377
|
+
__param(4, Inject(OUTBOX_DISPATCH_FAILS)),
|
|
378
|
+
__param(5, Optional()),
|
|
379
|
+
__param(5, Inject(ExtensionRegistry))
|
|
320
380
|
], OutboxDispatcher);
|
|
321
381
|
export { OutboxDispatcher };
|
|
@@ -5,6 +5,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
5
5
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
6
|
};
|
|
7
7
|
import { Global, Module } from "@nestjs/common";
|
|
8
|
+
import { ExtensionRegistryModule } from "../../extensions/registry.js";
|
|
8
9
|
import { OutboxDispatcher } from "./outbox.dispatcher.js";
|
|
9
10
|
import { OUTBOX_FAST_PATH, OutboxService } from "./outbox.service.js";
|
|
10
11
|
/**
|
|
@@ -35,6 +36,7 @@ let OutboxModule = class OutboxModule {
|
|
|
35
36
|
OutboxModule = __decorate([
|
|
36
37
|
Global(),
|
|
37
38
|
Module({
|
|
39
|
+
imports: [ExtensionRegistryModule],
|
|
38
40
|
providers: [
|
|
39
41
|
OutboxService,
|
|
40
42
|
OutboxDispatcher,
|