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