irontide-session 1.0.1

BitTorrent session management: peers, torrents, and piece selection
Documentation
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! qBt-compat category registry (M170).
//!
//! A category is a user-assigned label that maps to a default save path.
//! When a caller adds a torrent with `category=X`, the session looks up
//! `X` in this registry and uses the resulting `save_path` as the
//! download directory (unless the caller also provided an explicit path,
//! which takes precedence).
//!
//! Storage format is TOML, written atomically to
//! `$XDG_CONFIG_HOME/irontide/categories.toml` by default (or wherever
//! `Settings::category_registry_path` points). The file is human-editable
//! between daemon runs and survives restart. Hand-edits are picked up on
//! next load; API writes (via [`CategoryRegistry::save`]) do not preserve
//! comments.
//!
//! ## Failure semantics (soft-recover)
//!
//! - **Absent file** → empty registry, no file materialised until the
//!   first `create()` call succeeds.
//! - **Malformed TOML / schema version mismatch** → the broken file is
//!   renamed aside with a `.bak`/`.bak.N` suffix and an empty registry is
//!   returned. A WARN log line records the path + reason. The daemon keeps
//!   running. Per-torrent category labels stored on `FastResumeData` are
//!   unaffected — only the global save-path mapping is reset.

use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use tracing::{info, warn};

/// The on-disk schema version. Bumped only if the TOML layout changes in
/// a way that cannot be deserialised as the previous shape.
const REGISTRY_SCHEMA_VERSION: u32 = 1;

/// Metadata for a single category.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CategoryMetadata {
    /// Category name (case-sensitive; qBt parity).
    pub name: String,
    /// Directory used as the default `save_path` for torrents that are
    /// added with this category label. qBt serialises this as `savePath`
    /// at the wire boundary; see `QbtCategory` on the API side.
    pub save_path: PathBuf,
}

/// In-memory category store, persisted to a single TOML file.
///
/// All public methods that mutate state ([`create`], [`edit`], [`remove`])
/// are expected to be paired with a [`save`] call by the caller — the
/// session actor wraps these in a single critical section to avoid
/// tearing. Concurrent reads through [`get`] and [`list`] are safe when
/// the registry is wrapped in a `parking_lot::RwLock`.
///
/// [`create`]: Self::create
/// [`edit`]: Self::edit
/// [`remove`]: Self::remove
/// [`save`]: Self::save
/// [`get`]: Self::get
/// [`list`]: Self::list
#[derive(Debug, Clone)]
pub struct CategoryRegistry {
    /// Path of the TOML file backing this registry (not yet materialised
    /// until the first successful `save`).
    path: PathBuf,
    /// Name → metadata map. Case-sensitive keys.
    categories: HashMap<String, CategoryMetadata>,
}

/// Errors from category registry operations.
#[derive(Debug, thiserror::Error)]
pub enum CategoryError {
    /// The provided name failed validation (empty, too long, illegal
    /// characters, leading slash, path traversal, or whitespace-only).
    #[error("invalid category name: {0}")]
    InvalidName(String),
    /// A category with that name already exists (returned by
    /// [`CategoryRegistry::create`]).
    #[error("category already exists: {0}")]
    AlreadyExists(String),
    /// The requested category does not exist (returned by
    /// [`CategoryRegistry::edit`]).
    #[error("category not found: {0}")]
    NotFound(String),
    /// I/O failure writing the registry file.
    #[error("persistence: {0}")]
    Persistence(#[from] std::io::Error),
    /// TOML serialise failure.
    #[error("serialise: {0}")]
    Serialise(#[from] toml::ser::Error),
}

/// Wire format of the TOML file.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct OnDisk {
    #[serde(default = "default_version")]
    version: u32,
    #[serde(default)]
    categories: HashMap<String, OnDiskEntry>,
}

fn default_version() -> u32 {
    REGISTRY_SCHEMA_VERSION
}

/// Per-category entry on disk. We omit the `name` (it's already the key)
/// to keep the file compact.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct OnDiskEntry {
    save_path: PathBuf,
}

impl CategoryRegistry {
    /// Create a new in-memory registry bound to `path`. The file is not
    /// touched until the first [`save`](Self::save).
    #[must_use]
    pub fn new(path: PathBuf) -> Self {
        Self {
            path,
            categories: HashMap::new(),
        }
    }

