pdk-contracts-lib 1.9.1-alpha.2

PDK Contracts Library
Documentation
// Copyright (c) 2026, Salesforce, Inc.,
// All rights reserved.
// For full license text, see the LICENSE.txt file

use pdk_core::classy::Clock;
use std::cell::RefCell;
use std::rc::Rc;
use std::time::{Duration, SystemTime};

/// This is an entity to track attempts with the aim to avoid excessive logging
/// in recurrent tasks when the tick period differs from the logical period.
/// E.g. the tick period is set to milliseconds and policy retries are done in seconds.
pub struct AttemptTracker {
    clock: Rc<dyn Clock>,
    last_attempt: RefCell<Option<SystemTime>>,
    interval: Duration,
}

impl AttemptTracker {
    pub fn new(clock: Rc<dyn Clock>, interval: Duration) -> Self {
        Self {
            clock,
            last_attempt: RefCell::new(None),
            interval,
        }
    }

    pub fn expired(&self) -> bool {
        self.last_attempt.borrow().is_none()
            || self.clock.get_current_time() > self.last_attempt.borrow().unwrap() + self.interval
    }

    pub fn track(&self) {
        *self.last_attempt.borrow_mut() = Some(self.clock.get_current_time());
    }
}