agentmux_srv_core/identity/
sign_in_watch.rs1use std::collections::{HashMap, HashSet};
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17use std::time::Duration;
18
19use tokio::sync::broadcast::error::{RecvError, TryRecvError};
20
21use crate::backend::fs_watch::{FsWatchEventKind, FsWatchPool, Subscription};
22use crate::backend::providers::resolve_provider_alias;
23use crate::backend::storage::store::{SecretRef, Store};
24use crate::identity::resolver::{probe_oauth_status, sign_in_file};
25
26const RECONCILE: Duration = Duration::from_secs(15);
28
29const SETTLE: Duration = Duration::from_millis(150);
31
32struct Followed {
34 provider: String,
35 dir: String,
36 subscription: Subscription,
37}
38
39fn normal(path: &Path) -> PathBuf {
41 let canonical_parent = path.parent().and_then(|p| p.canonicalize().ok());
42 match (canonical_parent, path.file_name()) {
43 (Some(parent), Some(name)) => parent.join(name),
44 _ => path.to_path_buf(),
45 }
46}
47
48fn wanted(accounts: &Store) -> HashMap<PathBuf, (String, String)> {
50 let mut out = HashMap::new();
51 for account in accounts.identity_list(None).unwrap_or_default() {
52 let SecretRef::OAuthConfigDir { dir } = &account.secret_ref else { continue };
53 let provider = resolve_provider_alias(&account.provider).to_string();
54 if let Some(file) = sign_in_file(&provider, Path::new(dir)) {
55 out.insert(normal(&file), (provider, dir.clone()));
56 }
57 }
58 out
59}
60
61fn reconcile(pool: &Arc<FsWatchPool>, wanted: HashMap<PathBuf, (String, String)>, followed: &mut HashMap<PathBuf, Followed>) {
63 let gone: Vec<PathBuf> = followed.keys().filter(|file| !wanted.contains_key(*file)).cloned().collect();
64 for file in gone {
65 if let Some(f) = followed.remove(&file) {
66 pool.unsubscribe(f.subscription);
67 }
68 }
69 for (file, (provider, dir)) in wanted {
70 followed.entry(file.clone()).or_insert_with(|| Followed { subscription: pool.subscribe_file(&file), provider, dir });
71 }
72}
73
74async fn look(files: HashSet<PathBuf>, followed: &HashMap<PathBuf, Followed>) {
76 let looks: Vec<(String, String)> = files.iter().filter_map(|f| followed.get(f)).map(|f| (f.provider.clone(), f.dir.clone())).collect();
77 let _ = tokio::task::spawn_blocking(move || {
78 let now = agentmux_common::time::now_ms();
79 for (provider, dir) in looks {
80 probe_oauth_status(&provider, &dir, now);
81 }
82 })
83 .await;
84}
85
86async fn run(pool: Arc<FsWatchPool>, accounts: Arc<Store>) {
87 let mut events = pool.events();
89 let mut followed: HashMap<PathBuf, Followed> = HashMap::new();
90 reconcile(&pool, wanted(&accounts), &mut followed);
91 let mut tick = tokio::time::interval(RECONCILE);
92 tick.tick().await;
93 loop {
94 let mut changed: HashSet<PathBuf> = HashSet::new();
95 tokio::select! {
96 _ = tick.tick() => {
97 let accounts = accounts.clone();
98 if let Ok(now_wanted) = tokio::task::spawn_blocking(move || wanted(&accounts)).await {
99 reconcile(&pool, now_wanted, &mut followed);
100 }
101 continue;
102 }
103 event = events.recv() => match event {
104 Ok(e) if matches!(e.kind, FsWatchEventKind::Created | FsWatchEventKind::Modified | FsWatchEventKind::Other) => {
105 changed.insert(normal(&e.path));
106 }
107 Ok(_) => continue,
108 Err(RecvError::Lagged(_)) => changed.extend(followed.keys().cloned()),
109 Err(RecvError::Closed) => break,
110 },
111 }
112 tokio::time::sleep(SETTLE).await;
114 loop {
115 match events.try_recv() {
116 Ok(e) => {
117 changed.insert(normal(&e.path));
118 }
119 Err(TryRecvError::Lagged(_)) => changed.extend(followed.keys().cloned()),
120 Err(_) => break,
121 }
122 }
123 changed.retain(|file| followed.contains_key(file));
124 if !changed.is_empty() {
125 look(changed, &followed).await;
126 }
127 }
128}
129
130pub fn start(pool: Arc<FsWatchPool>, accounts: Arc<Store>) {
132 tokio::spawn(run(pool, accounts));
133}
134
135#[cfg(test)]
136#[path = "sign_in_watch_tests.rs"]
137mod tests;