Compare commits

..

No commits in common. "62da2102d61fad093b87e394f9161dd2355e3e21" and "a4b72a21c8766bfc5128be82db3e412a53d94e25" have entirely different histories.

7 changed files with 20 additions and 144 deletions

View File

@ -26,7 +26,7 @@ import json
from pathlib import Path
from typing import TYPE_CHECKING
from crdt_sync._firebase import _DEFAULT_TIMEOUT_SECONDS, FirebaseSyncClient
from crdt_sync._firebase import FirebaseSyncClient
from crdt_sync._firebase_auth import FileCredentialStore, FirebaseTokenProvider
from crdt_sync._mirror import MirrorSyncClient
@ -141,7 +141,6 @@ def firebase_client_for(
app_name: str,
*,
config: FirebaseConfig | None = None,
timeout_seconds: float = _DEFAULT_TIMEOUT_SECONDS,
) -> FirebaseSyncClient:
"""Return a signed-in client for ``app_name``.
@ -152,9 +151,6 @@ def firebase_client_for(
Args:
app_name: Names the credential cache, e.g. ``"diet_guard"``.
config: Overrides the on-disk config; for tests.
timeout_seconds: Per-request network timeout. Without this the
client fell back to its own default and a caller's tighter
budget reached the GitHub backend only.
Raises:
ConfigError: If the shared config is unusable.
@ -164,9 +160,7 @@ def firebase_client_for(
auth = FirebaseTokenProvider(resolved.api_key, credential_store_for(app_name))
if not auth.has_session():
auth.sign_in(resolved.email, resolved.read_password())
return FirebaseSyncClient(
resolved.database_url, auth, timeout_seconds=timeout_seconds
)
return FirebaseSyncClient(resolved.database_url, auth)
def mirror_client_for(

View File

@ -17,16 +17,10 @@ from __future__ import annotations
from typing import TYPE_CHECKING
import requests as _requests
import requests
from crdt_sync._http import new_session
from crdt_sync._remote import RemoteNotFoundError, RemoteSyncError
# Bound to the name ``requests`` so the call sites below -- and the tests
# that patch ``<module>.requests.<verb>`` -- are unchanged by pooling.
requests = new_session()
if TYPE_CHECKING:
from crdt_sync._firebase_auth import FirebaseTokenProvider
@ -169,7 +163,7 @@ class FirebaseSyncClient:
def _params(self, **extra: str) -> dict[str, str]:
return {"auth": self.auth.id_token(), **extra}
def _raise(self, what: str, response: _requests.Response) -> None:
def _raise(self, what: str, response: requests.Response) -> None:
"""Raise the right error type for a non-2xx response.
401/403 mean the rules rejected this uid or the token is bad.
@ -190,14 +184,14 @@ class FirebaseSyncClient:
msg = f"{what} failed: HTTP {response.status_code} {detail}"
raise FirebaseSyncError(msg)
def _get(self, path: str, **params: str) -> _requests.Response:
def _get(self, path: str, **params: str) -> requests.Response:
try:
return requests.get(
self._url(path),
params=self._params(**params),
timeout=self._timeout_seconds,
)
except _requests.RequestException as exc:
except requests.RequestException as exc:
msg = f"network error reading {path}"
raise FirebaseSyncError(msg) from exc
@ -263,7 +257,7 @@ class FirebaseSyncClient:
json=text,
timeout=self._timeout_seconds,
)
except _requests.RequestException as exc:
except requests.RequestException as exc:
msg = f"network error writing {path}"
raise FirebaseSyncError(msg) from exc
if not response.ok:
@ -308,7 +302,7 @@ class FirebaseSyncClient:
params=self._params(),
timeout=self._timeout_seconds,
)
except _requests.RequestException as exc:
except requests.RequestException as exc:
msg = f"network error deleting {path}"
raise FirebaseSyncError(msg) from exc
if not response.ok:
@ -327,7 +321,7 @@ class FirebaseSyncClient:
params=self._params(shallow="true"),
timeout=self._timeout_seconds,
)
except _requests.RequestException:
except requests.RequestException:
return False
except RemoteSyncError:
# Includes FirebaseAuthError: "cannot get a token" is exactly

