repository

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package repository contains all SQL used by Litebox application services.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("record not found")

ErrNotFound is returned when a requested domain record does not exist.

Functions

func ScanJob

func ScanJob(scanner interface{ Scan(...any) error }) (model.Job, error)

ScanJob converts a row into a durable job.

Types

type InboundMessage

type InboundMessage struct {
	MailboxID           string
	MailboxAddressID    string
	ThreadID            string
	ResendEmailID       string
	RFCMessageID        string
	InReplyTo           string
	References          string
	From                model.Address
	Recipients          map[string][]model.Address
	Subject             string
	TextBody            string
	SanitizedHTML       string
	RemoteImagesBlocked bool
	RawStorageKey       string
	ReceivedAt          time.Time
	SizeBytes           int64
	Attachments         []model.Attachment
	IngestStatus        string
}

InboundMessage is the fully archived provider-neutral input for one received email.

type Repository

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

Repository is a concurrency-safe collection of SQLite operations.

func New

func New(database *sql.DB) *Repository

New creates a repository over an initialized database.

func (*Repository) AcceptInvitation added in v0.4.1

func (r *Repository) AcceptInvitation(ctx context.Context, tokenHash []byte, passwordHash string) (model.User, error)

AcceptInvitation atomically creates or reuses the invited user, grants mailbox access, and consumes the single-use token.

func (*Repository) AddDraftAttachment

func (r *Repository) AddDraftAttachment(ctx context.Context, attachment model.Attachment) error

AddDraftAttachment persists metadata after the blob commit succeeds.

func (*Repository) AddMailboxAddress added in v0.2.0

func (r *Repository) AddMailboxAddress(ctx context.Context, mailboxID, value, displayName string) error

AddMailboxAddress creates a sendable and receivable alias.

func (*Repository) AttachmentByID

func (r *Repository) AttachmentByID(ctx context.Context, mailboxID, id string) (model.Attachment, error)

AttachmentByID loads private blob metadata for an authenticated route.

func (*Repository) ClaimJob

func (r *Repository) ClaimJob(ctx context.Context, worker string, lease time.Duration) (model.Job, error)

ClaimJob atomically reclaims expired leases and leases one runnable job.

func (*Repository) CleanupSessions

func (r *Repository) CleanupSessions(ctx context.Context) (int64, error)

CleanupSessions deletes expired session records.

func (*Repository) CompleteJob

func (r *Repository) CompleteJob(ctx context.Context, id string) error

CompleteJob records a successful terminal job state.

func (*Repository) CompleteWebhook

func (r *Repository) CompleteWebhook(ctx context.Context, id, status string) error

CompleteWebhook marks a durable provider event after its job succeeds.

func (*Repository) ConsumePasswordReset added in v0.4.1

func (r *Repository) ConsumePasswordReset(ctx context.Context, tokenHash []byte, passwordHash string) error

ConsumePasswordReset replaces the password and invalidates every session.

func (*Repository) CreateDraft

func (r *Repository) CreateDraft(ctx context.Context, mailboxID string, draft model.Draft) (model.Draft, error)

CreateDraft persists a new editable message.

func (*Repository) CreateFirstUser

func (r *Repository) CreateFirstUser(ctx context.Context, email, displayName, passwordHash string) (model.User, error)

CreateFirstUser atomically creates the installation owner and grants access to the bootstrapped primary mailbox.

func (*Repository) CreateInvitation added in v0.4.1

func (r *Repository) CreateInvitation(ctx context.Context, createdBy, mailboxID, email, displayName, role string, tokenHash []byte, expiresAt time.Time) (model.Invitation, error)

CreateInvitation stores a hashed, expiring invitation for one mailbox. The caller is responsible for delivering the returned raw token.

func (*Repository) CreateMailbox added in v0.2.0

func (r *Repository) CreateMailbox(ctx context.Context, creatorID, value, displayName string) (model.Mailbox, error)

CreateMailbox creates an independent inbox and grants its creator ownership.

func (*Repository) CreatePasswordResetForUser added in v0.4.1

func (r *Repository) CreatePasswordResetForUser(ctx context.Context, userID string, tokenHash []byte, expiresAt time.Time) error

CreatePasswordResetForUser creates a reset token for an enabled user.

