diff --git a/storage.js b/storage.js new file mode 100644 index 0000000..7f604bb --- /dev/null +++ b/storage.js @@ -0,0 +1,96 @@ +// 存檔的共同介面:把「檔名 → 文字內容」存起來,背後可以是資料夾裡的檔案或 SQLite。 +// read(name) → 文字,沒有這一筆就回 null +// write(name, text, { exclusive }) → 寫入;exclusive 時已存在會丟 code 'EEXIST' +// list(prefix) → 以 prefix 開頭的名稱(例如 'archives/') +// 全部同步(node:sqlite 本來就是同步的);呼叫端各自負責排隊,不會同時寫。 +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs'; +import { basename, dirname, resolve } from 'node:path'; + +export const sha256 = (text) => createHash('sha256').update(text, 'utf8').digest('hex'); + +function exists(name) { + const error = new Error(`${name} already exists`); + error.code = 'EEXIST'; + return error; +} + +// 檔案版:一個名稱就是 dir 底下的一個 .json 檔,先寫暫存檔再改名,權限 600。 +export function fileStorage(dir) { + const locate = (name) => resolve(dir, name); + return { + kind: 'file', + read(name) { + try { return readFileSync(locate(name), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } + }, + write(name, text, { exclusive = false } = {}) { + const file = locate(name); + if (exclusive && existsSync(file)) throw exists(name); + mkdirSync(dirname(file), { recursive: true }); + const temporary = `${file}.${process.pid}.tmp`; + writeFileSync(temporary, text, { mode: 0o600 }); + renameSync(temporary, file); + }, + list(prefix = '') { + try { + return readdirSync(locate(prefix), { withFileTypes: true }).filter(entry => entry.isFile()).map(entry => `${prefix}${entry.name}`).sort(); + } catch (error) { if (error.code === 'ENOENT') return []; throw error; } + }, + }; +} + +// SQLite 版:documents 表,一個名稱一列,內容原樣存成文字。db 是 node:sqlite 的 DatabaseSync。 +export function sqliteStorage(db, { now = () => new Date().toISOString() } = {}) { + const select = db.prepare('SELECT body FROM documents WHERE name = ?'); + const insert = db.prepare('INSERT INTO documents (name, body, sha256, bytes, updated_at) VALUES (?, ?, ?, ?, ?)'); + const upsert = db.prepare(`INSERT INTO documents (name, body, sha256, bytes, updated_at) VALUES (?, ?, ?, ?, ?) + ON CONFLICT(name) DO UPDATE SET body = excluded.body, sha256 = excluded.sha256, bytes = excluded.bytes, updated_at = excluded.updated_at`); + const names = db.prepare('SELECT name FROM documents WHERE substr(name, 1, length(?)) = ? ORDER BY name'); + return { + kind: 'sqlite', + db, + read(name) { + const row = select.get(name); + return row ? row.body : null; + }, + write(name, text, { exclusive = false } = {}) { + const values = [name, text, sha256(text), Buffer.byteLength(text, 'utf8'), now()]; + if (!exclusive) { upsert.run(...values); return; } + try { insert.run(...values); } catch (error) { + if (/UNIQUE|PRIMARY KEY/i.test(String(error?.message))) throw exists(name); + throw error; + } + }, + list(prefix = '') { return names.all(prefix, prefix).map(row => row.name); }, + }; +} + +// 單一檔案的把手:{ read(), write(text) }。傳字串路徑=檔案版(測試與本機預覽用);傳把手就直接用。 +export function bindFile(source) { + if (!source) return null; + if (typeof source !== 'string') return source; + const storage = fileStorage(dirname(source)); + const name = basename(source); + return { read: () => storage.read(name), write: (text) => storage.write(name, text) }; +} + +export const bind = (storage, name) => ({ read: () => storage.read(name), write: (text) => storage.write(name, text) }); + +// 把一組名稱放在同一個前綴下(archives/2027.json 對外只叫 2027.json)。 +export const prefixed = (storage, prefix) => ({ + read: (name) => storage.read(`${prefix}${name}`), + write: (name, text, options) => storage.write(`${prefix}${name}`, text, options), + list: () => storage.list(prefix).map(name => name.slice(prefix.length)), +}); + +// 資料夾路徑 → 同樣介面(封存用):名稱就是資料夾裡的檔名。傳物件就直接用。 +export function bindDirectory(source) { + if (!source) return null; + if (typeof source !== 'string') return source; + const storage = fileStorage(source); + return { + read: (name) => storage.read(name), + write: (name, text, options) => storage.write(name, text, options), + list: () => storage.list('').map(name => name), + }; +}