@capybara-hq/kernel 0.1.0-rc.140 → 0.1.0-rc.141
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/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/infra/queue/run-job.js +3 -1
- package/dist/models/enablement.d.ts +12 -0
- package/dist/models/enablement.js +32 -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,767 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
import { ApiError } from "../errors.js";
|
|
3
|
+
import { enabledExtensionsQuery, requiredExtensions } from "../extensions/enabled.js";
|
|
4
|
+
import { pluginItemsOf, pluginPathItem, } from "../extensions/plugin-items.js";
|
|
5
|
+
import { audit } from "../identity/audit.js";
|
|
6
|
+
import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
|
|
7
|
+
import { can } from "../orgs/roles.js";
|
|
8
|
+
import { componentLocked, componentOffered, componentOn, componentPluginOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, switchOf, } from "./component-state.js";
|
|
9
|
+
import { currentEnableDecision } from "./enable-decision.js";
|
|
10
|
+
import { decodeModelId, readEnableDetail, sameTarget, targetKey, } from "./enable-targets.js";
|
|
11
|
+
import { orgPluginDirectIntent, orgSees, orgUsable } from "./org-intent.js";
|
|
12
|
+
import { requestable } from "./scope.js";
|
|
13
|
+
/** Builds a {@link ModelListing} from `ProviderRegistry.catalog(orgId)`. */
|
|
14
|
+
export function modelListingOf(catalog) {
|
|
15
|
+
return new Map(catalog.map((p) => [
|
|
16
|
+
p.provider,
|
|
17
|
+
{
|
|
18
|
+
status: p.status,
|
|
19
|
+
listed: new Set(p.models.map((m) => m.id)),
|
|
20
|
+
disabled: new Set(p.models.filter((m) => m.disabled === true).map((m) => m.id)),
|
|
21
|
+
},
|
|
22
|
+
]));
|
|
23
|
+
}
|
|
24
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
25
|
+
const refuse = (code, message) => ({
|
|
26
|
+
ok: false,
|
|
27
|
+
error: new ApiError(code, message),
|
|
28
|
+
});
|
|
29
|
+
const alreadyOn = (what) => ({
|
|
30
|
+
ok: false,
|
|
31
|
+
on: true,
|
|
32
|
+
error: new ApiError("catalog.request_invalid", `This ${what} is already on in this organization; there is nothing to ask for`),
|
|
33
|
+
});
|
|
34
|
+
const blocked = (what) => refuse("catalog.item_disabled", `The super admin disabled this ${what} on the platform; an org admin cannot turn it on`);
|
|
35
|
+
const pluginNotFound = () => refuse("catalog.item_not_found", "Catalog item not found");
|
|
36
|
+
const extensionNotFound = (name) => refuse("extension.not_found", `Extension ${name} not found`);
|
|
37
|
+
const modelNotFound = () => refuse("model.not_found", "Model not found");
|
|
38
|
+
/**
|
|
39
|
+
* The owning switch of plugins in the org: refused when the org cannot see one (hidden by scope,
|
|
40
|
+
* an unshared plugin of another org, or disabled for a member), disabled by the super admin, not
|
|
41
|
+
* offered to the org (an org admin asks the super admin for access instead), builtin, already
|
|
42
|
+
* usable, or switched on with a dependency the org lacks. Two queries for any number of ids.
|
|
43
|
+
*/
|
|
44
|
+
export async function resolvePlugins(db, orgId, ids, isAdmin) {
|
|
45
|
+
const out = new Map();
|
|
46
|
+
const valid = [...new Set(ids)].filter((id) => UUID_RE.test(id));
|
|
47
|
+
const items = valid.length === 0
|
|
48
|
+
? []
|
|
49
|
+
: await orgSees(db, orgId, isAdmin)
|
|
50
|
+
.select([
|
|
51
|
+
"item.id",
|
|
52
|
+
"item.scope",
|
|
53
|
+
"item.builtin",
|
|
54
|
+
"item.disabled",
|
|
55
|
+
"item.shown_to_others",
|
|
56
|
+
"item.owner_org_id",
|
|
57
|
+
"item.shareable",
|
|
58
|
+
"named.item_id as namedItemId",
|
|
59
|
+
])
|
|
60
|
+
.select((eb) => orgUsable(db, orgId, eb.ref("item.id")).as("usable"))
|
|
61
|
+
.where("item.id", "in", valid)
|
|
62
|
+
.execute();
|
|
63
|
+
const candidates = items.filter((i) => !i.disabled && !i.usable && !requestable(i, i.namedItemId !== null));
|
|
64
|
+
const direct = new Set(candidates.length === 0
|
|
65
|
+
? []
|
|
66
|
+
: (await orgPluginDirectIntent(db, orgId)
|
|
67
|
+
.select("item.id")
|
|
68
|
+
.where("item.id", "in", candidates.map((i) => i.id))
|
|
69
|
+
.execute())
|
|
70
|
+
.filter((r) => r.directIntent)
|
|
71
|
+
.map((r) => r.id));
|
|
72
|
+
const byId = new Map(items.map((i) => [i.id, i]));
|
|
73
|
+
for (const id of ids) {
|
|
74
|
+
const item = byId.get(id);
|
|
75
|
+
if (!item)
|
|
76
|
+
out.set(id, pluginNotFound());
|
|
77
|
+
else if (item.disabled)
|
|
78
|
+
out.set(id, blocked("plugin"));
|
|
79
|
+
else if (item.usable)
|
|
80
|
+
out.set(id, alreadyOn("plugin"));
|
|
81
|
+
else if (requestable(item, item.namedItemId !== null)) {
|
|
82
|
+
out.set(id, refuse("catalog.request_invalid", "This plugin is not offered to this organization; an org admin can ask the super admin for access"));
|
|
83
|
+
}
|
|
84
|
+
else if (item.builtin && item.owner_org_id === null) {
|
|
85
|
+
out.set(id, refuse("catalog.request_invalid", "This plugin is built in: an org admin cannot switch it"));
|
|
86
|
+
}
|
|
87
|
+
else if (direct.has(id)) {
|
|
88
|
+
out.set(id, refuse("catalog.request_invalid", "This plugin is switched on in this organization but a plugin it depends on is not available; ask the super admin"));
|
|
89
|
+
}
|
|
90
|
+
else
|
|
91
|
+
out.set(id, { ok: true, target: { kind: "plugin", id }, bundle: null });
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
/** The plugin ids among `ids` that are usable in the org (one query). */
|
|
96
|
+
async function usablePlugins(db, orgId, ids) {
|
|
97
|
+
if (ids.length === 0)
|
|
98
|
+
return new Set();
|
|
99
|
+
const rows = await db
|
|
100
|
+
.selectFrom("catalog_items")
|
|
101
|
+
.select("id")
|
|
102
|
+
.where("id", "in", [...new Set(ids)])
|
|
103
|
+
.where(({ ref }) => orgUsable(db, orgId, ref("id")))
|
|
104
|
+
.execute();
|
|
105
|
+
return new Set(rows.map((r) => r.id));
|
|
106
|
+
}
|
|
107
|
+
async function extensionFacts(db, orgId, names, isAdmin) {
|
|
108
|
+
const items = await pluginItemsOf(db, names);
|
|
109
|
+
const itemIds = [...new Set([...items.values()].flat().map((i) => i.id))];
|
|
110
|
+
const [installed, required, enabled, seen, usable] = await Promise.all([
|
|
111
|
+
names.length === 0
|
|
112
|
+
? Promise.resolve([])
|
|
113
|
+
: db.selectFrom("extension_installs").select("name").where("name", "in", names).execute(),
|
|
114
|
+
requiredExtensions(db),
|
|
115
|
+
enabledExtensionsQuery(db, orgId).execute(),
|
|
116
|
+
itemIds.length === 0
|
|
117
|
+
? Promise.resolve([])
|
|
118
|
+
: orgSees(db, orgId, isAdmin, "offered")
|
|
119
|
+
.select("item.id")
|
|
120
|
+
.where("item.id", "in", itemIds)
|
|
121
|
+
.execute(),
|
|
122
|
+
usablePlugins(db, orgId, itemIds),
|
|
123
|
+
]);
|
|
124
|
+
return {
|
|
125
|
+
items,
|
|
126
|
+
installed: new Set(installed.map((r) => r.name)),
|
|
127
|
+
required,
|
|
128
|
+
enabled: new Set(enabled.map((r) => r.plugin)),
|
|
129
|
+
seen: new Set(seen.map((r) => r.id)),
|
|
130
|
+
usable,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The owning switch of extensions (by name): the extension's own switch, or its plugin when the
|
|
135
|
+
* plugin it comes with is off in the org. Unknown or hidden from the reader -> `extension.not_found`
|
|
136
|
+
* (a member's view hides a disabled source, as `resolvePlugins` does); required, built-in or
|
|
137
|
+
* already enabled -> already on; a disabled source -> blocked (org admins).
|
|
138
|
+
*/
|
|
139
|
+
async function resolveExtensions(db, orgId, names, isAdmin, loaded) {
|
|
140
|
+
const out = new Map();
|
|
141
|
+
if (names.length === 0)
|
|
142
|
+
return out;
|
|
143
|
+
const f = await extensionFacts(db, orgId, names, isAdmin);
|
|
144
|
+
const viaPlugin = new Map();
|
|
145
|
+
for (const name of names) {
|
|
146
|
+
const items = f.items.get(name);
|
|
147
|
+
const required = f.required.has(name);
|
|
148
|
+
if (items === undefined && !f.installed.has(name) && loaded?.has(name) !== true) {
|
|
149
|
+
out.set(name, extensionNotFound(name));
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (!required && items !== undefined) {
|
|
153
|
+
const visible = items.filter((i) => f.seen.has(i.id));
|
|
154
|
+
// a member sees no disabled source at all: one disabled source hides the extension
|
|
155
|
+
if (visible.length === 0 || (!isAdmin && items.some((i) => i.disabled))) {
|
|
156
|
+
out.set(name, extensionNotFound(name));
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (required || f.enabled.has(name)) {
|
|
161
|
+
out.set(name, alreadyOn("extension"));
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
if ((items ?? []).some((i) => i.disabled)) {
|
|
165
|
+
out.set(name, blocked("extension's plugin"));
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
const pathItem = pluginPathItem(items, required);
|
|
169
|
+
if (pathItem !== null && !f.usable.has(pathItem))
|
|
170
|
+
viaPlugin.set(name, pathItem);
|
|
171
|
+
else
|
|
172
|
+
out.set(name, { ok: true, target: { kind: "extension", id: name }, bundle: pathItem });
|
|
173
|
+
}
|
|
174
|
+
const plugins = await resolvePlugins(db, orgId, [...viaPlugin.values()], isAdmin);
|
|
175
|
+
for (const [name, item] of viaPlugin)
|
|
176
|
+
out.set(name, plugins.get(item) ?? pluginNotFound());
|
|
177
|
+
return out;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* The owning switch of platform skills, agent templates or connector templates of one kind: the
|
|
181
|
+
* component's org switch, or its plugin while a component that follows its plugin has that plugin
|
|
182
|
+
* off. One component read and one scope state read per kind.
|
|
183
|
+
*/
|
|
184
|
+
async function resolveComponents(db, orgId, kind, ids, isAdmin) {
|
|
185
|
+
const out = new Map();
|
|
186
|
+
if (ids.length === 0)
|
|
187
|
+
return out;
|
|
188
|
+
const comps = await loadComponents(db, kind, { ids: [...new Set(ids)] });
|
|
189
|
+
const st = await loadScopeState(db, kind, comps, orgId);
|
|
190
|
+
const byId = new Map(comps.map((c) => [c.id, c]));
|
|
191
|
+
const what = kind.replace("_", " ");
|
|
192
|
+
const viaPlugin = new Map();
|
|
193
|
+
for (const id of ids) {
|
|
194
|
+
const c = byId.get(id);
|
|
195
|
+
// missing, or an org-owned component of another org that its owner does not share
|
|
196
|
+
if (!c || (c.ownerOrgId !== null && c.ownerOrgId !== orgId && !c.shareable)) {
|
|
197
|
+
out.set(id, refuse("component.not_found", "Component not found"));
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const p = pluginFactsOf(st, c.itemId, orgId);
|
|
201
|
+
const listed = listedIn(st, c.id, orgId);
|
|
202
|
+
const on = componentOn(c, p, listed, switchOf(st, c.id, orgId));
|
|
203
|
+
const stopped = c.disabled || (p?.live === true && p.disabled);
|
|
204
|
+
const offered = componentOffered({ ...c, disabled: false }, p && { ...p, disabled: false }, listed);
|
|
205
|
+
if (!on && !offered)
|
|
206
|
+
out.set(id, refuse("component.not_found", "Component not found"));
|
|
207
|
+
else if (on)
|
|
208
|
+
out.set(id, alreadyOn(what));
|
|
209
|
+
else if (stopped) {
|
|
210
|
+
// disabled on the platform, a builtin plugin's too: not found for a member
|
|
211
|
+
out.set(id, isAdmin ? blocked(what) : refuse("component.not_found", "Component not found"));
|
|
212
|
+
}
|
|
213
|
+
else if (componentLocked(c, p))
|
|
214
|
+
out.set(id, alreadyOn(what));
|
|
215
|
+
else if (!componentPluginOn(c, p) && c.itemId !== null)
|
|
216
|
+
viaPlugin.set(id, c.itemId);
|
|
217
|
+
else {
|
|
218
|
+
out.set(id, {
|
|
219
|
+
ok: true,
|
|
220
|
+
target: { kind, id: c.id },
|
|
221
|
+
bundle: c.scopeMode === "follow" ? c.itemId : null,
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const plugins = await resolvePlugins(db, orgId, [...viaPlugin.values()], isAdmin);
|
|
226
|
+
for (const [id, item] of viaPlugin)
|
|
227
|
+
out.set(id, plugins.get(item) ?? pluginNotFound());
|
|
228
|
+
return out;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* The owning switch of org connectors: a connector a plugin switch-off disabled resolves to that
|
|
232
|
+
* plugin while it is off, and counts as coming on once the plugin is usable again (its effects
|
|
233
|
+
* switch it back on); any other disabled connector is its own switch. One connector read.
|
|
234
|
+
*/
|
|
235
|
+
async function resolveConnectors(db, orgId, ids, isAdmin) {
|
|
236
|
+
const out = new Map();
|
|
237
|
+
const valid = [...new Set(ids)].filter((id) => UUID_RE.test(id));
|
|
238
|
+
const rows = valid.length === 0
|
|
239
|
+
? []
|
|
240
|
+
: await db
|
|
241
|
+
.selectFrom("connectors")
|
|
242
|
+
.select(["id", "status", "disabled_by_plugin_id", "catalog_item_id"])
|
|
243
|
+
.where("id", "in", valid)
|
|
244
|
+
.where("org_id", "=", orgId)
|
|
245
|
+
.where("deleted_at", "is", null)
|
|
246
|
+
.execute();
|
|
247
|
+
const byId = new Map(rows.map((r) => [r.id, r]));
|
|
248
|
+
const markers = rows.flatMap((r) => r.status === "disabled" && r.disabled_by_plugin_id !== null ? [r.disabled_by_plugin_id] : []);
|
|
249
|
+
const usable = await usablePlugins(db, orgId, markers);
|
|
250
|
+
const viaPlugin = new Map();
|
|
251
|
+
for (const id of ids) {
|
|
252
|
+
const row = byId.get(id);
|
|
253
|
+
if (!row)
|
|
254
|
+
out.set(id, refuse("connector.not_found", "Connector not found"));
|
|
255
|
+
else if (row.status === "active")
|
|
256
|
+
out.set(id, alreadyOn("connector"));
|
|
257
|
+
else if (row.disabled_by_plugin_id !== null) {
|
|
258
|
+
if (usable.has(row.disabled_by_plugin_id))
|
|
259
|
+
out.set(id, alreadyOn("connector"));
|
|
260
|
+
else
|
|
261
|
+
viaPlugin.set(id, row.disabled_by_plugin_id);
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
out.set(id, {
|
|
265
|
+
ok: true,
|
|
266
|
+
target: { kind: "connector", id: row.id },
|
|
267
|
+
bundle: row.catalog_item_id,
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const plugins = await resolvePlugins(db, orgId, [...viaPlugin.values()], isAdmin);
|
|
272
|
+
for (const [id, item] of viaPlugin)
|
|
273
|
+
out.set(id, plugins.get(item) ?? pluginNotFound());
|
|
274
|
+
return out;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* The owning switch of models (`["<provider>","<model>"]`): the provider extension (or its plugin)
|
|
278
|
+
* while it is off in the org, else the org's own disabled list. A name the provider does not list
|
|
279
|
+
* and a model the platform disabled get the same `model.not_found`. With `listing` (what the
|
|
280
|
+
* providers list for the org) the provider's state is checked too: one that needs configuration
|
|
281
|
+
* or failed to list is refused as unavailable; without it (a settlement inside a writer's
|
|
282
|
+
* transaction) only the disabled lists decide.
|
|
283
|
+
*/
|
|
284
|
+
async function resolveModels(db, orgId, ids, isAdmin, listing, platformListing, loaded) {
|
|
285
|
+
const out = new Map();
|
|
286
|
+
const refs = new Map();
|
|
287
|
+
for (const id of ids) {
|
|
288
|
+
const ref = decodeModelId(id);
|
|
289
|
+
if (ref === null)
|
|
290
|
+
out.set(id, modelNotFound());
|
|
291
|
+
else
|
|
292
|
+
refs.set(id, ref);
|
|
293
|
+
}
|
|
294
|
+
if (refs.size === 0)
|
|
295
|
+
return out;
|
|
296
|
+
const providers = [...new Set([...refs.values()].map((r) => r.provider))];
|
|
297
|
+
const [disabledRows, facts] = await Promise.all([
|
|
298
|
+
db
|
|
299
|
+
.selectFrom("model_disabled")
|
|
300
|
+
.select(["org_id", "provider", "model"])
|
|
301
|
+
.where("provider", "in", providers)
|
|
302
|
+
.where((eb) => eb.or([eb("org_id", "is", null), eb("org_id", "=", orgId)]))
|
|
303
|
+
.execute(),
|
|
304
|
+
extensionFacts(db, orgId, providers, isAdmin),
|
|
305
|
+
]);
|
|
306
|
+
const platformOff = new Set(disabledRows.filter((r) => r.org_id === null).map((r) => `${r.provider}\u0000${r.model}`));
|
|
307
|
+
const orgOff = new Set(disabledRows.filter((r) => r.org_id !== null).map((r) => `${r.provider}\u0000${r.model}`));
|
|
308
|
+
const offProviders = providers.filter((p) => !facts.enabled.has(p));
|
|
309
|
+
const exts = await resolveExtensions(db, orgId, offProviders, isAdmin, loaded);
|
|
310
|
+
for (const [id, ref] of refs) {
|
|
311
|
+
const key = `${ref.provider}\u0000${ref.model}`;
|
|
312
|
+
if (platformOff.has(key)) {
|
|
313
|
+
out.set(id, modelNotFound());
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
if (!facts.enabled.has(ref.provider)) {
|
|
317
|
+
// the provider is off in the org: its switch (or its plugin's) comes first. The name is
|
|
318
|
+
// checked against the platform's list of the provider (an unknown name is not found, like a
|
|
319
|
+
// platform-disabled one); without a readable list the subject is recorded as the extension
|
|
320
|
+
const ext = exts.get(ref.provider);
|
|
321
|
+
if (ext === undefined || (!ext.ok && ext.error.code === "extension.not_found")) {
|
|
322
|
+
out.set(id, modelNotFound());
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
const platform = platformListing?.get(ref.provider);
|
|
326
|
+
if (platformListing !== undefined && platform?.status === "ok") {
|
|
327
|
+
out.set(id, platform.listed.has(ref.model) ? ext : modelNotFound());
|
|
328
|
+
}
|
|
329
|
+
else if (platformListing !== undefined && ext.ok) {
|
|
330
|
+
out.set(id, { ...ext, subject: { kind: "extension", id: ref.provider } });
|
|
331
|
+
}
|
|
332
|
+
else
|
|
333
|
+
out.set(id, ext);
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
const listed = listing?.get(ref.provider);
|
|
337
|
+
if (listing !== undefined) {
|
|
338
|
+
if (listed === undefined) {
|
|
339
|
+
out.set(id, modelNotFound());
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
if (listed.status === "needs_config") {
|
|
343
|
+
out.set(id, refuse("catalog.request_invalid", "This model's provider needs configuration in this organization first; ask an org admin to configure it"));
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (listed.status !== "ok") {
|
|
347
|
+
out.set(id, refuse("catalog.request_invalid", "This model's provider is unavailable right now (its model list failed); try again later"));
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
if (!listed.listed.has(ref.model)) {
|
|
351
|
+
out.set(id, modelNotFound());
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
if (!orgOff.has(key))
|
|
356
|
+
out.set(id, alreadyOn("model"));
|
|
357
|
+
else {
|
|
358
|
+
out.set(id, {
|
|
359
|
+
ok: true,
|
|
360
|
+
target: { kind: "model", id },
|
|
361
|
+
bundle: pluginPathItem(facts.items.get(ref.provider), facts.required.has(ref.provider)),
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return out;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* The owning switch of picker subjects in the org, by {@link targetKey}: one round of queries per
|
|
369
|
+
* kind present, whatever the number of subjects (see the per-kind resolvers).
|
|
370
|
+
*/
|
|
371
|
+
export async function resolveSubjects(db, orgId, subjects, isAdmin, live = {}) {
|
|
372
|
+
const ids = (kind) => subjects.filter((s) => s.kind === kind).map((s) => s.id);
|
|
373
|
+
const parts = [
|
|
374
|
+
["plugin", resolvePlugins(db, orgId, ids("plugin"), isAdmin)],
|
|
375
|
+
["extension", resolveExtensions(db, orgId, ids("extension"), isAdmin, live.loaded)],
|
|
376
|
+
["skill", resolveComponents(db, orgId, "skill", ids("skill"), isAdmin)],
|
|
377
|
+
[
|
|
378
|
+
"agent_template",
|
|
379
|
+
resolveComponents(db, orgId, "agent_template", ids("agent_template"), isAdmin),
|
|
380
|
+
],
|
|
381
|
+
[
|
|
382
|
+
"connector_template",
|
|
383
|
+
resolveComponents(db, orgId, "connector_template", ids("connector_template"), isAdmin),
|
|
384
|
+
],
|
|
385
|
+
["connector", resolveConnectors(db, orgId, ids("connector"), isAdmin)],
|
|
386
|
+
[
|
|
387
|
+
"model",
|
|
388
|
+
resolveModels(db, orgId, ids("model"), isAdmin, live.models, live.platformModels, live.loaded),
|
|
389
|
+
],
|
|
390
|
+
];
|
|
391
|
+
const out = new Map();
|
|
392
|
+
for (const [kind, part] of parts) {
|
|
393
|
+
for (const [id, r] of await part)
|
|
394
|
+
out.set(targetKey({ kind, id }), r);
|
|
395
|
+
}
|
|
396
|
+
return out;
|
|
397
|
+
}
|
|
398
|
+
/** The owning switch of one picker subject (see {@link resolveSubjects}). */
|
|
399
|
+
export async function resolveSubject(db, orgId, subject, isAdmin, live = {}) {
|
|
400
|
+
const r = (await resolveSubjects(db, orgId, [subject], isAdmin, live)).get(targetKey(subject));
|
|
401
|
+
return r ?? refuse("catalog.request_invalid", "Unknown subject");
|
|
402
|
+
}
|
|
403
|
+
/** The org's pending enable requests for `targets`, by {@link targetKey}. */
|
|
404
|
+
export async function pendingEnableRequests(db, orgId, targets) {
|
|
405
|
+
const out = new Map();
|
|
406
|
+
if (targets.length === 0)
|
|
407
|
+
return out;
|
|
408
|
+
const rows = await db
|
|
409
|
+
.selectFrom("catalog_requests")
|
|
410
|
+
.select([
|
|
411
|
+
"id",
|
|
412
|
+
sql `detail -> 'target' ->> 'kind'`.as("target_kind"),
|
|
413
|
+
sql `detail -> 'target' ->> 'id'`.as("target_id"),
|
|
414
|
+
])
|
|
415
|
+
.where("org_id", "=", orgId)
|
|
416
|
+
.where("kind", "=", "enable")
|
|
417
|
+
.where("status", "=", "pending")
|
|
418
|
+
.where(sql `(detail -> 'target' ->> 'kind', detail -> 'target' ->> 'id') IN (VALUES ${sql.join(targets.map((t) => sql `(${t.kind}::text, ${t.id}::text)`))})`)
|
|
419
|
+
.execute();
|
|
420
|
+
for (const r of rows)
|
|
421
|
+
out.set(targetKey({ kind: r.target_kind, id: r.target_id }), r.id);
|
|
422
|
+
return out;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* The picker projection (org-usable spec "Members and guests"): for each subject the caller may
|
|
426
|
+
* ask an org admin to turn on (the role has `catalog.request` and the subject resolves to a
|
|
427
|
+
* switch), its {@link RequestableFields}, by {@link targetKey} of the subject. Subjects that are
|
|
428
|
+
* hidden, blocked, unshared, built in or already on are absent, so nothing reveals them. Set-based:
|
|
429
|
+
* one round of queries per kind and one pending lookup.
|
|
430
|
+
*/
|
|
431
|
+
export async function requestableSubjects(db, orgId, role, subjects, live = {}) {
|
|
432
|
+
const out = new Map();
|
|
433
|
+
if (subjects.length === 0 || !can(role, "catalog.request"))
|
|
434
|
+
return out;
|
|
435
|
+
const resolved = await resolveSubjects(db, orgId, subjects, can(role, "catalog.decide"), live);
|
|
436
|
+
const targets = new Map();
|
|
437
|
+
for (const s of subjects) {
|
|
438
|
+
const r = resolved.get(targetKey(s));
|
|
439
|
+
if (r?.ok)
|
|
440
|
+
targets.set(targetKey(s), r.target);
|
|
441
|
+
}
|
|
442
|
+
const pending = await pendingEnableRequests(db, orgId, [...targets.values()]);
|
|
443
|
+
for (const [key, target] of targets) {
|
|
444
|
+
out.set(key, { requestable: true, pendingRequestId: pending.get(targetKey(target)) ?? null });
|
|
445
|
+
}
|
|
446
|
+
return out;
|
|
447
|
+
}
|
|
448
|
+
const decided = () => new ApiError("catalog.request_decided", "This request has already been decided");
|
|
449
|
+
/** Whether a resolution says the subject is usable (or coming on with its plugin). */
|
|
450
|
+
const usableNow = (r) => r !== undefined && !r.ok && r.on === true;
|
|
451
|
+
/**
|
|
452
|
+
* Settles locked pending enable rows of one org, in the caller's transaction: each subject (the
|
|
453
|
+
* requester's, and each follower's own) is resolved again in one batch; the row is approved when
|
|
454
|
+
* the requester's subject is usable (a `cancelReason: "target_changed"` cancellation otherwise),
|
|
455
|
+
* and each follower's own outcome is recorded in `detail.followers` for their notice. Audits
|
|
456
|
+
* each row under its own id. Returns the outcome of every row it settled (rows kept pending under
|
|
457
|
+
* `reconcile` are absent).
|
|
458
|
+
*/
|
|
459
|
+
export async function settleRequestRows(db, orgId, rows, mode, settlerOf) {
|
|
460
|
+
const out = new Map();
|
|
461
|
+
const parsed = rows.flatMap((r) => {
|
|
462
|
+
const d = readEnableDetail(r.detail);
|
|
463
|
+
return d === null ? [] : [{ row: r, d, subject: d.subject ?? d.target }];
|
|
464
|
+
});
|
|
465
|
+
const subjects = parsed.flatMap((p) => [
|
|
466
|
+
p.subject,
|
|
467
|
+
...(p.d.followers ?? []).map((f) => f.subject),
|
|
468
|
+
]);
|
|
469
|
+
const resolved = await resolveSubjects(db, orgId, subjects, true);
|
|
470
|
+
const outcomeOf = (subject, target) => (mode.kind === "on" && sameTarget(subject, mode.target) && sameTarget(target, mode.target)) ||
|
|
471
|
+
usableNow(resolved.get(targetKey(subject)))
|
|
472
|
+
? "approved"
|
|
473
|
+
: "target_changed";
|
|
474
|
+
for (const { row, d, subject } of parsed) {
|
|
475
|
+
if (mode.kind === "reconcile") {
|
|
476
|
+
const now = resolved.get(targetKey(subject));
|
|
477
|
+
if (now?.ok && sameTarget(now.target, d.target)) {
|
|
478
|
+
// the request stays; a follower whose own subject no longer needs this switch (hidden,
|
|
479
|
+
// removed, or another switch first) stops following it
|
|
480
|
+
const followers = d.followers ?? [];
|
|
481
|
+
const kept = followers.filter((f) => {
|
|
482
|
+
const r = resolved.get(targetKey(f.subject));
|
|
483
|
+
return r?.ok === true && sameTarget(r.target, d.target);
|
|
484
|
+
});
|
|
485
|
+
if (kept.length !== followers.length) {
|
|
486
|
+
const raw = (row.detail ?? {});
|
|
487
|
+
await db
|
|
488
|
+
.updateTable("catalog_requests")
|
|
489
|
+
.set({ detail: JSON.stringify({ ...raw, followers: kept }) })
|
|
490
|
+
.where("id", "=", row.id)
|
|
491
|
+
.where("org_id", "=", orgId)
|
|
492
|
+
.execute();
|
|
493
|
+
}
|
|
494
|
+
continue;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
const outcome = outcomeOf(subject, d.target);
|
|
498
|
+
const raw = (row.detail ?? {});
|
|
499
|
+
const next = {
|
|
500
|
+
...raw,
|
|
501
|
+
...(outcome === "target_changed" && { cancelReason: "target_changed" }),
|
|
502
|
+
...((d.followers ?? []).length > 0 && {
|
|
503
|
+
followers: (d.followers ?? []).map((f) => ({
|
|
504
|
+
...f,
|
|
505
|
+
outcome: outcomeOf(f.subject, d.target),
|
|
506
|
+
})),
|
|
507
|
+
}),
|
|
508
|
+
};
|
|
509
|
+
const s = settlerOf(row.id);
|
|
510
|
+
await db
|
|
511
|
+
.updateTable("catalog_requests")
|
|
512
|
+
.set({
|
|
513
|
+
status: outcome === "approved" ? "approved" : "cancelled",
|
|
514
|
+
detail: JSON.stringify(next),
|
|
515
|
+
decided_by: s.actor,
|
|
516
|
+
decided_at: sql `now()`,
|
|
517
|
+
})
|
|
518
|
+
.where("id", "=", row.id)
|
|
519
|
+
.where("org_id", "=", orgId)
|
|
520
|
+
.execute();
|
|
521
|
+
await audit(db, {
|
|
522
|
+
actorAccountId: s.actor,
|
|
523
|
+
...(s.actorTokenId !== undefined && { actorTokenId: s.actorTokenId }),
|
|
524
|
+
orgId,
|
|
525
|
+
action: outcome === "approved" ? "catalog.request_decided" : "catalog.request_cancelled",
|
|
526
|
+
target: row.id,
|
|
527
|
+
detail: {
|
|
528
|
+
...s.auditDetail,
|
|
529
|
+
itemId: row.item_id ?? null,
|
|
530
|
+
kind: "enable",
|
|
531
|
+
target: d.target,
|
|
532
|
+
...(outcome === "approved" ? { decision: "approve" } : { reason: "target_changed" }),
|
|
533
|
+
},
|
|
534
|
+
});
|
|
535
|
+
out.set(row.id, outcome);
|
|
536
|
+
}
|
|
537
|
+
return out;
|
|
538
|
+
}
|
|
539
|
+
/** An audit detail without a `requestId` (it names the request the writer was called for). */
|
|
540
|
+
function ownDetail(detail) {
|
|
541
|
+
const { requestId: _requestId, ...rest } = detail ?? {};
|
|
542
|
+
return rest;
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* A switch writer turned `target` on in the org, in its transaction: the org's pending enable
|
|
546
|
+
* requests for that target are settled (rows locked FOR UPDATE, {@link settleRequestRows}). With
|
|
547
|
+
* an org admin's approval in scope ({@link currentEnableDecision}) for this target, that request
|
|
548
|
+
* must still be pending (else `catalog.request_decided`, which rolls the write back) unless this
|
|
549
|
+
* transaction settled it already, and is settled as the admin's decision: approved when its
|
|
550
|
+
* subject is usable now, else cancelled (`target_changed`) and the admin is told another switch
|
|
551
|
+
* is needed. The caller reads the committed row: a rolled-back write leaves it pending.
|
|
552
|
+
* `opts.settle: false` (an install failure recording the switch) settles nothing.
|
|
553
|
+
*
|
|
554
|
+
* Called by: `ScopeWriter.setOrgSwitch` (plugin and component switches), `resolveRequestsByInstall`
|
|
555
|
+
* (installs), `OrgExtensionConfigs` (the extension switch), `ModelEnablement.setOrg` (org models
|
|
556
|
+
* switched back on) and `ConnectorsService` (a connector set active, by an org admin, the platform
|
|
557
|
+
* or a plugin switch-on).
|
|
558
|
+
*/
|
|
559
|
+
export async function settleEnableRequests(db, orgId, target, actor, opts = {}) {
|
|
560
|
+
if (opts.settle === false)
|
|
561
|
+
return [];
|
|
562
|
+
const decision = currentEnableDecision();
|
|
563
|
+
const deciding = decision !== undefined && decision.orgId === orgId && sameTarget(decision.target, target)
|
|
564
|
+
? decision
|
|
565
|
+
: undefined;
|
|
566
|
+
const rows = await db
|
|
567
|
+
.selectFrom("catalog_requests")
|
|
568
|
+
.select(["id", "detail", "item_id"])
|
|
569
|
+
.where("org_id", "=", orgId)
|
|
570
|
+
.where("kind", "=", "enable")
|
|
571
|
+
.where("status", "=", "pending")
|
|
572
|
+
.where(sql `detail -> 'target' ->> 'kind' = ${target.kind}`)
|
|
573
|
+
.where(sql `detail -> 'target' ->> 'id' = ${target.id}`)
|
|
574
|
+
.orderBy("id")
|
|
575
|
+
.forUpdate()
|
|
576
|
+
.execute();
|
|
577
|
+
if (deciding !== undefined && !rows.some((r) => r.id === deciding.requestId)) {
|
|
578
|
+
// settled earlier in this same transaction (an install settles twice) is fine; decided by
|
|
579
|
+
// anyone else is a conflict
|
|
580
|
+
const mine = await db
|
|
581
|
+
.selectFrom("catalog_requests")
|
|
582
|
+
.select("id")
|
|
583
|
+
.where("id", "=", deciding.requestId)
|
|
584
|
+
.where("org_id", "=", orgId)
|
|
585
|
+
// written by this transaction: the row's xmin is our (32-bit) transaction id
|
|
586
|
+
.where(sql `xmin::text::bigint = pg_current_xact_id()::text::bigint % 4294967296`)
|
|
587
|
+
.executeTakeFirst();
|
|
588
|
+
if (!mine)
|
|
589
|
+
throw decided();
|
|
590
|
+
}
|
|
591
|
+
if (deciding !== undefined && rows.some((r) => r.id === deciding.requestId)) {
|
|
592
|
+
deciding.settled = true;
|
|
593
|
+
}
|
|
594
|
+
const settled = await settleRequestRows(db, orgId, rows, { kind: "on", target }, (id) => id === deciding?.requestId
|
|
595
|
+
? {
|
|
596
|
+
actor: deciding.actor,
|
|
597
|
+
actorTokenId: deciding.actorTokenId,
|
|
598
|
+
auditDetail: deciding.auditDetail,
|
|
599
|
+
}
|
|
600
|
+
: {
|
|
601
|
+
actor,
|
|
602
|
+
actorTokenId: opts.actorTokenId,
|
|
603
|
+
auditDetail: { ...ownDetail(opts.auditDetail), switched: true },
|
|
604
|
+
});
|
|
605
|
+
return [...settled.keys()];
|
|
606
|
+
}
|
|
607
|
+
/** Cancels the pending enable requests `where` selects in the org (rows the caller chose). */
|
|
608
|
+
async function cancelEnableWhere(db, orgId, where, actor, reason) {
|
|
609
|
+
// rows locked in id order first, as settlement and reconciliation lock them (no deadlock)
|
|
610
|
+
const locked = await db
|
|
611
|
+
.selectFrom("catalog_requests")
|
|
612
|
+
.select("id")
|
|
613
|
+
.where("org_id", "=", orgId)
|
|
614
|
+
.where("kind", "=", "enable")
|
|
615
|
+
.where("status", "=", "pending")
|
|
616
|
+
.where(where)
|
|
617
|
+
.orderBy("id")
|
|
618
|
+
.forUpdate()
|
|
619
|
+
.execute();
|
|
620
|
+
if (locked.length === 0)
|
|
621
|
+
return;
|
|
622
|
+
const rows = await db
|
|
623
|
+
.updateTable("catalog_requests")
|
|
624
|
+
.set({
|
|
625
|
+
status: "cancelled",
|
|
626
|
+
// a removed connector is gone: no "ask again" notice
|
|
627
|
+
...(reason === "target_changed" && {
|
|
628
|
+
detail: sql `detail || '{"cancelReason":"target_changed"}'::jsonb`,
|
|
629
|
+
}),
|
|
630
|
+
decided_by: actor,
|
|
631
|
+
decided_at: sql `now()`,
|
|
632
|
+
})
|
|
633
|
+
.where("org_id", "=", orgId)
|
|
634
|
+
.where("id", "in", locked.map((r) => r.id))
|
|
635
|
+
.returning(["id", "detail"])
|
|
636
|
+
.execute();
|
|
637
|
+
for (const r of rows) {
|
|
638
|
+
await audit(db, {
|
|
639
|
+
actorAccountId: actor,
|
|
640
|
+
orgId,
|
|
641
|
+
action: "catalog.request_cancelled",
|
|
642
|
+
target: r.id,
|
|
643
|
+
detail: { kind: "enable", target: readEnableDetail(r.detail)?.target ?? null, reason },
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* A plugin was switched off in the org, in the writer's transaction: pending enable requests for
|
|
649
|
+
* an extension, a component, a connector or a model that needed that plugin on (`detail.bundle`)
|
|
650
|
+
* are stale (the plugin is their owning switch now) and are cancelled with
|
|
651
|
+
* `cancelReason: "target_changed"`. Called by `ScopeWriter.setOrgSwitch` (plugin off).
|
|
652
|
+
*/
|
|
653
|
+
export function cancelEnableRequestsOfBundle(db, orgId, itemId, actor) {
|
|
654
|
+
return cancelEnableWhere(db, orgId, sql `detail ->> 'bundle' = ${itemId}`, actor, "target_changed");
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* A model provider extension was switched off in the org, in the writer's transaction: pending
|
|
658
|
+
* requests for its models are stale (the extension is their owning switch now). Called by
|
|
659
|
+
* `OrgExtensionConfigs` (extension off).
|
|
660
|
+
*/
|
|
661
|
+
export function cancelEnableRequestsOfProvider(db, orgId, provider, actor) {
|
|
662
|
+
return cancelEnableWhere(db, orgId,
|
|
663
|
+
// a prefix match of the canonical tuple: never parses another row's id (nothing can throw)
|
|
664
|
+
sql `detail -> 'target' ->> 'kind' = 'model' AND starts_with(detail -> 'target' ->> 'id', '[' || to_jsonb(${provider}::text)::text || ',')`, actor, "target_changed");
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* A connector was disabled by its plugin's switch-off (`target_changed`: the plugin is its owning
|
|
668
|
+
* switch now) or removed (`connector_removed`, no notice), in the writer's transaction: pending
|
|
669
|
+
* requests for it are cancelled. Called by `ConnectorsService.disableWithPluginIn` and `removeIn`.
|
|
670
|
+
*/
|
|
671
|
+
export function cancelEnableRequestsOfConnector(db, orgId, connectorId, actor, reason) {
|
|
672
|
+
return cancelEnableWhere(db, orgId, sql `detail -> 'target' ->> 'kind' = 'connector' AND detail -> 'target' ->> 'id' = ${connectorId}`, actor, reason);
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* The platform disabled models of a provider, in its transaction: every org's pending requests
|
|
676
|
+
* for them (as target or subject) are cancelled; the model is hidden from the orgs, so no "ask
|
|
677
|
+
* again" notice. Called by `ModelEnablement.setPlatform`.
|
|
678
|
+
*/
|
|
679
|
+
export async function cancelEnableRequestsOfPlatformModels(db, provider, models, actor) {
|
|
680
|
+
if (models.length === 0)
|
|
681
|
+
return;
|
|
682
|
+
const ids = models.map((m) => JSON.stringify([provider, m]));
|
|
683
|
+
const rows = await asPlatform("cancel every org's requests for models the platform disabled", async () => {
|
|
684
|
+
// org-filter: deployment-wide: the platform's model list applies to every org (rows locked
|
|
685
|
+
// in id order first, as settlement and reconciliation lock them)
|
|
686
|
+
const locked = await db
|
|
687
|
+
.selectFrom("catalog_requests")
|
|
688
|
+
.select("id")
|
|
689
|
+
.where("kind", "=", "enable")
|
|
690
|
+
.where("status", "=", "pending")
|
|
691
|
+
.where((eb) => eb.or([
|
|
692
|
+
sql `(detail -> 'target' ->> 'kind' = 'model' AND detail -> 'target' ->> 'id' = ANY(${ids}::text[]))`,
|
|
693
|
+
sql `(detail -> 'subject' ->> 'kind' = 'model' AND detail -> 'subject' ->> 'id' = ANY(${ids}::text[]))`,
|
|
694
|
+
]))
|
|
695
|
+
.orderBy("id")
|
|
696
|
+
.forUpdate()
|
|
697
|
+
.execute();
|
|
698
|
+
if (locked.length === 0)
|
|
699
|
+
return [];
|
|
700
|
+
// org-filter: deployment-wide: the rows locked just above, of every org
|
|
701
|
+
const found = await db
|
|
702
|
+
.updateTable("catalog_requests")
|
|
703
|
+
.set({ status: "cancelled", decided_by: actor, decided_at: sql `now()` })
|
|
704
|
+
.where("id", "in", locked.map((r) => r.id))
|
|
705
|
+
.returning(["id", "org_id", "detail"])
|
|
706
|
+
.execute();
|
|
707
|
+
return found;
|
|
708
|
+
});
|
|
709
|
+
for (const r of rows) {
|
|
710
|
+
await withOrgScope(r.org_id, () => audit(db, {
|
|
711
|
+
actorAccountId: actor,
|
|
712
|
+
orgId: r.org_id,
|
|
713
|
+
action: "catalog.request_cancelled",
|
|
714
|
+
target: r.id,
|
|
715
|
+
detail: {
|
|
716
|
+
kind: "enable",
|
|
717
|
+
target: readEnableDetail(r.detail)?.target ?? null,
|
|
718
|
+
reason: "model_disabled",
|
|
719
|
+
},
|
|
720
|
+
}));
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* The platform changed a plugin's or a component's scope, share or disabled flag, in its
|
|
725
|
+
* transaction: the pending enable requests of every org that target it, or that need the plugin
|
|
726
|
+
* on (`detail.bundle`), are checked against their subjects again ({@link settleRequestRows},
|
|
727
|
+
* `reconcile`): a subject usable now approves the request, one whose owning switch is still the
|
|
728
|
+
* stored target keeps it pending, any other outcome (hidden, blocked, another switch first)
|
|
729
|
+
* cancels it with `cancelReason: "target_changed"`. Called by `writeScope` (every scope write),
|
|
730
|
+
* `ScopeWriter.setDisabled` and the unshare paths.
|
|
731
|
+
*/
|
|
732
|
+
export async function reconcileEnableRequestsOf(db, subject, actor) {
|
|
733
|
+
if (subject.kind === "theme")
|
|
734
|
+
return;
|
|
735
|
+
const kind = subject.kind;
|
|
736
|
+
const rows = await asPlatform("find every org's enable requests a platform scope change affects", async () => {
|
|
737
|
+
// org-filter: deployment-wide: a platform scope change re-checks the requests of every org
|
|
738
|
+
const found = await db
|
|
739
|
+
.selectFrom("catalog_requests")
|
|
740
|
+
.select(["id", "org_id", "detail", "item_id"])
|
|
741
|
+
.where("kind", "=", "enable")
|
|
742
|
+
.where("status", "=", "pending")
|
|
743
|
+
.where((eb) => eb.or([
|
|
744
|
+
sql `(detail -> 'target' ->> 'kind' = ${kind} AND detail -> 'target' ->> 'id' = ${subject.id})`,
|
|
745
|
+
...(kind === "plugin" ? [sql `detail ->> 'bundle' = ${subject.id}`] : []),
|
|
746
|
+
// a request whose own subject, or a follower's, is the changed one
|
|
747
|
+
sql `(detail -> 'subject' ->> 'kind' = ${kind} AND detail -> 'subject' ->> 'id' = ${subject.id})`,
|
|
748
|
+
sql `detail -> 'followers' @> jsonb_build_array(jsonb_build_object('subject', jsonb_build_object('kind', ${kind}::text, 'id', ${subject.id}::text)))`,
|
|
749
|
+
]))
|
|
750
|
+
.orderBy("id")
|
|
751
|
+
.forUpdate()
|
|
752
|
+
.execute();
|
|
753
|
+
return found;
|
|
754
|
+
});
|
|
755
|
+
const byOrg = new Map();
|
|
756
|
+
for (const r of rows)
|
|
757
|
+
byOrg.set(r.org_id, [...(byOrg.get(r.org_id) ?? []), r]);
|
|
758
|
+
for (const [orgId, list] of byOrg) {
|
|
759
|
+
// each org's requests are checked and written in that org's scope
|
|
760
|
+
await withOrgScope(orgId, () => settleRequestRows(db, orgId, list, { kind: "reconcile" }, () => ({ actor })));
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
/** Whether the request's subject is its target (a legacy row without a subject counts as one). */
|
|
764
|
+
export function subjectIsTarget(detail) {
|
|
765
|
+
const d = readEnableDetail(detail);
|
|
766
|
+
return d !== null && (d.subject === undefined || sameTarget(d.subject, d.target));
|
|
767
|
+
}
|