passwords_backupper: ежедневная зашифрованная (7z + age) копия Vaultwarden и Infisical на Google Drive, аварийные md, scheduler, deploy
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
50
packages/passwords_backupper/src/retention.ts
Normal file
50
packages/passwords_backupper/src/retention.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
/** Имя архива: passwords-YYYYMMDDTHHMMSSZ.7z.age (время UTC). */
|
||||
export const ARCHIVE_RE = /^passwords-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z\.7z\.age$/;
|
||||
|
||||
export const archiveName = (d: Date): string => `passwords-${d.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}.7z.age`;
|
||||
|
||||
export function parseArchiveTime(name: string): Date | null {
|
||||
const m = ARCHIVE_RE.exec(name);
|
||||
if (!m) return null;
|
||||
return new Date(Date.UTC(+m[1]!, +m[2]! - 1, +m[3]!, +m[4]!, +m[5]!, +m[6]!));
|
||||
}
|
||||
|
||||
export interface RetentionPolicy { daily: number; weekly: number; monthly: number }
|
||||
export interface DriveEntry { id: string; name: string }
|
||||
|
||||
const dayKey = (d: Date) => d.toISOString().slice(0, 10);
|
||||
const monthKey = (d: Date) => d.toISOString().slice(0, 7);
|
||||
function weekKey(d: Date): string {
|
||||
// ISO-неделя (понедельник - начало, неделя принадлежит году своего четверга)
|
||||
const t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
||||
t.setUTCDate(t.getUTCDate() + 4 - (t.getUTCDay() || 7));
|
||||
const yearStart = Date.UTC(t.getUTCFullYear(), 0, 1);
|
||||
const week = Math.ceil(((t.getTime() - yearStart) / 86_400_000 + 1) / 7);
|
||||
return `${t.getUTCFullYear()}-W${String(week).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Какие архивы удалить: оставляем последний архив каждого из `daily` последних дней, каждой из `weekly` последних недель и каждого из `monthly`
|
||||
* последних месяцев (среди дней/недель/месяцев, в которых архивы есть). Файлы, чьё имя не похоже на архив, не трогаем.
|
||||
*/
|
||||
export function selectForDeletion(entries: DriveEntry[], policy: RetentionPolicy): DriveEntry[] {
|
||||
const archives = entries
|
||||
.map((e) => ({ e, t: parseArchiveTime(e.name) }))
|
||||
.filter((x): x is { e: DriveEntry; t: Date } => x.t !== null)
|
||||
.sort((a, b) => b.t.getTime() - a.t.getTime()); // новые первыми
|
||||
const keep = new Set<string>();
|
||||
const pick = (key: (d: Date) => string, limit: number) => {
|
||||
const seen = new Set<string>();
|
||||
for (const { e, t } of archives) {
|
||||
const k = key(t);
|
||||
if (seen.has(k)) continue;
|
||||
if (seen.size >= limit) break;
|
||||
seen.add(k);
|
||||
keep.add(e.id);
|
||||
}
|
||||
};
|
||||
pick(dayKey, policy.daily);
|
||||
pick(weekKey, policy.weekly);
|
||||
pick(monthKey, policy.monthly);
|
||||
return archives.filter(({ e }) => !keep.has(e.id)).map(({ e }) => e);
|
||||
}
|
||||
Reference in New Issue
Block a user