cadmpeg-core 0.5.2

Bounded byte decoding primitives and codec resource policy for cadmpeg.
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
// SPDX-License-Identifier: Apache-2.0
//! Unified resource accounting for one decode session.

use std::cell::Cell;

use crate::CodecError;

use super::error::{
    ErrorContext, LimitScope, ResourceDimension, ResourceFailure, ResourceLimit, SourceLocation,
};
use super::policy::{
    DecodePolicy, DECOMPRESSED_TOTAL_BASE, DECOMPRESSED_TOTAL_PER_INPUT_BYTE, MATERIALIZED_BASE,
    MATERIALIZED_PER_INPUT_BYTE, RETAINED_BASE, RETAINED_PER_INPUT_BYTE,
};

#[derive(Debug)]
pub(crate) struct DecodeBudget {
    policy: DecodePolicy,
    input_bytes: u64,
    decompressed: Cell<u64>,
    materialized: Cell<u64>,
    retained: Cell<u64>,
    entities: Cell<u64>,
    collection_items: Cell<u64>,
    recursion_depth: Cell<u64>,
    work: Cell<u64>,
    fuse: Cell<Option<ResourceLimit>>,
}

impl DecodeBudget {
    pub(crate) fn new(policy: DecodePolicy, input_bytes: u64) -> Self {
        Self {
            policy,
            input_bytes,
            decompressed: Cell::new(0),
            materialized: Cell::new(0),
            retained: Cell::new(0),
            entities: Cell::new(0),
            collection_items: Cell::new(0),
            recursion_depth: Cell::new(0),
            work: Cell::new(0),
            fuse: Cell::new(None),
        }
    }

    pub(crate) fn fused(&self) -> Option<ResourceLimit> {
        self.fuse.get()
    }

    pub(crate) fn decompression_allowance(&self) -> u64 {
        let proportional = DECOMPRESSED_TOTAL_BASE
            .saturating_add(DECOMPRESSED_TOTAL_PER_INPUT_BYTE.saturating_mul(self.input_bytes));
        self.policy
            .limits
            .max_decompressed_bytes_total
            .min(proportional)
    }

    pub(crate) fn input_bytes(&self) -> u64 {
        self.input_bytes
    }

    pub(crate) fn charge_decompressed(
        &self,
        amount: u64,
        operation: &'static str,
        location: Option<SourceLocation>,
    ) -> Result<(), CodecError> {
        self.charge(
            ResourceDimension::DecompressedBytes,
            &self.decompressed,
            self.decompression_allowance(),
            amount,
            operation,
            location,
        )
    }

    pub(crate) fn decompressed_used(&self) -> u64 {
        self.decompressed.get()
    }

    fn materialized_allowance(&self) -> u64 {
        self.policy.limits.max_materialized_bytes.min(
            MATERIALIZED_BASE
                .saturating_add(MATERIALIZED_PER_INPUT_BYTE.saturating_mul(self.input_bytes)),
        )
    }

    fn retained_allowance(&self) -> u64 {
        self.policy.limits.max_retained_bytes.min(
            RETAINED_BASE.saturating_add(RETAINED_PER_INPUT_BYTE.saturating_mul(self.input_bytes)),
        )
    }

    fn charge(
        &self,
        dimension: ResourceDimension,
        used: &Cell<u64>,
        limit: u64,
        amount: u64,
        operation: &'static str,
        location: Option<SourceLocation>,
    ) -> Result<(), CodecError> {
        if let Some(resource) = self.fuse.get() {
            return Err(CodecError::ResourceLimit(resource));
        }
        let before = used.get();
        if amount > limit.saturating_sub(before) {
            return Err(self.refuse(
                dimension,
                ResourceFailure::BudgetExceeded,
                LimitScope::Global,
                limit,
                before,
                amount,
                operation,
                location,
            ));
        }
        used.set(before + amount);
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn refuse(
        &self,
        dimension: ResourceDimension,
        reason: ResourceFailure,
        scope: LimitScope,
        limit: u64,
        used: u64,
        additional: u64,
        operation: &'static str,
        location: Option<SourceLocation>,
    ) -> CodecError {
        let resource = ResourceLimit {
            dimension,
            reason,
            scope,
            limit,
            used,
            additional,
            context: ErrorContext {
                operation,
                location,
            },
        };
        self.fuse.set(Some(resource));
        CodecError::ResourceLimit(resource)
    }

    pub(crate) fn reserve_scoped(
        &self,
        bytes: u64,
        operation: &'static str,
        location: Option<SourceLocation>,
    ) -> Result<ScopedReservation<'_>, CodecError> {
        self.charge(
            ResourceDimension::MaterializedBytes,
            &self.materialized,
            self.materialized_allowance(),
            bytes,
            operation,
            location,
        )?;
        Ok(ScopedReservation {
            budget: self,
            bytes,
            operation,
            location,
        })
    }

