Repository navigation
Expand file tree
/
Copy pathcomposition.ts
More file actions
521 lines (508 loc) · 17.2 KB
/
Copy pathcomposition.ts
File metadata and controls
521 lines (508 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import { pluginServices } from "@core/shared/plugin-services.js";
import { registerKnowledgeBooks } from "../routes/knowledge-books.js";
import { createHostFileStore } from "../services/host-file-store.js";
import { createCredentialCipher } from "../services/credential-cipher.js";
import { verifyCredentialKey } from "../services/plugin-credentials.js";
import {
bindPluginStorage,
cleanupPluginObjects,
cleanupPluginDatabases,
} from "../services/plugin-storage.js";
import {
pluginDatabaseToken,
pluginObjectStorageToken,
pluginCredentialToken,
} from "@smartdoca/plugin-sdk/storage";
import { registerPluginMobileSessions } from "./mobile-session.js";
import { registerNavigation } from "../routes/navigation.js";
import { PluginManager } from "./manager.js";
import { registerPluginManagement } from "../routes/plugins.js";
import { cleanupFileReceipts } from "./file-receipt-cleanup.js";
import { searchServiceToken } from "@smartdoca/plugin-sdk/search";
import { activeActor } from "@core/modules/access/queries.js";
import { provideAI } from "./ai-capability.js";
import { createDocumentsPlugin } from "@doca/plugin-documents";
import { createFilesPlugin } from "@doca/plugin-files";
import { AIContributionHost } from "@doca/ai-host";
import { PluginHost } from "@doca/plugin-host";
import { definePlugin, type DocaPlugin } from "@smartdoca/plugin-sdk";
import type { FilesServiceV1 } from "@smartdoca/files-capability";
import { createFileProcessingWorker } from "../jobs/file-processing-worker.js";
import { waitForFileExtracts } from "../services/ai/file-extract.js";
import { registerAI } from "../routes/ai.js";
import type { AIContributionExecutionContext } from "../services/ai/runner.js";
import { registerFiles } from "../routes/files.js";
import { registerKnowledge } from "../routes/knowledge.js";
import { registerSearch } from "../routes/search.js";
import {
aiContributionToken,
searchRegistrationToken,
searchSourceRegistryToken,
serverRuntimeToken,
type SearchRegistration,
type SearchRegistrationService,
type ServerRuntimeService,
} from "./contracts.js";
import { mountFastifyAdapter } from "./fastify-adapter.js";
import { createServerFilesCapability } from "./files-capability-adapter.js";
import { createServerDocumentsCapability } from "./documents-capability-adapter.js";
import {
createDocumentSource,
createFileSource,
createKnowledgeSource,
} from "../services/search/sources.js";
import { importInstalledPlugins, pluginDirectory } from "./installation.js";
import { registerPluginAssets, pluginWebUrl } from "./web-assets.js";
import { registerStorePluginIcons } from "./store-icons.js";
import { providePlatform } from "./platform.js";
export interface ServerPluginDescriptor {
readonly id: string;
readonly version: string;
}
export interface ServerPluginComposition {
readonly host: PluginHost;
readonly search: SearchRegistration;
readonly plugins: readonly ServerPluginDescriptor[];
}
const runtimeManifest = {
schemaVersion: 1,
id: "doca.server-runtime",
version: "0.1.0",
displayName: "Doca Server Runtime",
} as const;
const searchManifest = {
schemaVersion: 1,
id: "doca.search",
version: "0.1.0",
displayName: "Doca Search",
dependencies: [{ id: "doca.server-runtime", range: "^0.1.0" }],
} as const;
const aiManifest = {
schemaVersion: 1,
id: "doca.ai",
version: "0.1.0",
displayName: "Doca AI",
dependencies: [
{ id: "doca.server-runtime", range: "^0.1.0" },
{ id: "doca.search", range: "^0.1.0" },
{ id: "doca.documents", range: "^0.1.0" },
],
} as const;
function runtimePlugin(runtime: ServerRuntimeService) {
return definePlugin({
manifest: runtimeManifest,
async discover(context) {
context.provide(serverRuntimeToken, runtime);
context.provide(pluginDatabaseToken, Object.freeze({}) as never);
context.provide(pluginObjectStorageToken, Object.freeze({}) as never);
context.provide(pluginCredentialToken, Object.freeze({}) as never);
await providePlatform(context, runtime);
},
});
}
function searchPlugin() {
let registration: SearchRegistration | undefined;
const service: SearchRegistrationService = {
require() {
if (!registration) throw new Error("Search registration is not mounted");
return registration;
},
};
return definePlugin({
manifest: searchManifest,
injections: { required: [serverRuntimeToken] },
discover(context) {
context.provide(searchRegistrationToken, service);
context.provide(searchServiceToken, {
register(source) {
const contextFor = (ctx: any) => ({
principalId: ctx.kind === "plugin" ? ctx.principalId : null,
signal: ctx.signal,
});
const handle = service.require().registerSource({
descriptor: source.descriptor,
prepareQuery: (request) =>
request.context.kind !== "plugin"
? null
: source.prepareQuery
? source.prepareQuery({
...request,
context: contextFor(request.context),
})
: { query: request.query },
authorize: (request) =>
request.context.kind !== "plugin"
? []
: source.authorize({
...request,
context: contextFor(request.context),
}),
hydrate: (request) =>
request.context.kind !== "plugin"
? []
: source.hydrate({
...request,
context: contextFor(request.context),
}),
...(source.projections
? {
projections: (request) =>
source.projections!({
...request,
context: contextFor(request.context),
}),
}
: {}),
});
return () => handle.dispose();
},
upsert(source, projections) {
return service
.require()
.searchHost.upsertProjections({ source, projections });
},
delete(source, documentIds) {
return service
.require()
.searchHost.deleteProjections({ source, documentIds });
},
rebuild(source, signal) {
return service.require().searchHost.rebuild({
source,
signal,
context: { kind: "system" },
});
},
async query(request, input) {
const runtime = context.inject(serverRuntimeToken);
await activeActor(runtime.db, {
id: request.principal.id,
display_name: request.principal.displayName,
public_id: request.principal.publicId,
admin: Number(request.principal.admin),
});
return service.require().searchHost.query({
query: input.query,
sources: [input.source],
offset: input.offset,
limit: input.limit,
context: {
kind: "plugin",
principalId: request.principal.id,
signal: request.signal,
},
});
},
});
context.provide(searchSourceRegistryToken, {
register(source) {
return service.require().registerSource(source);
},
});
},
async mount(context) {
const runtime = context.inject(serverRuntimeToken);
await context.effectAsync(async () => {
const mounted = await mountFastifyAdapter(runtime.api, (api) =>
registerSearch(api, runtime.db, runtime.admin, {
// Credential updates replace these fields on the shared runtime.
// Copying them here would keep the startup values until restart.
get allowedOrigins() {
return runtime.runtime.search.allowedOrigins;
},
get apiKey() {
return runtime.runtime.search.apiKey;
},
get fetch() {
return runtime.runtime.search.fetch;
},
sources: {
documents: false,
files: false,
knowledge: false,
},
}),
);
registration = mounted.value;
return async () => {
registration = undefined;
await mounted.dispose();
};
});
},
});
}
function documentsPlugin(
runtimeService: ServerRuntimeService,
files: FilesServiceV1,
) {
return createDocumentsPlugin({
runtimeToken: serverRuntimeToken,
searchToken: searchRegistrationToken,
unload: "app-close",
service: createServerDocumentsCapability(runtimeService.db, files),
searchSources: [
createDocumentSource(runtimeService.db),
createKnowledgeSource(runtimeService.db),
],
async mount({ runtime, search }) {
const registration = search.require();
const mounted = await mountFastifyAdapter(runtime.api, (api) => {
registerKnowledgeBooks(api, runtime.db, runtime.auth, runtime.runtime.storage);
return registerKnowledge(api, runtime.db, runtime.auth, {
indexer: registration.knowledgeIndex,
notify: runtime.realtime.documentChanged,
storage: runtime.runtime.storage,
});
});
return mounted.dispose;
},
});
}
function aiPlugin(files: FilesServiceV1) {
const contributions =
new AIContributionHost<AIContributionExecutionContext>();
return definePlugin({
manifest: aiManifest,
injections: {
required: [serverRuntimeToken, searchRegistrationToken],
},
discover(context) {
context.provide(aiContributionToken, contributions);
provideAI(context, context.inject(serverRuntimeToken).db, contributions);
},
async mount(context) {
const runtime = context.inject(serverRuntimeToken);
const search = context.inject(searchRegistrationToken).require();
await context.effectAsync(async () => {
const mounted = await mountFastifyAdapter(runtime.api, (api) =>
registerAI(api, runtime.db, runtime.auth, runtime.admin, {
...runtime.options.ai,
publicOrigin: runtime.origin.origin,
mcpRateLimit: runtime.consumeRateLimit,
storage: runtime.runtime.storage,
files,
notify: runtime.realtime.documentChanged,
search: search.search,
fileSearch: search.searchFiles,
contributions,
}),
);
return mounted.dispose;
});
},
});
}
function filesPlugin(
runtimeService: ServerRuntimeService,
service: FilesServiceV1,
) {
return createFilesPlugin({
runtimeToken: serverRuntimeToken,
searchToken: searchRegistrationToken,
unload: "app-close",
service,
searchSources: [createFileSource(runtimeService.db)],
async mount({ runtime, search }) {
const registration = search.require();
const routes = await mountFastifyAdapter(runtime.api, (api) =>
registerFiles(
api,
runtime.db,
runtime.auth,
runtime.runtime.storage,
runtime.admin,
registration.searchFiles,
),
);
const worker = createFileProcessingWorker(
runtime.db,
runtime.runtime.storage,
);
let processing: Promise<unknown> | undefined;
let cleaning: Promise<unknown> | undefined;
const clean = () => {
if (cleaning || !runtime.runtime.storage) return;
cleaning = cleanupFileReceipts(runtime.db, runtime.runtime.storage)
.catch((error) =>
runtime.api.log.error(error, "File staging cleanup failed"),
)
.finally(() => {
cleaning = undefined;
});
};
const cleanupTimer = setInterval(clean, 60 * 60 * 1000);
cleanupTimer.unref();
clean();
const timer = setInterval(() => {
if (processing) return;
processing = worker
.pump()
.catch((error) =>
runtime.api.log.error(error, "File processing failed"),
)
.finally(() => {
processing = undefined;
});
}, 1000);
timer.unref();
return async () => {
clearInterval(timer);
clearInterval(cleanupTimer);
await cleaning;
await processing;
await waitForFileExtracts(runtime.db);
await routes.dispose();
};
},
});
}
export async function composeServerPlugins(
runtime: ServerRuntimeService,
): Promise<ServerPluginComposition> {
const host = new PluginHost();
pluginServices(runtime.db).continuationsReady = false;
const credentialCipher = createCredentialCipher();
runtime.api.addHook("onClose", async () => credentialCipher.dispose());
try {
await verifyCredentialKey(runtime.db, credentialCipher);
const files = createServerFilesCapability(
runtime.db,
runtime.runtime.storage,
);
const plugins: DocaPlugin[] = [
runtimePlugin(runtime),
searchPlugin(),
documentsPlugin(runtime, files),
aiPlugin(files),
filesPlugin(runtime, files),
];
const manager = new PluginManager(
runtime.options.pluginDirectory ?? pluginDirectory(),
plugins.map((p) => p.manifest),
runtime.db,
undefined,
createHostFileStore(runtime.runtime.storage),
credentialCipher,
);
let cleanupInFlight: Promise<void> | undefined;
const cleanup = () => {
if (cleanupInFlight) return cleanupInFlight;
cleanupInFlight = Promise.all([
cleanupPluginObjects(runtime.db, manager.archiveStore),
cleanupPluginDatabases(runtime.db),
])
.then(([objects, databases]) => {
if (objects.failed || databases.failed)
runtime.api.log.warn({ objects, databases }, "Plugin storage cleanup pending");
})
.catch((error) =>
runtime.api.log.error(error, "Plugin storage cleanup failed"),
)
.finally(() => {
cleanupInFlight = undefined;
});
return cleanupInFlight;
};
const cleanupTimer = setInterval(() => void cleanup(), 60_000);
cleanupTimer.unref();
runtime.api.addHook("onClose", async () => {
clearInterval(cleanupTimer);
await cleanupInFlight;
});
await cleanup();
const installed = await manager.prepare(runtime.options.plugins);
plugins.push(
...(await importInstalledPlugins(
installed,
plugins.map((p) => p.manifest),
(p) =>
bindPluginStorage(
runtime.db,
manager.archiveStore,
p.manifest.id,
p.dataVersion,
credentialCipher,
),
)),
);
for (const plugin of plugins) host.register(plugin);
const descriptors = host.order.map((id) => {
const manifest = plugins.find(
(plugin) => plugin.manifest.id === id,
)!.manifest;
const installedPlugin = installed.find((p) => p.manifest.id === id);
return {
id: manifest.id,
version: manifest.version,
...(installedPlugin?.web ? { web: pluginWebUrl(installedPlugin) } : {}),
};
});
const unavailable = pluginServices(runtime.db).unavailablePlugins;
unavailable.clear();
for (const plugin of manager.unavailable()) unavailable.add(plugin.id);
runtime.api.addHook("onClose", async () => { unavailable.clear(); });
await host.start();
try {
await manager.confirm();
} catch (error) {
await host.dispose();
throw error;
}
for (const plugin of manager.unavailable())
runtime.api.log.warn({ pluginId: plugin.id, version: plugin.version, issue: plugin.issue }, "Plugin unavailable; upgrade the plugin and restart");
pluginServices(runtime.db).continuationsReady = true;
registerPluginManagement(runtime.api, runtime.db, runtime.admin, manager);
const iconPluginIds = new Set(
(await manager.inventory()).plugins
.filter(
(plugin) =>
plugin.source !== "local" &&
plugin.runningVersion !== null &&
installed.some((item) => item.manifest.id === plugin.id && !!item.web),
)
.map((plugin) => plugin.id),
);
registerStorePluginIcons(
runtime.api,
runtime.auth,
async (id) =>
iconPluginIds.has(id) ||
(await manager.inventory()).plugins.some(
(plugin) => plugin.id === id && plugin.source !== "local",
),
manager.store,
);
registerPluginMobileSessions(
runtime.api,
runtime.db,
runtime.auth,
installed.flatMap((p) => p.navigation),
runtime.origin.protocol === "https:",
);
registerNavigation(
runtime.api,
runtime.db,
runtime.auth,
runtime.admin,
installed.flatMap((p) => p.navigation),
);
registerPluginAssets(runtime.api, installed, (id, version) =>
manager.assetPlugin(id, version),
);
const search = host
.context(searchManifest.id)!
.inject(searchRegistrationToken)
.require();
return { host, search, plugins: descriptors };
} catch (error) {
pluginServices(runtime.db).continuationsReady = false;
pluginServices(runtime.db).unavailablePlugins.clear();
try {
await host.dispose();
} finally {
credentialCipher.dispose();
}
throw error;
}
}