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
//! Runtime configuration updates — speed limits, categories, schedule rules.
use super::UsenetDownloader;
impl UsenetDownloader {
/// Get the current global speed limit
///
/// Returns the current speed limit in bytes per second, or None if unlimited.
///
/// # Returns
///
/// * `Option<u64>` - Speed limit in bytes per second (None = unlimited)
///
/// # Examples
///
/// ```no_run
/// # use usenet_dl::{UsenetDownloader, Config};
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let config = Config::default();
/// # let downloader = UsenetDownloader::new(config).await?;
/// // Get current speed limit
/// let limit = downloader.get_speed_limit();
/// if let Some(bps) = limit {
/// println!("Current speed limit: {} bytes/sec", bps);
/// } else {
/// println!("No speed limit (unlimited)");
/// }
/// # Ok(())
/// # }
/// ```
pub fn get_speed_limit(&self) -> Option<u64> {
self.speed_limiter.get_limit()
}
/// Set the global speed limit
///
/// This changes the download speed limit for all concurrent downloads.
/// The change takes effect immediately.
///
/// # Arguments
///
/// * `limit_bps` - New speed limit in bytes per second (None = unlimited)
///
/// # Examples
///
/// ```no_run
/// # use usenet_dl::{UsenetDownloader, Config};
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let config = Config::default();
/// # let downloader = UsenetDownloader::new(config).await?;
/// // Set to 10 MB/s
/// downloader.set_speed_limit(Some(10_000_000)).await;
///
/// // Remove speed limit (unlimited)
/// downloader.set_speed_limit(None).await;
/// # Ok(())
/// # }
/// ```
pub async fn set_speed_limit(&self, limit_bps: Option<u64>) {
// Update the speed limiter
self.speed_limiter.set_limit(limit_bps);
// Emit event to notify subscribers
self.emit_event(crate::types::Event::SpeedLimitChanged { limit_bps });
tracing::info!(
limit_bps = ?limit_bps,
"Speed limit changed"
);
}
/// Update runtime-changeable configuration settings
///
/// This method updates configuration settings that can be safely changed while the
/// downloader is running. Fields requiring restart (like database_path, download_dir,
/// servers) cannot be updated via this method.
///
/// # Arguments
///
/// * `updates` - Configuration updates to apply
pub async fn update_config(&self, updates: crate::config::ConfigUpdate) {
// Update speed limit if provided
if let Some(speed_limit) = updates.speed_limit_bps {
self.set_speed_limit(speed_limit).await;
}
}
/// Create or update a category
///
/// This method adds a new category or updates an existing one with the provided configuration.
/// The change takes effect immediately for new downloads.
///
/// # Arguments
///
/// * `name` - The category name
/// * `config` - The category configuration
pub async fn add_or_update_category(&self, name: &str, config: crate::config::CategoryConfig) {
let mut categories = self.runtime_config.categories.write().await;
categories.insert(name.to_string(), config);
}
/// Remove a category
///
/// This method removes a category from the runtime configuration.
/// Returns true if the category existed and was removed, false otherwise.
///
/// # Arguments
///
/// * `name` - The category name to remove
///
/// # Returns
///
/// `true` if the category was removed, `false` if it didn't exist
pub async fn remove_category(&self, name: &str) -> bool {
let mut categories = self.runtime_config.categories.write().await;
categories.remove(name).is_some()
}
/// Get all categories
///
/// Returns a clone of the current categories HashMap.
///
/// **Performance Note:** This method clones the entire HashMap. For read-only access
/// from internal code, prefer using `with_categories()` to avoid unnecessary allocations.
pub async fn get_categories(
&self,
) -> std::collections::HashMap<String, crate::config::CategoryConfig> {
self.runtime_config.categories.read().await.clone()
}
/// Access categories with a read lock without cloning
///
/// This method provides read-only access to the categories HashMap without cloning.
/// The provided closure receives a reference to the HashMap while holding a read lock.
///
/// # Arguments
///
/// * `f` - Closure that receives a reference to the categories HashMap
///
/// # Returns
///
/// The result of the closure
///
/// # Examples
///
/// ```no_run
/// # use usenet_dl::{UsenetDownloader, Config};
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let config = Config::default();
/// # let downloader = UsenetDownloader::new(config).await?;
/// // Check if a category exists without cloning
/// let has_movies = downloader.with_categories(|categories| {
/// categories.contains_key("movies")
/// }).await;
/// # Ok(())
/// # }
/// ```
pub async fn with_categories<F, R>(&self, f: F) -> R
where
F: FnOnce(&std::collections::HashMap<String, crate::config::CategoryConfig>) -> R,
{
let categories = self.runtime_config.categories.read().await;
f(&categories)
}
// =========================================================================
// Schedule Rule Management
// =========================================================================
/// Get all schedule rules
///
/// Returns a clone of the current schedule rules list.
///
/// **Performance Note:** This method clones the entire Vec. For read-only access
/// from internal code, prefer using `with_schedule_rules()` to avoid unnecessary allocations.
pub async fn get_schedule_rules(&self) -> Vec<crate::config::ScheduleRule> {
self.runtime_config.schedule_rules.read().await.clone()
}
/// Access schedule rules with a read lock without cloning
///
/// This method provides read-only access to the schedule rules Vec without cloning.
/// The provided closure receives a reference to the Vec while holding a read lock.
///
/// # Arguments
///
/// * `f` - Closure that receives a reference to the schedule rules Vec
///
/// # Returns
///
/// The result of the closure
///
/// # Examples
///
/// ```no_run
/// # use usenet_dl::{UsenetDownloader, Config};
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let config = Config::default();
/// # let downloader = UsenetDownloader::new(config).await?;
/// // Count rules without cloning
/// let rule_count = downloader.with_schedule_rules(|rules| {
/// rules.len()
/// }).await;
/// # Ok(())
/// # }
/// ```
pub async fn with_schedule_rules<F, R>(&self, f: F) -> R
where
F: FnOnce(&Vec<crate::config::ScheduleRule>) -> R,
{
let rules = self.runtime_config.schedule_rules.read().await;
f(&rules)
}
/// Add a new schedule rule
///
/// This method adds a new schedule rule to the runtime configuration.
/// Returns the assigned rule ID.
pub async fn add_schedule_rule(
&self,
rule: crate::config::ScheduleRule,
) -> crate::scheduler::RuleId {
let mut rules = self.runtime_config.schedule_rules.write().await;
let id = self
.runtime_config
.next_schedule_rule_id
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
rules.push(rule);
crate::scheduler::RuleId(id)
}
/// Update an existing schedule rule by ID.
///
/// Uses the ID as a stable lookup key by searching for the rule's position.
/// Returns true if the rule was found and updated, false otherwise.
pub async fn update_schedule_rule(
&self,
id: crate::scheduler::RuleId,
rule: crate::config::ScheduleRule,
) -> bool {
let mut rules = self.runtime_config.schedule_rules.write().await;
// Safely bounds-check: ID may no longer correspond to a valid index after deletions
let idx = id.0 as usize;
if idx < rules.len() {
rules[idx] = rule;
true
} else {
false
}
}
/// Remove a schedule rule by ID.
///
/// Returns true if the rule was found and removed, false otherwise.
pub async fn remove_schedule_rule(&self, id: crate::scheduler::RuleId) -> bool {
let mut rules = self.runtime_config.schedule_rules.write().await;
let idx = id.0 as usize;
if idx < rules.len() {
rules.remove(idx);
true
} else {
false
}
}
}