store

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package store owns the SQLite database: opening it with the right pragmas, verifying that the schema is in place and the concrete repository types built on hand-written SQL. Migrations themselves live outside the application binary (see cmd/migrate). The database/sql primitives stay concrete inside this package; consumers depend on narrow interfaces of their own.

Index

Constants

This section is empty.

Variables

View Source
var ErrLeaseLost = errors.New("outbox lease lost")

ErrLeaseLost reports that a terminal transition was attempted by a worker that no longer owns the action: the lease expired and another worker reclaimed the row. The caller MUST NOT retry the transition — the current owner is responsible for the outcome.

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

ErrNotFound is returned by repository getters when no row matches.

View Source
var ErrUnmigrated = errors.New(
	"database is not migrated; run `task migrate:up`")

ErrUnmigrated is returned by CheckSchema when the database has no applied migrations. The wrapped message instructs the operator to run the migrate CLI.

Functions

func AlertSeverities added in v0.2.0

func AlertSeverities() []string

AlertSeverities returns every severity `admin_alerts.severity` accepts, from least to most urgent.

The list is owned here because the constraint is: `0001_init.sql` pins the column to exactly these four values. Consumers that must enumerate the whole set — the metrics endpoint zero-fills one open-alert series per severity, so that "no critical alerts" reads as `0` instead of as a missing series — take it from here rather than repeating the literals.

func CheckSchema

func CheckSchema(ctx context.Context, db *sql.DB) error

CheckSchema returns ErrUnmigrated if the database has no applied migrations. The application never creates schema on its own; this is the boundary check between "operator forgot to run migrate" and "schema is good enough to serve". It speaks plain SQL on purpose so the goose package does not get linked into the runtime binary.

func IsUpdateAlreadyTerminal

func IsUpdateAlreadyTerminal(err error) bool

IsUpdateAlreadyTerminal reports whether a terminal mark failed because the row was no longer pending.

func Open

func Open(ctx context.Context, dbPath string) (*sql.DB, error)

Open opens the SQLite database at dbPath, creating its parent directory (mode 0700) when missing, and configures the connection pool. Migrations are applied separately by the migrate CLI (see cmd/migrate); call CheckSchema to verify that schema is in place before serving traffic.

func WithTx added in v0.1.1

func WithTx(ctx context.Context, db DBTX, fn func(q DBTX) error) error

WithTx runs fn inside a single transaction when db can start one (a *sql.DB), committing on success and rolling back on error. When db cannot start a transaction (already a *sql.Tx, or a test double), fn runs directly against db. The DBTX handed to fn is tx-scoped, so repositories built from it use the transaction's connection rather than the pool. It centralizes the BeginTx type assertion so callers do not hand-roll it.

Types

type AccessActionInput

type AccessActionInput struct {
	Type     domain.ActionType
	TGID     *int64
	Resource *domain.Resource

	// AlertID links the row to the operational alert it reports on. Set it on
	// every operator notification about an alert: it is the only handle
	// resolve-time cancellation has on the delivery.
	AlertID        *int64
	IdempotencyKey string
	PayloadJSON    []byte
	RunAfter       time.Time
	MaxAttempts    int
}

AccessActionInput describes an action to enqueue in access_actions.

type AlertCount added in v0.2.0

type AlertCount struct {
	Kind     string
	Severity string
	Status   string
	Count    int
}

AlertCount is an operational alert count grouped by kind, severity and status.

type AlertInput

type AlertInput struct {
	Severity  string // info|warning|error|critical
	Kind      string
	Title     string
	Detail    string
	TGID      *int64
	DedupeKey string

	// OwnerNotifiedByCaller marks an alert whose owner notification the caller
	// sends itself, with copy written for that specific failure. A
	// delivery-enabled repository then skips its own generic owner DM, so one
	// failure costs the owner one message instead of two saying the same thing
	// in different words.
	//
	// It suppresses the owner DM only. When an admin log chat is configured the
	// generic delivery is not addressed to the owner at all — it is a line in
	// an operator feed — and it still goes out: dropping it would trade a
	// duplicate for a hole in the log.
	//
	// Every other alert kind is unaffected: with the flag unset the repository
	// remains the sole producer, which is what the paths with no message of
	// their own rely on.
	OwnerNotifiedByCaller bool
}

AlertInput describes a new operational alert for the administrator. A nil TGID is stored as a SQL NULL.

