db

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 30, 2026 License: AGPL-3.0 Imports: 18 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

Index

Constants

View Source
const (
	LinkArchiveStateCreated         = "created"
	LinkArchiveStateUploading       = "uploading"
	LinkArchiveStateUploadPaused    = "upload_paused"
	LinkArchiveStateUploaded        = "uploaded"
	LinkArchiveStateAvailable       = "available"
	LinkArchiveStateImporting       = "importing"
	LinkArchiveStateImportPaused    = "import_paused"
	LinkArchiveStateImported        = "imported"
	LinkArchiveStateAcknowledged    = "acknowledged"
	LinkArchiveStateAborted         = "aborted"
	LinkArchiveStateExpired         = "expired"
	LinkArchiveStateTerminalFailure = "terminal_failure"
)

Lifecycle states stored in link_archives.state. Mirrors the state machine in /home/yarin/hush/answer.md and the CHECK constraint in migration 000032.

Variables

View Source
var ErrInstanceUserLimitReached = errors.New("instance user registration limit reached")

ErrInstanceUserLimitReached is returned when instance_config.max_registered_users would be exceeded by creating a new persisted user.

View Source
var ErrLinkArchiveChunkConflict = errors.New("link archive chunk conflict")

ErrLinkArchiveChunkConflict is returned by InsertLinkArchiveChunk when a chunk for (archiveID, idx) already exists with a different hash. Callers surface this as a 409 Conflict; the row is left untouched.

View Source
var ErrLinkArchiveExpired = errors.New("link archive expired")

ErrLinkArchiveExpired is returned by lookup helpers when the archive row is past its expiry or hard deadline. Treated as 404 to avoid leaking existence information.

LinkArchiveActiveStates is the set of states that count toward the per-user concurrent-archive quota and the per-instance staging-bytes ceiling. A row in any of these states is "live" — it is reserving server resources.

Functions

This section is empty.

Types

type AuditLogFilter

type AuditLogFilter struct {
	Action   string // Filter by action type (e.g. "kick", "ban", "mute"). Empty = no filter.
	ActorID  string // Filter by actor user ID. Empty = no filter.
	TargetID string // Filter by target user ID. Empty = no filter.
}

AuditLogFilter holds optional filter parameters for ListAuditLog.

type GcEligibleLinkArchive

type GcEligibleLinkArchive struct {
	ID         string
	State      string
	StorageKey string // first chunk's storage backend; same for every chunk in current MVP
}

GcEligibleLinkArchive describes one row the supervisor purger should reap. Carries enough metadata for the caller to delete the chunk bytes from the storage backend before the DB row.

type InstanceAuditLogFilter

type InstanceAuditLogFilter struct {
	Action   string
	TargetID string
}

InstanceAuditLogFilter filters instance audit log queries.

type LinkArchive

type LinkArchive struct {
	ID                string
	UserID            string // empty for legacy MVP rows; new inserts always populate
	UploadTokenHash   []byte
	DownloadTokenHash []byte
	TotalChunks       int
	TotalBytes        int64
	ChunkSize         int
	ManifestHash      []byte
	ArchiveSHA256     []byte
	Finalized         bool   // legacy boolean; State is the authoritative lifecycle field
	State             string // see LinkArchiveState* constants
	CreatedAt         time.Time
	ExpiresAt         time.Time
	HardDeadlineAt    time.Time
}

LinkArchive is the metadata row that backs a chunked device-link transfer. Token columns hold SHA-256 of the raw bearer tokens; the raw bytes never touch persistent storage. Callers compare by hashing the inbound bearer.

type LinkArchiveChunkInsert

type LinkArchiveChunkInsert struct {
	ArchiveID      string
	Idx            int
	ChunkSize      int
	ChunkHash      []byte
	StorageBackend string
	StorageKey     string
}

LinkArchiveChunkInsert is the parameter struct for InsertLinkArchiveChunk.

type LinkArchiveChunkRow

type LinkArchiveChunkRow struct {
	Idx            int
	ChunkSize      int
	ChunkHash      []byte
	StorageBackend string
	StorageKey     string
}

LinkArchiveChunkRow describes a stored archive chunk for verification.

type LinkArchiveInsert

type LinkArchiveInsert struct {
	UserID            string
	UploadTokenHash   []byte
	DownloadTokenHash []byte
	TotalChunks       int
	TotalBytes        int64
	ChunkSize         int
	ManifestHash      []byte
	ArchiveSHA256     []byte
	ExpiresAt         time.Time
	HardDeadlineAt    time.Time
}

LinkArchiveInsert is the parameter struct for InsertLinkArchive. The previous positional signature was already five-argument heavy; bundling keeps call sites readable when more fields are added.

type MLSCommitRow

type MLSCommitRow struct {
	Epoch       int64
	CommitBytes []byte
	SenderID    string
	CreatedAt   time.Time
}

MLSCommitRow represents one row from the mls_commits table.

type PendingWelcomeRow

type PendingWelcomeRow struct {
	ID           string
	ChannelID    string
	WelcomeBytes []byte
	SenderID     string
	Epoch        int64
	CreatedAt    time.Time
}

PendingWelcomeRow represents one row from the mls_pending_welcomes table.

type Pool

type Pool struct {
	*pgxpool.Pool
}

Pool wraps pgxpool.Pool for dependency injection.

func Open

func Open(ctx context.Context, databaseURL string) (*Pool, error)

Open opens a PostgreSQL connection pool. Caller must call Close when done.

func SetupTestDB

func SetupTestDB(t *testing.T) (*Pool, func())

SetupTestDB runs migrations on the test database and returns a pool and cleanup function. Skips the test if TEST_DATABASE_URL is not set so unit tests without a DB still run. Caller should defer cleanup() to close the pool. For repeatable tests, truncate tables at the start of the test (see TestPool_Integration).

func (*Pool) AddFederatedServerMember

func (p *Pool) AddFederatedServerMember(ctx context.Context, serverID, federatedIdentityID string, permissionLevel int) error

AddFederatedServerMember inserts a guild membership record for a federated (foreign-instance) user.

func (*Pool) AddServerMember

func (p *Pool) AddServerMember(ctx context.Context, serverID, userID string, permissionLevel int) error

AddServerMember inserts a new guild membership record with the given permission level.

func (*Pool) AppendMLSCommit

func (p *Pool) AppendMLSCommit(ctx context.Context, channelID string, epoch int64, commitBytes []byte, senderID string) error

AppendMLSCommit inserts a Commit into the commit queue for a channel under the active server ciphersuite.

func (*Pool) BackfillRootDeviceKey

func (p *Pool) BackfillRootDeviceKey(ctx context.Context, userID, deviceID, label string, devicePublicKey []byte) (bool, error)

BackfillRootDeviceKey inserts a device key row only when no row exists for (userID, deviceID). Used by the post-/verify backfill path so a legitimate root-key holder cannot rewrite an already-certified device's public key by re-presenting /verify with the same deviceID.

Returns (true, nil) when a row was inserted. Returns (false, nil) when a row already existed (and was left untouched). Returns (false, err) only on hard DB failures.

func (*Pool) ChunkBlobExists

func (p *Pool) ChunkBlobExists(ctx context.Context, storageKey string) (bool, error)

ChunkBlobExists is a cheap existence probe.

func (*Pool) ClaimInviteUse

func (p *Pool) ClaimInviteUse(ctx context.Context, code string) (bool, error)

ClaimInviteUse atomically increments uses if the invite is still valid (not expired, under max). Returns true if the use was claimed, false if the invite is exhausted or expired.

func (*Pool) ConsumeAuthNonce

func (p *Pool) ConsumeAuthNonce(ctx context.Context, nonce string) ([]byte, error)

ConsumeAuthNonce atomically deletes and returns the public key stored with nonce if and only if the nonce exists and has not yet expired. Returns pgx.ErrNoRows (which satisfies errors.Is(err, sql.ErrNoRows)) when the nonce is absent or expired.

func (*Pool) ConsumeMLSKeyPackage

func (p *Pool) ConsumeMLSKeyPackage(ctx context.Context, userID, deviceID string) ([]byte, error)

ConsumeMLSKeyPackage atomically marks one unused, non-expired, non-last-resort KeyPackage as consumed and returns its bytes. Only packages stamped with the current server ciphersuite are eligible; legacy-suite rows are invisible to this query so a client running the current protocol never receives state from an incompatible suite. If no regular packages remain, the call falls back to the last-resort package for the same suite (without marking it consumed - it is reusable). Returns (nil, nil) when no eligible package is available.

func (*Pool) CountActiveLinkArchivesForUser

func (p *Pool) CountActiveLinkArchivesForUser(ctx context.Context, userID string) (int, error)

CountActiveLinkArchivesForUser returns the number of non-terminal archives the user owns. Used by the per-user concurrent quota check.

func (*Pool) CountInstanceAdmins

func (p *Pool) CountInstanceAdmins(ctx context.Context) (int, error)

CountInstanceAdmins returns the number of local instance-admin accounts.

func (*Pool) CountOwnedServers

func (p *Pool) CountOwnedServers(ctx context.Context, userID string) (int, error)

CountOwnedServers returns the number of non-DM servers where the user is the owner.

func (*Pool) CountUnusedMLSKeyPackages

func (p *Pool) CountUnusedMLSKeyPackages(ctx context.Context, userID, deviceID string) (int, error)

CountUnusedMLSKeyPackages returns the number of unconsumed, non-expired, non-last-resort KeyPackages stamped with the current server ciphersuite for a user+device. Legacy-suite rows are excluded so the low-watermark event and client replenishment logic only react to packages that are actually usable under the active protocol epoch.

func (*Pool) CreateChannel

func (p *Pool) CreateChannel(ctx context.Context, serverID string, encryptedMetadata []byte, channelType string, parentID *string, position int) (*models.Channel, error)

CreateChannel inserts a channel scoped to the given guild and returns the created row. encryptedMetadata is the client-encrypted channel name/description blob (may be nil for system channels, which clients display using the channel type).

func (*Pool) CreateDMGuild

func (p *Pool) CreateDMGuild(ctx context.Context, userAID, userBID string) (*models.Server, *models.Channel, error)

CreateDMGuild creates a DM guild for the two users in a single transaction. It inserts the servers row (is_dm=true), a dm_pairs entry, both participants as PermissionLevelOwner server_members, and one text channel (position 0). Returns the created server and the created channel.

func (*Pool) CreateInstanceAdmin

