lib/Langertha/Skeid.pm

filter: Statementstmt 97.8% 2021 / 2066 Branchbran 83.8% 1009 / 1204 Conditioncond 67.2% 821 / 1221 MC/DCmcdc 40.7% 267 / 656 Subroutinesub 99.2% 255 / 257 Podpod 96.9% 64 / 66 totaltotal 81.1% 4437 / 5470 CC 1158 SCAR 33.9
CC
1158
Cov
86%
call_function
226.2
_apply_config
61.5
_usage_lost
61.2
CRAP 29.6
« lib/Langertha/Skeid/UsageStore/JsonLog.pm ↑ Summary blib/lib/Langertha/Skeid/CustomerSource/DBI.pm »
1 package Langertha::Skeid;
2 127 our $VERSION = '0.005';
3 # ABSTRACT: Dynamic routing control-plane for multi-node LLM serving with normalized metrics and cost accounting
4 127 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 127 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 127 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 127 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 127 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 127 ▶use Digest::SHA qw(sha1_hex sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 127 ▶use Scalar::Util qw(blessed looks_like_number refaddr reftype weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 127 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 127 ▶use YAML::PP;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 127 ▶use Langertha ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 127 ▶use Langertha::Skeid::UsageStore;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 127 ▶use Langertha::Skeid::CustomerSource;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 127 ▶use Langertha::Skeid::NodeFiles;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 127 ▶use Langertha::Skeid::Rate;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 127 ▶use Langertha::Skeid::Protocol;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 127 ▶use Langertha::Skeid::Protocol::Anthropic;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 127 ▶use Langertha::Skeid::Protocol::Documents;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 127 ▶use Langertha::Skeid::Protocol::MCP;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 127 ▶use Langertha::Skeid::Protocol::Ollama;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 127 ▶use Langertha::Skeid::Protocol::Rerank;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 127 ▶use Langertha::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 127 ▶use Langertha::Cost;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 127 ▶use Langertha::Pricing;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 127 ▶use Langertha::UsageRecord;
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29  
30  
31 has nodes => (
32 is => 'rw',
33 924 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
34 # Routing caches derived node lists, so every path that can change the inventory has to
35 # invalidate them. The methods below bump the generation explicitly; this trigger catches
36 # the remaining one -- somebody assigning the whole list through the public accessor.
37 1757 ▶ trigger => sub { $_[0]->_bump_inventory },
Subroutine __ANON__: called CC=1 SCAR=0.0
38 127 );
39  
40  
41 has model_pricing => (
42 is => 'rw',
43 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
44 127 );
45  
46  
47 has model_aliases => (
48 is => 'rw',
49 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
50 127 );
51  
52  
53 has policies => (
54 is => 'rw',
55 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
56 127 );
57  
58  
59 has default_policy => (
60 is => 'rw',
61 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
62 127 );
63  
64  
65 # Key id -> resolved policy. Identical resolutions share one object, and a key that takes the
66 # default is not listed at all, so ten thousand identical customers cost nothing here.
67 has key_policies => (
68 is => 'rw',
69 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
70 127 );
71  
72 # Per customer key id: the token buckets of its policy's rate, and how often it was refused
73 # (skeid k125). In memory, per process.
74 924 ▶has _rate_buckets => (is => 'rw', default => sub { {} });
Subroutine __ANON__: called CC=1 SCAR=0.0
75 924 ▶has _rate_refusals => (is => 'rw', default => sub { {} });
Subroutine __ANON__: called CC=1 SCAR=0.0
76  
77  
78 # Readable name -> customer key id, from the config `names:` section. A config-authoring
79 # convenience only: it lets `keys:` entries be written by name and localises key rotation to
80 # one line, and is resolved to key ids once at config load. It never reaches the request path
81 # -- a request still carries a derived key id, and policy_for_key still costs one hash lookup.
82 has key_names => (
83 is => 'rw',
84 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
85 127 );
86  
87  
88 # /.well-known/langertha.json (skeid #29, ADR 0015). Off until the config enables it.
89 has manifest_enabled => (
90 is => 'rw',
91 924 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
92 127 );
93  
94 # Whether this Langertha has Langertha::Manifest (core newer than 0.503). Enabled without it,
95 # the route answers 404 rather than failing the config.
96 has manifest_available => (
97 is => 'rw',
98 924 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
99 127 );
100  
101 # Key id -> the canonical JSON of that key's manifest, built at config load. This is the
102 # manifest cache, and it is keyed by the key id the caller's key derives to: a customer can
103 # only ever be served the entry built from its own keys: line, never another key's catalog.
104 has key_manifests => (
105 is => 'rw',
106 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
107 127 );
108  
109  
110 # Key id -> 1, from client_auth.keys (skeid k90). Undef is off -- every caller gets in, as
111 # before the section existed -- and is a different thing from {}, which lets nobody in.
112 has client_auth_keys => (
113 is => 'rw',
114 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
115 127 );
116  
117  
118 # Server name -> resolved entry, from mcp.servers (skeid k103, ADR 0022). Undef is off -- both
119 # MCP routes are the unknown path they were before the section existed -- and is a different
120 # thing from {}, a gateway that is on and has no server.
121 has mcp_servers => (
122 is => 'rw',
123 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
124 127 );
125  
126 has mcp_public_url => (
127 is => 'rw',
128 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
129 127 );
130  
131  
132 127 my $MCP_MAX_REQUEST_BYTES = 10485760;
133  
134 has mcp_max_request_bytes => (
135 is => 'rw',
136 924 ▶ default => sub { $MCP_MAX_REQUEST_BYTES },
Subroutine __ANON__: called CC=1 SCAR=0.0
137 127 );
138  
139  
140 has openapi_swagger_ui => (
141 is => 'rw',
142 924 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
143 127 );
144  
145 has openapi_cache_dir => (
146 is => 'rw',
147 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
148 127 );
149  
150  
151 127 has customer_source_fetcher => (
152 is => 'ro',
153 predicate => 'has_customer_source_fetcher',
154 );
155  
156 # The customer source (ADR 0026). The normalized section of the config in force and a digest of
157 # it (a changed one restarts the fetcher), the loop that fetches, the latest snapshot -- the rows
158 # of the last successful fetch, merged into the file's config at every reload -- and what the
159 # last merge accepted, rejected and shadowed.
160 127 has _source_cfg => (is => 'rw');
161 127 has _source_cfg_print => (is => 'rw');
162 127 has _source_ctl => (is => 'rw');
163 127 has _source_snapshot => (is => 'rw');
164 127 has _source_report => (is => 'rw');
165 924 ▶has _source_started => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
166 127 has _source_stale_timer => (is => 'rw');
167 924 ▶has _source_gate_warned => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
168  
169  
170 # uploads.max_bytes (skeid k91): the body limit of the multipart routes, read per request by
171 # the proxy, so a reload holds from the next upload. The default is OpenAI's own limit for an
172 # audio file, 25 MiB.
173 127 my $UPLOAD_MAX_BYTES = 26214400;
174  
175 has upload_max_bytes => (
176 is => 'rw',
177 924 ▶ default => sub { $UPLOAD_MAX_BYTES },
Subroutine __ANON__: called CC=1 SCAR=0.0
178 127 );
179  
180  
181 # uploads.documents_max_bytes (skeid k94, ADR 0028): the body limit of /v1/convert/file and
182 # /v1/convert/source. Documents are bigger than audio, so it is a limit of its own.
183 127 my $DOCUMENTS_MAX_BYTES = 104857600;
184  
185 has documents_max_bytes => (
186 is => 'rw',
187 924 ▶ default => sub { $DOCUMENTS_MAX_BYTES },
Subroutine __ANON__: called CC=1 SCAR=0.0
188 127 );
189  
190  
191 has documents_allow_remote_sources => (
192 is => 'rw',
193 924 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
194 127 );
195  
196  
197 # realtime: (skeid k95, ADR 0029). Read when a session opens, so a reload holds for the next one.
198 127 my %REALTIME_DEFAULT = (
199 idle_timeout => 300,
200 max_session_seconds => 3600,
201 max_message_bytes => 1048576,
202 max_queued_bytes => 4194304,
203 );
204  
205 924 ▶has realtime_idle_timeout => (is => 'rw', default => sub { $REALTIME_DEFAULT{idle_timeout} });
Subroutine __ANON__: called CC=1 SCAR=0.0
206 924 ▶has realtime_max_session_seconds => (is => 'rw', default => sub { $REALTIME_DEFAULT{max_session_seconds} });
Subroutine __ANON__: called CC=1 SCAR=0.0
207 924 ▶has realtime_max_message_bytes => (is => 'rw', default => sub { $REALTIME_DEFAULT{max_message_bytes} });
Subroutine __ANON__: called CC=1 SCAR=0.0
208 924 ▶has realtime_max_queued_bytes => (is => 'rw', default => sub { $REALTIME_DEFAULT{max_queued_bytes} });
Subroutine __ANON__: called CC=1 SCAR=0.0
209  
210  
211  
212 127 has correlation_header => (
213 is => 'rw',
214 builder => '_build_correlation_header',
215 );
216  
217 924 ▶sub _build_correlation_header {
Subroutine _build_correlation_header: called CC=3 SCAR=13.1
218 924 my $name = $ENV{SKEID_CORRELATION_HEADER};
219 924 ▶ return (defined($name) && length($name)) ? _normalize_correlation_header($name) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $name && length $name ? : 0 924 924
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
92400
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
220 }
221  
222  
223 has catch_all => (
224 is => 'rw',
225 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
226 127 );
227  
228 # Whether x-skeid-key-id / x-api-key-id from the client may name the customer. Off by default:
229 # once a policy hangs off the key id, believing that header lets any client pick its own
230 # permissions in one line. Turn it on only when something in front of Skeid authenticates the
231 # caller and sets the header itself.
232 127 has trust_key_id_header => (
233 is => 'rw',
234 builder => '_build_trust_key_id_header',
235 );
236  
237 924 ▶sub _build_trust_key_id_header {
Subroutine _build_trust_key_id_header: called CC=3 SCAR=14.2
238 924 ▶ return (defined($ENV{SKEID_TRUST_KEY_ID_HEADER}) && $ENV{SKEID_TRUST_KEY_ID_HEADER} =~ /^(1|true|yes|on)$/i)
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_TRUST_KEY_ID_HEADER'} && $ENV{'SKEID_TRUST_KEY_ID_HEADER'} =~ /^(1|true|yes|on)$/i ? : 0 924 924
Condition33%1/3
defined $ENV{"SKEID_TRUST_KEY_ID_HEADER"} and $ENV{"SKEID_TRUST_KEY_ID_HEADER"} =~ /^(1|true|yes|on)$/i
!ll&&!rl&&r
92400
MC/DC0%0/2
defined $ENV{"SKEID_TRUST_KEY_ID_HEADER"} and $ENV{"SKEID_TRUST_KEY_ID_HEADER"} =~ /^(1|true|yes|on)$/i
defined $ENV{"SKEID_TRUST_KEY_ID_HEADER"} $ENV{"SKEID_TRUST_KEY_ID_HEADER"} =~ /^(1|true|yes|on)$/i
Truth table33%1/3
A and B
A= defined $ENV{"SKEID_TRUST_KEY_ID_HEADER"}B= $ENV{"SKEID_TRUST_KEY_ID_HEADER"} =~ /^(1|true|yes|on)$/i
ABresult
0X0
100
111
239 ? 1 : 0;
240 }
241  
242  
243 127 has route_wait_timeout_ms => (
244 is => 'rw',
245 builder => '_build_route_wait_timeout_ms',
246 );
247  
248 755 ▶sub _build_route_wait_timeout_ms {
Subroutine _build_route_wait_timeout_ms: called CC=3 SCAR=12.0
249 return (defined($ENV{SKEID_ROUTE_WAIT_TIMEOUT_MS}) && length($ENV{SKEID_ROUTE_WAIT_TIMEOUT_MS}))
250 ? 0 + $ENV{SKEID_ROUTE_WAIT_TIMEOUT_MS}
251 755 ▶ : 2000;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_ROUTE_WAIT_TIMEOUT_MS'} && length $ENV{'SKEID_ROUTE_WAIT_TIMEOUT_MS'} ? : 0 755 755
Condition66%2/3
defined $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"} and length $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"}
!ll&&!rl&&r
75410
MC/DC0%0/2
defined $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"} and length $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"}
defined $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"} length $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"}
Truth table66%2/3
A and B
A= defined $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"}B= length $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"}
ABresult
0X0
100
111
252 }
253  
254  
255 127 has route_wait_poll_ms => (
256 is => 'rw',
257 builder => '_build_route_wait_poll_ms',
258 );
259  
260 633 ▶sub _build_route_wait_poll_ms {
Subroutine _build_route_wait_poll_ms: called CC=3 SCAR=14.2
261 return (defined($ENV{SKEID_ROUTE_WAIT_POLL_MS}) && length($ENV{SKEID_ROUTE_WAIT_POLL_MS}))
262 ? 0 + $ENV{SKEID_ROUTE_WAIT_POLL_MS}
263 633 ▶ : 25;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_ROUTE_WAIT_POLL_MS'} && length $ENV{'SKEID_ROUTE_WAIT_POLL_MS'} ? : 0 633 633
Condition33%1/3
defined $ENV{"SKEID_ROUTE_WAIT_POLL_MS"} and length $ENV{"SKEID_ROUTE_WAIT_POLL_MS"}
!ll&&!rl&&r
63300
MC/DC0%0/2
defined $ENV{"SKEID_ROUTE_WAIT_POLL_MS"} and length $ENV{"SKEID_ROUTE_WAIT_POLL_MS"}
defined $ENV{"SKEID_ROUTE_WAIT_POLL_MS"} length $ENV{"SKEID_ROUTE_WAIT_POLL_MS"}
Truth table33%1/3
A and B
A= defined $ENV{"SKEID_ROUTE_WAIT_POLL_MS"}B= length $ENV{"SKEID_ROUTE_WAIT_POLL_MS"}
ABresult
0X0
100
111
264 }
265  
266  
267 has usage_db_path => (
268 is => 'rw',
269 predicate => 'has_usage_db_path',
270 clearer => 'clear_usage_db_path',
271 924 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=14.2
272 return (defined($ENV{SKEID_USAGE_DB}) && length($ENV{SKEID_USAGE_DB}))
273 ? $ENV{SKEID_USAGE_DB}
274 924 ▶ : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_USAGE_DB'} && length $ENV{'SKEID_USAGE_DB'} ? : 0 924 924
Condition33%1/3
defined $ENV{"SKEID_USAGE_DB"} and length $ENV{"SKEID_USAGE_DB"}
!ll&&!rl&&r
92400
MC/DC0%0/2
defined $ENV{"SKEID_USAGE_DB"} and length $ENV{"SKEID_USAGE_DB"}
defined $ENV{"SKEID_USAGE_DB"} length $ENV{"SKEID_USAGE_DB"}
Truth table33%1/3
A and B
A= defined $ENV{"SKEID_USAGE_DB"}B= length $ENV{"SKEID_USAGE_DB"}
ABresult
0X0
100
111
275 },
276 127 );
277  
278  
279 has usage_store => (
280 is => 'rw',
281 862 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
282 127 );
283  
284  
285 127 has store_usage_event => (
286 is => 'ro',
287 predicate => 'has_store_usage_event',
288 );
289  
290  
291 127 has query_usage_report => (
292 is => 'ro',
293 predicate => 'has_query_usage_report',
294 );
295  
296  
297 127 has on_usage_lost => (
298 is => 'rw',
299 predicate => 'has_on_usage_lost',
300 );
301  
302  
303 127 has admin_api_key => (
304 is => 'rw',
305 builder => '_build_admin_api_key',
306 );
307  
308 1834 ▶sub _build_admin_api_key { $_[0]->_env_admin_api_key }
Subroutine _build_admin_api_key: called CC=1 SCAR=0.0
309  
310 2368 ▶sub _env_admin_api_key {
Subroutine _env_admin_api_key: called CC=3 SCAR=11.0
311 return (defined($ENV{SKEID_ADMIN_API_KEY}) && length($ENV{SKEID_ADMIN_API_KEY}))
312 ? $ENV{SKEID_ADMIN_API_KEY}
313 2368 ▶ : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_ADMIN_API_KEY'} && length $ENV{'SKEID_ADMIN_API_KEY'} ? : 6 2362 2368
Condition100%3/3
defined $ENV{"SKEID_ADMIN_API_KEY"} and length $ENV{"SKEID_ADMIN_API_KEY"}
!ll&&!rl&&r
2340226
MC/DC100%2/2
defined $ENV{"SKEID_ADMIN_API_KEY"} and length $ENV{"SKEID_ADMIN_API_KEY"}
defined $ENV{"SKEID_ADMIN_API_KEY"} length $ENV{"SKEID_ADMIN_API_KEY"}
Truth table100%3/3
A and B
A= defined $ENV{"SKEID_ADMIN_API_KEY"}B= length $ENV{"SKEID_ADMIN_API_KEY"}
ABresult
0X0
100
111
314 }
315  
316 # The admin API key given explicitly -- to new(), to build_app, or by `skeid serve
317 # --admin-api-key` (skeid k64). It outranks the config, so a reload re-resolves the key under
318 # it instead of overwriting it; empty means none was given.
319 has _explicit_admin_api_key => (
320 is => 'rw',
321 init_arg => undef,
322 924 ▶ default => sub { '' },
Subroutine __ANON__: called CC=1 SCAR=0.0
323 127 );
324  
325 # The admin API key the config (or SKEID_ADMIN_API_KEY under it) resolved to when it was last
326 # applied. Kept apart from the explicit key so that clearing that one falls back to it at once.
327 127 has _config_admin_api_key => (
328 is => 'rw',
329 init_arg => undef,
330 builder => '_build_admin_api_key',
331 );
332  
333  
334 127 has key_broker => (is => 'ro', predicate => 'has_key_broker');
335  
336  
337 127 has config_file => (
338 is => 'ro',
339 predicate => 'has_config_file',
340 );
341  
342  
343 127 has config_loader => (
344 is => 'ro',
345 predicate => 'has_config_loader',
346 );
347  
348 # Node files (ADR 0031): per path, what was last read -- seen (mtime, size, inode), the nodes
349 # of the last good read, its error, and the last check's accepted count and rejections.
350 has _node_files => (
351 is => 'rw',
352 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
353 127 );
354  
355 has _config_mtime => (
356 is => 'rw',
357 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
358 127 );
359  
360 # A file version that failed before it could update _config_mtime, and when that same version
361 # may be tried again. A different mtime bypasses this window, so a correction is prompt; the
362 # retry keeps a transient read error from freezing an otherwise unchanged file forever.
363 has _config_file_failed_mtime => (
364 is => 'rw',
365 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
366 127 );
367  
368 has _config_file_retry_at => (
369 is => 'rw',
370 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
371 127 );
372  
373 # Set while config_file is missing after a good load, so the loss is warned once.
374 has _config_file_missing => (
375 is => 'rw',
376 924 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
377 127 );
378  
379  
380 has config_reload_interval => (
381 is => 'rw',
382 654 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=14.2
383 return (defined($ENV{SKEID_CONFIG_RELOAD_INTERVAL}) && length($ENV{SKEID_CONFIG_RELOAD_INTERVAL}))
384 ? 0 + $ENV{SKEID_CONFIG_RELOAD_INTERVAL}
385 654 ▶ : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_CONFIG_RELOAD_INTERVAL'} && length $ENV{'SKEID_CONFIG_RELOAD_INTERVAL'} ? : 0 654 654
Condition33%1/3
defined $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"} and length $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"}
!ll&&!rl&&r
65400
MC/DC0%0/2
defined $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"} and length $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"}
defined $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"} length $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"}
Truth table33%1/3
A and B
A= defined $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"}B= length $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"}
ABresult
0X0
100
111
386 },
387 127 );
388  
389 # When the loader may run next (see config_reload_interval).
390 has _config_next_check_at => (
391 is => 'rw',
392 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
393 127 );
394  
395 # What the last applied config was: the loader's version when it gives one, else a digest of
396 # the loaded structure. A reload that reads the same fingerprint changes nothing (skeid #38).
397 has _config_fingerprint => (
398 is => 'rw',
399 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
400 127 );
401  
402  
403 924 ▶has last_reload_error => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
404 924 ▶has last_reload_error_at => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
405 924 ▶has reload_failures => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
406  
407 # The fingerprint of the config that last failed to apply. Reading the same one again is not
408 # retried: the answer would be the same error (skeid #39).
409 has _failed_fingerprint => (
410 is => 'rw',
411 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
412 127 );
413  
414 # The routing attributes as they were before any config was applied (see BUILD).
415 has _routing_baseline => (
416 is => 'rw',
417 init_arg => undef,
418 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
419 127 );
420  
421 # The sections the last applied config declared (see _apply_config). A section that was declared
422 # and is gone from the next config goes back to its default; one never declared is left alone.
423 has _config_declared => (
424 is => 'rw',
425 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
426 127 );
427  
428 # Digest of the nodes section the node list was last built from. An unchanged section keeps
429 # the node list -- and with it the inventory generation, the running probes and any health an
430 # admin set -- even when another section of the config changed.
431 has _nodes_fingerprint => (
432 is => 'rw',
433 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
434 127 );
435  
436 # Per node id, the digest of the config entry it was built from: an unchanged entry keeps the
437 # health an admin set when the nodes section is rebuilt.
438 has _node_entry_prints => (
439 is => 'rw',
440 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
441 127 );
442 127 has _main_nodes_print => (is => 'rw');
443  
444 has _rr_cursor => (
445 is => 'rw',
446 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
447 127 );
448  
449 has _inventory_generation => (
450 is => 'rw',
451 924 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
452 127 );
453  
454 has _route_cache => (
455 is => 'rw',
456 924 ▶ default => sub { { generation => -1, entries => {}, order => [] } },
Subroutine __ANON__: called CC=1 SCAR=0.0
457 127 );
458  
459 # The model names of the chat-kind nodes as of one inventory generation (see _known_node_models).
460 has _known_models_cache => (
461 is => 'rw',
462 924 ▶ default => sub { { generation => -1 } },
Subroutine __ANON__: called CC=1 SCAR=0.0
463 127 );
464  
465 # The probe key (see _probe_inventory_key) as of one inventory generation.
466 has _probe_key_cache => (
467 is => 'rw',
468 924 ▶ default => sub { { generation => -1, key => undef } },
Subroutine __ANON__: called CC=1 SCAR=0.0
469 127 );
470  
471 has _inflight => (
472 is => 'rw',
473 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
474 127 );
475  
476 # node_id => normalized capacity reading (see set_capacity_reading). Written by probes off the
477 # request path, read by admission.
478 has _capacity => (
479 is => 'rw',
480 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
481 127 );
482  
483  
484 has capacity_max_age_ms => (
485 is => 'rw',
486 914 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=14.2
487 return (defined($ENV{SKEID_CAPACITY_MAX_AGE_MS}) && length($ENV{SKEID_CAPACITY_MAX_AGE_MS}))
488 ? 0 + $ENV{SKEID_CAPACITY_MAX_AGE_MS}
489 914 ▶ : 5000;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_CAPACITY_MAX_AGE_MS'} && length $ENV{'SKEID_CAPACITY_MAX_AGE_MS'} ? : 0 914 914
Condition33%1/3
defined $ENV{"SKEID_CAPACITY_MAX_AGE_MS"} and length $ENV{"SKEID_CAPACITY_MAX_AGE_MS"}
!ll&&!rl&&r
91400
MC/DC0%0/2
defined $ENV{"SKEID_CAPACITY_MAX_AGE_MS"} and length $ENV{"SKEID_CAPACITY_MAX_AGE_MS"}
defined $ENV{"SKEID_CAPACITY_MAX_AGE_MS"} length $ENV{"SKEID_CAPACITY_MAX_AGE_MS"}
Truth table33%1/3
A and B
A= defined $ENV{"SKEID_CAPACITY_MAX_AGE_MS"}B= length $ENV{"SKEID_CAPACITY_MAX_AGE_MS"}
ABresult
0X0
100
111
490 },
491 127 );
492  
493  
494 has worker_count => (
495 is => 'rw',
496 914 ▶ default => sub { 1 },
Subroutine __ANON__: called CC=1 SCAR=0.0
497 15 ▶ trigger => sub { $_[0]->_bump_inventory },
Subroutine __ANON__: called CC=1 SCAR=0.0
498 127 );
499  
500  
501 127 has frontend_count => (
502 is => 'rw',
503 builder => '_build_frontend_count',
504 );
505  
506 917 ▶sub _build_frontend_count {
Subroutine _build_frontend_count: called CC=3 SCAR=12.0
507 return (defined($ENV{SKEID_FRONTEND_COUNT}) && length($ENV{SKEID_FRONTEND_COUNT}))
508 ? 0 + $ENV{SKEID_FRONTEND_COUNT}
509 917 ▶ : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_FRONTEND_COUNT'} && length $ENV{'SKEID_FRONTEND_COUNT'} ? : 0 917 917
Condition66%2/3
defined $ENV{"SKEID_FRONTEND_COUNT"} and length $ENV{"SKEID_FRONTEND_COUNT"}
!ll&&!rl&&r
91610
MC/DC0%0/2
defined $ENV{"SKEID_FRONTEND_COUNT"} and length $ENV{"SKEID_FRONTEND_COUNT"}
defined $ENV{"SKEID_FRONTEND_COUNT"} length $ENV{"SKEID_FRONTEND_COUNT"}
Truth table66%2/3
A and B
A= defined $ENV{"SKEID_FRONTEND_COUNT"}B= length $ENV{"SKEID_FRONTEND_COUNT"}
ABresult
0X0
100
111
510 }
511  
512  
513 924 ▶has registry_enabled => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
514 924 ▶has registry_secret => (is => 'rw', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
515 924 ▶has registry_read_key => (is => 'rw', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
516 924 ▶has registry_ttl_s => (is => 'rw', default => sub { 10 });
Subroutine __ANON__: called CC=1 SCAR=0.0
517 924 ▶has registry_instance_id => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
518 924 ▶has registry_error_window_s => (is => 'rw', default => sub { 60 });
Subroutine __ANON__: called CC=1 SCAR=0.0
519  
520 # node_id => { last_at => epoch, buckets => { epoch_second => count } }. Failed requests, for
521 # the registry snapshot's errors_in_window and last_failure_at. Reported, never consulted by
522 # admission: health is operator state (ADR 0009, ADR 0017).
523 has _failures => (
524 is => 'rw',
525 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
526 127 );
527  
528 # The same shape for requests the client's own fault ended (k99): the registry snapshot's
529 # rejected_in_window. Kept apart from _failures so errors_in_window keeps its meaning.
530 has _rejections => (
531 is => 'rw',
532 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
533 127 );
534  
535 has _stats => (
536 is => 'rw',
537 924 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
538 127 );
539  
540 has _usage_store_obj => (
541 is => 'rw',
542 924 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
543 127 );
544  
545 127 my %FALLBACK_ENGINE_IDS = map { $_ => 1 } qw(
546 aki
547 akiopenai
548 anthropic
549 anthropicbase
550 cerebras
551 deepseek
552 gemini
553 groq
554 huggingface
555 lmstudio
556 lmstudioanthropic
557 lmstudioopenai
558 llamacpp
559 minimax
560 mistral
561 nousresearch
562 ollama
563 ollamaopenai
564 openai
565 openaibase
566 openrouter
567 perplexity
568 remote
569 replicate
570 sglang
571 vllm
572 whisper
573 );
574  
575 # How a routing key of the config sets its attribute. A key removed from the config sets it back
576 # to its value before any config was applied (_routing_baseline, skeid k65).
577 my %ROUTING_SETTINGS = (
578 19 ▶ wait_timeout_ms => [ route_wait_timeout_ms => sub { 0 + $_[0] } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
579 21 ▶ wait_poll_ms => [ route_wait_poll_ms => sub { my $poll = 0 + $_[0]; $poll < 1 ? 1 : $poll } ],
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$poll < 1 ? : 0 21 21
580 3 ▶ trust_key_id_header => [ trust_key_id_header => sub { $_[0] =~ /^(1|true|yes|on)$/i ? 1 : 0 } ],
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /^(1|true|yes|on)$/i ? : 3 0 3
581 # How many Skeid hosts share the nodes. Only the config knows it -- there is nothing to
582 # detect -- and forgetting it over-admits every node by that factor (ADR 0012). Floor at one,
583 # so a stray 0 falls back to today's single-frontend behaviour instead of dividing max_conns
584 # to nothing.
585 5 ▶ frontend_count => [ frontend_count => sub { my $n = int(0 + $_[0]); $n < 1 ? 1 : $n } ],
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$n < 1 ? : 1 4 5
586 correlation_header => [ correlation_header => \&_normalize_correlation_header ],
587 catch_all => [ catch_all => \&_normalize_catch_all ],
588 );
589  
590 # The kinds of route a catch-all can be set for (ADR 0033). The kind is the route's, not a
591 # node kind: both are served by chat-kind nodes.
592 127 my %CATCH_ALL_KIND = map { $_ => 1 } qw( chat embeddings );
593  
594 34 ▶sub _normalize_catch_all {
Subroutine _normalize_catch_all: called CC=7 SCAR=19.5
595 34 my ($catch_all) = @_;
596 34 ▶ croak 'routing.catch_all must be a mapping of chat and embeddings' unless ref($catch_all) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $catch_all eq "HASH" 1 33 34
597 33 my %targets;
598 33 for my $kind (sort keys %$catch_all) {
599 croak "routing.catch_all: unknown key '$kind' (expected chat, embeddings)"
600 54 ▶ unless $CATCH_ALL_KIND{$kind};
Branch: 1 branch
BranchTrueFalseTotal
unless $CATCH_ALL_KIND{$kind} 2 52 54
601 52 my $target = $catch_all->{$kind};
602 52 ▶ croak "routing.catch_all.$kind must be a model name"
Branch: 1 branch
BranchTrueFalseTotal
if not defined $target or ref $target or not length $target 3 49 52
Condition83%5/6
not defined $target or ref $target or not length $target
l!l&&r!l&&!r
2149
not defined $target or ref $target
l!l&&r!l&&!r
0250
MC/DC66%2/3
not defined $target or ref $target or not length $target
not defined $target ref $target not length $target
Truth table75%3/4
not(A) or B or not(C)
A= not defined $targetB= ref $targetC= not length $target
ABCresult
1XX1
01X1
0011
0000
603 if !defined($target) || ref($target) || !length($target);
604 49 $targets{$kind} = "$target";
605 }
606 28 return \%targets;
607 }
608  
609 5 ▶sub _normalize_correlation_header {
Subroutine _normalize_correlation_header: called CC=3 SCAR=11.0
610 5 my ($name) = @_;
611 5 ▶ croak 'routing.correlation_header must be a header name'
Branch: 1 branch
BranchTrueFalseTotal
if ref $name or not $name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/ 1 4 5
Condition66%2/3
ref $name or not $name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/
l!l&&r!l&&!r
014
MC/DC50%1/2
ref $name or not $name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/
ref $name not $name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/
Truth table66%2/3
A or not(B)
A= ref $nameB= not $name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/
ABresult
1X1
011
000
612 if ref($name) || $name !~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/;
613 4 return "$name";
614 }
615  
616 924 ▶sub BUILD {
Subroutine BUILD: called CC=9 SCAR=22.5
Pod undocumented
617 924 my ($self, $args) = @_;
618 # A key handed to new() is explicit: the config applied next must not replace it.
619 $self->_explicit_admin_api_key("$args->{admin_api_key}")
620 924 ▶ if defined($args->{admin_api_key}) && length($args->{admin_api_key});
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"admin_api_key"} and length $args->{"admin_api_key"} 14 910 924
Condition66%2/3
defined $args->{"admin_api_key"} and length $args->{"admin_api_key"}
!ll&&!rl&&r
910014
MC/DC50%1/2
defined $args->{"admin_api_key"} and length $args->{"admin_api_key"}
defined $args->{"admin_api_key"} length $args->{"admin_api_key"}
Truth table66%2/3
A and B
A= defined $args->{"admin_api_key"}B= length $args->{"admin_api_key"}
ABresult
0X0
100
111
621 # What the routing attributes are without a config -- passed to new(), else from the
622 # environment, else built in: a routing key removed from the config goes back to this.
623 924 $self->_routing_baseline({ map { my $attr = $_->[0]; ($attr => $self->$attr) } values %ROUTING_SETTINGS });
624 924 ▶ if ($self->has_config_loader || $self->has_config_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_config_loader or $self->has_config_file) 575 349 924
Condition100%3/3
$self->has_config_loader or $self->has_config_file
l!l&&r!l&&!r
55520349
MC/DC100%2/2
$self->has_config_loader or $self->has_config_file
$self->has_config_loader $self->has_config_file
Truth table100%3/3
A or B
A= $self->has_config_loaderB= $self->has_config_file
ABresult
1X1
011
000
625 575 $self->reload_config;
626 }
627 797 ▶ if (ref($self->usage_store) eq 'HASH' && keys %{$self->usage_store}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->usage_store eq 'HASH' and keys %{$self->usage_store;}) { } 72 725 797
Condition66%2/3
ref $self->usage_store eq "HASH" and keys %{$self->usage_store;}
!ll&&!rl&&r
072572
MC/DC50%1/2
ref $self->usage_store eq "HASH" and keys %{$self->usage_store;}
ref $self->usage_store eq "HASH" keys %{$self->usage_store;}
Truth table66%2/3
A and B
A= ref $self->usage_store eq "HASH"B= keys %{$self->usage_store;}
ABresult
0X0
100
111
628 72 $self->_configure_usage_store($self->usage_store);
629 } else {
630 725 my $path = $self->usage_db_path;
631 725 ▶ if (defined $path && length $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $path and length $path) 0 725 725
Condition33%1/3
defined $path and length $path
!ll&&!rl&&r
72500
MC/DC0%0/2
defined $path and length $path
defined $path length $path
Truth table33%1/3
A and B
A= defined $pathB= length $path
ABresult
0X0
100
111
632 0 $self->_set_usage_db_path($path);
633 }
634 }
635 }
636  
637  
638 1449 ▶sub add_node {
Subroutine add_node: called CC=27 SCAR=33.2
Pod documented
639 1449 my ($self, %node) = @_;
640 1449 ▶ my $id = $node{id} // croak 'node id required';
Condition50%1/2
$node{"id"} // croak("node id required")
l!l
14490
MC/DC0%0/1
$node{"id"} // croak("node id required")
$node{"id"}
Truth table50%1/2
A
A= $node{"id"}
Aresult
11
00
641 1449 ▶ my $url = $node{url} // croak 'node url required';
Condition50%1/2
$node{"url"} // croak("node url required")
l!l
14490
MC/DC0%0/1
$node{"url"} // croak("node url required")
$node{"url"}
Truth table50%1/2
A
A= $node{"url"}
Aresult
11
00
642  
643 # A registry probe with no secret would forget on every poll and look like a silent
644 # downstream; say so where the operator wrote it (ADR 0017).
645 1449 ▶ if (ref($node{capacity}) eq 'HASH'
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node{"capacity"} eq "HASH" and lc(($node{"capacity"}{"probe"} // $node{"capacity"}{"type"}) // "") eq "registry") 13 1436 1449
Condition75%6/8
ref $node{"capacity"} eq "HASH" and lc(($node{"capacity"}{"probe"} // $node{"capacity"}{"type"}) // "") eq "registry"
!ll&&!rl&&r
14181813
($node{"capacity"}{"probe"} // $node{"capacity"}{"type"}) // ""
l!l
310
$node{"capacity"}{"probe"} // $node{"capacity"}{"type"}
l!l&&r!l&&!r
3010
MC/DC33%1/3
ref $node{"capacity"} eq "HASH" and lc(($node{"capacity"}{"probe"} // $node{"capacity"}{"type"}) // "") eq "registry"
ref $node{"capacity"} eq "HASH" $node{"capacity"}{"probe"} $node{"capacity"}{"type"}
Truth table75%3/4
A and B // C
A= ref $node{"capacity"} eq "HASH"B= $node{"capacity"}{"probe"}C= $node{"capacity"}{"type"}
ABCresult
0XX0
1000
11X1
1011
646 && lc($node{capacity}{probe} // $node{capacity}{type} // '') eq 'registry') {
647 13 require Langertha::Skeid::CapacityProbe::Registry;
648 13 Langertha::Skeid::CapacityProbe::Registry->validate_config($node{capacity}, $id);
649 }
650  
651 # An unknown format croaks, like an unknown engine: a TEI node called in the default dialect
652 # answers every request with an error (skeid k92).
653 1443 my $rerank_format = Langertha::Skeid::Protocol::Rerank->normalize_format($node{rerank_format});
654  
655 # The same for the kind of node and the header its key goes in (skeid k94, ADR 0028): a node of
656 # a kind nobody spelled right would be sent the wrong sort of request, and a header name that
657 # is no token could carry a line break upstream.
658 1438 my $kind = Langertha::Skeid::Protocol::Documents->normalize_kind($node{kind});
659 1434 my $key_header = Langertha::Skeid::Protocol::Documents->normalize_key_header($node{api_key_header});
660  
661 # Whose infrastructure the node is (skeid k128, ADR 0032). An external node is sent no client
662 # header beyond an allowlist and never the client's credential: without a key of its own, the
663 # only credential left to send it would be the customer's.
664 1430 my $trust = $self->normalize_trust($node{trust});
665 1429 ▶ croak "node '$id' is external and names no key source: "
Branch: 1 branch
BranchTrueFalseTotal
if $trust eq "external" and not $self->node_has_key_source(\%node) 5 1424 1429
Condition100%3/3
$trust eq "external" and not $self->node_has_key_source(\%node)
!ll&&!rl&&r
1394305
MC/DC100%2/2
$trust eq "external" and not $self->node_has_key_source(\%node)
$trust eq "external" not $self->node_has_key_source(\%node)
Truth table100%3/3
A and not(B)
A= $trust eq "external"B= not $self->node_has_key_source(\%node)
ABresult
0X0
100
111
666 . 'set api_key_env or api_key_ref, or trust: internal'
667 if $trust eq 'external' && !$self->node_has_key_source(\%node);
668  
669 # Every check that can croak runs before the removal: a bad re-add must leave the working
670 # node in the inventory (skeid k98).
671 1424 ▶ my $engine = $self->normalize_engine_id((defined($node{engine}) && length($node{engine})) ? $node{engine} : 'OpenAIBase');
Branch: 1 branch
BranchTrueFalseTotal
defined $node{'engine'} && length $node{'engine'} ? : 980 444 1424
Condition66%2/3
defined $node{"engine"} and length $node{"engine"}
!ll&&!rl&&r
4440980
MC/DC50%1/2
defined $node{"engine"} and length $node{"engine"}
defined $node{"engine"} length $node{"engine"}
Truth table66%2/3
A and B
A= defined $node{"engine"}B= length $node{"engine"}
ABresult
0X0
100
111
672 1422 my $tags = $self->normalize_tags($node{tags});
673  
674 1422 $self->remove_node($id);
675 1422 ▶ push @{$self->nodes}, {
Branch: 8 branches
BranchTrueFalseTotal
defined $node{'weight'} ? : 16 1406 1422
defined $node{'max_conns'} ? : 1141 281 1422
exists $node{'healthy'} ? : 808 614 1422
$node{'healthy'} ? : 807 1 808
ref $node{'metadata'} eq 'HASH' ? : 1 1421 1422
defined $node{'api_key_env'} && length $node{'api_key_env'} ? : 116 1306 1422
defined $node{'api_key_ref'} && length $node{'api_key_ref'} ? : 107 1315 1422
ref $node{'capacity'} eq 'HASH' ? : 25 1397 1422
Condition75%6/8
$node{"model"} // ""
l!l
134775
defined $node{"api_key_env"} and length $node{"api_key_env"}
!ll&&!rl&&r
13060116
defined $node{"api_key_ref"} and length $node{"api_key_ref"}
!ll&&!rl&&r
13150107
MC/DC100%1/1
$node{"model"} // ""
$node{"model"}
MC/DC50%1/2
defined $node{"api_key_env"} and length $node{"api_key_env"}
defined $node{"api_key_env"} length $node{"api_key_env"}
MC/DC50%1/2
defined $node{"api_key_ref"} and length $node{"api_key_ref"}
defined $node{"api_key_ref"} length $node{"api_key_ref"}
Truth table100%2/2
A
A= $node{"model"}
Aresult
11
00
Truth table66%2/3
A and B
A= defined $node{"api_key_env"}B= length $node{"api_key_env"}
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= defined $node{"api_key_ref"}B= length $node{"api_key_ref"}
ABresult
0X0
100
111
676 id => $id,
677 url => $url,
678 model => ($node{model} // ''),
679 engine => $engine,
680 weight => (defined $node{weight} ? 0 + $node{weight} : 1),
681 max_conns => (defined $node{max_conns} ? 0 + $node{max_conns} : 0),
682 healthy => (exists $node{healthy} ? ($node{healthy} ? 1 : 0) : 1),
683 trust => $trust,
684 tags => $tags,
685 metadata => (ref($node{metadata}) eq 'HASH' ? $node{metadata} : {}),
686 (defined($node{api_key_env}) && length($node{api_key_env})
687 ? (api_key_env => "$node{api_key_env}")
688 : ()),
689 (defined($node{api_key_ref}) && length($node{api_key_ref})
690 ? (api_key_ref => "$node{api_key_ref}")
691 : ()),
692 # How this node's capacity is found (ADR 0009). Absent means inflight, which is every
693 # deployment that existed before probes did.
694 25 ▶ (ref($node{capacity}) eq 'HASH' ? (capacity => { %{$node{capacity}} }) : ()),
Branch: 4 branches
BranchTrueFalseTotal
length $rerank_format ? : 14 1408 1422
length $kind ? : 27 1395 1422
length $key_header ? : 3 1419 1422
defined $node{'node_file'} && length $node{'node_file'} ? : 13 1409 1422
Condition66%2/3
defined $node{"node_file"} and length $node{"node_file"}
!ll&&!rl&&r
1409013
MC/DC50%1/2
defined $node{"node_file"} and length $node{"node_file"}
defined $node{"node_file"} length $node{"node_file"}
Truth table66%2/3
A and B
A= defined $node{"node_file"}B= length $node{"node_file"}
ABresult
0X0
100
111
695 # The dialect the node's rerank route speaks when it is not the client's (skeid k92).
696 # Absent means the request is relayed as it came.
697 (length($rerank_format) ? (rerank_format => $rerank_format) : ()),
698 # What the node serves when it is not chat completions: `documents` is a docling-serve node,
699 # reached by the documents routes and by nothing else (ADR 0028). Absent means chat, which
700 # is every node there was before the option.
701 (length($kind) ? (kind => $kind) : ()),
702 # The header the node's key is sent in, raw, instead of `Authorization: Bearer` (docling's
703 # `X-Api-Key`). Absent means Authorization.
704 (length($key_header) ? (api_key_header => $key_header) : ()),
705 # The node file it came from (ADR 0031): such a node never gets the client's credentials.
706 1422 (defined($node{node_file}) && length($node{node_file}) ? (node_file => "$node{node_file}") : ()),
707 };
708 1422 $self->_bump_inventory;
709 1422 return 1;
710 }
711  
712  
713 1456 ▶sub normalize_trust {
Subroutine normalize_trust: called CC=6 SCAR=18.0
Pod documented
714 1456 my ($self, $value) = @_;
715 1456 ▶ return 'external' unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 34 1422 1456
716 1422 ▶ croak 'node trust must be internal or external' if ref $value;
Branch: 1 branch
BranchTrueFalseTotal
if ref $value 0 1422 1422
717 1422 (my $trust = lc "$value") =~ s/\A\s+|\s+\z//g;
718 1422 ▶ return 'external' unless length $trust;
Branch: 1 branch
BranchTrueFalseTotal
unless length $trust 0 1422 1422
719 1422 ▶ return $trust if $trust eq 'internal' || $trust eq 'external';
Branch: 1 branch
BranchTrueFalseTotal
if $trust eq "internal" or $trust eq "external" 1420 2 1422
Condition100%3/3
$trust eq "internal" or $trust eq "external"
l!l&&r!l&&!r
141462
MC/DC100%2/2
$trust eq "internal" or $trust eq "external"
$trust eq "internal" $trust eq "external"
Truth table100%3/3
A or B
A= $trust eq "internal"B= $trust eq "external"
ABresult
1X1
011
000
720 2 croak "unknown node trust '$value': internal or external";
721 }
722  
723  
724 38 ▶sub node_has_key_source {
Subroutine node_has_key_source: called CC=5 SCAR=16.1
Pod documented
725 38 my ($self, $node) = @_;
726 38 for my $field (qw( api_key_ref api_key_env )) {
727 64 my $value = $node->{$field};
728 64 ▶ return 1 if defined($value) && !ref($value) && length($value);
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and not ref $value and length $value 32 32 64
Condition83%5/6
defined $value and not ref $value and length $value
!ll&&!rl&&r
31132
defined $value and not ref $value
!ll&&!rl&&r
31033
MC/DC66%2/3
defined $value and not ref $value and length $value
defined $value not ref $value length $value
Truth table75%3/4
A and not(B) and C
A= defined $valueB= not ref $valueC= length $value
ABCresult
0XX0
10X0
1100
1111
729 }
730 6 return 0;
731 }
732  
733  
734 1442 ▶sub remove_node {
Subroutine remove_node: called CC=6 SCAR=18.2
Pod documented
735 1442 my ($self, $id) = @_;
736 1442 ▶ return 0 unless defined $id && length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 0 1442 1442
Condition33%1/3
defined $id and length $id
!ll&&!rl&&r
001442
MC/DC0%0/2
defined $id and length $id
defined $id length $id
Truth table33%1/3
A and B
A= defined $idB= length $id
ABresult
0X0
100
111
737 1442 ▶ my @keep = grep { ($_->{id} // '') ne $id } @{$self->nodes};
Condition50%1/2
$_->{"id"} // ""
l!l
19010
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
738 1442 my $removed = @{$self->nodes} - @keep;
739 1442 $self->nodes(\@keep);
740 # Or a node re-added under the same id inherits a reading -- or an error history -- about a
741 # different machine.
742 1442 ▶ if ($removed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($removed) 21 1421 1442
743 21 $self->forget_capacity($id);
744 21 delete $self->_failures->{$id};
745 21 delete $self->_rejections->{$id};
746 }
747 1442 ▶ return $removed ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$removed ? : 21 1421 1442
748 }
749  
750 # What the running capacity probes were built from: the worker count (it sets the poll interval,
751 # ADR 0010) and, per node with a capacity block, its id, URL and that block. The inventory
752 # generation is the wrong key for them -- it also moves on a health flip, which has to drop the
753 # route cache but changes nothing a probe polls, and restarting the probes forgets every reading
754 # (skeid #40). The URL is in because a Prometheus probe may derive its endpoint from it, and a
755 # reading about the machine a node id used to point at is not one about the new one.
756 # Recomputed only when the generation has moved, so the per-request check stays an integer
757 # compare.
758 2964 ▶sub _probe_inventory_key {
Subroutine _probe_inventory_key: called CC=7 SCAR=20.2
759 2964 my ($self) = @_;
760 2964 my $generation = $self->_inventory_generation;
761 2964 my $cache = $self->_probe_key_cache;
762 2964 ▶ return $cache->{key} if ($cache->{generation} // -1) == $generation;
Branch: 1 branch
BranchTrueFalseTotal
if ($cache->{"generation"} // -1) == $generation 2065 899 2964
Condition50%1/2
$cache->{"generation"} // -1
l!l
29640
MC/DC0%0/1
$cache->{"generation"} // -1
$cache->{"generation"}
Truth table50%1/2
A
A= $cache->{"generation"}
Aresult
11
00
763  
764 my $key = _config_digest([
765 0 + ($self->worker_count // 1),
766 40 map { [ $_->{id}, $_->{url}, $_->{capacity} ] }
767 20 ▶ sort { ($a->{id} // '') cmp ($b->{id} // '') }
Condition50%2/4
$Langertha::Skeid::a->{"id"} // ""
l!l
200
$Langertha::Skeid::b->{"id"} // ""
l!l
200
MC/DC0%0/1
$Langertha::Skeid::a->{"id"} // ""
$Langertha::Skeid::a->{"id"}
MC/DC0%0/1
$Langertha::Skeid::b->{"id"} // ""
$Langertha::Skeid::b->{"id"}
Truth table50%1/2
A
A= $Langertha::Skeid::a->{"id"}
Aresult
11
00
Truth table50%1/2
A
A= $Langertha::Skeid::b->{"id"}
Aresult
11
00
768 1303 grep { ref($_->{capacity}) eq 'HASH' }
769 899 ▶ @{$self->nodes || []},
Condition50%2/4
$self->worker_count // 1
l!l
8990
$self->nodes || []
l!l
8990
MC/DC0%0/1
$self->worker_count // 1
$self->worker_count
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $self->worker_count
Aresult
11
00
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
770 ]);
771 899 $self->_probe_key_cache({ generation => $generation, key => $key });
772 899 return $key;
773 }
774  
775 3230 ▶sub _bump_inventory {
Subroutine _bump_inventory: called CC=2 SCAR=7.0
776 3230 my ($self) = @_;
777 # Defensive //0: the nodes trigger can fire during construction, before this attribute's own
778 # default has been assigned.
779 3230 ▶ $self->_inventory_generation(($self->_inventory_generation // 0) + 1);
Condition50%1/2
$self->_inventory_generation // 0
l!l
32300
MC/DC0%0/1
$self->_inventory_generation // 0
$self->_inventory_generation
Truth table50%1/2
A
A= $self->_inventory_generation
Aresult
11
00
780 # A cursor names weighted ranges in exactly one inventory generation. Keeping it after a
781 # health, node or worker-share change both retains client-created keys and resumes fairness at
782 # a position that described a different set, so inventory invalidation clears all cursors.
783 3230 $self->_rr_cursor({});
784 3230 return;
785 }
786  
787  
788 19220 ▶sub normalize_tags {
Subroutine normalize_tags: called CC=7 SCAR=19.5
Pod documented
789 19220 my ($self, $value) = @_;
790 19220 ▶ return [] unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 6761 12459 19220
791  
792 12459 ▶ my @raw = ref($value) eq 'ARRAY' ? @$value : split(/[,\s]+/, "$value");
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'ARRAY' ? : 12457 2 12459
793 12459 my (@tags, %seen);
794 12459 for my $tag (@raw) {
795 1206 ▶ next unless defined $tag;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tag 0 1206 1206
796 1206 my $clean = lc "$tag";
797 1206 $clean =~ s/\A\s+//;
798 1206 $clean =~ s/\s+\z//;
799 1206 ▶ next unless length $clean;
Branch: 1 branch
BranchTrueFalseTotal
unless length $clean 0 1206 1206
800 1206 ▶ next if $seen{$clean}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$clean}++ 1 1205 1206
801 1205 push @tags, $clean;
802 }
803 12459 return \@tags;
804 }
805  
806  
807 391 ▶sub list_nodes {
Subroutine list_nodes: called CC=1 SCAR=0.0
Pod documented
808 391 my ($self) = @_;
809 391 return [ map { +{%$_} } @{$self->nodes} ];
810 }
811  
812  
813 50 ▶sub list_models {
Subroutine list_models: called CC=15 SCAR=27.5
Pod documented
814 50 my ($self, %args) = @_;
815 50 my $policy = $self->policy_for_key($args{api_key_id});
816 50 ▶ my $deny = $policy ? $policy->{deny_tags} : [];
Branch: 1 branch
BranchTrueFalseTotal
$policy ? : 6 44 50
817 50 my %entry;
818  
819 50 ▶ for my $n (@{$self->nodes || []}) {
Condition50%1/2
$self->nodes || []
l!l
500
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
820 91 my $model = $n->{model};
821 91 ▶ next unless defined $model && length $model;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and length $model 14 77 91
Condition66%2/3
defined $model and length $model
!ll&&!rl&&r
01477
MC/DC50%1/2
defined $model and length $model
defined $model length $model
Truth table66%2/3
A and B
A= defined $modelB= length $model
ABresult
0X0
100
111
822 # A documents node names no model a client can ask for (ADR 0028).
823 77 ▶ next if length($n->{kind} // '');
Branch: 1 branch
BranchTrueFalseTotal
if length($n->{"kind"} // "") 0 77 77
Condition50%1/2
$n->{"kind"} // ""
l!l
077
MC/DC0%0/1
$n->{"kind"} // ""
$n->{"kind"}
Truth table50%1/2
A
A= $n->{"kind"}
Aresult
11
00
824 77 ▶ next if $self->_node_has_any_tag($n, $deny);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_node_has_any_tag($n, $deny) 3 74 77
825 74 ▶ $entry{$model} //= { model => $model, engine => ($n->{engine} // '') };
Condition75%3/4
$entry{$model} //= {"model", $model, "engine", $n->{"engine"} // ""}
l!l
272
$n->{"engine"} // ""
l!l
720
MC/DC100%1/1
$entry{$model} //= {"model", $model, "engine", $n->{"engine"} // ""}
$entry{$model}
MC/DC0%0/1
$n->{"engine"} // ""
$n->{"engine"}
Truth table100%2/2
A
A= $entry{$model}
Aresult
11
00
Truth table50%1/2
A
A= $n->{"engine"}
Aresult
11
00
826 }
827 50 my $documents_key = Langertha::Skeid::Protocol::Documents->routing_key;
828 50 ▶ for my $name (keys %{$self->model_aliases || {}}) {
Condition50%1/2
$self->model_aliases || {}
l!l
500
MC/DC0%0/1
$self->model_aliases || {}
$self->model_aliases
Truth table50%1/2
A
A= $self->model_aliases
Aresult
11
00
829 # The alias of the documents routing key tiers documents nodes: it is not a chat model.
830 31 ▶ next if $name eq $documents_key;
Branch: 1 branch
BranchTrueFalseTotal
if $name eq $documents_key 1 30 31
831 30 ▶ $entry{$name} //= { model => $name, engine => '' };
Condition100%2/2
$entry{$name} //= {"model", $name, "engine", ""}
l!l
624
MC/DC100%1/1
$entry{$name} //= {"model", $name, "engine", ""}
$entry{$name}
Truth table100%2/2
A
A= $entry{$name}
Aresult
11
00
832 }
833  
834 return [
835 86 map { $entry{$_} }
836 50 grep { $self->route_plan(model => $_, api_key_id => $args{api_key_id})->{permitted} }
837 sort keys %entry
838 ];
839 }
840  
841  
842 38 ▶sub set_node_health {
Subroutine set_node_health: called CC=10 SCAR=23.2
Pod documented
843 38 my ($self, $id, $healthy) = @_;
844 38 ▶ return 0 unless defined $id && length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 0 38 38
Condition33%1/3
defined $id and length $id
!ll&&!rl&&r
0038
MC/DC0%0/2
defined $id and length $id
defined $id length $id
Truth table33%1/3
A and B
A= defined $idB= length $id
ABresult
0X0
100
111
845 38 my ($found, $changed) = (0, 0);
846 38 ▶ my $next = $healthy ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$healthy ? : 9 29 38
847 38 for my $n (@{$self->nodes}) {
848 50 ▶ next unless ($n->{id} // '') eq $id;
Branch: 1 branch
BranchTrueFalseTotal
unless ($n->{"id"} // "") eq $id 12 38 50
Condition50%1/2
$n->{"id"} // ""
l!l
500
MC/DC0%0/1
$n->{"id"} // ""
$n->{"id"}
Truth table50%1/2
A
A= $n->{"id"}
Aresult
11
00
849 38 ▶ if (($n->{healthy} ? 1 : 0) != $next) {
Branch: 2 branches
BranchTrueFalseTotal
if (($n->{"healthy"} ? 1 : 0) != $next) 36 2 38
$n->{'healthy'} ? : 29 9 38
850 36 $n->{healthy} = $next;
851 36 $changed = 1;
852 }
853 38 $found = 1;
854 38 last;
855 }
856 # Health is part of eligibility, so flipping it has to drop the derived lists -- otherwise a
857 # node taken out of rotation keeps receiving traffic until something else changes. It is not
858 # part of the probe key, so the capacity probes and their readings stay (skeid #40). Repeating
859 # the current value changes no inventory and must not reset its round-robin cursors.
860 38 ▶ $self->_bump_inventory if $changed;
Branch: 1 branch
BranchTrueFalseTotal
if $changed 36 2 38
861 38 return $found;
862 }
863  
864 # The prompt-cache rates a pricing rule may carry (skeid #28, ADR 0013). Optional: a rule
865 # without them prices every input token at input_per_million, exactly as before.
866 127 my @CACHE_RATE_KEYS = qw(cached_input_per_million cache_write_per_million);
867 127 my $cache_rates_unsupported_warned;
868  
869 # True when the installed Langertha prices prompt-cache reads and writes (Langertha::Cost has
870 # the cache amounts, core ADR 0031). The released 0.503 does not; there the cache rates are
871 # dropped at config load, so a rule prices exactly as a rule without them.
872 57 ▶sub _core_prices_cache { Langertha::Cost->can('cache_read_usd') ? 1 : 0 }
Subroutine _core_prices_cache: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
'Langertha::Cost'->can('cache_read_usd') ? : 57 0 57
873  
874  
875 151 ▶sub set_model_pricing {
Subroutine set_model_pricing: called CC=14 SCAR=26.6
Pod documented
876 151 my ($self, $model, $pricing) = @_;
877 151 ▶ croak 'model required' unless defined $model && length $model;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and length $model 0 151 151
Condition33%1/3
defined $model and length $model
!ll&&!rl&&r
00151
MC/DC0%0/2
defined $model and length $model
defined $model length $model
Truth table33%1/3
A and B
A= defined $modelB= length $model
ABresult
0X0
100
111
878 151 ▶ croak 'pricing hash required' unless ref($pricing) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pricing eq "HASH" 0 151 151
879 my %rule = (
880 input_per_million => 0 + ($pricing->{input_per_million} // 0),
881 151 ▶ output_per_million => 0 + ($pricing->{output_per_million} // 0),
Condition75%3/4
$pricing->{"input_per_million"} // 0
l!l
1510
$pricing->{"output_per_million"} // 0
l!l
1465
MC/DC0%0/1
$pricing->{"input_per_million"} // 0
$pricing->{"input_per_million"}
MC/DC100%1/1
$pricing->{"output_per_million"} // 0
$pricing->{"output_per_million"}
Truth table50%1/2
A
A= $pricing->{"input_per_million"}
Aresult
11
00
Truth table100%2/2
A
A= $pricing->{"output_per_million"}
Aresult
11
00
882 );
883 151 my @rates = grep { defined $pricing->{$_} } @CACHE_RATE_KEYS;
884 151 for my $key (@rates) {
885 123 my $rate = $pricing->{$key};
886 123 ▶ croak "pricing for '$model': $key must be a number >= 0"
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $rate and &looks_like_number($rate) and $rate >= 0 7 116 123
Condition100%6/6
not ref $rate and &looks_like_number($rate) and $rate >= 0
!ll&&!rl&&r
43116
not ref $rate and &looks_like_number($rate)
!ll&&!rl&&r
22119
MC/DC100%3/3
not ref $rate and &looks_like_number($rate) and $rate >= 0
not ref $rate &looks_like_number($rate) $rate >= 0
Truth table100%4/4
not(A) and B and C
A= not ref $rateB= &looks_like_number($rate)C= $rate >= 0
ABCresult
0XX0
10X0
1100
1111
887 unless !ref($rate) && looks_like_number($rate) && $rate >= 0;
888 }
889 144 ▶ if (@rates && !_core_prices_cache()) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rates and not _core_prices_cache()) 2 142 144
Condition100%3/3
@rates and not _core_prices_cache()
!ll&&!rl&&r
85572
MC/DC100%2/2
@rates and not _core_prices_cache()
@rates not _core_prices_cache()
Truth table100%3/3
A and not(B)
A= @ratesB= not _core_prices_cache()
ABresult
0X0
100
111
890 2 ▶ warn "skeid: pricing sets cached_input_per_million / cache_write_per_million, but this "
Branch: 1 branch
BranchTrueFalseTotal
unless $cache_rates_unsupported_warned++ 1 1 2
891 . "Langertha cannot price prompt-cache tokens; they are ignored and cached tokens bill "
892 . "at input_per_million\n"
893 unless $cache_rates_unsupported_warned++;
894 2 @rates = ();
895 }
896 144 $rule{$_} = 0 + $pricing->{$_} for @rates;
897 144 $self->model_pricing->{$model} = \%rule;
898 144 return $self->model_pricing->{$model};
899 }
900  
901  
902 731 ▶sub pricing_for_model {
Subroutine pricing_for_model: called CC=3 SCAR=11.0
Pod documented
903 731 my ($self, $model) = @_;
904 return $self->model_pricing->{$model}
905 731 ▶ || $self->model_pricing->{'*'}
Condition100%5/5
$self->model_pricing->{$model} || $self->model_pricing->{'*'} || {'input_per_million', 0, 'output_per_million', 0}
l!l
154577
$self->model_pricing->{$model} or $self->model_pricing->{"*"}
l!l&&r!l&&!r
44110577
MC/DC100%2/2
$self->model_pricing->{$model} || $self->model_pricing->{'*'} || {'input_per_million', 0, 'output_per_million', 0}
$self->model_pricing->{$model} $self->model_pricing->{"*"}
Truth table100%3/3
A or B
A= $self->model_pricing->{$model}B= $self->model_pricing->{"*"}
ABresult
1X1
011
000
906 || { input_per_million => 0, output_per_million => 0 };
907 }
908  
909 # The config state a reload replaces. A reload is all or nothing (skeid #29 review): a
910 # config that fails anywhere -- a bad policy, alias or manifest grant -- must not leave the
911 # sections before it applied and the ones after it not, which served every customer a 403
912 # from an emptied manifest map while routing already ran on the new policies.
913 127 my @CONFIG_STATE = qw(
914 model_aliases policies default_policy key_policies key_names nodes
915 route_wait_timeout_ms route_wait_poll_ms trust_key_id_header frontend_count catch_all
916 admin_api_key _config_admin_api_key
917 manifest_enabled manifest_available key_manifests client_auth_keys upload_max_bytes
918 documents_max_bytes documents_allow_remote_sources
919 mcp_servers mcp_public_url mcp_max_request_bytes openapi_swagger_ui openapi_cache_dir
920 realtime_idle_timeout realtime_max_session_seconds realtime_max_message_bytes
921 realtime_max_queued_bytes
922 registry_enabled registry_secret registry_read_key registry_ttl_s registry_instance_id registry_error_window_s
923 );
924  
925  
926 5905 ▶sub reload_config {
Subroutine reload_config: called CC=16 SCAR=27.7
Pod documented
927 5905 my ($self) = @_;
928 5905 my ($cfg, $fingerprint);
929 5905 ▶ unless (eval { ($cfg, $fingerprint) = $self->_read_config; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { () = $self->_read_config; 1 } }) 14 5891 5905
930 14 ▶ my $err = $@ || 'config loader failed';
Condition50%1/2
$@ || 'config loader failed'
l!l
140
MC/DC0%0/1
$@ || 'config loader failed'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
931 14 $self->_record_reload_failure($err, undef);
932 14 die $err;
933 }
934  
935 # With a customer_source, the config is two inputs: the file and the snapshot merged into it
936 # (ADR 0026). Either changing is a changed config; neither changing is the no-op below.
937 $fingerprint .= ';customer_source:' . $self->_source_digest
938 5891 ▶ if exists $cfg->{customer_source};
Branch: 1 branch
BranchTrueFalseTotal
if exists $cfg->{"customer_source"} 939 4952 5891
939  
940 # Same config as last applied: nothing to do. Rebuilding would replace the node list, which
941 # bumps the inventory generation, restarts every capacity probe and forgets health an admin
942 # set -- for a config that did not change (skeid #38).
943 5891 my $last = $self->_config_fingerprint;
944 5891 ▶ if (defined($last) && $last eq $fingerprint) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $last and $last eq $fingerprint) 5184 707 5891
Condition100%3/3
defined $last and $last eq $fingerprint
!ll&&!rl&&r
5661415184
MC/DC100%2/2
defined $last and $last eq $fingerprint
defined $last $last eq $fingerprint
Truth table100%3/3
A and B
A= defined $lastB= $last eq $fingerprint
ABresult
0X0
100
111
945 5184 $self->_clear_reload_failure;
946 5184 return $cfg;
947 }
948  
949 # The config that just failed, read again: it would fail the same way, so it is not applied
950 # again -- but it still counts as a failure, which is what the retry back-off grows on.
951 707 my $failed = $self->_failed_fingerprint;
952 707 ▶ if (defined($failed) && $failed eq $fingerprint && defined $self->last_reload_error) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $failed and $failed eq $fingerprint and defined $self->last_reload_error) 16 691 707
Condition83%5/6
defined $failed and $failed eq $fingerprint and defined $self->last_reload_error
!ll&&!rl&&r
691016
defined $failed and $failed eq $fingerprint
!ll&&!rl&&r
686516
MC/DC66%2/3
defined $failed and $failed eq $fingerprint and defined $self->last_reload_error
defined $failed $failed eq $fingerprint defined $self->last_reload_error
Truth table75%3/4
A and B and C
A= defined $failedB= $failed eq $fingerprintC= defined $self->last_reload_error
ABCresult
0XX0
10X0
1100
1111
953 16 my $err = $self->last_reload_error;
954 16 $self->_record_reload_failure($err, $fingerprint);
955 16 die $err;
956 }
957  
958 691 my %before = map { $_ => $self->$_ } @CONFIG_STATE;
959 691 ▶ my %pricing = %{$self->model_pricing || {}};
Condition50%1/2
$self->model_pricing || {}
l!l
6910
MC/DC0%0/1
$self->model_pricing || {}
$self->model_pricing
Truth table50%1/2
A
A= $self->model_pricing
Aresult
11
00
960 691 my ($generation, $route_cache, $probe_key_cache, $rr_cursor, $known_models_cache)
961 = ($self->_inventory_generation, $self->_route_cache, $self->_probe_key_cache, $self->_rr_cursor,
962 $self->_known_models_cache);
963  
964 691 my ($nodes_print, $declared, $notices, $source);
965 691 ▶ if (eval { ($nodes_print, $declared, $notices, $source) = $self->_apply_config($cfg); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { () = $self->_apply_config($cfg); 1 } }) 561 130 691
966 561 $self->_forget_departed_nodes;
967 561 $self->_config_fingerprint($fingerprint);
968 561 $self->_nodes_fingerprint($nodes_print);
969 561 $self->_config_declared($declared);
970 561 $self->_clear_reload_failure;
971 561 push @$notices, $self->_commit_customer_source($source);
972 561 warn 'skeid: ' . $_ . "\n" for @$notices;
973 561 return $cfg;
974 }
975  
976 130 ▶ my $err = $@ || 'config reload failed';
Condition50%1/2
$@ || 'config reload failed'
l!l
1300
MC/DC0%0/1
$@ || 'config reload failed'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
977 130 $self->_record_reload_failure($err, $fingerprint);
978 130 for my $attr (@CONFIG_STATE) {
979 4550 ▶ next if $attr eq 'nodes';
Branch: 1 branch
BranchTrueFalseTotal
if $attr eq "nodes" 130 4420 4550
980 4420 $self->$attr($before{$attr});
981 }
982 130 $self->model_pricing(\%pricing);
983 # Setting nodes bumps the inventory generation. The old list comes back unchanged (the failed
984 # load only built a new array), so its generation, derived caches and fairness cursors come back
985 # with it: an inventory that did not change must not look changed, and a cache left keyed on a
986 # generation number that is about to be reused would answer for a different list.
987 130 ▶ if ($self->nodes != $before{nodes}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->nodes != $before{"nodes"}) 29 101 130
988 29 $self->nodes($before{nodes});
989 29 $self->_inventory_generation($generation);
990 29 $self->_route_cache($route_cache);
991 29 $self->_probe_key_cache($probe_key_cache);
992 29 $self->_rr_cursor($rr_cursor);
993 29 $self->_known_models_cache($known_models_cache);
994 }
995 130 die $err;
996 }
997  
998 # A reload that drops a node drops what was known about it too, as remove_node does: its
999 # capacity reading and its failure history. Otherwise a node re-added later under the same id
1000 # inherits a reading -- or errors -- about whatever machine the id used to point at. Run only
1001 # after a reload succeeded, so a failed one that restores the old list loses nothing.
1002 561 ▶sub _forget_departed_nodes {
Subroutine _forget_departed_nodes: called CC=4 SCAR=13.9
1003 561 my ($self) = @_;
1004 561 ▶ my %present = map { (($_->{id} // '') => 1) } @{$self->nodes};
Condition50%1/2
$_->{"id"} // ""
l!l
9000
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
1005 561 for my $store ($self->_capacity, $self->_failures, $self->_rejections) {
1006 1683 delete $store->{$_} for grep { !$present{$_} } keys %$store;
1007 }
1008 561 return;
1009 }
1010  
1011 160 ▶sub _record_reload_failure {
Subroutine _record_reload_failure: called CC=2 SCAR=7.0
1012 160 my ($self, $err, $fingerprint) = @_;
1013 160 $self->last_reload_error("$err");
1014 160 $self->last_reload_error_at(time);
1015 160 ▶ $self->reload_failures(($self->reload_failures // 0) + 1);
Condition50%1/2
$self->reload_failures // 0
l!l
1600
MC/DC0%0/1
$self->reload_failures // 0
$self->reload_failures
Truth table50%1/2
A
A= $self->reload_failures
Aresult
11
00
1016 160 $self->_failed_fingerprint($fingerprint);
1017 160 return;
1018 }
1019  
1020 5745 ▶sub _clear_reload_failure {
Subroutine _clear_reload_failure: called CC=1 SCAR=0.0
1021 5745 my ($self) = @_;
1022 5745 $self->last_reload_error(undef);
1023 5745 $self->last_reload_error_at(undef);
1024 5745 $self->reload_failures(0);
1025 5745 $self->_failed_fingerprint(undef);
1026 5745 $self->_config_file_failed_mtime(undef);
1027 5745 $self->_config_file_retry_at(undef);
1028 5745 return;
1029 }
1030  
1031  
1032 92 ▶sub reload_status {
Subroutine reload_status: called CC=4 SCAR=14.1
Pod documented
1033 92 my ($self) = @_;
1034 92 my $err = $self->last_reload_error;
1035 92 ▶ return { ok => 1 } unless defined $err;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err 76 16 92
1036 16 (my $message = $err) =~ s/\s+\z//;
1037 return {
1038 16 ▶ ok => 0,
Condition50%2/4
$self->last_reload_error_at // time
l!l
160
$self->reload_failures // 0
l!l
160
MC/DC0%0/1
$self->last_reload_error_at // time
$self->last_reload_error_at
MC/DC0%0/1
$self->reload_failures // 0
$self->reload_failures
Truth table50%1/2
A
A= $self->last_reload_error_at
Aresult
11
00
Truth table50%1/2
A
A= $self->reload_failures
Aresult
11
00
1039 error => $message,
1040 failed_at => strftime('%Y-%m-%dT%H:%M:%SZ', gmtime($self->last_reload_error_at // time)),
1041 failures => 0 + ($self->reload_failures // 0),
1042 };
1043 }
1044  
1045 # Reads the config source: the loader's answer or the parsed file, plus its fingerprint. A
1046 # loader may return ($config, $version); a defined version is the fingerprint, otherwise it is
1047 # a digest of the structure (see _config_digest).
1048 5905 ▶sub _read_config {
Subroutine _read_config: called CC=11 SCAR=24.3
1049 5905 my ($self) = @_;
1050 5905 my $cfg = {};
1051 5905 my $version;
1052  
1053 5905 ▶ if ($self->has_config_loader) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->has_config_loader) { } 5865 40 5905
elsif ($self->has_config_file) { } 40 0 40
1054 # Counted from the start of the run, so the throttle also holds for a loader that dies.
1055 5865 ▶ $self->_config_next_check_at($self->_now + (0 + ($self->config_reload_interval // 0)));
Condition50%1/2
$self->config_reload_interval // 0
l!l
58650
MC/DC0%0/1
$self->config_reload_interval // 0
$self->config_reload_interval
Truth table50%1/2
A
A= $self->config_reload_interval
Aresult
11
00
1056 5865 my ($loaded, $loader_version) = $self->config_loader->($self);
1057 5862 ▶ $cfg = $loaded if ref($loaded) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $loaded eq "HASH" 5862 0 5862
1058 5862 $version = $loader_version;
1059 } elsif ($self->has_config_file) {
1060 40 my $file = $self->config_file;
1061 # A named config that is not there is an operator error, not an empty config: starting
1062 # with no nodes would answer every request 503 with nothing saying why (skeid k68). A file
1063 # that vanishes after a good load never gets here -- maybe_reload_config keeps the config.
1064 40 ▶ croak 'config file not found: ' . $file unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 1 39 40
1065 # Record the version observed before parsing. The file may be atomically replaced after
1066 # load_file has read its bytes; recording a later stat would mark that unread replacement
1067 # as applied and prevent the next dispatch from loading it.
1068 39 my $read_mtime = (stat($file))[9];
1069 39 my $ypp = YAML::PP->new;
1070 39 my $loaded = $ypp->load_file($file);
1071 37 ▶ $cfg = $loaded if ref($loaded) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $loaded eq "HASH" 37 0 37
1072 37 ▶ $self->_config_mtime($read_mtime) if defined $read_mtime;
Branch: 1 branch
BranchTrueFalseTotal
if defined $read_mtime 37 0 37
1073 }
1074  
1075 5899 ▶ my $fingerprint = defined($version) && !ref($version)
Branch: 1 branch
BranchTrueFalseTotal
defined $version && !ref($version) ? : 5 5894 5899
Condition66%2/3
defined $version and not ref $version
!ll&&!rl&&r
589405
MC/DC50%1/2
defined $version and not ref $version
defined $version not ref $version
Truth table66%2/3
A and not(B)
A= defined $versionB= not ref $version
ABresult
0X0
100
111
1076 ? "version:$version"
1077 : 'digest:' . _config_digest($cfg);
1078  
1079 # Node files are inputs of their own (ADR 0031): a loader's version does not cover them.
1080 5899 ▶ if (exists $cfg->{node_files}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $cfg->{'node_files'}) { } 27 5872 5899
1081 27 my $contributed;
1082 27 ($cfg, $contributed) = $self->_merge_node_files($cfg);
1083 19 $fingerprint .= ';node_files:' . $contributed;
1084 } else {
1085 5872 $self->_node_files({});
1086 }
1087 5891 return ($cfg, $fingerprint);
1088 }
1089  
1090 # What a node file is now: its mtime, size and inode, or 'missing'. A ConfigMap update swaps a
1091 # symlink, so the inode changes even when mtime and size happen not to.
1092 29 ▶sub _node_file_seen {
Subroutine _node_file_seen: called CC=2 SCAR=6.9
1093 29 my ($path) = @_;
1094 29 my @st = stat $path;
1095 29 ▶ return 'missing' unless @st;
Branch: 1 branch
BranchTrueFalseTotal
unless @st 2 27 29
1096 27 return join ':', @st[9, 7, 1];
1097 }
1098  
1099 # The config with the nodes of its node files appended, and a digest of what they contributed.
1100 # A file is read only when it changed; one that cannot be read keeps its last good nodes. Every
1101 # node is checked on every merge, so a changed main config re-judges them all.
1102 27 ▶sub _merge_node_files {
Subroutine _merge_node_files: called CC=19 SCAR=29.6
1103 27 my ($self, $cfg) = @_;
1104 27 my $entries = Langertha::Skeid::NodeFiles->normalize_config($cfg->{node_files});
1105 19 my $state = $self->_node_files;
1106  
1107 19 ▶ my @main = ref($cfg->{nodes}) eq 'ARRAY' ? @{$cfg->{nodes}} : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'nodes'} eq 'ARRAY' ? : 10 9 19
1108 19 ▶ my %taken = map { (ref($_) eq 'HASH' && defined($_->{id})) ? ("$_->{id}" => 1) : () } @main;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' && defined $_->{'id'} ? : 10 0 10
Condition33%1/3
ref $_ eq "HASH" and defined $_->{"id"}
!ll&&!rl&&r
0010
MC/DC0%0/2
ref $_ eq "HASH" and defined $_->{"id"}
ref $_ eq "HASH" defined $_->{"id"}
Truth table33%1/3
A and B
A= ref $_ eq "HASH"B= defined $_->{"id"}
ABresult
0X0
100
111
1109 19 my (@added, %next);
1110  
1111 19 for my $entry (@$entries) {
1112 19 my $path = $entry->{path};
1113 19 ▶ my $file = $state->{$path} || { nodes => [], loaded => 0 };
Condition100%2/2
$state->{$path} || {'nodes', [], 'loaded', 0}
l!l
811
MC/DC100%1/1
$state->{$path} || {'nodes', [], 'loaded', 0}
$state->{$path}
Truth table100%2/2
A
A= $state->{$path}
Aresult
11
00
1114 19 my $seen = _node_file_seen($path);
1115 19 ▶ my $fresh = !defined($file->{seen}) || $file->{seen} ne $seen;
Condition66%2/3
!defined($file->{'seen'}) || $file->{'seen'} ne $seen
l!l&&r!l&&!r
1180
MC/DC0%0/2
!defined($file->{'seen'}) || $file->{'seen'} ne $seen
!defined($file->{'seen'}) $file->{'seen'} ne $seen
Truth table66%2/3
not(A) || B
A= !defined($file->{'seen'})B= $file->{'seen'} ne $seen
ABresult
1X1
011
000
1116 19 ▶ if ($fresh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fresh) 19 0 19
1117 19 $file->{seen} = $seen;
1118 19 my $nodes;
1119 19 ▶ if ($seen eq 'missing') {
Branch: 2 branches
BranchTrueFalseTotal
if ($seen eq 'missing') { } 1 18 19
elsif (eval { do { $nodes = 'Langertha::Skeid::NodeFiles'->read_file($path); 1 } }) { } 14 4 18
1120 1 $file->{error} = "node file $path is missing";
1121 18 } elsif (eval { $nodes = Langertha::Skeid::NodeFiles->read_file($path); 1 }) {
1122 14 $file->{nodes} = $nodes;
1123 14 $file->{loaded} = 1;
1124 14 delete @{$file}{qw( error error_at )};
1125 } else {
1126 4 ▶ ($file->{error} = $@ || "node file $path cannot be read") =~ s/\s+\z//;
Condition50%1/2
$@ || "node file $path cannot be read"
l!l
40
MC/DC0%0/1
$@ || "node file $path cannot be read"
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
1127 }
1128 19 ▶ if (defined $file->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file->{"error"}) 5 14 19
1129 5 $file->{error_at} = time;
1130 warn 'skeid: ' . $file->{error}
1131 5 ▶ . ($file->{loaded} ? ', keeping its last good nodes' : '') . "\n";
Branch: 1 branch
BranchTrueFalseTotal
$file->{'loaded'} ? : 3 2 5
1132 }
1133 }
1134  
1135 19 my @rejected;
1136 19 my $nodes = $file->{nodes};
1137 19 for my $position (0 .. $#$nodes) {
1138 31 my $node = $nodes->[$position];
1139 31 my $rule = Langertha::Skeid::NodeFiles->check($self, $entry, $node);
1140 31 ▶ $rule = 'id_taken' if !defined($rule) && $taken{"$node->{id}"};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $rule and $taken{qq[$node->{"id"}]} 1 30 31
Condition100%3/3
not defined $rule and $taken{qq[$node->{"id"}]}
!ll&&!rl&&r
14161
MC/DC100%2/2
not defined $rule and $taken{qq[$node->{"id"}]}
not defined $rule $taken{qq[$node->{"id"}]}
Truth table100%3/3
not(A) and B
A= not defined $ruleB= $taken{qq[$node->{"id"}]}
ABresult
0X0
100
111
1141 31 ▶ if (defined $rule) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rule) 15 16 31
1142 15 push @rejected, { position => $position, rule => $rule };
1143 15 next;
1144 }
1145 16 $taken{"$node->{id}"} = 1;
1146 # Marked, so the proxy never hands a node from a node file the client's own credentials.
1147 # Its trust is the entry's, never the file's to grant (ADR 0032).
1148 16 push @added, { %$node, node_file => $path, trust => $entry->{trust} };
1149 }
1150 19 ▶ if ($fresh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fresh) 19 0 19
1151 19 warn "skeid: node file $path: node $_->{position} rejected ($_->{rule})\n" for @rejected;
1152 }
1153 19 $file->{rejected} = \@rejected;
1154 19 $file->{accepted} = @$nodes - @rejected;
1155 19 $next{$path} = $file;
1156 }
1157  
1158 19 $self->_node_files(\%next);
1159 19 return ({ %$cfg, nodes => [ @main, @added ] }, _config_digest(\@added));
1160 }
1161  
1162 # Whether a node file changed since it was last read; one stat per file.
1163 24 ▶sub _node_files_changed {
Subroutine _node_files_changed: called CC=4 SCAR=13.9
1164 24 my ($self) = @_;
1165 24 my $state = $self->_node_files;
1166 24 for my $path (keys %$state) {
1167 10 ▶ return 1 if _node_file_seen($path) ne ($state->{$path}{seen} // '');
Branch: 1 branch
BranchTrueFalseTotal
if _node_file_seen($path) ne ($state->{$path}{"seen"} // "") 5 5 10
Condition50%1/2
$state->{$path}{"seen"} // ""
l!l
100
MC/DC0%0/1
$state->{$path}{"seen"} // ""
$state->{$path}{"seen"}
Truth table50%1/2
A
A= $state->{$path}{"seen"}
Aresult
11
00
1168 }
1169 19 return 0;
1170 }
1171  
1172  
1173 29 ▶sub node_files_status {
Subroutine node_files_status: called CC=7 SCAR=19.7
Pod documented
1174 29 my ($self) = @_;
1175 29 my $state = $self->_node_files;
1176 29 ▶ return undef unless %$state;
Branch: 1 branch
BranchTrueFalseTotal
unless %$state 15 14 29
1177 return [ map {
1178 14 my $file = $state->{$_};
1179 14 ▶ my @rejected = @{$file->{rejected} || []};
Condition50%1/2
$file->{'rejected'} || []
l!l
140
MC/DC0%0/1
$file->{'rejected'} || []
$file->{'rejected'}
Truth table50%1/2
A
A= $file->{'rejected'}
Aresult
11
00
1180 +{
1181 path => $_,
1182 ok => defined($file->{error}) ? 0 : 1,
1183 accepted => 0 + ($file->{accepted} // 0),
1184 15 ▶ rejected => [ map { +{ %$_ } } @rejected[0 .. _last(49, @rejected)] ],
Branch: 1 branch
BranchTrueFalseTotal
defined $file->{'error'} ? : 5 9 14
Condition50%1/2
$file->{"error_at"} // time
l!l
50
MC/DC0%0/1
$file->{"error_at"} // time
$file->{"error_at"}
Truth table50%1/2
A
A= $file->{"error_at"}
Aresult
11
00
1185 (defined($file->{error}) ? (
1186 error => $file->{error},
1187 14 ▶ failed_at => strftime('%Y-%m-%dT%H:%M:%SZ', gmtime($file->{error_at} // time)),
Branch: 1 branch
BranchTrueFalseTotal
defined $file->{'error'} ? : 5 9 14
Condition50%1/2
$file->{"accepted"} // 0
l!l
140
MC/DC0%0/1
$file->{"accepted"} // 0
$file->{"accepted"}
Truth table50%1/2
A
A= $file->{"accepted"}
Aresult
11
00
1188 ) : ()),
1189 };
1190 } sort keys %$state ];
1191 }
1192  
1193 # A canonical digest of a loaded config structure: hash keys sorted, so two loads of the same
1194 # data digest alike whatever order the loader built them in. A code ref or an object other
1195 # than a boolean digests by identity -- the same callback digests alike, a fresh closure per
1196 # load counts as a change, which reloads rather than missing one.
1197 8325 ▶sub _config_digest {
Subroutine _config_digest: called CC=1 SCAR=0.0
1198 8325 my ($data) = @_;
1199 8325 my $out = '';
1200 8325 my $walk;
1201 82961 ▶ $walk = sub {
Subroutine __ANON__: called CC=12 SCAR=25.0
1202 82961 my ($node) = @_;
1203 82961 ▶ if (!defined $node) {
Branch: 5 branches
BranchTrueFalseTotal
if (not defined $node) { } 47 82914 82961
elsif (not ref $node) { } 49246 33668 82914
elsif (builtin::blessed($node) and builtin::reftype($node) eq 'SCALAR') { } 16 33652 33668
elsif (not builtin::blessed($node) and builtin::reftype($node) eq 'HASH') { } 24552 9100 33652
elsif (not builtin::blessed($node) and builtin::reftype($node) eq 'ARRAY') { } 9026 74 9100
1204 47 $out .= 'u;';
1205 } elsif (!ref $node) {
1206 49246 $out .= 's' . length($node) . ':' . $node . ';';
1207 ▶ } elsif (blessed($node) && reftype($node) eq 'SCALAR') {
Condition66%2/3
builtin::blessed($node) and builtin::reftype($node) eq "SCALAR"
!ll&&!rl&&r
33652016
MC/DC50%1/2
builtin::blessed($node) and builtin::reftype($node) eq "SCALAR"
builtin::blessed($node) builtin::reftype($node) eq "SCALAR"
Truth table66%2/3
A and B
A= builtin::blessed($node)B= builtin::reftype($node) eq "SCALAR"
ABresult
0X0
100
111
1208 # JSON / YAML booleans: their value is what counts, not which object carries it.
1209 16 ▶ $out .= 'b' . (${$node} ? 1 : 0) . ';';
Branch: 1 branch
BranchTrueFalseTotal
${$node;} ? : 16 0 16
1210 ▶ } elsif (!blessed($node) && reftype($node) eq 'HASH') {
Condition66%2/3
not builtin::blessed($node) and builtin::reftype($node) eq "HASH"
!ll&&!rl&&r
0910024552
MC/DC50%1/2
not builtin::blessed($node) and builtin::reftype($node) eq "HASH"
not builtin::blessed($node) builtin::reftype($node) eq "HASH"
Truth table66%2/3
not(A) and B
A= not builtin::blessed($node)B= builtin::reftype($node) eq "HASH"
ABresult
0X0
100
111
1211 24552 $out .= 'h{';
1212 24552 for my $key (sort keys %$node) {
1213 62485 $out .= 's' . length($key) . ':' . $key . ';';
1214 62485 $walk->($node->{$key});
1215 }
1216 24552 $out .= '}';
1217 ▶ } elsif (!blessed($node) && reftype($node) eq 'ARRAY') {
Condition66%2/3
not builtin::blessed($node) and builtin::reftype($node) eq "ARRAY"
!ll&&!rl&&r
0749026
MC/DC50%1/2
not builtin::blessed($node) and builtin::reftype($node) eq "ARRAY"
not builtin::blessed($node) builtin::reftype($node) eq "ARRAY"
Truth table66%2/3
not(A) and B
A= not builtin::blessed($node)B= builtin::reftype($node) eq "ARRAY"
ABresult
0X0
100
111
1218 9026 $out .= 'a[';
1219 9026 $walk->($_) for @$node;
1220 9026 $out .= ']';
1221 } else {
1222 74 $out .= 'r' . reftype($node) . ':' . refaddr($node) . ';';
1223 }
1224 8325 };
1225 8325 $walk->($data);
1226 8325 undef $walk;
1227 8325 return sha256_hex($out);
1228 }
1229  
1230 # Applies a config to $self, section by section; reload_config undoes it on a croak. The usage
1231 # store goes last and swaps only once the new store is prepared, so nothing after it can fail.
1232 #
1233 # A section the config declares replaces what is loaded: the file is the declared state. A
1234 # section the previously applied config declared and this one does not goes back to what a
1235 # restart with this config would give (skeid k65) -- except the usage store, see below. A
1236 # section no applied config ever declared is left to whoever set it: nodes pushed through the
1237 # admin API, prices set through pricing.set.
1238 #
1239 # Returns the fingerprint of the nodes section the node list now stands for (undef when the
1240 # config declares none), the sections this config declares, and notices to log once it applied.
1241 691 ▶sub _apply_config {
Subroutine _apply_config: called CC=59 SCAR=41.2
1242 691 my ($self, $cfg) = @_;
1243 691 my $before = $self->_config_declared;
1244 691 my (%declared, @notices);
1245  
1246 # First: the customer source's snapshot is merged into the file's config before any section
1247 # reads it (ADR 0026). Rows are checked against the file, the file wins per key id, and no row
1248 # can fail the load -- only the section itself can. A stale or absent snapshot merges nothing:
1249 # source customers are then refused (fail-closed).
1250 691 my %source;
1251 691 ▶ if (exists $cfg->{customer_source}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $cfg->{"customer_source"}) 54 637 691
1252 54 $declared{customer_source} = 1;
1253 $source{cfg} = Langertha::Skeid::CustomerSource->normalize_config($cfg->{customer_source},
1254 54 usage_store => $cfg->{usage_store});
1255 53 ▶ $self->_require_customer_source_driver unless $self->has_customer_source_fetcher;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_customer_source_fetcher 2 51 53
1256 51 my $snapshot = $self->_source_snapshot;
1257 51 ▶ if ($snapshot && !$snapshot->{stale}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($snapshot and not $snapshot->{"stale"}) 29 22 51
Condition100%3/3
$snapshot and not $snapshot->{"stale"}
!ll&&!rl&&r
21129
MC/DC100%2/2
$snapshot and not $snapshot->{"stale"}
$snapshot not $snapshot->{"stale"}
Truth table100%3/3
A and not(B)
A= $snapshotB= not $snapshot->{"stale"}
ABresult
0X0
100
111
1258 29 $source{merge} = Langertha::Skeid::CustomerSource->merge_into($cfg, $snapshot->{rows});
1259 29 $cfg = $source{merge}{config};
1260 }
1261 }
1262  
1263 688 ▶ if (exists $cfg->{pricing}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'pricing'}) { } 131 557 688
elsif ($before->{'pricing'}) { } 2 555 557
1264 131 $declared{pricing} = 1;
1265 # Replaced wholesale, not merged: a model removed from the section loses its price.
1266 131 $self->model_pricing({});
1267 131 ▶ my $pricing = ref($cfg->{pricing}) eq 'HASH' ? $cfg->{pricing} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'pricing'} eq 'HASH' ? : 131 0 131
1268 131 for my $model (keys %$pricing) {
1269 130 my $p = $pricing->{$model};
1270 130 ▶ next unless ref($p) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $p eq "HASH" 0 130 130
1271 130 $self->set_model_pricing($model, $p);
1272 }
1273 } elsif ($before->{pricing}) {
1274 2 $self->model_pricing({});
1275 }
1276  
1277 687 ▶ if (grep { exists $cfg->{$_} } qw( policies default_policy names keys )) {
Branch: 2 branches
BranchTrueFalseTotal
if (grep {exists $cfg->{$_};} 'policies', 'default_policy', 'names', 'keys') { } 156 531 687
elsif ($before->{'policies'}) { } 2 529 531
1278 156 $declared{policies} = 1;
1279 156 $self->_load_policies($cfg);
1280 } elsif ($before->{policies}) {
1281 2 $self->_load_policies({});
1282 }
1283  
1284 # After the policies: client_auth entries may be names: names, resolved through key_names.
1285 # Removed from the file, client authentication is off again -- as a restart without the
1286 # section would have it (skeid k90).
1287 670 ▶ if (exists $cfg->{client_auth}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'client_auth'}) { } 80 590 670
elsif ($before->{'client_auth'}) { } 2 588 590
1288 80 $declared{client_auth} = 1;
1289 80 my @said = $self->_load_client_auth($cfg->{client_auth});
1290 # With a customer source, an empty list in the file is the expected setup: the ids come
1291 # from the source. Every accepted row joins the file's own ids -- a union, so the database
1292 # cannot revoke an id the file lists.
1293 67 ▶ push @notices, @said unless $source{cfg};
Branch: 1 branch
BranchTrueFalseTotal
unless $source{"cfg"} 21 46 67
1294 67 ▶ if ($source{merge}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($source{"merge"}) 26 41 67
1295 26 my %allowed = %{$self->client_auth_keys};
1296 26 $allowed{$_} = 1 for @{$source{merge}{allow}};
1297 26 $self->client_auth_keys(\%allowed);
1298 }
1299 } elsif ($before->{client_auth}) {
1300 2 $self->client_auth_keys(undef);
1301 }
1302 657 ▶ $source{no_gate} = 1 if $source{cfg} && !exists $cfg->{client_auth};
Branch: 1 branch
BranchTrueFalseTotal
if $source{"cfg"} and not exists $cfg->{"client_auth"} 4 653 657
Condition100%3/3
$source{"cfg"} and not exists $cfg->{"client_auth"}
!ll&&!rl&&r
607464
MC/DC100%2/2
$source{"cfg"} and not exists $cfg->{"client_auth"}
$source{"cfg"} not exists $cfg->{"client_auth"}
Truth table100%3/3
A and not(B)
A= $source{"cfg"}B= not exists $cfg->{"client_auth"}
ABresult
0X0
100
111
1303  
1304 # The MCP gateway (skeid k103). After the policies as well: a server's keys: may be names:
1305 # names. Removed from the file, the gateway is off again and its routes are unknown paths.
1306 657 ▶ if (exists $cfg->{mcp}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'mcp'}) { } 55 602 657
elsif ($before->{'mcp'}) { } 1 601 602
1307 55 $declared{mcp} = 1;
1308 55 push @notices, $self->_load_mcp($cfg->{mcp});
1309 } elsif ($before->{mcp}) {
1310 1 $self->mcp_servers(undef);
1311 1 $self->mcp_public_url(undef);
1312 1 $self->mcp_max_request_bytes($MCP_MAX_REQUEST_BYTES);
1313 }
1314  
1315 # The OpenAPI document and its optional Swagger UI (skeid k105). Removed from the file, the
1316 # UI is off again and its cache directory forgotten.
1317 629 ▶ if (exists $cfg->{openapi}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'openapi'}) { } 17 612 629
elsif ($before->{'openapi'}) { } 1 611 612
1318 17 $declared{openapi} = 1;
1319 17 $self->_load_openapi($cfg->{openapi});
1320 } elsif ($before->{openapi}) {
1321 1 $self->openapi_swagger_ui(0);
1322 1 $self->openapi_cache_dir(undef);
1323 }
1324  
1325 # The upload limit of the multipart routes (skeid k91). Removed from the file, it is the
1326 # built-in default again.
1327 625 ▶ if (exists $cfg->{uploads}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'uploads'}) { } 18 607 625
elsif ($before->{'uploads'}) { } 2 605 607
1328 18 $declared{uploads} = 1;
1329 18 $self->_load_uploads($cfg->{uploads});
1330 } elsif ($before->{uploads}) {
1331 2 $self->upload_max_bytes($UPLOAD_MAX_BYTES);
1332 2 $self->documents_max_bytes($DOCUMENTS_MAX_BYTES);
1333 }
1334  
1335 # Whether the documents routes pass requests that make the node fetch from an address the
1336 # client names (skeid k94, ADR 0028). Removed from the file, it is refused again.
1337 614 ▶ if (exists $cfg->{documents}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'documents'}) { } 6 608 614
elsif ($before->{'documents'}) { } 0 608 608
1338 6 $declared{documents} = 1;
1339 6 $self->_load_documents($cfg->{documents});
1340 } elsif ($before->{documents}) {
1341 0 $self->documents_allow_remote_sources(0);
1342 }
1343  
1344 # The limits of a realtime session (skeid k95). Removed from the file, the defaults again.
1345 609 ▶ if (exists $cfg->{realtime}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'realtime'}) { } 24 585 609
elsif ($before->{'realtime'}) { } 1 584 585
1346 24 $declared{realtime} = 1;
1347 24 $self->_load_realtime($cfg->{realtime});
1348 } elsif ($before->{realtime}) {
1349 1 $self->_load_realtime({});
1350 }
1351  
1352 598 ▶ if (exists $cfg->{aliases}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'aliases'}) { } 75 523 598
elsif ($before->{'aliases'}) { } 4 519 523
1353 75 $declared{aliases} = 1;
1354 # Replaced wholesale, like nodes: the file is the declared state.
1355 75 $self->model_aliases({});
1356 75 ▶ my $aliases = ref($cfg->{aliases}) eq 'HASH' ? $cfg->{aliases} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'aliases'} eq 'HASH' ? : 75 0 75
1357 75 for my $name (keys %$aliases) {
1358 69 $self->set_model_alias($name, $aliases->{$name});
1359 }
1360 } elsif ($before->{aliases}) {
1361 4 $self->model_aliases({});
1362 }
1363  
1364 598 my $nodes_print = $self->_nodes_fingerprint;
1365 598 ▶ if (exists $cfg->{nodes}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'nodes'}) { } 324 274 598
elsif ($before->{'nodes'}) { } 1 273 274
1366 324 $declared{nodes} = 1;
1367 324 ▶ my $nodes = ref($cfg->{nodes}) eq 'ARRAY' ? $cfg->{nodes} : [];
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'nodes'} eq 'ARRAY' ? : 324 0 324
1368 # An unchanged nodes section keeps the node list as it is (skeid #38).
1369 324 my $print = _config_digest($nodes);
1370 324 ▶ if (!defined($nodes_print) || $print ne $nodes_print) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $nodes_print or $print ne $nodes_print) 280 44 324
Condition100%3/3
not defined $nodes_print or $print ne $nodes_print
l!l&&r!l&&!r
2552544
MC/DC100%2/2
not defined $nodes_print or $print ne $nodes_print
not defined $nodes_print $print ne $nodes_print
Truth table100%3/3
not(A) or B
A= not defined $nodes_printB= $print ne $nodes_print
ABresult
1X1
011
000
1371 # A changed main nodes section is the declared state again, health included. A change that
1372 # came only from node files (ADR 0031) must not reset the main config's nodes: there a node
1373 # whose entry did not change keeps the health an admin set on it.
1374 280 ▶ my $main_print = _config_digest([ grep { !(ref($_) eq 'HASH' && defined $_->{node_file}) } @$nodes ]);
Condition66%2/3
ref $_ eq 'HASH' && defined $_->{'node_file'}
!ll&&!rl&&r
084613
MC/DC50%1/2
ref $_ eq 'HASH' && defined $_->{'node_file'}
ref $_ eq 'HASH' defined $_->{'node_file'}
Truth table66%2/3
A && B
A= ref $_ eq 'HASH'B= defined $_->{'node_file'}
ABresult
0X0
100
111
1375 280 ▶ my $files_only = defined($self->_main_nodes_print) && $self->_main_nodes_print eq $main_print;
Condition100%3/3
defined $self->_main_nodes_print && $self->_main_nodes_print eq $main_print
!ll&&!rl&&r
255214
MC/DC100%2/2
defined $self->_main_nodes_print && $self->_main_nodes_print eq $main_print
defined $self->_main_nodes_print $self->_main_nodes_print eq $main_print
Truth table100%3/3
A && B
A= defined $self->_main_nodes_printB= $self->_main_nodes_print eq $main_print
ABresult
0X0
100
111
1376 280 $self->_main_nodes_print($main_print);
1377 280 ▶ my $entry_prints = $files_only ? $self->_node_entry_prints : {};
Branch: 1 branch
BranchTrueFalseTotal
$files_only ? : 4 276 280
1378 280 ▶ my %health = map { (($_->{id} // '') => $_->{healthy}) } @{$self->nodes};
Condition50%1/2
$_->{"id"} // ""
l!l
340
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
1379 280 my %prints;
1380 280 $self->nodes([]);
1381 280 for my $n (@$nodes) {
1382 859 ▶ next unless ref($n) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $n eq "HASH" 0 859 859
1383 859 ▶ next unless defined $n->{id} && defined $n->{url};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n->{"id"} and defined $n->{"url"} 0 859 859
Condition33%1/3
defined $n->{"id"} and defined $n->{"url"}
!ll&&!rl&&r
00859
MC/DC0%0/2
defined $n->{"id"} and defined $n->{"url"}
defined $n->{"id"} defined $n->{"url"}
Truth table33%1/3
A and B
A= defined $n->{"id"}B= defined $n->{"url"}
ABresult
0X0
100
111
1384 859 my $entry = _config_digest($n);
1385 859 $prints{$n->{id}} = $entry;
1386 859 $self->add_node(%$n);
1387 847 ▶ if (defined($entry_prints->{$n->{id}}) && $entry_prints->{$n->{id}} eq $entry
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$entry_prints{$n->{"id"}} and $$entry_prints{$n->{"id"}} eq $entry and exists $health{$n->{"id"}}) 4 843 847
Condition66%4/6
defined $$entry_prints{$n->{"id"}} and $$entry_prints{$n->{"id"}} eq $entry and exists $health{$n->{"id"}}
!ll&&!rl&&r
84304
defined $$entry_prints{$n->{"id"}} and $$entry_prints{$n->{"id"}} eq $entry
!ll&&!rl&&r
84304
MC/DC33%1/3
defined $$entry_prints{$n->{"id"}} and $$entry_prints{$n->{"id"}} eq $entry and exists $health{$n->{"id"}}
defined $$entry_prints{$n->{"id"}} $$entry_prints{$n->{"id"}} eq $entry exists $health{$n->{"id"}}
Truth table50%2/4
A and B and C
A= defined $$entry_prints{$n->{"id"}}B= $$entry_prints{$n->{"id"}} eq $entryC= exists $health{$n->{"id"}}
ABCresult
0XX0
10X0
1100
1111
1388 && exists $health{$n->{id}}) {
1389 4 my ($added) = grep { $_->{id} eq $n->{id} } @{$self->nodes};
1390 4 ▶ $added->{healthy} = $health{$n->{id}} if $added;
Branch: 1 branch
BranchTrueFalseTotal
if $added 4 0 4
1391 }
1392 }
1393 268 $self->_node_entry_prints(\%prints);
1394 268 $nodes_print = $print;
1395 }
1396 } elsif ($before->{nodes}) {
1397 1 $self->nodes([]);
1398 1 $nodes_print = undef;
1399 }
1400  
1401 586 ▶ my $routing = ref($cfg->{routing}) eq 'HASH' ? $cfg->{routing} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'routing'} eq 'HASH' ? : 69 517 586
1402 586 for my $key (sort keys %ROUTING_SETTINGS) {
1403 3482 my ($attr, $convert) = @{ $ROUTING_SETTINGS{$key} };
1404 3482 ▶ if (defined $routing->{$key}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $routing->{$key}) { } 87 3395 3482
elsif ($$before{'routing.' . $key}) { } 7 3388 3395
1405 87 $declared{'routing.' . $key} = 1;
1406 87 $self->$attr($convert->($routing->{$key}));
1407 } elsif ($before->{'routing.' . $key}) {
1408 7 $self->$attr($self->_routing_baseline->{$attr});
1409 }
1410 }
1411  
1412 579 $self->_config_admin_api_key($self->_admin_api_key_from_config($cfg));
1413 579 $self->_apply_admin_api_key;
1414  
1415 579 $self->_load_registry($cfg);
1416  
1417 # Last: a key's manifest is checked against its routing policy and the aliases.
1418 570 $self->_load_manifest($cfg);
1419  
1420 # A changed usage store is swapped here, the new one prepared before the old one goes. A
1421 # removed one is not: the removal names no destination, so honouring it would stop recording
1422 # usage events -- billing data (ADR 0004) -- on a reload, silently. The running store stays
1423 # until a restart, and the reload says so once (skeid k65).
1424 561 my $usage_cfg = $cfg->{usage_store};
1425 561 ▶ if (ref($usage_cfg) eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $usage_cfg eq 'HASH') { } 11 550 561
elsif (exists $cfg->{'usage_db_path'}) { } 0 550 550
elsif ($before->{'usage_store'}) { } 1 549 550
1426 11 $declared{usage_store} = 1;
1427 11 $self->_configure_usage_store($usage_cfg);
1428 } elsif (exists $cfg->{usage_db_path}) {
1429 0 $declared{usage_store} = 1;
1430 $self->_configure_usage_store({
1431 backend => 'sqlite',
1432 sqlite_path => $cfg->{usage_db_path},
1433 0 });
1434 } elsif ($before->{usage_store}) {
1435 1 ▶ my $backend = (ref($self->usage_store) eq 'HASH' && $self->usage_store->{backend}) || 'no';
Condition40%2/5
ref $self->usage_store eq 'HASH' && $self->usage_store->{'backend'} || 'no'
l!l
10
ref $self->usage_store eq "HASH" and $self->usage_store->{"backend"}
!ll&&!rl&&r
001
MC/DC0%0/2
ref $self->usage_store eq 'HASH' && $self->usage_store->{'backend'} || 'no'
ref $self->usage_store eq "HASH" $self->usage_store->{"backend"}
Truth table33%1/3
A and B
A= ref $self->usage_store eq "HASH"B= $self->usage_store->{"backend"}
ABresult
111
0X0
100
1436 1 push @notices, 'usage_store was removed from the config; the running ' . $backend
1437 . ' store stays in force until restart (usage events are billing data, ADR 0004)';
1438 }
1439  
1440 561 return ($nodes_print, \%declared, \@notices, \%source);
1441 }
1442  
1443 # The admin API key a config names (skeid k64). It may be named directly or handed over by
1444 # environment variable, the same way usage_store takes password_env -- a deployment should not
1445 # have to write the key into a file that gets mounted into a container. The first spelling
1446 # present decides, even when it is empty: a config may switch the admin API off. A config that
1447 # names none leaves the key to SKEID_ADMIN_API_KEY.
1448 579 ▶sub _admin_api_key_from_config {
Subroutine _admin_api_key_from_config: called CC=10 SCAR=25.1
1449 579 my ($self, $cfg) = @_;
1450 579 ▶ my $admin = ref($cfg->{admin}) eq 'HASH' ? $cfg->{admin} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'admin'} eq 'HASH' ? : 31 548 579
1451 return exists($cfg->{admin_api_key}) ? ($cfg->{admin_api_key} // '') . ''
1452 : defined($cfg->{admin_api_key_env}) ? $ENV{$cfg->{admin_api_key_env}} // ''
1453 : exists($admin->{api_key}) ? ($admin->{api_key} // '') . ''
1454 579 ▶ : defined($admin->{api_key_env}) ? $ENV{$admin->{api_key_env}} // ''
Branch: 4 branches
BranchTrueFalseTotal
exists $cfg->{'admin_api_key'} ? : 14 565 579
defined $cfg->{'admin_api_key_env'} ? : 0 565 565
exists $admin->{'api_key'} ? : 30 535 565
defined $admin->{'api_key_env'} ? : 1 534 535
Condition37%3/8
$cfg->{"admin_api_key"} // ""
l!l
140
$ENV{$cfg->{"admin_api_key_env"}} // ""
l!l
00
$admin->{"api_key"} // ""
l!l
300
$ENV{$admin->{"api_key_env"}} // ""
l!l
10
MC/DC0%0/1
$cfg->{"admin_api_key"} // ""
$cfg->{"admin_api_key"}
MC/DC0%0/1
$ENV{$cfg->{"admin_api_key_env"}} // ""
$ENV{$cfg->{"admin_api_key_env"}}
MC/DC0%0/1
$admin->{"api_key"} // ""
$admin->{"api_key"}
MC/DC0%0/1
$ENV{$admin->{"api_key_env"}} // ""
$ENV{$admin->{"api_key_env"}}
Truth table50%1/2
A
A= $cfg->{"admin_api_key"}
Aresult
11
00
Truth table0%0/2
A
A= $ENV{$cfg->{"admin_api_key_env"}}
Aresult
11
00
Truth table50%1/2
A
A= $admin->{"api_key"}
Aresult
11
00
Truth table50%1/2
A
A= $ENV{$admin->{"api_key_env"}}
Aresult
11
00
1455 : $self->_env_admin_api_key;
1456 }
1457  
1458 # The admin API key in force: the explicit one, else the config's.
1459 587 ▶sub _apply_admin_api_key {
Subroutine _apply_admin_api_key: called CC=2 SCAR=6.9
1460 587 my ($self) = @_;
1461 587 my $explicit = $self->_explicit_admin_api_key;
1462 587 ▶ $self->admin_api_key(length($explicit) ? $explicit : $self->_config_admin_api_key);
Branch: 1 branch
BranchTrueFalseTotal
length $explicit ? : 24 563 587
1463 587 return $self->admin_api_key;
1464 }
1465  
1466  
1467 8 ▶sub set_admin_api_key {
Subroutine set_admin_api_key: called CC=2 SCAR=7.1
Pod documented
1468 8 my ($self, $key) = @_;
1469 8 ▶ $self->_explicit_admin_api_key(defined($key) ? "$key" : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $key ? : 8 0 8
1470 8 return $self->_apply_admin_api_key;
1471 }
1472  
1473  
1474 # Longest wait between two retries of a failing config_loader, in seconds.
1475 127 my $RELOAD_BACKOFF_MAX = 60;
1476  
1477 10426 ▶sub maybe_reload_config {
Subroutine maybe_reload_config: called CC=16 SCAR=27.8
Pod documented
1478 10426 my ($self) = @_;
1479  
1480 10426 ▶ if ($self->has_config_loader && !$self->has_config_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_config_loader and not $self->has_config_file) 7174 3252 10426
Condition66%2/3
$self->has_config_loader and not $self->has_config_file
!ll&&!rl&&r
325207174
MC/DC50%1/2
$self->has_config_loader and not $self->has_config_file
$self->has_config_loader not $self->has_config_file
Truth table66%2/3
A and not(B)
A= $self->has_config_loaderB= not $self->has_config_file
ABresult
0X0
100
111
1481 # Loader-based configs are dynamic, but not re-read more often than
1482 # config_reload_interval, and a load that reads what was already applied is a no-op.
1483 7174 my $now = $self->_now;
1484 7174 my $next = $self->_config_next_check_at;
1485 7174 ▶ return 0 if defined($next) && $now < $next;
Branch: 1 branch
BranchTrueFalseTotal
if defined $next and $now < $next 1899 5275 7174
Condition66%2/3
defined $next and $now < $next
!ll&&!rl&&r
052751899
MC/DC50%1/2
defined $next and $now < $next
defined $next $now < $next
Truth table66%2/3
A and B
A= defined $nextB= $now < $next
ABresult
0X0
100
111
1486 5275 return $self->_reload_on_request;
1487 }
1488  
1489 3252 ▶ return 0 unless $self->has_config_file;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_config_file 3168 84 3252
1490 84 my $file = $self->config_file;
1491 84 ▶ unless (-f $file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $file) 6 78 84
1492 # Gone after a good load (a botched deploy, a volume that went away): the config in force
1493 # stays, as it would for a file that fails to parse -- but said once, not silently.
1494 6 ▶ warn 'skeid: config file ' . $file . " is gone, keeping the previous config\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_config_file_missing 2 4 6
1495 unless $self->_config_file_missing;
1496 6 $self->_config_file_missing(1);
1497 6 return 0;
1498 }
1499 78 $self->_config_file_missing(0);
1500  
1501 78 ▶ my $mtime = (stat($file))[9] || 0;
Condition50%1/2
(stat $file)[9] || 0
l!l
780
MC/DC0%0/1
(stat $file)[9] || 0
(stat $file)[9]
Truth table50%1/2
A
A= (stat $file)[9]
Aresult
11
00
1502 78 my $last = $self->_config_mtime;
1503 78 ▶ if (!defined($last) || $mtime > $last) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $last or $mtime > $last) 54 24 78
Condition66%2/3
not defined $last or $mtime > $last
l!l&&r!l&&!r
05424
MC/DC50%1/2
not defined $last or $mtime > $last
not defined $last $mtime > $last
Truth table66%2/3
not(A) or B
A= not defined $lastB= $mtime > $last
ABresult
1X1
011
000
1504 54 my $failed = $self->_config_file_failed_mtime;
1505 54 my $retry = $self->_config_file_retry_at;
1506 54 ▶ return 0 if defined($failed) && $mtime == $failed
Branch: 1 branch
BranchTrueFalseTotal
if defined $failed and $mtime == $failed and defined $retry and $self->_now < $retry 39 15 54
Condition88%8/9
defined $failed and $mtime == $failed and defined $retry and $self->_now < $retry
!ll&&!rl&&r
14139
defined $failed and $mtime == $failed and defined $retry
!ll&&!rl&&r
14040
defined $failed and $mtime == $failed
!ll&&!rl&&r
13140
MC/DC75%3/4
defined $failed and $mtime == $failed and defined $retry and $self->_now < $retry
defined $failed $mtime == $failed defined $retry $self->_now < $retry
Truth table80%4/5
A and B and C and D
A= defined $failedB= $mtime == $failedC= defined $retryD= $self->_now < $retry
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1507 && defined($retry) && $self->_now < $retry;
1508 15 return $self->_reload_on_request($mtime);
1509 }
1510 24 ▶ return $self->_reload_on_request if $self->_node_files_changed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_node_files_changed 5 19 24
1511 19 return 0;
1512 }
1513  
1514 # One retry schedule for loader and file failures. A file's next version bypasses this delay in
1515 # maybe_reload_config; the delay applies only while the observed mtime is unchanged.
1516 29 ▶sub _reload_retry_delay {
Subroutine _reload_retry_delay: called CC=5 SCAR=16.2
1517 29 my ($self) = @_;
1518 29 ▶ my $failures = $self->reload_failures // 0;
Condition50%1/2
$self->reload_failures // 0
l!l
290
MC/DC0%0/1
$self->reload_failures // 0
$self->reload_failures
Truth table50%1/2
A
A= $self->reload_failures
Aresult
11
00
1519 29 ▶ my $base = 0 + ($self->config_reload_interval // 0);
Condition50%1/2
$self->config_reload_interval // 0
l!l
290
MC/DC0%0/1
$self->config_reload_interval // 0
$self->config_reload_interval
Truth table50%1/2
A
A= $self->config_reload_interval
Aresult
11
00
1520 29 ▶ $base = 1 if $base < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $base < 1 12 17 29
1521 29 my $delay = $base * 2 ** ($failures - 1);
1522 29 ▶ $delay = $RELOAD_BACKOFF_MAX if $delay > $RELOAD_BACKOFF_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if $delay > $RELOAD_BACKOFF_MAX 9 20 29
1523 29 return $delay;
1524 }
1525  
1526 # A reload triggered by a request (skeid #39). Its failure is not the request's: the previous
1527 # config is still fully in force, so the request is served under it. Failing it with a 500
1528 # would take every request down until the config is fixed -- with a loader, every one.
1529 5295 ▶sub _reload_on_request {
Subroutine _reload_on_request: called CC=13 SCAR=26.4
1530 5295 my ($self, $file_mtime) = @_;
1531 5295 ▶ my $before = $self->_config_fingerprint // '';
Condition50%1/2
$self->_config_fingerprint // ""
l!l
52950
MC/DC0%0/1
$self->_config_fingerprint // ""
$self->_config_fingerprint
Truth table50%1/2
A
A= $self->_config_fingerprint
Aresult
11
00
1532 5295 my $error_before = $self->last_reload_error;
1533 5295 ▶ if (eval { $self->reload_config; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { $self->reload_config; 1 } }) 5266 29 5295
1534 5266 ▶ return (($self->_config_fingerprint // '') ne $before) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
($self->_config_fingerprint // '') ne $before ? : 82 5184 5266
Condition50%1/2
$self->_config_fingerprint // ""
l!l
52660
MC/DC0%0/1
$self->_config_fingerprint // ""
$self->_config_fingerprint
Truth table50%1/2
A
A= $self->_config_fingerprint
Aresult
11
00
1535 }
1536  
1537 29 ▶ my $err = $@ || 'config reload failed';
Condition50%1/2
$@ || 'config reload failed'
l!l
290
MC/DC0%0/1
$@ || 'config reload failed'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
1538 29 ▶ my $failures = $self->reload_failures // 0;
Condition50%1/2
$self->reload_failures // 0
l!l
290
MC/DC0%0/1
$self->reload_failures // 0
$self->reload_failures
Truth table50%1/2
A
A= $self->reload_failures
Aresult
11
00
1539 29 ▶ if ($self->has_config_loader && $failures > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->has_config_loader and $failures > 0) { } 27 2 29
elsif (defined $file_mtime and $failures > 0) { } 2 0 2
Condition66%2/3
$self->has_config_loader and $failures > 0
!ll&&!rl&&r
2027
MC/DC50%1/2
$self->has_config_loader and $failures > 0
$self->has_config_loader $failures > 0
Truth table66%2/3
A and B
A= $self->has_config_loaderB= $failures > 0
ABresult
0X0
100
111
1540 27 $self->_config_next_check_at($self->_now + $self->_reload_retry_delay);
1541 ▶ } elsif (defined($file_mtime) && $failures > 0) {
Condition33%1/3
defined $file_mtime and $failures > 0
!ll&&!rl&&r
002
MC/DC0%0/2
defined $file_mtime and $failures > 0
defined $file_mtime $failures > 0
Truth table33%1/3
A and B
A= defined $file_mtimeB= $failures > 0
ABresult
0X0
100
111
1542 2 $self->_config_file_failed_mtime($file_mtime);
1543 2 $self->_config_file_retry_at($self->_now + $self->_reload_retry_delay);
1544 }
1545 # Logged when the reason is new; the same failure again, retry after retry, is not.
1546 29 ▶ if (!defined($error_before) || $error_before ne $err) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $error_before or $error_before ne $err) 13 16 29
Condition100%3/3
not defined $error_before or $error_before ne $err
l!l&&r!l&&!r
12116
MC/DC100%2/2
not defined $error_before or $error_before ne $err
not defined $error_before $error_before ne $err
Truth table100%3/3
not(A) or B
A= not defined $error_beforeB= $error_before ne $err
ABresult
1X1
011
000
1547 13 (my $msg = $err) =~ s/\s+\z//;
1548 13 warn "skeid: config reload failed, keeping the previous config: $msg\n";
1549 }
1550 29 return 0;
1551 }
1552  
1553 12658 ▶sub _now { Time::HiRes::time() }
Subroutine _now: called CC=1 SCAR=0.0
1554  
1555 # --- customer source (ADR 0026) -------------------------------------------------------------
1556  
1557 # What the snapshot contributes to the config fingerprint.
1558 939 ▶sub _source_digest {
Subroutine _source_digest: called CC=3 SCAR=11.0
1559 939 my ($self) = @_;
1560 939 my $snapshot = $self->_source_snapshot;
1561 939 ▶ return 'none' unless $snapshot;
Branch: 1 branch
BranchTrueFalseTotal
unless $snapshot 49 890 939
1562 890 ▶ return $snapshot->{stale} ? 'stale' : $snapshot->{digest};
Branch: 1 branch
BranchTrueFalseTotal
$snapshot->{'stale'} ? : 1 889 890
1563 }
1564  
1565 2 ▶sub _require_customer_source_driver {
Subroutine _require_customer_source_driver: called CC=2 SCAR=7.2
1566 2 my ($self) = @_;
1567 0 ▶ return 1 if eval { require DBI; require DBD::Pg; 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { require DBI; require DBD::Pg; 1 } } 0 2 2
1568 2 croak 'customer_source needs DBD::Pg (and DBI), which is not installed: install DBD::Pg, '
1569 . 'or remove the customer_source section';
1570 }
1571  
1572 # Runs once a config applied: the source as the config now declares it. A removed section stops
1573 # the fetcher and drops the snapshot; a changed one restarts the fetcher, the snapshot staying in
1574 # force until the new source answered. Returns the notices to log.
1575 561 ▶sub _commit_customer_source {
Subroutine _commit_customer_source: called CC=14 SCAR=26.4
1576 561 my ($self, $source) = @_;
1577 561 ▶ $source ||= {};
Condition50%1/2
$source ||= {}
l!l
5610
MC/DC0%0/1
$source ||= {}
$source
Truth table50%1/2
A
A= $source
Aresult
11
00
1578 561 my $cfg = $source->{cfg};
1579 561 ▶ unless ($cfg) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cfg) 511 50 561
1580 511 $self->_stop_source_controller;
1581 511 $self->_source_snapshot(undef);
1582 511 $self->_source_report(undef);
1583 511 $self->_source_cfg(undef);
1584 511 $self->_source_cfg_print(undef);
1585 511 return;
1586 }
1587  
1588 50 my @notices;
1589 50 my $merge = $source->{merge};
1590 $self->_source_report($merge ? {
1591 accepted => $merge->{accepted},
1592 rejected => $merge->{rejected},
1593 shadowed => $merge->{shadowed},
1594 names => $merge->{names} || {},
1595 50 ▶ } : undef);
Branch: 1 branch
BranchTrueFalseTotal
$merge ? : 28 22 50
Condition50%1/2
$merge->{'names'} || {}
l!l
280
MC/DC0%0/1
$merge->{'names'} || {}
$merge->{'names'}
Truth table50%1/2
A
A= $merge->{'names'}
Aresult
11
00
1596 50 ▶ if ($merge) {
Branch: 1 branch
BranchTrueFalseTotal
if ($merge) 28 22 50
1597 # By label and reason only: a rejected value may be a key pasted where its id belongs.
1598 28 my @rejected = @{$merge->{rejected}};
1599 28 push @notices, map { "customer_source: $_->{row} rejected: $_->{reason}" } @rejected[0 .. _last(19, @rejected)];
1600 28 ▶ push @notices, 'customer_source: ' . (@rejected - 20) . ' more rows rejected' if @rejected > 20;
Branch: 1 branch
BranchTrueFalseTotal
if @rejected > 20 0 28 28
1601 28 my @shadowed = @{$merge->{shadowed}};
1602 28 push @notices, map { "customer_source: $_ shadowed: the file's keys: entry for that key id wins" }
1603 @shadowed[0 .. _last(19, @shadowed)];
1604 28 ▶ push @notices, 'customer_source: ' . (@shadowed - 20) . ' more rows shadowed' if @shadowed > 20;
Branch: 1 branch
BranchTrueFalseTotal
if @shadowed > 20 0 28 28
1605 }
1606 50 ▶ if ($source->{no_gate} && !$self->_source_gate_warned) {
Branch: 1 branch
BranchTrueFalseTotal
if ($source->{"no_gate"} and not $self->_source_gate_warned) 2 48 50
Condition100%3/3
$source->{"no_gate"} and not $self->_source_gate_warned
!ll&&!rl&&r
4622
MC/DC100%2/2
$source->{"no_gate"} and not $self->_source_gate_warned
$source->{"no_gate"} not $self->_source_gate_warned
Truth table100%3/3
A and not(B)
A= $source->{"no_gate"}B= not $self->_source_gate_warned
ABresult
0X0
100
111
1607 2 $self->_source_gate_warned(1);
1608 2 push @notices, 'customer_source is configured but client_auth is not: source keys are not '
1609 . 'gated, and a revoked key is not refused -- it routes under default_policy. Declare '
1610 . 'client_auth (client_auth: { keys: [] } is enough)';
1611 }
1612 50 ▶ $self->_source_gate_warned(0) unless $source->{no_gate};
Branch: 1 branch
BranchTrueFalseTotal
unless $source->{"no_gate"} 46 4 50
1613  
1614 50 my $print = _config_digest($cfg);
1615 50 ▶ my $changed = !defined($self->_source_cfg_print) || $print ne $self->_source_cfg_print;
Condition100%3/3
!defined($self->_source_cfg_print) || $print ne $self->_source_cfg_print
l!l&&r!l&&!r
21227
MC/DC100%2/2
!defined($self->_source_cfg_print) || $print ne $self->_source_cfg_print
!defined($self->_source_cfg_print) $print ne $self->_source_cfg_print
Truth table100%3/3
not(A) || B
A= !defined($self->_source_cfg_print)B= $print ne $self->_source_cfg_print
ABresult
1X1
011
000
1616 50 $self->_source_cfg($cfg);
1617 50 $self->_source_cfg_print($print);
1618 50 ▶ $self->_start_source_controller if $changed && $self->_source_started;
Branch: 1 branch
BranchTrueFalseTotal
if $changed and $self->_source_started 3 47 50
Condition100%3/3
$changed and $self->_source_started
!ll&&!rl&&r
27203
MC/DC100%2/2
$changed and $self->_source_started
$changed $self->_source_started
Truth table100%3/3
A and B
A= $changedB= $self->_source_started
ABresult
0X0
100
111
1619 50 return @notices;
1620 }
1621  
1622 546 ▶sub _last { my ($max, @list) = @_; return $#list < $max ? $#list : $max }
Subroutine _last: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$#list < $max ? : 546 0 546
1623  
1624 566 ▶sub _start_source_controller {
Subroutine _start_source_controller: called CC=3 SCAR=11.3
1625 566 my ($self) = @_;
1626 566 $self->_stop_source_controller;
1627 566 ▶ my $cfg = $self->_source_cfg or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cfg = $self->_source_cfg or return 22 544 566
1628 my $fetcher = $self->has_customer_source_fetcher
1629 ? $self->customer_source_fetcher->($self, $cfg)
1630 22 ▶ : do {
Branch: 1 branch
BranchTrueFalseTotal
$self->has_customer_source_fetcher ? : 22 0 22
1631 0 require Langertha::Skeid::CustomerSource::DBI;
1632 0 Langertha::Skeid::CustomerSource::DBI->new(config => $cfg);
1633 };
1634 22 my $weak = $self;
1635 22 weaken($weak);
1636 my $ctl = Langertha::Skeid::CustomerSource->new(
1637 config => $cfg,
1638 fetcher => $fetcher,
1639 33 ▶ on_rows => sub { $weak->_source_rows($_[0]) if $weak },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if $weak 33 0 33
1640 13 ▶ on_failure => sub { $weak->_source_failed($_[0]) if $weak },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if $weak 13 0 13
1641 22 );
1642 22 $self->_source_ctl($ctl);
1643 22 $ctl->start;
1644 22 return $ctl;
1645 }
1646  
1647 1818 ▶sub _stop_source_controller {
Subroutine _stop_source_controller: called CC=3 SCAR=11.0
1648 1818 my ($self) = @_;
1649 1818 my $ctl = $self->_source_ctl;
1650 1818 ▶ $ctl->stop if $ctl;
Branch: 1 branch
BranchTrueFalseTotal
if $ctl 22 1796 1818
1651 1818 $self->_source_ctl(undef);
1652 1818 my $timer = $self->_source_stale_timer;
1653 1818 ▶ Mojo::IOLoop->remove($timer) if defined $timer;
Branch: 1 branch
BranchTrueFalseTotal
if defined $timer 1 1817 1818
1654 1818 $self->_source_stale_timer(undef);
1655 1818 return;
1656 }
1657  
1658 # A successful fetch. An unchanged snapshot only renews its age: no reload, no inventory bump, no
1659 # probe restart. A changed one is merged by a reload -- in-memory work, run here, from the loop,
1660 # never from a request.
1661 33 ▶sub _source_rows {
Subroutine _source_rows: called CC=4 SCAR=13.9
1662 33 my ($self, $rows) = @_;
1663 33 my $digest = Langertha::Skeid::CustomerSource->snapshot_digest($rows);
1664 33 $self->_arm_source_stale_timer;
1665 33 my $snapshot = $self->_source_snapshot;
1666 33 ▶ if ($snapshot && !$snapshot->{stale} && $snapshot->{digest} eq $digest) {
Branch: 1 branch
BranchTrueFalseTotal
if ($snapshot and not $snapshot->{"stale"} and $snapshot->{"digest"} eq $digest) 8 25 33
Condition100%6/6
$snapshot and not $snapshot->{"stale"} and $snapshot->{"digest"} eq $digest
!ll&&!rl&&r
1878
$snapshot and not $snapshot->{"stale"}
!ll&&!rl&&r
17115
MC/DC100%3/3
$snapshot and not $snapshot->{"stale"} and $snapshot->{"digest"} eq $digest
$snapshot not $snapshot->{"stale"} $snapshot->{"digest"} eq $digest
Truth table100%4/4
A and not(B) and C
A= $snapshotB= not $snapshot->{"stale"}C= $snapshot->{"digest"} eq $digest
ABCresult
0XX0
10X0
1100
1111
1667 8 $snapshot->{fetched_at} = $self->_now;
1668 8 return;
1669 }
1670 25 $self->_source_snapshot({ rows => $rows, digest => $digest, fetched_at => $self->_now, stale => 0 });
1671 25 $self->_reload_for_source;
1672 25 return;
1673 }
1674  
1675 13 ▶sub _source_failed {
Subroutine _source_failed: called CC=1 SCAR=0.0
1676 13 my ($self, $err) = @_;
1677 13 $self->_check_source_stale;
1678 13 return;
1679 }
1680  
1681 # max_stale_s: how old the last good snapshot may get while fetches fail. Checked when a fetch
1682 # fails and when the limit runs out after the last success, whichever is first.
1683 33 ▶sub _arm_source_stale_timer {
Subroutine _arm_source_stale_timer: called CC=4 SCAR=14.3
1684 33 my ($self) = @_;
1685 33 my $timer = $self->_source_stale_timer;
1686 33 ▶ Mojo::IOLoop->remove($timer) if defined $timer;
Branch: 1 branch
BranchTrueFalseTotal
if defined $timer 0 33 33
1687 33 $self->_source_stale_timer(undef);
1688 33 ▶ my $max = $self->_source_cfg ? $self->_source_cfg->{max_stale_s} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->_source_cfg ? : 33 0 33
1689 33 ▶ return unless $max > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $max > 0 31 2 33
1690 2 my $weak = $self;
1691 2 weaken($weak);
1692 1 ▶ $self->_source_stale_timer(Mojo::IOLoop->timer($max => sub {
Subroutine __ANON__: called CC=4 SCAR=15.6
1693 1 ▶ return unless $weak;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak 0 1 1
1694 1 $weak->_source_stale_timer(undef);
1695 1 my $ctl = $weak->_source_ctl;
1696 1 ▶ $weak->_check_source_stale if $ctl && $ctl->failures;
Branch: 1 branch
BranchTrueFalseTotal
if $ctl and $ctl->failures 1 0 1
Condition33%1/3
$ctl and $ctl->failures
!ll&&!rl&&r
001
MC/DC0%0/2
$ctl and $ctl->failures
$ctl $ctl->failures
Truth table33%1/3
A and B
A= $ctlB= $ctl->failures
ABresult
0X0
100
111
1697 2 }));
1698 2 return;
1699 }
1700  
1701 14 ▶sub _check_source_stale {
Subroutine _check_source_stale: called CC=6 SCAR=18.3
1702 14 my ($self) = @_;
1703 14 ▶ my $cfg = $self->_source_cfg or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cfg = $self->_source_cfg or return 14 0 14
1704 14 my $max = $cfg->{max_stale_s};
1705 14 ▶ return unless $max > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $max > 0 11 3 14
1706 3 my $snapshot = $self->_source_snapshot;
1707 3 ▶ return unless $snapshot && !$snapshot->{stale};
Branch: 1 branch
BranchTrueFalseTotal
unless $snapshot and not $snapshot->{"stale"} 0 3 3
Condition33%1/3
$snapshot and not $snapshot->{"stale"}
!ll&&!rl&&r
003
MC/DC0%0/2
$snapshot and not $snapshot->{"stale"}
$snapshot not $snapshot->{"stale"}
Truth table33%1/3
A and not(B)
A= $snapshotB= not $snapshot->{"stale"}
ABresult
0X0
100
111
1708 3 ▶ return if $self->_now - $snapshot->{fetched_at} < $max - 0.001;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_now - $snapshot->{"fetched_at"} < $max - "0.001" 2 1 3
1709 1 warn "skeid: customer_source: the last good snapshot is older than max_stale_s (${max}s); its "
1710 . "rows are dropped until a fetch succeeds\n";
1711 1 $self->_source_snapshot({ %$snapshot, rows => [], stale => 1 });
1712 1 $self->_reload_for_source;
1713 1 return;
1714 }
1715  
1716 # The reload a new snapshot triggers: the existing all-or-nothing reload_config, with the file
1717 # read again and the snapshot in memory. It never dies -- it runs from a loop callback -- and a
1718 # failure is logged when its reason is new, like a reload a request triggers.
1719 26 ▶sub _reload_for_source {
Subroutine _reload_for_source: called CC=7 SCAR=29.9
1720 26 my ($self) = @_;
1721 26 ▶ return if $self->has_config_file && !-f $self->config_file;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_config_file and not -f $self->config_file 0 26 26
Condition33%1/3
$self->has_config_file and not -f $self->config_file
!ll&&!rl&&r
2600
MC/DC0%0/2
$self->has_config_file and not -f $self->config_file
$self->has_config_file not -f $self->config_file
Truth table33%1/3
A and not(B)
A= $self->has_config_fileB= not -f $self->config_file
ABresult
0X0
100
111
1722 26 my $error_before = $self->last_reload_error;
1723 26 ▶ return if eval { $self->reload_config; 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $self->reload_config; 1 } } 26 0 26
1724 0 ▶ my $err = $@ || 'config reload failed';
Condition0%0/2
$@ || 'config reload failed'
l!l
00
MC/DC0%0/1
$@ || 'config reload failed'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
1725 0 ▶ if (!defined($error_before) || $error_before ne $err) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $error_before or $error_before ne $err) 0 0 0
Condition0%0/3
not defined $error_before or $error_before ne $err
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $error_before or $error_before ne $err
not defined $error_before $error_before ne $err
Truth table0%0/3
not(A) or B
A= not defined $error_beforeB= $error_before ne $err
ABresult
1X1
011
000
1726 0 (my $msg = $err) =~ s/\s+\z//;
1727 0 warn "skeid: config reload for a new customer_source snapshot failed, keeping the previous "
1728 . "config: $msg\n";
1729 }
1730 0 return;
1731 }
1732  
1733  
1734 563 ▶sub start_customer_source {
Subroutine start_customer_source: called CC=4 SCAR=14.6
Pod documented
1735 563 my ($self) = @_;
1736 563 ▶ return 1 if $self->_source_started && $self->_source_ctl;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_source_started and $self->_source_ctl 0 563 563
Condition33%1/3
$self->_source_started and $self->_source_ctl
!ll&&!rl&&r
56300
MC/DC0%0/2
$self->_source_started and $self->_source_ctl
$self->_source_started $self->_source_ctl
Truth table33%1/3
A and B
A= $self->_source_startedB= $self->_source_ctl
ABresult
0X0
100
111
1737 563 $self->_source_started(1);
1738 563 ▶ return $self->_start_source_controller ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->_start_source_controller ? : 19 544 563
1739 }
1740  
1741  
1742 14 ▶sub stop_customer_source {
Subroutine stop_customer_source: called CC=1 SCAR=0.0
Pod documented
1743 14 my ($self) = @_;
1744 14 $self->_source_started(0);
1745 14 $self->_stop_source_controller;
1746 14 return;
1747 }
1748  
1749  
1750 6 ▶sub customer_source_startup_fetch {
Subroutine customer_source_startup_fetch: called CC=6 SCAR=18.1
Pod documented
1751 6 my ($self) = @_;
1752 6 ▶ my $ctl = $self->_source_ctl or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $ctl = $self->_source_ctl or return 0 6 0 6
1753 6 my $done = $ctl->completed;
1754 6 $ctl->fetch_now;
1755 6 my $end = $self->_now + $ctl->config->{connect_timeout_s} + 1;
1756 6 ▶ my $tick = Mojo::IOLoop->recurring(0.05 => sub { });
Subroutine __ANON__: called CC=1 SCAR=0.0
1757 6 ▶ Mojo::IOLoop->one_tick while $ctl->completed == $done && $self->_now < $end;
Branch: 1 branch
BranchTrueFalseTotal
$ctl->completed == $done and $self->_now < $end and do { "Mojo::IOLoop"->one_tick } 7 6 13
Condition66%2/3
$ctl->completed == $done and $self->_now < $end
!ll&&!rl&&r
607
MC/DC50%1/2
$ctl->completed == $done and $self->_now < $end
$ctl->completed == $done $self->_now < $end
Truth table66%2/3
A and B
A= $ctl->completed == $doneB= $self->_now < $end
ABresult
0X0
100
111
1758 6 Mojo::IOLoop->remove($tick);
1759 6 ▶ return ($ctl->completed > $done && !$ctl->failures) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ctl->completed > $done && !$ctl->failures ? : 4 2 6
Condition66%2/3
$ctl->completed > $done and not $ctl->failures
!ll&&!rl&&r
024
MC/DC50%1/2
$ctl->completed > $done and not $ctl->failures
$ctl->completed > $done not $ctl->failures
Truth table66%2/3
A and not(B)
A= $ctl->completed > $doneB= not $ctl->failures
ABresult
0X0
100
111
1760 }
1761  
1762  
1763 1 ▶sub customer_source_release {
Subroutine customer_source_release: called CC=2 SCAR=7.2
Pod documented
1764 1 my ($self) = @_;
1765 1 my $ctl = $self->_source_ctl;
1766 1 ▶ return unless $ctl;
Branch: 1 branch
BranchTrueFalseTotal
unless $ctl 0 1 1
1767 1 $ctl->release;
1768 1 weaken(my $weak = $self);
1769 1 ▶ Mojo::IOLoop->next_tick(sub {
Subroutine __ANON__: called CC=3 SCAR=13.1
1770 1 ▶ my $c = $weak && $weak->_source_ctl;
Condition33%1/3
$weak && $weak->_source_ctl
!ll&&!rl&&r
001
MC/DC0%0/2
$weak && $weak->_source_ctl
$weak $weak->_source_ctl
Truth table33%1/3
A && B
A= $weakB= $weak->_source_ctl
ABresult
0X0
100
111
1771 1 ▶ $c->fetch_now if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 1 0 1
1772 1 });
1773 1 return;
1774 }
1775  
1776  
1777 291 ▶sub customer_source_status {
Subroutine customer_source_status: called CC=6 SCAR=17.9
Pod documented
1778 291 my ($self) = @_;
1779 291 ▶ my $cfg = $self->_source_cfg or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $cfg = $self->_source_cfg or return undef 231 60 291
1780 231 my $ctl = $self->_source_ctl;
1781 231 ▶ my $status = $ctl ? $ctl->status : {
Branch: 1 branch
BranchTrueFalseTotal
$ctl ? : 231 0 231
1782 ok => 0, last_success_at => undef, failed_at => undef, failures => 0,
1783 error => 'the customer source is not being fetched (not started)',
1784 };
1785 231 ▶ my $report = $self->_source_report || { accepted => 0, rejected => [], shadowed => [] };
Condition100%2/2
$self->_source_report || {'accepted', 0, 'rejected', [], 'shadowed', []}
l!l
2274
MC/DC100%1/1
$self->_source_report || {'accepted', 0, 'rejected', [], 'shadowed', []}
$self->_source_report
Truth table100%2/2
A
A= $self->_source_report
Aresult
11
00
1786 231 my @rejected = @{$report->{rejected}};
1787 231 my @shadowed = @{$report->{shadowed}};
1788 231 my $snapshot = $self->_source_snapshot;
1789 return {
1790 %$status,
1791 relation => $cfg->{relation},
1792 listen => $cfg->{listen},
1793 stale => ($snapshot && $snapshot->{stale}) ? 1 : 0,
1794 rows => {
1795 accepted => 0 + $report->{accepted},
1796 rejected => scalar(@rejected),
1797 shadowed => scalar(@shadowed),
1798 },
1799 231 ▶ rejected => [ map { +{ %$_ } } @rejected[0 .. _last(49, @rejected)] ],
Branch: 1 branch
BranchTrueFalseTotal
$snapshot && $snapshot->{'stale'} ? : 1 230 231
Condition100%3/3
$snapshot and $snapshot->{"stale"}
!ll&&!rl&&r
32271
MC/DC100%2/2
$snapshot and $snapshot->{"stale"}
$snapshot $snapshot->{"stale"}
Truth table100%3/3
A and B
A= $snapshotB= $snapshot->{"stale"}
ABresult
0X0
100
111
1800 shadowed => [ @shadowed[0 .. _last(49, @shadowed)] ],
1801 };
1802 }
1803  
1804  
1805 7 ▶sub customer_names {
Subroutine customer_names: called CC=3 SCAR=11.4
Pod documented
1806 7 my ($self) = @_;
1807 7 ▶ my $report = $self->_source_report or return {};
Branch: 1 branch
BranchTrueFalseTotal
my $report = $self->_source_report or return {} 7 0 7
1808 7 ▶ return { %{$report->{names} || {}} };
Condition50%1/2
$report->{'names'} || {}
l!l
70
MC/DC0%0/1
$report->{'names'} || {}
$report->{'names'}
Truth table50%1/2
A
A= $report->{'names'}
Aresult
11
00
1809 }
1810  
1811  
1812 7 ▶sub customer_report {
Subroutine customer_report: called CC=3 SCAR=11.1
Pod documented
1813 7 my ($self) = @_;
1814 7 ▶ $self->_source_cfg or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->_source_cfg or return undef 7 0 7
1815 7 ▶ my $report = $self->_source_report || { accepted => 0, rejected => [], shadowed => [] };
Condition50%1/2
$self->_source_report || {'accepted', 0, 'rejected', [], 'shadowed', []}
l!l
70
MC/DC0%0/1
$self->_source_report || {'accepted', 0, 'rejected', [], 'shadowed', []}
$self->_source_report
Truth table50%1/2
A
A= $self->_source_report
Aresult
11
00
1816 7 my @rejected = @{$report->{rejected}};
1817 7 my @shadowed = @{$report->{shadowed}};
1818 return {
1819 accepted => 0 + $report->{accepted},
1820 7 rejected => [ map { +{ %$_ } } @rejected[0 .. _last(49, @rejected)] ],
1821 shadowed => [ @shadowed[0 .. _last(49, @shadowed)] ],
1822 };
1823 }
1824  
1825 # The client-facing faces Skeid serves, as manifest endpoints. Each face's spec -- dialect,
1826 # path under public_url, and the capability flags its translator actually carries upstream --
1827 # lives with that face's translator (ADR 0001: format-specific facts stay in the translator).
1828 my %MANIFEST_FACES = (
1829 18 ▶ openai => sub { Langertha::Skeid::Protocol->openai_manifest_endpoint },
Subroutine __ANON__: called CC=1 SCAR=0.0
1830 18 ▶ anthropic => sub { Langertha::Skeid::Protocol::Anthropic->manifest_endpoint },
Subroutine __ANON__: called CC=1 SCAR=0.0
1831 18 ▶ ollama => sub { Langertha::Skeid::Protocol::Ollama->manifest_endpoint },
Subroutine __ANON__: called CC=1 SCAR=0.0
1832 127 );
1833 127 my @MANIFEST_FACE_ORDER = qw(openai anthropic ollama);
1834 127 my $manifest_unavailable_warned;
1835  
1836 123 ▶sub _is_true {
Subroutine _is_true: called CC=3 SCAR=11.1
1837 123 my ($value) = @_;
1838 123 ▶ return (defined($value) && "$value" =~ /^(1|true|yes|on)$/i) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $value && "$value" =~ /^(1|true|yes|on)$/i ? : 115 8 123
Condition66%2/3
defined $value and "$value" =~ /^(1|true|yes|on)$/i
!ll&&!rl&&r
08115
MC/DC50%1/2
defined $value and "$value" =~ /^(1|true|yes|on)$/i
defined $value "$value" =~ /^(1|true|yes|on)$/i
Truth table66%2/3
A and B
A= defined $valueB= "$value" =~ /^(1|true|yes|on)$/i
ABresult
0X0
100
111
1839 }
1840  
1841 127 my %REGISTRY_KEYS = map { $_ => 1 } qw(enabled secret_env read_key_env ttl_s instance_id error_window_s);
1842  
1843 # The registry section (ADR 0017). Absent means off, so removing the block disables publishing
1844 # on the next reload. Enabled without a usable secret (set, at least MIN_SECRET_BYTES) or
1845 # without any credential to read it (admin key or read key) is a load error: the route never
1846 # answers unsigned, is unreadable without one of the two, and a config that asked for it should
1847 # not load as if it had not.
1848 579 ▶sub _load_registry {
Subroutine _load_registry: called CC=29 SCAR=35.5
1849 579 my ($self, $cfg) = @_;
1850 579 my $section = $cfg->{registry};
1851 579 my ($enabled, $secret, $read_key, $ttl, $instance, $window) = (0, '', '', 10, undef, 60);
1852  
1853 579 ▶ if (defined $section) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section) 20 559 579
1854 20 ▶ croak 'registry must be a hashref' unless ref($section) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 0 20 20
1855 20 for my $key (sort keys %$section) {
1856 croak "registry: unknown key '$key' (known: " . join(' ', sort keys %REGISTRY_KEYS)
1857 . '; the secret is named by secret_env, never written into the config)'
1858 45 ▶ unless $REGISTRY_KEYS{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless $REGISTRY_KEYS{$key} 2 43 45
1859 }
1860 18 $enabled = _is_true($section->{enabled});
1861  
1862 18 ▶ if (defined $section->{ttl_s}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"ttl_s"}) 2 16 18
1863 croak 'registry.ttl_s must be a positive number of seconds'
1864 2 ▶ unless looks_like_number($section->{ttl_s}) && $section->{ttl_s} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($section->{"ttl_s"}) and $section->{"ttl_s"} > 0 1 1 2
Condition66%2/3
&looks_like_number($section->{"ttl_s"}) and $section->{"ttl_s"} > 0
!ll&&!rl&&r
011
MC/DC50%1/2
&looks_like_number($section->{"ttl_s"}) and $section->{"ttl_s"} > 0
&looks_like_number($section->{"ttl_s"}) $section->{"ttl_s"} > 0
Truth table66%2/3
A and B
A= &looks_like_number($section->{"ttl_s"})B= $section->{"ttl_s"} > 0
ABresult
0X0
100
111
1865 1 $ttl = 0 + $section->{ttl_s};
1866 }
1867 17 ▶ if (defined $section->{error_window_s}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"error_window_s"}) 0 17 17
1868 croak 'registry.error_window_s must be a positive number of seconds'
1869 0 ▶ unless looks_like_number($section->{error_window_s}) && $section->{error_window_s} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($section->{"error_window_s"}) and $section->{"error_window_s"} > 0 0 0 0
Condition0%0/3
&looks_like_number($section->{"error_window_s"}) and $section->{"error_window_s"} > 0
!ll&&!rl&&r
000
MC/DC0%0/2
&looks_like_number($section->{"error_window_s"}) and $section->{"error_window_s"} > 0
&looks_like_number($section->{"error_window_s"}) $section->{"error_window_s"} > 0
Truth table0%0/3
A and B
A= &looks_like_number($section->{"error_window_s"})B= $section->{"error_window_s"} > 0
ABresult
0X0
100
111
1870 0 $window = 0 + $section->{error_window_s};
1871 }
1872 17 ▶ if (defined $section->{instance_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"instance_id"}) 1 16 17
1873 croak 'registry.instance_id must be a non-empty string'
1874 1 ▶ if ref($section->{instance_id}) || !length($section->{instance_id});
Branch: 1 branch
BranchTrueFalseTotal
if ref $section->{"instance_id"} or not length $section->{"instance_id"} 0 1 1
Condition33%1/3
ref $section->{"instance_id"} or not length $section->{"instance_id"}
l!l&&r!l&&!r
001
MC/DC0%0/2
ref $section->{"instance_id"} or not length $section->{"instance_id"}
ref $section->{"instance_id"} not length $section->{"instance_id"}
Truth table33%1/3
A or not(B)
A= ref $section->{"instance_id"}B= not length $section->{"instance_id"}
ABresult
1X1
011
000
1875 1 $instance = "$section->{instance_id}";
1876 }
1877  
1878 17 ▶ if ($enabled) {
Branch: 1 branch
BranchTrueFalseTotal
if ($enabled) 16 1 17
1879 16 my $env = $section->{secret_env};
1880 16 ▶ croak 'registry.secret_env is required when the registry is enabled: snapshots are '
Branch: 1 branch
BranchTrueFalseTotal
unless defined $env and not ref $env and length $env 2 14 16
Condition66%4/6
defined $env and not ref $env and length $env
!ll&&!rl&&r
2014
defined $env and not ref $env
!ll&&!rl&&r
2014
MC/DC33%1/3
defined $env and not ref $env and length $env
defined $env not ref $env length $env
Truth table50%2/4
A and not(B) and C
A= defined $envB= not ref $envC= length $env
ABCresult
0XX0
10X0
1100
1111
1881 . 'signed, never published unsigned'
1882 unless defined($env) && !ref($env) && length($env);
1883 14 ▶ $secret = $ENV{$env} // '';
Condition100%2/2
$ENV{$env} // ""
l!l
131
MC/DC100%1/1
$ENV{$env} // ""
$ENV{$env}
Truth table100%2/2
A
A= $ENV{$env}
Aresult
11
00
1884 14 ▶ croak "registry.secret_env names '$env', which is not set: snapshots are signed, never "
Branch: 1 branch
BranchTrueFalseTotal
unless length $secret 1 13 14
1885 . 'published unsigned'
1886 unless length $secret;
1887 13 require Langertha::Skeid::Registry;
1888 13 my $min = Langertha::Skeid::Registry->MIN_SECRET_BYTES;
1889 13 ▶ croak "registry.secret_env names '$env', which holds fewer than $min bytes: use a random "
Branch: 1 branch
BranchTrueFalseTotal
if length $secret < $min 1 12 13
1890 . "secret of at least $min bytes (e.g. openssl rand -hex 32)"
1891 if length($secret) < $min;
1892 # The read key opens the snapshot route and nothing else (skeid #49), so a fronting tier
1893 # need not hold the admin key. Named but empty is a mistake, not "no read key".
1894 12 ▶ if (defined $section->{read_key_env}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"read_key_env"}) 4 8 12
1895 4 my $read_env = $section->{read_key_env};
1896 4 ▶ croak 'registry.read_key_env must name an environment variable'
Branch: 1 branch
BranchTrueFalseTotal
if ref $read_env or not length $read_env 0 4 4
Condition33%1/3
ref $read_env or not length $read_env
l!l&&r!l&&!r
004
MC/DC0%0/2
ref $read_env or not length $read_env
ref $read_env not length $read_env
Truth table33%1/3
A or not(B)
A= ref $read_envB= not length $read_env
ABresult
1X1
011
000
1897 if ref($read_env) || !length($read_env);
1898 4 ▶ $read_key = $ENV{$read_env} // '';
Condition100%2/2
$ENV{$read_env} // ""
l!l
31
MC/DC100%1/1
$ENV{$read_env} // ""
$ENV{$read_env}
Truth table100%2/2
A
A= $ENV{$read_env}
Aresult
11
00
1899 4 ▶ croak "registry.read_key_env names '$read_env', which is not set"
Branch: 1 branch
BranchTrueFalseTotal
unless length $read_key 1 3 4
1900 unless length $read_key;
1901 }
1902 # The fronting tier reads the snapshot with the read key or this Skeid's admin key.
1903 # Without either nobody can, and a registry nobody can read is a config mistake, not a
1904 # choice -- say so at load instead of answering 404 forever.
1905 11 ▶ croak 'registry.enabled needs a credential to read the snapshot: registry.read_key_env '
Branch: 1 branch
BranchTrueFalseTotal
unless length $read_key or length($self->admin_api_key // "") 1 10 11
Condition80%4/5
length $read_key or length($self->admin_api_key // "")
l!l&&r!l&&!r
371
$self->admin_api_key // ""
l!l
80
MC/DC0%0/2
length $read_key or length($self->admin_api_key // "")
length $read_key $self->admin_api_key
Truth table66%2/3
A or B
A= length $read_keyB= $self->admin_api_key
ABresult
1X1
011
000
1906 . 'or an admin API key (admin.api_key or admin.api_key_env)'
1907 unless length($read_key) || length($self->admin_api_key // '');
1908 }
1909 }
1910  
1911 570 $self->registry_enabled($enabled);
1912 570 $self->registry_secret($secret);
1913 570 $self->registry_read_key($read_key);
1914 570 $self->registry_ttl_s($ttl);
1915 570 $self->registry_instance_id($instance);
1916 570 $self->registry_error_window_s($window);
1917 570 return 1;
1918 }
1919  
1920 # Resolves the manifest section and every key's manifest: grant once, at config load (ADR
1921 # 0015). Nothing is published that a keys: entry does not list, and what is listed has to be
1922 # something that key's routing policy lets it reach -- a contradiction is a load error, not a
1923 # manifest that promises a model the request path then refuses with 403. Everything is built
1924 # into lexicals and set together at the end; reload_config restores the old state on a croak.
1925 570 ▶sub _load_manifest {
Subroutine _load_manifest: called CC=48 SCAR=40.4
1926 570 my ($self, $cfg) = @_;
1927 570 my ($enabled, $available, %manifests) = (0, 0);
1928 561 ▶ my $commit = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1929 561 $self->manifest_enabled($enabled);
1930 561 $self->manifest_available($available);
1931 561 $self->key_manifests({%manifests});
1932 561 return 1;
1933 570 };
1934  
1935 570 my %grants;
1936 570 ▶ if (ref($cfg->{keys}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg->{"keys"} eq "HASH") 57 513 570
1937 57 for my $label (sort keys %{$cfg->{keys}}) {
1938 108 my $entry = $cfg->{keys}{$label};
1939 108 ▶ next unless ref($entry) eq 'HASH' && exists $entry->{manifest};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" and exists $entry->{"manifest"} 67 41 108
Condition100%3/3
ref $entry eq "HASH" and exists $entry->{"manifest"}
!ll&&!rl&&r
491841
MC/DC100%2/2
ref $entry eq "HASH" and exists $entry->{"manifest"}
ref $entry eq "HASH" exists $entry->{"manifest"}
Truth table100%3/3
A and B
A= ref $entry eq "HASH"B= exists $entry->{"manifest"}
ABresult
0X0
100
111
1940 41 my $grant = $entry->{manifest};
1941 croak "key '$label': manifest must be a hashref with a models list"
1942 41 ▶ unless ref($grant) eq 'HASH' && ref($grant->{models}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $grant eq "HASH" and ref $grant->{"models"} eq "ARRAY" 0 41 41
Condition33%1/3
ref $grant eq "HASH" and ref $grant->{"models"} eq "ARRAY"
!ll&&!rl&&r
0041
MC/DC0%0/2
ref $grant eq "HASH" and ref $grant->{"models"} eq "ARRAY"
ref $grant eq "HASH" ref $grant->{"models"} eq "ARRAY"
Truth table33%1/3
A and B
A= ref $grant eq "HASH"B= ref $grant->{"models"} eq "ARRAY"
ABresult
0X0
100
111
1943 41 my (%seen, @models);
1944 41 for my $model (@{$grant->{models}}) {
1945 80 ▶ croak "key '$label': manifest models must be non-empty model names"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and not ref $model and length $model 0 80 80
Condition33%2/6
defined $model and not ref $model and length $model
!ll&&!rl&&r
0080
defined $model and not ref $model
!ll&&!rl&&r
0080
MC/DC0%0/3
defined $model and not ref $model and length $model
defined $model not ref $model length $model
Truth table25%1/4
A and not(B) and C
A= defined $modelB= not ref $modelC= length $model
ABCresult
0XX0
10X0
1100
1111
1946 unless defined($model) && !ref($model) && length($model);
1947 80 ▶ push @models, "$model" unless $seen{$model}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$model}++ 80 0 80
1948 }
1949 41 ▶ my $id = $self->key_names->{$label} // $label;
Condition66%2/3
$self->key_names->{$label} // $label
l!l&&r!l&&!r
3920
MC/DC0%0/2
$self->key_names->{$label} // $label
$self->key_names->{$label} $label
Truth table66%2/3
A // B
A= $self->key_names->{$label}B= $label
ABresult
1X1
011
000
1950 41 $grants{$id} = { label => $label, models => \@models };
1951 }
1952 }
1953  
1954 570 my $section = $cfg->{manifest};
1955 570 ▶ return $commit->() unless defined $section;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $section 549 21 570
1956 21 ▶ croak 'manifest must be a hashref' unless ref($section) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 0 21 21
1957 21 ▶ return $commit->() unless _is_true($section->{enabled});
Branch: 1 branch
BranchTrueFalseTotal
unless _is_true($section->{"enabled"}) 1 20 21
1958  
1959 20 my $public_url = $section->{public_url};
1960 20 ▶ croak 'manifest.public_url is required when the manifest is enabled: the URL clients reach '
Branch: 1 branch
BranchTrueFalseTotal
unless defined $public_url and not ref $public_url and length $public_url 1 19 20
Condition66%4/6
defined $public_url and not ref $public_url and length $public_url
!ll&&!rl&&r
1019
defined $public_url and not ref $public_url
!ll&&!rl&&r
1019
MC/DC33%1/3
defined $public_url and not ref $public_url and length $public_url
defined $public_url not ref $public_url length $public_url
Truth table50%2/4
A and not(B) and C
A= defined $public_urlB= not ref $public_urlC= length $public_url
ABCresult
0XX0
10X0
1100
1111
1961 . 'Skeid at, never a node URL'
1962 unless defined($public_url) && !ref($public_url) && length($public_url);
1963 19 $public_url =~ s{/+\z}{};
1964 19 my ($issuer) = $public_url =~ m{\A([A-Za-z][A-Za-z0-9+.-]*://[^/?#]+)};
1965 19 ▶ croak "manifest.public_url must be an absolute http(s) URL, got '$public_url'" unless $issuer;
Branch: 1 branch
BranchTrueFalseTotal
unless $issuer 0 19 19
1966  
1967 19 ▶ my $provider_id = $section->{provider_id} // 'skeid';
Condition100%2/2
$section->{"provider_id"} // "skeid"
l!l
181
MC/DC100%1/1
$section->{"provider_id"} // "skeid"
$section->{"provider_id"}
Truth table100%2/2
A
A= $section->{"provider_id"}
Aresult
11
00
1968  
1969 19 my @faces = @MANIFEST_FACE_ORDER;
1970 19 ▶ if (defined $section->{faces}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"faces"}) 2 17 19
1971 2 ▶ croak 'manifest.faces must be a list' unless ref($section->{faces}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section->{"faces"} eq "ARRAY" 0 2 2
1972 2 my %want;
1973 2 for my $face (@{$section->{faces}}) {
1974 croak "manifest.faces: unknown face '" . ($face // '') . "' (known: @MANIFEST_FACE_ORDER)"
1975 2 ▶ unless defined($face) && !ref($face) && $MANIFEST_FACES{$face};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $face and not ref $face and $MANIFEST_FACES{$face} 1 1 2
Condition50%4/8
defined $face and not ref $face and $MANIFEST_FACES{$face}
!ll&&!rl&&r
011
defined $face and not ref $face
!ll&&!rl&&r
002
$face // ""
l!l
10
MC/DC33%1/3
defined $face and not ref $face and $MANIFEST_FACES{$face}
defined $face not ref $face $MANIFEST_FACES{$face}
MC/DC0%0/1
$face // ""
$face
Truth table50%2/4
A and not(B) and C
A= defined $faceB= not ref $faceC= $MANIFEST_FACES{$face}
ABCresult
0XX0
10X0
1100
1111
Truth table50%1/2
A
A= $face
Aresult
11
00
1976 1 $want{$face} = 1;
1977 }
1978 1 @faces = grep { $want{$_} } @MANIFEST_FACE_ORDER;
1979 1 ▶ croak 'manifest.faces must name at least one face' unless @faces;
Branch: 1 branch
BranchTrueFalseTotal
unless @faces 0 1 1
1980 }
1981 18 my %spec = map { $_ => $MANIFEST_FACES{$_}->() } @MANIFEST_FACE_ORDER;
1982  
1983 18 ▶ my $declared = $section->{capabilities} // {};
Condition100%2/2
$section->{"capabilities"} // {}
l!l
513
MC/DC100%1/1
$section->{"capabilities"} // {}
$section->{"capabilities"}
Truth table100%2/2
A
A= $section->{"capabilities"}
Aresult
11
00
1984 croak 'manifest.capabilities must map model names to capability hashes'
1985 18 ▶ unless ref($declared) eq 'HASH' && !grep { ref($_) ne 'HASH' } values %$declared;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $declared eq "HASH" and not grep({ref $_ ne "HASH";} values %$declared) 0 18 18
Condition33%1/3
ref $declared eq "HASH" and not grep({ref $_ ne "HASH";} values %$declared)
!ll&&!rl&&r
0018
MC/DC0%0/2
ref $declared eq "HASH" and not grep({ref $_ ne "HASH";} values %$declared)
ref $declared eq "HASH" not grep({ref $_ ne "HASH";} values %$declared)
Truth table33%1/3
A and not(B)
A= ref $declared eq "HASH"B= not grep({ref $_ ne "HASH";} values %$declared)
ABresult
0X0
100
111
1986  
1987 18 $enabled = 1;
1988  
1989 # Core's manifest (Langertha::Manifest, ADR 0029) is newer than the released Langertha this
1990 # dist requires. Without it the route answers 404; the config is still loaded.
1991 18 ▶ unless (eval { require Langertha::Manifest::Builder; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { require Langertha::Manifest::Builder; 1 } }) 0 18 18
1992 0 ▶ warn "skeid: manifest is enabled, but this Langertha has no Langertha::Manifest; "
Branch: 1 branch
BranchTrueFalseTotal
unless $manifest_unavailable_warned++ 0 0 0
1993 . "/.well-known/langertha.json answers 404\n"
1994 unless $manifest_unavailable_warned++;
1995 0 return $commit->();
1996 }
1997  
1998 # A claim no face of Skeid carries could never be published; saying so beats dropping it.
1999 18 my %allowed = map { $_ => 1 } Langertha::Manifest::Builder->model_capabilities;
2000 18 my %carried = map { $_ => 1 } map { @{$spec{$_}{capabilities}} } @MANIFEST_FACE_ORDER;
2001 18 for my $model (sort keys %$declared) {
2002 5 for my $flag (sort keys %{$declared->{$model}}) {
2003 croak "manifest.capabilities.$model: '$flag' is not a model capability a manifest may "
2004 . 'claim (see Langertha::Manifest::Builder->model_capabilities)'
2005 16 ▶ unless $allowed{$flag};
Branch: 1 branch
BranchTrueFalseTotal
unless $allowed{$flag} 1 15 16
2006 croak "manifest.capabilities.$model: '$flag' is not carried by any face Skeid serves"
2007 15 ▶ unless $carried{$flag};
Branch: 1 branch
BranchTrueFalseTotal
unless $carried{$flag} 1 14 15
2008 }
2009 }
2010  
2011 16 for my $id (sort keys %grants) {
2012 27 my $grant = $grants{$id};
2013 27 for my $model (@{$grant->{models}}) {
2014 52 ▶ croak "key '$grant->{label}': manifest lists model '$model', which its routing policy "
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_manifest_model_reachable($model, $id) 4 48 52
2015 . 'does not let it reach'
2016 unless $self->_manifest_model_reachable($model, $id);
2017 }
2018 23 my $json = eval {
2019 23 my $builder = Langertha::Manifest::Builder->new(
2020 provider_id => $provider_id,
2021 issuer => $issuer,
2022 );
2023 23 $builder->add_auth(id => 'api', type => 'api_key');
2024 23 for my $face (@faces) {
2025 63 my $face_spec = $spec{$face};
2026 63 my %face_carries = map { $_ => 1 } @{$face_spec->{capabilities}};
2027 $builder->add_endpoint(
2028 id => $face,
2029 dialect => $face_spec->{dialect},
2030 base_url => $public_url . $face_spec->{path},
2031 63 auth_ref => 'api',
2032 );
2033 62 for my $model (@{$grant->{models}}) {
2034 # Declared claims over the chat + streaming default, then cut to what this face's
2035 # translator carries: a claim holds "at that endpoint" (core ADR 0029) or not at all.
2036 124 my %caps = (chat => 1, streaming => 1);
2037 124 ▶ my $claims = $declared->{$model} || {};
Condition100%2/2
$declared->{$model} || {}
l!l
18106
MC/DC100%1/1
$declared->{$model} || {}
$declared->{$model}
Truth table100%2/2
A
A= $declared->{$model}
Aresult
11
00
2038 124 for my $flag (keys %$claims) {
2039 84 ▶ if (_is_true($claims->{$flag})) { $caps{$flag} = 1 } else { delete $caps{$flag} }
Branch: 1 branch
BranchTrueFalseTotal
if (_is_true($claims->{$flag})) { } 78 6 84
2040 }
2041 124 delete $caps{$_} for grep { !$face_carries{$_} } keys %caps;
2042 124 $builder->add_model(id => $model, endpoint_ref => $face, capabilities => \%caps);
2043 }
2044 }
2045 22 $builder->manifest->to_json;
2046 };
2047 23 ▶ unless (defined $json) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $json) 1 22 23
2048 1 (my $err = $@) =~ s/\s+at \S+ line \d+\.?\s*\z//s;
2049 1 croak "key '$grant->{label}': manifest does not validate: $err";
2050 }
2051 22 $manifests{$id} = $json;
2052 }
2053  
2054 11 $available = 1;
2055 11 return $commit->();
2056 }
2057  
2058 # Whether the key could be routed to the model at all: its policy grants the name, and some
2059 # node a permitted tier selects -- deny_tags applied, health ignored (a manifest is a claim,
2060 # not a probe) -- serves it. A raw node model behind a denied tag is as unreachable as an alias
2061 # the policy leaves out (ADR 0008), so it is not published either.
2062 52 ▶sub _manifest_model_reachable {
Subroutine _manifest_model_reachable: called CC=7 SCAR=19.7
2063 52 my ($self, $model, $api_key_id) = @_;
2064 52 my $plan = $self->route_plan(model => $model, api_key_id => $api_key_id);
2065 52 ▶ return 0 unless $plan->{permitted};
Branch: 1 branch
BranchTrueFalseTotal
unless $plan->{"permitted"} 2 50 52
2066 50 for my $tier (@{$plan->{tiers}}) {
2067 50 for my $node (@{$self->select_nodes(tags => $tier->{tags}, deny_tags => $tier->{deny_tags}, kind => '')}) {
2068 62 my $served = $node->{model};
2069 62 ▶ return 1 if !defined($served) || !length($served) || $served eq $tier->{model};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $served && length $served or $served eq $tier->{"model"} 48 14 62
Condition50%3/6
not defined $served && length $served or $served eq $tier->{"model"}
l!l&&r!l&&!r
04814
defined $served && length $served
!ll&&!rl&&r
0062
MC/DC33%1/3
not defined $served && length $served or $served eq $tier->{"model"}
defined $served length $served $served eq $tier->{"model"}
Truth table50%2/4
not(A && B) or C
A= defined $servedB= length $servedC= $served eq $tier->{"model"}
ABCresult
0XX1
10X1
1111
1100
2070 }
2071 }
2072 2 return 0;
2073 }
2074  
2075  
2076 17 ▶sub manifest_for_key {
Subroutine manifest_for_key: called CC=4 SCAR=14.6
Pod documented
2077 17 my ($self, $api_key_id) = @_;
2078 17 ▶ return undef unless $self->manifest_enabled && $self->manifest_available;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->manifest_enabled and $self->manifest_available 0 17 17
Condition33%1/3
$self->manifest_enabled and $self->manifest_available
!ll&&!rl&&r
0017
MC/DC0%0/2
$self->manifest_enabled and $self->manifest_available
$self->manifest_enabled $self->manifest_available
Truth table33%1/3
A and B
A= $self->manifest_enabledB= $self->manifest_available
ABresult
0X0
100
111
2079 17 my $id = $self->_configured_key_id($self->key_manifests, $api_key_id);
2080 17 ▶ return defined($id) ? $self->key_manifests->{$id} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $id ? : 14 3 17
2081 }
2082  
2083  
2084 15 ▶sub configure_usage_store {
Subroutine configure_usage_store: called CC=1 SCAR=0.0
Pod documented
2085 15 my ($self, $cfg) = @_;
2086 15 return $self->_configure_usage_store($cfg);
2087 }
2088  
2089  
2090 98 ▶sub _configure_usage_store {
Subroutine _configure_usage_store: called CC=44 SCAR=39.3
2091 98 my ($self, $cfg) = @_;
2092 98 ▶ my $normalized = Langertha::Skeid::UsageStore->normalize_config(
Branch: 1 branch
BranchTrueFalseTotal
$self->has_usage_db_path ? : 98 0 98
2093 $cfg,
2094 default_sqlite_path => ($self->has_usage_db_path ? $self->usage_db_path : undef),
2095 );
2096  
2097 96 ▶ my $old = $self->usage_store || {};
Condition50%1/2
$self->usage_store || {}
l!l
960
MC/DC0%0/1
$self->usage_store || {}
$self->usage_store
Truth table50%1/2
A
A= $self->usage_store
Aresult
11
00
2098 my $same = ref($old) eq 'HASH'
2099 && (($old->{backend} // '') eq ($normalized->{backend} // ''))
2100 && (($old->{dsn} // '') eq ($normalized->{dsn} // ''))
2101 && (($old->{path} // '') eq ($normalized->{path} // ''))
2102 && (($old->{mode} // '') eq ($normalized->{mode} // ''))
2103 && (($old->{user} // '') eq ($normalized->{user} // ''))
2104 && (($old->{password} // '') eq ($normalized->{password} // ''))
2105 && (($old->{schema_file} // '') eq ($normalized->{schema_file} // ''))
2106 && ((($old->{auto_migrate} // 1) ? 1 : 0) == (($normalized->{auto_migrate} // 1) ? 1 : 0))
2107 && (($old->{flush_interval_ms} // 0) == ($normalized->{flush_interval_ms} // 0))
2108 96 ▶ && (($old->{spool_dir} // '') eq ($normalized->{spool_dir} // ''));
Branch: 2 branches
BranchTrueFalseTotal
$old->{'auto_migrate'} // 1 ? : 30 0 30
$normalized->{'auto_migrate'} // 1 ? : 30 0 30
Condition90%63/70
ref $old eq 'HASH' && ($old->{'backend'} // '') eq ($normalized->{'backend'} // '') && ($old->{'dsn'} // '') eq ($normalized->{'dsn'} // '') && ($old->{'path'} // '') eq ($normalized->{'path'} // '') && ($old->{'mode'} // '') eq ($normalized->{'mode'} // '') && ($old->{'user'} // '') eq ($normalized->{'user'} // '') && ($old->{'password'} // '') eq ($normalized->{'password'} // '') && ($old->{'schema_file'} // '') eq ($normalized->{'schema_file'} // '') && ($old->{'auto_migrate'} // 1 ? 1 : 0) == ($normalized->{'auto_migrate'} // 1 ? 1 : 0) && ($old->{'flush_interval_ms'} // 0) == ($normalized->{'flush_interval_ms'} // 0) && ($old->{'spool_dir'} // '') eq ($normalized->{'spool_dir'} // '')
!ll&&!rl&&r
68127
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "") and ($old->{"mode"} // "") eq ($normalized->{"mode"} // "") and ($old->{"user"} // "") eq ($normalized->{"user"} // "") and ($old->{"password"} // "") eq ($normalized->{"password"} // "") and ($old->{"schema_file"} // "") eq ($normalized->{"schema_file"} // "") and ($old->{"auto_migrate"} // 1 ? 1 : 0) == ($normalized->{"auto_migrate"} // 1 ? 1 : 0) and ($old->{"flush_interval_ms"} // 0) == ($normalized->{"flush_interval_ms"} // 0)
!ll&&!rl&&r
66228
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "") and ($old->{"mode"} // "") eq ($normalized->{"mode"} // "") and ($old->{"user"} // "") eq ($normalized->{"user"} // "") and ($old->{"password"} // "") eq ($normalized->{"password"} // "") and ($old->{"schema_file"} // "") eq ($normalized->{"schema_file"} // "") and ($old->{"auto_migrate"} // 1 ? 1 : 0) == ($normalized->{"auto_migrate"} // 1 ? 1 : 0)
!ll&&!rl&&r
66030
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "") and ($old->{"mode"} // "") eq ($normalized->{"mode"} // "") and ($old->{"user"} // "") eq ($normalized->{"user"} // "") and ($old->{"password"} // "") eq ($normalized->{"password"} // "") and ($old->{"schema_file"} // "") eq ($normalized->{"schema_file"} // "")
!ll&&!rl&&r
66030
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "") and ($old->{"mode"} // "") eq ($normalized->{"mode"} // "") and ($old->{"user"} // "") eq ($normalized->{"user"} // "") and ($old->{"password"} // "") eq ($normalized->{"password"} // "")
!ll&&!rl&&r
66030
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "") and ($old->{"mode"} // "") eq ($normalized->{"mode"} // "") and ($old->{"user"} // "") eq ($normalized->{"user"} // "")
!ll&&!rl&&r
66030
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "") and ($old->{"mode"} // "") eq ($normalized->{"mode"} // "")
!ll&&!rl&&r
60630
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "")
!ll&&!rl&&r
52836
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "")
!ll&&!rl&&r
242844
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "")
!ll&&!rl&&r
02472
$old->{"backend"} // ""
l!l
7224
$normalized->{"backend"} // ""
l!l
960
$old->{"dsn"} // ""
l!l
666
$normalized->{"dsn"} // ""
l!l
3339
$old->{"path"} // ""
l!l
386
$normalized->{"path"} // ""
l!l
440
$old->{"mode"} // ""
l!l
2511
$normalized->{"mode"} // ""
l!l
315
$old->{"user"} // ""
l!l
525
$normalized->{"user"} // ""
l!l
525
$old->{"password"} // ""
l!l
525
$normalized->{"password"} // ""
l!l
525
$old->{"schema_file"} // ""
l!l
525
$normalized->{"schema_file"} // ""
l!l
525
$old->{"auto_migrate"} // 1
l!l
525
$normalized->{"auto_migrate"} // 1
l!l
525
$old->{"flush_interval_ms"} // 0
l!l
525
$normalized->{"flush_interval_ms"} // 0
l!l
525
$old->{"spool_dir"} // ""
l!l
325
$normalized->{"spool_dir"} // ""
l!l
325
MC/DC0%0/11
ref $old eq 'HASH' && ($old->{'backend'} // '') eq ($normalized->{'backend'} // '') && ($old->{'dsn'} // '') eq ($normalized->{'dsn'} // '') && ($old->{'path'} // '') eq ($normalized->{'path'} // '') && ($old->{'mode'} // '') eq ($normalized->{'mode'} // '') && ($old->{'user'} // '') eq ($normalized->{'user'} // '') && ($old->{'password'} // '') eq ($normalized->{'password'} // '') && ($old->{'schema_file'} // '') eq ($normalized->{'schema_file'} // '') && ($old->{'auto_migrate'} // 1 ? 1 : 0) == ($normalized->{'auto_migrate'} // 1 ? 1 : 0) && ($old->{'flush_interval_ms'} // 0) == ($normalized->{'flush_interval_ms'} // 0) && ($old->{'spool_dir'} // '') eq ($normalized->{'spool_dir'} // '')
ref $old eq "HASH" $old->{"backend"} $old->{"dsn"} $old->{"path"} $old->{"mode"} $old->{"user"} $old->{"password"} $old->{"schema_file"} $old->{"auto_migrate"} $old->{"flush_interval_ms"} $old->{"spool_dir"}
MC/DC0%0/1
$normalized->{"backend"} // ""
$normalized->{"backend"}
MC/DC100%1/1
$normalized->{"dsn"} // ""
$normalized->{"dsn"}
MC/DC0%0/1
$normalized->{"path"} // ""
$normalized->{"path"}
MC/DC100%1/1
$normalized->{"mode"} // ""
$normalized->{"mode"}
MC/DC100%1/1
$normalized->{"user"} // ""
$normalized->{"user"}
MC/DC100%1/1
$normalized->{"password"} // ""
$normalized->{"password"}
MC/DC100%1/1
$normalized->{"schema_file"} // ""
$normalized->{"schema_file"}
MC/DC100%1/1
$normalized->{"auto_migrate"} // 1
$normalized->{"auto_migrate"}
MC/DC100%1/1
$normalized->{"flush_interval_ms"} // 0
$normalized->{"flush_interval_ms"}
MC/DC100%1/1
$normalized->{"spool_dir"} // ""
$normalized->{"spool_dir"}
Truth table16%2/12
A and B and C and D and E and F and G and H and I and J && K
A= ref $old eq "HASH"B= $old->{"backend"}C= $old->{"dsn"}D= $old->{"path"}E= $old->{"mode"}F= $old->{"user"}G= $old->{"password"}H= $old->{"schema_file"}I= $old->{"auto_migrate"}J= $old->{"flush_interval_ms"}K= $old->{"spool_dir"}
ABCDEFGHIJKresult
0XXXXXXXXXX0
10XXXXXXXXX0
110XXXXXXXX0
1110XXXXXXX0
11110XXXXXX0
111110XXXXX0
1111110XXXX0
11111110XXX0
111111110XX0
1111111110X0
111111111100
111111111111
Truth table50%1/2
A
A= $normalized->{"backend"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"dsn"}
Aresult
11
00
Truth table50%1/2
A
A= $normalized->{"path"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"mode"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"user"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"password"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"schema_file"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"auto_migrate"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"flush_interval_ms"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"spool_dir"}
Aresult
11
00
2109  
2110 # Rebuild when the config changed, and also when there simply is no store object yet:
2111 # BUILD hands us the caller's raw config as $old, which can compare equal to its own
2112 # normalized form and would otherwise leave the store unbuilt.
2113 96 ▶ my $changed = $same ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$same ? : 27 69 96
2114 96 ▶ if ($changed || !$self->_usage_store_obj) {
Branch: 1 branch
BranchTrueFalseTotal
if ($changed or not $self->_usage_store_obj) 86 10 96
Condition100%3/3
$changed or not $self->_usage_store_obj
l!l&&r!l&&!r
691710
MC/DC100%2/2
$changed or not $self->_usage_store_obj
$changed not $self->_usage_store_obj
Truth table100%3/3
A or not(B)
A= $changedB= not $self->_usage_store_obj
ABresult
1X1
011
000
2115 # Prepare the new store before letting go of the old one: a store that fails to come up
2116 # fails the reload with the old store still connected (reload_config is all or nothing).
2117 86 my $store = Langertha::Skeid::UsageStore->for_config($normalized);
2118 86 ▶ $store->prepare if $store;
Branch: 1 branch
BranchTrueFalseTotal
if $store 86 0 86
2119 86 ▶ if ($store && $store->can('on_lost')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($store and $store->can("on_lost")) 37 49 86
Condition66%2/3
$store and $store->can("on_lost")
!ll&&!rl&&r
04937
MC/DC50%1/2
$store and $store->can("on_lost")
$store $store->can("on_lost")
Truth table66%2/3
A and B
A= $storeB= $store->can("on_lost")
ABresult
0X0
100
111
2120 37 weaken(my $weak = $self);
2121 37 ▶ $store->on_lost(sub { $weak->_usage_lost(@_) if $weak });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $weak 1 0 1
2122 }
2123 # The old store flushes what it still holds on the way out: those events were recorded
2124 # while it was the configured destination.
2125 86 $self->_disconnect_usage_store;
2126 86 $self->usage_store($normalized);
2127 86 $self->_usage_store_obj($store);
2128 }
2129  
2130 96 ▶ if ($normalized->{backend} eq 'sqlite') {
Branch: 2 branches
BranchTrueFalseTotal
if ($normalized->{'backend'} eq 'sqlite') { } 39 57 96
elsif ($normalized->{'backend'} ne 'jsonlog') { } 0 57 57
2131 39 $self->usage_db_path($normalized->{path});
2132 } elsif ($normalized->{backend} ne 'jsonlog') {
2133 0 ▶ $self->clear_usage_db_path if $self->has_usage_db_path;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_usage_db_path 0 0 0
2134 }
2135  
2136 96 return $self->usage_store;
2137 }
2138 0 ▶sub _set_usage_db_path {
Subroutine _set_usage_db_path: not called CC=1 SCAR=6.9
2139 0 my ($self, $path) = @_;
2140 0 return $self->_configure_usage_store({
2141 backend => 'sqlite',
2142 sqlite_path => $path,
2143 });
2144 }
2145  
2146  
2147 34307 ▶sub _num {
Subroutine _num: called CC=2 SCAR=6.9
2148 34307 my ($v) = @_;
2149 34307 ▶ return 0 unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 20010 14297 34307
2150 14297 return 0 + $v;
2151 }
2152  
2153 128 ▶sub _iso8601_now {
Subroutine _iso8601_now: called CC=1 SCAR=0.0
2154 128 return strftime('%Y-%m-%dT%H:%M:%SZ', gmtime());
2155 }
2156  
2157 1444 ▶sub _discover_engine_ids {
Subroutine _discover_engine_ids: called CC=7 SCAR=21.8
2158 1444 my %ids = %FALLBACK_ENGINE_IDS;
2159 1444 ▶ if (Langertha->can('available_engine_ids')) {
Branch: 1 branch
BranchTrueFalseTotal
if ("Langertha"->can("available_engine_ids")) 1444 0 1444
2160 1444 my $found = eval { Langertha->available_engine_ids };
2161 1444 ▶ if (!$@ && ref($found) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $@ and ref $found eq "ARRAY") 1444 0 1444
Condition33%1/3
not $@ and ref $found eq "ARRAY"
!ll&&!rl&&r
001444
MC/DC0%0/2
not $@ and ref $found eq "ARRAY"
not $@ ref $found eq "ARRAY"
Truth table33%1/3
not(A) and B
A= not $@B= ref $found eq "ARRAY"
ABresult
0X0
100
111
2162 1444 for my $id (@$found) {
2163 57760 ▶ next unless defined $id && length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 0 57760 57760
Condition33%1/3
defined $id and length $id
!ll&&!rl&&r
0057760
MC/DC0%0/2
defined $id and length $id
defined $id length $id
Truth table33%1/3
A and B
A= defined $idB= length $id
ABresult
0X0
100
111
2164 57760 $ids{lc $id} = 1;
2165 }
2166 }
2167 }
2168  
2169 1444 return \%ids;
2170 }
2171  
2172  
2173 0 ▶sub supported_engine_ids {
Subroutine supported_engine_ids: not called CC=1 SCAR=6.9
Pod documented
2174 0 my ($self) = @_;
2175 0 my $ids = _discover_engine_ids();
2176 0 return [ sort keys %$ids ];
2177 }
2178  
2179  
2180 14078 ▶sub normalize_engine_id {
Subroutine normalize_engine_id: called CC=4 SCAR=13.9
Pod documented
2181 14078 my ($self, $value) = @_;
2182 14078 ▶ return '' unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 14078 14078
2183  
2184 14078 my $raw = "$value";
2185 14078 $raw =~ s/^\s+//;
2186 14078 $raw =~ s/\s+$//;
2187 14078 ▶ return '' unless length $raw;
Branch: 1 branch
BranchTrueFalseTotal
unless length $raw 12634 1444 14078
2188  
2189 1444 my $id = lc($raw);
2190 1444 $id =~ s/\Alangertha::engine:://;
2191 1444 $id =~ s/\Alangerthax::engine:://;
2192  
2193 1444 my $ids = _discover_engine_ids();
2194 1444 ▶ return $id if $ids->{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $ids->{$id} 1441 3 1444
2195  
2196 3 my $known = join(', ', sort keys %$ids);
2197 3 croak "unknown engine '$raw' (expected one of: $known)";
2198 }
2199  
2200  
2201 1234 ▶sub record_usage {
Subroutine record_usage: called CC=50 SCAR=39.8
Pod documented
2202 1234 my ($self, %args) = @_;
2203  
2204 # Disabled fast path: with no sink at all, the event has nowhere to go, so
2205 # skip building it. record_usage runs once per forwarded request, and a
2206 # deployment that meters nothing should not pay for a normalized event it is
2207 # only going to throw away in _store_usage_event. (karr #15)
2208 1234 ▶ return { ok => 0, enabled => 0, error => 'usage_store not configured' }
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_has_usage_sink 29 1205 1234
2209 unless $self->_has_usage_sink;
2210  
2211 1205 ▶ my $metrics = ref($args{metrics}) eq 'HASH' ? $args{metrics} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $args{'metrics'} eq 'HASH' ? : 1139 66 1205
2212 1205 ▶ my $usage = ref($metrics->{usage}) eq 'HASH' ? $metrics->{usage} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $metrics->{'usage'} eq 'HASH' ? : 1138 67 1205
2213 my $tool_calls = ref($metrics->{tool_names}) eq 'ARRAY'
2214 696 ? scalar(@{$metrics->{tool_names}})
2215 1205 ▶ : _num($metrics->{tool_calls});
Branch: 1 branch
BranchTrueFalseTotal
ref $metrics->{'tool_names'} eq 'ARRAY' ? : 696 509 1205
2216 1205 ▶ my $input_tokens = _num($usage->{input}) || _num($usage->{prompt_tokens}) || _num($metrics->{input_tokens});
Condition100%6/6
_num($usage->{'input'}) || _num($usage->{'prompt_tokens'}) || _num($metrics->{'input_tokens'})
l!l&&r!l&&!r
72637496
_num($usage->{"input"}) or _num($usage->{"prompt_tokens"})
l!l&&r!l&&!r
6841133
MC/DC100%3/3
_num($usage->{'input'}) || _num($usage->{'prompt_tokens'}) || _num($metrics->{'input_tokens'})
_num($usage->{"input"}) _num($usage->{"prompt_tokens"}) _num($metrics->{'input_tokens'})
Truth table100%4/4
A or B || C
A= _num($usage->{"input"})B= _num($usage->{"prompt_tokens"})C= _num($metrics->{'input_tokens'})
ABCresult
1XX1
01X1
0011
0000
2217 1205 ▶ my $output_tokens = _num($usage->{output}) || _num($usage->{completion_tokens}) || _num($metrics->{output_tokens});
Condition100%6/6
_num($usage->{'output'}) || _num($usage->{'completion_tokens'}) || _num($metrics->{'output_tokens'})
l!l&&r!l&&!r
66521618
_num($usage->{"output"}) or _num($usage->{"completion_tokens"})
l!l&&r!l&&!r
6241139
MC/DC100%3/3
_num($usage->{'output'}) || _num($usage->{'completion_tokens'}) || _num($metrics->{'output_tokens'})
_num($usage->{"output"}) _num($usage->{"completion_tokens"}) _num($metrics->{'output_tokens'})
Truth table100%4/4
A or B || C
A= _num($usage->{"output"})B= _num($usage->{"completion_tokens"})C= _num($metrics->{'output_tokens'})
ABCresult
1XX1
01X1
0011
0000
2218 1205 ▶ my $total_tokens = _num($usage->{total}) || _num($metrics->{total_tokens}) || ($input_tokens + $output_tokens);
Condition100%6/6
_num($usage->{'total'}) || _num($metrics->{'total_tokens'}) || $input_tokens + $output_tokens
l!l&&r!l&&!r
7054496
_num($usage->{"total"}) or _num($metrics->{"total_tokens"})
l!l&&r!l&&!r
68637500
MC/DC100%3/3
_num($usage->{'total'}) || _num($metrics->{'total_tokens'}) || $input_tokens + $output_tokens
_num($usage->{"total"}) _num($metrics->{"total_tokens"}) $input_tokens + $output_tokens
Truth table100%4/4
A or B || C
A= _num($usage->{"total"})B= _num($metrics->{"total_tokens"})C= $input_tokens + $output_tokens
ABCresult
1XX1
01X1
0011
0000
2219 # Prompt-cache read count (k27). Read the same way as the token counts above: the normalized
2220 # name first, then the OpenAI wire spelling (nested under prompt_tokens_details on a real
2221 # OpenAI usage payload), then a flat cached_tokens some compatible servers use, then the
2222 # flattened metrics fallback. Pricing it is metrics.normalize's job (skeid #28): the cost
2223 # fields below arrive already priced.
2224 my $cached_tokens = _num($usage->{cached})
2225 || _num($usage->{cached_tokens})
2226 || _num(ref($usage->{prompt_tokens_details}) eq 'HASH' ? $usage->{prompt_tokens_details}{cached_tokens} : undef)
2227 1205 ▶ || _num($metrics->{cached_tokens});
Branch: 1 branch
BranchTrueFalseTotal
ref $usage->{'prompt_tokens_details'} eq 'HASH' ? : 4 1098 1102
Condition77%7/9
_num($usage->{'cached'}) || _num($usage->{'cached_tokens'}) || _num(ref $usage->{'prompt_tokens_details'} eq 'HASH' ? $usage->{'prompt_tokens_details'}{'cached_tokens'} : undef) || _num($metrics->{'cached_tokens'})
l!l&&r!l&&!r
10701098
_num($usage->{"cached"}) or _num($usage->{"cached_tokens"}) or _num(ref $usage->{"prompt_tokens_details"} eq "HASH" ? $usage->{"prompt_tokens_details"}{"cached_tokens"} : undef)
l!l&&r!l&&!r
10341098
_num($usage->{"cached"}) or _num($usage->{"cached_tokens"})
l!l&&r!l&&!r
10301102
MC/DC50%2/4
_num($usage->{'cached'}) || _num($usage->{'cached_tokens'}) || _num(ref $usage->{'prompt_tokens_details'} eq 'HASH' ? $usage->{'prompt_tokens_details'}{'cached_tokens'} : undef) || _num($metrics->{'cached_tokens'})
_num($usage->{"cached"}) _num($usage->{"cached_tokens"}) _num(ref $usage->{"prompt_tokens_details"} eq "HASH" ? $usage->{"prompt_tokens_details"}{"cached_tokens"} : undef) _num($metrics->{'cached_tokens'})
Truth table60%3/5
A or B or C || D
A= _num($usage->{"cached"})B= _num($usage->{"cached_tokens"})C= _num(ref $usage->{"prompt_tokens_details"} eq "HASH" ? $usage->{"prompt_tokens_details"}{"cached_tokens"} : undef)D= _num($metrics->{'cached_tokens'})
ABCDresult
1XXX1
01XX1
001X1
00011
00000
2228 # Prompt-cache write count (skeid #41), the count cost_cache_write_usd was priced from: the
2229 # normalized name, then the flat metrics value metrics.normalize or the proxy put there.
2230 my $cache_write_tokens = _num($usage->{cache_write})
2231 || _num($usage->{cache_write_tokens})
2232 1205 ▶ || _num($metrics->{cache_write_tokens});
Condition50%3/6
_num($usage->{'cache_write'}) || _num($usage->{'cache_write_tokens'}) || _num($metrics->{'cache_write_tokens'})
l!l&&r!l&&!r
0961109
_num($usage->{"cache_write"}) or _num($usage->{"cache_write_tokens"})
l!l&&r!l&&!r
001205
MC/DC33%1/3
_num($usage->{'cache_write'}) || _num($usage->{'cache_write_tokens'}) || _num($metrics->{'cache_write_tokens'})
_num($usage->{"cache_write"}) _num($usage->{"cache_write_tokens"}) _num($metrics->{'cache_write_tokens'})
Truth table50%2/4
A or B || C
A= _num($usage->{"cache_write"})B= _num($usage->{"cache_write_tokens"})C= _num($metrics->{'cache_write_tokens'})
ABCresult
1XX1
01X1
0011
0000
2233 1205 ▶ my $cost_input = _num($metrics->{cost_input_usd}) || _num($metrics->{input_cost_usd});
Condition66%2/3
_num($metrics->{'cost_input_usd'}) || _num($metrics->{'input_cost_usd'})
l!l&&r!l&&!r
01411064
MC/DC50%1/2
_num($metrics->{'cost_input_usd'}) || _num($metrics->{'input_cost_usd'})
_num($metrics->{'cost_input_usd'}) _num($metrics->{'input_cost_usd'})
Truth table66%2/3
A || B
A= _num($metrics->{'cost_input_usd'})B= _num($metrics->{'input_cost_usd'})
ABresult
1X1
011
000
2234 1205 ▶ my $cost_output = _num($metrics->{cost_output_usd}) || _num($metrics->{output_cost_usd});
Condition66%2/3
_num($metrics->{'cost_output_usd'}) || _num($metrics->{'output_cost_usd'})
l!l&&r!l&&!r
01211084
MC/DC50%1/2
_num($metrics->{'cost_output_usd'}) || _num($metrics->{'output_cost_usd'})
_num($metrics->{'cost_output_usd'}) _num($metrics->{'output_cost_usd'})
Truth table66%2/3
A || B
A= _num($metrics->{'cost_output_usd'})B= _num($metrics->{'output_cost_usd'})
ABresult
1X1
011
000
2235 1205 ▶ my $cost_total = _num($metrics->{cost_total_usd}) || _num($metrics->{total_cost_usd});
Condition100%3/3
_num($metrics->{'cost_total_usd'}) || _num($metrics->{'total_cost_usd'})
l!l&&r!l&&!r
11411063
MC/DC100%2/2
_num($metrics->{'cost_total_usd'}) || _num($metrics->{'total_cost_usd'})
_num($metrics->{'cost_total_usd'}) _num($metrics->{'total_cost_usd'})
Truth table100%3/3
A || B
A= _num($metrics->{'cost_total_usd'})B= _num($metrics->{'total_cost_usd'})
ABresult
1X1
011
000
2236 # Prompt-cache amounts (skeid #28), already part of cost_total. 0 when the rule had no cache
2237 # rate or the installed Langertha cannot price them -- the cached tokens are then in cost_input.
2238 1205 ▶ my $cost_cache_read = _num($metrics->{cost_cache_read_usd}) || _num($metrics->{cache_read_cost_usd});
Condition66%2/3
_num($metrics->{'cost_cache_read_usd'}) || _num($metrics->{'cache_read_cost_usd'})
l!l&&r!l&&!r
0551150
MC/DC50%1/2
_num($metrics->{'cost_cache_read_usd'}) || _num($metrics->{'cache_read_cost_usd'})
_num($metrics->{'cost_cache_read_usd'}) _num($metrics->{'cache_read_cost_usd'})
Truth table66%2/3
A || B
A= _num($metrics->{'cost_cache_read_usd'})B= _num($metrics->{'cache_read_cost_usd'})
ABresult
1X1
011
000
2239 1205 ▶ my $cost_cache_write = _num($metrics->{cost_cache_write_usd}) || _num($metrics->{cache_write_cost_usd});
Condition66%2/3
_num($metrics->{'cost_cache_write_usd'}) || _num($metrics->{'cache_write_cost_usd'})
l!l&&r!l&&!r
0541151
MC/DC50%1/2
_num($metrics->{'cost_cache_write_usd'}) || _num($metrics->{'cache_write_cost_usd'})
_num($metrics->{'cost_cache_write_usd'}) _num($metrics->{'cache_write_cost_usd'})
Truth table66%2/3
A || B
A= _num($metrics->{'cost_cache_write_usd'})B= _num($metrics->{'cache_write_cost_usd'})
ABresult
1X1
011
000
2240  
2241 my %event = (
2242 created_at => ($args{created_at} // _iso8601_now()),
2243 request_id => ($args{request_id} // ''),
2244 api_format => ($args{api_format} // ''),
2245 endpoint => ($args{endpoint} // ''),
2246 api_key_id => ($args{api_key_id} // ''),
2247 provider => ($args{provider} // ''),
2248 engine => ($args{engine} // ''),
2249 model => ($args{model} // ''),
2250 requested_model => ($args{requested_model} // $args{model} // ''),
2251 node_id => ($args{node_id} // ''),
2252 route_url => ($args{route_url} // ''),
2253 status_code => (_num($args{status_code}) || 0),
2254 ok => ($args{ok} ? 1 : 0),
2255 duration_ms => (_num($args{duration_ms}) || 0),
2256 input_tokens => $input_tokens,
2257 output_tokens => $output_tokens,
2258 total_tokens => $total_tokens,
2259 cached_tokens => $cached_tokens,
2260 cache_write_tokens => $cache_write_tokens,
2261 tool_calls => _num($tool_calls),
2262 cost_input_usd => $cost_input,
2263 cost_output_usd => $cost_output,
2264 cost_total_usd => $cost_total,
2265 cost_cache_read_usd => $cost_cache_read,
2266 cost_cache_write_usd => $cost_cache_write,
2267 error_type => ($args{error_type} // ''),
2268 1205 ▶ error_message => ($args{error_message} // ''),
Branch: 1 branch
BranchTrueFalseTotal
$args{'ok'} ? : 965 240 1205
Condition88%30/34
$args{"created_at"} // _iso8601_now()
l!l&&r!l&&!r
10961090
$args{"request_id"} // ""
l!l
1104101
$args{"api_format"} // ""
l!l
114263
$args{"endpoint"} // ""
l!l
110996
$args{"api_key_id"} // ""
l!l
119114
$args{"provider"} // ""
l!l
1067138
$args{"engine"} // ""
l!l
1067138
$args{"model"} // ""
l!l
12050
($args{"requested_model"} // $args{"model"}) // ""
l!l
12050
$args{"requested_model"} // $args{"model"}
l!l&&r!l&&!r
10731320
$args{"node_id"} // ""
l!l
1073132
$args{"route_url"} // ""
l!l
1066139
_num($args{'status_code'}) || 0
l!l
119411
_num($args{'duration_ms'}) || 0
l!l
1091114
$args{"error_type"} // ""
l!l
1066139
$args{"error_message"} // ""
l!l
1066139
MC/DC0%0/2
$args{"created_at"} // _iso8601_now()
$args{"created_at"} _iso8601_now()
MC/DC100%1/1
$args{"request_id"} // ""
$args{"request_id"}
MC/DC100%1/1
$args{"api_format"} // ""
$args{"api_format"}
MC/DC100%1/1
$args{"endpoint"} // ""
$args{"endpoint"}
MC/DC100%1/1
$args{"api_key_id"} // ""
$args{"api_key_id"}
MC/DC100%1/1
$args{"provider"} // ""
$args{"provider"}
MC/DC100%1/1
$args{"engine"} // ""
$args{"engine"}
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
MC/DC0%0/2
($args{"requested_model"} // $args{"model"}) // ""
$args{"requested_model"} $args{"model"}
MC/DC100%1/1
$args{"node_id"} // ""
$args{"node_id"}
MC/DC100%1/1
$args{"route_url"} // ""
$args{"route_url"}
MC/DC100%1/1
_num($args{'status_code'}) || 0
_num($args{'status_code'})
MC/DC100%1/1
_num($args{'duration_ms'}) || 0
_num($args{'duration_ms'})
MC/DC100%1/1
$args{"error_type"} // ""
$args{"error_type"}
MC/DC100%1/1
$args{"error_message"} // ""
$args{"error_message"}
Truth table66%2/3
A // B
A= $args{"created_at"}B= _iso8601_now()
ABresult
1X1
011
000
Truth table100%2/2
A
A= $args{"request_id"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"api_format"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"endpoint"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"api_key_id"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"provider"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
Truth table66%2/3
A // B
A= $args{"requested_model"}B= $args{"model"}
ABresult
1X1
011
000
Truth table100%2/2
A
A= $args{"node_id"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"route_url"}
Aresult
11
00
Truth table100%2/2
A
A= _num($args{'status_code'})
Aresult
11
00
Truth table100%2/2
A
A= _num($args{'duration_ms'})
Aresult
11
00
Truth table100%2/2
A
A= $args{"error_type"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"error_message"}
Aresult
11
00
2269 );
2270 # UTF-8 bytes of the content a streamed request relayed (skeid #36). Optional and additive: a
2271 # non-streamed event has no such key, which a store records as "not measured". An observation
2272 # beside the token counts -- never used to estimate or replace them.
2273 1205 ▶ $event{content_bytes} = _num($args{content_bytes}) if defined $args{content_bytes};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"content_bytes"} 241 964 1205
2274 # Seconds of audio an audio route's node reported (skeid k91, ADR 0021). Optional and additive
2275 # like content_bytes: absent means the node did not say, which is not a measured zero. Recorded
2276 # as reported, never priced here.
2277 1205 ▶ $event{audio_seconds} = _num($args{audio_seconds}) if defined $args{audio_seconds};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"audio_seconds"} 42 1163 1205
2278 # How many documents a rerank request carried (skeid k92, ADR 0021), counted off the request
2279 # the node answered. Optional and additive like the two above; recorded, never priced.
2280 1205 ▶ $event{documents} = _num($args{documents}) if defined $args{documents};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"documents"} 111 1094 1205
2281 # The pages a documents request converted (skeid k94, ADR 0028), read off json_content of the
2282 # answer when it carries one. Optional like audio_seconds: absent is not measured, never 0.
2283 1205 ▶ $event{pages} = _num($args{pages}) if defined $args{pages};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"pages"} 39 1166 1205
2284 # The usage contract (skeid k121), each optional like the ones above: how the answer ended
2285 # (stop, length, content_filter, tool_calls, error, other), the time to its first token in ms
2286 # (streams only), and the caller's correlation id. Absent is "not known", never a default.
2287 1205 for my $field (qw( finish_reason correlation_id )) {
2288 2410 ▶ $event{$field} = "$args{$field}" if defined($args{$field}) && !ref($args{$field});
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{$field} and not ref $args{$field} 707 1703 2410
Condition66%2/3
defined $args{$field} and not ref $args{$field}
!ll&&!rl&&r
17030707
MC/DC50%1/2
defined $args{$field} and not ref $args{$field}
defined $args{$field} not ref $args{$field}
Truth table66%2/3
A and not(B)
A= defined $args{$field}B= not ref $args{$field}
ABresult
0X0
100
111
2289 }
2290 1205 ▶ $event{ttft_ms} = _num($args{ttft_ms}) if defined $args{ttft_ms};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"ttft_ms"} 209 996 1205
2291 # The catch-all target a bent request was routed under (skeid k129, ADR 0033). Only a bent
2292 # request has it: an event without the key was not bent.
2293 $event{routed_model} = "$args{routed_model}"
2294 1205 ▶ if defined($args{routed_model}) && !ref($args{routed_model}) && length($args{routed_model});
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"routed_model"} and not ref $args{"routed_model"} and length $args{"routed_model"} 24 1181 1205
Condition66%4/6
defined $args{"routed_model"} and not ref $args{"routed_model"} and length $args{"routed_model"}
!ll&&!rl&&r
1181024
defined $args{"routed_model"} and not ref $args{"routed_model"}
!ll&&!rl&&r
1181024
MC/DC33%1/3
defined $args{"routed_model"} and not ref $args{"routed_model"} and length $args{"routed_model"}
defined $args{"routed_model"} not ref $args{"routed_model"} length $args{"routed_model"}
Truth table50%2/4
A and not(B) and C
A= defined $args{"routed_model"}B= not ref $args{"routed_model"}C= length $args{"routed_model"}
ABCresult
0XX0
10X0
1100
1111
2295  
2296 1205 return $self->_store_usage_event(\%event);
2297 }
2298  
2299 1201 ▶sub _store_usage_event {
Subroutine _store_usage_event: called CC=3 SCAR=11.0
2300 1201 my ($self, $event) = @_;
2301 1201 ▶ return $self->store_usage_event->($self, $event) if $self->has_store_usage_event;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_store_usage_event 1055 146 1201
2302 146 my $store = $self->_usage_store_obj;
2303 146 ▶ return { ok => 0, enabled => 0, error => 'usage_store not configured' } unless $store;
Branch: 1 branch
BranchTrueFalseTotal
unless $store 0 146 146
2304 146 return $store->store($event);
2305 }
2306  
2307 # A queued event the store could not write (skeid k78): through on_usage_lost when the
2308 # embedding application -- the proxy -- set it, else a warning. Never the DSN, never a key.
2309 1 ▶sub _usage_lost {
Subroutine _usage_lost: called CC=9 SCAR=41.1
2310 1 my ($self, $event, $err) = @_;
2311 1 ▶ return $self->on_usage_lost->($self, $event, $err) if $self->has_on_usage_lost;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_on_usage_lost 1 0 1
2312 0 my $cfg = $self->usage_store;
2313 warn 'skeid: usage event lost: request_id=' . ($event->{request_id} // '')
2314 . ' store=' . ((ref($cfg) eq 'HASH' && $cfg->{backend}) || 'custom')
2315 . ' api_key_id=' . ($event->{api_key_id} // '')
2316 . ' model=' . ($event->{model} // '')
2317 0 ▶ . ' status=' . ($event->{status_code} // 0)
Condition0%0/15
$event->{"request_id"} // ""
l!l
00
ref $cfg eq 'HASH' && $cfg->{'backend'} || 'custom'
l!l
00
ref $cfg eq "HASH" and $cfg->{"backend"}
!ll&&!rl&&r
000
$event->{"api_key_id"} // ""
l!l
00
$event->{"model"} // ""
l!l
00
$event->{"status_code"} // 0
l!l
00
$err // "unknown error"
l!l
00
MC/DC0%0/1
$event->{"request_id"} // ""
$event->{"request_id"}
MC/DC0%0/2
ref $cfg eq 'HASH' && $cfg->{'backend'} || 'custom'
ref $cfg eq "HASH" $cfg->{"backend"}
MC/DC0%0/1
$event->{"api_key_id"} // ""
$event->{"api_key_id"}
MC/DC0%0/1
$event->{"model"} // ""
$event->{"model"}
MC/DC0%0/1
$event->{"status_code"} // 0
$event->{"status_code"}
MC/DC0%0/1
$err // "unknown error"
$err
Truth table0%0/2
A
A= $event->{"request_id"}
Aresult
11
00
Truth table0%0/3
A and B
A= ref $cfg eq "HASH"B= $cfg->{"backend"}
ABresult
111
0X0
100
Truth table0%0/2
A
A= $event->{"api_key_id"}
Aresult
11
00
Truth table0%0/2
A
A= $event->{"model"}
Aresult
11
00
Truth table0%0/2
A
A= $event->{"status_code"}
Aresult
11
00
Truth table0%0/2
A
A= $err
Aresult
11
00
2318 . ': ' . ($err // 'unknown error') . "\n";
2319 0 return;
2320 }
2321  
2322  
2323  
2324 21 ▶sub purge_usage {
Subroutine purge_usage: called CC=7 SCAR=19.5
Pod documented
2325 21 my ($self, %args) = @_;
2326 21 my ($request, $error) = Langertha::Skeid::UsageStore->purge_request(\%args);
2327 21 ▶ return { ok => 0, error => $error } unless $request;
Branch: 1 branch
BranchTrueFalseTotal
unless $request 1 20 21
2328 20 my $store = $self->_usage_store_obj;
2329 20 ▶ return { ok => 0, error => 'no usage store is configured' } unless $store;
Branch: 1 branch
BranchTrueFalseTotal
unless $store 1 19 20
2330 19 ▶ return { ok => 0, error => 'the usage store ' . $store->backend . ' cannot purge' }
Branch: 1 branch
BranchTrueFalseTotal
unless $store->can("purge") 0 19 19
2331 unless $store->can('purge');
2332 19 my $result = $store->purge($request);
2333 19 ▶ $result = { ok => 0, error => 'the usage store answered nothing' } unless ref($result) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $result eq "HASH" 0 19 19
2334 return {
2335 %$result,
2336 backend => $store->backend,
2337 dry_run => $request->{dry_run},
2338 15 ▶ ($request->{api_key_ids} ? (api_key_ids => scalar @{$request->{api_key_ids}}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
defined $request->{'before'} ? : 4 15 19
2339 19 ▶ (defined($request->{before}) ? (before => $request->{before}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$request->{'api_key_ids'} ? : 15 4 19
2340 purged_at => _iso8601_now(),
2341 };
2342 }
2343  
2344  
2345 3 ▶sub usage_retention_before {
Subroutine usage_retention_before: called CC=3 SCAR=11.0
Pod documented
2346 3 my ($self) = @_;
2347 3 ▶ my $cfg = ref($self->usage_store) eq 'HASH' ? $self->usage_store : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $self->usage_store eq 'HASH' ? : 3 0 3
2348 3 ▶ my $days = $cfg->{retention_days} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $days = $cfg->{"retention_days"} or return undef 2 1 3
2349 2 return strftime('%Y-%m-%dT%H:%M:%SZ', gmtime(time - $days * 86400));
2350 }
2351  
2352 6 ▶sub flush_usage {
Subroutine flush_usage: called CC=3 SCAR=11.0
Pod documented
2353 6 my ($self) = @_;
2354 6 my $store = $self->_usage_store_obj;
2355 6 ▶ return { ok => 1, written => 0 } unless $store && $store->can('flush');
Branch: 1 branch
BranchTrueFalseTotal
unless $store and $store->can("flush") 4 2 6
Condition66%2/3
$store and $store->can("flush")
!ll&&!rl&&r
042
MC/DC50%1/2
$store and $store->can("flush")
$store $store->can("flush")
Truth table66%2/3
A and B
A= $storeB= $store->can("flush")
ABresult
0X0
100
111
2356 2 return $store->flush;
2357 }
2358  
2359 # True when a usage event has somewhere to go: a store_usage_event callback, a
2360 # configured usage store object, or a subclass that overrides _store_usage_event
2361 # (documented in README, exercised by t/14) -- the last is why this cannot be a
2362 # plain attribute check. record_usage consults this before building an event.
2363 1234 ▶sub _has_usage_sink {
Subroutine _has_usage_sink: called CC=5 SCAR=16.1
2364 1234 my ($self) = @_;
2365 1234 ▶ return 1 if $self->has_store_usage_event;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_store_usage_event 1055 179 1234
2366 179 ▶ return 1 if $self->_usage_store_obj;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_usage_store_obj 146 33 179
2367 33 my $impl = $self->can('_store_usage_event');
2368 33 ▶ return 1 if $impl && $impl != \&_store_usage_event;
Branch: 1 branch
BranchTrueFalseTotal
if $impl and $impl != \&Langertha::Skeid::_store_usage_event 4 29 33
Condition66%2/3
$impl and $impl != \&Langertha::Skeid::_store_usage_event
!ll&&!rl&&r
0294
MC/DC50%1/2
$impl and $impl != \&Langertha::Skeid::_store_usage_event
$impl $impl != \&Langertha::Skeid::_store_usage_event
Truth table66%2/3
A and B
A= $implB= $impl != \&Langertha::Skeid::_store_usage_event
ABresult
0X0
100
111
2369 29 return 0;
2370 }
2371  
2372  
2373 66 ▶sub usage_report {
Subroutine usage_report: called CC=9 SCAR=22.2
Pod documented
2374 66 my ($self, %args) = @_;
2375  
2376 66 my $limit = _num($args{limit});
2377 66 ▶ $limit = 20 if $limit < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $limit < 1 51 15 66
2378 66 ▶ $limit = 500 if $limit > 500;
Branch: 1 branch
BranchTrueFalseTotal
if $limit > 500 0 66 66
2379  
2380 66 my %filters;
2381 66 ▶ $filters{since} = $args{since} if defined $args{since} && length $args{since};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"since"} and length $args{"since"} 1 65 66
Condition66%2/3
defined $args{"since"} and length $args{"since"}
!ll&&!rl&&r
6501
MC/DC50%1/2
defined $args{"since"} and length $args{"since"}
defined $args{"since"} length $args{"since"}
Truth table66%2/3
A and B
A= defined $args{"since"}B= length $args{"since"}
ABresult
0X0
100
111
2382 66 ▶ $filters{api_key_id} = $args{api_key_id} if defined $args{api_key_id} && length $args{api_key_id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"api_key_id"} and length $args{"api_key_id"} 11 55 66
Condition66%2/3
defined $args{"api_key_id"} and length $args{"api_key_id"}
!ll&&!rl&&r
55011
MC/DC50%1/2
defined $args{"api_key_id"} and length $args{"api_key_id"}
defined $args{"api_key_id"} length $args{"api_key_id"}
Truth table66%2/3
A and B
A= defined $args{"api_key_id"}B= length $args{"api_key_id"}
ABresult
0X0
100
111
2383 66 ▶ $filters{model} = $args{model} if defined $args{model} && length $args{model};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"model"} and length $args{"model"} 2 64 66
Condition66%2/3
defined $args{"model"} and length $args{"model"}
!ll&&!rl&&r
6402
MC/DC50%1/2
defined $args{"model"} and length $args{"model"}
defined $args{"model"} length $args{"model"}
Truth table66%2/3
A and B
A= defined $args{"model"}B= length $args{"model"}
ABresult
0X0
100
111
2384 66 $filters{limit} = $limit;
2385  
2386 66 return $self->_query_usage_report(\%filters);
2387 }
2388  
2389 64 ▶sub _query_usage_report {
Subroutine _query_usage_report: called CC=3 SCAR=11.0
2390 64 my ($self, $filters) = @_;
2391 64 ▶ return $self->query_usage_report->($self, $filters) if $self->has_query_usage_report;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_query_usage_report 1 63 64
2392 63 my $store = $self->_usage_store_obj;
2393 63 ▶ return { ok => 0, enabled => 0, error => 'usage_store not configured' } unless $store;
Branch: 1 branch
BranchTrueFalseTotal
unless $store 1 62 63
2394 62 return $store->report($filters);
2395 }
2396 723 ▶sub _usage_object {
Subroutine _usage_object: called CC=4 SCAR=14.6
2397 723 my ($self, %args) = @_;
2398 723 ▶ return Langertha::Usage->from_hash($args{usage}) if ref($args{usage}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $args{"usage"} eq "HASH" 3 720 723
2399 720 ▶ return $args{usage} if ref($args{usage}) && $args{usage}->isa('Langertha::Usage');
Branch: 1 branch
BranchTrueFalseTotal
if ref $args{"usage"} and $args{"usage"}->isa("Langertha::Usage") 0 720 720
Condition33%1/3
ref $args{"usage"} and $args{"usage"}->isa("Langertha::Usage")
!ll&&!rl&&r
72000
MC/DC0%0/2
ref $args{"usage"} and $args{"usage"}->isa("Langertha::Usage")
ref $args{"usage"} $args{"usage"}->isa("Langertha::Usage")
Truth table33%1/3
A and B
A= ref $args{"usage"}B= $args{"usage"}->isa("Langertha::Usage")
ABresult
0X0
100
111
2400 720 return Langertha::Usage->from_response($args{response});
2401 }
2402  
2403  
2404 1 ▶sub estimate_cost {
Subroutine estimate_cost: called CC=3 SCAR=11.6
Pod documented
2405 1 my ($self, %args) = @_;
2406 1 ▶ my $model = $args{model} // '';
Condition50%1/2
$args{"model"} // ""
l!l
10
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
2407 1 my $usage = $self->_usage_object(%args);
2408 1 ▶ my $rule = $args{pricing} || $self->pricing_for_model($model);
Condition33%1/3
$args{'pricing'} || $self->pricing_for_model($model)
l!l&&r!l&&!r
010
MC/DC0%0/2
$args{'pricing'} || $self->pricing_for_model($model)
$args{'pricing'} $self->pricing_for_model($model)
Truth table33%1/3
A || B
A= $args{'pricing'}B= $self->pricing_for_model($model)
ABresult
1X1
011
000
2409 1 my $pricing = Langertha::Pricing->new( default_rule => $rule );
2410 1 return $pricing->cost_for( $usage, undef )->to_hash;
2411 }
2412  
2413  
2414 722 ▶sub normalize_metrics {
Subroutine normalize_metrics: called CC=14 SCAR=28.4
Pod documented
2415 722 my ($self, %args) = @_;
2416 722 ▶ my $model = $args{model} // '';
Condition50%1/2
$args{"model"} // ""
l!l
7220
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
2417 722 my $usage = $self->_usage_object(%args);
2418 722 ▶ my $rule = $args{pricing} || $self->pricing_for_model($model);
Condition33%1/3
$args{'pricing'} || $self->pricing_for_model($model)
l!l&&r!l&&!r
07220
MC/DC0%0/2
$args{'pricing'} || $self->pricing_for_model($model)
$args{'pricing'} $self->pricing_for_model($model)
Truth table33%1/3
A || B
A= $args{'pricing'}B= $self->pricing_for_model($model)
ABresult
1X1
011
000
2419 722 my $pricing = Langertha::Pricing->new( default_rule => $rule );
2420 722 my $cost = $pricing->cost_for( $usage, undef );
2421  
2422 722 my @names;
2423 722 ▶ for my $tc ( @{ $args{tool_calls} || [] } ) {
Condition50%1/2
$args{'tool_calls'} || []
l!l
7220
MC/DC0%0/1
$args{'tool_calls'} || []
$args{'tool_calls'}
Truth table50%1/2
A
A= $args{'tool_calls'}
Aresult
11
00
2424 5 ▶ next unless ref($tc) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tc eq "HASH" 0 5 5
2425 5 ▶ my $n = $tc->{name} // ( ref( $tc->{function} ) eq 'HASH' ? $tc->{function}{name} : undef );
Branch: 1 branch
BranchTrueFalseTotal
ref $tc->{'function'} eq 'HASH' ? : 2 0 2
Condition66%2/3
$tc->{"name"} // (ref $tc->{"function"} eq "HASH" ? $tc->{"function"}{"name"} : undef)
l!l&&r!l&&!r
320
MC/DC0%0/2
$tc->{"name"} // (ref $tc->{"function"} eq "HASH" ? $tc->{"function"}{"name"} : undef)
$tc->{"name"} (ref $tc->{"function"} eq "HASH" ? $tc->{"function"}{"name"} : undef)
Truth table66%2/3
A // B
A= $tc->{"name"}B= (ref $tc->{"function"} eq "HASH" ? $tc->{"function"}{"name"} : undef)
ABresult
1X1
011
000
2426 5 ▶ push @names, $n if defined $n && length $n;
Branch: 1 branch
BranchTrueFalseTotal
if defined $n and length $n 5 0 5
Condition33%1/3
defined $n and length $n
!ll&&!rl&&r
005
MC/DC0%0/2
defined $n and length $n
defined $n length $n
Truth table33%1/3
A and B
A= defined $nB= length $n
ABresult
0X0
100
111
2427 }
2428  
2429 my $record = Langertha::UsageRecord->new(
2430 usage => $usage,
2431 cost => $cost,
2432 provider => $args{provider},
2433 engine => $args{engine},
2434 model => $model,
2435 route => $args{route},
2436 duration_ms => $args{duration_ms},
2437 started_at => $args{started_at},
2438 finished_at => $args{finished_at},
2439 tool_calls => scalar(@names),
2440 tool_names => \@names,
2441 pricing_version => $args{pricing_version},
2442 722 );
2443 722 my $normalized = $record->to_hash;
2444 # The cache read count as the Usage read it, from whichever wire spelling the upstream used
2445 # (skeid #28) -- so the event's cached_tokens is the count its cache cost was priced from.
2446 # Langertha 0.503's Usage has no such count; there the caller reads it off the raw payload.
2447 722 ▶ if ($usage->can('cached_tokens') && defined(my $cached = $usage->cached_tokens)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($usage->can("cached_tokens") and defined(my $cached = $usage->cached_tokens)) 102 620 722
Condition66%2/3
$usage->can("cached_tokens") and defined(my $cached = $usage->cached_tokens)
!ll&&!rl&&r
0620102
MC/DC50%1/2
$usage->can("cached_tokens") and defined(my $cached = $usage->cached_tokens)
$usage->can("cached_tokens") defined(my $cached = $usage->cached_tokens)
Truth table66%2/3
A and B
A= $usage->can("cached_tokens")B= defined(my $cached = $usage->cached_tokens)
ABresult
0X0
100
111
2448 102 $normalized->{cached_tokens} = $cached;
2449 }
2450 # Likewise the cache write count, the one cost_cache_write_usd was priced from (skeid #41).
2451 722 ▶ if ($usage->can('cache_write_tokens') && defined(my $written = $usage->cache_write_tokens)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($usage->can("cache_write_tokens") and defined(my $written = $usage->cache_write_tokens)) 96 626 722
Condition66%2/3
$usage->can("cache_write_tokens") and defined(my $written = $usage->cache_write_tokens)
!ll&&!rl&&r
062696
MC/DC50%1/2
$usage->can("cache_write_tokens") and defined(my $written = $usage->cache_write_tokens)
$usage->can("cache_write_tokens") defined(my $written = $usage->cache_write_tokens)
Truth table66%2/3
A and B
A= $usage->can("cache_write_tokens")B= defined(my $written = $usage->cache_write_tokens)
ABresult
0X0
100
111
2452 96 $normalized->{cache_write_tokens} = $written;
2453 }
2454 722 return $normalized;
2455 }
2456  
2457 5415 ▶sub _route_key {
Subroutine _route_key: called CC=8 SCAR=20.8
2458 5415 my ($self, %args) = @_;
2459 5415 ▶ my $model = $args{model} // '';
Condition50%1/2
$args{"model"} // ""
l!l
54150
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
2460 5415 ▶ my $engine = $self->normalize_engine_id($args{engine} // '');
Condition100%2/2
$args{"engine"} // ""
l!l
40861329
MC/DC100%1/1
$args{"engine"} // ""
$args{"engine"}
Truth table100%2/2
A
A= $args{"engine"}
Aresult
11
00
2461 5415 my $tags = join(',', @{$self->normalize_tags($args{tags})});
2462 5415 my $deny = join(',', @{$self->normalize_tags($args{deny_tags})});
2463 # Tags belong in the key: two selections over the same model address different node sets, and
2464 # a shared round-robin cursor across different-sized sets picks the wrong node. Denied tags
2465 # too -- a key that may not use cloud addresses a smaller set than one that may.
2466 # A kind other than chat addresses a different set of nodes under the same name (a chat model
2467 # may be called `documents` too), so it is part of the key like the tags are.
2468 5415 my $kind = $self->_selector_kind(%args);
2469 5415 ▶ my @kind = length($kind) ? ("=$kind") : ();
Branch: 1 branch
BranchTrueFalseTotal
length $kind ? : 202 5213 5415
2470 5415 ▶ return join('|', $model, $engine, $tags, ($deny ? "-$deny" : ()), @kind)
Branch: 2 branches
BranchTrueFalseTotal
if length $tags or length $deny or @kind 787 4628 5415
$deny ? : 347 440 787
Condition100%6/6
length $tags or length $deny or @kind
l!l&&r!l&&!r
5991884628
length $tags or length $deny
l!l&&r!l&&!r
2943054816
MC/DC100%3/3
length $tags or length $deny or @kind
length $tags length $deny @kind
Truth table100%4/4
A or B or C
A= length $tagsB= length $denyC= @kind
ABCresult
1XX1
01X1
0011
0000
2471 if length($tags) || length($deny) || @kind;
2472 4628 return join('|', $model, $engine);
2473 }
2474  
2475 # The kind of node a selection is over: '' for chat, which is what every selection was before the
2476 # option, else a kind of Protocol::Documents.
2477 8203 ▶sub _selector_kind {
Subroutine _selector_kind: called CC=4 SCAR=13.9
2478 8203 my ($self, %args) = @_;
2479 8203 my $kind = $args{kind};
2480 8203 ▶ return '' unless defined($kind) && length($kind) && $kind ne 'chat';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $kind and length $kind and $kind ne "chat" 7915 288 8203
Condition83%5/6
defined $kind and length $kind and $kind ne "chat"
!ll&&!rl&&r
79150288
defined $kind and length $kind
!ll&&!rl&&r
786550288
MC/DC66%2/3
defined $kind and length $kind and $kind ne "chat"
defined $kind length $kind $kind ne "chat"
Truth table75%3/4
A and B and C
A= defined $kindB= length $kindC= $kind ne "chat"
ABCresult
0XX0
10X0
1100
1111
2481 288 return $kind;
2482 }
2483  
2484 4475 ▶sub _node_can_take {
Subroutine _node_can_take: called CC=8 SCAR=21.7
2485 4475 my ($self, $node) = @_;
2486 4475 ▶ return 0 unless ref($node) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $node eq "HASH" 0 4475 4475
2487 4475 ▶ return 0 unless ($node->{healthy} // 0);
Branch: 1 branch
BranchTrueFalseTotal
unless $node->{"healthy"} // 0 0 4475 4475
Condition50%1/2
$node->{"healthy"} // 0
l!l
44750
MC/DC0%0/1
$node->{"healthy"} // 0
$node->{"healthy"}
Truth table50%1/2
A
A= $node->{"healthy"}
Aresult
11
00
2488 4475 ▶ my $id = $node->{id} // '';
Condition50%1/2
$node->{"id"} // ""
l!l
44750
MC/DC0%0/1
$node->{"id"} // ""
$node->{"id"}
Truth table50%1/2
A
A= $node->{"id"}
Aresult
11
00
2489 4475 ▶ return 0 unless length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless length $id 0 4475 4475
2490  
2491 # Both have to agree, and they are not symmetric: max_conns is this process's own guardrail
2492 # and always applies, while a probe may only narrow what it allows. A probe that could widen
2493 # it would turn a stale or broken reading into an overload -- and for a rented node,
2494 # max_conns is a spend limit, not a capacity estimate (ADR 0009).
2495 4475 ▶ return 0 unless $self->_inflight_allows($node);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_inflight_allows($node) 549 3926 4475
2496 3926 ▶ return 0 unless $self->_capacity_allows($id);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_capacity_allows($id) 151 3775 3926
2497 3775 return 1;
2498 }
2499  
2500 4475 ▶sub _inflight_allows {
Subroutine _inflight_allows: called CC=5 SCAR=16.1
2501 4475 my ($self, $node) = @_;
2502 4475 my $max = $self->worker_max_conns($node);
2503 4475 ▶ return 1 if $max <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $max <= 0 668 3807 4475
2504 3807 ▶ return (0 + ($self->_inflight->{$node->{id} // ''} // 0)) < $max ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
0 + ($self->_inflight->{$node->{'id'} // ''} // 0) < $max ? : 3258 549 3807
Condition75%3/4
$self->_inflight->{$node->{"id"} // ""} // 0
l!l
22291578
$node->{"id"} // ""
l!l
38070
MC/DC100%1/1
$self->_inflight->{$node->{"id"} // ""} // 0
$self->_inflight->{$node->{"id"} // ""}
MC/DC0%0/1
$node->{"id"} // ""
$node->{"id"}
Truth table100%2/2
A
A= $self->_inflight->{$node->{"id"} // ""}
Aresult
11
00
Truth table50%1/2
A
A= $node->{"id"}
Aresult
11
00
2505 }
2506  
2507  
2508 4567 ▶sub worker_max_conns {
Subroutine worker_max_conns: called CC=6 SCAR=17.9
Pod documented
2509 4567 my ($self, $node) = @_;
2510 4567 ▶ my $max = 0 + ((ref($node) eq 'HASH' ? $node->{max_conns} : $node) // 0);
Branch: 1 branch
BranchTrueFalseTotal
ref $node eq 'HASH' ? : 4567 0 4567
Condition100%2/2
(ref $node eq "HASH" ? $node->{"max_conns"} : $node) // 0
l!l
45661
MC/DC100%1/1
(ref $node eq "HASH" ? $node->{"max_conns"} : $node) // 0
(ref $node eq "HASH" ? $node->{"max_conns"} : $node)
Truth table100%2/2
A
A= (ref $node eq "HASH" ? $node->{"max_conns"} : $node)
Aresult
11
00
2511 4567 ▶ return 0 if $max <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $max <= 0 670 3897 4567
2512  
2513 3897 my $divisor = $self->_admission_divisor;
2514 3897 ▶ return $max if $divisor <= 1;
Branch: 1 branch
BranchTrueFalseTotal
if $divisor <= 1 3861 36 3897
2515  
2516 36 my $share = int($max / $divisor);
2517 36 ▶ return $share > 0 ? $share : 1;
Branch: 1 branch
BranchTrueFalseTotal
$share > 0 ? : 34 2 36
2518 }
2519  
2520 # How many processes across the whole deployment share one node's max_conns: the prefork workers
2521 # of this process (worker_count) times the separate Skeid frontends in front of the node
2522 # (frontend_count). max_conns is partitioned across frontends first and then across workers, but
2523 # integer division composes -- floor(floor(max/F)/N) == floor(max/(F*N)) -- so the product is
2524 # the only number admission needs (ADR 0012).
2525 3982 ▶sub _admission_divisor {
Subroutine _admission_divisor: called CC=5 SCAR=17.2
2526 3982 my ($self) = @_;
2527 3982 ▶ my $workers = 0 + ($self->worker_count // 1);
Condition50%1/2
$self->worker_count // 1
l!l
39820
MC/DC0%0/1
$self->worker_count // 1
$self->worker_count
Truth table50%1/2
A
A= $self->worker_count
Aresult
11
00
2528 3982 ▶ my $frontends = 0 + ($self->frontend_count // 1);
Condition50%1/2
$self->frontend_count // 1
l!l
39820
MC/DC0%0/1
$self->frontend_count // 1
$self->frontend_count
Truth table50%1/2
A
A= $self->frontend_count
Aresult
11
00
2529 3982 ▶ $workers = 1 if $workers < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $workers < 1 0 3982 3982
2530 3982 ▶ $frontends = 1 if $frontends < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $frontends < 1 0 3982 3982
2531 3982 return $workers * $frontends;
2532 }
2533  
2534  
2535 6 ▶sub worker_share_warnings {
Subroutine worker_share_warnings: called CC=14 SCAR=26.8
Pod documented
2536 6 my ($self) = @_;
2537 6 ▶ my $workers = 0 + ($self->worker_count // 1);
Condition50%1/2
$self->worker_count // 1
l!l
60
MC/DC0%0/1
$self->worker_count // 1
$self->worker_count
Truth table50%1/2
A
A= $self->worker_count
Aresult
11
00
2538 6 ▶ my $frontends = 0 + ($self->frontend_count // 1);
Condition50%1/2
$self->frontend_count // 1
l!l
60
MC/DC0%0/1
$self->frontend_count // 1
$self->frontend_count
Truth table50%1/2
A
A= $self->frontend_count
Aresult
11
00
2539 6 ▶ $workers = 1 if $workers < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $workers < 1 0 6 6
2540 6 ▶ $frontends = 1 if $frontends < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $frontends < 1 0 6 6
2541 6 my $divisor = $workers * $frontends;
2542 6 ▶ return [] if $divisor <= 1;
Branch: 1 branch
BranchTrueFalseTotal
if $divisor <= 1 1 5 6
2543  
2544 # Name the axes that are actually in play, and the matching fix: the operator can only shed
2545 # what they configured. With both dividing, "worker" alone would misname where the surplus
2546 # comes from.
2547 5 my ($split, $fix);
2548 5 ▶ if ($frontends > 1 && $workers > 1) {
Branch: 2 branches
BranchTrueFalseTotal
if ($frontends > 1 and $workers > 1) { } 1 4 5
elsif ($frontends > 1) { } 2 2 4
Condition100%3/3
$frontends > 1 and $workers > 1
!ll&&!rl&&r
221
MC/DC100%2/2
$frontends > 1 and $workers > 1
$frontends > 1 $workers > 1
Truth table100%3/3
A and B
A= $frontends > 1B= $workers > 1
ABresult
0X0
100
111
2549 1 $split = sprintf('%d frontends x %d workers = %d processes', $frontends, $workers, $divisor);
2550 1 $fix = 'fewer frontends or workers, or raise max_conns';
2551 } elsif ($frontends > 1) {
2552 2 $split = sprintf('%d frontends', $frontends);
2553 2 $fix = 'fewer frontends or raise max_conns';
2554 } else {
2555 2 $split = sprintf('%d workers', $workers);
2556 2 $fix = 'fewer workers or raise max_conns';
2557 }
2558  
2559 5 my @warnings;
2560 5 for my $node (@{$self->nodes}) {
2561 5 ▶ my $max = 0 + ($node->{max_conns} // 0);
Condition50%1/2
$node->{"max_conns"} // 0
l!l
50
MC/DC0%0/1
$node->{"max_conns"} // 0
$node->{"max_conns"}
Truth table50%1/2
A
A= $node->{"max_conns"}
Aresult
11
00
2562 5 ▶ next if $max <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $max <= 0 0 5 5
2563 5 ▶ next if $max >= $divisor;
Branch: 1 branch
BranchTrueFalseTotal
if $max >= $divisor 2 3 5
2564 push @warnings, sprintf(
2565 "node '%s': max_conns %d cannot be split across %s; each process will admit 1, "
2566 . "so the node may see up to %d concurrent requests. Use %s.",
2567 3 ▶ ($node->{id} // '?'), $max, $split, $divisor, $fix,
Condition50%1/2
$node->{"id"} // "?"
l!l
30
MC/DC0%0/1
$node->{"id"} // "?"
$node->{"id"}
Truth table50%1/2
A
A= $node->{"id"}
Aresult
11
00
2568 );
2569 }
2570 5 return \@warnings;
2571 }
2572  
2573 # What a probe says about a node, if anything current. Unknown is a valid answer and means
2574 # "inflight decides" -- which is the entire behaviour of a deployment that configures no probes.
2575 3928 ▶sub _capacity_allows {
Subroutine _capacity_allows: called CC=8 SCAR=21.3
2576 3928 my ($self, $node_id) = @_;
2577 3928 ▶ my $reading = $self->capacity_reading($node_id) or return 1;
Branch: 1 branch
BranchTrueFalseTotal
my $reading = $self->capacity_reading($node_id) or return 1 197 3731 3928
2578  
2579 # A provider that told us to come back later is not busy in the inflight sense: no request of
2580 # ours is outstanding, and admitting one would just buy another 429.
2581 197 ▶ return 0 if $reading->{retry_after} && time < $reading->{retry_after};
Branch: 1 branch
BranchTrueFalseTotal
if $reading->{"retry_after"} and time < $reading->{"retry_after"} 37 160 197
Condition66%2/3
$reading->{"retry_after"} and time < $reading->{"retry_after"}
!ll&&!rl&&r
160037
MC/DC50%1/2
$reading->{"retry_after"} and time < $reading->{"retry_after"}
$reading->{"retry_after"} time < $reading->{"retry_after"}
Truth table66%2/3
A and B
A= $reading->{"retry_after"}B= time < $reading->{"retry_after"}
ABresult
0X0
100
111
2582  
2583 160 ▶ my $limit = 0 + ($reading->{limit} // 0);
Condition50%1/2
$reading->{"limit"} // 0
l!l
1600
MC/DC0%0/1
$reading->{"limit"} // 0
$reading->{"limit"}
Truth table50%1/2
A
A= $reading->{"limit"}
Aresult
11
00
2584 160 ▶ return 1 if $limit <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $limit <= 0 0 160 160
2585 160 ▶ return (0 + ($reading->{used} // 0)) < $limit ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
0 + ($reading->{'used'} // 0) < $limit ? : 45 115 160
Condition50%1/2
$reading->{"used"} // 0
l!l
1600
MC/DC0%0/1
$reading->{"used"} // 0
$reading->{"used"}
Truth table50%1/2
A
A= $reading->{"used"}
Aresult
11
00
2586 }
2587  
2588 1563 ▶sub _node_has_tags {
Subroutine _node_has_tags: called CC=6 SCAR=18.0
2589 1563 my ($self, $node, $tags) = @_;
2590 1563 ▶ return 1 unless $tags && @$tags;
Branch: 1 branch
BranchTrueFalseTotal
unless $tags and @$tags 1438 125 1563
Condition66%2/3
$tags and @$tags
!ll&&!rl&&r
01438125
MC/DC50%1/2
$tags and @$tags
$tags @$tags
Truth table66%2/3
A and B
A= $tagsB= @$tags
ABresult
0X0
100
111
2591 125 ▶ my %have = map { $_ => 1 } @{$node->{tags} || []};
Condition50%1/2
$node->{'tags'} || []
l!l
1250
MC/DC0%0/1
$node->{'tags'} || []
$node->{'tags'}
Truth table50%1/2
A
A= $node->{'tags'}
Aresult
11
00
2592 125 for my $tag (@$tags) {
2593 127 ▶ return 0 unless $have{$tag};
Branch: 1 branch
BranchTrueFalseTotal
unless $have{$tag} 68 59 127
2594 }
2595 57 return 1;
2596 }
2597  
2598 # The deny side is ANY, not ALL: one forbidden tag on a node is enough to rule it out. A policy
2599 # that denies "cloud" must exclude a node tagged [cloud, groq] without having to name groq too.
2600 1572 ▶sub _node_has_any_tag {
Subroutine _node_has_any_tag: called CC=6 SCAR=18.0
2601 1572 my ($self, $node, $tags) = @_;
2602 1572 ▶ return 0 unless $tags && @$tags;
Branch: 1 branch
BranchTrueFalseTotal
unless $tags and @$tags 1519 53 1572
Condition66%2/3
$tags and @$tags
!ll&&!rl&&r
0151953
MC/DC50%1/2
$tags and @$tags
$tags @$tags
Truth table66%2/3
A and B
A= $tagsB= @$tags
ABresult
0X0
100
111
2603 53 ▶ my %have = map { $_ => 1 } @{$node->{tags} || []};
Condition50%1/2
$node->{'tags'} || []
l!l
530
MC/DC0%0/1
$node->{'tags'} || []
$node->{'tags'}
Truth table50%1/2
A
A= $node->{'tags'}
Aresult
11
00
2604 53 for my $tag (@$tags) {
2605 53 ▶ return 1 if $have{$tag};
Branch: 1 branch
BranchTrueFalseTotal
if $have{$tag} 12 41 53
2606 }
2607 41 return 0;
2608 }
2609  
2610 # The selection cache includes negative requested models, and requested models are client input.
2611 # Keep a small fixed working set rather than turning every spelling ever seen into process-lifetime
2612 # state. FIFO makes eviction deterministic; an evicted route's cursor is removed with it, so that
2613 # route restarts weighted fairness if it is requested again.
2614 127 my $ROUTE_CACHE_MAX_ENTRIES = 256;
2615  
2616 # Everything derived from the inventory -- which nodes are eligible, their round-robin order
2617 # and their weights -- is computed once per selection and reused until the inventory changes.
2618 # Only admission stays per request, because inflight is the one part that moves between two
2619 # requests to the same selection.
2620 3624 ▶sub _route_entry {
Subroutine _route_entry: called CC=31 SCAR=36.2
2621 3624 my ($self, %args) = @_;
2622 3624 my $cache = $self->_route_cache;
2623 3624 ▶ if (($cache->{generation} // -1) != $self->_inventory_generation) {
Branch: 1 branch
BranchTrueFalseTotal
if (($cache->{"generation"} // -1) != $self->_inventory_generation) 521 3103 3624
Condition50%1/2
$cache->{"generation"} // -1
l!l
36240
MC/DC0%0/1
$cache->{"generation"} // -1
$cache->{"generation"}
Truth table50%1/2
A
A= $cache->{"generation"}
Aresult
11
00
2624 521 $cache = { generation => $self->_inventory_generation, entries => {}, order => [] };
2625 521 $self->_route_cache($cache);
2626 }
2627  
2628 3624 my $key = $self->_route_key(%args);
2629 3624 my $entry = $cache->{entries}{$key};
2630 3624 ▶ return $entry if $entry;
Branch: 1 branch
BranchTrueFalseTotal
if $entry 2206 1418 3624
2631  
2632 1418 my $model = $args{model};
2633 1418 ▶ my $engine = $self->normalize_engine_id($args{engine} // '');
Condition100%2/2
$args{"engine"} // ""
l!l
574844
MC/DC100%1/1
$args{"engine"} // ""
$args{"engine"}
Truth table100%2/2
A
A= $args{"engine"}
Aresult
11
00
2634 1418 my $tags = $self->normalize_tags($args{tags});
2635 1418 my $deny = $self->normalize_tags($args{deny_tags});
2636  
2637 # Chat and documents nodes are never each other's: a documents node carries no model name
2638 # Skeid reads, so a chat selection must not take it for one that serves any model, and a
2639 # documents selection takes the nodes of its kind whatever they are called (ADR 0028).
2640 1418 my $kind = $self->_selector_kind(%args);
2641  
2642 my @nodes = grep {
2643 (($_->{kind} // '') eq $kind)
2644 && (length($kind) || !defined($model) || !length($model) || !defined($_->{model}) || !length($_->{model}) || $_->{model} eq $model)
2645 && (!defined($engine) || !length($engine) || !defined($_->{engine}) || !length($_->{engine}) || $_->{engine} eq $engine)
2646 2835 ▶ && (($_->{healthy} // 0) ? 1 : 0)
Branch: 1 branch
BranchTrueFalseTotal
$_->{'healthy'} // 0 ? : 1451 25 1476
Condition71%33/46
($_->{'kind'} // '') eq $kind && (length $kind || !defined($model) || !length($model) || !defined($_->{'model'}) || !length($_->{'model'}) || $_->{'model'} eq $model) && (!(defined $engine && length $engine && defined $_->{'engine'} && length $_->{'engine'}) || $_->{'engine'} eq $engine) && ($_->{'healthy'} // 0 ? 1 : 0) && $self->_node_has_tags($_, $tags) && !$self->_node_has_any_tag($_, $deny)
!ll&&!rl&&r
142571403
($_->{"kind"} // "") eq $kind and length $kind || !defined($model) || !length($model) || !defined($_->{"model"}) || !length($_->{"model"}) || $_->{"model"} eq $model and !(defined $engine && length $engine && defined $_->{"engine"} && length $_->{"engine"}) || $_->{"engine"} eq $engine and $_->{"healthy"} // 0 ? 1 : 0 and $self->_node_has_tags($_, $tags)
!ll&&!rl&&r
1384411410
($_->{"kind"} // "") eq $kind and length $kind || !defined($model) || !length($model) || !defined($_->{"model"}) || !length($_->{"model"}) || $_->{"model"} eq $model and !(defined $engine && length $engine && defined $_->{"engine"} && length $_->{"engine"}) || $_->{"engine"} eq $engine and $_->{"healthy"} // 0 ? 1 : 0
!ll&&!rl&&r
1359251451
($_->{"kind"} // "") eq $kind and length $kind || !defined($model) || !length($model) || !defined($_->{"model"}) || !length($_->{"model"}) || $_->{"model"} eq $model and !(defined $engine && length $engine && defined $_->{"engine"} && length $_->{"engine"}) || $_->{"engine"} eq $engine
!ll&&!rl&&r
135901476
($_->{"kind"} // "") eq $kind and length $kind || !defined($model) || !length($model) || !defined($_->{"model"}) || !length($_->{"model"}) || $_->{"model"} eq $model
!ll&&!rl&&r
1113481476
$_->{"kind"} // ""
l!l
392796
length $kind or not defined $model or not length $model or not defined $_->{"model"} or not length $_->{"model"} or $_->{"model"} eq $model
l!l&&r!l&&!r
8426341348
length $kind or not defined $model or not length $model or not defined $_->{"model"} or not length $_->{"model"}
l!l&&r!l&&!r
338091982
length $kind or not defined $model or not length $model or not defined $_->{"model"}
l!l&&r!l&&!r
3302791
length $kind or not defined $model or not length $model
l!l&&r!l&&!r
3302791
length $kind or not defined $model
l!l&&r!l&&!r
3302791
not defined $engine && length $engine && defined $_->{"engine"} && length $_->{"engine"} or $_->{"engine"} eq $engine
l!l&&r!l&&!r
147600
defined $engine && length $engine && defined $_->{'engine'} && length $_->{'engine'}
!ll&&!rl&&r
147600
defined $engine and length $engine and defined $_->{"engine"}
!ll&&!rl&&r
147600
defined $engine and length $engine
!ll&&!rl&&r
014760
$_->{"healthy"} // 0
l!l
14760
MC/DC20%3/15
($_->{'kind'} // '') eq $kind && (length $kind || !defined($model) || !length($model) || !defined($_->{'model'}) || !length($_->{'model'}) || $_->{'model'} eq $model) && (!(defined $engine && length $engine && defined $_->{'engine'} && length $_->{'engine'}) || $_->{'engine'} eq $engine) && ($_->{'healthy'} // 0 ? 1 : 0) && $self->_node_has_tags($_, $tags) && !$self->_node_has_any_tag($_, $deny)
$_->{"kind"} length $kind not defined $model not length $model not defined $_->{"model"} not length $_->{"model"} $_->{"model"} eq $model defined $engine length $engine defined $_->{"engine"} length $_->{'engine'} $_->{"engine"} eq $engine $_->{"healthy"} $self->_node_has_tags($_, $tags) !$self->_node_has_any_tag($_, $deny)
Truth table3%4/128
A and B or not(C) or not(D) or not(E) or not(F) or G and not(H and I and J && K) or L and M and N && not(O)
A= $_->{"kind"}B= length $kindC= not defined $modelD= not length $modelE= not defined $_->{"model"}F= not length $_->{"model"}G= $_->{"model"} eq $modelH= defined $engineI= length $engineJ= defined $_->{"engine"}K= length $_->{'engine'}L= $_->{"engine"} eq $engineM= $_->{"healthy"}N= $self->_node_has_tags($_, $tags)O= !$self->_node_has_any_tag($_, $deny)
ABCDEFGHIJKLMNOresult
0XXXXXXXXXXXXXX0
1000000XXXXXXXX0
11XXXXX11110XXX0
101XXXX11110XXX0
1001XXX11110XXX0
10001XX11110XXX0
100001X11110XXX0
100000111110XXX0
11XXXXX0XXXX0XX0
11XXXXX10XXX0XX0
11XXXXX110XX0XX0
11XXXXX1110X0XX0
11XXXXX111110XX0
101XXXX0XXXX0XX0
101XXXX10XXX0XX0
101XXXX110XX0XX0
101XXXX1110X0XX0
101XXXX111110XX0
1001XXX0XXXX0XX0
1001XXX10XXX0XX0
1001XXX110XX0XX0
1001XXX1110X0XX0
1001XXX111110XX0
10001XX0XXXX0XX0
10001XX10XXX0XX0
10001XX110XX0XX0
10001XX1110X0XX0
10001XX111110XX0
100001X0XXXX0XX0
100001X10XXX0XX0
100001X110XX0XX0
100001X1110X0XX0
100001X111110XX0
10000010XXXX0XX0
100000110XXX0XX0
1000001110XX0XX0
10000011110X0XX0
1000001111110XX0
11XXXXX0XXXX10X0
11XXXXX10XXX10X0
11XXXXX110XX10X0
11XXXXX1110X10X0
11XXXXX1111110X0
101XXXX0XXXX10X0
101XXXX10XXX10X0
101XXXX110XX10X0
101XXXX1110X10X0
101XXXX1111110X0
1001XXX0XXXX10X0
1001XXX10XXX10X0
1001XXX110XX10X0
1001XXX1110X10X0
1001XXX1111110X0
10001XX0XXXX10X0
10001XX10XXX10X0
10001XX110XX10X0
10001XX1110X10X0
10001XX1111110X0
100001X0XXXX10X0
100001X10XXX10X0
100001X110XX10X0
100001X1110X10X0
100001X1111110X0
10000010XXXX10X0
100000110XXX10X0
1000001110XX10X0
10000011110X10X0
10000011111110X0
11XXXXX0XXXX1100
11XXXXX10XXX1100
11XXXXX110XX1100
11XXXXX1110X1100
11XXXXX111111100
101XXXX0XXXX1100
101XXXX10XXX1100
101XXXX110XX1100
101XXXX1110X1100
101XXXX111111100
1001XXX0XXXX1100
1001XXX10XXX1100
1001XXX110XX1100
1001XXX1110X1100
1001XXX111111100
10001XX0XXXX1100
10001XX10XXX1100
10001XX110XX1100
10001XX1110X1100
10001XX111111100
100001X0XXXX1100
100001X10XXX1100
100001X110XX1100
100001X1110X1100
100001X111111100
10000010XXXX1100
100000110XXX1100
1000001110XX1100
10000011110X1100
1000001111111100
11XXXXX0XXXX1111
11XXXXX10XXX1111
11XXXXX110XX1111
11XXXXX1110X1111
11XXXXX111111111
101XXXX0XXXX1111
101XXXX10XXX1111
101XXXX110XX1111
101XXXX1110X1111
101XXXX111111111
1001XXX0XXXX1111
1001XXX10XXX1111
1001XXX110XX1111
1001XXX1110X1111
1001XXX111111111
10001XX0XXXX1111
10001XX10XXX1111
10001XX110XX1111
10001XX1110X1111
10001XX111111111
100001X0XXXX1111
100001X10XXX1111
100001X110XX1111
100001X1110X1111
100001X111111111
10000010XXXX1111
100000110XXX1111
1000001110XX1111
10000011110X1111
1000001111111111
2647 && $self->_node_has_tags($_, $tags)
2648 && !$self->_node_has_any_tag($_, $deny)
2649 1418 ▶ } @{$self->nodes || []};
Condition50%1/2
$self->nodes || []
l!l
14180
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
2650  
2651 1418 ▶ @nodes = sort { ($a->{id} // '') cmp ($b->{id} // '') } @nodes;
Condition50%2/4
$Langertha::Skeid::a->{"id"} // ""
l!l
4300
$Langertha::Skeid::b->{"id"} // ""
l!l
4300
MC/DC0%0/1
$Langertha::Skeid::a->{"id"} // ""
$Langertha::Skeid::a->{"id"}
MC/DC0%0/1
$Langertha::Skeid::b->{"id"} // ""
$Langertha::Skeid::b->{"id"}
Truth table50%1/2
A
A= $Langertha::Skeid::a->{"id"}
Aresult
11
00
Truth table50%1/2
A
A= $Langertha::Skeid::b->{"id"}
Aresult
11
00
2652 my @weights = map {
2653 1418 ▶ my $w = 0 + ($_->{weight} // 1);
Condition100%2/2
$_->{"weight"} // 1
l!l
14021
MC/DC100%1/1
$_->{"weight"} // 1
$_->{"weight"}
Truth table100%2/2
A
A= $_->{"weight"}
Aresult
11
00
2654 1403 ▶ $w = 1 if $w < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $w < 1 0 1403 1403
2655 1403 int($w);
2656 } @nodes;
2657 1418 my $total_weight = 0;
2658 1418 $total_weight += $_ for @weights;
2659  
2660 1418 my $new_entry = {
2661 nodes => \@nodes,
2662 weights => \@weights,
2663 total_weight => $total_weight,
2664 };
2665  
2666 1418 ▶ my $order = $cache->{order} ||= [];
Condition50%1/2
$cache->{"order"} ||= []
l!l
14180
MC/DC0%0/1
$cache->{"order"} ||= []
$cache->{"order"}
Truth table50%1/2
A
A= $cache->{"order"}
Aresult
11
00
2667 1418 ▶ while (@$order >= $ROUTE_CACHE_MAX_ENTRIES) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$order >= $ROUTE_CACHE_MAX_ENTRIES) 290 1418 1708
2668 290 my $evicted = shift @$order;
2669 290 ▶ next unless exists $cache->{entries}{$evicted};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $cache->{"entries"}{$evicted} 0 290 290
2670 290 delete $cache->{entries}{$evicted};
2671 # The cursor tracks ranges stored by this entry. Keeping it would defeat the bound and would
2672 # resume at stale fairness state if this route key later re-enters the working set.
2673 290 delete $self->_rr_cursor->{$evicted};
2674 }
2675 1418 $cache->{entries}{$key} = $new_entry;
2676 1418 push @$order, $key;
2677 1418 return $new_entry;
2678 }
2679  
2680 # Returns the live node hashrefs, not copies. Callers read them and must not mutate them --
2681 # pick_node builds its own hash for the node it returns.
2682 1835 ▶sub _eligible_nodes {
Subroutine _eligible_nodes: called CC=1 SCAR=0.0
2683 1835 my ($self, %args) = @_;
2684 1835 return $self->_route_entry(%args)->{nodes};
2685 }
2686  
2687  
2688 91 ▶sub set_model_alias {
Subroutine set_model_alias: called CC=15 SCAR=28.2
Pod documented
2689 91 my ($self, $name, $spec) = @_;
2690 91 ▶ croak 'alias name required' unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 91 91
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
0091
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
2691  
2692 my $tiers = ref($spec) eq 'ARRAY' ? $spec
2693 : ref($spec) eq 'HASH' ? $spec->{tiers}
2694 91 ▶ : croak "alias '$name': must be a hashref with tiers, or an arrayref of tiers";
Branch: 2 branches
BranchTrueFalseTotal
ref $spec eq 'ARRAY' ? : 1 90 91
ref $spec eq 'HASH' ? : 89 1 90
2695 90 ▶ croak "alias '$name': tiers must be an arrayref" unless ref($tiers) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tiers eq "ARRAY" 0 90 90
2696 90 ▶ croak "alias '$name': needs at least one tier" unless @$tiers;
Branch: 1 branch
BranchTrueFalseTotal
unless @$tiers 1 89 90
2697  
2698 89 my @normalized;
2699 89 for my $tier (@$tiers) {
2700 101 ▶ croak "alias '$name': each tier must be a hashref" unless ref($tier) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tier eq "HASH" 0 101 101
2701 push @normalized, {
2702 tags => $self->normalize_tags($tier->{tags}),
2703 model => ((defined($tier->{model}) && length($tier->{model})) ? "$tier->{model}" : $name),
2704 engine => $self->normalize_engine_id($tier->{engine} // ''),
2705 # undef = not written: route_plan gives the last tier the global wait, the others 0.
2706 wait_ms => (!defined($tier->{wait_ms}) || !length($tier->{wait_ms}) ? undef
2707 101 ▶ : $tier->{wait_ms} > 0 ? 0 + $tier->{wait_ms} : 0),
Branch: 3 branches
BranchTrueFalseTotal
defined $tier->{'model'} && length $tier->{'model'} ? : 97 4 101
!(defined $tier->{'wait_ms'} && length $tier->{'wait_ms'}) ? : 92 9 101
$tier->{'wait_ms'} > 0 ? : 4 5 9
Condition62%5/8
defined $tier->{"model"} and length $tier->{"model"}
!ll&&!rl&&r
4097
$tier->{"engine"} // ""
l!l
0101
defined $tier->{'wait_ms'} && length $tier->{'wait_ms'}
!ll&&!rl&&r
9209
MC/DC50%1/2
defined $tier->{"model"} and length $tier->{"model"}
defined $tier->{"model"} length $tier->{"model"}
MC/DC0%0/1
$tier->{"engine"} // ""
$tier->{"engine"}
MC/DC50%1/2
defined $tier->{'wait_ms'} && length $tier->{'wait_ms'}
defined $tier->{'wait_ms'} length $tier->{'wait_ms'}
Truth table66%2/3
A and B
A= defined $tier->{"model"}B= length $tier->{"model"}
ABresult
0X0
100
111
Truth table50%1/2
A
A= $tier->{"engine"}
Aresult
11
00
Truth table66%2/3
A && B
A= defined $tier->{'wait_ms'}B= length $tier->{'wait_ms'}
ABresult
0X0
100
111
2708 };
2709 }
2710  
2711 89 $self->model_aliases->{$name} = { tiers => \@normalized };
2712 89 return 1;
2713 }
2714  
2715  
2716 3 ▶sub set_policy {
Subroutine set_policy: called CC=3 SCAR=12.0
Pod documented
2717 3 my ($self, $name, $spec) = @_;
2718 3 ▶ croak 'policy name required' unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 3 3
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
003
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
2719 3 $self->policies->{$name} = $self->resolve_policy($spec, $name);
2720 3 return 1;
2721 }
2722  
2723  
2724 229 ▶sub resolve_policy {
Subroutine resolve_policy: called CC=9 SCAR=22.3
Pod documented
2725 229 my ($self, $spec, $name) = @_;
2726 229 ▶ $spec = {} unless ref($spec) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 0 229 229
2727  
2728 229 ▶ my $allow = $spec->{models} // $spec->{aliases};
Condition66%2/3
$spec->{"models"} // $spec->{"aliases"}
l!l&&r!l&&!r
1040125
MC/DC50%1/2
$spec->{"models"} // $spec->{"aliases"}
$spec->{"models"} $spec->{"aliases"}
Truth table66%2/3
A // B
A= $spec->{"models"}B= $spec->{"aliases"}
ABresult
1X1
011
000
2729 229 my $allow_models;
2730 229 ▶ if (defined $allow) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $allow) 104 125 229
2731 104 ▶ my @list = ref($allow) eq 'ARRAY' ? @$allow : split(/[,\s]+/, "$allow");
Branch: 1 branch
BranchTrueFalseTotal
ref $allow eq 'ARRAY' ? : 103 1 104
2732 104 ▶ @list = grep { defined && length } @list;
Condition33%1/3
defined $_ && length $_
!ll&&!rl&&r
00129
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
2733 # An explicit '*' is the same as saying nothing, and saying it out loud reads better in a
2734 # config than an absent key.
2735 104 ▶ $allow_models = (grep { $_ eq '*' } @list) ? undef : { map { $_ => 1 } @list };
Branch: 1 branch
BranchTrueFalseTotal
grep({$_ eq '*';} @list) ? : 1 103 104
2736 }
2737  
2738 return {
2739 name => ($name // $spec->{name} // ''),
2740 allow_models => $allow_models,
2741 deny_tags => $self->normalize_tags($spec->{deny_tags}),
2742 229 ▶ rate => _normalize_rate($spec->{rate}, $name),
Condition80%4/5
($name // $spec->{"name"}) // ""
l!l
2218
$name // $spec->{"name"}
l!l&&r!l&&!r
22108
MC/DC50%1/2
($name // $spec->{"name"}) // ""
$name $spec->{"name"}
Truth table66%2/3
A // B
A= $nameB= $spec->{"name"}
ABresult
1X1
011
000
2743 };
2744 }
2745  
2746 # A policy's request rate (skeid k125): undef for none; see Langertha::Skeid::Rate.
2747 229 ▶sub _normalize_rate {
Subroutine _normalize_rate: called CC=3 SCAR=11.1
2748 229 my ($rate, $name) = @_;
2749 229 ▶ return Langertha::Skeid::Rate->normalize($rate, defined($name) && length($name) ? "policy '$name'" : undef);
Branch: 1 branch
BranchTrueFalseTotal
defined $name && length $name ? : 221 8 229
Condition66%2/3
defined $name and length $name
!ll&&!rl&&r
80221
MC/DC50%1/2
defined $name and length $name
defined $name length $name
Truth table66%2/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
2750 }
2751  
2752 # Key ids before ADR 0016 were the first 12 hex digits of the same digest, so a short id is
2753 # the prefix of the full id of the same key.
2754 127 my $LEGACY_KEY_ID_HEX = 12;
2755 127 my %legacy_key_id_warned;
2756  
2757 # Resolves the whole policy section once, at config load. Nothing here happens per request:
2758 # a request costs one hash lookup, and identical resolutions share a single object, so a
2759 # thousand keys on three profiles are three policy objects and a thousand pointers.
2760 158 ▶sub _load_policies {
Subroutine _load_policies: called CC=31 SCAR=34.4
2761 158 my ($self, $cfg) = @_;
2762  
2763 158 my %policies;
2764 158 ▶ if (ref($cfg->{policies}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg->{"policies"} eq "HASH") 119 39 158
2765 119 for my $name (keys %{$cfg->{policies}}) {
2766 217 $policies{$name} = $self->resolve_policy($cfg->{policies}{$name}, $name);
2767 }
2768 }
2769  
2770 152 my %interned = map { $self->_policy_fingerprint($_) => $_ } values %policies;
2771 59 ▶ my $intern = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
2772 59 my ($policy) = @_;
2773 59 my $print = $self->_policy_fingerprint($policy);
2774 59 ▶ return $interned{$print} ||= $policy;
Condition66%2/3
$interned{$print} ||= $policy
l!l&&r!l&&!r
5090
MC/DC0%0/2
$interned{$print} ||= $policy
$interned{$print} $policy
Truth table66%2/3
A ||= B
A= $interned{$print}B= $policy
ABresult
1X1
011
000
2775 152 };
2776  
2777 152 my $default;
2778 152 ▶ if (defined $cfg->{default_policy} && length $cfg->{default_policy}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cfg->{"default_policy"} and length $cfg->{"default_policy"}) 65 87 152
Condition66%2/3
defined $cfg->{"default_policy"} and length $cfg->{"default_policy"}
!ll&&!rl&&r
87065
MC/DC50%1/2
defined $cfg->{"default_policy"} and length $cfg->{"default_policy"}
defined $cfg->{"default_policy"} length $cfg->{"default_policy"}
Truth table66%2/3
A and B
A= defined $cfg->{"default_policy"}B= length $cfg->{"default_policy"}
ABresult
0X0
100
111
2779 65 $default = $policies{$cfg->{default_policy}};
2780 65 ▶ croak "default_policy '$cfg->{default_policy}' is not defined in policies" unless $default;
Branch: 1 branch
BranchTrueFalseTotal
unless $default 5 60 65
2781 }
2782  
2783 # names: is a readable-name -> key-id registry that lives in the config, resolved to key ids
2784 # here and never consulted on the request path (karr #17, ADR 0008). A value must be an id
2785 # from `skeid keyid`, never a customer key -- the config still holds no keys. With it, a
2786 # keys: entry may be written by name, and rotating a customer's key is a one-line edit here
2787 # rather than a rewrite of every policy line that named them by id.
2788 147 my %key_names;
2789 147 ▶ if (ref($cfg->{names}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg->{"names"} eq "HASH") 69 78 147
2790 69 for my $name (keys %{$cfg->{names}}) {
2791 115 my $id = $cfg->{names}{$name};
2792 115 ▶ croak "name '$name' must map to a key id string, not a structure" if ref $id;
Branch: 1 branch
BranchTrueFalseTotal
if ref $id 1 114 115
2793 114 ▶ croak "name '$name' maps to an empty key id" unless defined($id) && length($id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 1 113 114
Condition66%2/3
defined $id and length $id
!ll&&!rl&&r
01113
MC/DC50%1/2
defined $id and length $id
defined $id length $id
Truth table66%2/3
A and B
A= defined $idB= length $id
ABresult
0X0
100
111
2794 113 $key_names{$name} = $id;
2795 }
2796 }
2797  
2798 # Resolve a keys: entry's label through the names registry, if it is a known name; otherwise
2799 # it is taken to be a key id already. Two labels resolving to the same id is a config error,
2800 # not a silent last-wins -- it usually means a name and its own id were both listed.
2801 145 my %seen_id;
2802 117 ▶ my $resolve_key_id = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2803 117 my ($label) = @_;
2804 117 ▶ my $id = exists $key_names{$label} ? $key_names{$label} : $label;
Branch: 1 branch
BranchTrueFalseTotal
exists $key_names{$label} ? : 56 61 117
2805 croak "keys entry '$label' resolves to key id '$id', which another entry already claims"
2806 117 ▶ if $seen_id{$id}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen_id{$id}++ 1 116 117
2807 116 return $id;
2808 145 };
2809  
2810 145 my %key_policies;
2811 145 ▶ if (ref($cfg->{keys}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg->{"keys"} eq "HASH") 62 83 145
2812 62 for my $label (keys %{$cfg->{keys}}) {
2813 117 my $key = $resolve_key_id->($label);
2814 116 my $entry = $cfg->{keys}{$label};
2815  
2816 116 ▶ if (!ref($entry)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $entry) 57 59 116
2817 57 my $policy = $policies{$entry};
2818 57 ▶ croak "key '$label' references undefined policy '$entry'" unless $policy;
Branch: 1 branch
BranchTrueFalseTotal
unless $policy 1 56 57
2819 56 $key_policies{$key} = $policy;
2820 56 next;
2821 }
2822  
2823 59 ▶ croak "key '$label' must be a policy name or a hashref" unless ref($entry) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 0 59 59
2824  
2825 59 my $base = {};
2826 59 ▶ if (defined $entry->{policy} && length $entry->{policy}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $entry->{'policy'} and length $entry->{'policy'}) { } 34 25 59
elsif ($default) { } 23 2 25
Condition66%2/3
defined $entry->{"policy"} and length $entry->{"policy"}
!ll&&!rl&&r
25034
MC/DC50%1/2
defined $entry->{"policy"} and length $entry->{"policy"}
defined $entry->{"policy"} length $entry->{"policy"}
Truth table66%2/3
A and B
A= defined $entry->{"policy"}B= length $entry->{"policy"}
ABresult
0X0
100
111
2827 34 my $named = $policies{$entry->{policy}};
2828 34 ▶ croak "key '$label' references undefined policy '$entry->{policy}'" unless $named;
Branch: 1 branch
BranchTrueFalseTotal
unless $named 0 34 34
2829 34 $base = $named;
2830 } elsif ($default) {
2831 23 $base = $default;
2832 }
2833  
2834 # Overrides are sparse: an absent field keeps the profile's value, so "same as standard
2835 # but allowed to use cloud" is one line rather than a restated profile.
2836 59 ▶ my $overrides = ref($entry->{overrides}) eq 'HASH' ? $entry->{overrides} : $entry;
Branch: 1 branch
BranchTrueFalseTotal
ref $entry->{'overrides'} eq 'HASH' ? : 0 59 59
2837 my $merged = {
2838 name => ($base->{name} // ''),
2839 allow_models => (exists($overrides->{models}) || exists($overrides->{aliases})
2840 ? $self->resolve_policy($overrides)->{allow_models}
2841 : $base->{allow_models}),
2842 deny_tags => (exists($overrides->{deny_tags})
2843 ? $self->normalize_tags($overrides->{deny_tags})
2844 : ($base->{deny_tags} // [])),
2845 rate => (exists($overrides->{rate})
2846 ? Langertha::Skeid::Rate->normalize($overrides->{rate}, "key '$label'")
2847 59 ▶ : $base->{rate}),
Branch: 3 branches
BranchTrueFalseTotal
exists $overrides->{'models'} || exists $overrides->{'aliases'} ? : 5 54 59
exists $overrides->{'deny_tags'} ? : 2 57 59
exists $overrides->{'rate'} ? : 5 54 59
Condition85%6/7
$base->{"name"} // ""
l!l
572
exists $overrides->{"models"} or exists $overrides->{"aliases"}
l!l&&r!l&&!r
5054
$base->{"deny_tags"} // []
l!l
552
MC/DC100%1/1
$base->{"name"} // ""
$base->{"name"}
MC/DC50%1/2
exists $overrides->{"models"} or exists $overrides->{"aliases"}
exists $overrides->{"models"} exists $overrides->{"aliases"}
MC/DC100%1/1
$base->{"deny_tags"} // []
$base->{"deny_tags"}
Truth table100%2/2
A
A= $base->{"name"}
Aresult
11
00
Truth table66%2/3
A or B
A= exists $overrides->{"models"}B= exists $overrides->{"aliases"}
ABresult
1X1
011
000
Truth table100%2/2
A
A= $base->{"deny_tags"}
Aresult
11
00
2848 };
2849 59 $key_policies{$key} = $intern->($merged);
2850 }
2851 }
2852  
2853 # Short key ids from before ADR 0016 still name their customer: a request's full id falls
2854 # back to its short prefix (see _configured_key_id). Where one key would match two entries --
2855 # a short id and a full id it is the prefix of -- which one governs is not for Skeid to guess.
2856 143 my %legacy = map { $_ => 1 } grep { _is_legacy_key_id($_) } keys %seen_id;
2857 143 for my $id (sort keys %seen_id) {
2858 114 ▶ next unless $id =~ /\Ak_[0-9a-f]{40}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\Ak_[0-9a-f]{40}\z/ 24 90 114
2859 90 my $short = substr($id, 0, 2 + $LEGACY_KEY_ID_HEX);
2860 croak "key id '$short' is the short form of '$id', and both have a keys entry: one key "
2861 . 'would match both; keep only the full id'
2862 90 ▶ if $legacy{$short};
Branch: 1 branch
BranchTrueFalseTotal
if $legacy{$short} 2 88 90
2863 }
2864 141 _warn_legacy_key_id($_) for sort(keys %legacy), grep { _is_legacy_key_id($_) } values %key_names;
2865  
2866 141 $self->policies(\%policies);
2867 141 $self->default_policy($default);
2868 141 $self->key_policies(\%key_policies);
2869 141 $self->key_names(\%key_names);
2870 141 $self->_prune_rate_buckets;
2871 141 return 1;
2872 }
2873  
2874 235 ▶sub _is_legacy_key_id {
Subroutine _is_legacy_key_id: called CC=3 SCAR=11.1
2875 235 my ($id) = @_;
2876 235 ▶ return defined($id) && $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/ ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $id && $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/ ? : 21 214 235
Condition66%2/3
defined $id and $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/
!ll&&!rl&&r
021421
MC/DC50%1/2
defined $id and $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/
defined $id $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/
Truth table66%2/3
A and B
A= defined $idB= $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/
ABresult
0X0
100
111
2877 }
2878  
2879 19 ▶sub _warn_legacy_key_id {
Subroutine _warn_legacy_key_id: called CC=2 SCAR=6.9
2880 19 my ($id) = @_;
2881 19 ▶ return if $legacy_key_id_warned{$id}++;
Branch: 1 branch
BranchTrueFalseTotal
if $legacy_key_id_warned{$id}++ 11 8 19
2882 8 warn "skeid: key id '$id' is a short key id from before ADR 0016; it still matches the key "
2883 . "whose full id starts with it, but is deprecated: replace it with the full id "
2884 . "`skeid keyid` prints\n";
2885 8 return;
2886 }
2887  
2888 # The id a customer's entry in a config table is filed under: the request's own id, or -- for
2889 # a config still written with short ids -- that id's short prefix. Exact wins, so a full id
2890 # entry is always what a full id finds.
2891 4914 ▶sub _configured_key_id {
Subroutine _configured_key_id: called CC=6 SCAR=17.9
2892 4914 my ($self, $table, $api_key_id) = @_;
2893 4914 ▶ return undef unless defined($api_key_id) && length($api_key_id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $api_key_id and length $api_key_id 108 4806 4914
Condition66%2/3
defined $api_key_id and length $api_key_id
!ll&&!rl&&r
10804806
MC/DC50%1/2
defined $api_key_id and length $api_key_id
defined $api_key_id length $api_key_id
Truth table66%2/3
A and B
A= defined $api_key_idB= length $api_key_id
ABresult
0X0
100
111
2894 4806 ▶ return $api_key_id if exists $table->{$api_key_id};
Branch: 1 branch
BranchTrueFalseTotal
if exists $table->{$api_key_id} 736 4070 4806
2895 4070 ▶ return undef unless $api_key_id =~ /\Ak_[0-9a-f]{40}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $api_key_id =~ /\Ak_[0-9a-f]{40}\z/ 2295 1775 4070
2896 1775 my $short = substr($api_key_id, 0, 2 + $LEGACY_KEY_ID_HEX);
2897 1775 ▶ return exists $table->{$short} ? $short : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $table->{$short} ? : 10 1765 1775
2898 }
2899  
2900 270 ▶sub _policy_fingerprint {
Subroutine _policy_fingerprint: called CC=2 SCAR=6.9
2901 270 my ($self, $policy) = @_;
2902 270 ▶ my $models = defined($policy->{allow_models}) ? join(',', sort keys %{$policy->{allow_models}}) : '*';
Branch: 1 branch
BranchTrueFalseTotal
defined $policy->{'allow_models'} ? : 103 167 270
2903 270 return join("\0", $models, join(',', @{$policy->{deny_tags}}), _rate_print($policy->{rate}));
2904 }
2905  
2906 355 ▶sub _rate_print { Langertha::Skeid::Rate->print($_[0]) }
Subroutine _rate_print: called CC=1 SCAR=0.0
2907  
2908  
2909 127 my @CAPABILITIES = qw(
2910 documents ollama_embed node_files key_rate customer_source_rate usage_contract usage_purge
2911 openbao_token_file catch_all
2912 );
2913  
2914 2 ▶sub capabilities { return @CAPABILITIES }
Subroutine capabilities: called CC=1 SCAR=0.0
Pod documented
2915  
2916  
2917 1425 ▶sub rate_admit {
Subroutine rate_admit: called CC=20 SCAR=30.0
Pod documented
2918 1425 my ($self, $api_key_id) = @_;
2919 1425 my $policy = $self->policy_for_key($api_key_id);
2920 # Without client authentication any string is a key, so a key the config does not list would
2921 # get a fresh bucket per made-up key -- no limit, and unbounded memory. Unlisted keys then share
2922 # one bucket: the default policy's rate is for everyone it covers together.
2923 1425 ▶ my $id = $api_key_id // '';
Condition100%2/2
$api_key_id // ""
l!l
1325100
MC/DC100%1/1
$api_key_id // ""
$api_key_id
Truth table100%2/2
A
A= $api_key_id
Aresult
11
00
2924 1425 ▶ $id = '' if length($id) && !$self->client_auth_enabled
Branch: 1 branch
BranchTrueFalseTotal
if length $id and not $self->client_auth_enabled and not defined $self->_configured_key_id($self->key_policies, $api_key_id) 1059 366 1425
Condition100%6/6
length $id and not $self->client_auth_enabled and not defined $self->_configured_key_id($self->key_policies, $api_key_id)
!ll&&!rl&&r
2261401059
length $id and not $self->client_auth_enabled
!ll&&!rl&&r
1001261199
MC/DC100%3/3
length $id and not $self->client_auth_enabled and not defined $self->_configured_key_id($self->key_policies, $api_key_id)
length $id not $self->client_auth_enabled not defined $self->_configured_key_id($self->key_policies, $api_key_id)
Truth table100%4/4
A and not(B) and not(C)
A= length $idB= not $self->client_auth_enabledC= not defined $self->_configured_key_id($self->key_policies, $api_key_id)
ABCresult
0XX0
10X0
1100
1111
2925 && !defined($self->_configured_key_id($self->key_policies, $api_key_id));
2926 1425 ▶ my $rate = $policy ? $policy->{rate} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$policy ? : 386 1039 1425
2927 1425 my $buckets = $self->_rate_buckets;
2928 1425 ▶ unless ($rate) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rate) 1340 85 1425
2929 1340 delete $buckets->{$id};
2930 1340 return { ok => 1 };
2931 }
2932  
2933 85 my $div = $self->_admission_divisor;
2934 85 my $now = $self->_now;
2935 85 my $print = _rate_print($rate) . "/$div";
2936 85 my $b = $buckets->{$id};
2937 85 ▶ if (!$b || $b->{print} ne $print) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $b or $b->{"print"} ne $print) 8 77 85
Condition66%2/3
not $b or $b->{"print"} ne $print
l!l&&r!l&&!r
8077
MC/DC50%1/2
not $b or $b->{"print"} ne $print
not $b $b->{"print"} ne $print
Truth table66%2/3
not(A) or B
A= not $bB= $b->{"print"} ne $print
ABresult
1X1
011
000
2938 8 my @limits;
2939 push @limits, { refill => $rate->{per_s} / $div, cap => _at_least_one($rate->{burst} / $div) }
2940 8 ▶ if defined $rate->{per_s};
Branch: 1 branch
BranchTrueFalseTotal
if defined $rate->{"per_s"} 7 1 8
2941 push @limits, { refill => $rate->{per_min} / 60 / $div, cap => _at_least_one($rate->{per_min} / $div) }
2942 8 ▶ if defined $rate->{per_min};
Branch: 1 branch
BranchTrueFalseTotal
if defined $rate->{"per_min"} 1 7 8
2943 8 $_->{tokens} = $_->{cap} for @limits;
2944 8 $b = $buckets->{$id} = { print => $print, at => $now, limits => \@limits };
2945 }
2946  
2947 85 my $elapsed = $now - $b->{at};
2948 85 ▶ $elapsed = 0 if $elapsed < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $elapsed < 0 0 85 85
2949 85 $b->{at} = $now;
2950 85 my $wait = 0;
2951 85 for my $limit (@{$b->{limits}}) {
2952 85 $limit->{tokens} += $elapsed * $limit->{refill};
2953 85 ▶ $limit->{tokens} = $limit->{cap} if $limit->{tokens} > $limit->{cap};
Branch: 1 branch
BranchTrueFalseTotal
if $limit->{"tokens"} > $limit->{"cap"} 0 85 85
2954 85 ▶ if ($limit->{tokens} < 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($limit->{"tokens"} < 1) 64 21 85
2955 64 my $need = (1 - $limit->{tokens}) / $limit->{refill};
2956 64 ▶ $wait = $need if $need > $wait;
Branch: 1 branch
BranchTrueFalseTotal
if $need > $wait 64 0 64
2957 }
2958 }
2959 85 ▶ if ($wait > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wait > 0) 64 21 85
2960 64 $self->_rate_refusals->{$id}++;
2961 64 my $after = POSIX::ceil($wait);
2962 64 ▶ return { ok => 0, retry_after => ($after < 1 ? 1 : $after) };
Branch: 1 branch
BranchTrueFalseTotal
$after < 1 ? : 0 64 64
2963 }
2964 21 $_->{tokens} -= 1 for @{$b->{limits}};
2965 21 return { ok => 1 };
2966 }
2967  
2968 8 ▶sub _at_least_one { $_[0] < 1 ? 1 : $_[0] }
Subroutine _at_least_one: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$_[0] < 1 ? : 0 8 8
2969  
2970 # Buckets of keys whose policy no longer has a rate, or that are gone, after a policy load.
2971 141 ▶sub _prune_rate_buckets {
Subroutine _prune_rate_buckets: called CC=5 SCAR=17.5
2972 141 my ($self) = @_;
2973 141 my $buckets = $self->_rate_buckets;
2974 141 for my $id (keys %$buckets) {
2975 1 ▶ my $policy = $self->policy_for_key(length($id) ? $id : undef);
Branch: 1 branch
BranchTrueFalseTotal
length $id ? : 1 0 1
2976 1 ▶ delete $buckets->{$id} unless $policy && $policy->{rate};
Branch: 1 branch
BranchTrueFalseTotal
unless $policy and $policy->{"rate"} 1 0 1
Condition33%1/3
$policy and $policy->{"rate"}
!ll&&!rl&&r
010
MC/DC0%0/2
$policy and $policy->{"rate"}
$policy $policy->{"rate"}
Truth table33%1/3
A and B
A= $policyB= $policy->{"rate"}
ABresult
0X0
100
111
2977 }
2978 141 return;
2979 }
2980  
2981  
2982 2 ▶sub key_metrics {
Subroutine key_metrics: called CC=1 SCAR=0.0
Pod documented
2983 2 my ($self) = @_;
2984 2 my $refusals = $self->_rate_refusals;
2985 2 return { map { ($_ => { rate_limited => 0 + $refusals->{$_} }) } keys %$refusals };
2986 }
2987  
2988  
2989 1910 ▶sub key_id_for_key {
Subroutine key_id_for_key: called CC=3 SCAR=11.0
Pod documented
2990 1910 my ($self, $api_key) = @_;
2991 1910 ▶ return 'anonymous' unless defined($api_key) && length($api_key);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $api_key and length $api_key 916 994 1910
Condition66%2/3
defined $api_key and length $api_key
!ll&&!rl&&r
0916994
MC/DC50%1/2
defined $api_key and length $api_key
defined $api_key length $api_key
Truth table66%2/3
A and B
A= defined $api_keyB= length $api_key
ABresult
0X0
100
111
2992 994 return 'k_' . sha1_hex($api_key);
2993 }
2994  
2995  
2996 2825 ▶sub policy_for_key {
Subroutine policy_for_key: called CC=3 SCAR=11.0
Pod documented
2997 2825 my ($self, $api_key_id) = @_;
2998 2825 my $id = $self->_configured_key_id($self->key_policies, $api_key_id);
2999 2825 ▶ return $self->key_policies->{$id} if defined($id) && $self->key_policies->{$id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $id and $self->key_policies->{$id} 272 2553 2825
Condition66%2/3
defined $id and $self->key_policies->{$id}
!ll&&!rl&&r
25530272
MC/DC50%1/2
defined $id and $self->key_policies->{$id}
defined $id $self->key_policies->{$id}
Truth table66%2/3
A and B
A= defined $idB= $self->key_policies->{$id}
ABresult
0X0
100
111
3000 2553 return $self->default_policy;
3001 }
3002  
3003  
3004 3 ▶sub key_id_for_name {
Subroutine key_id_for_name: called CC=3 SCAR=12.5
Pod documented
3005 3 my ($self, $name) = @_;
3006 3 ▶ return undef unless defined($name) && length($name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 3 3
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
003
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
3007 3 return $self->key_names->{$name};
3008 }
3009  
3010 # The client_auth section (skeid k90), resolved once at config load into a key id set. An entry
3011 # is a names: name or a key id; anything else fails the load (see _key_id_set). Returns the
3012 # notices to log once the config applied.
3013 80 ▶sub _load_client_auth {
Subroutine _load_client_auth: called CC=8 SCAR=20.8
3014 80 my ($self, $section) = @_;
3015 80 ▶ croak 'client_auth must be a hash with a keys list' unless ref($section) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 2 78 80
3016 78 for my $key (sort keys %$section) {
3017 77 ▶ croak "client_auth: unknown key '$key' (known: keys)" unless $key eq 'keys';
Branch: 1 branch
BranchTrueFalseTotal
unless $key eq "keys" 1 76 77
3018 }
3019 77 my $list = $section->{keys};
3020 77 ▶ croak 'client_auth needs a keys list: the key ids (or names: entries) that may use the '
Branch: 1 branch
BranchTrueFalseTotal
unless defined $list 2 75 77
3021 . 'client routes' unless defined $list;
3022 75 ▶ $list = [ $list ] unless ref $list;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list 1 74 75
3023 75 ▶ croak 'client_auth.keys must be a list of key ids or names: entries' unless ref($list) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list eq "ARRAY" 1 74 75
3024  
3025 74 my $allowed = $self->_key_id_set($list, 'client_auth.keys');
3026 67 $self->client_auth_keys($allowed);
3027 67 ▶ return %$allowed ? () : ('client_auth.keys is empty: no key can use the client routes, every '
Branch: 1 branch
BranchTrueFalseTotal
%$allowed ? : 66 1 67
3028 . 'request on them answers 401');
3029 }
3030  
3031 # A list of customer keys in the config -- client_auth.keys, an MCP server's keys -- resolved
3032 # into a key id set, id to 1. An entry is a names: name or a key id; anything else fails the
3033 # load. The message names the entry by its position and never by its value: a value that is
3034 # neither is most likely a key someone pasted, and a reload error ends up in the log and on
3035 # /skeid/config (ADR 0003). $label is the list's place in the config, for that message. A short
3036 # (pre-ADR 0016) id is kept as it is and warned about once; _configured_key_id matches it.
3037 215 ▶sub _key_id_set {
Subroutine _key_id_set: called CC=13 SCAR=25.7
3038 215 my ($self, $list, $label) = @_;
3039 215 my (%allowed, @legacy);
3040 215 my $position = 0;
3041 215 for my $entry (@$list) {
3042 241 $position++;
3043 241 ▶ my $name = (defined($entry) && !ref($entry) && exists $self->key_names->{$entry}) ? $entry : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $entry && !ref($entry) && exists $self->key_names->{$entry} ? : 142 99 241
Condition83%5/6
defined $entry and not ref $entry and exists $self->key_names->{$entry}
!ll&&!rl&&r
198142
defined $entry and not ref $entry
!ll&&!rl&&r
01240
MC/DC66%2/3
defined $entry and not ref $entry and exists $self->key_names->{$entry}
defined $entry not ref $entry exists $self->key_names->{$entry}
Truth table75%3/4
A and not(B) and C
A= defined $entryB= not ref $entryC= exists $self->key_names->{$entry}
ABCresult
0XX0
10X0
1100
1111
3044 241 ▶ my $id = defined($name) ? $self->key_names->{$name} : $entry;
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 142 99 241
3045 241 ▶ my $full = defined($id) && !ref($id) && $id =~ /\Ak_[0-9a-f]{40}\z/;
Condition83%5/6
defined $id && !ref($id) && $id =~ /\Ak_[0-9a-f]{40}\z/
!ll&&!rl&&r
19231
defined $id and not ref $id
!ll&&!rl&&r
01240
MC/DC66%2/3
defined $id && !ref($id) && $id =~ /\Ak_[0-9a-f]{40}\z/
defined $id not ref $id $id =~ /\Ak_[0-9a-f]{40}\z/
Truth table75%3/4
A and not(B) && C
A= defined $idB= not ref $idC= $id =~ /\Ak_[0-9a-f]{40}\z/
ABCresult
0XX0
10X0
1100
1111
3046 241 ▶ unless ($full || _is_legacy_key_id($id)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($full or _is_legacy_key_id($id)) 8 233 241
Condition100%3/3
$full or _is_legacy_key_id($id)
l!l&&r!l&&!r
23128
MC/DC100%2/2
$full or _is_legacy_key_id($id)
$full _is_legacy_key_id($id)
Truth table100%3/3
A or B
A= $fullB= _is_legacy_key_id($id)
ABresult
1X1
011
000
3047 8 ▶ croak defined($name)
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 1 7 8
3048 ? "$label entry $position is the names: entry '$name', which does not map to a "
3049 . 'key id (k_ + 40 hex from `skeid keyid`)'
3050 : "$label entry $position is neither a names: entry nor a key id (k_ + 40 hex "
3051 . 'from `skeid keyid`); a key itself never goes into the config';
3052 }
3053 233 ▶ push @legacy, $id unless $full;
Branch: 1 branch
BranchTrueFalseTotal
unless $full 2 231 233
3054 233 $allowed{$id} = 1;
3055 }
3056 207 _warn_legacy_key_id($_) for @legacy;
3057 207 return \%allowed;
3058 }
3059  
3060 # The mcp section (skeid k103, ADR 0022), resolved once at config load into the server table.
3061 # Strict like client_auth and uploads: a misspelled key, a key of the other transport or a URL
3062 # that is none fails the load, and the previous config stays in force. No message repeats a
3063 # value that could be a secret -- a URL, a header value, a keys entry. What the wire allows --
3064 # the transports, a server name, the headers a server may set -- is Protocol::MCP's to know.
3065 # Returns the notices to log once the config applied.
3066 127 my %MCP_KEYS = map { $_ => 1 } qw( public_url servers max_request_bytes );
3067 127 my %MCP_SERVER_KEYS = (
3068 common => [qw( transport description keys )],
3069 relayed => [qw( url api_key_ref api_key_env headers )],
3070 stdio => [qw( command args env )],
3071 );
3072  
3073 55 ▶sub _load_mcp {
Subroutine _load_mcp: called CC=57 SCAR=40.9
3074 55 my ($self, $section) = @_;
3075 55 my $mcp = 'Langertha::Skeid::Protocol::MCP';
3076 55 ▶ croak 'mcp must be a hash with a servers map' unless ref($section) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 1 54 55
3077 54 for my $key (sort keys %$section) {
3078 croak "mcp: unknown key '$key' (known: " . join(' ', sort keys %MCP_KEYS) . ')'
3079 84 ▶ unless $MCP_KEYS{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless $MCP_KEYS{$key} 1 83 84
3080 }
3081  
3082 53 my $public_url;
3083 53 ▶ if (defined $section->{public_url}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"public_url"}) 21 32 53
3084 21 my $problem = $mcp->url_problem($section->{public_url});
3085 21 ▶ croak "mcp.public_url $problem: it is where clients reach Skeid" if defined $problem;
Branch: 1 branch
BranchTrueFalseTotal
if defined $problem 1 20 21
3086 20 ($public_url = "$section->{public_url}") =~ s{/+\z}{};
3087 }
3088  
3089 52 my $max_request = $MCP_MAX_REQUEST_BYTES;
3090 52 ▶ if (exists $section->{max_request_bytes}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $section->{"max_request_bytes"}) 9 43 52
3091 9 my $max = $section->{max_request_bytes};
3092 9 ▶ croak 'mcp.max_request_bytes must be an integer of at least 1 (bytes)'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $max and not ref $max and $max =~ /\A[0-9]+\z/ and $max >= 1 6 3 9
Condition100%9/9
defined $max and not ref $max and $max =~ /\A[0-9]+\z/ and $max >= 1
!ll&&!rl&&r
513
defined $max and not ref $max and $max =~ /\A[0-9]+\z/
!ll&&!rl&&r
234
defined $max and not ref $max
!ll&&!rl&&r
117
MC/DC100%4/4
defined $max and not ref $max and $max =~ /\A[0-9]+\z/ and $max >= 1
defined $max not ref $max $max =~ /\A[0-9]+\z/ $max >= 1
Truth table100%5/5
A and not(B) and C and D
A= defined $maxB= not ref $maxC= $max =~ /\A[0-9]+\z/D= $max >= 1
ABCDresult
0XXX0
10XX0
110X0
11100
11111
3093 unless defined($max) && !ref($max) && $max =~ /\A[0-9]+\z/ && $max >= 1;
3094 3 $max_request = 0 + $max;
3095 }
3096  
3097 46 ▶ my $servers = $section->{servers} // {};
Condition50%1/2
$section->{"servers"} // {}
l!l
460
MC/DC0%0/1
$section->{"servers"} // {}
$section->{"servers"}
Truth table50%1/2
A
A= $section->{"servers"}
Aresult
11
00
3098 46 ▶ croak 'mcp.servers must be a hash of server name to server' unless ref($servers) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $servers eq "HASH" 1 45 46
3099  
3100 45 my (%resolved, @notices);
3101 45 for my $name (sort keys %$servers) {
3102 158 my $problem = $mcp->name_problem($name);
3103 158 ▶ croak "mcp.servers: $problem" if defined $problem;
Branch: 1 branch
BranchTrueFalseTotal
if defined $problem 1 157 158
3104 157 my $at = "mcp.servers.$name";
3105 157 my $entry = $servers->{$name};
3106 157 ▶ croak "$at must be a hash" unless ref($entry) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 1 156 157
3107  
3108 156 ▶ my $transport = $entry->{transport} // $mcp->default_transport;
Condition66%2/3
$entry->{"transport"} // $mcp->default_transport
l!l&&r!l&&!r
281280
MC/DC0%0/2
$entry->{"transport"} // $mcp->default_transport
$entry->{"transport"} $mcp->default_transport
Truth table66%2/3
A // B
A= $entry->{"transport"}B= $mcp->default_transport
ABresult
1X1
011
000
3109 156 ▶ croak "$at: unknown transport (known: " . join(' ', $mcp->transports) . ')'
Branch: 1 branch
BranchTrueFalseTotal
unless $mcp->is_transport($transport) 1 155 156
3110 unless $mcp->is_transport($transport);
3111 155 my $relayed = $mcp->is_relayed($transport);
3112 155 ▶ my %own = map { $_ => 1 } @{$MCP_SERVER_KEYS{common}}, @{$MCP_SERVER_KEYS{$relayed ? 'relayed' : 'stdio'}};
Branch: 1 branch
BranchTrueFalseTotal
$relayed ? : 128 27 155
3113 155 ▶ my %other = map { $_ => 1 } @{$MCP_SERVER_KEYS{$relayed ? 'stdio' : 'relayed'}};
Branch: 1 branch
BranchTrueFalseTotal
$relayed ? : 128 27 155
3114 155 for my $key (sort keys %$entry) {
3115 512 ▶ next if $own{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $own{$key} 509 3 512
3116 croak "$at: '$key' " . ($relayed ? 'belongs to a stdio server' : 'does not belong to a stdio server')
3117 3 ▶ if $other{$key};
Branch: 2 branches
BranchTrueFalseTotal
if $other{$key} 2 1 3
$relayed ? : 1 1 2
3118 1 croak "$at: unknown key '$key' (known: " . join(' ', sort keys %own) . ')';
3119 }
3120  
3121 152 ▶ my $description = $entry->{description} // '';
Condition100%2/2
$entry->{"description"} // ""
l!l
46106
MC/DC100%1/1
$entry->{"description"} // ""
$entry->{"description"}
Truth table100%2/2
A
A= $entry->{"description"}
Aresult
11
00
3122 152 ▶ croak "$at.description must be a string" if ref $description;
Branch: 1 branch
BranchTrueFalseTotal
if ref $description 1 151 152
3123  
3124 151 my %server = (name => $name, transport => "$transport", description => "$description");
3125 151 ▶ if ($relayed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($relayed) { } 125 26 151
3126 125 ▶ croak "$at needs a url: where the MCP server is reached" unless defined $entry->{url};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry->{"url"} 1 124 125
3127 124 $problem = $mcp->url_problem($entry->{url});
3128 124 ▶ croak "$at.url $problem" if defined $problem;
Branch: 1 branch
BranchTrueFalseTotal
if defined $problem 3 121 124
3129 121 $server{url} = "$entry->{url}";
3130  
3131 121 for my $source (qw( api_key_ref api_key_env )) {
3132 242 ▶ next unless defined $entry->{$source};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry->{$source} 174 68 242
3133 croak "$at.$source must be a non-empty string"
3134 68 ▶ if ref($entry->{$source}) || !length($entry->{$source});
Branch: 1 branch
BranchTrueFalseTotal
if ref $entry->{$source} or not length $entry->{$source} 0 68 68
Condition33%1/3
ref $entry->{$source} or not length $entry->{$source}
l!l&&r!l&&!r
0068
MC/DC0%0/2
ref $entry->{$source} or not length $entry->{$source}
ref $entry->{$source} not length $entry->{$source}
Truth table33%1/3
A or not(B)
A= ref $entry->{$source}B= not length $entry->{$source}
ABresult
1X1
011
000
3135 68 $server{$source} = "$entry->{$source}";
3136 }
3137  
3138 121 ▶ my $headers = $entry->{headers} // {};
Condition100%2/2
$entry->{"headers"} // {}
l!l
2893
MC/DC100%1/1
$entry->{"headers"} // {}
$entry->{"headers"}
Truth table100%2/2
A
A= $entry->{"headers"}
Aresult
11
00
3139 121 ▶ croak "$at.headers must be a map of header name to value" unless ref($headers) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $headers eq "HASH" 0 121 121
3140 121 for my $header (sort keys %$headers) {
3141 29 ▶ croak "$at.headers: a header name must be an HTTP token"
Branch: 1 branch
BranchTrueFalseTotal
unless $header =~ /\A[A-Za-z0-9!#\$%&'*+.^_`|~-]+\z/ 0 29 29
3142 unless $header =~ /\A[A-Za-z0-9!#\$%&'*+.^_`|~-]+\z/;
3143 29 $problem = $mcp->config_header_problem($header);
3144 29 ▶ croak "$at.headers: '$header' may not be set here: $problem" if defined $problem;
Branch: 1 branch
BranchTrueFalseTotal
if defined $problem 2 27 29
3145 27 my $value = $headers->{$header};
3146 27 ▶ croak "$at.headers: the value of '$header' must be a string on one line"
Branch: 1 branch
BranchTrueFalseTotal
if not defined $value or ref $value or $value =~ /[\r\n\0]/ 1 26 27
Condition66%4/6
not defined $value or ref $value or $value =~ /[\r\n\0]/
l!l&&r!l&&!r
1026
not defined $value or ref $value
l!l&&r!l&&!r
0126
MC/DC33%1/3
not defined $value or ref $value or $value =~ /[\r\n\0]/
not defined $value ref $value $value =~ /[\r\n\0]/
Truth table50%2/4
not(A) or B or C
A= not defined $valueB= ref $valueC= $value =~ /[\r\n\0]/
ABCresult
1XX1
01X1
0011
0000
3147 if !defined($value) || ref($value) || $value =~ /[\r\n\0]/;
3148 26 $server{headers}{$header} = "$value";
3149 }
3150 118 ▶ $server{headers} ||= {};
Condition100%2/2
$server{"headers"} ||= {}
l!l
2593
MC/DC100%1/1
$server{"headers"} ||= {}
$server{"headers"}
Truth table100%2/2
A
A= $server{"headers"}
Aresult
11
00
3151 } else {
3152 croak "$at needs a command: what the customer runs on its own machine"
3153 26 ▶ unless defined($entry->{command}) && !ref($entry->{command}) && length($entry->{command});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry->{"command"} and not ref $entry->{"command"} and length $entry->{"command"} 1 25 26
Condition66%4/6
defined $entry->{"command"} and not ref $entry->{"command"} and length $entry->{"command"}
!ll&&!rl&&r
1025
defined $entry->{"command"} and not ref $entry->{"command"}
!ll&&!rl&&r
1025
MC/DC33%1/3
defined $entry->{"command"} and not ref $entry->{"command"} and length $entry->{"command"}
defined $entry->{"command"} not ref $entry->{"command"} length $entry->{"command"}
Truth table50%2/4
A and not(B) and C
A= defined $entry->{"command"}B= not ref $entry->{"command"}C= length $entry->{"command"}
ABCresult
0XX0
10X0
1100
1111
3154 25 $server{command} = "$entry->{command}";
3155  
3156 25 ▶ my $args = $entry->{args} // [];
Condition100%2/2
$entry->{"args"} // []
l!l
241
MC/DC100%1/1
$entry->{"args"} // []
$entry->{"args"}
Truth table100%2/2
A
A= $entry->{"args"}
Aresult
11
00
3157 croak "$at.args must be a list of strings"
3158 25 ▶ unless ref($args) eq 'ARRAY' && !grep { !defined($_) || ref($_) } @$args;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "ARRAY" and not grep({not defined $_ or ref $_;} @$args) 1 24 25
Condition50%3/6
ref $args eq "ARRAY" and not grep({not defined $_ or ref $_;} @$args)
!ll&&!rl&&r
1024
!defined($_) || ref $_
l!l&&r!l&&!r
0047
MC/DC50%1/2
ref $args eq "ARRAY" and not grep({not defined $_ or ref $_;} @$args)
ref $args eq "ARRAY" not grep({not defined $_ or ref $_;} @$args)
MC/DC0%0/2
!defined($_) || ref $_
!defined($_) ref $_
Truth table66%2/3
A and not(B)
A= ref $args eq "ARRAY"B= not grep({not defined $_ or ref $_;} @$args)
ABresult
0X0
100
111
Truth table33%1/3
not(A) || B
A= !defined($_)B= ref $_
ABresult
1X1
011
000
3159 24 $server{args} = [ map { "$_" } @$args ];
3160  
3161 24 ▶ my $env = $entry->{env} // {};
Condition50%1/2
$entry->{"env"} // {}
l!l
240
MC/DC0%0/1
$entry->{"env"} // {}
$entry->{"env"}
Truth table50%1/2
A
A= $entry->{"env"}
Aresult
11
00
3162 croak "$at.env must be a map of strings"
3163 24 ▶ unless ref($env) eq 'HASH' && !grep { !defined($_) || ref($_) } values %$env;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $env eq "HASH" and not grep({not defined $_ or ref $_;} values %$env) 1 23 24
Condition50%3/6
ref $env eq "HASH" and not grep({not defined $_ or ref $_;} values %$env)
!ll&&!rl&&r
1023
!defined($_) || ref $_
l!l&&r!l&&!r
0023
MC/DC50%1/2
ref $env eq "HASH" and not grep({not defined $_ or ref $_;} values %$env)
ref $env eq "HASH" not grep({not defined $_ or ref $_;} values %$env)
MC/DC0%0/2
!defined($_) || ref $_
!defined($_) ref $_
Truth table66%2/3
A and not(B)
A= ref $env eq "HASH"B= not grep({not defined $_ or ref $_;} values %$env)
ABresult
0X0
100
111
Truth table33%1/3
not(A) || B
A= !defined($_)B= ref $_
ABresult
1X1
011
000
3164 23 $server{env} = { map { $_ => "$env->{$_}" } keys %$env };
3165 }
3166  
3167 141 ▶ my $list = $entry->{keys} // [];
Condition100%2/2
$entry->{"keys"} // []
l!l
1401
MC/DC100%1/1
$entry->{"keys"} // []
$entry->{"keys"}
Truth table100%2/2
A
A= $entry->{"keys"}
Aresult
11
00
3168 141 ▶ $list = [ $list ] unless ref $list;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list 2 139 141
3169 141 ▶ croak "$at.keys must be a list of key ids or names: entries" unless ref($list) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list eq "ARRAY" 0 141 141
3170 141 $server{keys} = $self->_key_id_set($list, "$at.keys");
3171 push @notices, "$at is assigned to no key: no customer can reach or see it"
3172 140 ▶ unless %{$server{keys}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$server{"keys"};} 1 139 140
3173  
3174 140 $resolved{$name} = \%server;
3175 }
3176  
3177 27 $self->mcp_servers(\%resolved);
3178 27 $self->mcp_public_url($public_url);
3179 27 $self->mcp_max_request_bytes($max_request);
3180 27 return @notices;
3181 }
3182  
3183 # The uploads section (skeid k91). Strict like client_auth: a misspelled key or a limit that is
3184 # not a positive integer fails the load rather than leaving the default in force unnoticed --
3185 # and 0, which the server underneath reads as "no limit", is refused with the rest.
3186 18 ▶sub _load_uploads {
Subroutine _load_uploads: called CC=11 SCAR=24.1
3187 18 my ($self, $section) = @_;
3188 18 ▶ croak 'uploads must be a hash, as in uploads: { max_bytes: 26214400 }'
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 2 16 18
3189 unless ref($section) eq 'HASH';
3190 16 for my $key (sort keys %$section) {
3191 18 ▶ croak "uploads: unknown key '$key' (known: max_bytes, documents_max_bytes)"
Branch: 1 branch
BranchTrueFalseTotal
unless $key eq "max_bytes" or $key eq "documents_max_bytes" 2 16 18
Condition100%3/3
$key eq "max_bytes" or $key eq "documents_max_bytes"
l!l&&r!l&&!r
972
MC/DC100%2/2
$key eq "max_bytes" or $key eq "documents_max_bytes"
$key eq "max_bytes" $key eq "documents_max_bytes"
Truth table100%3/3
A or B
A= $key eq "max_bytes"B= $key eq "documents_max_bytes"
ABresult
1X1
011
000
3192 unless $key eq 'max_bytes' || $key eq 'documents_max_bytes';
3193 }
3194 14 my %limit = (max_bytes => $UPLOAD_MAX_BYTES, documents_max_bytes => $DOCUMENTS_MAX_BYTES);
3195 14 for my $key (sort keys %limit) {
3196 24 ▶ next unless exists $section->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $section->{$key} 8 16 24
3197 16 my $max = $section->{$key};
3198 16 ▶ croak "uploads.$key must be an integer of at least 1 (bytes)"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $max and not ref $max and $max =~ /\A[0-9]+\z/ and $max >= 1 7 9 16
Condition66%6/9
defined $max and not ref $max and $max =~ /\A[0-9]+\z/ and $max >= 1
!ll&&!rl&&r
529
defined $max and not ref $max and $max =~ /\A[0-9]+\z/
!ll&&!rl&&r
0511
defined $max and not ref $max
!ll&&!rl&&r
0016
MC/DC50%2/4
defined $max and not ref $max and $max =~ /\A[0-9]+\z/ and $max >= 1
defined $max not ref $max $max =~ /\A[0-9]+\z/ $max >= 1
Truth table60%3/5
A and not(B) and C and D
A= defined $maxB= not ref $maxC= $max =~ /\A[0-9]+\z/D= $max >= 1
ABCDresult
0XXX0
10XX0
110X0
11100
11111
3199 unless defined($max) && !ref($max) && $max =~ /\A[0-9]+\z/ && $max >= 1;
3200 9 $limit{$key} = 0 + $max;
3201 }
3202 7 $self->upload_max_bytes($limit{max_bytes});
3203 7 $self->documents_max_bytes($limit{documents_max_bytes});
3204 7 return;
3205 }
3206  
3207 # The documents section (skeid k94, ADR 0028). Strict like uploads: an unknown key or a switch
3208 # that is no boolean fails the load rather than leaving the default in force unnoticed. There is
3209 # no model name here: documents nodes are chosen by their kind.
3210 6 ▶sub _load_documents {
Subroutine _load_documents: called CC=9 SCAR=22.2
3211 6 my ($self, $section) = @_;
3212 6 ▶ croak 'documents must be a hash, as in documents: { allow_remote_sources: false }'
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 0 6 6
3213 unless ref($section) eq 'HASH';
3214 6 for my $key (sort keys %$section) {
3215 6 ▶ croak "documents: unknown key '$key' (known: allow_remote_sources)"
Branch: 1 branch
BranchTrueFalseTotal
unless $key eq "allow_remote_sources" 1 5 6
3216 unless $key eq 'allow_remote_sources';
3217 }
3218 5 my $allow = 0;
3219 5 ▶ if (defined(my $v = $section->{allow_remote_sources})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $v = $section->{"allow_remote_sources"})) 5 0 5
3220 5 ▶ croak 'documents.allow_remote_sources must be true or false' if ref($v) && !blessed($v);
Branch: 1 branch
BranchTrueFalseTotal
if ref $v and not builtin::blessed($v) 2 3 5
Condition100%3/3
ref $v and not builtin::blessed($v)
!ll&&!rl&&r
212
MC/DC100%2/2
ref $v and not builtin::blessed($v)
ref $v not builtin::blessed($v)
Truth table100%3/3
A and not(B)
A= ref $vB= not builtin::blessed($v)
ABresult
0X0
100
111
3221 3 my $s = lc "$v";
3222 3 ▶ if ($s =~ /\A(?:1|true|yes|on)\z/) { $allow = 1 }
Branch: 2 branches
BranchTrueFalseTotal
if ($s =~ /\A(?:1|true|yes|on)\z/) { } 1 2 3
elsif ($s =~ /\A(?:0|false|no|off|)\z/) { } 0 2 2
3223 0 elsif ($s =~ /\A(?:0|false|no|off|)\z/) { $allow = 0 }
3224 2 else { croak 'documents.allow_remote_sources must be true or false' }
3225 }
3226 1 $self->documents_allow_remote_sources($allow);
3227 1 return;
3228 }
3229  
3230 # The realtime section (skeid k95, ADR 0029). Strict like uploads: a misspelled key or a value
3231 # that is not an integer of at least 1 fails the load. A key left out is its default, also on a
3232 # reload that drops it.
3233 25 ▶sub _load_realtime {
Subroutine _load_realtime: called CC=10 SCAR=23.0
3234 25 my ($self, $section) = @_;
3235 25 ▶ croak 'realtime must be a hash, as in realtime: { idle_timeout: 300, max_session_seconds: 3600 }'
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 2 23 25
3236 unless ref($section) eq 'HASH';
3237 23 my @known = sort keys %REALTIME_DEFAULT;
3238 23 for my $key (sort keys %$section) {
3239 croak "realtime: unknown key '$key' (known: " . join(', ', @known) . ')'
3240 30 ▶ unless exists $REALTIME_DEFAULT{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $REALTIME_DEFAULT{$key} 1 29 30
3241 }
3242 22 my %value;
3243 22 for my $key (@known) {
3244 70 ▶ my $v = exists $section->{$key} ? $section->{$key} : $REALTIME_DEFAULT{$key};
Branch: 1 branch
BranchTrueFalseTotal
exists $section->{$key} ? : 29 41 70
3245 70 ▶ croak "realtime.$key must be an integer of at least 1"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and not ref $v and $v =~ /\A[0-9]+\z/ and $v >= 1 8 62 70
Condition88%8/9
defined $v and not ref $v and $v =~ /\A[0-9]+\z/ and $v >= 1
!ll&&!rl&&r
5362
defined $v and not ref $v and $v =~ /\A[0-9]+\z/
!ll&&!rl&&r
1465
defined $v and not ref $v
!ll&&!rl&&r
0169
MC/DC75%3/4
defined $v and not ref $v and $v =~ /\A[0-9]+\z/ and $v >= 1
defined $v not ref $v $v =~ /\A[0-9]+\z/ $v >= 1
Truth table80%4/5
A and not(B) and C and D
A= defined $vB= not ref $vC= $v =~ /\A[0-9]+\z/D= $v >= 1
ABCDresult
0XXX0
10XX0
110X0
11100
11111
3246 unless defined($v) && !ref($v) && $v =~ /\A[0-9]+\z/ && $v >= 1;
3247 62 $value{$key} = 0 + $v;
3248 }
3249 14 $self->realtime_idle_timeout($value{idle_timeout});
3250 14 $self->realtime_max_session_seconds($value{max_session_seconds});
3251 14 $self->realtime_max_message_bytes($value{max_message_bytes});
3252 14 $self->realtime_max_queued_bytes($value{max_queued_bytes});
3253 14 return;
3254 }
3255  
3256 # The openapi section (skeid k105). Strict like uploads: an unknown key, a switch that is no
3257 # boolean or a cache_dir that is not an absolute path fails the load -- a relative path would
3258 # mean "wherever the process was started".
3259 17 ▶sub _load_openapi {
Subroutine _load_openapi: called CC=14 SCAR=26.6
3260 17 my ($self, $section) = @_;
3261 17 ▶ croak 'openapi must be a hash, as in openapi: { swagger_ui: true, cache_dir: /var/cache/skeid }'
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 1 16 17
3262 unless ref($section) eq 'HASH';
3263 16 for my $key (sort keys %$section) {
3264 26 ▶ croak "openapi: unknown key '$key' (known: swagger_ui, cache_dir)"
Branch: 1 branch
BranchTrueFalseTotal
unless $key eq "swagger_ui" or $key eq "cache_dir" 1 25 26
Condition100%3/3
$key eq "swagger_ui" or $key eq "cache_dir"
l!l&&r!l&&!r
13121
MC/DC100%2/2
$key eq "swagger_ui" or $key eq "cache_dir"
$key eq "swagger_ui" $key eq "cache_dir"
Truth table100%3/3
A or B
A= $key eq "swagger_ui"B= $key eq "cache_dir"
ABresult
1X1
011
000
3265 unless $key eq 'swagger_ui' || $key eq 'cache_dir';
3266 }
3267  
3268 15 my $ui = 0;
3269 15 ▶ if (defined $section->{swagger_ui}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"swagger_ui"}) 13 2 15
3270 13 my $v = $section->{swagger_ui};
3271 13 ▶ croak 'openapi.swagger_ui must be true or false' if ref($v) && !blessed($v);
Branch: 1 branch
BranchTrueFalseTotal
if ref $v and not builtin::blessed($v) 0 13 13
Condition33%1/3
ref $v and not builtin::blessed($v)
!ll&&!rl&&r
1300
MC/DC0%0/2
ref $v and not builtin::blessed($v)
ref $v not builtin::blessed($v)
Truth table33%1/3
A and not(B)
A= ref $vB= not builtin::blessed($v)
ABresult
0X0
100
111
3272 13 my $s = lc "$v";
3273 13 ▶ if ($s =~ /\A(?:1|true|yes|on)\z/) { $ui = 1 }
Branch: 2 branches
BranchTrueFalseTotal
if ($s =~ /\A(?:1|true|yes|on)\z/) { } 11 2 13
elsif ($s =~ /\A(?:0|false|no|off|)\z/) { } 1 1 2
3274 1 elsif ($s =~ /\A(?:0|false|no|off|)\z/) { $ui = 0 }
3275 1 else { croak 'openapi.swagger_ui must be true or false' }
3276 }
3277  
3278 14 my $dir = $section->{cache_dir};
3279 14 ▶ croak 'openapi.cache_dir must be an absolute path'
Branch: 1 branch
BranchTrueFalseTotal
if defined $dir and ref $dir || !($dir =~ m[\A/]) || $dir =~ /[\0\n]/ 1 13 14
Condition77%7/9
defined $dir and ref $dir || !($dir =~ m[\A/]) || $dir =~ /[\0\n]/
!ll&&!rl&&r
2111
ref $dir or not $dir =~ m[\A/] or $dir =~ /[\0\n]/
l!l&&r!l&&!r
1011
ref $dir or not $dir =~ m[\A/]
l!l&&r!l&&!r
0111
MC/DC50%2/4
defined $dir and ref $dir || !($dir =~ m[\A/]) || $dir =~ /[\0\n]/
defined $dir ref $dir not $dir =~ m[\A/] $dir =~ /[\0\n]/
Truth table60%3/5
A and B or not(C) or D
A= defined $dirB= ref $dirC= not $dir =~ m[\A/]D= $dir =~ /[\0\n]/
ABCDresult
0XXX0
10000
11XX1
101X1
10011
3280 if defined($dir) && (ref($dir) || $dir !~ m{\A/} || $dir =~ /[\0\n]/);
3281  
3282 13 $self->openapi_swagger_ui($ui);
3283 13 $self->openapi_cache_dir($dir);
3284 13 return;
3285 }
3286  
3287  
3288 3028 ▶sub client_auth_enabled { defined $_[0]->client_auth_keys ? 1 : 0 }
Subroutine client_auth_enabled: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0]->client_auth_keys ? : 378 2650 3028
3289  
3290  
3291 767 ▶sub client_key_allowed {
Subroutine client_key_allowed: called CC=3 SCAR=11.0
Pod documented
3292 767 my ($self, $api_key_id) = @_;
3293 767 my $allowed = $self->client_auth_keys;
3294 767 ▶ return 1 unless defined $allowed;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $allowed 1 766 767
3295 766 ▶ return defined($self->_configured_key_id($allowed, $api_key_id)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $self->_configured_key_id($allowed, $api_key_id) ? : 254 512 766
3296 }
3297  
3298  
3299 105 ▶sub mcp_enabled { defined $_[0]->mcp_servers ? 1 : 0 }
Subroutine mcp_enabled: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0]->mcp_servers ? : 77 28 105
3300  
3301  
3302 61 ▶sub mcp_server_for_key {
Subroutine mcp_server_for_key: called CC=6 SCAR=19.3
Pod documented
3303 61 my ($self, $name, $api_key_id) = @_;
3304 61 my $servers = $self->mcp_servers;
3305 61 ▶ return undef unless $servers && defined($name) && length($name);
Branch: 1 branch
BranchTrueFalseTotal
unless $servers and defined $name and length $name 0 61 61
Condition33%2/6
$servers and defined $name and length $name
!ll&&!rl&&r
0061
$servers and defined $name
!ll&&!rl&&r
0061
MC/DC0%0/3
$servers and defined $name and length $name
$servers defined $name length $name
Truth table25%1/4
A and B and C
A= $serversB= defined $nameC= length $name
ABCresult
0XX0
10X0
1100
1111
3306 61 ▶ my $server = $servers->{$name} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $server = $servers->{$name} or return undef 57 4 61
3307 57 ▶ return defined($self->_configured_key_id($server->{keys}, $api_key_id)) ? $server : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $self->_configured_key_id($server->{'keys'}, $api_key_id) ? : 42 15 57
3308 }
3309  
3310  
3311 9 ▶sub mcp_servers_for_key {
Subroutine mcp_servers_for_key: called CC=2 SCAR=7.0
Pod documented
3312 9 my ($self, $api_key_id) = @_;
3313 9 ▶ my $servers = $self->mcp_servers || {};
Condition50%1/2
$self->mcp_servers || {}
l!l
90
MC/DC0%0/1
$self->mcp_servers || {}
$self->mcp_servers
Truth table50%1/2
A
A= $self->mcp_servers
Aresult
11
00
3314 return [
3315 50 grep { defined $self->_configured_key_id($_->{keys}, $api_key_id) }
3316 9 map { $servers->{$_} } sort keys %$servers
3317 ];
3318 }
3319  
3320  
3321 866 ▶sub catch_all_target {
Subroutine catch_all_target: called CC=7 SCAR=19.5
Pod documented
3322 866 my ($self, $model, $route_kind) = @_;
3323 866 ▶ my $target = $self->catch_all->{$route_kind // ''};
Condition50%1/2
$route_kind // ""
l!l
8660
MC/DC0%0/1
$route_kind // ""
$route_kind
Truth table50%1/2
A
A= $route_kind
Aresult
11
00
3324 866 ▶ return unless defined $target;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $target 824 42 866
3325 42 ▶ $model //= '';
Condition50%1/2
$model //= ""
l!l
420
MC/DC0%0/1
$model //= ""
$model
Truth table50%1/2
A
A= $model
Aresult
11
00
3326 42 ▶ return if exists $self->model_aliases->{$model};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->model_aliases->{$model} 3 39 42
3327 39 my $known = $self->_known_node_models;
3328 39 ▶ return if $known->{any} || $known->{models}{$model};
Branch: 1 branch
BranchTrueFalseTotal
if $known->{"any"} or $known->{"models"}{$model} 11 28 39
Condition100%3/3
$known->{"any"} or $known->{"models"}{$model}
l!l&&r!l&&!r
11028
MC/DC100%2/2
$known->{"any"} or $known->{"models"}{$model}
$known->{"any"} $known->{"models"}{$model}
Truth table100%3/3
A or B
A= $known->{"any"}B= $known->{"models"}{$model}
ABresult
1X1
011
000
3329 28 return $target;
3330 }
3331  
3332 # Which model names the chat-kind nodes serve, and whether one of them serves any name (a node
3333 # without a model). Health is left out on purpose: a model whose nodes are down is still known.
3334 # Derived once per inventory generation, like the route cache, so the per-request check is an
3335 # integer compare and a hash lookup.
3336 39 ▶sub _known_node_models {
Subroutine _known_node_models: called CC=9 SCAR=22.4
3337 39 my ($self) = @_;
3338 39 my $generation = $self->_inventory_generation;
3339 39 my $cache = $self->_known_models_cache;
3340 39 ▶ return $cache if ($cache->{generation} // -1) == $generation;
Branch: 1 branch
BranchTrueFalseTotal
if ($cache->{"generation"} // -1) == $generation 19 20 39
Condition50%1/2
$cache->{"generation"} // -1
l!l
390
MC/DC0%0/1
$cache->{"generation"} // -1
$cache->{"generation"}
Truth table50%1/2
A
A= $cache->{"generation"}
Aresult
11
00
3341  
3342 20 my ($any, %models) = (0);
3343 20 ▶ for my $node (@{$self->nodes || []}) {
Condition50%1/2
$self->nodes || []
l!l
200
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
3344 41 ▶ next if length($node->{kind} // '');
Branch: 1 branch
BranchTrueFalseTotal
if length($node->{"kind"} // "") 0 41 41
Condition50%1/2
$node->{"kind"} // ""
l!l
041
MC/DC0%0/1
$node->{"kind"} // ""
$node->{"kind"}
Truth table50%1/2
A
A= $node->{"kind"}
Aresult
11
00
3345 41 ▶ if (defined($node->{model}) && length($node->{model})) { $models{$node->{model}} = 1 }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $node->{'model'} and length $node->{'model'}) { } 40 1 41
Condition66%2/3
defined $node->{"model"} and length $node->{"model"}
!ll&&!rl&&r
0140
MC/DC50%1/2
defined $node->{"model"} and length $node->{"model"}
defined $node->{"model"} length $node->{"model"}
Truth table66%2/3
A and B
A= defined $node->{"model"}B= length $node->{"model"}
ABresult
0X0
100
111
3346 1 else { $any = 1 }
3347 }
3348 20 $cache = { generation => $generation, any => $any, models => \%models };
3349 20 $self->_known_models_cache($cache);
3350 20 return $cache;
3351 }
3352  
3353  
3354 1320 ▶sub route_plan {
Subroutine route_plan: called CC=19 SCAR=29.6
Pod documented
3355 1320 my ($self, %args) = @_;
3356 1320 ▶ my $model = $args{model} // '';
Condition50%1/2
$args{"model"} // ""
l!l
13200
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
3357 1320 my $policy = $self->policy_for_key($args{api_key_id});
3358 1320 ▶ my $deny = $policy ? $policy->{deny_tags} : [];
Branch: 1 branch
BranchTrueFalseTotal
$policy ? : 303 1017 1320
3359 1320 my $kind = $self->_selector_kind(%args);
3360 1320 ▶ my @kind = length($kind) ? (kind => $kind) : ();
Branch: 1 branch
BranchTrueFalseTotal
length $kind ? : 59 1261 1320
3361  
3362 1320 ▶ if ($policy && $policy->{allow_models} && !$policy->{allow_models}{$model}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($policy and $policy->{"allow_models"} and not $policy->{"allow_models"}{$model}) 30 1290 1320
Condition100%6/6
$policy and $policy->{"allow_models"} and not $policy->{"allow_models"}{$model}
!ll&&!rl&&r
109619430
$policy and $policy->{"allow_models"}
!ll&&!rl&&r
101779224
MC/DC100%3/3
$policy and $policy->{"allow_models"} and not $policy->{"allow_models"}{$model}
$policy $policy->{"allow_models"} not $policy->{"allow_models"}{$model}
Truth table100%4/4
A and B and not(C)
A= $policyB= $policy->{"allow_models"}C= not $policy->{"allow_models"}{$model}
ABCresult
0XX0
10X0
1100
1111
3363 30 return { tiers => [], permitted => 0, reason => 'model_not_permitted' };
3364 }
3365  
3366 # Every tier carries the kind of the route, whatever an alias says: a documents route plans
3367 # over documents nodes and a chat route over chat nodes, so the alias named like the documents
3368 # routing key tiers the one and finds nothing for the other.
3369 1290 my $alias = $self->model_aliases->{$model};
3370 my @tiers = $alias
3371 192 ▶ ? (map { +{ %$_, deny_tags => $deny, @kind } } @{$alias->{tiers}})
Condition50%2/4
$args{"engine"} // ""
l!l
01119
$self->route_wait_timeout_ms // 0
l!l
11190
MC/DC0%0/1
$args{"engine"} // ""
$args{"engine"}
MC/DC0%0/1
$self->route_wait_timeout_ms // 0
$self->route_wait_timeout_ms
Truth table50%1/2
A
A= $args{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $self->route_wait_timeout_ms
Aresult
11
00
3372 : ({
3373 tags => [],
3374 model => $model,
3375 1290 ▶ engine => $self->normalize_engine_id($args{engine} // ''),
Branch: 1 branch
BranchTrueFalseTotal
$alias ? : 171 1119 1290
3376 wait_ms => 0 + ($self->route_wait_timeout_ms // 0),
3377 deny_tags => $deny,
3378 @kind,
3379 });
3380  
3381 1290 my $before = scalar @tiers;
3382 1290 ▶ if (@$deny) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$deny) 98 1192 1290
3383 98 my %denied = map { $_ => 1 } @$deny;
3384 @tiers = grep {
3385 98 my $tier = $_;
3386 103 ▶ !grep { $denied{$_} } @{$tier->{tags} || []};
Condition50%1/2
$tier->{'tags'} || []
l!l
1030
MC/DC0%0/1
$tier->{'tags'} || []
$tier->{'tags'}
Truth table50%1/2
A
A= $tier->{'tags'}
Aresult
11
00
3387 } @tiers;
3388 }
3389  
3390 1290 ▶ return { tiers => [], permitted => 0, reason => 'all_tiers_denied' }
Branch: 1 branch
BranchTrueFalseTotal
if $before and not @tiers 4 1286 1290
Condition66%2/3
$before and not @tiers
!ll&&!rl&&r
012864
MC/DC50%1/2
$before and not @tiers
$before not @tiers
Truth table66%2/3
A and not(B)
A= $beforeB= not @tiers
ABresult
0X0
100
111
3391 if $before && !@tiers;
3392  
3393 # A tier without its own wait_ms waits 0, except the last one left after the deny filter: it
3394 # has nowhere to fall through to and waits like a model without an alias.
3395 1286 ▶ if ($alias) {
Branch: 1 branch
BranchTrueFalseTotal
if ($alias) 167 1119 1286
3396 167 for my $i (0 .. $#tiers) {
3397 183 ▶ next if defined $tiers[$i]{wait_ms};
Branch: 1 branch
BranchTrueFalseTotal
if defined $tiers[$i]{"wait_ms"} 11 172 183
3398 172 ▶ $tiers[$i]{wait_ms} = $i == $#tiers ? 0 + ($self->route_wait_timeout_ms // 0) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$i == $#tiers ? : 161 11 172
Condition50%1/2
$self->route_wait_timeout_ms // 0
l!l
1610
MC/DC0%0/1
$self->route_wait_timeout_ms // 0
$self->route_wait_timeout_ms
Truth table50%1/2
A
A= $self->route_wait_timeout_ms
Aresult
11
00
3399 }
3400 }
3401  
3402 1286 return { tiers => \@tiers, permitted => 1, reason => '' };
3403 }
3404  
3405  
3406 54 ▶sub select_nodes {
Subroutine select_nodes: called CC=7 SCAR=19.8
Pod documented
3407 54 my ($self, %args) = @_;
3408 54 my $tags = $self->normalize_tags($args{tags});
3409 54 my $deny = $self->normalize_tags($args{deny_tags});
3410 54 ▶ my $kind = exists($args{kind}) ? $self->_selector_kind(%args) : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'kind'} ? : 50 4 54
3411 return [
3412 83 map { +{%$_} }
3413 grep {
3414 $self->_node_has_tags($_, $tags) && !$self->_node_has_any_tag($_, $deny)
3415 112 ▶ && (!defined($kind) || ($_->{kind} // '') eq $kind)
Condition72%8/11
$self->_node_has_tags($_, $tags) && !$self->_node_has_any_tag($_, $deny) && (!defined($kind) || ($_->{'kind'} // '') eq $kind)
!ll&&!rl&&r
29083
$self->_node_has_tags($_, $tags) and not $self->_node_has_any_tag($_, $deny)
!ll&&!rl&&r
27283
not defined $kind or ($_->{"kind"} // "") eq $kind
l!l&&r!l&&!r
7760
$_->{"kind"} // ""
l!l
076
MC/DC75%3/4
$self->_node_has_tags($_, $tags) && !$self->_node_has_any_tag($_, $deny) && (!defined($kind) || ($_->{'kind'} // '') eq $kind)
$self->_node_has_tags($_, $tags) not $self->_node_has_any_tag($_, $deny) not defined $kind $_->{"kind"}
Truth table80%4/5
A and not(B) && not(C) or D
A= $self->_node_has_tags($_, $tags)B= not $self->_node_has_any_tag($_, $deny)C= not defined $kindD= $_->{"kind"}
ABCDresult
0XXX0
10XX0
11000
111X1
11011
3416 }
3417 54 ▶ @{$self->nodes || []}
Condition50%1/2
$self->nodes || []
l!l
540
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
3418 ];
3419 }
3420  
3421  
3422 1789 ▶sub pick_node {
Subroutine pick_node: called CC=10 SCAR=23.0
Pod documented
3423 1789 my ($self, %args) = @_;
3424 1789 my $entry = $self->_route_entry(%args);
3425 1789 my @nodes = @{$entry->{nodes}};
3426 1789 ▶ return unless @nodes;
Branch: 1 branch
BranchTrueFalseTotal
unless @nodes 4 1785 1789
3427  
3428 1785 my @weights = @{$entry->{weights}};
3429 1785 my $total_weight = $entry->{total_weight};
3430 1785 ▶ return unless $total_weight > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $total_weight > 0 0 1785 1785
3431  
3432 1785 my $key = $self->_route_key(%args);
3433 1785 ▶ my $cursor = 0 + ($self->_rr_cursor->{$key} // 0);
Condition100%2/2
$self->_rr_cursor->{$key} // 0
l!l
7511034
MC/DC100%1/1
$self->_rr_cursor->{$key} // 0
$self->_rr_cursor->{$key}
Truth table100%2/2
A
A= $self->_rr_cursor->{$key}
Aresult
11
00
3434 1785 $cursor %= $total_weight;
3435  
3436 # Locate the weighted range containing the cursor without expanding weights into slots. From
3437 # that owner onward, the old slot walk considered nodes in inventory order and, if none admitted
3438 # before the end, wrapped to target zero. Admission is one per-node observation for this
3439 # synchronous selection pass; resampling it once per weight slot describes no new capacity.
3440 # Check each node once and skip the rest of every saturated weight range.
3441 1785 my ($owner, $range_end) = (0, 0);
3442 1785 for my $idx (0 .. $#nodes) {
3443 1824 $range_end += $weights[$idx];
3444 1824 ▶ if ($cursor < $range_end) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cursor < $range_end) 1785 39 1824
3445 1785 $owner = $idx;
3446 1785 last;
3447 }
3448 }
3449  
3450 1785 for my $offset (0 .. $#nodes) {
3451 1852 my $idx = ($owner + $offset) % @nodes;
3452 1852 my $candidate = $nodes[$idx];
3453 1852 ▶ next unless $self->_node_can_take($candidate);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_node_can_take($candidate) 341 1511 1852
3454  
3455 # Before a wrap, the historical cursor advances one weighted slot even when a later node was
3456 # selected because the owning range was saturated. After a wrap, the first target examined is
3457 # slot zero, so its successor is slot one. Keeping both cases preserves partial-saturation
3458 # ordering while avoiding one admission check per skipped slot.
3459 1511 ▶ $self->_rr_cursor->{$key} = $idx < $owner
Branch: 1 branch
BranchTrueFalseTotal
$idx < $owner ? : 6 1505 1511
3460 ? (1 % $total_weight)
3461 : (($cursor + 1) % $total_weight);
3462 1511 my $id = $candidate->{id};
3463 1511 ▶ my $inflight = 0 + ($self->_inflight->{$id} // 0);
Condition100%2/2
$self->_inflight->{$id} // 0
l!l
552959
MC/DC100%1/1
$self->_inflight->{$id} // 0
$self->_inflight->{$id}
Truth table100%2/2
A
A= $self->_inflight->{$id}
Aresult
11
00
3464 return {
3465 1511 %$candidate,
3466 inflight => $inflight,
3467 route_key => $key,
3468 };
3469 }
3470  
3471 274 return;
3472 }
3473  
3474  
3475 1835 ▶sub route_state {
Subroutine route_state: called CC=5 SCAR=16.1
Pod documented
3476 1835 my ($self, %args) = @_;
3477 1835 ▶ my $engine = $self->normalize_engine_id($args{engine} // '');
Condition100%2/2
$args{"engine"} // ""
l!l
1406429
MC/DC100%1/1
$args{"engine"} // ""
$args{"engine"}
Truth table100%2/2
A
A= $args{"engine"}
Aresult
11
00
3478 1835 my $eligible = $self->_eligible_nodes(%args);
3479 1835 my $available = [ grep { $self->_node_can_take($_) } @$eligible ];
3480  
3481 return {
3482 model => ($args{model} // ''),
3483 engine => $engine,
3484 tags => $self->normalize_tags($args{tags}),
3485 1835 ▶ deny_tags => $self->normalize_tags($args{deny_tags}),
Branch: 2 branches
BranchTrueFalseTotal
@$eligible ? : 1376 459 1835
@$available ? : 1091 744 1835
Condition50%1/2
$args{"model"} // ""
l!l
18350
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
3486 eligible_count => scalar(@$eligible),
3487 available_count => scalar(@$available),
3488 has_eligible => @$eligible ? 1 : 0,
3489 has_available => @$available ? 1 : 0,
3490 };
3491 }
3492  
3493  
3494 95 ▶sub set_capacity_reading {
Subroutine set_capacity_reading: called CC=26 SCAR=33.2
Pod documented
3495 95 my ($self, $node_id, %reading) = @_;
3496 95 ▶ croak 'node_id required' unless defined $node_id && length $node_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 95 95
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
0095
MC/DC0%0/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table33%1/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
3497  
3498 95 my $now = time;
3499 my $entry = {
3500 source => ((defined($reading{source}) && length($reading{source})) ? "$reading{source}" : 'custom'),
3501 used => (defined $reading{used} ? 0 + $reading{used} : undef),
3502 limit => (defined $reading{limit} ? 0 + $reading{limit} : undef),
3503 at => (defined $reading{at} ? 0 + $reading{at} : $now),
3504 # Which of a provider's several quotas this reading is about, when it had more than one.
3505 # For reports only -- admission just sees used and limit.
3506 (defined $reading{quota} ? (quota => "$reading{quota}") : ()),
3507 (defined $reading{expires_at} ? (expires_at => 0 + $reading{expires_at}) : ()),
3508 # How often this source reports; it sets how long this reading holds a looser one off.
3509 ((defined($reading{interval_ms}) && $reading{interval_ms} > 0)
3510 95 ▶ ? (interval_ms => 0 + $reading{interval_ms}) : ()),
Branch: 7 branches
BranchTrueFalseTotal
defined $reading{'source'} && length $reading{'source'} ? : 91 4 95
defined $reading{'used'} ? : 81 14 95
defined $reading{'limit'} ? : 81 14 95
defined $reading{'at'} ? : 22 73 95
defined $reading{'quota'} ? : 13 82 95
defined $reading{'expires_at'} ? : 20 75 95
defined $reading{'interval_ms'} && $reading{'interval_ms'} > 0 ? : 31 64 95
Condition66%4/6
defined $reading{"source"} and length $reading{"source"}
!ll&&!rl&&r
4091
defined $reading{"interval_ms"} and $reading{"interval_ms"} > 0
!ll&&!rl&&r
64031
MC/DC50%1/2
defined $reading{"source"} and length $reading{"source"}
defined $reading{"source"} length $reading{"source"}
MC/DC50%1/2
defined $reading{"interval_ms"} and $reading{"interval_ms"} > 0
defined $reading{"interval_ms"} $reading{"interval_ms"} > 0
Truth table66%2/3
A and B
A= defined $reading{"source"}B= length $reading{"source"}
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= defined $reading{"interval_ms"}B= $reading{"interval_ms"} > 0
ABresult
0X0
100
111
3511 };
3512  
3513 95 ▶ if (defined $reading{retry_after_ms} && $reading{retry_after_ms} > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $reading{'retry_after_ms'} and $reading{'retry_after_ms'} > 0) { } 14 81 95
elsif (defined $reading{'retry_after'}) { } 0 81 81
Condition66%2/3
defined $reading{"retry_after_ms"} and $reading{"retry_after_ms"} > 0
!ll&&!rl&&r
81014
MC/DC50%1/2
defined $reading{"retry_after_ms"} and $reading{"retry_after_ms"} > 0
defined $reading{"retry_after_ms"} $reading{"retry_after_ms"} > 0
Truth table66%2/3
A and B
A= defined $reading{"retry_after_ms"}B= $reading{"retry_after_ms"} > 0
ABresult
0X0
100
111
3514 14 $entry->{retry_after} = $now + ($reading{retry_after_ms} / 1000);
3515 } elsif (defined $reading{retry_after}) {
3516 0 $entry->{retry_after} = 0 + $reading{retry_after};
3517 }
3518  
3519 # Two sources disagreeing about one node: the tighter one decides while it is current.
3520 # Taking the latest instead would let whichever probe polls last lift what the other just
3521 # said. But "tighter" alone lets a reading nobody refreshes -- a passive rate-limit reading
3522 # from the last response before traffic stopped -- block a probe that says the node is empty,
3523 # for as long as capacity_max_age_ms allows (forever with 0). So only a pending backoff, or a
3524 # reading younger than the longer of the two sources' poll intervals, holds the incoming one
3525 # off: within that window neither source has had a full poll since, and the tighter one is
3526 # the safer view of the same moment. Two passive readings (no interval) never hold.
3527 95 my $current = $self->capacity_reading($node_id);
3528 95 ▶ if ($current && $current->{source} ne $entry->{source}
Branch: 1 branch
BranchTrueFalseTotal
if ($current and $current->{"source"} ne $entry->{"source"} and _reading_tightness($current) > _reading_tightness($entry)) 9 86 95
Condition100%6/6
$current and $current->{"source"} ne $entry->{"source"} and _reading_tightness($current) > _reading_tightness($entry)
!ll&&!rl&&r
8249
$current and $current->{"source"} ne $entry->{"source"}
!ll&&!rl&&r
572513
MC/DC100%3/3
$current and $current->{"source"} ne $entry->{"source"} and _reading_tightness($current) > _reading_tightness($entry)
$current $current->{"source"} ne $entry->{"source"} _reading_tightness($current) > _reading_tightness($entry)
Truth table100%4/4
A and B and C
A= $currentB= $current->{"source"} ne $entry->{"source"}C= _reading_tightness($current) > _reading_tightness($entry)
ABCresult
0XX0
10X0
1100
1111
3529 && _reading_tightness($current) > _reading_tightness($entry)) {
3530 9 ▶ my $backoff_pending = ($current->{retry_after} && time < $current->{retry_after}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$current->{'retry_after'} && time < $current->{'retry_after'} ? : 2 7 9
Condition66%2/3
$current->{"retry_after"} and time < $current->{"retry_after"}
!ll&&!rl&&r
702
MC/DC50%1/2
$current->{"retry_after"} and time < $current->{"retry_after"}
$current->{"retry_after"} time < $current->{"retry_after"}
Truth table66%2/3
A and B
A= $current->{"retry_after"}B= time < $current->{"retry_after"}
ABresult
0X0
100
111
3531 9 ▶ my ($cur_ms, $new_ms) = (($current->{interval_ms} // 0), ($entry->{interval_ms} // 0));
Condition100%4/4
$current->{"interval_ms"} // 0
l!l
45
$entry->{"interval_ms"} // 0
l!l
63
MC/DC100%1/1
$current->{"interval_ms"} // 0
$current->{"interval_ms"}
MC/DC100%1/1
$entry->{"interval_ms"} // 0
$entry->{"interval_ms"}
Truth table100%2/2
A
A= $current->{"interval_ms"}
Aresult
11
00
Truth table100%2/2
A
A= $entry->{"interval_ms"}
Aresult
11
00
3532 9 ▶ my $hold_s = ($cur_ms > $new_ms ? $cur_ms : $new_ms) / 1000;
Branch: 1 branch
BranchTrueFalseTotal
$cur_ms > $new_ms ? : 4 5 9
3533 9 ▶ my $age = Time::HiRes::time() - ($current->{at} // 0);
Condition50%1/2
$current->{"at"} // 0
l!l
90
MC/DC0%0/1
$current->{"at"} // 0
$current->{"at"}
Truth table50%1/2
A
A= $current->{"at"}
Aresult
11
00
3534 9 ▶ return $current if $backoff_pending || $age < $hold_s;
Branch: 1 branch
BranchTrueFalseTotal
if $backoff_pending or $age < $hold_s 6 3 9
Condition100%3/3
$backoff_pending or $age < $hold_s
l!l&&r!l&&!r
243
MC/DC100%2/2
$backoff_pending or $age < $hold_s
$backoff_pending $age < $hold_s
Truth table100%3/3
A or B
A= $backoff_pendingB= $age < $hold_s
ABresult
1X1
011
000
3535 }
3536  
3537 89 $self->_capacity->{$node_id} = $entry;
3538 89 return $entry;
3539 }
3540  
3541 # How much a reading holds admission back: a pending backoff above everything, then the used
3542 # fraction, then nothing for a reading without a limit.
3543 26 ▶sub _reading_tightness {
Subroutine _reading_tightness: called CC=6 SCAR=18.8
3544 26 my ($reading) = @_;
3545 26 ▶ return 9**9**9 if $reading->{retry_after} && time < $reading->{retry_after};
Branch: 1 branch
BranchTrueFalseTotal
if $reading->{"retry_after"} and time < $reading->{"retry_after"} 4 22 26
Condition66%2/3
$reading->{"retry_after"} and time < $reading->{"retry_after"}
!ll&&!rl&&r
2204
MC/DC50%1/2
$reading->{"retry_after"} and time < $reading->{"retry_after"}
$reading->{"retry_after"} time < $reading->{"retry_after"}
Truth table66%2/3
A and B
A= $reading->{"retry_after"}B= time < $reading->{"retry_after"}
ABresult
0X0
100
111
3546 22 ▶ my $limit = 0 + ($reading->{limit} // 0);
Condition50%1/2
$reading->{"limit"} // 0
l!l
220
MC/DC0%0/1
$reading->{"limit"} // 0
$reading->{"limit"}
Truth table50%1/2
A
A= $reading->{"limit"}
Aresult
11
00
3547 22 ▶ return 0 if $limit <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $limit <= 0 0 22 22
3548 22 ▶ return (0 + ($reading->{used} // 0)) / $limit;
Condition50%1/2
$reading->{"used"} // 0
l!l
220
MC/DC0%0/1
$reading->{"used"} // 0
$reading->{"used"}
Truth table50%1/2
A
A= $reading->{"used"}
Aresult
11
00
3549 }
3550  
3551  
3552 4498 ▶sub capacity_reading {
Subroutine capacity_reading: called CC=14 SCAR=26.7
Pod documented
3553 4498 my ($self, $node_id) = @_;
3554 4498 ▶ return unless defined($node_id) && length($node_id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 4498 4498
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
004498
MC/DC0%0/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table33%1/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
3555 4498 ▶ my $entry = $self->_capacity->{$node_id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $entry = $self->_capacity->{$node_id} or return 295 4203 4498
3556  
3557 295 ▶ my $backoff_pending = ($entry->{retry_after} && time < $entry->{retry_after}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$entry->{'retry_after'} && time < $entry->{'retry_after'} ? : 58 237 295
Condition66%2/3
$entry->{"retry_after"} and time < $entry->{"retry_after"}
!ll&&!rl&&r
237058
MC/DC50%1/2
$entry->{"retry_after"} and time < $entry->{"retry_after"}
$entry->{"retry_after"} time < $entry->{"retry_after"}
Truth table66%2/3
A and B
A= $entry->{"retry_after"}B= time < $entry->{"retry_after"}
ABresult
0X0
100
111
3558 295 ▶ my $max_age = 0 + ($self->capacity_max_age_ms // 0);
Condition50%1/2
$self->capacity_max_age_ms // 0
l!l
2950
MC/DC0%0/1
$self->capacity_max_age_ms // 0
$self->capacity_max_age_ms
Truth table50%1/2
A
A= $self->capacity_max_age_ms
Aresult
11
00
3559 295 ▶ if (!$backoff_pending && $max_age > 0 && (time - ($entry->{at} // 0)) > ($max_age / 1000)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $backoff_pending and $max_age > 0 and time - ($entry->{"at"} // 0) > $max_age / 1000) 1 294 295
Condition87%7/8
not $backoff_pending and $max_age > 0 and time - ($entry->{"at"} // 0) > $max_age / 1000
!ll&&!rl&&r
702241
not $backoff_pending and $max_age > 0
!ll&&!rl&&r
5812225
$entry->{"at"} // 0
l!l
2250
MC/DC100%3/3
not $backoff_pending and $max_age > 0 and time - ($entry->{"at"} // 0) > $max_age / 1000
not $backoff_pending $max_age > 0 time - ($entry->{"at"} // 0) > $max_age / 1000
MC/DC0%0/1
$entry->{"at"} // 0
$entry->{"at"}
Truth table100%4/4
not(A) and B and C
A= not $backoff_pendingB= $max_age > 0C= time - ($entry->{"at"} // 0) > $max_age / 1000
ABCresult
0XX0
10X0
1100
1111
Truth table50%1/2
A
A= $entry->{"at"}
Aresult
11
00
3560 1 delete $self->_capacity->{$node_id};
3561 1 return;
3562 }
3563 # A reading that said how long it may be believed is not believed longer (ADR 0017).
3564 294 ▶ if (!$backoff_pending && defined($entry->{expires_at}) && Time::HiRes::time() > $entry->{expires_at}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $backoff_pending and defined $entry->{"expires_at"} and &Time::HiRes::time() > $entry->{"expires_at"}) 1 293 294
Condition100%6/6
not $backoff_pending and defined $entry->{"expires_at"} and &Time::HiRes::time() > $entry->{"expires_at"}
!ll&&!rl&&r
241521
not $backoff_pending and defined $entry->{"expires_at"}
!ll&&!rl&&r
5818353
MC/DC100%3/3
not $backoff_pending and defined $entry->{"expires_at"} and &Time::HiRes::time() > $entry->{"expires_at"}
not $backoff_pending defined $entry->{"expires_at"} &Time::HiRes::time() > $entry->{"expires_at"}
Truth table100%4/4
not(A) and B and C
A= not $backoff_pendingB= defined $entry->{"expires_at"}C= &Time::HiRes::time() > $entry->{"expires_at"}
ABCresult
0XX0
10X0
1100
1111
3565 1 delete $self->_capacity->{$node_id};
3566 1 return;
3567 }
3568 293 return $entry;
3569 }
3570  
3571  
3572 69 ▶sub forget_capacity {
Subroutine forget_capacity: called CC=7 SCAR=21.1
Pod documented
3573 69 my ($self, $node_id, %args) = @_;
3574 69 ▶ if (defined($node_id) && length($node_id)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $node_id and length $node_id) 69 0 69
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
0069
MC/DC0%0/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table33%1/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
3575 69 ▶ if (defined $args{source}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"source"}) 25 44 69
3576 25 my $entry = $self->_capacity->{$node_id};
3577 25 ▶ return 0 unless $entry && ($entry->{source} // '') eq $args{source};
Branch: 1 branch
BranchTrueFalseTotal
unless $entry and ($entry->{"source"} // "") eq $args{"source"} 17 8 25
Condition80%4/5
$entry and ($entry->{"source"} // "") eq $args{"source"}
!ll&&!rl&&r
1168
$entry->{"source"} // ""
l!l
140
MC/DC50%1/2
$entry and ($entry->{"source"} // "") eq $args{"source"}
$entry $entry->{"source"}
Truth table66%2/3
A and B
A= $entryB= $entry->{"source"}
ABresult
0X0
100
111
3578 }
3579 52 delete $self->_capacity->{$node_id};
3580 52 return 1;
3581 }
3582 0 %{$self->_capacity} = ();
3583 0 return 1;
3584 }
3585  
3586 # Rate-limit headers, in the spellings the big providers actually use. Ordered: the first one
3587 # present wins, so a provider sending several does not get read twice.
3588 # Providers meter more than one thing at once, and for an LLM API the token budget is usually
3589 # what runs out first -- a node with requests to spare and no tokens left answers 429 all the
3590 # same. Each quota is read separately and the tightest one decides.
3591 #
3592 # Within a quota the order is "most specific first": the first name present wins, so a provider
3593 # sending both a specific and a generic spelling is not counted twice.
3594 127 my @RATELIMIT_QUOTAS = (
3595 {
3596 name => 'requests',
3597 remaining => [qw(
3598 x-ratelimit-remaining-requests
3599 anthropic-ratelimit-requests-remaining
3600 x-ratelimit-remaining
3601 ratelimit-remaining
3602 )],
3603 limit => [qw(
3604 x-ratelimit-limit-requests
3605 anthropic-ratelimit-requests-limit
3606 x-ratelimit-limit
3607 ratelimit-limit
3608 )],
3609 },
3610 {
3611 name => 'tokens',
3612 remaining => [qw(
3613 x-ratelimit-remaining-tokens
3614 anthropic-ratelimit-tokens-remaining
3615 anthropic-ratelimit-input-tokens-remaining
3616 )],
3617 limit => [qw(
3618 x-ratelimit-limit-tokens
3619 anthropic-ratelimit-tokens-limit
3620 anthropic-ratelimit-input-tokens-limit
3621 )],
3622 },
3623 );
3624  
3625  
3626 99 ▶sub capacity_header_names {
Subroutine capacity_header_names: called CC=1 SCAR=0.0
Pod documented
3627 99 return ((map { @{$_->{remaining}}, @{$_->{limit}} } @RATELIMIT_QUOTAS), 'retry-after');
3628 }
3629  
3630  
3631 29 ▶sub observe_response_headers {
Subroutine observe_response_headers: called CC=22 SCAR=31.9
Pod documented
3632 29 my ($self, $node_id, $headers, %args) = @_;
3633 29 ▶ return unless defined($node_id) && length($node_id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 29 29
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
0029
MC/DC0%0/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table33%1/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
3634 29 ▶ return unless ref($headers) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $headers eq "HASH" 0 29 29
3635  
3636 # Case-insensitive: header casing is not something a provider promises.
3637 29 my %h = map { lc($_) => $headers->{$_} } keys %$headers;
3638 29 my %reading = (source => 'ratelimit');
3639 29 my $useful = 0;
3640  
3641 # The tightest quota wins, compared as a fraction because requests and tokens are not the
3642 # same unit. Reporting the roomier one would admit a request the provider is about to refuse.
3643 29 my $tightest = -1;
3644 29 for my $quota (@RATELIMIT_QUOTAS) {
3645 58 my ($remaining) = grep { defined } map { $h{$_} } @{$quota->{remaining}};
3646 58 ▶ next unless defined($remaining) && $remaining =~ /^\s*(\d+)/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $remaining and $remaining =~ /^\s*(\d+)/ 42 16 58
Condition66%2/3
defined $remaining and $remaining =~ /^\s*(\d+)/
!ll&&!rl&&r
42016
MC/DC50%1/2
defined $remaining and $remaining =~ /^\s*(\d+)/
defined $remaining $remaining =~ /^\s*(\d+)/
Truth table66%2/3
A and B
A= defined $remainingB= $remaining =~ /^\s*(\d+)/
ABresult
0X0
100
111
3647 16 my $left = 0 + $1;
3648  
3649 16 my ($limit) = grep { defined } map { $h{$_} } @{$quota->{limit}};
3650 # The probe contract counts what is used, not what is left; a limit we were not told is
3651 # reconstructed as "one more than we have", which is enough to stop admitting at zero.
3652 16 ▶ my $total = (defined($limit) && $limit =~ /^\s*(\d+)/) ? 0 + $1 : $left + 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $limit && $limit =~ /^\s*(\d+)/ ? : 13 3 16
Condition66%2/3
defined $limit and $limit =~ /^\s*(\d+)/
!ll&&!rl&&r
3013
MC/DC50%1/2
defined $limit and $limit =~ /^\s*(\d+)/
defined $limit $limit =~ /^\s*(\d+)/
Truth table66%2/3
A and B
A= defined $limitB= $limit =~ /^\s*(\d+)/
ABresult
0X0
100
111
3653 16 ▶ next unless $total > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $total > 0 0 16 16
3654  
3655 16 my $used = $total - $left;
3656 16 ▶ $used = $total if $used > $total;
Branch: 1 branch
BranchTrueFalseTotal
if $used > $total 0 16 16
3657 16 ▶ $used = 0 if $used < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $used < 0 0 16 16
3658  
3659 16 my $fraction = $used / $total;
3660 16 ▶ next unless $fraction > $tightest;
Branch: 1 branch
BranchTrueFalseTotal
unless $fraction > $tightest 1 15 16
3661 15 $tightest = $fraction;
3662 15 $reading{limit} = $total;
3663 15 $reading{used} = $used;
3664 15 $reading{quota} = $quota->{name};
3665 15 $useful = 1;
3666 }
3667  
3668 29 my $retry = $h{'retry-after'};
3669 29 ▶ my $status = 0 + ($args{status} // 0);
Condition100%2/2
$args{"status"} // 0
l!l
1613
MC/DC100%1/1
$args{"status"} // 0
$args{"status"}
Truth table100%2/2
A
A= $args{"status"}
Aresult
11
00
3670 29 ▶ if ($status == 429 || defined $retry) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status == 429 or defined $retry) 13 16 29
Condition66%2/3
$status == 429 or defined $retry
l!l&&r!l&&!r
13016
MC/DC50%1/2
$status == 429 or defined $retry
$status == 429 defined $retry
Truth table66%2/3
A or B
A= $status == 429B= defined $retry
ABresult
1X1
011
000
3671 13 my $secs;
3672 13 ▶ if (defined($retry) && $retry =~ /^\s*([\d.]+)\s*$/) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $retry and $retry =~ /^\s*([\d.]+)\s*$/) { } 8 5 13
elsif ($status == 429) { } 5 0 5
Condition66%2/3
defined $retry and $retry =~ /^\s*([\d.]+)\s*$/
!ll&&!rl&&r
508
MC/DC50%1/2
defined $retry and $retry =~ /^\s*([\d.]+)\s*$/
defined $retry $retry =~ /^\s*([\d.]+)\s*$/
Truth table66%2/3
A and B
A= defined $retryB= $retry =~ /^\s*([\d.]+)\s*$/
ABresult
0X0
100
111
3673 8 $secs = 0 + $1;
3674 } elsif ($status == 429) {
3675 # A 429 with no Retry-After still means "not now". One second is short enough not to
3676 # strand capacity and long enough to stop hammering.
3677 5 $secs = 1;
3678 }
3679 13 ▶ if (defined $secs && $secs > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $secs and $secs > 0) 13 0 13
Condition33%1/3
defined $secs and $secs > 0
!ll&&!rl&&r
0013
MC/DC0%0/2
defined $secs and $secs > 0
defined $secs $secs > 0
Truth table33%1/3
A and B
A= defined $secsB= $secs > 0
ABresult
0X0
100
111
3680 13 $reading{retry_after_ms} = $secs * 1000;
3681 13 $useful = 1;
3682 }
3683 }
3684  
3685 29 ▶ return unless $useful;
Branch: 1 branch
BranchTrueFalseTotal
unless $useful 3 26 29
3686 26 return $self->set_capacity_reading($node_id, %reading);
3687 }
3688  
3689  
3690 1123 ▶sub start_request {
Subroutine start_request: called CC=8 SCAR=21.4
Pod documented
3691 1123 my ($self, $node_id) = @_;
3692 1123 ▶ croak 'node_id required' unless defined $node_id && length $node_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 1123 1123
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
001123
MC/DC0%0/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table33%1/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
3693 1123 ▶ my $node = (grep { ($_->{id} // '') eq $node_id } @{$self->nodes})[0];
Condition50%1/2
$_->{"id"} // ""
l!l
25260
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
3694 1123 ▶ return 0 unless $node && $self->_node_can_take($node);
Branch: 1 branch
BranchTrueFalseTotal
unless $node and $self->_node_can_take($node) 6 1117 1123
Condition66%2/3
$node and $self->_node_can_take($node)
!ll&&!rl&&r
061117
MC/DC50%1/2
$node and $self->_node_can_take($node)
$node $self->_node_can_take($node)
Truth table66%2/3
A and B
A= $nodeB= $self->_node_can_take($node)
ABresult
0X0
100
111
3695  
3696 1117 ▶ $self->_inflight->{$node_id} = 1 + ($self->_inflight->{$node_id} // 0);
Condition100%2/2
$self->_inflight->{$node_id} // 0
l!l
577540
MC/DC100%1/1
$self->_inflight->{$node_id} // 0
$self->_inflight->{$node_id}
Truth table100%2/2
A
A= $self->_inflight->{$node_id}
Aresult
11
00
3697 1117 ▶ $self->_stats->{$node_id}{started} = 1 + ($self->_stats->{$node_id}{started} // 0);
Condition100%2/2
$self->_stats->{$node_id}{"started"} // 0
l!l
577540
MC/DC100%1/1
$self->_stats->{$node_id}{"started"} // 0
$self->_stats->{$node_id}{"started"}
Truth table100%2/2
A
A= $self->_stats->{$node_id}{"started"}
Aresult
11
00
3698 1117 return 1;
3699 }
3700  
3701  
3702 1109 ▶sub finish_request {
Subroutine finish_request: called CC=14 SCAR=26.6
Pod documented
3703 1109 my ($self, $node_id, %args) = @_;
3704 1109 ▶ croak 'node_id required' unless defined $node_id && length $node_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 1109 1109
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
001109
MC/DC0%0/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table33%1/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
3705 1109 ▶ my $cur = 0 + ($self->_inflight->{$node_id} // 0);
Condition50%1/2
$self->_inflight->{$node_id} // 0
l!l
11090
MC/DC0%0/1
$self->_inflight->{$node_id} // 0
$self->_inflight->{$node_id}
Truth table50%1/2
A
A= $self->_inflight->{$node_id}
Aresult
11
00
3706 1109 $cur--;
3707 1109 ▶ $cur = 0 if $cur < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cur < 0 0 1109 1109
3708 1109 $self->_inflight->{$node_id} = $cur;
3709  
3710 1109 ▶ if ($args{aborted}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($args{'aborted'}) { } 33 1076 1109
elsif ($args{'rejected'}) { } 31 1045 1076
elsif ($args{'ok'}) { } 884 161 1045
3711 # The client left. The node did nothing wrong: not an error, not a failure in the window.
3712 33 ▶ $self->_stats->{$node_id}{aborted} = 1 + ($self->_stats->{$node_id}{aborted} // 0);
Condition100%2/2
$self->_stats->{$node_id}{"aborted"} // 0
l!l
1815
MC/DC100%1/1
$self->_stats->{$node_id}{"aborted"} // 0
$self->_stats->{$node_id}{"aborted"}
Truth table100%2/2
A
A= $self->_stats->{$node_id}{"aborted"}
Aresult
11
00
3713 } elsif ($args{rejected}) {
3714 # The client's to fix: not an error, not a failure in the window, and not the node's ok.
3715 31 ▶ $self->_stats->{$node_id}{rejected} = 1 + ($self->_stats->{$node_id}{rejected} // 0);
Condition100%2/2
$self->_stats->{$node_id}{"rejected"} // 0
l!l
1912
MC/DC100%1/1
$self->_stats->{$node_id}{"rejected"} // 0
$self->_stats->{$node_id}{"rejected"}
Truth table100%2/2
A
A= $self->_stats->{$node_id}{"rejected"}
Aresult
11
00
3716 31 $self->_record_failure($node_id, $self->_rejections);
3717 } elsif ($args{ok}) {
3718 884 ▶ $self->_stats->{$node_id}{ok} = 1 + ($self->_stats->{$node_id}{ok} // 0);
Condition100%2/2
$self->_stats->{$node_id}{"ok"} // 0
l!l
477407
MC/DC100%1/1
$self->_stats->{$node_id}{"ok"} // 0
$self->_stats->{$node_id}{"ok"}
Truth table100%2/2
A
A= $self->_stats->{$node_id}{"ok"}
Aresult
11
00
3719 } else {
3720 161 ▶ $self->_stats->{$node_id}{error} = 1 + ($self->_stats->{$node_id}{error} // 0);
Condition100%2/2
$self->_stats->{$node_id}{"error"} // 0
l!l
45116
MC/DC100%1/1
$self->_stats->{$node_id}{"error"} // 0
$self->_stats->{$node_id}{"error"}
Truth table100%2/2
A
A= $self->_stats->{$node_id}{"error"}
Aresult
11
00
3721 161 $self->_record_failure($node_id);
3722 }
3723  
3724 1109 ▶ if (defined $args{duration_ms}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"duration_ms"}) 1065 44 1109
3725 $self->_stats->{$node_id}{duration_ms_total}
3726 1065 ▶ = (0 + ($self->_stats->{$node_id}{duration_ms_total} // 0)) + (0 + $args{duration_ms});
Condition100%2/2
$self->_stats->{$node_id}{"duration_ms_total"} // 0
l!l
548517
MC/DC100%1/1
$self->_stats->{$node_id}{"duration_ms_total"} // 0
$self->_stats->{$node_id}{"duration_ms_total"}
Truth table100%2/2
A
A= $self->_stats->{$node_id}{"duration_ms_total"}
Aresult
11
00
3727 }
3728  
3729 1109 return 1;
3730 }
3731  
3732 # One bucket per second, pruned to the window on every write, so a node that fails a lot costs
3733 # at most error_window_s buckets.
3734 192 ▶sub _record_failure {
Subroutine _record_failure: called CC=6 SCAR=18.2
3735 192 my ($self, $node_id, $store) = @_;
3736 192 my $now = Time::HiRes::time();
3737 192 ▶ my $f = ($store || $self->_failures)->{$node_id} //= { buckets => {} };
Condition80%4/5
+($store || $self->_failures)->{$node_id} //= {"buckets", {}}
l!l
64128
$store || $self->_failures
l!l&&r!l&&!r
311610
MC/DC0%0/2
+($store || $self->_failures)->{$node_id} //= {"buckets", {}}
$store $self->_failures
Truth table66%2/3
A || B
A= $storeB= $self->_failures
ABresult
1X1
011
000
3738 192 $f->{last_at} = $now;
3739 192 $f->{buckets}{int $now}++;
3740 192 ▶ my $oldest = int($now - (0 + ($self->registry_error_window_s || 60)));
Condition50%1/2
$self->registry_error_window_s || 60
l!l
1920
MC/DC0%0/1
$self->registry_error_window_s || 60
$self->registry_error_window_s
Truth table50%1/2
A
A= $self->registry_error_window_s
Aresult
11
00
3741 192 for my $second (keys %{$f->{buckets}}) {
3742 214 ▶ delete $f->{buckets}{$second} if $second < $oldest;
Branch: 1 branch
BranchTrueFalseTotal
if $second < $oldest 0 214 214
3743 }
3744 192 return;
3745 }
3746  
3747 150 ▶sub _errors_in_window {
Subroutine _errors_in_window: called CC=6 SCAR=18.2
3748 150 my ($self, $node_id, $store) = @_;
3749 150 ▶ my $f = ($store || $self->_failures)->{$node_id} or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $f = +($store || $self->_failures)->{$node_id} or return 0 17 133 150
Condition66%2/3
$store || $self->_failures
l!l&&r!l&&!r
75750
MC/DC0%0/2
$store || $self->_failures
$store $self->_failures
Truth table66%2/3
A || B
A= $storeB= $self->_failures
ABresult
1X1
011
000
3750 17 ▶ my $oldest = int(Time::HiRes::time() - (0 + ($self->registry_error_window_s || 60)));
Condition50%1/2
$self->registry_error_window_s || 60
l!l
170
MC/DC0%0/1
$self->registry_error_window_s || 60
$self->registry_error_window_s
Truth table50%1/2
A
A= $self->registry_error_window_s
Aresult
11
00
3751 17 my $count = 0;
3752 17 for my $second (keys %{$f->{buckets}}) {
3753 17 ▶ $count += $f->{buckets}{$second} if $second >= $oldest;
Branch: 1 branch
BranchTrueFalseTotal
if $second >= $oldest 17 0 17
3754 }
3755 17 return $count;
3756 }
3757  
3758  
3759 36 ▶sub registry_snapshot {
Subroutine registry_snapshot: called CC=19 SCAR=34.8
Pod documented
3760 36 my ($self) = @_;
3761 36 my $instance = $self->registry_instance_id;
3762 36 ▶ unless (defined($instance) && length($instance)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $instance and length $instance) 35 1 36
Condition66%2/3
defined $instance and length $instance
!ll&&!rl&&r
3501
MC/DC50%1/2
defined $instance and length $instance
defined $instance length $instance
Truth table66%2/3
A and B
A= defined $instanceB= length $instance
ABresult
0X0
100
111
3763 35 require Sys::Hostname;
3764 35 $instance = Sys::Hostname::hostname();
3765 }
3766  
3767 36 my @nodes;
3768 36 ▶ for my $node (sort { ($a->{id} // '') cmp ($b->{id} // '') } @{$self->nodes || []}) {
Condition50%3/6
$Langertha::Skeid::a->{"id"} // ""
l!l
620
$Langertha::Skeid::b->{"id"} // ""
l!l
620
$self->nodes || []
l!l
360
MC/DC0%0/1
$Langertha::Skeid::a->{"id"} // ""
$Langertha::Skeid::a->{"id"}
MC/DC0%0/1
$Langertha::Skeid::b->{"id"} // ""
$Langertha::Skeid::b->{"id"}
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $Langertha::Skeid::a->{"id"}
Aresult
11
00
Truth table50%1/2
A
A= $Langertha::Skeid::b->{"id"}
Aresult
11
00
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
3769 75 ▶ my $id = $node->{id} // next;
Condition50%1/2
$node->{"id"} // (next)
l!l
750
MC/DC0%0/1
$node->{"id"} // (next)
$node->{"id"}
Truth table50%1/2
A
A= $node->{"id"}
Aresult
11
00
3770 75 my $reading = $self->capacity_reading($id);
3771 75 my $failure = $self->_failures->{$id};
3772 push @nodes, {
3773 id => "$id",
3774 75 ▶ tags => [ @{$node->{tags} || []} ],
Branch: 6 branches
BranchTrueFalseTotal
$node->{'healthy'} ? : 75 0 75
$failure && defined $failure->{'last_at'} ? : 8 67 75
$reading ? : 0 75 75
defined $reading->{'used'} ? : 0 0 0
defined $reading->{'limit'} ? : 0 0 0
$reading->{'retry_after'} ? : 0 0 0
Condition71%5/7
$node->{'tags'} || []
l!l
750
$self->_inflight->{$id} // 0
l!l
5916
$failure and defined $failure->{"last_at"}
!ll&&!rl&&r
6708
MC/DC0%0/1
$node->{'tags'} || []
$node->{'tags'}
MC/DC100%1/1
$self->_inflight->{$id} // 0
$self->_inflight->{$id}
MC/DC50%1/2
$failure and defined $failure->{"last_at"}
$failure defined $failure->{"last_at"}
Truth table50%1/2
A
A= $node->{'tags'}
Aresult
11
00
Truth table100%2/2
A
A= $self->_inflight->{$id}
Aresult
11
00
Truth table66%2/3
A and B
A= $failureB= defined $failure->{"last_at"}
ABresult
0X0
100
111
3775 healthy => ($node->{healthy} ? 1 : 0),
3776 inflight => 0 + ($self->_inflight->{$id} // 0),
3777 max_conns => 0 + $self->worker_max_conns($node),
3778 errors_in_window => 0 + $self->_errors_in_window($id),
3779 last_failure_at => ($failure && defined $failure->{last_at} ? 0 + $failure->{last_at} : undef),
3780 rejected_in_window => 0 + $self->_errors_in_window($id, $self->_rejections),
3781 ($reading ? (capacity => {
3782 used => (defined $reading->{used} ? 0 + $reading->{used} : undef),
3783 limit => (defined $reading->{limit} ? 0 + $reading->{limit} : undef),
3784 source => "$reading->{source}",
3785 75 ($reading->{retry_after} ? (retry_after => 0 + $reading->{retry_after}) : ()),
3786 }) : ()),
3787 };
3788 }
3789  
3790 return {
3791 36 ▶ version => 1,
Condition50%2/4
$self->registry_ttl_s || 10
l!l
360
$self->worker_count // 1
l!l
360
MC/DC0%0/1
$self->registry_ttl_s || 10
$self->registry_ttl_s
MC/DC0%0/1
$self->worker_count // 1
$self->worker_count
Truth table50%1/2
A
A= $self->registry_ttl_s
Aresult
11
00
Truth table50%1/2
A
A= $self->worker_count
Aresult
11
00
3792 instance => "$instance",
3793 generated_at => Time::HiRes::time(),
3794 ttl => 0 + ($self->registry_ttl_s || 10),
3795 workers => 0 + ($self->worker_count // 1),
3796 nodes => \@nodes,
3797 };
3798 }
3799  
3800  
3801 338 ▶sub node_metrics {
Subroutine node_metrics: called CC=13 SCAR=25.7
Pod documented
3802 338 my ($self, $node_id) = @_;
3803 338 ▶ if (defined $node_id && length $node_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $node_id and length $node_id) 335 3 338
Condition66%2/3
defined $node_id and length $node_id
!ll&&!rl&&r
30335
MC/DC50%1/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table66%2/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
3804 335 ▶ my $s = $self->_stats->{$node_id} || {};
Condition100%2/2
$self->_stats->{$node_id} || {}
l!l
30629
MC/DC100%1/1
$self->_stats->{$node_id} || {}
$self->_stats->{$node_id}
Truth table100%2/2
A
A= $self->_stats->{$node_id}
Aresult
11
00
3805 335 my $reading = $self->capacity_reading($node_id);
3806 return {
3807 node_id => $node_id,
3808 inflight => 0 + ($self->_inflight->{$node_id} // 0),
3809 started => 0 + ($s->{started} // 0),
3810 ok => 0 + ($s->{ok} // 0),
3811 error => 0 + ($s->{error} // 0),
3812 aborted => 0 + ($s->{aborted} // 0),
3813 rejected => 0 + ($s->{rejected} // 0),
3814 335 ▶ duration_ms_total => 0 + ($s->{duration_ms_total} // 0),
Branch: 1 branch
BranchTrueFalseTotal
$reading ? : 16 319 335
Condition100%14/14
$self->_inflight->{$node_id} // 0
l!l
30629
$s->{"started"} // 0
l!l
30629
$s->{"ok"} // 0
l!l
123212
$s->{"error"} // 0
l!l
113222
$s->{"aborted"} // 0
l!l
36299
$s->{"rejected"} // 0
l!l
24311
$s->{"duration_ms_total"} // 0
l!l
27659
MC/DC100%1/1
$self->_inflight->{$node_id} // 0
$self->_inflight->{$node_id}
MC/DC100%1/1
$s->{"started"} // 0
$s->{"started"}
MC/DC100%1/1
$s->{"ok"} // 0
$s->{"ok"}
MC/DC100%1/1
$s->{"error"} // 0
$s->{"error"}
MC/DC100%1/1
$s->{"aborted"} // 0
$s->{"aborted"}
MC/DC100%1/1
$s->{"rejected"} // 0
$s->{"rejected"}
MC/DC100%1/1
$s->{"duration_ms_total"} // 0
$s->{"duration_ms_total"}
Truth table100%2/2
A
A= $self->_inflight->{$node_id}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"started"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"ok"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"error"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"aborted"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"rejected"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"duration_ms_total"}
Aresult
11
00
3815 # Present only when a probe has something current to say. A report must not present a
3816 # measured node and an inferred one as equally known (ADR 0009).
3817 ($reading ? (capacity => { %$reading }) : ()),
3818 };
3819 }
3820  
3821 3 my @rows;
3822 3 for my $n (@{$self->nodes}) {
3823 6 push @rows, $self->node_metrics($n->{id});
3824 }
3825 3 return \@rows;
3826 }
3827  
3828  
3829 8376 ▶sub call_function {
Subroutine call_function: called CC=58 SCAR=54.2
Pod documented
3830 8376 my ($self, $name, $args) = @_;
3831 8376 ▶ $args ||= {};
Condition50%1/2
$args ||= {}
l!l
83760
MC/DC0%0/1
$args ||= {}
$args
Truth table50%1/2
A
A= $args
Aresult
11
00
3832 8376 ▶ croak 'function name required' unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 8376 8376
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
008376
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
3833 8376 ▶ croak 'function args must be hashref' unless ref($args) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "HASH" 0 8376 8376
3834  
3835 # Dynamic config refresh on each task/function dispatch. Never dies: a failed reload keeps
3836 # the previous config and is reported by reload_status (skeid #39).
3837 8376 $self->maybe_reload_config;
3838  
3839 8376 ▶ if ($name eq 'metrics.estimate_cost') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "metrics.estimate_cost") 0 8376 8376
3840 0 return $self->estimate_cost(%$args);
3841 }
3842 8376 ▶ if ($name eq 'metrics.normalize') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "metrics.normalize") 721 7655 8376
3843 721 return $self->normalize_metrics(%$args);
3844 }
3845 7655 ▶ if ($name eq 'pricing.set') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "pricing.set") 13 7642 7655
3846 13 ▶ my $model = $args->{model} // croak 'pricing.set: model required';
Condition50%1/2
$args->{"model"} // croak("pricing.set: model required")
l!l
130
MC/DC0%0/1
$args->{"model"} // croak("pricing.set: model required")
$args->{"model"}
Truth table50%1/2
A
A= $args->{"model"}
Aresult
11
00
3847 13 ▶ my $pricing = $args->{pricing} // croak 'pricing.set: pricing required';
Condition50%1/2
$args->{"pricing"} // croak("pricing.set: pricing required")
l!l
130
MC/DC0%0/1
$args->{"pricing"} // croak("pricing.set: pricing required")
$args->{"pricing"}
Truth table50%1/2
A
A= $args->{"pricing"}
Aresult
11
00
3848 13 return $self->set_model_pricing($model, $pricing);
3849 }
3850 7642 ▶ if ($name eq 'nodes.add') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.add") 3 7639 7642
3851 3 ▶ return { ok => $self->add_node(%$args) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->add_node(%$args) ? : 1 0 1
3852 }
3853 7639 ▶ if ($name eq 'nodes.remove') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.remove") 0 7639 7639
3854 0 ▶ return { ok => $self->remove_node($args->{id}) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->remove_node($args->{'id'}) ? : 0 0 0
3855 }
3856 7639 ▶ if ($name eq 'nodes.list') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.list") 265 7374 7639
3857 265 return { nodes => $self->list_nodes };
3858 }
3859 7374 ▶ if ($name eq 'nodes.select') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.select") 0 7374 7374
3860 0 return { nodes => $self->select_nodes(tags => $args->{tags}, deny_tags => $args->{deny_tags}) };
3861 }
3862 7374 ▶ if ($name eq 'alias.set') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "alias.set") 0 7374 7374
3863 0 ▶ my $alias = $args->{name} // croak 'alias.set: name required';
Condition0%0/2
$args->{"name"} // croak("alias.set: name required")
l!l
00
MC/DC0%0/1
$args->{"name"} // croak("alias.set: name required")
$args->{"name"}
Truth table0%0/2
A
A= $args->{"name"}
Aresult
11
00
3864 0 ▶ return { ok => $self->set_model_alias($alias, $args->{alias} // $args) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->set_model_alias($alias, $args->{'alias'} // $args) ? : 0 0 0
Condition0%0/3
$args->{"alias"} // $args
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{"alias"} // $args
$args->{"alias"} $args
Truth table0%0/3
A // B
A= $args->{"alias"}B= $args
ABresult
1X1
011
000
3865 }
3866 7374 ▶ if ($name eq 'route.plan') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "route.plan") 1162 6212 7374
3867 return $self->route_plan(
3868 model => ($args->{model} // ''),
3869 engine => $args->{engine},
3870 api_key_id => $args->{api_key_id},
3871 kind => $args->{kind},
3872 1162 ▶ );
Condition50%1/2
$args->{"model"} // ""
l!l
11620
MC/DC0%0/1
$args->{"model"} // ""
$args->{"model"}
Truth table50%1/2
A
A= $args->{"model"}
Aresult
11
00
3873 }
3874 6212 ▶ if ($name eq 'policy.set') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "policy.set") 0 6212 6212
3875 0 ▶ my $policy = $args->{name} // croak 'policy.set: name required';
Condition0%0/2
$args->{"name"} // croak("policy.set: name required")
l!l
00
MC/DC0%0/1
$args->{"name"} // croak("policy.set: name required")
$args->{"name"}
Truth table0%0/2
A
A= $args->{"name"}
Aresult
11
00
3876 0 ▶ return { ok => $self->set_policy($policy, $args->{policy} // $args) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->set_policy($policy, $args->{'policy'} // $args) ? : 0 0 0
Condition0%0/3
$args->{"policy"} // $args
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{"policy"} // $args
$args->{"policy"} $args
Truth table0%0/3
A // B
A= $args->{"policy"}B= $args
ABresult
1X1
011
000
3877 }
3878 6212 ▶ if ($name eq 'policy.for_key') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "policy.for_key") 0 6212 6212
3879 0 return { policy => $self->policy_for_key($args->{api_key_id}) };
3880 }
3881 6212 ▶ if ($name eq 'nodes.set_health') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.set_health") 17 6195 6212
3882 17 ▶ return { ok => $self->set_node_health($args->{id}, $args->{healthy}) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->set_node_health($args->{'id'}, $args->{'healthy'}) ? : 17 0 17
3883 }
3884 6195 ▶ if ($name eq 'nodes.metrics') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.metrics") 1 6194 6195
3885 1 return { metrics => $self->node_metrics($args->{id}) };
3886 }
3887 6194 ▶ if ($name eq 'engines.list') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "engines.list") 0 6194 6194
3888 0 return { engines => $self->supported_engine_ids };
3889 }
3890 6194 ▶ if ($name eq 'route.next') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "route.next") 1340 4854 6194
3891 my $node = $self->pick_node(
3892 model => ($args->{model} // ''),
3893 engine => $self->normalize_engine_id($args->{engine} // ''),
3894 tags => $args->{tags},
3895 deny_tags => $args->{deny_tags},
3896 kind => $args->{kind},
3897 1340 ▶ );
Condition50%2/4
$args->{"model"} // ""
l!l
13400
$args->{"engine"} // ""
l!l
01340
MC/DC0%0/1
$args->{"model"} // ""
$args->{"model"}
MC/DC0%0/1
$args->{"engine"} // ""
$args->{"engine"}
Truth table50%1/2
A
A= $args->{"model"}
Aresult
11
00
Truth table50%1/2
A
A= $args->{"engine"}
Aresult
11
00
3898 1340 return { node => $node };
3899 }
3900 4854 ▶ if ($name eq 'route.state') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "route.state") 1406 3448 4854
3901 1406 ▶ my $engine = $self->normalize_engine_id($args->{engine} // '');
Condition50%1/2
$args->{"engine"} // ""
l!l
01406
MC/DC0%0/1
$args->{"engine"} // ""
$args->{"engine"}
Truth table50%1/2
A
A= $args->{"engine"}
Aresult
11
00
3902 return $self->route_state(
3903 model => ($args->{model} // ''),
3904 engine => $engine,
3905 tags => $args->{tags},
3906 deny_tags => $args->{deny_tags},
3907 kind => $args->{kind},
3908 1406 ▶ );
Condition50%1/2
$args->{"model"} // ""
l!l
14060
MC/DC0%0/1
$args->{"model"} // ""
$args->{"model"}
Truth table50%1/2
A
A= $args->{"model"}
Aresult
11
00
3909 }
3910 3448 ▶ if ($name eq 'capacity.set') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "capacity.set") 0 3448 3448
3911 0 ▶ my $id = $args->{id} // croak 'capacity.set: id required';
Condition0%0/2
$args->{"id"} // croak("capacity.set: id required")
l!l
00
MC/DC0%0/1
$args->{"id"} // croak("capacity.set: id required")
$args->{"id"}
Truth table0%0/2
A
A= $args->{"id"}
Aresult
11
00
3912 0 return { capacity => $self->set_capacity_reading($id, %$args) };
3913 }
3914 3448 ▶ if ($name eq 'capacity.get') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "capacity.get") 0 3448 3448
3915 0 ▶ my $id = $args->{id} // croak 'capacity.get: id required';
Condition0%0/2
$args->{"id"} // croak("capacity.get: id required")
l!l
00
MC/DC0%0/1
$args->{"id"} // croak("capacity.get: id required")
$args->{"id"}
Truth table0%0/2
A
A= $args->{"id"}
Aresult
11
00
3916 0 return { capacity => $self->capacity_reading($id) };
3917 }
3918 3448 ▶ if ($name eq 'capacity.observe') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "capacity.observe") 7 3441 3448
3919 7 ▶ my $id = $args->{id} // croak 'capacity.observe: id required';
Condition50%1/2
$args->{"id"} // croak("capacity.observe: id required")
l!l
70
MC/DC0%0/1
$args->{"id"} // croak("capacity.observe: id required")
$args->{"id"}
Truth table50%1/2
A
A= $args->{"id"}
Aresult
11
00
3920 return { capacity => $self->observe_response_headers(
3921 7 ▶ $id, ($args->{headers} || {}), status => $args->{status}) };
Condition50%1/2
$args->{'headers'} || {}
l!l
70
MC/DC0%0/1
$args->{'headers'} || {}
$args->{'headers'}
Truth table50%1/2
A
A= $args->{'headers'}
Aresult
11
00
3922 }
3923 3441 ▶ if ($name eq 'capacity.forget') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "capacity.forget") 0 3441 3441
3924 0 ▶ return { ok => $self->forget_capacity($args->{id}) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->forget_capacity($args->{'id'}) ? : 0 0 0
3925 }
3926 3441 ▶ if ($name eq 'request.start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "request.start") 1066 2375 3441
3927 1066 ▶ my $id = $args->{id} // croak 'request.start: id required';
Condition50%1/2
$args->{"id"} // croak("request.start: id required")
l!l
10660
MC/DC0%0/1
$args->{"id"} // croak("request.start: id required")
$args->{"id"}
Truth table50%1/2
A
A= $args->{"id"}
Aresult
11
00
3928 1066 ▶ return { ok => $self->start_request($id) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->start_request($id) ? : 1066 0 1066
3929 }
3930 2375 ▶ if ($name eq 'request.finish') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "request.finish") 1065 1310 2375
3931 1065 ▶ my $id = $args->{id} // croak 'request.finish: id required';
Condition50%1/2
$args->{"id"} // croak("request.finish: id required")
l!l
10650
MC/DC0%0/1
$args->{"id"} // croak("request.finish: id required")
$args->{"id"}
Truth table50%1/2
A
A= $args->{"id"}
Aresult
11
00
3932 1065 ▶ return { ok => $self->finish_request($id, %$args) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->finish_request($id, %$args) ? : 1065 0 1065
3933 }
3934 1310 ▶ if ($name eq 'config.reload') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "config.reload") 1 1309 1310
3935 1 return { config => $self->reload_config };
3936 }
3937 1309 ▶ if ($name eq 'config.status') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "config.status") 15 1294 1309
3938 15 return $self->reload_status;
3939 }
3940 1294 ▶ if ($name eq 'usage.record') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "usage.record") 1228 66 1294
3941 1228 return $self->record_usage(%$args);
3942 }
3943 66 ▶ if ($name eq 'usage.report') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "usage.report") 65 1 66
3944 65 return $self->usage_report(%$args);
3945 }
3946 1 ▶ if ($name eq 'usage.configure') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "usage.configure") 1 0 1
3947 1 ▶ my $store = $args->{usage_store} // $args;
Condition33%1/3
$args->{"usage_store"} // $args
l!l&&r!l&&!r
100
MC/DC0%0/2
$args->{"usage_store"} // $args
$args->{"usage_store"} $args
Truth table33%1/3
A // B
A= $args->{"usage_store"}B= $args
ABresult
1X1
011
000
3948 1 return { usage_store => $self->configure_usage_store($store) };
3949 }
3950  
3951 0 croak "unknown function: $name";
3952 }
3953  
3954 727 ▶sub DEMOLISH {
Subroutine DEMOLISH: called CC=2 SCAR=7.1
Pod undocumented
3955 727 my ($self, $global) = @_;
3956 # The customer source's timers hold only weak references; this takes them off the loop.
3957 727 ▶ $self->_stop_source_controller unless $global;
Branch: 1 branch
BranchTrueFalseTotal
unless $global 727 0 727
3958 727 $self->_disconnect_usage_store;
3959 }
3960  
3961 813 ▶sub _disconnect_usage_store {
Subroutine _disconnect_usage_store: called CC=2 SCAR=6.9
3962 813 my ($self) = @_;
3963 813 ▶ my $store = $self->_usage_store_obj or return;
Branch: 1 branch
BranchTrueFalseTotal
my $store = $self->_usage_store_obj or return 84 729 813
3964 84 $store->disconnect;
3965 84 $self->_usage_store_obj(undef);
3966 84 return;
3967 }
3968  
3969  
3970 127 1;
3971  
3972 __END__
« lib/Langertha/Skeid/UsageStore/JsonLog.pm ↑ Summary blib/lib/Langertha/Skeid/CustomerSource/DBI.pm »