Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 39 additions & 3 deletions application/firstrade_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,8 +278,10 @@ def __init__(
self.read_only_history_response_bytes: bytes | None = None
self.read_only_request_attempts = 0

def connect(self, *, force_login: bool = False) -> "FirstradeBrokerClient":
"""Log in (or reuse cache). force_login skips cache reuse but still saves the new cache."""
def connect(self, *, force_login: bool = False, defer_cache_save: bool = False) -> "FirstradeBrokerClient":
"""Log in or reuse cache; forced callers may defer saving until validation."""
if defer_cache_save and not force_login:
raise FirstradeSafetyError("Deferred cache saving requires a forced login.")
self.read_only_transport_enabled = False
self.credentials.require_login_fields()
session_factory = self._session_factory
Expand Down Expand Up @@ -310,7 +312,8 @@ def connect(self, *, force_login: bool = False) -> "FirstradeBrokerClient":
self.session = session
self.account_data = account_data_factory(session)
self.session_reused = False
self._save_session_cache(cookie_dir)
if not defer_cache_save:
self._save_session_cache(cookie_dir)
return self

def connect_read_only(self) -> "FirstradeBrokerClient":
Expand Down Expand Up @@ -575,6 +578,39 @@ def _save_session_cache(self, cookie_dir: Path) -> None:
except Exception:
return

def save_verified_session_cache(self) -> None:
"""Persist a validated forced-login session; fail closed on shared-store failure."""
if not self.credentials.reuse_session or not self.credentials.persist_session_cache or self.session is None:
raise FirstradeSafetyError("Validated session cache is unavailable.")
session_obj = getattr(self.session, "session", None)
headers = getattr(session_obj, "headers", {}) or {}
cookies = {}
if hasattr(session_obj, "cookies"):
try:
cookies = session_obj.cookies.get_dict()
except Exception:
cookies = {}
payload = {
"access-token": headers.get("access-token"),
"ftat": headers.get("ftat"),
"sid": headers.get("sid"),
"cookies": cookies,
"saved_at": time(),
}
if any(not isinstance(payload[key], str) or not payload[key].strip()
for key in ("access-token", "ftat", "sid")):
raise FirstradeSafetyError("Validated session cache is unavailable.")
try:
store = self._session_state_store()
if store is None or store.write_json(self._session_state_key(), payload) is not True:
raise FirstradeSafetyError("Validated session cache is unavailable.")
except Exception:
raise FirstradeSafetyError("Validated session cache is unavailable.") from None
try:
self._session_cache_path(Path(self.credentials.cookie_dir)).write_text(json.dumps(payload), encoding="utf-8")
except OSError:
pass

def _session_state_store(self) -> GcsStateStore | None:
if self._session_cache_store is not None:
return self._session_cache_store
Expand Down
6 changes: 4 additions & 2 deletions application/session_check_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -466,10 +466,11 @@ def run_forced_session_renewal(
client_factory: Callable[..., FirstradeBrokerClient] = FirstradeBrokerClient,
env_reader: Callable[[str, str | None], str | None] = os.getenv,
) -> dict[str, Any]:
"""Manual read-only session renewal: one fresh login, persist the session cache, read balances.
"""Manual session renewal: fresh login, select account, read balances, then persist cache.

Bypasses (never reads, writes, or deletes) the monthly session-check marker. The client is
always built with live trading disabled and only account-read methods are called.
A successful result requires the shared cache write to complete successfully.
"""

resolved_credentials = credentials or FirstradeCredentials.from_env(env_reader)
Expand All @@ -478,9 +479,10 @@ def run_forced_session_renewal(
client = client_factory(resolved_credentials, live_trading_enabled=False)
if getattr(client, "live_trading_enabled", False):
raise FirstradeSafetyError("Forced session renewal requires a non-trading client.")
client.connect(force_login=True)
client.connect(force_login=True, defer_cache_save=True)
account = client.select_account(env_reader("FIRSTRADE_ACCOUNT", "") or None)
balances = client.get_balances(account)
client.save_verified_session_cache()
print(
"Firstrade forced session renewal "
f"session_reused={bool(getattr(client, 'session_reused', False))} "
Expand Down
10 changes: 10 additions & 0 deletions docs/account-archive-history.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Saved account history

## Manual session renewal

Manual session renewal selects the configured account, or the sole returned
account when no account is configured, and completes the balance read before
writing its session cache. A successful response requires the shared cache
store to acknowledge the write. It does not prove a later snapshot succeeded;
an empty balance response remains visible through `balances_read=false`.
When a write fails or its outcome is unknown, inspect the existing state and
request outcome before taking another action; do not blindly retry.

## Snapshot request log diagnosis

The existing `Diagnose cached-balance stage failure` workflow also has a
Expand Down
76 changes: 71 additions & 5 deletions tests/test_forced_session_renewal.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from application.session_check_service import run_forced_session_renewal

ORDER_METHODS = ("place_stock_order", "place_order", "submit_order", "cancel_order", "preview_order")
READ_METHODS = {"connect", "select_account", "get_balances"}
READ_METHODS = {"connect", "select_account", "get_balances", "save_verified_session_cache"}


def _credentials(**overrides):
Expand All @@ -31,8 +31,8 @@ def __getattr__(self, name):
raise AssertionError(f"order method reached: {name}")
raise AttributeError(name)

def connect(self, *, force_login=False):
self.calls.append(("connect", force_login))
def connect(self, *, force_login=False, defer_cache_save=False):
self.calls.append(("connect", (force_login, defer_cache_save)))
return self

def select_account(self, requested=None):
Expand All @@ -43,6 +43,9 @@ def get_balances(self, account):
self.calls.append(("get_balances", account))
return {"cash": 1}

def save_verified_session_cache(self):
self.calls.append(("save_verified_session_cache", None))


def _factory(created):
def make(credentials, *, live_trading_enabled):
Expand All @@ -62,7 +65,8 @@ def test_forced_renewal_logs_in_once_read_only():
assert len(created) == 1
client = created[0]
assert client.live_trading_enabled is False
assert client.calls[0] == ("connect", True)
assert client.calls[0] == ("connect", (True, True))
assert [call[0] for call in client.calls] == ["connect", "select_account", "get_balances", "save_verified_session_cache"]
assert {name for name, _ in client.calls} <= READ_METHODS
assert "12345979" not in str(result)

Expand Down Expand Up @@ -117,8 +121,70 @@ def login(self):
order_factory=lambda *_a: (_ for _ in ()).throw(AssertionError("order factory reached")),
)
client._try_cached_session = lambda *a, **k: events.append("cached") or True
client._save_session_cache = lambda *_args: events.append("saved")
client.connect(force_login=True)
assert events == ["login"]
assert events == ["login", "saved"]


@pytest.mark.parametrize("scenario", ["success", "auto_single", "empty_balances", "wrong_account", "auto_multiple", "balances_fail", "store_false", "store_error"])
@pytest.mark.parametrize("invalid_token", [None, ("access-token", None), ("access-token", 123), ("access-token", " "), ("ftat", None), ("ftat", 123), ("ftat", " "), ("sid", None), ("sid", 123), ("sid", " ")])
def test_renewal_commits_shared_cache_only_after_account_and_balance_validation(tmp_path, scenario, invalid_token):
from application.firstrade_client import FirstradeBrokerClient, FirstradePlatformError

events = []

class Store:
def write_json(self, key, value):
events.append("write")
if scenario == "store_error":
raise RuntimeError("private storage error")
return scenario != "store_false"

class Session:
def __init__(self, **_kwargs):
headers = {"access-token": "synthetic", "ftat": "synthetic", "sid": "synthetic"}
if invalid_token:
headers[invalid_token[0]] = invalid_token[1]
self.session = type("Transport", (), {"headers": headers, "cookies": None})()

def login(self):
events.append("login")
return False

class Data:
account_numbers = ["12345678", "87654321"] if scenario == "auto_multiple" else ["12345678"]
account_balances = {}

def __init__(self, _session):
pass

def get_account_balances(self, _account):
events.append("balances")
if scenario == "balances_fail":
raise FirstradePlatformError("synthetic failure")
if scenario == "empty_balances":
return {}
return {"synthetic": 1}

def factory(credentials, *, live_trading_enabled):
return FirstradeBrokerClient(credentials, live_trading_enabled=live_trading_enabled,
session_factory=Session, account_data_factory=Data, session_cache_store=Store())

requested = "" if scenario in {"auto_single", "auto_multiple"} else "87654321" if scenario == "wrong_account" else "12345678"
def run():
return run_forced_session_renewal(credentials=_credentials(cookie_dir=str(tmp_path)), client_factory=factory,
env_reader=lambda key, default=None: requested if key == "FIRSTRADE_ACCOUNT" else default)

if scenario in {"success", "auto_single", "empty_balances"} and invalid_token is None:
result = run()
assert result["session_renewed"] is True
assert result["balances_read"] is (scenario != "empty_balances")
assert events == ["login", "balances", "write"]
else:
with pytest.raises(FirstradePlatformError) as error:
run()
assert "private storage error" not in str(error.value)
assert events.count("write") == (1 if scenario in {"store_false", "store_error"} and invalid_token is None else 0)


# --- HTTP route ---------------------------------------------------------------------------
Expand Down
Loading