storage

package
v0.1.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 16 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 the SQLite business database.

G1 uses modernc.org/sqlite (pure Go, CGO_ENABLED=0) and a single writer connection with WAL enabled. It stores chat message/ACK state and a small optional known-peer cache; the go-libp2p PeerStore remains the runtime address source of truth and is not duplicated here.

Index

Constants

View Source
const (
	OriginHuman   = "human"
	OriginAgent   = "agent"
	OriginUnknown = "unknown"
)

Message origin values. Provenance is a local operator model, not a cryptographic identity: every holder of the local API token can claim it.

View Source
const (
	DeliveryPending   = "pending"
	DeliveryAcked     = "acked"
	DeliveryFailed    = "failed"
	DeliveryCancelled = "cancelled"
	DeliveryUnknown   = "unknown"
	DeliveryReceived  = "received"
)

Message delivery states. Acked means the receiving node accepted the protocol message; it never means a human read it.

View Source
const (
	PeerSourceDHT       = "dht"
	PeerSourceKnown     = "known"
	PeerSourceManual    = "manual"
	PeerSourceBootstrap = "bootstrap"
	PeerSourcePinned    = "pinned"
)

Peer cache source values. Higher-priority sources are preserved when a lower-priority source refreshes the same peer.

View Source
const (
	// FileName is the SQLite database inside the data directory.
	FileName = "raminga.db"
)

Variables

View Source
var (
	ErrFriendNotFound      = errors.New("storage: friend not found")
	ErrFriendNameTaken     = errors.New("storage: friend name already used")
	ErrFriendPendingOutbox = errors.New("storage: friend has pending outbox messages")
)

Friend errors are stable so node/API can map them without parsing SQL text.

View Source
var ErrInvalidCursor = errors.New("storage: invalid cursor")

ErrInvalidCursor reports a malformed or stale pagination cursor.

View Source
var ErrOutboxFull = errors.New("storage: outbox is full")

ErrOutboxFull reports that the bounded outbox would exceed its entry or byte budget. The caller must not claim the message was stored.

View Source
var ErrOutboxNotFound = errors.New("storage: outbox entry not found")

ErrOutboxNotFound reports an unknown outbox entry.

