import { promiseVoid } from "../../../shared/src/resolved-promises.js";
import { RunningState } from "./running-state.js";
import { HeartbeatMonitor } from "./life-cycle.js";
import Fastify from "fastify";
//#region ../zero-cache/src/services/http-service.ts
/**
* Common functionality for all HttpServices. These include:
* * Responding to health checks at "/"
* * Tracking optional heartbeats at "/keepalive" and draining when they stop.
*/
var HttpService = class {
	id;
	_lc;
	#fastify;
	#port;
	_state;
	#heartbeatMonitor;
	#init;
	constructor(id, lc, opts, init) {
		this.id = id;
		this._lc = lc.withContext("component", this.id);
		this.#fastify = Fastify();
		this.#port = opts.port;
		this.#init = init;
		this._state = new RunningState(id);
		this.#heartbeatMonitor = new HeartbeatMonitor(this._lc);
	}
	_onStart() {}
	_onStop() {
		return promiseVoid;
	}
	async start() {
		this.#fastify.get("/", (_req, res) => res.send("OK"));
		this.#fastify.get("/keepalive", ({ headers }, res) => {
			this.#heartbeatMonitor.onHeartbeat(headers);
			return res.send("OK");
		});
		await this.#init(this.#fastify);
		const address = await this.#fastify.listen({
			host: "::",
			port: this.#port
		});
		this._lc.info?.(`${this.id} listening at ${address}`);
		this._onStart();
		return address;
	}
	async run() {
		await this.start();
		await this._state.stopped();
	}
	async stop() {
		this._lc.info?.(`${this.id}: no longer accepting connections`);
		this.#heartbeatMonitor.stop();
		this._state.stop(this._lc);
		await this.#fastify.close();
		await this._onStop();
	}
};
//#endregion
export { HttpService };

//# sourceMappingURL=http-service.js.map