# mstransfer
> Transfer mass spectrometry files (mzML / MSZ / MSZX) between machines over HTTP
mstransfer moves mass spectrometry files (mzML, MSZ, MSZX) between
machines over HTTP. Files always travel as compressed MSZ using
mscompress: mzML sources are compressed on the fly during upload, and
the receiver can store them as MSZ or decompress back to mzML. It
ships a CLI (`serve`, `upload`, `download`), a Python client library
with sync and async APIs, and an embeddable FastAPI server with
pluggable auth and file discovery. Every page below is available as
Markdown; `llms-full.txt` contains all of them in one file.
# Getting started
# mstransfer
Transfer mass spectrometry files (mzML / MSZ / MSZX) between machines over HTTP. Files always travel in compressed MSZ format using [mscompress](): mzML sources are compressed on the fly while they upload, with no temp files on the sender, and the receiver can store them as MSZ or decompress them back to mzML.
```bash
# On the receiving machine
mstransfer serve --port 1319 --store-as msz
# On the sending machine
mstransfer upload /data/experiment1.mzML /data/batch/ remote-host:1319
```
## What's included
- **CLI**: `mstransfer serve`, `upload`, and `download`, with parallel transfers and Rich progress bars. See [CLI]().
- **Python client**: `send_file` / `send_batch` and `download_file` / `download_batch`, each with an `async_` variant. See [Python guides]().
- **Embeddable server**: a FastAPI app factory and router with pluggable authentication and file discovery. See [Server]().
## How it works
```
flowchart LR
subgraph Sender
mzML[".mzML"] --> compress["compress_stream()"]
msz[".msz / .mszx"] --> read["read file"]
end
compress --> upload["POST /v1/upload
(MSZ bytes)"]
read --> upload
subgraph Server
upload --> mode{store-as?}
mode -- msz --> write["write .msz to disk"]
mode -- mzml --> temp["write temp .msz"]
temp --> decompress["decompress to .mzML"]
decompress --> cleanup["remove temp .msz"]
end
```
## Where to go next
- [Installation]()
- [Quick Start]()
- [CLI reference]()
- [HTTP API]()
- [API Reference]()
- [Contributing]()
## For LLMs and coding agents
These docs are also published as Markdown, which models read far more reliably than HTML:
- [`llms.txt`]() — index of every page, following the [llms.txt]() convention
- [`llms-full.txt`]() — the entire site concatenated into one file
- Per-page Markdown — append `index.md` to any page URL, e.g. [`getting-started/installation/index.md`]()
# Getting Started
mstransfer has two halves: a **server** that receives and serves files, and a **client** that uploads to or downloads from it. Both ship in the same package, so you install mstransfer on every machine involved.
- [Installation](): install the CLI or library
- [Quick Start](): send your first file
## File formats
| Format | Extension | Description |
| --- | --- | --- |
| mzML | `.mzML` | XML-based, uncompressed mass spectrometry data |
| MSZ | `.msz` | mscompress's compressed, random-access container for mzML |
| MSZX | `.mszx` | tar archive bundling one or more MSZ files with metadata |
See the [mscompress concepts]() for details on MSZ and MSZX.
# Installation
mstransfer requires Python 3.10 or newer and runs on Linux, macOS, and Windows.
## As a CLI tool
Install it as an isolated tool so the `mstransfer` command is on your `PATH`:
```bash
uv tool install mstransfer
```
```bash
pipx install mstransfer
```
## As a library
Add it to a project to use the [Python client]() or [embed the server]():
```bash
uv add mstransfer
```
```bash
pip install mstransfer
```
## Docker
The repository ships a `Dockerfile` that runs `mstransfer serve`. See [Deployment]().
## Verify
```bash
mstransfer --version
mstransfer --help
```
# Quick Start
## 1\. Start a server
On the machine that should receive files:
```bash
mstransfer serve --port 1319 --output-dir ./received --store-as msz
```
`--store-as msz` keeps files compressed. Use `--store-as mzml` to decompress each file back to mzML once it arrives.
## 2\. Upload files
On the sending machine, pass any mix of files and directories, followed by the server address:
```bash
mstransfer upload /data/experiment1.mzML /data/batch/ remote-host:1319
```
mzML files are compressed to MSZ on the fly; `.msz` and `.mszx` files are sent as-is. Received files land in the server's `--output-dir`.
## 3\. Download files
Anything the server stores can be fetched back over HTTP:
```bash
curl http://remote-host:1319/v1/files # list files
mstransfer download http://remote-host:1319/v1/files/experiment1.msz \
--output-dir ./downloads --store-as mzml
```
`--store-as mzml` decompresses the downloaded MSZ locally.
## 4\. Or do it from Python
```python
from pathlib import Path
from mstransfer.client import send_file
result = send_file(Path("experiment1.mzML"), "http://remote-host:1319")
print(result.state, result.stored_as)
```
## Next steps
- [CLI reference]() for every flag
- [Uploading files]() and [Downloading files]() from Python
- [Authentication]() to require an API key
# CLI
# CLI
The `mstransfer` command has three subcommands:
| Command | Purpose |
| --- | --- |
| [`serve`](<#mstransfer-serve>) | Run the receiving server |
| [`upload`](<#mstransfer-upload>) | Upload files to a server |
| [`download`](<#mstransfer-download>) | Download files from URLs |
`python -m mstransfer` is equivalent to `mstransfer`. `mstransfer --version` (or `-V`) prints the installed version.
## `mstransfer serve`
Start the receiver server.
```text
mstransfer serve [--host 0.0.0.0] [--port 1319] [--output-dir ./received]
[--store-as msz|mzml] [--api-key KEY]
```
| Flag | Default | Description |
| --- | --- | --- |
| `--host` | `0.0.0.0` | Bind address |
| `--port` | `1319` | Listen port |
| `--output-dir` | `./received` | Where received files are written (created if missing) |
| `--store-as` | `msz` | Store as `msz` (compressed) or `mzml` (decompress on arrival) |
| `--api-key` | `$MS_API_KEY` | Require this API key on every request except `/v1/health` |
The command exits immediately if the port is already in use. Connections a previous server left in `TIME-WAIT` don't count, so a restarted server can rebind the port right away.
## `mstransfer upload`
Upload files to a server. Accepts any mix of files and directories; the last positional argument is the target.
```text
mstransfer upload [--recursive] [--parallel 4]
[--chunk-size 1048576] [--api-key KEY]
```
| Flag | Default | Description |
| --- | --- | --- |
| `--recursive`, `-r` | off | Recurse into directories |
| `--parallel`, `-p` | `4` | Number of concurrent uploads |
| `--chunk-size` | `1048576` | Upload chunk size in bytes |
| `--api-key` | `$MS_API_KEY` | API key sent as `Authorization: Bearer ` |
**Target formats**
| Target | Resolves to |
| --- | --- |
| `host` | `http://host:1319` |
| `host:port` | `http://host:port` |
| `http://host:port` | used as-is |
| `https://host:port` | used as-is |
**Inputs**
- Files with the extensions `.mzML`, `.msz`, or `.mszx` are uploaded; other files are skipped with a warning.
- Directories are scanned for `.mzML` and `.msz` files (recursively with `-r`).
- mzML files are compressed to MSZ on the fly and streamed straight into the request body. MSZ and MSZX files are streamed as-is.
Before uploading, the command checks `GET /v1/health` and exits if the server is unreachable. When the batch finishes it prints a summary and lists any files that failed, with the server's reason when it gave one (for example `409 Conflict: run1.msz already exists on the server`). A file the server refuses because its output already exists ([409 Conflict]()) counts as failed, and the command exits non-zero if any file failed.
## `mstransfer download`
Download one or more files from URLs, such as a server's [`/v1/files/{filename}`]() endpoint.
```text
mstransfer download [--output-dir ./downloads] [--parallel 4]
[--chunk-size 1048576] [--store-as msz|mzml|mszx]
[--skip-existing] [--force] [--no-resume] [--api-key KEY]
```
| Flag | Default | Description |
| --- | --- | --- |
| `--output-dir`, `-o` | `./downloads` | Directory to save files into |
| `--parallel`, `-p` | `4` | Number of concurrent downloads |
| `--chunk-size` | `1048576` | Download chunk size in bytes |
| `--store-as` | keep as-is | Convert each file to `msz`, `mzml`, or `mszx` after downloading |
| `--skip-existing` | off | Skip files whose destination already exists |
| `--force` | off | Re-download even if the destination exists (overrides `--skip-existing`), discarding any partial download |
| `--no-resume` | off | Start interrupted downloads over instead of resuming them |
| `--api-key` | `$MS_API_KEY` | API key sent as `Authorization: Bearer ` |
The local file name is the last segment of the URL path. The source format is inferred from its extension. See [Downloading files]() for the supported conversions and how multi-member `.mszx` archives are handled.
If a download is interrupted (a dropped connection, Ctrl-C), running the same command again continues from the bytes already received. If the file changed on the server in the meantime, or the server can't serve byte ranges, the download starts over. See [Resuming]().
The summary counts downloaded, skipped, and failed files separately, and lists each failure with the server's reason when it gave one. The command exits non-zero if any file failed.
## API key
`serve`, `upload`, and `download` all take `--api-key`. When it isn't given, each command reads the `MS_API_KEY` environment variable instead. If neither is set (or `MS_API_KEY` is empty), no key is used.
```bash
export MS_API_KEY=s3cret
mstransfer serve # requires the key
mstransfer upload run1.mzML remote-host # sends the key
mstransfer download http://remote-host:1319/v1/files/run1.msz
```
## Exit status
| Code | Meaning |
| --- | --- |
| 0 | Every file succeeded (skipped downloads count as success) |
| 1 | At least one file failed, the server was unreachable, or the port was in use |
| 130 | Interrupted with Ctrl-C |
# Python guides
# Downloading files
`download_file` and `download_batch` fetch any HTTP URL, typically a server's [`/v1/files/{filename}`]() endpoint.
## A single file
```python
from pathlib import Path
from mstransfer.client import download_file
path = download_file(
"http://remote-host:1319/v1/files/experiment.msz",
Path("downloads/experiment.msz"),
)
```
The body streams into a `.part` file next to the destination and is renamed into place only once complete and exactly the size the server announced, so an interrupted download never leaves a truncated file at the destination. Missing parent directories are created.
## Resuming
By default (`resume=True`), an interrupted download keeps its `.part` file, plus a `.part.json` describing it, and the next call for the same URL and destination continues from where it stopped with a `Range` request. A partial is kept only when the server sent a strong `ETag` and the body size, and it is resumed with `If-Range` carrying that `ETag`, so a file that changed on the server is downloaded again from the start. A server that ignores ranges also just sends the whole file again.
Only one download to a destination at a time owns the resumable partial; it holds a lock on it. Any concurrent download to the same destination writes to its own private `.part` file, which is never resumed.
- `resume=False` starts from zero and keeps nothing on failure. On success it also removes a partial an earlier download left, unless another download is using it.
- `force=True` discards any partial before downloading.
## Converting on download
`store_as=` converts the file after download with mscompress. The source format comes from the URL's extension, and the destination's extension is adjusted to match the target:
```python
path = download_file(
"http://remote-host:1319/v1/files/experiment.msz",
Path("downloads/experiment.msz"),
store_as="mzml",
)
# path == Path("downloads/experiment.mzML")
```
| Source | `store_as="msz"` | `store_as="mzml"` | `store_as="mszx"` |
| --- | --- | --- | --- |
| `.msz` | kept as-is | decompressed | `NotImplementedError` |
| `.mzML` | compressed | kept as-is | `NotImplementedError` |
| `.mszx` | MSZ extracted | decompressed | kept as-is |
If the URL has no recognizable extension, the file is saved without conversion.
### Multi-member `.mszx` archives
An `.mszx` can bundle several MSZ files. When one with more than one member is stored as `msz` or `mzml`, every member is written into a directory named after the archive:
```text
downloads/batch.mszx → downloads/batch/run1.mzML
downloads/batch/run2.mzML
```
Members are extracted into a staging directory that replaces `batch/` only once all of them succeed, so a failure leaves no partial output. If two members would map to the same file name (compared case-insensitively), `ValueError` is raised before anything is written. The function returns the directory path.
## Skipping existing files
- `skip_existing=True` returns early when the final destination (or, for a multi-member `.mszx`, its directory) already exists.
- `force=True` always downloads, overriding `skip_existing`.
## Timeouts
Without `client=`, requests use a 10 s connect timeout and 300 s otherwise. `timeout=` takes an `httpx.Timeout` that replaces those (or a passed client's) for the download; `httpx.Timeout(None)` disables them.
## Many files
```python
from pathlib import Path
from mstransfer.client import DownloadRequest, download_batch
base = "http://remote-host:1319/v1/files"
requests = [
DownloadRequest(url=f"{base}/{name}", dest=Path("downloads") / name)
for name in ("a.msz", "b.msz")
]
results = download_batch(requests, store_as="mzml", parallel=4)
for r in results:
if r.error is not None:
print(f"{r.filename} failed: {r.error}")
elif r.response.skipped:
print(f"{r.filename} already exists at {r.response.path}")
else:
print(f"{r.filename} saved to {r.response.path}")
```
`download_batch` never raises for a single failed file. It returns one [`FileResult`]() per request, in input order and named after the request's `dest`. Each holds either a [`DownloadResult`]() (`request`, the final `path`, and `skipped`) in `response`, or the exception in `error`. A multi-member `.mszx` yields its archive directory as the path.
## Authentication
Pass `api_key=` to send `Authorization: Bearer `:
```python
download_file(url, dest, api_key="s3cret")
```
# Python Guides
The `mstransfer.client` package exposes the same transfers the CLI uses. Every function has a synchronous form and an `async_` form:
| Sync | Async | Purpose |
| --- | --- | --- |
| `send_file` | `async_send_file` | Upload one file |
| `send_batch` | `async_send_batch` | Upload many files in parallel |
| `download_file` | `async_download_file` | Download one file |
| `download_batch` | `async_download_batch` | Download many files in parallel |
The sync functions call `asyncio.run()`, so they cannot be used from inside a running event loop. Use the `async_` variants there instead.
- [Uploading files]()
- [Downloading files]()
- [Progress reporting]()
Full signatures are in the [API Reference]().
# Progress reporting
Progress callbacks receive byte deltas, throttled to roughly one call per 8 MiB plus a final flush, so they are cheap to drive a UI from.
## Uploads
`send_file` takes a plain callable:
```python
send_file(path, server, progress_callback=lambda delta: print(delta))
```
`send_batch` takes an object implementing [`BatchProgressCallback`]():
```python
from pathlib import Path
from mstransfer.server.models import UploadResponse
class Printer:
def file_started(
self, index: int, file_path: Path, total_bytes: int | None
) -> None:
print(f"[{index}] start {file_path.name} ({total_bytes or '?'} bytes)")
def file_progress(self, index: int, delta: int) -> None: ...
def file_done(self, index: int, result: UploadResponse) -> None:
print(f"[{index}] {result.state.value}")
def file_error(self, index: int, exc: Exception) -> None:
print(f"[{index}] failed: {exc}")
send_batch(paths, server, progress=Printer())
```
`total_bytes` is the file size for MSZ / MSZX and `None` for mzML, whose compressed size is not known until the upload ends.
## Downloads
`download_file` takes a [`DownloadProgressCallback`](), an object with two methods:
- `on_total(total_bytes)`: called when the server responds, with the file size, or `None` if the server didn't send `Content-Length` or the response is content-encoded.
- `on_progress(bytes_delta)`: called per chunk. A [resumed]() download first reports the bytes it already had as one delta, so the bar starts where it left off.
```python
class Printer:
def on_total(self, total_bytes: int | None) -> None:
print(f"downloading {total_bytes or '?'} bytes")
def on_progress(self, bytes_delta: int) -> None: ...
download_file(url, dest, progress_callback=Printer())
```
`download_batch` takes a [`BatchDownloadProgress`]() with `on_file_start`, `on_file_total`, `on_file_progress`, `on_file_complete`, and `on_file_error`, each keyed by the destination file name. `on_file_start` always receives `total_bytes=None`, because the size isn't known until the `GET` response arrives; `on_file_total` then reports it, with the same rules as `on_total`. A file skipped by `skip_existing` gets `on_file_start` and `on_file_complete` with no total in between. An exception raised by `on_file_complete` is logged and doesn't fail the download.
The CLI's Rich progress bars are implementations of these protocols; see `UploadProgressDisplay` and `DownloadProgressDisplay` in `mstransfer/cli.py`.
# Uploading files
## A single file
`send_file` accepts a `Path` or an already-opened mscompress object:
```python
from pathlib import Path
from mscompress import MSZFile, MZMLFile
from mscompress.mszx import MSZXFile
from mstransfer.client import send_file
server = "http://remote-host:1319"
send_file(Path("experiment.mzML"), server)
send_file(MZMLFile(b"/data/experiment.mzML"), server)
send_file(MSZFile(b"/data/experiment.msz"), server)
send_file(MSZXFile.open("/data/experiment.mszx"), server)
```
For a `Path`, the format is detected from the file contents. mzML is compressed on the fly with `compress_stream()`; MSZ and MSZX are streamed as-is. Anything else raises `ValueError`.
`send_file` returns an [`UploadResponse`](). If the server is still processing the file when the upload finishes (for example, decompressing to mzML), the client polls [`/v1/transfer/{id}/status`]() until it reaches `DONE` or `ERROR`, and returns that final state.
```python
from mstransfer.server.models import TransferState
result = send_file(Path("experiment.mzML"), server)
if result.state is TransferState.DONE:
print("stored at", result.stored_as)
```
HTTP errors raise `httpx.HTTPStatusError`, including the [409 Conflict]() the server returns when the file's output already exists there. The server's reason is in the response body as `{"detail": "..."}`.
Two timeouts apply:
- `timeout=` takes an `httpx.Timeout` for the upload request, replacing the client's. Without it, the client's timeouts are used (10 s connect, 3600 s otherwise, when the function creates its own client). `httpx.Timeout(None)` disables them.
- `poll_timeout=` is how many seconds polling may go without server-side progress (default 3600) before raising `TimeoutError`. `None` waits forever.
## Many files
`send_batch` uploads with bounded parallelism and never raises for a single failed file, including one that is missing or unreadable. Instead, each input gets a [`FileResult`]() in input order, holding either the final `UploadResponse` in `response` or the exception in `error`:
```python
from mstransfer.client import resolve_inputs, send_batch
paths = resolve_inputs(["/data/batch", "/data/extra.msz"], recursive=True)
results = send_batch(paths, server, parallel=4)
for r in results:
if r.error is not None:
print(f"{r.filename} failed: {r.error}")
```
`resolve_inputs` expands files and directories the same way [`mstransfer upload`]() does, and raises `FileNotFoundError` if nothing valid is found.
## Authentication
Pass `api_key=` to send `Authorization: Bearer ` on the upload and status requests (the batch functions take it too):
```python
send_file(Path("experiment.mzML"), server, api_key="s3cret")
```
## Async and connection reuse
```python
import httpx
from mstransfer.client import async_send_batch
async def main() -> None:
async with httpx.AsyncClient(timeout=httpx.Timeout(3600, connect=10)) as client:
await async_send_batch(paths, server, client=client)
```
Without `client=`, each call opens and closes its own `httpx.AsyncClient`.
# Server
# Authentication
Auth is off by default. When enabled, it protects every endpoint except `GET /v1/health`. Uploads and downloads can also be protected separately; see [Protecting uploads or downloads only](<#protecting-uploads-or-downloads-only>).
## API key
From the CLI:
```bash
mstransfer serve --api-key s3cret
mstransfer upload data/ remote-host:1319 --api-key s3cret
mstransfer download http://remote-host:1319/v1/files/run1.msz --api-key s3cret
```
Each command falls back to the `MS_API_KEY` environment variable when `--api-key` isn't given; see [CLI]().
From Python:
```python
from mstransfer import APIKeyAuthProvider, create_app
app = create_app(auth=APIKeyAuthProvider("s3cret"))
```
`APIKeyAuthProvider` accepts the key as `Authorization: Bearer ` or as an `?api_key=` query parameter, compares it in constant time, and returns 401 otherwise. Keys may contain non-ASCII characters; they are compared as UTF-8 bytes. The Python client's upload and download functions take an `api_key=` argument that sends the header.
## Custom providers
Any object with an async `authenticate(request)` method returning an `AuthContext` satisfies the `AuthProvider` protocol. Raise `HTTPException` to reject the request:
```python
from fastapi import HTTPException, Request
from mstransfer import AuthContext, create_app
class HeaderTokenProvider:
def __init__(self, tokens: dict[str, str]) -> None:
self._tokens = tokens # token -> user
async def authenticate(self, request: Request) -> AuthContext:
user = self._tokens.get(request.headers.get("X-Token", ""))
if user is None:
raise HTTPException(status_code=401, detail="Bad token")
return AuthContext(identity=user, scopes={"upload"})
app = create_app(auth=HeaderTokenProvider({"abc": "alice"}))
```
`create_app(auth=...)` also accepts a plain FastAPI dependency callable, so you can reuse your app's existing auth dependency. For `make_router`, wrap a provider with `make_auth_dependency(provider)`.
## Protecting uploads or downloads only
`auth` protects every route except `/v1/health`. To protect the two directions separately, pass `upload_auth` and/or `download_auth` instead:
| Group | Routes |
| --- | --- |
| upload | `POST /v1/upload`, `GET /v1/transfer/{id}/status` |
| download | `GET /v1/files`, `GET /v1/files/{filename}` |
A group with no auth is open. For example, a server that publishes files to anyone but only accepts uploads from trusted clients:
```python
from mstransfer import APIKeyAuthProvider, create_app
app = create_app(upload_auth=APIKeyAuthProvider("s3cret"))
```
Each accepts the same values as `auth`, so the two directions can also use different keys or providers. `auth` can't be combined with either one; doing so raises `TypeError`.
`make_router` takes the same split as `upload_auth_dep` and `download_auth_dep`, alongside `auth_dep`. The OpenAPI schema documents a 401 response only on routes that have auth.
# Deployment
## Docker
The repository's `Dockerfile` installs mstransfer with uv and runs `mstransfer serve`. Any extra arguments are passed to `serve`:
```bash
docker build -t mstransfer .
docker run -p 1319:1319 -v /data/received:/data mstransfer \
--output-dir /data --store-as msz --api-key s3cret
```
Each release also publishes `latest` and `` images for `linux/amd64` and `linux/arm64` to Docker Hub.
## Behind a reverse proxy
- Uploads are single long-lived streaming requests, so raise the proxy's body size limit and read timeouts accordingly, and disable request buffering so bytes reach the server as they arrive.
- Clients wait for the upload response until storage finishes, including mzML decompression. If a proxy cuts that request off, the transfer can still be checked via `/v1/transfer/{id}/status`.
- Transfer state is held in memory per process. Run a single worker, or route a client's status polls to the process that received its upload.
## TLS
The server speaks plain HTTP. For TLS, terminate it at a reverse proxy and point clients at `https://host:port`; the upload target accepts full URLs.
# Embedding in FastAPI
## Standalone app
`create_app` returns a configured FastAPI app with the router mounted at `/v1`:
```python
import uvicorn
from mstransfer import create_app
app = create_app(output_dir="/data/ms", store_as="mzml")
uvicorn.run(app, host="0.0.0.0", port=1319)
```
| Argument | Default | Description |
| --- | --- | --- |
| `output_dir` | `./received` | Where uploads are stored (created if missing) |
| `store_as` | `"msz"` | `"msz"` or `"mzml"` |
| `auth` | `None` | An [`AuthProvider`](), a raw FastAPI dependency, or `None` for no auth |
| `file_provider` | `None` | A [`FileProvider`](); defaults to scanning `output_dir` |
| `upload_auth` | `None` | Like `auth`, but only for upload and transfer status (keyword-only) |
| `download_auth` | `None` | Like `auth`, but only for file list and download (keyword-only) |
## Mounting as a sub-application
```python
from fastapi import FastAPI
from mstransfer import create_app
main_app = FastAPI()
main_app.mount("/transfer", create_app(output_dir="/data/ms"))
# Endpoints are now at /transfer/v1/...
```
## Including the router
To share your app's middleware, dependencies, and OpenAPI schema, include the router directly. Pass an `AppState` so the router does not depend on your app's `app.state`:
```python
from pathlib import Path
from fastapi import FastAPI
from mstransfer import AppState, make_router
from mstransfer.server.fileprovider import DirectoryFileProvider
out = Path("/data/ms")
out.mkdir(parents=True, exist_ok=True)
state = AppState(output_dir=out, store_as="msz", files=DirectoryFileProvider(out))
app = FastAPI()
app.include_router(make_router(state=state), prefix="/transfer/v1")
```
`make_router(auth_dep=...)` takes a FastAPI dependency to protect every route except `/health`. To protect only one direction, pass `upload_auth_dep` (upload and transfer status) and/or `download_auth_dep` (file list and download) instead; a group without a dependency is left open:
```python
from mstransfer import APIKeyAuthProvider, make_auth_dependency
auth = make_auth_dependency(APIKeyAuthProvider("s3cret"))
app.include_router(
make_router(state=state, upload_auth_dep=auth), prefix="/transfer/v1"
)
```
`auth_dep` can't be combined with the per-direction arguments. See [Authentication]().
Uploads are written to `state.output_dir` regardless of the file provider, so create that directory before serving.
# File providers
A file provider decides what `GET /v1/files` lists and what `GET /v1/files/{filename}` serves. It does not affect where uploads are written; that is always the server's output directory.
## Default: `DirectoryFileProvider`
Lists the `.msz` and `.mzML` files directly inside a directory (not subdirectories) and resolves names only within it. Names containing `/`, `\`, or `..` are rejected.
## Custom providers
Implement the `FileProvider` protocol, two async methods:
```python
from collections.abc import Sequence
from pathlib import Path
from mstransfer import create_app
from mstransfer.server.models import FileInfo
class ChecksumFileInfo(FileInfo):
sha256: str
class CatalogProvider:
def __init__(self, catalog: dict[str, tuple[Path, str]]) -> None:
self._catalog = catalog # name -> (path, sha256)
async def list_files(self) -> Sequence[FileInfo]:
return [
ChecksumFileInfo(
name=name,
size_bytes=path.stat().st_size,
format="msz",
sha256=digest,
)
for name, (path, digest) in self._catalog.items()
]
async def get_file(self, filename: str) -> Path | None:
entry = self._catalog.get(filename)
return entry[0] if entry else None
app = create_app(file_provider=CatalogProvider({...}))
```
Return `None` from `get_file` for unknown names to produce a 404. Fields added by a `FileInfo` subclass (like `sha256` above) appear in the `/v1/files` response.
## Serving a file under a different name
`get_file` may return a `ServedFile` instead of a `Path` when the bytes are not stored under the name the client asked for: a content-addressed blob, a cache entry keyed by ID, or a temp file fetched from object storage.
```python
from pathlib import Path
from mstransfer.server.models import ServedFile
class BlobProvider:
def __init__(self, index: dict[str, Path]) -> None:
self._index = index # "run1.mzML" -> blobs/sha256/ab/cdef...
async def list_files(self) -> Sequence[FileInfo]: ...
async def get_file(self, filename: str) -> Path | ServedFile | None:
blob = self._index.get(filename)
return ServedFile(path=blob, name=filename) if blob else None
```
The response streams `path` and uses `name` for the `Content-Disposition` filename and the content type (`application/xml` for `.mzML`, `application/octet-stream` otherwise). Range requests, `If-Range`, `ETag` and `Last-Modified` still come from the stored file, so interrupted downloads resume as usual. A plain `Path` is served under its own name.
# HTTP API
All endpoints live under `/v1`. When the server has an [auth provider](), every endpoint except `/v1/health` requires credentials. A server can instead require them only for uploads (`/v1/upload`, `/v1/transfer/{id}/status`) or only for downloads (`/v1/files`, `/v1/files/{filename}`); see [Protecting uploads or downloads only]().
FastAPI also serves interactive docs at `/docs` and the OpenAPI schema at `/openapi.json`.
Errors the routes raise have a JSON body with a human-readable reason:
```json
{"detail": "run1.msz already exists on the server"}
```
FastAPI's own 422 validation errors use a list `detail` instead.
## `GET /v1/health`
Server status. Never requires auth.
```json
{"status": "ok", "version": "0.2.3", "store_as": "msz"}
```
## `POST /v1/upload`
Upload one file as a streamed request body of MSZ bytes.
| Header | Required | Description |
| --- | --- | --- |
| `X-Transfer-ID` | yes | Client-chosen unique ID (the client uses a UUID4) |
| `X-Original-Filename` | yes | Original file name; its stem names the stored file |
| `X-Source-Format` | no | `mzML`, `msz`, or `mszx`; inferred from `X-Original-Filename` when absent |
| `Content-Type` | no | `application/octet-stream` |
The body is written to `/.msz`. With `store-as mzml`, it is then decompressed to `.mzML` and the `.msz` is removed. The response arrives once storage finishes.
The server never overwrites a stored file. Output names come from the upload's stem, so `run1.mzML` and `run1.msz` both map to `run1.msz`. If that output already exists, or another in-flight upload is writing it, the server responds **409 Conflict** before reading the body.
```json
{
"transfer_id": "6f1c…",
"filename": "experiment.mzML",
"stored_as": "received/experiment.mzML",
"state": "done",
"bytes_received": 104857600
}
```
| Status | Meaning |
| --- | --- |
| 200 | Stored. `state` is `done`, or `error` if decompression failed |
| 400 | Missing `X-Transfer-ID` or `X-Original-Filename`, or unsupported `X-Source-Format` |
| 401 | Auth failed |
| 409 | The output file already exists, or another transfer is writing it |
| 500 | Reading the body or writing the file failed |
## `GET /v1/transfer/{transfer_id}/status`
The registry record for a transfer, so a client can check on an upload from another connection.
```json
{
"transfer_id": "6f1c…",
"filename": "experiment.mzML",
"state": "decompressing",
"bytes_received": 104857600,
"stored_as": "",
"error": null,
"created_at": "2026-10-29T12:00:00"
}
```
`state` is one of `receiving`, `received`, `decompressing`, `done`, `error`. Returns 404 if the ID is unknown or has been evicted.
## `GET /v1/files`
Files available for download, as reported by the server's [file provider](). The default lists every `.msz` and `.mzML` file directly inside the output directory, sorted by name.
```json
{
"files": [
{"name": "experiment.msz", "size_bytes": 20971520, "format": "msz"}
]
}
```
Custom providers may add fields to each entry; they are passed through.
## `GET /v1/files/{filename}`
Stream one file. `Content-Type` is `application/xml` for mzML and `application/octet-stream` otherwise, with `Content-Length` and a `Content-Disposition: attachment` header. Returns 404 if the provider does not resolve the name. The default provider rejects names containing `/`, `\`, or `..`.
The response carries `ETag` and `Last-Modified` validators and supports byte `Range` requests (`206 Partial Content`, or `416` for an unsatisfiable range), including `If-Range`, which is how the client [resumes]() interrupted downloads.
# Server
The mstransfer server is a FastAPI application. Run it with [`mstransfer serve`](), or build it in Python and serve it however you like.
- [HTTP API](): endpoints, headers, and transfer states
- [Embedding in FastAPI](): `create_app` and `make_router`
- [Authentication](): API keys and custom auth providers
- [File providers](): control what `/v1/files` lists and serves
- [Deployment](): Docker and running behind a reverse proxy
## Transfer lifecycle
Each upload is tracked in an in-memory registry under the `X-Transfer-ID` the client sends:
```
stateDiagram-v2
[*] --> RECEIVING
RECEIVING --> RECEIVED: body fully written
RECEIVING --> ERROR: read/write failure
RECEIVED --> DONE: store-as msz
RECEIVED --> DECOMPRESSING: store-as mzml
DECOMPRESSING --> DONE
DECOMPRESSING --> ERROR
```
The registry keeps up to 1024 records. Past that, the least recently used finished (`DONE` or `ERROR`) record is evicted; in-progress transfers are never evicted. Records do not survive a restart.
# API reference
# Client
## Uploading
## sender
### BatchProgressCallback
Bases: `Protocol`
Callback protocol for observing batch upload progress.
### async\_send\_file
```python
async_send_file(
source: Path | MZMLFile | MSZFile | MSZXFile,
base_url: str,
progress_callback: Callable[[int], None] | None = None,
timeout: Timeout | None = None,
poll_timeout: float | None = 3600.0,
chunk_size: int = 1048576,
api_key: str | None = None,
client: AsyncClient | None = None,
) -> UploadResponse
```
Send a single file to the mstransfer listener (async).
Accepts a file path, or an already-opened MZMLFile / MSZFile / MSZXFile from mscompress. Returns the final transfer status from the server.
*timeout* replaces *client*'s timeouts for the upload request; pass `httpx.Timeout(None)` for no limit. If *None*, *client*'s timeouts are used (10 s connect, 3600 s otherwise, without *client*).
*poll\_timeout* is how long to wait without server-side progress while polling for completion, in seconds, or *None* to wait forever. Status polls use *client*'s timeout, or 10 s without *client*.
### async\_send\_batch
```python
async_send_batch(
sources: Sequence[Path | MZMLFile | MSZFile | MSZXFile],
base_url: str,
parallel: int = 4,
chunk_size: int = 1048576,
progress: BatchProgressCallback | None = None,
api_key: str | None = None,
client: AsyncClient | None = None,
timeout: Timeout | None = None,
poll_timeout: float | None = 3600.0,
) -> list[FileResult[UploadResponse]]
```
Send multiple files with configurable parallelism (async).
Returns one `FileResult` per source, in input order, carrying the final transfer status or the error.
*timeout* and *poll\_timeout* are passed to `async_send_file` for each file.
### send\_file
```python
send_file(
source: Path | MZMLFile | MSZFile | MSZXFile,
base_url: str,
progress_callback: Callable[[int], None] | None = None,
timeout: Timeout | None = None,
poll_timeout: float | None = 3600.0,
chunk_size: int = 1048576,
api_key: str | None = None,
client: AsyncClient | None = None,
) -> UploadResponse
```
Send a single file to the mstransfer listener.
Accepts a file path, or an already-opened MZMLFile / MSZFile / MSZXFile from mscompress. Returns the final transfer status from the server.
This is a synchronous wrapper around `async_send_file`.
### send\_batch
```python
send_batch(
sources: Sequence[Path | MZMLFile | MSZFile | MSZXFile],
base_url: str,
parallel: int = 4,
chunk_size: int = 1048576,
progress: BatchProgressCallback | None = None,
api_key: str | None = None,
client: AsyncClient | None = None,
timeout: Timeout | None = None,
poll_timeout: float | None = 3600.0,
) -> list[FileResult[UploadResponse]]
```
Send multiple files with configurable parallelism.
*timeout* and *poll\_timeout* are passed to `async_send_file` for each file.
This is a synchronous wrapper around `async_send_batch`.
## Downloading
## downloader
### DownloadProgressCallback
Bases: `Protocol`
Callback protocol for observing single-file download progress.
### BatchDownloadProgress
Bases: `Protocol`
Callback protocol for observing batch download progress.
### DownloadRequest
```python
DownloadRequest(url: str, dest: Path)
```
A single download request: URL to fetch and local destination path.
### DownloadResult
```python
DownloadResult(
request: DownloadRequest,
path: Path,
skipped: bool = False,
)
```
A completed download: the request and where its output was written.
*skipped* is *True* when the output already existed and nothing was downloaded (see *skip\_existing*).
### async\_download\_file
```python
async_download_file(
url: str,
dest: Path,
*,
store_as: DownloadFormat | None = None,
chunk_size: int = 1048576,
timeout: Timeout | None = None,
progress_callback: DownloadProgressCallback
| None = None,
skip_existing: bool = False,
force: bool = False,
resume: bool = True,
api_key: str | None = None,
client: AsyncClient | None = None,
) -> Path
```
Download a single file from *url* to *dest* (async).
The file is streamed to a temporary `.part` file first, then atomically renamed (or converted) to the final destination on success.
With *resume*, an interrupted download keeps its partial `.part` file (and a `.part.json` describing it) next to *dest*, and a later call continues from the bytes already received. A partial is only kept when the server sent a strong `ETag` and the body size, and it is only resumed with an `If-Range` request carrying that `ETag`. If the server does not support ranges, or the file changed, the download restarts from zero. The finished file must have exactly the expected size.
Parameters:
| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `url` | `str` | The URL to download from. | *required* |
| `dest` | `Path` | The local path where the file should be saved. If *store\_as* requires a format conversion, the extension will be adjusted automatically. | *required* |
| `store_as` | `DownloadFormat \| None` | Desired output format — `"msz"`, `"mzml"`, `"mszx"`, or *None* to keep the file as-is. When set, the downloaded file is converted after download using **mscompress**. Conversion *to* `"mszx"` is only supported when the source is already `.mszx` (no-op). When a multi-member (batch) `.mszx` is stored as `"msz"` or `"mzml"`, its members are written to a directory named after the archive, `dest.parent//.`. The directory appears only once every member is written, and replaces any existing directory of that name. | `None` |
| `chunk_size` | `int` | Number of bytes per read chunk (default 1 MiB). | `1048576` |
| `timeout` | `Timeout \| None` | Timeouts for the request, replacing *client*'s; pass `httpx.Timeout(None)` for no limit. If *None*, *client*'s timeouts are used (10 s connect, 300 s otherwise, without *client*). | `None` |
| `progress_callback` | `DownloadProgressCallback \| None` | Optional callback. `on_total` is invoked once the server responds, with the file size (or *None* if unknown); `on_progress` is invoked with byte deltas per chunk. A resumed download first reports the bytes it already had as one delta. | `None` |
| `skip_existing` | `bool` | If *True* and the final destination already exists, skip the download. For an `.mszx` stored as `"msz"` or `"mzml"`, an existing archive directory (see *store\_as*) also counts. | `False` |
| `force` | `bool` | If *True*, re-download even if the destination already exists (overrides *skip\_existing*), discarding any partial download. | `False` |
| `resume` | `bool` | If *True* (the default), resume a partial download of *url* to *dest* and keep this one's partial if it is interrupted. Only one download to *dest* at a time can do so; a concurrent one uses a private `.part` file that is never resumed. If *False*, start from zero and keep nothing on failure; on success, remove the partial an earlier download left, unless one is using it. | `True` |
| `api_key` | `str \| None` | Optional API key, sent as `Authorization: Bearer `. | `None` |
| `client` | `AsyncClient \| None` | Optional `httpx.AsyncClient` to reuse; a temporary one is created and closed otherwise. | `None` |
Returns:
| Type | Description |
| --- | --- |
| `Path` | The final destination path (may differ from *dest* if the extension |
| `Path` | was adjusted for format conversion), or the archive directory for a |
| `Path` | multi-member `.mszx`. |
Raises:
| Type | Description |
| --- | --- |
| `NotImplementedError` | The source cannot be converted to *store\_as*. |
| `ValueError` | Two members of a multi-member `.mszx` map to the same output name (raised before anything is written), the downloaded size does not match the size the server announced, or the server sent part of the file when it was not asked to. |
### async\_download\_batch
```python
async_download_batch(
files: list[DownloadRequest],
*,
store_as: DownloadFormat | None = None,
parallel: int = 4,
chunk_size: int = 1048576,
timeout: Timeout | None = None,
progress: BatchDownloadProgress | None = None,
skip_existing: bool = False,
force: bool = False,
resume: bool = True,
api_key: str | None = None,
client: AsyncClient | None = None,
) -> list[FileResult[DownloadResult]]
```
Download multiple files in parallel (async).
Parameters:
| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `files` | `list[DownloadRequest]` | List of `DownloadRequest` objects (url + dest pairs). | *required* |
| `store_as` | `DownloadFormat \| None` | Desired output format — `"msz"`, `"mzml"`, `"mszx"`, or *None* to keep files as-is. Forwarded to each `async_download_file` call. | `None` |
| `parallel` | `int` | Maximum number of concurrent downloads (capped to file count). | `4` |
| `chunk_size` | `int` | Number of bytes per read chunk. | `1048576` |
| `timeout` | `Timeout \| None` | Timeouts for each request, replacing *client*'s; pass `httpx.Timeout(None)` for no limit. If *None*, *client*'s timeouts are used (10 s connect, 300 s otherwise, without *client*). | `None` |
| `progress` | `BatchDownloadProgress \| None` | Optional batch progress callback. | `None` |
| `skip_existing` | `bool` | If *True*, skip files whose destination already exists. | `False` |
| `force` | `bool` | If *True*, re-download even if destination exists. | `False` |
| `resume` | `bool` | If *True* (the default), resume partial downloads and keep resumable partials of failed ones (see `async_download_file`). | `True` |
| `api_key` | `str \| None` | Optional API key, sent as `Authorization: Bearer `. | `None` |
| `client` | `AsyncClient \| None` | Optional `httpx.AsyncClient` shared by every download; a temporary one is created per request otherwise. | `None` |
Returns:
| Type | Description |
| --- | --- |
| `list[FileResult[DownloadResult]]` | One result per request, in input order, named after the request's |
| `list[FileResult[DownloadResult]]` | *dest*, carrying either a `DownloadResult` or the error. A |
| `list[FileResult[DownloadResult]]` | multi-member `.mszx` yields its archive directory as the path. A |
| `list[FileResult[DownloadResult]]` | file skipped by *skip\_existing* has `skipped` set and is still |
| `list[FileResult[DownloadResult]]` | reported to *progress* as complete. |
### download\_file
```python
download_file(
url: str,
dest: Path,
*,
store_as: DownloadFormat | None = None,
chunk_size: int = 1048576,
timeout: Timeout | None = None,
progress_callback: DownloadProgressCallback
| None = None,
skip_existing: bool = False,
force: bool = False,
resume: bool = True,
api_key: str | None = None,
client: AsyncClient | None = None,
) -> Path
```
Download a single file from *url* to *dest*.
This is a synchronous wrapper around `async_download_file`.
### download\_batch
```python
download_batch(
files: list[DownloadRequest],
*,
store_as: DownloadFormat | None = None,
parallel: int = 4,
chunk_size: int = 1048576,
timeout: Timeout | None = None,
progress: BatchDownloadProgress | None = None,
skip_existing: bool = False,
force: bool = False,
resume: bool = True,
api_key: str | None = None,
client: AsyncClient | None = None,
) -> list[FileResult[DownloadResult]]
```
Download multiple files in parallel.
This is a synchronous wrapper around `async_download_batch`.
## Results
## results
### FileResult
```python
FileResult(
filename: str,
response: T | None = None,
error: Exception | None = None,
)
```
Bases: `Generic[T]`
Result of transferring a single file in a batch.
Uploads return `FileResult[UploadResponse]` and downloads return `FileResult[DownloadResult]`, one per input, in input order.
Exactly one of *response* and *error* is set: *response* on success, *error* the exception that failed the transfer. An exception raised by the batch's completion progress callback is logged and does not count as a failure.
## Utilities
## resolve\_inputs
```python
resolve_inputs(
paths: list[str], recursive: bool = False
) -> list[Path]
```
Resolve files and directories into a sorted list of valid MS files.
# API Reference
Generated from the source docstrings.
- [Client](): `mstransfer.client` upload and download functions
- [Server](): `create_app`, `make_router`, auth, file providers, state
- [Models](): Pydantic request/response models and `TransferState`
- [Storage](): `MSFormat` and `StorePlan`, the `store_as` conversion logic
The top-level `mstransfer` package re-exports the server API: `create_app`, `make_router`, `AppState`, `AuthProvider`, `AuthContext`, `NoAuthProvider`, `APIKeyAuthProvider`, and `make_auth_dependency`.
# Models
## models
### TransferState
Bases: `StrEnum`
Enumeration of possible states for a file transfer.
### TransferRecord
Bases: `BaseModel`
Data model for a file transfer record in the registry.
### UploadResponse
Bases: `BaseModel`
Response model for a successful upload.
### ErrorResponse
Bases: `BaseModel`
Body of the errors the routes raise via `HTTPException`.
FastAPI's own 422 validation errors use a list `detail` instead.
### FileInfo
Bases: `BaseModel`
Metadata for a single stored file.
Subclass this to add provider-specific fields (e.g. checksum, URL, upload timestamp). Extra fields are preserved in the API response thanks to `SerializeAsAny` on `FileListResponse`.
### ServedFile
```python
ServedFile(path: Path, name: str)
```
A file to serve under a name other than its on-disk name.
Return this from `FileProvider.get_file` when the bytes are stored at a path whose name is not the one the client asked for (a content-addressed blob, a cache entry keyed by ID, a temp file).
Attributes:
| Name | Type | Description |
| --- | --- | --- |
| `path` | `Path` | Where the bytes are stored. Range requests and the `ETag` and `Last-Modified` validators come from this file. |
| `name` | `str` | The name to serve the file as. It is sent in `Content-Disposition` and its suffix picks the media type. |
### FileListResponse
Bases: `BaseModel`
Response model for the file listing endpoint.
### HealthResponse
Bases: `BaseModel`
Response model for health check endpoint.
# Server
## App factory
## create\_app
```python
create_app(
output_dir: str = "./received",
store_as: StoreFormat = "msz",
auth: AuthProvider | Callable[..., Any] | None = None,
file_provider: FileProvider | None = None,
*,
upload_auth: AuthProvider
| Callable[..., Any]
| None = None,
download_auth: AuthProvider
| Callable[..., Any]
| None = None,
) -> FastAPI
```
Create a configured mstransfer FastAPI application.
Parameters:
| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `output_dir` | `str` | Directory where received files are stored. | `'./received'` |
| `store_as` | `StoreFormat` | Output format — "msz" or "mzml". | `'msz'` |
| `auth` | `AuthProvider \| Callable[..., Any] \| None` | Authentication provider, raw FastAPI dependency, or *None* (no auth). Protects both uploads and downloads. Can't be combined with *upload\_auth* or *download\_auth*. | `None` |
| `file_provider` | `FileProvider \| None` | File discovery provider, or *None* to default to scanning *output\_dir* on disk. | `None` |
| `upload_auth` | `AuthProvider \| Callable[..., Any] \| None` | Like *auth*, but only for `POST /v1/upload` and `GET /v1/transfer/{id}/status`. | `None` |
| `download_auth` | `AuthProvider \| Callable[..., Any] \| None` | Like *auth*, but only for `GET /v1/files` and `GET /v1/files/{filename}`. | `None` |
Raises:
| Type | Description |
| --- | --- |
| `TypeError` | If *auth* is combined with *upload\_auth* or *download\_auth*, or any of them has an unsupported type. |
## Router
## make\_router
```python
make_router(
auth_dep: Callable[..., Any] | None = None,
state: AppState | None = None,
*,
upload_auth_dep: Callable[..., Any] | None = None,
download_auth_dep: Callable[..., Any] | None = None,
) -> APIRouter
```
Create the API router, optionally protecting routes with auth dependencies.
Routes are split into two groups that can be protected separately:
- upload: `POST /upload` and `GET /transfer/{transfer_id}/status`
- download: `GET /files` and `GET /files/{filename}`
`GET /health` is never protected.
Parameters:
| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `auth_dep` | `Callable[..., Any] \| None` | Optional FastAPI dependency applied to both groups. Can't be combined with *upload\_auth\_dep* or *download\_auth\_dep*. | `None` |
| `state` | `AppState \| None` | Optional `AppState` instance. When provided the router uses it directly (via a closure) instead of reading `request.app.state`. This allows the router to be included in a parent app with `app.include_router(...)` without requiring the parent to set up `app.state`. | `None` |
| `upload_auth_dep` | `Callable[..., Any] \| None` | Optional dependency for the upload group only. | `None` |
| `download_auth_dep` | `Callable[..., Any] \| None` | Optional dependency for the download group only. | `None` |
Raises:
| Type | Description |
| --- | --- |
| `TypeError` | If *auth\_dep* is combined with *upload\_auth\_dep* or *download\_auth\_dep*. |
## Authentication
## auth
Extensible authentication for mstransfer.
### AuthContext
Bases: `BaseModel`
Identity returned by an auth provider.
### AuthProvider
Bases: `Protocol`
Contract that auth providers must satisfy.
### NoAuthProvider
Default no-op provider — allows all requests.
### APIKeyAuthProvider
```python
APIKeyAuthProvider(api_key: str)
```
Validates `Authorization: Bearer ` or `?api_key=` query param.
### make\_auth\_dependency
```python
make_auth_dependency(
provider: AuthProvider,
) -> Callable[[Request], Awaitable[AuthContext]]
```
Convert an AuthProvider into a FastAPI dependency callable.
## File providers
## fileprovider
Extensible file discovery for mstransfer.
### FileProvider
Bases: `Protocol`
Contract that file providers must satisfy.
Implementations may return `FileInfo` subclasses from `list_files`; the return type is `Sequence` so that subclass lists are accepted without type errors.
`get_file` returns the file to serve for *filename*, or `None` for a 404. A `Path` is served under its own name. When the file is stored under a different name (e.g. a content-addressed blob with no extension), return a `ServedFile` instead: its `path` is streamed and its `name` is used for `Content-Disposition` and the media type.
### DirectoryFileProvider
```python
DirectoryFileProvider(directory: Path)
```
Default provider — scans a directory for .msz/.mszx/.mzML files.
#### list\_files
```python
list_files() -> Sequence[FileInfo]
```
Return metadata for every .msz / .mszx / .mzML file in the directory.
#### get\_file
```python
get_file(filename: str) -> Path | None
```
Resolve *filename* to a path inside the directory.
Returns *None* if the file does not exist or the name attempts directory traversal.
## State
## state
### AppState
```python
AppState(
output_dir: Path,
store_as: StoreFormat,
files: FileProvider,
)
```
Bases: `State`
Application state object to hold configuration and transfer registry.
### OutputClaims
```python
OutputClaims()
```
Output paths that in-flight uploads are writing.
Lets an upload refuse a destination another transfer already holds, so two uploads never write to the same file. Paths compare case-insensitively, as macOS and Windows filesystems do.
#### claim
```python
claim(path: Path) -> bool
```
Reserve *path*, returning *False* if it is already reserved.
#### release
```python
release(path: Path) -> None
```
Give up a reservation made with `claim`.
### TransferRegistry
```python
TransferRegistry(maxsize: int = 1024)
```
In-memory LRU registry of transfer records.
When the number of records exceeds *maxsize*, the least-recently-used **terminal** (DONE / ERROR) record is evicted. In-progress transfers are never evicted; the registry may temporarily exceed *maxsize* if all records are active.
# Storage
Shared by the client and server: `MSFormat` identifies a file's format, and `StorePlan` decides where a transferred file lands on disk and whether it is converted (`store_as`) on the way.
## store
Decide where and in what format a transferred file is stored on disk.
### MSFormat
Bases: `StrEnum`
An on-disk MS data format.
Members compare equal to their `DownloadFormat` string values.
#### ext
```python
ext: str
```
The canonical file extension, used to name converted outputs.
#### from\_path
```python
from_path(name: str) -> MSFormat | None
```
Infer the format from a filename extension, or *None*.
#### from\_url
```python
from_url(url: str) -> MSFormat | None
```
Infer the format from the URL filename extension, or *None*.
#### from\_header
```python
from_header(value: str) -> MSFormat
```
Parse an `X-Source-Format` header value, case-insensitively.
Raises `ValueError` for an unrecognised value.
### Conversion
```python
Conversion(source: MSFormat, target: MSFormat)
```
Turning a *source*-format file into a *target*-format file.
#### supported
```python
supported: bool
```
Whether a converter exists for this pair of formats.
#### run
```python
run(src: Path, dst: Path) -> None
```
Convert *src* to *dst* in a worker thread.
### MszxExpansion
```python
MszxExpansion(
src: Path, entries: tuple[str, ...], target: MSFormat
)
```
Writes every member of a multi-member .mszx into one directory.
Each spectra *entry* of *src* becomes `.` stored as *target* (`MSFormat.MSZ` or `MSFormat.MZML`).
#### targets
```python
targets: list[tuple[str, str]]
```
Map each spectra entry to an output file name.
Raises `ValueError` for unsafe names, or if two entries map to the same output name.
#### write
```python
write(archive_dir: Path) -> Path
```
Store every member in *archive\_dir*.
Members are extracted into a uniquely named staging directory that is renamed to *archive\_dir* only once all of them succeed, so a failure leaves no partial output behind and concurrent downloads never share staging files. Names are validated before anything is written.
### StorePlan
```python
StorePlan(
dest: Path,
source: MSFormat | None,
target: MSFormat | None,
)
```
How a file downloaded to *dest* ends up on disk.
*source* is the format of the downloaded bytes (or *None* if unknown) and *target* the requested `store_as` format (or *None* to keep the file as-is). Build one with `for_download` to also validate the combination before any I/O.
#### conversion
```python
conversion: Conversion | None
```
The conversion needed, or *None* if the file is stored as-is.
#### final\_dest
```python
final_dest: Path
```
The output path, with its extension adjusted for any conversion.
#### part\_path
```python
part_path: Path
```
Where the download is streamed before it is finalized.
#### may\_expand
```python
may_expand: bool
```
Whether a multi-member .mszx would be expanded into a directory.
#### archive\_dir
```python
archive_dir: Path
```
Where the members of a multi-member .mszx are written.
#### for\_download
```python
for_download(
url: str, dest: Path, store_as: DownloadFormat | None
) -> StorePlan
```
Plan storage for *url*, failing fast on unsupported conversions.
#### for\_upload
```python
for_upload(
dest_dir: Path,
filename: str,
source: MSFormat | None,
store_as: MSFormat,
) -> StorePlan
```
Plan storage for an upload of *filename* into *dest\_dir*.
*source* is the format the client declared, or *None* to infer it from *filename*. mzML is compressed on the wire, so anything but an .mszx archive arrives as MSZ. Archives are always kept as-is, whatever *store\_as* says.
#### unique\_part\_path
```python
unique_part_path() -> Path
```
A `part_path` variant that concurrent writers never share.
Two uploads can target the same *dest* (e.g. `run.msz` and `run.mzML` both arrive as `run.msz`), so each needs its own file.
#### existing
```python
existing() -> Path | None
```
Return the output already on disk, if any.
#### finalize
```python
finalize(part: Path) -> Path
```
Move or convert the downloaded *part* file into its final form.
Returns the final destination, or the archive directory for a multi-member `.mszx`.
# Contributing
# Contributing
## Setup
```bash
git clone https://github.com/chrisagrams/mstransfer
cd mstransfer
uv sync --dev
uv run pre-commit install
```
The pre-commit hooks run ruff (lint and format check), pyright, mypy, and pytest.
## Checks
```bash
uv run pytest # tests
uv run ruff check . # lint
uv run ruff format . # format
uv run mypy src/ # type check (strict)
```
CI runs all of these on Python 3.10 through 3.14 for every PR into `dev`, `stage`, and `main`.
## Docstrings
Docstrings use [Google style]() (`Args:`, `Returns:`, `Raises:`) with Markdown inline code (single backticks), since the [API Reference]() renders them with mkdocstrings. Ruff's pydocstyle rules (`D`, Google convention) check the format; missing docstrings are not flagged.
## Branches and releases
Work branches off `dev` and PRs target `dev`. PR titles follow [Conventional Commits]() (`feat:`, `fix:`, `docs:`, …), which release-please uses to version releases and write the changelog.
## Documentation
The docs are built with [Zensical]() from `mkdocs.yml` and `docs/`. API reference pages are generated from docstrings with mkdocstrings.
```bash
uv run --only-group docs zensical serve
```
To add a page, create it under `docs/` and add it to the `nav` in `mkdocs.yml`. Pages under an existing section directory are picked up by `llms.txt` automatically.
Every PR into `dev` builds the site with `zensical build --strict`; pushes to `main` deploy it to GitHub Pages.