type Alerts

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

Alerts is the repository for the admin_alerts table.

func NewAlerts

func NewAlerts(db DBTX) *Alerts

NewAlerts returns an Alerts repository backed by db or tx.

func NewAlertsWithDelivery

func NewAlertsWithDelivery(
	db DBTX,
	outbox *Outbox,
	ownerIDs []int64,
	adminLogChatID *int64,
) *Alerts

NewAlertsWithDelivery returns an Alerts repository that also enqueues durable operator notification actions in the same transaction.

func (*Alerts) Create

func (r *Alerts) Create(ctx context.Context, a AlertInput) (int64, error)

Create inserts a new open alert and returns its generated id.

func (*Alerts) CreateOpenIfMissing

func (r *Alerts) CreateOpenIfMissing(
	ctx context.Context, a AlertInput,
) (int64, bool, error)

CreateOpenIfMissing inserts an open alert unless one with the same kind and title is already open. The bool reports whether a new row was inserted.

func (*Alerts) IsOpen added in v0.2.0

func (r *Alerts) IsOpen(ctx context.Context, id int64) (bool, error)

IsOpen reports whether the alert is still open. A missing alert reads as not open: a delivery whose alert row is gone has nothing left to describe.

func (*Alerts) ResolveOpen

func (r *Alerts) ResolveOpen(ctx context.Context, kind, key string) error

ResolveOpen resolves an open alert by kind and stable key or title.

func (*Alerts) ResolveOpenByTitle

func (r *Alerts) ResolveOpenByTitle(ctx context.Context, kind, title string) error

ResolveOpenByTitle resolves matching open alerts and cancels the operator deliveries they still have queued. Missing alerts are a no-op.

Resolution and cancellation share one transaction so an alert can never end up resolved with its notifications left in the queue. Cancellation is best-effort even so: a worker that leased a delivery just before this commits still sends it, and closing that window would mean holding the alert row across a Telegram call. The enforcer's pre-execute check narrows the window; nothing removes it.

type Audit

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

Audit is the repository for the append-only audit_log table.

func NewAudit

func NewAudit(db DBTX) *Audit

NewAudit returns an Audit repository backed by db or tx.

func (*Audit) Append

func (r *Audit) Append(ctx context.Context, e AuditEntry) error

Append writes one audit record.

func (*Audit) ListRecentByUser

func (r *Audit) ListRecentByUser(
	ctx context.Context, tgID int64, limit int,
) ([]AuditEntry, error)

ListRecentByUser returns recent audit rows for a user from newest to oldest.

type AuditEntry

type AuditEntry struct {
	ID        int64
	TGID      *int64
	Kind      string
	Source    string
	Resource  string
	Actor     string // defaults to "system" when empty
	Detail    string
	CreatedAt time.Time
}

AuditEntry is one append-only business-journal record. A nil TGID, or an empty Source or Resource, is stored as a SQL NULL.

type Cleanup

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

Cleanup contains repository operations for retention and maintenance.

func NewCleanup

func NewCleanup(db DBTX) *Cleanup

NewCleanup returns cleanup operations backed by db or tx.

func (*Cleanup) DeleteAudit

func (r *Cleanup) DeleteAudit(ctx context.Context, cutoff time.Time) (int64, error)

DeleteAudit deletes old audit rows after retention.

func (*Cleanup) DeleteResolvedAlerts

func (r *Cleanup) DeleteResolvedAlerts(
	ctx context.Context,
	cutoff time.Time,
) (int64, error)

DeleteResolvedAlerts deletes resolved alerts after retention.

func (*Cleanup) DeleteSettledActions added in v0.2.0

func (r *Cleanup) DeleteSettledActions(
	ctx context.Context,
	cutoff time.Time,
) (int64, error)

DeleteSettledActions deletes outbox rows that ended without leaving anything for an operator to look at: `done` (delivered) and `cancelled` (retired before delivery, e.g. because the alert it reported on resolved first). `dead` rows are preserved — those are the ones worth investigating.

func (*Cleanup) DeleteTerminalTelegramUpdates

func (r *Cleanup) DeleteTerminalTelegramUpdates(
	ctx context.Context,
	cutoff time.Time,
) (int64, error)

DeleteTerminalTelegramUpdates deletes processed or ignored inbox rows.

func (*Cleanup) DeleteTerminalTributeEvents

