Architecture
Fret is one Go program that holds everything: the download engine, the REST API, the event stream,
the collection service, the command line and the interface, compiled to static files and embedded with
embed. Its state is one SQLite database.
┌──────────────────────────────── fret ─────────────────────────────────┐ Browser ──────▶│ HTTP :8080 REST API /api/v1 · SSE /api/v1/events · interface │ fret add ─────▶│ │ │ Click'n'Load ─▶│ HTTP :9666 (collection) │ │ ▼ │ │ queue.Manager: shipments, parcels, settings ──▶ events.Bus ──▶ SSE │ │ │ │ │ ▼ │ │ scheduler ──▶ dock doors (workers) │ │ │ │ │ ├─▶ carriers.Resolver ─▶ plugins (carriers, │ │ │ forwarders), accounts │ │ └─▶ transfer.Client: segments, resume, gauge │ │ after delivery: inspection ─▶ unpacking ─▶ warehouse register │ │ │ │ SQLite (data folder) Warehouse (download folder) │ └───────────────────────────────────────────────────────────────────────┘Technical choices
Section titled “Technical choices”| Topic | Choice | Why |
|---|---|---|
| Language | Go 1.27 | A single static binary, native concurrency, a small image |
| HTTP | net/http with its pattern routing |
No framework needed for a JSON API |
| Live updates | Server-Sent Events | One-way stream, native in browsers, automatic reconnection |
| Database | SQLite through modernc.org/sqlite |
One file, easy backups, pure Go: no CGO, easy cross-compilation |
| SQL | Hand-written queries, typed code generated by sqlc, embedded migrations |
No ORM, readable SQL |
| Interface | SvelteKit 3, Svelte 5, TypeScript, adapter-static |
Compiled once, embedded in the binary |
| Logs | log/slog, text or JSON |
Standard library |
| Archives | archive/zip, nwaples/rardecode, bodgit/sevenzip |
Pure Go, no external tool |
Packages
Section titled “Packages”cmd/fret/ entry point: serve, add, status, healthcheck, versioninternal/ app/ wiring of the components, startup and shutdown config/ startup options (flags and FRET_* variables) store/ SQLite: connection, migrations, sqlc queries (store/db) core/ domain types: statuses and their state machine, priorities, parcel numbers queue/ the dock: scheduler, workers, priorities, gauge, dock hours, consignments, duplicates, unpacking, warehouse transfer/ HTTP downloader: probe, segments, resume, speed limit plugin/ plugin interfaces, registry, HTTP and HTML helpers alldebrid/ realdebrid/ forwarders onefichier/ rapidgator/ mega/ googledrive/ carriers dropbox/ mediafire/ pixeldrain/ wetransfer/ plugintest/ fake service for plugin tests carriers/ resolution chain: forwarder, premium, free, direct accounts/ encrypted accounts, periodic checks, forwarder host lists clicknload/ collection server (Click'n'Load) unpack/ archive detection and safe extraction disk/ free and total space of the warehouse disk auth/ password, sessions, API tokens secret/ data/secret.key and AES-256-GCM encryption events/ in-process publish/subscribe bus api/ REST handlers, SSE, middlewares, serving the interfaceweb/ SvelteKit interfaceData model
Section titled “Data model”packages (shipment) 1 ── n files (parcel) 1 ── n segments name, dest_dir, priority, url, name, subdir, size, idx, start, end, password, position, held, received, hoster, debrid, received source, created_at, status, error, attempts, stored_at wait_until, unpacked, unpack_error, checksum │ │ 1 ── n unpacked_items 1 ── n file_events (tracking history) path status, code, args, message, created_at
accounts kind, plugin, label, encrypted credentials, status, premium, expirysettings JSON values by key: queue.settings, unpack.settings, collect.settings, auth…sessions token hash, expiryapi_tokens name, token hash, prefix, last use- The parcel number
FR-0042is the integerid, formatted; the API accepts both. - The tracking history is stored, not rebuilt. Each step has a stable
codeandargs; the interface translates them, andmessagekeeps an English fallback text. stored_atis0while a shipment is on the dock, and the storing time once it is in the warehouse.unpacked_itemsrecords the top-level paths placed by each unpacking, for Delete the files.
The life of a parcel
Section titled “The life of a parcel”queued ─▶ resolving ─▶ downloading ─▶ verifying ─▶ finished ─▶ extracting ─▶ finished ├─▶ waiting (customs, back to queued when due) ├─▶ offline (return to sender) └─▶ paused (held)retrying (missed delivery) ─▶ queued when due corrupted · duplicatecore holds the state machine: queue asks it for every transition and refuses any that is not
planned. The labels are in Statuses.
The dock
Section titled “The dock”queue.Manager owns the dock. A single loop:
- every second, releases the parcels whose retry delay or customs wait is over, applies the dock hours, and fills the free doors;
- every minute, stores the delivered shipments whose delay has passed.
Choosing departures: NextQueuedFiles orders the waiting parcels by shipment priority (Express,
Standard, Overnight), then shipment position, then position within the shipment. Overnight parcels are
skipped outside a night slot when one exists. Carriers with a free-mode limit (FreeSlots) that no
account or forwarder covers only get that many doors; their other parcels are skipped, not blocking.
A worker (one per door): resolve the link through the resolution chain, probe the file, reserve its
final path (duplicate detection), plan or resume the segments, download into name.fret, check the
size, rename, then signal the unpacker. Failures are classified (see below).
Failures: network errors, 5xx, 408 and 429 are retried after 10 s, doubled at each attempt up
to 10 minutes; after 5 attempts the parcel is held. 404, 410 and other 4xx are returns to sender.
Plugin errors carry their kind (plugin.ErrorKind), which maps to customs, held, return to sender or
retry.
Restart: at startup, parcels left in resolving, waiting or downloading go back to queued
and resume from their saved segments. A parcel interrupted during inspection or unpacking is marked
delivered if its file is in place (its archive is then examined again), otherwise sent back to the
dock.
Events: every change is published on the bus (package.updated, file.updated, queue.state…);
progress is grouped and published 4 times per second. The SSE handler forwards them as they come.
The downloader
Section titled “The downloader”- A first request with
Range: bytes=0-0gives the size, the suggested name and range support. - With ranges, the file is cut into up to segments per parcel parts of at least 8 MiB; without, a single stream.
- The
.fretfile is created at its final size; each segment writes at its own offset. Progress is saved every 3 seconds, so a crash loses at most a few seconds. - A segment silent for 60 seconds is cut and restarted. A server that ignores the range on resume makes the parcel start over rather than corrupt the file.
- The gauge is a token bucket (
golang.org/x/time/rate) shared by every transfer and changed live. - A carrier can provide request headers (cookies, referer) and a decryption stream (MEGA), applied while writing, at any offset.
The resolution chain
Section titled “The resolution chain”carriers.Resolver decides, for each departure, who carries the parcel:
- a folder link is listed by its carrier and replaced by one parcel per file (a consignment);
- approved forwarders that support the domain, in order. A refused key marks the account
invalid, a spent quota sets it aside for an hour, and the next one is tried; a dead link or a password error stops the chain; - the carrier’s premium account; refused or out of quota, it falls back to free mode;
- the carrier’s free mode;
- the direct link, when no carrier knows the domain. A direct link that answers
text/htmlis held instead of being saved.
Accounts (internal/accounts) are encrypted with AES-256-GCM, checked when added and every 12 hours.
Forwarder host lists are cached for 6 hours.
Collection
Section titled “Collection”internal/clicknload serves /jdcheck.js, /crossdomain.xml, /flash/add and /flash/addcrypted2.
For addcrypted2, the AES-128 key is read from the jk JavaScript function with a regular expression
(no JavaScript engine), with the key as initialisation vector, as the protocol requires. Collected
shipments are created held until confirmation, unless the setting says otherwise. If the port is taken,
Fret runs without collection.
Unpacking
Section titled “Unpacking”A single unpacker examines a shipment when one of its parcels is delivered, and every shipment at startup and when automatic unpacking is turned on. Archives are detected by name, folder by folder; an archive is unpacked when all its volumes are delivered, into a temporary folder, then moved into place without overwriting. Paths that escape the folder make the archive refused; symbolic links are skipped.
The warehouse
Section titled “The warehouse”A shipment is storable when every parcel is finished or duplicate. The dock queries only see
shipments with stored_at = 0; the register pages through the others, searched with instr on
lower-cased names and links, or by parcel number. Delete the files removes the delivered parcels
and the recorded unpacked items (never a duplicate, whose file belongs to another shipment), then
prunes the folders left empty up to the warehouse root. Disk space comes from internal/disk
(statfs on Linux and macOS, GetDiskFreeSpaceExW on Windows).
The API
Section titled “The API”- JSON under
/api/v1; errors as{"error": {"code", "message"}}with stable codes. - Every URL is in English, for the API and the interface; the Fret lexicon lives in displayed text only.
docs/api/openapi.yamlis written by hand and is the reference; the TypeScript types ofweb/src/lib/api.tsmirror it.- Middlewares, from the outside in: panic recovery, request logging, security headers, cross-origin
protection (
http.CrossOriginProtection), then authentication on private routes.
Authentication
Section titled “Authentication”A single user. The password is hashed with argon2id; sessions and API tokens are random tokens stored
as SHA-256 hashes. FRET_AUTH=none removes authentication for setups behind an authenticating proxy.
See Security.
Interface
Section titled “Interface”- One SPA: SvelteKit pages for the dock, new shipment, parcel, warehouse, carriers and settings, plus the sign-in and first-run pages.
- A single store (
queue.svelte.ts) loads/queue, then applies the SSE events; on every reconnection it reloads the whole state. - i18n: eight dictionaries (
en,fr,de,es,it,pl,ptfor Portugal,ru).en.tsis the reference and the fallback; the others have exactly the same keys (checked by TypeScript withsatisfies). The first browser language Fret speaks decides, otherwise English, unless chosen in Settings. Agreement with a number is written in the text:{n|parcel|parcels}, or three forms for Polish and Russian ({n|paczka|paczki|paczek}), picked byIntl.PluralRules.
Build and release
Section titled “Build and release”make buildbuilds the interface, then the binary with-trimpathand the version inmain.version.- The Dockerfile builds the interface and the binary on the build platform, cross-compiles for the
target, and copies the result into
distroless/static(non-root, with a health check). - Releases are described in Releasing.