storage

package
v0.0.0-...-9268282 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 17 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

Overview

Package storage owns a tenant's SQLite database and the transaction boundary for event data, projections and durable work intents.

Open creates the database and schema with SQLite WAL mode, full synchronous writes, foreign-key enforcement and one database connection. Each method uses its context for database work.

Save applies duplicate, deletion and replacement rules, stores searchable indexes and inserts durable work intents in one transaction. Callers validate events before passing them to storage. SaveTx performs the same operation inside a transaction supplied by the caller. The caller owns that transaction and commits it after SaveTx succeeds. WithTx provides the matching begin, commit and rollback boundary; its callback uses the supplied *sql.Tx for all database operations.

Query excludes expired, hidden and pending events and applies recipient checks through QueryOptions.Access. It returns events in created-at descending order with ID ascending as the stable tie breaker. The tenant gate applies the remaining policy and resource visibility rules. After reads events by their increasing insertion sequence for cursored replication; removed events leave gaps in that sequence.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddIntents

func AddIntents(ctx context.Context, tx *sql.Tx, intents []Intent, now int64) error

func IntentID

func IntentID(kind, eventID, target string) string

IntentID returns the stable identifier shared by transactional and queued durable work. Payload changes do not create a second intent.

func PutSetting

func PutSetting(ctx context.Context, tx *sql.Tx, key string, value any) error

PutSetting writes one setting using a caller-owned transaction.

Types

type Access

type Access struct {
	PubKeys []string
	All     bool
	// IncludeCallbackRegistrations opts out of the daemon's callback privacy
	// filter. Standalone relays use this to preserve opaque Nostr events.
	IncludeCallbackRegistrations bool
}

Access controls which private and callback events a query may return. All bypasses recipient filtering but still excludes hidden, pending and expired rows.

type CursorEvent

type CursorEvent struct {
	Sequence int64       `json:"seq"`
	Event    event.Event `json:"event"`
}

type Diff

type Diff struct {
	AddedTags      [][]string `json:"addedTags"`
	RemovedTags    [][]string `json:"removedTags"`
	ContentChanged bool       `json:"contentChanged"`
}

Diff describes content and tag changes between the retained and current versions.

type Draft

type Draft struct {
	Kind      int        `json:"kind"`
	CreatedAt int64      `json:"created_at"`
	Tags      [][]string `json:"tags"`
	Content   string     `json:"content"`
}

Draft is the event body needed to publish a restored list version.

type EventCursor

type EventCursor struct {
	CreatedAt int64
	ID        string
}

EventCursor follows the stable newest-first query order.

type HistoryRow

type HistoryRow struct {
	Kind      int    `json:"kind"`
	D         string `json:"d"`
	EventID   string `json:"event_id"`
	CreatedAt int64  `json:"created_at"`
	SavedAt   int64  `json:"saved_at"`
}

HistoryRow identifies one retained version of a replaceable list.

type Intent

type Intent struct {
	Kind    string `json:"kind"`
	EventID string `json:"event_id"`
	Target  string `json:"target"`
	Payload string `json:"payload"`
}

Intent describes durable work to insert with an event save. The tuple of Kind, EventID and Target determines its stable ID; Payload is retained for the worker handling that kind.

type KindStats

type KindStats struct {
	Kind   int   `json:"kind"`
	N      int64 `json:"n"`
	Bytes  int64 `json:"bytes"`
	Oldest int64 `json:"oldest"`
	Newest int64 `json:"newest"`
}

KindStats reports count, size and time bounds for one stored event kind.

type MemberRetention

type MemberRetention struct {
	PubKey string
	Days   int
}

MemberRetention removes eligible events and list history for one author older than Days.

type Observer

type Observer interface {
	ObserveStorage(operation, outcome string, duration time.Duration)
}

Observer receives operation name, outcome and duration for instrumented Store operations.

type QueryOptions

type QueryOptions struct {
	Now    int64
	Access Access
	Limit  int
	Before *EventCursor
}

QueryOptions supplies query time, access principals, an optional result limit and a cursor from a prior Query result.

type QueryResult

