sdkt-storage 2.7.0

Storage monitoring utility and TTL extensions logic for Soroban contracts.
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
//! File-system based WASM metadata cache.
//!
//! Stores parsed `WasmMetadata` and raw `.wasm` binaries locally to
//! avoid repeated RPC fetches for immutable contract code.

use crate::error::StorageError;
use directories::ProjectDirs;
use sdkt_wasm::WasmMetadata;
use std::fs;
use std::path::{Component, Path, PathBuf};

/// Info about the current state of the WASM cache for a specific network.
#[derive(Debug, Clone, PartialEq)]
pub struct CacheInfo {
    pub network: String,
    pub entry_count: usize,
    pub total_metadata_size_bytes: u64,
    pub total_wasm_size_bytes: u64,
}

/// A local file-system cache for Soroban WASM metadata and binaries.
pub struct WasmCache {
    base_dir: PathBuf,
}

impl WasmCache {
    /// Creates a new `WasmCache` instance.
    ///
    /// The directory location can be overridden via the `SDKT_CACHE_DIR` environment
    /// variable (checked first). If unset or empty, uses the standard OS cache directory:
    /// - Linux: `~/.cache/soroban-devkit/`
    /// - macOS: `~/Library/Caches/org.SaboLabs.soroban-devkit/`
    /// - Windows: `%LOCALAPPDATA%\SaboLabs\soroban-devkit\cache\`
    pub fn new() -> Result<Self, StorageError> {
        if let Ok(dir) = std::env::var("SDKT_CACHE_DIR") {
            let trimmed = dir.trim();
            if !trimmed.is_empty() {
                return Ok(Self {
                    base_dir: PathBuf::from(trimmed),
                });
            }
        }

        let proj_dirs =
            ProjectDirs::from("org", "SaboLabs", "soroban-devkit").ok_or_else(|| {
                StorageError::Io(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "Could not determine OS cache directory",
                ))
            })?;