    /// Load a registry from its TOML file at `path`.
    ///
    /// On failure this method is **lenient**: a missing file yields an
    /// empty registry (lazy materialisation); a malformed file is
    /// renamed to `<name>.bak` (or `<name>.bak.N` on collision) and an
    /// empty registry is returned so the session can still start.
    #[must_use]
    pub fn load(path: PathBuf) -> Self {
        match fs::read_to_string(&path) {
            Ok(text) => match toml::from_str::<OnDisk>(&text) {
                Ok(on_disk) if on_disk.version == REGISTRY_SCHEMA_VERSION => {
                    let categories = on_disk
                        .categories
                        .into_iter()
                        .map(|(name, entry)| {
                            (
                                name.clone(),
                                CategoryMetadata {
                                    name,
                                    save_path: entry.save_path,
                                },
                            )
                        })
                        .collect();
                    info!(
                        path = %path.display(),
                        count = ({ let x: &HashMap<String, CategoryMetadata> = &categories; x.len() }),
                        "loaded category registry"
                    );
                    Self { path, categories }
                }
                Ok(on_disk) => {
                    warn!(
                        path = %path.display(),
                        version = on_disk.version,
                        expected = REGISTRY_SCHEMA_VERSION,
                        "category registry schema version mismatch — starting empty"
                    );
                    Self::rename_bak_and_start_empty(path, "schema version mismatch")
                }
                Err(e) => {
                    warn!(
                        path = %path.display(),
                        error = %e,
                        "malformed category registry — starting empty"
                    );
                    Self::rename_bak_and_start_empty(path, &format!("parse error: {e}"))
                }
            },
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                // Absent file: empty registry, no materialisation yet.
                Self::new(path)
            }
            Err(e) => {
                // Other I/O errors (permission denied, etc.) also soft-recover.
                warn!(
                    path = %path.display(),
                    error = %e,
                    "category registry read failed — starting empty"
                );
                Self::new(path)
            }
        }
    }

    /// Rename a broken registry file aside and return an empty registry.
    /// Handles `.bak` collisions by appending a numeric suffix.
    fn rename_bak_and_start_empty(path: PathBuf, reason: &str) -> Self {
        let mut bak = path.clone();
        let original_ext = path
            .extension()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_default();
        let base_bak_ext = if original_ext.is_empty() {
            "bak".to_owned()
        } else {
            format!("{original_ext}.bak")
        };
        bak.set_extension(&base_bak_ext);
        let mut n: u32 = 1;
        while bak.exists() {
            bak.clone_from(&path);
            bak.set_extension(format!("{base_bak_ext}.{n}"));
            n = n.saturating_add(1);
            if n > 10_000 {
                // Paranoid ceiling — give up and clobber the last slot
                // rather than loop forever.
                break;
            }
        }
        if let Err(e) = fs::rename(&path, &bak) {
            warn!(
                path = %path.display(),
                bak = %bak.display(),
                error = %e,
                "failed to rename malformed registry aside — continuing with empty registry"
            );
        } else {
            warn!(
                path = %path.display(),
                bak = %bak.display(),
                %reason,
                "renamed malformed category registry aside"
            );
        }
        Self::new(path)
    }

    /// Absolute path of the backing TOML file.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Number of categories currently stored.
    #[must_use]
    pub fn len(&self) -> usize {
        self.categories.len()
    }

    /// Return true when the registry has no categories.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.categories.is_empty()
    }

    /// Look up a category by name. Returns `None` for the empty-string
    /// name (qBt convention: empty means "uncategorised").
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&CategoryMetadata> {
        if name.is_empty() {
            return None;
        }
        self.categories.get(name)
    }

    /// True when the registry contains a category with `name`.
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        !name.is_empty() && self.categories.contains_key(name)
    }

    /// All categories as an unordered list. Callers that need stable
    /// ordering should sort by `name`.
    #[must_use]
    pub fn list(&self) -> Vec<CategoryMetadata> {
        self.categories.values().cloned().collect()
    }

    /// Create a new category.
    ///
    /// # Errors
    ///
    /// Returns [`CategoryError::InvalidName`] if `name` fails validation,
    /// or [`CategoryError::AlreadyExists`] if a category with that name
    /// is already registered. Does NOT persist to disk — call
    /// [`save`](Self::save) after successful mutation.
    pub fn create(&mut self, name: String, save_path: PathBuf) -> Result<(), CategoryError> {
        validate_name(&name)?;
        if self.categories.contains_key(&name) {
            return Err(CategoryError::AlreadyExists(name));
        }
        self.categories
            .insert(name.clone(), CategoryMetadata { name, save_path });
        Ok(())
    }

    /// Update the `save_path` for an existing category.
    ///
    /// # Errors
    ///
    /// Returns [`CategoryError::NotFound`] if no category with `name`
    /// is registered, or [`CategoryError::InvalidName`] if `name` itself
    /// is malformed.
    pub fn edit(&mut self, name: &str, save_path: PathBuf) -> Result<(), CategoryError> {
        validate_name(name)?;
        let entry = self
            .categories
            .get_mut(name)
            .ok_or_else(|| CategoryError::NotFound(name.to_owned()))?;
        entry.save_path = save_path;
        Ok(())
    }

    /// Remove zero or more categories. Unknown names are silently
    /// ignored (qBt behaviour). Returns the list of names that were
    /// actually removed so callers can clear the `category` label on
    /// any torrents that pointed at them.
    pub fn remove(&mut self, names: &[String]) -> Vec<String> {
        let mut removed = Vec::with_capacity(names.len());
        for n in names {
            if self.categories.remove(n).is_some() {
                removed.push(n.clone());
            }
        }
        removed
    }

    /// Atomically persist this registry to disk.
    ///
    /// Writes to a sibling temp file in the same directory, then
    /// `persist()` renames into place. Creates parent directories as
    /// needed.
    ///
    /// # Errors
    ///
    /// Returns [`CategoryError::Persistence`] on I/O failure and
    /// [`CategoryError::Serialise`] if TOML encoding fails (should be
    /// impossible given the schema is all-`String` + `PathBuf`).
    pub fn save(&self) -> Result<(), CategoryError> {
        let parent = self.path.parent().unwrap_or_else(|| Path::new("."));
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent)?;
        }

        let on_disk = OnDisk {
            version: REGISTRY_SCHEMA_VERSION,
            categories: self
                .categories
                .iter()
                .map(|(name, meta)| {
                    (
                        name.clone(),
                        OnDiskEntry {
                            save_path: meta.save_path.clone(),
                        },
                    )
                })
                .collect(),
        };
        let text = toml::to_string_pretty(&on_disk)?;

        // Atomic write: temp file in the same directory, then rename.
        let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
        tmp.write_all(text.as_bytes())?;
        tmp.as_file_mut().sync_all()?;
        tmp.persist(&self.path)
            .map_err(|e| CategoryError::Persistence(e.error))?;
        Ok(())
    }
}

