root / store.mjs
2868 bytes
// ANBot store interface and in-memory implementation.
//
// A store holds four kinds of durable state behind one small async
// interface: signed records keyed by record ID, AndFS blocks keyed by
// hash, signed social posts keyed by record ID, and the selected update.
// Every implementation provides:
//
// getRecord(id) -> Uint8Array | undefined
// putRecord(id, bytes) -> boolean, true when newly stored, never overwrites
// getBlock(hash, maxSize) -> Uint8Array | undefined, throws when the
// stored bytes exceed maxSize
// putBlock(hash, bytes) -> boolean, true when newly stored, never overwrites
// getPost(id) -> Uint8Array | undefined
// putPost(id, bytes) -> boolean, true when newly stored, never overwrites
// getSelection() -> object | undefined
// putSelection(selection) -> replaces the stored selection
//
// Record and post keys use core recordPath(id): the unpadded Base64url form
// Stores hold bytes only; verification stays in core.mjs and in callers.
// Puts are durable before they return, on each platform to the extent that
// platform allows. Selection writes are the commit point: callers verify
// records and blocks durably before changing the selection.
//
// This module uses only platform-free imports, so it runs unchanged in
// runtimes with WebCrypto, TextEncoder, and TextDecoder.
import { decodeHash, parseJson, recordPath, requireThat, utf8Encode } from './core.mjs'
const copy = bytes => new Uint8Array(bytes)
export function memoryStore() {
const records = new Map()
const blocks = new Map()
const posts = new Map()
let selection
return {
async getRecord(id) {
const bytes = records.get(recordPath(id))
return bytes && copy(bytes)
},
async putRecord(id, bytes) {
const key = recordPath(id)
if (records.has(key)) return false
records.set(key, copy(bytes))
return true
},
async getBlock(hash, maxSize) {
decodeHash(hash, 32, true)
requireThat(Number.isSafeInteger(maxSize) && maxSize >= 0, 'Invalid block size limit')
const bytes = blocks.get(hash)
if (bytes === undefined) return undefined
requireThat(bytes.length <= maxSize, 'Block exceeds size limit')
return copy(bytes)
},
async putBlock(hash, bytes) {
decodeHash(hash, 32, true)
if (blocks.has(hash)) return false
blocks.set(hash, copy(bytes))
return true
},
async getPost(id) {
const bytes = posts.get(recordPath(id))
return bytes && copy(bytes)
},
async putPost(id, bytes) {
const key = recordPath(id)
if (posts.has(key)) return false
posts.set(key, copy(bytes))
return true
},
async getSelection() {
return selection && parseJson(selection)
},
async putSelection(value) {
selection = utf8Encode(JSON.stringify(value))
}
}
}
Git ยท Social feed