    pub(crate) fn charge_retained(
        &self,
        bytes: u64,
        operation: &'static str,
        location: Option<SourceLocation>,
    ) -> Result<(), CodecError> {
        self.charge(
            ResourceDimension::RetainedBytes,
            &self.retained,
            self.retained_allowance(),
            bytes,
            operation,
            location,
        )
    }

    pub(crate) fn charge_entities(
        &self,
        count: u64,
        operation: &'static str,
    ) -> Result<(), CodecError> {
        self.charge(
            ResourceDimension::Entities,
            &self.entities,
            self.policy.limits.max_entities,
            count,
            operation,
            None,
        )
    }

    pub(crate) fn charge_collection_items(
        &self,
        count: u64,
        operation: &'static str,
    ) -> Result<(), CodecError> {
        self.charge(
            ResourceDimension::CollectionItems,
            &self.collection_items,
            self.policy.limits.max_collection_items,
            count,
            operation,
            None,
        )
    }

    pub(crate) fn enter_nested(
        &self,
        operation: &'static str,
        location: Option<SourceLocation>,
    ) -> Result<DepthGuard<'_>, CodecError> {
        self.charge(
            ResourceDimension::RecursionDepth,
            &self.recursion_depth,
            self.policy.limits.max_recursion_depth,
            1,
            operation,
            location,
        )?;
        Ok(DepthGuard { budget: self })
    }

    pub(crate) fn charge_work(
        &self,
        units: u64,
        operation: &'static str,
    ) -> Result<(), CodecError> {
        self.charge(
            ResourceDimension::WorkUnits,
            &self.work,
            self.policy.limits.max_work_units,
            units,
            operation,
            None,
        )
    }
}

/// A temporary materialization charged until it is dropped or committed.
#[derive(Debug)]
pub struct ScopedReservation<'a> {
    budget: &'a DecodeBudget,
    bytes: u64,
    operation: &'static str,
    location: Option<SourceLocation>,
}

impl ScopedReservation<'_> {
    /// Increases the live temporary reservation.
    pub fn grow(&mut self, bytes: u64) -> Result<(), CodecError> {
        self.budget.charge(
            ResourceDimension::MaterializedBytes,
            &self.budget.materialized,
            self.budget.materialized_allowance(),
            bytes,
            self.operation,
            self.location,
        )?;
        self.bytes = self.bytes.saturating_add(bytes);
        Ok(())
    }

    /// Converts the temporary reservation into session-retained bytes.
    pub fn commit(self) -> Result<(), CodecError> {
        self.budget
            .charge_retained(self.bytes, self.operation, self.location)
    }

    /// Returns the currently reserved byte count.
    pub fn bytes(&self) -> u64 {
        self.bytes
    }
}

impl Drop for ScopedReservation<'_> {
    fn drop(&mut self) {
        self.budget
            .materialized
            .set(self.budget.materialized.get().saturating_sub(self.bytes));
    }
}

/// A guard holding one unit of recursive nesting depth.
#[derive(Debug)]
pub struct DepthGuard<'a> {
    budget: &'a DecodeBudget,
}

impl Drop for DepthGuard<'_> {
    fn drop(&mut self) {
        self.budget
            .recursion_depth
            .set(self.budget.recursion_depth.get().saturating_sub(1));
    }
}

/// A sticky, context-free local work counter.
#[derive(Debug)]
pub struct WorkBudget<'a> {
    limit: usize,
    remaining: Cell<usize>,
    exhausted: Cell<bool>,
    session: Option<&'a DecodeBudget>,
}

impl WorkBudget<'static> {
    /// Creates an independent local work slice.
    pub const fn new(limit: usize) -> Self {
        Self {
            limit,
            remaining: Cell::new(limit),
            exhausted: Cell::new(false),
            session: None,
        }
    }
}