func (*Repository) CreateSession

func (r *Repository) CreateSession(ctx context.Context, userID string, tokenHash, csrfHash []byte, expiresAt time.Time, ipHash []byte, userAgent string) (string, error)

CreateSession persists only hashes of browser secrets.

func (*Repository) CreateUserWithMembership added in v0.2.0

func (r *Repository) CreateUserWithMembership(ctx context.Context, creatorID, mailboxID, email, displayName, passwordHash, role string) (model.User, error)

CreateUserWithMembership creates login credentials and grants mailbox access.

func (*Repository) DB

func (r *Repository) DB() *sql.DB

DB exposes the connection pool only to operational commands such as backup.

func (*Repository) DeleteDraft

func (r *Repository) DeleteDraft(ctx context.Context, mailboxID, id string) ([]string, error)

DeleteDraft deletes a draft and returns storage keys that must be removed.

func (*Repository) DeleteDraftAttachment

func (r *Repository) DeleteDraftAttachment(ctx context.Context, mailboxID, draftID, attachmentID string) (string, error)

DeleteDraftAttachment deletes metadata and returns the blob key.

func (*Repository) DeleteMailboxAddress added in v0.2.0

func (r *Repository) DeleteMailboxAddress(ctx context.Context, mailboxID, addressID string) error

DeleteMailboxAddress removes an alias; the primary address is immutable.

func (*Repository) DeleteSession

func (r *Repository) DeleteSession(ctx context.Context, tokenHash []byte) error

DeleteSession revokes one browser session.

func (*Repository) DeleteThread

func (r *Repository) DeleteThread(ctx context.Context, mailboxID, id string) error

DeleteThread permanently removes local rows and schedules idempotent blob deletion.

func (*Repository) DeleteUserSession added in v0.2.0

func (r *Repository) DeleteUserSession(ctx context.Context, userID, sessionID string) error

DeleteUserSession revokes one session owned by a user.

func (*Repository) DigestCounts added in v0.3.1

func (r *Repository) DigestCounts(ctx context.Context, sub model.DigestSubscription, since, until time.Time) (model.DigestCounts, error)

DigestCounts returns metadata counts constrained by user mailbox access.

func (*Repository) DigestSubscriptionByID added in v0.3.1

func (r *Repository) DigestSubscriptionByID(ctx context.Context, id string) (model.DigestSubscription, error)

func (*Repository) DisableDigestSubscription added in v0.3.1

func (r *Repository) DisableDigestSubscription(ctx context.Context, userID string) error

func (*Repository) DraftByID

func (r *Repository) DraftByID(ctx context.Context, mailboxID, id string) (model.Draft, error)

DraftByID loads one draft and its attachments.

func (*Repository) DueDigestSubscriptions added in v0.3.1

func (r *Repository) DueDigestSubscriptions(ctx context.Context) ([]model.DigestSubscription, error)

DueDigestSubscriptions returns enabled subscriptions for the scheduler to evaluate in their own timezone.

func (*Repository) EnqueueJob

func (r *Repository) EnqueueJob(ctx context.Context, kind, dedupeKey, payload string, priority, maxAttempts int, runAfter time.Time) (string, bool, error)

EnqueueJob creates durable work and quietly deduplicates an existing logical job.

func (*Repository) EnsureMailbox

func (r *Repository) EnsureMailbox(ctx context.Context, address, displayName string) (string, error)

EnsureMailbox creates the configured primary mailbox without mutating an existing identity.

func (*Repository) EnsureMailboxAddress added in v0.2.0

func (r *Repository) EnsureMailboxAddress(ctx context.Context, mailboxID, value, displayName string) error

EnsureMailboxAddress adds a configured alias idempotently.

func (*Repository) FailJob

func (r *Repository) FailJob(ctx context.Context, id, message string, retryAt time.Time, permanent bool) error

FailJob records an error and either reschedules or dead-letters the job.

func (*Repository) FailWebhook

func (r *Repository) FailWebhook(ctx context.Context, id, message string) error

FailWebhook stores a safe error summary for operator diagnostics.

func (*Repository) FindInboundThread

func (r *Repository) FindInboundThread(ctx context.Context, mailboxID, inReplyTo, references, subjectNorm, participant string, receivedAt time.Time) (string, error)

