lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! WASM plugin types and data structures.
//!
//! This module defines the core types for the WASM plugin system including
//! manifests, hooks, permissions, and plugin context.

use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

// ═══════════════════════════════════════════════════════════════════════════════
// HOOK TYPES
// ═══════════════════════════════════════════════════════════════════════════════

/// Hook types that plugins can implement.
///
/// Each hook is called at a specific point in the I/O pipeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HookType {
    /// Called before write operation - can modify data
    PreWrite,
    /// Called after write operation - for logging/metrics
    PostWrite,
    /// Called before read operation - for access control
    PreRead,
    /// Called after read operation - can modify data
    PostRead,
    /// Called when file is created
    OnCreate,
    /// Called when file is deleted
    OnDelete,
    /// Custom compression algorithm
    Compress,
    /// Custom decompression algorithm
    Decompress,
    /// Data validation (return error to reject)
    Validate,
    /// Transform data (e.g., image resize)
    Transform,
}

impl HookType {
    /// Get the string name for this hook type.
    pub fn as_str(&self) -> &'static str {
        match self {
            HookType::PreWrite => "PreWrite",
            HookType::PostWrite => "PostWrite",
            HookType::PreRead => "PreRead",
            HookType::PostRead => "PostRead",
            HookType::OnCreate => "OnCreate",
            HookType::OnDelete => "OnDelete",
            HookType::Compress => "Compress",
            HookType::Decompress => "Decompress",
            HookType::Validate => "Validate",
            HookType::Transform => "Transform",
        }
    }

    /// Parse hook type from string.
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "PreWrite" => Some(HookType::PreWrite),
            "PostWrite" => Some(HookType::PostWrite),
            "PreRead" => Some(HookType::PreRead),
            "PostRead" => Some(HookType::PostRead),
            "OnCreate" => Some(HookType::OnCreate),
            "OnDelete" => Some(HookType::OnDelete),
            "Compress" => Some(HookType::Compress),
            "Decompress" => Some(HookType::Decompress),
            "Validate" => Some(HookType::Validate),
            "Transform" => Some(HookType::Transform),
            _ => None,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// PERMISSIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Plugin permissions - capabilities that plugins can request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Permission {
    /// Can read file content
    ReadContent,
    /// Can modify file content
    WriteContent,
    /// Can read file metadata
    ReadMetadata,
    /// Can modify file metadata
    WriteMetadata,
    /// Can make network calls (sandboxed)
    Network,
    /// Can access specific path patterns
    PathAccess(String),
    /// Can allocate up to N bytes of memory
    MemoryLimit(usize),
    /// Can execute for up to N milliseconds
    TimeLimit(u64),
}

