╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const hash = xit.hash; 5 const mrg = xit.merge; 6 const obj = xit.object; 7 const rf = xit.ref; 8 const pch = @import("patch.zig"); 9 10 pub const User = @import("event/User.zig"); 11 pub const Repo = @import("event/Repo.zig"); 12 pub const Fork = @import("event/Fork.zig"); 13 pub const Issue = @import("event/Issue.zig"); 14 pub const Discussion = @import("event/Discussion.zig"); 15 pub const Comment = @import("event/Comment.zig"); 16 pub const Attachment = @import("event/Attachment.zig"); 17 pub const Patch = @import("event/Patch.zig"); 18 pub const PatchRev = @import("event/PatchRev.zig"); 19 20 // the most bytes an event's serialized form may hold 21 pub const max_event_size: usize = 100 * 1024; 22 23 // the branch haxy events are committed to before being consumed 24 pub const events_ref: rf.Ref = .{ .kind = .head, .name = "haxy/events" }; 25 26 pub const history_key = "haxy/history"; 27 pub const last_object_id_key = "haxy/last-object-id"; 28 29 // options + db type for the admin repo 30 pub const admin_repo_opts: rp.RepoOpts(.xit) = .{}; 31 pub const AdminDB = rp.Repo(.xit, admin_repo_opts).DB; 32 33 // the admin repo's file the home page renders 34 pub const admin_about_path = "ABOUT.md"; 35 36 // create the admin repo with a master branch holding the default about page. 37 // pushes to master update its work dir. 38 pub fn initAdminRepo(io: std.Io, allocator: std.mem.Allocator, path: []const u8) !rp.Repo(.xit, admin_repo_opts) { 39 var repo = try rp.Repo(.xit, admin_repo_opts).init(io, allocator, .{ .path = path }); 40 errdefer repo.deinit(io, allocator); 41 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateInstead" }); 42 { 43 const file = try repo.core.work_dir.createFile(io, admin_about_path, .{}); 44 defer file.close(io); 45 try file.writeStreamingAll(io, "# HAXY\n\nWelcome to your Haxy instance!\n\nEdit `admin/ABOUT.md` in the server dir to change what this page says."); 46 } 47 try repo.add(io, allocator, &.{admin_about_path}); 48 _ = try repo.commit(io, allocator, .{ .author = "haxy <haxy@localhost>", .message = "init" }); 49 return repo; 50 } 51 52 // the xitdb type events are stored in. it only depends on the hash kind, so 53 // this matches the db of any xit repo using that hash kind. 54 pub fn EventDB(comptime hash_kind: hash.HashKind) type { 55 return rp.Repo(.xit, .{ .hash = hash_kind }).DB; 56 } 57 58 // the email between a commit author line's angle brackets, or null 59 pub fn authorEmail(author_line: []const u8) ?[]const u8 { 60 const open_bracket = std.mem.indexOfScalar(u8, author_line, '<') orelse return null; 61 const close_bracket = std.mem.indexOfScalarPos(u8, author_line, open_bracket + 1, '>') orelse return null; 62 return author_line[open_bracket + 1 .. close_bracket]; 63 } 64 65 // build a `T` by copying its fields, by name, out of `source` 66 pub fn project(comptime T: type, source: anytype) T { 67 var result: T = undefined; 68 inline for (std.meta.fields(T)) |field| { 69 @field(result, field.name) = @field(source, field.name); 70 } 71 return result; 72 } 73 74 pub const EventKind = enum { 75 user, 76 repo, 77 fork, 78 issue, 79 discuss, 80 comment, 81 attach, 82 patchrev, 83 patch, 84 }; 85 86 pub const RepoRole = enum { 87 admin, 88 repo, 89 fork, 90 91 fn allows(self: RepoRole, kind: EventKind) bool { 92 return switch (self) { 93 .admin => switch (kind) { 94 .user, .repo, .fork => true, 95 else => false, 96 }, 97 .repo => switch (kind) { 98 .issue, .discuss, .comment, .attach, .patchrev, .patch => true, 99 else => false, 100 }, 101 .fork => switch (kind) { 102 .patchrev, .patch => true, 103 else => false, 104 }, 105 }; 106 } 107 }; 108 109 // every logical event's kind and update-ordered active/removed id sets 110 pub const event_index_key = "event-id->kind"; 111 pub const active_event_id_set_key = "active-event-id-set"; 112 pub const removed_event_id_set_key = "removed-event-id-set"; 113 const event_order_key = "event-order"; 114 115 pub fn titleValid(title: []const u8) bool { 116 return std.mem.trim(u8, title, " \t\r\n").len != 0; 117 } 118 119 // a null payload removes the record 120 pub const Event = union(EventKind) { 121 user: ?User, 122 repo: ?Repo, 123 fork: ?Fork, 124 issue: ?Issue, 125 discuss: ?Discussion, 126 comment: ?Comment, 127 attach: ?Attachment, 128 patchrev: ?PatchRev, 129 patch: ?Patch, 130 }; 131 132 // a file committed alongside its event 133 pub const Blob = struct { 134 name: []const u8, 135 size: u64, 136 reader: *std.Io.Reader, 137 }; 138 139 // an entry in the fresh tree carried by one event commit 140 pub const EventTreeEntry = union(enum) { 141 blob: Blob, 142 tree: struct { 143 name: []const u8, 144 oid: []const u8, 145 }, 146 }; 147 148 pub const HostKind = enum { 149 local, 150 server, 151 }; 152 153 // who a commit is attributed to 154 pub const CommitAuthor = struct { 155 name: []const u8, 156 email: []const u8, 157 }; 158 159 pub const event_id_size: usize = 16; 160 161 pub fn parseEventId(id: []const u8) ![event_id_size]u8 { 162 var bytes: [event_id_size]u8 = undefined; 163 _ = try std.fmt.hexToBytes(&bytes, id); 164 if (!std.mem.eql(u8, id, &std.fmt.bytesToHex(bytes, .lower))) return error.InvalidEventId; 165 return bytes; 166 } 167 168 pub const EventWithId = struct { 169 id: [event_id_size * 2]u8, 170 event: Event, 171 timestamp: u64 = 0, // not serialized, because it comes from the commit timestamp 172 author: CommitAuthor, // not serialized, because it goes in the commit author line 173 tree_entries: []const EventTreeEntry = &.{}, // not serialized, because they go in the commit tree 174 175 pub fn jsonStringify(self: EventWithId, jw: anytype) !void { 176 try jw.beginObject(); 177 try jw.objectField("id"); 178 try jw.write(self.id); 179 try jw.objectField("kind"); 180 try jw.write(@tagName(self.event)); 181 try jw.objectField("data"); 182 switch (self.event) { 183 inline else => |event_maybe| try jw.write(event_maybe), 184 } 185 try jw.endObject(); 186 } 187 188 fn fromString(arena: *std.heap.ArenaAllocator, message: []const u8) !EventWithId { 189 const JsonEvent = struct { 190 id: [event_id_size * 2]u8, 191 kind: EventKind, 192 data: ?std.json.Value = null, 193 }; 194 const json_event = try std.json.parseFromSliceLeaky(JsonEvent, arena.allocator(), message, .{ .ignore_unknown_fields = true }); 195 return .{ 196 .id = json_event.id, 197 // unused when reading; the author lives in the commit 198 .author = .{ .name = "", .email = "" }, 199 .event = switch (json_event.kind) { 200 .user => .{ 201 .user = if (json_event.data) |value| 202 try std.json.parseFromValueLeaky(User, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 203 else 204 null, 205 }, 206 .repo => .{ 207 .repo = if (json_event.data) |value| 208 try std.json.parseFromValueLeaky(Repo, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 209 else 210 null, 211 }, 212 .fork => .{ 213 .fork = if (json_event.data) |value| 214 try std.json.parseFromValueLeaky(Fork, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 215 else 216 null, 217 }, 218 .issue => .{ 219 .issue = if (json_event.data) |value| 220 try std.json.parseFromValueLeaky(Issue, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 221 else 222 null, 223 }, 224 .discuss => .{ 225 .discuss = if (json_event.data) |value| 226 try std.json.parseFromValueLeaky(Discussion, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 227 else 228 null, 229 }, 230 .comment => .{ 231 .comment = if (json_event.data) |value| 232 try std.json.parseFromValueLeaky(Comment, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 233 else 234 null, 235 }, 236 .attach => .{ 237 .attach = if (json_event.data) |value| 238 try std.json.parseFromValueLeaky(Attachment, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 239 else 240 null, 241 }, 242 .patch => .{ 243 .patch = if (json_event.data) |value| 244 try std.json.parseFromValueLeaky(Patch, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 245 else 246 null, 247 }, 248 .patchrev => .{ 249 .patchrev = if (json_event.data) |value| 250 try std.json.parseFromValueLeaky(PatchRev, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 251 else 252 null, 253 }, 254 }, 255 }; 256 } 257 258 pub fn randomId(random: std.Random) [event_id_size]u8 { 259 var id_bytes: [event_id_size]u8 = undefined; 260 random.bytes(&id_bytes); 261 return id_bytes; 262 } 263 }; 264 265 // remove an event by emitting a null payload 266 pub fn remove( 267 host_kind: HostKind, 268 comptime role: RepoRole, 269 comptime repo_kind: rp.RepoKind, 270 comptime repo_opts: rp.RepoOpts(repo_kind), 271 io: std.Io, 272 allocator: std.mem.Allocator, 273 repo: *rp.Repo(repo_kind, repo_opts), 274 id: *const [event_id_size]u8, 275 kind: EventKind, 276 author: CommitAuthor, 277 ) !void { 278 const DB = EventDB(repo_opts.hash); 279 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; 280 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 281 const moment = (if (event_db_maybe) |*event_db| 282 currentMomentFromDb(repo_opts.hash, event_db.db) 283 else if (repo_kind == .git) 284 return error.EventNotFound 285 else 286 currentMoment(repo_opts, repo)) catch return error.EventNotFound; 287 const kind_map_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, event_index_key)) orelse return error.EventNotFound; 288 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 289 const stored_kind = (try readEventKind(repo_opts.hash, kind_map, id)) orelse return error.EventNotFound; 290 if (stored_kind != kind) return error.EventNotFound; 291 if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 292 event_db_maybe = null; 293 294 const event: Event = switch (kind) { 295 .user => .{ .user = null }, 296 .repo => .{ .repo = null }, 297 .fork => .{ .fork = null }, 298 .issue => .{ .issue = null }, 299 .discuss => .{ .discuss = null }, 300 .comment => .{ .comment = null }, 301 .attach => .{ .attach = null }, 302 .patchrev => .{ .patchrev = null }, 303 .patch => .{ .patch = null }, 304 }; 305 try consume(host_kind, role, repo_kind, repo_opts, io, allocator, repo, events_ref, &.{.{ 306 .id = std.fmt.bytesToHex(id.*, .lower), 307 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 308 .author = author, 309 .event = event, 310 }}); 311 } 312 313 pub const undo_action = "haxy/events"; 314 pub const merge_undo_action = "haxy/merge-events"; 315 316 // index that tracks the events consumed in a given haxy moment 317 pub const moment_index_to_event_id_set_key = "moment-index->event-id-set"; 318 319 // a haxy moment's own position in the haxy history 320 pub const moment_index_key = "moment-index"; 321 322 // a moment's key in the set map 323 fn momentIndexKey(comptime hash_kind: hash.HashKind, moment_index: u64) hash.HashInt(hash_kind) { 324 var buffer: [@sizeOf(u64)]u8 = undefined; 325 std.mem.writeInt(u64, &buffer, moment_index, .big); 326 return hash.hashInt(hash_kind, &buffer); 327 } 328 329 // the ids of the events a moment wrote, newest first, or null when it wrote none 330 pub fn momentEventIds( 331 comptime DB: type, 332 comptime hash_kind: hash.HashKind, 333 haxy_moment: DB.HashMap(.read_only), 334 moment_index: u64, 335 ) !?DB.SortedSet(.read_only) { 336 const sets_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, moment_index_to_event_id_set_key)) orelse return null; 337 const sets = try DB.HashMap(.read_only).init(sets_cursor); 338 const ids_cursor = try sets.getCursor(momentIndexKey(hash_kind, moment_index)) orelse return null; 339 return try DB.SortedSet(.read_only).init(ids_cursor); 340 } 341 342 // commit `events` (if any) as JSON commit messages on `ref`, then consume the 343 // events on `ref` into the db the repo's views read: the repo's own db for a 344 // xit repo, or the standalone event db next to a git repo. for a xit repo the 345 // commits and the consume run in one transaction, which also saves the 346 // mergeability of the patches the events touched. 347 pub fn consume( 348 host_kind: HostKind, 349 comptime role: RepoRole, 350 comptime repo_kind: rp.RepoKind, 351 comptime repo_opts: rp.RepoOpts(repo_kind), 352 io: std.Io, 353 allocator: std.mem.Allocator, 354 repo: *rp.Repo(repo_kind, repo_opts), 355 ref: rf.Ref, 356 events: []const EventWithId, 357 ) !void { 358 for (events) |event| { 359 if (!role.allows(std.meta.activeTag(event.event))) return error.EventKindNotAllowed; 360 } 361 362 var resolved_remote_name: ?[]u8 = null; 363 defer if (resolved_remote_name) |name| allocator.free(name); 364 365 // a branch that only exists on a remote is consumed from its remote-tracking 366 // ref, while commits go on the local branch, continuing from the remote tip 367 // so a cloned repo's local branch stays connected to the server history 368 const resolved_ref: rf.Ref, const first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8 = blk: { 369 if (null != try repo.readRef(io, ref)) break :blk .{ ref, null }; 370 var remotes = try repo.listRemotes(io, allocator); 371 defer remotes.deinit(); 372 for (remotes.sections.keys()) |remote_name| { 373 const remote_ref: rf.Ref = .{ .kind = .{ .remote = remote_name }, .name = ref.name }; 374 if (try repo.readRef(io, remote_ref)) |oid| { 375 if (events.len > 0) break :blk .{ ref, .{oid} }; 376 const name = try allocator.dupe(u8, remote_name); 377 resolved_remote_name = name; 378 break :blk .{ rf.Ref{ .kind = .{ .remote = name }, .name = ref.name }, null }; 379 } 380 } 381 if (events.len > 0) break :blk .{ ref, null }; 382 // the branch is gone (or never existed): drop any db from a previous 383 // sync rather than serving its issues indefinitely 384 if (repo_kind == .git) try LocalEventDB(repo_opts.hash).delete(io, repo.core.repo_dir); 385 return; 386 }; 387 388 switch (repo_kind) { 389 .git => { 390 try commitEvents(.git, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, allocator, ref, events, first_parent_oids); 391 392 var event_db = try LocalEventDB(repo_opts.hash).open(io, allocator, repo.core.repo_dir); 393 defer event_db.deinit(io, allocator); 394 395 try event_db.consume(repo_kind, repo_opts, io, allocator, repo, resolved_ref); 396 }, 397 .xit => { 398 const DB = rp.Repo(.xit, repo_opts).DB; 399 const State = rp.Repo(.xit, repo_opts).State; 400 var checks: pch.MergeCheckInputs(repo_opts) = .{}; 401 defer checks.deinit(io, allocator); 402 if (role == .repo and host_kind == .server) { 403 checks.prepare(io, allocator, repo, events) catch |err| { 404 std.log.warn("failed to prepare mergeability: {s}", .{@errorName(err)}); 405 }; 406 } 407 408 const Ctx = struct { 409 core: *rp.Repo(.xit, repo_opts).Core, 410 io: std.Io, 411 allocator: std.mem.Allocator, 412 ref: rf.Ref, 413 events: []const EventWithId, 414 checks: *pch.MergeCheckInputs(repo_opts), 415 first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8, 416 417 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 418 var moment = try DB.HashMap(.read_write).init(cursor.*); 419 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 420 421 try commitEvents(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.ref, ctx.events, ctx.first_parent_oids); 422 if (!try consumeInTransaction(role, .xit, repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, ctx.ref)) return error.CancelTransaction; 423 _ = try ctx.checks.update(state, ctx.io, ctx.allocator); 424 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action_kind = undo_action } }); 425 } 426 }; 427 428 try repo.core.db_file.lock(io, .exclusive); 429 defer repo.core.db_file.unlock(io); 430 431 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 432 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 433 .core = &repo.core, 434 .io = io, 435 .allocator = allocator, 436 .ref = resolved_ref, 437 .events = events, 438 .checks = &checks, 439 .first_parent_oids = first_parent_oids, 440 }) catch |err| switch (err) { 441 error.CancelTransaction => return, 442 else => |e| return e, 443 }; 444 }, 445 } 446 447 // consuming an existing ref does not provide the set of changed patches 448 // explicit patch writes already saved their checks in the event transaction 449 if (role == .repo and repo_kind == .xit and host_kind == .server and events.len == 0) { 450 pch.refreshOpenMergeability(repo_opts, io, allocator, repo, null, null); 451 } 452 } 453 454 // merge the remote events ref into the local events ref without touching head, 455 // the index, or the worktree 456 pub fn mergeEvents( 457 comptime repo_kind: rp.RepoKind, 458 comptime repo_opts: rp.RepoOpts(repo_kind), 459 io: std.Io, 460 allocator: std.mem.Allocator, 461 repo: *rp.Repo(repo_kind, repo_opts), 462 remote_ref: rf.Ref, 463 ) !void { 464 switch (repo_kind) { 465 .git => _ = try mergeEventsInTransaction(.git, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, allocator, remote_ref), 466 .xit => { 467 const DB = rp.Repo(.xit, repo_opts).DB; 468 const State = rp.Repo(.xit, repo_opts).State; 469 470 const Ctx = struct { 471 core: *rp.Repo(.xit, repo_opts).Core, 472 io: std.Io, 473 allocator: std.mem.Allocator, 474 remote_ref: rf.Ref, 475 476 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 477 var moment = try DB.HashMap(.read_write).init(cursor.*); 478 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 479 if (!try mergeEventsInTransaction(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.remote_ref)) return error.CancelTransaction; 480 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action_kind = merge_undo_action } }); 481 } 482 }; 483 484 try repo.core.db_file.lock(io, .exclusive); 485 defer repo.core.db_file.unlock(io); 486 487 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 488 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 489 .core = &repo.core, 490 .io = io, 491 .allocator = allocator, 492 .remote_ref = remote_ref, 493 }) catch |err| switch (err) { 494 error.CancelTransaction => {}, 495 else => |e| return e, 496 }; 497 }, 498 } 499 } 500 501 fn mergeEventsInTransaction( 502 comptime repo_kind: rp.RepoKind, 503 comptime repo_opts: rp.RepoOpts(repo_kind), 504 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 505 io: std.Io, 506 allocator: std.mem.Allocator, 507 remote_ref: rf.Ref, 508 ) !bool { 509 const remote_oid = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = remote_ref })) orelse return false; 510 const local_oid_maybe = try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = events_ref }); 511 512 var ref_path_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 513 const ref_path = try events_ref.toPath(&ref_path_buffer); 514 const local_oid = local_oid_maybe orelse { 515 try rf.write(repo_kind, repo_opts, state, io, ref_path, .{ .oid = &remote_oid }); 516 return true; 517 }; 518 if (std.mem.eql(u8, &local_oid, &remote_oid)) return false; 519 520 const ancestor_maybe: ?[hash.hexLen(repo_opts.hash)]u8 = mrg.commonAncestor(repo_kind, repo_opts, state.readOnly(), io, allocator, &local_oid, &remote_oid) catch |err| switch (err) { 521 error.NoCommonAncestor => null, 522 else => return err, 523 }; 524 if (ancestor_maybe) |ancestor| { 525 if (std.mem.eql(u8, &ancestor, &remote_oid)) return false; 526 if (std.mem.eql(u8, &ancestor, &local_oid)) { 527 try rf.write(repo_kind, repo_opts, state, io, ref_path, .{ .oid = &remote_oid }); 528 return true; 529 } 530 } 531 532 const parent_oids = [_][hash.hexLen(repo_opts.hash)]u8{ local_oid, remote_oid }; 533 var tree = try obj.Tree.init(allocator); 534 defer tree.deinit(); 535 _ = try obj.writeCommit(repo_kind, repo_opts, state, io, allocator, .{ 536 .message = "merge events", 537 .parent_oids = &parent_oids, 538 }, &tree, events_ref); 539 return true; 540 } 541 542 // the file an attach event carries: the one entry in its commit's tree. the 543 // name and oid are allocated in `arena`. 544 fn attachedFile( 545 comptime repo_kind: rp.RepoKind, 546 comptime repo_opts: rp.RepoOpts(repo_kind), 547 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 548 io: std.Io, 549 allocator: std.mem.Allocator, 550 arena: *std.heap.ArenaAllocator, 551 tree_oid: *const [hash.hexLen(repo_opts.hash)]u8, 552 ) !struct { name: []const u8, oid: []const u8 } { 553 var tree_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, tree_oid); 554 defer tree_object.deinit(); 555 556 const entries = switch (tree_object.content) { 557 .tree => |tree| tree.entries, 558 else => return error.InvalidAttachment, 559 }; 560 if (entries.count() != 1) return error.InvalidAttachment; 561 const entry = entries.values()[0]; 562 if (entry.isTree()) return error.InvalidAttachment; 563 const name = entries.keys()[0]; 564 if (!Attachment.nameValid(name)) return error.InvalidAttachment; 565 566 const oid = std.fmt.bytesToHex(entry.oid, .lower); 567 var object_reader = try obj.ObjectReader(repo_kind, repo_opts).init(state, io, allocator, &oid); 568 defer object_reader.deinit(); 569 if (object_reader.header().kind != .blob) return error.InvalidAttachment; 570 571 return .{ 572 .name = try arena.allocator().dupe(u8, name), 573 .oid = try arena.allocator().dupe(u8, &oid), 574 }; 575 } 576 577 fn commitIdentity(line: []const u8) ![]const u8 { 578 const close = std.mem.indexOfScalar(u8, line, '>') orelse return error.AuthorNotFound; 579 return line[0 .. close + 1]; 580 } 581 582 // commit each event as a JSON commit message on `ref` through `state`, so a 583 // xit repo can write them inside an already-open transaction 584 pub fn commitEvents( 585 comptime repo_kind: rp.RepoKind, 586 comptime repo_opts: rp.RepoOpts(repo_kind), 587 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 588 io: std.Io, 589 allocator: std.mem.Allocator, 590 ref: rf.Ref, 591 events: []const EventWithId, 592 first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8, 593 ) !void { 594 var parent_oids: ?[]const [hash.hexLen(repo_opts.hash)]u8 = if (first_parent_oids) |*oids| oids else null; 595 596 var json: std.Io.Writer.Allocating = .init(allocator); 597 defer json.deinit(); 598 599 for (events) |event| { 600 json.clearRetainingCapacity(); 601 try std.json.Stringify.value(event, .{}, &json.writer); 602 if (json.written().len > max_event_size) return error.EventTooLarge; 603 const author = try std.fmt.allocPrint(allocator, "{s} <{s}>", .{ event.author.name, event.author.email }); 604 defer allocator.free(author); 605 606 // every event gets a fresh tree 607 var tree = try obj.Tree.init(allocator); 608 defer tree.deinit(); 609 for (event.tree_entries) |entry| { 610 switch (entry) { 611 .blob => |blob| { 612 var oid_bytes = [_]u8{0} ** hash.byteLen(repo_opts.hash); 613 try obj.writeObject(repo_kind, repo_opts, state, io, allocator, blob.reader, .{ .kind = .blob, .size = blob.size }, &oid_bytes); 614 try tree.addBlobEntry(.{ .content = .{ .unix_permission = 0o644, .object_type = .regular_file } }, blob.name, &oid_bytes); 615 }, 616 .tree => |nested| { 617 var oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 618 _ = try std.fmt.hexToBytes(&oid_bytes, nested.oid); 619 if (!std.mem.eql(u8, nested.oid, &std.fmt.bytesToHex(oid_bytes, .lower))) return error.InvalidTreeObject; 620 try tree.addTreeEntry(nested.name, &oid_bytes); 621 }, 622 } 623 } 624 625 _ = try obj.writeCommit(repo_kind, repo_opts, state, io, allocator, .{ 626 .author = author, 627 .message = json.written(), 628 .timestamp = event.timestamp, 629 .parent_oids = parent_oids, 630 .allow_empty = true, 631 }, &tree, ref); 632 // later events parent on the ref's new tip 633 parent_oids = null; 634 } 635 } 636 637 // a standalone event db holding events consumed from a local repo's events 638 // branch. it lives inside the repo dir but is not part of the repo's own data, 639 // so viewing a repo never mutates it. 640 pub fn LocalEventDB(comptime hash_kind: hash.HashKind) type { 641 return struct { 642 file: std.Io.File, 643 buffer: *std.Io.Writer.Allocating, 644 db: *EventDB(hash_kind), 645 646 const db_name = "haxy"; 647 const Self = @This(); 648 649 // open the db in `repo_dir` for writing, creating it if it doesn't exist 650 pub fn open(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !Self { 651 const file = try repo_dir.createFile(io, db_name, .{ .truncate = false, .read = true, .lock = .exclusive }); 652 return fromFile(io, allocator, file); 653 } 654 655 // open the db in `repo_dir` for reading, or null if it doesn't exist 656 pub fn openReadOnly(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !?Self { 657 const file = repo_dir.openFile(io, db_name, .{ .mode = .read_write, .lock = .shared }) catch |err| switch (err) { 658 error.FileNotFound => return null, 659 else => |e| return e, 660 }; 661 return try fromFile(io, allocator, file); 662 } 663 664 // remove the db from `repo_dir`, so a repo whose events branch 665 // disappeared doesn't keep showing stale issues 666 pub fn delete(io: std.Io, repo_dir: std.Io.Dir) !void { 667 repo_dir.deleteFile(io, db_name) catch |err| switch (err) { 668 error.FileNotFound => {}, 669 else => |e| return e, 670 }; 671 } 672 673 fn fromFile(io: std.Io, allocator: std.mem.Allocator, file: std.Io.File) !Self { 674 errdefer file.close(io); 675 676 const buffer = try allocator.create(std.Io.Writer.Allocating); 677 errdefer allocator.destroy(buffer); 678 buffer.* = std.Io.Writer.Allocating.init(allocator); 679 errdefer buffer.deinit(); 680 681 const db = try allocator.create(EventDB(hash_kind)); 682 errdefer allocator.destroy(db); 683 db.* = try EventDB(hash_kind).init(.{ .io = io, .file = file, .buffer = buffer }); 684 685 return .{ .file = file, .buffer = buffer, .db = db }; 686 } 687 688 pub fn deinit(self: *Self, io: std.Io, allocator: std.mem.Allocator) void { 689 self.file.close(io); 690 self.buffer.deinit(); 691 allocator.destroy(self.buffer); 692 allocator.destroy(self.db); 693 } 694 695 // consume the events on `repo`'s `ref` into this db. the db must come 696 // from `open`, whose handle holds the exclusive lock guarding the 697 // transaction. 698 pub fn consume( 699 self: *Self, 700 comptime repo_kind: rp.RepoKind, 701 comptime repo_opts: rp.RepoOpts(repo_kind), 702 io: std.Io, 703 allocator: std.mem.Allocator, 704 repo: *rp.Repo(repo_kind, repo_opts), 705 ref: rf.Ref, 706 ) !void { 707 comptime if (repo_opts.hash != hash_kind) @compileError("the repo must use the db's hash kind"); 708 const DB = EventDB(hash_kind); 709 710 const Ctx = struct { 711 repo: *rp.Repo(repo_kind, repo_opts), 712 db: *DB, 713 io: std.Io, 714 allocator: std.mem.Allocator, 715 ref: rf.Ref, 716 717 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 718 var moment = try DB.HashMap(.read_write).init(cursor.*); 719 const state = rp.Repo(repo_kind, repo_opts).State(.read_write){ .core = &ctx.repo.core, .extra = .{} }; 720 if (!try consumeInTransaction(.repo, repo_kind, repo_opts, state, ctx.db, &moment, ctx.io, ctx.allocator, ctx.ref)) return error.CancelTransaction; 721 } 722 }; 723 724 const history = try DB.ArrayList(.read_write).init(self.db.rootCursor()); 725 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 726 .repo = repo, 727 .db = self.db, 728 .io = io, 729 .allocator = allocator, 730 .ref = ref, 731 }) catch |err| switch (err) { 732 error.CancelTransaction => {}, 733 else => |e| return e, 734 }; 735 } 736 }; 737 } 738 739 // consume the events on `ref` into the db `moment` writes to, returning false 740 // if there was nothing to do. events are read from `state`'s repo, which 741 // needn't be the repo backing the db — that's how a local (possibly 742 // git-backed) repo's events land in a standalone db. 743 pub fn consumeInTransaction( 744 comptime role: RepoRole, 745 comptime repo_kind: rp.RepoKind, 746 comptime repo_opts: rp.RepoOpts(repo_kind), 747 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 748 db: *EventDB(repo_opts.hash), 749 moment: *EventDB(repo_opts.hash).HashMap(.read_write), 750 io: std.Io, 751 allocator: std.mem.Allocator, 752 ref: rf.Ref, 753 ) !bool { 754 const DB = EventDB(repo_opts.hash); 755 const read_state = state.readOnly(); 756 757 // the last_object_id represents the object id that was last consumed 758 var last_object_id_maybe: ?[hash.byteLen(repo_opts.hash)]u8 = null; 759 if (try moment.getCursor(hash.hashInt(repo_opts.hash, last_object_id_key))) |last_object_id_cursor| { 760 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 761 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 762 last_object_id_maybe = last_object_id_buffer; 763 } 764 765 // the tip was already consumed, so there is nothing to do 766 if (last_object_id_maybe) |*last_object_id| { 767 const tip_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 768 var tip: [hash.byteLen(repo_opts.hash)]u8 = undefined; 769 _ = try std.fmt.hexToBytes(&tip, &tip_hex); 770 if (std.mem.eql(u8, last_object_id, &tip)) return false; 771 } 772 773 // the list with all of haxy's state, including materialized views. 774 // the reason it is a list is so we can keep every previous haxy 775 // state, making it easy to revert to an older state if the user 776 // rebases some of the past commits. 777 const haxy_history_cursor = try moment.putCursor(hash.hashInt(repo_opts.hash, history_key)); 778 const haxy_history = try DB.ArrayList(.read_write).init(haxy_history_cursor); 779 780 // add a new item to the haxy history list created above. 781 // we call the item haxy_moments. it is a map of object id to haxy moment. 782 // in other words, it maps each object id to a hash map containing the 783 // state that the database was in when that object id was consumed. 784 var haxy_moments_cursor = try haxy_history.appendCursor(); 785 // use the previous haxy_moments as the basis for this one if it exists 786 if (try haxy_history.getCursor(-2)) |last_haxy_moments_cursor| { 787 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 788 } 789 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 790 791 var commit_iter = try CommitIterator(repo_kind, repo_opts).init(read_state, io, allocator, haxy_moments.readOnly(), ref); 792 defer commit_iter.deinit(io, allocator); 793 794 // if there are no events to process, look at the oid at HEAD and update 795 // the last_object_id to point to it. this is important in situations 796 // where we do a merge and then force-push to remove the merge. see the 797 // merge test for an example. 798 if (commit_iter.newest_object_id == null) { 799 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 800 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 801 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 802 803 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 804 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 805 806 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, moment_index_key)) orelse return error.CursorNotFound; 807 const moment_index = try moment_index_cursor.readUint(); 808 809 try haxy_history.slice(moment_index + 1); 810 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = &head_oid }); 811 return true; 812 } 813 814 // if this branch was rebased and force pushed, we need to detect that and 815 // properly revert the haxy state to the last valid state. we detect this 816 // by simply asking if the last event is a descendent of the last event 817 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 818 if (last_object_id_maybe) |*last_object_id| { 819 var is_rebased = false; 820 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 821 822 _ = mrg.getDescendent( 823 repo_kind, 824 repo_opts, 825 read_state, 826 io, 827 allocator, 828 &std.fmt.bytesToHex(last_object_id, .lower), 829 &std.fmt.bytesToHex(&newest_object_id, .lower), 830 ) catch |err| switch (err) { 831 error.DescendentNotFound => is_rebased = true, 832 else => |e| return e, 833 }; 834 835 if (is_rebased) { 836 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 837 var oldest_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 838 defer oldest_object.deinit(); 839 840 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 841 switch (parent_oids.len) { 842 0 => { 843 // the branch was rebased all the way to the very beginning. 844 // we have a repo event with no parent, which means it is now 845 // the very first event. all we need to do is set the haxy 846 // history list to be empty and make a new haxy_moments map 847 // to work with. 848 849 try haxy_history.slice(0); 850 haxy_moments_cursor = try haxy_history.appendCursor(); 851 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 852 853 last_object_id_maybe = null; 854 }, 855 1 => { 856 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 857 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 858 859 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 860 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 861 862 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, moment_index_key)) orelse return error.CursorNotFound; 863 const old_moment_index = try old_moment_index_cursor.readUint(); 864 865 // resize the haxy history list so we truncate all the 866 // moments that were created after the parent_oid was consumed 867 try haxy_history.slice(old_moment_index + 1); 868 869 // make a new haxy moment and set its initial value to the last haxy moment 870 haxy_moments_cursor = try haxy_history.appendCursor(); 871 const old_haxy_moments_cursor = try haxy_history.getCursor(old_moment_index) orelse return error.CursorNotFound; 872 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 873 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 874 875 last_object_id_maybe = oid; 876 }, 877 else => return error.UnexpectedParentCount, 878 } 879 } 880 } 881 882 while (try commit_iter.next()) |repo_event_oid| { 883 var commit_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 884 defer commit_object.deinit(); 885 886 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 887 888 // create a moment for this object id 889 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 890 891 // if there was a previous object id, set this haxy moment's initial value to it. 892 // this efficiently "clones" the map so we make further modifications based on it. 893 if (parent_oids.len > 0) { 894 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 895 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 896 897 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 898 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 899 } 900 901 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 902 903 // graph generation gives every event a causal order independent of 904 // commit timestamps. concurrent events tie-break by id in their index. 905 var event_order: u64 = 1; 906 for (parent_oids) |*parent_oid| { 907 var parent_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 908 _ = try std.fmt.hexToBytes(&parent_id, parent_oid); 909 const parent_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &parent_id)) orelse return error.CursorNotFound; 910 const parent = try DB.HashMap(.read_only).init(parent_cursor); 911 const parent_order_cursor = try parent.getCursor(hash.hashInt(repo_opts.hash, event_order_key)) orelse return error.CursorNotFound; 912 const parent_order = try parent_order_cursor.readUint(); 913 event_order = @max(event_order, parent_order +| 1); 914 } 915 try haxy_moment.put(hash.hashInt(repo_opts.hash, event_order_key), .{ .uint = event_order }); 916 917 // merge changes from every parent after the first parent. the common 918 // ancestor is the baseline, so a later parent only contributes records 919 // it changed relative to the merge base. only the record maps are 920 // merged; every other view is derived from them, and each kind's 921 // `consume` re-derives its own as the winning records are written. 922 if (parent_oids.len > 1) { 923 for (parent_oids[1..]) |*parent_oid| { 924 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 925 _ = try std.fmt.hexToBytes(&oid, parent_oid); 926 927 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 928 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 929 930 const baseline_oid_hex = try mrg.commonAncestor(repo_kind, repo_opts, read_state, io, allocator, &parent_oids[0], parent_oid); 931 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 932 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 933 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 934 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 935 936 inline for (std.meta.fields(Event)) |field| { 937 const T = @typeInfo(field.type).optional.child; 938 try merge(T, DB, repo_opts.hash, allocator, haxy_moment, parent_haxy_moment, baseline_haxy_moment); 939 } 940 } 941 } 942 943 // associate this moment with the index it will first appear at in the 944 // haxy history list. this will be important later so we can truncate 945 // that list if the user ever rebases starting at this object id. 946 const moment_index = try haxy_history.count() - 1; 947 try haxy_moment.put(hash.hashInt(repo_opts.hash, moment_index_key), .{ .uint = moment_index }); 948 949 // consume the event unless it's a merge commit 950 if (parent_oids.len <= 1) { 951 var arena = std.heap.ArenaAllocator.init(allocator); 952 defer arena.deinit(); 953 954 // read the message from the commit 955 var message: std.ArrayList(u8) = .empty; 956 try commit_object.readMessage(arena.allocator(), &message, .limited(max_event_size)); 957 958 const event_with_id = try EventWithId.fromString(&arena, message.items); 959 if (!role.allows(std.meta.activeTag(event_with_id.event))) return error.EventKindNotAllowed; 960 961 const current_event_id = try parseEventId(&event_with_id.id); 962 963 // associate the transaction with the events it writes. this is 964 // used by the undo tab to link the events that were affected 965 // by a given transaction. 966 { 967 const sets = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, moment_index_to_event_id_set_key))); 968 const ids = try DB.SortedSet(.read_write).init(try sets.putCursor(momentIndexKey(repo_opts.hash, moment_index))); 969 try ids.put(&orderKeyDesc(event_order, &current_event_id)); 970 } 971 972 // wrap the payload into the record `consume` stores, with its 973 // commit-derived fields; on update, `consume` preserves the 974 // existing record's 975 switch (event_with_id.event) { 976 .user => |event_maybe| { 977 const record_maybe: ?User.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 978 try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 979 }, 980 .repo => |event_maybe| { 981 const record_maybe: ?Repo.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 982 try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 983 }, 984 .fork => |event_maybe| { 985 const record_maybe: ?Fork.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 986 try Fork.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 987 }, 988 .issue => |event_maybe| { 989 const record_maybe: ?Issue.Record = if (event_maybe) |event| .{ 990 .event = event, 991 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 992 .created_order = event_order, 993 .updated_order = event_order, 994 } else null; 995 try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 996 }, 997 .discuss => |event_maybe| { 998 const record_maybe: ?Discussion.Record = if (event_maybe) |event| .{ 999 .event = event, 1000 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1001 .created_order = event_order, 1002 .updated_order = event_order, 1003 } else null; 1004 try Discussion.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1005 }, 1006 .comment => |event_maybe| { 1007 const record_maybe: ?Comment.Record = if (event_maybe) |event| .{ 1008 .event = event, 1009 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1010 .created_order = event_order, 1011 .updated_order = event_order, 1012 } else null; 1013 try Comment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1014 }, 1015 .attach => |event_maybe| { 1016 const record_maybe: ?Attachment.Record = if (event_maybe) |event| blk: { 1017 const entry = try attachedFile(repo_kind, repo_opts, read_state, io, allocator, &arena, &commit_object.content.commit.tree); 1018 break :blk .{ 1019 .event = event, 1020 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1021 .created_order = event_order, 1022 .updated_order = event_order, 1023 .name = entry.name, 1024 .blob_oid = entry.oid, 1025 }; 1026 } else null; 1027 try Attachment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1028 }, 1029 .patchrev => |event_maybe| { 1030 const record_maybe: ?PatchRev.Record = if (event_maybe) |event| blk: { 1031 const trees = try PatchRev.readTrees(repo_kind, repo_opts, read_state, io, allocator, &commit_object.content.commit.tree); 1032 const existing_maybe = try PatchRev.readById(DB, repo_opts.hash, haxy_moment.readOnly(), &arena, &current_event_id); 1033 const event_oid = std.fmt.bytesToHex(repo_event_oid, .lower); 1034 1035 var patch_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1036 if (existing_maybe) |existing| { 1037 if (existing.patch_oid.len != patch_oid.len) return error.InvalidPatch; 1038 @memcpy(&patch_oid, existing.patch_oid); 1039 } else { 1040 const author = try commitIdentity(commit_object.content.commit.metadata.author orelse return error.AuthorNotFound); 1041 const committer = try commitIdentity(commit_object.content.commit.metadata.committer orelse author); 1042 patch_oid = try PatchRev.writeSquashCommit( 1043 repo_kind, 1044 repo_opts, 1045 state, 1046 io, 1047 allocator, 1048 event, 1049 &trees.head, 1050 author, 1051 committer, 1052 commit_object.content.commit.metadata.timestamp, 1053 ); 1054 } 1055 1056 break :blk .{ 1057 .event = event, 1058 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1059 .created_order = event_order, 1060 .updated_order = event_order, 1061 .event_oid = &event_oid, 1062 .base_tree_oid = &trees.base, 1063 .head_tree_oid = &trees.head, 1064 .patch_oid = &patch_oid, 1065 .commit_count = PatchRev.commitCount(repo_kind, repo_opts, read_state, io, allocator, event.base_oid, event.source_oid) catch null, 1066 }; 1067 } else null; 1068 try PatchRev.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1069 }, 1070 .patch => |event_maybe| { 1071 const record_maybe: ?Patch.Record = if (event_maybe) |event| .{ 1072 .event = event, 1073 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1074 .created_order = event_order, 1075 .updated_order = event_order, 1076 } else null; 1077 try Patch.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1078 }, 1079 } 1080 } 1081 1082 // the current object id is now the last one 1083 last_object_id_maybe = repo_event_oid; 1084 1085 // prevent any of the data created above from being mutated by future iterations of this loop 1086 try db.freeze(); 1087 } 1088 1089 if (last_object_id_maybe) |*last_object_id| { 1090 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = last_object_id }); 1091 } 1092 1093 return true; 1094 } 1095 1096 // the conflicted records of one kind, keyed by the same order key its id set 1097 // uses, so this doubles as the index the conflicts view lists and counts. every 1098 // value under an entry is a slot reference to a structure that already exists: 1099 // 1100 // <order key> -> conflict entry 1101 // conflicted-fields the conflicting field names, space separated 1102 // base-record the merge base's whole record 1103 // their-record the merged-in side's whole record 1104 // their-field->oid that side's field name to commit map 1105 // 1106 // our own value is the live record and our commit is in the kind's oid map, so 1107 // neither is repeated here. 1108 pub const conflicted_fields_key = "conflicted-fields"; 1109 pub const base_record_key = "base-record"; 1110 pub const their_record_key = "their-record"; 1111 pub const their_field_to_oid_key = "their-field->oid"; 1112 1113 // record the commit against every field this event changes. a merge passes no 1114 // oid, since each field's winner may come from a different side. 1115 pub fn writeOid( 1116 comptime T: type, 1117 comptime DB: type, 1118 comptime hash_kind: hash.HashKind, 1119 id_to_field_to_oid: DB.HashMap(.read_write), 1120 record_key: hash.HashInt(hash_kind), 1121 existing_maybe: ?T, 1122 event: T, 1123 event_oid: ?[]const u8, 1124 ) !void { 1125 const oid = event_oid orelse return; 1126 1127 // created only once a field actually changes 1128 var field_oids: ?DB.SortedMap(.read_write) = null; 1129 1130 inline for (std.meta.fields(T)) |field| { 1131 const changed = if (existing_maybe) |existing| 1132 !fieldEqual(field.type, @field(existing, field.name), @field(event, field.name)) 1133 else 1134 true; 1135 if (changed) { 1136 if (field_oids == null) { 1137 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1138 } 1139 if (field_oids) |map| try map.put(field.name, .{ .bytes = oid }); 1140 } 1141 } 1142 } 1143 1144 // the whole field list, space separated, is the longest it can get 1145 fn conflictedFieldsMaxLen(comptime T: type) usize { 1146 var len: usize = 0; 1147 for (std.meta.fields(T)) |field| len += field.name.len + 1; 1148 return len; 1149 } 1150 1151 pub const MergePolicy = enum { 1152 field_conflicts, 1153 target_wins, 1154 }; 1155 1156 // what a three-way merge did with a field 1157 pub const FieldMerge = enum { 1158 // the target's value stands, because neither side changed it, both made the 1159 // same change, or only the target changed it 1160 kept, 1161 parent, 1162 conflicted, 1163 }; 1164 1165 // three-way merge each field. one only the parent changed takes the parent's 1166 // value; one both sides changed differently keeps the target's. a missing 1167 // baseline makes every differing field a conflict. 1168 fn mergeFields( 1169 comptime T: type, 1170 baseline_maybe: ?T, 1171 target: T, 1172 parent: T, 1173 outcome: *[std.meta.fields(T).len]FieldMerge, 1174 ) T { 1175 var merged = target; 1176 1177 inline for (std.meta.fields(T), 0..) |field, i| { 1178 const target_value = @field(target, field.name); 1179 const parent_value = @field(parent, field.name); 1180 1181 if (!fieldEqual(field.type, target_value, parent_value)) { 1182 outcome[i] = if (baseline_maybe) |baseline| blk: { 1183 const baseline_value = @field(baseline, field.name); 1184 if (fieldEqual(field.type, target_value, baseline_value)) { 1185 @field(merged, field.name) = parent_value; 1186 break :blk .parent; 1187 } 1188 // only the target changed it 1189 if (fieldEqual(field.type, parent_value, baseline_value)) break :blk .kept; 1190 break :blk .conflicted; 1191 } else .conflicted; 1192 } 1193 } 1194 1195 return merged; 1196 } 1197 1198 // three-way merge of one kind's records from a merge parent. kinds that expose 1199 // conflicts merge field by field; the others take one whole record. the result 1200 // goes through the kind's `consume`, which re-derives the indexes from it. a 1201 // removal carries over unless the other side changed the record, so a merge 1202 // never fails. 1203 pub fn merge( 1204 comptime T: type, 1205 comptime DB: type, 1206 comptime hash_kind: hash.HashKind, 1207 allocator: std.mem.Allocator, 1208 haxy_moment: DB.HashMap(.read_write), 1209 parent_moment: DB.HashMap(.read_only), 1210 baseline_moment: DB.HashMap(.read_only), 1211 ) !void { 1212 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.all_id_set_key)) orelse return; 1213 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1214 1215 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1216 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1217 1218 var baseline_records: ?DB.HashMap(.read_only) = null; 1219 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1220 baseline_records = try DB.HashMap(.read_only).init(cursor); 1221 } 1222 1223 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1224 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1225 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1226 switch (comptime T.merge_policy) { 1227 .field_conflicts => { 1228 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1229 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1230 } 1231 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1232 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1233 } 1234 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1235 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1236 } 1237 }, 1238 .target_wins => {}, 1239 } 1240 1241 var arena = std.heap.ArenaAllocator.init(allocator); 1242 defer arena.deinit(); 1243 1244 var iter = try parent_set.iteratorFromIndex(0); 1245 while (try iter.next()) |kv_pair_cursor| { 1246 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1247 const record_key = hash.hashInt(hash_kind, &event_id); 1248 1249 _ = arena.reset(.retain_capacity); 1250 1251 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1252 const parent_slot = parent_record_cursor.slot(); 1253 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1254 1255 // the parent left this record alone 1256 if (baseline_slot) |slot| { 1257 if (slot.eql(parent_slot)) continue; 1258 } 1259 1260 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1261 1262 // re-derived every iteration, since `consume` writes through its own 1263 // handles 1264 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1265 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1266 1267 // a record the target doesn't have arrives wholesale from the parent 1268 var outcome: [std.meta.fields(T).len]FieldMerge = @splat(.parent); 1269 var merged = parent_record; 1270 1271 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1272 // both sides share the change 1273 if (target_record_cursor.slot().eql(parent_slot)) continue; 1274 1275 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1276 1277 var baseline_record: ?T.Record = null; 1278 if (baseline_records) |map| { 1279 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1280 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1281 } 1282 } 1283 1284 switch (comptime T.merge_policy) { 1285 .field_conflicts => { 1286 outcome = @splat(.kept); 1287 merged = target_record; 1288 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1289 merged.updated_order = @max(target_record.updated_order, parent_record.updated_order); 1290 if (comptime @hasDecl(T, "resolveMerge")) { 1291 T.resolveMerge(target_record.event, parent_record.event, &merged.event, &outcome); 1292 } 1293 1294 // merge the removed state separately from serialized fields. removal 1295 // carries over an unchanged record, while an edit or restoration 1296 // keeps it active. 1297 merged.removed = if (target_record.removed == parent_record.removed) 1298 target_record.removed 1299 else if (baseline_record) |baseline| blk: { 1300 const active = if (!target_record.removed) target_record else parent_record; 1301 if (active.removed != baseline.removed) break :blk false; 1302 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1303 break :blk true; 1304 } else false; 1305 }, 1306 .target_wins => { 1307 // an uncontested parent change carries over. if both sides 1308 // changed the record, the target wins as a whole, except that 1309 // an edit or restoration wins over a removal. 1310 const target_changed = if (baseline_slot) |slot| 1311 !target_record_cursor.slot().eql(slot) 1312 else 1313 true; 1314 merged = if (!target_changed) 1315 parent_record 1316 else if (target_record.removed != parent_record.removed) 1317 if (target_record.removed) parent_record else target_record 1318 else 1319 target_record; 1320 }, 1321 } 1322 } 1323 1324 // the index is unique, so a key the target gave to a different record 1325 // leaves this one out rather than stranding that one behind a name it 1326 // no longer owns 1327 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1328 const index_key = try merged.indexKey(arena.allocator()); 1329 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1330 const name_index = try DB.HashMap(.read_write).init(name_index_cursor); 1331 if (try name_index.getCursor(hash.hashInt(hash_kind, index_key))) |owner_cursor| { 1332 var owner_id: [event_id_size]u8 = undefined; 1333 _ = try owner_cursor.readBytes(&owner_id); 1334 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1335 } 1336 } 1337 1338 // `consume` sets no oids, since each field's winner may come from 1339 // a different side 1340 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1341 1342 switch (comptime T.merge_policy) { 1343 .field_conflicts => {}, 1344 .target_wins => continue, 1345 } 1346 1347 // removed records do not carry field conflicts 1348 if (merged.removed) continue; 1349 1350 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1351 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1352 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1353 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1354 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1355 1356 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1357 if (parent_id_to_field_to_oid) |map| { 1358 if (try map.getCursor(record_key)) |field_oids_cursor| { 1359 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1360 } 1361 } 1362 // created only once a field actually comes from the parent 1363 var field_oids: ?DB.SortedMap(.read_write) = null; 1364 1365 // the fields both sides changed differently, space separated 1366 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1367 var conflicted_len: usize = 0; 1368 1369 inline for (std.meta.fields(T), 0..) |field, i| { 1370 switch (outcome[i]) { 1371 // the target's value stands, so its oid does too 1372 .kept => {}, 1373 // the parent set this value, so its commit takes the field. a 1374 // parent with no oid took its own value from a merge, leaving 1375 // the field unattributed rather than crediting the target's 1376 // commit for a value it no longer holds. 1377 .parent => { 1378 if (field_oids == null) { 1379 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1380 } 1381 const map = field_oids orelse unreachable; 1382 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field.name) else null; 1383 if (parent_oid) |oid_cursor| { 1384 try map.put(field.name, .{ .slot = oid_cursor.slot() }); 1385 } else { 1386 _ = try map.remove(field.name); 1387 } 1388 }, 1389 .conflicted => { 1390 if (conflicted_len > 0) { 1391 conflicted_fields[conflicted_len] = ' '; 1392 conflicted_len += 1; 1393 } 1394 @memcpy(conflicted_fields[conflicted_len..][0..field.name.len], field.name); 1395 conflicted_len += field.name.len; 1396 }, 1397 } 1398 } 1399 1400 if (conflicted_len > 0) { 1401 // each side's whole record is stored by reference, so the view can 1402 // show any of them or take theirs wholesale 1403 _ = try conflicts.remove(&merged_key); 1404 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1405 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1406 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1407 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1408 if (parent_field_oids) |map| { 1409 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1410 } 1411 continue; 1412 } 1413 1414 // created_order never changes, so the parent keys this record's conflict 1415 // identically, and it carries over when the target has none, unless the 1416 // parent's entry is unchanged from the baseline, meaning the target 1417 // inherited it too and resolving it removed it here. 1418 if (parent_conflicts) |map| { 1419 if (null == try conflicts.getCursor(&merged_key)) { 1420 if (try map.getSlot(&merged_key)) |conflict_slot| { 1421 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1422 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1423 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1424 } 1425 } 1426 } 1427 } 1428 } 1429 1430 pub fn readFromRepo( 1431 comptime T: type, 1432 comptime repo_kind: rp.RepoKind, 1433 comptime repo_opts: rp.RepoOpts(repo_kind), 1434 io: std.Io, 1435 allocator: std.mem.Allocator, 1436 arena: *std.heap.ArenaAllocator, 1437 repo: *rp.Repo(repo_kind, repo_opts), 1438 id: *const [event_id_size]u8, 1439 ) !?T.Record { 1440 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; 1441 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1442 const moment = (if (event_db_maybe) |*event_db| 1443 currentMomentFromDb(repo_opts.hash, event_db.db) 1444 else if (repo_kind == .git) 1445 return null 1446 else 1447 currentMoment(repo_opts, repo)) catch return null; 1448 return T.readById(EventDB(repo_opts.hash), repo_opts.hash, moment, arena, id); 1449 } 1450 1451 pub fn currentMoment( 1452 comptime repo_opts: rp.RepoOpts(.xit), 1453 repo: *rp.Repo(.xit, repo_opts), 1454 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1455 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1456 } 1457 1458 pub fn currentMomentFromDb( 1459 comptime hash_kind: hash.HashKind, 1460 db: *EventDB(hash_kind), 1461 ) !EventDB(hash_kind).HashMap(.read_only) { 1462 const DB = EventDB(hash_kind); 1463 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1464 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1465 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1466 return try currentMomentFromRepoMoment(hash_kind, moment); 1467 } 1468 1469 pub fn currentMomentFromRepoMoment( 1470 comptime hash_kind: hash.HashKind, 1471 moment: EventDB(hash_kind).HashMap(.read_only), 1472 ) !EventDB(hash_kind).HashMap(.read_only) { 1473 const DB = EventDB(hash_kind); 1474 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1475 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1476 _ = try last_object_id_cursor.readBytes(&last_object_id); 1477 const haxy_history_cursor = try moment.getCursor(hash.hashInt(hash_kind, history_key)) orelse return error.NotFound; 1478 const haxy_history = try DB.ArrayList(.read_only).init(haxy_history_cursor); 1479 const haxy_moments_cursor = try haxy_history.getCursor(-1) orelse return error.NotFound; 1480 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1481 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1482 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1483 } 1484 1485 // build a sorted-set key from an order and event id. big-endian order makes 1486 // byte order match numeric order; the event id breaks ties. 1487 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1488 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1489 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1490 @memcpy(key[@sizeOf(u64)..], event_id); 1491 return key; 1492 } 1493 1494 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1495 return orderKey(std.math.maxInt(u64) - order, event_id); 1496 } 1497 1498 pub fn removedRecord( 1499 comptime T: type, 1500 comptime DB: type, 1501 comptime hash_kind: hash.HashKind, 1502 haxy_moment: DB.HashMap(.read_only), 1503 existing_maybe: ?T, 1504 ) !T { 1505 var record = existing_maybe orelse return error.EventNotFound; 1506 record.removed = true; 1507 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1508 record.updated_order = try order_cursor.readUint(); 1509 return record; 1510 } 1511 1512 // add or refresh one entry in the global logical-event index 1513 pub fn indexEvent( 1514 comptime DB: type, 1515 comptime hash_kind: hash.HashKind, 1516 haxy_moment: DB.HashMap(.read_write), 1517 event_id: *const [event_id_size]u8, 1518 kind: EventKind, 1519 existing_maybe: anytype, 1520 record: anytype, 1521 ) !void { 1522 const event_key = hash.hashInt(hash_kind, event_id); 1523 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1524 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1525 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1526 1527 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1528 const active = try DB.SortedSet(.read_write).init(active_cursor); 1529 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1530 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1531 1532 if (existing_maybe) |existing| { 1533 const old_key = orderKeyDesc(existing.updated_order, event_id); 1534 _ = try active.remove(&old_key); 1535 _ = try removed_set.remove(&old_key); 1536 } 1537 1538 const order_key = orderKeyDesc(record.updated_order, event_id); 1539 if (record.removed) { 1540 try removed_set.put(&order_key); 1541 } else { 1542 try active.put(&order_key); 1543 } 1544 } 1545 1546 pub fn touchThread( 1547 comptime DB: type, 1548 comptime hash_kind: hash.HashKind, 1549 haxy_moment: DB.HashMap(.read_write), 1550 thread_id: *const [event_id_size]u8, 1551 order: u64, 1552 arena: *std.heap.ArenaAllocator, 1553 ) !void { 1554 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1555 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1556 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1557 switch (kind) { 1558 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1559 else => {}, 1560 } 1561 } 1562 1563 pub fn readEventKind( 1564 comptime hash_kind: hash.HashKind, 1565 kind_map: anytype, 1566 id: *const [event_id_size]u8, 1567 ) !?EventKind { 1568 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1569 var buffer: [64]u8 = undefined; 1570 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1571 } 1572 1573 // the email of the event's author, or null when the id names no authored event 1574 // of this kind 1575 pub fn readAuthorEmail( 1576 comptime repo_kind: rp.RepoKind, 1577 comptime repo_opts: rp.RepoOpts(repo_kind), 1578 io: std.Io, 1579 allocator: std.mem.Allocator, 1580 arena: *std.heap.ArenaAllocator, 1581 repo: *rp.Repo(repo_kind, repo_opts), 1582 kind: EventKind, 1583 id: *const [event_id_size]u8, 1584 ) !?[]const u8 { 1585 const record_map_key = switch (kind) { 1586 .issue => Issue.record_map_key, 1587 .discuss => Discussion.record_map_key, 1588 .comment => Comment.record_map_key, 1589 .attach => Attachment.record_map_key, 1590 .patchrev => PatchRev.record_map_key, 1591 .patch => Patch.record_map_key, 1592 .user, .repo, .fork => return null, 1593 }; 1594 1595 const DB = EventDB(repo_opts.hash); 1596 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; 1597 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1598 const moment = (if (event_db_maybe) |*event_db| 1599 currentMomentFromDb(repo_opts.hash, event_db.db) 1600 else if (repo_kind == .git) 1601 return null 1602 else 1603 currentMoment(repo_opts, repo)) catch return null; 1604 1605 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 1606 const records = try DB.HashMap(.read_only).init(records_cursor); 1607 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 1608 const record = try DB.HashMap(.read_only).init(record_cursor); 1609 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 1610 } 1611 1612 // the event id embedded in a set entry's order key 1613 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1614 var cursor = kv_pair_cursor; 1615 const kv_pair = try cursor.readKeyValuePair(); 1616 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1617 _ = try kv_pair.key_cursor.readBytes(&order_key); 1618 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1619 } 1620 1621 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1622 // isn't exactly two non-empty segments. 1623 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1624 var it = std.mem.splitScalar(u8, path, '/'); 1625 const owner = it.next() orelse return null; 1626 const name = it.next() orelse return null; 1627 if (it.next() != null) return null; 1628 if (owner.len == 0 or name.len == 0) return null; 1629 1630 return .{ .owner = owner, .name = name }; 1631 } 1632 1633 pub const CreateRepoOptions = struct { 1634 read_access: Repo.Access = .private, 1635 }; 1636 1637 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1638 // directory under the repos dir 1639 pub fn resolveOrCreateRepo( 1640 io: std.Io, 1641 allocator: std.mem.Allocator, 1642 admin_repo_path: []const u8, 1643 owner_name: []const u8, 1644 repo_name: []const u8, 1645 create_options_maybe: ?CreateRepoOptions, 1646 ) !?[event_id_size * 2]u8 { 1647 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1648 error.RepoNotFound => return null, 1649 else => |e| return e, 1650 }; 1651 defer repo.deinit(io, allocator); 1652 1653 var arena = std.heap.ArenaAllocator.init(allocator); 1654 defer arena.deinit(); 1655 1656 const moment = try currentMoment(admin_repo_opts, &repo); 1657 1658 // an already-registered repo reuses its event id, so a re-push (or a clone) 1659 // lands in the same repo 1660 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1661 return std.fmt.bytesToHex(found.event_id, .lower); 1662 } 1663 1664 const create_options = create_options_maybe orelse return null; 1665 1666 // the new repo is owned by the named user, read from the name index; an 1667 // unknown owner can't own a repo, so the push is rejected 1668 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1669 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1670 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1671 var owner_user_id: [event_id_size]u8 = undefined; 1672 _ = try owner_id_cursor.readBytes(&owner_user_id); 1673 1674 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1675 1676 var id_bytes: [event_id_size]u8 = undefined; 1677 io.random(&id_bytes); 1678 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1679 1680 try consume(.server, .admin, .xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1681 .id = event_id_hex, 1682 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1683 .author = .{ .name = owner.event.name, .email = owner.event.email }, 1684 .event = .{ .repo = .{ 1685 .user_id = &owner_user_id, 1686 .name = repo_name, 1687 .description = "", 1688 .read_access = create_options.read_access, 1689 } }, 1690 }}); 1691 1692 return event_id_hex; 1693 } 1694 1695 // 1696 // reading from xitdb 1697 // 1698 1699 // read just `Fields`, a subset of `T.Record`, from the record with event id 1700 // `id`, or null when there is none 1701 pub fn readRecordSubset( 1702 comptime T: type, 1703 comptime Fields: type, 1704 comptime DB: type, 1705 comptime hash_kind: hash.HashKind, 1706 haxy_moment: DB.HashMap(.read_only), 1707 arena: *std.heap.ArenaAllocator, 1708 id: []const u8, 1709 ) !?Fields { 1710 comptime assertFieldSubset(Fields, T.Record); 1711 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 1712 const records = try DB.HashMap(.read_only).init(records_cursor); 1713 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1714 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 1715 } 1716 1717 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 1718 for (@typeInfo(Sub).@"struct".fields) |field| { 1719 if (!@hasField(Full, field.name)) @compileError(@typeName(Full) ++ " has no field " ++ field.name); 1720 const FullField = @FieldType(Full, field.name); 1721 if (@typeInfo(field.type) == .@"struct") { 1722 assertFieldSubset(field.type, FullField); 1723 } else if (field.type != FullField) { 1724 @compileError(@typeName(Full) ++ "." ++ field.name ++ " is a " ++ @typeName(FullField)); 1725 } 1726 } 1727 } 1728 1729 pub fn read( 1730 comptime T: type, 1731 comptime DB: type, 1732 comptime hash_kind: hash.HashKind, 1733 arena: *std.heap.ArenaAllocator, 1734 map: DB.HashMap(.read_only), 1735 ) !T { 1736 var event: T = undefined; 1737 switch (@typeInfo(T)) { 1738 .@"struct" => |struct_info| { 1739 inline for (struct_info.fields) |field| { 1740 const cursor = try map.getCursor(hash.hashInt(hash_kind, field.name)); 1741 @field(event, field.name) = try readField(field.type, DB, hash_kind, arena, cursor); 1742 } 1743 }, 1744 else => @compileError("read expects a struct"), 1745 } 1746 return event; 1747 } 1748 1749 fn readField( 1750 comptime Field: type, 1751 comptime DB: type, 1752 comptime hash_kind: hash.HashKind, 1753 arena: *std.heap.ArenaAllocator, 1754 cursor_maybe: ?DB.Cursor(.read_only), 1755 ) !Field { 1756 if (@typeInfo(Field) == .optional) { 1757 // a missing key or a null union payload is null 1758 const cursor = cursor_maybe orelse return null; 1759 if (cursor.slot().tag == .none) return null; 1760 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 1761 } 1762 const cursor = cursor_maybe orelse return error.NotFound; 1763 switch (@typeInfo(Field)) { 1764 .pointer => |pointer_info| { 1765 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.is_const) { 1766 @compileError("unsupported read field type: " ++ @typeName(Field)); 1767 } 1768 return try cursor.readBytesAlloc(arena.allocator(), null); 1769 }, 1770 .array => |array_info| { 1771 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 1772 var bytes: Field = undefined; 1773 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 1774 return bytes; 1775 }, 1776 .bool => { 1777 var buffer: [5]u8 = undefined; 1778 const bytes = try cursor.readBytesObject(&buffer); 1779 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1780 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1781 if (std.mem.eql(u8, bytes.value, "true")) return true; 1782 if (std.mem.eql(u8, bytes.value, "false")) return false; 1783 return error.InvalidBool; 1784 }, 1785 .int => |int_info| return switch (int_info.signedness) { 1786 .unsigned => @intCast(try cursor.readUint()), 1787 .signed => @intCast(try cursor.readInt()), 1788 }, 1789 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 1790 .@"union" => |union_info| { 1791 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 1792 switch (cursor.slot().tag) { 1793 .bytes, .short_bytes => { 1794 const name = try cursor.readBytesAlloc(arena.allocator(), null); 1795 inline for (union_info.fields) |variant| { 1796 if (variant.type == void and std.mem.eql(u8, name, variant.name)) { 1797 return @unionInit(Field, variant.name, {}); 1798 } 1799 } 1800 return error.InvalidUnion; 1801 }, 1802 .hash_map => { 1803 const variants = try DB.HashMap(.read_only).init(cursor); 1804 var iter = try variants.iterator(); 1805 const entry = (try iter.next()) orelse return error.InvalidUnion; 1806 const pair = try entry.readKeyValuePair(); 1807 if (try iter.next() != null) return error.InvalidUnion; 1808 inline for (union_info.fields) |variant| { 1809 if (variant.type != void and pair.hash == hash.hashInt(hash_kind, variant.name)) { 1810 return @unionInit(Field, variant.name, try readField(variant.type, DB, hash_kind, arena, pair.value_cursor)); 1811 } 1812 } 1813 return error.InvalidUnion; 1814 }, 1815 else => return error.InvalidUnion, 1816 } 1817 }, 1818 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 1819 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 1820 } 1821 } 1822 1823 // whether two events carry the same data 1824 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1825 switch (@typeInfo(T)) { 1826 .@"struct" => |struct_info| { 1827 inline for (struct_info.fields) |field| { 1828 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1829 } 1830 }, 1831 else => @compileError("fieldsEqual expects a struct"), 1832 } 1833 1834 return true; 1835 } 1836 1837 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1838 switch (@typeInfo(Field)) { 1839 .pointer => |pointer_info| { 1840 if (pointer_info.size == .slice and pointer_info.child == u8) { 1841 return std.mem.eql(u8, a, b); 1842 } else { 1843 @compileError("unsupported field type: " ++ @typeName(Field)); 1844 } 1845 }, 1846 .array => |array_info| { 1847 if (array_info.child == u8) { 1848 return std.mem.eql(u8, &a, &b); 1849 } else { 1850 @compileError("unsupported field type: " ++ @typeName(Field)); 1851 } 1852 }, 1853 .void => return true, 1854 .bool, .int, .@"enum" => return a == b, 1855 .@"union" => { 1856 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 1857 return switch (a) { 1858 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 1859 }; 1860 }, 1861 .@"struct" => return fieldsEqual(Field, a, b), 1862 .optional => |optional_info| { 1863 if (a) |a_value| { 1864 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 1865 return false; 1866 } 1867 return b == null; 1868 }, 1869 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1870 } 1871 } 1872 1873 // 1874 // writing to xitdb 1875 // 1876 1877 pub fn upsert( 1878 comptime T: type, 1879 comptime DB: type, 1880 comptime hash_kind: hash.HashKind, 1881 map: DB.HashMap(.read_write), 1882 event: T, 1883 ) !void { 1884 switch (@typeInfo(T)) { 1885 .@"struct" => |struct_info| { 1886 inline for (struct_info.fields) |field| { 1887 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1888 } 1889 }, 1890 else => @compileError("upsert expects a struct"), 1891 } 1892 } 1893 1894 fn upsertField( 1895 comptime DB: type, 1896 comptime hash_kind: hash.HashKind, 1897 map: DB.HashMap(.read_write), 1898 comptime field_name: []const u8, 1899 comptime Field: type, 1900 value: Field, 1901 ) !void { 1902 const key = hash.hashInt(hash_kind, field_name); 1903 1904 switch (@typeInfo(Field)) { 1905 .pointer => |pointer_info| { 1906 if (pointer_info.size == .slice and pointer_info.child == u8) { 1907 try upsertBytes(DB, hash_kind, map, key, value); 1908 } else { 1909 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1910 } 1911 }, 1912 .array => |array_info| { 1913 if (array_info.child == u8) { 1914 try upsertBytes(DB, hash_kind, map, key, &value); 1915 } else { 1916 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1917 } 1918 }, 1919 .int => |int_info| switch (int_info.signedness) { 1920 .unsigned => { 1921 if (try map.getCursor(key)) |value_cursor| { 1922 if (try value_cursor.readUint() == value) { 1923 return; 1924 } 1925 } 1926 1927 try map.put(key, .{ .uint = value }); 1928 }, 1929 .signed => { 1930 if (try map.getCursor(key)) |value_cursor| { 1931 if (try value_cursor.readInt() == value) { 1932 return; 1933 } 1934 } 1935 1936 try map.put(key, .{ .int = value }); 1937 }, 1938 }, 1939 .bool => { 1940 const bytes = if (value) "true" else "false"; 1941 if (try map.getCursor(key)) |value_cursor| { 1942 var buffer: [5]u8 = undefined; 1943 const existing = try value_cursor.readBytesObject(&buffer); 1944 if (existing.format_tag) |format_tag| { 1945 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1946 return; 1947 } 1948 } 1949 } 1950 1951 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1952 }, 1953 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1954 .@"union" => switch (value) { 1955 inline else => |payload, tag| { 1956 if (@TypeOf(payload) == void) { 1957 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 1958 } else { 1959 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 1960 if (try map.getCursor(key)) |cursor| { 1961 switch (cursor.slot().tag) { 1962 .hash_map => { 1963 const variants = try DB.HashMap(.read_only).init(cursor); 1964 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 1965 }, 1966 else => try map.put(key, .{ .slot = null }), 1967 } 1968 } 1969 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 1970 if (@typeInfo(@TypeOf(payload)) == .optional) { 1971 // keep the variant even when its payload is null 1972 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 1973 } 1974 if (try variants.getCursor(tag_key)) |cursor| { 1975 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 1976 } 1977 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 1978 } 1979 }, 1980 }, 1981 .optional => |optional_info| { 1982 // a missing key is null 1983 if (value) |child| { 1984 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 1985 } else { 1986 _ = try map.remove(key); 1987 } 1988 }, 1989 .@"struct" => try upsert( 1990 Field, 1991 DB, 1992 hash_kind, 1993 try DB.HashMap(.read_write).init(try map.putCursor(key)), 1994 value, 1995 ), 1996 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1997 } 1998 } 1999 2000 fn upsertBytes( 2001 comptime DB: type, 2002 comptime hash_kind: hash.HashKind, 2003 map: DB.HashMap(.read_write), 2004 key: hash.HashInt(hash_kind), 2005 value: []const u8, 2006 ) !void { 2007 var existing_cursor_maybe = try map.getCursor(key); 2008 if (existing_cursor_maybe) |*existing_cursor| { 2009 if (try bytesEqual(DB, existing_cursor, value)) { 2010 return; 2011 } 2012 } 2013 2014 try map.put(key, .{ .bytes = value }); 2015 } 2016 2017 fn bytesEqual( 2018 comptime DB: type, 2019 cursor: *DB.Cursor(.read_only), 2020 value: []const u8, 2021 ) !bool { 2022 switch (cursor.slot().tag) { 2023 .bytes, .short_bytes => {}, 2024 else => return false, 2025 } 2026 var read_buffer: [1024]u8 = undefined; 2027 var reader = try cursor.reader(&read_buffer); 2028 if (reader.size != value.len) { 2029 return false; 2030 } 2031 2032 var chunk_buffer: [1024]u8 = undefined; 2033 var offset: usize = 0; 2034 while (offset < value.len) { 2035 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2036 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2037 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2038 return false; 2039 } 2040 offset += chunk_len; 2041 } 2042 2043 return true; 2044 } 2045 2046 // 2047 // CommitIterator 2048 // 2049 // differs from xit's ObjectIterator in a few ways: 2050 // 2051 // 1. iterates parents first, rather than children first 2052 // 2. `next` only returns the object id, not the full Object 2053 // 3. stores its temporary state in a file on disk to avoid OOMs 2054 // 2055 2056 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2057 return struct { 2058 const DB = EventDB(repo_opts.hash); 2059 // a plain file is used for the scratch db because each write outside 2060 // a transaction is synced anyway, so buffering would gain nothing 2061 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2062 const db_name = "haxy-repo-events.db"; 2063 2064 repo_dir: std.Io.Dir, 2065 db_file: std.Io.File, 2066 db: *TempDB, 2067 // map of each object id to its children 2068 parent_to_children: TempDB.HashMap(.read_write), 2069 // tracking pending parents is necessary because a child can only 2070 // be returned after all of its unconsumed parents have been returned 2071 child_to_pending_parents: TempDB.HashMap(.read_write), 2072 // queue of object ids that are ready to be returned from `next` 2073 ready_queue: TempDB.ArrayList(.read_write), 2074 ready_queue_index: u64, 2075 // the object id at the tip of this branch 2076 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2077 // the object id furthest back in the history that hasn't been consumed 2078 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2079 2080 pub fn init( 2081 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2082 io: std.Io, 2083 allocator: std.mem.Allocator, 2084 consumed_object_ids: DB.HashMap(.read_only), 2085 ref: rf.Ref, 2086 ) !CommitIterator(repo_kind, repo_opts) { 2087 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2088 errdefer { 2089 db_file.close(io); 2090 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2091 } 2092 2093 // cursors point at the db, so it needs a stable address 2094 const db_ptr = try allocator.create(TempDB); 2095 errdefer allocator.destroy(db_ptr); 2096 // the db is scratch state that gets deleted after iteration, so 2097 // there is nothing worth fsyncing 2098 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2099 2100 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2101 2102 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2103 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2104 2105 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2106 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2107 2108 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2109 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2110 2111 var self = CommitIterator(repo_kind, repo_opts){ 2112 .repo_dir = state.core.repo_dir, 2113 .db_file = db_file, 2114 .db = db_ptr, 2115 .parent_to_children = parent_to_children, 2116 .child_to_pending_parents = child_to_pending_parents, 2117 .ready_queue = ready_queue, 2118 .ready_queue_index = 0, 2119 .newest_object_id = null, 2120 .oldest_object_id = null, 2121 }; 2122 errdefer self.deinit(io, allocator); 2123 2124 try self.collect(state, io, allocator, consumed_object_ids, ref); 2125 2126 return self; 2127 } 2128 2129 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2130 self.db_file.close(io); 2131 self.repo_dir.deleteFile(io, db_name) catch {}; 2132 allocator.destroy(self.db); 2133 } 2134 2135 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2136 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2137 2138 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2139 self.ready_queue_index += 1; 2140 2141 try self.enqueueChildren(&oid); 2142 return oid; 2143 } 2144 2145 fn collect( 2146 self: *CommitIterator(repo_kind, repo_opts), 2147 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2148 io: std.Io, 2149 allocator: std.mem.Allocator, 2150 consumed_object_ids: DB.HashMap(.read_only), 2151 ref: rf.Ref, 2152 ) !void { 2153 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2154 2155 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2156 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2157 var walk_queue_index: u64 = 0; 2158 2159 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2160 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2161 2162 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2163 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2164 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2165 try walk_queue.append(.{ .bytes = &head_oid }); 2166 2167 while (walk_queue_index < try walk_queue.count()) { 2168 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2169 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2170 2171 walk_queue_index += 1; 2172 2173 // if we've seen this object id, skip it 2174 if (null != try seen_object_ids.getCursor(oid_int)) { 2175 continue; 2176 } 2177 2178 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2179 2180 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2181 defer commit_object.deinit(); 2182 2183 // if this object id has already been consumed, skip it 2184 if (null != try consumed_object_ids.getCursor(oid_int)) { 2185 continue; 2186 } 2187 2188 if (self.newest_object_id == null) self.newest_object_id = oid; 2189 self.oldest_object_id = oid; 2190 2191 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2192 var pending_parent_count: u64 = 0; 2193 for (parent_oids) |*parent_oid| { 2194 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2195 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2196 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2197 2198 // if this object id has already been consumed, skip it 2199 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2200 continue; 2201 } 2202 2203 // if this object id hasn't already been seen, add it to the walk queue 2204 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2205 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2206 } 2207 2208 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2209 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2210 try children.put(oid_int, .{ .bytes = &oid }); 2211 pending_parent_count += 1; 2212 } 2213 2214 if (pending_parent_count == 0) { 2215 try self.ready_queue.append(.{ .bytes = &oid }); 2216 } else { 2217 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2218 } 2219 } 2220 } 2221 2222 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2223 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2224 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2225 const children = try TempDB.HashSet(.read_only).init(children_cursor); 2226 var children_iter = try children.iterator(); 2227 2228 while (try children_iter.next()) |*child_cursor| { 2229 const kv_pair = try child_cursor.readKeyValuePair(); 2230 const child_oid_int = kv_pair.hash; 2231 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2232 const pending_parent_count = try pending_parent_cursor.readUint(); 2233 2234 if (pending_parent_count <= 1) { 2235 _ = try self.child_to_pending_parents.remove(child_oid_int); 2236 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2237 try self.ready_queue.append(.{ .bytes = &child_oid }); 2238 } else { 2239 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2240 } 2241 } 2242 } 2243 2244 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2245 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2246 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2247 _ = try oid_cursor.readBytes(&oid); 2248 return oid; 2249 } 2250 }; 2251 } 2252