1import { existsSync, renameSync } from "node:fs";2import { join } from "node:path";3import { type Bucket, inTurn, KEPR_PREFIX } from "../bucket/reader.ts";4import type { SyncTarget } from "../bucket/sync.ts";5import { closeMirror } from "../mirror/store.ts";6import { keepState, setting } from "../server/db.ts";7import { RESERVED_NAMES } from "../server/reserved.ts";8import { dropTarballs } from "../tarball/cache.ts";9import type { AdminContext } from "./console.ts";10import { findRepo, moveRepoRows } from "./store.ts";111213const NEW_NAME = /^[a-z0-9_-][a-z0-9._-]{0,99}$/;1415const IMMUTABLE = /^[^/]+\/(objects|saves|events)\//;1617const AT_ONCE = 8;181920export const renames = new Map<string, string>();21export const renameErrors = new Map<string, string>();222324export async function renameProblem(25 ctx: AdminContext,26 from: string,27 to: string,28): Promise<string | null> {29 if (!NEW_NAME.test(to)) return "a new name is lowercase letters, digits, '.', '_' and '-'.";30 if (RESERVED_NAMES.has(to)) return `"${to}" is one of Kepr's own addresses.`;31 if (renames.has(from)) return `it is already being renamed to ${renames.get(from)}.`;32 33 if ((setting(ctx.kepr, "rename_pending") ?? "").startsWith(`${from}\n${to}\n`)) return null;34 if (findRepo(ctx.kepr, to) || (await ctx.sync.bucket.list(`${to}/`)).length > 0) {35 return `"${to}" is taken.`;36 }37 return null;38}394041424344454647export function renameRepo(ctx: AdminContext, from: string, to: string): void {48 renames.set(from, to);49 renameErrors.delete(from);50 ctx.syncer51 .hold(() => move(ctx.sync, from, to))52 .catch((error) => renameErrors.set(from, error instanceof Error ? error.message : `${error}`))53 .finally(() => renames.delete(from));54}5556async function move({ bucket, kepr, mirrorDir }: SyncTarget, from: string, to: string) {57 58 const [savedFrom, savedTo, savedHead] = (setting(kepr, "rename_pending") ?? "").split("\n");59 let moved = savedFrom === from && savedTo === to && savedHead === "1";60 keepState(kepr, "rename_pending", `${from}\n${to}\n${moved ? "1" : "0"}`);61 const copied = new Set<string>();62 let head: string | null = null;63 for (let pass = 0; ; pass++) {64 const now = await text(bucket, `${from}/head`);65 66 if (now === null && !moved) throw new Error(`${from} has no head in the bucket.`);67 if (now === null) break;68 if (now === head) break;69 if (pass === 5) throw new Error(`${from} kept moving while it was copied; try again.`);70 const keys = (await bucket.list(`${from}/`)).filter(71 (key) => key !== `${from}/head` && !(IMMUTABLE.test(key) && copied.has(key)),72 );73 await inTurn(keys, AT_ONCE, (key) => bucket.copy(key, `${to}/${key.slice(from.length + 1)}`));74 for (const key of keys) copied.add(key);75 await bucket.copy(`${from}/head`, `${to}/head`);76 moved = true;77 keepState(kepr, "rename_pending", `${from}\n${to}\n${moved ? "1" : "0"}`);78 head = now;79 }80 await bucket.put(81 `${KEPR_PREFIX}renamed/${from}`,82 new TextEncoder().encode(`${to}\n`),83 "text/plain",84 );85 const hidden = await bucket.get(`${KEPR_PREFIX}hidden/${from}`);86 if (hidden) {87 await bucket.put(`${KEPR_PREFIX}hidden/${to}`, hidden, "text/plain");88 await bucket.remove(`${KEPR_PREFIX}hidden/${from}`);89 }90 await dropTarballs(bucket, from);91 moveRepoRows(kepr, from, to);92 closeMirror(mirrorDir, from);93 for (const suffix of ["", "-wal", "-shm"]) {94 const path = join(mirrorDir, `${from}.db${suffix}`);95 if (existsSync(path)) renameSync(path, join(mirrorDir, `${to}.db${suffix}`));96 }97 await inTurn(await bucket.list(`${from}/`), AT_ONCE, (key) => bucket.removeRenamed(key));98 keepState(kepr, "rename_pending", null);99}100101async function text(bucket: Bucket, key: string): Promise<string | null> {102 const bytes = await bucket.get(key);103 return bytes && new TextDecoder().decode(bytes).trim();104}