sitestore

package
v0.1.0-alpha.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2026 License: Apache-2.0 Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ModeReadOnly      = 0
	ModeReadWrite     = 1
	ModeVersionChange = 2
)

Transaction modes.

View Source
const (
	QValue   = 'v' // first value
	QKey     = 'k' // first primary key
	QValues  = 'V' // all values (up to count)
	QKeys    = 'K' // all primary keys (up to count)
	QCount   = 'n'
	QRecords = 'R' // key, primary key, value triples
)

Query kinds.

View Source
const (
	DirNext       = 0
	DirNextUnique = 1
	DirPrev       = 2
	DirPrevUnique = 3
)

Cursor directions.

View Source
const (
	KeyNumber byte = 0x10
	KeyDate   byte = 0x20
	KeyString byte = 0x30
	KeyBinary byte = 0x40
	KeyArray  byte = 0x50
)

Key kinds in IndexedDB order.

View Source
const BlobThreshold = 64 << 10

BlobThreshold is the size above which a value is kept outside the store.

View Source
const DefaultQuota = int64(1) << 30

DefaultQuota is the per-origin hard cap used by NewManager when none is given and no budget can be derived.

Variables

View Source
var ErrInvalidKey = errors.New("sitestore: not a valid IndexedDB key")

ErrInvalidKey is returned for NaN numbers, invalid dates and malformed encodings.

Functions

func CompareKeys

func CompareKeys(a, b Key) int

CompareKeys is the specification's "compare two keys": number < date < string < binary < array; numbers and dates by value, strings by UTF-16 code unit, binaries by byte, arrays element by element and then by length. It is the oracle the encodings are tested against.

func DecodeNumberKey

func DecodeNumberKey(k string) (float64, bool)

DecodeNumberKey reads a wire key written by EncodeNumberKey.

func EncodeNumberKey

func EncodeNumberKey(f float64) string

EncodeNumberKey is the wire form of a number key: tag 0x10 and 16 hex digits of the order-preserving bit pattern.

func IsError

func IsError(err error, name string) bool

IsError reports whether err is the IndexedDB error with the given name.

func SortKeys

func SortKeys(ks []Key)

SortKeys sorts keys by CompareKeys (used by tests and tools).

func StorageToWire

func StorageToWire(s []byte) (string, error)

StorageToWire converts a storage key back to the wire form the script side decodes.

func WireToStorage

func WireToStorage(w string) ([]byte, error)

WireToStorage converts a wire key to its storage form.

Types

type Budget

type Budget struct {
	Global    int64 // bytes all origins together may use
	Used      int64 // bytes they use
	OriginCap int64 // bytes one origin may use
	Free      int64 // free bytes on the volume (-1 if unknown)
	Derived   bool  // Global came from the volume's free space
}

Budget is the quota state of the whole manager.

type CacheEntry

type CacheEntry struct {
	ID         int64  // the entry's sequence in its cache (stable when the request is replaced)
	URL        string // request URL without fragment
	Method     string
	ReqHeaders [][2]string
	Status     int
	StatusText string
	ResHeaders [][2]string
	Type       string // response type: basic, cors, default
	ResURL     string // response.url
	Size       int64  // body bytes
}

CacheEntry is one stored request/response pair.

type CacheMatch

type CacheMatch struct {
	Entry CacheEntry
	Body  []byte
}

CacheMatch is a stored entry together with its body.

type CacheQuery

type CacheQuery struct {
	URL          string
	Method       string
	IgnoreSearch bool
	IgnoreMethod bool
}

CacheQuery is the matching part of a request plus the CacheQueryOptions.

type CacheStore

type CacheStore struct {
	// contains filtered or unexported fields
}

CacheStore is the Cache Storage of one origin. It holds no data: every call goes to the ordered store.

func (*CacheStore) Delete

func (c *CacheStore) Delete(name string) bool

Delete removes a cache and its bodies. The entries are dropped by the background collector; the cache is gone for every reader the moment the batch commits.

func (*CacheStore) DeleteEntries

func (c *CacheStore) DeleteEntries(cacheName string, q CacheQuery) (int, error)

DeleteEntries removes the entries matching q from a cache and reports how many.

func (*CacheStore) Has

func (c *CacheStore) Has(name string) bool

func (*CacheStore) Keys

func (c *CacheStore) Keys() []string

Keys lists the cache names in creation order.

func (*CacheStore) Match

func (c *CacheStore) Match(cacheName string, everyCache bool, q CacheQuery, all bool) []CacheMatch

Match is MatchStream with the bodies read whole.

func (*CacheStore) MatchStream

