stable-fs 0.13.0

A Simple File system using the stable structures of the Internet Computer that implements WASI endpoints
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
use crate::{error::Error, fs::ChunkType};
use ic_stable_structures::storable::Bound;
use serde::{Deserialize, Serialize};

pub const FILE_CHUNK_SIZE_V1: usize = 4096;

pub const DEFAULT_FILE_CHUNK_SIZE_V2: usize = 16384;
pub const MAX_FILE_CHUNK_SIZE_V2: usize = 65536;

pub const MAX_FILE_NAME: usize = 255;

// maximal chunk index. (reserve last 10 chunks for custom needs)
pub const MAX_FILE_CHUNK_COUNT: u32 = u32::MAX - 10;

// maximal file size supported by the file system.
pub const MAX_FILE_SIZE: u64 = (MAX_FILE_CHUNK_COUNT as u64) * FILE_CHUNK_SIZE_V1 as u64;

// maximal file entry index
pub const MAX_FILE_ENTRY_INDEX: u32 = u32::MAX - 10;

// special "." entry index
pub const DUMMY_DOT_ENTRY_INDEX: u32 = u32::MAX - 5;
// special ".." entry index
pub const DUMMY_DOT_DOT_ENTRY_INDEX: u32 = u32::MAX - 4;

pub const DUMMY_DOT_ENTRY: (DirEntryIndex, DirEntry) = (
    DUMMY_DOT_ENTRY_INDEX,
    DirEntry {
        name: FileName {
            length: 1,
            bytes: {
                let mut arr = [0u8; 255];
                arr[0] = b'.';
                arr
            },
        },
        node: 0,
        entry_type: None,
    },
);

pub const DUMMY_DOT_DOT_ENTRY: (DirEntryIndex, DirEntry) = (
    DUMMY_DOT_DOT_ENTRY_INDEX,
    DirEntry {
        name: FileName {
            length: 2,
            bytes: {
                let mut arr = [0u8; 255];
                arr[0] = b'.';
                arr[1] = b'.';
                arr
            },
        },
        node: 0,
        entry_type: None,
    },
);

// The unique identifier of a node, which can be a file or a directory.
// Also known as inode in WASI and other file systems.
pub type Node = u64;

// An integer type for representing file sizes and offsets.
pub type FileSize = u64;

// An index of a file chunk.
pub type FileChunkIndex = u32;

// The address in memory where the V2 chunk is stored.
pub type FileChunkPtr = u64;

// An array filled with 0 used to fill memory with 0 via copy.
pub static ZEROES: [u8; MAX_FILE_CHUNK_SIZE_V2] = [0u8; MAX_FILE_CHUNK_SIZE_V2];

// A handle used for writing files in chunks.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct ChunkHandle {
    pub index: FileChunkIndex,
    pub offset: FileSize,
    pub len: FileSize,
}

// A file consists of multiple file chunks.
#[derive(Clone, Debug, PartialEq)]
pub struct FileChunk {
    pub bytes: [u8; FILE_CHUNK_SIZE_V1],
}

impl Default for FileChunk {
    fn default() -> Self {
        Self {
            bytes: [0; FILE_CHUNK_SIZE_V1],
        }
    }
}