FindInboundThread uses message relationships first and a conservative participant fallback second.

func (*Repository) FindSession

func (r *Repository) FindSession(ctx context.Context, tokenHash []byte) (model.Session, error)

FindSession authenticates a non-expired session from its hashed cookie.

func (*Repository) FindUserByEmail

func (r *Repository) FindUserByEmail(ctx context.Context, email string) (model.User, error)

FindUserByEmail finds an enabled user using normalized email comparison.

func (*Repository) GetDigestSubscription added in v0.3.1

func (r *Repository) GetDigestSubscription(ctx context.Context, userID string) (model.DigestSubscription, error)

GetDigestSubscription loads a user's personal summary preference.

func (*Repository) GrantMailboxAccess added in v0.2.0

func (r *Repository) GrantMailboxAccess(ctx context.Context, creatorID, mailboxID, email, role string) error

GrantMailboxAccess gives an existing enabled user access to a mailbox.

func (*Repository) HasUsers

func (r *Repository) HasUsers(ctx context.Context) (bool, error)

HasUsers reports whether first-run setup has completed.

func (*Repository) InvitationByToken added in v0.4.1

func (r *Repository) InvitationByToken(ctx context.Context, tokenHash []byte) (model.Invitation, error)

InvitationByToken returns an unexpired, unused invitation.

func (*Repository) LastBackupTimestamp

func (r *Repository) LastBackupTimestamp(context.Context) time.Time

LastBackupTimestamp is reserved for future backup history; zero means unknown.

func (*Repository) ListDrafts

func (r *Repository) ListDrafts(ctx context.Context, mailboxID string, limit int) ([]model.Draft, error)

ListDrafts returns recent drafts without loading attachment bytes.

func (*Repository) ListJobs

func (r *Repository) ListJobs(ctx context.Context, limit int) ([]model.Job, error)

ListJobs returns recent jobs for diagnostics.

func (*Repository) ListMailboxAddresses added in v0.2.0

func (r *Repository) ListMailboxAddresses(ctx context.Context, mailboxID string) ([]model.MailboxAddress, error)

ListMailboxAddresses returns the primary address followed by aliases.

func (*Repository) ListMailboxMembers added in v0.2.0

func (r *Repository) ListMailboxMembers(ctx context.Context, mailboxID string) ([]model.MailboxMembership, error)

ListMailboxMembers returns all users assigned to one mailbox.

func (*Repository) ListMailboxesForUser added in v0.2.0

func (r *Repository) ListMailboxesForUser(ctx context.Context, userID string) ([]model.Mailbox, error)

ListMailboxesForUser returns every mailbox visible to a user, with the membership role attached. The primary installation mailbox sorts first.

func (*Repository) ListSessions added in v0.2.0

func (r *Repository) ListSessions(ctx context.Context, userID string) ([]model.Session, error)

ListSessions returns active browser sessions for one user.

func (*Repository) ListThreads

func (r *Repository) ListThreads(ctx context.Context, mailboxID, folder string, limit int) ([]model.ThreadSummary, error)

ListThreads returns a bounded folder projection ordered by latest activity.

func (*Repository) ListThreadsPage

func (r *Repository) ListThreadsPage(ctx context.Context, mailboxID, folder string, limit int, before time.Time, beforeID string) ([]model.ThreadSummary, bool, error)

ListThreadsPage returns one keyset-paginated folder page. The cursor is the final (latest_message_at, id) tuple from the preceding page.

func (*Repository) ListWebhooks

func (r *Repository) ListWebhooks(ctx context.Context, limit int) ([]model.WebhookEvent, error)

ListWebhooks returns recent verified webhook deliveries.

func (*Repository) MailboxAddressForRecipients added in v0.3.1

func (r *Repository) MailboxAddressForRecipients(ctx context.Context, mailboxID string, recipients []model.Address) (model.MailboxAddress, error)

MailboxAddressForRecipients resolves the first enabled local alias that a provider message was addressed to. The result is used only for presentation; mailbox routing has already been validated by MailboxesForRecipients.

func (*Repository) MailboxAddressSet added in v0.2.0