func (c *CacheStore) MatchStream(cacheName string, everyCache bool, q CacheQuery, all bool) []CacheStream

MatchStream finds entries for a request in one cache, or, with everyCache, in every cache in creation order, and hands back each body as a stream (a large body is read from its file, never loaded whole). The caller closes every Body. all=false stops at the first match.

func (*CacheStore) Open

func (c *CacheStore) Open(name string) (bool, error)

Open creates the cache if it does not exist. It reports whether it was created.

func (*CacheStore) Put

func (c *CacheStore) Put(cacheName string, e CacheEntry, body []byte) error

Put stores an entry (replacing the first entry for the same request in place and dropping any other duplicates). body is the response body.

func (*CacheStore) Requests

func (c *CacheStore) Requests(cacheName string, q CacheQuery) ([]CacheEntry, error)

Requests lists the stored requests of one cache (those matching q when q.URL != "").

type CacheStream

type CacheStream struct {
	Entry CacheEntry
	Body  io.ReadCloser
}

CacheStream is a stored entry whose body is read as a stream.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn is an open connection (IDBDatabase).

type CursorReq

type CursorReq struct {
	Index    string
	Range    Range
	Dir      int
	CurKey   string // for index cursors the index key; for store cursors the primary key
	CurPK    string
	HasCur   bool
	Target   string
	TargetPK string
	Advance  int // number of steps (at least 1)
	KeyOnly  bool
}

CursorReq positions a cursor step. Cur* is the current position (empty on the first step); Target* is the key passed to continue()/continuePrimaryKey().

type DBInfo

type DBInfo struct {
	Name    string
	Version int64
}

DBInfo is one entry of indexedDB.databases().

type Database

type Database struct {
	// contains filtered or unexported fields
}

Database is one named database of an origin. Its mutex guards everything below it.

func (*Database) Delete

func (d *Database) Delete(reqID int64, sink Sink)

Delete queues a deleteDatabase request: delete-done or delete-error arrives through sink.

func (*Database) Open

func (d *Database) Open(reqID int64, sink Sink, version int64)

Open queues an open request. The outcome arrives through sink as one of: open-error, open-ready (with upgrade true or false), and possibly blocked and versionchange notifications to other connections first. reqID is echoed back.

type Error

type Error struct{ Name, Msg string }

Error is an IndexedDB error: Name is the DOMException name.

func (*Error) Error

func (e *Error) Error() string

type IndexEntry

type IndexEntry struct {
	PK   string
	Keys []string
}

IndexEntry is one record's keys in an index being created.

type Key

type Key struct {
	Kind byte
	Num  float64  // KeyNumber, KeyDate
	Str  []uint16 // KeyString: UTF-16 code units
	Bin  []byte   // KeyBinary
	Arr  []Key    // KeyArray
}

Key is a typed IndexedDB key, the reference form against which the byte encodings are tested.

func ArrayKey

func ArrayKey(elems ...Key) Key

func BinaryKey

func BinaryKey(b []byte) Key

func DateKey

func DateKey(ms float64) Key

func DecodeStorageKey

func DecodeStorageKey(b []byte) (Key, int, error)

DecodeStorageKey reads one key from the front of b and returns it with the bytes consumed.

func NumberKey

func NumberKey(f float64) Key

NumberKey, DateKey, StringKey, BinaryKey and ArrayKey build keys.

func ParseWire

func ParseWire(w string) (Key, error)

ParseWire reads a wire key.

func StringKey

func StringKey(s string) Key

func (Key) AppendStorage

func (k Key) AppendStorage(dst []byte) []byte

AppendStorage appends the storage form of the key. The key must be Valid.

func (Key) Storage

func (k Key) Storage() []byte

Storage returns the storage form of the key.

func (Key) Valid

func (k Key) Valid() bool

Valid reports whether the key (and every element) is a valid IndexedDB key.

func (Key) Wire

func (k Key) Wire() string

Wire returns the wire form of the key, byte for byte what idb_prelude.js produces.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager owns the storage of one browsing context. With an empty root it keeps everything in memory (incognito, ephemeral agent contexts); with a root directory it persists every origin under it:

<root>/<sha256(origin)[:24]>/meta.json        {"origin": ..., "persisted": ..., "lastAccess": ...}
<root>/<...>/kv/                              the origin's ordered store (IndexedDB, Cache Storage, OPFS tree)
<root>/<...>/blobs/                           large values and bodies, one file each
<root>/<...>/sw/                              service worker registrations

Quota, eviction and persistence are described in policy.go.

func NewManager

func NewManager(root string, quota int64) *Manager

NewManager returns a manager. quota > 0 is a hard cap per origin in bytes; quota <= 0 derives the cap from the global budget (see Options).