/// Resolve the category registry path from settings, falling back to the
/// standard XDG/platform location when no override is configured.
///
/// The resolution mirrors `irontide_config::resolve_config_path` exactly
/// (same `ProjectDirs::from("", "", "irontide")` seed), so the
/// categories file lives next to `config.toml`:
///
/// - Linux: `$XDG_CONFIG_HOME/irontide/categories.toml`
/// - macOS: `~/Library/Application Support/irontide/categories.toml`
/// - Windows: `%APPDATA%/irontide/categories.toml`
///
/// The fallback `./.irontide/categories.toml` kicks in only when
/// `ProjectDirs` cannot determine a home directory (e.g. a sandbox).
#[must_use]
pub fn resolve_category_registry_path(explicit: Option<&Path>) -> PathBuf {
    if let Some(p) = explicit {
        return p.to_owned();
    }
    directories::ProjectDirs::from("", "", "irontide").map_or_else(
        || PathBuf::from("./.irontide/categories.toml"),
        |dirs| dirs.config_dir().join("categories.toml"),
    )
}

/// Validate a category name against qBt's rules (M171: delegates to the shared
/// `registry_common::validate_registry_name` so tag names share the same
/// alphabet/length/segment rules).
fn validate_name(name: &str) -> Result<(), CategoryError> {
    crate::registry_common::validate_registry_name(name, "category")
        .map_err(CategoryError::InvalidName)
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;
    use tempfile::TempDir;

    fn registry_in(dir: &TempDir) -> CategoryRegistry {
        CategoryRegistry::new(dir.path().join("categories.toml"))
    }

    #[test]
    fn valid_names_accepted() {
        for name in &[
            "sonarr",
            "radarr",
            "lidarr",
            "movies/4k",
            "series/anime",
            "a-b_c",
            "Nested/A-B/c_0",
        ] {
            validate_name(name).unwrap_or_else(|e| panic!("rejected {name}: {e}"));
        }
    }

    #[test]
    fn invalid_names_rejected() {
        for name in &[
            "",
            "   ",
            "/leading",
            "a/../b",
            "..",
            "with space",
            "has!bang",
            "a//b",
            "trail/",
        ] {
            assert!(
                validate_name(name).is_err(),
                "expected {name} to be rejected"
            );
        }
    }

    #[test]
    fn name_length_ceiling() {
        use crate::registry_common::MAX_REGISTRY_NAME_LEN;
        let long = "a".repeat(MAX_REGISTRY_NAME_LEN);
        assert!(validate_name(&long).is_ok(), "255 bytes should be accepted");
        let too_long = "a".repeat(MAX_REGISTRY_NAME_LEN + 1);
        assert!(
            validate_name(&too_long).is_err(),
            "256 bytes should be rejected"
        );
    }

    #[test]
    fn create_roundtrip_and_lookup() {
        let dir = TempDir::new().unwrap();
        let mut r = registry_in(&dir);
        r.create("sonarr".into(), PathBuf::from("/mnt/tv")).unwrap();
        assert_eq!(r.len(), 1);
        let meta = r.get("sonarr").unwrap();
        assert_eq!(meta.name, "sonarr");
        assert_eq!(meta.save_path, PathBuf::from("/mnt/tv"));
    }

    #[test]
    fn create_rejects_duplicate() {
        let dir = TempDir::new().unwrap();
        let mut r = registry_in(&dir);
        r.create("sonarr".into(), PathBuf::from("/a")).unwrap();
        let err = r.create("sonarr".into(), PathBuf::from("/b")).unwrap_err();
        assert!(matches!(err, CategoryError::AlreadyExists(_)));
    }

    #[test]
    fn edit_updates_save_path() {
        let dir = TempDir::new().unwrap();
        let mut r = registry_in(&dir);
        r.create("sonarr".into(), PathBuf::from("/old")).unwrap();
        r.edit("sonarr", PathBuf::from("/new")).unwrap();
        assert_eq!(r.get("sonarr").unwrap().save_path, PathBuf::from("/new"));
    }

    #[test]
    fn edit_missing_returns_not_found() {
        let dir = TempDir::new().unwrap();
        let mut r = registry_in(&dir);
        let err = r.edit("ghost", PathBuf::from("/x")).unwrap_err();
        assert!(matches!(err, CategoryError::NotFound(_)));
    }

    #[test]
    fn remove_returns_removed_names_only() {
        let dir = TempDir::new().unwrap();
        let mut r = registry_in(&dir);
        r.create("a".into(), PathBuf::from("/a")).unwrap();
        r.create("b".into(), PathBuf::from("/b")).unwrap();
        let removed = r.remove(&["a".to_owned(), "ghost".to_owned(), "b".to_owned()]);
        assert_eq!(removed, vec!["a".to_owned(), "b".to_owned()]);
        assert!(r.is_empty());
    }

    #[test]
    fn save_then_load_roundtrip() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("categories.toml");
        {
            let mut r = CategoryRegistry::new(path.clone());
            r.create("sonarr".into(), PathBuf::from("/mnt/tv")).unwrap();
            r.create("radarr".into(), PathBuf::from("/mnt/movies"))
                .unwrap();
            r.save().unwrap();
        }
        let r = CategoryRegistry::load(path);
        assert_eq!(r.len(), 2);
        assert_eq!(r.get("sonarr").unwrap().save_path, PathBuf::from("/mnt/tv"));
        assert_eq!(
            r.get("radarr").unwrap().save_path,
            PathBuf::from("/mnt/movies")
        );
    }

    #[test]
    fn load_absent_file_returns_empty_registry() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("does-not-exist.toml");
        let r = CategoryRegistry::load(path.clone());
        assert!(r.is_empty());
        // Absent file must not materialise on load.
        assert!(!path.exists());
    }

    #[test]
    fn load_malformed_toml_renames_bak_and_starts_empty() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("categories.toml");
        fs::write(&path, b"this is not valid toml!!! = [\n").unwrap();
        let r = CategoryRegistry::load(path.clone());
        assert!(r.is_empty());
        // The broken file must have been renamed aside.
        assert!(
            !path.exists(),
            "malformed file should have been moved aside"
        );
        assert!(dir.path().join("categories.toml.bak").exists());
    }

    #[test]
    fn load_malformed_toml_collision_gets_numeric_suffix() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("categories.toml");
        let bak = dir.path().join("categories.toml.bak");
        fs::write(&bak, b"pre-existing backup").unwrap();
        fs::write(&path, b"garbage =").unwrap();
        let _ = CategoryRegistry::load(path);
        assert!(bak.exists(), "pre-existing .bak must not be overwritten");
        // The new collision should end up as .bak.1 (or similar).
        let bak_1 = dir.path().join("categories.toml.bak.1");
        assert!(
            bak_1.exists(),
            "collision should land at categories.toml.bak.1"
        );
    }

    #[test]
    fn case_sensitivity_preserved() {
        let dir = TempDir::new().unwrap();
        let mut r = registry_in(&dir);
        r.create("Sonarr".into(), PathBuf::from("/A")).unwrap();
        r.create("sonarr".into(), PathBuf::from("/a")).unwrap();
        assert_eq!(r.len(), 2);
        assert_eq!(r.get("Sonarr").unwrap().save_path, PathBuf::from("/A"));
        assert_eq!(r.get("sonarr").unwrap().save_path, PathBuf::from("/a"));
        // Lookup of a different case must not match.
        assert!(r.get("SONARR").is_none());
    }

    #[test]
    fn hand_edited_toml_loads() {
        // Simulates a user hand-editing the file while the daemon is off.
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("categories.toml");
        let hand_edited = r#"version = 1

[categories.sonarr]
save_path = "/mnt/tv"

[categories.radarr]
save_path = "/mnt/movies"
"#;
        fs::write(&path, hand_edited).unwrap();
        let r = CategoryRegistry::load(path);
        assert_eq!(r.len(), 2);
        assert_eq!(r.get("sonarr").unwrap().save_path, PathBuf::from("/mnt/tv"));
        assert_eq!(
            r.get("radarr").unwrap().save_path,
            PathBuf::from("/mnt/movies")
        );
    }

    #[test]
    fn nested_name_is_label_only() {
        // M170 treats `a/b/c` purely as a label — no directory creation
        // from the category name. The save_path comes from the caller.
        let dir = TempDir::new().unwrap();
        let mut r = registry_in(&dir);
        r.create("movies/4k".into(), PathBuf::from("/mnt/flat"))
            .unwrap();
        assert_eq!(r.get("movies/4k").unwrap().name, "movies/4k");
        // No actual `/mnt/flat/movies/4k` materialisation expected.
        assert_eq!(
            r.get("movies/4k").unwrap().save_path,
            PathBuf::from("/mnt/flat")
        );
    }

    #[test]
    fn empty_string_lookup_returns_none() {
        let dir = TempDir::new().unwrap();
        let mut r = registry_in(&dir);
        r.create("sonarr".into(), PathBuf::from("/x")).unwrap();
        assert!(r.get("").is_none());
        assert!(!r.contains(""));
    }

    #[test]
    fn resolve_path_honours_explicit_override() {
        let custom = PathBuf::from("/tmp/my-categories.toml");
        assert_eq!(
            resolve_category_registry_path(Some(custom.as_path())),
            custom
        );
    }

    #[test]
    fn resolve_path_default_ends_with_categories_toml() {
        let p = resolve_category_registry_path(None);
        assert!(
            p.to_string_lossy().ends_with("categories.toml"),
            "expected path ending with categories.toml, got {p:?}"
        );
    }
}