indexer

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 22 Imported by: 0 modules, 0 packages

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

Documentation

Index

Constants

View Source
const (
	HealthUnknown           = "unknown"
	HealthOK                = "ok"
	HealthDefinitionMissing = "definition_missing"
	HealthFailing           = "failing"
)

Indexer health states.

  • unknown/ok/definition_missing are maintained by AuditCatalog (definition-resolution dimension, boot + daily refresh).
  • failing is maintained by RecordSearchOutcome (live search dimension): N consecutive search failures flip an indexer to failing; one success flips it back to ok. Unlike definition_missing, failing indexers are still synced to services — they may recover on their own.

Variables

This section is empty.

Functions

func CapabilityForCategory added in v0.5.0

func CapabilityForCategory(category string) string

AutoAssigner handles automatic indexer-to-service assignment based on category↔capability matching. CapabilityForCategory is the service capability that wants indexers of a catalog category ("Movies" → "content:movies"), or "".

func CatalogLanguages

func CatalogLanguages() []string

CatalogLanguages returns the distinct languages present in the catalog.

func IsLikelyIPBan added in v0.4.0

func IsLikelyIPBan(lastError string) bool

IsLikelyIPBan reports whether a search error message looks like a Cloudflare IP ban (vs an ordinary failure). Used by the API to offer the "Rotate VPN IP" action in context.

func SetCatalogSource

func SetCatalogSource(fn func() []CatalogEntry)

SetCatalogSource replaces the catalog provider function. Call this once at startup after creating a ProwlarrCatalog.

func TopMedian added in v0.5.0

func TopMedian(seeders []int) int

TopMedian is the typical seed count of the best-seeded results: the median of the seederSample largest values.

func UniqueCounts added in v0.5.0

func UniqueCounts(bySource map[string][]ReleaseID) map[string]int

UniqueCounts returns, for each source, how many of its releases no other source returned. Needs at least two sources; otherwise it returns nil.

Types

type AssignmentInput

type AssignmentInput struct {
	IndexerID string `json:"indexer_id"`
	ServiceID string `json:"service_id"`
	Overrides string `json:"overrides"`
}

AssignmentInput specifies how to assign an indexer to a service.

type AutoAssigner

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

func NewAutoAssigner

func NewAutoAssigner(q db.Querier, pusher *Pusher, logger *slog.Logger) *AutoAssigner

NewAutoAssigner creates a new AutoAssigner.

func (*AutoAssigner) AssignExistingIndexersToService

func (a *AutoAssigner) AssignExistingIndexersToService(ctx context.Context, serviceID string)

AssignExistingIndexersToService finds all unassigned indexers whose categories match the service's content:* capabilities and creates assignments. Called when a new service registers.

func (*AutoAssigner) AssignIndexerToMatchingServices

func (a *AutoAssigner) AssignIndexerToMatchingServices(ctx context.Context, indexerID string, categories []string)

AssignIndexerToMatchingServices finds all services whose content:* capabilities match the indexer's categories and creates assignments. Called when an indexer is created.

type CatalogEntry

type CatalogEntry struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Language    string   `json:"language"`
	Protocol    string   `json:"protocol"`   // torrent, usenet
	Privacy     string   `json:"privacy"`    // public, semi-private, private
	Categories  []string `json:"categories"` // Movies, TV, Audio, Books, XXX, Other
	URLs        []string `json:"urls"`
	Settings    []Field  `json:"settings"` // config fields required to add this indexer
}

CatalogEntry describes an available indexer that users can browse and add. This is the "template" — not yet configured or saved.

func Catalog

func Catalog() []CatalogEntry

Catalog returns the current catalog entries (from Prowlarr or static fallback).

func FilterCatalog

func FilterCatalog(filter CatalogFilter) []CatalogEntry

FilterCatalog returns catalog entries matching the given filter.

type CatalogFilter

type CatalogFilter struct {
	Query    string `json:"query,omitempty"`
	Protocol string `json:"protocol,omitempty"`
	Privacy  string `json:"privacy,omitempty"`
	Category string `json:"category,omitempty"`
	Language string `json:"language,omitempty"`
}

