import Fastify from "fastify";
import { promiseVoid } from "../../../shared/src/resolved-promises.js";
import { HeartbeatMonitor } from "./life-cycle.js";
import { RunningState } from "./running-state.js";
class HttpService {
  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);
  }
  // Life-cycle hooks for subclass implementations
  _onStart() {
  }
  _onStop() {
    return promiseVoid;
  }
  // start() is used in unit tests.
  // run() is the lifecycle method called by the ServiceRunner.
  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();
  }
}
export {
  HttpService
};
//# sourceMappingURL=http-service.js.map
