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