microsandbox 0.5.6

`microsandbox` is the core library for the microsandbox project.
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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! Named volume management.
//!
//! Volumes are persistent host-side directories stored under
//! `~/.microsandbox/volumes/<name>/` with metadata tracked in the database.

pub mod fs;
pub use fs::{VolumeFs, VolumeFsReadStream, VolumeFsWriteSink};

use std::{fs::File, os::fd::AsRawFd, path::PathBuf};

use microsandbox_image::ext4::{self, Ext4FormatOptions};
use sea_orm::{ColumnTrait, ConnectionTrait, EntityTrait, QueryFilter, QueryOrder, Set};

use crate::{
    MicrosandboxError, MicrosandboxResult,
    db::entity::{sandbox as sandbox_entity, volume as volume_entity},
    sandbox::{NamedVolumeMode, SandboxConfig, SandboxStatus, VolumeMount},
    size::Mebibytes,
};

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

/// A named volume.
pub struct Volume {
    name: String,
    path: PathBuf,
    kind: VolumeKind,
    capacity_bytes: Option<u64>,
    disk_format: Option<String>,
    disk_fstype: Option<String>,
}

/// Configuration for creating a volume.
#[derive(Debug, Clone)]
pub struct VolumeConfig {
    /// Volume name.
    pub name: String,

    /// Storage kind.
    pub kind: VolumeKind,

    /// Size quota in MiB (None = unlimited).
    pub quota_mib: Option<u32>,

    /// Disk capacity in MiB. Required for disk volumes.
    pub capacity_mib: Option<u32>,

    /// Labels for organization (JSON-serialized in DB).
    pub labels: Vec<(String, String)>,
}

/// Storage kind for a named volume.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VolumeKind {
    /// Directory-backed named volume mounted through virtiofs.
    Directory,

    /// Raw ext4 disk-image named volume mounted through virtio-blk.
    Disk,
}

/// A lightweight handle to a volume from the database.
///
/// Provides metadata access and management operations without requiring
/// a live [`Volume`] instance. Obtained via [`Volume::get`] or [`Volume::list`].
#[derive(Debug)]
pub struct VolumeHandle {
    db_id: i32,
    name: String,
    kind: VolumeKind,
    quota_mib: Option<u32>,
    used_bytes: u64,
    capacity_bytes: Option<u64>,
    disk_format: Option<String>,
    disk_fstype: Option<String>,
    labels: Vec<(String, String)>,
    created_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// Builder for creating a volume.
pub struct VolumeBuilder {
    config: VolumeConfig,
}

/// Result of provisioning a named volume record.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum VolumeProvision {
    /// The volume record was inserted by this operation.
    Inserted,
    /// A compatible existing record was reused.
    Existing,
}

//--------------------------------------------------------------------------------------------------
// Methods: VolumeHandle
//--------------------------------------------------------------------------------------------------

impl VolumeHandle {
    /// Create a handle from a database entity model.
    pub(crate) fn from_model(model: volume_entity::Model) -> Self {
        let labels = model
            .labels
            .as_deref()
            .map(|s| {
                serde_json::from_str::<Vec<(String, String)>>(s).unwrap_or_else(|e| {
                    tracing::warn!(volume = %model.name, error = %e, "failed to parse volume labels JSON");
                    Vec::new()
                })
            })
            .unwrap_or_default();

        Self {
            db_id: model.id,
            name: model.name,
            kind: VolumeKind::from_db_value(&model.kind),
            quota_mib: model.quota_mib.map(|v| v.max(0) as u32),
            used_bytes: model.size_bytes.unwrap_or(0).max(0) as u64,
            capacity_bytes: model.capacity_bytes.map(|v| v.max(0) as u64),
            disk_format: model.disk_format,
            disk_fstype: model.disk_fstype,
            labels,
            created_at: model.created_at.map(|dt| dt.and_utc()),
        }
    }

    /// Unique name identifying this volume. Used to reference the volume
    /// in sandbox mount configurations via `v.named(handle.name())`.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Storage kind for this volume.
    pub fn kind(&self) -> VolumeKind {
        self.kind
    }

    /// Maximum storage in MiB, or `None` if unlimited.
    pub fn quota_mib(&self) -> Option<u32> {
        self.quota_mib
    }

