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