type QueryResult struct {
	Events []event.Event
	More   bool
}

QueryResult contains the matching events and whether the limit hid more rows.

type Rejection

type Rejection string

Rejection is a stable Save error that callers can match with errors.Is.

const (
	ErrDuplicate Rejection = "duplicate: already have this event"
	ErrReplaced  Rejection = "duplicate: a newer version exists"
	ErrDeleted   Rejection = "blocked: event was previously deleted by its author"
	ErrVanished  Rejection = "blocked: this pubkey asked for its events to be deleted"
)

func (Rejection) Error

func (e Rejection) Error() string

type RestoreOptions

type RestoreOptions struct {
	Owner   string
	EventID string
	Now     int64
}

RestoreOptions identifies the retained list event and the query time used for expiration checks.

type RestoreResult

type RestoreResult struct {
	Draft Draft `json:"draft"`
	Diff  Diff  `json:"diff"`
}

RestoreResult contains a prior list event draft and its difference from the current list.

type RetentionOptions

type RetentionOptions struct {
	Now      int64
	Identity string
	Rules    []RetentionRule
	Members  []MemberRetention
}

RetentionOptions supplies the retention time, relay identity and rules.

type RetentionRule

type RetentionRule struct {
	Kind int
	Days int
}

RetentionRule removes non-identity events older than Days. A negative Kind applies the catch-all rule to kinds eligible for retention.

type SaveOptions

type SaveOptions struct {
	Now          int64
	SearchMode   string
	Intents      []Intent
	BeforeCommit func(context.Context, *sql.Tx) error
}

SaveOptions controls event persistence. Now is the Unix time used for history and intent timestamps. SearchMode is empty for the default indexed kinds, "full" for all public content and "off" to skip content indexing. For stored events, Intents and BeforeCommit run in the event transaction. Ephemeral events return before those hooks. A BeforeCommit error rolls back the transaction owned by Save; SaveTx returns it to the transaction's owner.

func (*SaveOptions) AddBeforeCommit

func (o *SaveOptions) AddBeforeCommit(next func(context.Context, *sql.Tx) error)

AddBeforeCommit appends a projection to this save's transaction. Projections run in registration order and the first error rolls back the complete save.

type SaveResult

type SaveResult struct {
	Sequence  int64
	Ephemeral bool
}

SaveResult reports the event sequence. Ephemeral events return without a database row and set Ephemeral.

func SaveTx

func SaveTx(ctx context.Context, tx *sql.Tx, e event.Event, opts SaveOptions) (SaveResult, error)

SaveTx composes event persistence with membership or other tenant changes. The caller owns commit/rollback; no success may be acknowledged before commit.

type Stats

type Stats struct {
	Events   int64 `json:"events"`
	Bytes    int64 `json:"bytes"`
	Oldest   int64 `json:"oldest"`
	Newest   int64 `json:"newest"`
	WALBytes int64 `json:"wal_bytes"`
}

Stats reports event counts, database size and the current WAL size.

type Store

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

Store is a tenant's SQLite database. A Store must be closed when its owner is done with it.

func Open

func Open(ctx context.Context, path string) (*Store, error)

Open creates or opens path, initializes the tenant schema and returns a Store. The parent directory is created with mode 0700 and the database file with mode 0600.

func (*Store) After

func (s *Store) After(ctx context.Context, seq int64, f event.Filter, opts QueryOptions) ([]CursorEvent, error)

func (*Store) Close

func (s *Store) Close() error

Close releases the database connection.

func (*Store) Count

func (s *Store) Count(ctx context.Context, filters []event.Filter, opts QueryOptions) (count int64, err error)

func (*Store) DB

func (s *Store) DB() *sql.DB

DB returns the database used by tenant services for their schemas, queries and transactions. Event persistence uses Save or SaveTx to apply storage's replacement, deletion and indexing rules.

func (*Store) DeleteEvent

func (s *Store) DeleteEvent(ctx context.Context, id string) (bool, error)

DeleteEvent removes one event by ID and reports whether a row was removed.

func (*Store) DeleteSetting

func (s *Store) DeleteSetting(ctx context.Context, key string) error