func (p *Pool) CreateInstanceAdmin(ctx context.Context, username string, email *string, passwordHash, role string) (*models.InstanceAdmin, error)

CreateInstanceAdmin inserts a new local instance-admin account.

func (*Pool) CreateInstanceAdminSession

func (p *Pool) CreateInstanceAdminSession(
	ctx context.Context,
	sessionID, adminID, tokenHash string,
	expiresAt time.Time,
	createdIP, userAgent *string,
) (*models.InstanceAdminSession, error)

CreateInstanceAdminSession stores a hashed cookie session for an instance admin.

func (*Pool) CreateInvite

func (p *Pool) CreateInvite(ctx context.Context, serverID, code, createdBy string, maxUses int, expiresAt time.Time) (*models.InviteCode, error)

CreateInvite inserts a new invite code scoped to the given guild.

func (*Pool) CreateServer

func (p *Pool) CreateServer(ctx context.Context, encryptedMetadata []byte) (*models.Server, error)

CreateServer inserts a new guild with an optional encrypted metadata blob and returns the created row. encryptedMetadata may be nil - the two-step creation flow allows the client to set it after establishing the guild metadata MLS group.

func (*Pool) CreateServerTemplate

func (p *Pool) CreateServerTemplate(ctx context.Context, name string, channels json.RawMessage, isDefault bool) (*models.ServerTemplate, error)

CreateServerTemplate inserts a new server template. If isDefault is true, clears default on all others.

func (*Pool) CreateSession

func (p *Pool) CreateSession(ctx context.Context, sessionID, userID, tokenHash string, expiresAt time.Time) (*models.Session, error)

CreateSession inserts a session with the given id (for JWT session_id claim) and returns it.

func (*Pool) CreateUserWithPublicKey

func (p *Pool) CreateUserWithPublicKey(ctx context.Context, username, displayName string, publicKey []byte) (*models.User, error)

CreateUserWithPublicKey inserts a user with a BIP39 Ed25519 root public key and returns the created user with server-assigned ID. No password is stored.

func (*Pool) DeleteAuthNonce

func (p *Pool) DeleteAuthNonce(ctx context.Context, nonce string) error

DeleteAuthNonce removes a nonce regardless of expiry. Missing rows are ignored.

func (*Pool) DeleteChannel

func (p *Pool) DeleteChannel(ctx context.Context, channelID, serverID string) error

DeleteChannel deletes the channel iff (channelID, serverID) matches. Returns pgx.ErrNoRows when no row was deleted so handlers can map the cross-guild case to 404 without distinguishing it from "not found".

func (*Pool) DeleteChannelTree

func (p *Pool) DeleteChannelTree(ctx context.Context, channelID, serverID string) (deletedIDs []string, storageKeys []string, err error)

DeleteChannelTree atomically removes a channel and, when the target is a category, every channel parented to it. Snapshots the attachment storage keys for every removed channel inside the same transaction so the caller can schedule async blob cleanup without a race against the cascade.

Returns:

  • deletedIDs: ids actually removed (may be empty if a concurrent admin already deleted the row); the slice always contains the root id last when it was deleted, so callers that rely on stable ordering get a deterministic shape.
  • storageKeys: every not-yet-tombstoned attachment storage_key across the removed channels. Order is unspecified.
  • error: pgx.ErrNoRows when the root channel did not exist or belonged to a different server (cross-guild attempt). All other errors are wrapped.

Children must be removed in the same SQL statement because the schema declares `parent_id ON DELETE SET NULL`: deleting the category first would silently reparent the children to root, which is the opposite of what the user-visible "delete category" affordance promises.

func (*Pool) DeleteChunkBlob

func (p *Pool) DeleteChunkBlob(ctx context.Context, storageKey string) error

DeleteChunkBlob removes the row. Missing rows are treated as success.

func (*Pool) DeleteInstanceAdminSessionByID

func (p *Pool) DeleteInstanceAdminSessionByID(ctx context.Context, sessionID string) error

DeleteInstanceAdminSessionByID revokes the target admin session.

func (*Pool) DeleteLinkArchive

func (p *Pool) DeleteLinkArchive(ctx context.Context, archiveID string) error

DeleteLinkArchive removes the archive row; chunk rows cascade. Storage backend cleanup is the caller's responsibility (see the supervisor purger which handles both DB and backend together).

func (*Pool) DeleteMLSGroupInfo

func (p *Pool) DeleteMLSGroupInfo(ctx context.Context, channelID string, groupType string) error

DeleteMLSGroupInfo removes the GroupInfo row for a channel and group type at the current server ciphersuite. groupType must be "text" or "voice". For voice groups this is called when the last participant leaves the voice channel to enforce the clean forward-secrecy boundary between voice sessions. Legacy-suite rows are intentionally preserved: they are invisible to consumers and serve as audit history that the operator can purge in a separate intentional action.

func (*Pool) DeleteMLSGuildMetadataGroupInfo

func (p *Pool) DeleteMLSGuildMetadataGroupInfo(ctx context.Context, serverID string) error

DeleteMLSGuildMetadataGroupInfo removes the metadata group row for the given guild at the current server ciphersuite. Called when a guild is deleted. Legacy-suite rows are preserved as audit history.

func (*Pool) DeleteMessage

func (p *Pool) DeleteMessage(ctx context.Context, messageID, serverID string) error

DeleteMessage removes the message iff it lives in a channel whose server_id matches serverID. The server filter is enforced via a subquery so cross-guild attempts cannot delete the row even when the caller knows the messageID. Returns pgx.ErrNoRows on cross-guild mismatch so handlers can map the result to 404.

func (*Pool) DeletePendingWelcome

func (p *Pool) DeletePendingWelcome(ctx context.Context, welcomeID string) error

DeletePendingWelcome removes a specific pending Welcome at the current server ciphersuite after the client ACKs it. Legacy-suite welcomes are not deletable through this path: a current-suite client has no way to obtain their ID (GetPendingWelcomes already filters them out), and a server-side janitor that wants to purge legacy welcomes wholesale should do so as an intentional migration, not through the per-row ACK endpoint.

func (*Pool) DeleteServer

func (p *Pool) DeleteServer(ctx context.Context, serverID string) error

DeleteServer removes the guild by ID.

func (*Pool) DeleteServerTemplate

func (p *Pool) DeleteServerTemplate(ctx context.Context, id string) error

DeleteServerTemplate deletes a server template by ID.

func (*Pool) DeleteSessionByID

func (p *Pool) DeleteSessionByID(ctx context.Context, sessionID string) error

DeleteSessionByID removes the session (logout).

func (*Pool) DeleteSessionsByUserID

func (p *Pool) DeleteSessionsByUserID(ctx context.Context, userID string) error

DeleteSessionsByUserID removes all active sessions for the given user. Used when kicking or banning a user to invalidate their current tokens.

func (*Pool) DiscoverGuilds

func (p *Pool) DiscoverGuilds(ctx context.Context, category, search, sort string, page, pageSize int) ([]models.DiscoverGuild, int, error)

DiscoverGuilds returns publicly discoverable guilds that are not closed, filtered by optional category and search query, sorted by members or creation date. Returns the guilds for the requested page plus the total matching count. instance_config.guild_discovery = 'disabled' causes an empty result set.

func (*Pool) FindDMGuild

func (p *Pool) FindDMGuild(ctx context.Context, userAID, userBID string) (*models.Server, error)

FindDMGuild returns the DM guild for the given user pair, or pgx.ErrNoRows when no DM exists. User IDs are canonically ordered (min < max) so the lookup is consistent regardless of the call-site parameter order.

func (*Pool) GetActiveBan

func (p *Pool) GetActiveBan(ctx context.Context, serverID, userID string) (*models.Ban, error)

GetActiveBan returns the active ban for userID within the given guild, or nil if none exists. A ban is active when lifted_at IS NULL and either expires_at IS NULL or expires_at > now().

func (*Pool) GetActiveInstanceBan

func (p *Pool) GetActiveInstanceBan(ctx context.Context, userID string) (*models.InstanceBan, error)

GetActiveInstanceBan returns the active instance ban for userID, or nil if none exists. A ban is active when lifted_at IS NULL and either expires_at IS NULL or expires_at > now().

func (*Pool) GetActiveMute

func (p *Pool) GetActiveMute(ctx context.Context, serverID, userID string) (*models.Mute, error)

GetActiveMute returns the active mute for userID within the given guild, or nil if none exists. A mute is active when lifted_at IS NULL and either expires_at IS NULL or expires_at > now().

func (*Pool) GetAllLeafHashes

func (p *Pool) GetAllLeafHashes(ctx context.Context) ([][32]byte, error)

GetAllLeafHashes returns every leaf_hash in leaf_index order. Used at startup to rehydrate the in-memory Merkle tree so Proof() works for entries appended before the current process started.

func (*Pool) GetAttachmentByID

func (p *Pool) GetAttachmentByID(ctx context.Context, attachmentID string) (*models.Attachment, error)

GetAttachmentByID fetches an attachment row, including soft-deleted rows. Callers check DeletedAt to return a stable "gone" placeholder for messages that still reference a quota- or retention-purged attachment.

func (*Pool) GetChannelByID

func (p *Pool) GetChannelByID(ctx context.Context, channelID string) (*models.Channel, error)

GetChannelByID returns the channel by ID, or nil if not found.

func (*Pool) GetChannelByTypeAndPosition

func (p *Pool) GetChannelByTypeAndPosition(ctx context.Context, serverID, channelType string, position int) (*models.Channel, error)

GetChannelByTypeAndPosition returns the channel matching both type and position within a guild, or nil if not found. Replaces GetChannelByNameAndType for idempotency checks during template channel creation (no name column exists after migration 000017).

func (*Pool) GetChunkBlob

func (p *Pool) GetChunkBlob(ctx context.Context, storageKey string) ([]byte, error)

GetChunkBlob fetches the bytes previously stored under storageKey. Returns pgx.ErrNoRows when absent.

func (*Pool) GetDefaultServerTemplate

func (p *Pool) GetDefaultServerTemplate(ctx context.Context) (*models.ServerTemplate, error)

GetDefaultServerTemplate returns the template marked as default, or nil.

func (*Pool) GetFederatedIdentityByID

func (p *Pool) GetFederatedIdentityByID(ctx context.Context, id string) (*models.FederatedIdentity, error)

GetFederatedIdentityByID returns the federated identity by primary-key ID, or (nil, nil) when no such row exists.

func (*Pool) GetFederatedIdentityByPublicKey

