BlueGit

ict rusty-teams

Files

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

avatars.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
avatars.rs 5.9 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
79 .chunks(AVATAR_BATCH)
80 .chain(people.chunks(AVATAR_BATCH))
81 {
82 let photos = match chunk.first() {
83 Some(key) if key.starts_with(TEAM_AVATAR_PREFIX) => {
84 let team_ids: Vec<String> = chunk
85 .iter()
86 .map(|key| key.trim_start_matches(TEAM_AVATAR_PREFIX).to_owned())
87 .collect();
88 self.remote.team_photos(&team_ids).await
89 }
90 _ => self.remote.user_photos(chunk).await,
91 };
92 let photos = match photos {
93 Ok(photos) => photos,
94 Err(error) => {
95 first_error.get_or_insert(error);
96 continue;
97 }
98 };
99 let mut changed = Vec::new();
100 for (user_id, photo) in chunk.iter().zip(photos) {
101 let (bytes, content_type) = match photo {
102 Ok(Some(photo)) => (Some(photo.bytes), photo.content_type),
103 Ok(None) => (None, String::new()),
104 Err(error) => {
105 first_error.get_or_insert(error);
106 continue;
107 }
108 };
109 fetched_any = true;
110 if bytes.is_some() {
111 changed.push(user_id.clone());
112 }
113 self.store.upsert_avatar(&AvatarRecord {
114 user_id: user_id.clone(),
115 bytes,
116 content_type,
117 fetched_at: Utc::now(),
118 })?;
119 }
120 if !changed.is_empty() {
121 let _ = self
122 .events
123 .send(CoreEvent::AvatarsChanged { user_ids: changed });
124 }
125 }
126 match first_error {
127 Some(error) if !fetched_any => Err(error),
128 Some(error) => {
129 self.report(format!("some avatars could not be fetched: {error}"));
130 Ok(())
131 }
132 None => Ok(()),
133 }
134 }
135
136 fn claim_avatar_ids(&self, wanted: Vec<String>) -> Vec<String> {
137 let mut in_flight = self
138 .avatars_in_flight
139 .lock()
140 .unwrap_or_else(|poisoned| poisoned.into_inner());
141 wanted
142 .into_iter()
143 .filter(|user_id| in_flight.insert(user_id.clone()))
144 .collect()
145 }
146
147 fn release_avatar_ids(&self, claimed: &[String]) {
148 let mut in_flight = self
149 .avatars_in_flight
150 .lock()
151 .unwrap_or_else(|poisoned| poisoned.into_inner());
152 for user_id in claimed {
153 in_flight.remove(user_id);
154 }
155 }
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 #[test]
163 fn photos_fetched_before_the_larger_rendition_count_as_stale() {
164 let since = DateTime::parse_from_rfc3339(PHOTO_RENDITION_SINCE)
165 .unwrap()
166 .with_timezone(&Utc);
167 assert_eq!(avatar_cutoff(since + Duration::days(1)), since);
168 let later = since + Duration::days(30);
169 assert_eq!(
170 avatar_cutoff(later),
171 later - Duration::days(AVATAR_MAX_AGE_DAYS)
172 );
173 }
174}