mstransfer 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mstransfer/__init__.py +7 -0
- mstransfer/__main__.py +3 -0
- mstransfer/cli.py +223 -0
- mstransfer/client/__init__.py +3 -0
- mstransfer/client/sender.py +292 -0
- mstransfer/log.py +49 -0
- mstransfer/server/__init__.py +0 -0
- mstransfer/server/app.py +26 -0
- mstransfer/server/models.py +42 -0
- mstransfer/server/routes.py +196 -0
- mstransfer/server/state.py +67 -0
- mstransfer-0.1.0.dist-info/METADATA +173 -0
- mstransfer-0.1.0.dist-info/RECORD +15 -0
- mstransfer-0.1.0.dist-info/WHEEL +4 -0
- mstransfer-0.1.0.dist-info/entry_points.txt +2 -0
mstransfer/__init__.py
ADDED
mstransfer/__main__.py
ADDED
mstransfer/cli.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import socket
|
|
5
|
+
import sys
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
import uvicorn
|
|
10
|
+
from rich.live import Live
|
|
11
|
+
from rich.table import Table
|
|
12
|
+
|
|
13
|
+
from mstransfer.client.sender import resolve_inputs, send_batch
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from rich.progress import TaskID
|
|
19
|
+
|
|
20
|
+
from mstransfer.log import (
|
|
21
|
+
console,
|
|
22
|
+
make_file_progress,
|
|
23
|
+
make_overall_progress,
|
|
24
|
+
setup_logging,
|
|
25
|
+
)
|
|
26
|
+
from mstransfer.server.app import create_app
|
|
27
|
+
from mstransfer.server.models import TransferState, UploadResponse
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_target(target: str) -> str:
|
|
31
|
+
"""Parse a target string into a base URL.
|
|
32
|
+
|
|
33
|
+
Accepts formats like:
|
|
34
|
+
- host → http://host:1319
|
|
35
|
+
- host:port → http://host:port
|
|
36
|
+
- http://host:port → http://host:port (passed through)
|
|
37
|
+
- https://host:port → https://host:port (passed through)
|
|
38
|
+
"""
|
|
39
|
+
default_port = 1319
|
|
40
|
+
|
|
41
|
+
# If the target already has a scheme, use it as-is.
|
|
42
|
+
if target.startswith(("http://", "https://")):
|
|
43
|
+
return target.rstrip("/")
|
|
44
|
+
|
|
45
|
+
if ":" in target:
|
|
46
|
+
host, port_str = target.rsplit(":", 1)
|
|
47
|
+
try:
|
|
48
|
+
port = int(port_str)
|
|
49
|
+
except ValueError:
|
|
50
|
+
console.print(f"[red]Invalid port in target: {target}")
|
|
51
|
+
sys.exit(1)
|
|
52
|
+
return f"http://{host}:{port}"
|
|
53
|
+
return f"http://{target}:{default_port}"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def cmd_serve(args: argparse.Namespace) -> None:
|
|
57
|
+
setup_logging()
|
|
58
|
+
|
|
59
|
+
# Fail fast if the port is already in use.
|
|
60
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
61
|
+
try:
|
|
62
|
+
sock.bind((args.host, args.port))
|
|
63
|
+
except OSError:
|
|
64
|
+
console.print(
|
|
65
|
+
f"[red]Port {args.port} is already in use. "
|
|
66
|
+
"Is another mstransfer server running?"
|
|
67
|
+
)
|
|
68
|
+
sys.exit(1)
|
|
69
|
+
|
|
70
|
+
app = create_app(output_dir=args.output_dir, store_as=args.store_as)
|
|
71
|
+
console.print(
|
|
72
|
+
f"[bold green]mstransfer server[/] starting on "
|
|
73
|
+
f"[cyan]{args.host}:{args.port}[/] "
|
|
74
|
+
f"(store-as={args.store_as}, output={args.output_dir})"
|
|
75
|
+
)
|
|
76
|
+
uvicorn.run(app, host=args.host, port=args.port, log_level="warning")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class UploadProgressDisplay:
|
|
80
|
+
"""Rich-based implementation of BatchProgressCallback for the CLI."""
|
|
81
|
+
|
|
82
|
+
def __init__(self, total_files: int) -> None:
|
|
83
|
+
self.overall = make_overall_progress()
|
|
84
|
+
self.files = make_file_progress()
|
|
85
|
+
self.overall_task = self.overall.add_task("Transferring", total=total_files)
|
|
86
|
+
self.table = Table.grid()
|
|
87
|
+
self.table.add_row(self.overall)
|
|
88
|
+
self.table.add_row(self.files)
|
|
89
|
+
self._task_ids: dict[int, TaskID] = {}
|
|
90
|
+
|
|
91
|
+
def file_started(
|
|
92
|
+
self, index: int, file_path: Path, total_bytes: int | None,
|
|
93
|
+
) -> None:
|
|
94
|
+
task_id = self.files.add_task(file_path.name, total=total_bytes)
|
|
95
|
+
self._task_ids[index] = task_id
|
|
96
|
+
|
|
97
|
+
def file_progress(self, index: int, delta: int) -> None:
|
|
98
|
+
self.files.advance(self._task_ids[index], delta)
|
|
99
|
+
|
|
100
|
+
def file_done(self, index: int, result: UploadResponse) -> None:
|
|
101
|
+
task_id = self._task_ids[index]
|
|
102
|
+
desc = self.files.tasks[task_id].description
|
|
103
|
+
self.files.update(task_id, description=f"[green]{desc}")
|
|
104
|
+
self.overall.advance(self.overall_task)
|
|
105
|
+
|
|
106
|
+
def file_error(self, index: int, exc: Exception) -> None:
|
|
107
|
+
task_id = self._task_ids[index]
|
|
108
|
+
desc = self.files.tasks[task_id].description
|
|
109
|
+
self.files.update(task_id, description=f"[red]{desc}")
|
|
110
|
+
self.overall.advance(self.overall_task)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def cmd_upload(args: argparse.Namespace) -> None:
|
|
114
|
+
setup_logging()
|
|
115
|
+
|
|
116
|
+
if len(args.targets) < 2:
|
|
117
|
+
console.print("[red]Usage: mstransfer upload <paths...> <target>")
|
|
118
|
+
sys.exit(1)
|
|
119
|
+
|
|
120
|
+
*raw_paths, target = args.targets
|
|
121
|
+
base_url = parse_target(target)
|
|
122
|
+
|
|
123
|
+
try:
|
|
124
|
+
file_paths = resolve_inputs(raw_paths, recursive=args.recursive)
|
|
125
|
+
except FileNotFoundError as exc:
|
|
126
|
+
console.print(f"[red]{exc}")
|
|
127
|
+
sys.exit(1)
|
|
128
|
+
|
|
129
|
+
# Quick healthcheck before starting uploads.
|
|
130
|
+
try:
|
|
131
|
+
httpx.get(f"{base_url}/v1/health", timeout=5.0)
|
|
132
|
+
except httpx.ConnectError:
|
|
133
|
+
console.print(f"[red]Cannot connect to server at {base_url}. Is it running?")
|
|
134
|
+
sys.exit(1)
|
|
135
|
+
except httpx.TimeoutException:
|
|
136
|
+
console.print(f"[red]Server at {base_url} did not respond in time.")
|
|
137
|
+
sys.exit(1)
|
|
138
|
+
|
|
139
|
+
console.print(
|
|
140
|
+
f"Sending [bold]{len(file_paths)}[/] file(s) to "
|
|
141
|
+
f"[cyan]{base_url}[/] (parallel={args.parallel})"
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
display = UploadProgressDisplay(len(file_paths))
|
|
145
|
+
|
|
146
|
+
with Live(display.table, console=console, refresh_per_second=10):
|
|
147
|
+
results = send_batch(
|
|
148
|
+
file_paths, base_url,
|
|
149
|
+
parallel=args.parallel,
|
|
150
|
+
chunk_size=args.chunk_size,
|
|
151
|
+
progress=display,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
ok = sum(
|
|
155
|
+
1 for r in results
|
|
156
|
+
if r.response and r.response.state == TransferState.DONE
|
|
157
|
+
)
|
|
158
|
+
fail = len(results) - ok
|
|
159
|
+
if fail:
|
|
160
|
+
console.print(f"\n[green]{ok} succeeded[/], [red]{fail} failed[/]")
|
|
161
|
+
for r in results:
|
|
162
|
+
if r.response and r.response.state == TransferState.DONE:
|
|
163
|
+
continue
|
|
164
|
+
err = r.error or (str(r.response.state.value) if r.response else "unknown")
|
|
165
|
+
console.print(f" [red]- {r.filename}: {err}")
|
|
166
|
+
else:
|
|
167
|
+
console.print(f"\n[green]All {ok} file(s) transferred successfully.")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def main() -> None:
|
|
171
|
+
parser = argparse.ArgumentParser(
|
|
172
|
+
prog="mstransfer",
|
|
173
|
+
description=("Transfer mass spectrometry files (mzML/MSZ) between endpoints"),
|
|
174
|
+
)
|
|
175
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
176
|
+
|
|
177
|
+
# --- serve ---
|
|
178
|
+
lp = sub.add_parser("serve", help="Start the mstransfer server")
|
|
179
|
+
lp.add_argument("--host", default="0.0.0.0", help="Bind address")
|
|
180
|
+
lp.add_argument("--port", type=int, default=1319, help="Listen port")
|
|
181
|
+
lp.add_argument(
|
|
182
|
+
"--output-dir",
|
|
183
|
+
default="./received",
|
|
184
|
+
help="Directory for received files",
|
|
185
|
+
)
|
|
186
|
+
lp.add_argument(
|
|
187
|
+
"--store-as",
|
|
188
|
+
choices=["msz", "mzml"],
|
|
189
|
+
default="msz",
|
|
190
|
+
help="Storage format (default: msz)",
|
|
191
|
+
)
|
|
192
|
+
lp.set_defaults(func=cmd_serve)
|
|
193
|
+
|
|
194
|
+
# --- upload ---
|
|
195
|
+
sp = sub.add_parser("upload", help="Upload files to a mstransfer server")
|
|
196
|
+
sp.add_argument(
|
|
197
|
+
"targets",
|
|
198
|
+
nargs="+",
|
|
199
|
+
help="File/directory paths followed by target host[:port]",
|
|
200
|
+
)
|
|
201
|
+
sp.add_argument(
|
|
202
|
+
"--recursive",
|
|
203
|
+
"-r",
|
|
204
|
+
action="store_true",
|
|
205
|
+
help="Recurse into directories",
|
|
206
|
+
)
|
|
207
|
+
sp.add_argument(
|
|
208
|
+
"--parallel",
|
|
209
|
+
"-p",
|
|
210
|
+
type=int,
|
|
211
|
+
default=4,
|
|
212
|
+
help="Concurrent uploads (default: 4)",
|
|
213
|
+
)
|
|
214
|
+
sp.add_argument(
|
|
215
|
+
"--chunk-size",
|
|
216
|
+
type=int,
|
|
217
|
+
default=1_048_576,
|
|
218
|
+
help="Upload chunk size in bytes (default: 1048576)",
|
|
219
|
+
)
|
|
220
|
+
sp.set_defaults(func=cmd_upload)
|
|
221
|
+
|
|
222
|
+
args = parser.parse_args()
|
|
223
|
+
args.func(args)
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import time
|
|
5
|
+
import uuid
|
|
6
|
+
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING, Protocol, runtime_checkable
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
from mscompress import MSZFile, MZMLFile
|
|
16
|
+
from mscompress.mszx import MSZXFile
|
|
17
|
+
from mscompress.utils import detect_filetype
|
|
18
|
+
|
|
19
|
+
from mstransfer.server.models import TransferRecord, TransferState, UploadResponse
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
VALID_EXTENSIONS = {".mzml", ".msz", ".mszx"}
|
|
24
|
+
VALID_FORMATS = {"mzML", "msz", "mszx"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@runtime_checkable
|
|
28
|
+
class BatchProgressCallback(Protocol):
|
|
29
|
+
"""Callback protocol for observing batch upload progress."""
|
|
30
|
+
|
|
31
|
+
def file_started(
|
|
32
|
+
self,
|
|
33
|
+
index: int,
|
|
34
|
+
file_path: Path,
|
|
35
|
+
total_bytes: int | None
|
|
36
|
+
) -> None: ...
|
|
37
|
+
|
|
38
|
+
def file_progress(self, index: int, delta: int) -> None: ...
|
|
39
|
+
def file_done(self, index: int, result: UploadResponse) -> None: ...
|
|
40
|
+
def file_error(self, index: int, exc: Exception) -> None: ...
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class FileResult:
|
|
45
|
+
"""Result of uploading a single file in a batch."""
|
|
46
|
+
|
|
47
|
+
filename: str
|
|
48
|
+
response: UploadResponse | None = field(default=None)
|
|
49
|
+
error: str | None = field(default=None)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def resolve_inputs(paths: list[str], recursive: bool = False) -> list[Path]:
|
|
53
|
+
"""Resolve files and directories into a sorted list of valid MS files."""
|
|
54
|
+
result: list[Path] = []
|
|
55
|
+
for p in paths:
|
|
56
|
+
path = Path(p)
|
|
57
|
+
if path.is_file():
|
|
58
|
+
if path.suffix.lower() in VALID_EXTENSIONS:
|
|
59
|
+
result.append(path)
|
|
60
|
+
else:
|
|
61
|
+
logger.warning("Skipping unsupported file: %s", path)
|
|
62
|
+
elif path.is_dir():
|
|
63
|
+
for ext in ("*.mzML", "*.msz", "*.mzml", "*.MSZ"):
|
|
64
|
+
if recursive:
|
|
65
|
+
result.extend(path.rglob(ext))
|
|
66
|
+
else:
|
|
67
|
+
result.extend(path.glob(ext))
|
|
68
|
+
result = list(dict.fromkeys(result))
|
|
69
|
+
else:
|
|
70
|
+
logger.warning("Path does not exist: %s", path)
|
|
71
|
+
if not result:
|
|
72
|
+
raise FileNotFoundError("No valid .mzML or .msz files found in the given paths")
|
|
73
|
+
return sorted(set(result))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _counting_generator(iterator, callback: Callable[[int], None] | None = None):
|
|
77
|
+
"""Wrap an iterator, calling callback with byte count per chunk."""
|
|
78
|
+
for chunk in iterator:
|
|
79
|
+
if callback:
|
|
80
|
+
callback(len(chunk))
|
|
81
|
+
yield chunk
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _file_chunk_generator(
|
|
85
|
+
file_path: Path,
|
|
86
|
+
chunk_size: int = 1_048_576,
|
|
87
|
+
callback: Callable[[int], None] | None = None,
|
|
88
|
+
):
|
|
89
|
+
"""Read a file in chunks, calling callback with each chunk's size."""
|
|
90
|
+
with open(file_path, "rb") as f:
|
|
91
|
+
while True:
|
|
92
|
+
chunk = f.read(chunk_size)
|
|
93
|
+
if not chunk:
|
|
94
|
+
break
|
|
95
|
+
if callback:
|
|
96
|
+
callback(len(chunk))
|
|
97
|
+
yield chunk
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def send_file(
|
|
101
|
+
source: Path | MZMLFile | MSZFile | MSZXFile,
|
|
102
|
+
base_url: str,
|
|
103
|
+
progress_callback: Callable[[int], None] | None = None,
|
|
104
|
+
timeout: float = 3600.0,
|
|
105
|
+
chunk_size: int = 1_048_576,
|
|
106
|
+
) -> UploadResponse:
|
|
107
|
+
"""Send a single file to the mstransfer listener.
|
|
108
|
+
|
|
109
|
+
Accepts a file path, or an already-opened MZMLFile / MSZFile / MSZXFile
|
|
110
|
+
from mscompress. Returns the final transfer status from the server.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
# Generate a unique transfer ID.
|
|
114
|
+
transfer_id = str(uuid.uuid4())
|
|
115
|
+
|
|
116
|
+
# Normalize source into (file_path, filetype, mzml_obj | None).
|
|
117
|
+
if isinstance(source, MZMLFile):
|
|
118
|
+
file_path = Path(source.path.decode())
|
|
119
|
+
filetype = "mzML"
|
|
120
|
+
mzml_obj: MZMLFile | None = source
|
|
121
|
+
elif isinstance(source, MSZFile):
|
|
122
|
+
file_path = Path(source.path.decode())
|
|
123
|
+
filetype = "msz"
|
|
124
|
+
mzml_obj = None
|
|
125
|
+
elif isinstance(source, MSZXFile):
|
|
126
|
+
file_path = source.archive_path
|
|
127
|
+
filetype = "mszx"
|
|
128
|
+
mzml_obj = None
|
|
129
|
+
elif isinstance(source, Path):
|
|
130
|
+
file_path = source
|
|
131
|
+
filetype = detect_filetype(str(file_path))
|
|
132
|
+
if filetype not in VALID_FORMATS:
|
|
133
|
+
raise ValueError(f"Unsupported file type for {file_path}: {filetype}")
|
|
134
|
+
mzml_obj = MZMLFile(str(file_path).encode()) if filetype == "mzML" else None
|
|
135
|
+
else:
|
|
136
|
+
raise TypeError(f"Unsupported source type: {type(source)}")
|
|
137
|
+
|
|
138
|
+
# Build the upload stream.
|
|
139
|
+
# If its an mzML file, we can use the compress_stream for on-the-fly compression.
|
|
140
|
+
if mzml_obj is not None:
|
|
141
|
+
stream = _counting_generator(
|
|
142
|
+
mzml_obj.compress_stream(chunk_size=chunk_size), progress_callback,
|
|
143
|
+
)
|
|
144
|
+
# Otherwise, we stream the file in chuncks.
|
|
145
|
+
else:
|
|
146
|
+
stream = _file_chunk_generator(
|
|
147
|
+
file_path, chunk_size=chunk_size, callback=progress_callback,
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
# Construct headers with metadata for the server.
|
|
151
|
+
headers = {
|
|
152
|
+
"X-Transfer-ID": transfer_id,
|
|
153
|
+
"X-Original-Filename": file_path.name,
|
|
154
|
+
"X-Source-Format": filetype,
|
|
155
|
+
"Content-Type": "application/octet-stream",
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
# Send the POST request with streaming upload and handle the response.
|
|
159
|
+
with httpx.Client(timeout=httpx.Timeout(timeout, connect=10.0)) as client:
|
|
160
|
+
resp = client.post(
|
|
161
|
+
f"{base_url}/v1/upload",
|
|
162
|
+
headers=headers,
|
|
163
|
+
content=stream,
|
|
164
|
+
)
|
|
165
|
+
resp.raise_for_status()
|
|
166
|
+
upload_result = UploadResponse.model_validate(resp.json())
|
|
167
|
+
|
|
168
|
+
# Poll for server-side processing completion
|
|
169
|
+
if upload_result.state not in (TransferState.DONE, TransferState.ERROR):
|
|
170
|
+
state = _poll_status(base_url, transfer_id, timeout=timeout)
|
|
171
|
+
upload_result.state = state
|
|
172
|
+
|
|
173
|
+
return upload_result
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _poll_status(
|
|
177
|
+
base_url: str,
|
|
178
|
+
transfer_id: str,
|
|
179
|
+
timeout: float = 300.0,
|
|
180
|
+
interval: float = 0.5,
|
|
181
|
+
) -> TransferState:
|
|
182
|
+
"""Poll transfer status until terminal state or timeout."""
|
|
183
|
+
|
|
184
|
+
# Configure a deadline for the polling operation.
|
|
185
|
+
deadline = time.monotonic() + timeout
|
|
186
|
+
|
|
187
|
+
# Keep track of the last seen state and bytes to detect progress.
|
|
188
|
+
last_state: TransferState | None = None
|
|
189
|
+
last_bytes: int = 0
|
|
190
|
+
|
|
191
|
+
# Individual request timeout should be reasonably short.
|
|
192
|
+
with httpx.Client(timeout=10.0) as client:
|
|
193
|
+
# Continously poll until we hit a terminal state or exceed the deadline.
|
|
194
|
+
while time.monotonic() < deadline:
|
|
195
|
+
# Make a GET request to the status endpoint for this transfer ID.
|
|
196
|
+
resp = client.get(f"{base_url}/v1/transfer/{transfer_id}/status")
|
|
197
|
+
if resp.status_code == 200:
|
|
198
|
+
record = TransferRecord.model_validate(resp.json())
|
|
199
|
+
|
|
200
|
+
# If the transfer is done or errored, return the final state.
|
|
201
|
+
if record.state in (TransferState.DONE, TransferState.ERROR):
|
|
202
|
+
return record.state
|
|
203
|
+
|
|
204
|
+
# Reset deadline if the server is still making progress
|
|
205
|
+
# Either by a state change or receiving more bytes.
|
|
206
|
+
if record.state != last_state or record.bytes_received > last_bytes:
|
|
207
|
+
last_state = record.state
|
|
208
|
+
last_bytes = record.bytes_received
|
|
209
|
+
deadline = time.monotonic() + timeout
|
|
210
|
+
# Sleep until the next poll interval before checking again.
|
|
211
|
+
time.sleep(interval)
|
|
212
|
+
raise TimeoutError(
|
|
213
|
+
f"Transfer {transfer_id} did not complete within {timeout}s"
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def send_batch(
|
|
218
|
+
sources: list[Path | MZMLFile | MSZFile | MSZXFile],
|
|
219
|
+
base_url: str,
|
|
220
|
+
parallel: int = 4,
|
|
221
|
+
chunk_size: int = 1_048_576,
|
|
222
|
+
progress: BatchProgressCallback | None = None,
|
|
223
|
+
) -> list[FileResult]:
|
|
224
|
+
"""Send multiple files with configurable parallelism."""
|
|
225
|
+
# Set the number of workers.
|
|
226
|
+
workers = min(parallel, len(sources))
|
|
227
|
+
|
|
228
|
+
results: list[FileResult] = []
|
|
229
|
+
|
|
230
|
+
with ThreadPoolExecutor(max_workers=workers) as pool:
|
|
231
|
+
# Keep track of futures and their corresponding index + file path.
|
|
232
|
+
futures: dict[Future[UploadResponse], tuple[int, Path]] = {}
|
|
233
|
+
|
|
234
|
+
for idx, source in enumerate(sources):
|
|
235
|
+
# Extract a Path for progress reporting and metadata.
|
|
236
|
+
if isinstance(source, MSZXFile):
|
|
237
|
+
fpath = source.archive_path
|
|
238
|
+
elif isinstance(source, (MZMLFile, MSZFile)):
|
|
239
|
+
fpath = Path(source.path.decode())
|
|
240
|
+
else:
|
|
241
|
+
fpath = source
|
|
242
|
+
|
|
243
|
+
# We can determine total bytes for compressed files (MSZ/MSZX).
|
|
244
|
+
# For mzML, compression is on-the-fly so the total is unknown.
|
|
245
|
+
if isinstance(source, (MSZFile, MSZXFile)):
|
|
246
|
+
total_bytes = fpath.stat().st_size
|
|
247
|
+
elif isinstance(source, MZMLFile):
|
|
248
|
+
total_bytes = None
|
|
249
|
+
else:
|
|
250
|
+
is_compressed = fpath.suffix.lower() in (".msz", ".mszx")
|
|
251
|
+
total_bytes = fpath.stat().st_size if is_compressed else None
|
|
252
|
+
|
|
253
|
+
# If the progress callback is provided, notify that this file is starting.
|
|
254
|
+
if progress:
|
|
255
|
+
progress.file_started(idx, fpath, total_bytes)
|
|
256
|
+
|
|
257
|
+
def make_callback(i: int):
|
|
258
|
+
"""
|
|
259
|
+
Create a callback function that captures the file index for progress.
|
|
260
|
+
"""
|
|
261
|
+
def cb(delta: int):
|
|
262
|
+
if progress:
|
|
263
|
+
progress.file_progress(i, delta)
|
|
264
|
+
return cb
|
|
265
|
+
|
|
266
|
+
# Submit the file upload task to the thread pool and store the future.
|
|
267
|
+
future = pool.submit(
|
|
268
|
+
send_file,
|
|
269
|
+
source,
|
|
270
|
+
base_url,
|
|
271
|
+
progress_callback=make_callback(idx),
|
|
272
|
+
chunk_size=chunk_size,
|
|
273
|
+
)
|
|
274
|
+
futures[future] = (idx, fpath)
|
|
275
|
+
|
|
276
|
+
# As the futures complete,
|
|
277
|
+
for future in as_completed(futures):
|
|
278
|
+
# Unpack the index and file path for this future to report progress callback
|
|
279
|
+
idx, fpath = futures[future]
|
|
280
|
+
try:
|
|
281
|
+
result = future.result()
|
|
282
|
+
results.append(FileResult(filename=fpath.name, response=result))
|
|
283
|
+
if progress:
|
|
284
|
+
progress.file_done(idx, result)
|
|
285
|
+
# On exception, append a FileResult with the error message.
|
|
286
|
+
except Exception as exc:
|
|
287
|
+
results.append(FileResult(filename=fpath.name, error=str(exc)))
|
|
288
|
+
if progress:
|
|
289
|
+
progress.file_error(idx, exc)
|
|
290
|
+
logger.error("Failed to send %s: %s", fpath, exc)
|
|
291
|
+
|
|
292
|
+
return results
|
mstransfer/log.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
from rich.console import Console
|
|
6
|
+
from rich.logging import RichHandler
|
|
7
|
+
from rich.progress import (
|
|
8
|
+
BarColumn,
|
|
9
|
+
DownloadColumn,
|
|
10
|
+
MofNCompleteColumn,
|
|
11
|
+
Progress,
|
|
12
|
+
SpinnerColumn,
|
|
13
|
+
TextColumn,
|
|
14
|
+
TimeElapsedColumn,
|
|
15
|
+
TransferSpeedColumn,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
console = Console()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def setup_logging(level: int = logging.INFO) -> None:
|
|
22
|
+
logging.basicConfig(
|
|
23
|
+
level=level,
|
|
24
|
+
format="%(message)s",
|
|
25
|
+
datefmt="[%X]",
|
|
26
|
+
handlers=[RichHandler(console=console, rich_tracebacks=True)],
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def make_overall_progress() -> Progress:
|
|
31
|
+
return Progress(
|
|
32
|
+
SpinnerColumn(),
|
|
33
|
+
TextColumn("[bold blue]{task.description}"),
|
|
34
|
+
MofNCompleteColumn(),
|
|
35
|
+
TimeElapsedColumn(),
|
|
36
|
+
console=console,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def make_file_progress() -> Progress:
|
|
41
|
+
return Progress(
|
|
42
|
+
SpinnerColumn(),
|
|
43
|
+
TextColumn("{task.description}", style="dim"),
|
|
44
|
+
BarColumn(bar_width=30),
|
|
45
|
+
DownloadColumn(),
|
|
46
|
+
TransferSpeedColumn(),
|
|
47
|
+
TimeElapsedColumn(),
|
|
48
|
+
console=console,
|
|
49
|
+
)
|
|
File without changes
|
mstransfer/server/app.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from fastapi import FastAPI
|
|
6
|
+
|
|
7
|
+
from mstransfer.server.routes import router
|
|
8
|
+
from mstransfer.server.state import AppState
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def create_app(
|
|
12
|
+
output_dir: str = "./received",
|
|
13
|
+
store_as: str = "msz",
|
|
14
|
+
) -> FastAPI:
|
|
15
|
+
"""Create a configured mstransfer FastAPI application.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
output_dir: Directory where received files are stored.
|
|
19
|
+
store_as: Output format — "msz" or "mzml".
|
|
20
|
+
"""
|
|
21
|
+
app = FastAPI(title="mstransfer")
|
|
22
|
+
out = Path(output_dir)
|
|
23
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
24
|
+
app.state = AppState(output_dir=out, store_as=store_as)
|
|
25
|
+
app.include_router(router, prefix="/v1")
|
|
26
|
+
return app
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from enum import Enum
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, Field
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class TransferState(str, Enum):
|
|
8
|
+
"""Enumeration of possible states for a file transfer."""
|
|
9
|
+
RECEIVING = "receiving"
|
|
10
|
+
RECEIVED = "received"
|
|
11
|
+
DECOMPRESSING = "decompressing"
|
|
12
|
+
DONE = "done"
|
|
13
|
+
ERROR = "error"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TransferRecord(BaseModel):
|
|
17
|
+
"""Data model for a file transfer record in the registry."""
|
|
18
|
+
transfer_id: str
|
|
19
|
+
filename: str
|
|
20
|
+
state: TransferState = TransferState.RECEIVING
|
|
21
|
+
bytes_received: int = 0
|
|
22
|
+
stored_as: str = ""
|
|
23
|
+
error: str | None = None
|
|
24
|
+
created_at: datetime = Field(default_factory=datetime.now)
|
|
25
|
+
|
|
26
|
+
model_config = {"from_attributes": True}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class UploadResponse(BaseModel):
|
|
30
|
+
"""Response model for a successful upload."""
|
|
31
|
+
transfer_id: str
|
|
32
|
+
filename: str
|
|
33
|
+
stored_as: str
|
|
34
|
+
state: TransferState
|
|
35
|
+
bytes_received: int
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class HealthResponse(BaseModel):
|
|
39
|
+
"""Response model for health check endpoint."""
|
|
40
|
+
status: str
|
|
41
|
+
version: str
|
|
42
|
+
store_as: str
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
import aiofiles
|
|
9
|
+
import aiofiles.os
|
|
10
|
+
from fastapi import APIRouter, Depends, HTTPException, Request
|
|
11
|
+
from mscompress import MSZFile
|
|
12
|
+
|
|
13
|
+
from mstransfer import __version__
|
|
14
|
+
from mstransfer.server.models import (
|
|
15
|
+
HealthResponse,
|
|
16
|
+
TransferRecord,
|
|
17
|
+
TransferState,
|
|
18
|
+
UploadResponse,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from mstransfer.server.state import AppState
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def get_state(request: Request) -> AppState:
|
|
26
|
+
return request.app.state
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
StateDep = Depends(get_state)
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
router = APIRouter()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@router.get("/health", response_model=HealthResponse)
|
|
37
|
+
async def health(state: AppState = StateDep) -> HealthResponse:
|
|
38
|
+
"""
|
|
39
|
+
Simple health check endpoint that returns the server status, version,
|
|
40
|
+
and storage configuration.
|
|
41
|
+
"""
|
|
42
|
+
return HealthResponse(
|
|
43
|
+
status="ok",
|
|
44
|
+
version=__version__,
|
|
45
|
+
store_as=state.store_as,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@router.get("/transfer/{transfer_id}/status", response_model=TransferRecord)
|
|
50
|
+
async def transfer_status(
|
|
51
|
+
transfer_id: str, state: AppState = StateDep
|
|
52
|
+
) -> TransferRecord:
|
|
53
|
+
"""
|
|
54
|
+
Endpoint to check the status of an ongoing or completed transfer by its ID.
|
|
55
|
+
"""
|
|
56
|
+
# Get the corresponding transfer record from the registry.
|
|
57
|
+
record = state.transfers.get(transfer_id)
|
|
58
|
+
|
|
59
|
+
# If no record is found, return a 404 error.
|
|
60
|
+
if record is None:
|
|
61
|
+
raise HTTPException(status_code=404, detail="Transfer not found")
|
|
62
|
+
return record
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@router.post("/upload", response_model=UploadResponse)
|
|
66
|
+
async def upload(
|
|
67
|
+
request: Request, state: AppState = StateDep
|
|
68
|
+
) -> UploadResponse:
|
|
69
|
+
"""
|
|
70
|
+
Endpoint to handle file uploads. Expects the file content in the request body
|
|
71
|
+
and requires the following headers:
|
|
72
|
+
|
|
73
|
+
- X-Transfer-ID: A unique identifier for the transfer.
|
|
74
|
+
- X-Original-Filename: The original filename of the uploaded file.
|
|
75
|
+
|
|
76
|
+
The server will stream the incoming data to a file, update the transfer registry
|
|
77
|
+
with the progress, and optionally decompress if configured to do so.
|
|
78
|
+
"""
|
|
79
|
+
# Get the transfer ID, raise if missing.
|
|
80
|
+
transfer_id = request.headers.get("X-Transfer-ID")
|
|
81
|
+
if not transfer_id:
|
|
82
|
+
raise HTTPException(
|
|
83
|
+
status_code=400,
|
|
84
|
+
detail="Missing X-Transfer-ID header"
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
# Get the original filename, raise if missing.
|
|
88
|
+
original_filename = request.headers.get("X-Original-Filename")
|
|
89
|
+
if not original_filename:
|
|
90
|
+
raise HTTPException(
|
|
91
|
+
status_code=400,
|
|
92
|
+
detail="Missing X-Original-Filename header"
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
output_dir = state.output_dir
|
|
96
|
+
store_as = state.store_as
|
|
97
|
+
registry = state.transfers
|
|
98
|
+
|
|
99
|
+
# Create a new transfer record in the registry.
|
|
100
|
+
registry.create(transfer_id, original_filename)
|
|
101
|
+
logger.info("Receiving %s (transfer_id=%s)", original_filename, transfer_id)
|
|
102
|
+
|
|
103
|
+
# Use the filename stem for the output file.
|
|
104
|
+
stem = Path(original_filename).stem
|
|
105
|
+
msz_path = output_dir / f"{stem}.msz"
|
|
106
|
+
bytes_received = 0
|
|
107
|
+
|
|
108
|
+
# Stream the incoming data to a file asynchronously.
|
|
109
|
+
update_every = 64 # throttle registry updates to reduce lock overhead
|
|
110
|
+
chunk_count = 0
|
|
111
|
+
try:
|
|
112
|
+
async with aiofiles.open(msz_path, "wb") as f:
|
|
113
|
+
async for chunk in request.stream():
|
|
114
|
+
await f.write(chunk)
|
|
115
|
+
bytes_received += len(chunk)
|
|
116
|
+
chunk_count += 1
|
|
117
|
+
if chunk_count % update_every == 0:
|
|
118
|
+
registry.update(transfer_id, bytes_received=bytes_received)
|
|
119
|
+
|
|
120
|
+
# Final update to ensure accurate total
|
|
121
|
+
registry.update(transfer_id, bytes_received=bytes_received)
|
|
122
|
+
|
|
123
|
+
except Exception as exc:
|
|
124
|
+
registry.update(transfer_id, state=TransferState.ERROR, error=str(exc))
|
|
125
|
+
raise HTTPException(
|
|
126
|
+
status_code=500, detail=f"Error receiving data: {exc}"
|
|
127
|
+
) from exc
|
|
128
|
+
|
|
129
|
+
registry.update(transfer_id, state=TransferState.RECEIVED)
|
|
130
|
+
logger.info(
|
|
131
|
+
"Received %s (%d bytes, transfer_id=%s)",
|
|
132
|
+
original_filename,
|
|
133
|
+
bytes_received,
|
|
134
|
+
transfer_id,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
if store_as == "msz":
|
|
138
|
+
# If we're storing as .msz, we're done at this point.
|
|
139
|
+
# Just update the registry with the final path and state.
|
|
140
|
+
registry.update(
|
|
141
|
+
transfer_id,
|
|
142
|
+
state=TransferState.DONE,
|
|
143
|
+
stored_as=str(msz_path),
|
|
144
|
+
bytes_received=bytes_received,
|
|
145
|
+
)
|
|
146
|
+
elif store_as == "mzml":
|
|
147
|
+
# If we need to decompress to .mzML, update the state and then
|
|
148
|
+
# offload the decompression to a thread to avoid blocking the event loop.
|
|
149
|
+
registry.update(transfer_id, state=TransferState.DECOMPRESSING)
|
|
150
|
+
try:
|
|
151
|
+
# Open the .msz file
|
|
152
|
+
msz_file = MSZFile(str(msz_path).encode())
|
|
153
|
+
|
|
154
|
+
# Construct the output path for the decompressed .mzML file
|
|
155
|
+
mzml_path = output_dir / f"{stem}.mzML"
|
|
156
|
+
|
|
157
|
+
# Offload decompression to a thread to avoid blocking the event loop
|
|
158
|
+
await asyncio.to_thread(msz_file.decompress, str(mzml_path))
|
|
159
|
+
|
|
160
|
+
# Clean up the original .msz file after successful decompression
|
|
161
|
+
await aiofiles.os.remove(str(msz_path))
|
|
162
|
+
|
|
163
|
+
# Update the registry with the final state and path to the decompressed file
|
|
164
|
+
registry.update(
|
|
165
|
+
transfer_id,
|
|
166
|
+
state=TransferState.DONE,
|
|
167
|
+
stored_as=str(mzml_path),
|
|
168
|
+
bytes_received=bytes_received,
|
|
169
|
+
)
|
|
170
|
+
logger.info("Decompressed to %s", mzml_path)
|
|
171
|
+
except Exception as exc:
|
|
172
|
+
# On error, update the registry w/ error and log the failure.
|
|
173
|
+
registry.update(
|
|
174
|
+
transfer_id,
|
|
175
|
+
state=TransferState.ERROR,
|
|
176
|
+
error=str(exc),
|
|
177
|
+
)
|
|
178
|
+
logger.error("Decompression failed for %s: %s", transfer_id, exc)
|
|
179
|
+
|
|
180
|
+
# Return the final transfer record as the response.
|
|
181
|
+
final = registry.get(transfer_id)
|
|
182
|
+
|
|
183
|
+
# This should not be None,
|
|
184
|
+
# however if it is, return a 500 error indicating an unexpected state.
|
|
185
|
+
if final is None:
|
|
186
|
+
raise HTTPException(
|
|
187
|
+
status_code=500,
|
|
188
|
+
detail="Unexpected error: transfer record missing after processing",
|
|
189
|
+
)
|
|
190
|
+
return UploadResponse(
|
|
191
|
+
transfer_id=final.transfer_id,
|
|
192
|
+
filename=final.filename,
|
|
193
|
+
stored_as=final.stored_as,
|
|
194
|
+
state=final.state,
|
|
195
|
+
bytes_received=final.bytes_received,
|
|
196
|
+
)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
from starlette.datastructures import State
|
|
8
|
+
|
|
9
|
+
from mstransfer.server.models import TransferRecord, TransferState
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AppState(State):
|
|
16
|
+
"""Application state object to hold configuration and transfer registry."""
|
|
17
|
+
output_dir: Path
|
|
18
|
+
store_as: str
|
|
19
|
+
transfers: TransferRegistry
|
|
20
|
+
|
|
21
|
+
def __init__(self, output_dir: Path, store_as: str) -> None:
|
|
22
|
+
super().__init__()
|
|
23
|
+
self.output_dir = output_dir
|
|
24
|
+
self.store_as = store_as
|
|
25
|
+
self.transfers = TransferRegistry()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TransferRegistry:
|
|
29
|
+
"""Thread-safe in-memory registry of transfer records."""
|
|
30
|
+
|
|
31
|
+
def __init__(self) -> None:
|
|
32
|
+
self._records: dict[str, TransferRecord] = {}
|
|
33
|
+
self._lock = threading.Lock()
|
|
34
|
+
|
|
35
|
+
def create(self, transfer_id: str, filename: str) -> TransferRecord:
|
|
36
|
+
record = TransferRecord(transfer_id=transfer_id, filename=filename)
|
|
37
|
+
with self._lock:
|
|
38
|
+
self._records[transfer_id] = record
|
|
39
|
+
return record
|
|
40
|
+
|
|
41
|
+
def get(self, transfer_id: str) -> TransferRecord | None:
|
|
42
|
+
with self._lock:
|
|
43
|
+
return self._records.get(transfer_id)
|
|
44
|
+
|
|
45
|
+
def update(self, transfer_id: str, **kwargs: object) -> TransferRecord | None:
|
|
46
|
+
with self._lock:
|
|
47
|
+
record = self._records.get(transfer_id)
|
|
48
|
+
if record is None:
|
|
49
|
+
return None
|
|
50
|
+
for key, value in kwargs.items():
|
|
51
|
+
setattr(record, key, value)
|
|
52
|
+
return record
|
|
53
|
+
|
|
54
|
+
def cleanup(self, max_age_seconds: float = 300) -> int:
|
|
55
|
+
"""Remove old completed/errored records. Returns count removed."""
|
|
56
|
+
now = time.time()
|
|
57
|
+
terminal = {TransferState.DONE, TransferState.ERROR}
|
|
58
|
+
to_remove: list[str] = []
|
|
59
|
+
with self._lock:
|
|
60
|
+
for tid, record in self._records.items():
|
|
61
|
+
if record.state in terminal:
|
|
62
|
+
age = now - record.created_at.timestamp()
|
|
63
|
+
if age > max_age_seconds:
|
|
64
|
+
to_remove.append(tid)
|
|
65
|
+
for tid in to_remove:
|
|
66
|
+
del self._records[tid]
|
|
67
|
+
return len(to_remove)
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mstransfer
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Transfer mass spectrometry files (mzML/MSZ) between endpoints using mscompress
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Requires-Dist: aiofiles
|
|
7
|
+
Requires-Dist: fastapi
|
|
8
|
+
Requires-Dist: httpx
|
|
9
|
+
Requires-Dist: mscompress
|
|
10
|
+
Requires-Dist: pydantic>=2.0
|
|
11
|
+
Requires-Dist: python-multipart
|
|
12
|
+
Requires-Dist: rich
|
|
13
|
+
Requires-Dist: uvicorn[standard]
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# mstransfer
|
|
17
|
+
|
|
18
|
+
[](https://github.com/chrisagrams/mstransfer/actions/workflows/test.yml)
|
|
19
|
+
[](https://codecov.io/gh/chrisagrams/mstransfer)
|
|
20
|
+
|
|
21
|
+
Transfer mass spectrometry files (mzML / MSZ) between machines over HTTP. Files are always transported in compressed MSZ format using [mscompress](https://github.com/chrisagrams/mscompress) — mzML sources are compressed on-the-fly without temp files, and the receiving end can optionally decompress back to mzML.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
# Recommended — installs as an isolated CLI tool
|
|
27
|
+
uv tool install mstransfer
|
|
28
|
+
|
|
29
|
+
# Or with pipx
|
|
30
|
+
pipx install mstransfer
|
|
31
|
+
|
|
32
|
+
# Or as a project dependency
|
|
33
|
+
uv pip install mstransfer
|
|
34
|
+
pip install mstransfer
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Quick start
|
|
38
|
+
|
|
39
|
+
Start a server on the receiving machine:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
mstransfer serve --port 1319 --store-as msz
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Upload files from the source machine:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
mstransfer upload /data/experiment1.mzML /data/batch/ remote-host:1319
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Usage
|
|
52
|
+
|
|
53
|
+
### `mstransfer serve`
|
|
54
|
+
|
|
55
|
+
Start the receiver server.
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
mstransfer serve [--host 0.0.0.0] [--port 1319] [--output-dir ./received] [--store-as msz|mzml]
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
| Flag | Default | Description |
|
|
62
|
+
|------|---------|-------------|
|
|
63
|
+
| `--host` | `0.0.0.0` | Bind address |
|
|
64
|
+
| `--port` | `1319` | Listen port |
|
|
65
|
+
| `--output-dir` | `./received` | Where received files are written |
|
|
66
|
+
| `--store-as` | `msz` | Store as `msz` (compressed) or `mzml` (decompress on arrival) |
|
|
67
|
+
|
|
68
|
+
### `mstransfer upload`
|
|
69
|
+
|
|
70
|
+
Upload files to a server. Accepts any mix of files and directories. The last positional argument is the target.
|
|
71
|
+
|
|
72
|
+
```
|
|
73
|
+
mstransfer upload <paths...> <host[:port]> [--recursive] [--parallel 4]
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
| Flag | Default | Description |
|
|
77
|
+
|------|---------|-------------|
|
|
78
|
+
| `--recursive`, `-r` | off | Recurse into directories |
|
|
79
|
+
| `--parallel`, `-p` | `4` | Number of concurrent uploads |
|
|
80
|
+
|
|
81
|
+
Supported file types: `.mzML`, `.msz`, `.mszx`.
|
|
82
|
+
|
|
83
|
+
- **mzML files** are compressed to MSZ on-the-fly via `compress_stream()` and streamed directly into the HTTP request — no temp files on the sender.
|
|
84
|
+
- **MSZ / MSZX files** are streamed as-is.
|
|
85
|
+
|
|
86
|
+
## Programmatic access
|
|
87
|
+
|
|
88
|
+
You can use mstransfer as a library to send files from your own Python code:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from pathlib import Path
|
|
92
|
+
from mstransfer.client import send_file, send_batch
|
|
93
|
+
|
|
94
|
+
# Send a single file (Path)
|
|
95
|
+
result = send_file(Path("experiment.mzML"), "http://remote-host:1319")
|
|
96
|
+
|
|
97
|
+
# Send an already-opened mscompress object
|
|
98
|
+
from mscompress import MZMLFile, MSZFile
|
|
99
|
+
from mscompress.mszx import MSZXFile
|
|
100
|
+
|
|
101
|
+
mzml = MZMLFile(b"/data/experiment.mzML")
|
|
102
|
+
send_file(mzml, "http://remote-host:1319")
|
|
103
|
+
|
|
104
|
+
msz = MSZFile(b"/data/experiment.msz")
|
|
105
|
+
send_file(msz, "http://remote-host:1319")
|
|
106
|
+
|
|
107
|
+
mszx = MSZXFile.open("/data/experiment.mszx")
|
|
108
|
+
send_file(mszx, "http://remote-host:1319")
|
|
109
|
+
|
|
110
|
+
# Send multiple files in parallel
|
|
111
|
+
send_batch(
|
|
112
|
+
[Path("a.mzML"), Path("b.msz"), mszx],
|
|
113
|
+
"http://remote-host:1319",
|
|
114
|
+
parallel=4,
|
|
115
|
+
)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
`send_file` and `send_batch` accept any mix of `Path`, `MZMLFile`, `MSZFile`, and `MSZXFile` inputs.
|
|
119
|
+
|
|
120
|
+
## API
|
|
121
|
+
|
|
122
|
+
The server exposes a REST API under `/v1/`:
|
|
123
|
+
|
|
124
|
+
| Endpoint | Method | Description |
|
|
125
|
+
|----------|--------|-------------|
|
|
126
|
+
| `/v1/health` | GET | Server status, version, storage mode |
|
|
127
|
+
| `/v1/upload` | POST | Upload a file (streamed MSZ body) |
|
|
128
|
+
| `/v1/transfer/{id}/status` | GET | Poll transfer state |
|
|
129
|
+
|
|
130
|
+
### Embedding in another app
|
|
131
|
+
|
|
132
|
+
The server is built as a FastAPI app factory:
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
from mstransfer import create_app
|
|
136
|
+
|
|
137
|
+
# Standalone
|
|
138
|
+
app = create_app(output_dir="/data/ms", store_as="mzml")
|
|
139
|
+
|
|
140
|
+
# Mount in an existing FastAPI app
|
|
141
|
+
from fastapi import FastAPI
|
|
142
|
+
main_app = FastAPI()
|
|
143
|
+
main_app.mount("/transfer", create_app())
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## How it works
|
|
147
|
+
|
|
148
|
+
```mermaid
|
|
149
|
+
flowchart LR
|
|
150
|
+
subgraph Sender
|
|
151
|
+
mzML[".mzML"] --> compress["compress_stream()"]
|
|
152
|
+
msz[".msz / .mszx"] --> read["read file"]
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
compress --> upload["POST /v1/upload\n(MSZ bytes)"]
|
|
156
|
+
read --> upload
|
|
157
|
+
|
|
158
|
+
subgraph Server
|
|
159
|
+
upload --> mode{store-as?}
|
|
160
|
+
mode -- msz --> write["write to disk"]
|
|
161
|
+
mode -- mzml --> temp["write temp .msz"]
|
|
162
|
+
temp --> decompress["decompress"]
|
|
163
|
+
decompress --> cleanup["cleanup temp"]
|
|
164
|
+
end
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Development
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
uv sync --dev
|
|
171
|
+
uv run pytest
|
|
172
|
+
uv run ruff check src/ tests/
|
|
173
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
mstransfer/__init__.py,sha256=fPFZiRU0CDT276kPwETsFUkcAc83V7v9dGM_fk_vBqg,183
|
|
2
|
+
mstransfer/__main__.py,sha256=YGYqMGVE_QbnE8xjpjRqxMIa62ecRLlODoxFbx5xPnE,40
|
|
3
|
+
mstransfer/cli.py,sha256=QDD4mQxcEMOUgXO4QykxPQ67isnaQqwpmJO0Xj2nEiI,6986
|
|
4
|
+
mstransfer/log.py,sha256=HoonbkUzfyUuyh6vorvI__kSj46_iBZ5ZGexUSrgtrY,1085
|
|
5
|
+
mstransfer/client/__init__.py,sha256=czAiNBgNz4RpqbJ4tj-cmHOCMivPInwg8oRAirEhSmw,132
|
|
6
|
+
mstransfer/client/sender.py,sha256=cE8nWuCRtdUz7YA5W2t8IZC6E_mWPwzYejsr4bAAbog,10578
|
|
7
|
+
mstransfer/server/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
mstransfer/server/app.py,sha256=IdjsHjx1X79n5LITwHJaEzleruCSgpSwWwcT7eKzz-M,697
|
|
9
|
+
mstransfer/server/models.py,sha256=1XvK0nXYM28KqLqtPMBJyUb02Um0gSFzwik2qT2GC0Q,1025
|
|
10
|
+
mstransfer/server/routes.py,sha256=tL02eNY1atkQBKO0rjJV9ddYrPezmk1vCoD-jKPyky4,6514
|
|
11
|
+
mstransfer/server/state.py,sha256=3d8GJDahc6vE4bDmevyHjKVsMSkTxwtQdRp9SxZqeXc,2211
|
|
12
|
+
mstransfer-0.1.0.dist-info/METADATA,sha256=NJimvhLl94UoGf9wyq_ve2G6SWEue9lmBx5RcG-aYlQ,4741
|
|
13
|
+
mstransfer-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
14
|
+
mstransfer-0.1.0.dist-info/entry_points.txt,sha256=UCAZC4ai8vpp0KmWIMtoq68t3rGvksp_pBFH6NS3Hbk,51
|
|
15
|
+
mstransfer-0.1.0.dist-info/RECORD,,
|