func NewManagerOptions

func NewManagerOptions(root string, opts Options) *Manager

NewManagerOptions returns a manager with explicit policy options.

func (*Manager) Abort

func (m *Manager) Abort(txID int64)

Abort rolls a transaction back.

func (*Manager) AllRecords

func (m *Manager) AllRecords(txID int64, storeName string) ([]any, error)

AllRecords lists the (key, value) pairs of a store, for populating a new index. It materialises the store: RecordsPage is the bounded form.

func (*Manager) Begin

func (m *Manager) Begin(connID int64, stores []string, mode int) (txID int64, started bool, err error)

Begin creates a transaction on a connection. started tells whether it can run now; otherwise a txstart notification follows when it can.

func (*Manager) Budget

func (m *Manager) Budget() Budget

Budget reports the global budget, the use and the per-origin cap.

func (*Manager) Clear

func (m *Manager) Clear(txID int64, storeName string) error

func (*Manager) ClearOrigin

func (m *Manager) ClearOrigin(origin string)

ClearOrigin deletes everything stored for origin ("" = every origin): the open connections are closed by force, the files removed. The caller reloads or discards the script contexts that used it.

func (*Manager) Close

func (m *Manager) Close()

Close flushes and closes every store that nothing is using and writes meta.json files. The manager stays usable: a store is reopened by the next access.

func (*Manager) CloseConn

func (m *Manager) CloseConn(connID int64)

CloseConn marks a connection close-pending; it closes for real once its transactions are finished.

func (*Manager) Commit

func (m *Manager) Commit(txID int64) error

Commit makes a transaction durable. A QuotaExceededError leaves it uncommitted: the caller aborts it.

func (*Manager) CreateIndex

func (m *Manager) CreateIndex(txID int64, storeName, name, kp string, unique, multi bool, ents []idxEntry) error

func (*Manager) CreateStore

func (m *Manager) CreateStore(txID int64, name, kp string, hasKP, auto bool) error

func (*Manager) Cursor

func (m *Manager) Cursor(txID int64, storeName string, q CursorReq) ([]any, error)

Cursor moves a cursor and returns [key, primaryKey, value] or nil at the end. It is stateless: the current position comes with the request and the step is a seek in the key range plus at most Advance moves, so a cursor over any number of records costs the same memory as one over three.

func (*Manager) CursorN

func (m *Manager) CursorN(txID int64, storeName string, q CursorReq, n int) ([][]any, error)

CursorN returns up to n consecutive cursor positions starting after q's current one, in one call: a cursor that is only being stepped (continue()) is served from this read-ahead instead of one storage seek per step. Each row is what Cursor returns for a single step; the result is empty at the end of the range. n is clamped to 256.

func (*Manager) DeleteIndex

func (m *Manager) DeleteIndex(txID int64, storeName, name string) error

func (*Manager) DeleteRange

func (m *Manager) DeleteRange(txID int64, storeName string, r Range) error

DeleteRange removes the records of a store whose key lies in the range.

func (*Manager) DeleteStore

func (m *Manager) DeleteStore(txID int64, name string) error

func (*Manager) DropSink

func (m *Manager) DropSink(sink Sink)

DropSink closes every connection that belongs to sink (its script VM is gone), aborting their transactions and withdrawing their queued requests.

func (*Manager) Evicted

func (m *Manager) Evicted() int64

Evicted is how many origins were evicted under pressure since the manager was created.

func (*Manager) EvictionOrder

func (m *Manager) EvictionOrder() []string

EvictionOrder lists the best-effort origins in the order global pressure would delete them.

func (*Manager) GenKey

func (m *Manager) GenKey(txID int64, storeName string) (string, error)

GenKey hands out the next generated key of an auto-increment store (the encoded key).

func (*Manager) Meta

func (m *Manager) Meta(connID int64) (map[string]any, error)

Meta describes the schema as the transaction (or connection) sees it.

func (*Manager) Origin

func (m *Manager) Origin(origin string) *Origin

Origin returns the storage of one origin (creating its in-memory state; nothing touches the disk until something is written).

func (*Manager) Origins

func (m *Manager) Origins() []string

Origins lists every origin that has data (in memory or on disk).

func (*Manager) Persistent

func (m *Manager) Persistent() bool

Persistent reports whether data survives the process.

func (*Manager) Put

func (m *Manager) Put(txID int64, storeName, key, val string, noOverwrite bool, ik map[string][]string) (string, error)

Put stores a record. key == "" asks the store's key generator (out-of-line keys with autoIncrement). It returns the key the record was stored under.

func (*Manager) Query

