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