SPB Git

Repository Public

db.ts 7.3 KB 136 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Storage Node8 * File             : server/src/db.ts9 * Description      : SQLite catalog (node:sqlite, WAL): devices, pairing codes,10 *                    objects, fragments, placements, tasks, telemetry.11 * Module           : server12 * Repository       : https://git.spboucher.ai/maclustr-storage-ios13 * Project Website  : https://storage.spboucher.ai14 * Created          : 2026-12-0115 * Last Modified    : 2026-12-0116 *17 * Author           : Simon-Pierre Boucher18 * Position         : Professor of Finance19 * Institution      : Université du Québec en Outaouais (UQO)20 * Organization     : SP Boucher21 * Website          : https://spboucher.ai22 * Git              : https://git.spboucher.ai23 *24 * Preferred Contact: admin@spboucher.ai25 * Technical Contact: dev@spboucher.ai26 * Security/Admin   : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * License          : None specified (no license file in this repository)35 *36 * Do not embed credentials, private keys, access tokens,37 * certificates or confidential personal information.38 *39 * =============================================================================40 * END OF SP BOUCHER SOURCE HEADER41 * =============================================================================42 */4344import { DatabaseSync } from "node:sqlite";45import { mkdirSync } from "node:fs";46import { config } from "./config.ts";4748mkdirSync(config.dataDir, { recursive: true });49export const db = new DatabaseSync(config.dbPath);50db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;");5152db.exec(`53CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);54CREATE TABLE IF NOT EXISTS devices (55  id TEXT PRIMARY KEY, name TEXT NOT NULL, model TEXT, os_version TEXT, app_version TEXT,56  pubkey TEXT NOT NULL,                       -- base64 X9.63 P-256 public key57  status TEXT NOT NULL,                       -- active | suspended | draining | drained | revoked | removed58  quota_bytes INTEGER NOT NULL DEFAULT 0,59  accepting INTEGER NOT NULL DEFAULT 0, accepting_reason TEXT,60  reported TEXT NOT NULL DEFAULT '{}',        -- last heartbeat body (device-reported facts)61  bench TEXT,                                 -- last on-device benchmark report62  paired_at INTEGER NOT NULL, last_seen INTEGER NOT NULL DEFAULT 0, last_ip TEXT, last_via TEXT,63  key_rotated_at INTEGER,64  rx_bytes INTEGER NOT NULL DEFAULT 0,        -- bytes sent to the device (measured by the coordinator)65  tx_bytes INTEGER NOT NULL DEFAULT 0,        -- bytes received from the device66  verify_ok INTEGER NOT NULL DEFAULT 0, verify_fail INTEGER NOT NULL DEFAULT 0,67  drain_mode TEXT, remove_after_drain INTEGER NOT NULL DEFAULT 0, drain_started_at INTEGER68);69CREATE TABLE IF NOT EXISTS pairing_codes (70  code_hash TEXT PRIMARY KEY, label TEXT, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL,71  used_at INTEGER, device_id TEXT, revoked_at INTEGER72);73CREATE TABLE IF NOT EXISTS objects (74  id TEXT PRIMARY KEY, name TEXT NOT NULL, class TEXT NOT NULL, size INTEGER NOT NULL, sha256 TEXT NOT NULL,75  fragment_size INTEGER NOT NULL, fragments INTEGER NOT NULL, created_at INTEGER NOT NULL76);77CREATE TABLE IF NOT EXISTS object_fragments (78  object_id TEXT NOT NULL REFERENCES objects(id) ON DELETE CASCADE, idx INTEGER NOT NULL,79  fragment_id TEXT NOT NULL, plain_sha256 TEXT NOT NULL, plain_size INTEGER NOT NULL,80  PRIMARY KEY (object_id, idx)81);82CREATE INDEX IF NOT EXISTS object_fragments_fragment ON object_fragments(fragment_id);83CREATE TABLE IF NOT EXISTS fragments (84  id TEXT PRIMARY KEY,                        -- SHA-256 of the encrypted fragment85  size INTEGER NOT NULL, refs INTEGER NOT NULL, created_at INTEGER NOT NULL,86  stable_state TEXT NOT NULL DEFAULT 'ok',    -- ok | missing | corrupt  (copy on the coordinator's stable store)87  stable_checked_at INTEGER NOT NULL DEFAULT 088);89CREATE TABLE IF NOT EXISTS placements (90  fragment_id TEXT NOT NULL, device_id TEXT NOT NULL, size INTEGER NOT NULL,91  state TEXT NOT NULL,                        -- assigned | stored | deleting92  assigned_at INTEGER NOT NULL, stored_at INTEGER, verified_at INTEGER,93  PRIMARY KEY (fragment_id, device_id)94);95CREATE INDEX IF NOT EXISTS placements_device ON placements(device_id, state);96CREATE TABLE IF NOT EXISTS tasks (97  id TEXT PRIMARY KEY, device_id TEXT NOT NULL, op TEXT NOT NULL,   -- store | retrieve | verify | delete98  fragment_id TEXT NOT NULL, size INTEGER NOT NULL, nonce TEXT,99  state TEXT NOT NULL,                        -- queued | leased | done | failed | cancelled100  lease_until INTEGER NOT NULL DEFAULT 0, attempts INTEGER NOT NULL DEFAULT 0,101  reason TEXT, error TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL102);103CREATE INDEX IF NOT EXISTS tasks_device ON tasks(device_id, state);104CREATE INDEX IF NOT EXISTS tasks_fragment ON tasks(fragment_id, state);105CREATE TABLE IF NOT EXISTS nonces (device_id TEXT NOT NULL, nonce TEXT NOT NULL, ts INTEGER NOT NULL, PRIMARY KEY (device_id, nonce));106CREATE TABLE IF NOT EXISTS presence (device_id TEXT NOT NULL, minute INTEGER NOT NULL, PRIMARY KEY (device_id, minute));107CREATE TABLE IF NOT EXISTS events (108  id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER NOT NULL, device_id TEXT, kind TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '{}'109);110CREATE INDEX IF NOT EXISTS events_device ON events(device_id, id);111CREATE TABLE IF NOT EXISTS transfers (112  id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER NOT NULL, device_id TEXT NOT NULL, fragment_id TEXT NOT NULL,113  direction TEXT NOT NULL,                    -- to_device | from_device114  bytes INTEGER NOT NULL, ms INTEGER NOT NULL, ok INTEGER NOT NULL, via TEXT NOT NULL, resumed_from INTEGER NOT NULL DEFAULT 0115);116CREATE INDEX IF NOT EXISTS transfers_device ON transfers(device_id, id);117`);118119export const now = () => Math.floor(Date.now() / 1000);120121export function q<T = any>(sql: string, ...args: any[]): T[] { return db.prepare(sql).all(...args) as T[]; }122export function q1<T = any>(sql: string, ...args: any[]): T | undefined { return db.prepare(sql).get(...args) as T | undefined; }123export function run(sql: string, ...args: any[]) { return db.prepare(sql).run(...args); }124125export function tx<T>(fn: () => T): T {126  db.exec("BEGIN IMMEDIATE");127  try { const r = fn(); db.exec("COMMIT"); return r; } catch (e) { db.exec("ROLLBACK"); throw e; }128}129130export function event(kind: string, deviceId: string | null, detail: Record<string, unknown> = {}) {131  run("INSERT INTO events (ts, device_id, kind, detail) VALUES (?,?,?,?)", now(), deviceId, kind, JSON.stringify(detail));132}133134export function getMeta(key: string): string | undefined { return q1<{ value: string }>("SELECT value FROM meta WHERE key=?", key)?.value; }135export function setMeta(key: string, value: string) { run("INSERT INTO meta (key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", key, value); }136
Files main
Menu

Theme