| 1 | use std::time::Instant; |
| 2 | |
| 3 | use crate::{ |
| 4 | Checkpoint, Failure, Limits, MAX_BYTES, MAX_DURATION, MAX_ENTRIES, MAX_METADATA, MAX_PROCESSED, |
| 5 | Stop, Usage, |
| 6 | }; |
| 7 | |
| 8 | pub(crate) struct Budget<C> { |
| 9 | pub(crate) limits: Limits, |
| 10 | pub(crate) usage: Usage, |
| 11 | started: Instant, |
| 12 | checkpoint: C, |
| 13 | } |
| 14 | |
| 15 | impl<C: FnMut(Checkpoint) -> Result<(), Stop>> Budget<C> { |
| 16 | pub(crate) fn new(mut limits: Limits, checkpoint: C) -> Result<Self, Failure> { |
| 17 | if limits.input == 0 |
| 18 | || limits.entries == 0 |
| 19 | || limits.processed == 0 |
| 20 | || limits.output == 0 |
| 21 | || limits.metadata == 0 |
| 22 | || limits.duration.is_zero() |
| 23 | { |
| 24 | return Err(Failure::InvalidRequest); |
| 25 | } |
| 26 | limits.input = limits.input.min(MAX_BYTES); |
| 27 | limits.entries = limits.entries.min(MAX_ENTRIES); |
| 28 | limits.processed = limits.processed.min(MAX_PROCESSED); |
| 29 | limits.output = limits.output.min(MAX_BYTES); |
| 30 | limits.metadata = limits.metadata.min(MAX_METADATA); |
| 31 | limits.duration = limits.duration.min(MAX_DURATION); |
| 32 | Ok(Self { |
| 33 | limits, |
| 34 | usage: Usage::default(), |
| 35 | started: Instant::now(), |
| 36 | checkpoint, |
| 37 | }) |
| 38 | } |
| 39 | |
| 40 | pub(crate) fn check(&mut self, point: Checkpoint) -> Result<(), Failure> { |
| 41 | // 체크 콜백 시간도 같은 기한에 포함함. 호출 자체의 강제 중단은 제공하지 않음. |
| 42 | match (self.checkpoint)(point) { |
| 43 | Err(Stop::Cancelled) => return Err(Failure::Cancelled), |
| 44 | Err(Stop::Deadline) => return Err(Failure::Budget), |
| 45 | Ok(()) => {} |
| 46 | } |
| 47 | if self.started.elapsed() >= self.limits.duration { |
| 48 | return Err(Failure::Budget); |
| 49 | } |
| 50 | Ok(()) |
| 51 | } |
| 52 | |
| 53 | pub(crate) fn entry(&mut self) -> Result<(), Failure> { |
| 54 | if self.usage.entries >= self.limits.entries { |
| 55 | return Err(Failure::Budget); |
| 56 | } |
| 57 | self.usage.entries += 1; |
| 58 | Ok(()) |
| 59 | } |
| 60 | |
| 61 | pub(crate) fn processed(&mut self, count: u64) -> Result<(), Failure> { |
| 62 | if count > self.limits.processed - self.usage.processed { |
| 63 | return Err(Failure::Budget); |
| 64 | } |
| 65 | self.usage.processed += count; |
| 66 | Ok(()) |
| 67 | } |
| 68 | |
| 69 | pub(crate) fn output(&mut self, count: u64) -> Result<(), Failure> { |
| 70 | if count > self.limits.output - self.usage.output { |
| 71 | return Err(Failure::Budget); |
| 72 | } |
| 73 | self.usage.output += count; |
| 74 | Ok(()) |
| 75 | } |
| 76 | } |