    /// Disk usage snapshot from when this handle was created. Not live —
    /// call [`Volume::get`] again for a fresh reading.
    pub fn used_bytes(&self) -> u64 {
        self.used_bytes
    }

    /// Disk capacity in bytes for disk volumes.
    pub fn capacity_bytes(&self) -> Option<u64> {
        self.capacity_bytes
    }

    /// Disk image format for disk volumes. V1 always creates `raw`.
    pub fn disk_format(&self) -> Option<&str> {
        self.disk_format.as_deref()
    }

    /// Inner disk filesystem for disk volumes. V1 always creates `ext4`.
    pub fn disk_fstype(&self) -> Option<&str> {
        self.disk_fstype.as_deref()
    }

    /// Host path to the managed raw disk image for disk volumes.
    pub fn disk_path(&self) -> Option<PathBuf> {
        (self.kind == VolumeKind::Disk).then(|| {
            crate::config::config()
                .volumes_dir()
                .join(&self.name)
                .join("disk.raw")
        })
    }

    /// Key-value labels for organizing and filtering volumes.
    pub fn labels(&self) -> &[(String, String)] {
        &self.labels
    }

    /// When this volume was first created, if recorded.
    pub fn created_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
        self.created_at
    }

    /// Operate on the volume's host-side directory (read, write, list files)
    /// without needing a running sandbox.
    pub fn fs(&self) -> fs::VolumeFs<'_> {
        let path = crate::config::config().volumes_dir().join(&self.name);
        fs::VolumeFs::from_path(path)
    }

    /// Remove this volume from the database and filesystem.
    ///
    /// Deletes the DB record first, then the directory. An orphaned directory
    /// is easier to detect and clean up than an orphaned DB record.
    pub async fn remove(&self) -> MicrosandboxResult<()> {
        let _name_lock = lock_volume_name(&self.name)?;
        let _disk_lock = lock_disk_volume_for_remove(self)?;
        let pools = crate::db::init_global().await?;
        ensure_volume_not_referenced_by_active_sandbox(pools.read(), &self.name).await?;

        // Delete the DB record first.
        volume_entity::Entity::delete_by_id(self.db_id)
            .exec(pools.write())
            .await?;

        // Then delete the directory.
        let path = crate::config::config().volumes_dir().join(&self.name);
        if path.exists() {
            tokio::fs::remove_dir_all(&path).await?;
        }

        Ok(())
    }
}

//--------------------------------------------------------------------------------------------------
// Methods: Static
//--------------------------------------------------------------------------------------------------

impl Volume {
    /// Start building a new named volume. Call `.create()` on the returned
    /// builder to persist it.
    pub fn builder(name: impl Into<String>) -> VolumeBuilder {
        VolumeBuilder::new(name)
    }

    /// Provision a volume: creates the host directory and database record.
    /// Fails with [`MicrosandboxError::VolumeAlreadyExists`] if a volume
    /// with the same name already exists.
    pub async fn create(config: VolumeConfig) -> MicrosandboxResult<Self> {
        tracing::debug!(
            name = %config.name,
            kind = config.kind.as_str(),
            quota_mib = ?config.quota_mib,
            capacity_mib = ?config.capacity_mib,
            "Volume::create"
        );
        validate_volume_name(&config.name)?;
        validate_volume_config(&config)?;
        let _name_lock = lock_volume_name(&config.name)?;

        let pools = crate::db::init_global().await?;

        // Check for existing volume.
        let existing = volume_entity::Entity::find()
            .filter(volume_entity::Column::Name.eq(&config.name))
            .one(pools.read())
            .await?;
        if existing.is_some() {
            return Err(MicrosandboxError::VolumeAlreadyExists(config.name));
        }

        let volumes_dir = crate::config::config().volumes_dir();
        tokio::fs::create_dir_all(&volumes_dir).await?;
        let path = volumes_dir.join(&config.name);
        if path.exists() {
            return Err(MicrosandboxError::VolumeAlreadyExists(config.name));
        }

        let temp = tempfile::Builder::new()
            .prefix(&format!(".{}.", config.name))
            .tempdir_in(&volumes_dir)?;
        provision_volume_path(&config, temp.path()).await?;
        tokio::fs::rename(temp.path(), &path).await?;
        let _ = temp.keep();

        // Serialize labels.
        let labels_json = if config.labels.is_empty() {
            None
        } else {
            Some(serde_json::to_string(&config.labels)?)
        };

        // Insert DB record first — orphaned directories are easier to clean
        // up than orphaned DB records.
        let now = chrono::Utc::now().naive_utc();
        let capacity_bytes = config.capacity_mib.map(|mib| i64::from(mib) * 1024 * 1024);
        let model = volume_entity::ActiveModel {
            name: Set(config.name.clone()),
            kind: Set(config.kind.as_str().to_string()),
            quota_mib: Set(config.quota_mib.map(|v| v as i32)),
            size_bytes: Set(None),
            capacity_bytes: Set(capacity_bytes),
            disk_format: Set((config.kind == VolumeKind::Disk).then(|| "raw".to_string())),
            disk_fstype: Set((config.kind == VolumeKind::Disk).then(|| "ext4".to_string())),
            labels: Set(labels_json),
            created_at: Set(Some(now)),
            updated_at: Set(Some(now)),
            ..Default::default()
        };

        if let Err(e) = volume_entity::Entity::insert(model)
            .exec(pools.write())
            .await
        {
            let _ = tokio::fs::remove_dir_all(&path).await;
            return Err(e.into());
        }

        Ok(Self {
            name: config.name,
            path,
            kind: config.kind,
            capacity_bytes: capacity_bytes.map(|v| v as u64),
            disk_format: (config.kind == VolumeKind::Disk).then(|| "raw".to_string()),
            disk_fstype: (config.kind == VolumeKind::Disk).then(|| "ext4".to_string()),
        })
    }

