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