        let base_dir = proj_dirs.cache_dir().to_path_buf();
        Ok(Self { base_dir })
    }

    /// Returns the base directory of the cache.
    pub fn base_dir(&self) -> &Path {
        &self.base_dir
    }

    /// Creates a cache instance targeting a specific directory (useful for testing).
    pub fn with_dir<P: AsRef<Path>>(path: P) -> Self {
        Self {
            base_dir: path.as_ref().to_path_buf(),
        }
    }

    /// Returns the directory for a specific network (e.g., `testnet`).
    /// Creates the directory if it doesn't exist.
    fn network_dir(&self, network: &str) -> Result<PathBuf, StorageError> {
        validate_network_name(network)?;
        let net_dir = self.base_dir.join("wasm").join(network);
        if !net_dir.exists() {
            fs::create_dir_all(&net_dir).map_err(StorageError::Io)?;
        }
        Ok(net_dir)
    }

    /// Returns `true` if metadata for the `wasm_hash` exists in the given `network`.
    pub fn contains(&self, network: &str, wasm_hash: &str) -> Result<bool, StorageError> {
        let net_dir = self.network_dir(network)?;
        let meta_path = net_dir.join(format!("{}.json", wasm_hash));
        Ok(meta_path.exists())
    }

    /// Retrieves parsed metadata from the cache.
    ///
    /// # Errors
    /// Returns `StorageError::CorruptCache` if the JSON is malformed.
    pub fn get(
        &self,
        network: &str,
        wasm_hash: &str,
    ) -> Result<Option<WasmMetadata>, StorageError> {
        let net_dir = self.network_dir(network)?;
        let meta_path = net_dir.join(format!("{}.json", wasm_hash));

        if !meta_path.exists() {
            return Ok(None);
        }

        let json = fs::read_to_string(&meta_path).map_err(StorageError::Io)?;
        let metadata: WasmMetadata = serde_json::from_str(&json).map_err(|e| {
            StorageError::CorruptCache(format!("Malformed JSON for {}: {}", wasm_hash, e))
        })?;

        Ok(Some(metadata))
    }

    /// Writes both metadata and raw WASM to the cache using atomic tempfile renaming.
    pub fn put(
        &self,
        network: &str,
        metadata: &WasmMetadata,
        wasm_bytes: &[u8],
    ) -> Result<(), StorageError> {
        let net_dir = self.network_dir(network)?;
        let hash = &metadata.hash;

        let meta_path = net_dir.join(format!("{}.json", hash));
        let wasm_path = net_dir.join(format!("{}.wasm", hash));

        let meta_temp = net_dir.join(format!("{}.json.tmp", hash));
        let wasm_temp = net_dir.join(format!("{}.wasm.tmp", hash));

        // Serialize JSON to string
        let json = serde_json::to_string(metadata)
            .map_err(|e| StorageError::Parse(format!("Failed to serialize metadata: {}", e)))?;

        // Write to temporary files first to prevent corruption
        fs::write(&meta_temp, json).map_err(StorageError::Io)?;
        fs::write(&wasm_temp, wasm_bytes).map_err(StorageError::Io)?;

        // Atomic rename
        fs::rename(&meta_temp, &meta_path).map_err(StorageError::Io)?;
        fs::rename(&wasm_temp, &wasm_path).map_err(StorageError::Io)?;

        Ok(())
    }

    /// Removes a specific WASM entry (both JSON and `.wasm`) from the cache.
    ///
    /// A hash that is not cached is an error, not a silent success: callers
    /// print "Removed" on `Ok`, and reporting success for a no-op reads as a
    /// completed mutation to scripts and agents. Matches `identity delete` and
    /// `network remove`, which surface `Not found:` and exit non-zero.
    pub fn remove(&self, network: &str, wasm_hash: &str) -> Result<(), StorageError> {
        let net_dir = self.network_dir(network)?;
        let meta_path = net_dir.join(format!("{}.json", wasm_hash));
        let wasm_path = net_dir.join(format!("{}.wasm", wasm_hash));

        if !meta_path.exists() && !wasm_path.exists() {
            return Err(StorageError::NotFound(format!(
                "WASM cache entry '{}' not found in {} cache",
                wasm_hash, network
            )));
        }

        if meta_path.exists() {
            fs::remove_file(meta_path).map_err(StorageError::Io)?;
        }
        if wasm_path.exists() {
            fs::remove_file(wasm_path).map_err(StorageError::Io)?;
        }

        Ok(())
    }

    /// Clears all cached WASM entries for a specific network.
    ///
    /// Unlike `remove`, this stays truthful as a no-op success: "cleared" is
    /// accurate for an empty cache (the post-condition holds), and unlike a
    /// hash miss it is not evidence that a named target was deleted.
    pub fn clear(&self, network: &str) -> Result<(), StorageError> {
        let net_dir = self.network_dir(network)?;
        if net_dir.exists() {
            fs::remove_dir_all(&net_dir).map_err(StorageError::Io)?;
            fs::create_dir_all(&net_dir).map_err(StorageError::Io)?;
        }
        Ok(())
    }

    /// Retrieves usage statistics for a specific network.
    /// A missing or unreadable cache directory is treated as an empty cache
    /// (zero entries / zero size) on every platform. This keeps `cache info`
    /// working on fresh CI runners (Linux/macOS/Windows) where the cache path
    /// does not yet exist.
    pub fn cache_info(&self, network: &str) -> Result<CacheInfo, StorageError> {
        validate_network_name(network)?;
        let net_dir = self.base_dir.join("wasm").join(network);

        let mut entry_count = 0;
        let mut total_metadata_size_bytes = 0;
        let mut total_wasm_size_bytes = 0;

        // A missing or unreadable directory is an empty cache, not an error.
        // Swallowing the error (instead of `.map_err`) prevents ENOENT from
        // propagating on platforms where the path is absent or a symlink
        // target is missing (e.g. a fresh macOS runner).
        if let Ok(entries) = fs::read_dir(&net_dir) {
            for entry in entries {
                let entry = match entry {
                    Ok(e) => e,
                    Err(_) => continue,
                };
                let meta = match entry.metadata() {
                    Ok(m) => m,
                    Err(_) => continue,
                };
                let name = entry.file_name().to_string_lossy().to_string();

                if name.ends_with(".json") {
                    entry_count += 1; // Count by JSON files
                    total_metadata_size_bytes += meta.len();
                } else if name.ends_with(".wasm") {
                    total_wasm_size_bytes += meta.len();
                }
            }
        }

        Ok(CacheInfo {
            network: network.to_string(),
            entry_count,
            total_metadata_size_bytes,
            total_wasm_size_bytes,
        })
    }
}