    /// Provision the volume DB record inside the caller's transaction.
    ///
    /// Lets sandbox-time named volume creation insert the volume and sandbox
    /// in one atomic write so a concurrent `Volume::list` cannot observe the
    /// volume before the owning sandbox exists.
    /// Returns [`MicrosandboxError::VolumeAlreadyExists`] if the name
    /// is already in the table.
    ///
    /// The caller is responsible for creating the on-disk directory
    /// after the transaction commits (or rolling back via
    /// `Volume::remove` if the directory step fails).
    pub(crate) async fn provision_in_transaction<C: ConnectionTrait>(
        txn: &C,
        config: &VolumeConfig,
        mode: NamedVolumeMode,
    ) -> MicrosandboxResult<VolumeProvision> {
        validate_volume_name(&config.name)?;
        validate_volume_config(config)?;

        let existing = volume_entity::Entity::find()
            .filter(volume_entity::Column::Name.eq(&config.name))
            .one(txn)
            .await?;
        if let Some(existing) = existing {
            return match mode {
                NamedVolumeMode::Create => {
                    Err(MicrosandboxError::VolumeAlreadyExists(config.name.clone()))
                }
                NamedVolumeMode::EnsureExists => {
                    validate_existing_volume_config(&existing, config)?;
                    Ok(VolumeProvision::Existing)
                }
                NamedVolumeMode::Existing => Ok(VolumeProvision::Existing),
            };
        }

        if mode == NamedVolumeMode::Existing {
            return Err(MicrosandboxError::VolumeNotFound(config.name.clone()));
        }

        let labels_json = if config.labels.is_empty() {
            None
        } else {
            Some(serde_json::to_string(&config.labels)?)
        };
        let now = chrono::Utc::now().naive_utc();
        let capacity_bytes = config.capacity_mib.map(|mib| i64::from(mib) * 1024 * 1024);
        let model = volume_entity::ActiveModel {
            name: Set(config.name.clone()),
            kind: Set(config.kind.as_str().to_string()),
            quota_mib: Set(config.quota_mib.map(|v| v as i32)),
            size_bytes: Set(None),
            capacity_bytes: Set(capacity_bytes),
            disk_format: Set((config.kind == VolumeKind::Disk).then(|| "raw".to_string())),
            disk_fstype: Set((config.kind == VolumeKind::Disk).then(|| "ext4".to_string())),
            labels: Set(labels_json),
            created_at: Set(Some(now)),
            updated_at: Set(Some(now)),
            ..Default::default()
        };
        volume_entity::Entity::insert(model).exec(txn).await?;
        Ok(VolumeProvision::Inserted)
    }

    /// Resolve the on-disk path for a named volume.
    pub(crate) fn path_for(name: &str) -> PathBuf {
        crate::config::config().volumes_dir().join(name)
    }

