smallpict 0.0.8

Official Rust SDK for SmallPict Image Optimization API — next-gen compression (AVIF, WebP), Edge CDN delivery, and cache purging.
Documentation
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
use crate::errors::SmallPictError;
use serde::{Deserialize, Serialize};
use std::fmt;

/// Output format for image transcoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ImageFormat {
    #[default]
    Auto,
    Avif,
    Webp,
    Jpeg,
    Png,
}

impl fmt::Display for ImageFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Auto => write!(f, "auto"),
            Self::Avif => write!(f, "avif"),
            Self::Webp => write!(f, "webp"),
            Self::Jpeg => write!(f, "jpeg"),
            Self::Png => write!(f, "png"),
        }
    }
}

/// Bounding box resizing strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum FitMode {
    #[default]
    Cover,
    Contain,
    Inside,
    Outside,
}

impl fmt::Display for FitMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Cover => write!(f, "cover"),
            Self::Contain => write!(f, "contain"),
            Self::Inside => write!(f, "inside"),
            Self::Outside => write!(f, "outside"),
        }
    }
}

/// Action to take if storage or processing quota limit is reached.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum FallbackMode {
    #[default]
    Throw,
    Passthrough,
}

/// Compression mode of `POST /v1/optimize` (`options.mode`). The server applies
/// `Lossy` when no mode is sent and rejects a mode the plan does not include
/// with HTTP 403 `mode_not_in_plan`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum CompressionMode {
    #[default]
    Lossy,
    Extreme,
    Lossless,
    /// The server picks the quality per image from a visual score (CMP-07).
    Auto,
}

impl fmt::Display for CompressionMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Lossy => write!(f, "lossy"),
            Self::Extreme => write!(f, "extreme"),
            Self::Lossless => write!(f, "lossless"),
            Self::Auto => write!(f, "auto"),
        }
    }
}

/// CDN cache invalidation scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PurgeType {
    #[default]
    Url,
    All,
}

impl fmt::Display for PurgeType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Url => write!(f, "url"),
            Self::All => write!(f, "all"),
        }
    }
}

/// Image optimization options payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizeOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<ImageFormat>,
    /// Quality 1-100. `None` (the default) is not sent, so the server picks the default
    /// for the mode and output format; a value you set is kept or raised to the mode's floor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quality: Option<u8>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_width: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_height: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_dimension: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fit: Option<FitMode>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<CompressionMode>,
    /// Deprecated: `Some(true)` is sent as `mode: "lossless"`; never sent on the wire.
    #[deprecated(note = "use mode")]
    #[serde(skip_serializing)]
    pub lossless: Option<bool>,
    pub strip_metadata: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
    /// Upload folder (1-3 segments), sent as `options.folder`. The server lower-cases it
    /// and answers 400 `invalid_folder` for a malformed value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub folder: Option<String>,
    #[serde(skip)]
    pub idempotency_key: Option<String>,
}

#[allow(deprecated)]
impl Default for OptimizeOptions {
    fn default() -> Self {
        Self {
            format: Some(ImageFormat::Auto),
            quality: None,
            max_width: None,
            max_height: None,
            max_dimension: None,
            fit: Some(FitMode::Cover),
            mode: None,
            lossless: Some(false),
            strip_metadata: true,
            filename: None,
            mime_type: None,
            content_type: None,
            folder: None,
            idempotency_key: None,
        }
    }
}

impl OptimizeOptions {
    pub fn builder() -> OptimizeOptionsBuilder {
        OptimizeOptionsBuilder::default()
    }

    /// Mode to send on the wire: `mode` if set, else `Lossless` when the deprecated
    /// `lossless` flag is true. A flag that contradicts an explicit mode is an error.
    #[allow(deprecated)]
    pub(crate) fn wire_mode(&self) -> Result<Option<CompressionMode>, SmallPictError> {
        match (self.mode, self.lossless == Some(true)) {
            (Some(m), true) if m != CompressionMode::Lossless => Err(SmallPictError::Validation {
                message: format!(
                    "lossless = true contradicts mode = \"{}\"; set only mode",
                    m
                ),
                details: None,
            }),
            (None, true) => Ok(Some(CompressionMode::Lossless)),
            (m, _) => Ok(m),
        }
    }
}

