Pairing and jobs
How the Bridge and the server find each other, how the server knows the Bridge is
there, and how work moves between them. Every route named here is in the
API reference; server code is
auth/bridge.go, internal/bridge and api/handlers_bridge.go, and the Bridge's
is internal/link (the client), internal/app (pairing and the heartbeat) and
internal/jobs (the runner).
Pairing
- An admin makes a code in Settings > Bridge (
POST /admin/bridge/pair, a session only: an API key is refused, since this mints a credential). The code is shown once, lasts 15 minutes, and is stored only as a hash in the singlebridge_statusrow. Making another replaces one still waiting; a Bridge that is already paired keeps working until a new Bridge exchanges the code. The answer'sserver_urlis the address to give the Bridge: the server's home address when it has one (plainhttpon the local network for a self-signed server, whose certificate the Bridge can't verify), else its public or request address. - The Bridge exchanges it at the public
POST /bridge/pair, which shares the per-address failure limit ofPOST /auth/redeem. In one transaction the server checks the code, its expiry and that the admin who made it is still an enabled admin, uses it up, revokes every earlier bridge token and clears the last Bridge's status, then mints a token of kindbridgefor that admin. So there is one Bridge per server, and a new one starts from nothing. - The Bridge keeps the token sealed in its secrets folder, never in its config file (see Configuration), and sends its first heartbeat at once.
The Bridge pairs from its own page, or on its first start from the two environment variables the console's dialog shows. It listens on its page's port before it uses an environment code, so a start that can't serve never spends the code. A Bridge that is already paired refuses to pair again until it is unpaired. Its page words a failed pairing:
| What happened | What the page says |
|---|---|
a wrong, used or expired code (401) | the code is wrong, used or expired: make a new one in the console |
404 or 405 | the server doesn't know about a Bridge: update it |
429 with a valid Retry-After | the server is limiting pairing requests and the page says when to try again, for example "Try again in 15 minutes." |
another refusal (a 4xx) | the server refused the pairing, with the server's message |
| the server's certificate can't be verified (a self-signed one) | pair with the server's http:// address on the local network (the server also answers plain HTTP on the same port there) |
an address that isn't an absolute http(s) URL | a 400 on the page's own API |
| no answer (the request itself failed, or the answer didn't finish in time) | Couldn't reach <address> with the reason in a few words, and the address to use instead (below the table). A 502 on the page's API |
a 5xx from the server | the server at that address answered with an error (its status and message): try again, then check the server's log. A 502 |
| an answer the Bridge can't use (not JSON, no token) | check the address is the AudioSilo server's and that it is up to date. A 502 |
the server accepted the code, but the Bridge couldn't keep its token or the pairing (pairNotSaved) | the pairing wasn't saved: fix the cause (the Bridge's log), make a new code and pair again, since the code is spent. A 500 that shows this sentence (api.ErrFailed); the token is forgotten again, so a restart never comes back half paired |
For no answer, the reason is one of: no such host, its name couldn't be looked
up, nothing answered on that port, no route to that address, or it didn't answer
in time. For those, the message also gives the address to use instead: the
server's as this computer reaches it, like http://192.168.1.10:8080. A compose
service name given to a Bridge outside that compose project is the usual cause.
Pairing waits out only a short 429 and answers a longer one at once (the page's
budget in When the server returns 429).
pairError (internal/app/backend.go) has worded pairing failures since v0.4.0. Once the
server has accepted the code, Conn.Pair saves without the caller's cancellation
(context.WithoutCancel), so a page closed mid-pairing doesn't lose a spent code.
Unpairing is either side's. The console's DELETE /admin/bridge revokes the
token and forgets the Bridge's status (its jobs stay). The Bridge's own Unpair only
forgets the token on its side, so the console still shows it paired until it is
unpaired there too.
A refused token. A 401 on any call means the server refuses the token. It
was unpaired in the console, another Bridge was paired, or the admin who paired it
is no longer an enabled admin. The Bridge keeps the token but stops calling in
(no heartbeat, no claims), says why on its page, and tries a heartbeat again every
5 minutes.
- If the server takes the token again (the admin was made an admin again), the Bridge carries on by itself, resuming the jobs the refusal stopped.
- An unpair or a new pairing revoked the token for good, so the Bridge has to be paired again.
- A
503(the server couldn't check the token) is not a refusal. The Bridge tries again.
The bridge token
A bridge token is a tokens row of kind bridge, hashed like every token. It is
the narrowest credential the server has:
- The Bridge's routes only. Routes opt in to the token kinds they accept, and
only
/api/v1/bridge/*listsbridge. Every other route refuses it with401, and the media routes'?token=never takes it. A route-table test sends a bridge token, in the header and as?token=, to every other authenticated route. - The header only:
Authorization: Bearer <token>. - Its admin's. It belongs to the admin who made the code, and works only while that account exists, is enabled and is still an admin. Demoting or disabling the admin stops the Bridge at its next call.
- Checked again inside the write. The heartbeat checks the token again in its
own transaction, and every claim checks it again on the reader and, if it goes on
to write, in its transaction too (see Claims and leases), so
a call authenticated just before a pairing or an unpair revoked its token (a claim
waiting out its long poll, say) saves nothing and claims nothing:
401. - Never a device, never touched. The device lists and sign-outs leave it out,
and its calls don't bump
last_seen: a heartbeat every 30 seconds is not its admin's activity.
The Bridge's routes refuse every other credential in turn: a session, an API key or
a cast token gets 401 there.
The heartbeat and the capability
The status body is limited to 2 MiB. The server keeps up to 4,096 library IDs and mappings and
filters them to libraries it owns. A size refusal (400 too_large or HTTP 413) makes the Bridge
retry within the older limits of 64 KiB and 512 entries, keeping mapped libraries first. It tries
the full list again after an hour.
The Bridge sends PUT /bridge/status every 30 seconds, and at once after
pairing and after a mapping check finishes:
| Field | What it carries |
|---|---|
version | the Bridge's version |
kinds | the job kinds it runs (bridge.verify, sidecars.generate, sidecars.describe, chapters.detect, sidecars.contribute, meta.correct, readalong.align, audible.poll, audible.import, audible.sync and librivox.fetch; an older Bridge lists fewer) |
libraries | its last mapping check of each library |
workers | its ASR workers that have connected at least once: name, version, platform (the GOOS/GOARCH and the speech recognition in one line, e.g. darwin/arm64, mlx-whisper (metal)) and last_seen |
ui_url | its own page as the local network reaches it (its public_url setting), which the console links to |
estimates | its figures for costing a job before it is queued, one block per family (sidecars: the Bridge's figures); absent until its engine has started |
setup | only once the server accepts it (below): the setup checklist (items), can_contribute and github_login |
The server checks the heartbeat's structure and refuses it when that is wrong:
- kinds of the form
family.name, listed once; - library ids above 0, listed once;
ui_urlan absolutehttp(s)URL, since the console renders it as a link.
Its free text (the version, the mappings' paths and errors, the workers) is cleaned rather than refused. Control characters become spaces, and each text is cut to its limit. Much of it comes from the outside world (a file name, an OS error), and a refused heartbeat would leave the Bridge offline.
The server keeps only the last one, in bridge_status. Its answer lists the
server's libraries (id, name, root), which is how the Bridge learns which
libraries to map, and accepts.
Optional blocks: accepts
The server decodes the heartbeat strictly (an unknown field is a 400), so a
newer Bridge can't simply add a field. The two sides negotiate instead. The reply
carries accepts, the optional protocol features this server reads
(bridge.HeartbeatAccepts, ["setup", "claim_min_priority", "internet_reachable"]
today). An older server sends none. setup names a heartbeat block and
internet_reachable a top-level boolean, while claim_min_priority permits a
claim query option, not a new heartbeat request field. The Bridge
(link.StatusReply.Accepting, internal/app):
- sends
setuporinternet_reachableonly after a reply listed it, per pairing and in memory, and kicks a second beat at once when one first appears, so neither the checklist nor the reachability waits 30 seconds; - on a
400to a beat that carried an optional field (the server was downgraded), sends the beat again without it (dropOptional, below); - forgets all of it on every pair and unpair, and when the server refuses its token or takes it again.
The 400 doesn't name the field. A server refuses an unknown one with a bare
invalid request, or invalid status before 2.7.0. With both fields sent, the
Bridge tries without setup, then without internet_reachable, then with
neither, so a refused setup block never stops the reachability report. A retry that goes through holds off each field it left
out for an hour, on that field's own timer, and ignores accepts for it until
then. The other field keeps going. A failure other than a 400 before the last
try holds nothing off, and the next beat sends the fields again. When the beat
with neither field is refused too (a 400 about a core field, or a fault),
nothing is held off, and the beats go without the fields until a reply's
accepts lists them again. The Bridge logs the server's 400 with the field it
dropped.
So a Bridge that sends setup works with an older server (no checklist in the
console), and an older Bridge works with a server that accepts it (no setup
sent, none shown).
The link separately remembers claim_min_priority for that pairing. Without
it, the runner makes ordinary claims and uses two ordinary download slots.
Internet reachability
internet_reachable is the Bridge's own outbound connectivity. The server uses
it to tell a dead feed from a dead connection
(When the Bridge's internet is down).
The Bridge (internal/app/connectivity.go) leaves the field out until it has
evidence:
- Every dial of the podcast and LibriVox clients (
netguard.Options.OnInternetDial) is evidence. A connection to a public address sets ittrue. A DNS failure, or a failed dial whose addresses were all public, asks for a check and kicks a beat (at most one per interval), so the check reaches the server within seconds. A LAN address allowed bypodcasts.allow_networks, a refused address and a dial cut short by the Bridge stopping leave the field as it is. - The check (
netguard.CheckInternet) runs on the next beat, at most once per heartbeat interval (30 s). It opens a bare TCP connection, with no request sent, to the host ofmetadata.base_urland toarchive.org:443, side by side, public addresses only, within 2 seconds. A metadata host on the LAN fails that rule, so only archive.org counts. - The field is
falseonly when both connections fail. While it isfalse, the Bridge checks again on every beat, even when the server queues no feed polls. Any public connection sets ittrueat once, and kicks a beat when it wasfalseor unknown.
A beat without the field (an older Bridge, or an older server that never listed it) leaves the server's per-feed rules in charge.
The setup checklist
The Audible status checks both the scheduled sync job and the push to Audible. A successful push can clear its own failure while a job failure still needs attention.
setup is the Bridge's onboarding checklist (FIRST-RUN-PLAN F2), built by the
Bridge's pure setup.Checklist from what the app already knows, in a fixed order:
id | required | done when | detail |
|---|---|---|---|
paired | yes | the Bridge is paired | |
libraries | yes | the Bridge has checked libraries and every one is mapped and writable (a library counts once it has been checked) | "checking the libraries..." (setup.DetailLibrariesChecking, from v0.5.0) from pairing until a heartbeat has listed the server's libraries and each has been checked (Input.LibrariesPending: no lastBeat yet, or libs.Unchecked()), never done and no library_ids meanwhile; then "1 of 2 libraries writable" (or "the server has no libraries yet"); library_ids lists the ones still to fix |
asr | yes | the engine has started and something can transcribe now, not waiting for a worker | local, worker, "waiting for an ASR worker" (with needs_worker: true), "the engine is starting", or why it isn't available |
agent | no | the agent container is available (with its own or a handed-over credential); only characters, recaps and descriptions need it | the backend, or why it isn't ready in plain words (below). A ready agent whose handed credential goes to every uid because another uid spoiled the group probe adds ", but its credential is shared with every user on the agent's volume, because something else there interfered with the Bridge's check: the Accounts tab says more" (setup.DetailAgentShared) |
budget | yes | the monthly budget was saved on the page or is set by the environment (Config.BudgetReviewed) | "$100 a month" or "no monthly cap" |
github | no | a GitHub token resolves and isn't refused | the login, "a token from the environment" or "the gh CLI's token". While a sign-in's refresh fails: "signed in as octocat, but the sign-in couldn't be refreshed: GitHub couldn't be reached; the Bridge tries again every minute". While GitHub refuses it: "GitHub refused the sign-in: sign in again on the Accounts tab" (setup.DetailGitHubRefused) |
audible | no | at least one Audible account signed in, none refused and none on an older device profile (an additive id: older servers and pages leave it out) | "1 account signed in", "1 account needs signing in again", or "... signing in again to keep backups working" when any is on an older profile, or "1 account is mapped on another server: map one on this server on the Accounts tab" when every account is mapped elsewhere; it adds "; places don't sync until then" while one is refused, and "; places not syncing for 1 account: " and the reason when an account's last position sync failed (that alone never makes it not done) |
"setup": {
"items": [
{"id": "paired", "done": true, "required": true},
{"id": "libraries", "done": false, "required": true, "detail": "1 of 2 libraries writable", "library_ids": [3]},
{"id": "asr", "done": true, "required": true, "detail": "local"},
{"id": "agent", "done": false, "required": false, "detail": "set the agent's sign-in on the Accounts tab; the agent signs in to Claude or ChatGPT and is needed for characters, recaps and descriptions"},
{"id": "budget", "done": true, "required": true, "detail": "$100 a month"},
{"id": "github", "done": false, "required": false}
],
"can_contribute": false
}
From v0.5.0 the agent item's detail is worded by setup.Checklist from the
agent container's problem as a kind (agentbox.Status.Problem, carried as
setup.AgentProblem), never the container's own text (which names the staging
volume and stays on the Status tab's agent line). Each ends with what the agent
is for ("the agent signs in to Claude or ChatGPT and is needed for characters,
recaps and descriptions"), but the backend mismatch, which names both CLIs:
| Problem | detail |
|---|---|
not_running (no status, an unreadable one, a stale heartbeat; also an unknown kind) | DetailAgentNotRunning: "the agent container isn't running yet; ..." |
outdated (another protocol, or an image too old to take the Accounts tab's credential) | DetailAgentOutdated: "the agent image isn't this Bridge's version: run the same version of both images; ..." |
no_cli | "the agent image has no claude CLI: use this Bridge's agent image; ..." (agentNoCLI) |
other_backend | "codex is signed in, but this Bridge runs claude: set agent.backend: codex and restart the Bridge, or set claude's sign-in on the Accounts tab" (agentOtherBackend) |
no_credential | DetailAgentNoCredential: "set the agent's sign-in on the Accounts tab; ..." |
group_required (agent.require_group is on and the handed credential can't be kept to the Bridge's group) | DetailAgentGroupRequired: "agent.require_group is on, and the agent's credential can't be kept to the Bridge's group: the Accounts tab says why" (no "what the agent is for" ending) |
handoff_failed (giving the handed credential to the Bridge's group failed with an error that is not a refusal) | DetailAgentHandoffFailed: "the Bridge couldn't hand the agent its credential: the Accounts tab says why; ..." |
no_endpoint (the openai-compatible backend with no endpoint address) | DetailAgentNoEndpoint: "set the OpenAI-compatible endpoint's address in Settings > Agent; ..." |
endpoint_service (the openai-compatible backend with no agent service of its own: no agent.endpoint_staging_dir, a folder shared with the agent container's, or a runner there that isn't --endpoint-only or runs as the agent container's user) | DetailAgentEndpointService: "an OpenAI-compatible endpoint needs an agent service of its own, apart from the agent container (agent-runner --endpoint-only, its own user, no /agent): the Accounts tab says what to change" (no ending) |
own_credentials (the endpoint's agent service holds a credential or reaches /agent) | DetailAgentOwnCredentials: "the endpoint's agent service holds a credential or can reach /agent, which an OpenAI-compatible endpoint's run could read: give it neither, or choose claude or codex in Settings > Agent" (no ending) |
endpoint_only (the claude or codex backend whose staging folder holds the endpoint's agent service) | DetailAgentEndpointOnly: "for claude or codex the Bridge reaches the OpenAI-compatible endpoint's agent service, not the agent container: the Accounts tab says what to change" (no ending) |
a refused credential (Refused) | the container's own detail, saying where to replace it (else DetailAgentNoCredential) |
The item is optional (required: false, an owner decision reversing FIRST-RUN
F2): podcasts, read-along, chapters and Audible need no agent, so setup reads
complete without an agent container. The console's Setup card shows the
Bridge's detail when it sends one, and otherwise its own hint for the id
(bridge.setup.hint.agent, also saying what the agent is for). The console still
holds Generate back while the agent step isn't done, required or not
(generateNeed): a run without the agent would park agent_unavailable.
An item that waits for an ASR worker carries needs_worker: true (the asr row
above). The usual fix is then a worker, not a setting, so the Bridge's Status tab
(setupLinks in web/src/lib/setup.ts) puts a Workers link before the step's
own tab, and the console's Setup card in Server > Settings > Bridge
(setupItemLink in setup-model.ts) links the Workers tab instead of Settings.
An older server ignores the key, as it reads the block leniently.
An older console, and the current one for a Bridge that sends no flag, match the
asr item's detail text "waiting for an ASR worker" instead
(setup.DetailASRWaiting, ASR_WAITING_DETAIL in setup-model.ts). Keep those
words stable when changing the checklist.
The Bridge collapses each detail's whitespace and cuts it to 200 bytes (ending
"..."). The server reads the block
leniently, like estimates (bridge/setup.go; a block that doesn't decode is
dropped, never the heartbeat), within the bounds in the
heartbeat reference. An
unknown id is kept: the Bridge owns the list, and the console words the ids it
knows and shows the rest with a capital first letter, _, . and - read as
spaces (ebook_reader is "Ebook reader"). GET /admin/bridge
carries it (with the login, admins only); GET /server never does.
Beside items, the block carries four optional fields, all additive (an older
Bridge sends none, and the server drops a value of the wrong shape):
can_contribute, below;github_login, the signed-in GitHub user;github_state, why the GitHub sign-in can't be used now:unrefreshed(still signed in,github_loginkept, waiting for GitHub to answer a refresh) orrefused(sign in again). Omitted otherwise;agent_credential, how the Accounts tab's agent credential reaches the agent container (The credential hand-off):group(the Bridge's group alone),world(every uid on the staging volume until the runner takes it),group_required(agent.require_groupcan't be met, so nothing is handed over) orfailed(the Bridge couldn't give it to the runner). Omitted while no hand-off is in play: the container's own credential, or no live runner.
The console's Setup card shows agent_credential as its Credential hand-off
row, and counts the agent credential as set whenever a hand-off is reported, even
while the agent step waits on it. It shows github_state on the GitHub account
row. It shows nothing for a value it doesn't know.
can_contribute here wins over estimates.sidecars.can_contribute
(Status.CanContribute(): the setup block's when one was sent and kept, else the
estimates'). The Bridge keeps sending both, so an older server still reads the
estimates' copy. The Bridge's page shows the same checklist as its Status tab's
"Get set up" card until every required item is done.
The server counts the Bridge online while the last heartbeat is under two
minutes old (bridge.OnlineWindow). Then, and only then, GET /server says
capabilities.bridge: true, with a top-level bridge: {version, features} beside
capabilities. features are the job families the Bridge runs that the server
knows: the part of each known kind before its dot. It is a list, [] for none,
never null.
| Kind | Feature |
|---|---|
bridge.verify | bridge |
sidecars.generate, sidecars.describe, sidecars.contribute | sidecars |
chapters.detect | chapters |
meta.correct | meta |
readalong.align | readalong |
podcast.subscribe, podcast.poll | podcast |
features also lists contribute while the Bridge can contribute
(Status.CanContribute(), above; bridge.FeatureContribute). It is the first
feature that is not a job family, and the server's contributions
module needs it.
The bridge block goes only to a signed-in caller: a session or an API key of
any role, not a demo account's (api.signedIn over auth.Peek, which records
nothing on the token). An anonymous, refused, demo or bridge token sees the flag
alone. The capability flags stay public.
The server reuses the heartbeat it read for up to 5 seconds, so
GET /server, which every client calls often, rarely reads the database for it. A
pairing or an unpair drops that copy at once. A
client checks the flag and the feature it needs; a feature the Bridge doesn't
advertise is off even while the flag is on. The console reads GET /admin/bridge
for its Bridge page, and both the console and the player gate
Generate characters and recaps on the flag
and the sidecars feature.
The Bridge counts itself online the same way on its own page: the last heartbeat went through less than two minutes ago and the last one didn't fail. It runs no job on a new link (after pairing, a restart or a refusal that ended) until a heartbeat has gone through on it, so it knows the server's libraries first.
The job model
Two rows describe every job:
- The server's
bridge_jobsrow is the intent and the lease: what an admin asked for, its state, and which claim holds it until when. It is path-keyed like durable user state (library_id,rel_path; no foreign key to the book index), moves with its book and goes with its library. - The Bridge's
server_jobsrow is the execution truth: the jobs this Bridge claimed, by the server's job id and attempt, with what it found and whether the server has taken its final report.
States
queued, claimed, running and needs_attention are open; a kind, a library
and a path have at most one open job (the dedupe_key and a unique partial index),
so a second press of the same button returns the open job (200, not 201).
The Bridge may report a job it holds (claimed, running or needs_attention) as
running, done, failed, needs_attention or cancelled; it can never put a
job back in the queue.
Job progress
A job's progress is one flat JSON object (jobs.Progress), at most 16 KiB. The
server stores it as sent and reads none of its keys but a parked job's park
(which it keeps when a later report names none), so each kind can add its own
fields beside these:
| Field | Meaning |
|---|---|
step | always set: the kind's step, a short machine word (download, stat, waiting) |
message | the step as an English sentence |
message_code | optional: the code of message's sentence, when it is one of the Bridge's fixed sentences (from Bridge v0.7.0) |
message_params | optional: the values (strings or numbers) the coded sentence fills in, only for a code that has them |
done, total | the step's counts, when it has some |
{
"step": "download",
"message": "Downloading section 2 of 3 from archive.org",
"message_code": "downloading_section",
"message_params": { "section": 2, "sections": 3 },
"done": 1,
"total": 3
}
The codes are stable snake_case names, listed with their English sentences in
the Bridge's internal/jobs/phrases.go (the Say* constants). A sentence's
placeholders are i18next's {{name}}. Two codes have params:
library_not_writablefills inlibrary(the library's name);downloading_sectionfills insectionandsections(numbers).
A book waiting for its turn in the ASR lane stays running. The Bridge sends
step: "waiting" and message_code: "asr_turn_wait", with the English message
"Waiting for a turn to use speech recognition". It keeps the engine's stage
and omits done, total and eta_seconds. The rule covers the ASR lane's
stages (asr, retranscribing and readalong_aligning) only, so a book still at
the engine's queued step reports its eta_seconds. A book waiting for a
worker to connect has a worker park.

The job keeps its Running badge while another book uses speech recognition.
A handler names a sentence by its code (Progress.Code, with Params), and the
Bridge fills in message from the code's English (Progress.Text), so every
report carries the English. Text that is not a fixed sentence is sent without a
code: an engine stage's label in sidecars.generate ("Transcribing (12 of 40)"),
and the park reasons of the book jobs' own parks (sidecars.generate,
sidecars.describe, chapters.detect), each a sentence with the library's name
or an error in it. When a progress is over 16 KiB, the Bridge drops the kind's
own fields, then message_params, and keeps the code; the console shows a code
without its params as the English message.
Who reads it:
- The admin console words a code it knows in the admin's language and shows
message, elsestep, for anything else (The job list has the detail). - The Bridge's own page shows
message, in English. - The player never shows a job's message: it words its jobs from
step,stage, the park's code (a code it doesn't know shows the park'shint) and the counts.
The codes are part of the wire: a code is never renamed or reused. A new
sentence gets a new code, added in the same change to phrases.go, to the
console's PROGRESS_CODES (in admin-ui/src/features/bridge/bridge-model.ts,
each code with its param names) and to all six of the console's locales. The
Bridge's internal/jobs/testdata/phrases.json pins the shipped codes and their
English (TestPhrasesShipped), and the console's tests check that every code in
PROGRESS_CODES has an English sentence naming exactly its params and that the
other five locales keep the same placeholders.
Job results
The server stores the Bridge's result JSON as it arrives; each kind's page
gives its shape. A result that filed a GitHub issue can carry an optional
routing note for an issue a maintainer must send to intake
(Intake routing):
| Job | Result field |
|---|---|
sidecars.generate, sidecars.contribute | intake_notes: each affected dimension (characters, recaps) to its note |
meta.correct | intake_note: one string for the correction issue |
The console has no message for these notes yet: they appear only in the job's raw result, under Details in the jobs list.
Job history
When the server enqueues a new job, it applies the kind's history rule
(kindSpec.prune) in the same transaction. Each rule applies only to ended
jobs of the same kind.
| Job kind | History kept on enqueue |
|---|---|
audible.poll, audible.sync | The newest ended poll and the newest ended sync for each Audible account. |
podcast.poll | The newest ended poll for the show in that library. |
podcast.fetch, podcast.retain | The newest ended fetch for the episode or retain for the show in that library, plus any older results the server has yet to apply (podcast_folded). |
Other kinds, including audible.import | All of it. |
Claims and leases
The Bridge long-polls GET /bridge/jobs/next?wait=25&kind=…. The server picks the
highest-priority, oldest queued job among the kinds the last heartbeat named that
the server knows. It narrows them to the kind values, the kinds the Bridge has a
free lane for. It leases the job to the Bridge for 2 minutes
(bridge.Lease) and increments attempts.
- With none queued, the server waits up to 25 seconds. A job queued meanwhile, or one put back by a lapsed lease, wakes it.
- With no kind left after the narrowing, it answers
204at once. - A server that is stopping ends the wait with
204. - Before the first heartbeat, a claim is
409 no_heartbeat. - A claim whose token a pairing or an unpair revoked during the wait is
401.
An idle claim writes nothing. Each try first reads, on the reader pool
(bridge.claimDue), whether the token is still live and whether the claim has
anything to write: a lease that ran out, a private follow request whose feed URL
the server no longer holds, or a queued job it would hand out. Only then does it
take the writer, check the token again and claim, in one transaction committed
durably (WithDurableTx: an attempt
number is never handed out twice). An idle Bridge long-polls without pause, so a
write per claim would keep emptying the server's
list answer cache and token cache
for nothing. A job queued after the read still wakes the waiting
claim, and a lease that lapses later is due at the next one.
After accepts lists claim_min_priority, the reserved dispatcher uses
GET /bridge/jobs/next?kind=podcast.fetch&min_priority=100&wait=25.
The optional floor is one signed base-10 int32; malformed, empty, repeated or
out-of-range values are 400 invalid_request. Omission keeps ordinary claim
behavior. Filtering happens inside the claim transaction before lease or
attempt mutation, alongside kind/module/token checks; priority descending
then id ascending still decides order. A request deadline answers 503.
The Bridge's internal/jobs runner has one ordinary and one reserved
dispatcher, reserving lane admission before claiming. Defaults are light:2,
download:1, interactive:1, pipeline:25. The reserve only accepts opted-in
handlers at priority at least 100 (InteractiveHandler, podcast.fetch
today), never background work. Ordinary slots can take interactive jobs too;
total enclosure concurrency stays at two. Without negotiated support,
interactive becomes zero and download two, so an older server ignoring an
unknown query cannot fill the reserve with background jobs. The lanes the page
lists (Runner.Lanes, in GET /api/status) leave out a lane with no capacity
and nothing running, so that folded interactive lane no longer shows as
"0 of 0" (v0.3.0).
Each dispatcher sends one long poll with wait=25 for the kinds whose lanes
have room. It keeps a slot in each requested lane until the poll returns. When
a lane the poll left out gains a free slot, the dispatcher keeps the poll open
and sends a second claim with wait=0. This claim asks only for kinds in
omitted lanes that now have room. The server accepts both claims on the same
Bridge token. It selects and leases each queued job in one transaction, so only
one claim can receive that job while the lease holds.
If the second claim returns 204 and the lanes still have room, the dispatcher
checks them again after 4 seconds. It makes at most three timed rechecks in
total during that long poll. This lets it pick up work queued after the empty
reply. Each dispatcher sends only one wait=0 claim at a time.
Unpairing, pairing again, stopping the Bridge or changing lane capacities (including the negotiated reserve) cancels both requests. The dispatcher waits for both calls to return before its next long poll. Every job belongs to the pairing that handed it out, even if its reply arrives during cancellation. The Bridge drops a reply from a pairing that has ended. If a job arrives as the Bridge stops on the same pairing, it records the job for the next start.
If the claim committed a lease but the reply was not delivered (including write/flush failure or Bridge disconnect), the server releases that untouched claim without spending an attempt. State, attempt and lease must still match; a reported/renewed claim is left alone. A successfully flushed reply is not released merely because shutdown or a deadline follows it. Lost replies that cannot be released still use normal lease recovery.
Each accepted running report (PATCH /bridge/jobs/{id}) renews the lease.
The handler records progress. A reporting loop sends each new step at once,
other changes at most every 2 seconds, and an idle keepalive after 30 seconds
(jobs.DefaultKeepalive). A report that only
renews the lease or carries progress is a user-state write on the server, which
leaves the caches keyed on the content generation warm. A new
state, result or error, or a report that expires another job's lease, is a
content write.
Progress reports and keepalives make one HTTP attempt (link.SingleAttempt) and
hold the report send lock only for that attempt. After no answer, a 5xx or a 408,
the loop schedules the next idle report after 10 seconds (jobs.DefaultReportRetry).
After a 429, it waits those 10 seconds or a longer Retry-After, up to one minute.
Progress within the same step waits too. A new step, a park or the final report
can go through during that wait. Other 4xx responses use the normal keepalive interval.
A report carries the attempt its claim returned: a report from an earlier claim is
409 not_held, as is one about a job that ended, was cancelled or no longer exists
(the route never answers finished). A report's error text is cleaned rather than
refused (control characters become spaces, line breaks stay, cut at 2 KiB), since
a refused final report would be retried for ever while its job ran again; the
Bridge also keeps its own reports inside the server's limits (a step of 128 bytes,
a message of 1 KiB, an error of 1 KiB) and fails a job whose result wouldn't fit.
When the job ended cancelled and no later claim took it, the 409 adds
reason: "cancelled" (server 2.7.0; the causes are listed under the route's
409). The Bridge reads that
as link.ErrCancelledHere, stops the job as it does for cancel_requested, and
its Jobs tab shows Cancelled. Any other not_held ends the job as lost
(Lost, "The server took it back"). A report with attempt 0, which no claim
returned, always gets the plain answer. An older server never sends the reason, so
its cancelled jobs still read as lost.
When a lease runs out the job goes back to queued, with the dead attempt's
progress, result and error reset, unless:
- it was on its third attempt (
bridge.MaxAttempts): it fails, with the error "the Bridge stopped reporting on every attempt"; - an admin had asked to cancel it: it is cancelled.
Those two keep what was reported.
The server checks leases whenever a job is claimed, reported on, cancelled or read by the console, so a Bridge that died mid-job leaves the job queued again (or ended) by the time anyone looks.
When the server returns 429
The server answers a 429 before the request has any effect: its
rate limiter before the route
runs, and pairing's wrong-code lockout before the code is read. So the Bridge
can send it again.
link.Backoff.Do waits the Retry-After, read as seconds or an HTTP date
(link.APIError.RetryAfter; RetryAfterSet says the header was valid). A
Retry-After: 0, or a date in the past, asks again at once and still counts as
an attempt. With a missing or invalid header it backs off exponentially with
jitter, the first wait between 0.5 and 1 second by default.
The budget depends on the call:
- A required call in a running job.
link.WithRetryDeadlinesupplies the lease expiry from the claim or latest successful report, minus a 10-second margin (jobs.leaseMargin). The call takes that deadline at its first 429. If the requested wait would put the next attempt past it, the call returns the 429 immediately. - Any other call (no known lease, or a deadline already passed at the first refusal): three attempts, each wait capped at one minute.
- A call a person waits for on the Bridge's page (
link.Client.Prompt: pairing, and the Accounts tab's list of people): three attempts, and a wait over 10 seconds returns the 429 at once. - Progress reports and keepalives make one attempt and leave the wait to the reporting loop (above).
- A call with its own
link.Backoffgives up sooner and leaves the work to a later run: Audible's enrichment PUTs, and the podcast episode and poll rescans. A subscribe's show rescan keeps the job's budget.
If a required call still fails with a 429, the runner checks
jobs.ServerQueuedHandler. The podcast, Audible and LibriVox handlers return
true from ServerQueued(). The runner reports these jobs as failed with
the handler's usual error, so the server can schedule another run. For an
admin-started kind such as bridge.verify, the runner reports needs_attention
and asks the admin to cancel and queue the job again when the server is ready.
Cancelling
POST /admin/bridge/jobs/{id}/cancel ends a queued or needs_attention job at
once (nobody is working on it). For a claimed or running job it sets
cancel_requested: the Bridge reads it in the answer to its next report (within
about 32 seconds at a job with nothing new to report: the keepalive plus one
2-second reporter tick, or up to a minute after a report the server answered
429), stops the job and reports it cancelled. The console
shows the job as cancelling meanwhile. If the Bridge never reports again, the
lease runs out and the job is cancelled then. Cancelling an ended job is
409 finished. When the same request arrives while the old job is stopping, the server records
the old job as cancelled and queues a new job. The old claim learns this at its next report.
The Bridge's own page can cancel a job it is running too; that is reported to the
server as cancelled, the same as an admin's cancel.
A parked job the server cancels at once is still held by the Bridge until its
next keepalive (up to 30 seconds). So a book job queued for the same book right
after would meet it as an open job and be refused ("cancel it first"). That
keepalive is 409 not_held with reason: "cancelled"
(above), so the Bridge records the job cancelled, not lost.
From v0.5.0, a new sidecars.generate, sidecars.describe, chapters.detect or
readalong.align job that finds another open job on its engine book first asks
that job to report now (jobs.Reporter.Refresh). When the answer stopped it, or it
couldn't be asked, the new job waits for its end, up to openJobWait (30 s), with
the progress message "Waiting for the book's earlier job to end"
(Handler.awaitOpenJobEnd). A job the server still holds open is refused at once.
An ending job stops its engine book before its end is recorded (release), so the
waiting job starts only once the engine's cancel has returned.
The server's cancel reasons (server 2.5.1). When the server stops a job itself,
it writes the reason as the job's error. IsCancelReason names the reasons:
- the kinds'
cancelsOpenstrings: "a generate job for the book replaced it", "... replaced it; it finds the chapters itself", "... replaced what it was sharing", "... replaced it; make the read-along again after"; CancelMoved("the book moved onto another job of this kind",MoveJobs);CancelReplacedRequest("a newer request replaced it", a podcast request replaced byEnqueuethroughcancelOpenTx);CancelModuleOff("its module was turned off", a share-only job the Bridge held when the Contributions module was turned off, set byUpdateHeld; see Jobs of a managed module);- an Audible account's job's:
CancelAudibleRemoved,CancelAudiblePausedandCancelAudibleSyncOff(see Audible).
MoveJobs cancels the old path's open job at once in any state, with no
cancel_requested. A Bridge still working on it learns at its next report
(ErrNotHeld).
Through cancelOpenTx, a queued or parked job is cancelled at once with the
reason. For a claimed or running one, cancelOpenTx sets cancel_requested and
records the reason now, unless an admin asked first, whose cancel keeps its own
error. UpdateHeld keeps the reason through the Bridge's reports, which always
send an error of their own, while the job works and when it ends cancelled. After a cancel
request, the server stores a failure or park as cancelled and preserves the cancel reason. A
completed job remains done. A cancelled podcast job counts against
the feed's outage only for a definite feed response.
The console words a cancelled row (cancelledView in generate-model.ts;
CancelledStatus in generate-status.tsx; en.json bridge.jobs.*). It tells
a server's reason by the admin reads' error_code: "server_cancelled"
(The job object), which the Bridge
never receives:
- a server reason as it is;
- else
bridge.jobs.cancelledByAdmin"Cancelled by an admin." whencancel_requested(an admin's cancel); - else
bridge.jobs.cancelledOther"Cancelled." (the Bridge ended it itself); - plus, for a job cancelled from a park,
bridge.jobs.cancelledPark("It was waiting for attention:" and the park's reason) and the park's plain hint.
A working job with cancel_requested and the server code (isServerCancelled)
shows that reason muted, not as an error (bridge-jobs.tsx), for a kind outside
BOOK_KINDS (a podcast request). A book kind's row (every cancelsOpen kind among
them) is GenerateStatus, which keeps its progress until the job ends
cancelled. Any other error on a cancelled job (a supervisor's text, say) is
never shown.
Resuming after a restart
A Bridge that stops (a restart, an update, a crash) leaves its server_jobs rows as
they were:
- A job that was running is resumed at the next start, once the link is up,
under the same claim: its first report carries the old attempt. If the lease
is still alive the job simply carries on. If it ran out meanwhile, the server
has queued the job again (or claimed it as a later attempt), so that report gets
409; the Bridge records the row aslostand the claim loop takes the job again as the next attempt. A409withreason: "cancelled"records the rowcancelledinstead. - A job that had finished but whose final report never reached the server is reported again, every 30 seconds, until the server takes it or says it has moved on.
- A running job of a kind the Bridge no longer runs is failed.
- A parked job (
needs_attention) resumes parked, and its first report sends the progress it last recorded, park code and all (v0.3.0). While it stays parked, a report whose progress names no park keeps the one before it (Reporter.Progress), since a resumed job reports its first steps before it hears its engine's park again. The server keeps the stored park too when an update to a parked job names none (carryParkininternal/bridge, server 2.4.0), so a restart no longer reads as a park dropped and a new one raised: no spuriousbridge_job_failedevents, and the console keeps the reason.
If the admin who paired the Bridge loses the admin role, the server refuses that Bridge’s token. Restoring the role lets the same pairing work again.
A refused token stops the running job. The Bridge can resume it after a temporary refusal of the
same pairing: pairing the same server again after a refusal, with no unpair between, keeps the
pairing and its ID. Forgetting the link (unpairing on the Bridge's own page) ends the pairing, and
pairing after that is a new one, even with the same server, so the old claims end. A pairing with
another server is a new one too, and its libraries can share the old server's library ids.
The Bridge reads GET /api/v1/server for the server ID, binds each claim to its pairing
(jobs.Job.Under) and releases work before recording it lost. It never reports an old result on
the new link.
Kinds are allow-listed twice
The server queues a job only when its kind is one the server knows (it can
check the job's parameters: bridge.Known, a per-kind table in internal/bridge)
and one the paired Bridge advertised in its last heartbeat. Otherwise
POST /admin/bridge/jobs is 409 kind_unavailable. The Bridge may be offline: the
job waits for it. Likewise a claim only ever hands out kinds that are in both lists.
So neither side can be made to run something the other doesn't understand: a
Bridge can't advertise a kind into existence, and the server can't queue one the
Bridge doesn't have.
The server's table also says whether a kind writes into the library. Such a
kind (sidecars.generate, sidecars.describe, chapters.detect, readalong.align, podcast.subscribe,
podcast.poll, podcast.fetch, podcast.retain, audible.import, librivox.fetch) is queued only for a library the last heartbeat reports
mapped and writable, else 409 library_not_writable, after the dedupe (an open
job is still returned). bridge.verify, sidecars.contribute and meta.correct
write nothing. Book-writing jobs refuse a podcast library with
409 not_book_library; podcast jobs require a podcast library.
Two kinds write the same book's files, so the server keeps them apart
(bridge.Service.Enqueue, inside its transaction, after the dedupe): a
sidecars.describe job is refused with 409 generate_open (ErrGenerateOpen)
while a sidecars.generate job is open for the book, which writes the description
itself when it finishes; and a sidecars.generate job queued while a
sidecars.describe job is open cancels that one (cancelOpenTx: at once when
it is queued or parked, else cancel_requested, its error "a generate job for the
book replaced it"). A generate job is never refused for an open describe job. See
A description on its own.
chapters.detect and readalong.align join them. kindSpec's refusedWhileOpen and
cancelsOpen are the one statement of which open kind refuses, or gives way to,
which:
| New job | Refused while open for the book | Cancels |
|---|---|---|
sidecars.generate | chapters.detect queued, claimed or running (409 detect_open: cancelling it would throw its transcription away, and a generate job queued after it reuses it); sidecars.contribute queued or working (409 contribute_open, ErrContributeOpen: it would replace the characters and recaps being filed), but not a queued one held while the contributions module is off (Service.givesWay, Service.held); readalong.align queued or working (409 readalong_open, ErrReadalongOpen: both transcribe the same audio, and a generate job after it continues its run) | an open sidecars.describe; a parked chapters.detect ("it finds the chapters itself"); a parked or held sidecars.contribute ("a generate job for the book replaced what it was sharing"); a parked readalong.align ("a generate job for the book replaced it; make the read-along again after") |
sidecars.describe | sidecars.generate (409 generate_open), chapters.detect (409 detect_open: both rewrite the book's bridge.json) | nothing |
chapters.detect | sidecars.generate (409 generate_open), sidecars.describe (409 describe_open), readalong.align (409 readalong_open) | nothing |
sidecars.contribute | sidecars.generate (409 generate_open: that run replaces what it would file) | nothing |
meta.correct | nothing | nothing |
readalong.align | sidecars.generate (409 generate_open), chapters.detect (409 detect_open), parked ones too: the Bridge runs one engine book per audio source, so runs over the same audio never overlap | nothing |
A job being cancelled (cancel_requested) refuses nothing, since it ends without
writing. So a detect job queues behind a generate job being cancelled. The
blocker kinds are asked in name order, so the answer is stable.
Service.Blocker names the open job that refuses a new job of a kind now, and the
estimate's open_job uses it.
The api also refuses two kinds before the queue:
chapters.detectwith409 chapters_chosenfor a book whose chapter source an admin chose (the catalog holds the choice), since a found list stands in only with no choice;readalong.alignwith409 no_ebookfor a book whose index holds no ebook. See Read-along.
Jobs of a managed module
The community jobs belong to the contributions module.
kindSpec.module names it for sidecars.contribute and meta.correct, and
bridge.ModuleFor(kind, params) also names it for a sidecars.generate job with
contribute: "issue". For such a job:
POST /admin/bridge/jobsanswers404 module_offwhile the module's toggle is off, before anything else about the job is checked (as the module's own routes would);Enqueuerefuses it409 cannot_contributeunlessStatus.CanContribute();- while the toggle is off, a queued share-only job is held.
nextQueuedpasses over it (bridge.Service.ModuleOn, wired bySetBridge), so turning the module off leaves its queued jobs at rest, a requeued one included, until it is on again. A heldsidecars.contributejob still gives way to a newsidecars.generatejob for the book like a parked one: no409 contribute_open, not the estimate'sopen_job, and cancelled; - "off" is the toggle alone. With it on, a queued share refuses a generate job even while the Bridge can't contribute;
- a
sidecars.contributeormeta.correctjob the Bridge already holds (claimed, running or parked) is asked to stop. These kinds only file to the community and write nothing, so stopping one loses no work (Service.stopsShare). At the Bridge's next report of a claimed or running one,UpdateHeldsetscancel_requestedwith the server's reasonCancelModuleOff(see Cancelling). A parked one is asked when it reports working again; - a Bridge that claims with
share_off=1can take a queued generate-and-share job for local processing. The server sendsshare_off: trueon the claim and reports while the toggle is off. The Bridge remembers that decision and finishes the local files. Older Bridges leave the queued job held.
On the Bridge, each kind has a handler and a lane, which sets how many jobs of that lane run at once:
| Lane | Room | Kinds |
|---|---|---|
light | 2 | bridge.verify, sidecars.contribute and meta.correct: a few reads and HTTP calls each |
pipeline | 25 | sidecars.generate, whose jobs mostly wait on the engine's own scheduler, which decides what actually runs; sidecars.describe, which can wait a long time on an agent park; chapters.detect, which follows an engine book like generate; and readalong.align, likewise |
Podcast jobs
podcast.subscribe, podcast.poll, podcast.fetch and podcast.retain belong
to podcasts and require a mapped, writable podcast library. Fetch runs in the
download lane (1 ordinary slot), with an additional reserved interactive
slot for priority 100 work after negotiation; the others run in light (2).
The server creates them from dedicated actions and its scheduler;
POST /admin/bridge/jobs refuses these internal kinds with 400.
The module's toggle holds queued jobs while off, as for contributions. A job the
Bridge already holds carries on.
Heartbeat replies always include library kind; the Bridge treats a missing
kind as books. Private subscribe URLs are injected only into the claim
response, sealed before local claim recording, and redacted on other reads.
Default admin job lists omit polls unless kind=podcast.poll is requested;
fetch and retain jobs are listed.
The OPML import queues the same podcast.subscribe jobs as a single
follow, so the Bridge sees no new kind or params; directory search runs on
the server (Discovery and OPML).
All podcast kinds are quiet and send no job notifications. Fetch/retain outcomes
never update feed polling state.
A failed podcast job's result carries a code that says whose failure it was:
- the feed's or the episode host's: the HTTP guard's code as given (
dns,networkfor a refused connection,timeout,tls,redirect_looppast 10 redirects,http_<status>, andgonefor an HTTP 410 from a feed or an episode host), or what the answer was (not_a_feed, say). An episode download that runs past its ceiling istimeoutwherever it stops; - the Bridge's own:
write_failedfor a local fault (the show path, an unreadablefeed.json, bad params, its own partial download), andbridge_lostfor its own deadline or stop outside the fetch, or the server out of reach at a lease check mid-job.
The server reads a failed job with no code as bridge_lost (a lease that ran out
on every attempt). Its scheduler's polls carry "scheduled": true in their
params, which the Bridge reads leniently and otherwise ignores, and which the
console shows as Scheduled by the server. Which codes count toward the
failing-feed notice is in
Podcast events.
Triggers share one fetch intent per episode; params, dedupe, priorities and promotion are in fetch and retain jobs.
Podcasts describes job params/results, scheduling, privacy and file ownership; the reference lists the listener routes.
Audible jobs
A failed audible.sync carries the counts reached once Audible gave places, and
{code, message} when the failure has a code (its result).
A backup reporting exists can name the conflict as file, book or audio. The console alone
controls the account’s sync switch.
audible.poll belongs to the audible module. It is internal (refused by
POST /admin/bridge/jobs with 400) and quiet. Its params are
{"account", "template"} (template the account's placement template, omitted
when empty), with no library or path. It is deduped per account, and it promotes
an open poll to a person's priority when Check now asks. It runs in the light
lane, and gives the slot back while it backfills missing ASINs through the
server (Enrichment pacing). A refused poll fails
with a code in its result. The module's scheduler queues it, and queued polls are
held while the module is off. One the Bridge already holds
carries on, as every Audible job does. See
Audible.
audible.import backs up one title into the account's library. It belongs to
the audible module too:
- internal;
- a writing kind: it needs a writable mapping of a books library, else
library_not_writable; - no book path;
- params
{account, asin, library_id, dest_path, template}, built by the server; - deduped per account and title;
- not quiet: done and failed are notified, named by the title.
The server sets its priority by who asked (a console Back
up, a policy or Back up everything; see
the priorities).
It runs in the download lane, one import per account at a time. An import
parked for its library mapping gives up its slot until the mapping is writable
again (see The job).
After a restart the import can resume from a partial download or place a completed decrypt. A new claim after a temporary placement failure can reuse that decrypt too. See Resume and temp files.
audible.sync brings an account's places on Audible to the server. It belongs to
the audible module. It is internal and quiet, with no library or book path. The
queued job stores only {account}; the server fills in the titles when the
Bridge claims it (see
Audible to the server). It is
deduped per account, and only the newest ended one is kept. The scheduler queues it every 15 minutes for each account
whose sync is on, at priority -10, and the console queues it at once when sync is
turned on or a title's sync changes. It runs in the light lane and writes nothing
into a library. Its failure codes are audible_refused (the server stops queueing
until a sign-in again), audible_sign_in, unknown_account, user_unavailable
and audible_error. The push back to Audible is no job: a loop reads
GET /bridge/progress every minute. See
Position sync.
LibriVox jobs
librivox.fetch adds one LibriVox recording to a books library. It belongs to no
module:
- internal (
POST /admin/bridge/jobsrefuses it with400), queued byPOST /admin/librivox/fetch; - a writing kind for a books library: it needs a writable mapping, else
library_not_writable, and a podcast library isnot_book_library; - no book path, since the book does not exist until the job places it;
- params
{librivox_id, work_id, recording_id, library_id, title}, built by the server (titleoptional); - deduped per library and project;
- not quiet: done is notified, named by the book its result names; a failed
or parked one is named by the params'
title, since only a done job's result names the book.
It runs in the download lane, so it takes turns with audible.import and the
ordinary podcast.fetch slot, and its partial download survives a restart. While
it is parked it gives its slot back (jobs.Reporter.Yield) and takes one again
before it carries on (see Parked fetches). When
it ends done, the server records the book as the recording. See
Add from LibriVox.
Notifications
The server tells admins about notable jobs itself (the Bridge has no route for
it); neither podcast kind is Job.Notable. When a notable job moves into done
it records bridge_job_finished, and into failed, or into
needs_attention with a park that isn't transient, bridge_job_failed, after the move commits. A
repeated park on the same claim is quiet for six hours unless its reason or its need for a person
changes. That covers the Bridge's reports and a
lease that runs out on the last attempt alike. A report that leaves the state as it
was is never news. The rules (which parks are transient) are in
Characters and recaps, the events in
Notifications.
The proof job: bridge.verify
bridge.verify proves the loop end to end without changing anything. The
console's Verify button on a library queues it.
| Queued with | library_id (required) and an optional book path (an indexed book; without one, the library's sample book, the one the mapping check uses: the first whole book among its first five by title) |
| Params | { "hold_seconds": 0-600 }, optional: how long to wait before finishing, so a cancel, an unpair or a killed Bridge can be tried mid-job (0 is stored as {}) |
| Lane | light |
What the Bridge does:
- Finds the library among the ones the server listed and where it sees it (its mapping, else the server's root path).
- Asks the server for the book's files (
GET /bridge/libraries/{id}/book). The link handles a 429 within the job's retry budget. Verify retries an unavailable server, a refused token, a 408 or a 5xx for up to two minutes. Other 4xx responses end the check at once. - Stats each file through its mount and compares the size with the server's.
- When they all match, probes whether it can write in the book's own folder (a probe file created and removed; a folder can refuse writes where the library root allows them).
- Holds for
hold_seconds, reporting each second.
Progress is { step, message, message_code, done?, total? }
(Job progress), with these steps:
| Step | Code | Message |
|---|---|---|
mapping | finding_library | Finding the library |
lookup | book_files_lookup | Asking the server for the book's files |
stat | comparing_files, then compared_files | Comparing the files, then Compared the files, with the count |
writable | checking_writable | Checking the book's folder can be written |
hold | holding | Holding, as asked, with the seconds |
The result:
{
"library_id": 1,
"mount_path": "/audiobooks",
"path": "Andy Weir/Project Hail Mary",
"files": [
{ "path": "Andy Weir/Project Hail Mary/Project Hail Mary.m4b",
"size": 912345678, "expected_size": 912345678, "ok": true }
],
"writable": true,
"elapsed_ms": 412
}
The full shape is {library_id, mount_path, path, files[{path, size, expected_size, ok, error?}], writable, writable_error?, elapsed_ms}, with at most
50 files. A file that doesn't match carries an error ("not found here",
"permission denied", or "size differs: N bytes here, M on the server"); when the
book's folder isn't writable, writable_error says why. Both are left out when
there is nothing to say. A mismatch fails the job with its result,
so the console still shows which files didn't match. The console's job list sums
the result up in one line (how many files matched, whether it can write, how long
it took, where it looked) and shows the raw JSON under Details.