    /// Provision the on-disk artifact for a volume registered via
    /// [`provision_in_transaction`].
    pub(crate) async fn materialise_for(config: &VolumeConfig) -> MicrosandboxResult<()> {
        let volumes_dir = crate::config::config().volumes_dir();
        tokio::fs::create_dir_all(&volumes_dir).await?;
        let path = volumes_dir.join(&config.name);
        if path.exists() {
            return Err(MicrosandboxError::VolumeAlreadyExists(config.name.clone()));
        }
        let temp = tempfile::Builder::new()
            .prefix(&format!(".{}.", config.name))
            .tempdir_in(&volumes_dir)?;
        provision_volume_path(config, temp.path()).await?;
        tokio::fs::rename(temp.path(), &path).await?;
        let _ = temp.keep();
        Ok(())
    }

    /// Get a volume handle by name from the database.
    ///
    /// Returns a lightweight handle for metadata and management operations.
    pub async fn get(name: &str) -> MicrosandboxResult<VolumeHandle> {
        let db = crate::db::init_global().await?.read();

        let model = volume_entity::Entity::find()
            .filter(volume_entity::Column::Name.eq(name))
            .one(db)
            .await?
            .ok_or_else(|| MicrosandboxError::VolumeNotFound(name.into()))?;

        Ok(VolumeHandle::from_model(model))
    }

    /// List all volumes, ordered by creation time (newest first).
    pub async fn list() -> MicrosandboxResult<Vec<VolumeHandle>> {
        let db = crate::db::init_global().await?.read();

        let models = volume_entity::Entity::find()
            .order_by_desc(volume_entity::Column::CreatedAt)
            .all(db)
            .await?;

        Ok(models.into_iter().map(VolumeHandle::from_model).collect())
    }

    /// Delete a volume's database record and host directory.
    /// Fails with [`MicrosandboxError::VolumeNotFound`] if no such volume exists.
    pub async fn remove(name: &str) -> MicrosandboxResult<()> {
        Self::get(name).await?.remove().await
    }
}

//--------------------------------------------------------------------------------------------------
// Methods: Instance
//--------------------------------------------------------------------------------------------------

impl Volume {
    /// Unique name identifying this volume.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Storage kind for this volume.
    pub fn kind(&self) -> VolumeKind {
        self.kind
    }

    /// Host-side directory where this volume's data is stored
    /// (under `~/.microsandbox/volumes/<name>/`).
    pub fn path(&self) -> &std::path::Path {
        &self.path
    }

    /// Disk capacity in bytes for disk volumes.
    pub fn capacity_bytes(&self) -> Option<u64> {
        self.capacity_bytes
    }

    /// Disk image format for disk volumes. V1 always creates `raw`.
    pub fn disk_format(&self) -> Option<&str> {
        self.disk_format.as_deref()
    }

    /// Inner disk filesystem for disk volumes. V1 always creates `ext4`.
    pub fn disk_fstype(&self) -> Option<&str> {
        self.disk_fstype.as_deref()
    }

    /// Host path to the managed raw disk image for disk volumes.
    pub fn disk_path(&self) -> Option<PathBuf> {
        (self.kind == VolumeKind::Disk).then(|| self.path.join("disk.raw"))
    }

    /// Operate on the volume's host-side directory (read, write, list files)
    /// without needing a running sandbox.
    pub fn fs(&self) -> fs::VolumeFs<'_> {
        fs::VolumeFs::from_path_ref(&self.path)
    }
}

//--------------------------------------------------------------------------------------------------
// Methods: VolumeBuilder
//--------------------------------------------------------------------------------------------------

