Skip to main content

brep_plm/
thumbnail.rs

1//! Revision thumbnails (P9): a small PNG per revision, made by a CAD client
2//! when it saves and by the bake worker for generated members. The server
3//! never links the kernel, so it never renders one; it keeps what it is sent.
4//!
5//! - **Keyed by the document.** A thumbnail records the revision's
6//!   `content_hash` when it was made, and the renderer's version. It is
7//!   *current* only while that hash is still the revision's; a save makes it
8//!   stale, and a stale one is never served as the revision's picture (the
9//!   GET answers `204`, the listings leave it out). It is kept, not deleted,
10//!   until a new one replaces it: the next save's upload does.
11//! - **Stored like an attachment.** The bytes are a content-addressed blob in
12//!   `<data>/blobs/` ([`crate::attach`]), referenced from the revision, so
13//!   [`crate::attach::referenced`] and the backup see it and it goes when the
14//!   last reference does.
15//! - **Who may upload.** An author, or the bake worker (its group and its
16//!   token scope). No lock and no editable revision are needed: the upload
17//!   says which document it pictures, and the hash check is the whole rule,
18//!   so a newer renderer can re-picture a released revision.
19//! - **A part's thumbnail** is its newest revision's that is current.
20
21use crate::attach::{self, Staged};
22use crate::db::{now, Db, State};
23use crate::model::{Part, Revision, Thumbnail, User};
24use crate::Error;
25
26/// The largest PNG kept, in bytes.
27pub const MAX_BYTES: u64 = 1024 * 1024;
28
29/// The largest edge, in pixels.
30pub const MAX_EDGE: u32 = 1024;
31
32/// The media type every thumbnail is.
33pub const MEDIA_TYPE: &str = "image/png";
34
35/// A PNG's width and height from its header, or why the bytes are not one.
36pub fn png_size(bytes: &[u8]) -> Result<(u32, u32), Error> {
37    const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n'];
38    if bytes.len() < 24 || bytes[..8] != SIGNATURE || &bytes[12..16] != b"IHDR" {
39        return Err(Error::bad_request("a thumbnail must be a PNG image"));
40    }
41    let word = |at: usize| u32::from_be_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]);
42    let (width, height) = (word(16), word(20));
43    if width == 0 || height == 0 || width > MAX_EDGE || height > MAX_EDGE {
44        return Err(Error::bad_request(format!(
45            "a thumbnail is at most {MAX_EDGE}×{MAX_EDGE} pixels; this one is {width}×{height}"
46        )));
47    }
48    Ok((width, height))
49}
50
51/// The revision's thumbnail if it pictures the document as it is now.
52pub fn current(revision: &Revision) -> Option<&Thumbnail> {
53    revision
54        .thumbnail
55        .as_ref()
56        .filter(|t| !revision.content_hash.is_empty() && t.content_hash == revision.content_hash)
57}
58
59/// A part's thumbnail: the newest revision (by creation, drafts included)
60/// whose thumbnail is current.
61pub fn of_part(part: &Part) -> Option<(&Revision, &Thumbnail)> {
62    part.revisions.iter().rev().find_map(|r| current(r).map(|t| (r, t)))
63}
64
65/// The URL a page shows a part's thumbnail from, versioned by the blob so a
66/// browser may cache it for good; empty when the part has none.
67pub fn part_url(part: &Part) -> String {
68    of_part(part).map(|(_, t)| format!("/api/parts/{}/thumbnail?v={}", crate::identity::segment(&part.id), t.sha256)).unwrap_or_default()
69}
70
71/// The same for one revision.
72pub fn revision_url(part_id: &str, revision: &Revision) -> String {
73    current(revision)
74        .map(|t| format!("/api/parts/{}/revisions/{}/thumbnail?v={}", crate::identity::segment(part_id), crate::identity::segment(&revision.id), t.sha256))
75        .unwrap_or_default()
76}
77
78/// What the uploader says the picture is of.
79#[derive(Debug, Clone, Default)]
80pub struct Claim {
81    /// The document's `content_hash` the picture was made from.
82    pub content_hash: String,
83    pub renderer: String,
84}
85
86/// A portable model preview staged before the document transaction. Import and
87/// ordinary saves use the same path, so an image never needs a second upload.
88pub(crate) struct Embedded {
89    staged: attach::Staged,
90    width: u32,
91    height: u32,
92    renderer: String,
93}
94
95impl Embedded {
96    pub(crate) fn place(&self, root: &std::path::Path, content_hash: &str, user: &str) -> Result<Thumbnail, Error> {
97        attach::place(root, &self.staged)?;
98        Ok(Thumbnail {
99            sha256: self.staged.sha256.clone(), size: self.staged.size,
100            width: self.width, height: self.height, content_hash: content_hash.into(),
101            renderer: self.renderer.clone(), uploaded_by: user.into(), uploaded_at: now(),
102        })
103    }
104}
105
106pub(crate) fn embedded(root: &std::path::Path, body: &str) -> Result<Option<Embedded>, Error> {
107    use base64::Engine;
108    let Ok(document) = serde_json::from_str::<serde_json::Value>(body) else { return Ok(None) };
109    let Some(image) = document.get("thumbnail").filter(|v| !v.is_null()) else { return Ok(None) };
110    if image.get("mimeType").and_then(|v| v.as_str()) != Some(MEDIA_TYPE) {
111        return Err(Error::bad_request("the embedded thumbnail must have mimeType image/png"));
112    }
113    let data = image.get("data").and_then(|v| v.as_str())
114        .ok_or_else(|| Error::bad_request("the embedded thumbnail needs base64 PNG data"))?;
115    if data.len() as u64 > MAX_BYTES.div_ceil(3) * 4 {
116        return Err(Error::bad_request("the embedded thumbnail exceeds 1 MiB"));
117    }
118    let bytes = base64::engine::general_purpose::STANDARD.decode(data)
119        .map_err(|_| Error::bad_request("the embedded thumbnail is not valid base64"))?;
120    if bytes.len() as u64 > MAX_BYTES { return Err(Error::bad_request("the embedded thumbnail exceeds 1 MiB")); }
121    let (width, height) = png_size(&bytes)?;
122    let renderer = image.get("renderer").and_then(|v| v.as_str()).unwrap_or("embedded-png").trim();
123    if renderer.is_empty() || renderer.len() > 64 { return Err(Error::bad_request("invalid embedded thumbnail renderer")); }
124    let mut upload = attach::Upload::start(root, MAX_BYTES).map_err(Error::internal)?;
125    upload.write(&bytes)?;
126    Ok(Some(Embedded { staged: upload.finish()?, width, height, renderer: renderer.into() }))
127}
128
129impl Db {
130    /// Keep `staged` (already checked by [`png_size`]) as the thumbnail of
131    /// `revision_key` of `part_key`. Refused `409` when the revision's
132    /// document is not the one pictured.
133    pub fn put_thumbnail(
134        &self,
135        user: &User,
136        part_key: &str,
137        revision_key: &str,
138        staged: Staged,
139        (width, height): (u32, u32),
140        claim: &Claim,
141    ) -> Result<Thumbnail, Error> {
142        if !user.can_author() && !user.can_bake() {
143            return Err(Error::forbidden("a thumbnail is uploaded by an author or the bake worker"));
144        }
145        let renderer = claim.renderer.trim().to_string();
146        if renderer.is_empty() || renderer.len() > 64 {
147            return Err(Error::bad_request("name the renderer that made the thumbnail (renderer=…, at most 64 characters)"));
148        }
149        let root = self.root().to_path_buf();
150        let user_id = user.id.clone();
151        let (part_key, revision_key, claimed) = (part_key.to_string(), revision_key.to_string(), claim.content_hash.trim().to_string());
152        self.mutate(move |state| {
153            let part = state.part_by_id_or_number(&part_key).ok_or_else(|| Error::not_found("part"))?;
154            let (part_id, number) = (part.id.clone(), part.number.clone());
155            let revision = crate::bom::find_revision(part, &revision_key).ok_or_else(|| Error::not_found("revision"))?;
156            let revision_id = revision.id.clone();
157            if revision.content_hash.is_empty() {
158                return Err(Error::conflict(format!("{number} revision {} has no document to picture", revision.label)));
159            }
160            if claimed != revision.content_hash {
161                return Err(Error::conflict(format!(
162                    "the thumbnail pictures document {}, but {number} revision {} is now {} — render it again",
163                    short(&claimed),
164                    revision.label,
165                    short(&revision.content_hash)
166                )));
167            }
168            attach::place(&root, &staged)?;
169            let thumbnail = Thumbnail {
170                sha256: staged.sha256.clone(),
171                size: staged.size,
172                width,
173                height,
174                content_hash: claimed,
175                renderer,
176                uploaded_by: user_id,
177                uploaded_at: now(),
178            };
179            let part = state.parts.get_mut(&part_id).ok_or_else(|| Error::not_found("part"))?;
180            let revision = part.revision_mut(&revision_id).ok_or_else(|| Error::not_found("revision"))?;
181            let old = revision.thumbnail.replace(thumbnail.clone());
182            if let Some(old) = old.filter(|o| o.sha256 != thumbnail.sha256) {
183                attach::remove_if_unreferenced(state, &root, &old.sha256)?;
184            }
185            // A separate CAD thumbnail upload can land after the document
186            // save. Readers must hear about both while checkout stays held.
187            state.touch(crate::identity::document_key(&part_id, &revision_id));
188            Ok(thumbnail)
189        })
190    }
191
192    /// The thumbnail to serve for a revision (`revision_key` non-empty) or a
193    /// part: `None` when there is no current one. `Err` only for an unknown
194    /// part or revision.
195    pub fn thumbnail(&self, part_key: &str, revision_key: &str) -> Result<Option<(String, Thumbnail)>, Error> {
196        self.read(|state: &State| {
197            let part = state.part_by_id_or_number(part_key).ok_or_else(|| Error::not_found("part"))?;
198            if revision_key.is_empty() {
199                return Ok(of_part(part).map(|(r, t)| (r.label.clone(), t.clone())));
200            }
201            let revision = crate::bom::find_revision(part, revision_key).ok_or_else(|| Error::not_found("revision"))?;
202            Ok(current(revision).map(|t| (revision.label.clone(), t.clone())))
203        })
204    }
205}
206
207fn short(hash: &str) -> &str {
208    if hash.is_empty() { "(none)" } else { &hash[..hash.len().min(12)] }
209}