func (p *Pool) GetFederatedIdentityByPublicKey(
	ctx context.Context,
	publicKey []byte,
) (*models.FederatedIdentity, error)

GetFederatedIdentityByPublicKey returns the cached foreign-instance user whose public_key matches, or (nil, nil) when no such row exists.

func (*Pool) GetInstanceAdminByID

func (p *Pool) GetInstanceAdminByID(ctx context.Context, id string) (*models.InstanceAdmin, error)

GetInstanceAdminByID returns an instance admin by ID, or nil when absent.

func (*Pool) GetInstanceAdminByUsername

func (p *Pool) GetInstanceAdminByUsername(ctx context.Context, username string) (*models.InstanceAdmin, error)

GetInstanceAdminByUsername returns an instance admin by username, or nil when absent.

func (*Pool) GetInstanceAdminSessionByTokenHash

func (p *Pool) GetInstanceAdminSessionByTokenHash(ctx context.Context, tokenHash string) (*models.InstanceAdminSession, error)

GetInstanceAdminSessionByTokenHash returns the active admin session for the token hash.

func (*Pool) GetInstanceConfig

func (p *Pool) GetInstanceConfig(ctx context.Context) (*models.InstanceConfig, error)

GetInstanceConfig returns the single instance configuration row.

func (*Pool) GetInstanceServiceIdentity

func (p *Pool) GetInstanceServiceIdentity(ctx context.Context) (*models.InstanceServiceIdentity, error)

GetInstanceServiceIdentity returns the stored technical service identity, or nil when absent.

func (*Pool) GetInviteByCode

func (p *Pool) GetInviteByCode(ctx context.Context, code string) (*models.InviteCode, error)

GetInviteByCode returns the invite by code, or nil if not found.

func (*Pool) GetLatestTransparencyTreeHead

func (p *Pool) GetLatestTransparencyTreeHead(
	ctx context.Context,
) (*models.TransparencyTreeHead, error)

GetLatestTransparencyTreeHead returns the tree head with the highest tree_size. Returns nil (no error) when the table is empty.

func (*Pool) GetLinkArchiveByDownloadTokenHash

func (p *Pool) GetLinkArchiveByDownloadTokenHash(ctx context.Context, archiveID string, tokenHash []byte) (*LinkArchive, error)

GetLinkArchiveByDownloadTokenHash returns the archive row whose download_token_hash matches the supplied 32-byte hash, gated on freshness.

func (*Pool) GetLinkArchiveByID

func (p *Pool) GetLinkArchiveByID(ctx context.Context, archiveID string) (*LinkArchive, error)

GetLinkArchiveByID returns the archive row for archiveID. Freshness is gated in scanLinkArchive (returns ErrLinkArchiveExpired past the sliding-expiry or hard-deadline boundary). Terminal-state rows are also rejected because they no longer accept any operations.

func (*Pool) GetLinkArchiveByUploadTokenHash

func (p *Pool) GetLinkArchiveByUploadTokenHash(ctx context.Context, archiveID string, tokenHash []byte) (*LinkArchive, error)

GetLinkArchiveByUploadTokenHash returns the archive row whose upload_token_hash matches the supplied 32-byte hash, gated on freshness.

func (*Pool) GetLinkArchiveChunkPointer

func (p *Pool) GetLinkArchiveChunkPointer(ctx context.Context, archiveID string, idx int) (storageBackend, storageKey string, err error)

GetLinkArchiveChunkPointer returns the storage backend kind and key for (archiveID, idx). Used by the API download handler to look up where the bytes actually live.

func (*Pool) GetMLSCommitsSinceEpoch

func (p *Pool) GetMLSCommitsSinceEpoch(ctx context.Context, channelID string, sinceEpoch int64, limit int) ([]MLSCommitRow, error)

GetMLSCommitsSinceEpoch returns commits for a channel at the current server ciphersuite with epoch > sinceEpoch, ordered by epoch ascending, limited to at most limit rows. Legacy-suite commits are filtered out: replaying them under the new protocol epoch would either fail validation or corrupt local state, so they must never reach a current-suite client.

func (*Pool) GetMLSCredential

func (p *Pool) GetMLSCredential(ctx context.Context, userID, deviceID string) (credentialBytes, signingPublicKey []byte, identityVersion int, err error)

GetMLSCredential returns the stored MLS credential for a user+device. Returns (nil, nil, 0, nil) when no row exists.

func (*Pool) GetMLSGroupInfo

func (p *Pool) GetMLSGroupInfo(ctx context.Context, channelID string, groupType string) (groupInfoBytes []byte, epoch int64, err error)

GetMLSGroupInfo returns the GroupInfo bytes and epoch for a channel and group type at the current server ciphersuite. groupType must be "text" or "voice". Legacy-suite rows are never returned: a client running the current protocol must be able to treat a missing row as "no group at the active suite, start a fresh one". Returns (nil, 0, nil) when no current-suite row exists.

func (*Pool) GetMLSGuildMetadataGroupInfo

func (p *Pool) GetMLSGuildMetadataGroupInfo(ctx context.Context, serverID string) (groupInfoBytes []byte, epoch int64, err error)

GetMLSGuildMetadataGroupInfo returns the GroupInfo bytes and epoch for a guild metadata group at the current server ciphersuite. Legacy-suite rows are never returned. Returns (nil, 0, nil) when no current-suite row exists.

func (*Pool) GetMessageByID

func (p *Pool) GetMessageByID(ctx context.Context, messageID string) (*models.Message, error)

GetMessageByID returns the message with the given ID, or nil if not found.

func (*Pool) GetMessages

func (p *Pool) GetMessages(ctx context.Context, channelID, recipientID string, before time.Time, limit int) ([]models.Message, error)

GetMessages returns messages for the channel for the given recipient (rows where recipient_id IS NULL OR recipient_id = recipientID), ordered by timestamp DESC.

func (*Pool) GetMessagesAfter

func (p *Pool) GetMessagesAfter(ctx context.Context, channelID, recipientID string, after time.Time, limit int) ([]models.Message, error)

GetMessagesAfter returns messages for the channel newer than the given timestamp, ordered by timestamp ASC. Used for reconnect catch-up: the client sends the timestamp of the last known message and receives any messages created after that point in chronological order.

func (*Pool) GetOrCreateFederatedIdentity

func (p *Pool) GetOrCreateFederatedIdentity(
	ctx context.Context,
	publicKey []byte,
	homeInstance, username, displayName string,
) (*models.FederatedIdentity, error)

GetOrCreateFederatedIdentity upserts a foreign-instance user by their Ed25519 public key. On conflict it refreshes the username, display_name, and cached_at. Returns the full FederatedIdentity row (including server-assigned ID).

func (*Pool) GetPendingWelcomes

func (p *Pool) GetPendingWelcomes(ctx context.Context, recipientUserID string) ([]PendingWelcomeRow, error)

GetPendingWelcomes returns all pending Welcome messages for a recipient user at the current server ciphersuite, ordered by created_at ascending (oldest first). Legacy-suite welcomes are filtered out: a client running the new protocol cannot process them and forwarding them would either error out or burn forward secrecy.

func (*Pool) GetServerByID

func (p *Pool) GetServerByID(ctx context.Context, serverID string) (*models.Server, error)

GetServerByID returns the guild by ID, or nil if not found.

func (*Pool) GetServerMemberLevel

func (p *Pool) GetServerMemberLevel(ctx context.Context, serverID, userID string) (int, error)

GetServerMemberLevel returns the permission_level of the user within the guild. Returns an error if the user is not a member.

func (*Pool) GetServerMemberLevelByFederatedID

func (p *Pool) GetServerMemberLevelByFederatedID(ctx context.Context, serverID, federatedIdentityID string) (int, error)

GetServerMemberLevelByFederatedID returns the permission_level for a federated guild member. Returns an error if the federated user is not a member.

func (*Pool) GetServerTemplateByID

func (p *Pool) GetServerTemplateByID(ctx context.Context, id string) (*models.ServerTemplate, error)

GetServerTemplateByID returns a single server template by ID.

func (*Pool) GetSessionByTokenHash

func (p *Pool) GetSessionByTokenHash(ctx context.Context, tokenHash string) (*models.Session, error)

GetSessionByTokenHash returns the session if it exists and is not expired.

func (*Pool) GetSystemMessageRetentionDays

func (p *Pool) GetSystemMessageRetentionDays(ctx context.Context) (*int, error)

GetSystemMessageRetentionDays returns the configured retention period from instance_config. Returns nil if the value is NULL (meaning keep forever).

func (*Pool) GetTransparencyLogEntriesByPubKey

func (p *Pool) GetTransparencyLogEntriesByPubKey(
	ctx context.Context,
	pubKey []byte,
) ([]models.TransparencyLogEntry, error)

GetTransparencyLogEntriesByPubKey returns all log entries for a public key, ordered by leaf_index ASC.

func (*Pool) GetUnreadCount

func (p *Pool) GetUnreadCount(ctx context.Context, channelID, userID string) (int, error)

GetUnreadCount returns the count of messages in channelID that are visible to userID (recipient_id IS NULL OR recipient_id = userID), not sent by userID, and newer than the user's read marker. Returns 0 if no marker exists and there are no messages.

func (*Pool) GetUserByID

func (p *Pool) GetUserByID(ctx context.Context, id string) (*models.User, error)

GetUserByID returns the user by UUID.

func (*Pool) GetUserByPublicKey

func (p *Pool) GetUserByPublicKey(ctx context.Context, publicKey []byte) (*models.User, error)

GetUserByPublicKey returns the user whose root_public_key matches the given Ed25519 public key, or (nil, nil) if not found.

func (*Pool) GetUserByUsername

func (p *Pool) GetUserByUsername(ctx context.Context, username string) (*models.User, error)

GetUserByUsername returns the user by username.

func (*Pool) GetUserRole

func (p *Pool) GetUserRole(ctx context.Context, userID string) (string, error)

GetUserRole returns the role of the user by ID (column value: 'admin' or 'member'). The 'owner' role no longer exists at the users level; guild ownership is permission_level=3 in server_members. Instance admin access is via API key auth, not a user role.

func (*Pool) GetVoiceKeyRotationHours

func (p *Pool) GetVoiceKeyRotationHours(ctx context.Context) (int, error)

GetVoiceKeyRotationHours returns the configured voice group periodic key rotation interval from instance_config. Returns the default of 2 when the row is missing.

func (*Pool) IncrementGuildMemberCount