impl ic_stable_structures::Storable for FileChunk {
    fn to_bytes(&'_ self) -> std::borrow::Cow<'_, [u8]> {
        std::borrow::Cow::Borrowed(&self.bytes)
    }

    fn into_bytes(self) -> Vec<u8> {
        self.bytes.to_vec()
    }

    fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self {
        Self {
            bytes: bytes.as_ref().try_into().unwrap(),
        }
    }

    const BOUND: Bound = Bound::Bounded {
        max_size: FILE_CHUNK_SIZE_V1 as u32,
        is_fixed_size: true,
    };
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Header {
    pub version: u32,
    pub next_node: Node,
}

impl ic_stable_structures::Storable for Header {
    fn to_bytes(&'_ self) -> std::borrow::Cow<'_, [u8]> {
        let mut buf = vec![];
        ciborium::ser::into_writer(&self, &mut buf).unwrap();
        std::borrow::Cow::Owned(buf)
    }

    fn into_bytes(self) -> Vec<u8> {
        let mut buf = vec![];
        ciborium::ser::into_writer(&self, &mut buf).unwrap();
        buf
    }

    fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self {
        ciborium::de::from_reader(bytes.as_ref()).unwrap()
    }

    const BOUND: Bound = Bound::Unbounded;
}

#[repr(C, align(8))]
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Metadata {
    pub node: Node,
    pub file_type: FileType,
    pub link_count: u64,
    pub size: FileSize,
    pub times: Times,
    pub first_dir_entry: Option<DirEntryIndex>, // obsolete field, must be kept for compatibility because of repr(C)
    pub last_dir_entry: Option<DirEntryIndex>, // obsolete field, must be kept for compatibility because of repr(C)
    pub chunk_type: Option<ChunkType>,
    pub maximum_size_allowed: Option<FileSize>,
}

impl ic_stable_structures::Storable for Metadata {
    fn to_bytes(&'_ self) -> std::borrow::Cow<'_, [u8]> {
        let mut buf = vec![];
        ciborium::ser::into_writer(&self, &mut buf).unwrap();
        std::borrow::Cow::Owned(buf)
    }

    fn into_bytes(self) -> Vec<u8> {
        let mut buf = vec![];
        ciborium::ser::into_writer(&self, &mut buf).unwrap();
        buf
    }

    fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self {
        ciborium::de::from_reader(bytes.as_ref()).unwrap()
    }

    const BOUND: Bound = Bound::Unbounded;
}

// The type of a node.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum FileType {
    Directory = 3,
    #[default]
    RegularFile = 4,
    SymbolicLink = 7,
}

impl TryFrom<u8> for FileType {
    type Error = Error;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            3 => Ok(FileType::Directory),
            4 => Ok(FileType::RegularFile),
            7 => Ok(FileType::SymbolicLink),
            _ => Err(Error::InvalidArgument),
        }
    }
}

impl From<FileType> for u8 {
    fn from(val: FileType) -> Self {
        match val {
            FileType::Directory => 3,
            FileType::RegularFile => 4,
            FileType::SymbolicLink => 7,
        }
    }
}

// The time stats of a node.
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Times {
    pub accessed: u64,
    pub modified: u64,
    pub created: u64,
}

use std::cmp::{Ord, Ordering, PartialOrd};

// The name of a file or a directory. Most operating systems limit the max file
// name length to 255.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FileName {
    pub length: u8,
    #[serde(
        deserialize_with = "deserialize_file_name",
        serialize_with = "serialize_file_name"
    )]
    pub bytes: [u8; MAX_FILE_NAME],
}

impl Eq for FileName {}

impl PartialEq for FileName {
    fn eq(&self, other: &Self) -> bool {
        self.length == other.length
            && self.bytes[..self.length as usize] == other.bytes[..other.length as usize]
    }
}

impl PartialOrd for FileName {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for FileName {
    fn cmp(&self, other: &Self) -> Ordering {
        let min_len = self.length.min(other.length) as usize;

        match self.bytes[..min_len].cmp(&other.bytes[..min_len]) {
            Ordering::Equal => self.length.cmp(&other.length),
            ord => ord,
        }
    }
}

use ic_stable_structures::Storable;

impl Storable for FileName {
    fn to_bytes(&'_ self) -> std::borrow::Cow<'_, [u8]> {
        let mut buf = [0u8; MAX_FILE_NAME + 1];

        buf[0] = self.length;
        buf[1..256].copy_from_slice(&self.bytes);

        std::borrow::Cow::Owned(buf.to_vec())
    }

    fn into_bytes(self) -> Vec<u8> {
        let mut buf = [0u8; MAX_FILE_NAME + 1];

        buf[0] = self.length;
        buf[1..256].copy_from_slice(&self.bytes);

        buf.to_vec()
    }

    fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self {
        let mut arr = [0u8; MAX_FILE_NAME];
        arr.copy_from_slice(&bytes[1..MAX_FILE_NAME + 1]);

        FileName {
            length: bytes[0],
            bytes: arr,
        }
    }

    const BOUND: ic_stable_structures::storable::Bound =
        ic_stable_structures::storable::Bound::Bounded {
            max_size: 256,
            is_fixed_size: true,
        };
}

fn serialize_file_name<S>(bytes: &[u8; MAX_FILE_NAME], serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serde_bytes::Bytes::new(bytes).serialize(serializer)
}

fn deserialize_file_name<'de, D>(deserializer: D) -> Result<[u8; MAX_FILE_NAME], D::Error>
where
    D: serde::Deserializer<'de>,
{
    let bytes: Vec<u8> = serde_bytes::deserialize(deserializer).unwrap();
    let len = bytes.len();
    let bytes_array: [u8; MAX_FILE_NAME] = bytes
        .try_into()
        .map_err(|_| serde::de::Error::invalid_length(len, &"expected MAX_FILE_NAME bytes"))?;
    Ok(bytes_array)
}

impl Default for FileName {
    fn default() -> Self {
        Self {
            length: 0,
            bytes: [0; MAX_FILE_NAME],
        }
    }
}

impl FileName {
    pub fn new(name: &[u8]) -> Result<Self, Error> {
        let len = name.len();
        if len > MAX_FILE_NAME {
            return Err(Error::FilenameTooLong);
        }

        let mut bytes = [0; MAX_FILE_NAME];
        bytes[0..len].copy_from_slice(name);
        Ok(Self {
            length: len as u8,
            bytes,
        })
    }
}

impl std::fmt::Display for FileName {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", unsafe {
            std::str::from_utf8_unchecked(&self.bytes[..(self.length as usize)])
        })
    }
}

