Files
khb_microservices/packages/passwords_backupper/src/service.test.ts
2026-10-22 20:46:23 +03:00

92 lines
4.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describe, expect, it } from "vitest";
import { buildApi } from "./http-api.js";
import type { BackupResult } from "./pipeline.js";
import { BackupService } from "./service.js";
const ok = (at: string, warnings: string[] = []): BackupResult => ({ ok: true, startedAt: at, finishedAt: at, archiveName: "passwords-x.7z.age", warnings, notes: [], trashedOld: 0 });
describe("BackupService", () => {
it("один запуск одновременно; после завершения состояние и итог сохраняются", async () => {
let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
const messages: string[] = [];
const s = new BackupService({ maxAgeHours: 26, notify: async (t) => void messages.push(t), run: async () => (await gate, ok("2026-10-22T03:30:00Z")) });
const first = s.start("schedule")!;
expect(first).not.toBeNull();
expect(s.isRunning()).toBe(true);
expect(s.start("manual")).toBeNull(); // второй одновременный запуск отклоняется
release();
await first.done;
expect(s.isRunning()).toBe(false);
expect(s.status().lastSuccessAt).toBe("2026-10-22T03:30:00.000Z");
expect(messages).toEqual([]); // успех без замечаний - тишина
});
it("сбой и замечания уходят в уведомление ИТ", async () => {
const messages: string[] = [];
let n = 0;
const s = new BackupService({
maxAgeHours: 26,
notify: async (t) => void messages.push(t),
run: async () => {
n++;
if (n === 1) return { ...ok("t"), ok: false, error: "pg_dump: код 1" };
if (n === 2) return ok("2026-10-22T03:30:00Z", ["Infisical: выгрузка секретов не удалась"]);
throw new Error("неожиданно");
},
});
await s.start("schedule")!.done;
await s.start("schedule")!.done;
await s.start("manual")!.done;
expect(messages[0]).toContain("НЕ сделана");
expect(messages[0]).toContain("pg_dump");
expect(messages[1]).toContain("с замечаниями");
expect(messages[1]).toContain("Infisical");
expect(messages[2]).toContain("НЕ сделана");
expect(messages[2]).toContain("неожиданно");
});
it("контроль свежести: тревога при отсутствии копии дольше срока, повтор не чаще раза в сутки, после успеха тишина", async () => {
let now = new Date("2026-10-22T00:00:00Z");
const messages: string[] = [];
const s = new BackupService({ maxAgeHours: 26, now: () => now, notify: async (t) => void messages.push(t), run: async () => ok(now.toISOString()) });
now = new Date("2026-10-22T20:00:00Z"); // 20 ч с запуска сервиса - ещё рано
expect(await s.checkFreshness()).toBe(false);
now = new Date("2026-10-23T03:00:00Z"); // 27 ч
expect(await s.checkFreshness()).toBe(true);
now = new Date("2026-10-23T09:00:00Z");
expect(await s.checkFreshness()).toBe(false); // повтор не чаще раза в 24 ч
now = new Date("2026-10-24T03:30:00Z");
expect(await s.checkFreshness()).toBe(true);
expect(messages).toHaveLength(2);
expect(messages[0]).toContain("успешных запусков с момента старта сервиса не было");
await s.start("manual")!.done; // успешная копия
now = new Date("2026-10-25T00:00:00Z");
expect(await s.checkFreshness()).toBe(false);
});
});
describe("http-api", () => {
it("токен обязателен (кроме /healthz); POST /runs стартует запуск, второй одновременно - 409; /status без секретов", async () => {
let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
const s = new BackupService({ maxAgeHours: 26, notify: async () => undefined, run: async () => (await gate, ok("2026-10-22T03:30:00Z")) });
const app = buildApi(s, "tok");
const h = { authorization: "Bearer tok" };
expect((await app.inject("/healthz")).statusCode).toBe(200);
expect((await app.inject("/status")).statusCode).toBe(401);
expect((await app.inject({ method: "POST", url: "/runs", headers: { authorization: "Bearer wrong" } })).statusCode).toBe(401);
const r1 = await app.inject({ method: "POST", url: "/runs", headers: h });
expect(r1.statusCode).toBe(202);
expect(r1.json().runId).toBeTruthy();
expect((await app.inject({ method: "POST", url: "/runs", headers: h })).statusCode).toBe(409);
expect((await app.inject({ url: "/status", headers: h })).json().running).not.toBeNull();
release();
await new Promise((r) => setTimeout(r, 20));
const st = (await app.inject({ url: "/status", headers: h })).json();
expect(st.running).toBeNull();
expect(st.last.result.ok).toBe(true);
await app.close();
});
});