const std = @import("std"); const types = @import("types.zig"); pub const validation_cache_dir = ".zig-cache/wasm-module-cache"; pub const validation_cache_schema_version: u32 = 1; const ValidationCacheEntry = struct { schema_version: u32, backend: []const u8, module_hash_hex: []const u8, validation: types.ModuleValidation, }; pub const ModuleBytesLoad = struct { bytes: []const u8, state: types.ModuleBytesCacheState, }; pub const CachedValidationLoad = struct { validation: ?types.ModuleValidation, state: types.ValidationCacheState, }; const BytesCacheEntry = struct { mtime_ns: i128, size: u64, bytes: []u8, }; var bytes_cache_mutex: std.Thread.Mutex = .{}; var bytes_cache: std.StringHashMapUnmanaged(BytesCacheEntry) = .empty; pub fn deinitModuleCaches(allocator: std.mem.Allocator) void { bytes_cache_mutex.lock(); defer bytes_cache_mutex.unlock(); var iter = bytes_cache.iterator(); while (iter.next()) |entry| { allocator.free(entry.key_ptr.*); allocator.free(entry.value_ptr.bytes); } bytes_cache.deinit(allocator); bytes_cache = .empty; } pub fn loadModuleBytes(allocator: std.mem.Allocator, wasm_path: []const u8) ![]const u8 { return (try loadModuleBytesDetailed(allocator, wasm_path)).bytes; } pub fn loadModuleBytesDetailed(allocator: std.mem.Allocator, wasm_path: []const u8) !ModuleBytesLoad { const stat = try std.fs.cwd().statFile(wasm_path); bytes_cache_mutex.lock(); defer bytes_cache_mutex.unlock(); if (bytes_cache.getPtr(wasm_path)) |entry| { if (entry.mtime_ns == stat.mtime and entry.size == stat.size) { return .{ .bytes = entry.bytes, .state = .hit, }; } allocator.free(entry.bytes); entry.bytes = try std.fs.cwd().readFileAlloc(allocator, wasm_path, 8 * 1024 * 1024); entry.mtime_ns = stat.mtime; entry.size = stat.size; return .{ .bytes = entry.bytes, .state = .reloaded, }; } const owned_path = try allocator.dupe(u8, wasm_path); errdefer allocator.free(owned_path); const bytes = try std.fs.cwd().readFileAlloc(allocator, wasm_path, 8 * 1024 * 1024); errdefer allocator.free(bytes); try bytes_cache.put(allocator, owned_path, .{ .mtime_ns = stat.mtime, .size = stat.size, .bytes = bytes, }); return .{ .bytes = bytes_cache.getPtr(wasm_path).?.bytes, .state = .miss, }; } pub fn storeCachedValidation( allocator: std.mem.Allocator, backend: types.Backend, hash_hex: [64]u8, validation: types.ModuleValidation, ) !void { try std.fs.cwd().makePath(validation_cache_dir); const path = try validationCachePath(allocator, backend, hash_hex); defer allocator.free(path); const file = try std.fs.cwd().createFile(path, .{ .truncate = true }); defer file.close(); var buffer: [512]u8 = undefined; var writer = file.writer(&buffer); const entry = ValidationCacheEntry{ .schema_version = validation_cache_schema_version, .backend = backendPrefix(backend), .module_hash_hex = hash_hex[0..], .validation = validation, }; try std.json.Stringify.value(entry, .{}, &writer.interface); try writer.interface.flush(); } pub fn loadCachedValidation( allocator: std.mem.Allocator, backend: types.Backend, hash_hex: [64]u8, ) anyerror!CachedValidationLoad { const path = try validationCachePath(allocator, backend, hash_hex); defer allocator.free(path); const content = std.fs.cwd().readFileAlloc(allocator, path, 4096) catch |err| switch (err) { error.FileNotFound => return .{ .validation = null, .state = .miss, }, else => return err, }; defer allocator.free(content); const parsed = std.json.parseFromSlice(ValidationCacheEntry, allocator, content, .{}) catch { std.fs.cwd().deleteFile(path) catch {}; return .{ .validation = null, .state = .stale, }; }; defer parsed.deinit(); const entry = parsed.value; if (entry.schema_version != validation_cache_schema_version or !std.mem.eql(u8, entry.backend, backendPrefix(backend)) or !std.mem.eql(u8, entry.module_hash_hex, hash_hex[0..]) or !types.isSupportedValidation(entry.validation)) { std.fs.cwd().deleteFile(path) catch {}; return .{ .validation = null, .state = .stale, }; } return .{ .validation = entry.validation, .state = .hit, }; } pub fn validationCachePath(allocator: std.mem.Allocator, backend: types.Backend, hash_hex: [64]u8) ![]u8 { return try std.fmt.allocPrint(allocator, "{s}/v{d}-{s}-{s}.json", .{ validation_cache_dir, validation_cache_schema_version, backendPrefix(backend), hash_hex, }); } pub fn hashHex(bytes: []const u8) [64]u8 { var digest: [32]u8 = undefined; std.crypto.hash.Blake3.hash(bytes, &digest, .{}); var out: [64]u8 = undefined; const alphabet = "0123456789abcdef"; for (digest, 0..) |byte, index| { out[index * 2] = alphabet[byte >> 4]; out[index * 2 + 1] = alphabet[byte & 0x0F]; } return out; } fn backendPrefix(backend: types.Backend) []const u8 { return switch (backend) { .wamr => "wamr", .wasm3 => "wasm3", }; } fn resetModuleBytesCacheForTests() void { deinitModuleCaches(std.testing.allocator); } test "validation cache path uses schema version backend and hash" { const path = try validationCachePath(std.testing.allocator, .wamr, [_]u8{'a'} ** 64); defer std.testing.allocator.free(path); try std.testing.expect(std.mem.indexOf(u8, path, "v1-wamr-") != null); try std.testing.expect(std.mem.endsWith(u8, path, ".json")); } test "module bytes cache reloads file after mtime change" { resetModuleBytesCacheForTests(); defer resetModuleBytesCacheForTests(); var tmp_dir = std.testing.tmpDir(.{}); defer tmp_dir.cleanup(); try tmp_dir.dir.writeFile(.{ .sub_path = "scenario.wasm", .data = "one", }); const path = try std.fmt.allocPrint(std.testing.allocator, ".zig-cache/tmp/{s}/scenario.wasm", .{tmp_dir.sub_path}); defer std.testing.allocator.free(path); const first = try loadModuleBytesDetailed(std.testing.allocator, path); try std.testing.expectEqual(types.ModuleBytesCacheState.miss, first.state); try std.testing.expectEqualStrings("one", first.bytes); const second = try loadModuleBytesDetailed(std.testing.allocator, path); try std.testing.expectEqual(types.ModuleBytesCacheState.hit, second.state); try std.testing.expectEqualStrings("one", second.bytes); std.Thread.sleep(2 * std.time.ns_per_ms); try tmp_dir.dir.writeFile(.{ .sub_path = "scenario.wasm", .data = "two", }); const third = try loadModuleBytesDetailed(std.testing.allocator, path); try std.testing.expectEqual(types.ModuleBytesCacheState.reloaded, third.state); try std.testing.expectEqualStrings("two", third.bytes); } test "validation cache round trips via exact path lookup" { const hash_hex = [_]u8{'b'} ** 64; const cache_path = try validationCachePath(std.testing.allocator, .wamr, hash_hex); defer std.testing.allocator.free(cache_path); std.fs.cwd().deleteFile(cache_path) catch {}; defer std.fs.cwd().deleteFile(cache_path) catch {}; const validation = types.ModuleValidation{ .abi_version = types.expected_workflow_abi_version, .has_init = true, .has_start_iteration = true, .has_next_request = true, .has_handle_response = true, .has_setup = false, .has_teardown = false, }; try storeCachedValidation(std.testing.allocator, .wamr, hash_hex, validation); const loaded = try loadCachedValidation(std.testing.allocator, .wamr, hash_hex); try std.testing.expectEqual(types.ValidationCacheState.hit, loaded.state); try std.testing.expect(loaded.validation != null); try std.testing.expectEqualDeep(validation, loaded.validation.?); } test "stale validation cache entry is ignored and removed" { const hash_hex = [_]u8{'c'} ** 64; const cache_path = try validationCachePath(std.testing.allocator, .wamr, hash_hex); defer std.testing.allocator.free(cache_path); try std.fs.cwd().makePath(validation_cache_dir); defer std.fs.cwd().deleteFile(cache_path) catch {}; try std.fs.cwd().writeFile(.{ .sub_path = cache_path, .data = \\{"schema_version":1,"backend":"wamr","module_hash_hex":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc","validation":{"abi_version":2,"has_init":true,"has_start_iteration":true,"has_next_request":true,"has_handle_response":true,"has_setup":false,"has_teardown":false}} , }); const loaded = try loadCachedValidation(std.testing.allocator, .wamr, hash_hex); try std.testing.expectEqual(types.ValidationCacheState.stale, loaded.state); try std.testing.expectEqual(@as(?types.ModuleValidation, null), loaded.validation); try std.testing.expectError(error.FileNotFound, std.fs.cwd().access(cache_path, .{})); }