// An index of a directory entry.
pub type DirEntryIndex = u32;

// A directory contains a list of directory entries.
// Each entry describes a name of a file or a directory.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct DirEntry {
    pub name: FileName,
    pub node: Node,
    pub entry_type: Option<FileType>,
}

impl ic_stable_structures::Storable for DirEntry {
    fn to_bytes(&'_ self) -> std::borrow::Cow<'_, [u8]> {
        let mut buf = vec![];
        ciborium::ser::into_writer(&self, &mut buf).unwrap();
        std::borrow::Cow::Owned(buf)
    }

    fn into_bytes(self) -> Vec<u8> {
        let mut buf = vec![];
        ciborium::ser::into_writer(&self, &mut buf).unwrap();
        buf
    }

    fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self {
        ciborium::de::from_reader(bytes.as_ref()).unwrap()
    }

    const BOUND: ic_stable_structures::storable::Bound = Bound::Unbounded;
}

/// Mounting policy to determine actual mounted memory file size
pub enum MountedFileSizePolicy {
    /// Reuse the size from a previous mount or 0 if unknown
    PreviousOrZero,
    /// Reuse the size from a previous mount or determine from memory pages.
    PreviousOrMemoryPages,
    /// Explicitly set the file size, overriding other options.
    Explicit(FileSize),
    /// Determine file size from the memory pages.
    MemoryPages,
}

impl MountedFileSizePolicy {
    pub fn get_mounted_file_size(
        &self,
        previous_size: Option<FileSize>,
        current_memory_pages: FileSize,
    ) -> FileSize {
        let current_size = current_memory_pages * ic_cdk::stable::WASM_PAGE_SIZE_IN_BYTES;

        match self {
            MountedFileSizePolicy::PreviousOrZero => {
                if let Some(old_size) = previous_size
                    && old_size <= current_size
                {
                    old_size
                } else {
                    0
                }
            }
            MountedFileSizePolicy::PreviousOrMemoryPages => {
                if let Some(old_size) = previous_size
                    && old_size <= current_size
                {
                    old_size
                } else {
                    current_size
                }
            }
            MountedFileSizePolicy::Explicit(size) => *size,
            MountedFileSizePolicy::MemoryPages => current_size,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{fs::ChunkType, storage::types::MountedFileSizePolicy};

    use super::{DirEntryIndex, FileSize, FileType, Node, Times};
    use serde::{Deserialize, Serialize};

    // Old node structure.
    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
    pub struct MetadataOld {
        pub node: Node,
        pub file_type: FileType,
        pub link_count: u64,
        pub size: FileSize,
        pub times: Times,
        pub first_dir_entry: Option<DirEntryIndex>,
        pub last_dir_entry: Option<DirEntryIndex>,
    }

    // New node structure.
    #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
    pub struct MetadataNew {
        pub node: Node,
        pub file_type: FileType,
        pub link_count: u64,
        pub size: FileSize,
        pub times: Times,
        pub _first_dir_entry: Option<DirEntryIndex>, // obsolete field
        pub _last_dir_entry: Option<DirEntryIndex>,  // obsolete field
        pub chunk_type: Option<ChunkType>,
    }

    fn meta_to_bytes(meta: &'_ MetadataOld) -> std::borrow::Cow<'_, [u8]> {
        let mut buf = vec![];
        ciborium::ser::into_writer(meta, &mut buf).unwrap();
        std::borrow::Cow::Owned(buf)
    }

    fn meta_from_bytes(bytes: std::borrow::Cow<[u8]>) -> MetadataNew {
        ciborium::de::from_reader(bytes.as_ref()).unwrap()
    }

    #[test]
    fn store_old_load_new() {
        let meta_old = MetadataOld {
            node: 23,
            file_type: FileType::RegularFile,
            link_count: 3,
            size: 123,
            times: Times::default(),
            first_dir_entry: Some(23),
            last_dir_entry: Some(35),
        };

        let bytes = meta_to_bytes(&meta_old);

        let meta_new = meta_from_bytes(bytes);

        assert_eq!(meta_new.node, meta_old.node);
        assert_eq!(meta_new.file_type, meta_old.file_type);
        assert_eq!(meta_new.link_count, meta_old.link_count);
        assert_eq!(meta_new.size, meta_old.size);
        assert_eq!(meta_new.times, meta_old.times);
        assert_eq!(meta_new.chunk_type, None);
    }

    #[test]
    fn store_old_load_new_both_none() {
        let meta_old = MetadataOld {
            node: 23,
            file_type: FileType::RegularFile,
            link_count: 3,
            size: 123,
            times: Times::default(),
            first_dir_entry: None,
            last_dir_entry: None,
        };

        let bytes = meta_to_bytes(&meta_old);

        let meta_new = meta_from_bytes(bytes);

        assert_eq!(meta_new.node, meta_old.node);
        assert_eq!(meta_new.file_type, meta_old.file_type);
        assert_eq!(meta_new.link_count, meta_old.link_count);
        assert_eq!(meta_new.size, meta_old.size);
        assert_eq!(meta_new.times, meta_old.times);
        assert_eq!(meta_new.chunk_type, None);
    }

    #[test]
    fn store_old_load_new_first_none() {
        let meta_old = MetadataOld {
            node: 23,
            file_type: FileType::RegularFile,
            link_count: 3,
            size: 123,
            times: Times::default(),
            first_dir_entry: None,
            last_dir_entry: Some(23),
        };

        let bytes = meta_to_bytes(&meta_old);

        let meta_new = meta_from_bytes(bytes);

        assert_eq!(meta_new.node, meta_old.node);
        assert_eq!(meta_new.file_type, meta_old.file_type);
        assert_eq!(meta_new.link_count, meta_old.link_count);
        assert_eq!(meta_new.size, meta_old.size);
        assert_eq!(meta_new.times, meta_old.times);
        assert_eq!(meta_new.chunk_type, None);
    }

    #[test]
    fn size_policy_test() {
        use ic_cdk::stable::WASM_PAGE_SIZE_IN_BYTES as PAGE_SIZE;

        let p = MountedFileSizePolicy::PreviousOrZero;
        assert_eq!(p.get_mounted_file_size(Some(100000), 1), 0);
        assert_eq!(p.get_mounted_file_size(Some(100000), 2), 100000);
        assert_eq!(p.get_mounted_file_size(None, 2), 0);

        let p = MountedFileSizePolicy::PreviousOrMemoryPages;
        assert_eq!(p.get_mounted_file_size(Some(100000), 1), PAGE_SIZE);
        assert_eq!(p.get_mounted_file_size(Some(100000), 2), 100000);
        assert_eq!(p.get_mounted_file_size(None, 2), PAGE_SIZE * 2);

        let p = MountedFileSizePolicy::Explicit(3000);
        assert_eq!(p.get_mounted_file_size(Some(100000), 1), 3000);
        assert_eq!(p.get_mounted_file_size(Some(100000), 2), 3000);
        assert_eq!(p.get_mounted_file_size(None, 2), 3000);

        let p = MountedFileSizePolicy::MemoryPages;
        assert_eq!(p.get_mounted_file_size(Some(100000), 1), PAGE_SIZE);
        assert_eq!(p.get_mounted_file_size(Some(100000), 2), PAGE_SIZE * 2);
        assert_eq!(p.get_mounted_file_size(None, 2), PAGE_SIZE * 2);
    }
}