Files
arr/crates/arr-meta/src/cache.rs
T
Miguel Palhas 0fa422e170
ci / web (pull_request) Successful in 6s
ci / rust (pull_request) Successful in 46s
feat(meta): TMDB search and movie lookup
Search and detail lookup, carrying the two fields the policy engine
needs and that are easy to lose at the edge.

`original_language` arrives as bare ISO 639-1, which has one code for
both Portuguese variants, so the dub rule in §5.2 cannot be expressed
against it alone. `Movie` therefore also carries `origin_countries`,
from `origin_country` where TMDB has it and `production_countries`
otherwise, which is what separates a Brazilian film from a Portuguese
one.

Digital release dates come back appended to the detail call rather than
costing a second round trip, reduced to the earliest type-4 entry across
every country: a release existing in one region is a release that exists
on the indexers. `Movie::is_digitally_released` puts the §6.2 gate in
one tested place.

Responses are cached in process for a day, matching the metadata refresh
tick. Failures are never cached, so an outage cannot pin a title into a
bad state until tomorrow.

Tests are wiremock-backed, per §12.
2026-08-22 19:39:21 +01:00

63 lines
1.8 KiB
Rust

//! A small time-to-live cache over raw response bodies.
//!
//! Keyed on a logical request key rather than the URL, so the API key never
//! becomes part of a cache key. Bodies are stored unparsed: parsing again on a
//! hit costs microseconds and keeps one cache serving every endpoint.
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::{Mutex, PoisonError};
use std::time::{Duration, Instant};
#[derive(Debug)]
struct Entry {
stored_at: Instant,
body: Arc<str>,
}
#[derive(Debug)]
pub(crate) struct Cache {
ttl: Duration,
entries: Mutex<HashMap<String, Entry>>,
}
impl Cache {
pub(crate) fn new(ttl: Duration) -> Self {
Self {
ttl,
entries: Mutex::new(HashMap::new()),
}
}
/// The cached body for `key`, if one is present and still fresh.
pub(crate) fn get(&self, key: &str) -> Option<Arc<str>> {
let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
let entry = entries.get(key)?;
if entry.stored_at.elapsed() < self.ttl {
return Some(Arc::clone(&entry.body));
}
entries.remove(key);
None
}
pub(crate) fn insert(&self, key: String, body: Arc<str>) {
let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
entries.insert(
key,
Entry {
stored_at: Instant::now(),
body,
},
);
}
/// Drop everything. The daily metadata refresh does not need this — entries
/// expire on their own — but a forced refresh from the UI does.
pub(crate) fn clear(&self) {
self.entries
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
}
}