SPB Git

Repository Public

store.ts 9.6 KB 185 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Storage Node8 * File             : server/src/store.ts9 * Description      : Stable fragment store on the coordinator's disk and the10 *                    object layer (chunking, encryption, deduplication,11 *                    read-back).12 * Module           : server13 * Repository       : https://git.spboucher.ai/maclustr-storage-ios14 * Project Website  : https://storage.spboucher.ai15 * Created          : 2026-12-0116 * Last Modified    : 2026-12-0117 *18 * Author           : Simon-Pierre Boucher19 * Position         : Professor of Finance20 * Institution      : Université du Québec en Outaouais (UQO)21 * Organization     : SP Boucher22 * Website          : https://spboucher.ai23 * Git              : https://git.spboucher.ai24 *25 * Preferred Contact: admin@spboucher.ai26 * Technical Contact: dev@spboucher.ai27 * Security/Admin   : admin@spboucher.ai28 *29 * Copyright (c) 202630 * Simon-Pierre Boucher31 * All rights reserved where applicable. This file is governed by the32 * applicable project license, copyright notices and relevant law.33 * Existing third-party rights and notices remain unaffected.34 *35 * License          : None specified (no license file in this repository)36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445import { createHash } from "node:crypto";46import { existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, openSync, writeSync, fsyncSync, closeSync, statfsSync } from "node:fs";47import { join } from "node:path";48import type { Readable, Writable } from "node:stream";49import { config, type Secrets } from "./config.ts";50import { db, q, q1, run, tx, now, event } from "./db.ts";51import { decryptFragment, encryptChunk, randomId, sha256hex } from "./crypto.ts";5253export function fragmentPath(id: string): string { return join(config.fragmentDir, id.slice(0, 2), id.slice(2, 4), id); }5455export function stableExists(id: string, size?: number): boolean {56  try { const s = statSync(fragmentPath(id)); return size === undefined || s.size === size; } catch { return false; }57}5859// Atomic write: temporary file on the same volume, fsync, rename.60export function writeStable(id: string, data: Buffer) {61  const p = fragmentPath(id);62  mkdirSync(join(config.fragmentDir, id.slice(0, 2), id.slice(2, 4)), { recursive: true });63  const tmp = join(config.tmpDir, `${id}.${randomId(4)}`);64  const fd = openSync(tmp, "w", 0o600);65  try { writeSync(fd, data); fsyncSync(fd); } finally { closeSync(fd); }66  renameSync(tmp, p);67}6869export function readStable(id: string): Buffer { return readFileSync(fragmentPath(id)); }7071// Reads the stable copy and checks its SHA-256 against the fragment id. Records the outcome in the catalog.72export function readStableVerified(id: string): Buffer | null {73  let data: Buffer;74  try { data = readStable(id); } catch {75    markStable(id, "missing");76    return null;77  }78  if (sha256hex(data) !== id) { markStable(id, "corrupt"); return null; }79  run("UPDATE fragments SET stable_state='ok', stable_checked_at=? WHERE id=?", now(), id);80  return data;81}8283function markStable(id: string, state: "missing" | "corrupt") {84  const cur = q1<{ stable_state: string }>("SELECT stable_state FROM fragments WHERE id=?", id);85  if (cur && cur.stable_state !== state) event("stable.fragment." + state, null, { fragment: id });86  run("UPDATE fragments SET stable_state=?, stable_checked_at=? WHERE id=?", state, now(), id);87}8889// Restores a stable copy from bytes returned by a mobile node (already checked against the fragment id by the caller).90export function restoreStable(id: string, data: Buffer) {91  writeStable(id, data);92  run("UPDATE fragments SET stable_state='ok', stable_checked_at=? WHERE id=?", now(), id);93  event("stable.fragment.restored", null, { fragment: id, bytes: data.length });94}9596export type ObjectRow = { id: string; name: string; class: string; size: number; sha256: string; fragment_size: number; fragments: number; created_at: number };9798// Ingests a stream as one object: fixed-size chunks, each encrypted then written to the stable store before the99// catalog transaction commits. A crash before the commit leaves only unreferenced fragment files (swept later).100export async function ingestObject(secrets: Secrets, input: Readable, name: string, klass: string): Promise<ObjectRow & { new_fragments: number; deduplicated: number }> {101  const objectId = randomId(12);102  const whole = createHash("sha256");103  const parts: { id: string; plainSha: string; plainSize: number; size: number; isNew: boolean }[] = [];104  let size = 0;105  let pending: Buffer[] = [];106  let pendingLen = 0;107  const flush = (chunk: Buffer) => {108    const { fragment, id, plainSha } = encryptChunk(secrets.master, chunk);109    const known = q1("SELECT id FROM fragments WHERE id=?", id);110    const isNew = !known || !stableExists(id, fragment.length);111    if (isNew) writeStable(id, fragment);112    parts.push({ id, plainSha, plainSize: chunk.length, size: fragment.length, isNew: !known });113  };114  for await (const buf of input as AsyncIterable<Buffer>) {115    whole.update(buf); size += buf.length;116    pending.push(buf); pendingLen += buf.length;117    while (pendingLen >= config.fragmentSize) {118      const all = pending.length === 1 ? pending[0] : Buffer.concat(pending);119      flush(all.subarray(0, config.fragmentSize));120      const rest = all.subarray(config.fragmentSize);121      pending = rest.length ? [rest] : []; pendingLen = rest.length;122    }123  }124  if (pendingLen > 0) flush(pending.length === 1 ? pending[0] : Buffer.concat(pending));125  if (size === 0) throw Object.assign(new Error("empty object"), { status: 400 });126  const sha = whole.digest("hex");127  const t = now();128  tx(() => {129    run("INSERT INTO objects (id,name,class,size,sha256,fragment_size,fragments,created_at) VALUES (?,?,?,?,?,?,?,?)", objectId, name, klass, size, sha, config.fragmentSize, parts.length, t);130    parts.forEach((p, idx) => {131      run("INSERT INTO fragments (id,size,refs,created_at,stable_state,stable_checked_at) VALUES (?,?,1,?,'ok',?) ON CONFLICT(id) DO UPDATE SET refs=refs+1, stable_state='ok'", p.id, p.size, t, t);132      run("INSERT INTO object_fragments (object_id,idx,fragment_id,plain_sha256,plain_size) VALUES (?,?,?,?,?)", objectId, idx, p.id, p.plainSha, p.plainSize);133    });134  });135  const fresh = parts.filter(p => p.isNew).length;136  event("object.created", null, { object: objectId, name, size, fragments: parts.length, new_fragments: fresh });137  return { id: objectId, name, class: klass, size, sha256: sha, fragment_size: config.fragmentSize, fragments: parts.length, created_at: t, new_fragments: fresh, deduplicated: parts.length - fresh };138}139140// Streams an object back, verifying every fragment and the whole-object digest. Fails with the list of fragments whose141// stable copy is unusable; the coordinator then schedules their recovery from mobile nodes.142export async function readObject(secrets: Secrets, objectId: string, out: Writable): Promise<{ ok: boolean; missing: string[] }> {143  const obj = q1<ObjectRow>("SELECT * FROM objects WHERE id=?", objectId);144  if (!obj) throw Object.assign(new Error("object not found"), { status: 404 });145  const parts = q<{ fragment_id: string; plain_sha256: string }>("SELECT fragment_id, plain_sha256 FROM object_fragments WHERE object_id=? ORDER BY idx", objectId);146  const missing = parts.filter(p => !stableExists(p.fragment_id)).map(p => p.fragment_id);147  if (missing.length) { for (const id of missing) markStable(id, "missing"); return { ok: false, missing }; }148  const whole = createHash("sha256");149  for (const p of parts) {150    const data = readStableVerified(p.fragment_id);151    if (!data) return { ok: false, missing: [p.fragment_id] };152    const plain = decryptFragment(secrets.master, data, p.plain_sha256);153    whole.update(plain);154    if (!out.write(plain)) await new Promise<void>(r => out.once("drain", () => r()));155  }156  if (whole.digest("hex") !== obj.sha256) throw new Error("object digest mismatch");157  return { ok: true, missing: [] };158}159160// Deletes an object; fragments no longer referenced leave the stable store and are queued for deletion on mobile nodes.161export function deleteObject(objectId: string): { released: string[] } {162  const parts = q<{ fragment_id: string }>("SELECT fragment_id FROM object_fragments WHERE object_id=?", objectId);163  if (!q1("SELECT id FROM objects WHERE id=?", objectId)) throw Object.assign(new Error("object not found"), { status: 404 });164  const released: string[] = [];165  tx(() => {166    for (const p of parts) {167      run("UPDATE fragments SET refs=refs-1 WHERE id=?", p.fragment_id);168      const f = q1<{ refs: number }>("SELECT refs FROM fragments WHERE id=?", p.fragment_id);169      if (f && f.refs <= 0) released.push(p.fragment_id);170    }171    run("DELETE FROM objects WHERE id=?", objectId);172  });173  event("object.deleted", null, { object: objectId, released: released.length });174  return { released };175}176177export function dropStable(id: string) { try { unlinkSync(fragmentPath(id)); } catch { /* already gone */ } }178179export function diskFree(): { free: number; total: number } {180  const s = statfsSync(config.dataDir);181  return { free: Number(s.bavail) * Number(s.bsize), total: Number(s.blocks) * Number(s.bsize) };182}183184export { db, existsSync };185
Files main
Menu

Theme