fn validate_network_name(network: &str) -> Result<(), StorageError> {
    if network.is_empty()
        || network == "."
        || network == ".."
        || network.contains('/')
        || network.contains('\\')
        || !matches!(
            Path::new(network).components().next(),
            Some(Component::Normal(_))
        )
        || Path::new(network).components().nth(1).is_some()
    {
        return Err(StorageError::ConfigError(format!(
            "invalid network name '{}': must be a non-empty path component",
            network
        )));
    }
    Ok(())
}

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

    fn get_temp_cache() -> (WasmCache, TempDir) {
        let tmp_dir = TempDir::new().unwrap();
        let cache = WasmCache::with_dir(tmp_dir.path());
        (cache, tmp_dir)
    }

    fn dummy_metadata(hash: &str) -> WasmMetadata {
        WasmMetadata {
            hash: hash.to_string(),
            size_bytes: 10,
            version: 1,
            exports: vec![],
            imports: vec![],
            custom_sections: vec![],
            contract_meta: vec![],
            function_count: 0,
            memory: None,
            table_count: 0,
            global_count: 0,
            data_segment_count: 0,
        }
    }

    #[test]
    fn test_put_get_contains() {
        let (cache, _dir) = get_temp_cache();
        let network = "testnet";
        let hash = "abcd123";

        assert!(!cache.contains(network, hash).unwrap());
        assert!(cache.get(network, hash).unwrap().is_none());

        let meta = dummy_metadata(hash);
        cache.put(network, &meta, b"1234567890").unwrap();

        assert!(cache.contains(network, hash).unwrap());
        let retrieved = cache.get(network, hash).unwrap().unwrap();
        assert_eq!(retrieved.hash, hash);
    }

    #[test]
    fn test_remove() {
        let (cache, _dir) = get_temp_cache();
        let meta = dummy_metadata("test_hash");

        cache.put("mainnet", &meta, b"xyz").unwrap();
        assert!(cache.contains("mainnet", "test_hash").unwrap());

        cache.remove("mainnet", "test_hash").unwrap();
        assert!(!cache.contains("mainnet", "test_hash").unwrap());

        // ensure files are physically gone
        let info = cache.cache_info("mainnet").unwrap();
        assert_eq!(info.entry_count, 0);
        assert_eq!(info.total_metadata_size_bytes, 0);
        assert_eq!(info.total_wasm_size_bytes, 0);
    }

    #[test]
    fn test_remove_missing_is_not_found_error() {
        // A no-op removal must not report success: callers print "Removed" on
        // Ok, and scripts/agents read that as a completed mutation.
        let (cache, _dir) = get_temp_cache();
        let err = cache
            .remove("mainnet", "never_cached")
            .expect_err("removing an absent entry must fail");
        assert!(
            matches!(&err, StorageError::NotFound(m) if m.contains("never_cached")),
            "expected NotFound, got {err:?}"
        );
    }

    #[test]
    fn test_clear() {
        let (cache, _dir) = get_temp_cache();

        cache.put("testnet", &dummy_metadata("1"), b"").unwrap();
        cache.put("testnet", &dummy_metadata("2"), b"").unwrap();
        cache.put("mainnet", &dummy_metadata("3"), b"").unwrap();

        assert_eq!(cache.cache_info("testnet").unwrap().entry_count, 2);

        cache.clear("testnet").unwrap();

        assert_eq!(cache.cache_info("testnet").unwrap().entry_count, 0);
        assert_eq!(cache.cache_info("mainnet").unwrap().entry_count, 1);
    }

    #[test]
    fn test_corrupt_json() {
        let (cache, _dir) = get_temp_cache();
        let network = "testnet";
        let hash = "corrupt";

        // Create network dir and write garbage to the JSON file
        let net_dir = cache.network_dir(network).unwrap();
        fs::write(net_dir.join(format!("{}.json", hash)), b"{ invalid_json").unwrap();

        let err = cache.get(network, hash).unwrap_err();
        assert!(matches!(err, StorageError::CorruptCache(_)));
    }

    #[test]
    fn test_missing_cache_dir_is_empty() {
        // Simulate a fresh runner where the cache base dir does not exist yet
        // (the macOS CI failure scenario). cache_info must succeed with zero
        // counts instead of returning ENOENT.
        let tmp = TempDir::new().unwrap();
        // Point at a sub-path that does NOT exist.
        let cache = WasmCache::with_dir(tmp.path().join("does-not-exist-yet"));

        let info = cache.cache_info("testnet").unwrap();
        assert_eq!(info.entry_count, 0);
        assert_eq!(info.total_metadata_size_bytes, 0);
        assert_eq!(info.total_wasm_size_bytes, 0);
        assert_eq!(info.network, "testnet");
    }

    #[test]
    fn test_cache_info_empty_network_dir() {
        // Base dir exists but the per-network subdir does not.
        let (cache, _dir) = get_temp_cache();
        let info = cache.cache_info("nonexistent-network").unwrap();
        assert_eq!(info.entry_count, 0);
    }

    #[test]
    fn rejects_path_traversal_before_filesystem_access() {
        let (cache, dir) = get_temp_cache();
        let outside = dir.path().join("outside");
        fs::create_dir_all(&outside).unwrap();

        assert!(matches!(
            cache.clear("../outside"),
            Err(StorageError::ConfigError(_))
        ));
        assert!(outside.exists());
        assert!(matches!(
            cache.remove("nested/name", "hash"),
            Err(StorageError::ConfigError(_))
        ));
        assert!(matches!(
            cache.cache_info(""),
            Err(StorageError::ConfigError(_))
        ));
    }

    #[cfg(windows)]
    #[test]
    fn rejects_drive_relative_network_name() {
        let (cache, _dir) = get_temp_cache();

        assert!(matches!(
            cache.clear("C:outside"),
            Err(StorageError::ConfigError(_))
        ));
    }

    // ---------------------------------------------------------------------------
    // Windows-specific regression tests
    // ---------------------------------------------------------------------------

    /// Verifies the production WasmCache::new() constructor resolves a
    /// platform-appropriate cache directory on Windows.
    ///
    /// The test is read-only against the production constructor: it does not
    /// write any cache data. It only verifies the resolved base directory
    /// contains the expected OS-managed namespace.
    #[cfg(windows)]
    #[test]
    fn test_new_resolves_windows_cache_path() {
        let cache = WasmCache::new().expect("WasmCache::new() must succeed on Windows");

        // Windows: %LOCALAPPDATA%\SaboLabs\soroban-devkit\cache\
        // We do not assert an absolute path (OS-managed); only the namespace.
        let path_str = cache.base_dir.to_string_lossy().to_lowercase();
        assert!(
            path_str.contains("sabolabs"),
            "Windows cache path should contain the 'SaboLabs' namespace, got: {}",
            cache.base_dir.display()
        );
        assert!(
            path_str.contains("soroban-devkit"),
            "Windows cache path should contain the 'soroban-devkit' app name, got: {}",
            cache.base_dir.display()
        );
    }

    #[test]
    fn test_new_with_env_var_override() {
        let tmp = TempDir::new().unwrap();
        let key = "SDKT_CACHE_DIR";
        let prev = std::env::var_os(key);
        std::env::set_var(key, tmp.path());

        let cache = WasmCache::new().expect("WasmCache::new() with SDKT_CACHE_DIR");
        assert_eq!(cache.base_dir(), tmp.path());

        if let Some(p) = prev {
            std::env::set_var(key, p);
        } else {
            std::env::remove_var(key);
        }
    }
}