File size: 38,403 Bytes
6648d93
1
2
{"repo_name": "filedb", "file_name": "/filedb/src/oldfiles.zig", "inference_info": {"prefix_code": "const std = @import(\"std\");\nconst utils = @import(\"utils.zig\");\nconst Datafile = @import(\"datafile.zig\").Datafile;\n\npub ", "suffix_code": "\n\nconst ErrorMissingData = error{MissingData};\n", "middle_code": "const OldFiles = struct {\n    filemap: std.AutoHashMap(u32, *Datafile),\n    allocator: std.mem.Allocator,\n    pub fn init(allocator: std.mem.Allocator, filemap: std.AutoHashMap(u32, *Datafile)) !*OldFiles {\n        const oldfiles = try allocator.create(OldFiles);\n        oldfiles.* = .{ .filemap = filemap, .allocator = allocator };\n        return oldfiles;\n    }\n    pub fn initializeMap(self: *OldFiles, dir: std.fs.Dir) !void {\n        const filelist = try utils.listAllDatabaseFiles(self.allocator, dir);\n        for (filelist.items) |entry| {\n            std.debug.print(\"Found file: {s}\", .{entry});\n            const file_id = try utils.parseIdFromFilename(entry);\n            const df = try Datafile.init(self.allocator, file_id, dir);\n            try self.filemap.put(file_id, df);\n        }\n        for (filelist.items) |entry| {\n            self.allocator.free(entry);\n        }\n        filelist.deinit();\n    }\n    pub fn deinit(self: *OldFiles) void {\n        var keydirIterator = self.filemap.iterator();\n        while (keydirIterator.next()) |entry| {\n            entry.value_ptr.*.deinit();\n        }\n        self.filemap.deinit();\n        self.allocator.destroy(self);\n    }\n    pub fn get(self: OldFiles, buf: []u8, file_id: u32, value_pos: usize, value_size: usize) !void {\n        const df = self.filemap.get(file_id);\n        if (df == null) {\n            return error.EmptyDatafile;\n        }\n        return df.?.get(buf, value_pos, value_size);\n    }\n};", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "zig", "sub_task_type": null}, "context_code": [["/filedb/src/filedb.zig", "const std = @import(\"std\");\nconst time = std.time;\nconst expect = std.testing.expect;\nconst Datafile = @import(\"datafile.zig\").Datafile;\nconst utils = @import(\"utils.zig\");\nconst Oldfiles = @import(\"oldfiles.zig\").OldFiles;\nconst kd = @import(\"keydir.zig\");\nconst record = @import(\"record.zig\");\nconst config = @import(\"config.zig\");\nconst Logger = @import(\"logger.zig\").Logger;\n\npub const FileDB = struct {\n    datafile: *Datafile,\n    keydir: std.StringHashMap(kd.Metadata),\n    oldfiles: *Oldfiles,\n    mu: std.Thread.Mutex,\n    allocator: std.mem.Allocator,\n    config: config.Options,\n    log: Logger,\n    compaction_thread: ?std.Thread = null,\n    dfRotation_thread: ?std.Thread = null,\n    sync_thread: ?std.Thread = null,\n    should_shutdown: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),\n\n    // initialize the filedb with keydir and other structures\n    pub fn init(allocator: std.mem.Allocator, options: ?config.Options) !*FileDB {\n        var conf = config.defaultOptions();\n        if (options) |option| {\n            conf = option;\n        }\n\n        // Initialize oldfiles\n        const oldfilesMap = std.AutoHashMap(u32, *Datafile).init(allocator);\n        var dir = try utils.openUserDir(conf.dir);\n        defer dir.close();\n        const oldfiles = try Oldfiles.init(allocator, oldfilesMap);\n        try oldfiles.initializeMap(dir);\n        // Initialize keydir first\n        const keydir = std.StringHashMap(kd.Metadata).init(allocator);\n\n        const filedb = try allocator.create(FileDB);\n        filedb.* = .{\n            .mu = std.Thread.Mutex{},\n            .allocator = allocator,\n            .config = conf,\n            .keydir = keydir,\n            .oldfiles = oldfiles,\n            .datafile = undefined, // Will be set after calculating the ID\n            .log = Logger.init(conf.log_level),\n        };\n        filedb.log.info(\"============= STARTING FILEDB ================\", .{});\n        // get the last used fileid\n        var id: u32 = 1;\n        var it = filedb.oldfiles.filemap.keyIterator();\n        while (it.next()) |entry| {\n            if (entry.* >= id) {\n                id = entry.* + 1;\n            }\n        }\n        filedb.log.debug(\"last used file id: {}\", .{id});\n        filedb.datafile = try Datafile.init(allocator, id, dir);\n\n        // Load keydir data\n        try filedb.loadKeyDir();\n\n        filedb.compaction_thread = try std.Thread.spawn(.{}, runCompaction, .{filedb});\n        filedb.dfRotation_thread = try std.Thread.spawn(.{}, runRotation, .{filedb});\n        filedb.sync_thread = try std.Thread.spawn(.{}, runSync, .{filedb});\n\n        filedb.log.info(\"================== FileDB created ===============\", .{});\n        return filedb;\n    }\n\n    pub fn deinit(self: *FileDB) void {\n        self.should_shutdown.store(true, .release);\n\n        // Join thread if it was started\n        if (self.compaction_thread) |t| {\n            t.join();\n        }\n        if (self.dfRotation_thread) |t| {\n            t.join();\n        }\n        if (self.sync_thread) |t| {\n            t.join();\n        }\n\n        self.storeHashMap() catch |err| {\n            self.log.err(\"Error storing hashmap: {}\", .{err});\n        };\n\n        var key_it = self.keydir.iterator();\n        while (key_it.next()) |entry| {\n            self.allocator.free(entry.key_ptr.*);\n        }\n\n        self.keydir.deinit();\n\n        // Clean up other resources\n        self.oldfiles.deinit();\n        self.datafile.deinit();\n\n        // Finally free the FileDB struct itself\n        self.log.info(\"SHUTTING DOWN FILEDB\", .{});\n        self.allocator.destroy(self);\n    }\n\n    pub fn put(self: *FileDB, key: []const u8, value: []const u8) !void {\n        self.mu.lock();\n        defer self.mu.unlock();\n\n        try utils.validateKV(key, value);\n        try self.storeKV(self.datafile, key, value);\n    }\n\n    pub fn get(self: *FileDB, key: []const u8) !?[]const u8 {\n        self.mu.lock();\n        defer self.mu.unlock();\n\n        const result = self.getValue(key);\n        return result;\n    }\n\n    fn storeKV(self: *FileDB, datafile: *Datafile, key: []const u8, value: []const u8) !void {\n        const rec = try record.Record.init(self.allocator, key, value);\n        defer rec.deinit();\n\n        const record_size = @sizeOf(record.Record) - @sizeOf([]u8) * 2 + rec.key_len + rec.value_len;\n        const buf = try self.allocator.alloc(u8, record_size);\n        defer self.allocator.free(buf);\n\n        try rec.encode(buf);\n        const offset = try datafile.store(buf);\n        const metadata = kd.Metadata.init(datafile.id, record_size, offset, rec.tstamp);\n\n        // get the entry if already present, if doesnt exist,\n        // dynamically allocate a new key else reuse the old one.\n        const entry = try self.keydir.getOrPut(key);\n        if (!entry.found_existing) {\n            const copy_key = try self.allocator.dupe(u8, key);\n            entry.key_ptr.* = copy_key;\n        }\n        entry.value_ptr.* = metadata;\n\n        //possible fsync\n        if (self.config.alwaysFsync) {\n            try self.datafile.sync();\n        }\n    }\n\n    fn getValue(self: *FileDB, key: []const u8) !?[]const u8 {\n        const metadata = self.keydir.get(key);\n        if (metadata == null) {\n            // if no key exists in the keydir\n            return undefined;\n        }\n\n        const buf = try self.allocator.alloc(u8, metadata.?.value_sz);\n        defer self.allocator.free(buf);\n        if (self.datafile.id == metadata.?.file_id) {\n            // get data from datafile\n            try self.datafile.get(buf, metadata.?.value_pos, metadata.?.value_sz);\n        } else {\n            //get data from oldfiles\n            try self.oldfiles.get(buf, metadata.?.file_id, metadata.?.value_pos, metadata.?.value_sz);\n        }\n        //decode data and put in response array\n        const rec = try record.decodeRecord(self.allocator, buf);\n        defer rec.deinit();\n\n        const value = try self.allocator.dupe(u8, rec.value);\n        return value;\n    }\n\n    pub fn delete(self: *FileDB, key: []const u8) !void {\n        self.mu.lock();\n        defer self.mu.unlock();\n\n        // update the value of the key with a tombstone value\n        const data = [_]u8{};\n        try self.storeKV(self.datafile, key, &data);\n\n        // remove the key from the keydir and deallocate the key memory.\n        const entry = self.keydir.fetchRemove(key);\n        if (entry) |e| {\n            // Free the dynamically allocated key\n            self.allocator.free(e.key);\n            std.log.info(\"Deleted key: {s}\", .{key});\n        } else {\n            std.log.info(\"Key not found: {s}\", .{key});\n        }\n    }\n\n    pub fn list(self: *FileDB, allocator: std.mem.Allocator) !std.ArrayList([]u8) {\n        self.mu.lock();\n        defer self.mu.unlock();\n\n        // Initialize the array list\n        var keylist = std.ArrayList([]u8).init(allocator);\n        errdefer {\n            // Free any keys we've already added if we encounter an error\n            for (keylist.items) |item| {\n                allocator.free(item);\n            }\n            keylist.deinit();\n        }\n\n        // Iterate through all keys in the map\n        var key_itr = self.keydir.keyIterator();\n        while (key_itr.next()) |entry| {\n            // Duplicate the key\n            const key = try allocator.dupe(u8, entry.*);\n            // Try to append, free key if append fails\n            keylist.append(key) catch |err| {\n                allocator.free(key);\n                return err;\n            };\n        }\n\n        return keylist;\n    }\n\n    pub fn sync(self: *FileDB) !void {\n        self.mu.lock();\n        defer self.mu.unlock();\n\n        try self.datafile.sync();\n    }\n\n    pub fn storeHashMap(self: *FileDB) !void {\n        self.mu.lock();\n        defer self.mu.unlock();\n        try self.StoreHashMap();\n    }\n\n    fn StoreHashMap(self: *FileDB) !void {\n        const path = try utils.openUserDir(self.config.dir);\n        var file = try path.createFile(kd.HINTS_FILE, .{});\n        defer file.close();\n        var writer = file.writer();\n\n        // Write number of hashmap entries\n        try writer.writeInt(u32, @intCast(self.keydir.count()), std.builtin.Endian.little);\n        var it = self.keydir.iterator();\n        while (it.next()) |entry| {\n            // Write key length and key\n            try writer.writeInt(u32, @intCast(entry.key_ptr.*.len), std.builtin.Endian.little);\n            try writer.writeAll(entry.key_ptr.*);\n\n            const meta = entry.value_ptr.*;\n            // Write number of metadata entries\n            try writer.writeInt(u32, meta.file_id, std.builtin.Endian.little);\n            try writer.writeInt(usize, meta.value_sz, std.builtin.Endian.little);\n            try writer.writeInt(usize, meta.value_pos, std.builtin.Endian.little);\n            try writer.writeInt(i64, meta.tstamp, std.builtin.Endian.little);\n        }\n    }\n\n    pub fn loadKeyDir(self: *FileDB) !void {\n        self.mu.lock();\n        defer self.mu.unlock();\n        const path = try utils.openUserDir(self.config.dir);\n\n        var file = path.openFile(kd.HINTS_FILE, .{}) catch |err| {\n            std.log.debug(\"Error opening hint file: {}\", .{err});\n            return;\n        };\n        defer file.close();\n        var reader = file.reader();\n        const stat = try file.stat();\n        if (stat.size == 0) {\n            return;\n        }\n\n        // Read number of hashmap entries\n        const entry_count = try reader.readInt(u32, std.builtin.Endian.little);\n        var i: u32 = 0;\n        while (i < entry_count) : (i += 1) {\n            // Read key length and key\n            const key_len = try reader.readInt(u32, std.builtin.Endian.little);\n            const key_buf = try self.allocator.alloc(u8, key_len);\n            errdefer self.allocator.free(key_buf);\n            try reader.readNoEof(key_buf);\n\n            // Read metadata items\n            const file_id = try reader.readInt(u32, std.builtin.Endian.little);\n            const value_sz = try reader.readInt(usize, std.builtin.Endian.little);\n            const value_pos = try reader.readInt(usize, std.builtin.Endian.little);\n            const tstamp = try reader.readInt(i64, std.builtin.Endian.little);\n\n            const metadata = kd.Metadata.init(file_id, value_sz, value_pos, tstamp);\n\n            try self.keydir.put(key_buf, metadata);\n        }\n\n        return;\n    }\n};\n\nfn runCompaction(self: *FileDB) !void {\n    const interval: u64 = self.config.compactionInterval * time.ns_per_s;\n    while (!self.should_shutdown.load(.acquire)) {\n        time.sleep(interval);\n        {\n            self.mu.lock();\n            defer self.mu.unlock();\n            self.log.info(\"Starting compaction\", .{});\n            try mergeDatafiles(self);\n            try self.StoreHashMap();\n            self.log.info(\"Ended compaction\", .{});\n        }\n    }\n}\nfn runSync(self: *FileDB) !void {\n    const interval: u64 = self.config.syncInterval * time.ns_per_s;\n    while (!self.should_shutdown.load(.acquire)) {\n        time.sleep(interval);\n        {\n            self.mu.lock();\n            defer self.mu.unlock();\n            try self.datafile.sync();\n        }\n    }\n}\nfn runRotation(self: *FileDB) !void {\n    const interval: u64 = self.config.dfRotationInterval * time.ns_per_s;\n    while (!self.should_shutdown.load(.acquire)) {\n        time.sleep(interval);\n        {\n            self.mu.lock();\n            defer self.mu.unlock();\n            try rotateDf(self);\n        }\n    }\n}\n\nfn rotateDf(self: *FileDB) !void {\n    self.log.info(\"Current Datafile Size: {}\", .{try self.datafile.size()});\n    if (try self.datafile.size() < self.config.maxFileSize) {\n        return;\n    }\n\n    self.log.info(\"Starting DF Rotation\", .{});\n    const oldId = self.datafile.id;\n    try self.oldfiles.filemap.put(oldId, self.datafile);\n    var dir = try utils.openUserDir(self.config.dir);\n    defer dir.close();\n    self.datafile = try Datafile.init(self.allocator, oldId + 1, dir);\n    self.log.info(\"Ended DF Rotation\", .{});\n    return;\n}\nfn mergeDatafiles(self: *FileDB) !void {\n    var mergeFsync = false;\n    if (self.oldfiles.filemap.count() < 2) {\n        return;\n    }\n    std.fs.cwd().makeDir(\"tmp\") catch |err| switch (err) {\n        error.PathAlreadyExists => {\n            self.log.debug(\"Directory already exists: {s}\\n\", .{\"tmp\"});\n        },\n        else => return err,\n    };\n\n    var tmpDirectory = try std.fs.cwd().openDir(\"tmp\", .{ .iterate = true });\n    defer tmpDirectory.close();\n    defer std.fs.cwd().deleteTree(\"tmp\") catch |err| {\n        self.log.debug(\"Cannot Delete TempDir: {}\", .{err});\n    };\n\n    const mergedDf = try Datafile.init(self.allocator, 0, tmpDirectory);\n    if (self.config.alwaysFsync) {\n        mergeFsync = true;\n        self.config.alwaysFsync = false;\n    }\n\n    var it = self.keydir.iterator();\n    while (it.next()) |entry| {\n        const keydir_record = try self.getValue(entry.key_ptr.*);\n        if (keydir_record) |existing_record| {\n            try self.storeKV(mergedDf, entry.key_ptr.*, existing_record);\n            self.allocator.free(existing_record);\n        }\n    }\n\n    var oldDir = try utils.openUserDir(self.config.dir);\n    defer oldDir.close();\n    var walker = try oldDir.walk(self.allocator);\n    defer walker.deinit();\n    while (try walker.next()) |entry| {\n        if (entry.kind != .file) {\n            continue;\n        }\n        if (std.mem.endsWith(u8, entry.basename, \".db\")) {\n            oldDir.deleteFile(entry.path) catch |err| {\n                self.log.debug(\"Failed to remove {s}: {}\\n\", .{ entry.path, err });\n                continue;\n            };\n        }\n    }\n\n    const filemap = std.AutoHashMap(u32, *Datafile).init(self.allocator);\n    self.oldfiles.deinit();\n    self.oldfiles = try Oldfiles.init(self.allocator, filemap);\n    try self.oldfiles.initializeMap(oldDir);\n\n    try tmpDirectory.copyFile(\"file_0.db\", oldDir, \"file_0.db\", .{});\n    self.datafile.deinit();\n    self.datafile = mergedDf;\n\n    if (mergeFsync) {\n        try self.datafile.sync();\n        self.config.alwaysFsync = true;\n    }\n    return;\n}\n\ntest \"filedbInitialized\" {\n    var gpa = std.heap.GeneralPurposeAllocator(.{}){};\n    defer if (gpa.deinit() != .ok) @panic(\"leak\");\n    const allocator = gpa.allocator();\n\n    var options = config.defaultOptions();\n    options.dir = \"/home/rajiv/projects/filedb/test_initialize\";\n    const filedb = try FileDB.init(allocator, options);\n    time.sleep(10 * time.ns_per_s);\n    defer filedb.deinit();\n    try expect(true);\n}\n\ntest \"insert a value and get it back\" {\n    var gpa = std.heap.GeneralPurposeAllocator(.{}){};\n    defer if (gpa.deinit() != .ok) @panic(\"leak\");\n    const allocator = gpa.allocator();\n\n    var options = config.defaultOptions();\n    options.dir = \"test_3\";\n    const filedb = try FileDB.init(allocator, options);\n    defer filedb.deinit();\n\n    try filedb.put(\"key1\", \"value1\");\n\n    const value = try filedb.get(\"key1\");\n\n    try expect(value != null);\n    defer if (value) |v| allocator.free(v);\n\n    const final_value = value.?;\n    std.log.debug(\"found value '{s}'\", .{final_value});\n    try std.testing.expectEqualStrings(\"value1\", final_value);\n}\n\ntest \"get a value which does not exist\" {\n    var gpa = std.heap.GeneralPurposeAllocator(.{}){};\n    defer if (gpa.deinit() != .ok) @panic(\"leak\");\n    const allocator = gpa.allocator();\n\n    var options = config.defaultOptions();\n    options.dir = \"test_2\";\n    const filedb = try FileDB.init(allocator, options);\n    defer filedb.deinit();\n\n    const value = try filedb.get(\"key1\");\n\n    try expect(value == null);\n}\n\ntest \"list all keys\" {\n    var gpa = std.heap.GeneralPurposeAllocator(.{}){};\n    defer if (gpa.deinit() != .ok) @panic(\"leak\");\n    const allocator = gpa.allocator();\n\n    var options = config.defaultOptions();\n    options.dir = \"test_1\";\n    const filedb = try FileDB.init(allocator, options);\n    defer filedb.deinit();\n\n    try filedb.put(\"key1\", \"value1\");\n    try filedb.put(\"key2\", \"value1\");\n    try filedb.put(\"key3\", \"value1\");\n    try filedb.put(\"key4\", \"value1\");\n\n    const keylist = try filedb.list(allocator);\n    defer {\n        for (keylist.items) |v| {\n            allocator.free(v);\n        }\n        keylist.deinit();\n    }\n\n    try std.testing.expectEqual(4, keylist.items.len);\n}\n"], ["/filedb/src/datafile.zig", "const std = @import(\"std\");\nconst util = @import(\"utils.zig\");\nconst filename = \"file_{}.db\";\n\npub const Datafile = struct {\n    reader: std.fs.File,\n    writer: std.fs.File,\n    mu: std.Thread.Mutex,\n    id: u32,\n    offset: u64,\n    allocator: std.mem.Allocator,\n\n    pub fn init(allocator: std.mem.Allocator, index: u32, dir: std.fs.Dir) !*Datafile {\n        var file_buf: [32]u8 = undefined;\n        const file_name = try std.fmt.bufPrint(&file_buf, filename, .{index});\n        _ = dir.createFile(file_name, .{ .read = true, .exclusive = true }) catch |err| switch (err) {\n            error.PathAlreadyExists => {\n                // Open existing file\n            },\n            else => return err,\n        };\n        const file = try dir.openFile(file_name, .{ .mode = .read_write });\n\n        const stat = try file.stat();\n        const datafile = try allocator.create(Datafile);\n\n        datafile.* = .{\n            .reader = file,\n            .writer = file,\n            .mu = std.Thread.Mutex{},\n            .id = index,\n            .offset = stat.size,\n            .allocator = allocator,\n        };\n        return datafile;\n    }\n\n    pub fn deinit(self: *Datafile) void {\n        self.reader.close();\n\n        self.allocator.destroy(self);\n    }\n\n    pub fn size(self: *Datafile) !u64 {\n        const stat = self.writer.stat() catch |err| {\n            std.log.debug(\"cannot stat file '{}': {}\", .{ self.id, err });\n\n            return err;\n        };\n\n        return stat.size;\n    }\n\n    pub fn store(self: *Datafile, buf: []const u8) !u64 {\n        const sz = try self.writer.write(buf);\n\n        const offset = self.offset;\n        self.offset += sz;\n\n        return offset;\n    }\n\n    pub fn get(self: *Datafile, buf: []u8, value_pos: usize, value_size: usize) !void {\n        try self.reader.seekTo(value_pos);\n        const data = try self.reader.read(buf);\n\n        if (data != value_size) {\n            return ErrorMissingData.MissingData;\n        }\n    }\n\n    pub fn sync(self: *Datafile) !void {\n        try self.writer.sync();\n    }\n};\n\nconst ErrorMissingData = error{MissingData};\n"], ["/filedb/src/utils.zig", "const std = @import(\"std\");\nconst Crc32 = std.hash.crc.Crc32;\n\n// list all the database files in the given directory\n// directory must be open with the iterate flag true\npub fn listAllDatabaseFiles(allocator: std.mem.Allocator, dir: std.fs.Dir) !std.ArrayList([]const u8) {\n    var walker = try dir.walk(allocator);\n    defer walker.deinit();\n\n    var filelist = std.ArrayList([]const u8).init(allocator);\n\n    while (try walker.next()) |entry| {\n        if (std.mem.endsWith(u8, entry.basename, \".db\")) {\n            const f = try allocator.dupe(u8, entry.basename);\n            try filelist.append(f);\n        }\n    }\n    return filelist;\n}\n\npub fn parseIdFromFilename(filename: []const u8) !u32 {\n    const prefix = \"file_\";\n    const suffix = \".db\";\n    const start_index = prefix.len;\n    const end_index = std.mem.indexOf(u8, filename, suffix) orelse filename.len;\n\n    if (start_index >= end_index) {\n        std.debug.print(\"Invalid format\\n\", .{});\n        return error.InvalidFormat;\n    }\n\n    // Extract the substring containing the number\n    const id_str = filename[start_index..end_index];\n\n    // Convert to integer\n    const id = try std.fmt.parseInt(u32, id_str, 10);\n    return id;\n}\n\npub fn validateKV(key: []const u8, value: []const u8) !void {\n    if (key.len == 0) {\n        return ErrorKVValidation.KeyCannotBeEmpty;\n    }\n\n    if (key.len > MAX_KEY_LEN) {\n        return ErrorKVValidation.KeyLengthExceeded;\n    }\n\n    if (value.len > MAX_VAL_LEN) {\n        return ErrorKVValidation.ValueLengthExceeded;\n    }\n}\n\npub const ErrorKVValidation = error{\n    KeyCannotBeEmpty,\n    KeyLengthExceeded,\n    ValueLengthExceeded,\n};\n\npub fn crc32Checksum(data: []const u8) u32 {\n    var crc = Crc32.init();\n    crc.update(data);\n    return crc.final();\n}\n\npub const MAX_KEY_LEN = 4294967296; // 2^32\npub const MAX_VAL_LEN = 4294967296; // 2^32\n\npub fn openUserDir(user_path: []const u8) !std.fs.Dir {\n    if (std.fs.path.isAbsolute(user_path)) {\n        // Try opening absolute path\n        return std.fs.openDirAbsolute(user_path, .{ .iterate = true }) catch |err| switch (err) {\n            error.FileNotFound => {\n                try std.fs.makeDirAbsolute(user_path); // Create missing directory\n                return std.fs.openDirAbsolute(user_path, .{ .iterate = true });\n            },\n            else => return err,\n        };\n    } else {\n        // Try opening relative path from CWD\n        const cwd = std.fs.cwd();\n        return cwd.openDir(user_path, .{ .iterate = true }) catch |err| switch (err) {\n            error.FileNotFound => {\n                try cwd.makeDir(user_path);\n                return cwd.openDir(user_path, .{ .iterate = true });\n            },\n            else => return err,\n        };\n    }\n}\n"], ["/filedb/src/main.zig", "const std = @import(\"std\");\nconst FileDB = @import(\"filedb.zig\").FileDB;\nconst FileDBConfig = @import(\"config.zig\");\n\npub fn main() !void {\n    var gpa = std.heap.GeneralPurposeAllocator(.{}){};\n    defer _ = gpa.deinit();\n    const allocator = gpa.allocator();\n\n    var options = FileDBConfig.defaultOptions();\n    options.alwaysFsync = false;\n    options.compactionInterval = 100;\n    options.dfRotationInterval = 150;\n    options.maxFileSize = 1000 * 1024 * 1024;\n    options.log_level = std.log.Level.info;\n    var filedb = try FileDB.init(allocator, options);\n    defer filedb.deinit();\n\n    var listener = try std.net.Address.listen(try std.net.Address.parseIp(\"0.0.0.0\", 6379), .{\n        .reuse_address = true,\n    });\n    defer listener.deinit();\n\n    filedb.log.debug(\"Listening on 0.0.0.0:6379\\n\", .{});\n\n    while (true) {\n        const conn = listener.accept() catch |err| {\n            filedb.log.debug(\"Accept error: {}\\n\", .{err});\n            continue;\n        };\n\n        const context = try allocator.create(ClientContext);\n        context.* = ClientContext{\n            .stream = conn.stream,\n            .db = filedb,\n            .allocator = allocator,\n        };\n\n        _ = try std.Thread.spawn(.{}, handleClient, .{context});\n    }\n}\n\nfn readRespCommand(reader: anytype, allocator: std.mem.Allocator) ![][]const u8 {\n    var buf1: [128]u8 = undefined;\n    const first_line = try reader.readUntilDelimiterOrEof(&buf1, '\\n') orelse return error.EndOfStream;\n\n    if (first_line.len < 1 or first_line[0] != '*') return error.InvalidCommand;\n\n    const argc = try std.fmt.parseInt(usize, std.mem.trimRight(u8, first_line[1..], \"\\r\"), 10);\n    var args = try allocator.alloc([]const u8, argc);\n    errdefer {\n        for (args[0..]) |arg| {\n            allocator.free(arg);\n        }\n        allocator.free(args);\n    }\n\n    var i: usize = 0;\n    while (i < argc) {\n        var len_buf: [128]u8 = undefined;\n        const len_line = try reader.readUntilDelimiterOrEof(&len_buf, '\\n') orelse return error.UnexpectedEof;\n\n        if (len_line.len < 1 or len_line[0] != '$') return error.InvalidCommand;\n\n        const len = try std.fmt.parseInt(usize, std.mem.trimRight(u8, len_line[1..], \"\\r\"), 10);\n        const data = try allocator.alloc(u8, len);\n        _ = try reader.readNoEof(data);\n\n        var crlf: [2]u8 = undefined;\n        _ = try reader.readNoEof(&crlf);\n        if (!(crlf[0] == '\\r' and crlf[1] == '\\n')) return error.InvalidLineEnding;\n\n        args[i] = data;\n        i += 1;\n    }\n\n    return args;\n}\n\nconst ClientContext = struct {\n    stream: std.net.Stream,\n    db: *FileDB,\n    allocator: std.mem.Allocator,\n};\n\nfn handleClient(context: *ClientContext) !void {\n    defer {\n        context.stream.close();\n        context.allocator.destroy(context);\n    }\n\n    const reader = context.stream.reader();\n    const writer = context.stream.writer();\n\n    while (true) {\n        context.db.log.debug(\"===> parsing next RESP command\\n\", .{});\n\n        const args = readRespCommand(reader, context.allocator) catch |err| {\n            switch (err) {\n                error.EndOfStream => {\n                    context.db.log.debug(\"Client disconnected\\n\", .{});\n                    break;\n                },\n                else => {\n                    try writer.writeAll(\"-ERR parse error\\r\\n\");\n                    context.db.log.debug(\"Parse error: {}\\n\", .{err});\n                    continue;\n                },\n            }\n        };\n\n        defer {\n            for (args) |item| {\n                context.allocator.free(item);\n            }\n            context.allocator.free(args);\n        }\n\n        if (args.len == 0) continue;\n\n        const cmd = std.ascii.allocUpperString(context.allocator, args[0]) catch args[0];\n        defer if (cmd.ptr != args[0].ptr) context.allocator.free(cmd);\n\n        if (std.mem.eql(u8, cmd, \"PING\")) {\n            try writer.writeAll(\"+PONG\\r\\n\");\n        } else if (std.mem.eql(u8, cmd, \"SET\") and args.len == 3) {\n            try context.db.put(args[1], args[2]);\n            try writer.writeAll(\"+OK\\r\\n\");\n        } else if (std.mem.eql(u8, cmd, \"GET\") and args.len == 2) {\n            if (try context.db.get(args[1])) |val| {\n                try writer.print(\"${d}\\r\\n{s}\\r\\n\", .{ val.len, val });\n            } else {\n                try writer.writeAll(\"$-1\\r\\n\");\n            }\n        } else if (std.mem.eql(u8, cmd, \"DEL\") and args.len == 2) {\n            try context.db.delete(args[1]);\n            try writer.writeAll(\":1\\r\\n\");\n        } else if (std.mem.eql(u8, cmd, \"CONFIG\")) {\n            // Handle CONFIG commands more properly\n            if (args.len >= 2 and std.mem.eql(u8, std.ascii.allocUpperString(context.allocator, args[1]) catch args[1], \"GET\")) {\n                try writer.writeAll(\"*0\\r\\n\");\n            } else {\n                try writer.writeAll(\"*0\\r\\n\");\n            }\n        } else {\n            try writer.writeAll(\"-ERR unknown command\\r\\n\");\n        }\n    }\n}\n"], ["/filedb/src/record.zig", "const std = @import(\"std\");\nconst utils = @import(\"utils.zig\");\n\npub const Record = struct {\n    crc: u32,\n    tstamp: i64,\n    key_len: usize,\n    value_len: usize,\n    key: []const u8,\n    value: []const u8,\n    allocator: std.mem.Allocator,\n\n    pub fn init(allocator: std.mem.Allocator, key: []const u8, value: []const u8) !*Record {\n        const record = try allocator.create(Record); // better error handling\n        const key_copy = try allocator.dupe(u8, key);\n        const value_copy = try allocator.dupe(u8, value);\n        record.* = .{\n            .crc = utils.crc32Checksum(key),\n            .tstamp = std.time.timestamp(),\n            .key_len = key.len,\n            .value_len = value.len,\n            .key = key_copy,\n            .value = value_copy,\n            .allocator = allocator,\n        };\n\n        return record;\n    }\n\n    pub fn encode(self: *Record, buf: []u8) !void {\n        var fbs = std.io.fixedBufferStream(buf);\n        var writer = fbs.writer();\n\n        try writer.writeInt(u32, self.crc, std.builtin.Endian.little);\n        try writer.writeInt(i64, self.tstamp, std.builtin.Endian.little);\n        try writer.writeInt(usize, self.key_len, std.builtin.Endian.little);\n        try writer.writeInt(usize, self.value_len, std.builtin.Endian.little);\n        try writer.writeAll(self.key);\n        try writer.writeAll(self.value);\n    }\n\n    pub fn deinit(self: *Record) void {\n        self.allocator.free(self.key);\n        self.allocator.free(self.value);\n        self.allocator.destroy(self);\n    }\n};\n\npub fn decodeRecord(allocator: std.mem.Allocator, buf: []u8) !*Record {\n    var fbs = std.io.fixedBufferStream(buf);\n    var reader = fbs.reader();\n\n    _ = try reader.readInt(u32, std.builtin.Endian.little);\n    _ = try reader.readInt(i64, std.builtin.Endian.little);\n    const key_len = try reader.readInt(usize, std.builtin.Endian.little);\n    const value_len = try reader.readInt(usize, std.builtin.Endian.little);\n    const key = try allocator.alloc(u8, key_len);\n    defer allocator.free(key);\n    _ = try reader.read(key);\n    const value = try allocator.alloc(u8, value_len);\n    defer allocator.free(value);\n    _ = try reader.read(value);\n    return Record.init(allocator, key, value);\n}\n"], ["/filedb/src/keydir.zig", "const std = @import(\"std\");\nconst Oldfiles = @import(\"oldfiles.zig\").OldFiles;\nconst utils = @import(\"utils.zig\");\n\n// hashmap of key-> file_id, value_sz, value_pos, tstamp\n\npub const HINTS_FILE = \"filedb.hints\";\n\npub const Metadata = struct {\n    file_id: u32,\n    value_sz: usize,\n    value_pos: usize,\n    tstamp: i64,\n\n    pub fn init(file_id: u32, value_sz: usize, value_pos: usize, tstamp: i64) Metadata {\n        return .{\n            .file_id = file_id,\n            .value_pos = value_pos,\n            .value_sz = value_sz,\n            .tstamp = tstamp,\n        };\n    }\n};\n"], ["/filedb/src/logger.zig", "const std = @import(\"std\");\nconst log = std.log;\n\npub const Logger = struct {\n    level: log.Level,\n\n    const Self = @This();\n\n    pub fn init(level: log.Level) Self {\n        return Self{\n            .level = level,\n        };\n    }\n\n    // Helper method to check if a log level should be printed\n    fn shouldLog(self: *const Self, level: log.Level) bool {\n        return @intFromEnum(level) <= @intFromEnum(self.level);\n    }\n\n    // Custom logging methods\n    pub fn info(self: *const Self, comptime format: []const u8, args: anytype) void {\n        if (self.shouldLog(.info)) {\n            log.info(format, args);\n        }\n    }\n\n    pub fn debug(self: *const Self, comptime format: []const u8, args: anytype) void {\n        if (self.shouldLog(.debug)) {\n            log.debug(format, args);\n        }\n    }\n\n    pub fn warn(self: *const Self, comptime format: []const u8, args: anytype) void {\n        if (self.shouldLog(.warn)) {\n            log.warn(format, args);\n        }\n    }\n\n    pub fn err(self: *const Self, comptime format: []const u8, args: anytype) void {\n        if (self.shouldLog(.err)) {\n            log.err(format, args);\n        }\n    }\n};\n"], ["/filedb/src/config.zig", "const std = @import(\"std\");\nconst log = std.log;\n\npub const Options = struct {\n    dir: []const u8,\n    alwaysFsync: bool,\n    log_level: log.Level,\n    maxFileSize: u32,\n    compactionInterval: u64, // in seconds\n    dfRotationInterval: u64,\n    syncInterval: u64,\n};\n\npub fn defaultOptions() Options {\n    return .{\n        .dir = \"/home/rajiv/projects/filedb/filedb\",\n        .alwaysFsync = false,\n        .log_level = log.Level.info,\n        .maxFileSize = 10 * 1024 * 1024, //10mb\n        .compactionInterval = 10,\n        .dfRotationInterval = 15,\n        .syncInterval = 15,\n    };\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:44:58", "created_task_model": "DeepSeek-R1", "function_skeleton": "const OldFiles = struct {\n    filemap: std.AutoHashMap(u32, *Datafile),\n    allocator: std.mem.Allocator,\n    // path: []const u8,\n\n    pub fn init(allocator: std.mem.Allocator, filemap: std.AutoHashMap(u32, *Datafile)) !*OldFiles {\n        const oldfiles = try allocator.create(OldFiles);\n        oldfiles.* = .{ .filemap = filemap, .allocator = allocator };\n        return oldfiles;\n    }\n\n    pub fn initializeMap(self: *OldFiles, dir: std.fs.Dir) !void {\n        const filelist = try utils.listAllDatabaseFiles(self.allocator, dir);\n        for (filelist.items) |entry| {\n            std.debug.print(\"Found file: {s}\", .{entry});\n            const file_id = try utils.parseIdFromFilename(entry);\n            const df = try Datafile.init(self.allocator, file_id, dir);\n            try self.filemap.put(file_id, df);\n        }\n        for (filelist.items) |entry| {\n            self.allocator.free(entry);\n        }\n        filelist.deinit();\n    }\n\n    pub fn deinit(self: *OldFiles) void {\n        var keydirIterator = self.filemap.iterator();\n        while (keydirIterator.next()) |entry| {\n            entry.value_ptr.*.deinit();\n        }\n        self.filemap.deinit();\n        self.allocator.destroy(self);\n    }\n\n    pub fn get(self: OldFiles, buf: []u8, file_id: u32, value_pos: usize, value_size: usize) !void {\n        const df = self.filemap.get(file_id);\n        if (df == null) {\n            return error.EmptyDatafile;\n        }\n\n        return df.?.get(buf, value_pos, value_size);\n    }\n}; { }", "code_description": "This code segment functions to: Manage the lifecycle of stored data resources by initializing from directory contents, maintaining lookup references, providing controlled access to stored values, and handling memory cleanup operations."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```zig\n[TASK_BEGIN]\n    pub fn get(self: OldFiles, buf: []u8, file_id: u32, value_pos: usize, value_size: usize) !void {\n        const df = self.filemap.get(file_id) orelse return ErrorMissingData.MissingData;\n        return df.get(buf, value_pos, value_size);\n    }\n[TASK_END]\n```", "inference_time": "2025-08-21 03-45-21"}, "editdistance_info": {"edit_distance": 15.2, "calculate_time": "2025-08-21 03:45:21", "true_code_clean": "const OldFiles = struct {\n    filemap: std.AutoHashMap(u32, *Datafile),\n    allocator: std.mem.Allocator,\n    pub fn init(allocator: std.mem.Allocator, filemap: std.AutoHashMap(u32, *Datafile)) !*OldFiles {\n        const oldfiles = try allocator.create(OldFiles);\n        oldfiles.* = .{ .filemap = filemap, .allocator = allocator };\n        return oldfiles;\n    }\n    pub fn initializeMap(self: *OldFiles, dir: std.fs.Dir) !void {\n        const filelist = try utils.listAllDatabaseFiles(self.allocator, dir);\n        for (filelist.items) |entry| {\n            std.debug.print(\"Found file: {s}\", .{entry});\n            const file_id = try utils.parseIdFromFilename(entry);\n            const df = try Datafile.init(self.allocator, file_id, dir);\n            try self.filemap.put(file_id, df);\n        }\n        for (filelist.items) |entry| {\n            self.allocator.free(entry);\n        }\n        filelist.deinit();\n    }\n    pub fn deinit(self: *OldFiles) void {\n        var keydirIterator = self.filemap.iterator();\n        while (keydirIterator.next()) |entry| {\n            entry.value_ptr.*.deinit();\n        }\n        self.filemap.deinit();\n        self.allocator.destroy(self);\n    }\n    pub fn get(self: OldFiles, buf: []u8, file_id: u32, value_pos: usize, value_size: usize) !void {\n        const df = self.filemap.get(file_id);\n        if (df == null) {\n            return error.EmptyDatafile;\n        }\n        return df.?.get(buf, value_pos, value_size);\n    }\n};", "predict_code_clean": "pub fn get(self: OldFiles, buf: []u8, file_id: u32, value_pos: usize, value_size: usize) !void {\n        const df = self.filemap.get(file_id) orelse return ErrorMissingData.MissingData;\n        return df.get(buf, value_pos, value_size);\n    }"}}