func (r *Cleanup) DeleteTerminalTributeEvents(
	ctx context.Context,
	cutoff time.Time,
) (int64, error)

DeleteTerminalTributeEvents deletes processed or ignored Tribute rows.

func (*Cleanup) ExpireInvite

func (r *Cleanup) ExpireInvite(ctx context.Context, id int64) error

ExpireInvite marks an invite as expired.

func (*Cleanup) WALCheckpoint

func (r *Cleanup) WALCheckpoint(ctx context.Context) error

WALCheckpoint runs a passive SQLite WAL checkpoint.

type CountByName

type CountByName struct {
	Name  string
	Count int
}

CountByName is a bounded-label counter value.

type DBTX

type DBTX interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

DBTX is the narrow SQL executor shared by *sql.DB and *sql.Tx. Repository constructors accept it so handlers can bind repositories to the transaction that owns the update's terminal state transition.

type ExportRow

type ExportRow struct {
	TGID          int64
	Username      string
	FirstName     string
	LastName      string
	LanguageCode  string
	DMState       domain.DMState
	Banned        bool
	BannedReason  string
	Subscriptions string
	ExpiresAt     string
	GrantChat     string
	GrantChannel  string
	Whitelisted   bool
	LastSeenAt    time.Time
}

ExportRow is one CSV row for owner export.

type GrantCount

type GrantCount struct {
	Resource domain.Resource
	State    domain.GrantState
	Count    int
}

GrantCount is an access grant count grouped by resource and state.

type Grants

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

Grants is the repository for the access_grants table: one row per (user, resource) pair.

func NewGrants

func NewGrants(db DBTX) *Grants

NewGrants returns a Grants repository backed by db or tx.

func (*Grants) Get

func (r *Grants) Get(
	ctx context.Context, tgID int64, resource domain.Resource,
) (domain.AccessGrant, error)

Get returns the access grant for (tgID, resource), or ErrNotFound.

func (*Grants) ListBotAdmittedJoinedTGIDs

func (r *Grants) ListBotAdmittedJoinedTGIDs(
	ctx context.Context,
	limit int,
) ([]int64, error)

ListBotAdmittedJoinedTGIDs returns users with current bot-managed access.

func (*Grants) ListByUser

func (r *Grants) ListByUser(
	ctx context.Context, tgID int64,
) ([]domain.AccessGrant, error)

ListByUser returns all access grants for a user.

func (*Grants) ListEligibleForRevoke

func (r *Grants) ListEligibleForRevoke(
	ctx context.Context,
	tgID int64,
) ([]domain.AccessGrant, error)

ListEligibleForRevoke returns grants that automatic revocation may touch.

func (*Grants) MarkJoined

func (r *Grants) MarkJoined(
	ctx context.Context,
	tgID int64,
	resource domain.Resource,
	admittedBy string,
) error

MarkJoined records observed membership and admission metadata.

func (*Grants) MarkJoinedByAdmission

func (r *Grants) MarkJoinedByAdmission(
	ctx context.Context,
	tgID int64,
	resource domain.Resource,
	admittedBy string,
) error

MarkJoinedByAdmission records a fresh bot-approved admission cycle. Unlike passive verification, this may restore a previously revoked grant.

func (*Grants) MarkLeftUnlessRevoked

func (r *Grants) MarkLeftUnlessRevoked(
	ctx context.Context,
	tgID int64,
	resource domain.Resource,
) (bool, error)

MarkLeftUnlessRevoked records that a user left a resource, preserving a prior revoked state.

func (*Grants) MarkPending

func (r *Grants) MarkPending(
	ctx context.Context,
	tgID int64,
	resource domain.Resource,
) (time.Time, error)

MarkPending idempotently stores a pending grant without changing already joined access. It returns the grant cycle timestamp: stable while the row remains pending, refreshed when a new pending cycle starts after left/external states.

func (*Grants) Revoke

func (r *Grants) Revoke(
	ctx context.Context,
	tgID int64,
	resource domain.Resource,
	reason string,
) (bool, error)

Revoke marks one grant as revoked. Missing or already-revoked rows are no-op.

func (*Grants) Upsert

func (r *Grants) Upsert(ctx context.Context, g domain.AccessGrant) error

Upsert inserts or updates the access grant for a (user, resource) pair. created_at is preserved on update; updated_at is set to now.

type InviteLinkCount

type InviteLinkCount struct {
	Resource domain.Resource
	Mode     domain.InviteMode
	Status   domain.InviteStatus
	Count    int
}

