BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / avatars.rs

avatars.rs

avatars.rs 5.8 KiB Download Raw
1use chrono::{DateTime, Duration, Utc};
2use store::{AvatarRecord, is_bot_id};
3
4use crate::engine::SyncEngine;
5use crate::error::Result;
6use crate::events::CoreEvent;
7use crate::remote::Remote;
8
9const AVATAR_MAX_AGE_DAYS: i64 = 7;
10const AVATAR_BATCH: usize = 60;
11const PHOTO_RENDITION_SINCE: &str = "2026-10-17T17:00:00Z";
12const TEAM_AVATAR_PREFIX: &str = "team:";
13
14/// Team pictures share the avatar cache under this key; Teams serves a lettered tile for teams without one.
15pub fn team_avatar_key(team_id: &str) -> String {
16 format!("{TEAM_AVATAR_PREFIX}{team_id}")
17}
18
19fn avatar_cutoff(now: DateTime<Utc>) -> DateTime<Utc> {
20 let since = DateTime::parse_from_rfc3339(PHOTO_RENDITION_SINCE)
21 .map(|since| since.with_timezone(&Utc))
22 .unwrap_or(DateTime::UNIX_EPOCH);
23 (now - Duration::days(AVATAR_MAX_AGE_DAYS)).max(since)
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Avatar {
28 pub bytes: Vec<u8>,
29 pub content_type: String,
30}
31
32impl<R: Remote> SyncEngine<R> {
33 pub fn avatar(&self, user_id: &str) -> Option<Avatar> {
34 let record = self.store.avatar(user_id).ok().flatten()?;
35 Some(Avatar {
36 bytes: record.bytes?,
37 content_type: record.content_type,
38 })
39 }
40
41 pub async fn fetch_avatars(&self, user_ids: &[String]) -> Result<()> {
42 let cutoff = avatar_cutoff(Utc::now());
43 let mut unique = user_ids.to_vec();
44 unique.sort();
45 unique.dedup();
46 let wanted = self.store.avatar_ids_needing_fetch(&unique, cutoff)?;
47 let claimed = self.claim_avatar_ids(wanted);
48 let outcome = self.fetch_claimed_avatars(&claimed).await;
49 self.release_avatar_ids(&claimed);
50 outcome
51 }
52
53 async fn fetch_claimed_avatars(&self, claimed: &[String]) -> Result<()> {
54 let (bots, people): (Vec<String>, Vec<String>) = claimed
55 .iter()
56 .cloned()
57 .partition(|user_id| is_bot_id(user_id));
58 let mut first_error = None;
59 let mut fetched_any = false;
60 if !bots.is_empty() {
61 match self.fetch_bot_icons(&bots).await {
62 Ok(changed) => {
63 fetched_any = true;
64 if !changed.is_empty() {
65 let _ = self
66 .events
67 .send(CoreEvent::AvatarsChanged { user_ids: changed });
68 }
69 }
70 Err(error) => {
71 first_error.get_or_insert(error);
72 }
73 }
74 }
75 let (teams, people): (Vec<String>, Vec<String>) = people
76 .into_iter()
77 .partition(|key| key.starts_with(TEAM_AVATAR_PREFIX));
78 for chunk in teams.chunks(AVATAR_BATCH).chain(people.chunks(AVATAR_BATCH)) {
79 let photos = match chunk.first() {
80 Some(key) if key.starts_with(TEAM_AVATAR_PREFIX) => {
81 let team_ids: Vec<String> = chunk
82 .iter()
83 .map(|key| key.trim_start_matches(TEAM_AVATAR_PREFIX).to_owned())
84 .collect();
85 self.remote.team_photos(&team_ids).await
86 }
87 _ => self.remote.user_photos(chunk).await,
88 };
89 let photos = match photos {
90 Ok(photos) => photos,
91 Err(error) => {
92 first_error.get_or_insert(error);
93 continue;
94 }
95 };
96 let mut changed = Vec::new();
97 for (user_id, photo) in chunk.iter().zip(photos) {
98 let (bytes, content_type) = match photo {
99 Ok(Some(photo)) => (Some(photo.bytes), photo.content_type),
100 Ok(None) => (None, String::new()),
101 Err(error) => {
102 first_error.get_or_insert(error);
103 continue;
104 }
105 };
106 fetched_any = true;
107 if bytes.is_some() {
108 changed.push(user_id.clone());
109 }
110 self.store.upsert_avatar(&AvatarRecord {
111 user_id: user_id.clone(),
112 bytes,
113 content_type,
114 fetched_at: Utc::now(),
115 })?;
116 }
117 if !changed.is_empty() {
118 let _ = self
119 .events
120 .send(CoreEvent::AvatarsChanged { user_ids: changed });
121 }
122 }
123 match first_error {
124 Some(error) if !fetched_any => Err(error),
125 Some(error) => {
126 self.report(format!("some avatars could not be fetched: {error}"));
127 Ok(())
128 }
129 None => Ok(()),
130 }
131 }
132
133 fn claim_avatar_ids(&self, wanted: Vec<String>) -> Vec<String> {
134 let mut in_flight = self
135 .avatars_in_flight
136 .lock()
137 .unwrap_or_else(|poisoned| poisoned.into_inner());
138 wanted
139 .into_iter()
140 .filter(|user_id| in_flight.insert(user_id.clone()))
141 .collect()
142 }
143
144 fn release_avatar_ids(&self, claimed: &[String]) {
145 let mut in_flight = self
146 .avatars_in_flight
147 .lock()
148 .unwrap_or_else(|poisoned| poisoned.into_inner());
149 for user_id in claimed {
150 in_flight.remove(user_id);
151 }
152 }
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158
159 #[test]
160 fn photos_fetched_before_the_larger_rendition_count_as_stale() {
161 let since = DateTime::parse_from_rfc3339(PHOTO_RENDITION_SINCE)
162 .unwrap()
163 .with_timezone(&Utc);
164 assert_eq!(avatar_cutoff(since + Duration::days(1)), since);
165 let later = since + Duration::days(30);
166 assert_eq!(
167 avatar_cutoff(later),
168 later - Duration::days(AVATAR_MAX_AGE_DAYS)
169 );
170 }
171}