func (r *Repository) MailboxAddressSet(ctx context.Context, mailboxID string) (map[string]struct{}, error)

MailboxAddressSet returns every local address for reply-all de-duplication.

func (*Repository) MailboxByID added in v0.2.0

func (r *Repository) MailboxByID(ctx context.Context, mailboxID string) (model.Mailbox, error)

MailboxByID returns one mailbox without applying user authorization. It is intended for provider-side routing and background jobs.

func (*Repository) MailboxForUser added in v0.2.0

func (r *Repository) MailboxForUser(ctx context.Context, userID, preferredID string) (model.Mailbox, error)

MailboxForUser resolves an authorized mailbox. An inaccessible or empty preference falls back to the user's first mailbox, avoiding a mailbox oracle.

func (*Repository) MailboxRoleForUser added in v0.2.0

func (r *Repository) MailboxRoleForUser(ctx context.Context, mailboxID, userID string) (string, error)

MailboxRoleForUser returns one membership role.

func (*Repository) MailboxesForRecipients added in v0.2.0

func (r *Repository) MailboxesForRecipients(ctx context.Context, recipients []model.Address) ([]model.Mailbox, error)

MailboxesForRecipients resolves every enabled local recipient to its mailbox.

func (*Repository) MarkDigestAttempt added in v0.4.1

func (r *Repository) MarkDigestAttempt(ctx context.Context, subscriptionID string, counts model.DigestCounts, attemptedAt time.Time, deliveryErr error) error

MarkDigestAttempt records metadata-only counts and the outcome of a digest delivery attempt. It never stores message content.

func (*Repository) MarkDigestSent added in v0.3.1

func (r *Repository) MarkDigestSent(ctx context.Context, subscriptionID string, sentAt time.Time) error

func (*Repository) MarkMessageSendError

func (r *Repository) MarkMessageSendError(ctx context.Context, id, code, message string, permanent bool) error

MarkMessageSendError stores a safe provider failure for display.

func (*Repository) MarkMessageSubmitted

func (r *Repository) MarkMessageSubmitted(ctx context.Context, id, resendID string) error

MarkMessageSubmitted records the provider resource ID after an idempotent send.

func (*Repository) MarkThreadRead

func (r *Repository) MarkThreadRead(ctx context.Context, mailboxID, id string, read bool) error

MarkThreadRead changes all inbound messages and refreshes the denormalized count.

func (*Repository) MessageDelivery

func (r *Repository) MessageDelivery(ctx context.Context, resendID string) (string, time.Time, error)

MessageDelivery returns the current aggregate status and provider event timestamp.

func (*Repository) OutboundMessage

func (r *Repository) OutboundMessage(ctx context.Context, id string) (model.Message, error)

OutboundMessage loads one queued/sending message for a provider adapter.

func (*Repository) PersistWebhook

func (r *Repository) PersistWebhook(ctx context.Context, event model.WebhookEvent, providerCreatedAt time.Time, jobKind, dedupeKey string, payload any) (bool, error)

PersistWebhook stores a verified payload and its durable processing job in one transaction.

func (*Repository) Ping

func (r *Repository) Ping(ctx context.Context) error

Ping checks database readiness.

func (*Repository) PrimaryMailbox

func (r *Repository) PrimaryMailbox(ctx context.Context) (model.Mailbox, error)

PrimaryMailbox returns the current persisted mailbox identity.

func (*Repository) PrimaryMailboxID

func (r *Repository) PrimaryMailboxID(ctx context.Context) (string, error)

PrimaryMailboxID returns the configured primary mailbox database ID.

func (*Repository) QueueDraft

func (r *Repository) QueueDraft(ctx context.Context, draftID, mailboxID string, from model.Address) (messageID, threadID string, err error)

QueueDraft turns a draft into a locally durable outbound message and job.

func (*Repository) ReferencedBlobs

func (r *Repository) ReferencedBlobs(ctx context.Context) (map[string]string, error)

ReferencedBlobs lists every logical object required by the SQLite state.

func (*Repository) Reindex

func (r *Repository) Reindex(ctx context.Context) error

Reindex rebuilds the FTS table from normalized message rows.

func (*Repository) RemoveMailboxAccess added in v0.2.0

func (r *Repository) RemoveMailboxAccess(ctx context.Context, actorID, mailboxID, userID string) error

