pasta_lua 0.2.2

Pasta Lua - Lua integration for Pasta DSL
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
//! Persistence module for Lua.
//!
//! Provides the `@pasta_persistence` module with functions to load and save
//! persistent data to files with optional gzip compression (obfuscation).
//!
//! # Example
//! ```lua
//! local persistence = require "@pasta_persistence"
//!
//! -- Load data (returns empty table if file not found)
//! local data = persistence.load()
//!
//! -- Modify data
//! data.player_name = "Alice"
//! data.play_count = 42
//!
//! -- Save data (explicit save)
//! local ok, err = persistence.save(data)
//! if not ok then
//!     print("Save failed:", err)
//! end
//! ```

use crate::loader::PersistenceConfig;
use flate2::Compression;
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use mlua::{Lua, LuaSerdeExt, Result as LuaResult, Table, Value};
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};
use thiserror::Error;

/// Module version.
const VERSION: &str = "0.1.0";

/// Module description.
const DESCRIPTION: &str = "Persistent data storage (JSON/gzip)";

/// Gzip magic header bytes.
const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b];

/// Persistence error types.
#[derive(Debug, Error)]
pub enum PersistenceError {
    /// IO error during file operations.
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),

    /// JSON serialization/deserialization error.
    #[error("JSON error: {0}")]
    JsonError(#[from] serde_json::Error),

    /// Lua value conversion error.
    #[error("Lua conversion error: {0}")]
    LuaConversionError(String),

    /// Configuration not found.
    #[error("Persistence configuration not found")]
    ConfigNotFound,

    /// Lua VM access error.
    #[error("Lua VM access error: {0}")]
    LuaAccessError(String),

    /// Invalid file format.
    #[error("Invalid file format: {0}")]
    InvalidFormat(String),
}

impl From<mlua::Error> for PersistenceError {
    fn from(e: mlua::Error) -> Self {
        PersistenceError::LuaConversionError(e.to_string())
    }
}

/// Internal state for the persistence module.
/// Stored as upvalue in Lua closures.
#[derive(Debug, Clone)]
struct PersistenceState {
    /// Absolute path to the persistence file.
    file_path: PathBuf,
    /// Whether to use gzip compression (obfuscation).
    obfuscate: bool,
    /// Enable debug logging.
    debug_mode: bool,
}

/// Register the @pasta_persistence module with the Lua state.
///
/// Creates a module table with:
/// - `_VERSION` - Module version string
/// - `_DESCRIPTION` - Module description
/// - `load()` - Load data from persistence file
/// - `save(data)` - Save data to persistence file
///
/// # Arguments
/// * `lua` - The Lua state to register the module with
/// * `config` - Persistence configuration
/// * `base_dir` - Base directory for resolving relative paths
///
/// # Returns
/// * `Ok(Table)` - The module table
/// * `Err(e)` - Registration failed
pub fn register(lua: &Lua, config: &PersistenceConfig, base_dir: &Path) -> LuaResult<Table> {
    let module = lua.create_table()?;

    // Set module metadata
    module.set("_VERSION", VERSION)?;
    module.set("_DESCRIPTION", DESCRIPTION)?;

    // Validate file path to prevent directory traversal
    let effective_path = config.effective_file_path();
    let relative = Path::new(&effective_path);
    if relative.is_absolute()
        || relative.components().any(|c| {
            matches!(
                c,
                Component::ParentDir | Component::RootDir | Component::Prefix(_)
            )
        })
    {
        return Err(mlua::Error::RuntimeError(format!(
            "Invalid persistence file path (directory traversal detected): {}",
            effective_path
        )));
    }

    // Create state for closures
    let file_path = base_dir.join(&effective_path);
    let state = PersistenceState {
        file_path: file_path.clone(),
        obfuscate: config.obfuscate,
        debug_mode: config.debug_mode,
    };

    if config.debug_mode {
        tracing::debug!(
            path = %file_path.display(),
            obfuscate = config.obfuscate,
            "Persistence module initialized"
        );
    }

    // Register load function
    let load_state = state.clone();
    module.set(
        "load",
        lua.create_function(move |lua, ()| load_impl(lua, &load_state))?,
    )?;

    // Register save function
    let save_state = state;
    module.set(
        "save",
        lua.create_function(move |lua, data: Table| save_impl(lua, &save_state, data))?,
    )?;

    Ok(module)
}

