import "../../../../zero-protocol/src/protocol-version.js";
import "../../../../shared/src/dotenv.js";
import { childWorker } from "../../types/processes.js";
import { ProcessManager, runUntilKilled } from "../../services/life-cycle.js";
import { normalizeZeroConfig } from "../../config/normalize.js";
import { getServerVersion, getZeroConfig } from "../../config/zero-config.js";
import { createLogContext } from "../logging.js";
import { MAIN_URL } from "../worker-urls.js";
import { getTaskID } from "./runtime.js";
import { ZeroDispatcher } from "./zero-dispatcher.js";
import { resolver } from "@rocicorp/resolver";
//#region ../zero-cache/src/server/runner/run-worker.ts
/**
* Top-level `runner` entry point to the zero-cache. This layer is responsible for:
* * runtime-based config normalization
* * lazy startup
* * serving /statsz
* * auto-reset restarts (TODO)
*/
async function runWorker(parent, env) {
	const cfg = getZeroConfig({
		env,
		emitDeprecationWarnings: true
	});
	const lc = createLogContext(cfg, { worker: "runner" });
	const config = normalizeZeroConfig(lc, cfg, env, await getTaskID(lc));
	const processes = new ProcessManager(lc, parent ?? process);
	const { port, lazyStartup } = config;
	const serverVersion = getServerVersion(config);
	lc.info?.(`starting server${!serverVersion ? "" : `@${serverVersion}`} `, {
		protocolVersion: 50,
		taskID: config.taskID,
		app: config.app,
		shard: config.shard,
		port: config.port
	});
	let zeroCache;
	function startZeroCache() {
		if (zeroCache === void 0) {
			const startMs = performance.now();
			lc.info?.("starting zero-cache");
			const r = zeroCache = resolver();
			const w = childWorker(MAIN_URL, env).once("message", () => {
				r.resolve(w);
				lc.info?.(`zero-cache ready (${performance.now() - startMs} ms)`);
			}).once("error", r.reject);
			processes.addWorker(w, "user-facing", "zero-cache");
		}
		return zeroCache.promise;
	}
	if (!lazyStartup) startZeroCache();
	await processes.allWorkersReady();
	parent?.send(["ready", { ready: true }]);
	try {
		await runUntilKilled(lc, parent ?? process, new ZeroDispatcher(config, lc, { port }, startZeroCache));
	} catch (err) {
		processes.logErrorAndExit(err, "main");
	}
	await processes.done();
}
//#endregion
export { runWorker };

//# sourceMappingURL=run-worker.js.map