storage

package
v0.1.0-rc.4 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 22 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 (
	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.

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 (
	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")
)
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 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.

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 DecodeDiscoveryRefreshCursor

func DecodeDiscoveryRefreshCursor(raw string) (at int64, peerID string, err error)

DecodeDiscoveryRefreshCursor validates an opaque cursor produced by this package. An empty cursor starts at the newest candidate.

func DecodeFavoriteCursor

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

DecodeFavoriteCursor validates an opaque favorites cursor.

func EncodeConversationCursor

func EncodeConversationCursor(c ConversationCursor) string

func EncodeDiscoveryCursor

func EncodeDiscoveryCursor(at, id int64) string

EncodeDiscoveryCursor serializes the (fetched_at_ms, id) position.

func EncodeDiscoveryRefreshCursor

func EncodeDiscoveryRefreshCursor(at int64, peerID string) string

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

func EncodeFavoriteCursor(at int64, id string) string

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

func ValidateDraftID(id string) bool

ValidateDraftID constrains the opaque id used by local RPCs. The fixed profile draft id is the only non-generated id.

func ValidateFriendName

func ValidateFriendName(name string) error

ValidateFriendName applies the pre-existing local name rule.

Types

type BootstrapPeer

type BootstrapPeer struct {
	PeerID    string
	Addrs     []string
	SavedAtMS int64
	Paused    bool
}

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

type DiscoveryRefreshPeer struct {
	PeerID        string
	FromDiscovery bool
	FromOutbound  bool
}

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

type FavoritePage struct {
	Items      []Favorite
	NextBefore string
	HasMore    bool
}

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

type MarkReadResult struct {
	State       ReadState
	UnreadCount int
}

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

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 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 Open

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

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

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

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

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

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) ContactCard

func (s *Store) ContactCard(ctx context.Context, peerID string) ([]byte, error)

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) CountUnread

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

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

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) 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

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) 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

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

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

func (*Store) GetBootstrapPeer

func (s *Store) GetBootstrapPeer(ctx context.Context, peerID string) (BootstrapPeer, bool, error)

GetBootstrapPeer reads one saved bootstrap role and its cached addresses.

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) 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 (s *Store) GetProfilePublicationRequest(ctx context.Context, id string) (ProfilePublicationRequest, bool, error)

func (*Store) GetPublicDraft

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

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

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

GetReadState returns the current human cursor, or a zero cursor when the Peer has never been marked read.

func (*Store) ImportBootstrapPeersOnce

func (s *Store) ImportBootstrapPeersOnce(ctx context.Context, seed []string) (int, bool, error)

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) IsPaused

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

IsPaused reports the persistent pause flag.

func (*Store) LatestProfilePublicationTime

func (s *Store) LatestProfilePublicationTime(ctx context.Context) (sql.NullInt64, error)

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

func (s *Store) ListFavorites(ctx context.Context, before string, limit int) (FavoritePage, error)

ListFavorites returns favorites newest first with a stable keyset cursor.

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, 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

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) 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

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) 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

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 and accumulates the acquisition path; a changed SHA-256 is a new version and stays as a separate row.

func (*Store) RemoveBootstrapPeer

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

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

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) SaveContactCard

func (s *Store) SaveContactCard(ctx context.Context, peerID string, seq uint64, envelope []byte) error

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

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) 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

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

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.

Jump to

Keyboard shortcuts

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