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
- Variables
- func DecodeDiscoveryCursor(raw string) (at, id int64, err error)
- func EncodeConversationCursor(c ConversationCursor) string
- func EncodeDiscoveryCursor(at, id int64) string
- func EncodeMessageCursor(c MessageCursor) string
- func ValidateFriendName(name string) error
- type ConversationCursor
- type ConversationSummary
- type Friend
- type HumanOutboundPeer
- type KnownPeer
- type Message
- type MessageCursor
- type MessageRetention
- type OutboxEntry
- type OutboxStats
- type PublicDiscovery
- type PublicDiscoveryPage
- type Store
- func (s *Store) CancelOutbox(ctx context.Context, messageID string) (bool, error)
- func (s *Store) Close() error
- func (s *Store) CountMessages(ctx context.Context) (int, error)
- func (s *Store) CountPeerCache(ctx context.Context) (int, error)
- func (s *Store) CountPublicDiscoveries(ctx context.Context, familiarOnly bool) (int, error)
- func (s *Store) DB() *sql.DB
- func (s *Store) DeletePeerCache(ctx context.Context, peerID string) error
- func (s *Store) DueOutbox(ctx context.Context, now time.Time, limit int) ([]OutboxEntry, error)
- func (s *Store) ExpireOutbox(ctx context.Context, now time.Time) (int, error)
- func (s *Store) FailOutbox(ctx context.Context, messageID, reason string) error
- func (s *Store) FriendsForRestart(ctx context.Context, limit int) ([]Friend, error)
- func (s *Store) GetFriend(ctx context.Context, peerID string) (Friend, bool, error)
- func (s *Store) GetFriendByName(ctx context.Context, name string) (Friend, bool, error)
- func (s *Store) GetMessage(ctx context.Context, messageID string) (Message, bool, error)
- func (s *Store) GetMessageByRequest(ctx context.Context, peerID, requestID string) (Message, bool, error)
- func (s *Store) IsPaused(ctx context.Context, peerID string) bool
- func (s *Store) ListConversations(ctx context.Context, before ConversationCursor, limit int) ([]ConversationSummary, bool, int64, error)
- func (s *Store) ListFriends(ctx context.Context) ([]Friend, error)
- func (s *Store) ListHumanOutboundPeers(ctx context.Context, before ConversationCursor, limit int) ([]HumanOutboundPeer, bool, error)
- func (s *Store) ListKnownPeers(ctx context.Context) ([]KnownPeer, error)
- func (s *Store) ListMessages(ctx context.Context, peerID string, before MessageCursor, limit int) ([]Message, bool, error)
- func (s *Store) ListOutbox(ctx context.Context, limit int) ([]OutboxEntry, error)
- func (s *Store) ListPausedPeers(ctx context.Context) ([]string, error)
- func (s *Store) ListPublicDiscoveries(ctx context.Context, before string, limit int, familiarOnly bool) (PublicDiscoveryPage, error)
- func (s *Store) MarkAcked(ctx context.Context, messageID string, ackedAt time.Time) error
- func (s *Store) MarkOutboxDelivered(ctx context.Context, messageID string, ackedAt time.Time) error
- func (s *Store) MessageRetention(ctx context.Context) (MessageRetention, error)
- func (s *Store) OutboxStats(ctx context.Context) (OutboxStats, error)
- func (s *Store) Path() string
- func (s *Store) PausePeer(ctx context.Context, peerID string) error
- func (s *Store) RecentMessages(ctx context.Context, limit int) ([]Message, error)
- func (s *Store) RecordOutboxFailure(ctx context.Context, messageID string, attempts int, nextAttempt time.Time, ...) error
- func (s *Store) RecordPublicDiscovery(ctx context.Context, peerID, path, sha256 string, sizeBytes, fetchedAtMS int64, ...) (PublicDiscovery, error)
- func (s *Store) RemoveFriend(ctx context.Context, peerID string, cancelPending bool) (bool, int, error)
- func (s *Store) ResetOutboxPeer(ctx context.Context, peerID string) error
- func (s *Store) ResumePeer(ctx context.Context, peerID string) error
- func (s *Store) SaveInbound(ctx context.Context, messageID, peerID, text string, createdAt time.Time) (bool, error)
- func (s *Store) SaveOutbound(ctx context.Context, messageID, peerID, text string, createdAt time.Time) error
- func (s *Store) SaveOutboundOrigin(ctx context.Context, messageID, peerID, text string, createdAt time.Time, ...) error
- func (s *Store) SaveOutboundWithOutbox(ctx context.Context, messageID, peerID, text, multiaddr string, ...) error
- func (s *Store) SaveOutboundWithOutboxOrigin(ctx context.Context, messageID, peerID, text, multiaddr string, ...) error
- func (s *Store) SetFriendCapabilities(ctx context.Context, peerID string, relay, dht bool) error
- func (s *Store) SetFriendDescription(ctx context.Context, peerID, description string) (Friend, error)
- func (s *Store) SetFriendName(ctx context.Context, peerID, name string) (Friend, error)
- func (s *Store) SetMaxFriends(max int)
- func (s *Store) SetMaxMessages(max int)
- func (s *Store) UpsertFriend(ctx context.Context, peerID string, addrs []string, ...) (Friend, bool, error)
- func (s *Store) UpsertKnownPeer(ctx context.Context, peerID string, addrs []string, source string) error
- func (s *Store) UpsertPeerCache(ctx context.Context, peerID string, addrs []string, source string, ...) error
Constants ¶
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.
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.
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.
const (
// FileName is the SQLite database inside the data directory.
FileName = "raminga.db"
)
Variables ¶
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.
var ErrInvalidCursor = errors.New("storage: invalid cursor")
ErrInvalidCursor reports a malformed or stale pagination cursor.
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.
var ErrOutboxNotFound = errors.New("storage: outbox entry not found")
ErrOutboxNotFound reports an unknown outbox entry.
var FriendNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`)
FriendNamePattern is the existing local-name rule.
Functions ¶
func DecodeDiscoveryCursor ¶
DecodeDiscoveryCursor validates an opaque cursor produced by this package.
func EncodeConversationCursor ¶
func EncodeConversationCursor(c ConversationCursor) string
func EncodeDiscoveryCursor ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 (*Store) CancelOutbox ¶
CancelOutbox cancels a pending entry and persists the cancelled delivery state on the history row. Terminal entries are not cancellable.
func (*Store) CountMessages ¶
CountMessages returns the persisted message row count (diagnostics/tests).
func (*Store) CountPeerCache ¶
CountPeerCache returns the number of cache rows.
func (*Store) CountPublicDiscoveries ¶
CountPublicDiscoveries returns the total and familiar-only counts so a bounded UI scan can say whether it saw every traceable entry.
func (*Store) 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 ¶
DeletePeerCache removes one hint (used by tests/diagnostics).
func (*Store) DueOutbox ¶
DueOutbox returns pending entries whose retry time and expiry are in range.
func (*Store) ExpireOutbox ¶
ExpireOutbox marks every overdue pending entry failed and persists that failed state on the retained history rows. It returns the count.
func (*Store) FailOutbox ¶
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 ¶
FriendsForRestart returns manual, unpaused friends with relay/DHT capability.
func (*Store) GetFriendByName ¶
GetFriendByName resolves a local name.
func (*Store) GetMessage ¶
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) 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 ¶
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 ¶
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 ¶
ListOutbox returns newest-first outbox rows, including terminal states.
func (*Store) ListPausedPeers ¶
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 ¶
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 ¶
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) RecentMessages ¶
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 ¶
ResetOutboxPeer makes pending entries for one peer due immediately, used when that peer reconnects (fresh connectivity resets the backoff wait).
func (*Store) ResumePeer ¶
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 ¶
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 ¶
SetFriendName replaces (or clears, when name is empty) a friend's local name.
func (*Store) SetMaxFriends ¶
SetMaxFriends bounds the friends table. Values <= 0 restore the default.
func (*Store) SetMaxMessages ¶
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.