View Source
var FriendNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`)

FriendNamePattern is the existing local-name rule.

Functions

func DecodeDiscoveryCursor

func DecodeDiscoveryCursor(raw string) (at, id int64, err error)

DecodeDiscoveryCursor validates an opaque cursor produced by this package.

func EncodeConversationCursor

func EncodeConversationCursor(c ConversationCursor) string

func EncodeDiscoveryCursor

func EncodeDiscoveryCursor(at, id int64) string

EncodeDiscoveryCursor serializes the (fetched_at_ms, id) position.

func EncodeMessageCursor

func EncodeMessageCursor(c MessageCursor) string

EncodeMessageCursor serializes a position without relying on rowids, which are not stable across pruning and vacuum.

func ValidateFriendName

func ValidateFriendName(name string) error

ValidateFriendName applies the pre-existing local name rule.

Types

type ConversationCursor

type ConversationCursor struct {
	LastAtMS      int64
	PeerID        string
	SnapshotRowID int64
	// RowID is an immutable rowid position for the human-relation snapshot.
	// last_at_ms changes on every new human send, so ordering by it while a
	// client pages would skip rows that moved across the boundary.
	RowID int64
}

ConversationCursor is the stable keyset position (last_at_ms, peer_id) for conversation summaries.

func DecodeConversationCursor

func DecodeConversationCursor(raw string) (ConversationCursor, error)

type ConversationSummary

type ConversationSummary struct {
	PeerID         string
	LastMessageID  string
	Direction      string
	Preview        string
	LastAtMS       int64
	DeliveryStatus string
	Origin         string
	MessageCount   int
}

ConversationSummary is one Peer's latest retained message.

type Friend

type Friend struct {
	PeerID            string
	Name              string
	Addrs             []string
	Description       string
	ManuallyConnected bool
	RelayCapable      bool
	DHTCapable        bool
	Paused            bool
	FirstSeenMS       int64
	LastInteractionMS int64
}

Friend is one local friend record. It is not the wire identity; names and descriptions are local UI data only.

type HumanOutboundPeer

type HumanOutboundPeer struct {
	PeerID    string
	FirstAtMS int64
	LastAtMS  int64
	// RowID and SnapshotRowID are opaque paging positions. They are not exposed
	// by the API but keep a snapshot complete while last_at_ms changes.
	RowID         int64
	SnapshotRowID int64
}

HumanOutboundPeer is a stage-6 "has human outbound" relation. It is updated when a human send is accepted and persisted, and is not pruned with messages.

type KnownPeer

type KnownPeer struct {
	PeerID      string
	Addrs       []string
	Source      string
	UpdatedAtMS int64
	ExpiresAtMS int64
}

KnownPeer is one bounded SQLite peer-cache row. It is a restart hint for the in-memory go-libp2p PeerStore, never an online-state claim. Sources are bootstrap, known, pinned and manual.

type Message

type Message struct {
	MessageID         string
	PeerID            string
	Direction         string // "in" or "out"
	Text              string
	Acked             bool
	CreatedAtMS       int64
	AckedAtMS         int64
	Origin            string
	DeliveryStatus    string
	DeliveryError     string
	DeliveryUpdatedMS int64
	ClientRequestID   string
}

Message is one persisted chat message.

type MessageCursor

type MessageCursor struct {
	CreatedAtMS int64
	MessageID   string
}

MessageCursor is the stable keyset position (created_at_ms, message_id) for one Peer's message history. message_id breaks ties for equal timestamps.

func DecodeMessageCursor

func DecodeMessageCursor(raw string) (MessageCursor, error)

DecodeMessageCursor validates an opaque cursor from a previous response.

type MessageRetention

type MessageRetention struct {
	RetainedMessages int
	OldestAtMS       int64
	MaxMessages      int
}

MessageRetention is the currently retained bounded history.

type OutboxEntry

type OutboxEntry struct {
	MessageID     string
	PeerID        string
	Text          string
	Multiaddr     string
	Status        string // pending, acked, failed, cancelled
	Attempts      int
	Bytes         int
	LastError     string
	CreatedAt     time.Time
	ExpiresAt     time.Time
	NextAttemptAt time.Time
	UpdatedAt     time.Time
}

OutboxEntry is one durable outbound message awaiting a real ACK.

type OutboxStats

type OutboxStats struct {
	Pending      int
	Acked        int
	Failed       int
	Cancelled    int
	PendingBytes int64
}

OutboxStats is the bounded outbox accounting view.

type PublicDiscovery

type PublicDiscovery struct {
	ID          int64
	PeerID      string
	Path        string
	SHA256      string
	SizeBytes   int64
	FetchedAtMS int64
	Source      string
}

PublicDiscovery is one successful Agent content acquisition from a remote peer's public manifest. It is a private local index: the source path, SHA-256 and fetch context are evidence, never a recommendation by themselves.

type PublicDiscoveryPage

type PublicDiscoveryPage struct {
	Items      []PublicDiscovery
	NextBefore string
	HasMore    bool
}

PublicDiscoveryPage is one keyset page of discovery evidence.

type Store

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

Store is the SQLite handle.

func Open

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

Open opens <dataDir>/raminga.db, applies pragmas and migrations.

func (*Store) CancelOutbox

func (s *Store) CancelOutbox(ctx context.Context, messageID string) (bool, error)

CancelOutbox cancels a pending entry and persists the cancelled delivery state on the history row. Terminal entries are not cancellable.

func (*Store) Close

func (s *Store) Close() error

Close closes the database.

func (*Store) CountMessages

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

CountMessages returns the persisted message row count (diagnostics/tests).

func (*Store) CountPeerCache

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

CountPeerCache returns the number of cache rows.

func (*Store) CountPublicDiscoveries

func (s *Store) CountPublicDiscoveries(ctx context.Context, familiarOnly bool) (int, error)

CountPublicDiscoveries returns the total and familiar-only counts so a bounded UI scan can say whether it saw every traceable entry.

func (*Store) DB

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

DB exposes the underlying handle for tests and diagnostics. Callers must not open a second competing address/state source with it.

func (*Store) DeletePeerCache

func (s *Store) DeletePeerCache(ctx context.Context, peerID string) error

DeletePeerCache removes one hint (used by tests/diagnostics).

func (*Store) DueOutbox

func (s *Store) DueOutbox(ctx context.Context, now time.Time, limit int) ([]OutboxEntry, error)

DueOutbox returns pending entries whose retry time and expiry are in range.

func (*Store) ExpireOutbox

func (s *Store) ExpireOutbox(ctx context.Context, now time.Time) (int, error)

ExpireOutbox marks every overdue pending entry failed and persists that failed state on the retained history rows. It returns the count.

func (*Store) FailOutbox

func (s *Store) FailOutbox(ctx context.Context, messageID, reason string) error

FailOutbox marks a pending entry failed with an honest reason (for example a permanent policy rejection) and persists it on the history row. It never marks the message ACKed.

func (*Store) FriendsForRestart

func (s *Store) FriendsForRestart(ctx context.Context, limit int) ([]Friend, error)

FriendsForRestart returns manual, unpaused friends with relay/DHT capability.

func (*Store) GetFriend

func (s *Store) GetFriend(ctx context.Context, peerID string) (Friend, bool, error)

GetFriend returns one row by Peer ID.

func (*Store) GetFriendByName

func (s *Store) GetFriendByName(ctx context.Context, name string) (Friend, bool, error)

GetFriendByName resolves a local name.

func (*Store) GetMessage

func (s *Store) GetMessage(ctx context.Context, messageID string) (Message, bool, error)

GetMessage returns one persisted message, if the row is still retained.

func (*Store) GetMessageByRequest

func (s *Store) GetMessageByRequest(ctx context.Context, peerID, requestID string) (Message, bool, error)

GetMessageByRequest returns a message created with one idempotency key for peerID. It is used to reconcile a timed-out send without creating another.

func (*Store) IsPaused

func (s *Store) IsPaused(ctx context.Context, peerID string) bool

IsPaused reports the persistent pause flag.

func (*Store) ListConversations

func (s *Store) ListConversations(ctx context.Context, before ConversationCursor, limit int) ([]ConversationSummary, bool, int64, error)

ListConversations returns one summary per Peer, newest first.

func (*Store) ListFriends

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

ListFriends returns all rows, named peers first and then by Peer ID.

func (*Store) ListHumanOutboundPeers

func (s *Store) ListHumanOutboundPeers(ctx context.Context, before ConversationCursor, limit int) ([]HumanOutboundPeer, bool, error)

ListHumanOutboundPeers returns the durable stage-6 relation as a stable rowid snapshot. The first page pins MAX(rowid); later pages walk strictly older rowids. A human send that updates last_at_ms between pages therefore cannot move an unseen row across the cursor and silently omit it.

For compatibility with a cursor minted by the stage-5 last_at ordering, a cursor without RowID falls back to that legacy order.

func (*Store) ListKnownPeers

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

ListKnownPeers returns all cache rows (including expired hints; callers that need only valid hints should filter on ExpiresAtMS). The in-memory PeerStore remains the runtime source of truth.

func (*Store) ListMessages

func (s *Store) ListMessages(ctx context.Context, peerID string, before MessageCursor, limit int) ([]Message, bool, error)

ListMessages returns one Peer's retained messages newest first and whether more older rows exist. The keyset cursor is stable across inserts, equal timestamps and pruning; it never uses rowid.

func (*Store) ListOutbox

func (s *Store) ListOutbox(ctx context.Context, limit int) ([]OutboxEntry, error)

ListOutbox returns newest-first outbox rows, including terminal states.

func (*Store) ListPausedPeers

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

ListPausedPeers returns persisted pause Peer IDs.

func (*Store) ListPublicDiscoveries

func (s *Store) ListPublicDiscoveries(ctx context.Context, before string, limit int, familiarOnly bool) (PublicDiscoveryPage, error)

ListPublicDiscoveries returns discovery evidence newest first. familiarOnly joins the durable human outbound relation, so the filter is applied to the whole content set rather than only the rows visible on one UI page.

func (*Store) MarkAcked

func (s *Store) MarkAcked(ctx context.Context, messageID string, ackedAt time.Time) error

MarkAcked records a matching ACK for messageID and its persisted delivery state. ACK means protocol acceptance, not that a human read the message.

func (*Store) MarkOutboxDelivered

func (s *Store) MarkOutboxDelivered(ctx context.Context, messageID string, ackedAt time.Time) error

MarkOutboxDelivered records a real matching ACK for an outbox entry and the history row. A missing history row (pruned by the message bound) does not erase the outbox success.

func (*Store) MessageRetention

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

MessageRetention returns the currently retained range and hard cap.

func (*Store) OutboxStats

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

OutboxStats returns bounded-outbox accounting.

func (*Store) Path

func (s *Store) Path() string

Path returns the database path.

func (*Store) PausePeer

func (s *Store) PausePeer(ctx context.Context, peerID string) error

PausePeer persists a pause without creating a friend row.

func (*Store) RecentMessages

func (s *Store) RecentMessages(ctx context.Context, limit int) ([]Message, error)

RecentMessages returns the newest messages first.

func (*Store) RecordOutboxFailure

func (s *Store) RecordOutboxFailure(ctx context.Context, messageID string, attempts int, nextAttempt time.Time, reason string) error

RecordOutboxFailure persists the next exponential-backoff attempt and the real error. It never marks the entry acked; the history row stays pending so the UI can distinguish "queued/unknown" from protocol acceptance.

func (*Store) RecordPublicDiscovery

func (s *Store) RecordPublicDiscovery(ctx context.Context, peerID, path, sha256 string, sizeBytes, fetchedAtMS int64, source string) (PublicDiscovery, error)

RecordPublicDiscovery stores one successful fetch. A re-download of the same version updates the observed time/source but does not create a duplicate; a changed SHA-256 is a new version and stays as a separate row.

func (*Store) RemoveFriend

func (s *Store) RemoveFriend(ctx context.Context, peerID string, cancelPending bool) (bool, int, error)

RemoveFriend deletes the row (chat history is untouched). If pending outbox rows exist, they must be explicitly cancelled or the delete is refused.

func (*Store) ResetOutboxPeer

func (s *Store) ResetOutboxPeer(ctx context.Context, peerID string) error

ResetOutboxPeer makes pending entries for one peer due immediately, used when that peer reconnects (fresh connectivity resets the backoff wait).

func (*Store) ResumePeer

func (s *Store) ResumePeer(ctx context.Context, peerID string) error

ResumePeer clears a persisted pause.

func (*Store) SaveInbound

func (s *Store) SaveInbound(ctx context.Context, messageID, peerID, text string, createdAt time.Time) (bool, error)

SaveInbound stores an inbound message. It returns false when messageID was already stored, which makes duplicate delivery harmless. An inbound row is "received"; its remote human/agent provenance is not authenticated and stays unknown.

func (*Store) SaveOutbound

func (s *Store) SaveOutbound(ctx context.Context, messageID, peerID, text string, createdAt time.Time) error

SaveOutbound persists an outbound message before it is sent, with acked=0. It is a legacy diagnostic path without a durable outbox entry, so its delivery state is unknown rather than an unprovable "pending".

func (*Store) SaveOutboundOrigin

func (s *Store) SaveOutboundOrigin(ctx context.Context, messageID, peerID, text string, createdAt time.Time, origin, requestID string) error

SaveOutboundOrigin persists one outbound row without an outbox entry.

func (*Store) SaveOutboundWithOutbox

func (s *Store) SaveOutboundWithOutbox(ctx context.Context, messageID, peerID, text, multiaddr string, createdAt, expiresAt time.Time, maxEntries int, maxBytes int64) error

SaveOutboundWithOutbox persists one outbound message and its durable outbox entry in a single transaction. Capacity is checked before insert, so a full outbox returns ErrOutboxFull without creating a misleading history row.

func (*Store) SaveOutboundWithOutboxOrigin

func (s *Store) SaveOutboundWithOutboxOrigin(ctx context.Context, messageID, peerID, text, multiaddr string, createdAt, expiresAt time.Time, maxEntries int, maxBytes int64, origin, requestID string) error

SaveOutboundWithOutboxOrigin is SaveOutboundWithOutbox with explicit local provenance and an optional idempotency key. A human send records the durable human_outbound_peers relation in the same transaction that persists the message, so later pruning of message rows cannot erase the relationship.

func (*Store) SetFriendCapabilities

func (s *Store) SetFriendCapabilities(ctx context.Context, peerID string, relay, dht bool) error

SetFriendCapabilities persists protocol capabilities learned from identify.

func (*Store) SetFriendDescription

func (s *Store) SetFriendDescription(ctx context.Context, peerID, description string) (Friend, error)

SetFriendDescription replaces a description. It is at most 280 characters and rejects control characters.

func (*Store) SetFriendName

func (s *Store) SetFriendName(ctx context.Context, peerID, name string) (Friend, error)

SetFriendName replaces (or clears, when name is empty) a friend's local name.

func (*Store) SetMaxFriends

func (s *Store) SetMaxFriends(max int)

SetMaxFriends bounds the friends table. Values <= 0 restore the default.

func (*Store) SetMaxMessages

func (s *Store) SetMaxMessages(max int)

SetMaxMessages bounds the messages table. Oldest rows (by created_at_ms, then rowid) are pruned in the same transaction as each insert. Zero disables the bound and is only for tests/diagnostics, never for a daemon.

func (*Store) UpsertFriend

func (s *Store) UpsertFriend(ctx context.Context, peerID string, addrs []string, manuallyConnected, touch bool) (Friend, bool, error)

UpsertFriend records an interaction. New rows and address/manual changes write immediately; a plain interaction is throttled to once per 10 minutes.

func (*Store) UpsertKnownPeer

func (s *Store) UpsertKnownPeer(ctx context.Context, peerID string, addrs []string, source string) error

UpsertKnownPeer writes a bounded peer-cache hint with the default TTL.

func (*Store) UpsertPeerCache

func (s *Store) UpsertPeerCache(ctx context.Context, peerID string, addrs []string, source string, ttl time.Duration, maxEntries int) error

UpsertPeerCache merges addrs into the peer's cache entry, preserves valid existing addresses instead of truncating them, and prunes expired/over-cap rows. It is a hint cache only; callers must not treat it as online state.

Jump to

Keyboard shortcuts

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