impl Permission {
    /// Parse permission from JSON-like string.
    pub fn from_str(s: &str) -> Option<Self> {
        // Handle simple permissions
        match s {
            "ReadContent" => return Some(Permission::ReadContent),
            "WriteContent" => return Some(Permission::WriteContent),
            "ReadMetadata" => return Some(Permission::ReadMetadata),
            "WriteMetadata" => return Some(Permission::WriteMetadata),
            "Network" => return Some(Permission::Network),
            _ => {}
        }

        // Handle parameterized permissions
        if let Some(path) = s.strip_prefix("PathAccess:") {
            return Some(Permission::PathAccess(path.to_string()));
        }
        if let Some(limit) = s.strip_prefix("MemoryLimit:") {
            if let Ok(n) = limit.parse() {
                return Some(Permission::MemoryLimit(n));
            }
        }
        if let Some(limit) = s.strip_prefix("TimeLimit:") {
            if let Ok(n) = limit.parse() {
                return Some(Permission::TimeLimit(n));
            }
        }

        None
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// PLUGIN MANIFEST
// ═══════════════════════════════════════════════════════════════════════════════

/// Plugin metadata loaded from WASM module.
#[derive(Debug, Clone, PartialEq)]
pub struct PluginManifest {
    /// Plugin name
    pub name: String,
    /// Version string (semver)
    pub version: String,
    /// Author name
    pub author: String,
    /// Description of what the plugin does
    pub description: String,
    /// Hooks this plugin implements
    pub hooks: Vec<HookType>,
    /// Permissions the plugin requires
    pub permissions: Vec<Permission>,
}

impl Default for PluginManifest {
    fn default() -> Self {
        Self {
            name: String::new(),
            version: "0.0.0".into(),
            author: "Unknown".into(),
            description: String::new(),
            hooks: Vec::new(),
            permissions: Vec::new(),
        }
    }
}

impl PluginManifest {
    /// Create a new manifest with required fields.
    pub fn new(name: &str, version: &str) -> Self {
        Self {
            name: name.into(),
            version: version.into(),
            ..Default::default()
        }
    }

    /// Parse manifest from JSON string.
    ///
    /// Expected format:
    /// ```json
    /// {
    ///   "name": "plugin-name",
    ///   "version": "1.0.0",
    ///   "author": "Author Name",
    ///   "description": "What it does",
    ///   "hooks": ["PreWrite", "PostRead"],
    ///   "permissions": ["ReadContent", "WriteContent"]
    /// }
    /// ```
    pub fn from_json(json: &str) -> Result<Self, ManifestError> {
        let mut manifest = PluginManifest::default();

        // Simple JSON parser - handles basic cases
        let json = json.trim();
        if !json.starts_with('{') || !json.ends_with('}') {
            return Err(ManifestError::InvalidFormat);
        }

        // Extract fields
        if let Some(name) = extract_string_field(json, "name") {
            manifest.name = name;
        } else {
            return Err(ManifestError::MissingField("name"));
        }

        if let Some(version) = extract_string_field(json, "version") {
            manifest.version = version;
        }

        if let Some(author) = extract_string_field(json, "author") {
            manifest.author = author;
        }

        if let Some(description) = extract_string_field(json, "description") {
            manifest.description = description;
        }

        // Parse hooks array
        if let Some(hooks_str) = extract_array_field(json, "hooks") {
            for hook_str in parse_string_array(&hooks_str) {
                if let Some(hook) = HookType::from_str(&hook_str) {
                    manifest.hooks.push(hook);
                }
            }
        }

        // Parse permissions array
        if let Some(perms_str) = extract_array_field(json, "permissions") {
            for perm_str in parse_string_array(&perms_str) {
                if let Some(perm) = Permission::from_str(&perm_str) {
                    manifest.permissions.push(perm);
                }
            }
        }

        Ok(manifest)
    }

    /// Check if plugin has a specific permission.
    pub fn has_permission(&self, perm: &Permission) -> bool {
        self.permissions.iter().any(|p| {
            match (p, perm) {
                (Permission::PathAccess(pattern), Permission::PathAccess(path)) => {
                    // Simple glob matching
                    if pattern.ends_with('*') {
                        let prefix = &pattern[..pattern.len() - 1];
                        path.starts_with(prefix)
                    } else {
                        pattern == path
                    }
                }
                _ => p == perm,
            }
        })
    }

    /// Check if plugin implements a specific hook.
    pub fn implements_hook(&self, hook: HookType) -> bool {
        self.hooks.contains(&hook)
    }
}

/// Errors when parsing plugin manifest.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ManifestError {
    /// JSON format is invalid
    InvalidFormat,
    /// Required field is missing
    MissingField(&'static str),
    /// Field has invalid value
    InvalidField(&'static str),
}

// ═══════════════════════════════════════════════════════════════════════════════
// PLUGIN CONTEXT
// ═══════════════════════════════════════════════════════════════════════════════

/// Context passed to plugin during hook execution.
#[derive(Debug, Clone, Default)]
pub struct PluginContext {
    /// File path being operated on
    pub path: String,
    /// File size in bytes
    pub size: u64,
    /// Dataset name
    pub dataset: String,
    /// Operation type (read, write, etc.)
    pub operation: String,
    /// Custom metadata key-value pairs
    pub metadata: BTreeMap<String, String>,
}

impl PluginContext {
    /// Create new context for an operation.
    pub fn new(path: &str, dataset: &str, operation: &str) -> Self {
        Self {
            path: path.into(),
            dataset: dataset.into(),
            operation: operation.into(),
            ..Default::default()
        }
    }

    /// Set file size.
    pub fn with_size(mut self, size: u64) -> Self {
        self.size = size;
        self
    }

    /// Add metadata.
    pub fn with_metadata(mut self, key: &str, value: &str) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Serialize context to JSON for WASM.
    pub fn to_json(&self) -> String {
        let mut json = String::from("{");

        json.push_str(&alloc::format!("\"path\":\"{}\",", escape_json(&self.path)));
        json.push_str(&alloc::format!("\"size\":{},", self.size));
        json.push_str(&alloc::format!(
            "\"dataset\":\"{}\",",
            escape_json(&self.dataset)
        ));
        json.push_str(&alloc::format!(
            "\"operation\":\"{}\",",
            escape_json(&self.operation)
        ));

        // Metadata as nested object
        json.push_str("\"metadata\":{");
        let mut first = true;
        for (k, v) in &self.metadata {
            if !first {
                json.push(',');
            }
            json.push_str(&alloc::format!(
                "\"{}\":\"{}\"",
                escape_json(k),
                escape_json(v)
            ));
            first = false;
        }
        json.push_str("}}");

        json
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RESOURCE LIMITS
// ═══════════════════════════════════════════════════════════════════════════════

/// Resource limits for plugin execution.
#[derive(Debug, Clone)]
pub struct PluginLimits {
    /// Maximum WASM memory in bytes (default: 16 MB)
    pub max_memory: usize,
    /// Maximum execution time in milliseconds (default: 1000ms)
    pub max_execution_ms: u64,
    /// Maximum output size in bytes (default: 64 MB)
    pub max_output_size: usize,
    /// Maximum stack depth for calls
    pub max_stack_depth: usize,
}

impl Default for PluginLimits {
    fn default() -> Self {
        Self {
            max_memory: 16 * 1024 * 1024,      // 16 MB
            max_execution_ms: 1000,            // 1 second
            max_output_size: 64 * 1024 * 1024, // 64 MB
            max_stack_depth: 1024,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// PLUGIN INFO
// ═══════════════════════════════════════════════════════════════════════════════

/// Information about a loaded plugin.
#[derive(Debug, Clone)]
pub struct PluginInfo {
    /// Plugin name
    pub name: String,
    /// Plugin version
    pub version: String,
    /// Author
    pub author: String,
    /// Description
    pub description: String,
    /// Hooks implemented
    pub hooks: Vec<HookType>,
    /// Whether plugin is currently enabled
    pub enabled: bool,
    /// Number of times plugin has been invoked
    pub invocation_count: u64,
    /// Total execution time in microseconds
    pub total_execution_us: u64,
}

impl From<&PluginManifest> for PluginInfo {
    fn from(manifest: &PluginManifest) -> Self {
        Self {
            name: manifest.name.clone(),
            version: manifest.version.clone(),
            author: manifest.author.clone(),
            description: manifest.description.clone(),
            hooks: manifest.hooks.clone(),
            enabled: true,
            invocation_count: 0,
            total_execution_us: 0,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// HELPER FUNCTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Extract a string field from JSON.
fn extract_string_field(json: &str, field: &str) -> Option<String> {
    let pattern = alloc::format!("\"{}\":", field);
    let start = json.find(&pattern)?;
    let rest = &json[start + pattern.len()..];
    let rest = rest.trim_start();

    if !rest.starts_with('"') {
        return None;
    }

    let rest = &rest[1..];
    let end = rest.find('"')?;
    Some(rest[..end].to_string())
}

/// Extract an array field from JSON.
fn extract_array_field(json: &str, field: &str) -> Option<String> {
    let pattern = alloc::format!("\"{}\":", field);
    let start = json.find(&pattern)?;
    let rest = &json[start + pattern.len()..];
    let rest = rest.trim_start();

    if !rest.starts_with('[') {
        return None;
    }

    let mut depth = 0;
    let mut end = 0;
    for (i, c) in rest.chars().enumerate() {
        match c {
            '[' => depth += 1,
            ']' => {
                depth -= 1;
                if depth == 0 {
                    end = i;
                    break;
                }
            }
            _ => {}
        }
    }

    Some(rest[1..end].to_string())
}

/// Parse a JSON string array into a vector.
fn parse_string_array(s: &str) -> Vec<String> {
    let mut result = Vec::new();
    let mut in_string = false;
    let mut current = String::new();

    for c in s.chars() {
        match c {
            '"' => {
                if in_string {
                    result.push(current.clone());
                    current.clear();
                }
                in_string = !in_string;
            }
            _ if in_string => {
                current.push(c);
            }
            _ => {}
        }
    }

    result
}

/// Escape a string for JSON output.
fn escape_json(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '"' => result.push_str("\\\""),
            '\\' => result.push_str("\\\\"),
            '\n' => result.push_str("\\n"),
            '\r' => result.push_str("\\r"),
            '\t' => result.push_str("\\t"),
            _ => result.push(c),
        }
    }
    result
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    #[test]
    fn test_hook_type_round_trip() {
        let hooks = [
            HookType::PreWrite,
            HookType::PostWrite,
            HookType::PreRead,
            HookType::PostRead,
            HookType::OnCreate,
            HookType::OnDelete,
            HookType::Compress,
            HookType::Decompress,
            HookType::Validate,
            HookType::Transform,
        ];

        for hook in hooks {
            let s = hook.as_str();
            let parsed = HookType::from_str(s).unwrap();
            assert_eq!(hook, parsed);
        }
    }

    #[test]
    fn test_permission_parsing() {
        assert_eq!(
            Permission::from_str("ReadContent"),
            Some(Permission::ReadContent)
        );
        assert_eq!(
            Permission::from_str("WriteContent"),
            Some(Permission::WriteContent)
        );
        assert_eq!(
            Permission::from_str("PathAccess:/data/*"),
            Some(Permission::PathAccess("/data/*".into()))
        );
        assert_eq!(
            Permission::from_str("MemoryLimit:1048576"),
            Some(Permission::MemoryLimit(1048576))
        );
        assert_eq!(
            Permission::from_str("TimeLimit:5000"),
            Some(Permission::TimeLimit(5000))
        );
    }

    #[test]
    fn test_manifest_from_json() {
        let json = r#"{
            "name": "test-plugin",
            "version": "1.0.0",
            "author": "Test Author",
            "description": "A test plugin",
            "hooks": ["PreWrite", "PostRead"],
            "permissions": ["ReadContent", "WriteContent"]
        }"#;

        let manifest = PluginManifest::from_json(json).unwrap();
        assert_eq!(manifest.name, "test-plugin");
        assert_eq!(manifest.version, "1.0.0");
        assert_eq!(manifest.author, "Test Author");
        assert_eq!(manifest.hooks.len(), 2);
        assert!(manifest.hooks.contains(&HookType::PreWrite));
        assert!(manifest.hooks.contains(&HookType::PostRead));
        assert_eq!(manifest.permissions.len(), 2);
    }

    #[test]
    fn test_manifest_missing_name() {
        let json = r#"{"version": "1.0.0"}"#;
        let result = PluginManifest::from_json(json);
        assert_eq!(result, Err(ManifestError::MissingField("name")));
    }

    #[test]
    fn test_manifest_has_permission() {
        let mut manifest = PluginManifest::new("test", "1.0");
        manifest.permissions.push(Permission::ReadContent);
        manifest
            .permissions
            .push(Permission::PathAccess("/data/*".into()));

        assert!(manifest.has_permission(&Permission::ReadContent));
        assert!(!manifest.has_permission(&Permission::WriteContent));
        assert!(manifest.has_permission(&Permission::PathAccess("/data/file.txt".into())));
        assert!(!manifest.has_permission(&Permission::PathAccess("/other/file.txt".into())));
    }

    #[test]
    fn test_plugin_context_json() {
        let ctx = PluginContext::new("/path/to/file", "dataset1", "write")
            .with_size(1024)
            .with_metadata("key", "value");

        let json = ctx.to_json();
        assert!(json.contains("\"path\":\"/path/to/file\""));
        assert!(json.contains("\"size\":1024"));
        assert!(json.contains("\"dataset\":\"dataset1\""));
        assert!(json.contains("\"operation\":\"write\""));
        assert!(json.contains("\"key\":\"value\""));
    }

    #[test]
    fn test_plugin_limits_default() {
        let limits = PluginLimits::default();
        assert_eq!(limits.max_memory, 16 * 1024 * 1024);
        assert_eq!(limits.max_execution_ms, 1000);
        assert_eq!(limits.max_output_size, 64 * 1024 * 1024);
    }

    #[test]
    fn test_escape_json() {
        assert_eq!(escape_json("hello"), "hello");
        assert_eq!(escape_json("hello\"world"), "hello\\\"world");
        assert_eq!(escape_json("line1\nline2"), "line1\\nline2");
        assert_eq!(escape_json("path\\to\\file"), "path\\\\to\\\\file");
    }
}