lib/Langertha/Skeid/UsageStore/JsonLog.pm

filter: Statementstmt 91.8% 247 / 269 Branchbran 70.3% 90 / 128 Conditioncond 51.3% 58 / 113 MC/DCmcdc 19.6% 12 / 61 Subroutinesub 100% 27 / 27 Podpod 100% 6 / 6 totaltotal 72.8% 440 / 604 CC 116 SCAR 35.7
CC
116
Cov
77%
report
68.6
purge
51.2
store
16.1
CRAP 35.7
« lib/Langertha/Skeid/Protocol/Anthropic.pm ↑ Summary lib/Langertha/Skeid.pm »
1 package Langertha::Skeid::UsageStore::JsonLog;
2 31 our $VERSION = '0.005';
3 # ABSTRACT: Append-only JSON usage store - one file per event, or one line per event
4 31 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 31 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 31 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 31 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 31 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 31 ▶use Fcntl qw(O_WRONLY O_CREAT O_EXCL LOCK_EX);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 31 ▶use Errno qw(EEXIST EINTR);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 31 ▶use Digest::SHA qw(sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 31 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 31 ▶use File::Basename qw(dirname);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 31 ▶use File::Path qw(make_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 31 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 31 ▶use JSON::MaybeXS qw(encode_json decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 31 ▶use Langertha::Skeid::UsageStore;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19  
20 31 has path => (is => 'ro', required => 1);
21 6 ▶has mode => (is => 'ro', default => sub { 'dir' });
Subroutine __ANON__: called CC=1 SCAR=0.0
22  
23  
24 5 ▶has fsync => (is => 'ro', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
25  
26  
27 13 ▶sub backend { 'jsonlog' }
Subroutine backend: called CC=1 SCAR=0.0
Pod documented
28  
29  
30 49 ▶sub prepare {
Subroutine prepare: called CC=6 SCAR=19.0
Pod documented
31 49 my ($self) = @_;
32 49 my $path = $self->path;
33 49 ▶ if ($self->mode eq 'dir') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->mode eq 'dir') { } 35 14 49
34 35 ▶ make_path($path) unless -d $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $path 17 18 35
35 } else {
36 14 my $dir = dirname($path);
37 14 ▶ make_path($dir) if length($dir) && $dir ne '.' && !-d $dir;
Branch: 1 branch
BranchTrueFalseTotal
if length $dir and $dir ne "." and not -d $dir 0 14 14
Condition33%2/6
length $dir and $dir ne "." and not -d $dir
!ll&&!rl&&r
0140
length $dir and $dir ne "."
!ll&&!rl&&r
0014
MC/DC0%0/3
length $dir and $dir ne "." and not -d $dir
length $dir $dir ne "." not -d $dir
Truth table25%1/4
A and B and not(C)
A= length $dirB= $dir ne "."C= not -d $dir
ABCresult
0XX0
10X0
1100
1111
38 }
39 49 return 1;
40 }
41  
42  
43 48 ▶sub disconnect { return }
Subroutine disconnect: called CC=1 SCAR=0.0
Pod documented
44  
45 31 our %EVENT_ID_STATE;
46 31 my $CREATE_ATTEMPTS = 16;
47 31 my $PROCESS_NONCE_BYTES = 16;
48  
49 15 ▶sub _new_process_nonce {
Subroutine _new_process_nonce: called CC=7 SCAR=23.8
50 15 my $random = '';
51 15 ▶ if (open my $fh, '<:raw', '/dev/urandom') {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, "<:raw", "/dev/urandom") 15 0 15
52 15 ▶ while (length($random) < $PROCESS_NONCE_BYTES) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $random < $PROCESS_NONCE_BYTES) 15 15 30
53 15 my $chunk = '';
54 15 my $read = sysread($fh, $chunk, $PROCESS_NONCE_BYTES - length($random));
55 15 ▶ if (!defined $read) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $read) 0 15 15
56 0 ▶ next if $! == EINTR;
Branch: 1 branch
BranchTrueFalseTotal
if $! == 4 0 0 0
57 0 last;
58 }
59 15 ▶ last unless $read;
Branch: 1 branch
BranchTrueFalseTotal
unless $read 0 15 15
60 15 $random .= $chunk;
61 }
62 15 close $fh;
63 }
64 15 ▶ return unpack('H*', $random) if length($random) == $PROCESS_NONCE_BYTES;
Branch: 1 branch
BranchTrueFalseTotal
if length $random == $PROCESS_NONCE_BYTES 15 0 15
65  
66 # /dev/urandom is present on supported service platforms. Keep a portable
67 # best-effort fallback for other Perl targets without reseeding the process'
68 # global PRNG, which belongs to the application as a whole.
69 0 my $marker = {};
70 0 my @entropy = ($$, Time::HiRes::time(), "$marker", map { rand() } 1 .. 4);
71 0 return substr(sha256_hex(join("\0", @entropy)), 0, $PROCESS_NONCE_BYTES * 2);
72 }
73  
74 102 ▶sub _event_id {
Subroutine _event_id: called CC=3 SCAR=11.0
75 102 my $pid = $$;
76 102 ▶ if (!defined($EVENT_ID_STATE{pid}) || $EVENT_ID_STATE{pid} != $pid) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $Langertha::Skeid::UsageStore::JsonLog::EVENT_ID_STATE{"pid"} or $Langertha::Skeid::UsageStore::JsonLog::EVENT_ID_STATE{"pid"} != $pid) 20 82 102
Condition66%2/3
not defined $Langertha::Skeid::UsageStore::JsonLog::EVENT_ID_STATE{"pid"} or $Langertha::Skeid::UsageStore::JsonLog::EVENT_ID_STATE{"pid"} != $pid
l!l&&r!l&&!r
20082
MC/DC50%1/2
not defined $Langertha::Skeid::UsageStore::JsonLog::EVENT_ID_STATE{"pid"} or $Langertha::Skeid::UsageStore::JsonLog::EVENT_ID_STATE{"pid"} != $pid
not defined $Langertha::Skeid::UsageStore::JsonLog::EVENT_ID_STATE{"pid"} $Langertha::Skeid::UsageStore::JsonLog::EVENT_ID_STATE{"pid"} != $pid
Truth table66%2/3
not(A) or B
A= not defined $Langertha::Skeid::UsageStore::JsonLog::EVENT_ID_STATE{"pid"}B= $Langertha::Skeid::UsageStore::JsonLog::EVENT_ID_STATE{"pid"} != $pid
ABresult
1X1
011
000
77 20 %EVENT_ID_STATE = (
78 pid => $pid,
79 nonce => _new_process_nonce(),
80 sequence => 0,
81 );
82 }
83 102 my $sequence = ++$EVENT_ID_STATE{sequence};
84 102 my $ts = strftime('%Y%m%d-%H%M%S', gmtime());
85 102 return sprintf('%s-%d-%s-%010d', $ts, $pid, $EVENT_ID_STATE{nonce}, $sequence);
86 }
87  
88 3 ▶sub _io_error {
Subroutine _io_error: called CC=3 SCAR=12.5
89 3 my ($operation, $path, $reason) = @_;
90 3 ▶ $reason = 'unknown I/O error' unless defined($reason) && length($reason);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $reason and length $reason 0 3 3
Condition33%1/3
defined $reason and length $reason
!ll&&!rl&&r
003
MC/DC0%0/2
defined $reason and length $reason
defined $reason length $reason
Truth table33%1/3
A and B
A= defined $reasonB= length $reason
ABresult
0X0
100
111
91 3 return "Cannot $operation $path: $reason";
92 }
93  
94 100 ▶sub _write_and_close {
Subroutine _write_and_close: called CC=9 SCAR=22.1
95 100 my ($self, $fh, $path, $json, $operation) = @_;
96 100 my $error;
97  
98 100 ▶ unless (print {$fh} $json, "\n") {
Branch: 1 branch
BranchTrueFalseTotal
unless (print {$fh;} $json, "\n") 1 99 100
99 1 $error = _io_error($operation, $path, "$!");
100 }
101 100 ▶ if (!$error && $self->fsync) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $error and $self->fsync) 5 95 100
Condition100%3/3
not $error and $self->fsync
!ll&&!rl&&r
1945
MC/DC100%2/2
not $error and $self->fsync
not $error $self->fsync
Truth table100%3/3
not(A) and B
A= not $errorB= $self->fsync
ABresult
0X0
100
111
102 5 ▶ unless ($fh->flush) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($fh->flush) 0 5 5
103 0 $error = _io_error('flush', $path, "$!");
104 }
105 5 ▶ unless ($error || $fh->sync) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($error or $fh->sync) 1 4 5
Condition66%2/3
$error or $fh->sync
l!l&&r!l&&!r
041
MC/DC50%1/2
$error or $fh->sync
$error $fh->sync
Truth table66%2/3
A or B
A= $errorB= $fh->sync
ABresult
1X1
011
000
106 1 $error = _io_error('sync', $path, "$!");
107 }
108 }
109 100 ▶ unless (close $fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close $fh) 2 98 100
110 2 ▶ $error ||= _io_error('close', $path, "$!");
Condition66%2/3
$error ||= _io_error("close", $path, "$!")
l!l&&r!l&&!r
110
MC/DC0%0/2
$error ||= _io_error("close", $path, "$!")
$error _io_error("close", $path, "$!")
Truth table66%2/3
A ||= B
A= $errorB= _io_error("close", $path, "$!")
ABresult
1X1
011
000
111 }
112  
113 100 return $error;
114 }
115  
116  
117 102 ▶sub store {
Subroutine store: called CC=14 SCAR=27.8
Pod documented
118 102 my ($self, $event) = @_;
119  
120 102 ▶ if ($self->mode eq 'dir') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->mode eq "dir") 70 32 102
121 70 for (1 .. $CREATE_ATTEMPTS) {
122 86 my $id = _event_id();
123 86 my $json = encode_json({ %$event, id => $id });
124 86 my $file = File::Spec->catfile($self->path, "${id}.json");
125 86 my $fh;
126 86 ▶ unless (sysopen $fh, $file, O_WRONLY | O_CREAT | O_EXCL, 0666) {
Branch: 1 branch
BranchTrueFalseTotal
unless (sysopen $fh, $file, 193, 438) 18 68 86
127 18 ▶ next if $! == EEXIST;
Branch: 1 branch
BranchTrueFalseTotal
if $! == 17 17 1 18
128 1 return { ok => 0, error => "Cannot write $file: $!" };
129 }
130 68 my $error = _write_and_close($self, $fh, $file, $json, 'write');
131 68 ▶ if ($error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error) 2 66 68
132 2 unlink $file;
133 2 return { ok => 0, error => $error };
134 }
135 66 return { ok => 1, id => $id };
136 }
137 return {
138 1 ok => 0,
139 error => "Cannot store usage event: event id collisions exhausted $CREATE_ATTEMPTS attempts",
140 };
141 }
142  
143 32 my $id = _event_id();
144 32 my $json = encode_json({ %$event, id => $id });
145 32 my $path = $self->path;
146 32 my $fh;
147 # A purge replaces the file by renaming a rewritten copy over it, under this same lock. An
148 # append that opened the old file and waited for the lock would write into the replaced file
149 # and be lost, so after the lock it checks that it still holds the file at $path.
150 32 for (1 .. $CREATE_ATTEMPTS) {
151 32 ▶ open $fh, '>>', $path or return { ok => 0, error => "Cannot append $path: $!" };
Branch: 1 branch
BranchTrueFalseTotal
open $fh, ">>", $path or return {"ok", 0, "error", "Cannot append ${path}: $!"} 32 0 32
152 32 ▶ unless (flock($fh, LOCK_EX)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (flock $fh, 2) 0 32 32
153 0 my $error = _io_error('lock', $path, "$!");
154 0 close $fh;
155 0 return { ok => 0, error => $error };
156 }
157 32 my @held = stat $fh;
158 32 my @now = stat $path;
159 32 ▶ last if @now && $held[0] == $now[0] && $held[1] == $now[1];
Branch: 1 branch
BranchTrueFalseTotal
if @now and $held[0] == $now[0] and $held[1] == $now[1] 32 0 32
Condition33%2/6
@now and $held[0] == $now[0] and $held[1] == $now[1]
!ll&&!rl&&r
0032
@now and $held[0] == $now[0]
!ll&&!rl&&r
0032
MC/DC0%0/3
@now and $held[0] == $now[0] and $held[1] == $now[1]
@now $held[0] == $now[0] $held[1] == $now[1]
Truth table25%1/4
A and B and C
A= @nowB= $held[0] == $now[0]C= $held[1] == $now[1]
ABCresult
0XX0
10X0
1100
1111
160 0 close $fh;
161 0 undef $fh;
162 }
163 32 ▶ return { ok => 0, error => "Cannot append $path: it was replaced while waiting for the lock" } unless $fh;
Branch: 1 branch
BranchTrueFalseTotal
unless $fh 0 32 32
164 32 my $error = _write_and_close($self, $fh, $path, $json, 'append');
165 32 ▶ return { ok => 0, error => $error } if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 1 31 32
166  
167 31 return { ok => 1, id => $id };
168 }
169  
170  
171 13 ▶sub purge {
Subroutine purge: called CC=31 SCAR=39.4
Pod documented
172 13 my ($self, $request) = @_;
173 56 ▶ my $matches = sub {
Subroutine __ANON__: called CC=8 SCAR=21.0
174 56 my ($ev) = @_;
175 56 ▶ return 0 unless ref($ev) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ev eq "HASH" 0 56 56
176 56 ▶ if (my $ids = $request->{api_key_ids}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ids = $request->{"api_key_ids"}) 47 9 56
177 47 ▶ my $id = $ev->{api_key_id} // '';
Condition50%1/2
$ev->{"api_key_id"} // ""
l!l
470
MC/DC0%0/1
$ev->{"api_key_id"} // ""
$ev->{"api_key_id"}
Truth table50%1/2
A
A= $ev->{"api_key_id"}
Aresult
11
00
178 47 ▶ return 0 unless grep { $_ eq $id } @$ids;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $id;} @$ids 26 21 47
179 }
180 30 ▶ return 0 if defined($request->{before}) && !(($ev->{created_at} // '') lt $request->{before});
Branch: 1 branch
BranchTrueFalseTotal
if defined $request->{"before"} and not +($ev->{"created_at"} // "") lt $request->{"before"} 5 25 30
Condition80%4/5
defined $request->{"before"} and not +($ev->{"created_at"} // "") lt $request->{"before"}
!ll&&!rl&&r
2145
$ev->{"created_at"} // ""
l!l
90
MC/DC0%0/2
defined $request->{"before"} and not +($ev->{"created_at"} // "") lt $request->{"before"}
defined $request->{"before"} $ev->{"created_at"}
Truth table66%2/3
A and not(B)
A= defined $request->{"before"}B= $ev->{"created_at"}
ABresult
0X0
110
101
181 25 return 1;
182 13 };
183  
184 13 ▶ if ($self->mode eq 'dir') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->mode eq "dir") 4 9 13
185 4 my ($matched, $deleted) = (0, 0);
186 4 for my $file (sort glob(File::Spec->catfile($self->path, '*.json'))) {
187 14 my $text = eval { Langertha::Skeid::UsageStore::read_text_file($file) };
188 14 ▶ next unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 0 14 14
189 14 my $ev = eval { decode_json($text) };
190 14 ▶ next unless $matches->($ev);
Branch: 1 branch
BranchTrueFalseTotal
unless &$matches($ev) 7 7 14
191 7 $matched++;
192 7 ▶ next if $request->{dry_run};
Branch: 1 branch
BranchTrueFalseTotal
if $request->{"dry_run"} 3 4 7
193 4 ▶ unlink($file) or return { ok => 0, error => "Cannot remove $file: $!", matched => $matched, deleted => $deleted };
Branch: 1 branch
BranchTrueFalseTotal
unlink $file or return {"ok", 0, "error", "Cannot remove ${file}: $!", "matched", $matched, "deleted", $deleted} 4 0 4
194 4 $deleted++;
195 }
196 4 return { ok => 1, matched => $matched, deleted => $deleted };
197 }
198  
199 9 my $path = $self->path;
200 9 ▶ return { ok => 1, matched => 0, deleted => 0 } unless -e $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $path 0 9 9
201 # The lock must be on the file at $path: another purge may have renamed a rewritten copy over
202 # it while this one waited, and a lock on the replaced file guards nothing.
203 9 my $lock;
204 9 for (1 .. $CREATE_ATTEMPTS) {
205 9 ▶ open $lock, '>>', $path or return { ok => 0, error => "Cannot open $path: $!" };
Branch: 1 branch
BranchTrueFalseTotal
open $lock, ">>", $path or return {"ok", 0, "error", "Cannot open ${path}: $!"} 9 0 9
206 9 ▶ flock($lock, LOCK_EX) or return { ok => 0, error => _io_error('lock', $path, "$!") };
Branch: 1 branch
BranchTrueFalseTotal
flock $lock, 2 or return {"ok", 0, "error", _io_error("lock", $path, "$!")} 9 0 9
207 9 my @held = stat $lock;
208 9 my @now = stat $path;
209 9 ▶ last if @now && $held[0] == $now[0] && $held[1] == $now[1];
Branch: 1 branch
BranchTrueFalseTotal
if @now and $held[0] == $now[0] and $held[1] == $now[1] 9 0 9
Condition33%2/6
@now and $held[0] == $now[0] and $held[1] == $now[1]
!ll&&!rl&&r
009
@now and $held[0] == $now[0]
!ll&&!rl&&r
009
MC/DC0%0/3
@now and $held[0] == $now[0] and $held[1] == $now[1]
@now $held[0] == $now[0] $held[1] == $now[1]
Truth table25%1/4
A and B and C
A= @nowB= $held[0] == $now[0]C= $held[1] == $now[1]
ABCresult
0XX0
10X0
1100
1111
210 0 close $lock;
211 0 undef $lock;
212 }
213 9 ▶ return { ok => 0, error => "Cannot purge $path: it kept being replaced" } unless $lock;
Branch: 1 branch
BranchTrueFalseTotal
unless $lock 0 9 9
214 9 my $mode = (stat $lock)[2] & 07777;
215 9 ▶ open my $in, '<', $path or return { ok => 0, error => "Cannot read $path: $!" };
Branch: 1 branch
BranchTrueFalseTotal
open my $in, "<", $path or return {"ok", 0, "error", "Cannot read ${path}: $!"} 9 0 9
216 9 my ($matched, @keep) = (0);
217 9 ▶ while (my $line = <$in>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $in)) 42 9 51
218 42 my $text = $line;
219 42 chomp $text;
220 42 ▶ my $ev = length($text) ? eval { decode_json($text) } : undef;
Branch: 1 branch
BranchTrueFalseTotal
length $text ? : 42 0 42
221 42 ▶ if ($matches->($ev)) { $matched++; next }
Branch: 1 branch
BranchTrueFalseTotal
if (&$matches($ev)) 18 24 42
222 24 push @keep, $line;
223 }
224 9 close $in;
225 9 ▶ return { ok => 1, matched => $matched, deleted => 0 } if $request->{dry_run} || !$matched;
Branch: 1 branch
BranchTrueFalseTotal
if $request->{"dry_run"} or not $matched 4 5 9
Condition100%3/3
$request->{"dry_run"} or not $matched
l!l&&r!l&&!r
315
MC/DC100%2/2
$request->{"dry_run"} or not $matched
$request->{"dry_run"} not $matched
Truth table100%3/3
A or not(B)
A= $request->{"dry_run"}B= not $matched
ABresult
1X1
011
000
226  
227 5 my $tmp = "$path.purge-$$";
228 # The rewritten file keeps the old one's permissions: a 0600 usage log stays 0600.
229 5 ▶ sysopen(my $out, $tmp, O_WRONLY | O_CREAT | O_EXCL, 0600)
Branch: 1 branch
BranchTrueFalseTotal
sysopen my $out, $tmp, 193, 384 or return {"ok", 0, "error", "Cannot write ${tmp}: $!"} 5 0 5
230 or return { ok => 0, error => "Cannot write $tmp: $!" };
231 5 chmod $mode, $tmp;
232 5 my $error;
233 5 ▶ print {$out} @keep or $error = _io_error('write', $tmp, "$!");
Branch: 1 branch
BranchTrueFalseTotal
print {$out;} @keep or $error = _io_error("write", $tmp, "$!") 5 0 5
234 5 ▶ if (!$error && $self->fsync) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $error and $self->fsync) 0 5 5
Condition33%1/3
not $error and $self->fsync
!ll&&!rl&&r
050
MC/DC0%0/2
not $error and $self->fsync
not $error $self->fsync
Truth table33%1/3
not(A) and B
A= not $errorB= $self->fsync
ABresult
0X0
100
111
235 0 ▶ ($out->flush && $out->sync) or $error = _io_error('sync', $tmp, "$!");
Branch: 1 branch
BranchTrueFalseTotal
$out->flush and $out->sync or $error = _io_error("sync", $tmp, "$!") 0 0 0
Condition0%0/3
$out->flush and $out->sync
!ll&&!rl&&r
000
MC/DC0%0/2
$out->flush and $out->sync
$out->flush $out->sync
Truth table0%0/3
A and B
A= $out->flushB= $out->sync
ABresult
0X0
100
111
236 }
237 5 ▶ close($out) or $error ||= _io_error('close', $tmp, "$!");
Branch: 1 branch
BranchTrueFalseTotal
close $out or $error ||= _io_error("close", $tmp, "$!") 5 0 5
Condition0%0/3
$error ||= _io_error("close", $tmp, "$!")
l!l&&r!l&&!r
000
MC/DC0%0/2
$error ||= _io_error("close", $tmp, "$!")
$error _io_error("close", $tmp, "$!")
Truth table0%0/3
A ||= B
A= $errorB= _io_error("close", $tmp, "$!")
ABresult
1X1
011
000
238 0 ▶ if ($error) { unlink $tmp; return { ok => 0, error => $error } }
Branch: 1 branch
BranchTrueFalseTotal
if ($error) 0 5 5
239 5 ▶ unless (rename $tmp, $path) {
Branch: 1 branch
BranchTrueFalseTotal
unless (rename $tmp, $path) 0 5 5
240 0 my $err = "Cannot replace $path: $!";
241 0 unlink $tmp;
242 0 return { ok => 0, error => $err };
243 }
244 5 close $lock;
245 5 return { ok => 1, matched => $matched, deleted => $matched };
246 }
247  
248  
249 41 ▶sub report {
Subroutine report: called CC=43 SCAR=42.3
Pod documented
250 41 my ($self, $filters) = @_;
251 41 ▶ $filters ||= {};
Condition50%1/2
$filters ||= {}
l!l
410
MC/DC0%0/1
$filters ||= {}
$filters
Truth table50%1/2
A
A= $filters
Aresult
11
00
252 41 my $num = \&Langertha::Skeid::UsageStore::num;
253  
254 41 my @events;
255 41 ▶ if ($self->mode eq 'dir') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->mode eq 'dir') { } 31 10 41
256 31 my @files = sort glob(File::Spec->catfile($self->path, '*.json'));
257 31 for my $file (@files) {
258 101 my $text = eval { Langertha::Skeid::UsageStore::read_text_file($file) };
259 101 ▶ next unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 0 101 101
260 101 my $ev = eval { decode_json($text) };
261 101 ▶ push @events, $ev if ref($ev) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $ev eq "HASH" 101 0 101
262 }
263 } else {
264 10 ▶ if (open my $fh, '<', $self->path) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, "<", $self->path) 10 0 10
265 10 ▶ while (my $line = <$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 26 10 36
266 26 chomp $line;
267 26 ▶ next unless length $line;
Branch: 1 branch
BranchTrueFalseTotal
unless length $line 0 26 26
268 26 my $ev = eval { decode_json($line) };
269 26 ▶ push @events, $ev if ref($ev) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $ev eq "HASH" 26 0 26
270 }
271 10 close $fh;
272 }
273 }
274  
275 41 ▶ if (defined $filters->{since} && length $filters->{since}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $filters->{"since"} and length $filters->{"since"}) 0 41 41
Condition33%1/3
defined $filters->{"since"} and length $filters->{"since"}
!ll&&!rl&&r
4100
MC/DC0%0/2
defined $filters->{"since"} and length $filters->{"since"}
defined $filters->{"since"} length $filters->{"since"}
Truth table33%1/3
A and B
A= defined $filters->{"since"}B= length $filters->{"since"}
ABresult
0X0
100
111
276 0 ▶ @events = grep { ($_->{created_at} // '') ge $filters->{since} } @events;
Condition0%0/2
$_->{"created_at"} // ""
l!l
00
MC/DC0%0/1
$_->{"created_at"} // ""
$_->{"created_at"}
Truth table0%0/2
A
A= $_->{"created_at"}
Aresult
11
00
277 }
278 41 ▶ if (defined $filters->{api_key_id} && length $filters->{api_key_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $filters->{"api_key_id"} and length $filters->{"api_key_id"}) 8 33 41
Condition66%2/3
defined $filters->{"api_key_id"} and length $filters->{"api_key_id"}
!ll&&!rl&&r
3308
MC/DC50%1/2
defined $filters->{"api_key_id"} and length $filters->{"api_key_id"}
defined $filters->{"api_key_id"} length $filters->{"api_key_id"}
Truth table66%2/3
A and B
A= defined $filters->{"api_key_id"}B= length $filters->{"api_key_id"}
ABresult
0X0
100
111
279 8 ▶ @events = grep { ($_->{api_key_id} // '') eq $filters->{api_key_id} } @events;
Condition50%1/2
$_->{"api_key_id"} // ""
l!l
170
MC/DC0%0/1
$_->{"api_key_id"} // ""
$_->{"api_key_id"}
Truth table50%1/2
A
A= $_->{"api_key_id"}
Aresult
11
00
280 }
281 41 ▶ if (defined $filters->{model} && length $filters->{model}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $filters->{"model"} and length $filters->{"model"}) 1 40 41
Condition66%2/3
defined $filters->{"model"} and length $filters->{"model"}
!ll&&!rl&&r
4001
MC/DC50%1/2
defined $filters->{"model"} and length $filters->{"model"}
defined $filters->{"model"} length $filters->{"model"}
Truth table66%2/3
A and B
A= defined $filters->{"model"}B= length $filters->{"model"}
ABresult
0X0
100
111
282 1 ▶ @events = grep { ($_->{model} // '') eq $filters->{model} } @events;
Condition50%1/2
$_->{"model"} // ""
l!l
20
MC/DC0%0/1
$_->{"model"} // ""
$_->{"model"}
Truth table50%1/2
A
A= $_->{"model"}
Aresult
11
00
283 }
284  
285 41 my %totals = (requests => 0, input_tokens => 0, output_tokens => 0, total_tokens => 0, cached_tokens => 0, cache_write_tokens => 0, tool_calls => 0, audio_seconds => 0, documents => 0, pages => 0, total_cost_usd => 0);
286 41 my (%by_key, %by_model);
287 41 for my $ev (@events) {
288 115 $totals{requests}++;
289 115 $totals{input_tokens} += $num->($ev->{input_tokens});
290 115 $totals{output_tokens} += $num->($ev->{output_tokens});
291 115 $totals{total_tokens} += $num->($ev->{total_tokens});
292 # Old events predate the field and read undef; num() treats that as zero (k27).
293 115 $totals{cached_tokens} += $num->($ev->{cached_tokens});
294 115 $totals{cache_write_tokens} += $num->($ev->{cache_write_tokens});
295 115 $totals{tool_calls} += $num->($ev->{tool_calls});
296 # Only an audio route's event carries it (skeid k91); every other event adds nothing.
297 115 $totals{audio_seconds} += $num->($ev->{audio_seconds});
298 # Likewise the documents of a rerank event (skeid k92).
299 115 $totals{documents} += $num->($ev->{documents});
300 # And the pages a documents event read off its answer (skeid k94).
301 115 $totals{pages} += $num->($ev->{pages});
302 115 $totals{total_cost_usd} += $num->($ev->{cost_total_usd});
303  
304 115 ▶ my $kid = $ev->{api_key_id} // '';
Condition50%1/2
$ev->{"api_key_id"} // ""
l!l
1150
MC/DC0%0/1
$ev->{"api_key_id"} // ""
$ev->{"api_key_id"}
Truth table50%1/2
A
A= $ev->{"api_key_id"}
Aresult
11
00
305 115 $by_key{$kid}{requests}++;
306 115 $by_key{$kid}{total_tokens} += $num->($ev->{total_tokens});
307 115 $by_key{$kid}{audio_seconds} += $num->($ev->{audio_seconds});
308 115 $by_key{$kid}{documents} += $num->($ev->{documents});
309 115 $by_key{$kid}{pages} += $num->($ev->{pages});
310 115 $by_key{$kid}{total_cost_usd} += $num->($ev->{cost_total_usd});
311  
312 115 ▶ my $mid = $ev->{model} // '';
Condition50%1/2
$ev->{"model"} // ""
l!l
1150
MC/DC0%0/1
$ev->{"model"} // ""
$ev->{"model"}
Truth table50%1/2
A
A= $ev->{"model"}
Aresult
11
00
313 115 $by_model{$mid}{requests}++;
314 115 $by_model{$mid}{total_tokens} += $num->($ev->{total_tokens});
315 115 $by_model{$mid}{audio_seconds} += $num->($ev->{audio_seconds});
316 115 $by_model{$mid}{documents} += $num->($ev->{documents});
317 115 $by_model{$mid}{pages} += $num->($ev->{pages});
318 115 $by_model{$mid}{total_cost_usd} += $num->($ev->{cost_total_usd});
319 }
320  
321 41 ▶ my $limit = $filters->{limit} // 20;
Condition50%1/2
$filters->{"limit"} // 20
l!l
410
MC/DC0%0/1
$filters->{"limit"} // 20
$filters->{"limit"}
Truth table50%1/2
A
A= $filters->{"limit"}
Aresult
11
00
322 41 my @recent = reverse @events;
323 41 ▶ @recent = @recent[0 .. $limit - 1] if @recent > $limit;
Branch: 1 branch
BranchTrueFalseTotal
if @recent > $limit 1 40 41
324  
325 return {
326 ok => 1,
327 enabled => 1,
328 backend => 'jsonlog',
329 log_path => $self->path,
330 since => ($filters->{since} // ''),
331 totals => \%totals,
332 by_key => [ map {
333 +{ api_key_id => $_, requests => $by_key{$_}{requests}, total_tokens => $by_key{$_}{total_tokens}, audio_seconds => $by_key{$_}{audio_seconds}, documents => $by_key{$_}{documents}, pages => $by_key{$_}{pages}, total_cost_usd => $by_key{$_}{total_cost_usd} }
334 80 ▶ } sort { ($by_key{$b}{total_cost_usd} || 0) <=> ($by_key{$a}{total_cost_usd} || 0) or $a cmp $b } keys %by_key ],
Condition42%3/7
($by_key{$b}{'total_cost_usd'} || 0) <=> ($by_key{$a}{'total_cost_usd'} || 0) || $a cmp $b
l!l&&r!l&&!r
0840
$by_key{$b}{'total_cost_usd'} || 0
l!l
084
$by_key{$a}{'total_cost_usd'} || 0
l!l
084
MC/DC0%0/2
($by_key{$b}{'total_cost_usd'} || 0) <=> ($by_key{$a}{'total_cost_usd'} || 0) || $a cmp $b
$by_key{$b}{'total_cost_usd'} $a cmp $b
MC/DC0%0/1
$by_key{$a}{'total_cost_usd'} || 0
$by_key{$a}{'total_cost_usd'}
Truth table33%1/3
A || B
A= $by_key{$b}{'total_cost_usd'}B= $a cmp $b
ABresult
1X1
011
000
Truth table50%1/2
A
A= $by_key{$a}{'total_cost_usd'}
Aresult
11
00
335 by_model => [ map {
336 +{ model => $_, requests => $by_model{$_}{requests}, total_tokens => $by_model{$_}{total_tokens}, audio_seconds => $by_model{$_}{audio_seconds}, documents => $by_model{$_}{documents}, pages => $by_model{$_}{pages}, total_cost_usd => $by_model{$_}{total_cost_usd} }
337 70 ▶ } sort { ($by_model{$b}{total_cost_usd} || 0) <=> ($by_model{$a}{total_cost_usd} || 0) or $a cmp $b } keys %by_model ],
Condition42%3/7
($by_model{$b}{'total_cost_usd'} || 0) <=> ($by_model{$a}{'total_cost_usd'} || 0) || $a cmp $b
l!l&&r!l&&!r
0760
$by_model{$b}{'total_cost_usd'} || 0
l!l
076
$by_model{$a}{'total_cost_usd'} || 0
l!l
076
MC/DC0%0/2
($by_model{$b}{'total_cost_usd'} || 0) <=> ($by_model{$a}{'total_cost_usd'} || 0) || $a cmp $b
$by_model{$b}{'total_cost_usd'} $a cmp $b
MC/DC0%0/1
$by_model{$a}{'total_cost_usd'} || 0
$by_model{$a}{'total_cost_usd'}
Truth table33%1/3
A || B
A= $by_model{$b}{'total_cost_usd'}B= $a cmp $b
ABresult
1X1
011
000
Truth table50%1/2
A
A= $by_model{$a}{'total_cost_usd'}
Aresult
11
00
338 recent => [ map {
339 41 ▶ +{
Condition50%1/2
$filters->{"since"} // ""
l!l
041
MC/DC0%0/1
$filters->{"since"} // ""
$filters->{"since"}
Truth table50%1/2
A
A= $filters->{"since"}
Aresult
11
00
340 id => ($_->{id} // ''), created_at => ($_->{created_at} // ''), api_format => ($_->{api_format} // ''),
341 endpoint => ($_->{endpoint} // ''), api_key_id => ($_->{api_key_id} // ''), model => ($_->{model} // ''),
342 requested_model => ($_->{requested_model} // $_->{model} // ''),
343 (defined($_->{routed_model}) && length($_->{routed_model}) ? (routed_model => $_->{routed_model}) : ()),
344 node_id => ($_->{node_id} // ''), status_code => $num->($_->{status_code}), ok => ($_->{ok} ? 1 : 0),
345 input_tokens => $num->($_->{input_tokens}), output_tokens => $num->($_->{output_tokens}),
346 total_tokens => $num->($_->{total_tokens}), cached_tokens => $num->($_->{cached_tokens}),
347 cache_write_tokens => $num->($_->{cache_write_tokens}),
348 tool_calls => $num->($_->{tool_calls}),
349 114 ▶ cost_total_usd => $num->($_->{cost_total_usd}),
Branch: 2 branches
BranchTrueFalseTotal
defined $_->{'routed_model'} && length $_->{'routed_model'} ? : 0 114 114
$_->{'ok'} ? : 109 5 114
Condition68%15/22
$_->{"id"} // ""
l!l
1131
$_->{"created_at"} // ""
l!l
1140
$_->{"api_format"} // ""
l!l
1131
$_->{"endpoint"} // ""
l!l
1131
$_->{"api_key_id"} // ""
l!l
1140
$_->{"model"} // ""
l!l
1140
($_->{"requested_model"} // $_->{"model"}) // ""
l!l
1140
$_->{"requested_model"} // $_->{"model"}
l!l&&r!l&&!r
11310
defined $_->{"routed_model"} and length $_->{"routed_model"}
!ll&&!rl&&r
11400
$_->{"node_id"} // ""
l!l
1131
MC/DC100%1/1
$_->{"id"} // ""
$_->{"id"}
MC/DC0%0/1
$_->{"created_at"} // ""
$_->{"created_at"}
MC/DC100%1/1
$_->{"api_format"} // ""
$_->{"api_format"}
MC/DC100%1/1
$_->{"endpoint"} // ""
$_->{"endpoint"}
MC/DC0%0/1
$_->{"api_key_id"} // ""
$_->{"api_key_id"}
MC/DC0%0/1
$_->{"model"} // ""
$_->{"model"}
MC/DC0%0/2
($_->{"requested_model"} // $_->{"model"}) // ""
$_->{"requested_model"} $_->{"model"}
MC/DC0%0/2
defined $_->{"routed_model"} and length $_->{"routed_model"}
defined $_->{"routed_model"} length $_->{"routed_model"}
MC/DC100%1/1
$_->{"node_id"} // ""
$_->{"node_id"}
Truth table100%2/2
A
A= $_->{"id"}
Aresult
11
00
Truth table50%1/2
A
A= $_->{"created_at"}
Aresult
11
00
Truth table100%2/2
A
A= $_->{"api_format"}
Aresult
11
00
Truth table100%2/2
A
A= $_->{"endpoint"}
Aresult
11
00
Truth table50%1/2
A
A= $_->{"api_key_id"}
Aresult
11
00
Truth table50%1/2
A
A= $_->{"model"}
Aresult
11
00
Truth table66%2/3
A // B
A= $_->{"requested_model"}B= $_->{"model"}
ABresult
1X1
011
000
Truth table33%1/3
A and B
A= defined $_->{"routed_model"}B= length $_->{"routed_model"}
ABresult
0X0
100
111
Truth table100%2/2
A
A= $_->{"node_id"}
Aresult
11
00
350 }
351 } @recent ],
352 };
353 }
354  
355  
356 31 1;
357  
358 __END__
« lib/Langertha/Skeid/Protocol/Anthropic.pm ↑ Summary lib/Langertha/Skeid.pm »