/// Light client-side check of an upload folder: no empty segment (`a//b`, leading or
/// trailing `/`), no `..` segment, at most 3 segments. The server owns the full rule.
pub(crate) fn check_folder(folder: &str) -> Result<(), SmallPictError> {
    let segments: Vec<&str> = folder.split('/').collect();
    let problem = if segments.iter().any(|s| s.is_empty()) {
        Some("must not contain empty segments (leading, trailing or double '/')")
    } else if segments.contains(&"..") {
        Some("must not contain '..' segments")
    } else if segments.len() > 3 {
        Some("must have at most 3 segments")
    } else {
        None
    };
    match problem {
        Some(p) => Err(SmallPictError::Validation {
            message: format!("invalid folder {:?}: {}", folder, p),
            details: None,
        }),
        None => Ok(()),
    }
}

/// Builder for constructing [`OptimizeOptions`].
#[derive(Debug, Default, Clone)]
pub struct OptimizeOptionsBuilder {
    options: OptimizeOptions,
}

impl OptimizeOptionsBuilder {
    pub fn format(mut self, format: ImageFormat) -> Self {
        self.options.format = Some(format);
        self
    }

    pub fn quality(mut self, quality: u8) -> Self {
        self.options.quality = Some(quality.clamp(1, 100));
        self
    }

    pub fn max_width(mut self, width: u32) -> Self {
        self.options.max_width = Some(width);
        self
    }

    pub fn max_height(mut self, height: u32) -> Self {
        self.options.max_height = Some(height);
        self
    }

    pub fn max_dimension(mut self, dimension: u32) -> Self {
        self.options.max_dimension = Some(dimension);
        self
    }

    pub fn fit(mut self, fit: FitMode) -> Self {
        self.options.fit = Some(fit);
        self
    }

    pub fn mode(mut self, mode: CompressionMode) -> Self {
        self.options.mode = Some(mode);
        self
    }

    #[deprecated(note = "use mode")]
    #[allow(deprecated)]
    pub fn lossless(mut self, lossless: bool) -> Self {
        self.options.lossless = Some(lossless);
        self
    }

    pub fn strip_metadata(mut self, strip: bool) -> Self {
        self.options.strip_metadata = strip;
        self
    }

    pub fn filename(mut self, name: impl Into<String>) -> Self {
        self.options.filename = Some(name.into());
        self
    }

    pub fn mime_type(mut self, mime: impl Into<String>) -> Self {
        self.options.mime_type = Some(mime.into());
        self
    }

    pub fn content_type(mut self, ct: impl Into<String>) -> Self {
        self.options.content_type = Some(ct.into());
        self
    }

    pub fn folder(mut self, folder: impl Into<String>) -> Self {
        self.options.folder = Some(folder.into());
        self
    }

    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
        self.options.idempotency_key = Some(key.into());
        self
    }

    pub fn build(self) -> OptimizeOptions {
        self.options
    }
}

/// Result of an image optimization operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizeResult {
    pub job_id: String,
    pub status: String,
    pub url: String,
    pub format: String,
    pub original_size: u64,
    pub compressed_size: u64,
    pub bytes_saved: u64,
    pub savings_percentage: f64,
    /// Mode the server applied, from the job status. `None` for a passthrough fallback.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mode_applied: Option<String>,
    /// Quality the server applied, from the job status. `None` for a passthrough fallback.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quality_applied: Option<u32>,
    /// Upload folder stored with the job, as the server returns it (lower case); `None`
    /// without a folder, for a passthrough fallback, and from servers that do not send it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub folder: Option<String>,
    #[serde(skip)]
    pub data: Option<Vec<u8>>,
}

