Documentation
¶
Index ¶
- Constants
- Variables
- func CompareKeys(a, b Key) int
- func DecodeNumberKey(k string) (float64, bool)
- func EncodeNumberKey(f float64) string
- func IsError(err error, name string) bool
- func SortKeys(ks []Key)
- func StorageToWire(s []byte) (string, error)
- func WireToStorage(w string) ([]byte, error)
- type Budget
- type CacheEntry
- type CacheMatch
- type CacheQuery
- type CacheStore
- func (c *CacheStore) Delete(name string) bool
- func (c *CacheStore) DeleteEntries(cacheName string, q CacheQuery) (int, error)
- func (c *CacheStore) Has(name string) bool
- func (c *CacheStore) Keys() []string
- func (c *CacheStore) Match(cacheName string, everyCache bool, q CacheQuery, all bool) []CacheMatch
- func (c *CacheStore) MatchStream(cacheName string, everyCache bool, q CacheQuery, all bool) []CacheStream
- func (c *CacheStore) Open(name string) (bool, error)
- func (c *CacheStore) Put(cacheName string, e CacheEntry, body []byte) error
- func (c *CacheStore) Requests(cacheName string, q CacheQuery) ([]CacheEntry, error)
- type CacheStream
- type Conn
- type CursorReq
- type DBInfo
- type Database
- type Error
- type IndexEntry
- type Key
- type Manager
- func (m *Manager) Abort(txID int64)
- func (m *Manager) AllRecords(txID int64, storeName string) ([]any, error)
- func (m *Manager) Begin(connID int64, stores []string, mode int) (txID int64, started bool, err error)
- func (m *Manager) Budget() Budget
- func (m *Manager) Clear(txID int64, storeName string) error
- func (m *Manager) ClearOrigin(origin string)
- func (m *Manager) Close()
- func (m *Manager) CloseConn(connID int64)
- func (m *Manager) Commit(txID int64) error
- func (m *Manager) CreateIndex(txID int64, storeName, name, kp string, unique, multi bool, ents []idxEntry) error
- func (m *Manager) CreateStore(txID int64, name, kp string, hasKP, auto bool) error
- func (m *Manager) Cursor(txID int64, storeName string, q CursorReq) ([]any, error)
- func (m *Manager) CursorN(txID int64, storeName string, q CursorReq, n int) ([][]any, error)
- func (m *Manager) DeleteIndex(txID int64, storeName, name string) error
- func (m *Manager) DeleteRange(txID int64, storeName string, r Range) error
- func (m *Manager) DeleteStore(txID int64, name string) error
- func (m *Manager) DropSink(sink Sink)
- func (m *Manager) Evicted() int64
- func (m *Manager) EvictionOrder() []string
- func (m *Manager) GenKey(txID int64, storeName string) (string, error)
- func (m *Manager) Meta(connID int64) (map[string]any, error)
- func (m *Manager) Origin(origin string) *Origin
- func (m *Manager) Origins() []string
- func (m *Manager) Persistent() bool
- func (m *Manager) Put(txID int64, storeName, key, val string, noOverwrite bool, ...) (string, error)
- func (m *Manager) Query(txID int64, storeName, indexName string, kind byte, r Range, count int) ([]any, error)
- func (m *Manager) RecordsPage(txID int64, storeName, after string, limit int) (page []any, next string, err error)
- func (m *Manager) RenameIndex(txID int64, storeName, from, to string) error
- func (m *Manager) RenameStore(txID int64, from, to string) error
- func (m *Manager) Root() string
- func (m *Manager) SetDurability(txID int64, strict bool)
- func (m *Manager) SetEvictHook(f func(origin string))
- func (m *Manager) SetPersistPolicy(f func(origin string) bool)
- func (m *Manager) Shutdown()
- func (m *Manager) Sites() []SiteInfo
- func (m *Manager) StoreMeta(txID int64, name string) (map[string]any, error)
- func (m *Manager) VersionChangeDone(connID int64)
- type Msg
- type OPFS
- func (f *OPFS) Get(parts []string, dir, create bool) error
- func (f *OPFS) List(parts []string) ([]OPFSEntry, error)
- func (f *OPFS) Move(from, to []string) error
- func (f *OPFS) Read(parts []string) ([]byte, int64, error)
- func (f *OPFS) Remove(parts []string, recursive bool) error
- func (f *OPFS) Stat(parts []string) (*OPFSStat, error)
- func (f *OPFS) Usage() int64
- func (f *OPFS) Write(parts []string, data []byte) error
- type OPFSEntry
- type OPFSStat
- type Options
- type Origin
- func (o *Origin) Caches() (*CacheStore, error)
- func (o *Origin) DB(name string) (*Database, error)
- func (o *Origin) Databases() []DBInfo
- func (o *Origin) LastAccess() time.Time
- func (o *Origin) Name() string
- func (o *Origin) OPFS() *OPFS
- func (o *Origin) Persisted() bool
- func (o *Origin) Quota() int64
- func (o *Origin) RequestPersist() bool
- func (o *Origin) SWDir() string
- func (o *Origin) SetOtherBytes(n int64)
- func (o *Origin) SetPersisted(v bool)
- func (o *Origin) StoreOpen() bool
- func (o *Origin) Touch()
- func (o *Origin) Usage() Usage
- func (o *Origin) WaitGC()
- type Range
- type Sink
- type SiteInfo
- type Tx
- type Usage
Constants ¶
const ( ModeReadOnly = 0 ModeReadWrite = 1 ModeVersionChange = 2 )
Transaction modes.
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.
const ( DirNext = 0 DirNextUnique = 1 DirPrev = 2 DirPrevUnique = 3 )
Cursor directions.
const ( KeyNumber byte = 0x10 KeyDate byte = 0x20 KeyString byte = 0x30 KeyBinary byte = 0x40 KeyArray byte = 0x50 )
Key kinds in IndexedDB order.
const BlobThreshold = 64 << 10
BlobThreshold is the size above which a value is kept outside the store.
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 ¶
var ErrInvalidKey = errors.New("sitestore: not a valid IndexedDB key")
ErrInvalidKey is returned for NaN numbers, invalid dates and malformed encodings.
Functions ¶
func CompareKeys ¶
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 ¶
DecodeNumberKey reads a wire key written by EncodeNumberKey.
func EncodeNumberKey ¶
EncodeNumberKey is the wire form of a number key: tag 0x10 and 16 hex digits of the order-preserving bit pattern.
func SortKeys ¶
func SortKeys(ks []Key)
SortKeys sorts keys by CompareKeys (used by tests and tools).
func StorageToWire ¶
StorageToWire converts a storage key back to the wire form the script side decodes.
func WireToStorage ¶
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 ¶
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 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 ¶
Delete queues a deleteDatabase request: delete-done or delete-error arrives through sink.
type Error ¶
type Error struct{ Name, Msg string }
Error is an IndexedDB error: Name is the DOMException name.
type IndexEntry ¶
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 DecodeStorageKey ¶
DecodeStorageKey reads one key from the front of b and returns it with the bytes consumed.
func (Key) AppendStorage ¶
AppendStorage appends the storage form of the key. The key must be Valid.
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 ¶
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 ¶
NewManagerOptions returns a manager with explicit policy options.
func (*Manager) AllRecords ¶
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) ClearOrigin ¶
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 ¶
CloseConn marks a connection close-pending; it closes for real once its transactions are finished.
func (*Manager) Commit ¶
Commit makes a transaction durable. A QuotaExceededError leaves it uncommitted: the caller aborts it.
func (*Manager) CreateIndex ¶
func (*Manager) CreateStore ¶
func (*Manager) Cursor ¶
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 ¶
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 (*Manager) DeleteRange ¶
DeleteRange removes the records of a store whose key lies in the range.
func (*Manager) DropSink ¶
DropSink closes every connection that belongs to sink (its script VM is gone), aborting their transactions and withdrawing their queued requests.
func (*Manager) Evicted ¶
Evicted is how many origins were evicted under pressure since the manager was created.
func (*Manager) EvictionOrder ¶
EvictionOrder lists the best-effort origins in the order global pressure would delete them.
func (*Manager) GenKey ¶
GenKey hands out the next generated key of an auto-increment store (the encoded key).
func (*Manager) Origin ¶
Origin returns the storage of one origin (creating its in-memory state; nothing touches the disk until something is written).
func (*Manager) Persistent ¶
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 (*Manager) SetDurability ¶
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 ¶
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 ¶
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) VersionChangeDone ¶
VersionChangeDone acknowledges a versionchange notification: the owner has run its event handlers (which usually closed the connection).
type Msg ¶
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 ¶
Get gets or creates a child: parts is the full path, dir says what kind it must be.
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 ¶
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) LastAccess ¶
LastAccess is when the origin last opened a database, committed a transaction or touched its caches.
func (*Origin) Persisted ¶
Persisted reports whether the origin has persistent storage (it is never evicted).
func (*Origin) Quota ¶
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 ¶
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 ¶
SWDir is where the origin's service worker registrations live ("" = memory only).
func (*Origin) SetOtherBytes ¶
SetOtherBytes records how much the origin's service worker scripts occupy (counted in usage and quota).
func (*Origin) SetPersisted ¶
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 ¶
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).
type Range ¶
Range is a key range in the prelude's wire form; an empty bound is unbounded.
func ParseRange ¶
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.