1
0
silverbullet/cli/plug_run.ts

70 lines
2.0 KiB
TypeScript
Raw Normal View History

2023-08-04 16:56:55 +00:00
import { DiskSpacePrimitives } from "../common/spaces/disk_space_primitives.ts";
import { AssetBundle } from "../plugos/asset_bundle/bundle.ts";
2023-08-11 18:37:13 +00:00
import { Application } from "../server/deps.ts";
2023-08-29 19:17:29 +00:00
import { sleep } from "$sb/lib/async.ts";
2023-08-26 06:31:51 +00:00
import { ServerSystem } from "../server/server_system.ts";
import { AssetBundlePlugSpacePrimitives } from "../common/spaces/asset_bundle_space_primitives.ts";
import { determineDatabaseBackend } from "../server/db_backend.ts";
import { EndpointHook } from "../plugos/hooks/endpoint.ts";
import { determineShellBackend } from "../server/shell_backend.ts";
2023-08-11 18:37:13 +00:00
2023-08-04 16:56:55 +00:00
export async function runPlug(
spacePath: string,
2023-08-11 18:37:13 +00:00
functionName: string | undefined,
2023-08-04 16:56:55 +00:00
args: string[] = [],
builtinAssetBundle: AssetBundle,
2023-08-11 18:37:13 +00:00
httpServerPort = 3123,
httpHostname = "127.0.0.1",
2023-08-04 16:56:55 +00:00
) {
2023-08-11 18:37:13 +00:00
const serverController = new AbortController();
2023-08-26 06:31:51 +00:00
const app = new Application();
2023-12-18 13:39:52 +00:00
const dbBackend = await determineDatabaseBackend(spacePath);
if (!dbBackend) {
console.error("Cannot run plugs in databaseless mode.");
return;
}
const endpointHook = new EndpointHook("/_/");
2023-08-26 06:31:51 +00:00
const serverSystem = new ServerSystem(
new AssetBundlePlugSpacePrimitives(
new DiskSpacePrimitives(spacePath),
builtinAssetBundle,
),
dbBackend,
determineShellBackend(spacePath),
2023-08-26 06:31:51 +00:00
);
2023-11-02 11:46:33 +00:00
await serverSystem.init(true);
app.use((context, next) => {
return endpointHook.handleRequest(serverSystem.system!, context, next);
});
2023-08-11 18:37:13 +00:00
app.listen({
hostname: httpHostname,
port: httpServerPort,
signal: serverController.signal,
});
if (functionName) {
const [plugName, funcName] = functionName.split(".");
2023-08-04 16:56:55 +00:00
2023-08-26 06:31:51 +00:00
const plug = serverSystem.system.loadedPlugs.get(plugName);
2023-08-11 18:37:13 +00:00
if (!plug) {
throw new Error(`Plug ${plugName} not found`);
}
const result = await plug.invoke(funcName, args);
2023-08-26 06:31:51 +00:00
await serverSystem.close();
serverSystem.kvPrimitives.close();
2023-08-11 18:37:13 +00:00
serverController.abort();
return result;
} else {
console.log("Running in server mode, use Ctrl-c to stop");
while (true) {
await sleep(1000);
}
2023-08-04 16:56:55 +00:00
}
}