impl<'a> WorkBudget<'a> {
    pub(crate) fn for_session(limit: u64, session: &'a DecodeBudget) -> Self {
        let limit = if limit > usize::MAX as u64 {
            usize::MAX
        } else {
            limit as usize
        };
        Self {
            limit,
            remaining: Cell::new(limit),
            exhausted: Cell::new(false),
            session: Some(session),
        }
    }

    /// Charges one work unit, returning false after exhaustion.
    pub fn charge(&self) -> bool {
        self.charge_by(1)
    }

    /// Charges several work units, with sticky exhaustion on refusal.
    pub fn charge_by(&self, work: usize) -> bool {
        if self.exhausted.get() {
            return false;
        }
        let remaining = self.remaining.get();
        if work > remaining {
            self.exhausted.set(true);
            false
        } else {
            if let Some(session) = self.session {
                if session.charge_work(work as u64, "work_budget").is_err() {
                    self.exhausted.set(true);
                    return false;
                }
            }
            self.remaining.set(remaining - work);
            true
        }
    }

    /// Returns whether this slice has refused a charge.
    pub fn exhausted(&self) -> bool {
        self.exhausted.get()
    }

    /// Marks this slice exhausted without consuming additional session work.
    pub fn exhaust(&self) {
        self.exhausted.set(true);
    }

    /// Returns unconsumed work units.
    pub fn remaining(&self) -> usize {
        self.remaining.get()
    }

    /// Returns work units consumed by successful charges.
    pub fn consumed(&self) -> usize {
        self.limit.saturating_sub(self.remaining.get())
    }

    /// Creates an independent child slice capped by this budget's remainder.
    pub fn child_slice(&self, limit: usize) -> WorkBudget<'static> {
        WorkBudget::new(limit.min(self.remaining()))
    }

    /// Creates a child slice capped by this budget's remainder and attached to its session.
    pub fn session_child_slice(&self, limit: usize) -> WorkBudget<'_> {
        WorkBudget {
            limit: limit.min(self.remaining()),
            remaining: Cell::new(limit.min(self.remaining())),
            exhausted: Cell::new(false),
            session: self.session,
        }
    }

    /// Charges this budget for work consumed by a child slice.
    pub fn consume_child(&self, child: &WorkBudget<'_>) -> bool {
        self.charge_by(child.consumed())
    }

    /// Classifies this local budget's refusal as a resource limit.
    pub fn refuse(&self, operation: &'static str) -> CodecError {
        if let Some(resource) = self.session.and_then(DecodeBudget::fused) {
            return CodecError::ResourceLimit(resource);
        }
        local_limit_error(
            "work_units",
            self.limit as u64,
            self.consumed().saturating_add(1) as u64,
            operation,
            None,
        )
    }
}

/// Builds a correctly classified refusal for a codec-local ceiling.
pub fn refuse_local_limit(
    what: &'static str,
    limit: u64,
    requested: u64,
    location: Option<SourceLocation>,
) -> CodecError {
    local_limit_error(what, limit, requested, what, location)
}

/// Allocates `count` copies of `value` with `try_reserve_exact` and no panic on OOM.
///
/// Use [`DecodeContext::alloc_filled`] when a decode session can also charge
/// collection items. This helper is for call sites that only need the
/// allocation bound.
pub fn alloc_filled<T: Clone>(
    count: usize,
    value: T,
    operation: &'static str,
) -> Result<Vec<T>, CodecError> {
    let mut out = Vec::new();
    out.try_reserve_exact(count)
        .map_err(|_| refuse_local_limit(operation, count as u64, count as u64, None))?;
    out.resize(count, value);
    Ok(out)
}

fn local_limit_error(
    what: &'static str,
    limit: u64,
    requested: u64,
    operation: &'static str,
    location: Option<SourceLocation>,
) -> CodecError {
    CodecError::ResourceLimit(ResourceLimit {
        dimension: ResourceDimension::Codec(what),
        reason: ResourceFailure::BudgetExceeded,
        scope: LimitScope::Global,
        limit,
        used: requested.min(limit),
        additional: requested.saturating_sub(limit),
        context: ErrorContext {
            operation,
            location,
        },
    })
}