import fs from "node:fs"; import path from "node:path"; import { DatabaseSync } from "node:sqlite"; import { getDataConfig } from "../config/env.js"; import { VPS, vpsListSchema, vpsSchema } from "../types/vps.js"; /** * Storage-agnostic repository contract. */ export interface IVPSRepository { getAll(): VPS[]; getById(id: string): VPS | undefined; getByName(name: string): VPS | undefined; close?(): void; } interface VPSRow { id: string; name: string; provider: string; region: string; environment: string; cpu: number; ramGB: number; diskGB: number; ip: string | null; sshUser: string | null; sshPort: number | null; } const CORE_SEED_RECORDS: readonly VPS[] = [ { id: "vps-001", name: "shop-prod-01", provider: "Vultr", region: "Singapore", environment: "Production", cpu: 4, ramGB: 8, diskGB: 160, ip: "203.0.113.10", sshUser: "deploy", sshPort: 22, }, { id: "vps-002", name: "staging-01", provider: "DigitalOcean", region: "Singapore", environment: "Staging", cpu: 2, ramGB: 4, diskGB: 80, ip: "198.51.100.20", sshUser: "ubuntu", sshPort: 2222, }, { id: "vps-003", name: "db-prod-01", provider: "Vultr", region: "Singapore", environment: "Production", cpu: 4, ramGB: 16, diskGB: 320, ip: "192.0.2.30", }, ]; const PROVIDERS = ["Vultr", "DigitalOcean", "AWS", "Linode", "Hetzner"] as const; const REGIONS = ["Singapore", "Tokyo", "Frankfurt", "US-East"] as const; const ENVIRONMENTS = ["Production", "Staging", "Development"] as const; const DOC_PREFIXES = ["203.0.113", "198.51.100", "192.0.2"] as const; const CPU_TIERS = [2, 4, 8] as const; function buildGeneratedSeedRecords(totalTarget = 100): VPS[] { const records: VPS[] = [...CORE_SEED_RECORDS]; for (let i = records.length + 1; i <= totalTarget; i++) { const num = String(i).padStart(3, "0"); const env = ENVIRONMENTS[(i - 1) % ENVIRONMENTS.length]; const envShort = env === "Production" ? "prod" : env === "Staging" ? "stg" : "dev"; const provider = PROVIDERS[(i - 1) % PROVIDERS.length]; const region = REGIONS[(i - 1) % REGIONS.length]; const cpu = CPU_TIERS[(i - 1) % CPU_TIERS.length]; const ramGB = cpu * 2; const diskGB = cpu * 40; const ipPrefix = DOC_PREFIXES[(i - 1) % DOC_PREFIXES.length]; const lastOctet = ((i * 7) % 240) + 10; records.push({ id: `vps-${num}`, name: `app-${envShort}-${num}`, provider, region, environment: env, cpu, ramGB, diskGB, ip: `${ipPrefix}.${lastOctet}`, sshUser: env === "Production" ? "deploy" : "ubuntu", sshPort: env === "Staging" ? 2222 : 22, }); } return records; } export const SEED_VPS_RECORDS: readonly VPS[] = buildGeneratedSeedRecords(100); const SELECT_COLUMNS = ` id, name, provider, region, environment, cpu, ram_gb AS ramGB, disk_gb AS diskGB, ip, ssh_user AS sshUser, ssh_port AS sshPort `; function mapRowToVPS(row: VPSRow): VPS { const candidate = { id: row.id, name: row.name, provider: row.provider, region: row.region, environment: row.environment, cpu: row.cpu, ramGB: row.ramGB, diskGB: row.diskGB, ip: row.ip ?? undefined, sshUser: row.sshUser ?? undefined, sshPort: row.sshPort ?? undefined, }; return vpsSchema.parse(candidate); } export class VPSRepository implements IVPSRepository { private dbPath: string; private db: DatabaseSync | null = null; constructor(dbPath?: string) { const configuredPath = dbPath || getDataConfig().VPS_DB_PATH; this.dbPath = configuredPath === ":memory:" ? ":memory:" : path.resolve(process.cwd(), configuredPath); } /** * Opens the SQLite database connection and ensures the `vps` table exists. */ public init(): void { if (this.db) { return; } try { if (this.dbPath !== ":memory:") { fs.mkdirSync(path.dirname(this.dbPath), { recursive: true }); } this.db = new DatabaseSync(this.dbPath); this.db.exec(` PRAGMA foreign_keys = ON; ${this.dbPath !== ":memory:" ? "PRAGMA journal_mode = WAL;" : ""} CREATE TABLE IF NOT EXISTS vps ( id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE COLLATE NOCASE, provider TEXT NOT NULL, region TEXT NOT NULL, environment TEXT NOT NULL CHECK (environment IN ('Production', 'Staging', 'Development')), cpu INTEGER NOT NULL CHECK (cpu > 0), ram_gb REAL NOT NULL CHECK (ram_gb > 0), disk_gb REAL NOT NULL CHECK (disk_gb > 0), ip TEXT, ssh_user TEXT, ssh_port INTEGER CHECK (ssh_port IS NULL OR (ssh_port >= 1 AND ssh_port <= 65535)) ); `); } catch (err) { throw new Error(`Failed to initialize SQLite database: ${(err as Error).message}`); } } private getDb(): DatabaseSync { if (!this.db) { this.init(); } return this.db!; } /** * Inserts default workshop seed records if the `vps` table is currently empty. * Returns the number of inserted records. */ public seedIfEmpty(records: readonly VPS[] = SEED_VPS_RECORDS): number { const db = this.getDb(); const countRow = db.prepare("SELECT COUNT(*) AS count FROM vps").get() as { count: number }; if (countRow.count > 0) { return 0; } const insert = db.prepare(` INSERT INTO vps (id, name, provider, region, environment, cpu, ram_gb, disk_gb, ip, ssh_user, ssh_port) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `); for (const vps of records) { insert.run( vps.id, vps.name, vps.provider, vps.region, vps.environment, vps.cpu, vps.ramGB, vps.diskGB, vps.ip ?? null, vps.sshUser ?? null, vps.sshPort ?? null ); } return records.length; } /** * Returns all VPS records from SQLite. */ public getAll(): VPS[] { try { const db = this.getDb(); const rows = db.prepare(`SELECT ${SELECT_COLUMNS} FROM vps ORDER BY rowid ASC`).all() as unknown as VPSRow[]; const mapped = rows.map(mapRowToVPS); return vpsListSchema.parse(mapped); } catch (err) { throw new Error(`Failed to query VPS records: ${(err as Error).message}`); } } /** * Finds a VPS by exact ID. */ public getById(id: string): VPS | undefined { try { const db = this.getDb(); const row = db .prepare(`SELECT ${SELECT_COLUMNS} FROM vps WHERE id = ? LIMIT 1`) .get(id) as unknown as VPSRow | undefined; return row ? mapRowToVPS(row) : undefined; } catch (err) { throw new Error(`Failed to query VPS by ID: ${(err as Error).message}`); } } /** * Finds a VPS by name (case-insensitive). */ public getByName(name: string): VPS | undefined { const trimmed = name.trim(); if (!trimmed) { return undefined; } try { const db = this.getDb(); const row = db .prepare(`SELECT ${SELECT_COLUMNS} FROM vps WHERE LOWER(name) = LOWER(?) LIMIT 1`) .get(trimmed) as unknown as VPSRow | undefined; return row ? mapRowToVPS(row) : undefined; } catch (err) { throw new Error(`Failed to query VPS by name: ${(err as Error).message}`); } } /** * Closes the SQLite database connection. */ public close(): void { if (this.db) { this.db.close(); this.db = null; } } }