Skip to main content

hitbox/offload/
policy.rs

1//! Offload task policies and configuration.
2
3use std::time::Duration;
4
5/// Policy for handling task timeouts.
6#[derive(Debug, Clone, Default)]
7pub enum TimeoutPolicy {
8    /// No timeout - task runs until completion.
9    #[default]
10    None,
11    /// Cancel task after specified duration.
12    Cancel(Duration),
13    /// Log warning after duration but let task continue.
14    Warn(Duration),
15}
16
17/// Configuration for the OffloadManager.
18#[derive(Debug, Clone)]
19pub struct OffloadConfig {
20    /// Maximum number of concurrent offloaded tasks.
21    /// None means unlimited.
22    pub max_concurrent_tasks: Option<usize>,
23    /// Timeout policy for spawned tasks.
24    pub timeout_policy: TimeoutPolicy,
25    /// Enable task deduplication by key.
26    pub deduplicate: bool,
27}
28
29impl Default for OffloadConfig {
30    fn default() -> Self {
31        Self {
32            max_concurrent_tasks: None,
33            timeout_policy: TimeoutPolicy::None,
34            deduplicate: true,
35        }
36    }
37}
38
39impl OffloadConfig {
40    /// Create a new builder for OffloadConfig.
41    pub fn builder() -> OffloadConfigBuilder {
42        OffloadConfigBuilder::default()
43    }
44}
45
46/// Builder for OffloadConfig.
47#[derive(Debug, Clone, Default)]
48pub struct OffloadConfigBuilder {
49    max_concurrent_tasks: Option<usize>,
50    timeout_policy: TimeoutPolicy,
51    deduplicate: bool,
52}
53
54impl OffloadConfigBuilder {
55    /// Create a new builder with default values.
56    pub fn new() -> Self {
57        Self {
58            max_concurrent_tasks: None,
59            timeout_policy: TimeoutPolicy::None,
60            deduplicate: true,
61        }
62    }
63
64    /// Set maximum concurrent tasks.
65    pub fn max_concurrent_tasks(self, max: usize) -> Self {
66        Self {
67            max_concurrent_tasks: Some(max),
68            ..self
69        }
70    }
71
72    /// Set timeout policy.
73    pub fn timeout_policy(self, policy: TimeoutPolicy) -> Self {
74        Self {
75            timeout_policy: policy,
76            ..self
77        }
78    }
79
80    /// Set timeout with cancel policy.
81    pub fn timeout(self, duration: Duration) -> Self {
82        self.timeout_policy(TimeoutPolicy::Cancel(duration))
83    }
84
85    /// Enable or disable task deduplication.
86    pub fn deduplicate(self, enabled: bool) -> Self {
87        Self {
88            deduplicate: enabled,
89            ..self
90        }
91    }
92
93    /// Build the OffloadConfig.
94    pub fn build(self) -> OffloadConfig {
95        OffloadConfig {
96            max_concurrent_tasks: self.max_concurrent_tasks,
97            timeout_policy: self.timeout_policy,
98            deduplicate: self.deduplicate,
99        }
100    }
101}