╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
992 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 993 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 994 last_object_id_maybe = last_object_id_buffer; 995 } 996 997 // the tip was already consumed, so there is nothing to do 998 if (last_object_id_maybe) |*last_object_id| { 999 const tip_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1000 var tip: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1001 _ = try std.fmt.hexToBytes(&tip, &tip_hex); 1002 if (std.mem.eql(u8, last_object_id, &tip)) return false; 1003 } 1004 1005 // the list with all of haxy's state, including materialized views. 1006 // the reason it is a list is so we can keep every previous haxy 1007 // state, making it easy to revert to an older state if the user 1008 // rebases some of the past commits. 1009 const haxy_history_cursor = try moment.putCursor(hash.hashInt(repo_opts.hash, history_key)); 1010 const haxy_history = try DB.ArrayList(.read_write).init(haxy_history_cursor); 1011 1012 // add a new item to the haxy history list created above. 1013 // we call the item haxy_moments. it is a map of object id to haxy moment. 1014 // in other words, it maps each object id to a hash map containing the 1015 // state that the database was in when that object id was consumed. 1016 var haxy_moments_cursor = try haxy_history.appendCursor(); 1017 // use the previous haxy_moments as the basis for this one if it exists 1018 if (try haxy_history.getCursor(-2)) |last_haxy_moments_cursor| { 1019 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 1020 } 1021 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 1022 1023 var commit_iter = try CommitIterator(repo_kind, repo_opts).init(read_state, io, allocator, haxy_moments.readOnly(), ref); 1024 defer commit_iter.deinit(io, allocator); 1025 1026 // if there are no events to process, look at the oid at HEAD and update 1027 // the last_object_id to point to it. this is important in situations 1028 // where we do a merge and then force-push to remove the merge. see the 1029 // merge test for an example. 1030 if (commit_iter.newest_object_id == null) { 1031 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1032 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1033 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 1034 1035 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 1036 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 1037 1038 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, moment_index_key)) orelse return error.CursorNotFound; 1039 const moment_index = try moment_index_cursor.readUint(); 1040 1041 try haxy_history.slice(moment_index + 1); 1042 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = &head_oid }); 1043 return true; 1044 } 1045 1046 // if this branch was rebased and force pushed, we need to detect that and 1047 // properly revert the haxy state to the last valid state. we detect this 1048 // by simply asking if the last event is a descendent of the last event 1049 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 1050 if (last_object_id_maybe) |*last_object_id| { 1051 var is_rebased = false; 1052 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 1053 1054 _ = mrg.getDescendent( 1055 repo_kind, 1056 repo_opts, 1057 read_state, 1058 io, 1059 allocator, 1060 &std.fmt.bytesToHex(last_object_id, .lower), 1061 &std.fmt.bytesToHex(&newest_object_id, .lower), 1062 ) catch |err| switch (err) { 1063 error.DescendentNotFound => is_rebased = true, 1064 else => |e| return e, 1065 }; 1066 1067 if (is_rebased) { 1068 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 1069 var oldest_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 1070 defer oldest_object.deinit(); 1071 1072 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1073 switch (parent_oids.len) { 1074 0 => { 1075 // the branch was rebased all the way to the very beginning. 1076 // we have a repo event with no parent, which means it is now 1077 // the very first event. all we need to do is set the haxy 1078 // history list to be empty and make a new haxy_moments map 1079 // to work with. 1080 1081 try haxy_history.slice(0); 1082 haxy_moments_cursor = try haxy_history.appendCursor(); 1083 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 1084 1085 last_object_id_maybe = null; 1086 }, 1087 1 => { 1088 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1089 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 1090 1091 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 1092 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 1093 1094 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, moment_index_key)) orelse return error.CursorNotFound; 1095 const old_moment_index = try old_moment_index_cursor.readUint(); 1096 1097 // resize the haxy history list so we truncate all the 1098 // moments that were created after the parent_oid was consumed 1099 try haxy_history.slice(old_moment_index + 1); 1100 1101 // make a new haxy moment and set its initial value to the last haxy moment 1102 haxy_moments_cursor = try haxy_history.appendCursor(); 1103 const old_haxy_moments_cursor = try haxy_history.getCursor(old_moment_index) orelse return error.CursorNotFound; 1104 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 1105 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 1106 1107 last_object_id_maybe = oid; 1108 }, 1109 else => return error.UnexpectedParentCount, 1110 } 1111 } 1112 } 1113 1114 while (try commit_iter.next()) |repo_event_oid| { 1115 var commit_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 1116 defer commit_object.deinit(); 1117 1118 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1119 1120 // create a moment for this object id 1121 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 1122 1123 // if there was a previous object id, set this haxy moment's initial value to it. 1124 // this efficiently "clones" the map so we make further modifications based on it. 1125 if (parent_oids.len > 0) { 1126 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1127 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 1128 1129 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 1130 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 1131 } 1132 1133 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 1134 1135 // graph generation gives every event a causal order independent of 1136 // commit timestamps. concurrent events tie-break by id in their index. 1137 var event_order: u64 = 1; 1138 for (parent_oids) |*parent_oid| { 1139 var parent_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1140 _ = try std.fmt.hexToBytes(&parent_id, parent_oid); 1141 const parent_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &parent_id)) orelse return error.CursorNotFound; 1142 const parent = try DB.HashMap(.read_only).init(parent_cursor); 1143 const parent_order_cursor = try parent.getCursor(hash.hashInt(repo_opts.hash, event_order_key)) orelse return error.CursorNotFound; 1144 const parent_order = try parent_order_cursor.readUint(); 1145 event_order = @max(event_order, parent_order +| 1); 1146 } 1147 try haxy_moment.put(hash.hashInt(repo_opts.hash, event_order_key), .{ .uint = event_order }); 1148 1149 // merge changes from every parent after the first parent. the common 1150 // ancestor is the baseline, so a later parent only contributes records 1151 // it changed relative to the merge base. only the record maps are 1152 // merged; every other view is derived from them, and each kind's 1153 // `consume` re-derives its own as the winning records are written. 1154 if (parent_oids.len > 1) { 1155 for (parent_oids[1..]) |*parent_oid| { 1156 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1157 _ = try std.fmt.hexToBytes(&oid, parent_oid); 1158 1159 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 1160 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 1161 1162 const baseline_oid_hex = try mrg.commonAncestor(repo_kind, repo_opts, read_state, io, allocator, &parent_oids[0], parent_oid); 1163 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1164 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 1165 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 1166 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 1167 1168 inline for (@typeInfo(Event).@"union".field_types) |field_type| { 1169 const T = @typeInfo(field_type).optional.child; 1170 try merge(T, DB, repo_opts.hash, allocator, haxy_moment, parent_haxy_moment, baseline_haxy_moment); 1171 } 1172 } 1173 } 1174 1175 // associate this moment with the index it will first appear at in the 1176 // haxy history list. this will be important later so we can truncate 1177 // that list if the user ever rebases starting at this object id. 1178 const moment_index = try haxy_history.count() - 1; 1179 try haxy_moment.put(hash.hashInt(repo_opts.hash, moment_index_key), .{ .uint = moment_index }); 1180 1181 // consume the event unless it's a merge commit 1182 if (parent_oids.len <= 1) { 1183 var arena = std.heap.ArenaAllocator.init(allocator); 1184 defer arena.deinit(); 1185 1186 // read the message from the commit 1187 var message: std.ArrayList(u8) = .empty; 1188 try commit_object.readMessage(arena.allocator(), &message, .limited(max_event_size)); 1189 1190 const event_with_id = try EventWithId.fromString(&arena, message.items); 1191 if (!role.allows(std.meta.activeTag(event_with_id.event))) return error.EventKindNotAllowed; 1192 1193 const current_event_id = try parseEventId(&event_with_id.id); 1194 1195 // associate the transaction with the events it writes. this is 1196 // used by the undo tab to link the events that were affected 1197 // by a given transaction. 1198 { 1199 const sets = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, moment_index_to_event_id_set_key))); 1200 const ids = try DB.SortedSet(.read_write).init(try sets.putCursor(momentIndexKey(repo_opts.hash, moment_index))); 1201 try ids.put(&orderKeyDesc(event_order, &current_event_id)); 1202 } 1203 1204 // wrap the payload into the record `consume` stores, with its 1205 // commit-derived fields; on update, `consume` preserves the 1206 // existing record's 1207 switch (event_with_id.event) { 1208 .user => |event_maybe| { 1209 const record_maybe: ?User.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1210 try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1211 }, 1212 .repo => |event_maybe| { 1213 const record_maybe: ?Repo.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1214 try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1215 }, 1216 .fork => |event_maybe| { 1217 const record_maybe: ?Fork.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1218 try Fork.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1219 }, 1220 .grant => |event_maybe| { 1221 const record_maybe: ?Grant.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1222 try Grant.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1223 }, 1224 .discuss => |event_maybe| { 1225 const record_maybe: ?Discussion.Record = if (event_maybe) |event| .{ 1226 .event = event, 1227 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1228 .created_timestamp = commit_object.content.commit.metadata.timestamp, 1229 .created_order = event_order, 1230 .updated_order = event_order, 1231 } else null; 1232 try Discussion.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1233 }, 1234 .issue => |event_maybe| { 1235 const record_maybe: ?Issue.Record = if (event_maybe) |event| .{ 1236 .event = event, 1237 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1238 .created_timestamp = commit_object.content.commit.metadata.timestamp, 1239 .created_order = event_order, 1240 .updated_order = event_order, 1241 } else null; 1242 try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1243 }, 1244 .comment => |event_maybe| { 1245 const record_maybe: ?Comment.Record = if (event_maybe) |event| .{ 1246 .event = event, 1247 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1248 .created_timestamp = commit_object.content.commit.metadata.timestamp, 1249 .created_order = event_order, 1250 .updated_order = event_order, 1251 } else null; 1252 try Comment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1253 }, 1254 .attach => |event_maybe| { 1255 const record_maybe: ?Attachment.Record = if (event_maybe) |event| blk: { 1256 const entry = try attachedFile(repo_kind, repo_opts, read_state, io, allocator, &arena, &commit_object.content.commit.tree); 1257 break :blk .{ 1258 .event = event, 1259 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1260 .created_order = event_order, 1261 .updated_order = event_order, 1262 .name = entry.name, 1263 .blob_oid = entry.oid, 1264 }; 1265 } else null; 1266 try Attachment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1267 }, 1268 .assign => |event_maybe| { 1269 const record_maybe: ?Assignment.Record = if (event_maybe) |event| .{ 1270 .event = event, 1271 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1272 .created_order = event_order, 1273 .updated_order = event_order, 1274 } else null; 1275 try Assignment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1276 }, 1277 .patchrev => |event_maybe| { 1278 const record_maybe: ?PatchRev.Record = if (event_maybe) |event| blk: { 1279 const trees = try PatchRev.readTrees(repo_kind, repo_opts, read_state, io, allocator, &commit_object.content.commit.tree); 1280 const existing_maybe = try PatchRev.readById(DB, repo_opts.hash, haxy_moment.readOnly(), &arena, &current_event_id); 1281 const event_oid = std.fmt.bytesToHex(repo_event_oid, .lower); 1282 1283 var patch_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1284 if (existing_maybe) |existing| { 1285 if (existing.patch_oid.len != patch_oid.len) return error.InvalidPatch; 1286 @memcpy(&patch_oid, existing.patch_oid); 1287 } else { 1288 const author = try commitIdentity(commit_object.content.commit.metadata.author orelse return error.AuthorNotFound); 1289 const committer = try commitIdentity(commit_object.content.commit.metadata.committer orelse author); 1290 patch_oid = try PatchRev.writeSquashCommit( 1291 repo_kind, 1292 repo_opts, 1293 state, 1294 io, 1295 allocator, 1296 event, 1297 &trees.head, 1298 author, 1299 committer, 1300 commit_object.content.commit.metadata.timestamp, 1301 ); 1302 } 1303 1304 break :blk .{ 1305 .event = event, 1306 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1307 .created_order = event_order, 1308 .updated_order = event_order, 1309 .event_oid = &event_oid, 1310 .base_tree_oid = &trees.base, 1311 .head_tree_oid = &trees.head, 1312 .patch_oid = &patch_oid, 1313 .commit_count = PatchRev.commitCount(repo_kind, repo_opts, read_state, io, allocator, event.base_oid, event.source_oid) catch null, 1314 }; 1315 } else null; 1316 try PatchRev.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1317 }, 1318 .patch => |event_maybe| { 1319 const record_maybe: ?Patch.Record = if (event_maybe) |event| .{ 1320 .event = event, 1321 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1322 .created_timestamp = commit_object.content.commit.metadata.timestamp, 1323 .created_order = event_order, 1324 .updated_order = event_order, 1325 } else null; 1326 try Patch.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1327 }, 1328 } 1329 } 1330 1331 // the current object id is now the last one 1332 last_object_id_maybe = repo_event_oid; 1333 1334 // prevent any of the data created above from being mutated by future iterations of this loop 1335 try db.freeze(); 1336 } 1337 1338 if (last_object_id_maybe) |*last_object_id| { 1339 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = last_object_id }); 1340 } 1341 1342 return true; 1343 } 1344 1345 // the conflicted records of one kind, keyed by the same order key its id set 1346 // uses, so this doubles as the index the conflicts view lists and counts. every 1347 // value under an entry is a slot reference to a structure that already exists: 1348 // 1349 // <order key> -> conflict entry 1350 // conflicted-fields the conflicting field names, space separated 1351 // base-record the merge base's whole record 1352 // their-record the merged-in side's whole record 1353 // their-field->oid that side's field name to commit map 1354 // 1355 // our own value is the live record and our commit is in the kind's oid map, so 1356 // neither is repeated here. 1357 pub const conflicted_fields_key = "conflicted-fields"; 1358 pub const base_record_key = "base-record"; 1359 pub const their_record_key = "their-record"; 1360 pub const their_field_to_oid_key = "their-field->oid"; 1361 1362 // record the commit against every field this event changes. a merge passes no 1363 // oid, since each field's winner may come from a different side. 1364 pub fn writeOid( 1365 comptime T: type, 1366 comptime DB: type, 1367 comptime hash_kind: hash.HashKind, 1368 id_to_field_to_oid: DB.HashMap(.read_write), 1369 record_key: hash.HashInt(hash_kind), 1370 existing_maybe: ?T, 1371 event: T, 1372 event_oid: ?[]const u8, 1373 ) !void { 1374 const oid = event_oid orelse return; 1375 1376 // created only once a field actually changes 1377 var field_oids: ?DB.SortedMap(.read_write) = null; 1378 1379 const info = @typeInfo(T).@"struct"; 1380 inline for (info.field_names, info.field_types) |field_name, field_type| { 1381 const changed = if (existing_maybe) |existing| 1382 !fieldEqual(field_type, @field(existing, field_name), @field(event, field_name)) 1383 else 1384 true; 1385 if (changed) { 1386 if (field_oids == null) { 1387 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1388 } 1389 if (field_oids) |map| try map.put(field_name, .{ .bytes = oid }); 1390 } 1391 } 1392 } 1393 1394 // the whole field list, space separated, is the longest it can get 1395 fn conflictedFieldsMaxLen(comptime T: type) usize { 1396 var len: usize = 0; 1397 for (@typeInfo(T).@"struct".field_names) |name| len += name.len + 1; 1398 return len; 1399 } 1400 1401 pub const MergePolicy = enum { 1402 field_conflicts, 1403 target_wins, 1404 }; 1405 1406 // what a three-way merge did with a field 1407 pub const FieldMerge = enum { 1408 // the target's value stands, because neither side changed it, both made the 1409 // same change, or only the target changed it 1410 kept, 1411 parent, 1412 conflicted, 1413 }; 1414 1415 // three-way merge each field. one only the parent changed takes the parent's 1416 // value; one both sides changed differently keeps the target's. a missing 1417 // baseline makes every differing field a conflict. 1418 fn mergeFields( 1419 comptime T: type, 1420 baseline_maybe: ?T, 1421 target: T, 1422 parent: T, 1423 outcome: *[@typeInfo(T).@"struct".field_names.len]FieldMerge, 1424 ) T { 1425 var merged = target; 1426 1427 const info = @typeInfo(T).@"struct"; 1428 inline for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { 1429 const target_value = @field(target, field_name); 1430 const parent_value = @field(parent, field_name); 1431 1432 if (!fieldEqual(field_type, target_value, parent_value)) { 1433 outcome[i] = if (baseline_maybe) |baseline| blk: { 1434 const baseline_value = @field(baseline, field_name); 1435 if (fieldEqual(field_type, target_value, baseline_value)) { 1436 @field(merged, field_name) = parent_value; 1437 break :blk .parent; 1438 } 1439 // only the target changed it 1440 if (fieldEqual(field_type, parent_value, baseline_value)) break :blk .kept; 1441 break :blk .conflicted; 1442 } else .conflicted; 1443 } 1444 } 1445 1446 return merged; 1447 } 1448 1449 // three-way merge of one kind's records from a merge parent. kinds that expose 1450 // conflicts merge field by field; the others take one whole record. the result 1451 // goes through the kind's `consume`, which re-derives the indexes from it. a 1452 // removal carries over unless the other side changed the record, so a merge 1453 // never fails. 1454 pub fn merge( 1455 comptime T: type, 1456 comptime DB: type, 1457 comptime hash_kind: hash.HashKind, 1458 allocator: std.mem.Allocator, 1459 haxy_moment: DB.HashMap(.read_write), 1460 parent_moment: DB.HashMap(.read_only), 1461 baseline_moment: DB.HashMap(.read_only), 1462 ) !void { 1463 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.all_id_set_key)) orelse return; 1464 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1465 1466 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1467 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1468 1469 var baseline_records: ?DB.HashMap(.read_only) = null; 1470 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1471 baseline_records = try DB.HashMap(.read_only).init(cursor); 1472 } 1473 1474 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1475 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1476 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1477 switch (comptime T.merge_policy) { 1478 .field_conflicts => { 1479 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1480 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1481 } 1482 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1483 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1484 } 1485 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1486 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1487 } 1488 }, 1489 .target_wins => {}, 1490 } 1491 1492 var arena = std.heap.ArenaAllocator.init(allocator); 1493 defer arena.deinit(); 1494 1495 var iter = try parent_set.iteratorFromIndex(0); 1496 while (try iter.next()) |kv_pair_cursor| { 1497 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1498 const record_key = hash.hashInt(hash_kind, &event_id); 1499 1500 _ = arena.reset(.retain_capacity); 1501 1502 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1503 const parent_slot = parent_record_cursor.slot(); 1504 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1505 1506 // the parent left this record alone 1507 if (baseline_slot) |slot| { 1508 if (slot.eql(parent_slot)) continue; 1509 } 1510 1511 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1512 1513 // re-derived every iteration, since `consume` writes through its own 1514 // handles 1515 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1516 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1517 1518 // a record the target doesn't have arrives wholesale from the parent 1519 var outcome: [@typeInfo(T).@"struct".field_names.len]FieldMerge = @splat(.parent); 1520 var merged = parent_record; 1521 1522 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1523 // both sides share the change 1524 if (target_record_cursor.slot().eql(parent_slot)) continue; 1525 1526 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1527 1528 var baseline_record: ?T.Record = null; 1529 if (baseline_records) |map| { 1530 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1531 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1532 } 1533 } 1534 1535 switch (comptime T.merge_policy) { 1536 .field_conflicts => { 1537 outcome = @splat(.kept); 1538 merged = target_record; 1539 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1540 merged.updated_order = @max(target_record.updated_order, parent_record.updated_order); 1541 if (comptime @hasDecl(T, "resolveMerge")) { 1542 T.resolveMerge(target_record.event, parent_record.event, &merged.event, &outcome); 1543 } 1544 1545 // merge the removed state separately from serialized fields. removal 1546 // carries over an unchanged record, while an edit or restoration 1547 // keeps it active. 1548 merged.removed = if (target_record.removed == parent_record.removed) 1549 target_record.removed 1550 else if (baseline_record) |baseline| blk: { 1551 const active = if (!target_record.removed) target_record else parent_record; 1552 if (active.removed != baseline.removed) break :blk false; 1553 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1554 break :blk true; 1555 } else false; 1556 }, 1557 .target_wins => { 1558 // an uncontested parent change carries over. if both sides 1559 // changed the record, the target wins as a whole, except that 1560 // an edit or restoration wins over a removal. 1561 const target_changed = if (baseline_slot) |slot| 1562 !target_record_cursor.slot().eql(slot) 1563 else 1564 true; 1565 merged = if (!target_changed) 1566 parent_record 1567 else if (target_record.removed != parent_record.removed) 1568 if (target_record.removed) parent_record else target_record 1569 else 1570 target_record; 1571 }, 1572 } 1573 } 1574 1575 // the index is unique, so a key the target gave to a different record 1576 // leaves this one out rather than stranding that one behind a name it 1577 // no longer owns 1578 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1579 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1580 const name_index = try DB.SortedMap(.read_write).init(name_index_cursor); 1581 if (try name_index.getCursor(merged.event.name)) |owner_cursor| { 1582 var owner_id: [event_id_size]u8 = undefined; 1583 _ = try owner_cursor.readBytes(&owner_id); 1584 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1585 } 1586 } 1587 1588 // `consume` sets no oids, since each field's winner may come from 1589 // a different side 1590 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1591 1592 switch (comptime T.merge_policy) { 1593 .field_conflicts => {}, 1594 .target_wins => continue, 1595 } 1596 1597 // removed records do not carry field conflicts 1598 if (merged.removed) continue; 1599 1600 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1601 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1602 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1603 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1604 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1605 1606 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1607 if (parent_id_to_field_to_oid) |map| { 1608 if (try map.getCursor(record_key)) |field_oids_cursor| { 1609 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1610 } 1611 } 1612 // created only once a field actually comes from the parent 1613 var field_oids: ?DB.SortedMap(.read_write) = null; 1614 1615 // the fields both sides changed differently, space separated 1616 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1617 var conflicted_len: usize = 0; 1618 1619 inline for (@typeInfo(T).@"struct".field_names, 0..) |field_name, i| { 1620 switch (outcome[i]) { 1621 // the target's value stands, so its oid does too 1622 .kept => {}, 1623 // the parent set this value, so its commit takes the field. a 1624 // parent with no oid took its own value from a merge, leaving 1625 // the field unattributed rather than crediting the target's 1626 // commit for a value it no longer holds. 1627 .parent => { 1628 if (field_oids == null) { 1629 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1630 } 1631 const map = field_oids orelse unreachable; 1632 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field_name) else null; 1633 if (parent_oid) |oid_cursor| { 1634 try map.put(field_name, .{ .slot = oid_cursor.slot() }); 1635 } else { 1636 _ = try map.remove(field_name); 1637 } 1638 }, 1639 .conflicted => { 1640 if (conflicted_len > 0) { 1641 conflicted_fields[conflicted_len] = ' '; 1642 conflicted_len += 1; 1643 } 1644 @memcpy(conflicted_fields[conflicted_len..][0..field_name.len], field_name); 1645 conflicted_len += field_name.len; 1646 }, 1647 } 1648 } 1649 1650 if (conflicted_len > 0) { 1651 // each side's whole record is stored by reference, so the view can 1652 // show any of them or take theirs wholesale 1653 _ = try conflicts.remove(&merged_key); 1654 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1655 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1656 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1657 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1658 if (parent_field_oids) |map| { 1659 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1660 } 1661 continue; 1662 } 1663 1664 // created_order never changes, so the parent keys this record's conflict 1665 // identically, and it carries over when the target has none, unless the 1666 // parent's entry is unchanged from the baseline, meaning the target 1667 // inherited it too and resolving it removed it here. 1668 if (parent_conflicts) |map| { 1669 if (null == try conflicts.getCursor(&merged_key)) { 1670 if (try map.getSlot(&merged_key)) |conflict_slot| { 1671 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1672 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1673 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1674 } 1675 } 1676 } 1677 } 1678 } 1679 1680 // a comment, attachment or assignment a write names under a thread 1681 pub const ThreadChild = union(enum) { 1682 comment: *const [event_id_size]u8, 1683 attach: *const [event_id_size]u8, 1684 assign: *const [event_id_size]u8, 1685 }; 1686 1687 // whether `thread_id` names a thread of `thread_kind` in the repo's events, and 1688 // `child`, when given, belongs to it. a caller's url can claim any kind for any 1689 // id, so every write under a thread checks its claim here first. 1690 pub fn threadHolds( 1691 comptime repo_kind: rp.RepoKind, 1692 comptime repo_opts: rp.RepoOpts(repo_kind), 1693 io: std.Io, 1694 allocator: std.mem.Allocator, 1695 repo: *rp.Repo(repo_kind, repo_opts), 1696 thread_kind: EventKind, 1697 thread_id: *const [event_id_size]u8, 1698 child_maybe: ?ThreadChild, 1699 ) !bool { 1700 const DB = EventDB(repo_opts.hash); 1701 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 1702 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1703 const moment = (if (event_db_maybe) |*event_db| 1704 currentMomentFromDb(repo_opts.hash, event_db.db) 1705 else if (repo_kind == .git) 1706 return false 1707 else 1708 currentMoment(repo_opts, repo)) catch return false; 1709 1710 // only these kinds are threads 1711 switch (thread_kind) { 1712 .discuss, .issue, .patch => {}, 1713 else => return false, 1714 } 1715 const kinds_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, event_index_key)) orelse return false; 1716 const kinds = try DB.HashMap(.read_only).init(kinds_cursor); 1717 if ((try readEventKind(repo_opts.hash, kinds, thread_id)) != thread_kind) return false; 1718 1719 const child = child_maybe orelse return true; 1720 var arena = std.heap.ArenaAllocator.init(allocator); 1721 defer arena.deinit(); 1722 const thread_id_hex = std.fmt.bytesToHex(thread_id.*, .lower); 1723 switch (child) { 1724 .comment => |id| { 1725 const comment = (try readRecordSubset(Comment, struct { event: struct { thread_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1726 return std.mem.eql(u8, &comment.event.thread_id, &thread_id_hex); 1727 }, 1728 .attach => |id| { 1729 const attachment = (try readRecordSubset(Attachment, struct { event: struct { parent_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1730 return std.mem.eql(u8, &attachment.event.parent_id, &thread_id_hex); 1731 }, 1732 // only an active assignment can be removed 1733 .assign => |id| { 1734 const assignment = (try readRecordSubset(Assignment, struct { removed: bool, event: struct { thread_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1735 return !assignment.removed and std.mem.eql(u8, &assignment.event.thread_id, &thread_id_hex); 1736 }, 1737 } 1738 } 1739 1740 // remove an event a thread's page names: the thread itself, or a comment, 1741 // attachment or assignment, which must belong to it 1742 pub fn removeInThread( 1743 host: Host, 1744 comptime repo_kind: rp.RepoKind, 1745 comptime repo_opts: rp.RepoOpts(repo_kind), 1746 io: std.Io, 1747 allocator: std.mem.Allocator, 1748 repo: *rp.Repo(repo_kind, repo_opts), 1749 thread_kind: EventKind, 1750 thread_id: *const [event_id_size]u8, 1751 kind: EventKind, 1752 id: *const [event_id_size]u8, 1753 author: CommitAuthor, 1754 ) !void { 1755 const child_maybe: ?ThreadChild = switch (kind) { 1756 .comment => .{ .comment = id }, 1757 .attach => .{ .attach = id }, 1758 .assign => .{ .assign = id }, 1759 else => null, 1760 }; 1761 if (child_maybe) |child| { 1762 if (!try threadHolds(repo_kind, repo_opts, io, allocator, repo, thread_kind, thread_id, child)) return error.EventNotFound; 1763 } 1764 try remove(host, .repo, repo_kind, repo_opts, io, allocator, repo, id, kind, author); 1765 } 1766 1767 pub fn readFromRepo( 1768 comptime T: type, 1769 comptime repo_kind: rp.RepoKind, 1770 comptime repo_opts: rp.RepoOpts(repo_kind), 1771 io: std.Io, 1772 allocator: std.mem.Allocator, 1773 arena: *std.heap.ArenaAllocator, 1774 repo: *rp.Repo(repo_kind, repo_opts), 1775 id: *const [event_id_size]u8, 1776 ) !?T.Record { 1777 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 1778 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1779 const moment = (if (event_db_maybe) |*event_db| 1780 currentMomentFromDb(repo_opts.hash, event_db.db) 1781 else if (repo_kind == .git) 1782 return null 1783 else 1784 currentMoment(repo_opts, repo)) catch return null; 1785 return T.readById(EventDB(repo_opts.hash), repo_opts.hash, moment, arena, id); 1786 } 1787 1788 pub fn currentMoment( 1789 comptime repo_opts: rp.RepoOpts(.xit), 1790 repo: *rp.Repo(.xit, repo_opts), 1791 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1792 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1793 } 1794 1795 pub fn currentMomentFromDb( 1796 comptime hash_kind: hash.HashKind, 1797 db: *EventDB(hash_kind), 1798 ) !EventDB(hash_kind).HashMap(.read_only) { 1799 const DB = EventDB(hash_kind); 1800 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1801 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1802 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1803 return try currentMomentFromRepoMoment(hash_kind, moment); 1804 } 1805 1806 pub fn currentMomentFromRepoMoment( 1807 comptime hash_kind: hash.HashKind, 1808 moment: EventDB(hash_kind).HashMap(.read_only), 1809 ) !EventDB(hash_kind).HashMap(.read_only) { 1810 const DB = EventDB(hash_kind); 1811 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1812 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1813 _ = try last_object_id_cursor.readBytes(&last_object_id); 1814 const haxy_history_cursor = try moment.getCursor(hash.hashInt(hash_kind, history_key)) orelse return error.NotFound; 1815 const haxy_history = try DB.ArrayList(.read_only).init(haxy_history_cursor); 1816 const haxy_moments_cursor = try haxy_history.getCursor(-1) orelse return error.NotFound; 1817 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1818 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1819 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1820 } 1821 1822 // build a sorted-set key from an order and event id. big-endian order makes 1823 // byte order match numeric order; the event id breaks ties. 1824 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1825 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1826 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1827 @memcpy(key[@sizeOf(u64)..], event_id); 1828 return key; 1829 } 1830 1831 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1832 return orderKey(std.math.maxInt(u64) - order, event_id); 1833 } 1834 1835 pub fn removedRecord( 1836 comptime T: type, 1837 comptime DB: type, 1838 comptime hash_kind: hash.HashKind, 1839 haxy_moment: DB.HashMap(.read_only), 1840 existing_maybe: ?T, 1841 ) !T { 1842 var record = existing_maybe orelse return error.EventNotFound; 1843 record.removed = true; 1844 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1845 record.updated_order = try order_cursor.readUint(); 1846 return record; 1847 } 1848 1849 // add or refresh one entry in the global logical-event index 1850 pub fn indexEvent( 1851 comptime DB: type, 1852 comptime hash_kind: hash.HashKind, 1853 haxy_moment: DB.HashMap(.read_write), 1854 event_id: *const [event_id_size]u8, 1855 kind: EventKind, 1856 existing_maybe: anytype, 1857 record: anytype, 1858 ) !void { 1859 const event_key = hash.hashInt(hash_kind, event_id); 1860 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1861 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1862 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1863 1864 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1865 const active = try DB.SortedSet(.read_write).init(active_cursor); 1866 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1867 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1868 1869 if (existing_maybe) |existing| { 1870 const old_key = orderKeyDesc(existing.updated_order, event_id); 1871 _ = try active.remove(&old_key); 1872 _ = try removed_set.remove(&old_key); 1873 } 1874 1875 const order_key = orderKeyDesc(record.updated_order, event_id); 1876 if (record.removed) { 1877 try removed_set.put(&order_key); 1878 } else { 1879 try active.put(&order_key); 1880 } 1881 } 1882 1883 pub fn touchThread( 1884 comptime DB: type, 1885 comptime hash_kind: hash.HashKind, 1886 haxy_moment: DB.HashMap(.read_write), 1887 thread_id: *const [event_id_size]u8, 1888 order: u64, 1889 arena: *std.heap.ArenaAllocator, 1890 ) !void { 1891 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1892 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1893 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1894 switch (kind) { 1895 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1896 else => {}, 1897 } 1898 } 1899 1900 pub fn readEventKind( 1901 comptime hash_kind: hash.HashKind, 1902 kind_map: anytype, 1903 id: *const [event_id_size]u8, 1904 ) !?EventKind { 1905 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1906 var buffer: [64]u8 = undefined; 1907 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1908 } 1909 1910 // the email of the event's author, or null when the id names no authored event 1911 // of this kind 1912 pub fn readAuthorEmail( 1913 comptime repo_kind: rp.RepoKind, 1914 comptime repo_opts: rp.RepoOpts(repo_kind), 1915 io: std.Io, 1916 allocator: std.mem.Allocator, 1917 arena: *std.heap.ArenaAllocator, 1918 repo: *rp.Repo(repo_kind, repo_opts), 1919 kind: EventKind, 1920 id: *const [event_id_size]u8, 1921 ) !?[]const u8 { 1922 const record_map_key = switch (kind) { 1923 .discuss => Discussion.record_map_key, 1924 .issue => Issue.record_map_key, 1925 .comment => Comment.record_map_key, 1926 .attach => Attachment.record_map_key, 1927 .assign => Assignment.record_map_key, 1928 .patchrev => PatchRev.record_map_key, 1929 .patch => Patch.record_map_key, 1930 .user, .repo, .fork, .grant => return null, 1931 }; 1932 1933 const DB = EventDB(repo_opts.hash); 1934 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 1935 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1936 const moment = (if (event_db_maybe) |*event_db| 1937 currentMomentFromDb(repo_opts.hash, event_db.db) 1938 else if (repo_kind == .git) 1939 return null 1940 else 1941 currentMoment(repo_opts, repo)) catch return null; 1942 1943 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 1944 const records = try DB.HashMap(.read_only).init(records_cursor); 1945 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 1946 const record = try DB.HashMap(.read_only).init(record_cursor); 1947 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 1948 } 1949 1950 // the event id embedded in a set entry's order key 1951 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1952 var cursor = kv_pair_cursor; 1953 const kv_pair = try cursor.readKeyValuePair(); 1954 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1955 _ = try kv_pair.key_cursor.readBytes(&order_key); 1956 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1957 } 1958 1959 // split a pushed "<owner>:<repo>" path into its two components, or null if it 1960 // isn't exactly two non-empty parts with no "/". 1961 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1962 if (std.mem.indexOfScalar(u8, path, '/') != null) return null; 1963 var it = std.mem.splitScalar(u8, path, ':'); 1964 const owner = it.next() orelse return null; 1965 const name = it.next() orelse return null; 1966 if (it.next() != null) return null; 1967 if (owner.len == 0 or name.len == 0) return null; 1968 1969 return .{ .owner = owner, .name = name }; 1970 } 1971 1972 pub const CreateRepoOptions = struct { 1973 read_access: Repo.Access = .private, 1974 }; 1975 1976 // the ids that locate a repo's on-disk directory 1977 pub const RepoLocation = struct { 1978 owner_id: [event_id_size]u8, 1979 repo_id: [event_id_size]u8, 1980 }; 1981 1982 // resolve a pushed `<owner>:<repo>` to the ids that locate its on-disk directory 1983 pub fn resolveOrCreateRepo( 1984 io: std.Io, 1985 allocator: std.mem.Allocator, 1986 users_dir: []const u8, 1987 admin_repo_path: []const u8, 1988 owner_name: []const u8, 1989 repo_name: []const u8, 1990 create_options_maybe: ?CreateRepoOptions, 1991 ) !?RepoLocation { 1992 var admin_repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1993 error.RepoNotFound => return null, 1994 else => |e| return e, 1995 }; 1996 defer admin_repo.deinit(io, allocator); 1997 1998 var arena = std.heap.ArenaAllocator.init(allocator); 1999 defer arena.deinit(); 2000 2001 const admin_moment = try currentMoment(admin_repo_opts, &admin_repo); 2002 2003 // an unknown owner can't own a repo, so the push is rejected 2004 const owner_user_id = (try User.readIdByName(AdminDB, admin_repo_opts.hash, admin_moment, owner_name)) orelse return null; 2005 var user_repo = (try openUserRepo(io, allocator, users_dir, &owner_user_id)) orelse return null; 2006 defer user_repo.deinit(io, allocator); 2007 2008 // an already-registered repo reuses its event id, so a re-push (or a clone) 2009 // lands in the same repo 2010 if (try userMoment(&user_repo)) |moment| { 2011 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, repo_name)) |found| { 2012 return .{ .owner_id = owner_user_id, .repo_id = found.event_id }; 2013 } 2014 } 2015 2016 const create_options = create_options_maybe orelse return null; 2017 2018 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, admin_moment, &arena, &owner_user_id)) orelse unreachable; 2019 2020 var id_bytes: [event_id_size]u8 = undefined; 2021 io.random(&id_bytes); 2022 try writeRepoEvent(io, allocator, users_dir, &user_repo, &owner_user_id, .{ .name = owner.event.name, .email = owner.event.email }, &id_bytes, repo_name, "", create_options.read_access); 2023 return .{ .owner_id = owner_user_id, .repo_id = id_bytes }; 2024 } 2025 2026 // create a bare repo with `hash_kind` and register it in its owner's user repo 2027 pub fn createRepo( 2028 io: std.Io, 2029 allocator: std.mem.Allocator, 2030 users_dir: []const u8, 2031 owner_id: *const [event_id_size]u8, 2032 owner: CommitAuthor, 2033 name: []const u8, 2034 description: []const u8, 2035 read_access: Repo.Access, 2036 hash_kind: hash.HashKind, 2037 ) !RepoLocation { 2038 try Repo.validateName(name); 2039 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2040 defer user_repo.deinit(io, allocator); 2041 if (try userMoment(&user_repo)) |moment| { 2042 var arena = std.heap.ArenaAllocator.init(allocator); 2043 defer arena.deinit(); 2044 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name) != null) return error.NameTaken; 2045 } 2046 2047 var id_bytes: [event_id_size]u8 = undefined; 2048 io.random(&id_bytes); 2049 2050 // the directory comes first so a listed repo always has one 2051 { 2052 const path = try repoPath(allocator, users_dir, owner_id, &id_bytes); 2053 defer allocator.free(path); 2054 switch (hash_kind) { 2055 inline else => |kind| { 2056 var repo = try rp.Repo(.xit, .{ .hash = kind }).init(io, allocator, .{ .path = path, .bare = true }); 2057 defer repo.deinit(io, allocator); 2058 }, 2059 } 2060 } 2061 2062 try writeRepoEvent(io, allocator, users_dir, &user_repo, owner_id, owner, &id_bytes, name, description, read_access); 2063 return .{ .owner_id = owner_id.*, .repo_id = id_bytes }; 2064 } 2065 2066 // change the name, description, read access, and tab roles of the repo 2067 // named `old_name` in its owner's user repo 2068 pub fn updateRepo( 2069 io: std.Io, 2070 allocator: std.mem.Allocator, 2071 users_dir: []const u8, 2072 owner_id: *const [event_id_size]u8, 2073 author: CommitAuthor, 2074 old_name: []const u8, 2075 name: []const u8, 2076 description: []const u8, 2077 read_access: Repo.Access, 2078 discuss_role: ?Repo.Role, 2079 issue_role: ?Repo.Role, 2080 patch_role: ?Repo.Role, 2081 ) !void { 2082 try Repo.validateName(name); 2083 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2084 defer user_repo.deinit(io, allocator); 2085 var arena = std.heap.ArenaAllocator.init(allocator); 2086 defer arena.deinit(); 2087 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2088 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, old_name)) orelse return error.NotFound; 2089 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name)) |taken| { 2090 if (!std.mem.eql(u8, &taken.event_id, &found.event_id)) return error.NameTaken; 2091 } 2092 2093 var event = found.repo.event; 2094 event.name = name; 2095 event.description = description; 2096 event.read_access = read_access; 2097 event.discuss_role = discuss_role; 2098 event.issue_role = issue_role; 2099 event.patch_role = patch_role; 2100 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2101 .id = std.fmt.bytesToHex(found.event_id, .lower), 2102 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2103 .author = author, 2104 .event = .{ .repo = event }, 2105 }}); 2106 } 2107 2108 // grant `user_id` `role` on the repo `repo_id` in its owner's user repo, 2109 // replacing any role they held 2110 pub fn grantRole( 2111 io: std.Io, 2112 allocator: std.mem.Allocator, 2113 users_dir: []const u8, 2114 owner_id: *const [event_id_size]u8, 2115 repo_id: *const [event_id_size]u8, 2116 user_id: *const [event_id_size]u8, 2117 role: Repo.Role, 2118 author: CommitAuthor, 2119 ) !void { 2120 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2121 defer user_repo.deinit(io, allocator); 2122 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2123 .id = std.fmt.bytesToHex(Grant.idOf(repo_id, user_id), .lower), 2124 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2125 .author = author, 2126 .event = .{ .grant = .{ .target_id = repo_id, .user_id = user_id, .role = role } }, 2127 }}); 2128 } 2129 2130 // revoke `user_id`'s grant on the repo `repo_id` in its owner's user repo 2131 pub fn revokeRole( 2132 io: std.Io, 2133 allocator: std.mem.Allocator, 2134 users_dir: []const u8, 2135 owner_id: *const [event_id_size]u8, 2136 repo_id: *const [event_id_size]u8, 2137 user_id: *const [event_id_size]u8, 2138 author: CommitAuthor, 2139 ) !void { 2140 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2141 defer user_repo.deinit(io, allocator); 2142 // a revoked grant stays in the kind index, which is all `remove` checks 2143 { 2144 var arena = std.heap.ArenaAllocator.init(allocator); 2145 defer arena.deinit(); 2146 const moment = (try userMoment(&user_repo)) orelse return error.EventNotFound; 2147 if (try Grant.readRole(UserDB, user_repo_opts.hash, moment, &arena, repo_id, user_id) == null) return error.EventNotFound; 2148 } 2149 try remove(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, &Grant.idOf(repo_id, user_id), .grant, author); 2150 } 2151 2152 // create a user and their user repo, returning the new user's id 2153 pub fn createUser( 2154 io: std.Io, 2155 allocator: std.mem.Allocator, 2156 users_dir: []const u8, 2157 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2158 name: []const u8, 2159 email: []const u8, 2160 password: []const u8, 2161 password_again: []const u8, 2162 ) ![event_id_size]u8 { 2163 try User.validateName(name); 2164 if (email.len == 0) return error.EmailEmpty; 2165 if (password.len == 0) return error.PasswordEmpty; 2166 if (!std.mem.eql(u8, password, password_again)) return error.PasswordMismatch; 2167 // a fresh admin repo has no moment until its first event 2168 if (currentMoment(admin_repo_opts, admin_repo)) |moment| { 2169 if (try User.readIdByName(AdminDB, admin_repo_opts.hash, moment, name) != null) return error.NameTaken; 2170 var arena = std.heap.ArenaAllocator.init(allocator); 2171 defer arena.deinit(); 2172 if (try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2173 } else |err| switch (err) { 2174 error.NotFound => {}, 2175 else => |e| return e, 2176 } 2177 2178 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2179 const password_hash = try User.hashPassword(password, &password_hash_buf, io); 2180 2181 var id_bytes: [event_id_size]u8 = undefined; 2182 io.random(&id_bytes); 2183 2184 // the user repo comes first so a listed user can always create repos 2185 { 2186 const path = try userRepoPath(allocator, users_dir, &id_bytes); 2187 defer allocator.free(path); 2188 var user_repo = try initUserRepo(io, allocator, path); 2189 defer user_repo.deinit(io, allocator); 2190 } 2191 2192 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2193 .id = std.fmt.bytesToHex(id_bytes, .lower), 2194 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2195 .author = .{ .name = name, .email = email }, 2196 .event = .{ .user = .{ .name = name, .email = email, .password_hash = password_hash } }, 2197 }}); 2198 return id_bytes; 2199 } 2200 2201 // change a user's email, and their password when the password fields are 2202 // filled in 2203 pub fn updateUser( 2204 io: std.Io, 2205 allocator: std.mem.Allocator, 2206 users_dir: []const u8, 2207 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2208 user_id: *const [event_id_size]u8, 2209 email: []const u8, 2210 current_password: []const u8, 2211 new_password: []const u8, 2212 new_password_again: []const u8, 2213 ) !void { 2214 if (email.len == 0) return error.EmailEmpty; 2215 var arena = std.heap.ArenaAllocator.init(allocator); 2216 defer arena.deinit(); 2217 const moment = try currentMoment(admin_repo_opts, admin_repo); 2218 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2219 if (user.removed) return error.NotFound; 2220 if (!std.mem.eql(u8, email, user.event.email) and try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2221 2222 var event = user.event; 2223 event.email = email; 2224 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2225 if (current_password.len + new_password.len + new_password_again.len > 0) { 2226 if (!User.verifyPassword(user.event.password_hash, current_password)) return error.WrongPassword; 2227 if (new_password.len == 0) return error.PasswordEmpty; 2228 if (!std.mem.eql(u8, new_password, new_password_again)) return error.PasswordMismatch; 2229 event.password_hash = try User.hashPassword(new_password, &password_hash_buf, io); 2230 } 2231 2232 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2233 .id = std.fmt.bytesToHex(user_id.*, .lower), 2234 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2235 .author = .{ .name = event.name, .email = email }, 2236 .event = .{ .user = event }, 2237 }}); 2238 } 2239 2240 // consume a new repo's event into its owner's user repo and mark it active 2241 fn writeRepoEvent( 2242 io: std.Io, 2243 allocator: std.mem.Allocator, 2244 users_dir: []const u8, 2245 user_repo: *rp.Repo(.xit, user_repo_opts), 2246 owner_id: *const [event_id_size]u8, 2247 owner: CommitAuthor, 2248 id_bytes: *const [event_id_size]u8, 2249 name: []const u8, 2250 description: []const u8, 2251 read_access: Repo.Access, 2252 ) !void { 2253 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2254 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2255 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2256 .timestamp = timestamp, 2257 .author = owner, 2258 .event = .{ .repo = .{ 2259 .user_id = owner_id, 2260 .name = name, 2261 .description = description, 2262 .read_access = read_access, 2263 } }, 2264 }}); 2265 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2266 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2267 }; 2268 } 2269 2270 // 2271 // reading from xitdb 2272 // 2273 2274 // read just `Fields`, a subset of `T.Record`, from the record with event id 2275 // `id`, or null when there is none 2276 pub fn readRecordSubset( 2277 comptime T: type, 2278 comptime Fields: type, 2279 comptime DB: type, 2280 comptime hash_kind: hash.HashKind, 2281 haxy_moment: DB.HashMap(.read_only), 2282 arena: *std.heap.ArenaAllocator, 2283 id: []const u8, 2284 ) !?Fields { 2285 comptime assertFieldSubset(Fields, T.Record); 2286 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2287 const records = try DB.HashMap(.read_only).init(records_cursor); 2288 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2289 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2290 } 2291 2292 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2293 const info = @typeInfo(Sub).@"struct"; 2294 for (info.field_names, info.field_types) |field_name, field_type| { 2295 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2296 const FullField = @FieldType(Full, field_name); 2297 if (@typeInfo(field_type) == .@"struct") { 2298 assertFieldSubset(field_type, FullField); 2299 } else if (field_type != FullField) { 2300 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2301 } 2302 } 2303 } 2304 2305 pub fn read( 2306 comptime T: type, 2307 comptime DB: type, 2308 comptime hash_kind: hash.HashKind, 2309 arena: *std.heap.ArenaAllocator, 2310 map: DB.HashMap(.read_only), 2311 ) !T { 2312 var event: T = undefined; 2313 switch (@typeInfo(T)) { 2314 .@"struct" => |struct_info| { 2315 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2316 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2317 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2318 } 2319 }, 2320 else => @compileError("read expects a struct"), 2321 } 2322 return event; 2323 } 2324 2325 fn readField( 2326 comptime Field: type, 2327 comptime DB: type, 2328 comptime hash_kind: hash.HashKind, 2329 arena: *std.heap.ArenaAllocator, 2330 cursor_maybe: ?DB.Cursor(.read_only), 2331 ) !Field { 2332 if (@typeInfo(Field) == .optional) { 2333 // a missing key or a null union payload is null 2334 const cursor = cursor_maybe orelse return null; 2335 if (cursor.slot().tag == .none) return null; 2336 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2337 } 2338 const cursor = cursor_maybe orelse return error.NotFound; 2339 switch (@typeInfo(Field)) { 2340 .pointer => |pointer_info| { 2341 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2342 @compileError("unsupported read field type: " ++ @typeName(Field)); 2343 } 2344 return try cursor.readBytesAlloc(arena.allocator(), null); 2345 }, 2346 .array => |array_info| { 2347 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2348 var bytes: Field = undefined; 2349 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2350 return bytes; 2351 }, 2352 .bool => { 2353 var buffer: [5]u8 = undefined; 2354 const bytes = try cursor.readBytesObject(&buffer); 2355 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2356 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2357 if (std.mem.eql(u8, bytes.value, "true")) return true; 2358 if (std.mem.eql(u8, bytes.value, "false")) return false; 2359 return error.InvalidBool; 2360 }, 2361 .int => |int_info| return switch (int_info.signedness) { 2362 .unsigned => @intCast(try cursor.readUint()), 2363 .signed => @intCast(try cursor.readInt()), 2364 }, 2365 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2366 .@"union" => |union_info| { 2367 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2368 switch (cursor.slot().tag) { 2369 .bytes, .short_bytes => { 2370 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2371 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2372 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2373 return @unionInit(Field, variant_name, {}); 2374 } 2375 } 2376 return error.InvalidUnion; 2377 }, 2378 .hash_map => { 2379 const variants = try DB.HashMap(.read_only).init(cursor); 2380 var iter = try variants.iterator(); 2381 const entry = (try iter.next()) orelse return error.InvalidUnion; 2382 const pair = try entry.readKeyValuePair(); 2383 if (try iter.next() != null) return error.InvalidUnion; 2384 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2385 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2386 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2387 } 2388 } 2389 return error.InvalidUnion; 2390 }, 2391 else => return error.InvalidUnion, 2392 } 2393 }, 2394 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2395 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2396 } 2397 } 2398 2399 // whether two events carry the same data 2400 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2401 switch (@typeInfo(T)) { 2402 .@"struct" => |struct_info| { 2403 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2404 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2405 } 2406 }, 2407 else => @compileError("fieldsEqual expects a struct"), 2408 } 2409 2410 return true; 2411 } 2412 2413 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2414 switch (@typeInfo(Field)) { 2415 .pointer => |pointer_info| { 2416 if (pointer_info.size == .slice and pointer_info.child == u8) { 2417 return std.mem.eql(u8, a, b); 2418 } else { 2419 @compileError("unsupported field type: " ++ @typeName(Field)); 2420 } 2421 }, 2422 .array => |array_info| { 2423 if (array_info.child == u8) { 2424 return std.mem.eql(u8, &a, &b); 2425 } else { 2426 @compileError("unsupported field type: " ++ @typeName(Field)); 2427 } 2428 }, 2429 .void => return true, 2430 .bool, .int, .@"enum" => return a == b, 2431 .@"union" => { 2432 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2433 return switch (a) { 2434 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2435 }; 2436 }, 2437 .@"struct" => return fieldsEqual(Field, a, b), 2438 .optional => |optional_info| { 2439 if (a) |a_value| { 2440 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2441 return false; 2442 } 2443 return b == null; 2444 }, 2445 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2446 } 2447 } 2448 2449 // 2450 // writing to xitdb 2451 // 2452 2453 pub fn upsert( 2454 comptime T: type, 2455 comptime DB: type, 2456 comptime hash_kind: hash.HashKind, 2457 map: DB.HashMap(.read_write), 2458 event: T, 2459 ) !void { 2460 switch (@typeInfo(T)) { 2461 .@"struct" => |struct_info| { 2462 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2463 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2464 } 2465 }, 2466 else => @compileError("upsert expects a struct"), 2467 } 2468 } 2469 2470 fn upsertField( 2471 comptime DB: type, 2472 comptime hash_kind: hash.HashKind, 2473 map: DB.HashMap(.read_write), 2474 comptime field_name: []const u8, 2475 comptime Field: type, 2476 value: Field, 2477 ) !void { 2478 const key = hash.hashInt(hash_kind, field_name); 2479 2480 switch (@typeInfo(Field)) { 2481 .pointer => |pointer_info| { 2482 if (pointer_info.size == .slice and pointer_info.child == u8) { 2483 try upsertBytes(DB, hash_kind, map, key, value); 2484 } else { 2485 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2486 } 2487 }, 2488 .array => |array_info| { 2489 if (array_info.child == u8) { 2490 try upsertBytes(DB, hash_kind, map, key, &value); 2491 } else { 2492 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2493 } 2494 }, 2495 .int => |int_info| switch (int_info.signedness) { 2496 .unsigned => { 2497 if (try map.getCursor(key)) |value_cursor| { 2498 if (try value_cursor.readUint() == value) { 2499 return; 2500 } 2501 } 2502 2503 try map.put(key, .{ .uint = value }); 2504 }, 2505 .signed => { 2506 if (try map.getCursor(key)) |value_cursor| { 2507 if (try value_cursor.readInt() == value) { 2508 return; 2509 } 2510 } 2511 2512 try map.put(key, .{ .int = value }); 2513 }, 2514 }, 2515 .bool => { 2516 const bytes = if (value) "true" else "false"; 2517 if (try map.getCursor(key)) |value_cursor| { 2518 var buffer: [5]u8 = undefined; 2519 const existing = try value_cursor.readBytesObject(&buffer); 2520 if (existing.format_tag) |format_tag| { 2521 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2522 return; 2523 } 2524 } 2525 } 2526 2527 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2528 }, 2529 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2530 .@"union" => switch (value) { 2531 inline else => |payload, tag| { 2532 if (@TypeOf(payload) == void) { 2533 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2534 } else { 2535 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2536 if (try map.getCursor(key)) |cursor| { 2537 switch (cursor.slot().tag) { 2538 .hash_map => { 2539 const variants = try DB.HashMap(.read_only).init(cursor); 2540 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2541 }, 2542 else => try map.put(key, .{ .slot = null }), 2543 } 2544 } 2545 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2546 if (@typeInfo(@TypeOf(payload)) == .optional) { 2547 // keep the variant even when its payload is null 2548 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2549 } 2550 if (try variants.getCursor(tag_key)) |cursor| { 2551 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2552 } 2553 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2554 } 2555 }, 2556 }, 2557 .optional => |optional_info| { 2558 // a missing key is null 2559 if (value) |child| { 2560 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2561 } else { 2562 _ = try map.remove(key); 2563 } 2564 }, 2565 .@"struct" => try upsert( 2566 Field, 2567 DB, 2568 hash_kind, 2569 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2570 value, 2571 ), 2572 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2573 } 2574 } 2575 2576 fn upsertBytes( 2577 comptime DB: type, 2578 comptime hash_kind: hash.HashKind, 2579 map: DB.HashMap(.read_write), 2580 key: hash.HashInt(hash_kind), 2581 value: []const u8, 2582 ) !void { 2583 var existing_cursor_maybe = try map.getCursor(key); 2584 if (existing_cursor_maybe) |*existing_cursor| { 2585 if (try bytesEqual(DB, existing_cursor, value)) { 2586 return; 2587 } 2588 } 2589 2590 try map.put(key, .{ .bytes = value }); 2591 } 2592 2593 fn bytesEqual( 2594 comptime DB: type, 2595 cursor: *DB.Cursor(.read_only), 2596 value: []const u8, 2597 ) !bool { 2598 switch (cursor.slot().tag) { 2599 .bytes, .short_bytes => {}, 2600 else => return false, 2601 } 2602 var read_buffer: [1024]u8 = undefined; 2603 var reader = try cursor.reader(&read_buffer); 2604 if (reader.size != value.len) { 2605 return false; 2606 } 2607 2608 var chunk_buffer: [1024]u8 = undefined; 2609 var offset: usize = 0; 2610 while (offset < value.len) { 2611 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2612 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2613 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2614 return false; 2615 } 2616 offset += chunk_len; 2617 } 2618 2619 return true; 2620 } 2621 2622 // 2623 // CommitIterator 2624 // 2625 // differs from xit's ObjectIterator in a few ways: 2626 // 2627 // 1. iterates parents first, rather than children first 2628 // 2. `next` only returns the object id, not the full Object 2629 // 3. stores its temporary state in a file on disk to avoid OOMs 2630 // 2631 2632 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2633 return struct { 2634 const DB = EventDB(repo_opts.hash); 2635 // a plain file is used for the scratch db because each write outside 2636 // a transaction is synced anyway, so buffering would gain nothing 2637 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2638 const db_name = "haxy-repo-events.db"; 2639 2640 repo_dir: std.Io.Dir, 2641 db_file: std.Io.File, 2642 db: *TempDB, 2643 // map of each object id to its children 2644 parent_to_children: TempDB.HashMap(.read_write), 2645 // tracking pending parents is necessary because a child can only 2646 // be returned after all of its unconsumed parents have been returned 2647 child_to_pending_parents: TempDB.HashMap(.read_write), 2648 // queue of object ids that are ready to be returned from `next` 2649 ready_queue: TempDB.ArrayList(.read_write), 2650 ready_queue_index: u64, 2651 // the object id at the tip of this branch 2652 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2653 // the object id furthest back in the history that hasn't been consumed 2654 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2655 2656 pub fn init( 2657 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2658 io: std.Io, 2659 allocator: std.mem.Allocator, 2660 consumed_object_ids: DB.HashMap(.read_only), 2661 ref: rf.Ref, 2662 ) !CommitIterator(repo_kind, repo_opts) { 2663 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2664 errdefer { 2665 db_file.close(io); 2666 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2667 } 2668 2669 // cursors point at the db, so it needs a stable address 2670 const db_ptr = try allocator.create(TempDB); 2671 errdefer allocator.destroy(db_ptr); 2672 // the db is scratch state that gets deleted after iteration, so 2673 // there is nothing worth fsyncing 2674 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2675 2676 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2677 2678 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2679 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2680 2681 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2682 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2683 2684 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2685 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2686 2687 var self = CommitIterator(repo_kind, repo_opts){ 2688 .repo_dir = state.core.repo_dir, 2689 .db_file = db_file, 2690 .db = db_ptr, 2691 .parent_to_children = parent_to_children, 2692 .child_to_pending_parents = child_to_pending_parents, 2693 .ready_queue = ready_queue, 2694 .ready_queue_index = 0, 2695 .newest_object_id = null, 2696 .oldest_object_id = null, 2697 }; 2698 errdefer self.deinit(io, allocator); 2699 2700 try self.collect(state, io, allocator, consumed_object_ids, ref); 2701 2702 return self; 2703 } 2704 2705 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2706 self.db_file.close(io); 2707 self.repo_dir.deleteFile(io, db_name) catch {}; 2708 allocator.destroy(self.db); 2709 } 2710 2711 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2712 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2713 2714 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2715 self.ready_queue_index += 1; 2716 2717 try self.enqueueChildren(&oid); 2718 return oid; 2719 } 2720 2721 fn collect( 2722 self: *CommitIterator(repo_kind, repo_opts), 2723 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2724 io: std.Io, 2725 allocator: std.mem.Allocator, 2726 consumed_object_ids: DB.HashMap(.read_only), 2727 ref: rf.Ref, 2728 ) !void { 2729 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2730 2731 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2732 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2733 var walk_queue_index: u64 = 0; 2734 2735 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2736 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2737 2738 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2739 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2740 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2741 try walk_queue.append(.{ .bytes = &head_oid }); 2742 2743 while (walk_queue_index < try walk_queue.count()) { 2744 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2745 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2746 2747 walk_queue_index += 1; 2748 2749 // if we've seen this object id, skip it 2750 if (null != try seen_object_ids.getCursor(oid_int)) { 2751 continue; 2752 } 2753 2754 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2755 2756 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2757 defer commit_object.deinit(); 2758 2759 // if this object id has already been consumed, skip it 2760 if (null != try consumed_object_ids.getCursor(oid_int)) { 2761 continue; 2762 } 2763 2764 if (self.newest_object_id == null) self.newest_object_id = oid; 2765 self.oldest_object_id = oid; 2766 2767 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2768 var pending_parent_count: u64 = 0; 2769 for (parent_oids) |*parent_oid| { 2770 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2771 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2772 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2773 2774 // if this object id has already been consumed, skip it 2775 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2776 continue; 2777 } 2778 2779 // if this object id hasn't already been seen, add it to the walk queue 2780 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2781 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2782 } 2783 2784 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2785 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2786 try children.put(oid_int, .{ .bytes = &oid }); 2787 pending_parent_count += 1; 2788 } 2789 2790 if (pending_parent_count == 0) { 2791 try self.ready_queue.append(.{ .bytes = &oid }); 2792 } else { 2793 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2794 } 2795 } 2796 } 2797 2798 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2799 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2800 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2801 const children = try TempDB.HashSet(.read_only).init(children_cursor); 2802 var children_iter = try children.iterator(); 2803 2804 while (try children_iter.next()) |*child_cursor| { 2805 const kv_pair = try child_cursor.readKeyValuePair(); 2806 const child_oid_int = kv_pair.hash; 2807 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2808 const pending_parent_count = try pending_parent_cursor.readUint(); 2809 2810 if (pending_parent_count <= 1) { 2811 _ = try self.child_to_pending_parents.remove(child_oid_int); 2812 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2813 try self.ready_queue.append(.{ .bytes = &child_oid }); 2814 } else { 2815 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2816 } 2817 } 2818 } 2819 2820 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2821 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2822 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2823 _ = try oid_cursor.readBytes(&oid); 2824 return oid; 2825 } 2826 }; 2827 } 2828