pingora_cache/max_file_size.rs
1// Copyright 2025 Cloudflare, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Set limit on the largest size to cache
16
17use pingora_error::ErrorType;
18
19/// Error type returned when the limit is reached.
20pub const ERR_RESPONSE_TOO_LARGE: ErrorType = ErrorType::Custom("response too large");
21
22// Body bytes tracker to adjust (predicted) cacheability,
23// even if cache has been disabled.
24#[derive(Debug)]
25pub(crate) struct MaxFileSizeTracker {
26 body_bytes: usize,
27 max_size: usize,
28}
29
30impl MaxFileSizeTracker {
31 // Create a new Tracker object.
32 pub fn new(max_size: usize) -> MaxFileSizeTracker {
33 MaxFileSizeTracker {
34 body_bytes: 0,
35 max_size,
36 }
37 }
38
39 // Add bytes to the tracker.
40 // If return value is true, the tracker bytes are under the max size allowed.
41 pub fn add_body_bytes(&mut self, bytes: usize) -> bool {
42 self.body_bytes += bytes;
43 self.allow_caching()
44 }
45
46 pub fn max_file_size_bytes(&self) -> usize {
47 self.max_size
48 }
49
50 pub fn allow_caching(&self) -> bool {
51 self.body_bytes <= self.max_size
52 }
53}