var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import DatabaseService from "./DatabaseService";
import DockerHostLabelRuleEngineService from "./DockerHostLabelRuleEngineService";
import DockerHostOwnerRuleEngineService from "./DockerHostOwnerRuleEngineService";
import Model from "../../Models/DatabaseModels/DockerHost";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import ObjectID from "../../Types/ObjectID";
import QueryHelper from "../Types/Database/QueryHelper";
import OneUptimeDate from "../../Types/Date";
import LIMIT_MAX from "../../Types/Database/LimitMax";
import GlobalCache from "../Infrastructure/GlobalCache";
import logger from "../Utils/Logger";
import crypto from "crypto";
const LAST_SEEN_CACHE_NAMESPACE = "docker-host-last-seen";
const LAST_SEEN_THROTTLE_SECONDS = 60;
const LABELS_APPLIED_CACHE_NAMESPACE = "docker-host-labels-applied";
const LABELS_APPLIED_CACHE_TTL_SECONDS = 60;
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onCreateSuccess(_onCreate, createdItem) {
        if (createdItem.projectId && createdItem.id) {
            Promise.resolve()
                .then(async () => {
                await DockerHostLabelRuleEngineService.applyRulesToDockerHost(createdItem);
            })
                .then(async () => {
                await DockerHostOwnerRuleEngineService.applyRulesToDockerHost(createdItem);
            })
                .catch((error) => {
                var _a, _b;
                logger.error(`Error applying docker host rules in DockerHostService.onCreateSuccess: ${error}`, {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    dockerHostId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
            });
        }
        return createdItem;
    }
    async findOrCreateByHostIdentifier(data) {
        /*
         * Canonicalize + look up case-insensitively. A Docker host is keyed by
         * the OTel `host.name` resource attribute (see autoDiscoverDockerHost),
         * whose casing is not stable — Windows surfaces PRIMARY01 vs primary01
         * across resource detectors. Ingest already canonicalizes host.name
         * (OtelIngestBaseService.normalizeHostNameAttributesInPlace); we repeat
         * it here so the method is correct for any caller. A case-sensitive
         * lookup would miss an existing row, then fail to create it because the
         * unique guard (checkUniqueColumnBy -> findWithSameText) compares
         * case-insensitively, wedging ingest for that host. Mirrors HostService.
         */
        const hostIdentifier = data.hostIdentifier.trim().toLowerCase();
        const existingHost = await this.findOneBy({
            query: {
                projectId: data.projectId,
                hostIdentifier: QueryHelper.findWithSameText(hostIdentifier),
            },
            select: {
                _id: true,
                projectId: true,
                hostIdentifier: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (existingHost) {
            /*
             * Converge a legacy mixed-case identifier onto the canonical form so
             * the stored resource.host.name (canonicalized at ingest) keeps
             * matching the Docker-host detail page filter. Best-effort — never
             * block ingest on it. Updates don't re-run the unique guard.
             */
            if (existingHost._id &&
                existingHost.hostIdentifier &&
                existingHost.hostIdentifier !== hostIdentifier) {
                try {
                    await this.updateOneById({
                        id: new ObjectID(existingHost._id.toString()),
                        data: {
                            hostIdentifier: hostIdentifier,
                        },
                        props: {
                            isRoot: true,
                        },
                    });
                    existingHost.hostIdentifier = hostIdentifier;
                }
                catch (err) {
                    logger.warn(`DockerHostService: failed to canonicalize hostIdentifier for host ${existingHost._id.toString()}: ${err instanceof Error ? err.message : String(err)}`);
                }
            }
            return existingHost;
        }
        try {
            // Create new host
            const newHost = new Model();
            newHost.projectId = data.projectId;
            newHost.name = hostIdentifier;
            newHost.hostIdentifier = hostIdentifier;
            newHost.otelCollectorStatus = "connected";
            newHost.lastSeenAt = OneUptimeDate.getCurrentDate();
            const createdHost = await this.create({
                data: newHost,
                props: {
                    isRoot: true,
                },
            });
            return createdHost;
        }
        catch (_a) {
            /*
             * Either two ingest workers raced to create the same host, or a host
             * with this identifier in a different case already existed and the
             * unique guard rejected the insert. Re-resolve case-insensitively so
             * the caller still gets the existing row instead of throwing.
             */
            const reFetchedHost = await this.findOneBy({
                query: {
                    projectId: data.projectId,
                    hostIdentifier: QueryHelper.findWithSameText(hostIdentifier),
                },
                select: {
                    _id: true,
                    projectId: true,
                    hostIdentifier: true,
                },
                props: {
                    isRoot: true,
                },
            });
            if (reFetchedHost) {
                return reFetchedHost;
            }
            throw new Error("Failed to create or find Docker host: " + hostIdentifier);
        }
    }
    async updateLastSeen(hostId, extra) {
        var _a, _b, _c;
        const cacheKey = hostId.toString();
        const extrasFingerprint = crypto
            .createHash("sha1")
            .update(JSON.stringify({
            osType: (_a = extra === null || extra === void 0 ? void 0 : extra.osType) !== null && _a !== void 0 ? _a : null,
            osVersion: (_b = extra === null || extra === void 0 ? void 0 : extra.osVersion) !== null && _b !== void 0 ? _b : null,
            agentVersion: (_c = extra === null || extra === void 0 ? void 0 : extra.agentVersion) !== null && _c !== void 0 ? _c : null,
        }))
            .digest("hex");
        const cached = await GlobalCache.getString(LAST_SEEN_CACHE_NAMESPACE, cacheKey);
        if (cached === extrasFingerprint) {
            return; // same data was written recently
        }
        await GlobalCache.setString(LAST_SEEN_CACHE_NAMESPACE, cacheKey, extrasFingerprint, { expiresInSeconds: LAST_SEEN_THROTTLE_SECONDS });
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const data = {
            lastSeenAt: OneUptimeDate.getCurrentDate(),
            otelCollectorStatus: "connected",
        };
        if (extra === null || extra === void 0 ? void 0 : extra.osType) {
            data.osType = extra.osType;
        }
        if (extra === null || extra === void 0 ? void 0 : extra.osVersion) {
            data.osVersion = extra.osVersion;
        }
        if (extra === null || extra === void 0 ? void 0 : extra.agentVersion) {
            data.agentVersion = extra.agentVersion;
        }
        await this.updateOneById({
            id: hostId,
            data: data,
            props: {
                isRoot: true,
            },
        });
    }
    /**
     * Additively attach labels to a Docker host. Existing labels are
     * never removed — manual labels set via the UI survive ingest. The
     * set of labelIds passed in is fingerprinted and cached for 60s so
     * the common case (steady-state collector pushing the same label
     * set every batch) costs one in-memory lookup, not a join-table
     * scan.
     */
    async attachLabels(data) {
        var _a;
        if (!data.labelIds || data.labelIds.length === 0) {
            return;
        }
        const cacheKey = data.dockerHostId.toString();
        const fingerprint = fingerprintLabelIds(data.labelIds);
        const cached = await GlobalCache.getString(LABELS_APPLIED_CACHE_NAMESPACE, cacheKey);
        if (cached === fingerprint) {
            return;
        }
        try {
            const dockerHostIdStr = data.dockerHostId.toString();
            const existingLabels = await this.getRepository()
                .createQueryBuilder()
                .relation(Model, "labels")
                .of(dockerHostIdStr)
                .loadMany();
            const existingIds = new Set();
            for (const lbl of existingLabels) {
                const idStr = (_a = lbl._id) === null || _a === void 0 ? void 0 : _a.toString();
                if (idStr) {
                    existingIds.add(idStr);
                }
            }
            const toAddIds = [];
            const seen = new Set();
            for (const id of data.labelIds) {
                const idStr = id.toString();
                if (existingIds.has(idStr) || seen.has(idStr)) {
                    continue;
                }
                seen.add(idStr);
                toAddIds.push(idStr);
            }
            if (toAddIds.length > 0) {
                await this.getRepository()
                    .createQueryBuilder()
                    .relation(Model, "labels")
                    .of(dockerHostIdStr)
                    .add(toAddIds);
            }
            await GlobalCache.setString(LABELS_APPLIED_CACHE_NAMESPACE, cacheKey, fingerprint, { expiresInSeconds: LABELS_APPLIED_CACHE_TTL_SECONDS });
        }
        catch (err) {
            logger.warn(`DockerHostService.attachLabels failed for docker host ${data.dockerHostId.toString()}: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    async markDisconnectedHosts() {
        const fiveMinutesAgo = OneUptimeDate.addRemoveMinutes(OneUptimeDate.getCurrentDate(), -5);
        const connectedHosts = await this.findBy({
            query: {
                otelCollectorStatus: "connected",
                lastSeenAt: QueryHelper.lessThan(fiveMinutesAgo),
            },
            select: {
                _id: true,
            },
            limit: LIMIT_MAX,
            skip: 0,
            props: {
                isRoot: true,
            },
        });
        for (const host of connectedHosts) {
            if (host._id) {
                await this.updateOneById({
                    id: new ObjectID(host._id.toString()),
                    data: {
                        otelCollectorStatus: "disconnected",
                    },
                    props: {
                        isRoot: true,
                    },
                });
            }
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Model]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onCreateSuccess", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "findOrCreateByHostIdentifier", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID, Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "updateLastSeen", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "attachLabels", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], Service.prototype, "markDisconnectedHosts", null);
function fingerprintLabelIds(labelIds) {
    const sorted = labelIds
        .map((id) => {
        return id.toString();
    })
        .sort();
    return crypto.createHash("sha1").update(sorted.join(",")).digest("hex");
}
export default new Service();
//# sourceMappingURL=DockerHostService.js.map