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