DeleteSetting removes one settings row. A missing row is not an error.

func (*Store) EraseAuthor

func (s *Store) EraseAuthor(ctx context.Context, pubkey string) (int64, error)

EraseAuthor removes an author's events and retained list and wiki history.

func (*Store) GetSetting

func (s *Store) GetSetting(ctx context.Context, key string, dest any) error

GetSetting decodes a JSON setting into dest.

func (*Store) HasPrivateRepositories

func (s *Store) HasPrivateRepositories(ctx context.Context) (bool, error)

HasPrivateRepositories checks the stored announcements, including legacy events. Multiword tags such as private are not in the NIP-01 tag index.

func (*Store) IsPrivateRepository

func (s *Store) IsPrivateRepository(ctx context.Context, pubkey, identifier string) (bool, error)

IsPrivateRepository resolves a state event's privacy from its announcement.

func (*Store) KindStats

func (s *Store) KindStats(ctx context.Context) ([]KindStats, error)

func (*Store) ListHistory

func (s *Store) ListHistory(ctx context.Context, owner string, now int64) ([]HistoryRow, error)

func (*Store) Path

func (s *Store) Path() string

Path returns the database file path supplied to Open.

func (*Store) PruneSettings

func (s *Store) PruneSettings(ctx context.Context, prefix string, keep map[string]struct{}) error

PruneSettings removes rows under prefix whose keys are not in keep, so per-filter state cannot accumulate as filters come and go.

func (*Store) PutSetting

func (s *Store) PutSetting(ctx context.Context, key string, value any) error

PutSetting encodes value as JSON and upserts it under key.

func (*Store) Query

func (s *Store) Query(ctx context.Context, f event.Filter, opts QueryOptions) (result QueryResult, err error)

func (*Store) RestoreHistory

func (s *Store) RestoreHistory(ctx context.Context, opts RestoreOptions) (RestoreResult, error)

func (*Store) Save

func (s *Store) Save(ctx context.Context, e event.Event, opts SaveOptions) (SaveResult, error)

Save commits an event, its indexes and the supplied transaction hooks together. Callers validate the event before saving. Duplicate, replaced, deleted and vanished events return a Rejection. Ephemeral events return an Ephemeral result without writing rows or running the hooks.

func (*Store) SetObserver

func (s *Store) SetObserver(o Observer)

SetObserver replaces the observer used for operation timing and outcomes.

func (*Store) Stats

func (s *Store) Stats(ctx context.Context) (Stats, error)

func (*Store) SweepExpired

func (s *Store) SweepExpired(ctx context.Context, now int64) (int64, error)

SweepExpired removes expired events and history and returns the next event expiration timestamp, or zero when none remain.

func (*Store) SweepRetention

func (s *Store) SweepRetention(ctx context.Context, opts RetentionOptions) (int64, error)

SweepRetention enforces user-selected content retention, independent of host capacity. The catch-all deliberately retains replaceable lists and mail.

func (*Store) Vanish

func (s *Store) Vanish(ctx context.Context, pubkey string, until int64) error

Vanish records a deletion horizon and removes the author's events and related history through until, inclusive.

func (*Store) WikiRevision

func (s *Store) WikiRevision(ctx context.Context, id string) (WikiRevision, bool, error)

WikiRevision reads one archived revision by event id.

func (*Store) WikiRevisions

func (s *Store) WikiRevisions(ctx context.Context, author, d string) ([]WikiRevision, error)

WikiRevisions lists archived revisions newest first. An empty author or d matches every author or page.

func (*Store) WithTx

func (s *Store) WithTx(ctx context.Context, fn func(*sql.Tx) error) (err error)

WithTx opens a transaction, calls fn and commits after fn succeeds. It rolls back on failure. The callback uses the supplied transaction for database work because it holds the store's sole connection until completion.

type WikiRevision

type WikiRevision struct {
	ID           string
	Author       string
	D            string
	CreatedAt    int64
	SupersededBy string
	Event        event.Event
}

WikiRevision is one archived version of a wiki page.

Jump to

Keyboard shortcuts

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