From 4269cd63764eb1e58e91ee92be38fb2c89be79ff Mon Sep 17 00:00:00 2001 From: Emil Lerch Date: Thu, 18 Dec 2025 16:50:36 -0800 Subject: [PATCH] make sure cache saves to file properly --- src/location/GeoCache.zig | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/location/GeoCache.zig b/src/location/GeoCache.zig index 216aee1..7d62b81 100644 --- a/src/location/GeoCache.zig +++ b/src/location/GeoCache.zig @@ -6,6 +6,8 @@ const GeoCache = @This(); allocator: std.mem.Allocator, cache: std.StringHashMap(CachedLocation), cache_file: ?[]const u8, +dirty: bool, +last_save: i64, pub const CachedLocation = struct { name: []const u8, @@ -26,6 +28,8 @@ pub fn init(allocator: std.mem.Allocator, cache_file: ?[]const u8) !GeoCache { .allocator = allocator, .cache = cache, .cache_file = if (cache_file) |f| try allocator.dupe(u8, f) else null, + .dirty = false, + .last_save = std.time.milliTimestamp(), }; } @@ -47,6 +51,7 @@ pub fn deinit(self: *GeoCache) void { } pub fn get(self: *GeoCache, query: []const u8) ?CachedLocation { + self.saveIfNeeded(); return self.cache.get(query); } @@ -57,6 +62,28 @@ pub fn put(self: *GeoCache, query: []const u8, location: CachedLocation) !void { .coords = location.coords, }; try self.cache.put(key, value); + self.dirty = true; +} + +/// Save cache to disk if dirty and enough time has passed (15 minutes) +pub fn saveIfNeeded(self: *GeoCache) void { + if (!self.dirty) return; + + const cache_file = self.cache_file orelse return; + + const now = std.time.milliTimestamp(); + const elapsed_ms = now - self.last_save; + const fifteen_minutes_ms = 15 * std.time.ms_per_min; + + if (elapsed_ms < fifteen_minutes_ms) return; + + self.saveToFile(cache_file) catch |err| { + std.log.warn("Failed to save geocoding cache to {s}: {}", .{ cache_file, err }); + return; + }; + + self.dirty = false; + self.last_save = now; } fn loadFromFile(allocator: std.mem.Allocator, cache: *std.StringHashMap(CachedLocation), file_path: []const u8) !void {