anbot

root / store-browser.mjs

7017 bytes

// Browser store for ANBot: OPFS first, IndexedDB fallback.
//
// The same store interface as store.mjs, backed by browser storage.
// createBrowserStore selects a backend:
//
//   backend 'auto' (default): OPFS when navigator.storage.getDirectory
//     exists, otherwise IndexedDB.
//   backend 'opfs': OPFS, throwing when the API is missing.
//   backend 'idb': IndexedDB, throwing when the API is missing.
//
// Durability limits, stated honestly: a browser has no fsync. OPFS writes
// go through FileSystemWritableFileStream and are flushed when the stream
// closes, but the browser and OS decide when bytes reach disk; a crash can
// lose the tail of recent writes. IndexedDB transactions are durable once
// they complete, subject to the same OS-level caveat. The verify-then-select
// rule still holds: records and blocks are verified before they are stored,
// and the selection is written last, so a lost write can leave unselected
// records or blocks behind but never selects unverified data. Concurrent
// writers in separate tabs are not coordinated; the no-overwrite rule for
// records, posts, and blocks is best-effort here, checked before each write.
//
// Nothing in this module touches browser storage APIs at import time, so
// importing it never throws in runtimes without them.

import { decodeHash, parseJson, recordPath, requireThat, utf8Encode } from './core.mjs'

function checkBlockArgs(hash, maxSize) {
  decodeHash(hash, 32, true)
  requireThat(Number.isSafeInteger(maxSize) && maxSize >= 0, 'Invalid block size limit')
}

async function opfsStore(name) {
  const storage = globalThis.navigator?.storage
  requireThat(storage && typeof storage.getDirectory === 'function', 'OPFS is unavailable')
  const root = await storage.getDirectory()
  const directory = await root.getDirectoryHandle(name, { create: true })
  const records = await directory.getDirectoryHandle('records', { create: true })
  const blocks = await directory.getDirectoryHandle('blocks', { create: true })
  const posts = await directory.getDirectoryHandle('posts', { create: true })

  async function readFile(handle, key) {
    try {
      const file = await (await handle.getFileHandle(key)).getFile()
      return new Uint8Array(await file.arrayBuffer())
    } catch (error) {
      if (error?.name === 'NotFoundError') return undefined
      throw error
    }
  }

  async function writeFile(handle, key, bytes, replace) {
    if (!replace) {
      try {
        await handle.getFileHandle(key)
        return false
      } catch (error) {
        if (error?.name !== 'NotFoundError') throw error
      }
    }
    const fileHandle = await handle.getFileHandle(key, { create: true })
    const writable = await fileHandle.createWritable()
    try {
      await writable.write(bytes)
      await writable.close()
    } catch (error) {
      await writable.abort().catch(() => {})
      throw error
    }
    return true
  }

  return {
    async getRecord(id) {
      return readFile(records, recordPath(id))
    },
    async putRecord(id, bytes) {
      return writeFile(records, recordPath(id), bytes, false)
    },
    async getBlock(hash, maxSize) {
      checkBlockArgs(hash, maxSize)
      const bytes = await readFile(blocks, hash)
      if (bytes !== undefined) requireThat(bytes.length <= maxSize, 'Block exceeds size limit')
      return bytes
    },
    async putBlock(hash, bytes) {
      decodeHash(hash, 32, true)
      return writeFile(blocks, hash, bytes, false)
    },
    async getPost(id) {
      return readFile(posts, recordPath(id))
    },
    async putPost(id, bytes) {
      return writeFile(posts, recordPath(id), bytes, false)
    },
    async getSelection() {
      const bytes = await readFile(directory, 'selection.json')
      return bytes && parseJson(bytes)
    },
    async putSelection(selection) {
      await writeFile(directory, 'selection.json', utf8Encode(JSON.stringify(selection)), true)
    }
  }
}

async function idbStore(name) {
  const indexedDB = globalThis.indexedDB
  requireThat(indexedDB, 'IndexedDB is unavailable')
  const db = await new Promise((resolve, reject) => {
    const request = indexedDB.open(name, 1)
    request.onupgradeneeded = () => { request.result.createObjectStore('kv') }
    request.onsuccess = () => resolve(request.result)
    request.onerror = () => reject(request.error)
  })

  function transact(mode, operation) {
    return new Promise((resolve, reject) => {
      const tx = db.transaction('kv', mode)
      const request = operation(tx.objectStore('kv'))
      tx.oncomplete = () => resolve(request.result)
      tx.onabort = tx.onerror = () =>
        reject(tx.error || new Error('Storage transaction failed'))
    })
  }

  function putIfAbsent(key, value) {
    return new Promise((resolve, reject) => {
      let installed = false
      const tx = db.transaction('kv', 'readwrite')
      const store = tx.objectStore('kv')
      const get = store.get(key)
      get.onsuccess = () => {
        if (get.result === undefined) {
          installed = true
          store.put(value, key)
        }
      }
      tx.oncomplete = () => resolve(installed)
      tx.onabort = tx.onerror = () =>
        reject(tx.error || new Error('Storage transaction failed'))
    })
  }

  const stored = bytes => new Uint8Array(bytes).buffer
  const loaded = value => value === undefined ? undefined : new Uint8Array(value)

  return {
    async getRecord(id) {
      return loaded(await transact('readonly', store => store.get(`records/${recordPath(id)}`)))
    },
    async putRecord(id, bytes) {
      return putIfAbsent(`records/${recordPath(id)}`, stored(bytes))
    },
    async getBlock(hash, maxSize) {
      checkBlockArgs(hash, maxSize)
      const bytes = loaded(await transact('readonly', store => store.get(`blocks/${hash}`)))
      if (bytes !== undefined) requireThat(bytes.length <= maxSize, 'Block exceeds size limit')
      return bytes
    },
    async putBlock(hash, bytes) {
      decodeHash(hash, 32, true)
      return putIfAbsent(`blocks/${hash}`, stored(bytes))
    },
    async getPost(id) {
      return loaded(await transact('readonly', store => store.get(`posts/${recordPath(id)}`)))
    },
    async putPost(id, bytes) {
      return putIfAbsent(`posts/${recordPath(id)}`, stored(bytes))
    },
    async getSelection() {
      const bytes = loaded(await transact('readonly', store => store.get('selection')))
      return bytes && parseJson(bytes)
    },
    async putSelection(selection) {
      await transact('readwrite',
        store => store.put(stored(utf8Encode(JSON.stringify(selection))), 'selection'))
    }
  }
}

export async function createBrowserStore({ backend = 'auto', name = 'anbot-v1' } = {}) {
  requireThat(['auto', 'opfs', 'idb'].includes(backend), 'Unknown browser store backend')
  const opfsAvailable = typeof globalThis.navigator?.storage?.getDirectory === 'function'
  if (backend === 'opfs' || (backend === 'auto' && opfsAvailable)) return opfsStore(name)
  return idbStore(name)
}

Git ยท Social feed