zfskit 0.2.0

Async toolkit for OpenZFS: datasets, snapshots, send/recv streams, holds, bookmarks, pools - via the zfs/zpool CLI with JSON output
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! High-level, entity-typed handles over `CommandRunner`.
//!
//! `Zfs` is the entry point. It hands out `Pool` handles by name and an
//! absolute-name `Dataset`, `Snapshot`, and `Bookmark` shortcuts. Distinct
//! handles keep invalid operations out of the API: snapshots expose holds and
//! rollback, while filesystems expose mount and child creation.
//!
//! The handle layer exists for ergonomics — consumers carry a single `Zfs`
//! value instead of threading a `&dyn CommandRunner` through every call,
//! and they navigate by relative name once a parent is in scope. Tests can
//! still target the free functions directly when parser/error-classification
//! detail matters.
use std::sync::Arc;

use crate::dataset::{
    CreateOptions, GetOptions, ListOptions, MountOptions, UnmountOptions, ZfsGetEntry, ZfsListEntry,
};
use crate::error::ZfsError;
use crate::models::{PropertyValue, ZpoolGetEntry, ZpoolListEntry, ZpoolStatusEntry};
use crate::names::{BookmarkName, DatasetName, NameError, PoolName, SnapshotName};
use crate::pool::{
    DestroyOptions, DiscoveredPool, ExportOptions, GetOptions as PoolGetOptions, ImportOptions,
    ListOptions as PoolListOptions, PoolCreateOptions,
};
use crate::runner::{CommandRunner, RealRunner};

/// Top-level handle. Construct once with [`Zfs::new`] (uses the system's
/// `zfs(8)`/`zpool(8)`) or [`Zfs::with_runner`] (custom runner — typically
/// `RecordingRunner` in tests).
#[derive(Clone)]
pub struct Zfs {
    runner: Arc<dyn CommandRunner>,
}

impl Zfs {
    pub fn new() -> Self {
        Self {
            runner: Arc::new(RealRunner),
        }
    }