/// Implementation of `persistence.load()`.
///
/// Loads data from the persistence file.
/// Returns empty table if file doesn't exist or is corrupted.
fn load_impl(lua: &Lua, state: &PersistenceState) -> LuaResult<Table> {
    match load_from_file(&state.file_path) {
        Ok(value) => {
            if state.debug_mode {
                tracing::debug!(path = %state.file_path.display(), "Loaded persistence data");
            }
            // Convert serde_json::Value to Lua Value, then extract table
            let lua_value: Value = lua.to_value(&value)?;
            match lua_value {
                Value::Table(t) => Ok(t),
                _ => {
                    tracing::warn!(
                        path = %state.file_path.display(),
                        "Persistence data is not an object, using empty table"
                    );
                    lua.create_table()
                }
            }
        }
        Err(PersistenceError::IoError(ref e)) if e.kind() == std::io::ErrorKind::NotFound => {
            // File not found is expected on first run
            tracing::warn!(path = %state.file_path.display(), "Persistence file not found, using empty table");
            lua.create_table()
        }
        Err(e) => {
            // Other errors: log warning and return empty table
            tracing::warn!(error = %e, path = %state.file_path.display(), "Failed to load persistence data, using empty table");
            lua.create_table()
        }
    }
}

/// Implementation of `persistence.save(data)`.
///
/// Saves data to the persistence file.
/// Returns (true, nil) on success, (nil, error_message) on error.
fn save_impl(
    lua: &Lua,
    state: &PersistenceState,
    data: Table,
) -> LuaResult<(Option<bool>, Option<String>)> {
    // Convert Lua table to serde_json::Value
    let lua_value = Value::Table(data);
    let json_value: serde_json::Value = match lua.from_value(lua_value) {
        Ok(v) => v,
        Err(e) => {
            let err_msg = format!("Failed to convert Lua value: {}", e);
            tracing::warn!(error = %err_msg, "Persistence save conversion error");
            return Ok((None, Some(err_msg)));
        }
    };

    // Save to file
    match save_to_file(&json_value, &state.file_path, state.obfuscate) {
        Ok(()) => {
            if state.debug_mode {
                tracing::debug!(path = %state.file_path.display(), "Saved persistence data");
            }
            Ok((Some(true), None))
        }
        Err(e) => {
            let err_msg = format!("Failed to save: {}", e);
            tracing::error!(error = %err_msg, path = %state.file_path.display(), "Persistence save error");
            Ok((None, Some(err_msg)))
        }
    }
}

/// Load data from a persistence file.
///
/// Automatically detects format (JSON or gzip) based on file content.
///
/// # Arguments
/// * `path` - Path to the persistence file
///
/// # Returns
/// * `Ok(Value)` - Loaded JSON value
/// * `Err(e)` - Load failed
pub fn load_from_file(path: &Path) -> Result<serde_json::Value, PersistenceError> {
    let data = fs::read(path)?;

    if data.is_empty() {
        return Ok(serde_json::Value::Object(serde_json::Map::new()));
    }

    // Detect format by magic header
    if data.len() >= 2 && data[0] == GZIP_MAGIC[0] && data[1] == GZIP_MAGIC[1] {
        // Gzip compressed
        let mut decoder = GzDecoder::new(&data[..]);
        let mut json_bytes = Vec::new();
        decoder.read_to_end(&mut json_bytes)?;
        Ok(serde_json::from_slice(&json_bytes)?)
    } else {
        // Plain JSON
        Ok(serde_json::from_slice(&data)?)
    }
}

