|
| 1 | +use std::collections::HashSet; |
| 2 | + |
| 3 | +use arenabuddy_core::{ |
| 4 | + models::{MTGAMatch, MatchData}, |
| 5 | + services::match_service::{GetMatchDataRequest, ListMatchesRequest, match_service_client::MatchServiceClient}, |
| 6 | +}; |
| 7 | +use arenabuddy_data::{ArenabuddyRepository, MatchDB}; |
| 8 | +use tracingx::{error, info}; |
| 9 | + |
| 10 | +use super::auth::{SharedAuthState, needs_refresh, refresh}; |
| 11 | + |
| 12 | +fn attach_token<T>(request: &mut tonic::Request<T>, token: &str) { |
| 13 | + let bearer = format!("Bearer {token}"); |
| 14 | + if let Ok(value) = bearer.parse() { |
| 15 | + request.metadata_mut().insert("authorization", value); |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +async fn current_token(auth_state: &SharedAuthState, grpc_url: &str) -> Option<String> { |
| 20 | + let mut guard = auth_state.lock().await; |
| 21 | + let state = guard.as_ref()?; |
| 22 | + |
| 23 | + if needs_refresh(state) { |
| 24 | + info!("Access token expiring soon, refreshing for sync"); |
| 25 | + match refresh(grpc_url, state).await { |
| 26 | + Ok(new_state) => { |
| 27 | + let token = new_state.token.clone(); |
| 28 | + *guard = Some(new_state); |
| 29 | + return Some(token); |
| 30 | + } |
| 31 | + Err(e) => { |
| 32 | + error!("Failed to refresh token for sync: {e}"); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + Some(state.token.clone()) |
| 38 | +} |
| 39 | + |
| 40 | +/// Sync matches from the server into the local database. |
| 41 | +/// |
| 42 | +/// Fetches the server's match list for the authenticated user, compares |
| 43 | +/// against local matches, and downloads any that are missing locally. |
| 44 | +/// |
| 45 | +/// Returns the number of newly synced matches. |
| 46 | +/// |
| 47 | +/// # Errors |
| 48 | +/// |
| 49 | +/// Returns an error if the user is not authenticated, the gRPC connection |
| 50 | +/// fails, or the server returns an error from `ListMatches`. |
| 51 | +pub async fn sync_matches( |
| 52 | + db: &MatchDB, |
| 53 | + auth_state: &SharedAuthState, |
| 54 | +) -> Result<usize, Box<dyn std::error::Error + Send + Sync>> { |
| 55 | + let grpc_url = super::paths::grpc_url(); |
| 56 | + |
| 57 | + let token = current_token(auth_state, &grpc_url).await.ok_or("not authenticated")?; |
| 58 | + |
| 59 | + let mut client = MatchServiceClient::connect(grpc_url).await?; |
| 60 | + |
| 61 | + // Get server match list |
| 62 | + let mut request = tonic::Request::new(ListMatchesRequest {}); |
| 63 | + attach_token(&mut request, &token); |
| 64 | + |
| 65 | + let server_matches = client.list_matches(request).await?.into_inner().matches; |
| 66 | + info!("Server has {} matches for this user", server_matches.len()); |
| 67 | + |
| 68 | + // Get local match IDs |
| 69 | + let local_ids: HashSet<_> = db |
| 70 | + .list_matches(None) |
| 71 | + .await |
| 72 | + .map_err(|e| e.to_string())? |
| 73 | + .iter() |
| 74 | + .map(|m| m.id().to_owned()) |
| 75 | + .collect(); |
| 76 | + |
| 77 | + // Find matches we're missing locally |
| 78 | + let missing: Vec<_> = server_matches |
| 79 | + .iter() |
| 80 | + .filter(|m| !local_ids.contains(m.id.as_str())) |
| 81 | + .collect(); |
| 82 | + |
| 83 | + if missing.is_empty() { |
| 84 | + info!("Local database is up to date"); |
| 85 | + return Ok(0); |
| 86 | + } |
| 87 | + |
| 88 | + info!("Syncing {} new matches from server", missing.len()); |
| 89 | + |
| 90 | + let mut synced = 0; |
| 91 | + for server_match in &missing { |
| 92 | + let mut request = tonic::Request::new(GetMatchDataRequest { |
| 93 | + match_id: server_match.id.clone(), |
| 94 | + }); |
| 95 | + attach_token(&mut request, &token); |
| 96 | + |
| 97 | + let response = match client.get_match_data(request).await { |
| 98 | + Ok(r) => r.into_inner(), |
| 99 | + Err(e) => { |
| 100 | + error!("Failed to fetch match {}: {e}", server_match.id); |
| 101 | + continue; |
| 102 | + } |
| 103 | + }; |
| 104 | + |
| 105 | + let Some(match_data_proto) = response.match_data else { |
| 106 | + error!("Server returned empty match_data for {}", server_match.id); |
| 107 | + continue; |
| 108 | + }; |
| 109 | + |
| 110 | + let match_data: MatchData = match (&match_data_proto).try_into() { |
| 111 | + Ok(data) => data, |
| 112 | + Err(e) => { |
| 113 | + error!("Failed to convert match {}: {e}", server_match.id); |
| 114 | + continue; |
| 115 | + } |
| 116 | + }; |
| 117 | + |
| 118 | + if let Err(e) = db |
| 119 | + .upsert_match_data( |
| 120 | + &match_data.mtga_match, |
| 121 | + &match_data.decks, |
| 122 | + &match_data.mulligans, |
| 123 | + &match_data.results, |
| 124 | + &match_data.opponent_deck.cards, |
| 125 | + &match_data.event_logs, |
| 126 | + None, |
| 127 | + ) |
| 128 | + .await |
| 129 | + { |
| 130 | + error!("Failed to write match {} locally: {e}", server_match.id); |
| 131 | + continue; |
| 132 | + } |
| 133 | + |
| 134 | + synced += 1; |
| 135 | + } |
| 136 | + |
| 137 | + info!("Synced {synced}/{} matches from server", missing.len()); |
| 138 | + Ok(synced) |
| 139 | +} |
0 commit comments