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