/// Save data to a persistence file.
///
/// Uses atomic write (temp file + rename) to prevent corruption.
///
/// # Arguments
/// * `data` - JSON value to save
/// * `path` - Path to the persistence file
/// * `obfuscate` - Whether to use gzip compression
///
/// # Returns
/// * `Ok(())` - Save successful
/// * `Err(e)` - Save failed
pub fn save_to_file(
    data: &serde_json::Value,
    path: &Path,
    obfuscate: bool,
) -> Result<(), PersistenceError> {
    // Ensure parent directory exists
    if let Some(parent) = path.parent()
        && !parent.exists()
    {
        fs::create_dir_all(parent)?;
        tracing::debug!(path = %parent.display(), "Created persistence directory");
    }

    // Serialize data
    let bytes = if obfuscate {
        // Gzip compressed
        let json_bytes = serde_json::to_vec(data)?;
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(&json_bytes)?;
        encoder.finish()?
    } else {
        // Pretty-printed JSON
        serde_json::to_vec_pretty(data)?
    };

    // Atomic write: write to temp file, then rename
    let temp_path = path.with_extension("tmp");

    // Write to temp file
    let mut file = File::create(&temp_path)?;
    file.write_all(&bytes)?;
    file.sync_all()?;
    drop(file);

    // Rename to final path
    if let Err(e) = fs::rename(&temp_path, path) {
        // Cleanup temp file on failure
        let _ = fs::remove_file(&temp_path);
        return Err(PersistenceError::IoError(e));
    }

    Ok(())
}

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

    fn create_test_config(temp_dir: &TempDir, obfuscate: bool) -> (PersistenceConfig, PathBuf) {
        let file_name = if obfuscate { "save.dat" } else { "save.json" };
        let config = PersistenceConfig {
            obfuscate,
            file_path: file_name.to_string(),
            debug_mode: true,
        };
        let base_dir = temp_dir.path().to_path_buf();
        (config, base_dir)
    }

    #[test]
    fn test_save_load_json() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("save.json");

        let data = serde_json::json!({
            "player_name": "Alice",
            "play_count": 42,
            "flags": {
                "tutorial_complete": true
            }
        });

        // Save
        save_to_file(&data, &file_path, false).unwrap();

        // Load
        let loaded = load_from_file(&file_path).unwrap();
        assert_eq!(loaded, data);
    }

    #[test]
    fn test_save_load_obfuscated() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("save.dat");

        let data = serde_json::json!({
            "player_name": "Bob",
            "inventory": ["sword", "shield"]
        });

        // Save with obfuscation
        save_to_file(&data, &file_path, true).unwrap();

        // Verify file starts with gzip magic
        let raw = fs::read(&file_path).unwrap();
        assert!(raw.len() >= 2);
        assert_eq!(raw[0], GZIP_MAGIC[0]);
        assert_eq!(raw[1], GZIP_MAGIC[1]);

        // Load
        let loaded = load_from_file(&file_path).unwrap();
        assert_eq!(loaded, data);
    }

    #[test]
    fn test_load_nonexistent_returns_error() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("nonexistent.json");

        let result = load_from_file(&file_path);
        assert!(matches!(result, Err(PersistenceError::IoError(_))));
    }

    #[test]
    fn test_load_corrupted_returns_error() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("corrupted.json");

        // Write invalid JSON
        fs::write(&file_path, "{ invalid json }").unwrap();

        let result = load_from_file(&file_path);
        assert!(matches!(result, Err(PersistenceError::JsonError(_))));
    }

    #[test]
    fn test_auto_detect_format() {
        let temp_dir = TempDir::new().unwrap();

        let data = serde_json::json!({"key": "value"});

        // Save as JSON
        let json_path = temp_dir.path().join("test.json");
        save_to_file(&data, &json_path, false).unwrap();

        // Save as gzip
        let gzip_path = temp_dir.path().join("test.dat");
        save_to_file(&data, &gzip_path, true).unwrap();

        // Both should load correctly
        let loaded_json = load_from_file(&json_path).unwrap();
        let loaded_gzip = load_from_file(&gzip_path).unwrap();

        assert_eq!(loaded_json, data);
        assert_eq!(loaded_gzip, data);
    }

    #[test]
    fn test_atomic_write_creates_directory() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir
            .path()
            .join("subdir")
            .join("nested")
            .join("save.json");

        let data = serde_json::json!({"test": true});

        // Should create directories automatically
        save_to_file(&data, &file_path, false).unwrap();

        assert!(file_path.exists());
        let loaded = load_from_file(&file_path).unwrap();
        assert_eq!(loaded, data);
    }

    #[test]
    fn test_nested_table_serialization() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("nested.json");

        let data = serde_json::json!({
            "level1": {
                "level2": {
                    "level3": {
                        "value": 123,
                        "array": [1, 2, 3],
                        "bool": true,
                        "string": "nested"
                    }
                }
            }
        });

        save_to_file(&data, &file_path, false).unwrap();
        let loaded = load_from_file(&file_path).unwrap();
        assert_eq!(loaded, data);
    }

    #[test]
    fn test_empty_file_returns_empty_object() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("empty.json");

        // Create empty file
        fs::write(&file_path, "").unwrap();

        let loaded = load_from_file(&file_path).unwrap();
        assert_eq!(loaded, serde_json::json!({}));
    }

    #[test]
    fn test_lua_module_load() {
        let temp_dir = TempDir::new().unwrap();
        let (config, base_dir) = create_test_config(&temp_dir, false);

        let lua = Lua::new();
        let module = register(&lua, &config, &base_dir).unwrap();

        // Load should return empty table when file doesn't exist
        let load_fn: mlua::Function = module.get("load").unwrap();
        let result: Table = load_fn.call(()).unwrap();

        // Should be an empty table
        assert_eq!(result.len().unwrap(), 0);
    }

    #[test]
    fn test_lua_module_save_and_load() {
        let temp_dir = TempDir::new().unwrap();
        let (config, base_dir) = create_test_config(&temp_dir, false);

        let lua = Lua::new();
        let module = register(&lua, &config, &base_dir).unwrap();

        // Create test data
        let data: Table = lua.create_table().unwrap();
        data.set("name", "Test").unwrap();
        data.set("count", 42).unwrap();

        // Save
        let save_fn: mlua::Function = module.get("save").unwrap();
        let (ok, err): (Option<bool>, Option<String>) = save_fn.call(data.clone()).unwrap();
        assert_eq!(ok, Some(true));
        assert!(err.is_none());

        // Load
        let load_fn: mlua::Function = module.get("load").unwrap();
        let result: Table = load_fn.call(()).unwrap();

        // Verify data
        let name: String = result.get("name").unwrap();
        let count: i32 = result.get("count").unwrap();
        assert_eq!(name, "Test");
        assert_eq!(count, 42);
    }

    #[test]
    fn test_register_rejects_directory_traversal() {
        let temp_dir = TempDir::new().unwrap();
        let base_dir = temp_dir.path().to_path_buf();

        let config = PersistenceConfig {
            obfuscate: false,
            file_path: "../../etc/malicious.json".to_string(),
            debug_mode: false,
        };

        let lua = Lua::new();
        let result = register(&lua, &config, &base_dir);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("directory traversal"),
            "Expected traversal error, got: {}",
            err_msg
        );
    }

    #[test]
    fn test_register_rejects_rooted_path() {
        let temp_dir = TempDir::new().unwrap();
        let base_dir = temp_dir.path().to_path_buf();

        // "/" prefix has RootDir component on all platforms
        let config = PersistenceConfig {
            obfuscate: false,
            file_path: "/etc/passwd".to_string(),
            debug_mode: false,
        };

        let lua = Lua::new();
        let result = register(&lua, &config, &base_dir);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("directory traversal"),
            "Expected traversal error, got: {}",
            err_msg
        );
    }
}