func (p *Pool) IncrementGuildMemberCount(ctx context.Context, serverID string, delta int) error

IncrementGuildMemberCount adjusts member_count by delta (+1 on join, -1 on leave).

func (*Pool) IncrementGuildMessageCount

func (p *Pool) IncrementGuildMessageCount(ctx context.Context, channelID string) error

IncrementGuildMessageCount increments the message_count and updates last_active_at for the guild that owns the given channel. Called on every relayed message.

func (*Pool) InsertAttachment

func (p *Pool) InsertAttachment(ctx context.Context, channelID, ownerID, storageKey, contentType string, size int64) (*models.Attachment, error)

InsertAttachment records a new attachment row before the client uploads bytes to the storage backend. Callers must Soft-delete the row if the upload never lands so the supervised purger can drop the orphan after the presign TTL expires.

func (*Pool) InsertAuditLog

func (p *Pool) InsertAuditLog(ctx context.Context, serverID, actorID string, targetID *string, action, reason string, metadata map[string]interface{}) error

InsertAuditLog records a moderation action scoped to the given guild. metadata may be nil.

func (*Pool) InsertAuthNonce

func (p *Pool) InsertAuthNonce(ctx context.Context, nonce string, publicKey []byte, expiresAt time.Time) error

InsertAuthNonce stores a challenge nonce associated with a user's public key. The nonce expires at expiresAt; expired nonces are rejected by ConsumeAuthNonce.

func (*Pool) InsertBan

func (p *Pool) InsertBan(ctx context.Context, serverID, userID, actorID, reason string, expiresAt *time.Time) (*models.Ban, error)

InsertBan creates a new ban record scoped to the given guild and returns the created row.

func (*Pool) InsertDeviceKey

func (p *Pool) InsertDeviceKey(ctx context.Context, userID, deviceID, label string, devicePublicKey, certificate []byte) error

InsertDeviceKey stores a certified device public key for a user. certificate may be nil for the first (root) device registered at sign-up. On conflict (user_id, device_id) the existing row is overwritten so that device re-registration (e.g. after a factory reset) is handled gracefully.

func (*Pool) InsertInstanceAuditLog

func (p *Pool) InsertInstanceAuditLog(ctx context.Context, actorID string, targetID *string, action, reason string, metadata map[string]interface{}) error

InsertInstanceAuditLog records an instance-level admin action. metadata may be nil.

func (*Pool) InsertInstanceBan

func (p *Pool) InsertInstanceBan(ctx context.Context, userID, actorID, reason string, expiresAt *time.Time) (*models.InstanceBan, error)

InsertInstanceBan creates a new instance-level ban record and returns the created row.

func (*Pool) InsertInstanceBanByAdmin

func (p *Pool) InsertInstanceBanByAdmin(ctx context.Context, userID, actorAdminID, reason string, expiresAt *time.Time) (*models.InstanceBan, error)

InsertInstanceBanByAdmin creates a new instance-level ban with a local admin actor.

func (*Pool) InsertLinkArchive

func (p *Pool) InsertLinkArchive(ctx context.Context, in LinkArchiveInsert) (*LinkArchive, error)

InsertLinkArchive persists a new archive metadata row in state 'created'. State is advanced by the API layer via TransitionLinkArchiveState.

func (*Pool) InsertLinkArchiveChunk

func (p *Pool) InsertLinkArchiveChunk(ctx context.Context, in LinkArchiveChunkInsert) error

InsertLinkArchiveChunk stores chunk metadata. The bytes themselves live wherever the storage backend put them, addressed by StorageKey. Hash-keyed idempotency:

  • first write for the (archive, idx) succeeds
  • retry with the same chunk_hash is a no-op accept and returns no error
  • retry with a different chunk_hash returns ErrLinkArchiveChunkConflict and the stored row is unchanged

func (*Pool) InsertMLSKeyPackages

func (p *Pool) InsertMLSKeyPackages(ctx context.Context, userID, deviceID string, packages [][]byte, expiresAt time.Time) error

InsertMLSKeyPackages stores a batch of opaque KeyPackage blobs for a user+device. All packages in the batch share the same expiry time and are stamped with the active server ciphersuite (version.CurrentMLSCiphersuite); the delivery service will only hand these packages back out to consumers running the same suite.

func (*Pool) InsertMLSLastResortKeyPackage

func (p *Pool) InsertMLSLastResortKeyPackage(ctx context.Context, userID, deviceID string, keyPackageBytes []byte) error

InsertMLSLastResortKeyPackage replaces the existing last-resort KeyPackage for a user+device under the active ciphersuite with the new one. The last-resort package uses a far-future expiry (year 2099) so it is never purged by the cleanup job. Last-resort packages from previous ciphersuites are intentionally left in place: they are invisible to consume/count under the current suite and serve only as audit history until the operator chooses to purge them.

func (*Pool) InsertMessage

func (p *Pool) InsertMessage(ctx context.Context, channelID string, senderID *string, federatedSenderID *string, recipientID *string, ciphertext []byte) (*models.Message, error)

InsertMessage stores an encrypted message and returns the created row. Exactly one of senderID or federatedSenderID should be non-nil. recipientID nil = broadcast/single ciphertext; non-nil = fan-out for that recipient.

func (*Pool) InsertMute

func (p *Pool) InsertMute(ctx context.Context, serverID, userID, actorID, reason string, expiresAt *time.Time) (*models.Mute, error)

InsertMute creates a new mute record scoped to the given guild and returns the created row.

func (*Pool) InsertSystemMessage

func (p *Pool) InsertSystemMessage(ctx context.Context, serverID, eventType, actorID string, targetID *string, reason string, metadata map[string]interface{}) (*models.SystemMessage, error)

InsertSystemMessage inserts a system message row and returns it with generated UUID and timestamp.

func (*Pool) InsertTransparencyLogEntry

func (p *Pool) InsertTransparencyLogEntry(
	ctx context.Context,
	leafIndex uint64,
	operation string,
	userPubKey, subjectKey, entryCBOR, leafHash, userSig, logSig []byte,
) error

InsertTransparencyLogEntry persists a fully-signed transparency log entry. Called after Append + Countersign within TransparencyService.AppendEntry.

func (*Pool) InsertTransparencyTreeHead

func (p *Pool) InsertTransparencyTreeHead(
	ctx context.Context,
	treeSize uint64,
	rootHash, fringe, headSig []byte,
) error

InsertTransparencyTreeHead persists the Merkle tree state after a successful append. The primary key is tree_size, so each unique tree size is stored exactly once.

func (*Pool) IsChannelMember

func (p *Pool) IsChannelMember(ctx context.Context, channelID, userID string) (bool, error)

IsChannelMember checks whether the user belongs to the guild that owns the channel. A user is a channel member if they are a member of the server that contains the channel.

func (*Pool) IsDeviceActive

func (p *Pool) IsDeviceActive(ctx context.Context, userID, deviceID string) (bool, error)

IsDeviceActive reports whether a device key row still exists for the (userID, deviceID) pair. Used by RequireAuth and the WS upgrade path to enforce revocation: a device whose key has been deleted by RevokeDeviceKey loses its ability to make authenticated calls on the next request.

func (*Pool) LiftBan

func (p *Pool) LiftBan(ctx context.Context, banID, liftedByID string) error

LiftBan sets lifted_at = now() and lifted_by on the given ban record. Returns an error if the ban does not exist or is already lifted.

func (*Pool) LiftInstanceBan

func (p *Pool) LiftInstanceBan(ctx context.Context, banID, liftedByID string) error

LiftInstanceBan sets lifted_at = now() and lifted_by on the given instance ban record.

func (*Pool) LiftInstanceBanByAdmin

func (p *Pool) LiftInstanceBanByAdmin(ctx context.Context, banID, liftedByAdminID string) error

LiftInstanceBanByAdmin sets lifted_at = now() and lifted_by_admin_id for the ban.

func (*Pool) LiftMute

func (p *Pool) LiftMute(ctx context.Context, muteID, liftedByID string) error

LiftMute sets lifted_at = now() and lifted_by on the given mute record. Returns an error if the mute does not exist or is already lifted.

func (*Pool) ListActiveBans

func (p *Pool) ListActiveBans(ctx context.Context, serverID string) ([]models.Ban, error)

ListActiveBans returns all active (non-lifted, non-expired) bans for the given guild, ordered by created_at DESC.

func (*Pool) ListActiveMutes

func (p *Pool) ListActiveMutes(ctx context.Context, serverID string) ([]models.Mute, error)

ListActiveMutes returns all active (non-lifted, non-expired) mutes for the given guild, ordered by created_at DESC.

func (*Pool) ListAttachmentsForGuildQuota

func (p *Pool) ListAttachmentsForGuildQuota(ctx context.Context, channelID string) (string, []models.Attachment, error)

ListAttachmentsForGuildQuota returns the channel's guild id and all active attachments in that guild, oldest first. The presign path uses this to decide which objects to tombstone when a new attachment would exceed the configured guild storage quota.

func (*Pool) ListAuditLog

func (p *Pool) ListAuditLog(ctx context.Context, serverID string, limit, offset int, filter *AuditLogFilter) ([]models.AuditLogEntry, error)

ListAuditLog returns audit log entries for the given guild ordered by created_at DESC with pagination. An optional filter may narrow results by action type, actor ID, and/or target ID.

func (*Pool) ListChannels

func (p *Pool) ListChannels(ctx context.Context, serverID string) ([]models.Channel, error)

ListChannels returns all channels for the given guild ordered by position.

func (*Pool) ListDeviceIDsForUser

func (p *Pool) ListDeviceIDsForUser(ctx context.Context, userID string) ([]string, error)

ListDeviceIDsForUser returns all device IDs that have an MLS credential for the user.

func (*Pool) ListDeviceKeys

func (p *Pool) ListDeviceKeys(ctx context.Context, userID string) ([]models.DeviceKey, error)

ListDeviceKeys returns all device keys belonging to a user, ordered by certified_at ascending so the first (root) device appears first.

func (*Pool) ListExpiredAttachments

func (p *Pool) ListExpiredAttachments(ctx context.Context, retentionDays int, limit int) ([]models.Attachment, error)

ListExpiredAttachments returns active attachment rows older than the message retention window. The caller deletes storage objects after tombstoning them.

func (*Pool) ListGcEligibleLinkArchives

func (p *Pool) ListGcEligibleLinkArchives(ctx context.Context, limit int) ([]string, error)