InviteLinkCount is an invite-link count grouped by resource, mode and status.

type InviteLinkInput

type InviteLinkInput struct {
	TGID               *int64
	Resource           domain.Resource
	Mode               domain.InviteMode
	InviteLink         string
	InviteLinkHash     string
	TelegramName       string
	Nonce              string
	CreatesJoinRequest bool
	ExpiresAt          *time.Time
}

InviteLinkInput describes a Telegram invite link to persist.

type Invites

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

Invites is the repository for invite_links.

func NewInvites

func NewInvites(db DBTX) *Invites

NewInvites returns an Invites repository backed by db or tx.

func (*Invites) FindActiveByHash

func (r *Invites) FindActiveByHash(
	ctx context.Context,
	resource domain.Resource,
	inviteLinkHash string,
) (domain.InviteLink, bool, error)

FindActiveByHash returns an active invite link for a managed resource by hash.

func (*Invites) FindActivePersonal

func (r *Invites) FindActivePersonal(
	ctx context.Context,
	tgID int64,
	resource domain.Resource,
	mode domain.InviteMode,
) (domain.InviteLink, bool, error)

FindActivePersonal returns the active personal or direct link.

func (*Invites) FindActiveShared

func (r *Invites) FindActiveShared(
	ctx context.Context,
	resource domain.Resource,
	mode domain.InviteMode,
) (domain.InviteLink, bool, error)

FindActiveShared returns the active shared link for a resource and mode.

func (*Invites) GetByID

func (r *Invites) GetByID(ctx context.Context, id int64) (domain.InviteLink, error)

GetByID returns an invite link by primary key.

func (*Invites) ListExpiredActive

func (r *Invites) ListExpiredActive(
	ctx context.Context,
	now time.Time,
	limit int,
) ([]domain.InviteLink, error)

ListExpiredActive returns active invite links whose TTL has elapsed.

func (*Invites) MarkStatus

func (r *Invites) MarkStatus(
	ctx context.Context,
	id int64,
	status domain.InviteStatus,
	attemptedBy *int64,
	lastError string,
) error

MarkStatus moves an invite link to a new lifecycle status.

func (*Invites) SaveCreated

func (r *Invites) SaveCreated(
	ctx context.Context,
	input InviteLinkInput,
) (domain.InviteLink, error)

SaveCreated inserts a newly created Telegram invite link.

type Meta

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

Meta is the repository for the meta key-value table: poller offset, reconcile time, chat health and other service state.

func NewMeta

func NewMeta(db DBTX) *Meta

NewMeta returns a Meta repository backed by db or tx.

func (*Meta) Get

func (r *Meta) Get(ctx context.Context, key string) (string, bool, error)

Get returns the value for a key. The second result is false when the key is absent.

func (*Meta) GetUpdateOffset

func (r *Meta) GetUpdateOffset(ctx context.Context) (int64, bool, error)

GetUpdateOffset returns the durable Telegram polling offset.

func (*Meta) Set

func (r *Meta) Set(ctx context.Context, key, value string) error

Set stores a value for a key, overwriting any existing value.

func (*Meta) SetHealth

func (r *Meta) SetHealth(ctx context.Context, key, value string) error

SetHealth stores a stable health.<key> value. The caller may pass either "club_chat" or "health.club_chat".

func (*Meta) SetUpdateOffset

func (r *Meta) SetUpdateOffset(ctx context.Context, offset int64) error

SetUpdateOffset stores the durable Telegram polling offset.

type Ops

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

Ops contains read-only operational queries for owner commands and metrics.

func NewOps

func NewOps(db DBTX) *Ops

NewOps returns read-only operational queries backed by db or tx.

func (*Ops) AlertCounts added in v0.2.0

func (r *Ops) AlertCounts(ctx context.Context) ([]AlertCount, error)

AlertCounts returns operational alert counts grouped by bounded dimensions.

func (*Ops) ExportRows

func (r *Ops) ExportRows(ctx context.Context, limit int) ([]ExportRow, error)

ExportRows returns current users and their active access state.

func (*Ops) InviteLinkCounts

func (r *Ops) InviteLinkCounts(ctx context.Context) ([]InviteLinkCount, error)

InviteLinkCounts returns invite-link counts grouped by bounded dimensions.

func (*Ops) OpenAlerts

