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