Open-source personal finance manager. Self-hosted, privacy-first.
feat: trigger Pluggy item refresh before manual sync (closes #226) (#230)
Tássio Noronha78a867e9edb0
diff --git a/backend/app/api/connections.py b/backend/app/api/connections.pyindex 508f1c9e..771cd111 100644--- a/backend/app/api/connections.py+++ b/backend/app/api/connections.py@@ -161,8 +161,15 @@ async def sync_connection(session: AsyncSession = Depends(get_async_session),):try:+ # Manual sync is user-initiated, so ask the provider to pull fresh+ # data from the bank before we read. Scheduled syncs (Celery) keep+ # the default behaviour: read whatever the provider already has.connection, merged_count = await connection_service.sync_connection(- session, connection_id, ctx.workspace.id, ctx.user_id+ session,+ connection_id,+ ctx.workspace.id,+ ctx.user_id,+ trigger_provider_refresh=True,)result = BankConnectionRead.model_validate(connection)return {**result.model_dump(mode="json"), "merged_count": merged_count}diff --git a/backend/app/providers/__init__.py b/backend/app/providers/__init__.pyindex 1ea183d4..b253a9cc 100644--- a/backend/app/providers/__init__.py+++ b/backend/app/providers/__init__.py@@ -7,6 +7,7 @@ from app.providers.base import (InstitutionData,InstitutionListData,ProviderUserActionRequired,+ RefreshOutcome,SessionExpiredError,TransactionData,)@@ -115,6 +116,7 @@ __all__ = ["InstitutionData","InstitutionListData","ProviderUserActionRequired",+ "RefreshOutcome","SessionExpiredError","register_provider","get_provider",diff --git a/backend/app/providers/base.py b/backend/app/providers/base.pyindex 65bc3e93..cc25ef1a 100644--- a/backend/app/providers/base.py+++ b/backend/app/providers/base.py@@ -2,7 +2,20 @@ from abc import ABC, abstractmethodfrom dataclasses import dataclass, fieldfrom datetime import datefrom decimal import Decimal-from typing import Optional+from typing import Literal, Optional+++# Outcome of asking a provider to pull fresh data from the underlying institution+# before we read accounts/transactions.+#+# - "refreshed": provider successfully synced; safe to read.+# - "skipped": provider has no on-demand refresh (default for most providers).+# - "needs_user_action": provider needs the user to act (MFA, expired credentials).+# Caller should mark the connection as needing reconnection+# and skip the read pass.+# - "failed": transient error (timeout, rate limit). Caller may proceed+# with a stale read; we don't punish the user for it.+RefreshOutcome = Literal["refreshed", "skipped", "needs_user_action", "failed"]@dataclass@@ -253,6 +266,20 @@ class BankProvider(ABC):"""Refresh access token if needed."""...+ async def trigger_refresh(self, credentials: dict) -> RefreshOutcome:+ """Ask the provider to pull fresh data from the underlying institution.++ Some aggregator providers cache the bank's data on their own side and+ only re-fetch on their own schedule. For those, the value we read on a+ sync may be older than what the bank actually has. When the user asks+ for fresh data, providers that expose an on-demand refresh should+ override this method to trigger it and poll until it completes.++ The default is a no-op (returns ``"skipped"``) — providers whose APIs+ already serve live data on every read don't need to override.+ """+ return "skipped"+async def get_holdings(self, credentials: dict) -> list[HoldingData]:"""Fetch investment holdings for a connection.diff --git a/backend/app/providers/pluggy.py b/backend/app/providers/pluggy.pyindex 95cd55ba..13dbb644 100644--- a/backend/app/providers/pluggy.py+++ b/backend/app/providers/pluggy.py@@ -1,3 +1,5 @@+import asyncio+import loggingimport timefrom datetime import datefrom decimal import Decimal, InvalidOperation@@ -13,9 +15,38 @@ from app.providers.base import (ConnectionData,ConnectTokenData,HoldingData,+ RefreshOutcome,TransactionData,)+logger = logging.getLogger(__name__)++# How long to wait for Pluggy to finish syncing with the bank before giving up+# and reading whatever Pluggy already has. Pluggy docs describe credential+# connectors completing in tens of seconds; we cap at 90s to keep manual sync+# requests bounded.+PLUGGY_REFRESH_TIMEOUT_SECONDS = 90+PLUGGY_REFRESH_POLL_INTERVAL = 3.0++# Item statuses we treat as terminal when polling /items/{id}.+# https://docs.pluggy.ai/docs/item-lifecycle+_PLUGGY_TERMINAL_STATUSES = {+ "UPDATED",+ "LOGIN_ERROR",+ "OUTDATED",+ "WAITING_USER_INPUT",+}++# Pluggy 400 ``codeDescription`` values that genuinely require the user to+# re-authenticate through the widget (MFA path). Every other 400 — items+# under MeuPluggy that can't be PATCHed, transient rate limits, etc. — is+# treated as a soft failure: we fall back to reading whatever Pluggy+# already has rather than punishing the user with a reconnect prompt.+_PLUGGY_REFRESH_USER_ACTION_CODES = {+ "MFA_PARAMERTER_WAS_ALREADY_USED_ERROR",+ "CONNECTOR_REQUIRED_PARAMETER_VALIDATION_ERROR",+}+PLUGGY_API_BASE = "https://api.pluggy.ai"@@ -421,6 +452,104 @@ class PluggyProvider(BankProvider):# Pluggy manages API keys at the provider level, not per-connectionreturn credentials+ async def trigger_refresh(self, credentials: dict) -> RefreshOutcome:+ """Trigger ``PATCH /items/{id}`` and poll the item until it leaves+ the ``UPDATING`` state.++ See https://docs.pluggy.ai/docs/item-lifecycle for the state machine.+ Pluggy's own auto-sync runs daily; this triggers an on-demand pull so+ Securo reads what the bank shows now, not what Pluggy last cached.+ """+ item_id = credentials.get("item_id") if credentials else None+ if not item_id:+ return "skipped"++ headers = await self._headers()+ async with httpx.AsyncClient(timeout=30.0) as client:+ try:+ trigger_resp = await client.patch(+ f"{PLUGGY_API_BASE}/items/{item_id}",+ headers=headers,+ json={},+ )+ except httpx.HTTPError:+ logger.warning("Pluggy refresh PATCH failed for item %s", item_id)+ return "failed"++ if trigger_resp.status_code == 400:+ # Pluggy returns 400 for several distinct cases. Only treat+ # the explicit MFA-related codes as "needs_user_action" — the+ # others (MeuPluggy-managed items that can't be PATCHed,+ # consecutive-failure backoffs, etc.) are transient or+ # outside the user's control. For those, fall through to a+ # read of cached data.+ body: dict = {}+ try:+ body = trigger_resp.json()+ except ValueError:+ pass+ code_desc = str(body.get("codeDescription") or "").upper()+ logger.info(+ "Pluggy refresh rejected for item %s (code=%s): %s",+ item_id,+ code_desc or "<no code>",+ trigger_resp.text[:200],+ )+ if code_desc in _PLUGGY_REFRESH_USER_ACTION_CODES:+ return "needs_user_action"+ return "failed"+ if trigger_resp.status_code >= 400:+ logger.warning(+ "Pluggy refresh returned %s for item %s: %s",+ trigger_resp.status_code,+ item_id,+ trigger_resp.text[:200],+ )+ return "failed"++ deadline = time.monotonic() + PLUGGY_REFRESH_TIMEOUT_SECONDS+ while time.monotonic() < deadline:+ await asyncio.sleep(PLUGGY_REFRESH_POLL_INTERVAL)+ try:+ status_resp = await client.get(+ f"{PLUGGY_API_BASE}/items/{item_id}", headers=headers+ )+ except httpx.HTTPError:+ continue # transient — retry until deadline+ if status_resp.status_code >= 400:+ logger.warning(+ "Pluggy item poll returned %s for %s",+ status_resp.status_code,+ item_id,+ )+ return "failed"++ item = status_resp.json() or {}+ status = (item.get("status") or "").upper()+ if status == "UPDATING":+ continue+ if status not in _PLUGGY_TERMINAL_STATUSES:+ # Unknown status — be conservative.+ return "failed"+ if status == "UPDATED":+ return "refreshed"+ if status == "WAITING_USER_INPUT":+ return "needs_user_action"+ if status == "LOGIN_ERROR":+ return "needs_user_action"+ # OUTDATED: previous sync failed but credentials were valid.+ # Surfacing this as a hard error would hide otherwise-readable+ # cached data, so treat as a soft failure and read what we have.+ return "failed"++ logger.info(+ "Pluggy refresh for item %s timed out after %ss; "+ "proceeding with cached data",+ item_id,+ PLUGGY_REFRESH_TIMEOUT_SECONDS,+ )+ return "failed"+async def get_holdings(self, credentials: dict) -> list[HoldingData]:"""Fetch investment holdings from Pluggy's /investments endpoint.diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.pyindex 4ec8cc35..fc887bde 100644--- a/backend/app/services/connection_service.py+++ b/backend/app/services/connection_service.py@@ -1074,6 +1074,7 @@ async def sync_connection(connection_id: uuid.UUID,workspace_id: uuid.UUID,user_id: uuid.UUID,+ trigger_provider_refresh: bool = False,) -> tuple[BankConnection, int]:connection = await get_connection(session, connection_id, workspace_id)if not connection:@@ -1091,6 +1092,24 @@ async def sync_connection(credentials = await provider.refresh_credentials(connection.credentials)connection.credentials = credentials+ # When the caller asks for fresh data (typically a user-initiated+ # manual sync), ask the provider to pull from the bank before we+ # read. Providers that don't expose an on-demand refresh return+ # "skipped" via the default implementation and we proceed normally.+ if trigger_provider_refresh:+ outcome = await provider.trigger_refresh(credentials)+ if outcome == "needs_user_action":+ # Surfacing reconnect immediately is better than silently+ # reading stale data the user knows is stale.+ connection.status = "error"+ await session.commit()+ raise RuntimeError(+ "Provider needs the user to reconnect before fetching fresh data"+ )+ # "refreshed", "skipped", or "failed" all fall through to a read.+ # On "failed" we read whatever cached copy the provider has —+ # better than aborting the entire sync over a transient hiccup.+# Update accountsuser = await session.get(User, user_id)user_currency = user.primary_currency if user else get_settings().default_currencydiff --git a/backend/tests/test_providers_pluggy_trigger_refresh.py b/backend/tests/test_providers_pluggy_trigger_refresh.pynew file mode 100644index 00000000..c7de17ec--- /dev/null+++ b/backend/tests/test_providers_pluggy_trigger_refresh.py@@ -0,0 +1,231 @@+"""Tests for ``PluggyProvider.trigger_refresh``.++Pluggy's auto-sync only runs once per day, so on a user-initiated manual sync+we ask Pluggy to pull fresh data from the bank first. These tests cover the+state machine around ``PATCH /items/{id}`` + polling ``GET /items/{id}``.+"""++from unittest.mock import AsyncMock, MagicMock, patch++import httpx+import pytest++from app.providers import pluggy as pluggy_module+from app.providers.pluggy import PluggyProvider+++def _http_response(status_code: int, json_body: dict | None = None, text: str = "") -> MagicMock:+ resp = MagicMock()+ resp.status_code = status_code+ resp.json = MagicMock(return_value=json_body or {})+ resp.text = text+ return resp+++def _client_with(patch_resp: MagicMock, get_responses: list[MagicMock]) -> MagicMock:+ """Build a MagicMock AsyncClient where PATCH returns ``patch_resp`` and+ successive GETs walk through ``get_responses``."""+ client = MagicMock()+ client.patch = AsyncMock(return_value=patch_resp)+ client.get = AsyncMock(side_effect=get_responses)+ client.__aenter__ = AsyncMock(return_value=client)+ client.__aexit__ = AsyncMock(return_value=None)+ return client+++async def _run(client: MagicMock) -> str:+ provider = PluggyProvider()+ with patch.object(+ PluggyProvider, "_headers", new=AsyncMock(return_value={"X-API-KEY": "k"})+ ), patch("app.providers.pluggy.httpx.AsyncClient", return_value=client), patch(+ "app.providers.pluggy.asyncio.sleep", new=AsyncMock(return_value=None)+ ):+ return await provider.trigger_refresh({"item_id": "item-1"})+++async def test_refresh_happy_path_returns_refreshed():+ """PATCH 200 → poll shows UPDATING → UPDATED → "refreshed"."""+ patch_resp = _http_response(200, {})+ client = _client_with(+ patch_resp,+ [+ _http_response(200, {"status": "UPDATING"}),+ _http_response(200, {"status": "UPDATED", "executionStatus": "SUCCESS"}),+ ],+ )+ assert await _run(client) == "refreshed"+++async def test_refresh_missing_item_id_skipped():+ """Connections without an item_id (non-Pluggy, malformed) skip refresh."""+ provider = PluggyProvider()+ assert await provider.trigger_refresh({}) == "skipped"+ assert await provider.trigger_refresh(None) == "skipped" # type: ignore[arg-type]+++async def test_refresh_400_mfa_code_signals_user_action_needed():+ """Pluggy 400 with an MFA-related codeDescription → user must reconnect+ via the widget so the new MFA token can be entered."""+ client = _client_with(+ _http_response(+ 400,+ {+ "code": 400,+ "codeDescription": "MFA_PARAMERTER_WAS_ALREADY_USED_ERROR",+ "message": "MFA parameter has to be updated from last execution",+ },+ ),+ [],+ )+ assert await _run(client) == "needs_user_action"+++async def test_refresh_400_meupluggy_is_soft_failure():+ """Items created via MeuPluggy return ``"MeuPluggy item cant be updated"``+ when we PATCH them. Treat as a soft failure — reconnect won't help."""+ client = _client_with(+ _http_response(+ 400,+ {+ "code": 400,+ "message": "MeuPluggy item cant be updated",+ "errorId": "abc",+ },+ ),+ [],+ )+ assert await _run(client) == "failed"+++async def test_refresh_400_unknown_code_is_soft_failure():+ """Defensive: 400 with no codeDescription → assume transient, read cached."""+ client = _client_with(+ _http_response(400, {"code": 400, "message": "Something else"}),+ [],+ )+ assert await _run(client) == "failed"+++async def test_refresh_waiting_user_input_signals_user_action_needed():+ """Item enters WAITING_USER_INPUT after PATCH — surface so user reconnects."""+ client = _client_with(+ _http_response(200, {}),+ [_http_response(200, {"status": "WAITING_USER_INPUT"})],+ )+ assert await _run(client) == "needs_user_action"+++async def test_refresh_login_error_signals_user_action_needed():+ """LOGIN_ERROR → credentials no longer valid; user must reconnect."""+ client = _client_with(+ _http_response(200, {}),+ [_http_response(200, {"status": "LOGIN_ERROR"})],+ )+ assert await _run(client) == "needs_user_action"+++async def test_refresh_outdated_treats_as_failed():+ """OUTDATED is a soft failure — credentials were valid but the last+ execution errored. Reading cached data is still useful, so don't punish+ the user with a reconnect prompt."""+ client = _client_with(+ _http_response(200, {}),+ [_http_response(200, {"status": "OUTDATED", "executionStatus": "ERROR"})],+ )+ assert await _run(client) == "failed"+++async def test_refresh_unknown_status_treats_as_failed():+ """Defensive against Pluggy adding new statuses we don't know about."""+ client = _client_with(+ _http_response(200, {}),+ [_http_response(200, {"status": "SOMETHING_NEW"})],+ )+ assert await _run(client) == "failed"+++async def test_refresh_patch_http_error_returns_failed():+ """Network blip on the PATCH — proceed with cached data."""+ client = MagicMock()+ client.patch = AsyncMock(side_effect=httpx.HTTPError("boom"))+ client.__aenter__ = AsyncMock(return_value=client)+ client.__aexit__ = AsyncMock(return_value=None)+ provider = PluggyProvider()+ with patch.object(+ PluggyProvider, "_headers", new=AsyncMock(return_value={"X-API-KEY": "k"})+ ), patch("app.providers.pluggy.httpx.AsyncClient", return_value=client):+ assert await provider.trigger_refresh({"item_id": "item-1"}) == "failed"+++async def test_refresh_poll_eventually_times_out():+ """Item stays UPDATING past the deadline → "failed", caller reads stale data."""+ # Patch the deadline to fire on the first iteration.+ patch_resp = _http_response(200, {})+ client = _client_with(+ patch_resp,+ [_http_response(200, {"status": "UPDATING"})] * 10,+ )+ provider = PluggyProvider()+ monotonic_values = iter([0.0, 0.0, 999.0]) # before patch, before sleep, after sleep++ def fake_monotonic() -> float:+ try:+ return next(monotonic_values)+ except StopIteration:+ return 999.0++ with patch.object(+ PluggyProvider, "_headers", new=AsyncMock(return_value={"X-API-KEY": "k"})+ ), patch("app.providers.pluggy.httpx.AsyncClient", return_value=client), patch(+ "app.providers.pluggy.asyncio.sleep", new=AsyncMock(return_value=None)+ ), patch("app.providers.pluggy.time.monotonic", side_effect=fake_monotonic):+ assert await provider.trigger_refresh({"item_id": "item-1"}) == "failed"+++async def test_default_trigger_refresh_returns_skipped():+ """Providers that don't override get the no-op default."""+ from app.providers.base import BankProvider++ class _Stub(BankProvider):+ name = "stub"+ flow_type = "oauth"++ async def get_oauth_url(self, *a, **kw): # type: ignore[override]+ return ""++ async def handle_oauth_callback(self, code): # type: ignore[override]+ raise NotImplementedError++ async def get_accounts(self, credentials): # type: ignore[override]+ return []++ async def get_transactions(self, *a, **kw): # type: ignore[override]+ return []++ async def refresh_credentials(self, credentials): # type: ignore[override]+ return credentials++ assert await _Stub().trigger_refresh({}) == "skipped"+++# --- guard: existing pluggy module wiring is what the tests assume ---+++def test_pluggy_terminal_statuses_cover_expected_values():+ """Sanity-check the constant the implementation polls against."""+ assert "UPDATED" in pluggy_module._PLUGGY_TERMINAL_STATUSES+ assert "WAITING_USER_INPUT" in pluggy_module._PLUGGY_TERMINAL_STATUSES+ assert "LOGIN_ERROR" in pluggy_module._PLUGGY_TERMINAL_STATUSES+ assert "OUTDATED" in pluggy_module._PLUGGY_TERMINAL_STATUSES