favicons 1.0.0

Privacy-first favicon and logo API: any site's icon as a clean, sandboxed SVG with light and dark theme colours
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use anyhow::Context;
use bytes::Bytes;
use http::HeaderValue;
use moka::sync::Cache;
use object_store::path::Path;
use object_store::{Attribute, Attributes, ObjectStore, ObjectStoreExt, PutOptions, PutPayload};
use serde::{Deserialize, Serialize};
use url::Url;

use crate::config::{Cache as CacheCfg, HttpCache};
use crate::contract::{MonoSource, Provenance, SVG_MIME, Slot};
use crate::disk::Disk;
use crate::palette::Palette;
use crate::vector::VectorOrigin;

pub const LAYOUT_VERSION: &str = "v3";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Status {
    Ok,
    NotFound,
    FetchFailed,
    TooNew,
    Blocked,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Meta {
    pub domain: String,
    pub fetched_at: u64,
    pub status: Status,
    #[serde(default)]
    pub color: Option<VectorOrigin>,
    #[serde(default)]
    pub mono: Option<VectorOrigin>,
    #[serde(default)]
    pub mono_source: Option<MonoSource>,
    #[serde(default)]
    pub upstream: Option<String>,
    #[serde(default)]
    pub provenance: Option<Provenance>,
    #[serde(default)]
    pub license: Option<String>,
    #[serde(default)]
    pub etags: BTreeMap<String, String>,
    #[serde(default)]
    pub palette: Option<Palette>,
}

impl Meta {
    pub fn new(domain: &str, status: Status) -> Self {
        Self {
            domain: domain.into(),
            fetched_at: now(),
            status,
            color: None,
            mono: None,
            mono_source: None,
            upstream: None,
            provenance: None,
            license: None,
            etags: BTreeMap::new(),
            palette: None,
        }
    }
}

pub fn now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs())
}

pub fn object_name(slot: Slot) -> &'static str {
    match slot {
        Slot::Color => "color.svg",
        Slot::Mono => "mono.svg",
    }
}

pub struct Icon {
    pub data: Bytes,
    pub etag: Option<HeaderValue>,
    pub domain: Option<HeaderValue>,
    pub palette: crate::palette::Headers,
}

impl Icon {
    pub fn new(
        data: Bytes,
        etag: Option<&str>,
        domain: Option<&str>,
        palette: Option<Palette>,
    ) -> Arc<Self> {
        Arc::new(Self::build(data, etag, domain, palette))
    }

    fn build(
        data: Bytes,
        etag: Option<&str>,
        domain: Option<&str>,
        palette: Option<Palette>,
    ) -> Self {
        Self {
            data,
            etag: etag.and_then(|e| HeaderValue::from_str(&format!("\"{e}\"")).ok()),
            domain: domain.and_then(|d| HeaderValue::from_str(d).ok()),
            palette: palette.map(|p| p.headers()).unwrap_or_default(),
        }
    }

    fn of(meta: &Meta, slot: Slot, data: Bytes) -> Arc<Self> {
        Arc::new(Self::build(
            data,
            meta.etags.get(object_name(slot)).map(String::as_str),
            Some(&meta.domain),
            meta.palette,
        ))
    }
}

type IconCache = Cache<String, Arc<Icon>>;

fn icon_cache(cfg: &CacheCfg) -> IconCache {
    Cache::builder()
        .max_capacity(cfg.memory_max_bytes / 2)
        .weigher(|k: &String, v: &Arc<Icon>| {
            (k.len() + v.data.len()).try_into().unwrap_or(u32::MAX)
        })
        .time_to_live(Duration::from_secs(cfg.memory_ttl_secs))
        .build()
}

pub struct Store {
    backend: Option<Arc<dyn ObjectStore>>,
    pub disk: Option<Arc<Disk>>,
    attributes: bool,
    prefix: Path,
    timeout: Duration,
    object_cache_control: String,
    meta_mem: Cache<String, Arc<Meta>>,
    absent: Cache<String, ()>,
    img_color: IconCache,
    img_mono: IconCache,
}