func (r *Ops) OpenAlerts(ctx context.Context, limit int) ([]OpsAlert, error)

OpenAlerts returns open alerts ordered for operator triage.

func (*Ops) OutboxBacklog added in v0.2.0

func (r *Ops) OutboxBacklog(
	ctx context.Context,
	now time.Time,
) (OutboxBacklog, error)

OutboxBacklog returns queue pressure at now in one scan.

The aggregate is expressed with `sum(CASE WHEN ... THEN 1 ELSE 0 END)` and `min(CASE WHEN ... THEN col END)` rather than the `FILTER` clause, to stay on the SQL surface the rest of this package already uses. An aggregate without GROUP BY always yields exactly one row, so the empty table arrives here as a row of NULLs: the counts are coalesced in SQL and the timestamps are scanned as nullable, which is what makes an empty queue report zeros instead of failing to scan.

func (*Ops) RevocationReasonCounts

func (r *Ops) RevocationReasonCounts(ctx context.Context) ([]CountByName, error)

RevocationReasonCounts returns bounded revocation counters.

func (*Ops) Stats

func (r *Ops) Stats(ctx context.Context, now time.Time) (OpsStats, error)

Stats returns a bounded operational summary.

func (*Ops) TelegramUpdateCounts

func (r *Ops) TelegramUpdateCounts(ctx context.Context) ([]CountByName, error)

TelegramUpdateCounts returns update counts grouped by type.

func (*Ops) TributeEventCounts

func (r *Ops) TributeEventCounts(ctx context.Context) ([]CountByName, error)

TributeEventCounts returns webhook counts grouped by terminal status.

type OpsAlert

type OpsAlert struct {
	ID        int64
	Severity  string
	Kind      string
	Title     string
	Detail    string
	CreatedAt time.Time
}

OpsAlert is one open alert for owner summaries.

type OpsStats

type OpsStats struct {
	ActiveSubscriptions []CountByName
	Grants              []GrantCount
	PendingRevocations  int
	DueRevocations      int
	Health              map[string]string
	ReconcileLastRunAt  *time.Time
	Outbox              []OutboxCount
	OpenAlerts          int
}

OpsStats is the owner-facing runtime summary.

type Outbox

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

Outbox is the repository for durable Telegram actions.

func NewOutbox

func NewOutbox(db DBTX) *Outbox

NewOutbox returns an Outbox repository backed by db or tx.

func (*Outbox) CancelQueuedForAlert added in v0.2.0

func (r *Outbox) CancelQueuedForAlert(
	ctx context.Context,
	alertID int64,
	reason string,
) (int64, error)

CancelQueuedForAlert retires the deliveries still waiting in the queue for alertID and reports how many rows it retired.

Only `queued` rows are touched. A `running` row is mid-flight and belongs to the worker that leased it; cancelling it here would be a second writer racing that worker for the outcome, which is exactly what lease fencing exists to prevent. The worker's own pre-execute check covers that narrow window instead, so cancellation is best-effort by construction: an action leased microseconds before this statement commits can still be delivered.

func (*Outbox) Enqueue

func (r *Outbox) Enqueue(
	ctx context.Context,
	input AccessActionInput,
) (domain.AccessAction, bool, error)

Enqueue idempotently stores one queued action.

func (*Outbox) GetByID

func (r *Outbox) GetByID(
	ctx context.Context,
	id int64,
) (domain.AccessAction, error)

GetByID returns an action by primary key.

func (*Outbox) GetByIdempotencyKey

func (r *Outbox) GetByIdempotencyKey(
	ctx context.Context,
	key string,
) (domain.AccessAction, error)

GetByIdempotencyKey returns an action by its unique idempotency key.

func (*Outbox) LeaseReady

func (r *Outbox) LeaseReady(
	ctx context.Context,
	now time.Time,
	leaseFor time.Duration,
) (domain.AccessAction, bool, error)

LeaseReady atomically leases one ready or expired running action.

func (*Outbox) MarkCancelled added in v0.2.0

func (r *Outbox) MarkCancelled(
	ctx context.Context,
	id int64,
	leaseUntil time.Time,
	reason string,
) error

MarkCancelled retires a leased action that must not be executed after all, recording why in last_error. It is not a failure: nothing was attempted and nothing is owed a retry. leaseUntil is the fencing token returned by LeaseReady; a stale one yields ErrLeaseLost.

func (*Outbox) MarkDead

