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 DecodeDiscoveryRefreshCursor(raw string) (at int64, peerID string, err error)
- func DecodeFavoriteCursor(raw string) (at int64, id string, err error)
- func EncodeConversationCursor(c ConversationCursor) string
- func EncodeDiscoveryCursor(at, id int64) string
- func EncodeDiscoveryRefreshCursor(at int64, peerID string) string
- func EncodeDraftCursor(d PublicDraft) string
- func EncodeFavoriteCursor(at int64, id string) string
- func EncodeMessageCursor(c MessageCursor) string
- func ValidateDraftID(id string) bool
- func ValidateFriendName(name string) error
- type BootstrapPeer
- type ConversationCursor
- type ConversationSummary
- type DiscoveryRefreshPeer
- type DiscoveryRefreshPeerPage
- type Favorite
- type FavoritePage
- type Friend
- type HumanOutboundPeer
- type KnownPeer
- type MarkReadResult
- type Message
- type MessageCursor
- type MessageRetention
- type OutboxEntry
- type OutboxStats
- type ProfilePublicationRequest
- type PublicDiscovery
- type PublicDiscoveryPage
- type PublicDraft
- type PublicDraftAsset
- type ReadState
- type Store
- func (s *Store) AddBootstrapPeer(ctx context.Context, raw string, more ...string) (BootstrapPeer, bool, error)
- func (s *Store) BeginProfilePublication(ctx context.Context, r ProfilePublicationRequest) error
- func (s *Store) BootstrapImported(ctx context.Context) (bool, error)
- func (s *Store) CancelOutbox(ctx context.Context, messageID string) (bool, error)
- func (s *Store) Close() error
- func (s *Store) ContactCard(ctx context.Context, peerID string) ([]byte, 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) CountUnread(ctx context.Context, peerID string) (int, error)
- func (s *Store) CreatePublicDraft(ctx context.Context, d PublicDraft) (PublicDraft, error)
- func (s *Store) DB() *sql.DB
- func (s *Store) DeletePeerCache(ctx context.Context, peerID string) error
- func (s *Store) DeletePublicDraft(ctx context.Context, id string, expectedRevision int64) (bool, 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) FindPublicDraftByPublishedPath(ctx context.Context, rel string) (PublicDraft, bool, error)
- func (s *Store) FinishProfilePublication(ctx context.Context, r ProfilePublicationRequest, profilePath string, ...) error
- func (s *Store) FriendsForRestart(ctx context.Context, limit int) ([]Friend, error)
- func (s *Store) GetBootstrapPeer(ctx context.Context, peerID string) (BootstrapPeer, bool, 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) GetPeerMessage(ctx context.Context, peerID, messageID string) (Message, bool, error)
- func (s *Store) GetProfilePublicationRequest(ctx context.Context, id string) (ProfilePublicationRequest, bool, error)
- func (s *Store) GetPublicDraft(ctx context.Context, id string) (PublicDraft, bool, error)
- func (s *Store) GetPublicDraftAsset(ctx context.Context, draftID, assetID string) (PublicDraftAsset, bool, error)
- func (s *Store) GetReadState(ctx context.Context, peerID string) (ReadState, error)
- func (s *Store) ImportBootstrapPeersOnce(ctx context.Context, seed []string) (int, bool, error)
- func (s *Store) IsPaused(ctx context.Context, peerID string) bool
- func (s *Store) LatestProfilePublicationTime(ctx context.Context) (sql.NullInt64, error)
- func (s *Store) ListBootstrapPeers(ctx context.Context) ([]BootstrapPeer, error)
- func (s *Store) ListConversations(ctx context.Context, before ConversationCursor, limit int) ([]ConversationSummary, bool, int64, error)
- func (s *Store) ListDiscoveryRefreshPeers(ctx context.Context, familiarOnly bool, limit int, after string) (DiscoveryRefreshPeerPage, error)
- func (s *Store) ListFavorites(ctx context.Context, before string, limit int) (FavoritePage, 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) ListPublicDrafts(ctx context.Context, kind, before string, limit int) ([]PublicDraft, bool, error)
- func (s *Store) MarkAcked(ctx context.Context, messageID string, ackedAt time.Time) error
- func (s *Store) MarkConversationRead(ctx context.Context, peerID, messageID string, nowMS int64) (MarkReadResult, 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) PendingProfilePublication(ctx context.Context, sha string) (ProfilePublicationRequest, bool, error)
- func (s *Store) PublicDiscoveryExists(ctx context.Context, peerID, publicPath, sha256 string) (bool, error)
- func (s *Store) PutPublicDraftAsset(ctx context.Context, a PublicDraftAsset) (PublicDraftAsset, 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) RemoveBootstrapPeer(ctx context.Context, peerID string) (bool, 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) SaveContactCard(ctx context.Context, peerID string, seq uint64, envelope []byte) 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) SetFavorite(ctx context.Context, peerID, publicPath, sha256, title string, nowMS int64, ...) (Favorite, bool, 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) SetPublicDraftPublished(ctx context.Context, id string, revision int64, ...) error
- func (s *Store) TotalUnread(ctx context.Context) (int, error)
- func (s *Store) UpdatePublicDraft(ctx context.Context, d PublicDraft, expectedRevision int64) (PublicDraft, error)
- 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 ( DraftKindProfile = "profile" DraftKindPost = "post" DraftAuthorUser = "user" DraftAuthorAgent = "agent" MaxPublicDraftsPerKind = 100 MaxDraftImageBytes = 64 << 20 MaxDraftImageCount = 4 )
Public draft kinds. A profile draft is private until the user publishes it; a post draft similarly never enters public/ before publish.
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 ( ErrDraftNotFound = errors.New("storage: public draft not found") ErrDraftConflict = errors.New("storage: public draft revision conflict") ErrDraftLimit = errors.New("storage: public draft limit reached") ErrDraftAsset = errors.New("storage: public draft asset limit reached") )
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 ErrMessageNotFound = errors.New("storage: message not found for peer")
ErrMessageNotFound reports that a requested message ID does not belong to the stated Peer in the currently retained history.
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 DecodeDiscoveryRefreshCursor ¶
DecodeDiscoveryRefreshCursor validates an opaque cursor produced by this package. An empty cursor starts at the newest candidate.
func DecodeFavoriteCursor ¶
DecodeFavoriteCursor validates an opaque favorites cursor.
func EncodeConversationCursor ¶
func EncodeConversationCursor(c ConversationCursor) string
func EncodeDiscoveryCursor ¶
EncodeDiscoveryCursor serializes the (fetched_at_ms, id) position.
func EncodeDiscoveryRefreshCursor ¶
EncodeDiscoveryRefreshCursor serializes the stable (last_at, peer_id) position used by the refresh candidate scheduler.
func EncodeDraftCursor ¶
func EncodeDraftCursor(d PublicDraft) string
EncodeDraftCursor returns an opaque cursor for ListPublicDrafts.
func EncodeFavoriteCursor ¶
EncodeFavoriteCursor serializes the (created_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 ValidateDraftID ¶
ValidateDraftID constrains the opaque id used by local RPCs. The fixed profile draft id is the only non-generated id.
func ValidateFriendName ¶
ValidateFriendName applies the pre-existing local name rule.
Types ¶
type BootstrapPeer ¶
BootstrapPeer is one ordinary peer record carrying the bootstrap role. Addrs are the stored peer-cache addresses, Paused is the existing explicit disconnect state, and SavedAtMS is when the role first appeared. Online is deliberately not part of this record: it is a live network fact, not a stored setting.
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
UnreadCount int
LastReadMessageID string
LastReadAtMS int64
}
ConversationSummary is one Peer's latest retained message.
type DiscoveryRefreshPeer ¶
DiscoveryRefreshPeer is one bounded local Feed refresh candidate. It is a local relation/index fact, not a remote recommendation or online claim.
type DiscoveryRefreshPeerPage ¶
type DiscoveryRefreshPeerPage struct {
Peers []DiscoveryRefreshPeer
Total int
Truncated bool
HasMore bool
NextAfter string
}
DiscoveryRefreshPeerPage is one bounded snapshot of refresh candidates. Total is the complete count before Limit; Truncated means the returned page is smaller than Total. HasMore and NextAfter let a repeat refresh advance through the complete set instead of always rechecking the first page.
type Favorite ¶
type Favorite struct {
ID string
PeerID string
Path string
SHA256 string
Title string
CreatedAtMS int64
}
Favorite is one privately retained public-post bookmark. The unique key is only (peer_id, path, sha256): messages, contacts and private notes cannot be represented here.
type FavoritePage ¶
FavoritePage is one keyset page of favorites, newest first.
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
// UnreadCount is a read-only view derived from the shared message cursor.
// It is never stored on the friends row.
UnreadCount int
}
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 MarkReadResult ¶
MarkReadResult is one monotonic cursor update and the remaining unread count.
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 ProfilePublicationRequest ¶
type ProfilePublicationRequest struct {
RequestID string
DraftCreatedAtMS int64
Revision int64
BaseSHA256 string
PublishedAtNS int64
TargetSHA256 string
FilesJSON []byte
ReceiptJSON []byte
}
ProfilePublicationRequest records the private intent before any public files are written. An empty receipt indicates an interrupted attempt.
type PublicDiscovery ¶
type PublicDiscovery struct {
ID int64
PeerID string
Path string
SHA256 string
SizeBytes int64
FetchedAtMS int64
// Source is the most recent local acquisition path. Sources keeps every
// distinct acquisition path for this exact (peer, path, sha256) version.
Source string
Sources []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 PublicDraft ¶
type PublicDraft struct {
DraftID string
Kind string
AuthorKind string
Revision int64
AgentName string
AgentDescription string
AgentInterests []string
AgentConversationStyle string
HumanName string
HumanBioMarkdown string
HumanAvatarAssetID string
AvatarAssetID string
Title string
BodyMarkdown string
Tags []string
ImageAssetIDs []string
PublishedPath string
PublishedSHA256 string
PublishedRevision int64
CreatedAt time.Time
UpdatedAt time.Time
}
PublicDraft is one private SQLite draft. Published* is metadata about the last successful public commit; the bytes themselves live in public/.
type PublicDraftAsset ¶
type PublicDraftAsset struct {
AssetID string
DraftID string
Role string
SHA256 string
Mime string
Width int
Height int
SizeBytes int64
Bytes []byte
CreatedAt time.Time
}
PublicDraftAsset is one image/avatar blob stored privately in SQLite.
type ReadState ¶
type ReadState struct {
PeerID string
LastReadAtMS int64
LastReadMessageID string
UpdatedAtMS int64
}
ReadState is the human read cursor for one Peer. The timestamp is the authoritative boundary; last_read_message_id is the public, human-readable position at that same millisecond. Same-millisecond messages are treated as one read batch.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the SQLite handle.
func (*Store) AddBootstrapPeer ¶
func (s *Store) AddBootstrapPeer(ctx context.Context, raw string, more ...string) (BootstrapPeer, bool, error)
AddBootstrapPeer validates a peer's addresses, merges them into the ordinary peer cache and adds the bootstrap role. Re-adding the same peer/address is idempotent; the bool reports whether the persisted list changed. It never dials, publishes, or changes contact/pause records.
func (*Store) BeginProfilePublication ¶
func (s *Store) BeginProfilePublication(ctx context.Context, r ProfilePublicationRequest) error
func (*Store) BootstrapImported ¶
BootstrapImported reports whether the one-time legacy/preset import has already committed. It is read before config recovery so a missing config cannot resolve a new official preset over an existing database marker.
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) ContactCard ¶
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) CountUnread ¶
CountUnread returns the number of retained inbound messages newer than the shared human cursor.
func (*Store) CreatePublicDraft ¶
func (s *Store) CreatePublicDraft(ctx context.Context, d PublicDraft) (PublicDraft, error)
CreatePublicDraft inserts a new private draft. Creation of a second profile draft is rejected; the fixed id "profile" is the only profile draft.
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) DeletePublicDraft ¶
func (s *Store) DeletePublicDraft(ctx context.Context, id string, expectedRevision int64) (bool, error)
DeletePublicDraft removes one draft and its private assets when the revision matches. A stale caller must reload instead of deleting a newer draft.
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) FindPublicDraftByPublishedPath ¶
func (s *Store) FindPublicDraftByPublishedPath(ctx context.Context, rel string) (PublicDraft, bool, error)
FindPublicDraftByPublishedPath returns the newest private draft whose last public target is exactly rel. Import uses this to reopen the same edit draft instead of creating a second copy for an already published post.
func (*Store) FinishProfilePublication ¶
func (s *Store) FinishProfilePublication(ctx context.Context, r ProfilePublicationRequest, profilePath string, receipt []byte) error
FinishProfilePublication remembers the exact receipt and updates the draft together. The draft can have a newer private revision, or have been deleted entirely, while the public files from this attempt remain committed.
func (*Store) FriendsForRestart ¶
FriendsForRestart returns manual, unpaused friends with relay/DHT capability.
func (*Store) GetBootstrapPeer ¶
GetBootstrapPeer reads one saved bootstrap role and its cached addresses.
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) GetPeerMessage ¶
func (s *Store) GetPeerMessage(ctx context.Context, peerID, messageID string) (Message, bool, error)
GetPeerMessage returns one retained message scoped to a Peer.
func (*Store) GetProfilePublicationRequest ¶
func (*Store) GetPublicDraft ¶
GetPublicDraft returns one draft.
func (*Store) GetPublicDraftAsset ¶
func (s *Store) GetPublicDraftAsset(ctx context.Context, draftID, assetID string) (PublicDraftAsset, bool, error)
GetPublicDraftAsset returns one private asset for publication.
func (*Store) GetReadState ¶
GetReadState returns the current human cursor, or a zero cursor when the Peer has never been marked read.
func (*Store) ImportBootstrapPeersOnce ¶
ImportBootstrapPeersOnce consumes the legacy TOML bootstrap list (including the first-run release preset) exactly once. It returns the number of roles seeded and whether this call performed the one-time import. A marker is written even for an empty list, so an explicit clear or opt-out can never be undone by a later restart or config edit.
func (*Store) LatestProfilePublicationTime ¶
func (*Store) ListBootstrapPeers ¶
func (s *Store) ListBootstrapPeers(ctx context.Context) ([]BootstrapPeer, error)
ListBootstrapPeers returns saved bootstrap roles with ordinary peer-cache addresses and the existing persistent pause flag. The order is stable: role creation time, then Peer ID; addresses are sorted.
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) ListDiscoveryRefreshPeers ¶
func (s *Store) ListDiscoveryRefreshPeers(ctx context.Context, familiarOnly bool, limit int, after string) (DiscoveryRefreshPeerPage, error)
ListDiscoveryRefreshPeers returns the bounded local candidate set for an explicit Feed refresh. The discovery branch only counts versioned-post acquisitions; the outbound branch reuses the same durable human relation and retained real Agent outbound evidence as familiarPeerCondition. Contacts, inbound messages, profile visits and last_interaction never qualify.
func (*Store) ListFavorites ¶
ListFavorites returns favorites newest first with a stable keyset cursor.
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, peerID string, postCandidatesOnly 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. postCandidatesOnly restricts the keyset page itself to post-shaped paths; callers that omit it (old clients) still receive every file. The default false keeps that legacy mixed-page contract.
func (*Store) ListPublicDrafts ¶
func (s *Store) ListPublicDrafts(ctx context.Context, kind, before string, limit int) ([]PublicDraft, bool, error)
ListPublicDrafts returns newest-first private drafts and whether more exist.
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) MarkConversationRead ¶
func (s *Store) MarkConversationRead(ctx context.Context, peerID, messageID string, nowMS int64) (MarkReadResult, error)
MarkConversationRead advances the human cursor monotonically through one retained message. A message belongs to the stated Peer and may be inbound or outbound (the newest message the human actually saw). A lower timestamp never moves the cursor backwards; an equal timestamp only records the message ID without widening the read boundary.
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) PendingProfilePublication ¶
func (s *Store) PendingProfilePublication(ctx context.Context, sha string) (ProfilePublicationRequest, bool, error)
PendingProfilePublication matches the public metadata, so a later publish can finish recording the previous commit before replacing it.
func (*Store) PublicDiscoveryExists ¶
func (s *Store) PublicDiscoveryExists(ctx context.Context, peerID, publicPath, sha256 string) (bool, error)
PublicDiscoveryExists reports whether one exact remote post version is recorded as verified local acquisition evidence.
func (*Store) PutPublicDraftAsset ¶
func (s *Store) PutPublicDraftAsset(ctx context.Context, a PublicDraftAsset) (PublicDraftAsset, error)
PutPublicDraftAsset stores one role asset and enforces the private quota. Bytes are copied into SQLite; no public file is created.
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 and accumulates the acquisition path; a changed SHA-256 is a new version and stays as a separate row.
func (*Store) RemoveBootstrapPeer ¶
RemoveBootstrapPeer removes only the bootstrap role. Peer addresses, friend history/contact semantics, other roles and the explicit-disconnect record are preserved. A non-member is an idempotent no-op (removed=false).
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) SaveContactCard ¶
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) SetFavorite ¶
func (s *Store) SetFavorite(ctx context.Context, peerID, publicPath, sha256, title string, nowMS int64, favorite bool) (Favorite, bool, error)
SetFavorite is idempotent for one (peer, path, sha256) key. Clearing an absent key succeeds with an empty item and favorite=false; it never errors.
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) SetPublicDraftPublished ¶
func (s *Store) SetPublicDraftPublished(ctx context.Context, id string, revision int64, publishedPath, publishedSHA string) error
SetPublicDraftPublished records the committed public metadata. It is called only inside the publication critical section after the public files exist.
func (*Store) TotalUnread ¶
TotalUnread returns the sum of the same unread definition used by ListConversations and ListFriends. It counts every retained Peer, not only the current page.
func (*Store) UpdatePublicDraft ¶
func (s *Store) UpdatePublicDraft(ctx context.Context, d PublicDraft, expectedRevision int64) (PublicDraft, error)
UpdatePublicDraft replaces editable fields and increments revision only when expectedRevision matches. It never changes kind or published_* metadata.
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.