func (m *Manager) Query(txID int64, storeName, indexName string, kind byte, r Range, count int) ([]any, error)

Query reads from a store, or from one of its indexes (indexName != ""). The result is a slice of strings: for QCount, a single decimal string.

func (*Manager) RecordsPage

func (m *Manager) RecordsPage(txID int64, storeName, after string, limit int) (page []any, next string, err error)

RecordsPage returns up to limit (key, value) pairs of a store whose key is greater than after ("" = from the start) and the key to continue after ("" when there is no more). Index population reads a store this way without holding it in memory.

func (*Manager) RenameIndex

func (m *Manager) RenameIndex(txID int64, storeName, from, to string) error

func (*Manager) RenameStore

func (m *Manager) RenameStore(txID int64, from, to string) error

func (*Manager) Root

func (m *Manager) Root() string

Root is the directory everything lives under ("" = memory only).

func (*Manager) SetDurability

func (m *Manager) SetDurability(txID int64, strict bool)

SetDurability marks a transaction strict: its commit returns only once the data is on stable storage (IDBTransaction durability "strict"). The default commit reaches the journal, which survives a crash of the process and is written out with the next synchronous commit, when a store is closed and by the operating system; a version change always commits strictly.

func (*Manager) SetEvictHook

func (m *Manager) SetEvictHook(f func(origin string))

SetEvictHook installs the function called after an origin was evicted (to drop what lives outside the store, e.g. service worker registrations).

func (*Manager) SetPersistPolicy

func (m *Manager) SetPersistPolicy(f func(origin string) bool)

SetPersistPolicy installs the hook that decides persist() calls: it gets the origin and answers whether persistent storage is granted. It may be called from any goroutine and should not block for long.

func (*Manager) Shutdown

func (m *Manager) Shutdown()

Shutdown closes every store, in-memory ones included (their data is gone), and writes meta.json files. The manager must not be used afterwards: it is for the end of a browsing context's life.

func (*Manager) Sites

func (m *Manager) Sites() []SiteInfo

Sites lists the origins that store data, largest first.

func (*Manager) StoreMeta

func (m *Manager) StoreMeta(txID int64, name string) (map[string]any, error)

StoreMeta returns one store's schema as the transaction sees it.

func (*Manager) VersionChangeDone

func (m *Manager) VersionChangeDone(connID int64)

VersionChangeDone acknowledges a versionchange notification: the owner has run its event handlers (which usually closed the connection).

type Msg

type Msg = map[string]any

Msg is a notification to a connection's owner (a script VM). It is delivered through Sink.Notify and is plain JSON-compatible data.

type OPFS

type OPFS struct {
	// contains filtered or unexported fields
}

OPFS is the file system of one origin.

func (*OPFS) Get

func (f *OPFS) Get(parts []string, dir, create bool) error

Get gets or creates a child: parts is the full path, dir says what kind it must be.

func (*OPFS) List

func (f *OPFS) List(parts []string) ([]OPFSEntry, error)

List lists a directory in name order.

func (*OPFS) Move

func (f *OPFS) Move(from, to []string) error

Move renames or moves a node within the tree.

func (*OPFS) Read

func (f *OPFS) Read(parts []string) ([]byte, int64, error)

Read returns a file's bytes and modification time.

func (*OPFS) Remove

func (f *OPFS) Remove(parts []string, recursive bool) error

Remove deletes a file or directory; a non-empty directory needs recursive.

func (*OPFS) Stat

func (f *OPFS) Stat(parts []string) (*OPFSStat, error)

Stat reports a node; nil when the path does not exist.

func (*OPFS) Usage

func (f *OPFS) Usage() int64

Usage is the number of bytes the tree occupies.

func (*OPFS) Write

func (f *OPFS) Write(parts []string, data []byte) error

Write replaces a file's contents.

type OPFSEntry

type OPFSEntry struct {
	Name string
	Dir  bool
}

OPFSEntry is one directory entry.

type OPFSStat

type OPFSStat struct {
	Dir   bool
	Size  int64
	Mtime int64
}

OPFSStat is what stat reports.

type Options