    pub fn with_runner<R: CommandRunner + 'static>(runner: R) -> Self {
        Self {
            runner: Arc::new(runner),
        }
    }

    /// Access the advanced execution backend for operations not yet surfaced
    /// by a typed handle. Application state should store `Zfs`, not the runner.
    pub fn command_runner(&self) -> &dyn CommandRunner {
        &*self.runner
    }

    /// Handle bound to a specific zpool by name.
    pub fn pool(&self, name: impl Into<String>) -> Result<Pool, NameError> {
        Ok(Pool {
            runner: self.runner.clone(),
            name: PoolName::parse(name)?,
        })
    }

    /// Sugar: handle to any dataset by absolute name. Equivalent to
    /// `zfs.pool("a").unwrap().dataset("b/c")` for `zfs.dataset("a/b/c").unwrap()` — useful
    /// when you already have the full path and don't need a `Pool` handle.
    pub fn dataset(&self, abs_name: impl Into<String>) -> Result<Dataset, NameError> {
        Ok(Dataset {
            runner: self.runner.clone(),
            name: DatasetName::parse(abs_name)?,
        })
    }

    pub fn snapshot(&self, name: impl Into<String>) -> Result<Snapshot, NameError> {
        Ok(Snapshot {
            runner: self.runner.clone(),
            name: SnapshotName::parse(name)?,
        })
    }

    pub fn bookmark(&self, name: impl Into<String>) -> Result<Bookmark, NameError> {
        Ok(Bookmark {
            runner: self.runner.clone(),
            name: BookmarkName::parse(name)?,
        })
    }

    /// List datasets across the system.
    pub async fn list_datasets(&self, opts: &ListOptions) -> Result<Vec<ZfsListEntry>, ZfsError> {
        crate::dataset::list(&*self.runner, opts).await
    }

    /// List pools imported on the system.
    pub async fn list_pools(
        &self,
        opts: &PoolListOptions,
    ) -> Result<Vec<ZpoolListEntry>, ZfsError> {
        crate::pool::list(&*self.runner, opts).await
    }

    /// `zpool status -j` for all pools.
    pub async fn pool_status_all(&self) -> Result<Vec<ZpoolStatusEntry>, ZfsError> {
        crate::pool::status_all(&*self.runner).await
    }

    /// `zpool import` (no args) — discover pools available for import.
    /// Returns an empty Vec when no pools are visible.
    pub async fn discover_importable_pools(&self) -> Result<Vec<DiscoveredPool>, ZfsError> {
        crate::pool::discover(&*self.runner).await
    }

    /// Create a new pool. Returns a [`Pool`] handle to the just-created pool.
    pub async fn create_pool(&self, opts: &PoolCreateOptions) -> Result<Pool, ZfsError> {
        crate::pool::create(&*self.runner, opts).await?;
        let name = PoolName::parse(opts.name.clone())?;
        Ok(Pool {
            runner: self.runner.clone(),
            name,
        })
    }

    /// Create a dataset by absolute name (e.g., `"tank/data/home"`). Convenience
    /// for callers that have full paths and don't want to navigate via a
    /// `Pool` or `Dataset` handle. Equivalent to looking up the parent and
    /// calling `pool.create_dataset(rel)` / `dataset.create_dataset(rel)`,
    /// but lets the caller skip the split.
    pub async fn create_dataset(
        &self,
        abs_name: impl Into<String>,
        opts: &CreateOptions,
    ) -> Result<Dataset, ZfsError> {
        let name = DatasetName::parse(abs_name)?;
        crate::dataset::create(&*self.runner, name.as_str(), opts).await?;
        Ok(Dataset {
            runner: self.runner.clone(),
            name,
        })
    }

    /// `zfs mount -a` — mount all importable filesystems on the system.
    pub async fn mount_all(&self) -> Result<(), ZfsError> {
        crate::dataset::mount_all(&*self.runner).await
    }

    /// `zfs umount -a [-f]` — unmount all mounted filesystems on the system.
    pub async fn unmount_all(&self, force: bool) -> Result<(), ZfsError> {
        crate::dataset::unmount_all(&*self.runner, force).await
    }

    /// `zfs destroy <bookmark>` — destroy a bookmark by its full name
    /// (e.g., `"tank/data#bm1"`).
    pub async fn destroy_bookmark(&self, bookmark_name: &str) -> Result<(), ZfsError> {
        let bookmark = BookmarkName::parse(bookmark_name)?;
        crate::bookmark::destroy(&*self.runner, bookmark.as_str()).await
    }

    pub async fn list_holds_many(
        &self,
        snapshots: &[SnapshotName],
    ) -> Result<Vec<crate::hold::Hold>, ZfsError> {
        let names: Vec<&str> = snapshots.iter().map(SnapshotName::as_str).collect();
        crate::hold::list_holds_many(&*self.runner, &names).await
    }

    pub async fn send(
        &self,
        args: &crate::send::SendArgs,
    ) -> Result<crate::send::SendProcess, ZfsError> {
        crate::send::send(&*self.runner, args).await
    }

    pub async fn receive(
        &self,
        args: &crate::recv::RecvArgs,
    ) -> Result<crate::recv::RecvProcess, crate::recv::RecvError> {
        crate::recv::recv(&*self.runner, args).await
    }

    pub async fn send_dry_run(
        &self,
        args: &crate::send::SendArgs,
    ) -> Result<crate::send::DryRunSize, ZfsError> {
        crate::send::dry_run(&*self.runner, args).await
    }

    pub async fn decode_resume_token(
        &self,
        token: &str,
    ) -> Result<crate::resume_token::ResumeToken, crate::resume_token::ResumeTokenError> {
        crate::resume_token::decode(&*self.runner, token).await
    }

    pub async fn abort_partial_receive(&self, dataset: &DatasetName) -> Result<(), ZfsError> {
        crate::recv::abort_partial(&*self.runner, dataset.as_str()).await
    }
}

impl Default for Zfs {
    fn default() -> Self {
        Self::new()
    }
}

/// Handle bound to a specific zpool.
#[derive(Clone)]
pub struct Pool {
    runner: Arc<dyn CommandRunner>,
    name: PoolName,
}