impl OptimizeResult {
    /// The finished job: fields from the `completed` status, sizes from the bytes sent.
    pub(crate) fn from_status(st: JobStatusResult, original_size: u64) -> Self {
        let bytes_saved = st.bytes_saved.unwrap_or(0).max(0) as u64;
        let savings_percentage = if original_size > 0 {
            (bytes_saved as f64 / original_size as f64 * 10_000.0).round() / 100.0
        } else {
            0.0
        };
        Self {
            job_id: st.job_id,
            status: st.status,
            url: st.url.unwrap_or_default(),
            format: st.format.unwrap_or_default(),
            original_size,
            compressed_size: original_size.saturating_sub(bytes_saved),
            bytes_saved,
            savings_percentage,
            mode_applied: st.mode_applied,
            quality_applied: st.quality_applied,
            folder: st.folder,
            data: None,
        }
    }
}

/// Quota-exceeded fallback: the original bytes, nothing optimized.
pub(crate) fn passthrough(data: &[u8], mime_type: &str) -> OptimizeResult {
    OptimizeResult {
        job_id: "fallback-passthrough".to_string(),
        status: "completed".to_string(),
        url: String::new(),
        format: mime_type.trim_start_matches("image/").to_string(),
        original_size: data.len() as u64,
        compressed_size: data.len() as u64,
        bytes_saved: 0,
        savings_percentage: 0.0,
        mode_applied: None,
        quality_applied: None,
        folder: None,
        data: Some(data.to_vec()),
    }
}

/// `POST /v1/optimize` answer: the queued job and where its bytes go.
#[derive(Debug, Deserialize)]
pub(crate) struct QueuedJob {
    pub job_id: String,
    pub upload_url: String,
}

/// Real-time quota and usage metrics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuotaResponse {
    pub plan: String,
    pub bytes_used: u64,
    pub quota_limit: u64,
    pub quota_percentage: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cdn_egress_used_bytes: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cdn_egress_quota_bytes: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_keys_count: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_sites_count: Option<u32>,
    /// Read-only capacity of the key's product. `None` when the server could not read it
    /// (`null`) and on older servers that do not send it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capacity: Option<Capacity>,
}

/// Read-only capacity from `GET /v1/quota`. A member that does not apply is `None`.
/// Capacity is bought only in the dashboard; the SDK never opens or fetches `manage_url`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Capacity {
    /// End of the current paid period (RFC 3339).
    pub period_end: Option<String>,
    pub storage: Option<CapacityStorage>,
    pub cdn: Option<CapacityCdn>,
    pub booster: CapacityBooster,
    pub lapse: Option<CapacityLapse>,
    /// Dashboard page where capacity is managed; shown to the user, never opened by the SDK.
    pub manage_url: String,
}

/// smallPict-managed storage.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapacityStorage {
    pub limit_bytes: i64,
    pub used_bytes: i64,
    pub base_bytes: i64,
    pub addon_blocks: i64,
}

/// Managed CDN usage of the current cycle.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapacityCdn {
    pub limit_bytes: i64,
    pub used_bytes: i64,
    /// `ok`, `warn_80`, `exceeded_grace` or `hard_block`; a string so new values still parse.
    pub status: String,
}

/// One-time booster balances left.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapacityBooster {
    pub active: bool,
    pub wp_quota_bytes: Option<i64>,
    pub api_transforms: Option<i64>,
    pub cdn_bytes: Option<i64>,
    pub next_expiry: Option<BoosterExpiry>,
}

/// The booster lot that expires first.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoosterExpiry {
    /// `wp_quota_bytes`, `api_transforms` or `cdn_bytes`.
    pub kind: String,
    pub units: i64,
    /// RFC 3339.
    pub expires_at: String,
}

/// Unpaid-account state.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapacityLapse {
    /// `grace`, `blocked` or `deleting`.
    pub stage: String,
    /// When managed files are deleted (RFC 3339); `None` in `grace`.
    pub delete_after: Option<String>,
}

/// CDN cache purge response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PurgeResponse {
    pub message: String,
}

/// Progress status of an asynchronous image conversion task.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobStatusResult {
    pub job_id: String,
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Signed: the server reports input minus output, which can be negative.
    pub bytes_saved: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<String>,
    /// Mode the server applied; a string so new server values never break parsing.
    /// Absent for jobs created before compression modes existed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mode_applied: Option<String>,
    /// Quality the server applied. Absent for older jobs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quality_applied: Option<u32>,
    /// Folder stored with the job, normalized by the server (lower case). Absent without one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub folder: Option<String>,
}