Showing the changes to apps/host-selfhost/src/apps.ts (1 of 19 files). Show all
Unified · Split
| @@ -0,0 +1,71 @@ | ||
| 1 | +import { join } from "node:path"; | |
| 2 | + | |
| 3 | +import { Effect } from "effect"; | |
| 4 | + | |
| 5 | +import { | |
| 6 | + appsPlugin, | |
| 7 | + BindingError, | |
| 8 | + makeSelfHostAppsRuntime, | |
| 9 | + makeSqliteAppsStore, | |
| 10 | + type AppsRuntime, | |
| 11 | + type ClientResolver, | |
| 12 | +} from "@executor-js/plugin-apps/api"; | |
| 13 | +import type { PluginCtx } from "@executor-js/sdk"; | |
| 14 | + | |
| 15 | +import { resolveDataDir } from "./config"; | |
| 16 | +import { makeSelfHostAppsResolver } from "./apps-resolver"; | |
| 17 | + | |
| 18 | +const missingResolver = (): ClientResolver => ({ | |
| 19 | + listConnections: () => Effect.succeed([]), | |
| 20 | + resolveConnection: () => Effect.succeed(null), | |
| 21 | + call: ({ integration, connection }) => | |
| 22 | + Effect.fail( | |
| 23 | + new BindingError({ | |
| 24 | + role: integration, | |
| 25 | + integration, | |
| 26 | + requestedConnection: connection, | |
| 27 | + message: "apps resolver is unavailable outside a request-scoped executor", | |
| 28 | + }), | |
| 29 | + ), | |
| 30 | +}); | |
| 31 | + | |
| 32 | +const createSubsystem = (dataDir: string) => { | |
| 33 | + const appsDir = join(dataDir, "apps"); | |
| 34 | + const store = makeSqliteAppsStore({ path: join(appsDir, "store.sqlite") }); | |
| 35 | + const host = makeSelfHostAppsRuntime({ | |
| 36 | + dataDir: appsDir, | |
| 37 | + store, | |
| 38 | + resolver: missingResolver(), | |
| 39 | + }); | |
| 40 | + const plugin = appsPlugin({ | |
| 41 | + runtime: host.runtime, | |
| 42 | + makeResolver: ({ ctx }) => makeSelfHostAppsResolver({ ctx: ctx as PluginCtx }), | |
| 43 | + }); | |
| 44 | + return { | |
| 45 | + runtime: host.runtime, | |
| 46 | + plugin, | |
| 47 | + close: host.close, | |
| 48 | + }; | |
| 49 | +}; | |
| 50 | + | |
| 51 | +export interface SelfHostAppsSubsystem { | |
| 52 | + readonly runtime: AppsRuntime; | |
| 53 | + readonly plugin: ReturnType<typeof appsPlugin>; | |
| 54 | + readonly close: () => Promise<void>; | |
| 55 | +} | |
| 56 | + | |
| 57 | +let current: { readonly dataDir: string; readonly subsystem: SelfHostAppsSubsystem } | undefined; | |
| 58 | + | |
| 59 | +export const getSelfHostAppsSubsystem = (): SelfHostAppsSubsystem => { | |
| 60 | + const dataDir = resolveDataDir(); | |
| 61 | + if (current && current.dataDir === dataDir) return current.subsystem; | |
| 62 | + const subsystem = createSubsystem(dataDir); | |
| 63 | + current = { dataDir, subsystem }; | |
| 64 | + return subsystem; | |
| 65 | +}; | |
| 66 | + | |
| 67 | +export const closeSelfHostAppsSubsystem = async (): Promise<void> => { | |
| 68 | + const subsystem = current?.subsystem; | |
| 69 | + current = undefined; | |
| 70 | + await subsystem?.close(); | |
| 71 | +}; | |