Skip to main content

alpha2_extensions/
budget.rs

1//! Limits every provider checks before it reads, decodes, or draws a source. A source past one
2//! is refused with [`ExtensionError::Budget`], natively and in the browser alike.
3//!
4//! The limits cover document size ([`document_limit`]), canvas size ([`check_canvas`]), decoded
5//! pixels ([`MAX_ANIMATION_PIXELS`], [`MAX_SOURCE_IMAGE_PIXELS`], [`DEFAULT_FRAME_BUDGET`]) and
6//! drawing cost ([`MAX_DRAWING`]). Format-specific counts (SVG elements, Lottie draws, dotLottie
7//! files) live next to each parser.
8
9use alpha2_model::{
10    MAX_LOTTIE_DOCUMENT_BYTES, MAX_PROVIDER_DOCUMENT_BYTES, MAX_SVG_DOCUMENT_BYTES, ProviderSource,
11};
12
13use crate::api::ExtensionError;
14
15/// Largest canvas side a provider opens, in pixels.
16pub const MAX_CANVAS_SIDE: u32 = 16_384;
17/// Largest canvas a provider opens, in pixels (8K UHD).
18pub const MAX_CANVAS_PIXELS: u64 = 7_680 * 4_320;
19/// Most frames an animated image may have.
20pub const MAX_ANIMATION_FRAMES: usize = 10_000;
21/// Most pixels all of an animated image's frames may cover together. About a thousand 1080p
22/// frames, roughly ten seconds of native decoding.
23pub const MAX_ANIMATION_PIXELS: u64 = 1 << 31;
24/// Decoded bytes an animated source or an image sequence keeps between requests.
25pub const DEFAULT_FRAME_BUDGET: usize = 256 * 1024 * 1024;
26/// Most pixels the raster images inside one source may decode to together. An SVG counts every
27/// image draw per render (an image reused through `<use>` counts twice); Lottie counts its assets
28/// once at open.
29pub const MAX_SOURCE_IMAGE_PIXELS: u64 = 4 * MAX_CANVAS_PIXELS;
30
31/// Most canvases of blended fill one SVG render or Lottie frame may draw. A 1080p canvas of
32/// blended fill costs about 4 to 10 ms natively, so this is about 2 s. Opaque fills are not
33/// discounted, since whether something above fades is unknown before drawing.
34#[cfg(any(feature = "svg", feature = "lottie"))]
35pub(crate) const MAX_DRAWING: f64 = 256.0;
36
37/// Minimum canvas an SVG counts as for [`MAX_DRAWING`], since a small icon can still draw many
38/// blurs. Lottie uses its own canvas because all its layers are frame-sized.
39#[cfg(feature = "svg")]
40pub(crate) const FLOOR_CANVAS: f64 = 1920.0 * 1080.0;
41
42/// Refuses a canvas larger than a provider opens.
43///
44/// # Errors
45/// [`ExtensionError::Budget`] or, for an empty canvas,
46/// [`ExtensionError::Malformed`].
47pub fn check_canvas(width: u32, height: u32) -> Result<(), ExtensionError> {
48    if width == 0 || height == 0 {
49        return Err(ExtensionError::Malformed("the canvas is empty".into()));
50    }
51    if width > MAX_CANVAS_SIDE
52        || height > MAX_CANVAS_SIDE
53        || u64::from(width) * u64::from(height) > MAX_CANVAS_PIXELS
54    {
55        return Err(ExtensionError::Budget(format!(
56            "a {width}x{height} canvas is larger than {MAX_CANVAS_PIXELS} pixels"
57        )));
58    }
59    Ok(())
60}
61
62/// The most bytes a provider reads of a whole-file format (SVG, Lottie JSON, dotLottie), with a
63/// name for the file kind; `None` for streamed formats. `head` is the file's start, used to tell
64/// a dotLottie ZIP from Lottie JSON.
65#[must_use]
66pub fn document_limit(source: &ProviderSource, head: &[u8]) -> Option<(usize, &'static str)> {
67    match source {
68        ProviderSource::Svg => Some((MAX_SVG_DOCUMENT_BYTES, "SVG document")),
69        ProviderSource::Lottie { .. } if head.starts_with(b"PK\x03\x04") => {
70            Some((MAX_PROVIDER_DOCUMENT_BYTES, "dotLottie package"))
71        }
72        ProviderSource::Lottie { .. } => Some((MAX_LOTTIE_DOCUMENT_BYTES, "Lottie file")),
73        _ => None,
74    }
75}
76
77/// Refuses a source file of `length` bytes larger than its [`document_limit`].
78///
79/// # Errors
80/// [`ExtensionError::Budget`].
81pub fn check_document_size(
82    source: &ProviderSource,
83    head: &[u8],
84    length: u64,
85) -> Result<(), ExtensionError> {
86    match document_limit(source, head) {
87        Some((limit, what)) if length > limit as u64 => Err(ExtensionError::Budget(format!(
88            "the {what} is {length} bytes, more than the {limit} a provider reads"
89        ))),
90        _ => Ok(()),
91    }
92}
93
94/// Refuses images that together decode to more than [`MAX_SOURCE_IMAGE_PIXELS`].
95///
96/// # Errors
97/// [`ExtensionError::Budget`].
98pub fn check_image_pixels(pixels: u64) -> Result<(), ExtensionError> {
99    if pixels > MAX_SOURCE_IMAGE_PIXELS {
100        return Err(ExtensionError::Budget(format!(
101            "its images decode to {pixels} pixels, more than the {MAX_SOURCE_IMAGE_PIXELS} one source may"
102        )));
103    }
104    Ok(())
105}