Documentation
¶
Overview ¶
Package admin owns the diagnostic registry and the soft-delete shim (cleanup_history) used by the Settings → System → Diagnostics tab.
Each diagnostic surfaces "this looks abnormal" rows in a stable shape and offers a cleanup action. By default cleanup is soft — the deleted rows are first captured into cleanup_history as JSONB, then removed from their source table. A daily sweep purges rows older than the configured retention.
See plans/db-inspector.md for the full design.
Index ¶
- Variables
- func InsertCleanupHistory(ctx context.Context, tx *sql.Tx, capture CaptureContext, sourcePKs []string, ...) ([]int64, error)
- type CaptureContext
- type CleanupMode
- type CleanupRequest
- type CleanupResult
- type Diagnostic
- type HistoryEntry
- type HistoryListFilter
- type OrphanTorrents
- type Registry
- func (r *Registry) DB() *sql.DB
- func (r *Registry) DeleteHistoryEntry(ctx context.Context, id int64) error
- func (r *Registry) Get(name string) Diagnostic
- func (r *Registry) GetHistoryEntry(ctx context.Context, id int64) (*HistoryEntry, error)
- func (r *Registry) List() []Diagnostic
- func (r *Registry) ListHistory(ctx context.Context, filter HistoryListFilter) ([]HistoryEntry, error)
- func (r *Registry) Logger() *slog.Logger
- func (r *Registry) PurgeOlderThan(ctx context.Context, retention time.Duration) (int64, error)
- func (r *Registry) Register(d Diagnostic)
- type Row
- type SessionRemover
Constants ¶
This section is empty.
Variables ¶
var ErrNoMatch = errors.New("no matching rows for cleanup")
ErrNoMatch is returned by cleanup when the requested IDs don't match any rows in the diagnostic's current detection set.
Functions ¶
func InsertCleanupHistory ¶
func InsertCleanupHistory(ctx context.Context, tx *sql.Tx, capture CaptureContext, sourcePKs []string, rowsJSON [][]byte) ([]int64, error)
InsertCleanupHistory writes one cleanup_history row per (sourcePK, rowJSON) pair within an existing transaction. Use this when soft-deleting; skip it when hard-deleting. Returns the inserted IDs in the same order as the input pairs (caller may want to log them).
rowJSON should be the JSON-encoded full row at deletion time; the caller is responsible for encoding (see captureTorrentsToHistory).
Types ¶
type CaptureContext ¶
type CaptureContext struct {
Diagnostic string
SourceTable string
RequestID string
ActorKeyPrefix string
}
CaptureContext is the metadata passed to InsertCleanupHistory so the audit row identifies the actor that triggered the cleanup. Filled by the HTTP handler from the request.
type CleanupMode ¶
type CleanupMode string
CleanupMode selects whether a cleanup writes a cleanup_history row (recoverable) before deleting, or hard-deletes immediately.
const ( // ModeSoft writes the row to cleanup_history before deletion. The // row can be restored within the retention window. Default. ModeSoft CleanupMode = "soft" // ModeHard deletes the row immediately without writing // cleanup_history. Not recoverable. ModeHard CleanupMode = "hard" )
func ParseMode ¶
func ParseMode(s string) (CleanupMode, error)
ParseMode validates a string mode and falls back to soft for empty.
type CleanupRequest ¶
type CleanupRequest struct {
IDs []string
All bool
Mode CleanupMode
}
CleanupRequest is what cleanup() receives — a list of IDs (or "all" to use whatever the diagnostic currently matches), plus the mode.
type CleanupResult ¶
type CleanupResult struct {
RowsDeleted int `json:"rows_deleted"`
HistoryEntryIDs []int64 `json:"history_entry_ids,omitempty"` // empty slice in hard mode
}
CleanupResult is what cleanup() returns to the handler. HistoryEntryIDs is populated only in soft mode; the frontend uses it to offer an Undo affordance on the success toast that calls restore for each id.
type Diagnostic ¶
type Diagnostic interface {
// Name is a stable identifier used in URLs and logs (e.g. "orphan_torrents").
Name() string
// Description is a short one-line description shown in the UI.
Description() string
// Detect runs the diagnostic and returns matching rows.
Detect(ctx context.Context) ([]Row, error)
// Cleanup deletes the matching rows. Captures JSONB to cleanup_history
// in soft mode; skips the capture in hard mode.
Cleanup(ctx context.Context, req CleanupRequest) (CleanupResult, error)
}
Diagnostic is the contract every named diagnostic implements.
Diagnostics MUST be deterministic given the current DB state — the frontend assumes Detect() called twice in a row returns the same rows (modulo intervening writes). They MUST be cheap enough to run on every diagnostics-tab open without rate-limiting.
type HistoryEntry ¶
type HistoryEntry struct {
ID int64 `json:"id"`
Diagnostic string `json:"diagnostic"`
SourceTable string `json:"source_table"`
SourcePK string `json:"source_pk"`
RowData json.RawMessage `json:"row_data"`
DeletedAt time.Time `json:"deleted_at"`
RequestID string `json:"request_id"`
ActorKeyPrefix string `json:"actor_key_prefix"`
}
HistoryEntry is one row of cleanup_history surfaced via the admin API. row_data is kept opaque (json.RawMessage) — the frontend can render it generically and only diagnostics that own a specific source_table know how to deserialize it for restore.
type HistoryListFilter ¶
HistoryListFilter narrows the cleanup_history query. All fields are optional; zero values disable the filter.
type OrphanTorrents ¶
type OrphanTorrents struct {
// contains filtered or unexported fields
}
OrphanTorrents detects torrent rows that exist in the DB but aren't tracked by the in-memory engine. These are the "ghost rows" that today's smoke-fixture cleanup surfaced - a delete via the API can silently leave the DB row behind in some edge cases, and on restart restoreFromDB happily re-loads them.
func NewOrphanTorrents ¶
func NewOrphanTorrents(db *sql.DB, session SessionRemover) *OrphanTorrents
NewOrphanTorrents constructs the diagnostic.
func (*OrphanTorrents) Cleanup ¶
func (o *OrphanTorrents) Cleanup(ctx context.Context, req CleanupRequest) (CleanupResult, error)
Cleanup deletes the listed (or all-matching) orphans. Soft mode captures the full torrents row as JSON into cleanup_history before removing.
func (*OrphanTorrents) Description ¶
func (o *OrphanTorrents) Description() string
func (*OrphanTorrents) Name ¶
func (o *OrphanTorrents) Name() string
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry owns the set of available diagnostics. Use Register at boot; Get by name; List for the diagnostics index.
func (*Registry) DeleteHistoryEntry ¶
DeleteHistoryEntry removes one cleanup_history row by id (used after a successful restore so the entry doesn't reappear in the trash list).
func (*Registry) Get ¶
func (r *Registry) Get(name string) Diagnostic
Get returns the diagnostic with the given name, or nil.
func (*Registry) GetHistoryEntry ¶
GetHistoryEntry fetches a single cleanup_history row by id.
func (*Registry) List ¶
func (r *Registry) List() []Diagnostic
List returns all registered diagnostics in insertion order — actually in iteration order (Go maps are randomized) but the frontend sorts by name anyway.
func (*Registry) ListHistory ¶
func (r *Registry) ListHistory(ctx context.Context, filter HistoryListFilter) ([]HistoryEntry, error)
ListHistory returns cleanup_history rows newest-first.
func (*Registry) Logger ¶
Logger returns the registry's logger for diagnostic implementations that want to emit structured logs.
func (*Registry) PurgeOlderThan ¶
PurgeOlderThan hard-deletes cleanup_history rows whose deleted_at is older than now - retention. Returns rows affected. Idempotent.
deleted_at is TEXT-encoded RFC3339; the cutoff is computed in Go and compared lexicographically (RFC3339 sorts the same as time).
func (*Registry) Register ¶
func (r *Registry) Register(d Diagnostic)
Register adds a diagnostic to the registry. Panics on duplicate name — diagnostic names must be unique and known at boot.
type Row ¶
type Row struct {
// ID identifies the row for cleanup. The diagnostic chooses the
// representation (info_hash for torrents, integer id for tags, etc).
ID string `json:"id"`
// Summary is a one-line human-readable description of the row.
Summary string `json:"summary"`
// WhyFlagged states the test that matched (e.g. "no in-memory torrent").
WhyFlagged string `json:"why_flagged"`
// SuggestedAction is what cleanup will do (free-text for the modal).
SuggestedAction string `json:"suggested_action"`
}
Row is one matching record returned from a diagnostic. The shape is deliberately stable across all diagnostics so the frontend renders every diagnostic with the same component.
type SessionRemover ¶
type SessionRemover interface {
// LiveHashes returns the info hashes currently tracked in memory.
LiveHashes() map[string]struct{}
}
SessionRemover is the narrow surface OrphanTorrents needs from the torrent Session - just enough to look up which hashes are currently in-memory. Defined here (instead of importing core/torrent) so the admin package doesn't depend on the torrent engine.
Note: we deliberately do NOT use Session.Remove for the cleanup - orphan rows are by definition NOT in the in-memory map, so Session.Remove returns "torrent not found". Direct DB delete is the correct path; the bolt-DB piece-completion entry (if any) becomes a harmless tiny stale entry until the same hash is re-added.