impl Pool {
    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    pub async fn import(&self, opts: &ImportOptions) -> Result<(), ZfsError> {
        crate::pool::import(&*self.runner, self.name.as_str(), opts).await
    }

    pub async fn export(&self, opts: &ExportOptions) -> Result<(), ZfsError> {
        crate::pool::export(&*self.runner, self.name.as_str(), opts).await
    }

    /// `zpool destroy [-f] <pool>`. Permanent.
    pub async fn destroy(&self, opts: &DestroyOptions) -> Result<(), ZfsError> {
        crate::pool::destroy(&*self.runner, self.name.as_str(), opts).await
    }

    /// Read multiple properties via `zpool get -j`. The `pools` field of
    /// `opts` is overridden with this handle's name.
    pub async fn get(&self, opts: &PoolGetOptions) -> Result<Vec<ZpoolGetEntry>, ZfsError> {
        let mut opts = opts.clone();
        opts.pools = vec![self.name.to_string()];
        crate::pool::get(&*self.runner, &opts).await
    }

    /// Read a single pool property.
    pub async fn get_property(&self, property: &str) -> Result<PropertyValue, ZfsError> {
        crate::pool::get_property(&*self.runner, self.name.as_str(), property).await
    }

    /// `zpool set <name>=<value> <pool>`.
    pub async fn set_property(&self, property: &str, value: &str) -> Result<(), ZfsError> {
        crate::pool::set_property(&*self.runner, self.name.as_str(), property, value).await
    }

    /// `zpool status -j <pool>`.
    pub async fn status(&self) -> Result<ZpoolStatusEntry, ZfsError> {
        crate::pool::status(&*self.runner, self.name.as_str()).await
    }

    /// Returns whether the pool is imported and visible, preserving failures.
    pub async fn exists(&self) -> Result<bool, ZfsError> {
        let opts = PoolListOptions {
            pools: vec![self.name.to_string()],
            ..Default::default()
        };
        match crate::pool::list(&*self.runner, &opts).await {
            Ok(entries) => Ok(!entries.is_empty()),
            Err(ZfsError::PoolNotFound { .. }) => Ok(false),
            Err(error) => Err(error),
        }
    }

    pub async fn exists_best_effort(&self) -> bool {
        self.exists().await.unwrap_or(false)
    }

    pub async fn scrub(&self, action: crate::pool::ScrubAction) -> Result<(), ZfsError> {
        crate::pool::scrub(&*self.runner, self.name.as_str(), action).await
    }

    /// Handle to the pool's root filesystem (the zfs dataset whose name
    /// matches the pool name). Encryption properties of a pool actually
    /// live on this dataset.
    pub fn root_dataset(&self) -> Dataset {
        Dataset {
            runner: self.runner.clone(),
            name: DatasetName::parse(self.name.to_string()).expect("pool name is a dataset name"),
        }
    }

    /// Lookup a nested dataset by relative name. The full ZFS name is
    /// `<pool>/<rel_name>`.
    pub fn dataset(&self, rel_name: &str) -> Result<Dataset, NameError> {
        Ok(Dataset {
            runner: self.runner.clone(),
            name: DatasetName::parse(format!("{}/{rel_name}", self.name))?,
        })
    }

    /// Create a child dataset within this pool. The full ZFS name is
    /// `<pool>/<rel_name>`. Returns a `Dataset` handle to the just-created
    /// dataset on success.
    pub async fn create_dataset(
        &self,
        rel_name: &str,
        opts: &CreateOptions,
    ) -> Result<Dataset, ZfsError> {
        let full_name = DatasetName::parse(format!("{}/{rel_name}", self.name))?;
        crate::dataset::create(&*self.runner, full_name.as_str(), opts).await?;
        Ok(Dataset {
            runner: self.runner.clone(),
            name: full_name,
        })
    }
}

/// Handle bound to a specific dataset.
#[derive(Clone)]
pub struct Dataset {
    runner: Arc<dyn CommandRunner>,
    name: DatasetName,
}

