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