ListGcEligibleLinkArchives returns archives that have aged past their state-specific TTL. Three retention rules:

  • 'acknowledged' / 'aborted' are GC-eligible immediately.
  • 'terminal_failure' / 'imported' (no ACK yet) are GC-eligible 24 hours after they entered the state — diagnostic grace window.
  • everything else is governed by the sliding expires_at + hard deadline pair.

State-entry timestamps are not currently tracked per state; a 24-hour grace is implemented as `expires_at < now() - 24h` because every transition refreshes expires_at, so the sliding window naturally times out 60 min after the last touch and well past the 24-hour grace by the time the retention rule applies. Future work to emit a per-state-entry timestamp can refine this.

func (*Pool) ListGuildBillingStats

func (p *Pool) ListGuildBillingStats(ctx context.Context) ([]models.GuildBillingStats, error)

ListGuildBillingStats returns guild infrastructure metrics for the instance operator. No guild name, channel list, or member details are exposed.

member_count is computed LIVE from server_members rather than read from the cached `servers.member_count` column. The cached counter is incremented only on invite-driven joins (api/servers.go:568, api/invites.go:254) and is NOT incremented at server creation for the owner, NOR decremented on kick/ban/leave/admin-remove, so it drifts arbitrarily — the symptom operators see is "instance admin shows servers with 0 members when they actually have members". Live counting via LEFT JOIN is authoritative; the cached counter stays in the schema for backward compatibility but is no longer trusted by this read path.

func (*Pool) ListInstanceAdmins

func (p *Pool) ListInstanceAdmins(ctx context.Context) ([]models.InstanceAdmin, error)

ListInstanceAdmins returns all instance-admin accounts ordered by creation time.

func (*Pool) ListInstanceAuditLog

func (p *Pool) ListInstanceAuditLog(ctx context.Context, limit, offset int, filter *InstanceAuditLogFilter) ([]models.InstanceAuditLogEntry, error)

ListInstanceAuditLog returns instance audit log entries ordered by created_at DESC with pagination. An optional filter may narrow results by action type and/or target ID.

func (*Pool) ListLinkArchiveChunkRows

func (p *Pool) ListLinkArchiveChunkRows(ctx context.Context, archiveID string) ([]LinkArchiveChunkRow, error)

ListLinkArchiveChunkRows returns metadata for every stored chunk, ordered by idx ASC. Used at finalize time and to compute the manifest the NEW device fetches.

func (*Pool) ListMembers

func (p *Pool) ListMembers(ctx context.Context) ([]models.Member, error)

ListMembers returns all users ordered by creation time.

func (*Pool) ListServerMembers

func (p *Pool) ListServerMembers(ctx context.Context, serverID string) ([]models.ServerMemberWithUser, error)

ListServerMembers returns all guild members (local and federated) with their profiles, ordered by join time. HomeInstance is nil for local users.

func (*Pool) ListServerTemplates

func (p *Pool) ListServerTemplates(ctx context.Context) ([]models.ServerTemplate, error)

ListServerTemplates returns all server templates ordered by position.

func (*Pool) ListServersForUser

func (p *Pool) ListServersForUser(ctx context.Context, userID string) ([]models.Server, error)

ListServersForUser returns all guilds the user is a member of, ordered by creation time. DM guilds are enriched with OtherUser and ChannelID via JOINs on dm_pairs, users, and channels.

func (*Pool) ListSupersedableLinkArchivesForUser

func (p *Pool) ListSupersedableLinkArchivesForUser(ctx context.Context, userID string, lastTouchBefore time.Time) ([]string, error)

ListSupersedableLinkArchivesForUser returns IDs of the user's active archives whose last sliding-expiry refresh predates lastTouchBefore.

The sliding-expiry contract is: every authenticated touch sets expires_at = LEAST(now() + linkArchiveDefaultExpiry, hard_deadline_at). So an archive that has not been touched since time T has expires_at <= T + linkArchiveDefaultExpiry. The caller computes lastTouchBefore as (now + linkArchiveDefaultExpiry - graceWindow); rows matching the query have not seen a touch within the grace window.

Used by /api/auth/link-archive-init to auto-abort an abandoned prior archive (e.g. NEW-device tab killed before the import-failure DELETE fired) so a fresh link attempt is not blocked by the per-user concurrent-archive quota until the 60-min sliding-expiry purge tick.

func (*Pool) ListSystemMessages

func (p *Pool) ListSystemMessages(ctx context.Context, serverID string, before time.Time, limit int) ([]models.SystemMessage, error)

ListSystemMessages returns system messages for a guild, ordered by created_at DESC. If before is zero time, no cursor filter is applied.

func (*Pool) MarkChannelRead

func (p *Pool) MarkChannelRead(ctx context.Context, channelID, userID, messageID string) error

MarkChannelRead advances the read marker for (channelID, userID) to the stored timestamp of messageID. The marker never moves backward. Returns an error if the message does not exist, does not belong to channelID, or is not visible to userID.

func (*Pool) MarkLinkArchiveFinalized

func (p *Pool) MarkLinkArchiveFinalized(ctx context.Context, archiveID string) error

MarkLinkArchiveFinalized flips finalized=true for backward compatibility and transitions state to 'uploaded'. Caller is expected to have verified completeness and hash bindings already.

func (*Pool) MoveChannel

func (p *Pool) MoveChannel(ctx context.Context, channelID, serverID string, newParentID *string, newPosition int) error

MoveChannel updates a channel's parent and position, shifting sibling channels to maintain a contiguous, collision-free position sequence within each scope.

Scope rules (position is ordinal within the scope, 0-indexed):

  • type='category' → among all categories
  • type!='category', parentID=nil → among uncategorized non-category channels
  • type!='category', parentID=some → among channels within that parent category

func (*Pool) PurgeExpiredLinkArchives

func (p *Pool) PurgeExpiredLinkArchives(ctx context.Context) (int64, error)

PurgeExpiredLinkArchives deletes archives where either expires_at or hard_deadline_at has passed. Returns rows affected.

Kept for backward compatibility with the existing purger; the new supervisor uses ListGcEligibleLinkArchives + DeleteLinkArchive so it can clean storage-backend objects between the list and delete steps.

func (*Pool) PurgeExpiredMLSKeyPackages

func (p *Pool) PurgeExpiredMLSKeyPackages(ctx context.Context) (int64, error)

PurgeExpiredMLSKeyPackages deletes key package rows that are safe to remove:

  • Consumed rows older than 30 days (no longer needed for audit or retry).
  • Unconsumed rows whose expiry has passed (useless - would be rejected on consume).

Last-resort packages are never deleted. Processes at most 10 000 rows per call to bound the DELETE scan time (consistent with the prior OPK cleanup pattern). Returns the number of rows deleted.

func (*Pool) PurgeExpiredMessages

func (p *Pool) PurgeExpiredMessages(ctx context.Context, retentionDays int) (int64, error)

PurgeExpiredMessages deletes encrypted chat messages older than the instance-level retention window. This is intentionally coarse-grained: message bodies are opaque ciphertext, so retention is enforced by row age.

func (*Pool) PurgeExpiredNonces

func (p *Pool) PurgeExpiredNonces(ctx context.Context) (int64, error)

PurgeExpiredNonces deletes all auth_nonces whose expires_at is in the past. Returns the number of rows deleted.

func (*Pool) PurgeExpiredSessions

func (p *Pool) PurgeExpiredSessions(ctx context.Context) (int64, error)

PurgeExpiredSessions deletes session rows whose expires_at is in the past. Returns the number of rows removed. Expired rows are already rejected by GetSessionByTokenHash; this exists to keep the table bounded.

func (*Pool) PurgeExpiredSystemMessages

func (p *Pool) PurgeExpiredSystemMessages(ctx context.Context, retentionDays int) (int64, error)

PurgeExpiredSystemMessages deletes system messages older than retentionDays. Returns the number of rows deleted.

func (*Pool) PurgeOldMLSCommits

func (p *Pool) PurgeOldMLSCommits(ctx context.Context, maxPerChannel int) (int64, error)

PurgeOldMLSCommits deletes commits beyond maxPerChannel per channel, keeping the most recent maxPerChannel commits. Processes at most 10 000 excess rows per call to bound the DELETE scan time. Returns the total number of rows deleted.

func (*Pool) PurgeStaleAdminSessions

func (p *Pool) PurgeStaleAdminSessions(ctx context.Context, revokedRetention time.Duration) (int64, error)

PurgeStaleAdminSessions deletes admin-session rows whose expires_at is in the past, plus any revoked rows older than revokedRetention. Returns the number of rows removed.

func (*Pool) RefreshLinkArchiveExpiry

func (p *Pool) RefreshLinkArchiveExpiry(ctx context.Context, archiveID string, ttl time.Duration) (time.Time, error)

RefreshLinkArchiveExpiry advances expires_at to LEAST(now() + ttl, hard_deadline_at). Stuck archives never live longer than the hard deadline. Returns the updated expires_at, or pgx.ErrNoRows if the archive does not exist.

func (*Pool) RemoveFederatedServerMember

func (p *Pool) RemoveFederatedServerMember(ctx context.Context, serverID, federatedIdentityID string) error

RemoveFederatedServerMember removes a federated user from the guild.

func (*Pool) RemoveServerMember

func (p *Pool) RemoveServerMember(ctx context.Context, serverID, userID string) error

RemoveServerMember removes the user from the guild.

func (*Pool) RevokeAllDeviceKeys

func (p *Pool) RevokeAllDeviceKeys(ctx context.Context, userID string) error

RevokeAllDeviceKeys deletes every device key for a user (used on account wipe).

func (*Pool) RevokeDeviceKey

func (p *Pool) RevokeDeviceKey(ctx context.Context, userID, deviceID string) error

RevokeDeviceKey deletes the device key for (userID, deviceID). No-op if not found.

func (*Pool) SearchUsers

func (p *Pool) SearchUsers(ctx context.Context, query string, limit int) ([]models.UserSearchResult, error)

SearchUsers searches for users by username prefix. Returns at most `limit` results (capped at 25). Includes active instance ban status via LEFT JOIN.

func (*Pool) SearchUsersPublic

func (p *Pool) SearchUsersPublic(ctx context.Context, query string, limit int) ([]models.UserSearchPublicResult, error)

SearchUsersPublic returns users matching the query string on username or displayName. Only id, username, and displayName are returned - no ban status, roles, or credentials.

func (*Pool) SoftDeleteAttachment