impl Dataset {
    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    /// Read multiple properties via `zfs get -j`. The `datasets` field of
    /// `opts` is overridden with this handle's name.
    pub async fn get(&self, opts: &GetOptions) -> Result<Vec<ZfsGetEntry>, ZfsError> {
        let mut opts = opts.clone();
        opts.datasets = vec![self.name.to_string()];
        crate::dataset::get(&*self.runner, &opts).await
    }

    /// Read a single property.
    pub async fn get_property(&self, property: &str) -> Result<PropertyValue, ZfsError> {
        crate::dataset::get_property(&*self.runner, self.name.as_str(), property).await
    }

    /// `zfs set <property>=<value> <dataset>`.
    pub async fn set_property(&self, property: &str, value: &str) -> Result<(), ZfsError> {
        crate::dataset::set_property(&*self.runner, self.name.as_str(), property, value).await
    }

    /// `zfs mount [-R] <dataset>`. Idempotent on already-mounted.
    pub async fn mount(&self, opts: &MountOptions) -> Result<(), ZfsError> {
        crate::dataset::mount(&*self.runner, self.name.as_str(), opts).await
    }

    /// `zfs umount [-f] <dataset>`. Idempotent on not-currently-mounted.
    pub async fn unmount(&self, opts: &UnmountOptions) -> Result<(), ZfsError> {
        crate::dataset::unmount(&*self.runner, self.name.as_str(), opts).await
    }

    /// Returns whether this dataset exists, preserving transport and parse errors.
    pub async fn exists(&self) -> Result<bool, ZfsError> {
        let opts = ListOptions {
            roots: vec![self.name.to_string()],
            ..Default::default()
        };
        match crate::dataset::list(&*self.runner, &opts).await {
            Ok(entries) => Ok(!entries.is_empty()),
            Err(ZfsError::DatasetNotFound { .. }) => Ok(false),
            Err(error) => Err(error),
        }
    }

    /// Best-effort existence probe that deliberately collapses errors to false.
    pub async fn exists_best_effort(&self) -> bool {
        self.exists().await.unwrap_or(false)
    }

    /// `zfs load-key <dataset>`. Reads the key from the dataset's
    /// `keylocation` (file://, prompt, ...). Idempotent on already-loaded.
    pub async fn load_key(&self) -> Result<(), ZfsError> {
        crate::encryption::load_key(&*self.runner, self.name.as_str()).await
    }

    /// `zfs load-key <dataset>` with the passphrase delivered via stdin —
    /// no terminal prompt, no temp keyfile. Idempotent on already-loaded.
    pub async fn load_key_with_passphrase(&self, passphrase: &[u8]) -> Result<(), ZfsError> {
        crate::encryption::load_key_with_passphrase(&*self.runner, self.name.as_str(), passphrase)
            .await
    }

    /// Verify a prompt passphrase without loading or unloading the key.
    pub async fn verify_passphrase(&self, passphrase: &[u8]) -> Result<bool, ZfsError> {
        crate::encryption::verify_passphrase(&*self.runner, self.name.as_str(), passphrase).await
    }

    /// `zfs load-key -L <keylocation> <dataset>` — load with an explicit
    /// keylocation override (e.g., `file:///path` when the key file lives at
    /// a known location but the dataset's `keylocation` property is `prompt`).
    /// Idempotent on already-loaded.
    pub async fn load_key_with_keylocation(&self, keylocation: &str) -> Result<(), ZfsError> {
        crate::encryption::load_key_with_keylocation(&*self.runner, self.name.as_str(), keylocation)
            .await
    }

    /// `zfs unload-key <dataset>`. Idempotent on already-unloaded.
    pub async fn unload_key(&self) -> Result<(), ZfsError> {
        crate::encryption::unload_key(&*self.runner, self.name.as_str()).await
    }

    /// Lookup a nested dataset by relative name. The full ZFS name is
    /// `<self>/<rel_name>`.
    pub fn dataset(&self, rel_name: &str) -> Result<Dataset, NameError> {
        Ok(Dataset {
            runner: self.runner.clone(),
            name: DatasetName::parse(format!("{}/{rel_name}", self.name))?,
        })
    }

