feat(remote): end a remote session when its client is gone

This commit is contained in:
imSp4rky
2026-11-30 17:23:35 -07:00
parent e813737506
commit ffe812f054
13 changed files with 747 additions and 53 deletions
+2 -2
View File
@@ -950,7 +950,7 @@ Report the install status of the external binaries unshackle depends on (the sam
!!! note "Developer feature"
The `/api/session/*` endpoints power unshackle's **remote download** mode. A thin local client authenticates once against a remote server, then fetches titles, tracks, and segments, and proxies DRM licensing back through it. The server mounts these endpoints in `--remote-only` mode, and they are what the built-in `RemoteService` client drives. Most end users never call them directly.
The server holds remote sessions in memory. They expire after `serve.session_ttl` (default 300s) without a request, except while the login runs, which can stay idle for the larger of `session_ttl` and 600s. A remote session binds to the IP that made it, so the server rejects a request from a different IP with `403 FORBIDDEN`.
The server holds remote sessions in memory. They expire after `serve.session_ttl` (default 300s) without a request, except while the login runs, which can stay idle for the larger of `session_ttl` and 600s. A remote session whose client is gone ends sooner: see [Client presence](remote-sessions.md#client-presence). A remote session binds to the IP that made it, so the server rejects a request from a different IP with `403 FORBIDDEN`.
### Remote session lifecycle overview
@@ -989,7 +989,7 @@ the newlines must go out at once.
Make a remote session for a service and title. Authentication runs asynchronously in the background. This call returns immediately with `status: "authenticating"`, and you then poll the prompt endpoint. The body accepts `service` and `title_id` (both required). It also accepts a broad set of optional keys, because the body allows `additionalProperties`. These are `session_id`, `credentials` (`{username, password, extra?}`), `cookies` (base64 of zlib-compressed Netscape cookie file), `proxy`, `no_proxy`, `profile`, `cache` (map of forwarded cache files, keyed by the file path relative to the service cache directory with `/` separators and no `.json` suffix, so a nested key such as `session_web/<sha1>` lands in a subdirectory), `client_region`, `proxy_region`, `cdm_type`, `range_`, `vcodec`, `quality`, `best_available`, `dl_params`, `client`, and any service CLI options. `proxy_region` is the country code the client resolved `proxy` from; the server matches it against its own accounts. `client` is a freeform object the dashboard shows as sent (the CLI puts `version`, `code_hash`, `platform` and a redacted `argv` in it); the server ignores it above 4096 bytes of JSON.
`session_id` is the ID that you give the remote session, so that you can delete it before this call answers. It must be the canonical text of a version 4 UUID. Without it, the server makes the ID. A second create with the same ID from the same API key and IP ends the first one if the first one has not answered, and replaces its remote session when the new one is stored. A second create that fails leaves that remote session open.
`session_id` is the ID that you give the remote session, so that you can delete it before this call answers. It must be the canonical text of a version 4 UUID. Without it, the server makes the ID. A remote session with your ID ends when you send no request for it and open no channel within 150s of the create. A second create with the same ID from the same API key and IP ends the first one if the first one has not answered, and replaces its remote session when the new one is stored. A second create that fails leaves that remote session open.
`dl_params` is an object with the `dl` track selection: `lang`, `v_lang`, `a_lang` and `s_lang` (arrays of language strings), `acodec` (an array of audio codec names or `dl -a` aliases such as `ddp`), and `forced_subs` and `exact_lang` (booleans). The service reads these values from `ctx.parent.params`. The server uses the `dl` default for each absent value. It refuses a malformed value, an unknown codec, range or vcodec name, and a height of 0 or less with `INVALID_PARAMETERS`. The flat `range_`, `vcodec`, `quality`, `best_available` and `generate_dv` keys are `dl` values on this route. On the list and search routes they are `dl` values only when the body has `service_params`.
+38 -10
View File
@@ -385,20 +385,22 @@ HTTP session headers and `track.data` lose their secret-looking keys, as for a s
## Remote session lifecycle and expiry
Remote sessions live in an **in-memory store on the server** and expire on a timer. You
Remote sessions live in an **in-memory store on the server**. They expire on a timer, or when their client is gone. You
generally never touch this directly, but it explains behaviour you might observe.
| Behavior | Value | Notes |
|---|---|---|
| Idle session TTL | **300s** (5 min) default | Refreshed on every request to the session and when a `titles` or `tracks` request ends. A remote session does not expire while a request works on it or while its remote session channel is open |
| Idle session TTL | **300s** (5 min) default | Refreshed on every request to the session and when a `titles` or `tracks` request ends. A remote session does not reach this limit while a request works on it or while its remote session channel is open |
| Client presence | **180s**, **150s** or **90s** | The time that a client can be silent after it lost its channel, after `create`, or after it closed its channel. See [Client presence](#client-presence) |
| Max concurrent sessions | **100** default | When full, the least recently used remote session of the API key that holds the most is evicted. A remote session that a request works on goes last |
| Auth/input timeout | **600s** (10 min) | A remote session that still logs in, a prompt included, can stay idle for the larger of the TTL and this value |
| Cleanup sweep | every 60s | Expired sessions are removed and their input prompts cancelled |
| Auth/input timeout | **600s** (10 min) | A remote session that still logs in, a prompt included, can stay idle for the larger of the TTL and this value, unless its client is gone |
| Cleanup sweep | every 5s | Expired sessions are removed and their input prompts cancelled |
!!! note "Auth is never rushed"
A remote session that is still `authenticating` or waiting on `pending_input` can stay
idle for the larger of `session_ttl` and 600s. This gives you time to enter an interactive
code without the remote session vanishing mid-prompt.
code without the remote session vanishing mid-prompt. The client must stay: it keeps its
channel open, or it polls.
The TTL and max-session limits are read from server config:
@@ -550,7 +552,7 @@ layer.
fails then, because no client is listening. A fetched call waits 60 seconds for its answer.
The call leaves the auth status as it was. An answer never marks the remote session as client-authenticated.
- `AUTH_INPUT_TIMEOUT = 600.0` seconds. An `AUTHENTICATING` remote session expires in the store after
the larger of `session_ttl` and this value. A remote session that waits on a prompt stays `AUTHENTICATING`.
the larger of `session_ttl` and this value, or when its client is gone. A remote session that waits on a prompt stays `AUTHENTICATING`.
`GET /api/session/{id}/prompt` returns one of:
@@ -621,15 +623,17 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from
key or IP has. **`end_pending()`** ends such a create for a `DELETE`, and then `create()` stores nothing.
- **`create()`** evicts the least-recently-accessed remote session of the API key that holds the most when at capacity,
then stores a complete `SessionEntry` from the fields of the `create` handler and publishes the `create` event.
- **Expiry.** `get()` and `cleanup_expired()` use one rule. A remote session that no request holds
expires when it is idle for longer than `ttl`. While its login runs (`AUTHENTICATING`), the limit is
- **Expiry.** `get()` and `cleanup_expired()` use one rule. A remote session expires when its client is gone
([Client presence](#client-presence)), also while a request holds it. A remote session that no request holds
also expires when it is idle for longer than `ttl`. While its login runs (`AUTHENTICATING`), the limit is
the larger of `ttl` and `AUTH_INPUT_TIMEOUT`.
- **`get()`** refreshes `last_accessed` and `idle_since` through `touch()`. It returns `None` and
deletes the entry when the remote session has expired.
- **`cleanup_expired()`** runs every 60s and removes each expired remote session.
- **`cleanup_expired()`** runs every 5s and removes each expired remote session.
- **Removal.** Eviction, expiry and `delete()` end the remote session the same way: they cancel its
`InputBridge`, close its channel, send the `delete` dashboard event, schedule a staged service reload
and delete its cache directory (pruning empty parent dirs up to, but not including, the cache root).
and delete its cache directory (pruning empty parent dirs up to, but not including, the cache root). A request
that waits for the remote session then answers `SESSION_NOT_FOUND` and starts no service code.
- **`track_login(task)`** keeps each login task of `session/create` until it ends.
- The server calls **`close()`** on shutdown. It ends each open remote session, which
unblocks any waiting auth threads, and deletes the cache directory of each one. It sends no dashboard event
@@ -649,9 +653,33 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from
| `cache_tag` | Per-session cache directory tag |
| `input_bridge` | `InputBridge` for interactive auth, if any |
| `auth_status` / `auth_error` | Current `AuthStatus`, read from `input_bridge` (`AUTHENTICATED` without one), and last error message |
| `presence` | `ClientPresence`: the state of the client and its last sign of life |
| `created_at` / `last_accessed` | Timestamps; `last_accessed` drives LRU eviction |
| `idle_since` | Monotonic time of the last access; it drives the TTL, so a step of the system clock expires no remote session |
### Client presence
Source: `unshackle/core/api/client_presence.py`. The server knows a client by its channel, its requests and its
`create`. Each state has a limit for the silence of the client. At the limit, the server ends the remote session.
| State | When | Limit |
|---|---|---|
| awaited | The client gave the remote session its ID in `create`, and has sent no request and opened no channel since | 150s |
| polling | The client has had no channel | The TTL rule only |
| present | The channel is open | None |
| away | The channel closed with any code except 1000, the connection broke, or the server closed the channel | 180s, or half of `session_ttl` when that is more |
| left | The client closed the channel with code 1000 | 90s |
- **Sign of life.** A request of the client for the remote session, or a new channel, starts the time again. The end
of a request does not. A request after the state left makes the state away.
- **Work in progress.** A request that still works for the client does not keep the remote session past the limit.
- **Login.** A client that is away or left does not get the 600s of a login. Its login ends with the remote session.
- **TTL.** The limit never makes a remote session stay for longer than the TTL rule lets it.
- **The `DELETE`.** The client closes its channel and then sends the `DELETE`, whose answer has the login cache.
Thus the close does not end the remote session at once.
- **A silent loss.** A client that the network cuts off sends no close. The server sends a ping after 20s without
data, and counts the client as away when no answer comes in 10s.
### Per-session cache namespacing
The `create` handler builds a `Cacher` namespaced as: