main.ts

2.3 KB · raw

1import { join } from "node:path";2import type { Hono } from "hono";3import { createSetupApp } from "./admin/setup.ts";4import { startStorageLoop } from "./admin/storage.ts";5import { openBucket } from "./bucket/reader.ts";6import { startSyncWorker } from "./bucket/sync.ts";7import { openMirrors } from "./mirror/store.ts";8import { createApp } from "./server/app.ts";9import { startBackupLoop } from "./server/backup.ts";10import { CONFIG_FILE, type Config, ConfigError, loadConfig } from "./server/config.ts";11import { oneTimeCode } from "./server/connect.ts";12import { openKeprDb } from "./server/db.ts";13import { startMailLoop } from "./server/mail.ts";1415// Where a first-run setup puts Kepr's data, beside kepr.toml.16const DATA_DIR = "data";1718/** Starts the loops for a config and returns the app that serves it. */19function start(config: Config): Hono["fetch"] {20	const kepr = openKeprDb(config.dataDir);21	// One bucket for the sync loop and the app, so settings saved in the console reach both.22	const bucket = openBucket(config.bucket);23	startMailLoop(kepr, config);24	const mirrorDir = join(config.dataDir, "mirror");25	openMirrors(mirrorDir);26	// The first visitor after a new save would otherwise wait a second or two on a big repo.27	const syncer = startSyncWorker(config.dataDir, config.bucket);28	// A backup vacuums and copies on the sync's thread, so it never stalls a request.29	startBackupLoop(kepr, config, () => syncer.backup(config.dataDir, "due"));30	startStorageLoop({ bucket, kepr, mirrorDir });31	return createApp(config, kepr, bucket, CONFIG_FILE, syncer).fetch;32}3334try {35	let fetch: Hono["fetch"];36	if (await Bun.file(CONFIG_FILE).exists()) {37		fetch = start(await loadConfig(CONFIG_FILE));38	} else {39		const code = oneTimeCode();40		fetch = createSetupApp({41			code,42			configPath: CONFIG_FILE,43			dataDir: DATA_DIR,44			done: (config) => {45				fetch = start(config);46			},47		}).fetch;48		console.log(49			`kepr: no ${CONFIG_FILE} yet. Open /setup in a browser and enter the code ${code.slice(0, 4)}-${code.slice(4)}`,50		);51	}52	// Bun.serve reads the port from $PORT (default 3000).53	const server = Bun.serve({ fetch: (request, bun) => fetch(request, bun) });54	console.log(`kepr listening on ${server.url}`);55} catch (error) {56	if (!(error instanceof ConfigError)) throw error;57	console.error(`kepr: ${error.message}`);58	process.exit(1);59}