impl Store {
    pub fn new(cfg: &CacheCfg, http: &HttpCache) -> anyhow::Result<Self> {
        let (backend, prefix, attributes, local) = build_backend(cfg)?;
        let disk = local.and_then(|root| {
            Disk::new(
                root.join(LAYOUT_VERSION),
                cfg.max_disk_bytes,
                cfg.max_disk_entries,
            )
            .map(Arc::new)
        });
        Ok(Self {
            backend,
            disk,
            attributes,
            prefix,
            timeout: Duration::from_millis(cfg.storage_timeout_ms),
            object_cache_control: http.icon.browser.clone(),
            meta_mem: Cache::builder()
                .max_capacity(cfg.memory_meta_entries)
                .time_to_live(Duration::from_secs(cfg.memory_ttl_secs))
                .build(),
            absent: Cache::builder()
                .max_capacity(cfg.memory_meta_entries)
                .time_to_live(Duration::from_secs(cfg.absent_ttl_secs.max(1)))
                .build(),
            img_color: icon_cache(cfg),
            img_mono: icon_cache(cfg),
        })
    }

    fn icons(&self, slot: Slot) -> &IconCache {
        match slot {
            Slot::Color => &self.img_color,
            Slot::Mono => &self.img_mono,
        }
    }

    pub fn has_backend(&self) -> bool {
        self.backend.is_some()
    }

    fn path(&self, domain: &str, name: &str) -> Path {
        let rel = format!("{LAYOUT_VERSION}/{domain}/{name}");
        if self.prefix.as_ref().is_empty() {
            Path::from(rel)
        } else {
            Path::from(format!("{}/{rel}", self.prefix))
        }
    }

    pub async fn meta(&self, domain: &str) -> Option<Arc<Meta>> {
        if let Some(m) = self.meta_mem.get(domain) {
            return Some(m);
        }
        let backend = self.backend.as_ref()?;
        if self.absent.contains_key(domain) {
            return None;
        }
        match self.read(backend, &self.path(domain, "meta.json")).await {
            Ok(Some(bytes)) => match serde_json::from_slice::<Meta>(&bytes) {
                Ok(meta) if meta.domain == domain => {
                    if let Some(disk) = self.disk.clone() {
                        let domain = domain.to_string();
                        tokio::task::spawn_blocking(move || disk.touch(&domain));
                    }
                    let meta = Arc::new(meta);
                    self.meta_mem.insert(domain.to_string(), meta.clone());
                    Some(meta)
                }
                _ => {
                    tracing::warn!(domain, "ignoring corrupt meta.json");
                    None
                }
            },
            Ok(None) => {
                self.absent.insert(domain.to_string(), ());
                None
            }
            Err(e) => {
                tracing::warn!(domain, error = %e, "storage read failed");
                None
            }
        }
    }

    pub async fn image(&self, meta: &Meta, slot: Slot) -> Option<Arc<Icon>> {
        let domain = meta.domain.as_str();
        let cache = self.icons(slot);
        if let Some(icon) = cache.get(domain) {
            return Some(icon);
        }
        let backend = self.backend.as_ref()?;
        match self
            .read(backend, &self.path(domain, object_name(slot)))
            .await
        {
            Ok(Some(b)) => {
                let icon = Icon::of(meta, slot, b);
                cache.insert(domain.to_string(), icon.clone());
                Some(icon)
            }
            Ok(None) => None,
            Err(e) => {
                tracing::warn!(domain, error = %e, "storage read failed");
                None
            }
        }
    }

    pub async fn put(&self, meta: Meta, images: Vec<(Slot, Vec<u8>)>) {
        let domain = meta.domain.clone();
        let new_entry = self.disk.as_ref().is_some_and(|d| !d.exists(&domain));
        let mut sizes = Vec::with_capacity(3);
        for (slot, data) in images {
            sizes.push(data.len());
            let name = object_name(slot);
            let bytes = Bytes::from(data);
            if let Some(backend) = &self.backend {
                let opts = self.put_options(SVG_MIME, &self.object_cache_control);
                let path = self.path(&domain, name);
                let res = tokio::time::timeout(
                    self.timeout,
                    backend.put_opts(&path, PutPayload::from(bytes.clone()), opts),
                )
                .await;
                if !matches!(res, Ok(Ok(_))) {
                    tracing::warn!(domain, name, "storage write failed");
                }
            }
            self.icons(slot)
                .insert(domain.clone(), Icon::of(&meta, slot, bytes));
        }
        if let Some(backend) = &self.backend {
            match serde_json::to_vec(&meta) {
                Ok(json) => {
                    sizes.push(json.len());
                    let opts = self.put_options("application/json", "no-store");
                    let res = tokio::time::timeout(
                        self.timeout,
                        backend.put_opts(
                            &self.path(&domain, "meta.json"),
                            PutPayload::from(json),
                            opts,
                        ),
                    )
                    .await;
                    if !matches!(res, Ok(Ok(_))) {
                        tracing::warn!(domain, "storage meta write failed");
                    }
                }
                Err(e) => tracing::warn!(domain, error = %e, "meta serialization failed"),
            }
        }
        if let Some(disk) = &self.disk {
            disk.added(sizes, new_entry);
        }
        self.absent.invalidate(&domain);
        self.meta_mem.insert(domain, Arc::new(meta));
    }

