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