func (r *Outbox) MarkDead(
	ctx context.Context,
	id int64,
	leaseUntil time.Time,
	lastError string,
) error

MarkDead moves an action to dead and records the final error. leaseUntil is the fencing token returned by LeaseReady; a stale one yields ErrLeaseLost.

func (*Outbox) MarkDone

func (r *Outbox) MarkDone(
	ctx context.Context,
	id int64,
	leaseUntil time.Time,
) error

MarkDone marks a running action as successfully completed. leaseUntil is the fencing token returned by LeaseReady; a stale one yields ErrLeaseLost.

func (*Outbox) ReleaseLease added in v0.2.0

func (r *Outbox) ReleaseLease(
	ctx context.Context,
	id int64,
	leaseUntil time.Time,
) error

ReleaseLease returns an in-flight action to the queue without recording a failed attempt. Used when the process stops mid-execution: the next process picks the action up immediately instead of waiting out locked_until.

func (*Outbox) Retry

func (r *Outbox) Retry(
	ctx context.Context,
	id int64,
	leaseUntil time.Time,
	runAfter time.Time,
	lastError string,
) (domain.AccessAction, error)

Retry returns an action to the queue and records retry metadata. leaseUntil is the fencing token returned by LeaseReady; a stale one yields ErrLeaseLost.

type OutboxBacklog added in v0.2.0

type OutboxBacklog struct {
	// Queued counts rows waiting for a worker, whether or not they are due.
	Queued int
	// Running counts rows a worker currently holds a lease on.
	Running int
	// Due counts queued rows whose run_after has already passed — the part of
	// the backlog that a healthy pool would be draining right now.
	Due int
	// OldestQueuedAge is now minus the oldest queued row's created_at: how long
	// the least recently created piece of pending work has existed. Zero when
	// nothing is queued.
	OldestQueuedAge time.Duration
	// OldestDueAge is now minus the earliest run_after among due rows: how long
	// the queue has been overdue. Zero when nothing is due, which is the normal
	// state of a pool that keeps up.
	OldestDueAge time.Duration
}

OutboxBacklog is queue pressure at one instant: how much work is waiting, how much is in flight, and how long the oldest waiting item has waited.

Counts and ages come from a single scan so they describe the same instant; two queries could disagree with each other while a worker commits between them, and a backlog metric that contradicts itself is worse than none.

type OutboxCount

type OutboxCount struct {
	Type   domain.ActionType
	Status domain.ActionStatus
	Count  int
}

OutboxCount is an outbox count grouped by action type and status.

type Revocations

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

Revocations is the repository for the pending_revocations table — the grace-period queue, keyed by user.

func NewRevocations

func NewRevocations(db DBTX) *Revocations

NewRevocations returns a Revocations repository backed by db or tx.

func (*Revocations) CreateIfAbsent

func (r *Revocations) CreateIfAbsent(
	ctx context.Context,
	p domain.PendingRevocation,
) (bool, error)

CreateIfAbsent schedules a revocation without changing an existing one.

func (*Revocations) Delete

func (r *Revocations) Delete(ctx context.Context, tgID int64) error

Delete cancels a pending revocation. Removing a missing row is a no-op.

func (*Revocations) Get

Get returns a pending revocation, or ok=false when none exists.

func (*Revocations) ListDue

func (r *Revocations) ListDue(
	ctx context.Context,
	now time.Time,
	limit int,
) ([]domain.PendingRevocation, error)

ListDue returns due revocations ordered by scheduled_at.

func (*Revocations) MarkNotified

func (r *Revocations) MarkNotified(ctx context.Context, tgID int64) error

MarkNotified records that the warning message was scheduled.

func (*Revocations) Upsert

Upsert schedules (or reschedules) a pending revocation for a user.

type Subscriptions

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

Subscriptions is the repository for the subscriptions table, which is append-only: a new period adds a new row and an expired one is marked rather than deleted.

func NewSubscriptions

func NewSubscriptions(db DBTX) *Subscriptions

NewSubscriptions returns a Subscriptions repository backed by db or tx.

func (*Subscriptions) Create

Create inserts a new subscription row and returns its generated id. The partial unique index idx_subscriptions_active_unique rejects a second active subscription for the same (user, platform) pair.

func (*Subscriptions) ExpireActive

func (r *Subscriptions) ExpireActive(
	ctx context.Context,
	tgID int64,
	platform domain.Platform,
	endedAt time.Time,
	signal string,
) (bool, error)