    pub fn forget(&self, domains: &[String]) {
        for d in domains {
            self.meta_mem.invalidate(d);
            self.img_color.invalidate(d);
            self.img_mono.invalidate(d);
        }
    }

    fn put_options(&self, content_type: &str, cache_control: &str) -> PutOptions {
        if !self.attributes {
            return PutOptions::default();
        }
        let mut attrs = Attributes::new();
        attrs.insert(Attribute::ContentType, content_type.to_string().into());
        attrs.insert(Attribute::CacheControl, cache_control.to_string().into());
        PutOptions {
            attributes: attrs,
            ..Default::default()
        }
    }

    async fn read(
        &self,
        backend: &Arc<dyn ObjectStore>,
        path: &Path,
    ) -> anyhow::Result<Option<Bytes>> {
        let fut = async {
            match backend.get(path).await {
                Ok(r) => Ok(Some(r.bytes().await?)),
                Err(object_store::Error::NotFound { .. }) => Ok(None),
                Err(e) => Err(anyhow::Error::from(e)),
            }
        };
        tokio::time::timeout(self.timeout, fut)
            .await
            .context("storage timeout")?
    }
}

type Backend = (Option<Arc<dyn ObjectStore>>, Path, bool, Option<PathBuf>);

fn build_backend(cfg: &CacheCfg) -> anyhow::Result<Backend> {
    let spec = cfg.storage.trim();
    if spec.is_empty() || spec.eq_ignore_ascii_case("none") || spec.eq_ignore_ascii_case("memory") {
        return Ok((None, Path::default(), false, None));
    }
    let url = if spec.contains("://") {
        Url::parse(spec).context("cache.storage is not a valid URL")?
    } else {
        let abs = std::path::absolute(spec)?;
        Url::from_directory_path(&abs).map_err(|_| anyhow::anyhow!("bad cache directory {spec}"))?
    };
    if url.scheme() == "file" {
        let dir = url
            .to_file_path()
            .map_err(|_| anyhow::anyhow!("bad file url"))?;
        std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
        let fs = object_store::local::LocalFileSystem::new_with_prefix(&dir)?
            .with_automatic_cleanup(true);
        return Ok((Some(Arc::new(fs)), Path::default(), false, Some(dir)));
    }
    let attributes = !matches!(url.scheme(), "memory");
    let (store, prefix) = object_store::parse_url_opts(&url, cfg.options.iter())?;
    Ok((Some(Arc::from(store)), prefix, attributes, None))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn store_in(dir: &std::path::Path) -> Store {
        let cfg = CacheCfg {
            storage: format!("file://{}", dir.display()),
            ..CacheCfg::default()
        };
        Store::new(&cfg, &HttpCache::default()).unwrap()
    }

    #[tokio::test]
    async fn round_trips_through_filesystem() {
        let dir = std::env::temp_dir().join(format!("favicons-test-{}", rand::random::<u64>()));
        let store = store_in(&dir);
        assert!(store.meta("example.com").await.is_none());
        let mut meta = Meta::new("example.com", Status::Ok);
        meta.color = Some(VectorOrigin::Traced);
        store
            .put(
                meta,
                vec![(Slot::Color, vec![1, 2, 3]), (Slot::Mono, vec![4, 5])],
            )
            .await;

        let fresh = store_in(&dir);
        let meta = fresh.meta("example.com").await.unwrap();
        assert_eq!(meta.color, Some(VectorOrigin::Traced));
        assert_eq!(
            fresh.image(&meta, Slot::Mono).await.unwrap().data.as_ref(),
            [4, 5]
        );
        assert!(dir.join("v3/example.com/color.svg").exists());
        assert!(dir.join("v3/example.com/mono.svg").exists());
        let _ = std::fs::remove_dir_all(dir);
    }
}