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