1use std::collections::HashMap;
7use serde::Serialize;
8
9pub const OUTCOME_ACCEPTED: u8 = 1;
10pub const OUTCOME_REJECTED_MIME: u8 = 2;
11pub const OUTCOME_SIZE_ONLY: u8 = 3;
14
15pub const STALE_AFTER_SECS: i64 = 4 * 24 * 3600;
18
19#[derive(Clone, Debug, Serialize)]
20pub struct CapabilityEntry {
21 pub mime_type: String,
22 pub is_encrypted: bool,
26 pub outcome: u8, pub max_accepted_size: u64,
28 pub min_rejected_size: Option<u64>,
30 pub updated_at: i64,
31}
32
33fn now_secs() -> i64 {
34 crate::clock::now_secs() as i64
35}
36
37fn norm_url(url: &str) -> String {
38 url.trim().trim_end_matches('/').to_lowercase()
39}
40
41pub fn record_accepted(
50 server_url: &str,
51 mime_type: &str,
52 is_encrypted: bool,
53 size_bytes: u64,
54) -> Result<(), String> {
55 let conn = crate::db::get_write_connection_guard_static()?;
56 let server = norm_url(server_url);
57 let mime = mime_type.to_lowercase();
58 let enc = if is_encrypted { 1i64 } else { 0i64 };
59 let now = now_secs();
60 conn.execute(
61 "INSERT INTO blossom_server_capabilities
62 (server_url, mime_type, is_encrypted, outcome, max_accepted_size, updated_at)
63 VALUES (?1, ?2, ?3, ?4, ?5, ?6)
64 ON CONFLICT(server_url, mime_type, is_encrypted) DO UPDATE SET
65 outcome = ?4,
66 max_accepted_size = MAX(max_accepted_size, ?5),
67 min_rejected_size = CASE
68 WHEN min_rejected_size IS NOT NULL AND min_rejected_size <= ?5
69 THEN NULL
70 ELSE min_rejected_size
71 END,
72 updated_at = ?6",
73 rusqlite::params![server, mime, enc, OUTCOME_ACCEPTED as i64, size_bytes as i64, now],
74 ).map_err(|e| format!("Failed to record accepted capability: {}", e))?;
75 Ok(())
76}
77
78pub fn record_rejected_mime(
81 server_url: &str,
82 mime_type: &str,
83 is_encrypted: bool,
84) -> Result<(), String> {
85 let conn = crate::db::get_write_connection_guard_static()?;
86 let server = norm_url(server_url);
87 let mime = mime_type.to_lowercase();
88 let enc = if is_encrypted { 1i64 } else { 0i64 };
89 let now = now_secs();
90 conn.execute(
91 "INSERT INTO blossom_server_capabilities
92 (server_url, mime_type, is_encrypted, outcome, max_accepted_size, updated_at)
93 VALUES (?1, ?2, ?3, ?4, 0, ?5)
94 ON CONFLICT(server_url, mime_type, is_encrypted) DO UPDATE SET
95 outcome = ?4,
96 updated_at = ?5",
97 rusqlite::params![server, mime, enc, OUTCOME_REJECTED_MIME as i64, now],
98 ).map_err(|e| format!("Failed to record rejected capability: {}", e))?;
99 Ok(())
100}
101
102pub fn record_rejected_size(
107 server_url: &str,
108 mime_type: &str,
109 is_encrypted: bool,
110 size_bytes: u64,
111) -> Result<(), String> {
112 let conn = crate::db::get_write_connection_guard_static()?;
113 let server = norm_url(server_url);
114 let mime = mime_type.to_lowercase();
115 let enc = if is_encrypted { 1i64 } else { 0i64 };
116 let now = now_secs();
117 conn.execute(
120 "INSERT INTO blossom_server_capabilities
121 (server_url, mime_type, is_encrypted, outcome, max_accepted_size, min_rejected_size, updated_at)
122 VALUES (?1, ?2, ?3, ?4, 0, ?5, ?6)
123 ON CONFLICT(server_url, mime_type, is_encrypted) DO UPDATE SET
124 min_rejected_size = MIN(COALESCE(min_rejected_size, ?5), ?5),
125 updated_at = ?6",
126 rusqlite::params![server, mime, enc, OUTCOME_SIZE_ONLY as i64, size_bytes as i64, now],
127 ).map_err(|e| format!("Failed to record size rejection: {}", e))?;
128 Ok(())
129}
130
131pub fn has_fresh_capability_for(server_url: &str, mime_type: &str, is_encrypted: bool) -> bool {
135 let conn = match crate::db::get_db_connection_guard_static() {
136 Ok(c) => c,
137 Err(_) => return false,
138 };
139 let server = norm_url(server_url);
140 let mime = mime_type.to_lowercase();
141 let enc = if is_encrypted { 1i64 } else { 0i64 };
142 let cutoff = now_secs().saturating_sub(STALE_AFTER_SECS);
143 conn.query_row(
144 "SELECT 1 FROM blossom_server_capabilities
145 WHERE server_url = ?1 AND mime_type = ?2 AND is_encrypted = ?3 AND updated_at >= ?4",
146 rusqlite::params![server, mime, enc, cutoff],
147 |_| Ok(()),
148 ).is_ok()
149}
150
151pub fn preflight_redundant(server_url: &str, mime: &str, is_encrypted: bool, size_bytes: u64) -> bool {
155 let info = crate::blossom_info::cached(server_url).and_then(|d| d.accepts_size(size_bytes));
156 let servers = [server_url.to_string()];
157 let Ok(cache) = load_cache_for(&servers, mime, is_encrypted) else { return false };
158 known_to_take(cache.get(&norm_url(server_url)), info, size_bytes)
159}
160
161fn known_to_take(state: Option<&CapabilityState>, info_verdict: Option<bool>, size_bytes: u64) -> bool {
163 info_verdict != Some(false)
164 && matches!(
165 state,
166 Some(st) if st.outcome == OUTCOME_ACCEPTED
167 && size_bytes <= st.max_accepted_size
168 && st.min_rejected_size.is_none_or(|m| size_bytes < m)
169 )
170}
171
172pub fn purge_server(server_url: &str) -> Result<usize, String> {
175 let conn = crate::db::get_write_connection_guard_static()?;
176 let server = norm_url(server_url);
177 let n = conn.execute(
178 "DELETE FROM blossom_server_capabilities WHERE server_url = ?1",
179 rusqlite::params![server],
180 ).map_err(|e| format!("Failed to purge capabilities for {}: {}", server, e))?;
181 Ok(n)
182}
183
184pub fn list_for_server(server_url: &str) -> Result<Vec<CapabilityEntry>, String> {
186 let conn = crate::db::get_db_connection_guard_static()?;
187 let server = norm_url(server_url);
188 let mut stmt = conn.prepare(
189 "SELECT mime_type, is_encrypted, outcome, max_accepted_size, min_rejected_size, updated_at
190 FROM blossom_server_capabilities
191 WHERE server_url = ?1
192 ORDER BY updated_at DESC"
193 ).map_err(|e| format!("Prepare failed: {}", e))?;
194 let rows = stmt.query_map(rusqlite::params![server], |row| {
195 let enc: i64 = row.get(1)?;
196 let min_rej: Option<i64> = row.get(4)?;
197 Ok(CapabilityEntry {
198 mime_type: row.get(0)?,
199 is_encrypted: enc != 0,
200 outcome: row.get::<_, i64>(2)? as u8,
201 max_accepted_size: row.get::<_, i64>(3)? as u64,
202 min_rejected_size: min_rej.map(|v| v as u64),
203 updated_at: row.get(5)?,
204 })
205 }).map_err(|e| format!("Query failed: {}", e))?;
206 let mut out = Vec::new();
207 for entry in rows.flatten() { out.push(entry); }
208 Ok(out)
209}
210
211#[derive(Clone, Copy, Debug, PartialEq)]
217pub struct CapabilityState {
218 pub outcome: u8,
219 pub max_accepted_size: u64,
220 pub min_rejected_size: Option<u64>,
221}
222
223pub fn classify(
232 cache: &HashMap<String, CapabilityState>,
233 verdicts: &HashMap<String, bool>,
234 servers: Vec<String>,
235 size_bytes: u64,
236) -> Vec<String> {
237 let mut informed_yes = Vec::new();
238 let mut known_good = Vec::new();
239 let mut unknown = Vec::new();
240 let mut too_large = Vec::new();
241 let mut mime_rejected = Vec::new();
242 let mut informed_no = Vec::new();
243 for s in servers {
244 let key = norm_url(&s);
245 match verdicts.get(&key) {
246 Some(true) => { informed_yes.push(s); continue; }
247 Some(false) => { informed_no.push(s); continue; }
248 None => {}
249 }
250 match cache.get(&key) {
251 Some(st) if st.outcome == OUTCOME_REJECTED_MIME => mime_rejected.push(s),
252 Some(st) => {
253 if let Some(min_rej) = st.min_rejected_size {
255 if size_bytes >= min_rej {
256 too_large.push(s);
257 continue;
258 }
259 }
260 if size_bytes <= st.max_accepted_size {
261 known_good.push(s);
262 } else {
263 unknown.push(s);
264 }
265 }
266 None => unknown.push(s),
267 }
268 }
269 informed_yes.extend(known_good);
270 informed_yes.extend(unknown);
271 informed_yes.extend(too_large);
272 informed_yes.extend(mime_rejected);
273 informed_yes.extend(informed_no);
274 informed_yes
275}
276
277fn info_verdicts(servers: &[String], size_bytes: u64) -> HashMap<String, bool> {
280 servers
281 .iter()
282 .filter_map(|s| {
283 let verdict = crate::blossom_info::cached(s)?.accepts_size(size_bytes)?;
284 Some((norm_url(s), verdict))
285 })
286 .collect()
287}
288
289pub fn rank_servers(servers: Vec<String>, mime: &str, is_encrypted: bool, size_bytes: u64) -> Vec<String> {
291 if servers.is_empty() { return servers; }
292 let cache = load_cache_for(&servers, mime, is_encrypted).unwrap_or_default();
293 let verdicts = info_verdicts(&servers, size_bytes);
294 classify(&cache, &verdicts, servers, size_bytes)
295}
296
297#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
300pub struct UploadVerdict {
301 pub likely: bool,
302 pub reasons: Vec<String>,
303}
304
305pub fn upload_verdict(servers: &[String], mime: &str, is_encrypted: bool, size_bytes: u64) -> UploadVerdict {
310 if servers.is_empty() {
311 return UploadVerdict {
312 likely: false,
313 reasons: vec!["No media server is configured.".to_string()],
314 };
315 }
316 let cache = load_cache_for(servers, mime, is_encrypted).unwrap_or_default();
317 let mut reasons = Vec::new();
318 for s in servers {
319 let host = crate::blossom_error::host_of(s);
320 if let Some(info) = crate::blossom_info::cached(s) {
321 match info.accepts_size(size_bytes) {
322 Some(true) => return UploadVerdict { likely: true, reasons: Vec::new() },
323 Some(false) => {
324 if let Some(why) = info.refusal_reason(&host, size_bytes) {
325 reasons.push(why);
326 }
327 continue;
328 }
329 None => {}
330 }
331 }
332 match cache.get(&norm_url(s)) {
333 Some(st) if st.outcome == OUTCOME_REJECTED_MIME => {
334 reasons.push(format!("{} doesn't accept {} files.", host, mime));
335 }
336 Some(st) if st.min_rejected_size.is_some_and(|min| size_bytes >= min) => {
337 reasons.push(format!(
338 "{} has refused files of {} before.",
339 host, crate::crypto::format_bytes(st.min_rejected_size.unwrap_or(size_bytes)),
340 ));
341 }
342 _ => return UploadVerdict { likely: true, reasons: Vec::new() },
343 }
344 }
345 UploadVerdict { likely: false, reasons }
346}
347
348pub fn any_server_likely_accepts(servers: &[String], mime: &str, is_encrypted: bool, size_bytes: u64) -> bool {
350 upload_verdict(servers, mime, is_encrypted, size_bytes).likely
351}
352
353fn load_cache_for(servers: &[String], mime: &str, is_encrypted: bool) -> Result<HashMap<String, CapabilityState>, String> {
354 if servers.is_empty() { return Ok(HashMap::new()); }
355 let conn = crate::db::get_db_connection_guard_static()?;
356 let mime_lower = mime.to_lowercase();
357 let enc: i64 = if is_encrypted { 1 } else { 0 };
358 let cutoff = now_secs().saturating_sub(STALE_AFTER_SECS);
360 let placeholders = servers.iter().enumerate()
362 .map(|(i, _)| format!("?{}", i + 4)).collect::<Vec<_>>().join(",");
363 let sql = format!(
364 "SELECT server_url, outcome, max_accepted_size, min_rejected_size
365 FROM blossom_server_capabilities
366 WHERE mime_type = ?1 AND is_encrypted = ?2 AND updated_at >= ?3 AND server_url IN ({})",
367 placeholders,
368 );
369 let mut stmt = conn.prepare(&sql).map_err(|e| format!("Prepare failed: {}", e))?;
370 let cutoff_param: i64 = cutoff;
371 let mut params: Vec<&dyn rusqlite::ToSql> = vec![&mime_lower, &enc, &cutoff_param];
372 let normalized: Vec<String> = servers.iter().map(|s| norm_url(s)).collect();
373 for n in normalized.iter() { params.push(n); }
374 let rows = stmt.query_map(rusqlite::params_from_iter(params.iter()), |row| {
375 let url: String = row.get(0)?;
376 let outcome: i64 = row.get(1)?;
377 let max: i64 = row.get(2)?;
378 let min_rej: Option<i64> = row.get(3)?;
379 Ok((url, CapabilityState {
380 outcome: outcome as u8,
381 max_accepted_size: max as u64,
382 min_rejected_size: min_rej.map(|v| v as u64),
383 }))
384 }).map_err(|e| format!("Query failed: {}", e))?;
385 let mut out = HashMap::new();
386 for (url, state) in rows.flatten() {
387 out.insert(url, state);
388 }
389 Ok(out)
390}
391
392pub fn is_size_rejection(http_status: Option<u16>) -> bool {
398 matches!(http_status, Some(413))
399}
400
401pub fn is_mime_rejection(http_status: Option<u16>, error_msg: &str) -> bool {
411 if matches!(http_status, Some(415)) { return true; }
412 if matches!(http_status, Some(401)) { return true; }
413 if matches!(http_status, Some(402)) { return true; }
414 if matches!(http_status, Some(413) | Some(409)) { return false; }
415 if matches!(http_status, Some(408) | Some(429)) { return false; }
416 if let Some(s) = http_status {
417 if (500..=504).contains(&s) {
418 let lower = error_msg.to_ascii_lowercase();
421 return lower.contains("could not be processed")
422 || lower.contains("cannot be processed");
423 }
424 }
425 let lower = error_msg.to_ascii_lowercase();
427 let hints = [
428 "could not be processed",
429 "cannot be processed",
430 "unsupported",
431 "file type",
432 "mime",
433 "invalid file",
434 "not allowed",
435 "does not match",
436 "doesn't match",
437 "content-type",
438 ];
439 hints.iter().any(|h| lower.contains(h))
440}
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445
446 fn cache_of(entries: &[(&str, u8, u64)]) -> HashMap<String, CapabilityState> {
447 entries.iter()
448 .map(|(url, o, max)| (norm_url(url), CapabilityState {
449 outcome: *o,
450 max_accepted_size: *max,
451 min_rejected_size: None,
452 }))
453 .collect()
454 }
455
456 fn cache_with_size_cap(entries: &[(&str, u8, u64, u64)]) -> HashMap<String, CapabilityState> {
457 entries.iter()
458 .map(|(url, o, max, min_rej)| (norm_url(url), CapabilityState {
459 outcome: *o,
460 max_accepted_size: *max,
461 min_rejected_size: Some(*min_rej),
462 }))
463 .collect()
464 }
465
466 #[test]
467 fn norm_url_handles_case_and_trailing_slash() {
468 assert_eq!(norm_url("HTTPS://Example.COM/"), "https://example.com");
469 assert_eq!(norm_url(" https://example.com "), "https://example.com");
470 assert_eq!(norm_url("https://example.com"), "https://example.com");
471 }
472
473 #[test]
474 fn classify_empty_input_returns_empty() {
475 let cache = HashMap::new();
476 assert!(classify(&cache, &HashMap::new(), vec![], 1024).is_empty());
477 }
478
479 #[test]
480 fn classify_all_unknown_preserves_order() {
481 let cache = HashMap::new();
482 let servers = vec!["https://a".to_string(), "https://b".to_string(), "https://c".to_string()];
483 assert_eq!(classify(&cache, &HashMap::new(), servers.clone(), 1024), servers);
484 }
485
486 #[test]
487 fn classify_known_good_floats_to_top() {
488 let cache = cache_of(&[("https://b", OUTCOME_ACCEPTED, 10_000)]);
489 let servers = vec!["https://a".to_string(), "https://b".to_string(), "https://c".to_string()];
490 assert_eq!(classify(&cache, &HashMap::new(), servers, 5_000), vec!["https://b", "https://a", "https://c"]);
491 }
492
493 #[test]
494 fn classify_known_good_falls_to_unknown_when_over_size_ceiling() {
495 let cache = cache_of(&[("https://b", OUTCOME_ACCEPTED, 10_000)]);
496 let servers = vec!["https://a".to_string(), "https://b".to_string(), "https://c".to_string()];
497 let out = classify(&cache, &HashMap::new(), servers, 20_000);
498 assert_eq!(out, vec!["https://a", "https://b", "https://c"]);
499 }
500
501 #[test]
502 fn classify_mime_rejected_sinks_to_bottom() {
503 let cache = cache_of(&[("https://b", OUTCOME_REJECTED_MIME, 0)]);
504 let servers = vec!["https://a".to_string(), "https://b".to_string(), "https://c".to_string()];
505 let out = classify(&cache, &HashMap::new(), servers, 1024);
506 assert_eq!(out, vec!["https://a", "https://c", "https://b"]);
507 }
508
509 #[test]
510 fn classify_mixed_tiers_full_ordering() {
511 let cache = cache_of(&[
512 ("https://b", OUTCOME_ACCEPTED, 10_000),
513 ("https://c", OUTCOME_REJECTED_MIME, 0),
514 ("https://d", OUTCOME_ACCEPTED, 1_000),
515 ]);
516 let servers = vec![
517 "https://a".to_string(), "https://b".to_string(),
518 "https://c".to_string(), "https://d".to_string(),
519 ];
520 assert_eq!(
521 classify(&cache, &HashMap::new(), servers, 5_000),
522 vec!["https://b", "https://a", "https://d", "https://c"],
523 );
524 }
525
526 #[test]
527 fn classify_demotes_servers_above_known_size_ceiling() {
528 let cache = cache_with_size_cap(&[("https://b", OUTCOME_ACCEPTED, 10_000, 50_000)]);
529 let servers = vec!["https://a".to_string(), "https://b".to_string(), "https://c".to_string()];
530 let out = classify(&cache, &HashMap::new(), servers, 60_000);
531 assert_eq!(out, vec!["https://a", "https://c", "https://b"]);
532 }
533
534 #[test]
535 fn any_server_likely_accepts_smoke_test() {
536 let cache = cache_with_size_cap(&[
538 ("https://a", OUTCOME_ACCEPTED, 1_000, 10_000),
539 ("https://b", OUTCOME_ACCEPTED, 1_000, 10_000),
540 ]);
541 for (_, st) in &cache {
542 assert!(st.min_rejected_size.unwrap() <= 50_000);
543 }
544 }
545
546 #[test]
547 fn a_server_whose_document_says_yes_outranks_everything_learned() {
548 let cache = cache_of(&[("https://b", OUTCOME_ACCEPTED, 10_000)]);
549 let verdicts: HashMap<String, bool> = [("https://c".to_string(), true)].into_iter().collect();
550 let servers = vec!["https://a".to_string(), "https://b".to_string(), "https://c".to_string()];
551 assert_eq!(classify(&cache, &verdicts, servers, 5_000), vec!["https://c", "https://b", "https://a"]);
552 }
553
554 #[test]
555 fn a_server_whose_document_says_no_goes_last_even_when_learned_good() {
556 let cache = cache_of(&[("https://b", OUTCOME_ACCEPTED, 10_000)]);
557 let verdicts: HashMap<String, bool> = [("https://b".to_string(), false)].into_iter().collect();
558 let servers = vec!["https://a".to_string(), "https://b".to_string()];
559 assert_eq!(classify(&cache, &verdicts, servers, 5_000), vec!["https://a", "https://b"]);
560 }
561
562 #[test]
563 fn classify_keys_are_normalized_against_cache() {
564 let cache = cache_of(&[("https://b.example.com", OUTCOME_ACCEPTED, 10_000)]);
565 let servers = vec!["https://a".to_string(), "https://B.Example.com/".to_string()];
566 let out = classify(&cache, &HashMap::new(), servers, 5_000);
567 assert_eq!(out, vec!["https://B.Example.com/", "https://a"]);
568 }
569
570 #[test]
571 fn mime_rejection_415_is_always_a_reject() {
572 assert!(is_mime_rejection(Some(415), ""));
573 }
574
575 #[test]
576 fn mime_rejection_413_and_409_never_mime_regardless_of_body() {
577 assert!(!is_mime_rejection(Some(413), "Payload Too Large mime"));
578 assert!(!is_mime_rejection(Some(409), "Conflict file type"));
579 }
580
581 #[test]
582 fn mime_rejection_401_treated_as_permanent() {
583 assert!(is_mime_rejection(Some(401), "Unauthorized"));
584 assert!(is_mime_rejection(Some(401), ""));
585 }
586
587 #[test]
588 fn mime_rejection_5xx_with_body_hint_recorded() {
589 assert!(is_mime_rejection(
591 Some(500),
592 r#"Upload failed with status 500 Internal Server Error: {"status":"error","message":"File could not be processed"}"#,
593 ));
594 }
595
596 #[test]
597 fn mime_rejection_content_type_sniff_mismatch_recorded() {
598 assert!(is_mime_rejection(
600 Some(400),
601 "Upload failed with status 400 Bad Request: Content-Type header does not match the file content, expected application/json",
602 ));
603 }
604
605 #[test]
606 fn mime_rejection_transient_5xx_without_hint_not_recorded() {
607 assert!(!is_mime_rejection(Some(500), "Internal Server Error"));
608 assert!(!is_mime_rejection(Some(503), "service unavailable"));
609 }
610
611 #[test]
612 fn mime_rejection_transient_5xx_with_unrelated_body_keywords_not_recorded() {
613 assert!(!is_mime_rejection(Some(503), "file type detection service down"));
615 assert!(!is_mime_rejection(Some(429), "rate limit reached for content-type uploads"));
616 }
617
618 #[test]
619 fn mime_rejection_payment_required_treated_as_permanent() {
620 assert!(is_mime_rejection(Some(402), ""));
621 assert!(is_mime_rejection(Some(402), "Payment Required"));
622 }
623
624 #[test]
625 fn mime_rejection_no_status_with_body_hint_recorded() {
626 assert!(is_mime_rejection(None, "Unsupported file type"));
627 }
628
629 #[test]
630 fn mime_rejection_no_status_no_body_hint_not_recorded() {
631 assert!(!is_mime_rejection(None, "network error"));
632 assert!(!is_mime_rejection(None, "timeout"));
633 }
634}
635
636#[cfg(test)]
637mod preflight_tests {
638 use super::*;
639
640 fn took(max: u64, min_rejected: Option<u64>) -> CapabilityState {
641 CapabilityState { outcome: OUTCOME_ACCEPTED, max_accepted_size: max, min_rejected_size: min_rejected }
642 }
643
644 #[test]
645 fn a_server_that_took_as_much_needs_no_asking() {
646 assert!(known_to_take(Some(&took(10_000, None)), None, 9_000));
647 assert!(known_to_take(Some(&took(10_000, None)), Some(true), 10_000));
648 }
649
650 #[test]
651 fn anything_unproven_is_asked_first() {
652 assert!(!known_to_take(None, Some(true), 1), "never uploaded there: the document alone is not proof");
653 assert!(!known_to_take(Some(&took(10_000, None)), None, 10_001), "larger than it has taken");
654 assert!(!known_to_take(Some(&took(10_000, Some(9_000))), None, 9_500), "a refusal at this size since");
655 let mime_refused = CapabilityState { outcome: OUTCOME_REJECTED_MIME, max_accepted_size: 10_000, min_rejected_size: None };
656 assert!(!known_to_take(Some(&mime_refused), None, 1));
657 }
658
659 #[test]
660 fn the_servers_own_no_overrides_its_history() {
661 assert!(!known_to_take(Some(&took(10_000, None)), Some(false), 1), "a quota or tier change the history can't know");
662 }
663}