func (p *Pool) SoftDeleteAttachment(ctx context.Context, attachmentID, ownerID string) (*models.Attachment, error)

SoftDeleteAttachment marks the row as deleted and returns the freshly loaded row so the caller can hand the storage_key to the configured Backend.Delete. Returns pgx.ErrNoRows if the attachment does not exist, is already deleted, or does not belong to ownerID.

func (*Pool) SoftDeleteAttachmentsByID

func (p *Pool) SoftDeleteAttachmentsByID(ctx context.Context, attachmentIDs []string) ([]models.Attachment, error)

SoftDeleteAttachmentsByID tombstones active attachments and returns the rows that changed state so callers can delete the corresponding storage objects. Missing or already-deleted ids are ignored.

func (*Pool) StorePendingWelcome

func (p *Pool) StorePendingWelcome(ctx context.Context, channelID, recipientUserID, senderID string, welcomeBytes []byte, epoch int64) error

StorePendingWelcome stores a Welcome message to be delivered to an offline member under the active server ciphersuite.

func (*Pool) SumActiveLinkArchiveBytes

func (p *Pool) SumActiveLinkArchiveBytes(ctx context.Context) (int64, error)

SumActiveLinkArchiveBytes returns the sum of total_bytes across every non-terminal archive on the instance. Used by the per-instance staging-bytes ceiling check.

func (*Pool) TouchInstanceAdminLastLogin

func (p *Pool) TouchInstanceAdminLastLogin(ctx context.Context, id string, loginAt time.Time) error

TouchInstanceAdminLastLogin records the latest successful login time.

func (*Pool) TransitionLinkArchiveState

func (p *Pool) TransitionLinkArchiveState(ctx context.Context, archiveID, nextState string, allowedFrom []string) error

TransitionLinkArchiveState moves the archive into nextState only when its current state is one of allowedFrom. Returns pgx.ErrNoRows when the transition is rejected (caller treats this as a state-machine violation and surfaces an appropriate error to the client). Allowed transitions are enforced here, not just at the application layer, so a race between two requests cannot land the row in an inconsistent state.

func (*Pool) UpdateDeviceLastSeen

func (p *Pool) UpdateDeviceLastSeen(ctx context.Context, userID, deviceID string) error

UpdateDeviceLastSeen sets last_seen = now() for the given device. No-op if the device does not exist.

func (*Pool) UpdateFederatedIdentityProfile

func (p *Pool) UpdateFederatedIdentityProfile(
	ctx context.Context,
	id, username, displayName string,
) error

UpdateFederatedIdentityProfile refreshes the username, display_name, and cached_at for an existing federated identity row.

func (*Pool) UpdateGuildChannelCounts

func (p *Pool) UpdateGuildChannelCounts(ctx context.Context, serverID string) error

UpdateGuildChannelCounts recalculates text_channel_count and voice_channel_count for the guild. Uses a COUNT subquery so the result is always consistent with the channels table.

func (*Pool) UpdateInstanceAdmin

func (p *Pool) UpdateInstanceAdmin(ctx context.Context, id string, email *string, role string, isActive bool) (*models.InstanceAdmin, error)

UpdateInstanceAdmin updates mutable fields for an instance-admin account.

func (*Pool) UpdateInstanceAdminPassword

func (p *Pool) UpdateInstanceAdminPassword(ctx context.Context, id, passwordHash string) error

UpdateInstanceAdminPassword replaces the password hash for the target admin.

func (*Pool) UpdateInstanceAdminSessionLastSeen

func (p *Pool) UpdateInstanceAdminSessionLastSeen(ctx context.Context, sessionID string, seenAt time.Time) error

UpdateInstanceAdminSessionLastSeen records the latest request time for a session.

func (*Pool) UpdateInstanceConfig

func (p *Pool) UpdateInstanceConfig(ctx context.Context, name *string, iconURL *string, registrationMode *string, guildDiscovery *string, serverCreationPolicy *string, maxServersPerUser *int, maxMembersPerServer *int, maxRegisteredUsers *int, screenShareResolutionCap *string, maxAttachmentBytes *int64, maxGuildAttachmentStorageBytes *int64, messageRetentionDays *int) error

UpdateInstanceConfig updates only the non-nil fields of instance_config. serverCreationPolicy must be one of "open", "paid", or "disabled" when non-nil.

func (*Pool) UpdateServerEncryptedMetadata

func (p *Pool) UpdateServerEncryptedMetadata(ctx context.Context, serverID string, encryptedMetadata []byte) error

UpdateServerEncryptedMetadata replaces the encrypted_metadata blob for the given guild. Returns pgx.ErrNoRows if no server with that ID exists (caller maps to 404).

func (*Pool) UpdateServerMemberCapOverride

func (p *Pool) UpdateServerMemberCapOverride(ctx context.Context, serverID string, cap *int) error

UpdateServerMemberCapOverride sets or clears the per-server member cap override. Pass nil to clear (inherit instance default).

func (*Pool) UpdateServerMemberLevel

func (p *Pool) UpdateServerMemberLevel(ctx context.Context, serverID, userID string, permissionLevel int) error

UpdateServerMemberLevel sets a new permission level for the given member.

func (*Pool) UpdateServerTemplate

func (p *Pool) UpdateServerTemplate(ctx context.Context, id string, name string, channels json.RawMessage, isDefault bool) error

UpdateServerTemplate updates a server template by ID. If isDefault is true, clears default on all others.

func (*Pool) UpdateUserRole

func (p *Pool) UpdateUserRole(ctx context.Context, userID, role string) error

UpdateUserRole sets the role for a user.

func (*Pool) UpsertChunkBlob

func (p *Pool) UpsertChunkBlob(ctx context.Context, storageKey string, bytes []byte) error

UpsertChunkBlob writes (storage_key, bytes) to link_archive_chunk_blobs. The same storage_key may legitimately appear twice when a client retries an upload with identical bytes; ON CONFLICT DO NOTHING keeps the first writer and lets the API layer detect hash mismatches at the chunk-row level.

func (*Pool) UpsertDevice

func (p *Pool) UpsertDevice(ctx context.Context, userID, deviceID, label string) error

UpsertDevice inserts or updates a device for a user (e.g. on credential upload).

func (*Pool) UpsertInstanceServiceIdentity

func (p *Pool) UpsertInstanceServiceIdentity(
	ctx context.Context,
	username string,
	publicKey, wrappedPrivateKey []byte,
	wrappingKeyVersion string,
) (*models.InstanceServiceIdentity, error)

UpsertInstanceServiceIdentity stores or replaces the single technical service identity row.

func (*Pool) UpsertMLSCredential

func (p *Pool) UpsertMLSCredential(ctx context.Context, userID, deviceID string, credentialBytes, signingPublicKey []byte, identityVersion int) error

UpsertMLSCredential inserts or replaces the MLS credential for a user+device. On conflict (user_id, device_id) the credential bytes, signing public key, identity version, and updated_at timestamp are all refreshed.

func (*Pool) UpsertMLSGroupInfo

func (p *Pool) UpsertMLSGroupInfo(ctx context.Context, channelID string, groupType string, groupInfoBytes []byte, epoch int64) error

UpsertMLSGroupInfo inserts or updates the GroupInfo bytes for a channel and group type under the active server ciphersuite. groupType must be "text" or "voice". A legacy suite row for the same (channel, group_type) is left intact; the partial unique index on (channel_id, group_type, ciphersuite) keeps the two rows from colliding. On conflict at the current suite the group_info_bytes, epoch, and updated_at are refreshed.

func (*Pool) UpsertMLSGuildMetadataGroupInfo

func (p *Pool) UpsertMLSGuildMetadataGroupInfo(ctx context.Context, serverID string, groupInfoBytes []byte, epoch int64) error

UpsertMLSGuildMetadataGroupInfo inserts or updates the GroupInfo bytes for a guild metadata group (group_type = 'metadata', server_id scoped, channel_id = NULL) at the active server ciphersuite. A legacy-suite metadata row for the same guild is left intact; the partial unique index on (server_id, group_type, ciphersuite) keeps the two rows from colliding. On conflict at the current suite the group_info_bytes, epoch, and updated_at are refreshed.

type Store

