| 1 | # ABSTRACT: Activity log writer for karr board operations | ||
| 2 | |||
| 3 | package App::karr::ActivityLog; | ||
| 4 | our $VERSION = '0.602'; | ||
| 5 | 27 | ▶ | use Moo; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | 27 | ▶ | use App::karr::Encoding qw( json_encode json_decode ); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 7 | 27 | ▶ | use POSIX qw( strftime ); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | 27 | ▶ | use Encode qw( encode decode FB_CROAK ); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 9 | 27 | ▶ | use Try::Tiny; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 10 | 0 | ▶ | use Git::Native; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 11 | |||
| 12 | |||
| 13 | has git => ( | ||
| 14 | is => 'ro', | ||
| 15 | required => 1, | ||
| 16 | ); | ||
| 17 | |||
| 18 | |||
| 19 | has role => ( | ||
| 20 | is => 'ro', | ||
| 21 | default => sub { $ENV{KARR_ROLE} || 'user' }, | ||
| 22 | ); | ||
| 23 | |||
| 24 | # A log ref is rewritten in full on every append -- that is what a ref blob | ||
| 25 | # is -- so an uncapped one makes the write path O(n): after 10,000 entries of | ||
| 26 | # the ~93 bytes karr writes, the blobs written add up to ~93*10000**2/2, about | ||
| 27 | # 4.6 GB of objects for a log that is 1 MB (#171). Capping a segment caps that: | ||
| 28 | # a single entry never costs more than one blob of this size, and the total | ||
| 29 | # written grows linearly. 8 KiB is roughly 80 karr entries, so a board gains | ||
| 30 | # about one extra ref per 80 mutating commands. | ||
| 31 | use constant SEGMENT_MAX_BYTES => 8192; | ||
| 32 | |||
| 33 | # The one source for the action vocabulary of the board activity log. Every | ||
| 34 | # entry is written either by a command's log_action (the command's own name, | ||
| 35 | # hyphenated -- create, move, edit, delete, archive, handoff, needs) or by the | ||
| 36 | # explicit 'pick' of C<karr pick> (Role::BoardAccess/append_log), so this is | ||
| 37 | # exactly the set that can appear in refs/karr/log/*. C<karr log --action> | ||
| 38 | # validates against it and prints it in the usage error, instead of keeping a | ||
| 39 | # second hand-maintained list that drifts from what the commands actually write | ||
| 40 | # (ticket #278). | ||
| 41 | use constant ACTIONS => qw( archive create delete edit handoff move needs pick ); | ||
| 42 | |||
| 43 | |||
| 44 | has segment_max_bytes => ( | ||
| 45 | is => 'ro', | ||
| 46 | default => sub { SEGMENT_MAX_BYTES }, | ||
| 47 | ); | ||
| 48 | |||
| 49 | # Percent-encode one identity component into a single git ref path component. | ||
| 50 | # | ||
| 51 | # git-check-ref-format forbids far more than the old s/[^a-zA-Z0-9._-]/_/g | ||
| 52 | # mapped away: a component may not start with '.', contain '..', or end in '.' | ||
| 53 | # or '.lock', and the whole name may not contain a space, a control character, | ||
| 54 | # '~^:?*[', '\' or '@{'. An ordinary address like a..b@example.com therefore | ||
| 55 | # produced a name libgit2 refuses outright (#75), and because every unsafe | ||
| 56 | # character collapsed onto '_' four different addresses could share one log. | ||
| 57 | # | ||
| 58 | # Encoding the octets instead fixes both: '.' '-' '_' and alphanumerics stay | ||
| 59 | # literal so the common address remains readable, everything else -- '%' | ||
| 60 | # included, which is what makes _decode_component an exact inverse -- becomes | ||
| 61 | # %XX, and the few dots that would still break a ref name are encoded too. The | ||
| 62 | # result is pure [A-Za-z0-9%._-], always a legal component, never empty. | ||
| 63 | sub _encode_component { | ||
| 64 | my ( $self, $s ) = @_; | ||
| 65 | return 'unknown' unless defined $s && length $s; | ||
| 66 | |||
| 67 | # git_user_email arrives straight out of libgit2 as UTF-8 octets, while a | ||
| 68 | # value that already crossed karr's character boundary arrives as | ||
| 69 | # characters. Upgrade only the latter, so both spellings of one address | ||
| 70 | # encode to the same ref name and no email can turn into mojibake. | ||
| 71 | my $octets = utf8::is_utf8($s) ? encode( 'UTF-8', $s ) : $s; | ||
| 72 | |||
| 73 | $octets =~ s/([^A-Za-z0-9._-])/sprintf('%%%02X', ord($1))/ge; | ||
| 74 | $octets =~ s/(\.{2,})/'%2E' x length($1)/ge; # no '..' | ||
| 75 | $octets =~ s/\A\./%2E/; # no leading '.' | ||
| 76 | $octets =~ s/\.\z/%2E/; # no trailing '.' | ||
| 77 | $octets =~ s/\.lock\z/%2Elock/; # no trailing '.lock' | ||
| 78 | return $octets; | ||
| 79 | } | ||
| 80 | |||
| 81 | sub _decode_component { | ||
| 82 | my ( $self, $encoded ) = @_; | ||
| 83 | return '' unless defined $encoded && length $encoded; | ||
| 84 | my $octets = $encoded; | ||
| 85 | $octets =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge; | ||
| 86 | # A component that is not valid UTF-8 was never written by us; hand back | ||
| 87 | # the octets rather than substituting U+FFFD into somebody's address. | ||
| 88 | return try { decode( 'UTF-8', $octets, FB_CROAK ) } catch { $octets }; | ||
| 89 | } | ||
| 90 | |||
| 91 | sub _email { | ||
| 92 | my ($self) = @_; | ||
| 93 | return $self->git->git_user_email || 'unknown'; | ||
| 94 | } | ||
| 95 | |||
| 96 | # The role attribute can be handed an empty string explicitly, and an empty | ||
| 97 | # component would make the ref name a legal-looking 'refs/karr/log//x'. | ||
| 98 | sub _role { | ||
| 99 | my ($self) = @_; | ||
| 100 | my $role = $self->role; | ||
| 101 | return defined $role && length $role ? $role : 'user'; | ||
| 102 | } | ||
| 103 | |||
| 104 | |||
| 105 | |||
| 106 | sub identity { | ||
| 107 | my ($self) = @_; | ||
| 108 | return $self->_encode_component( $self->_role ) . '/' | ||
| 109 | . $self->_encode_component( $self->_email ); | ||
| 110 | } | ||
| 111 | |||
| 112 | |||
| 113 | sub decode_identity { | ||
| 114 | my ( $self, $identity ) = @_; | ||
| 115 | my ( $role, $email ) = split m{/}, ( $identity // '' ), 2; | ||
| 116 | return ( $self->_decode_component($role), $self->_decode_component($email) ); | ||
| 117 | } | ||
| 118 | |||
| 119 | sub _ref { | ||
| 120 | my ($self) = @_; | ||
| 121 | return 'refs/karr/log/' . $self->identity; | ||
| 122 | } | ||
| 123 | |||
| 124 | # One identity's log is a chain of segment refs, not a single ref: | ||
| 125 | # | ||
| 126 | # refs/karr/log/<role>/<email> segment 0 -- the only ref karr wrote | ||
| 127 | # before #171, and still the first one | ||
| 128 | # written on a fresh board | ||
| 129 | # refs/karr/log/<role>/<email>+000001 segment 1, opened when 0 is full | ||
| 130 | # | ||
| 131 | # '+' is legal in a git ref name and _encode_component never produces one (it | ||
| 132 | # encodes to %2B), so a segment name can collide with no identity's own ref. | ||
| 133 | # The segments are *siblings* of segment 0 rather than children of it, which | ||
| 134 | # rules out the more obvious .../<email>/000001 spelling: git cannot hold a ref | ||
| 135 | # and a directory of the same name, so that layout would be unwritable on every | ||
| 136 | # board that already has a log. | ||
| 137 | # | ||
| 138 | # Nothing marks the format. The encoding switch needed refs/karr/meta/encoding | ||
| 139 | # (see App::karr::Cmd::Repair) because the content could not tell you which of | ||
| 140 | # two spellings it was in; here the layout is the ref names themselves. A board | ||
| 141 | # written before #171 has segment 0 and nothing else, which is exactly what a | ||
| 142 | # board that has not rotated yet looks like, so it is read -- and appended to -- | ||
| 143 | # without migration, and needs no repair pass. | ||
| 144 | sub _segment_ref { | ||
| 145 | my ( $self, $index ) = @_; | ||
| 146 | return $index ? sprintf( '%s+%06d', $self->_ref, $index ) : $self->_ref; | ||
| 147 | } | ||
| 148 | |||
| 149 | # The exact set of ref names this identity's log occupies, as one regex: the | ||
| 150 | # base ref and its '+NNNNNN' segments, nothing else. Takes the base as an | ||
| 151 | # argument because _ref reaches into libgit2's config for the mail address | ||
| 152 | # every time, which is nothing per command and a lot per ref in a loop. | ||
| 153 | sub _own_ref_re { | ||
| 154 | my ( $self, $base ) = @_; | ||
| 155 | $base //= $self->_ref; | ||
| 156 | return qr/\A\Q$base\E(?:\+([0-9]+))?\z/; | ||
| 157 | } | ||
| 158 | |||
| 159 | sub _segment_index { | ||
| 160 | my ( $self, $ref ) = @_; | ||
| 161 | return $ref =~ $self->_own_ref_re ? ( $1 // 0 ) + 0 : 0; | ||
| 162 | } | ||
| 163 | |||
| 164 | # Every segment of this identity that exists, oldest first -- which is also | ||
| 165 | # chronological order, because a segment is only ever appended to while it is | ||
| 166 | # the newest one. The glob is the base ref name, so it also catches any other | ||
| 167 | # identity whose encoded email merely starts with this one's; the regex is | ||
| 168 | # what makes the match exact. | ||
| 169 | sub _segment_refs { | ||
| 170 | my ($self) = @_; | ||
| 171 | my $base = $self->_ref; | ||
| 172 | my $re = $self->_own_ref_re($base); | ||
| 173 | my %index; | ||
| 174 | for my $ref ( $self->git->list_refs($base) ) { | ||
| 175 | $index{$ref} = ( $1 // 0 ) + 0 if $ref =~ $re; | ||
| 176 | } | ||
| 177 | return sort { $index{$a} <=> $index{$b} } keys %index; | ||
| 178 | } | ||
| 179 | |||
| 180 | # The segment an append goes to: the newest existing one, or segment 0 when | ||
| 181 | # this identity has never logged. Read through read_ref_with_oid so the caller | ||
| 182 | # gets the content together with the OID to guard the write against. | ||
| 183 | sub _active_segment { | ||
| 184 | my ($self) = @_; | ||
| 185 | my @refs = $self->_segment_refs; | ||
| 186 | return ( $self->_ref, undef, '' ) unless @refs; | ||
| 187 | my ( $oid, $content ) = $self->git->read_ref_with_oid( $refs[-1] ); | ||
| 188 | return ( $refs[-1], $oid, $content // '' ); | ||
| 189 | } | ||
| 190 | |||
| 191 | |||
| 192 | sub owns_ref { | ||
| 193 | my ( $self, $ref ) = @_; | ||
| 194 | return 0 unless defined $ref; | ||
| 195 | return $ref =~ $self->_own_ref_re ? 1 : 0; | ||
| 196 | } | ||
| 197 | |||
| 198 | # The lossy pre-#75 mapping, kept only to find refs written with it. | ||
| 199 | sub _legacy_sanitize { | ||
| 200 | my ( $self, $s ) = @_; | ||
| 201 | $s //= ''; | ||
| 202 | $s =~ s/[^a-zA-Z0-9._-]/_/g; | ||
| 203 | return $s; | ||
| 204 | } | ||
| 205 | |||
| 206 | # Ref names earlier karr versions logged to, oldest scheme first: before the | ||
| 207 | # role joined the identity the log was keyed by bare sanitized email, and up to | ||
| 208 | # #75 both components went through _legacy_sanitize. Nothing is migrated -- the | ||
| 209 | # names are only read (see entries), so no history is orphaned and no entry is | ||
| 210 | # ever counted twice. | ||
| 211 | sub _legacy_refs { | ||
| 212 | my ($self) = @_; | ||
| 213 | my $email = $self->_legacy_sanitize( $self->_email ); | ||
| 214 | my @refs; | ||
| 215 | push @refs, "refs/karr/log/$email" if $self->_role eq 'user'; | ||
| 216 | push @refs, 'refs/karr/log/' | ||
| 217 | . $self->_legacy_sanitize( $self->_role ) . "/$email"; | ||
| 218 | my $current = $self->_ref; | ||
| 219 | return grep { $_ ne $current } @refs; | ||
| 220 | } | ||
| 221 | |||
| 222 | |||
| 223 | sub log_entry { | ||
| 224 | my ($self, %entry) = @_; | ||
| 225 | $entry{ts} //= strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()); | ||
| 226 | my $ref = $self->_ref; | ||
| 227 | |||
| 228 | # _encode_component makes this unreachable for any identity; it stays as | ||
| 229 | # the guarantee that the check happens before the first write, not as the | ||
| 230 | # libgit2 exception halfway through one. | ||
| 231 | unless ( Git::Native->reference_name_is_valid($ref) ) { | ||
| 232 | warn "karr: not logging activity, '$ref' is not a valid git ref name\n"; | ||
| 233 | return 0; | ||
| 234 | } | ||
| 235 | |||
| 236 | my $line = json_encode(\%entry); | ||
| 237 | # Read-modify-write appended to the log ref used unguarded write_ref; two | ||
| 238 | # concurrent writers both read the same existing content, both wrote their | ||
| 239 | # append, and the loser overwrote the winner -- ticket #156: a task is | ||
| 240 | # saved, its log entry is dropped, and the log starts lying about what | ||
| 241 | # happened. read_ref_with_oid + write_ref_cas inside retry_contended turns | ||
| 242 | # the race into a textbook CAS that backs off and re-reads on contention. | ||
| 243 | # retry_contended treats an empty return as "lost the race, try again"; | ||
| 244 | # write_ref_cas returns 0 on contention, so we map that to () here. | ||
| 245 | # | ||
| 246 | # What the CAS is taken against is the *newest segment*, re-resolved on | ||
| 247 | # every attempt: rotation is as much a lost race as an append is, and a | ||
| 248 | # writer that cached the segment it saw before backing off would append to | ||
| 249 | # a segment another writer has already sealed. | ||
| 250 | return try { | ||
| 251 | $self->git->retry_contended( "log entry to $ref", sub { | ||
| 252 | my ( $segment, $current_oid, $current ) = $self->_active_segment; | ||
| 253 | |||
| 254 | # Rotate before the append, never after, so no segment is ever | ||
| 255 | # written past the cap and no entry is written twice. A full | ||
| 256 | # segment is simply left where it is -- immutable from here on -- | ||
| 257 | # and the entry opens the next one guarded with expected_old => | ||
| 258 | # undef, i.e. "only if that ref does not exist yet". Two writers | ||
| 259 | # rotating at the same moment therefore cannot clobber each other: | ||
| 260 | # the loser gets 0, re-reads, and appends to the segment the winner | ||
| 261 | # opened. An entry bigger than the whole cap still lands, in a | ||
| 262 | # segment of its own, rather than looping forever. | ||
| 263 | if ( length($current) | ||
| 264 | && length($current) + 1 + length($line) > $self->segment_max_bytes ) | ||
| 265 | { | ||
| 266 | $segment = $self->_segment_ref( $self->_segment_index($segment) + 1 ); | ||
| 267 | ( $current_oid, $current ) = ( undef, '' ); | ||
| 268 | } | ||
| 269 | |||
| 270 | my $new = length $current ? "$current\n$line" : $line; | ||
| 271 | return $self->git->write_ref_cas( $segment, $new, $current_oid ) ? 1 : (); | ||
| 272 | } ); | ||
| 273 | } catch { | ||
| 274 | warn "karr: activity log write to '$ref' failed: $_"; | ||
| 275 | 0; | ||
| 276 | }; | ||
| 277 | } | ||
| 278 | |||
| 279 | |||
| 280 | sub entries { | ||
| 281 | my ($self) = @_; | ||
| 282 | return map { $self->_entries_from($_) } | ||
| 283 | ( $self->_legacy_refs, $self->_segment_refs ); | ||
| 284 | } | ||
| 285 | |||
| 286 | sub _entries_from { | ||
| 287 | my ( $self, $ref ) = @_; | ||
| 288 | my $content = $self->git->read_ref($ref); | ||
| 289 | return () unless defined $content && length $content; | ||
| 290 | my @entries; | ||
| 291 | for my $line (split /\n/, $content) { | ||
| 292 | next unless length $line; | ||
| 293 | my $decoded = eval { json_decode($line) }; | ||
| 294 | push @entries, $self->git->maybe_repair_legacy($decoded) if $decoded; | ||
| 295 | } | ||
| 296 | return @entries; | ||
| 297 | } | ||
| 298 | |||
| 299 | |||
| 300 | sub last_entry { | ||
| 301 | my ($self) = @_; | ||
| 302 | for my $ref ( reverse( $self->_legacy_refs, $self->_segment_refs ) ) { | ||
| 303 | my @entries = $self->_entries_from($ref); | ||
| 304 | return $entries[-1] if @entries; | ||
| 305 | } | ||
| 306 | return undef; | ||
| 307 | } | ||
| 308 | |||
| 309 | 1; | ||
| 310 | |||
| 311 | __END__ | ||