/**
* Content-Addressed Storage
*
* Stores content by SHA256 hash (like APDS)
*/
import { readFile, writeFile, mkdir } from 'fs/promises'
import { existsSync } from 'fs'
import { join } from 'path'
export class ContentStore {
constructor(storagePath) {
this.storagePath = storagePath
this.dbPath = join(storagePath, 'content.json')
this.db = new Map()
this.dirty = false
}
async init() {
await mkdir(this.storagePath, { recursive: true })
if (existsSync(this.dbPath)) {
const data = await readFile(this.dbPath, 'utf8')
const obj = JSON.parse(data)
this.db = new Map(Object.entries(obj))
console.log(`Loaded ${this.db.size} content entries`)
}
// Auto-save every 5 seconds if dirty
setInterval(async () => {
if (this.dirty) {
await this.save()
}
}, 5000)
}
async put(hash, content) {
this.db.set(hash, content)
this.dirty = true
}
get(hash) {
return this.db.get(hash)
}
has(hash) {
return this.db.has(hash)
}
async save() {
if (!this.dirty) return
const obj = Object.fromEntries(this.db)
await writeFile(this.dbPath, JSON.stringify(obj, null, 2))
this.dirty = false
}
async close() {
await this.save()
}
}