CatalogFilter holds the query parameters for browsing the catalog.

type Field

type Field struct {
	Name        string        `json:"name"`
	Type        string        `json:"type"` // text, password, checkbox, select, info
	Label       string        `json:"label"`
	HelpText    string        `json:"help_text,omitempty"`
	Required    bool          `json:"required"`
	Default     string        `json:"default,omitempty"`
	Placeholder string        `json:"placeholder,omitempty"`
	Options     []FieldOption `json:"options,omitempty"` // for select type
}

Field describes a single user-configurable setting for an indexer.

type FieldOption

type FieldOption struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

FieldOption is a name/value pair for select fields.

type IndexerInfo

type IndexerInfo struct {
	db.Indexer
	AssignedServices []string `json:"assigned_services,omitempty"`
}

IndexerInfo is the enriched view with assignments.

type IndexerStats added in v0.5.0

type IndexerStats struct {
	IndexerID string `json:"indexer_id"`
	// Searches counts real scrapes (cache hits excluded).
	Searches int `json:"searches"`
	Failures int `json:"failures"`
	// SuccessRate is successful searches / searches (0–1).
	SuccessRate float64 `json:"success_rate"`
	// MedianMs and P90Ms are search durations, successful searches only.
	MedianMs int `json:"median_ms"`
	P90Ms    int `json:"p90_ms"`
	// AvgResults and AvgWithSeeders are per successful search.
	AvgResults     float64 `json:"avg_results"`
	AvgWithSeeders float64 `json:"avg_with_seeders"`
	// MedianSeeders is the typical seed count of the best-seeded results
	// (median over searches that returned something).
	MedianSeeders int `json:"median_seeders"`
	// BehindCloudflare is the share of searches that met Cloudflare (0–1);
	// SolveRate is how many of those were solved (0–1).
	BehindCloudflare float64 `json:"behind_cloudflare"`
	SolveRate        float64 `json:"solve_rate"`
	// ErrorKinds counts failures by kind.
	ErrorKinds map[string]int `json:"error_kinds,omitempty"`
	// Comparisons is how many times this indexer answered a query alongside
	// others; UniqueShare is the share of its results nobody else returned
	// (0–1) and AvgUnique the number per comparison. Zero when never
	// compared.
	Comparisons int     `json:"comparisons"`
	UniqueShare float64 `json:"unique_share"`
	AvgUnique   float64 `json:"avg_unique"`
	LastSearch  string  `json:"last_search,omitempty"`
}

IndexerStats summarizes one indexer's searches over the stats window.

type Input

type Input struct {
	Name     string `json:"name"`
	Kind     string `json:"kind"`
	Enabled  bool   `json:"enabled"`
	Priority int    `json:"priority"`
	URL      string `json:"url"`
	APIKey   string `json:"api_key"`
	Settings string `json:"settings"`
}

Input is the data required to create or update an indexer.

type Manager

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

Manager handles centralized indexer management.

func NewManager

func NewManager(q db.Querier, bus *events.Bus, logger *slog.Logger) *Manager

NewManager creates a new indexer manager.

func (*Manager) Assign

func (m *Manager) Assign(ctx context.Context, input AssignmentInput) (*db.IndexerAssignment, error)

Assign links an indexer to a service.

func (*Manager) AuditCatalog added in v0.4.0

func (m *Manager) AuditCatalog(ctx context.Context, resolve func(name, url string) string)

AuditCatalog cross-checks every configured indexer against the loaded Prowlarr definition catalog and records the result in the indexer's health columns. It runs after each definition load (boot and the daily refresh), using the same resolver the torznab proxy uses at search time so the audit can never disagree with what a search would hit.

Without this, an indexer whose upstream definition was removed (a site shuts down and Prowlarr deletes its definition) stays configured and assigned, and the first place it fails is every search.

A transition into or out of definition_missing changes what ListIndexersForService returns, so assigned services are push-notified to re-sync on those transitions only.

func (*Manager) AutoAssigner

func (m *Manager) AutoAssigner() *AutoAssigner