impl VolumeBuilder {
    /// Start building a volume with the given name. Names must contain only
    /// alphanumeric characters, dots, hyphens, and underscores.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            config: VolumeConfig {
                name: name.into(),
                kind: VolumeKind::Directory,
                quota_mib: None,
                capacity_mib: None,
                labels: Vec::new(),
            },
        }
    }

    /// Create a directory-backed named volume.
    pub fn directory(mut self) -> Self {
        self.config.kind = VolumeKind::Directory;
        self
    }

    /// Create a raw ext4 disk-image named volume.
    pub fn disk(mut self) -> Self {
        self.config.kind = VolumeKind::Disk;
        self
    }

    /// Limit the volume's storage capacity. Accepts bare `u32` (MiB) or a
    /// [`SizeExt`](crate::size::SizeExt) helper:
    ///
    /// ```ignore
    /// .quota(1024)         // 1024 MiB
    /// .quota(1.gib())      // 1 GiB = 1024 MiB
    /// ```
    ///
    /// Omit to allow unlimited growth (default).
    pub fn quota(mut self, size: impl Into<Mebibytes>) -> Self {
        self.config.quota_mib = Some(size.into().as_u32());
        self
    }

    /// Set disk volume capacity. Required for disk volumes.
    pub fn size(mut self, size: impl Into<Mebibytes>) -> Self {
        self.config.capacity_mib = Some(size.into().as_u32());
        self
    }

    /// Attach a key-value label for organizing and filtering volumes.
    /// Can be called multiple times.
    pub fn label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.config.labels.push((key.into(), value.into()));
        self
    }

    /// Build the volume config without creating it.
    pub fn build(self) -> VolumeConfig {
        self.config
    }

    /// Create the volume.
    pub async fn create(self) -> MicrosandboxResult<Volume> {
        Volume::create(self.config).await
    }
}

//--------------------------------------------------------------------------------------------------
// Trait Implementations
//--------------------------------------------------------------------------------------------------

impl From<VolumeConfig> for VolumeBuilder {
    fn from(config: VolumeConfig) -> Self {
        Self { config }
    }
}

//--------------------------------------------------------------------------------------------------
// Methods: VolumeKind
//--------------------------------------------------------------------------------------------------

impl VolumeKind {
    /// Database string for this volume kind.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Directory => "dir",
            Self::Disk => "disk",
        }
    }

    fn from_db_value(value: &str) -> Self {
        match value {
            "disk" => Self::Disk,
            _ => Self::Directory,
        }
    }
}

//--------------------------------------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------------------------------------

async fn provision_volume_path(
    config: &VolumeConfig,
    path: &std::path::Path,
) -> MicrosandboxResult<()> {
    tokio::fs::create_dir_all(path).await?;

    match config.kind {
        VolumeKind::Directory => Ok(()),
        VolumeKind::Disk => {
            let capacity_mib = config.capacity_mib.ok_or_else(|| {
                MicrosandboxError::InvalidConfig(
                    "disk named volumes require .size(...) / --size".into(),
                )
            })?;
            let disk_path = path.join("disk.raw");
            let options = Ext4FormatOptions {
                size_bytes: u64::from(capacity_mib) * 1024 * 1024,
                ..Default::default()
            };
            tokio::task::spawn_blocking(move || ext4::format_ext4(&disk_path, &options))
                .await
                .map_err(|e| MicrosandboxError::Custom(format!("ext4 format task failed: {e}")))?
                .map_err(|e| {
                    MicrosandboxError::Custom(format!("failed to create disk.raw: {e}"))
                })?;
            Ok(())
        }
    }
}

fn validate_volume_config(config: &VolumeConfig) -> MicrosandboxResult<()> {
    match config.kind {
        VolumeKind::Directory => {
            if config.capacity_mib.is_some() {
                return Err(MicrosandboxError::InvalidConfig(
                    "directory named volumes do not support .size(...) / --size in v1".into(),
                ));
            }
            Ok(())
        }
        VolumeKind::Disk => {
            if config.capacity_mib.is_none() {
                return Err(MicrosandboxError::InvalidConfig(
                    "disk named volumes require .size(...) / --size".into(),
                ));
            }
            if config.quota_mib.is_some() {
                return Err(MicrosandboxError::InvalidConfig(
                    "disk named volumes do not support .quota(...)".into(),
                ));
            }
            Ok(())
        }
    }
}

