Buckets:
AnonymousSpottedToad/human_verified_bucket / codebase /python /elisiariocouto_leggen /leggen /services /sync_service.py
| import asyncio | |
| from datetime import UTC, datetime, timedelta | |
| from loguru import logger | |
| from leggen.api.models.sync import SyncResult, SyncStatus | |
| from leggen.errors import ConflictError, describe_exception | |
| from leggen.repositories import ( | |
| AccountRepository, | |
| BalanceRepository, | |
| SessionRepository, | |
| SyncRepository, | |
| TransactionRepository, | |
| run_migrations, | |
| ) | |
| from leggen.services.data_processors import ( | |
| enrich_account_details, | |
| merge_account_metadata_into_balances, | |
| process_transactions, | |
| transform_to_database_format, | |
| ) | |
| from leggen.services.enablebanking_service import EnableBankingService | |
| from leggen.services.notification_service import NotificationService | |
| # Constants for notification | |
| EXPIRED_DAYS_LEFT = 0 | |
| EXPIRY_WARNING_THRESHOLDS = [7, 3, 1] | |
| class SyncAlreadyRunningError(ConflictError): | |
| """Raised when a sync is triggered while another one is still running.""" | |
| code = "SYNC_ALREADY_RUNNING" | |
| class SyncService: | |
| # Class-level so the "already running" guard and reported status hold | |
| # across all instances — only one sync may run per process. | |
| _sync_lock = asyncio.Lock() | |
| _sync_status = SyncStatus(is_running=False) | |
| def __init__(self): | |
| self.enablebanking = EnableBankingService() | |
| self.notifications = NotificationService() | |
| # Ensure the schema is present and current (for CLI use outside the | |
| # FastAPI lifespan, which migrates at startup) | |
| run_migrations() | |
| # Repositories | |
| self.accounts = AccountRepository() | |
| self.balances = BalanceRepository() | |
| self.transactions = TransactionRepository() | |
| self.sync = SyncRepository() | |
| self.session_repo = SessionRepository() | |
| async def get_sync_status(self) -> SyncStatus: | |
| """Get current sync status""" | |
| return self._sync_status | |
| async def sync_all_accounts( | |
| self, | |
| full_sync: bool = False, | |
| trigger_type: str = "manual", | |
| account_ids: list[str] | None = None, | |
| ) -> SyncResult: | |
| """Sync connected accounts, optionally restricted to account_ids. | |
| account_ids accepts the IDs returned by GET /accounts (IBAN-based | |
| database IDs) as well as EnableBanking account UIDs. | |
| """ | |
| if self._sync_lock.locked(): | |
| raise SyncAlreadyRunningError("Sync is already running") | |
| await self._sync_lock.acquire() | |
| start_time = datetime.now(UTC) | |
| self._sync_status.is_running = True | |
| self._sync_status.errors = [] | |
| accounts_processed = 0 | |
| transactions_added = 0 | |
| transactions_updated = 0 | |
| balances_updated = 0 | |
| errors = [] | |
| warnings: list[str] = [] | |
| logs = [f"Sync started at {start_time.isoformat()}"] | |
| # Initialize sync operation record | |
| sync_operation = { | |
| "started_at": start_time.isoformat(), | |
| "trigger_type": trigger_type, | |
| "accounts_processed": 0, | |
| "transactions_added": 0, | |
| "transactions_updated": 0, | |
| "balances_updated": 0, | |
| "errors": [], | |
| "warnings": [], | |
| "logs": logs, | |
| } | |
| operation_id = None | |
| try: | |
| logger.info("Starting sync of all accounts") | |
| logs.append("Starting sync of all accounts") | |
| # Get all sessions from local DB | |
| sessions = self.session_repo.get_sessions() | |
| # Build account-to-session mapping. Session rows store the raw | |
| # EnableBanking account objects, whose IBAN (when present) is the | |
| # database account ID — keep it for the per-account filter below. | |
| account_session_map = {} | |
| account_iban_map: dict = {} | |
| all_account_ids = set() | |
| for session in sessions: | |
| session_accounts = session.get("accounts", []) or [] | |
| for account in session_accounts: | |
| if isinstance(account, dict): | |
| uid = account.get("uid") or account.get("id") | |
| iban = (account.get("account_id") or {}).get("iban") | |
| else: | |
| uid = account | |
| iban = None | |
| if uid: | |
| all_account_ids.add(uid) | |
| account_session_map[uid] = session | |
| account_iban_map[uid] = iban | |
| # Skip deleted accounts | |
| deleted_ids = { | |
| a["id"] | |
| for a in self.accounts.get_accounts(include_deleted=True) | |
| if a.get("status") == "DELETED" | |
| } | |
| all_account_ids -= deleted_ids | |
| # Per-account sync: keep accounts whose UID or IBAN was requested. | |
| # A UID with no locally known IBAN can't be ruled out yet — keep it | |
| # and let the in-loop check (which resolves the IBAN via account | |
| # details) decide. | |
| requested_ids = set(account_ids) if account_ids else None | |
| if requested_ids: | |
| all_account_ids = { | |
| uid | |
| for uid in all_account_ids | |
| if uid in requested_ids | |
| or account_iban_map.get(uid) in requested_ids | |
| or account_iban_map.get(uid) is None | |
| } | |
| logs.append(f"Per-account sync requested for: {sorted(requested_ids)}") | |
| self._sync_status.total_accounts = len(all_account_ids) | |
| logs.append(f"Found {len(all_account_ids)} accounts to sync") | |
| date_from: str | None = None | |
| if not full_sync: | |
| date_from = (datetime.now(UTC) - timedelta(days=30)).strftime( | |
| "%Y-%m-%d" | |
| ) | |
| logs.append(f"Fetching transactions from {date_from}") | |
| else: | |
| logs.append("Full sync: fetching all transactions") | |
| # Check for expired sessions | |
| await self._check_session_expiry(sessions) | |
| # Process each account | |
| for account_id in all_account_ids: | |
| try: | |
| session = account_session_map[account_id] | |
| # Get account details from EnableBanking | |
| details = await self.enablebanking.get_account_details(account_id) | |
| # Use IBAN as stored ID to prevent duplicates across providers | |
| stored_id = details.get("account_id", {}).get("iban") or account_id | |
| # Authoritative per-account filter: accounts kept only | |
| # because their IBAN wasn't known locally are resolved now | |
| if ( | |
| requested_ids | |
| and account_id not in requested_ids | |
| and stored_id not in requested_ids | |
| ): | |
| logger.debug( | |
| f"Skipping account {account_id}: not in requested accounts" | |
| ) | |
| continue | |
| # Map to internal format | |
| account_details = { | |
| "id": stored_id, | |
| "institution_id": session["aspsp_name"], | |
| "status": "READY", | |
| "iban": details.get("account_id", {}).get("iban"), | |
| "name": details.get("name"), | |
| "currency": details.get("currency"), | |
| "created": session.get("created_at"), | |
| } | |
| # Get balances | |
| balances = await self.enablebanking.get_account_balances(account_id) | |
| # Enrich and persist account details | |
| if account_details and balances: | |
| enriched_account_details = await enrich_account_details( | |
| account_details, | |
| balances, | |
| aspsp_country=session.get("aspsp_country"), | |
| enablebanking_service=self.enablebanking, | |
| ) | |
| self.accounts.persist(enriched_account_details) | |
| balances_with_account_info = ( | |
| merge_account_metadata_into_balances( | |
| balances, enriched_account_details | |
| ) | |
| ) | |
| balance_rows = transform_to_database_format( | |
| stored_id, balances_with_account_info | |
| ) | |
| self.balances.persist(stored_id, balance_rows) | |
| balances_updated += len(balances.get("balances", [])) | |
| elif account_details: | |
| self.accounts.persist(account_details) | |
| # Get and save transactions | |
| transactions = await self.enablebanking.get_account_transactions( | |
| account_id, date_from=date_from | |
| ) | |
| if transactions: | |
| processed_transactions, skipped_count = process_transactions( | |
| stored_id, account_details, transactions | |
| ) | |
| if skipped_count: | |
| warnings.append( | |
| f"{skipped_count} transaction(s) skipped for account " | |
| f"{account_id} — see server logs" | |
| ) | |
| new_transactions, updated_count = self.transactions.persist( | |
| stored_id, processed_transactions | |
| ) | |
| transactions_added += len(new_transactions) | |
| transactions_updated += updated_count | |
| # Send notifications for new transactions | |
| if new_transactions: | |
| await self.notifications.send_transaction_notifications( | |
| new_transactions | |
| ) | |
| accounts_processed += 1 | |
| self._sync_status.accounts_synced = accounts_processed | |
| logger.info(f"Synced account {account_id} successfully") | |
| logs.append(f"Synced account {account_id} successfully") | |
| except Exception as e: | |
| error_msg = ( | |
| f"Failed to sync account {account_id}: {describe_exception(e)}" | |
| ) | |
| errors.append(error_msg) | |
| logger.error(error_msg) | |
| logs.append(error_msg) | |
| # Send notification for account sync failure | |
| try: | |
| await self.notifications.send_sync_failure_notification( | |
| { | |
| "account_id": account_id, | |
| "error": error_msg, | |
| "type": "account_sync_failure", | |
| } | |
| ) | |
| except Exception as notify_err: | |
| logger.error( | |
| f"Failed to send sync failure notification: {notify_err}" | |
| ) | |
| end_time = datetime.now(UTC) | |
| duration = (end_time - start_time).total_seconds() | |
| self._sync_status.last_sync = end_time | |
| # Update sync operation with final results | |
| sync_operation.update( | |
| { | |
| "completed_at": end_time.isoformat(), | |
| "success": len(errors) == 0, | |
| "accounts_processed": accounts_processed, | |
| "transactions_added": transactions_added, | |
| "transactions_updated": transactions_updated, | |
| "balances_updated": balances_updated, | |
| "duration_seconds": duration, | |
| "errors": errors, | |
| "warnings": warnings, | |
| "logs": logs, | |
| } | |
| ) | |
| # Persist sync operation to database | |
| try: | |
| operation_id = self.sync.persist(sync_operation) | |
| logger.debug(f"Saved sync operation with ID: {operation_id}") | |
| except Exception as e: | |
| logger.error(f"Failed to persist sync operation: {e}") | |
| result = SyncResult( | |
| success=len(errors) == 0, | |
| accounts_processed=accounts_processed, | |
| transactions_added=transactions_added, | |
| transactions_updated=transactions_updated, | |
| balances_updated=balances_updated, | |
| duration_seconds=duration, | |
| errors=errors, | |
| warnings=warnings, | |
| started_at=start_time, | |
| completed_at=end_time, | |
| ) | |
| logger.info( | |
| f"Sync completed: {accounts_processed} accounts, {transactions_added} new transactions" | |
| ) | |
| logs.append( | |
| f"Sync completed: {accounts_processed} accounts, {transactions_added} new transactions" | |
| ) | |
| return result | |
| except Exception as e: | |
| error_msg = f"Sync failed: {describe_exception(e)}" | |
| errors.append(error_msg) | |
| logs.append(error_msg) | |
| logger.error(error_msg) | |
| # Save failed sync operation | |
| end_time = datetime.now(UTC) | |
| duration = (end_time - start_time).total_seconds() | |
| sync_operation.update( | |
| { | |
| "completed_at": end_time.isoformat(), | |
| "success": False, | |
| "accounts_processed": accounts_processed, | |
| "transactions_added": transactions_added, | |
| "transactions_updated": transactions_updated, | |
| "balances_updated": balances_updated, | |
| "duration_seconds": duration, | |
| "errors": errors, | |
| "warnings": warnings, | |
| "logs": logs, | |
| } | |
| ) | |
| try: | |
| operation_id = self.sync.persist(sync_operation) | |
| logger.debug(f"Saved failed sync operation with ID: {operation_id}") | |
| except Exception as persist_error: | |
| logger.error( | |
| f"Failed to persist failed sync operation: {persist_error}" | |
| ) | |
| raise | |
| finally: | |
| self._sync_status.is_running = False | |
| self._sync_lock.release() | |
| async def _check_session_expiry(self, sessions: list[dict]) -> None: | |
| """Check sessions for expiry and send notifications. | |
| Sends a notification once when a session expires, and once per warning | |
| threshold (7, 3, 1 days) when the remaining validity crosses it — | |
| sent state is persisted so syncs don't re-notify every run. | |
| Args: | |
| sessions: List of session dictionaries to check | |
| """ | |
| now = datetime.now(UTC) | |
| for session in sessions: | |
| session_id = session.get("session_id", "unknown") | |
| aspsp_name = session.get("aspsp_name", "unknown") | |
| valid_until_str = session.get("valid_until") | |
| if not valid_until_str: | |
| continue | |
| try: | |
| valid_until = datetime.fromisoformat(valid_until_str) | |
| except (ValueError, TypeError): | |
| logger.warning( | |
| f"Session {session_id} has unparseable valid_until: {valid_until_str!r}" | |
| ) | |
| continue | |
| # Timestamps stored without an offset are UTC | |
| if valid_until.tzinfo is None: | |
| valid_until = valid_until.replace(tzinfo=UTC) | |
| if valid_until < now: | |
| status = "expired" | |
| days_left = EXPIRED_DAYS_LEFT | |
| threshold = EXPIRED_DAYS_LEFT | |
| else: | |
| days_left = (valid_until - now).days | |
| crossed = [t for t in EXPIRY_WARNING_THRESHOLDS if days_left <= t] | |
| if not crossed: | |
| continue | |
| status = "expiring" | |
| # Only the most urgent crossed threshold fires; skipped | |
| # thresholds (e.g. sync was down at day 7) don't pile up. | |
| threshold = min(crossed) | |
| if self.session_repo.was_expiry_notified(session_id, threshold): | |
| continue | |
| log = logger.warning if status == "expired" else logger.info | |
| log( | |
| f"Session {session_id} for {aspsp_name} is {status} " | |
| f"({days_left} day(s) left)" | |
| ) | |
| await self.notifications.send_expiry_notification( | |
| { | |
| "bank": aspsp_name, | |
| "session_id": session_id, | |
| "status": status, | |
| "days_left": days_left, | |
| } | |
| ) | |
| self.session_repo.mark_expiry_notified(session_id, threshold) | |
Xet Storage Details
- Size:
- 17.2 kB
- Xet hash:
- a6d57cc57445c96720614721ece7f8957ba7d0162da26f6a3f9cf3bf1f0035e8
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.