Skip to main content

byob_protocol/
media.rs

1//! Media in the conversation: charts and images that tools made, and files users attached.
2//!
3//! Entries and steps carry only small [`MediaRef`]s (a workspace-relative path). Clients
4//! fetch the content with [`crate::ClientMsg::GetMedia`]; the engine answers with
5//! [`crate::ServerMsg::Media`], and only for paths the transcript references, so a client
6//! can never read arbitrary files. Uploads travel in [`crate::ClientMsg::Upload`] chunks
7//! that each fit well inside [`crate::MAX_FRAME_BYTES`].
8
9use base64::Engine as _;
10pub use byob_types::chart::ChartSpec;
11use serde::{Deserialize, Serialize};
12
13/// Largest file a user may attach.
14pub const MAX_UPLOAD_BYTES: u64 = 25 * 1024 * 1024;
15/// Raw bytes per upload chunk (base64 makes it 4/3 bigger on the wire).
16pub const UPLOAD_CHUNK_BYTES: usize = 1024 * 1024;
17/// Largest encoded image sent to a client in one [`MediaContent::Image`]; bigger images are
18/// downscaled by the engine first.
19pub const MAX_IMAGE_BYTES: usize = 2_500_000;
20/// Files attached to one message.
21pub const MAX_ATTACHMENTS: usize = 10;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum MediaKind {
26    /// A `.chart.json` drawn natively.
27    Chart,
28    /// A PNG or JPEG shown inline.
29    Image,
30    /// Anything else (shown as a file chip), including kinds this client doesn't know.
31    #[serde(other)]
32    File,
33}
34
35impl MediaKind {
36    /// What a workspace path is shown as, by its name.
37    pub fn for_path(path: &str) -> Self {
38        let lower = path.to_ascii_lowercase();
39        if lower.ends_with(".chart.json") {
40            Self::Chart
41        } else if [".png", ".jpg", ".jpeg"].iter().any(|e| lower.ends_with(e)) {
42            Self::Image
43        } else {
44            Self::File
45        }
46    }
47}
48
49/// A file shown in the conversation. `path` is relative to the workspace.
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51pub struct MediaRef {
52    pub kind: MediaKind,
53    pub path: String,
54    /// Size in bytes, if known.
55    #[serde(default)]
56    pub size: u64,
57}
58
59impl MediaRef {
60    pub fn new(path: impl Into<String>, size: u64) -> Self {
61        let path = path.into();
62        Self { kind: MediaKind::for_path(&path), path, size }
63    }
64
65    /// File name for display.
66    pub fn name(&self) -> &str {
67        self.path.rsplit(['/', '\\']).next().unwrap_or(&self.path)
68    }
69}
70
71/// The content behind a [`MediaRef`].
72#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
73#[serde(tag = "kind", rename_all = "snake_case")]
74pub enum MediaContent {
75    Chart {
76        spec: ChartSpec,
77    },
78    /// An encoded PNG or JPEG, base64 (see [`encode`]).
79    Image {
80        mime: String,
81        data: String,
82    },
83    /// The file is gone, too big, or not something we show.
84    Error {
85        message: String,
86    },
87}
88
89/// Standard base64, as used for upload chunks and images.
90pub fn encode(bytes: &[u8]) -> String {
91    base64::engine::general_purpose::STANDARD.encode(bytes)
92}
93
94/// Decode untrusted base64.
95pub fn decode(text: &str) -> Result<Vec<u8>, String> {
96    base64::engine::general_purpose::STANDARD.decode(text).map_err(|e| format!("bad base64: {e}"))
97}
98
99/// Human-readable size.
100pub fn size_label(n: u64) -> String {
101    #[allow(clippy::cast_precision_loss)] // display only
102    let f = n as f64;
103    if n < 1024 {
104        format!("{n} B")
105    } else if n < 1024 * 1024 {
106        format!("{:.0} KB", f / 1024.0)
107    } else {
108        format!("{:.1} MB", f / (1024.0 * 1024.0))
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn kinds_by_name() {
118        assert_eq!(MediaKind::for_path("charts/Sales.chart.json"), MediaKind::Chart);
119        assert_eq!(MediaKind::for_path("out/plot.PNG"), MediaKind::Image);
120        assert_eq!(MediaKind::for_path("a.jpeg"), MediaKind::Image);
121        assert_eq!(MediaKind::for_path("data.json"), MediaKind::File);
122        assert_eq!(MediaRef::new("uploads/sales.csv", 3).name(), "sales.csv");
123        assert_eq!(MediaRef::new("x", 0).name(), "x");
124    }
125
126    #[test]
127    fn base64_round_trip_and_garbage() {
128        assert_eq!(decode(&encode(b"hello\0")).unwrap(), b"hello\0");
129        assert!(decode("!!!").is_err());
130    }
131
132    #[test]
133    fn upload_chunks_fit_in_a_frame() {
134        let chunk = encode(&vec![0xffu8; UPLOAD_CHUNK_BYTES]);
135        assert!(chunk.len() + 1024 < crate::MAX_FRAME_BYTES);
136        assert!(encode(&vec![0u8; MAX_IMAGE_BYTES]).len() + 1024 < crate::MAX_FRAME_BYTES);
137    }
138
139    #[test]
140    fn sizes() {
141        assert_eq!(size_label(10), "10 B");
142        assert_eq!(size_label(2048), "2 KB");
143        assert_eq!(size_label(3 * 1024 * 1024), "3.0 MB");
144    }
145}