╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
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 .discuss => |event_maybe| { 1215 const record_maybe: ?Discussion.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 Discussion.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1222 }, 1223 .issue => |event_maybe| { 1224 const record_maybe: ?Issue.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 Issue.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 // a comment or attachment a write names under a thread 1658 pub const ThreadChild = union(enum) { 1659 comment: *const [event_id_size]u8, 1660 attach: *const [event_id_size]u8, 1661 }; 1662 1663 // whether `thread_id` names a thread of `thread_kind` in the repo's events, and 1664 // `child`, when given, belongs to it. a caller's url can claim any kind for any 1665 // id, so every write under a thread checks its claim here first. 1666 pub fn threadHolds( 1667 comptime repo_kind: rp.RepoKind, 1668 comptime repo_opts: rp.RepoOpts(repo_kind), 1669 io: std.Io, 1670 allocator: std.mem.Allocator, 1671 repo: *rp.Repo(repo_kind, repo_opts), 1672 thread_kind: EventKind, 1673 thread_id: *const [event_id_size]u8, 1674 child_maybe: ?ThreadChild, 1675 ) !bool { 1676 const DB = EventDB(repo_opts.hash); 1677 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; 1678 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1679 const moment = (if (event_db_maybe) |*event_db| 1680 currentMomentFromDb(repo_opts.hash, event_db.db) 1681 else if (repo_kind == .git) 1682 return false 1683 else 1684 currentMoment(repo_opts, repo)) catch return false; 1685 1686 // only these kinds are threads 1687 switch (thread_kind) { 1688 .discuss, .issue, .patch => {}, 1689 else => return false, 1690 } 1691 const kinds_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, event_index_key)) orelse return false; 1692 const kinds = try DB.HashMap(.read_only).init(kinds_cursor); 1693 if ((try readEventKind(repo_opts.hash, kinds, thread_id)) != thread_kind) return false; 1694 1695 const child = child_maybe orelse return true; 1696 var arena = std.heap.ArenaAllocator.init(allocator); 1697 defer arena.deinit(); 1698 const thread_id_hex = std.fmt.bytesToHex(thread_id.*, .lower); 1699 switch (child) { 1700 .comment => |id| { 1701 const comment = (try readRecordSubset(Comment, struct { event: struct { thread_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1702 return std.mem.eql(u8, &comment.event.thread_id, &thread_id_hex); 1703 }, 1704 .attach => |id| { 1705 const attachment = (try readRecordSubset(Attachment, struct { event: struct { parent_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1706 return std.mem.eql(u8, &attachment.event.parent_id, &thread_id_hex); 1707 }, 1708 } 1709 } 1710 1711 // remove an event a thread's page names: the thread itself, or a comment or 1712 // attachment, which must belong to it 1713 pub fn removeInThread( 1714 host: Host, 1715 comptime repo_kind: rp.RepoKind, 1716 comptime repo_opts: rp.RepoOpts(repo_kind), 1717 io: std.Io, 1718 allocator: std.mem.Allocator, 1719 repo: *rp.Repo(repo_kind, repo_opts), 1720 thread_kind: EventKind, 1721 thread_id: *const [event_id_size]u8, 1722 kind: EventKind, 1723 id: *const [event_id_size]u8, 1724 author: CommitAuthor, 1725 ) !void { 1726 const child_maybe: ?ThreadChild = switch (kind) { 1727 .comment => .{ .comment = id }, 1728 .attach => .{ .attach = id }, 1729 else => null, 1730 }; 1731 if (child_maybe) |child| { 1732 if (!try threadHolds(repo_kind, repo_opts, io, allocator, repo, thread_kind, thread_id, child)) return error.EventNotFound; 1733 } 1734 try remove(host, .repo, repo_kind, repo_opts, io, allocator, repo, id, kind, author); 1735 } 1736 1737 pub fn readFromRepo( 1738 comptime T: type, 1739 comptime repo_kind: rp.RepoKind, 1740 comptime repo_opts: rp.RepoOpts(repo_kind), 1741 io: std.Io, 1742 allocator: std.mem.Allocator, 1743 arena: *std.heap.ArenaAllocator, 1744 repo: *rp.Repo(repo_kind, repo_opts), 1745 id: *const [event_id_size]u8, 1746 ) !?T.Record { 1747 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; 1748 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1749 const moment = (if (event_db_maybe) |*event_db| 1750 currentMomentFromDb(repo_opts.hash, event_db.db) 1751 else if (repo_kind == .git) 1752 return null 1753 else 1754 currentMoment(repo_opts, repo)) catch return null; 1755 return T.readById(EventDB(repo_opts.hash), repo_opts.hash, moment, arena, id); 1756 } 1757 1758 pub fn currentMoment( 1759 comptime repo_opts: rp.RepoOpts(.xit), 1760 repo: *rp.Repo(.xit, repo_opts), 1761 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1762 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1763 } 1764 1765 pub fn currentMomentFromDb( 1766 comptime hash_kind: hash.HashKind, 1767 db: *EventDB(hash_kind), 1768 ) !EventDB(hash_kind).HashMap(.read_only) { 1769 const DB = EventDB(hash_kind); 1770 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1771 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1772 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1773 return try currentMomentFromRepoMoment(hash_kind, moment); 1774 } 1775 1776 pub fn currentMomentFromRepoMoment( 1777 comptime hash_kind: hash.HashKind, 1778 moment: EventDB(hash_kind).HashMap(.read_only), 1779 ) !EventDB(hash_kind).HashMap(.read_only) { 1780 const DB = EventDB(hash_kind); 1781 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1782 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1783 _ = try last_object_id_cursor.readBytes(&last_object_id); 1784 const haxy_history_cursor = try moment.getCursor(hash.hashInt(hash_kind, history_key)) orelse return error.NotFound; 1785 const haxy_history = try DB.ArrayList(.read_only).init(haxy_history_cursor); 1786 const haxy_moments_cursor = try haxy_history.getCursor(-1) orelse return error.NotFound; 1787 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1788 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1789 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1790 } 1791 1792 // build a sorted-set key from an order and event id. big-endian order makes 1793 // byte order match numeric order; the event id breaks ties. 1794 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1795 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1796 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1797 @memcpy(key[@sizeOf(u64)..], event_id); 1798 return key; 1799 } 1800 1801 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1802 return orderKey(std.math.maxInt(u64) - order, event_id); 1803 } 1804 1805 pub fn removedRecord( 1806 comptime T: type, 1807 comptime DB: type, 1808 comptime hash_kind: hash.HashKind, 1809 haxy_moment: DB.HashMap(.read_only), 1810 existing_maybe: ?T, 1811 ) !T { 1812 var record = existing_maybe orelse return error.EventNotFound; 1813 record.removed = true; 1814 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1815 record.updated_order = try order_cursor.readUint(); 1816 return record; 1817 } 1818 1819 // add or refresh one entry in the global logical-event index 1820 pub fn indexEvent( 1821 comptime DB: type, 1822 comptime hash_kind: hash.HashKind, 1823 haxy_moment: DB.HashMap(.read_write), 1824 event_id: *const [event_id_size]u8, 1825 kind: EventKind, 1826 existing_maybe: anytype, 1827 record: anytype, 1828 ) !void { 1829 const event_key = hash.hashInt(hash_kind, event_id); 1830 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1831 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1832 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1833 1834 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1835 const active = try DB.SortedSet(.read_write).init(active_cursor); 1836 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1837 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1838 1839 if (existing_maybe) |existing| { 1840 const old_key = orderKeyDesc(existing.updated_order, event_id); 1841 _ = try active.remove(&old_key); 1842 _ = try removed_set.remove(&old_key); 1843 } 1844 1845 const order_key = orderKeyDesc(record.updated_order, event_id); 1846 if (record.removed) { 1847 try removed_set.put(&order_key); 1848 } else { 1849 try active.put(&order_key); 1850 } 1851 } 1852 1853 pub fn touchThread( 1854 comptime DB: type, 1855 comptime hash_kind: hash.HashKind, 1856 haxy_moment: DB.HashMap(.read_write), 1857 thread_id: *const [event_id_size]u8, 1858 order: u64, 1859 arena: *std.heap.ArenaAllocator, 1860 ) !void { 1861 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1862 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1863 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1864 switch (kind) { 1865 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1866 else => {}, 1867 } 1868 } 1869 1870 pub fn readEventKind( 1871 comptime hash_kind: hash.HashKind, 1872 kind_map: anytype, 1873 id: *const [event_id_size]u8, 1874 ) !?EventKind { 1875 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1876 var buffer: [64]u8 = undefined; 1877 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1878 } 1879 1880 // the email of the event's author, or null when the id names no authored event 1881 // of this kind 1882 pub fn readAuthorEmail( 1883 comptime repo_kind: rp.RepoKind, 1884 comptime repo_opts: rp.RepoOpts(repo_kind), 1885 io: std.Io, 1886 allocator: std.mem.Allocator, 1887 arena: *std.heap.ArenaAllocator, 1888 repo: *rp.Repo(repo_kind, repo_opts), 1889 kind: EventKind, 1890 id: *const [event_id_size]u8, 1891 ) !?[]const u8 { 1892 const record_map_key = switch (kind) { 1893 .discuss => Discussion.record_map_key, 1894 .issue => Issue.record_map_key, 1895 .comment => Comment.record_map_key, 1896 .attach => Attachment.record_map_key, 1897 .patchrev => PatchRev.record_map_key, 1898 .patch => Patch.record_map_key, 1899 .user, .repo, .fork, .grant => return null, 1900 }; 1901 1902 const DB = EventDB(repo_opts.hash); 1903 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; 1904 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1905 const moment = (if (event_db_maybe) |*event_db| 1906 currentMomentFromDb(repo_opts.hash, event_db.db) 1907 else if (repo_kind == .git) 1908 return null 1909 else 1910 currentMoment(repo_opts, repo)) catch return null; 1911 1912 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 1913 const records = try DB.HashMap(.read_only).init(records_cursor); 1914 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 1915 const record = try DB.HashMap(.read_only).init(record_cursor); 1916 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 1917 } 1918 1919 // the event id embedded in a set entry's order key 1920 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1921 var cursor = kv_pair_cursor; 1922 const kv_pair = try cursor.readKeyValuePair(); 1923 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1924 _ = try kv_pair.key_cursor.readBytes(&order_key); 1925 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1926 } 1927 1928 // split a pushed "<owner>:<repo>" path into its two components, or null if it 1929 // isn't exactly two non-empty parts with no "/". 1930 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1931 if (std.mem.indexOfScalar(u8, path, '/') != null) return null; 1932 var it = std.mem.splitScalar(u8, path, ':'); 1933 const owner = it.next() orelse return null; 1934 const name = it.next() orelse return null; 1935 if (it.next() != null) return null; 1936 if (owner.len == 0 or name.len == 0) return null; 1937 1938 return .{ .owner = owner, .name = name }; 1939 } 1940 1941 pub const CreateRepoOptions = struct { 1942 read_access: Repo.Access = .private, 1943 }; 1944 1945 // the ids that locate a repo's on-disk directory 1946 pub const RepoLocation = struct { 1947 owner_id: [event_id_size]u8, 1948 repo_id: [event_id_size]u8, 1949 }; 1950 1951 // resolve a pushed `<owner>:<repo>` to the ids that locate its on-disk directory 1952 pub fn resolveOrCreateRepo( 1953 io: std.Io, 1954 allocator: std.mem.Allocator, 1955 users_dir: []const u8, 1956 admin_repo_path: []const u8, 1957 owner_name: []const u8, 1958 repo_name: []const u8, 1959 create_options_maybe: ?CreateRepoOptions, 1960 ) !?RepoLocation { 1961 var admin_repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1962 error.RepoNotFound => return null, 1963 else => |e| return e, 1964 }; 1965 defer admin_repo.deinit(io, allocator); 1966 1967 var arena = std.heap.ArenaAllocator.init(allocator); 1968 defer arena.deinit(); 1969 1970 const admin_moment = try currentMoment(admin_repo_opts, &admin_repo); 1971 1972 // an unknown owner can't own a repo, so the push is rejected 1973 const owner_user_id = (try User.readIdByName(AdminDB, admin_repo_opts.hash, admin_moment, owner_name)) orelse return null; 1974 var user_repo = (try openUserRepo(io, allocator, users_dir, &owner_user_id)) orelse return null; 1975 defer user_repo.deinit(io, allocator); 1976 1977 // an already-registered repo reuses its event id, so a re-push (or a clone) 1978 // lands in the same repo 1979 if (try userMoment(&user_repo)) |moment| { 1980 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, repo_name)) |found| { 1981 return .{ .owner_id = owner_user_id, .repo_id = found.event_id }; 1982 } 1983 } 1984 1985 const create_options = create_options_maybe orelse return null; 1986 1987 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, admin_moment, &arena, &owner_user_id)) orelse unreachable; 1988 1989 var id_bytes: [event_id_size]u8 = undefined; 1990 io.random(&id_bytes); 1991 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); 1992 return .{ .owner_id = owner_user_id, .repo_id = id_bytes }; 1993 } 1994 1995 // create a bare repo with `hash_kind` and register it in its owner's user repo 1996 pub fn createRepo( 1997 io: std.Io, 1998 allocator: std.mem.Allocator, 1999 users_dir: []const u8, 2000 owner_id: *const [event_id_size]u8, 2001 owner: CommitAuthor, 2002 name: []const u8, 2003 description: []const u8, 2004 read_access: Repo.Access, 2005 hash_kind: hash.HashKind, 2006 ) !RepoLocation { 2007 try Repo.validateName(name); 2008 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2009 defer user_repo.deinit(io, allocator); 2010 if (try userMoment(&user_repo)) |moment| { 2011 var arena = std.heap.ArenaAllocator.init(allocator); 2012 defer arena.deinit(); 2013 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name) != null) return error.NameTaken; 2014 } 2015 2016 var id_bytes: [event_id_size]u8 = undefined; 2017 io.random(&id_bytes); 2018 2019 // the directory comes first so a listed repo always has one 2020 { 2021 const path = try repoPath(allocator, users_dir, owner_id, &id_bytes); 2022 defer allocator.free(path); 2023 switch (hash_kind) { 2024 inline else => |kind| { 2025 var repo = try rp.Repo(.xit, .{ .hash = kind }).init(io, allocator, .{ .path = path, .bare = true }); 2026 defer repo.deinit(io, allocator); 2027 }, 2028 } 2029 } 2030 2031 try writeRepoEvent(io, allocator, users_dir, &user_repo, owner_id, owner, &id_bytes, name, description, read_access); 2032 return .{ .owner_id = owner_id.*, .repo_id = id_bytes }; 2033 } 2034 2035 // change the name, description, read access, and tab roles of the repo 2036 // named `old_name` in its owner's user repo 2037 pub fn updateRepo( 2038 io: std.Io, 2039 allocator: std.mem.Allocator, 2040 users_dir: []const u8, 2041 owner_id: *const [event_id_size]u8, 2042 author: CommitAuthor, 2043 old_name: []const u8, 2044 name: []const u8, 2045 description: []const u8, 2046 read_access: Repo.Access, 2047 discuss_role: ?Repo.Role, 2048 issue_role: ?Repo.Role, 2049 patch_role: ?Repo.Role, 2050 ) !void { 2051 try Repo.validateName(name); 2052 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2053 defer user_repo.deinit(io, allocator); 2054 var arena = std.heap.ArenaAllocator.init(allocator); 2055 defer arena.deinit(); 2056 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2057 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, old_name)) orelse return error.NotFound; 2058 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name)) |taken| { 2059 if (!std.mem.eql(u8, &taken.event_id, &found.event_id)) return error.NameTaken; 2060 } 2061 2062 var event = found.repo.event; 2063 event.name = name; 2064 event.description = description; 2065 event.read_access = read_access; 2066 event.discuss_role = discuss_role; 2067 event.issue_role = issue_role; 2068 event.patch_role = patch_role; 2069 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2070 .id = std.fmt.bytesToHex(found.event_id, .lower), 2071 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2072 .author = author, 2073 .event = .{ .repo = event }, 2074 }}); 2075 } 2076 2077 // create a user and their user repo, returning the new user's id 2078 pub fn createUser( 2079 io: std.Io, 2080 allocator: std.mem.Allocator, 2081 users_dir: []const u8, 2082 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2083 name: []const u8, 2084 email: []const u8, 2085 password: []const u8, 2086 password_again: []const u8, 2087 ) ![event_id_size]u8 { 2088 try User.validateName(name); 2089 if (email.len == 0) return error.EmailEmpty; 2090 if (password.len == 0) return error.PasswordEmpty; 2091 if (!std.mem.eql(u8, password, password_again)) return error.PasswordMismatch; 2092 // a fresh admin repo has no moment until its first event 2093 if (currentMoment(admin_repo_opts, admin_repo)) |moment| { 2094 if (try User.readIdByName(AdminDB, admin_repo_opts.hash, moment, name) != null) return error.NameTaken; 2095 var arena = std.heap.ArenaAllocator.init(allocator); 2096 defer arena.deinit(); 2097 if (try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2098 } else |err| switch (err) { 2099 error.NotFound => {}, 2100 else => |e| return e, 2101 } 2102 2103 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2104 const password_hash = try User.hashPassword(password, &password_hash_buf, io); 2105 2106 var id_bytes: [event_id_size]u8 = undefined; 2107 io.random(&id_bytes); 2108 2109 // the user repo comes first so a listed user can always create repos 2110 { 2111 const path = try userRepoPath(allocator, users_dir, &id_bytes); 2112 defer allocator.free(path); 2113 var user_repo = try initUserRepo(io, allocator, path); 2114 defer user_repo.deinit(io, allocator); 2115 } 2116 2117 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2118 .id = std.fmt.bytesToHex(id_bytes, .lower), 2119 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2120 .author = .{ .name = name, .email = email }, 2121 .event = .{ .user = .{ .name = name, .email = email, .password_hash = password_hash } }, 2122 }}); 2123 return id_bytes; 2124 } 2125 2126 // change a user's email, and their password when the password fields are 2127 // filled in 2128 pub fn updateUser( 2129 io: std.Io, 2130 allocator: std.mem.Allocator, 2131 users_dir: []const u8, 2132 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2133 user_id: *const [event_id_size]u8, 2134 email: []const u8, 2135 current_password: []const u8, 2136 new_password: []const u8, 2137 new_password_again: []const u8, 2138 ) !void { 2139 if (email.len == 0) return error.EmailEmpty; 2140 var arena = std.heap.ArenaAllocator.init(allocator); 2141 defer arena.deinit(); 2142 const moment = try currentMoment(admin_repo_opts, admin_repo); 2143 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2144 if (user.removed) return error.NotFound; 2145 if (!std.mem.eql(u8, email, user.event.email) and try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2146 2147 var event = user.event; 2148 event.email = email; 2149 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2150 if (current_password.len + new_password.len + new_password_again.len > 0) { 2151 if (!User.verifyPassword(user.event.password_hash, current_password)) return error.WrongPassword; 2152 if (new_password.len == 0) return error.PasswordEmpty; 2153 if (!std.mem.eql(u8, new_password, new_password_again)) return error.PasswordMismatch; 2154 event.password_hash = try User.hashPassword(new_password, &password_hash_buf, io); 2155 } 2156 2157 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2158 .id = std.fmt.bytesToHex(user_id.*, .lower), 2159 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2160 .author = .{ .name = event.name, .email = email }, 2161 .event = .{ .user = event }, 2162 }}); 2163 } 2164 2165 // consume a new repo's event into its owner's user repo and mark it active 2166 fn writeRepoEvent( 2167 io: std.Io, 2168 allocator: std.mem.Allocator, 2169 users_dir: []const u8, 2170 user_repo: *rp.Repo(.xit, user_repo_opts), 2171 owner_id: *const [event_id_size]u8, 2172 owner: CommitAuthor, 2173 id_bytes: *const [event_id_size]u8, 2174 name: []const u8, 2175 description: []const u8, 2176 read_access: Repo.Access, 2177 ) !void { 2178 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2179 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2180 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2181 .timestamp = timestamp, 2182 .author = owner, 2183 .event = .{ .repo = .{ 2184 .user_id = owner_id, 2185 .name = name, 2186 .description = description, 2187 .read_access = read_access, 2188 } }, 2189 }}); 2190 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2191 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2192 }; 2193 } 2194 2195 // 2196 // reading from xitdb 2197 // 2198 2199 // read just `Fields`, a subset of `T.Record`, from the record with event id 2200 // `id`, or null when there is none 2201 pub fn readRecordSubset( 2202 comptime T: type, 2203 comptime Fields: type, 2204 comptime DB: type, 2205 comptime hash_kind: hash.HashKind, 2206 haxy_moment: DB.HashMap(.read_only), 2207 arena: *std.heap.ArenaAllocator, 2208 id: []const u8, 2209 ) !?Fields { 2210 comptime assertFieldSubset(Fields, T.Record); 2211 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2212 const records = try DB.HashMap(.read_only).init(records_cursor); 2213 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2214 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2215 } 2216 2217 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2218 const info = @typeInfo(Sub).@"struct"; 2219 for (info.field_names, info.field_types) |field_name, field_type| { 2220 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2221 const FullField = @FieldType(Full, field_name); 2222 if (@typeInfo(field_type) == .@"struct") { 2223 assertFieldSubset(field_type, FullField); 2224 } else if (field_type != FullField) { 2225 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2226 } 2227 } 2228 } 2229 2230 pub fn read( 2231 comptime T: type, 2232 comptime DB: type, 2233 comptime hash_kind: hash.HashKind, 2234 arena: *std.heap.ArenaAllocator, 2235 map: DB.HashMap(.read_only), 2236 ) !T { 2237 var event: T = undefined; 2238 switch (@typeInfo(T)) { 2239 .@"struct" => |struct_info| { 2240 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2241 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2242 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2243 } 2244 }, 2245 else => @compileError("read expects a struct"), 2246 } 2247 return event; 2248 } 2249 2250 fn readField( 2251 comptime Field: type, 2252 comptime DB: type, 2253 comptime hash_kind: hash.HashKind, 2254 arena: *std.heap.ArenaAllocator, 2255 cursor_maybe: ?DB.Cursor(.read_only), 2256 ) !Field { 2257 if (@typeInfo(Field) == .optional) { 2258 // a missing key or a null union payload is null 2259 const cursor = cursor_maybe orelse return null; 2260 if (cursor.slot().tag == .none) return null; 2261 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2262 } 2263 const cursor = cursor_maybe orelse return error.NotFound; 2264 switch (@typeInfo(Field)) { 2265 .pointer => |pointer_info| { 2266 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2267 @compileError("unsupported read field type: " ++ @typeName(Field)); 2268 } 2269 return try cursor.readBytesAlloc(arena.allocator(), null); 2270 }, 2271 .array => |array_info| { 2272 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2273 var bytes: Field = undefined; 2274 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2275 return bytes; 2276 }, 2277 .bool => { 2278 var buffer: [5]u8 = undefined; 2279 const bytes = try cursor.readBytesObject(&buffer); 2280 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2281 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2282 if (std.mem.eql(u8, bytes.value, "true")) return true; 2283 if (std.mem.eql(u8, bytes.value, "false")) return false; 2284 return error.InvalidBool; 2285 }, 2286 .int => |int_info| return switch (int_info.signedness) { 2287 .unsigned => @intCast(try cursor.readUint()), 2288 .signed => @intCast(try cursor.readInt()), 2289 }, 2290 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2291 .@"union" => |union_info| { 2292 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2293 switch (cursor.slot().tag) { 2294 .bytes, .short_bytes => { 2295 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2296 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2297 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2298 return @unionInit(Field, variant_name, {}); 2299 } 2300 } 2301 return error.InvalidUnion; 2302 }, 2303 .hash_map => { 2304 const variants = try DB.HashMap(.read_only).init(cursor); 2305 var iter = try variants.iterator(); 2306 const entry = (try iter.next()) orelse return error.InvalidUnion; 2307 const pair = try entry.readKeyValuePair(); 2308 if (try iter.next() != null) return error.InvalidUnion; 2309 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2310 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2311 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2312 } 2313 } 2314 return error.InvalidUnion; 2315 }, 2316 else => return error.InvalidUnion, 2317 } 2318 }, 2319 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2320 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2321 } 2322 } 2323 2324 // whether two events carry the same data 2325 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2326 switch (@typeInfo(T)) { 2327 .@"struct" => |struct_info| { 2328 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2329 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2330 } 2331 }, 2332 else => @compileError("fieldsEqual expects a struct"), 2333 } 2334 2335 return true; 2336 } 2337 2338 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2339 switch (@typeInfo(Field)) { 2340 .pointer => |pointer_info| { 2341 if (pointer_info.size == .slice and pointer_info.child == u8) { 2342 return std.mem.eql(u8, a, b); 2343 } else { 2344 @compileError("unsupported field type: " ++ @typeName(Field)); 2345 } 2346 }, 2347 .array => |array_info| { 2348 if (array_info.child == u8) { 2349 return std.mem.eql(u8, &a, &b); 2350 } else { 2351 @compileError("unsupported field type: " ++ @typeName(Field)); 2352 } 2353 }, 2354 .void => return true, 2355 .bool, .int, .@"enum" => return a == b, 2356 .@"union" => { 2357 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2358 return switch (a) { 2359 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2360 }; 2361 }, 2362 .@"struct" => return fieldsEqual(Field, a, b), 2363 .optional => |optional_info| { 2364 if (a) |a_value| { 2365 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2366 return false; 2367 } 2368 return b == null; 2369 }, 2370 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2371 } 2372 } 2373 2374 // 2375 // writing to xitdb 2376 // 2377 2378 pub fn upsert( 2379 comptime T: type, 2380 comptime DB: type, 2381 comptime hash_kind: hash.HashKind, 2382 map: DB.HashMap(.read_write), 2383 event: T, 2384 ) !void { 2385 switch (@typeInfo(T)) { 2386 .@"struct" => |struct_info| { 2387 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2388 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2389 } 2390 }, 2391 else => @compileError("upsert expects a struct"), 2392 } 2393 } 2394 2395 fn upsertField( 2396 comptime DB: type, 2397 comptime hash_kind: hash.HashKind, 2398 map: DB.HashMap(.read_write), 2399 comptime field_name: []const u8, 2400 comptime Field: type, 2401 value: Field, 2402 ) !void { 2403 const key = hash.hashInt(hash_kind, field_name); 2404 2405 switch (@typeInfo(Field)) { 2406 .pointer => |pointer_info| { 2407 if (pointer_info.size == .slice and pointer_info.child == u8) { 2408 try upsertBytes(DB, hash_kind, map, key, value); 2409 } else { 2410 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2411 } 2412 }, 2413 .array => |array_info| { 2414 if (array_info.child == u8) { 2415 try upsertBytes(DB, hash_kind, map, key, &value); 2416 } else { 2417 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2418 } 2419 }, 2420 .int => |int_info| switch (int_info.signedness) { 2421 .unsigned => { 2422 if (try map.getCursor(key)) |value_cursor| { 2423 if (try value_cursor.readUint() == value) { 2424 return; 2425 } 2426 } 2427 2428 try map.put(key, .{ .uint = value }); 2429 }, 2430 .signed => { 2431 if (try map.getCursor(key)) |value_cursor| { 2432 if (try value_cursor.readInt() == value) { 2433 return; 2434 } 2435 } 2436 2437 try map.put(key, .{ .int = value }); 2438 }, 2439 }, 2440 .bool => { 2441 const bytes = if (value) "true" else "false"; 2442 if (try map.getCursor(key)) |value_cursor| { 2443 var buffer: [5]u8 = undefined; 2444 const existing = try value_cursor.readBytesObject(&buffer); 2445 if (existing.format_tag) |format_tag| { 2446 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2447 return; 2448 } 2449 } 2450 } 2451 2452 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2453 }, 2454 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2455 .@"union" => switch (value) { 2456 inline else => |payload, tag| { 2457 if (@TypeOf(payload) == void) { 2458 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2459 } else { 2460 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2461 if (try map.getCursor(key)) |cursor| { 2462 switch (cursor.slot().tag) { 2463 .hash_map => { 2464 const variants = try DB.HashMap(.read_only).init(cursor); 2465 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2466 }, 2467 else => try map.put(key, .{ .slot = null }), 2468 } 2469 } 2470 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2471 if (@typeInfo(@TypeOf(payload)) == .optional) { 2472 // keep the variant even when its payload is null 2473 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2474 } 2475 if (try variants.getCursor(tag_key)) |cursor| { 2476 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2477 } 2478 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2479 } 2480 }, 2481 }, 2482 .optional => |optional_info| { 2483 // a missing key is null 2484 if (value) |child| { 2485 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2486 } else { 2487 _ = try map.remove(key); 2488 } 2489 }, 2490 .@"struct" => try upsert( 2491 Field, 2492 DB, 2493 hash_kind, 2494 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2495 value, 2496 ), 2497 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2498 } 2499 } 2500 2501 fn upsertBytes( 2502 comptime DB: type, 2503 comptime hash_kind: hash.HashKind, 2504 map: DB.HashMap(.read_write), 2505 key: hash.HashInt(hash_kind), 2506 value: []const u8, 2507 ) !void { 2508 var existing_cursor_maybe = try map.getCursor(key); 2509 if (existing_cursor_maybe) |*existing_cursor| { 2510 if (try bytesEqual(DB, existing_cursor, value)) { 2511 return; 2512 } 2513 } 2514 2515 try map.put(key, .{ .bytes = value }); 2516 } 2517 2518 fn bytesEqual( 2519 comptime DB: type, 2520 cursor: *DB.Cursor(.read_only), 2521 value: []const u8, 2522 ) !bool { 2523 switch (cursor.slot().tag) { 2524 .bytes, .short_bytes => {}, 2525 else => return false, 2526 } 2527 var read_buffer: [1024]u8 = undefined; 2528 var reader = try cursor.reader(&read_buffer); 2529 if (reader.size != value.len) { 2530 return false; 2531 } 2532 2533 var chunk_buffer: [1024]u8 = undefined; 2534 var offset: usize = 0; 2535 while (offset < value.len) { 2536 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2537 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2538 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2539 return false; 2540 } 2541 offset += chunk_len; 2542 } 2543 2544 return true; 2545 } 2546 2547 // 2548 // CommitIterator 2549 // 2550 // differs from xit's ObjectIterator in a few ways: 2551 // 2552 // 1. iterates parents first, rather than children first 2553 // 2. `next` only returns the object id, not the full Object 2554 // 3. stores its temporary state in a file on disk to avoid OOMs 2555 // 2556 2557 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2558 return struct { 2559 const DB = EventDB(repo_opts.hash); 2560 // a plain file is used for the scratch db because each write outside 2561 // a transaction is synced anyway, so buffering would gain nothing 2562 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2563 const db_name = "haxy-repo-events.db"; 2564 2565 repo_dir: std.Io.Dir, 2566 db_file: std.Io.File, 2567 db: *TempDB, 2568 // map of each object id to its children 2569 parent_to_children: TempDB.HashMap(.read_write), 2570 // tracking pending parents is necessary because a child can only 2571 // be returned after all of its unconsumed parents have been returned 2572 child_to_pending_parents: TempDB.HashMap(.read_write), 2573 // queue of object ids that are ready to be returned from `next` 2574 ready_queue: TempDB.ArrayList(.read_write), 2575 ready_queue_index: u64, 2576 // the object id at the tip of this branch 2577 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2578 // the object id furthest back in the history that hasn't been consumed 2579 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2580 2581 pub fn init( 2582 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2583 io: std.Io, 2584 allocator: std.mem.Allocator, 2585 consumed_object_ids: DB.HashMap(.read_only), 2586 ref: rf.Ref, 2587 ) !CommitIterator(repo_kind, repo_opts) { 2588 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2589 errdefer { 2590 db_file.close(io); 2591 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2592 } 2593 2594 // cursors point at the db, so it needs a stable address 2595 const db_ptr = try allocator.create(TempDB); 2596 errdefer allocator.destroy(db_ptr); 2597 // the db is scratch state that gets deleted after iteration, so 2598 // there is nothing worth fsyncing 2599 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2600 2601 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2602 2603 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2604 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2605 2606 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2607 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2608 2609 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2610 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2611 2612 var self = CommitIterator(repo_kind, repo_opts){ 2613 .repo_dir = state.core.repo_dir, 2614 .db_file = db_file, 2615 .db = db_ptr, 2616 .parent_to_children = parent_to_children, 2617 .child_to_pending_parents = child_to_pending_parents, 2618 .ready_queue = ready_queue, 2619 .ready_queue_index = 0, 2620 .newest_object_id = null, 2621 .oldest_object_id = null, 2622 }; 2623 errdefer self.deinit(io, allocator); 2624 2625 try self.collect(state, io, allocator, consumed_object_ids, ref); 2626 2627 return self; 2628 } 2629 2630 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2631 self.db_file.close(io); 2632 self.repo_dir.deleteFile(io, db_name) catch {}; 2633 allocator.destroy(self.db); 2634 } 2635 2636 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2637 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2638 2639 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2640 self.ready_queue_index += 1; 2641 2642 try self.enqueueChildren(&oid); 2643 return oid; 2644 } 2645 2646 fn collect( 2647 self: *CommitIterator(repo_kind, repo_opts), 2648 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2649 io: std.Io, 2650 allocator: std.mem.Allocator, 2651 consumed_object_ids: DB.HashMap(.read_only), 2652 ref: rf.Ref, 2653 ) !void { 2654 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2655 2656 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2657 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2658 var walk_queue_index: u64 = 0; 2659 2660 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2661 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2662 2663 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2664 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2665 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2666 try walk_queue.append(.{ .bytes = &head_oid }); 2667 2668 while (walk_queue_index < try walk_queue.count()) { 2669 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2670 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2671 2672 walk_queue_index += 1; 2673 2674 // if we've seen this object id, skip it 2675 if (null != try seen_object_ids.getCursor(oid_int)) { 2676 continue; 2677 } 2678 2679 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2680 2681 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2682 defer commit_object.deinit(); 2683 2684 // if this object id has already been consumed, skip it 2685 if (null != try consumed_object_ids.getCursor(oid_int)) { 2686 continue; 2687 } 2688 2689 if (self.newest_object_id == null) self.newest_object_id = oid; 2690 self.oldest_object_id = oid; 2691 2692 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2693 var pending_parent_count: u64 = 0; 2694 for (parent_oids) |*parent_oid| { 2695 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2696 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2697 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2698 2699 // if this object id has already been consumed, skip it 2700 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2701 continue; 2702 } 2703 2704 // if this object id hasn't already been seen, add it to the walk queue 2705 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2706 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2707 } 2708 2709 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2710 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2711 try children.put(oid_int, .{ .bytes = &oid }); 2712 pending_parent_count += 1; 2713 } 2714 2715 if (pending_parent_count == 0) { 2716 try self.ready_queue.append(.{ .bytes = &oid }); 2717 } else { 2718 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2719 } 2720 } 2721 } 2722 2723 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2724 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2725 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2726 const children = try TempDB.HashSet(.read_only).init(children_cursor); 2727 var children_iter = try children.iterator(); 2728 2729 while (try children_iter.next()) |*child_cursor| { 2730 const kv_pair = try child_cursor.readKeyValuePair(); 2731 const child_oid_int = kv_pair.hash; 2732 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2733 const pending_parent_count = try pending_parent_cursor.readUint(); 2734 2735 if (pending_parent_count <= 1) { 2736 _ = try self.child_to_pending_parents.remove(child_oid_int); 2737 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2738 try self.ready_queue.append(.{ .bytes = &child_oid }); 2739 } else { 2740 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2741 } 2742 } 2743 } 2744 2745 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2746 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2747 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2748 _ = try oid_cursor.readBytes(&oid); 2749 return oid; 2750 } 2751 }; 2752 } 2753