make sure cache saves to file properly
This commit is contained in:
parent
c99551e35c
commit
4269cd6376
1 changed files with 27 additions and 0 deletions
|
|
@ -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 {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue