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