SPB Git

Repository Public

storage.ts 3.8 KB 79 lines typescript

1import { createReadStream, createWriteStream } from "node:fs";2import { mkdir, rename, rm, stat, statfs, copyFile } from "node:fs/promises";3import path from "node:path";4import type { Readable } from "node:stream";5import { pipeline } from "node:stream/promises";6import { env } from "@/lib/env";78/**9 * Private object storage of the library. Keys are opaque strings built by the server10 * ("originals/ab/<sha256>.flac"); nothing a client sends ever reaches a key or a path.11 */12export interface Storage {13  readonly driver: string;14  /** Moves a finished local file into storage (atomic on the local driver). */15  putFile(key: string, localPath: string): Promise<void>;16  put(key: string, data: Readable): Promise<void>;17  /** Byte range, both bounds inclusive. */18  read(key: string, range?: { start: number; end: number }): Readable;19  size(key: string): Promise<number | null>;20  delete(key: string): Promise<void>;21  /** A path ffmpeg/ffprobe can open. Local driver: the file itself. */22  localPath(key: string): Promise<string>;23  health(): Promise<{ ok: boolean; freeBytes: number | null; totalBytes: number | null; detail?: string }>;24}2526const KEY_RE = /^[a-z0-9]+(\/[A-Za-z0-9._-]+)+$/;2728class LocalStorage implements Storage {29  readonly driver = "local";30  constructor(private root: string) {}31  private resolve(key: string): string {32    if (!KEY_RE.test(key) || key.includes("..")) throw new Error("invalid storage key");33    const p = path.resolve(this.root, key);34    if (!p.startsWith(this.root + path.sep)) throw new Error("invalid storage key");35    return p;36  }37  async putFile(key: string, localPath: string) {38    const dest = this.resolve(key);39    await mkdir(path.dirname(dest), { recursive: true, mode: 0o700 });40    try { await rename(localPath, dest); }41    catch (e) { if ((e as NodeJS.ErrnoException).code !== "EXDEV") throw e; await copyFile(localPath, dest + ".part"); await rename(dest + ".part", dest); await rm(localPath, { force: true }); }42  }43  async put(key: string, data: Readable) {44    const dest = this.resolve(key);45    await mkdir(path.dirname(dest), { recursive: true, mode: 0o700 });46    await pipeline(data, createWriteStream(dest + ".part", { mode: 0o600 }));47    await rename(dest + ".part", dest);48  }49  read(key: string, range?: { start: number; end: number }) { return createReadStream(this.resolve(key), range); }50  async size(key: string) { try { return (await stat(this.resolve(key))).size; } catch { return null; } }51  async delete(key: string) { await rm(this.resolve(key), { force: true }); }52  async localPath(key: string) { return this.resolve(key); }53  async health() {54    try {55      await mkdir(this.root, { recursive: true, mode: 0o700 });56      const s = await statfs(this.root);57      return { ok: true, freeBytes: Number(s.bavail) * Number(s.bsize), totalBytes: Number(s.blocks) * Number(s.bsize) };58    } catch (e) { return { ok: false, freeBytes: null, totalBytes: null, detail: (e as NodeJS.ErrnoException).code ?? "error" }; }59  }60}6162let instance: Storage | null = null;63export function storage(): Storage {64  if (instance) return instance;65  const driver = env.storageDriver;66  if (driver === "local") return (instance = new LocalStorage(env.storageRoot));67  // The cluster uses a node volume. An S3-compatible driver plugs in here by implementing `Storage`68  // (see docs/ARCHITECTURE.md); it is deliberately not shipped untested.69  throw new Error(`STORAGE_DRIVER=${driver} is not implemented (available: local)`);70}7172export const keys = {73  original: (sha: string, ext: string) => `originals/${sha.slice(0, 2)}/${sha}.${ext}`,74  rendition: (trackId: string) => `renditions/${trackId.slice(0, 2)}/${trackId}.m4a`,75  artOriginal: (sha: string, ext: string) => `art/${sha.slice(0, 2)}/${sha}/orig.${ext}`,76  artThumb: (sha: string, size: number) => `art/${sha.slice(0, 2)}/${sha}/${size}.jpg`,77};78export const THUMB_SIZES = [96, 320, 640] as const;79
Files main
Menu

Theme