type Options struct {
	// OriginQuota is the hard cap of one origin in bytes (0 = OriginFraction of the budget).
	OriginQuota int64
	// Budget is the global budget in bytes (0 = derived from the free space of the volume).
	Budget int64
	// BudgetCap bounds the derived budget (0 = 64 GiB).
	BudgetCap int64
	// FreeFraction is the share of the available space the derived budget may take (0 = 0.6).
	FreeFraction float64
	// OriginFraction is the share of the budget one origin may take (0 = 0.2).
	OriginFraction float64
	// MemoryBudget is the budget of a manager without a root directory (0 = 1 GiB).
	MemoryBudget int64
	// FreeSpace reports the free bytes of the volume that holds dir (nil = the operating system's answer).
	FreeSpace func(dir string) (uint64, error)
	// Now is the clock (nil = time.Now); tests use it to order accesses.
	Now func() time.Time
	// PersistPolicy decides persist() calls (nil = deny).
	PersistPolicy func(origin string) bool
	// OnEvict is called, with no lock held, after an origin was evicted.
	OnEvict func(origin string)
	// MaxOpenStores caps how many origins keep their ordered store open at once (0 = 12).
	MaxOpenStores int
	// IdleClose is how long an unused store stays open (0 = 20 s).
	IdleClose time.Duration
	// MaxTxBytes caps the uncommitted writes of one transaction (0 = 256 MiB).
	MaxTxBytes int64
	// contains filtered or unexported fields
}

Options configure a Manager. The zero value derives everything from the volume.

type Origin

type Origin struct {
	// contains filtered or unexported fields
}

Origin is the storage of one origin.

func (*Origin) Caches

func (o *Origin) Caches() (*CacheStore, error)

Caches returns the origin's Cache Storage.

func (*Origin) DB

func (o *Origin) DB(name string) (*Database, error)

DB returns the named database, loading its schema from the store when it exists. A database that does not exist yet is created empty in memory (it exists for the platform only once an upgrade transaction commits).

func (*Origin) Databases

func (o *Origin) Databases() []DBInfo

Databases lists the databases that exist.

func (*Origin) LastAccess

func (o *Origin) LastAccess() time.Time

LastAccess is when the origin last opened a database, committed a transaction or touched its caches.

func (*Origin) Name

func (o *Origin) Name() string

Name is the origin string.

func (*Origin) OPFS

func (o *Origin) OPFS() *OPFS

OPFS returns the origin's private file system.

func (*Origin) Persisted

func (o *Origin) Persisted() bool

Persisted reports whether the origin has persistent storage (it is never evicted).

func (*Origin) Quota

func (o *Origin) Quota() int64

Quota is what navigator.storage.estimate() reports as the quota: the origin's cap, or its use plus what is left of the global budget when that is less.

func (*Origin) RequestPersist

func (o *Origin) RequestPersist() bool

RequestPersist implements navigator.storage.persist(): true when the origin is persistent after the call. A memory-only manager never grants it (nothing there survives the process).

func (*Origin) SWDir

func (o *Origin) SWDir() string

SWDir is where the origin's service worker registrations live ("" = memory only).

func (*Origin) SetOtherBytes

func (o *Origin) SetOtherBytes(n int64)

SetOtherBytes records how much the origin's service worker scripts occupy (counted in usage and quota).

func (*Origin) SetPersisted

func (o *Origin) SetPersisted(v bool)

SetPersisted records a grant (or revocation) of persistent storage, bypassing the policy: for the app layer, which knows when the person has decided.

func (*Origin) StoreOpen

func (o *Origin) StoreOpen() bool

StoreOpen reports whether the origin's ordered store is currently open (tests, diagnostics).

func (*Origin) Touch

func (o *Origin) Touch()

Touch makes sure the origin is listed on disk (see Manager.Origins).

func (*Origin) Usage

func (o *Origin) Usage() Usage

Usage reports the origin's current storage use.

func (*Origin) WaitGC

func (o *Origin) WaitGC()

WaitGC blocks until the background deletion of dropped data has finished (tests, and the quota code, which wants the space back).

type Range

type Range struct {
	Lo, Hi         string
	LoOpen, HiOpen bool
}

Range is a key range in the prelude's wire form; an empty bound is unbounded.

func ParseRange

func ParseRange(lo, hi string, loOpen, hiOpen bool) Range

ParseRange builds a Range from a host argument slice [lo, hi, loOpen, hiOpen].

type Sink

type Sink interface{ Notify(m Msg) }

Sink receives notifications. Notify must not block and must not call back into the store from the same goroutine.

type SiteInfo

type SiteInfo struct {
	Origin     string    `json:"origin"`
	Usage      Usage     `json:"usage"`
	Persisted  bool      `json:"persisted"`
	LastAccess time.Time `json:"lastAccess"`
}

SiteInfo is one origin as the settings page shows it.

type Tx

type Tx struct {
	// contains filtered or unexported fields
}

Tx is a transaction.

type Usage

type Usage struct {
	IndexedDB int64
	Caches    int64
	OPFS      int64
	Other     int64 // service worker scripts
	Total     int64
}

Usage is what the origin stores, by kind, in bytes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL