import { setActiveUsersGetter } from "../../server/anonymous-otel-start.js";
import { cvrSchema } from "../../types/shards.js";
import { RunningState } from "../running-state.js";
const MINUTE = 60 * 1000;
const DAY = 24 * 60 * MINUTE;
export class ActiveUsersGauge {
    id = 'active-users-gauge';
    #lc;
    #db;
    #schema;
    #updateIntervalMs;
    #state = new RunningState('active-users-gauge');
    // latest computed value exposed via the observable gauge callback
    #value = 0;
    #getterSet = false;
    constructor(lc, db, shard, opts = {}) {
        this.#lc = lc;
        this.#db = db;
        this.#schema = cvrSchema(shard);
        this.#updateIntervalMs = opts.updateIntervalMs ?? 60 * 1000; // default 1 minute
    }
    async run() {
        while (this.#state.shouldRun()) {
            try {
                const since = Date.now() - DAY;
                const [{ cnt }] = await this.#db `
          SELECT COUNT(*) AS cnt
          FROM ${this.#db(this.#schema)}.instances
          WHERE "lastActive" > ${since}
        `;
                this.#value = Number(cnt);
                // Set the getter after the first value is computed
                if (!this.#getterSet) {
                    setActiveUsersGetter(() => this.#value);
                    this.#getterSet = true;
                }
                this.#lc.debug?.(`updated active-users gauge to ${this.#value}`);
            }
            catch (e) {
                this.#lc.warn?.('error updating active-users gauge', e);
            }
            await this.#state.sleep(this.#updateIntervalMs);
        }
    }
    stop() {
        this.#state.stop(this.#lc);
        return this.#state.stopped();
    }
}
//# sourceMappingURL=active-users-gauge.js.map