type Store interface {
	// Ping checks database connectivity.
	Ping(ctx context.Context) error

	// CreateUserWithPublicKey inserts a user with a BIP39 Ed25519 root public key
	// instead of a password. Returns the created user with a server-assigned ID.
	CreateUserWithPublicKey(ctx context.Context, username, displayName string, publicKey []byte) (*models.User, error)
	// GetUserByPublicKey returns the user whose root_public_key matches the
	// given 32-byte Ed25519 public key, or sql.ErrNoRows if not found.
	GetUserByPublicKey(ctx context.Context, publicKey []byte) (*models.User, error)
	GetUserByUsername(ctx context.Context, username string) (*models.User, error)
	GetUserByID(ctx context.Context, id string) (*models.User, error)

	// GetOrCreateFederatedIdentity upserts a foreign-instance user by Ed25519 public key.
	// On conflict it refreshes username, display_name, and cached_at. Always returns a full row.
	GetOrCreateFederatedIdentity(ctx context.Context, publicKey []byte, homeInstance, username, displayName string) (*models.FederatedIdentity, error)
	// GetFederatedIdentityByPublicKey returns the cached foreign user, or (nil, nil) when absent.
	GetFederatedIdentityByPublicKey(ctx context.Context, publicKey []byte) (*models.FederatedIdentity, error)
	// GetFederatedIdentityByID returns the cached foreign user by primary-key ID, or (nil, nil) when absent.
	GetFederatedIdentityByID(ctx context.Context, id string) (*models.FederatedIdentity, error)
	// UpdateFederatedIdentityProfile refreshes username, display_name, and cached_at by ID.
	UpdateFederatedIdentityProfile(ctx context.Context, id string, username, displayName string) error

	// BIP39 auth nonce methods
	// InsertAuthNonce stores a challenge nonce associated with a public key.
	InsertAuthNonce(ctx context.Context, nonce string, publicKey []byte, expiresAt time.Time) error
	// ConsumeAuthNonce atomically deletes the nonce (if present and unexpired)
	// and returns the associated public key. Returns sql.ErrNoRows if absent or expired.
	ConsumeAuthNonce(ctx context.Context, nonce string) (publicKey []byte, err error)
	// DeleteAuthNonce removes a stored nonce regardless of expiry.
	// Used to invalidate companion link records after the first scan/resolve.
	DeleteAuthNonce(ctx context.Context, nonce string) error
	// PurgeExpiredNonces deletes all auth_nonces where expires_at < now() and
	// returns the number of rows deleted.
	PurgeExpiredNonces(ctx context.Context) (int64, error)

	// Chunked device-link archive methods (migrations 000031 + 000032).
	// Token hashes are SHA-256 of the raw 32-byte bearer tokens; raw tokens
	// never touch persistent storage.
	InsertLinkArchive(ctx context.Context, in LinkArchiveInsert) (*LinkArchive, error)
	CountActiveLinkArchivesForUser(ctx context.Context, userID string) (int, error)
	ListSupersedableLinkArchivesForUser(ctx context.Context, userID string, lastTouchBefore time.Time) ([]string, error)
	SumActiveLinkArchiveBytes(ctx context.Context) (int64, error)
	TransitionLinkArchiveState(ctx context.Context, archiveID, nextState string, allowedFrom []string) error
	GetLinkArchiveByID(ctx context.Context, archiveID string) (*LinkArchive, error)
	GetLinkArchiveByUploadTokenHash(ctx context.Context, archiveID string, tokenHash []byte) (*LinkArchive, error)
	GetLinkArchiveByDownloadTokenHash(ctx context.Context, archiveID string, tokenHash []byte) (*LinkArchive, error)
	RefreshLinkArchiveExpiry(ctx context.Context, archiveID string, ttl time.Duration) (time.Time, error)
	InsertLinkArchiveChunk(ctx context.Context, in LinkArchiveChunkInsert) error
	GetLinkArchiveChunkPointer(ctx context.Context, archiveID string, idx int) (storageBackend, storageKey string, err error)
	ListLinkArchiveChunkRows(ctx context.Context, archiveID string) ([]LinkArchiveChunkRow, error)
	MarkLinkArchiveFinalized(ctx context.Context, archiveID string) error
	DeleteLinkArchive(ctx context.Context, archiveID string) error
	ListGcEligibleLinkArchives(ctx context.Context, limit int) ([]string, error)
	PurgeExpiredLinkArchives(ctx context.Context) (int64, error)

	// Storage-backend chunk-bytes plane (migration 000032).
	// PostgresBytea backend persists archive chunk bytes here; the s3
	// backend never touches these methods.
	UpsertChunkBlob(ctx context.Context, storageKey string, bytes []byte) error
	GetChunkBlob(ctx context.Context, storageKey string) ([]byte, error)
	DeleteChunkBlob(ctx context.Context, storageKey string) error
	ChunkBlobExists(ctx context.Context, storageKey string) (bool, error)

	// Device key methods
	// InsertDeviceKey stores a certified device public key for a user.
	// certificate may be nil for the first (root) device.
	InsertDeviceKey(ctx context.Context, userID, deviceID, label string, devicePublicKey, certificate []byte) error
	// BackfillRootDeviceKey inserts a row only when (userID, deviceID) is
	// missing. Returns true when a row was actually inserted, false when
	// the (userID, deviceID) already existed (and was left untouched).
	// Used by the post-/verify backfill path so a root-key holder cannot
	// rewrite an already-certified device's public key by replaying
	// /verify with a chosen deviceID.
	BackfillRootDeviceKey(ctx context.Context, userID, deviceID, label string, devicePublicKey []byte) (bool, error)
	// ListDeviceKeys returns all device keys belonging to a user.
	ListDeviceKeys(ctx context.Context, userID string) ([]models.DeviceKey, error)
	// IsDeviceActive returns true iff a device key row still exists for
	// (userID, deviceID). Used to enforce revocation: any auth path
	// that ran beyond key validation must call this before honouring
	// the bearer.
	IsDeviceActive(ctx context.Context, userID, deviceID string) (bool, error)
	// RevokeDeviceKey deletes a specific device key. No-op if not found.
	RevokeDeviceKey(ctx context.Context, userID, deviceID string) error
	// RevokeAllDeviceKeys deletes every device key for a user (used on account wipe).
	RevokeAllDeviceKeys(ctx context.Context, userID string) error
	// UpdateDeviceLastSeen sets last_seen = now() for the given device.
	UpdateDeviceLastSeen(ctx context.Context, userID, deviceID string) error
	CreateSession(ctx context.Context, sessionID, userID, tokenHash string, expiresAt time.Time) (*models.Session, error)
	GetSessionByTokenHash(ctx context.Context, tokenHash string) (*models.Session, error)
	DeleteSessionByID(ctx context.Context, sessionID string) error
	// PurgeExpiredSessions deletes user-session rows whose expires_at is in
	// the past. Returns the number of rows removed. Hygienic only — expired
	// rows are already rejected by GetSessionByTokenHash; this prevents the
	// table from growing unboundedly.
	PurgeExpiredSessions(ctx context.Context) (int64, error)
	// PurgeStaleAdminSessions deletes admin-session rows whose expires_at is
	// in the past, plus any revoked rows older than revokedRetention. Returns
	// the number of rows removed.
	PurgeStaleAdminSessions(ctx context.Context, revokedRetention time.Duration) (int64, error)

	// MLS credential methods
	UpsertMLSCredential(ctx context.Context, userID, deviceID string, credentialBytes, signingPublicKey []byte, identityVersion int) error
	GetMLSCredential(ctx context.Context, userID, deviceID string) (credentialBytes, signingPublicKey []byte, identityVersion int, err error)

	// MLS key package methods
	InsertMLSKeyPackages(ctx context.Context, userID, deviceID string, packages [][]byte, expiresAt time.Time) error
	InsertMLSLastResortKeyPackage(ctx context.Context, userID, deviceID string, keyPackageBytes []byte) error
	ConsumeMLSKeyPackage(ctx context.Context, userID, deviceID string) (keyPackageBytes []byte, err error)
	CountUnusedMLSKeyPackages(ctx context.Context, userID, deviceID string) (int, error)
	PurgeExpiredMLSKeyPackages(ctx context.Context) (int64, error)

	// Device enumeration (now backed by mls_credentials)
	ListDeviceIDsForUser(ctx context.Context, userID string) ([]string, error)
	UpsertDevice(ctx context.Context, userID, deviceID, label string) error

	// Message methods
	InsertMessage(ctx context.Context, channelID string, senderID *string, federatedSenderID *string, recipientID *string, ciphertext []byte) (*models.Message, error)
	GetMessages(ctx context.Context, channelID, recipientID string, before time.Time, limit int) ([]models.Message, error)
	GetMessagesAfter(ctx context.Context, channelID, recipientID string, after time.Time, limit int) ([]models.Message, error)
	IsChannelMember(ctx context.Context, channelID, userID string) (bool, error)
	// GetUnreadCount returns the number of messages in channelID visible to userID
	// that are newer than the user's read marker and not sent by userID.
	GetUnreadCount(ctx context.Context, channelID, userID string) (int, error)
	// MarkChannelRead advances the read marker for (channelID, userID) to the stored
	// timestamp of messageID. Never moves the marker backward. Rejects invisible messages.
	MarkChannelRead(ctx context.Context, channelID, userID, messageID string) error

	// Instance config methods
	GetInstanceConfig(ctx context.Context) (*models.InstanceConfig, error)
	// UpdateInstanceConfig updates only the non-nil fields. serverCreationPolicy must be
	// one of "open", "paid", or "disabled" when non-nil.
	UpdateInstanceConfig(ctx context.Context, name *string, iconURL *string, registrationMode *string, guildDiscovery *string, serverCreationPolicy *string, maxServersPerUser *int, maxMembersPerServer *int, maxRegisteredUsers *int, screenShareResolutionCap *string, maxAttachmentBytes *int64, maxGuildAttachmentStorageBytes *int64, messageRetentionDays *int) error
	GetUserRole(ctx context.Context, userID string) (string, error)
	UpdateUserRole(ctx context.Context, userID, role string) error
	ListMembers(ctx context.Context) ([]models.Member, error)

	// Channel operations
	// CreateChannel uses encryptedMetadata instead of a plaintext name.
	CreateChannel(ctx context.Context, serverID string, encryptedMetadata []byte, channelType string, parentID *string, position int) (*models.Channel, error)
	ListChannels(ctx context.Context, serverID string) ([]models.Channel, error)
	GetChannelByID(ctx context.Context, channelID string) (*models.Channel, error)
	// GetChannelByTypeAndPosition replaces GetChannelByNameAndType (no name column).
	GetChannelByTypeAndPosition(ctx context.Context, serverID, channelType string, position int) (*models.Channel, error)
	// DeleteChannel deletes the channel iff it belongs to serverID. The
	// server filter is enforced in SQL as defence in depth — handler-level
	// guards already check ch.ServerID == serverID. Returns pgx.ErrNoRows
	// when no row matched, so callers can map cross-guild attempts to 404.
	DeleteChannel(ctx context.Context, channelID, serverID string) error
	// DeleteChannelTree atomically removes a channel and, when the
	// target is a category, every channel parented to it. Returns the
	// ids actually removed (children first, root last) and the
	// attachment storage_keys that the caller must asynchronously
	// purge from the blob backend. Returns pgx.ErrNoRows when the
	// root does not exist or belongs to another server.
	DeleteChannelTree(ctx context.Context, channelID, serverID string) (deletedIDs []string, storageKeys []string, err error)
	// MoveChannel updates parent/position iff the channel and any non-nil
	// parent both belong to serverID. Returns pgx.ErrNoRows on cross-guild
	// mismatch.
	MoveChannel(ctx context.Context, channelID, serverID string, parentID *string, position int) error

	// Attachments (per-channel encrypted blob refs).
	InsertAttachment(ctx context.Context, channelID, ownerID, storageKey, contentType string, size int64) (*models.Attachment, error)
	GetAttachmentByID(ctx context.Context, attachmentID string) (*models.Attachment, error)
	SoftDeleteAttachment(ctx context.Context, attachmentID, ownerID string) (*models.Attachment, error)
	SoftDeleteAttachmentsByID(ctx context.Context, attachmentIDs []string) ([]models.Attachment, error)
	ListAttachmentsForGuildQuota(ctx context.Context, channelID string) (serverID string, active []models.Attachment, err error)
	ListExpiredAttachments(ctx context.Context, retentionDays int, limit int) ([]models.Attachment, error)
	PurgeExpiredMessages(ctx context.Context, retentionDays int) (int64, error)

	// Server templates
	ListServerTemplates(ctx context.Context) ([]models.ServerTemplate, error)
	GetServerTemplateByID(ctx context.Context, id string) (*models.ServerTemplate, error)
	GetDefaultServerTemplate(ctx context.Context) (*models.ServerTemplate, error)
	CreateServerTemplate(ctx context.Context, name string, channels json.RawMessage, isDefault bool) (*models.ServerTemplate, error)
	UpdateServerTemplate(ctx context.Context, id string, name string, channels json.RawMessage, isDefault bool) error
	DeleteServerTemplate(ctx context.Context, id string) error

	// Invite operations
	CreateInvite(ctx context.Context, serverID, code, createdBy string, maxUses int, expiresAt time.Time) (*models.InviteCode, error)
	GetInviteByCode(ctx context.Context, code string) (*models.InviteCode, error)
	ClaimInviteUse(ctx context.Context, code string) (bool, error)

	// CountOwnedServers returns the number of non-DM servers where the user is the owner.
	CountOwnedServers(ctx context.Context, userID string) (int, error)
	// UpdateServerMemberCapOverride sets or clears the per-server member cap override.
	UpdateServerMemberCapOverride(ctx context.Context, serverID string, cap *int) error

	// Server operations
	// CreateServer accepts encryptedMetadata (may be nil for two-step creation flow).
	CreateServer(ctx context.Context, encryptedMetadata []byte) (*models.Server, error)
	// UpdateServerEncryptedMetadata updates only the encrypted_metadata blob.
	// Used in the two-step guild creation flow and after MLS epoch advances.
	// Returns sql.ErrNoRows if no server with that ID exists.
	UpdateServerEncryptedMetadata(ctx context.Context, serverID string, encryptedMetadata []byte) error
	GetServerByID(ctx context.Context, serverID string) (*models.Server, error)
	ListServersForUser(ctx context.Context, userID string) ([]models.Server, error)
	DeleteServer(ctx context.Context, serverID string) error
	ListGuildBillingStats(ctx context.Context) ([]models.GuildBillingStats, error)

	// Server member operations
	// AddServerMember uses permissionLevel int instead of role string.
	AddServerMember(ctx context.Context, serverID, userID string, permissionLevel int) error
	RemoveServerMember(ctx context.Context, serverID, userID string) error
	// GetServerMemberLevel returns the permission_level int for a guild member.
	GetServerMemberLevel(ctx context.Context, serverID, userID string) (int, error)
	// UpdateServerMemberLevel sets a new permission level for the given member.
	UpdateServerMemberLevel(ctx context.Context, serverID, userID string, permissionLevel int) error
	ListServerMembers(ctx context.Context, serverID string) ([]models.ServerMemberWithUser, error)

	// AddFederatedServerMember inserts a guild membership record for a federated (foreign-instance) user.
	AddFederatedServerMember(ctx context.Context, serverID, federatedIdentityID string, permissionLevel int) error
	// RemoveFederatedServerMember removes a federated user from the guild.
	RemoveFederatedServerMember(ctx context.Context, serverID, federatedIdentityID string) error
	// GetServerMemberLevelByFederatedID returns the permission_level for a federated guild member.
	GetServerMemberLevelByFederatedID(ctx context.Context, serverID, federatedIdentityID string) (int, error)

	// Moderation - bans
	InsertBan(ctx context.Context, serverID, userID, actorID, reason string, expiresAt *time.Time) (*models.Ban, error)
	GetActiveBan(ctx context.Context, serverID, userID string) (*models.Ban, error)
	LiftBan(ctx context.Context, banID, liftedByID string) error
	ListActiveBans(ctx context.Context, serverID string) ([]models.Ban, error)

	// Moderation - mutes
	InsertMute(ctx context.Context, serverID, userID, actorID, reason string, expiresAt *time.Time) (*models.Mute, error)
	GetActiveMute(ctx context.Context, serverID, userID string) (*models.Mute, error)
	LiftMute(ctx context.Context, muteID, liftedByID string) error
	ListActiveMutes(ctx context.Context, serverID string) ([]models.Mute, error)

	// Moderation - audit log
	InsertAuditLog(ctx context.Context, serverID, actorID string, targetID *string, action, reason string, metadata map[string]interface{}) error
	ListAuditLog(ctx context.Context, serverID string, limit, offset int, filter *AuditLogFilter) ([]models.AuditLogEntry, error)

	// Moderation - messages
	GetMessageByID(ctx context.Context, messageID string) (*models.Message, error)
	// DeleteMessage deletes a message iff it lives in a channel belonging
	// to serverID. Returns pgx.ErrNoRows on cross-guild mismatch so callers
	// can map to 404.
	DeleteMessage(ctx context.Context, messageID, serverID string) error

	// Moderation - sessions
	DeleteSessionsByUserID(ctx context.Context, userID string) error

	// Instance bans
	InsertInstanceBan(ctx context.Context, userID, actorID, reason string, expiresAt *time.Time) (*models.InstanceBan, error)
	GetActiveInstanceBan(ctx context.Context, userID string) (*models.InstanceBan, error)
	LiftInstanceBan(ctx context.Context, banID, liftedByID string) error

	// Instance audit log
	InsertInstanceAuditLog(ctx context.Context, actorID string, targetID *string, action, reason string, metadata map[string]interface{}) error
	ListInstanceAuditLog(ctx context.Context, limit, offset int, filter *InstanceAuditLogFilter) ([]models.InstanceAuditLogEntry, error)

	// User search (admin)
	SearchUsers(ctx context.Context, query string, limit int) ([]models.UserSearchResult, error)

	// System messages
	InsertSystemMessage(ctx context.Context, serverID, eventType, actorID string, targetID *string, reason string, metadata map[string]interface{}) (*models.SystemMessage, error)
	ListSystemMessages(ctx context.Context, serverID string, before time.Time, limit int) ([]models.SystemMessage, error)
	PurgeExpiredSystemMessages(ctx context.Context, retentionDays int) (int64, error)
	GetSystemMessageRetentionDays(ctx context.Context) (*int, error)

	// MLS group methods
	// groupType is "text" or "voice" - each channel can have one group of each type.
	UpsertMLSGroupInfo(ctx context.Context, channelID string, groupType string, groupInfoBytes []byte, epoch int64) error
	GetMLSGroupInfo(ctx context.Context, channelID string, groupType string) (groupInfoBytes []byte, epoch int64, err error)
	DeleteMLSGroupInfo(ctx context.Context, channelID string, groupType string) error
	AppendMLSCommit(ctx context.Context, channelID string, epoch int64, commitBytes []byte, senderID string) error
	GetMLSCommitsSinceEpoch(ctx context.Context, channelID string, sinceEpoch int64, limit int) ([]MLSCommitRow, error)
	PurgeOldMLSCommits(ctx context.Context, maxPerChannel int) (int64, error)
	StorePendingWelcome(ctx context.Context, channelID, recipientUserID, senderID string, welcomeBytes []byte, epoch int64) error
	GetPendingWelcomes(ctx context.Context, recipientUserID string) ([]PendingWelcomeRow, error)
	DeletePendingWelcome(ctx context.Context, welcomeID string) error
	// GetVoiceKeyRotationHours returns the configured voice group key rotation interval in hours.
	GetVoiceKeyRotationHours(ctx context.Context) (int, error)

	// MLS guild metadata group methods (server_id scoped, group_type = 'metadata').
	UpsertMLSGuildMetadataGroupInfo(ctx context.Context, serverID string, groupInfoBytes []byte, epoch int64) error
	GetMLSGuildMetadataGroupInfo(ctx context.Context, serverID string) (groupInfoBytes []byte, epoch int64, err error)
	DeleteMLSGuildMetadataGroupInfo(ctx context.Context, serverID string) error

	// Guild metrics increment methods.
	// IncrementGuildMessageCount increments the message_count and updates last_active_at for
	// the guild that owns the given channel.
	IncrementGuildMessageCount(ctx context.Context, channelID string) error
	// IncrementGuildMemberCount adjusts member_count by delta (+1 on join, -1 on leave).
	IncrementGuildMemberCount(ctx context.Context, serverID string, delta int) error
	// UpdateGuildChannelCounts recalculates text_channel_count and voice_channel_count for the guild.
	UpdateGuildChannelCounts(ctx context.Context, serverID string) error

	// FindDMGuild returns the DM guild for the given user pair, or sql.ErrNoRows
	// when no DM exists yet. User IDs are canonically ordered internally.
	FindDMGuild(ctx context.Context, userAID, userBID string) (*models.Server, error)
	// CreateDMGuild creates a DM guild for the two users in a single transaction.
	// Inserts the servers row (is_dm=true), dm_pairs entry, both server_members
	// (PermissionLevelOwner), and one text channel. Returns the new server.
	CreateDMGuild(ctx context.Context, userAID, userBID string) (*models.Server, *models.Channel, error)
	// DiscoverGuilds returns publicly discoverable guilds filtered by category,
	// search query, and sort order. Returns results and total count for pagination.
	DiscoverGuilds(ctx context.Context, category, search, sort string, page, pageSize int) ([]models.DiscoverGuild, int, error)
	// SearchUsersPublic returns users matching the query on username or displayName.
	// Only id, username, and displayName are returned - no ban/role info.
	SearchUsersPublic(ctx context.Context, query string, limit int) ([]models.UserSearchPublicResult, error)

	// Transparency log methods (migration 000019).
	// InsertTransparencyLogEntry persists a signed log entry after it is appended
	// to the Merkle tree. All byte slices are mandatory.
	InsertTransparencyLogEntry(ctx context.Context, leafIndex uint64, operation string, userPubKey, subjectKey, entryCBOR, leafHash, userSig, logSig []byte) error
	// GetTransparencyLogEntriesByPubKey returns all log entries for a public key,
	// ordered by leaf_index ASC. Returns an empty slice when no entries exist.
	GetTransparencyLogEntriesByPubKey(ctx context.Context, pubKey []byte) ([]models.TransparencyLogEntry, error)
	// GetLatestTransparencyTreeHead returns the highest tree_size row, or nil
	// when the log is empty (no error).
	GetLatestTransparencyTreeHead(ctx context.Context) (*models.TransparencyTreeHead, error)
	// InsertTransparencyTreeHead persists the Merkle tree state after each append.
	InsertTransparencyTreeHead(ctx context.Context, treeSize uint64, rootHash, fringe, headSig []byte) error
}

Store defines the database operations used by the API and WebSocket layers. *Pool satisfies this interface. Use for dependency injection in tests.

Jump to

Keyboard shortcuts

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