View File

@ -17,16 +17,10 @@ import datetime as dt
import json
from typing import TYPE_CHECKING, Protocol
import requests as _requests
import requests
from crdt_sync._http import new_session
from crdt_sync._remote import RemoteSyncError
# Bound to the name ``requests`` so the call sites below -- and the tests
# that patch ``<module>.requests.<verb>`` -- are unchanged by pooling.
requests = new_session()
if TYPE_CHECKING:
from pathlib import Path
@ -379,7 +373,7 @@ class FirebaseTokenProvider:
json=payload,
timeout=self._timeout_seconds,
)
except _requests.RequestException as exc:
except requests.RequestException as exc:
msg = f"network error trying to {what}"
raise FirebaseAuthError(msg) from exc
if not response.ok:
@ -389,7 +383,7 @@ class FirebaseTokenProvider:
return response.json()
def _reason(response: _requests.Response) -> str:
def _reason(response: requests.Response) -> str:
"""Return Google's machine-readable error reason, in parentheses.
Pulls ``INVALID_PASSWORD`` / ``TOKEN_EXPIRED`` / ``USER_DISABLED`` out of

View File

@ -11,16 +11,10 @@ from __future__ import annotations
import base64
import requests as _requests
import requests
from crdt_sync._http import new_session
from crdt_sync._remote import RemoteNotFoundError, RemoteSyncError
# Bound to the name ``requests`` so the call sites below -- and the tests
# that patch ``<module>.requests.<verb>`` -- are unchanged by pooling.
requests = new_session()
_API_BASE = "https://api.github.com"
_HTTP_NOT_FOUND = 404
_DEFAULT_TIMEOUT_SECONDS = 15
@ -74,14 +68,14 @@ class GitHubSyncClient:
def _contents_url(self, path: str) -> str:
return f"{_API_BASE}/repos/{self._owner}/{self._repo}/contents/{path}"
def _get(self, path: str) -> _requests.Response:
def _get(self, path: str) -> requests.Response:
try:
return requests.get(
self._contents_url(path),
headers=self._headers,
timeout=self._timeout_seconds,
)
except _requests.RequestException as exc:
except requests.RequestException as exc:
msg = f"network error reading {path}"
raise GitHubSyncError(msg) from exc
@ -92,7 +86,7 @@ class GitHubSyncClient:
headers=self._headers,
timeout=self._timeout_seconds,
)
except _requests.RequestException:
except requests.RequestException:
return False
return response.ok
@ -172,7 +166,7 @@ class GitHubSyncClient:
json=payload,
timeout=self._timeout_seconds,
)
except _requests.RequestException as exc:
except requests.RequestException as exc:
msg = f"network error pushing {path}"
raise GitHubSyncError(msg) from exc
if not response.ok:
@ -247,7 +241,7 @@ class GitHubSyncClient:
json={"message": message, "sha": sha},
timeout=self._timeout_seconds,
)
except _requests.RequestException as exc:
except requests.RequestException as exc:
msg = f"network error deleting {path}"
raise GitHubSyncError(msg) from exc
if not response.ok:

View File

@ -1,57 +0,0 @@
"""Pooled HTTP sessions, so every request does not re-handshake.
Every call site in this package used the module-level ``requests.get`` /
``put`` / ``post`` / ``delete`` helpers, each of which opens a throwaway
connection: fresh DNS, TCP and TLS on every single request. Measured against
the two real backends on 2026-08-21 that costs 82ms per request to
``api.github.com`` and 51ms to Realtime Database -- on a 27-request sync tick,
most of the wall clock.
A :class:`requests.Session` keeps the connection alive between requests, and
is a drop-in for the module-level helpers: same verb names, same signatures.
So each transport module binds one of these to the name ``requests`` and its
call sites are unchanged.
**One session per module, deliberately not one global.** The tests patch the
verb on the module attribute (``patch.object(fb.requests, "get", ...)``), and
several use sequence-consuming ``side_effect`` lists. Were all three modules
to share a single object, a call from one would consume another's queued
response and the failure would look like a logic bug. Per-module also happens
to be per-host here -- GitHub, Realtime Database, and the token endpoint are
three different origins -- so pooling loses nothing by the split.
Not thread-safe, in that :class:`requests.Session` is not documented to be;
this package spawns no threads and its consumers drive sync from one.
"""
from __future__ import annotations
import requests
from requests.adapters import HTTPAdapter, Retry
_RETRY_TOTAL = 3
_RETRY_BACKOFF_SECONDS = 0.3
_RETRY_STATUSES = (429, 500, 502, 503, 504)
def new_session() -> requests.Session:
"""Return a connection-pooling session that retries transient GET failures.
Retries are restricted to ``GET``. A ``PUT`` here carries a Contents-API
``sha`` (and a Realtime Database write is a full-node replace); replaying
one whose response was merely lost would push a second write built on a
now-stale precondition, against a remote another device reads. Reads are
idempotent, so only they are replayed.
"""
session = requests.Session()
retry = Retry(
total=_RETRY_TOTAL,
backoff_factor=_RETRY_BACKOFF_SECONDS,
status_forcelist=_RETRY_STATUSES,
allowed_methods=frozenset({"GET"}),
raise_on_status=False,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("https://", adapter)
session.mount("http://", adapter)
return session

View File

@ -20,7 +20,7 @@ from crdt_sync import (
credential_store_for,
mirror_client_for,
)
from crdt_sync._config import _DEFAULT_TIMEOUT_SECONDS, firebase_client_for
from crdt_sync._config import firebase_client_for
if TYPE_CHECKING:
from pathlib import Path
@ -283,46 +283,3 @@ def test_client_loads_the_shared_config_when_none_is_given(
monkeypatch.setattr("crdt_sync._config.FirebaseTokenProvider", _Auth)
assert firebase_client_for("wake_alarm") is not None
def _client_with_stub_auth(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
**kwargs: float,
) -> FirebaseSyncClient:
"""Return a client built with stubbed auth, forwarding ``kwargs``."""
config = FirebaseConfig.load(_write(tmp_path / "firebase.json", _VALID))
class _Auth:
def __init__(self, api_key: str, _store: object) -> None:
"""Record the key; the credential store is irrelevant here."""
self.api_key = api_key
def has_session(self) -> bool:
"""Pretend a cached session exists, so no sign-in is attempted."""
return True
monkeypatch.setattr("crdt_sync._config.FirebaseTokenProvider", _Auth)
return firebase_client_for("diet_guard", config=config, **kwargs)
def test_client_uses_the_requested_timeout(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A caller's timeout must reach the client, not just the GitHub half."""
# A keyword with a default adds no branch, so coverage alone cannot tell
# whether it is actually threaded through to the client.
client = _client_with_stub_auth(tmp_path, monkeypatch, timeout_seconds=3)
assert client._timeout_seconds == 3
def test_client_timeout_defaults_to_the_shared_value(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Omitting the keyword keeps the library-wide default."""
client = _client_with_stub_auth(tmp_path, monkeypatch)
assert client._timeout_seconds == _DEFAULT_TIMEOUT_SECONDS

View File

@ -1,6 +1,6 @@
[project]
name = "crdt-sync"
version = "0.8.1"
version = "0.7.0"
description = "Shared CRDT merge scheme + GitHub-Contents-API sync transport for cross-device apps"
requires-python = ">=3.10"
dependencies = ["requests"]