    /// Create a child dataset within this dataset. The full ZFS name is
    /// `<self>/<rel_name>`. Returns a `Dataset` handle to the just-created
    /// dataset on success.
    pub async fn create_dataset(
        &self,
        rel_name: &str,
        opts: &CreateOptions,
    ) -> Result<Dataset, ZfsError> {
        let full_name = DatasetName::parse(format!("{}/{rel_name}", self.name))?;
        crate::dataset::create(&*self.runner, full_name.as_str(), opts).await?;
        Ok(Dataset {
            runner: self.runner.clone(),
            name: full_name,
        })
    }

    /// `zfs snapshot [-r] <self>@<tag>`.
    pub async fn snapshot(
        &self,
        tag: &str,
        opts: &crate::dataset::SnapshotOptions,
    ) -> Result<Snapshot, ZfsError> {
        let name = SnapshotName::new(self.name.clone(), tag)?;
        crate::dataset::snapshot(&*self.runner, name.as_str(), opts).await?;
        Ok(Snapshot {
            runner: self.runner.clone(),
            name,
        })
    }

    /// Construct a typed handle for an existing snapshot.
    pub fn snapshot_handle(&self, tag: &str) -> Result<Snapshot, NameError> {
        Ok(Snapshot {
            runner: self.runner.clone(),
            name: SnapshotName::new(self.name.clone(), tag)?,
        })
    }

    /// `zfs destroy [flags] <self>` — destroy this dataset. Snapshots and
    /// bookmarks are destroyed through their own typed handles.
    pub async fn destroy(&self, opts: &crate::dataset::DestroyOptions) -> Result<(), ZfsError> {
        crate::dataset::destroy(&*self.runner, self.name.as_str(), opts).await
    }

    /// Probe whether this dataset has a partial-receive in flight. `None`
    /// means no pending receive; `Some(token)` means a previous recv was
    /// interrupted and can be resumed by feeding `token` into
    /// [`crate::send::SendArgs::resume`].
    pub async fn receive_resume_token(&self) -> Result<Option<String>, ZfsError> {
        crate::recv::receive_resume_token(&*self.runner, self.name.as_str()).await
    }
}

/// Handle bound to a snapshot. Only snapshot-valid operations are exposed.
#[derive(Clone)]
pub struct Snapshot {
    runner: Arc<dyn CommandRunner>,
    name: SnapshotName,
}

impl Snapshot {
    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    pub async fn exists(&self) -> Result<bool, ZfsError> {
        let opts = ListOptions {
            roots: vec![self.name.to_string()],
            types: vec![crate::models::DatasetType::Snapshot],
            ..Default::default()
        };
        match crate::dataset::list(&*self.runner, &opts).await {
            Ok(entries) => Ok(!entries.is_empty()),
            Err(ZfsError::DatasetNotFound { .. }) => Ok(false),
            Err(error) => Err(error),
        }
    }

    pub async fn hold(&self, tag: &str) -> Result<(), ZfsError> {
        crate::hold::hold(&*self.runner, self.name.as_str(), tag).await
    }

    pub async fn release(&self, tag: &str) -> Result<(), ZfsError> {
        crate::hold::release(&*self.runner, self.name.as_str(), tag).await
    }

    pub async fn list_holds(&self) -> Result<Vec<crate::hold::Hold>, ZfsError> {
        crate::hold::list_holds(&*self.runner, self.name.as_str()).await
    }

    pub async fn rollback(&self, opts: &crate::dataset::RollbackOptions) -> Result<(), ZfsError> {
        crate::dataset::rollback(&*self.runner, self.name.as_str(), opts).await
    }

    pub async fn destroy(&self, opts: &crate::dataset::DestroyOptions) -> Result<(), ZfsError> {
        crate::dataset::destroy(&*self.runner, self.name.as_str(), opts).await
    }

    pub async fn bookmark(&self, mark: &str) -> Result<Bookmark, ZfsError> {
        let name = BookmarkName::new(self.name.dataset().clone(), mark)?;
        crate::bookmark::create(&*self.runner, self.name.as_str(), name.as_str()).await?;
        Ok(Bookmark {
            runner: self.runner.clone(),
            name,
        })
    }
}