ExpireActive closes the active row for (tgID, platform), if present.

func (*Subscriptions) ExpireManual

func (r *Subscriptions) ExpireManual(
	ctx context.Context,
	tgID int64,
	endedAt time.Time,
	signal string,
) (bool, error)

ExpireManual expires the active manual subscription, if one exists.

func (*Subscriptions) GetActive

func (r *Subscriptions) GetActive(
	ctx context.Context, tgID int64, platform domain.Platform,
) (domain.Subscription, bool, error)

GetActive returns the active subscription for (tgID, platform), or false when none exists. idx_subscriptions_active_unique guarantees at most one such row.

func (*Subscriptions) ListActiveByUser

func (r *Subscriptions) ListActiveByUser(
	ctx context.Context, tgID int64,
) ([]domain.Subscription, error)

ListActiveByUser returns all active subscriptions for a user.

func (*Subscriptions) ListActiveTGIDs

func (r *Subscriptions) ListActiveTGIDs(
	ctx context.Context,
	limit int,
) ([]int64, error)

ListActiveTGIDs returns users that have at least one active subscription.

func (*Subscriptions) ListByUser

func (r *Subscriptions) ListByUser(
	ctx context.Context, tgID int64,
) ([]domain.Subscription, error)

ListByUser returns a user's subscription history from newest to oldest.

func (*Subscriptions) UpsertActive

func (r *Subscriptions) UpsertActive(
	ctx context.Context, s domain.Subscription,
) (int64, error)

UpsertActive creates or updates the active row for (tgID, platform). Existing periods keep their original started_at. Empty identity fields do not clear previous values; last_signal tracks the newest signal.

func (*Subscriptions) UpsertManual

func (r *Subscriptions) UpsertManual(
	ctx context.Context,
	tgID int64,
	expiresAt *time.Time,
	signal string,
) (int64, error)

UpsertManual creates or refreshes a manual active subscription.

type TelegramUpdate

type TelegramUpdate struct {
	UpdateID    int64
	UpdateType  string
	ChatID      *int64
	TGID        *int64
	PayloadJSON []byte
	Status      TelegramUpdateStatus
	Error       string
	ReceivedAt  time.Time
	ProcessedAt *time.Time
}

TelegramUpdate is one row from the durable Telegram inbox.

type TelegramUpdateStatus

type TelegramUpdateStatus string

TelegramUpdateStatus is the durable inbox state machine.

const (
	TelegramUpdatePending   TelegramUpdateStatus = "pending"
	TelegramUpdateProcessed TelegramUpdateStatus = "processed"
	TelegramUpdateIgnored   TelegramUpdateStatus = "ignored"
	TelegramUpdateFailed    TelegramUpdateStatus = "failed"
)

type TelegramUpdates

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

TelegramUpdates is the repository for the telegram_updates inbox.

func NewTelegramUpdates

func NewTelegramUpdates(db DBTX) *TelegramUpdates

NewTelegramUpdates returns a repository backed by db or tx.

func (*TelegramUpdates) InsertBatch

func (r *TelegramUpdates) InsertBatch(
	ctx context.Context, updates []TelegramUpdate, nextOffset int64,
) error

InsertBatch stores new updates as pending and advances the polling offset in the same transaction. Duplicate update_id rows are ignored.

func (*TelegramUpdates) ListPending

func (r *TelegramUpdates) ListPending(
	ctx context.Context, limit int,
) ([]TelegramUpdate, error)

ListPending returns pending updates ordered by update_id.

func (*TelegramUpdates) MarkTerminal

func (r *TelegramUpdates) MarkTerminal(
	ctx context.Context, updateID int64, status TelegramUpdateStatus, errorText string,
) error

MarkTerminal moves a pending update to a terminal state.

func (*TelegramUpdates) MaxUpdateID

func (r *TelegramUpdates) MaxUpdateID(ctx context.Context) (int64, bool, error)

MaxUpdateID returns the largest update_id recorded in the inbox.

func (*TelegramUpdates) ResolveOffset

func (r *TelegramUpdates) ResolveOffset(ctx context.Context, meta *Meta) (int64, error)

ResolveOffset returns max(meta.update_offset, max(update_id)+1).

type TributeEvent