RemoveMailboxAccess revokes a membership while protecting the last owner.

func (*Repository) RetryJob

func (r *Repository) RetryJob(ctx context.Context, id string) error

RetryJob returns a failed/dead job to the queue without erasing its history.

func (*Repository) SaveDigestSubscription added in v0.3.1

func (r *Repository) SaveDigestSubscription(ctx context.Context, sub model.DigestSubscription) error

SaveDigestSubscription validates and replaces one user's preference. Selected mailboxes must already be visible to that user.

func (*Repository) SaveDraft

func (r *Repository) SaveDraft(ctx context.Context, mailboxID string, draft model.Draft) error

SaveDraft validates and stores editable fields.

func (*Repository) SaveInbound

func (r *Repository) SaveInbound(ctx context.Context, input InboundMessage) (string, string, error)

SaveInbound atomically finalizes a locally archived message and its search index.

func (*Repository) SearchThreads

func (r *Repository) SearchThreads(ctx context.Context, mailboxID string, query search.Query, limit int) ([]model.ThreadSummary, error)

SearchThreads runs FTS and structured filters with parameterized values.

func (*Repository) SearchThreadsPage

func (r *Repository) SearchThreadsPage(ctx context.Context, mailboxID string, query search.Query, limit int, before time.Time, beforeID string) ([]model.ThreadSummary, bool, error)

SearchThreadsPage runs FTS and structured filters with keyset pagination.

func (*Repository) SenderForMailbox added in v0.2.0

func (r *Repository) SenderForMailbox(ctx context.Context, mailboxID, requested string) (model.Address, error)

SenderForMailbox validates a requested From identity against enabled aliases.

func (*Repository) StoreProviderEvent

func (r *Repository) StoreProviderEvent(ctx context.Context, svixID, resendID, eventType, payload, status string, eventAt time.Time) error

StoreProviderEvent deduplicates a delivery event and advances an outbound message state.

func (*Repository) SystemStats

func (r *Repository) SystemStats(ctx context.Context, databasePath string) (model.SystemStats, error)

SystemStats returns inexpensive, secret-free operational measurements.

func (*Repository) ThreadAction

func (r *Repository) ThreadAction(ctx context.Context, mailboxID, id, action string) error

ThreadAction applies one explicit mailbox state transition.

func (*Repository) ThreadByID

func (r *Repository) ThreadByID(ctx context.Context, mailboxID, id string) (model.Thread, error)

ThreadByID loads a conversation and all of its normalized metadata.

func (*Repository) TouchSession

func (r *Repository) TouchSession(ctx context.Context, sessionID, userID string, login bool) error

TouchSession records bounded activity and login metadata.

func (*Repository) Transaction

func (r *Repository) Transaction(ctx context.Context, work func(*sql.Tx) error) error

Transaction runs work atomically.

func (*Repository) UpdateAddressColor added in v0.3.1

func (r *Repository) UpdateAddressColor(ctx context.Context, mailboxID, addressID, color string) error

UpdateAddressColor changes the display color without changing routing.

func (*Repository) UpdateMailboxDisplayName

func (r *Repository) UpdateMailboxDisplayName(ctx context.Context, mailboxID, displayName string) error

UpdateMailboxDisplayName changes the human-facing name of one mailbox and its primary sender identity.

func (*Repository) UpdatePassword

func (r *Repository) UpdatePassword(ctx context.Context, email, hash string) error

UpdatePassword replaces a user's password and revokes all active sessions.

func (*Repository) UpdatePrimaryMailbox added in v0.3.1

func (r *Repository) UpdatePrimaryMailbox(ctx context.Context, value, displayName string) error

UpdatePrimaryMailbox changes the bootstrap mailbox identity during setup.

func (*Repository) UserForPasswordReset added in v0.4.1

func (r *Repository) UserForPasswordReset(ctx context.Context, tokenHash []byte) (model.User, error)

UserForPasswordReset returns the target user when a token is valid.

func (*Repository) WebhookByID

func (r *Repository) WebhookByID(ctx context.Context, id string) (model.WebhookEvent, error)

WebhookByID loads one verified event for worker processing.

Jump to

Keyboard shortcuts

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