/// Handle bound to a bookmark.
#[derive(Clone)]
pub struct Bookmark {
    runner: Arc<dyn CommandRunner>,
    name: BookmarkName,
}

impl Bookmark {
    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    pub async fn destroy(&self) -> Result<(), ZfsError> {
        crate::bookmark::destroy(&*self.runner, self.name.as_str()).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::runner::{Cmd, RecordingRunner};

    fn get_property_json(ds: &str, value: &str, source_kind: &str) -> Vec<u8> {
        format!(
            "{{\"output_version\":{{\"command\":\"zfs get\",\"vers_major\":0,\"vers_minor\":1}},\
             \"datasets\":{{\"{ds}\":{{\"name\":\"{ds}\",\"type\":\"FILESYSTEM\",\
             \"pool\":\"{ds}\",\"createtxg\":\"1\",\"properties\":{{\"encryption\":\
             {{\"value\":\"{value}\",\"source\":{{\"type\":\"{source_kind}\",\"data\":\"-\"}}}}}}}}}}}}"
        )
        .into_bytes()
    }

    #[tokio::test]
    async fn dataset_get_property_via_handle() {
        let runner = RecordingRunner::new().record(
            Cmd::new("zfs").args(["get", "-j", "-p", "encryption", "tank"]),
            get_property_json("tank", "off", "DEFAULT"),
            vec![],
            0,
        );
        let zfs = Zfs::with_runner(runner);
        let prop = zfs
            .dataset("tank")
            .unwrap()
            .get_property("encryption")
            .await
            .unwrap();
        assert_eq!(prop.value, "off");
    }

    #[tokio::test]
    async fn pool_import_export_via_handle() {
        let runner = RecordingRunner::new()
            .record(
                Cmd::new("zpool").args(["import", "-f", "-N", "tank"]),
                vec![],
                vec![],
                0,
            )
            .record(
                Cmd::new("zpool").args(["export", "tank"]),
                vec![],
                vec![],
                0,
            );
        let zfs = Zfs::with_runner(runner);
        let pool = zfs.pool("tank").unwrap();
        let opts = ImportOptions {
            force: true,
            no_mount: true,
            ..Default::default()
        };
        pool.import(&opts).await.expect("import succeeds");
        pool.export(&ExportOptions::default())
            .await
            .expect("export succeeds");
    }

    #[tokio::test]
    async fn pool_create_dataset_returns_handle_with_full_name() {
        let runner = RecordingRunner::new().record(
            Cmd::new("zfs").args(["create", "-o", "compression=lz4", "tank/data"]),
            vec![],
            vec![],
            0,
        );
        let zfs = Zfs::with_runner(runner);
        let pool = zfs.pool("tank").unwrap();
        let ds = pool
            .create_dataset("data", &CreateOptions::new().property("compression", "lz4"))
            .await
            .expect("create_dataset succeeds");
        assert_eq!(ds.name(), "tank/data");
    }

    #[tokio::test]
    async fn zfs_create_dataset_takes_absolute_name() {
        let runner = RecordingRunner::new().record(
            Cmd::new("zfs").args(["create", "-o", "compression=lz4", "tank/data/home"]),
            vec![],
            vec![],
            0,
        );
        let zfs = Zfs::with_runner(runner);
        let ds = zfs
            .create_dataset(
                "tank/data/home",
                &CreateOptions::new().property("compression", "lz4"),
            )
            .await
            .expect("create_dataset by abs name succeeds");
        assert_eq!(ds.name(), "tank/data/home");
    }

    #[tokio::test]
    async fn nested_create_dataset_joins_path() {
        let runner = RecordingRunner::new().record(
            Cmd::new("zfs").args(["create", "tank/data/home"]),
            vec![],
            vec![],
            0,
        );
        let zfs = Zfs::with_runner(runner);
        let parent = zfs.dataset("tank/data").unwrap();
        let child = parent
            .create_dataset("home", &CreateOptions::new())
            .await
            .expect("nested create_dataset succeeds");
        assert_eq!(child.name(), "tank/data/home");
    }

    #[tokio::test]
    async fn pool_root_dataset_uses_pool_name() {
        let zfs = Zfs::with_runner(RecordingRunner::new());
        let root = zfs.pool("tank").unwrap().root_dataset();
        assert_eq!(root.name(), "tank");
    }

    #[tokio::test]
    async fn pool_dataset_lookup_joins_path() {
        let zfs = Zfs::with_runner(RecordingRunner::new());
        let ds = zfs.pool("tank").unwrap().dataset("data/home").unwrap();
        assert_eq!(ds.name(), "tank/data/home");
    }

    #[tokio::test]
    async fn dataset_set_property_via_handle() {
        let runner = RecordingRunner::new().record(
            Cmd::new("zfs").args(["set", "compression=zstd", "tank/data"]),
            vec![],
            vec![],
            0,
        );
        let zfs = Zfs::with_runner(runner);
        zfs.dataset("tank/data")
            .unwrap()
            .set_property("compression", "zstd")
            .await
            .expect("set_property succeeds");
    }

    #[tokio::test]
    async fn dataset_mount_unmount_via_handle() {
        let runner = RecordingRunner::new()
            .record(
                Cmd::new("zfs").args(["mount", "tank/data"]),
                vec![],
                vec![],
                0,
            )
            .record(
                Cmd::new("zfs").args(["umount", "-f", "tank/data"]),
                vec![],
                vec![],
                0,
            );
        let zfs = Zfs::with_runner(runner);
        let ds = zfs.dataset("tank/data").unwrap();
        ds.mount(&MountOptions::default())
            .await
            .expect("mount succeeds");
        ds.unmount(&UnmountOptions { force: true })
            .await
            .expect("unmount succeeds");
    }

    #[tokio::test]
    async fn dataset_snapshot_rollback_destroy_via_handle() {
        let runner = RecordingRunner::new()
            .record(
                Cmd::new("zfs").args(["snapshot", "tank/data@snap1"]),
                vec![],
                vec![],
                0,
            )
            .record(
                Cmd::new("zfs").args(["rollback", "-r", "tank/data@snap1"]),
                vec![],
                vec![],
                0,
            )
            .record(
                Cmd::new("zfs").args(["destroy", "tank/data@snap1"]),
                vec![],
                vec![],
                0,
            )
            .record(
                Cmd::new("zfs").args(["destroy", "-r", "-f", "tank/data"]),
                vec![],
                vec![],
                0,
            );
        let zfs = Zfs::with_runner(runner);
        let ds = zfs.dataset("tank/data").unwrap();
        let snap = ds
            .snapshot("snap1", &crate::dataset::SnapshotOptions::new())
            .await
            .expect("snapshot succeeds");
        assert_eq!(snap.name(), "tank/data@snap1");
        snap.rollback(&crate::dataset::RollbackOptions::new().destroy_newer())
            .await
            .expect("rollback succeeds");
        snap.destroy(&crate::dataset::DestroyOptions::new())
            .await
            .expect("destroy_snapshot succeeds");
        ds.destroy(
            &crate::dataset::DestroyOptions::new()
                .recursive()
                .force_unmount(),
        )
        .await
        .expect("destroy succeeds");
    }

    #[tokio::test]
    async fn zfs_unmount_all_force() {
        let runner = RecordingRunner::new().record(
            Cmd::new("zfs").args(["umount", "-a", "-f"]),
            vec![],
            vec![],
            0,
        );
        let zfs = Zfs::with_runner(runner);
        zfs.unmount_all(true)
            .await
            .expect("unmount_all force succeeds");
    }

    #[tokio::test]
    async fn dataset_load_key_with_passphrase_via_handle() {
        let runner = RecordingRunner::new().record(
            Cmd::new("zfs")
                .args(["load-key", "-L", "prompt", "tank/encrypted"])
                .stdin_secret(b"correct".to_vec()),
            vec![],
            vec![],
            0,
        );
        let zfs = Zfs::with_runner(runner);
        zfs.dataset("tank/encrypted")
            .unwrap()
            .load_key_with_passphrase(b"correct")
            .await
            .expect("load_key_with_passphrase succeeds");
    }
}