AutoAssigner returns the auto-assigner for use by other packages (e.g., service registry for retroactive assignment on registration).

func (*Manager) Create

func (m *Manager) Create(ctx context.Context, input Input) (*db.Indexer, error)

Create adds a new indexer.

func (*Manager) Delete

func (m *Manager) Delete(ctx context.Context, id string) error

Delete removes an indexer and its assignments, and notifies all affected services so they can remove the indexer locally.

func (*Manager) Get

func (m *Manager) Get(ctx context.Context, id string) (*db.Indexer, error)

Get returns a single indexer.

func (*Manager) List

func (m *Manager) List(ctx context.Context) ([]db.Indexer, error)

List returns all indexers.

func (*Manager) ListAssignments

func (m *Manager) ListAssignments(ctx context.Context, indexerID string) ([]db.IndexerAssignment, error)

ListAssignments returns all assignments for an indexer.

func (*Manager) ListForService

func (m *Manager) ListForService(ctx context.Context, serviceID string) ([]db.Indexer, error)

ListForService returns indexers assigned to a specific service.

func (*Manager) RecordSearchOutcome added in v0.4.0

func (m *Manager) RecordSearchOutcome(ctx context.Context, indexerID string, searchErr error)

RecordSearchOutcome updates an indexer's search-health counters after a proxied search. searchErr == nil records a success (resets the failure streak and, if the indexer was failing, restores it to ok).

func (*Manager) Stats added in v0.5.0

func (m *Manager) Stats() *Stats

Stats returns the per-indexer search stats recorder.

func (*Manager) Unassign

func (m *Manager) Unassign(ctx context.Context, indexerID, serviceID string) error

Unassign removes an indexer-service link.

func (*Manager) Update

func (m *Manager) Update(ctx context.Context, id string, input Input) (*db.Indexer, error)

Update modifies an existing indexer.

type ProwlarrCatalog

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

ProwlarrCatalog manages a catalog sourced from Prowlarr's GitHub repo.

func NewProwlarrCatalog

func NewProwlarrCatalog(logger *slog.Logger) *ProwlarrCatalog

NewProwlarrCatalog creates a catalog that pulls from Prowlarr's definitions. It initializes with the static fallback and fetches live data asynchronously.

func (*ProwlarrCatalog) AllRawYAML

func (pc *ProwlarrCatalog) AllRawYAML() map[string][]byte

AllRawYAML returns all raw YAML bytes, keyed by catalog ID.

func (*ProwlarrCatalog) Entries

func (pc *ProwlarrCatalog) Entries() []CatalogEntry

Entries returns the current catalog entries.

func (*ProwlarrCatalog) LastFetched

func (pc *ProwlarrCatalog) LastFetched() time.Time

LastFetched returns when the catalog was last refreshed from Prowlarr.

func (*ProwlarrCatalog) LoadLocal added in v0.4.0

func (pc *ProwlarrCatalog) LoadLocal() (string, error)

LoadLocal populates the catalog without touching the network, preferring the freshest source: the on-disk cache written after the last successful GitHub fetch, then the snapshot embedded at build time. It returns which source was used ("disk-cache" or "embedded").

func (*ProwlarrCatalog) Refresh

func (pc *ProwlarrCatalog) Refresh(ctx context.Context) error

Refresh fetches the latest definitions from Prowlarr's GitHub repo. On failure it keeps the existing catalog (previous fetch, local cache, or static fallback).

func (*ProwlarrCatalog) SetCachePath added in v0.4.0

func (pc *ProwlarrCatalog) SetCachePath(path string)

SetCachePath enables persisting each successfully fetched definitions zipball to path, and makes LoadLocal prefer that file over the embedded snapshot. Call before LoadLocal / StartRefreshLoop.

func (*ProwlarrCatalog) SetUpdateFunc added in v0.4.0

func (pc *ProwlarrCatalog) SetUpdateFunc(fn func(map[string][]byte))

SetUpdateFunc registers fn to be called with a copy of the raw YAML definition map whenever definitions are (re)loaded from any source — local load at startup and every successful GitHub refresh. Call before LoadLocal / StartRefreshLoop.