type TributeEvent struct {
	ID             int64
	DedupKey       string
	EventName      string
	TGID           *int64
	SubscriptionID string
	SignatureValid bool
	PayloadJSON    []byte
	Status         TributeEventStatus
	Error          string
	ReceivedAt     time.Time
	ProcessedAt    *time.Time
}

TributeEvent is one row from the Tribute webhook inbox.

type TributeEventInput

type TributeEventInput struct {
	DedupKey       string
	EventName      string
	TGID           *int64
	SubscriptionID string
	SignatureValid bool
	PayloadJSON    []byte
	ReceivedAt     time.Time
}

TributeEventInput describes a received Tribute webhook.

type TributeEventStatus

type TributeEventStatus string

TributeEventStatus is the durable Tribute webhook state machine.

const (
	TributeEventReceived  TributeEventStatus = "received"
	TributeEventProcessed TributeEventStatus = "processed"
	TributeEventIgnored   TributeEventStatus = "ignored"
	TributeEventFailed    TributeEventStatus = "failed"
)

type TributeEvents

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

TributeEvents is the repository for the tribute_events inbox.

func NewTributeEvents

func NewTributeEvents(db DBTX) *TributeEvents

NewTributeEvents returns a repository backed by db or tx.

func (*TributeEvents) GetByDedupKey

func (r *TributeEvents) GetByDedupKey(
	ctx context.Context,
	dedupKey string,
) (TributeEvent, error)

GetByDedupKey returns one event by dedup key.

func (*TributeEvents) InsertReceived

func (r *TributeEvents) InsertReceived(
	ctx context.Context,
	input TributeEventInput,
) (TributeEvent, bool, error)

InsertReceived inserts a received event. If the dedup key already exists, the existing row is returned with inserted=false.

func (*TributeEvents) MarkTerminal

func (r *TributeEvents) MarkTerminal(
	ctx context.Context,
	id int64,
	status TributeEventStatus,
	errorText string,
) error

MarkTerminal moves an event to a terminal status.

type Users

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

Users is the repository for the users table.

func NewUsers

func NewUsers(db DBTX) *Users

NewUsers returns a Users repository backed by db or tx.

func (*Users) EnsureStub

func (r *Users) EnsureStub(ctx context.Context, tgID int64) error

EnsureStub creates a minimal local user row when only tg_id is known.

func (*Users) FindByUsername

func (r *Users) FindByUsername(
	ctx context.Context, username string,
) (domain.User, bool, error)

FindByUsername returns a locally known user by Telegram username.

func (*Users) Get

func (r *Users) Get(ctx context.Context, tgID int64) (domain.User, error)

Get returns the user with the given Telegram ID, or ErrNotFound.

func (*Users) SetBanned

func (r *Users) SetBanned(
	ctx context.Context,
	tgID int64,
	banned bool,
	reason string,
) error

SetBanned narrowly updates the owner-controlled hard-ban fields.

func (*Users) SetDMState

func (r *Users) SetDMState(
	ctx context.Context, tgID int64, state domain.DMState,
) error

SetDMState narrowly updates the direct-message state without touching profile cache fields. Opening a DM also advances last_seen_at.

func (*Users) Upsert

func (r *Users) Upsert(ctx context.Context, u domain.User) error

Upsert inserts a user or refreshes Telegram-owned profile fields. Admin-owned fields such as bans and notes are preserved on update. created_at is preserved; updated_at and last_seen_at are set to now.

type Whitelist

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

Whitelist is the repository for the whitelist table: users with permanent free access (owner, moderators, etc.).

func NewWhitelist

func NewWhitelist(db DBTX) *Whitelist

NewWhitelist returns a Whitelist repository backed by db or tx.

func (*Whitelist) Add

func (r *Whitelist) Add(ctx context.Context, tgID, addedBy int64, reason string) error

Add whitelists a user, recording who added them and why. Adding an already-whitelisted user updates the reason and the admin.

func (*Whitelist) Has

func (r *Whitelist) Has(ctx context.Context, tgID int64) (bool, error)

Has reports whether the user is whitelisted.

func (*Whitelist) ListTGIDs

func (r *Whitelist) ListTGIDs(ctx context.Context, limit int) ([]int64, error)

ListTGIDs returns whitelisted users for reconciliation candidates.

func (*Whitelist) Remove

func (r *Whitelist) Remove(ctx context.Context, tgID int64) error

Remove drops a user from the whitelist. Removing a missing row is a no-op.

Jump to

Keyboard shortcuts

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