blib/lib/Langertha/Skeid/UsageStore/DBI.pm

filter: Statementstmt 95.4% 254 / 266 Branchbran 72.4% 71 / 98 Conditioncond 46.3% 44 / 95 MC/DCmcdc 7.8% 4 / 51 Subroutinesub 100% 42 / 42 Podpod 100% 7 / 7 totaltotal 75.4% 422 / 559 CC 97 SCAR 29.9
CC
97
Cov
80%
_report
72.8
dbh
20.0
shipped_schema_file
12.5
CRAP 19.8
« blib/lib/Langertha/Skeid/Protocol/Anthropic/Stream.pm ↑ Summary blib/lib/Langertha/Skeid/Protocol/Ollama.pm »
1 package Langertha::Skeid::UsageStore::DBI;
2 9 our $VERSION = '0.003';
3 # ABSTRACT: SQLite and PostgreSQL usage store
4 9 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 9 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 9 ▶use File::Basename qw(dirname);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 9 ▶use File::Path qw(make_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 9 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 9 ▶use File::ShareDir qw(dist_dir);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 9 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 9 ▶use Scalar::Util qw(weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 9 ▶use Langertha::Skeid::UsageStore;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16  
17 9 has backend => (is => 'ro', required => 1);
18 9 has dsn => (is => 'ro', required => 1);
19 13 ▶has user => (is => 'ro', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
20 13 ▶has password => (is => 'ro', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
21 3 ▶has path => (is => 'ro', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
22 13 ▶has schema_file => (is => 'ro', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
23 13 ▶has auto_migrate => (is => 'ro', default => sub { 1 });
Subroutine __ANON__: called CC=1 SCAR=0.0
24 8 ▶has flush_interval_ms => (is => 'ro', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
25 9 has on_lost => (is => 'rw');
26  
27 9 has _dbh => (is => 'rw');
28 31 ▶has _queue => (is => 'ro', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
29 9 has _flush_timer => (is => 'rw');
30  
31  
32 27 ▶sub prepare {
Subroutine prepare: called CC=9 SCAR=22.1
Pod documented
33 27 my ($self) = @_;
34 27 ▶ my $dbh = $self->dbh or return;
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = $self->dbh or return 27 0 27
35 27 ▶ return 1 unless $self->auto_migrate;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->auto_migrate 0 27 27
36  
37 27 my $schema_file = $self->schema_file;
38 27 ▶ $schema_file = $self->shipped_schema_file unless length $schema_file;
Branch: 1 branch
BranchTrueFalseTotal
unless length $schema_file 27 0 27
39 27 ▶ croak "usage schema file not found: $schema_file" unless -f $schema_file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $schema_file 0 27 27
40  
41 27 my $sql = Langertha::Skeid::UsageStore::read_text_file($schema_file);
42 135 my @stmts = grep { /\S/ } map {
43 27 my $s = $_;
44 135 $s =~ s/^\s+//;
45 135 $s =~ s/\s+$//;
46 135 $s;
47 } split /;\s*(?:\n|$)/, $sql;
48 # Tables first, then any column an older table is missing, then the rest. The index
49 # statements reference columns, so on an upgraded table they only work after the ALTER --
50 # running the file top to bottom fails on exactly the deployments this exists for.
51 27 my (@tables, @rest);
52 27 for my $stmt (@stmts) {
53 135 ▶ if ($stmt =~ /\A\s*CREATE\s+TABLE\b/i) { push @tables, $stmt }
Branch: 1 branch
BranchTrueFalseTotal
if ($stmt =~ /\A\s*CREATE\s+TABLE\b/i) { } 27 108 135
54 108 else { push @rest, $stmt }
55 }
56 27 $dbh->do($_) for @tables;
57 27 $self->_add_missing_columns($dbh);
58 27 $dbh->do($_) for @rest;
59 27 return 1;
60 }
61  
62 # The shipped schema is CREATE TABLE IF NOT EXISTS, so it does nothing to a table that already
63 # exists -- a deployment that upgrades Skeid keeps its old columns and every insert naming a
64 # new one fails. Usage failures are reported rather than thrown, so that would show up as
65 # silently missing billing data. Adding the column is the whole migration story; nothing here
66 # ever drops or rewrites one.
67 9 my @ADDED_COLUMNS = (
68 ['requested_model', 'TEXT'],
69 # Prompt-cache read count (k27). Nullable on purpose: an old row that predates it reads NULL
70 # ("was not measured"), which is not the same as a measured zero. BIGINT is INTEGER affinity
71 # in SQLite and a 64-bit integer in PostgreSQL, so one type serves both ALTER statements.
72 ['cached_tokens', 'BIGINT'],
73 # UTF-8 bytes a streamed request relayed (skeid #36). Nullable: only streamed events carry it.
74 ['content_bytes', 'BIGINT'],
75 # Prompt-cache read / write cost (skeid #28), already part of cost_total_usd. Nullable: an old
76 # row reads NULL ("was not priced apart"). DOUBLE PRECISION is REAL affinity in SQLite.
77 ['cost_cache_read_usd', 'DOUBLE PRECISION'],
78 ['cost_cache_write_usd', 'DOUBLE PRECISION'],
79 # Prompt-cache write count (skeid #41), beside cached_tokens. Nullable: an old row reads NULL.
80 ['cache_write_tokens', 'BIGINT'],
81 );
82  
83 27 ▶sub _add_missing_columns {
Subroutine _add_missing_columns: called CC=5 SCAR=16.1
84 27 my ($self, $dbh) = @_;
85  
86 27 ▶ my $existing = eval {
Branch: 1 branch
BranchTrueFalseTotal
my $existing = eval { do { my $sth = $dbh->prepare("SELECT * FROM usage_events WHERE 1=0"); $sth->execute; my(%cols) = map({lc $_, 1;} @{$sth->{"NAME_lc"} or [];}); $sth->finish; \%cols } } or return 27 0 27
87 27 my $sth = $dbh->prepare('SELECT * FROM usage_events WHERE 1=0');
88 27 $sth->execute;
89 27 ▶ my %cols = map { lc($_) => 1 } @{ $sth->{NAME_lc} || [] };
Condition50%1/2
$sth->{'NAME_lc'} || []
l!l
270
MC/DC0%0/1
$sth->{'NAME_lc'} || []
$sth->{'NAME_lc'}
Truth table50%1/2
A
A= $sth->{'NAME_lc'}
Aresult
11
00
90 27 $sth->finish;
91 27 \%cols;
92 } or return;
93  
94 27 for my $column (@ADDED_COLUMNS) {
95 162 my ($name, $type) = @$column;
96 162 ▶ next if $existing->{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $existing->{$name} 143 19 162
97 19 eval { $dbh->do("ALTER TABLE usage_events ADD COLUMN $name $type") };
98 }
99 27 return 1;
100 }
101  
102  
103 89 ▶sub dbh {
Subroutine dbh: called CC=12 SCAR=29.9
Pod documented
104 89 my ($self) = @_;
105 89 my $cached = $self->_dbh;
106 89 ▶ return $cached if $cached;
Branch: 1 branch
BranchTrueFalseTotal
if $cached 54 35 89
107 35 ▶ return unless length($self->backend) && length($self->dsn);
Branch: 1 branch
BranchTrueFalseTotal
unless length $self->backend and length $self->dsn 0 35 35
Condition33%1/3
length $self->backend and length $self->dsn
!ll&&!rl&&r
0035
MC/DC0%0/2
length $self->backend and length $self->dsn
length $self->backend length $self->dsn
Truth table33%1/3
A and B
A= length $self->backendB= length $self->dsn
ABresult
0X0
100
111
108  
109 35 ▶ eval { require DBI } or return;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require DBI } } or return 35 0 35
110  
111 35 ▶ if ($self->backend eq 'sqlite' && length $self->path) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->backend eq "sqlite" and length $self->path) 35 0 35
Condition33%1/3
$self->backend eq "sqlite" and length $self->path
!ll&&!rl&&r
0035
MC/DC0%0/2
$self->backend eq "sqlite" and length $self->path
$self->backend eq "sqlite" length $self->path
Truth table33%1/3
A and B
A= $self->backend eq "sqlite"B= length $self->path
ABresult
0X0
100
111
112 35 my $dir = dirname($self->path);
113 35 ▶ if (defined $dir && length $dir && $dir ne '.' && !-d $dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $dir and length $dir and $dir ne "." and not -d $dir) 0 35 35
Condition33%3/9
defined $dir and length $dir and $dir ne "." and not -d $dir
!ll&&!rl&&r
0350
defined $dir and length $dir and $dir ne "."
!ll&&!rl&&r
0035
defined $dir and length $dir
!ll&&!rl&&r
0035
MC/DC0%0/4
defined $dir and length $dir and $dir ne "." and not -d $dir
defined $dir length $dir $dir ne "." not -d $dir
Truth table20%1/5
A and B and C and not(D)
A= defined $dirB= length $dirC= $dir ne "."D= not -d $dir
ABCDresult
0XXX0
10XX0
110X0
11100
11111
114 0 make_path($dir);
115 }
116 }
117  
118 35 my %connect_attr = (
119 RaiseError => 1,
120 PrintError => 0,
121 AutoCommit => 1,
122 );
123 35 ▶ $connect_attr{sqlite_unicode} = 1 if $self->backend eq 'sqlite';
Branch: 1 branch
BranchTrueFalseTotal
if $self->backend eq "sqlite" 35 0 35
124  
125 35 my $dbh = DBI->connect($self->dsn, $self->user, $self->password, \%connect_attr);
126 32 $self->_dbh($dbh);
127 32 return $dbh;
128 }
129  
130  
131 18 ▶sub disconnect {
Subroutine disconnect: called CC=1 SCAR=0.0
Pod documented
132 18 my ($self) = @_;
133 18 $self->flush;
134 18 $self->_drop_handle;
135 18 return;
136 }
137  
138 # Forget the handle without flushing: what _with_handle does to a handle a failed statement left
139 # dead, in the middle of a flush as well -- where a flush of its own would be a re-entry.
140 22 ▶sub _drop_handle {
Subroutine _drop_handle: called CC=2 SCAR=7.0
141 22 my ($self) = @_;
142 22 ▶ my $dbh = $self->_dbh or return;
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = $self->_dbh or return 22 0 22
143 22 eval { $dbh->disconnect };
144 22 $self->_dbh(undef);
145 22 return;
146 }
147  
148  
149 29 ▶sub shipped_schema_file {
Subroutine shipped_schema_file: called CC=10 SCAR=25.3
Pod documented
150 29 my ($self) = @_;
151 29 ▶ my $name = ($self->backend eq 'postgresql') ? 'usage_events.postgresql.sql' : 'usage_events.sqlite.sql';
Branch: 1 branch
BranchTrueFalseTotal
$self->backend eq 'postgresql' ? : 1 28 29
152 29 my @candidates;
153  
154 # Installed/runtime lookup via dist sharedir.
155 29 my $share_dir = eval { dist_dir('Langertha-Skeid') };
156 29 ▶ if (!$@ && defined($share_dir) && length($share_dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $@ and defined $share_dir and length $share_dir) 29 0 29
Condition33%2/6
not $@ and defined $share_dir and length $share_dir
!ll&&!rl&&r
0029
not $@ and defined $share_dir
!ll&&!rl&&r
0029
MC/DC0%0/3
not $@ and defined $share_dir and length $share_dir
not $@ defined $share_dir length $share_dir
Truth table25%1/4
not(A) and B and C
A= not $@B= defined $share_dirC= length $share_dir
ABCresult
0XX0
10X0
1100
1111
157 29 push @candidates, File::Spec->catfile($share_dir, 'sql', $name);
158 }
159  
160 # Dev + dzil test fallback: walk up from this file looking for the repo's share/.
161 29 my $dir = dirname(dirname(dirname(dirname(__FILE__))));
162 29 for (1 .. 6) {
163 174 push @candidates, File::Spec->catfile($dir, 'share', 'sql', $name);
164 174 push @candidates, File::Spec->catfile($dir, 'sql', $name);
165 174 my $parent = dirname($dir);
166 174 ▶ last if !defined($parent) || $parent eq $dir;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $parent or $parent eq $dir 0 174 174
Condition33%1/3
not defined $parent or $parent eq $dir
l!l&&r!l&&!r
00174
MC/DC0%0/2
not defined $parent or $parent eq $dir
not defined $parent $parent eq $dir
Truth table33%1/3
not(A) or B
A= not defined $parentB= $parent eq $dir
ABresult
1X1
011
000
167 174 $dir = $parent;
168 }
169  
170 29 for my $path (@candidates) {
171 29 ▶ return $path if -f $path;
Branch: 1 branch
BranchTrueFalseTotal
if -f $path 29 0 29
172 }
173  
174 0 return $candidates[0];
175 }
176  
177  
178 39 ▶sub store {
Subroutine store: called CC=3 SCAR=11.0
Pod documented
179 39 my ($self, $event) = @_;
180 39 ▶ if ($self->_writes_behind) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_writes_behind) 18 21 39
181 18 push @{ $self->_queue }, { %$event };
182 18 $self->_arm_flush;
183 18 return { ok => 1, queued => 1 };
184 }
185 # Whatever was queued while the loop ran goes first, so the table keeps the order the events
186 # arrived in.
187 21 ▶ $self->flush if @{ $self->_queue };
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->_queue;} 1 20 21
188 22 ▶ return $self->_with_handle(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
189 22 my ($dbh) = @_;
190 22 return { ok => 1, $self->_insert($dbh, $event) };
191 21 });
192 }
193  
194 # Queue only while a loop runs to fire the flush timer. Outside one -- a script calling
195 # usage.record, the prefork manager before it forks -- there is no request path to keep free and
196 # a queue that nothing would ever write.
197 39 ▶sub _writes_behind {
Subroutine _writes_behind: called CC=3 SCAR=11.0
198 39 my ($self) = @_;
199 39 ▶ return 0 unless $self->flush_interval_ms > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->flush_interval_ms > 0 19 20 39
200 20 ▶ return Mojo::IOLoop->is_running ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
'Mojo::IOLoop'->is_running ? : 18 2 20
201 }
202  
203 18 ▶sub _arm_flush {
Subroutine _arm_flush: called CC=2 SCAR=6.9
204 18 my ($self) = @_;
205 18 ▶ return if defined $self->_flush_timer;
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->_flush_timer 7 11 18
206 11 weaken(my $weak = $self);
207 2 ▶ $self->_flush_timer(Mojo::IOLoop->timer($self->flush_interval_ms / 1000 => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
208 2 ▶ return unless $weak;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak 0 2 2
209 2 $weak->_flush_timer(undef);
210 2 $weak->flush;
211 11 }));
212 11 return;
213 }
214  
215  
216 33 ▶sub flush {
Subroutine flush: called CC=9 SCAR=22.0
Pod documented
217 33 my ($self) = @_;
218 33 ▶ if (defined(my $timer = $self->_flush_timer)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $timer = $self->_flush_timer)) 9 24 33
219 9 Mojo::IOLoop->remove($timer);
220 9 $self->_flush_timer(undef);
221 }
222 33 my @events = splice @{ $self->_queue };
223 33 ▶ return { ok => 1, written => 0 } unless @events;
Branch: 1 branch
BranchTrueFalseTotal
unless @events 22 11 33
224  
225 11 ▶ my $batch = $self->_with_handle(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
226 11 my ($dbh) = @_;
227 11 $dbh->begin_work;
228 11 my $done = eval {
229 11 $self->_insert($dbh, $_) for @events;
230 8 $dbh->commit;
231 8 1;
232 };
233 11 ▶ unless ($done) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($done) 3 8 11
234 3 my $err = $@;
235 3 eval { $dbh->rollback };
236 3 die $err;
237 }
238 8 return { ok => 1, written => scalar @events };
239 11 });
240 11 ▶ return $batch if $batch->{ok};
Branch: 1 branch
BranchTrueFalseTotal
if $batch->{"ok"} 8 3 11
241  
242 # No handle left: the reconnect failed, and one attempt per event would only repeat it.
243 3 ▶ return $self->_lose(0, \@events, $batch->{error}) unless $self->_dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_dbh 1 2 3
244  
245 2 my ($written, $lost, $error) = (0, 0);
246 2 ▶ while (@events) {
Branch: 1 branch
BranchTrueFalseTotal
if (@events) 4 2 6
247 4 my $event = shift @events;
248 4 ▶ my $one = $self->_with_handle(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
249 4 my ($dbh) = @_;
250 4 $self->_insert($dbh, $event);
251 2 return { ok => 1 };
252 4 });
253 4 ▶ if ($one->{ok}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($one->{"ok"}) 2 2 4
254 2 $written++;
255 2 next;
256 }
257 2 $lost++;
258 2 $error = $one->{error};
259 2 $self->_report_lost($event, $error);
260 2 ▶ next if $self->_dbh;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_dbh 2 0 2
261 # The handle died under the single writes and did not come back: the rest go with it.
262 0 $lost += $self->_lose(0, \@events, $error)->{lost};
263 0 last;
264 }
265 2 ▶ return $lost
Branch: 1 branch
BranchTrueFalseTotal
$lost ? : 2 0 2
266 ? { ok => 0, written => $written, lost => $lost, error => $error }
267 : { ok => 1, written => $written };
268 }
269  
270 # Reports every event in $events as lost and answers the flush with it.
271 1 ▶sub _lose {
Subroutine _lose: called CC=2 SCAR=6.9
272 1 my ($self, $written, $events, $err) = @_;
273 1 my $failure = $self->_failure($err);
274 1 $self->_report_lost($_, $failure->{error}) for @$events;
275 1 return { ok => 0, written => $written, lost => scalar(@$events), error => $failure->{error} };
276 }
277  
278 5 ▶sub _report_lost {
Subroutine _report_lost: called CC=4 SCAR=17.9
279 5 my ($self, $event, $err) = @_;
280 5 my $cb = $self->on_lost;
281 5 ▶ return if $cb && eval { $cb->($event, $err); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if $cb and eval { do { &$cb($event, $err); 1 } } 5 0 5
Condition33%1/3
$cb and eval {
!ll&&!rl&&r
005
MC/DC0%0/2
$cb and eval { do { &$cb($event, $err); 1 } }
$cb eval { do { &$cb($event, $err); 1 } }
Truth table33%1/3
A and B
A= $cbB= eval { do { &$cb($event, $err); 1 } }
ABresult
0X0
100
111
282 # A timer callback that dies takes the reactor's error path; a lost event must still be said.
283 0 ▶ warn 'skeid: usage event lost: request_id=' . ($event->{request_id} // '')
Condition0%0/2
$event->{"request_id"} // ""
l!l
00
MC/DC0%0/1
$event->{"request_id"} // ""
$event->{"request_id"}
Truth table0%0/2
A
A= $event->{"request_id"}
Aresult
11
00
284 . ' store=' . $self->backend . ': ' . $err . "\n";
285 0 return;
286 }
287  
288 # Runs $work with the store's handle and returns its answer, or { ok => 0, error } when it dies.
289 # On a failure that left the handle dead the handle is dropped, connected once more and $work
290 # retried once on the new one (skeid k71). Never more than that, never a wait.
291 44 ▶sub _with_handle {
Subroutine _with_handle: called CC=8 SCAR=21.0
292 44 my ($self, $work) = @_;
293  
294 44 my $dbh = eval { $self->dbh };
295 44 ▶ return $self->_failure($@ || 'failed to connect usage database') unless $dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh 1 43 44
Condition50%1/2
$@ || 'failed to connect usage database'
l!l
10
MC/DC0%0/1
$@ || 'failed to connect usage database'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
296  
297 43 my $res = eval { $work->($dbh) };
298 43 ▶ return $res if $res;
Branch: 1 branch
BranchTrueFalseTotal
if $res 32 11 43
299 11 my $err = $@;
300 11 ▶ return $self->_failure($err) if $self->_handle_alive($dbh);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_handle_alive($dbh) 7 4 11
301  
302 4 $self->_drop_handle;
303 4 my $fresh = eval { $self->dbh };
304 4 ▶ return $self->_failure('usage database connection lost, reconnect failed: '
Branch: 1 branch
BranchTrueFalseTotal
unless $fresh 2 2 4
Condition50%1/2
$@ || 'no database handle'
l!l
20
MC/DC0%0/1
$@ || 'no database handle'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
305 .($@ || 'no database handle')) unless $fresh;
306  
307 2 $res = eval { $work->($fresh) };
308 2 ▶ return $res || $self->_failure($@);
Condition33%1/3
$res || $self->_failure($@)
l!l&&r!l&&!r
200
MC/DC0%0/2
$res || $self->_failure($@)
$res $self->_failure($@)
Truth table33%1/3
A || B
A= $resB= $self->_failure($@)
ABresult
1X1
011
000
309 }
310  
311 # Asked only after a statement failed, so the round-trip a ping costs on PostgreSQL is never
312 # paid by a healthy write. DBD::Pg keeps Active set on a connection the server dropped; ping
313 # is what notices.
314 11 ▶sub _handle_alive {
Subroutine _handle_alive: called CC=3 SCAR=11.0
315 11 my ($self, $dbh) = @_;
316 11 ▶ return 0 unless $dbh->{Active};
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh->{"Active"} 4 7 11
317 7 ▶ return eval { $dbh->ping } ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $dbh->ping } } ? : 7 0 7
318 }
319  
320 11 ▶sub _failure {
Subroutine _failure: called CC=1 SCAR=0.0
321 11 my ($self, $err) = @_;
322 11 return { ok => 0, error => $self->_error_text($err) };
323 }
324  
325 # A DBI error names the DSN it failed on, and a DSN may carry the password. Nothing that
326 # leaves this store may (ADR 0003).
327 12 ▶sub _error_text {
Subroutine _error_text: called CC=3 SCAR=11.8
328 12 my ($self, $err) = @_;
329 12 ▶ $err = 'unknown database error' unless defined($err) && length($err);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err and length $err 0 12 12
Condition33%1/3
defined $err and length $err
!ll&&!rl&&r
0012
MC/DC0%0/2
defined $err and length $err
defined $err length $err
Truth table33%1/3
A and B
A= defined $errB= length $err
ABresult
0X0
100
111
330 12 $err =~ s/\b(password|pwd)=[^;'"\s)]*/$1=***/gi;
331 12 $err =~ s/\s+$//;
332 12 return $err;
333 }
334  
335 41 ▶sub _insert {
Subroutine _insert: called CC=5 SCAR=18.1
336 41 my ($self, $dbh, $event) = @_;
337 41 my $sth = $dbh->prepare_cached(q{
338 INSERT INTO usage_events (
339 created_at, request_id, api_format, endpoint, api_key_id, provider, engine, model, node_id, route_url,
340 status_code, ok, duration_ms, input_tokens, output_tokens, total_tokens, cached_tokens, tool_calls,
341 cost_input_usd, cost_output_usd, cost_total_usd, error_type, error_message, requested_model,
342 content_bytes, cost_cache_read_usd, cost_cache_write_usd, cache_write_tokens
343 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
344 });
345 $sth->execute(
346 $event->{created_at},
347 $event->{request_id},
348 $event->{api_format},
349 $event->{endpoint},
350 $event->{api_key_id},
351 $event->{provider},
352 $event->{engine},
353 $event->{model},
354 $event->{node_id},
355 $event->{route_url},
356 $event->{status_code},
357 $event->{ok},
358 $event->{duration_ms},
359 $event->{input_tokens},
360 $event->{output_tokens},
361 $event->{total_tokens},
362 # Nullable: an event that carried no cache count writes NULL, not a measured zero.
363 $event->{cached_tokens},
364 $event->{tool_calls},
365 $event->{cost_input_usd},
366 $event->{cost_output_usd},
367 $event->{cost_total_usd},
368 $event->{error_type},
369 $event->{error_message},
370 ($event->{requested_model} // $event->{model} // ''),
371 # Nullable: only a streamed request carries it; anything else writes NULL, "not measured".
372 $event->{content_bytes},
373 # Nullable: an event from a caller that does not price the cache apart writes NULL.
374 $event->{cost_cache_read_usd},
375 $event->{cost_cache_write_usd},
376 # Nullable: an event that carried no cache write count writes NULL.
377 $event->{cache_write_tokens},
378 33 ▶ );
Condition60%3/5
($event->{"requested_model"} // $event->{"model"}) // ""
l!l
330
$event->{"requested_model"} // $event->{"model"}
l!l&&r!l&&!r
13200
MC/DC0%0/2
($event->{"requested_model"} // $event->{"model"}) // ""
$event->{"requested_model"} $event->{"model"}
Truth table66%2/3
A // B
A= $event->{"requested_model"}B= $event->{"model"}
ABresult
1X1
011
000
379  
380 31 ▶ return ($self->backend eq 'sqlite' && $dbh->can('sqlite_last_insert_rowid'))
Branch: 1 branch
BranchTrueFalseTotal
$self->backend eq 'sqlite' && $dbh->can('sqlite_last_insert_rowid') ? : 31 0 31
Condition33%1/3
$self->backend eq "sqlite" and $dbh->can("sqlite_last_insert_rowid")
!ll&&!rl&&r
0031
MC/DC0%0/2
$self->backend eq "sqlite" and $dbh->can("sqlite_last_insert_rowid")
$self->backend eq "sqlite" $dbh->can("sqlite_last_insert_rowid")
Truth table33%1/3
A and B
A= $self->backend eq "sqlite"B= $dbh->can("sqlite_last_insert_rowid")
ABresult
0X0
100
111
381 ? ( id => Langertha::Skeid::UsageStore::num($dbh->sqlite_last_insert_rowid) )
382 : ();
383 }
384  
385  
386 8 ▶sub report {
Subroutine report: called CC=3 SCAR=11.0
Pod documented
387 8 my ($self, $filters) = @_;
388 8 ▶ $filters ||= {};
Condition50%1/2
$filters ||= {}
l!l
80
MC/DC0%0/1
$filters ||= {}
$filters
Truth table50%1/2
A
A= $filters
Aresult
11
00
389 8 $self->flush;
390  
391 8 ▶ my $report = $self->_with_handle(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
392 8 my ($dbh) = @_;
393 8 return $self->_report($dbh, $filters);
394 8 });
395 8 ▶ return $report->{ok} ? $report : { %$report, enabled => 0 };
Branch: 1 branch
BranchTrueFalseTotal
$report->{'ok'} ? : 7 1 8
396 }
397  
398 8 ▶sub _report {
Subroutine _report: called CC=27 SCAR=42.9
399 8 my ($self, $dbh, $filters) = @_;
400 8 my $num = \&Langertha::Skeid::UsageStore::num;
401  
402 8 ▶ my $limit = $filters->{limit} // 20;
Condition100%2/2
$filters->{"limit"} // 20
l!l
53
MC/DC100%1/1
$filters->{"limit"} // 20
$filters->{"limit"}
Truth table100%2/2
A
A= $filters->{"limit"}
Aresult
11
00
403  
404 8 my @where;
405 my @bind;
406 8 ▶ if (defined $filters->{since} && length $filters->{since}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $filters->{"since"} and length $filters->{"since"}) 0 8 8
Condition33%1/3
defined $filters->{"since"} and length $filters->{"since"}
!ll&&!rl&&r
800
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
407 0 push @where, 'created_at >= ?';
408 0 push @bind, $filters->{since};
409 }
410 8 ▶ 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"}) 0 8 8
Condition33%1/3
defined $filters->{"api_key_id"} and length $filters->{"api_key_id"}
!ll&&!rl&&r
800
MC/DC0%0/2
defined $filters->{"api_key_id"} and length $filters->{"api_key_id"}
defined $filters->{"api_key_id"} length $filters->{"api_key_id"}
Truth table33%1/3
A and B
A= defined $filters->{"api_key_id"}B= length $filters->{"api_key_id"}
ABresult
0X0
100
111
411 0 push @where, 'api_key_id = ?';
412 0 push @bind, $filters->{api_key_id};
413 }
414 8 ▶ if (defined $filters->{model} && length $filters->{model}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $filters->{"model"} and length $filters->{"model"}) 0 8 8
Condition33%1/3
defined $filters->{"model"} and length $filters->{"model"}
!ll&&!rl&&r
800
MC/DC0%0/2
defined $filters->{"model"} and length $filters->{"model"}
defined $filters->{"model"} length $filters->{"model"}
Truth table33%1/3
A and B
A= defined $filters->{"model"}B= length $filters->{"model"}
ABresult
0X0
100
111
415 0 push @where, 'model = ?';
416 0 push @bind, $filters->{model};
417 }
418  
419 8 ▶ my $where_sql = @where ? ('WHERE ' . join(' AND ', @where)) : '';
Branch: 1 branch
BranchTrueFalseTotal
@where ? : 0 8 8
420  
421 8 ▶ my $totals = $dbh->selectrow_hashref(
Condition50%1/2
$dbh->selectrow_hashref("SELECT\n COUNT(*) AS requests,\n COALESCE(SUM(input_tokens), 0) AS input_tokens,\n COALESCE(SUM(output_tokens), 0) AS output_tokens,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cached_tokens), 0) AS cached_tokens,\n COALESCE(SUM(cache_write_tokens), 0) AS cache_write_tokens,\n COALESCE(SUM(tool_calls), 0) AS tool_calls,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events $where_sql", undef, @bind) || {}
l!l
70
MC/DC0%0/1
$dbh->selectrow_hashref("SELECT\n COUNT(*) AS requests,\n COALESCE(SUM(input_tokens), 0) AS input_tokens,\n COALESCE(SUM(output_tokens), 0) AS output_tokens,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cached_tokens), 0) AS cached_tokens,\n COALESCE(SUM(cache_write_tokens), 0) AS cache_write_tokens,\n COALESCE(SUM(tool_calls), 0) AS tool_calls,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events $where_sql", undef, @bind) || {}
$dbh->selectrow_hashref("SELECT\n COUNT(*) AS requests,\n COALESCE(SUM(input_tokens), 0) AS input_tokens,\n COALESCE(SUM(output_tokens), 0) AS output_tokens,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cached_tokens), 0) AS cached_tokens,\n COALESCE(SUM(cache_write_tokens), 0) AS cache_write_tokens,\n COALESCE(SUM(tool_calls), 0) AS tool_calls,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events $where_sql", undef, @bind)
Truth table50%1/2
A
A= $dbh->selectrow_hashref("SELECT\n COUNT(*) AS requests,\n COALESCE(SUM(input_tokens), 0) AS input_tokens,\n COALESCE(SUM(output_tokens), 0) AS output_tokens,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cached_tokens), 0) AS cached_tokens,\n COALESCE(SUM(cache_write_tokens), 0) AS cache_write_tokens,\n COALESCE(SUM(tool_calls), 0) AS tool_calls,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events $where_sql", undef, @bind)
Aresult
11
00
422 "SELECT
423 COUNT(*) AS requests,
424 COALESCE(SUM(input_tokens), 0) AS input_tokens,
425 COALESCE(SUM(output_tokens), 0) AS output_tokens,
426 COALESCE(SUM(total_tokens), 0) AS total_tokens,
427 COALESCE(SUM(cached_tokens), 0) AS cached_tokens,
428 COALESCE(SUM(cache_write_tokens), 0) AS cache_write_tokens,
429 COALESCE(SUM(tool_calls), 0) AS tool_calls,
430 COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd
431 FROM usage_events $where_sql",
432 undef,
433 @bind,
434 ) || {};
435  
436 7 ▶ my $by_key = $dbh->selectall_arrayref(
Condition50%1/2
$dbh->selectall_arrayref("SELECT\n COALESCE(api_key_id, '') AS api_key_id,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY api_key_id\n ORDER BY total_cost_usd DESC, requests DESC", {'Slice', {}}, @bind) || []
l!l
70
MC/DC0%0/1
$dbh->selectall_arrayref("SELECT\n COALESCE(api_key_id, '') AS api_key_id,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY api_key_id\n ORDER BY total_cost_usd DESC, requests DESC", {'Slice', {}}, @bind) || []
$dbh->selectall_arrayref("SELECT\n COALESCE(api_key_id, '') AS api_key_id,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY api_key_id\n ORDER BY total_cost_usd DESC, requests DESC", {'Slice', {}}, @bind)
Truth table50%1/2
A
A= $dbh->selectall_arrayref("SELECT\n COALESCE(api_key_id, '') AS api_key_id,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY api_key_id\n ORDER BY total_cost_usd DESC, requests DESC", {'Slice', {}}, @bind)
Aresult
11
00
437 "SELECT
438 COALESCE(api_key_id, '') AS api_key_id,
439 COUNT(*) AS requests,
440 COALESCE(SUM(total_tokens), 0) AS total_tokens,
441 COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd
442 FROM usage_events
443 $where_sql
444 GROUP BY api_key_id
445 ORDER BY total_cost_usd DESC, requests DESC",
446 { Slice => {} },
447 @bind,
448 ) || [];
449  
450 7 ▶ my $by_model = $dbh->selectall_arrayref(
Condition50%1/2
$dbh->selectall_arrayref("SELECT\n COALESCE(model, '') AS model,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY model\n ORDER BY total_cost_usd DESC, requests DESC", {'Slice', {}}, @bind) || []
l!l
70
MC/DC0%0/1
$dbh->selectall_arrayref("SELECT\n COALESCE(model, '') AS model,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY model\n ORDER BY total_cost_usd DESC, requests DESC", {'Slice', {}}, @bind) || []
$dbh->selectall_arrayref("SELECT\n COALESCE(model, '') AS model,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY model\n ORDER BY total_cost_usd DESC, requests DESC", {'Slice', {}}, @bind)
Truth table50%1/2
A
A= $dbh->selectall_arrayref("SELECT\n COALESCE(model, '') AS model,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY model\n ORDER BY total_cost_usd DESC, requests DESC", {'Slice', {}}, @bind)
Aresult
11
00
451 "SELECT
452 COALESCE(model, '') AS model,
453 COUNT(*) AS requests,
454 COALESCE(SUM(total_tokens), 0) AS total_tokens,
455 COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd
456 FROM usage_events
457 $where_sql
458 GROUP BY model
459 ORDER BY total_cost_usd DESC, requests DESC",
460 { Slice => {} },
461 @bind,
462 ) || [];
463  
464 7 ▶ my $recent = $dbh->selectall_arrayref(
Condition50%1/2
$dbh->selectall_arrayref("SELECT\n id, created_at, api_format, endpoint, api_key_id, model, requested_model, node_id, status_code, ok,\n input_tokens, output_tokens, total_tokens, cached_tokens, cache_write_tokens, tool_calls, cost_total_usd\n FROM usage_events\n $where_sql\n ORDER BY id DESC\n LIMIT ?", {'Slice', {}}, @bind, $limit) || []
l!l
70
MC/DC0%0/1
$dbh->selectall_arrayref("SELECT\n id, created_at, api_format, endpoint, api_key_id, model, requested_model, node_id, status_code, ok,\n input_tokens, output_tokens, total_tokens, cached_tokens, cache_write_tokens, tool_calls, cost_total_usd\n FROM usage_events\n $where_sql\n ORDER BY id DESC\n LIMIT ?", {'Slice', {}}, @bind, $limit) || []
$dbh->selectall_arrayref("SELECT\n id, created_at, api_format, endpoint, api_key_id, model, requested_model, node_id, status_code, ok,\n input_tokens, output_tokens, total_tokens, cached_tokens, cache_write_tokens, tool_calls, cost_total_usd\n FROM usage_events\n $where_sql\n ORDER BY id DESC\n LIMIT ?", {'Slice', {}}, @bind, $limit)
Truth table50%1/2
A
A= $dbh->selectall_arrayref("SELECT\n id, created_at, api_format, endpoint, api_key_id, model, requested_model, node_id, status_code, ok,\n input_tokens, output_tokens, total_tokens, cached_tokens, cache_write_tokens, tool_calls, cost_total_usd\n FROM usage_events\n $where_sql\n ORDER BY id DESC\n LIMIT ?", {'Slice', {}}, @bind, $limit)
Aresult
11
00
465 "SELECT
466 id, created_at, api_format, endpoint, api_key_id, model, requested_model, node_id, status_code, ok,
467 input_tokens, output_tokens, total_tokens, cached_tokens, cache_write_tokens, tool_calls, cost_total_usd
468 FROM usage_events
469 $where_sql
470 ORDER BY id DESC
471 LIMIT ?",
472 { Slice => {} },
473 @bind,
474 $limit,
475 ) || [];
476  
477 return {
478 ok => 1,
479 enabled => 1,
480 backend => $self->backend,
481 db_path => ($self->backend eq 'sqlite' ? ($self->path // '') : ''),
482 since => ($filters->{since} // ''),
483 totals => {
484 requests => $num->($totals->{requests}),
485 input_tokens => $num->($totals->{input_tokens}),
486 output_tokens => $num->($totals->{output_tokens}),
487 total_tokens => $num->($totals->{total_tokens}),
488 cached_tokens => $num->($totals->{cached_tokens}),
489 cache_write_tokens => $num->($totals->{cache_write_tokens}),
490 tool_calls => $num->($totals->{tool_calls}),
491 total_cost_usd => $num->($totals->{total_cost_usd}),
492 },
493 by_key => [ map {
494 +{
495 api_key_id => ($_->{api_key_id} // ''),
496 requests => $num->($_->{requests}),
497 total_tokens => $num->($_->{total_tokens}),
498 9 ▶ total_cost_usd => $num->($_->{total_cost_usd}),
Condition50%1/2
$_->{"api_key_id"} // ""
l!l
90
MC/DC0%0/1
$_->{"api_key_id"} // ""
$_->{"api_key_id"}
Truth table50%1/2
A
A= $_->{"api_key_id"}
Aresult
11
00
499 }
500 } @$by_key ],
501 by_model => [ map {
502 +{
503 model => ($_->{model} // ''),
504 requests => $num->($_->{requests}),
505 total_tokens => $num->($_->{total_tokens}),
506 9 ▶ total_cost_usd => $num->($_->{total_cost_usd}),
Condition50%1/2
$_->{"model"} // ""
l!l
90
MC/DC0%0/1
$_->{"model"} // ""
$_->{"model"}
Truth table50%1/2
A
A= $_->{"model"}
Aresult
11
00
507 }
508 } @$by_model ],
509 recent => [ map {
510 7 ▶ +{
Branch: 1 branch
BranchTrueFalseTotal
$self->backend eq 'sqlite' ? : 7 0 7
Condition50%2/4
$self->path // ""
l!l
70
$filters->{"since"} // ""
l!l
07
MC/DC0%0/1
$self->path // ""
$self->path
MC/DC0%0/1
$filters->{"since"} // ""
$filters->{"since"}
Truth table50%1/2
A
A= $self->path
Aresult
11
00
Truth table50%1/2
A
A= $filters->{"since"}
Aresult
11
00
511 id => $num->($_->{id}),
512 created_at => ($_->{created_at} // ''),
513 api_format => ($_->{api_format} // ''),
514 endpoint => ($_->{endpoint} // ''),
515 api_key_id => ($_->{api_key_id} // ''),
516 model => ($_->{model} // ''),
517 requested_model => ($_->{requested_model} // $_->{model} // ''),
518 node_id => ($_->{node_id} // ''),
519 status_code => $num->($_->{status_code}),
520 ok => ($_->{ok} ? 1 : 0),
521 input_tokens => $num->($_->{input_tokens}),
522 output_tokens => $num->($_->{output_tokens}),
523 total_tokens => $num->($_->{total_tokens}),
524 cached_tokens => $num->($_->{cached_tokens}),
525 cache_write_tokens => $num->($_->{cache_write_tokens}),
526 tool_calls => $num->($_->{tool_calls}),
527 11 ▶ cost_total_usd => $num->($_->{cost_total_usd}),
Branch: 1 branch
BranchTrueFalseTotal
$_->{'ok'} ? : 11 0 11
Condition70%12/17
$_->{"created_at"} // ""
l!l
110
$_->{"api_format"} // ""
l!l
92
$_->{"endpoint"} // ""
l!l
92
$_->{"api_key_id"} // ""
l!l
110
$_->{"model"} // ""
l!l
110
($_->{"requested_model"} // $_->{"model"}) // ""
l!l
110
$_->{"requested_model"} // $_->{"model"}
l!l&&r!l&&!r
920
$_->{"node_id"} // ""
l!l
92
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/DC100%1/1
$_->{"node_id"} // ""
$_->{"node_id"}
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 table100%2/2
A
A= $_->{"node_id"}
Aresult
11
00
528 }
529 } @$recent ],
530 };
531 }
532  
533  
534 9 1;
535  
536 __END__
537  
538 =pod
539  
540 =encoding UTF-8
541  
542 =head1 NAME
543  
544 Langertha::Skeid::UsageStore::DBI - SQLite and PostgreSQL usage store
545  
546 =head1 VERSION
547  
548 version 0.003
549  
550 =head1 DESCRIPTION
551  
552 Usage events in a real database — SQLite for a single box, PostgreSQL for a deployment. Both
553 speak the same C<usage_events> table, shipped as F<share/sql/usage_events.E<lt>backendE<gt>.sql>.
554  
555 By default every event costs a synchronous database round-trip -- and a commit -- on the request
556 path, which is why L<Langertha::Skeid::UsageStore::JsonLog> is the recommended default and this
557 backend is a deliberate choice. See F<docs/adr/0004-usage-events-are-the-billing-unit.md>.
558  
559 C<flush_interval_ms> turns on write-behind: while the event loop runs, L</store> only queues the
560 event and answers at once, and a L<Mojo::IOLoop> timer writes the queue in one transaction. The
561 request is answered without waiting for the database, and a burst of events costs one commit
562 instead of one each. The flush itself is still a synchronous database call on the loop -- it
563 runs once per interval instead of once per request, it is not off the loop. The price is a wider
564 loss window: events still queued when the process dies without a flush are lost (ADR 0005,
565 Update skeid k78). Off by default.
566  
567 C<DBI> is loaded at runtime rather than compile time: a Skeid that never configures a database
568 backend must not require one to be installed.
569  
570 =head2 backend
571  
572 C<sqlite> or C<postgresql>. Decides the schema file and whether an insert can report a row id.
573  
574 =head2 dsn
575  
576 Required. The DBI data source, as normalized by L<Langertha::Skeid::UsageStore/normalize_config>
577 (C<dbi:SQLite:dbname=...> or C<dbi:Pg:...>).
578  
579 =head2 user
580  
581 Database user (default empty).
582  
583 =head2 password
584  
585 Database password (default empty). Normalization reads it from C<password_env> when the config
586 names that instead; it is never written anywhere.
587  
588 =head2 path
589  
590 SQLite database file. Its parent directory is created on connect. Empty for PostgreSQL.
591  
592 =head2 schema_file
593  
594 Explicit schema path. Empty means "find the shipped one for this backend".
595  
596 =head2 auto_migrate
597  
598 Apply the schema when the store is prepared. On by default.
599  
600 =head2 flush_interval_ms
601  
602 Write-behind interval in milliseconds; C<0> (the default) writes every event synchronously when
603 L</store> is called. Above C<0>, L</store> queues the event while L<Mojo::IOLoop> is running, and
604 the first queued event arms a timer that calls L</flush> after this many milliseconds. With no
605 running loop there is nothing to protect and nothing to fire the timer, so L</store> writes at
606 once, after anything still queued.
607  
608 =head2 on_lost
609  
610 Optional code ref, called as C<< ->($event, $error) >> for every queued event a L</flush> could
611 not write -- the request it describes was answered long ago, so there is no caller left to hand
612 the failure to. L<Langertha::Skeid> sets it to its own lost-event report. Without it the store
613 C<warn>s one line naming the request id and the backend, never the DSN.
614  
615 =head2 prepare
616  
617 Connects if possible and applies the schema when C<auto_migrate> is on: its C<CREATE TABLE>
618 statements, then any column an older table lacks (C<ALTER TABLE ... ADD COLUMN>; nothing is
619 ever dropped or rewritten), then the rest. Returns false without complaint when C<DBI> is
620 unavailable -- an unusable store degrades to "no usage recorded", it does not take the proxy
621 down. Croaks when the schema file does not exist; a failing connect or statement dies.
622  
623 =head2 dbh
624  
625 The cached database handle, connecting on first use. Returns nothing when C<DBI> is not
626 installed or no DSN is configured.
627  
628 =head2 disconnect
629  
630 Writes what is still queued (L</flush>), then drops the cached handle, so the next L</dbh>
631 connects anew. Called when the store is replaced on a reload -- the queued events belong to this
632 store's destination, not the next one's -- and from Skeid's C<DEMOLISH>.
633  
634 =head2 shipped_schema_file
635  
636 The schema file this backend would apply when C<schema_file> is not set. Looks in the installed
637 sharedir first, then walks up from this file for the repository's F<share/sql/> — the dev and
638 C<dzil test> case, where nothing is installed yet. Returns the first candidate that exists, or
639 the first candidate at all, so the caller can report a useful path when none does.
640  
641 =head2 store
642  
643 my $res = $store->store($event);
644  
645 Inserts one event. Returns C<< { ok => 1 } >> (plus C<id> on SQLite), or
646 C<< { ok => 0, error => … } >> when there is no database handle or the insert fails -- a failure
647 is reported, never thrown, because the request it describes has already been served. The proxy
648 logs such an answer at C<error> level as a lost usage event. A C<password=> in the error text
649 (a DSN that carries one) is masked.
650  
651 With L</flush_interval_ms> set and the event loop running, the event is queued instead and the
652 answer is C<< { ok => 1, queued => 1 } >>, without an C<id>: the row does not exist yet. What
653 becomes of it is L</flush>'s to report.
654  
655 A dropped connection is survived: when the insert fails and the handle turns out to be dead
656 (not C<Active>, or C<ping> fails -- checked only after a failure, so a healthy write costs
657 nothing extra), the store connects once more and retries that one event once. The new handle
658 serves every later event. A reconnect that fails is reported like any other failure (the next
659 event tries again), and a failure on a live handle -- a dropped table, a constraint -- is
660 reported without a reconnect. There is no loop and no wait: at most one extra synchronous
661 connect per event, the cost ADR 0005 already accepts for this backend. The schema is not
662 re-applied on a reconnect; L</prepare> ran when the store was configured, and a lost connection
663 does not lose the table. One corner remains: a connection that drops after the server committed
664 the insert but before it answered is indistinguishable from one that dropped before, so that
665 event can be written twice. A duplicate row carries the same C<request_id>; a lost one leaves
666 nothing to reconcile.
667  
668 =head2 flush
669  
670 my $res = $store->flush;
671  
672 Writes every queued event in one transaction and empties the queue. Returns
673 C<< { ok => 1, written => $n } >>, or C<< { ok => 0, written => $n, lost => $m, error => … } >>
674 when some could not be written; each of those is also handed to L</on_lost>. Never dies, never
675 waits, never retries later: every queued event gets the one attempt a synchronous L</store>
676 would have given it.
677  
678 A failing batch is rolled back, so nothing is half written. When the handle survived the failure
679 -- one event a constraint rejects, a dropped table -- the events are written one by one, so a
680 single bad event loses only itself. When the handle died, it is reconnected once and the batch
681 retried once, as for L</store>; a reconnect that fails loses the whole batch with one connect
682 attempt, not one per event. The duplicate corner of L</store> applies to a batch: a connection
683 that drops after the server committed but before it answered is retried as a whole.
684  
685 Called by the flush timer, by L</disconnect>, by L</report> (so a report counts what was queued)
686 and by L</store> when it writes synchronously. L<Langertha::Skeid/flush_usage> calls it.
687  
688 =head2 report
689  
690 my $report = $store->report(\%filters);
691  
692 Aggregates in SQL: totals, per-key and per-model breakdowns, and the newest C<limit> events.
693 The same C<since> / C<api_key_id> / C<model> filter set applies to every part of the report, so
694 the breakdowns always add up to the totals shown next to them. C<limit> defaults to 20. The shape
695 is described in L<Langertha::Skeid::UsageStore/The store contract>; a failure to connect or a
696 failing query is C<< { ok => 0, enabled => 0, error => … } >>. A dropped connection is
697 reconnected once, exactly as for L</store>. Queued events are flushed first, so a report counts
698 every event recorded before it was asked for.
699  
700 =head1 SEE ALSO
701  
702 L<Langertha::Skeid::UsageStore>, L<Langertha::Skeid::UsageStore::JsonLog>
703  
704 =head1 SUPPORT
705  
706 =head2 Issues
707  
708 Please report bugs and feature requests on GitHub at
709 L<https://github.com/Getty/langertha-skeid/issues>.
710  
711 =head2 IRC
712  
713 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
714  
715 =head1 CONTRIBUTING
716  
717 Contributions are welcome! Please fork the repository and submit a pull request.
718  
719 =head1 AUTHOR
720  
721 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
722  
723 =head1 COPYRIGHT AND LICENSE
724  
725 This software is copyright (c) 2026 by Torsten Raudssus.
726  
727 This is free software; you can redistribute it and/or modify it under
728 the same terms as the Perl 5 programming language system itself.
729  
730 =cut
« blib/lib/Langertha/Skeid/Protocol/Anthropic/Stream.pm ↑ Summary blib/lib/Langertha/Skeid/Protocol/Ollama.pm »