fn validate_existing_volume_config(
    existing: &volume_entity::Model,
    requested: &VolumeConfig,
) -> MicrosandboxResult<()> {
    let existing_kind = VolumeKind::from_db_value(&existing.kind);
    if existing_kind != requested.kind {
        return Err(MicrosandboxError::InvalidConfig(format!(
            "named volume {:?} already exists with kind {:?}, requested {:?}",
            requested.name, existing_kind, requested.kind
        )));
    }

    let requested_quota = requested.quota_mib.map(|value| value as i32);
    if existing.quota_mib != requested_quota {
        return Err(MicrosandboxError::InvalidConfig(format!(
            "named volume {:?} already exists with quota {:?}, requested {:?}",
            requested.name, existing.quota_mib, requested_quota
        )));
    }

    let requested_capacity = requested
        .capacity_mib
        .map(|value| i64::from(value) * 1024 * 1024);
    if existing.capacity_bytes != requested_capacity {
        return Err(MicrosandboxError::InvalidConfig(format!(
            "named volume {:?} already exists with capacity {:?}, requested {:?}",
            requested.name, existing.capacity_bytes, requested_capacity
        )));
    }

    if !requested.labels.is_empty() {
        let existing_labels = existing
            .labels
            .as_deref()
            .map(serde_json::from_str::<Vec<(String, String)>>)
            .transpose()?
            .unwrap_or_default();
        if existing_labels != requested.labels {
            return Err(MicrosandboxError::InvalidConfig(format!(
                "named volume {:?} already exists with different labels",
                requested.name
            )));
        }
    }

    Ok(())
}

pub(crate) fn lock_volume_name(name: &str) -> MicrosandboxResult<File> {
    let volumes_dir = crate::config::config().volumes_dir();
    std::fs::create_dir_all(&volumes_dir)?;
    let locks_dir = volumes_dir.join(".locks");
    std::fs::create_dir_all(&locks_dir)?;
    let path = locks_dir.join(format!("{name}.lock"));
    let file = std::fs::OpenOptions::new()
        .create(true)
        .read(true)
        .truncate(false)
        .write(true)
        .open(&path)?;

    if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 {
        return Err(std::io::Error::last_os_error().into());
    }

    Ok(file)
}

fn lock_disk_volume_for_remove(handle: &VolumeHandle) -> MicrosandboxResult<Option<File>> {
    if handle.kind() != VolumeKind::Disk {
        return Ok(None);
    }

    let Some(path) = handle.disk_path() else {
        return Ok(None);
    };
    if !path.exists() {
        return Ok(None);
    }

    let file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(&path)
        .map_err(|e| {
            MicrosandboxError::InvalidConfig(format!(
                "open disk named volume {} for removal: {e}",
                handle.name()
            ))
        })?;

    if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
        let err = std::io::Error::last_os_error();
        if matches!(err.kind(), std::io::ErrorKind::WouldBlock) {
            return Err(MicrosandboxError::InvalidConfig(format!(
                "volume {:?} is currently attached by a running sandbox",
                handle.name()
            )));
        }
        return Err(MicrosandboxError::InvalidConfig(format!(
            "lock disk named volume {} for removal: {err}",
            handle.name()
        )));
    }

    Ok(Some(file))
}

async fn ensure_volume_not_referenced_by_active_sandbox<C>(
    db: &C,
    name: &str,
) -> MicrosandboxResult<()>
where
    C: ConnectionTrait,
{
    let sandboxes = sandbox_entity::Entity::find()
        .filter(sandbox_entity::Column::Status.is_in([
            SandboxStatus::Running,
            SandboxStatus::Draining,
            SandboxStatus::Paused,
        ]))
        .all(db)
        .await?;

    for sandbox in sandboxes {
        let config: SandboxConfig = serde_json::from_str(&sandbox.config)?;
        if config.mounts.iter().any(|mount| {
            matches!(
                mount,
                VolumeMount::Named {
                    name: mounted_name,
                    ..
                } if mounted_name == name
            )
        }) {
            return Err(MicrosandboxError::InvalidConfig(format!(
                "volume {name:?} is attached to active sandbox {:?}",
                sandbox.name
            )));
        }
    }

    Ok(())
}

/// Validate that a volume name is safe for use as a directory name.
///
/// Names must start with an alphanumeric character and contain only
/// alphanumeric characters, dots, hyphens, and underscores.
pub(crate) fn validate_volume_name(name: &str) -> MicrosandboxResult<()> {
    if name.is_empty() {
        return Err(MicrosandboxError::InvalidConfig(
            "volume name must not be empty".into(),
        ));
    }

    let valid = name
        .chars()
        .next()
        .is_some_and(|c| c.is_ascii_alphanumeric())
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_');

    if !valid {
        return Err(MicrosandboxError::InvalidConfig(format!(
            "volume name must start with an alphanumeric character and contain only \
             alphanumeric characters, dots, hyphens, and underscores: {name}"
        )));
    }

    Ok(())
}