- Go 80.1%
- HTML 9.8%
- CSS 9.5%
- JavaScript 0.6%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
sniffarr's WAL reached 53 GB: its reads of minutes overlap, so the read marks are never all free and TRUNCATE ends busy however long it waits (busy=1 at 200 ms and at 3 s with 600 ms reads). Holding new reads back until the running ones end lets it through in the time of one read. Assisted-by: Claude Code (claude-opus-5-5) |
||
| .beads | ||
| .forgejo/workflows | ||
| cli | ||
| database | ||
| names | ||
| static | ||
| telemetry | ||
| tmdb | ||
| torznab | ||
| typesafe | ||
| ui | ||
| version | ||
| .gitignore | ||
| AGENTS.md | ||
| CHANGELOG.md | ||
| go.mod | ||
| go.sum | ||
| LICENSE | ||
| README.md | ||
libarr
Code that sniffarr and spidarr share.
ui
sarak.sh/mikluko/libarr/ui is the design system of both web interfaces,
embedded for a service to serve:
static/system.css: the tokens and the elements, light and dark byprefers-color-schemestatic/fonts/: JetBrains Mono 400 and 600, under the SIL Open Font License 1.1 inOFL.txtstatic/vendor/: htmx 2.0.11 and the idiomorph 0.8.0 extension,idiomorph-ext.min.jsfrom its npmdist/static/app.js: writes the browser's time zone to thetzcookie, firing atzevent ondocumentonce it is set, and copiesdata-copybuttons inside a.tticons/: Lucide icons, under the ISC License inicons/LICENSE
These are the copies both services serve: a service links them from the ui handler and ships none of its own.
design/system.html and design/system.png show every token and element in both themes.
assets, err := ui.New("/ui/")
mux.Handle("/ui/", assets.Handler())
tmpl := template.New("page").Funcs(assets.FuncMap())
In a template, {{static "system.css"}} is the stylesheet's URL with a version of its content,
which the handler serves as immutable for a year, and {{icon "copy"}} is an icon's inline SVG.
Templates that already have a static or icon function take the two under other names with assets.FuncMapNamed("shared", "icon").
The handler is a static.Files, and ui.New takes its options.
A page model embeds ui.Locale, whose methods its templates call to translate and format in Russian or English:
T and Fmt for messages, Count with <key>.one/.few/.many plurals, Num, Size, Pct, and Clock, Time, TimeFull and Date in the page's zone.
ui.LoadMessages reads <lang>.json and <lang>/*.json, and ui.Zone the time zone from the tz cookie.
ui.ParseLanguages reads the languages a deployment offers from the service's variable, such as SPIDARR_UI_LANGUAGES=ru,en, in the switch's order;
unset, the service's defaults; empty, or naming a language without messages, an error naming the variable.
ui.Lang picks a page's language among them from ?lang=, the lang cookie, the signed-in user's locale, Accept-Language, or the first;
with one language there is no switch, and ?lang= and the cookie are ignored. C and POSIX are en throughout.
v, set := os.LookupEnv("SPIDARR_UI_LANGUAGES")
langs, err := ui.ParseLanguages("SPIDARR_UI_LANGUAGES", v, set, []string{"ru", "en"}, []string{"ru", "en"})
msgs, err := ui.LoadMessages(i18n, langs)
lang := ui.Lang(w, r, langs, userLocale)
page := Page{Locale: ui.Locale{Lang: lang, Path: r.RequestURI, Loc: ui.Zone(r, time.Local), Messages: msgs[lang]}}
static
sarak.sh/mikluko/libarr/static serves the files of an fs.FS under a URL prefix:
files, err := static.New(sub, "/static/", static.WithNotFound(notFoundPage))
mux.Handle("GET /static/", files)
tmpl := template.New("page").Funcs(template.FuncMap{"asset": files.URL})
files.URL("app.css") is the file's URL with a version of its content; there it is immutable for a year,
and at any other URL the browser revalidates it by ETag.
Text files are compressed once, in New, with brotli and gzip, and served in the encoding the request accepts best.
Without WithNotFound, a missing file or a directory is a bare 404.
cli
sarak.sh/mikluko/libarr/cli runs a service's main: cli.Main(load, run) loads the configuration,
logs as JSON to stderr at the configuration's LogLevel with the trace and span IDs of the context,
and runs until SIGINT or SIGTERM. It exits 0 after -h, 2 when the configuration does not load and 1 when run fails.
telemetry
sarak.sh/mikluko/libarr/telemetry sets up OpenTelemetry traces and metrics exported over OTLP from the standard OTEL_* variables:
telemetry.Setup(ctx, "spidarr", log) installs the global providers, honouring OTEL_SDK_DISABLED, and telemetry.Flush stops them.
telemetry.Handler adds trace_id and span_id to slog records, and telemetry.HTTPClient traces outgoing requests.
In tests, telemetrytest.RequireClientChild requires a call to record a client span under its parent.
version
sarak.sh/mikluko/libarr/version is the release a binary was built from. A build links it in with
-ldflags "-X sarak.sh/mikluko/libarr/version.version=0.2.0 -X sarak.sh/mikluko/libarr/version.commit=<sha> -X sarak.sh/mikluko/libarr/version.built=<RFC 3339>"
and otherwise version.Get takes the commit and time from the build's VCS stamp, with version dev.
version.Middleware("spidarr", h) sets every response's Server header to spidarr/<version>.
database
sarak.sh/mikluko/libarr/database opens a SQLite database in WAL mode with one writing connection and a pool for reads,
traced and measured through OpenTelemetry, and applies each component's migrations:
db, err := database.Open(ctx, path, database.Options{Service: "spidarr", Log: log})
err = db.Migrate(ctx, "store", migrations)
The WAL's size is the gauge <Service>.db.wal.size.
A read that runs long goes through Read, so a truncating checkpoint can hold new reads back
until the running ones end instead of waiting for a moment without readers:
err = db.Read(ctx, func(conn *sql.Conn) error { ... })
c, err := db.Checkpoint(ctx, database.Truncate)
torznab
sarak.sh/mikluko/libarr/torznab holds the Torznab responses a server writes and a client reads:
RSS, Item, Caps and the Newznab Error, each marshalling and unmarshalling to the same value.
req, err := torznab.ParseRequest(r.URL.Query(), torznab.Limits{Default: 100, Max: 500})
var te *torznab.Error
if errors.As(err, &te) {
torznab.WriteError(w, te)
return
}
torznab.WriteFeed(w, &torznab.RSS{Channel: torznab.Channel{Title: "spidarr", Items: items}})
ParseRequest keeps season, ep and the ids as sent and cuts limit so that offset+limit stays within the maximum.
A service's own elements go into Item.Extra: torznab.NewElement(v) builds one from a type whose XMLName names the service's namespace,
and Element.Decode reads it back.
names
sarak.sh/mikluko/libarr/names reads what a torrent is from its name alone: names.Parse tells a series, a movie or neither,
the title key releases of one title share, and the year, season, episode and quality; names.Source the video source.
names.Titles splits a name such as Фоллаут / Fallout / Сезон: 1 [2024, WEB-DL 1080p] into its titles.
tmdb
sarak.sh/mikluko/libarr/tmdb is a TMDB API v3 client, Search, Details and FindTVDB, paced by a rate limiter and retrying 429 and 5xx answers,
and the matching of a release to a TMDB work.
c := tmdb.NewClient(token, tmdb.DefaultRate)
c.Service = "spidarr" // metrics are spidarr.tmdb.requests
m := &tmdb.Matcher{Client: c}
p := names.Parse(name)
w := tmdb.Work{Name: name, Series: p.Kind == names.Series, Year: p.Year, Titles: names.Titles(name)}
if w.Series {
w.Year = 0 // a series name's year is mostly its season's, not the first air
}
match, err := m.Find(ctx, w)
Find searches each title in English, and in Russian too when it is Cyrillic, and takes a candidate whose title is the work's and whose year is the work's or one off:
the only one, or one far more popular than the rest. Among several, a Matcher.Chooser picks, or the work stays unmatched (nil).
A Chooser's error comes back from Find as it is.
typesafe
sarak.sh/mikluko/libarr/typesafe asks Jev, through TypeSafe's System One API, typed questions about a state:
Choice picks one of named options, Noul is a probability of yes, Score a place on ordered levels.
Each Response carries the tokens it took, input and output apart; TypeSafe bills the input.
c := typesafe.NewClient(key, typesafe.DefaultRate)
c.Service = "spidarr" // metrics are spidarr.typesafe.requests
res, err := c.Ask(ctx, map[string]any{"name": name}, map[string]typesafe.Question{
"dub": typesafe.Noul("Does the torrent `name` carry a Russian dub?"),
})
m := &tmdb.Matcher{Client: tc, Chooser: &typesafe.Chooser{Client: c, OnUsage: spend}}
names/jev
sarak.sh/mikluko/libarr/names/jev reads a torrent name with Jev in two requests.
The first asks which beginning of the name, if any, is a prefix to drop, such as www.UIndex.org -, [Обновлено] or (Trance) [WEB];
a prefix under Reader.MinPrefix confidence stays.
The second asks for the title, year and kind, each chosen among parts of the rest that the reader cuts, so each is a verbatim part of the name, with its byte span.
Reading.Rest is the name for names.Parse: without the prefix, or whole when the prefix is bracketed tags only, which names drops itself.
r := &jev.Reader{Client: c}
reading, err := r.Read(ctx, name, jev.Extra{
State: map[string]any{"files": files},
Questions: map[string]typesafe.Question{"dub": typesafe.Noul("Does the torrent `name` or its `files` carry a Russian dub?")},
})
p := names.Parse(reading.Rest) // season and episode
A name reads at about 1200 input tokens over both requests, 700 when it has no beginning that could be a prefix.
License
MIT; see LICENSE.