func (*ProwlarrCatalog) StartRefreshLoop

func (pc *ProwlarrCatalog) StartRefreshLoop(ctx context.Context, interval time.Duration)

StartRefreshLoop refreshes the catalog immediately, then periodically.

type Pusher

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

Pusher notifies services when their indexer assignments change. It POSTs to each affected service's sync webhook endpoint.

func NewPusher

func NewPusher(q db.Querier, logger *slog.Logger) *Pusher

NewPusher creates a new Pusher.

func (*Pusher) NotifyAllAssigned

func (p *Pusher) NotifyAllAssigned(ctx context.Context, indexerID string)

NotifyAllAssigned notifies all services that have the given indexer assigned.

func (*Pusher) NotifyService

func (p *Pusher) NotifyService(ctx context.Context, serviceID string)

NotifyService sends a sync trigger to a service's Pulse webhook. The endpoint is: POST {service.api_url}/api/v1/hooks/pulse/sync

func (*Pusher) NotifyServiceAsync

func (p *Pusher) NotifyServiceAsync(serviceID string)

NotifyServiceAsync is a fire-and-forget version of NotifyService.

type ReleaseID added in v0.5.0

type ReleaseID struct {
	Hash  string
	Title string
	Size  int64
}

ReleaseID identifies a release across indexers. Hash is the lower-case info hash when the indexer gives one (many HTML indexers don't: their magnet links live on detail pages); Title is the normalized title and Size is in bytes (0 when unknown).

type SearchEvent added in v0.5.0

type SearchEvent struct {
	IndexerID string
	At        time.Time
	Duration  time.Duration
	// ErrorKind is empty on success, else a short class such as
	// "timeout", "unreachable", "http_error", "cloudflare_no_solver",
	// "cloudflare_solve_failed", "ip_banned" or "other".
	ErrorKind string
	// Seeders has one entry per result (0 when unknown).
	Seeders    []int
	Challenged bool
	Solved     bool
	// Query is the composed search keywords; Mode is "movie", "tv" or
	// "search". Kept so the catalog tester can reuse recent real queries.
	Query string
	Mode  string
}

SearchEvent is one real scrape's outcome.

type Stats added in v0.5.0

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

Stats records and summarizes per-indexer search stats.

func NewStats added in v0.5.0

func NewStats(q db.Querier, logger *slog.Logger) *Stats

NewStats returns a recorder backed by q.

func (*Stats) FlushOverlap added in v0.5.0

func (s *Stats) FlushOverlap(ctx context.Context)

FlushOverlap finalizes query groups whose window has closed.

func (*Stats) NoteResults added in v0.5.0

func (s *Stats) NoteResults(indexerID, queryKey string, releases []ReleaseID)

NoteResults registers the results an indexer returned for a query, for the overlap comparison. Called for every answer served, including cache hits, so all indexers asked the same query are compared.

func (*Stats) Prune added in v0.5.0

func (s *Stats) Prune(ctx context.Context)

Prune deletes stats older than the retention window.

func (*Stats) RecordSearch added in v0.5.0

func (s *Stats) RecordSearch(ctx context.Context, ev SearchEvent)

RecordSearch stores one scrape's outcome.

func (*Stats) Run added in v0.5.0

func (s *Stats) Run(ctx context.Context)

Run finalizes overlap groups every minute and prunes old rows daily, until ctx ends.

func (*Stats) Summarize added in v0.5.0

func (s *Stats) Summarize(ctx context.Context) (map[string]*IndexerStats, error)

Summarize returns stats for every indexer with any recorded activity in the retention window, keyed by indexer ID.

type TestResult

type TestResult struct {
	Success  bool   `json:"success"`
	Message  string `json:"message"`
	Duration string `json:"duration"`
}

TestResult holds the outcome of probing an indexer.

func TestIndexer

func TestIndexer(ctx context.Context, kind, url, apiKey string) TestResult

TestIndexer probes an indexer URL to validate connectivity and credentials. For Torznab/Newznab it performs a caps query; for generic URLs it checks HTTP status.

Jump to

Keyboard shortcuts

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