Bind serve's socket before writing client.json

A serve that lost the port race had already signed in, so client.json
named a port another engine held and every client talked to that one.
The socket is now bound first and handed to uvicorn.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QgG6TJw5qBZzaLghQSRVrq
This commit is contained in:
2026-09-16 16:47:11 +02:00
co-authored by Claude Opus 5
parent 3dc43be6d0
commit 7dfe646e2b
3 changed files with 70 additions and 13 deletions
+32
View File
@@ -935,6 +935,38 @@ def test_serve_moves_off_a_port_that_is_taken() -> None:
assert DEFAULT_PORT == 8000
def test_a_port_that_cannot_be_bound_writes_no_credential(tmp_path, monkeypatch):
"""The token is written once the socket is ours, not on the way to it.
Written first, a failed start left `client.json` naming a port another
project's engine holds — and every client here then talked to that one.
"""
import socket
from types import SimpleNamespace
from fluksio import cli
from fluksio.core import bootstrap
admin = SimpleNamespace(id="admin", email="admin@example.com")
monkeypatch.setattr(cli, "_prepare", lambda data_dir: None)
monkeypatch.setattr(bootstrap, "ensure_superuser", lambda *a, **k: (admin, None))
# uvicorn's logging config would otherwise outlive this test.
monkeypatch.setattr(cli, "_log_config", lambda level: None)
data_dir = tmp_path / ".fluksio"
with socket.socket() as held:
held.bind(("127.0.0.1", 0))
held.listen(1)
taken = held.getsockname()[1]
args = cli._parser().parse_args(
["serve", "--plain", "--port", str(taken), "--data-dir", str(data_dir)]
)
assert cli.cmd_serve(args) == 1
assert not (data_dir / "client.json").exists()
assert not (data_dir / cli.PIDFILE).exists()
def test_a_duration_reads_the_way_an_age_does() -> None:
"""One notation for both, rather than one per place that printed one."""
from fluksio.sdk.cli import _dur