lib/Langertha/Skeid.pm

filter: Statementstmt 97.5% 1785 / 1830 Branchbran 83.2% 886 / 1064 Conditioncond 67.0% 748 / 1115 MC/DCmcdc 40.3% 240 / 595 Subroutinesub 99.1% 227 / 229 Podpod 96.4% 55 / 57 totaltotal 80.5% 3941 / 4890 CC 1035 SCAR 34.1
CC
1035
Cov
85%
call_function
226.2
_usage_lost
61.2
_load_mcp
59.9
CRAP 30.4
« lib/Langertha/Skeid/Protocol/Anthropic.pm ↑ Summary lib/Langertha/Skeid/UsageStore/JsonLog.pm »
1 package Langertha::Skeid;
2 113 our $VERSION = '0.004';
3 # ABSTRACT: Dynamic routing control-plane for multi-node LLM serving with normalized metrics and cost accounting
4 113 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 113 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 113 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 113 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 113 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 113 ▶use Digest::SHA qw(sha1_hex sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 113 ▶use Scalar::Util qw(blessed looks_like_number refaddr reftype weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 113 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 113 ▶use YAML::PP;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 113 ▶use Langertha ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 113 ▶use Langertha::Skeid::UsageStore;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 113 ▶use Langertha::Skeid::CustomerSource;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 113 ▶use Langertha::Skeid::Protocol;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 113 ▶use Langertha::Skeid::Protocol::Anthropic;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 113 ▶use Langertha::Skeid::Protocol::Documents;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 113 ▶use Langertha::Skeid::Protocol::MCP;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 113 ▶use Langertha::Skeid::Protocol::Ollama;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 113 ▶use Langertha::Skeid::Protocol::Rerank;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 113 ▶use Langertha::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 113 ▶use Langertha::Cost;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 113 ▶use Langertha::Pricing;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 113 ▶use Langertha::UsageRecord;
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27  
28  
29 has nodes => (
30 is => 'rw',
31 823 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
32 # Routing caches derived node lists, so every path that can change the inventory has to
33 # invalidate them. The methods below bump the generation explicitly; this trigger catches
34 # the remaining one -- somebody assigning the whole list through the public accessor.
35 1637 ▶ trigger => sub { $_[0]->_bump_inventory },
Subroutine __ANON__: called CC=1 SCAR=0.0
36 113 );
37  
38  
39 has model_pricing => (
40 is => 'rw',
41 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
42 113 );
43  
44  
45 has model_aliases => (
46 is => 'rw',
47 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
48 113 );
49  
50  
51 has policies => (
52 is => 'rw',
53 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
54 113 );
55  
56  
57 has default_policy => (
58 is => 'rw',
59 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
60 113 );
61  
62  
63 # Key id -> resolved policy. Identical resolutions share one object, and a key that takes the
64 # default is not listed at all, so ten thousand identical customers cost nothing here.
65 has key_policies => (
66 is => 'rw',
67 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
68 113 );
69  
70  
71 # Readable name -> customer key id, from the config `names:` section. A config-authoring
72 # convenience only: it lets `keys:` entries be written by name and localises key rotation to
73 # one line, and is resolved to key ids once at config load. It never reaches the request path
74 # -- a request still carries a derived key id, and policy_for_key still costs one hash lookup.
75 has key_names => (
76 is => 'rw',
77 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
78 113 );
79  
80  
81 # /.well-known/langertha.json (skeid #29, ADR 0015). Off until the config enables it.
82 has manifest_enabled => (
83 is => 'rw',
84 823 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
85 113 );
86  
87 # Whether this Langertha has Langertha::Manifest (core newer than 0.503). Enabled without it,
88 # the route answers 404 rather than failing the config.
89 has manifest_available => (
90 is => 'rw',
91 823 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
92 113 );
93  
94 # Key id -> the canonical JSON of that key's manifest, built at config load. This is the
95 # manifest cache, and it is keyed by the key id the caller's key derives to: a customer can
96 # only ever be served the entry built from its own keys: line, never another key's catalog.
97 has key_manifests => (
98 is => 'rw',
99 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
100 113 );
101  
102  
103 # Key id -> 1, from client_auth.keys (skeid k90). Undef is off -- every caller gets in, as
104 # before the section existed -- and is a different thing from {}, which lets nobody in.
105 has client_auth_keys => (
106 is => 'rw',
107 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
108 113 );
109  
110  
111 # Server name -> resolved entry, from mcp.servers (skeid k103, ADR 0022). Undef is off -- both
112 # MCP routes are the unknown path they were before the section existed -- and is a different
113 # thing from {}, a gateway that is on and has no server.
114 has mcp_servers => (
115 is => 'rw',
116 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
117 113 );
118  
119 has mcp_public_url => (
120 is => 'rw',
121 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
122 113 );
123  
124  
125 113 my $MCP_MAX_REQUEST_BYTES = 10485760;
126  
127 has mcp_max_request_bytes => (
128 is => 'rw',
129 823 ▶ default => sub { $MCP_MAX_REQUEST_BYTES },
Subroutine __ANON__: called CC=1 SCAR=0.0
130 113 );
131  
132  
133 has openapi_swagger_ui => (
134 is => 'rw',
135 823 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
136 113 );
137  
138 has openapi_cache_dir => (
139 is => 'rw',
140 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
141 113 );
142  
143  
144 113 has customer_source_fetcher => (
145 is => 'ro',
146 predicate => 'has_customer_source_fetcher',
147 );
148  
149 # The customer source (ADR 0026). The normalized section of the config in force and a digest of
150 # it (a changed one restarts the fetcher), the loop that fetches, the latest snapshot -- the rows
151 # of the last successful fetch, merged into the file's config at every reload -- and what the
152 # last merge accepted, rejected and shadowed.
153 113 has _source_cfg => (is => 'rw');
154 113 has _source_cfg_print => (is => 'rw');
155 113 has _source_ctl => (is => 'rw');
156 113 has _source_snapshot => (is => 'rw');
157 113 has _source_report => (is => 'rw');
158 823 ▶has _source_started => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
159 113 has _source_stale_timer => (is => 'rw');
160 823 ▶has _source_gate_warned => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
161  
162  
163 # uploads.max_bytes (skeid k91): the body limit of the multipart routes, read per request by
164 # the proxy, so a reload holds from the next upload. The default is OpenAI's own limit for an
165 # audio file, 25 MiB.
166 113 my $UPLOAD_MAX_BYTES = 26214400;
167  
168 has upload_max_bytes => (
169 is => 'rw',
170 823 ▶ default => sub { $UPLOAD_MAX_BYTES },
Subroutine __ANON__: called CC=1 SCAR=0.0
171 113 );
172  
173  
174 # uploads.documents_max_bytes (skeid k94, ADR 0028): the body limit of /v1/convert/file and
175 # /v1/convert/source. Documents are bigger than audio, so it is a limit of its own.
176 113 my $DOCUMENTS_MAX_BYTES = 104857600;
177  
178 has documents_max_bytes => (
179 is => 'rw',
180 823 ▶ default => sub { $DOCUMENTS_MAX_BYTES },
Subroutine __ANON__: called CC=1 SCAR=0.0
181 113 );
182  
183  
184 has documents_allow_remote_sources => (
185 is => 'rw',
186 823 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
187 113 );
188  
189  
190 # realtime: (skeid k95, ADR 0029). Read when a session opens, so a reload holds for the next one.
191 113 my %REALTIME_DEFAULT = (
192 idle_timeout => 300,
193 max_session_seconds => 3600,
194 max_message_bytes => 1048576,
195 max_queued_bytes => 4194304,
196 );
197  
198 823 ▶has realtime_idle_timeout => (is => 'rw', default => sub { $REALTIME_DEFAULT{idle_timeout} });
Subroutine __ANON__: called CC=1 SCAR=0.0
199 823 ▶has realtime_max_session_seconds => (is => 'rw', default => sub { $REALTIME_DEFAULT{max_session_seconds} });
Subroutine __ANON__: called CC=1 SCAR=0.0
200 823 ▶has realtime_max_message_bytes => (is => 'rw', default => sub { $REALTIME_DEFAULT{max_message_bytes} });
Subroutine __ANON__: called CC=1 SCAR=0.0
201 823 ▶has realtime_max_queued_bytes => (is => 'rw', default => sub { $REALTIME_DEFAULT{max_queued_bytes} });
Subroutine __ANON__: called CC=1 SCAR=0.0
202  
203  
204 # Whether x-skeid-key-id / x-api-key-id from the client may name the customer. Off by default:
205 # once a policy hangs off the key id, believing that header lets any client pick its own
206 # permissions in one line. Turn it on only when something in front of Skeid authenticates the
207 # caller and sets the header itself.
208 113 has trust_key_id_header => (
209 is => 'rw',
210 builder => '_build_trust_key_id_header',
211 );
212  
213 823 ▶sub _build_trust_key_id_header {
Subroutine _build_trust_key_id_header: called CC=3 SCAR=14.2
214 823 ▶ 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 823 823
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
82300
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
215 ? 1 : 0;
216 }
217  
218  
219 113 has route_wait_timeout_ms => (
220 is => 'rw',
221 builder => '_build_route_wait_timeout_ms',
222 );
223  
224 684 ▶sub _build_route_wait_timeout_ms {
Subroutine _build_route_wait_timeout_ms: called CC=3 SCAR=12.0
225 return (defined($ENV{SKEID_ROUTE_WAIT_TIMEOUT_MS}) && length($ENV{SKEID_ROUTE_WAIT_TIMEOUT_MS}))
226 ? 0 + $ENV{SKEID_ROUTE_WAIT_TIMEOUT_MS}
227 684 ▶ : 2000;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_ROUTE_WAIT_TIMEOUT_MS'} && length $ENV{'SKEID_ROUTE_WAIT_TIMEOUT_MS'} ? : 0 684 684
Condition66%2/3
defined $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"} and length $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"}
!ll&&!rl&&r
68310
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
228 }
229  
230  
231 113 has route_wait_poll_ms => (
232 is => 'rw',
233 builder => '_build_route_wait_poll_ms',
234 );
235  
236 563 ▶sub _build_route_wait_poll_ms {
Subroutine _build_route_wait_poll_ms: called CC=3 SCAR=14.2
237 return (defined($ENV{SKEID_ROUTE_WAIT_POLL_MS}) && length($ENV{SKEID_ROUTE_WAIT_POLL_MS}))
238 ? 0 + $ENV{SKEID_ROUTE_WAIT_POLL_MS}
239 563 ▶ : 25;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_ROUTE_WAIT_POLL_MS'} && length $ENV{'SKEID_ROUTE_WAIT_POLL_MS'} ? : 0 563 563
Condition33%1/3
defined $ENV{"SKEID_ROUTE_WAIT_POLL_MS"} and length $ENV{"SKEID_ROUTE_WAIT_POLL_MS"}
!ll&&!rl&&r
56300
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
240 }
241  
242  
243 has usage_db_path => (
244 is => 'rw',
245 predicate => 'has_usage_db_path',
246 clearer => 'clear_usage_db_path',
247 823 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=14.2
248 return (defined($ENV{SKEID_USAGE_DB}) && length($ENV{SKEID_USAGE_DB}))
249 ? $ENV{SKEID_USAGE_DB}
250 823 ▶ : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_USAGE_DB'} && length $ENV{'SKEID_USAGE_DB'} ? : 0 823 823
Condition33%1/3
defined $ENV{"SKEID_USAGE_DB"} and length $ENV{"SKEID_USAGE_DB"}
!ll&&!rl&&r
82300
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
251 },
252 113 );
253  
254  
255 has usage_store => (
256 is => 'rw',
257 774 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
258 113 );
259  
260  
261 113 has store_usage_event => (
262 is => 'ro',
263 predicate => 'has_store_usage_event',
264 );
265  
266  
267 113 has query_usage_report => (
268 is => 'ro',
269 predicate => 'has_query_usage_report',
270 );
271  
272  
273 113 has on_usage_lost => (
274 is => 'rw',
275 predicate => 'has_on_usage_lost',
276 );
277  
278  
279 113 has admin_api_key => (
280 is => 'rw',
281 builder => '_build_admin_api_key',
282 );
283  
284 1638 ▶sub _build_admin_api_key { $_[0]->_env_admin_api_key }
Subroutine _build_admin_api_key: called CC=1 SCAR=0.0
285  
286 2099 ▶sub _env_admin_api_key {
Subroutine _env_admin_api_key: called CC=3 SCAR=11.0
287 return (defined($ENV{SKEID_ADMIN_API_KEY}) && length($ENV{SKEID_ADMIN_API_KEY}))
288 ? $ENV{SKEID_ADMIN_API_KEY}
289 2099 ▶ : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_ADMIN_API_KEY'} && length $ENV{'SKEID_ADMIN_API_KEY'} ? : 6 2093 2099
Condition100%3/3
defined $ENV{"SKEID_ADMIN_API_KEY"} and length $ENV{"SKEID_ADMIN_API_KEY"}
!ll&&!rl&&r
2071226
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
290 }
291  
292 # The admin API key given explicitly -- to new(), to build_app, or by `skeid serve
293 # --admin-api-key` (skeid k64). It outranks the config, so a reload re-resolves the key under
294 # it instead of overwriting it; empty means none was given.
295 has _explicit_admin_api_key => (
296 is => 'rw',
297 init_arg => undef,
298 823 ▶ default => sub { '' },
Subroutine __ANON__: called CC=1 SCAR=0.0
299 113 );
300  
301 # The admin API key the config (or SKEID_ADMIN_API_KEY under it) resolved to when it was last
302 # applied. Kept apart from the explicit key so that clearing that one falls back to it at once.
303 113 has _config_admin_api_key => (
304 is => 'rw',
305 init_arg => undef,
306 builder => '_build_admin_api_key',
307 );
308  
309  
310 113 has key_broker => (is => 'ro', predicate => 'has_key_broker');
311  
312  
313 113 has config_file => (
314 is => 'ro',
315 predicate => 'has_config_file',
316 );
317  
318  
319 113 has config_loader => (
320 is => 'ro',
321 predicate => 'has_config_loader',
322 );
323  
324 has _config_mtime => (
325 is => 'rw',
326 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
327 113 );
328  
329 # A file version that failed before it could update _config_mtime, and when that same version
330 # may be tried again. A different mtime bypasses this window, so a correction is prompt; the
331 # retry keeps a transient read error from freezing an otherwise unchanged file forever.
332 has _config_file_failed_mtime => (
333 is => 'rw',
334 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
335 113 );
336  
337 has _config_file_retry_at => (
338 is => 'rw',
339 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
340 113 );
341  
342 # Set while config_file is missing after a good load, so the loss is warned once.
343 has _config_file_missing => (
344 is => 'rw',
345 823 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
346 113 );
347  
348  
349 has config_reload_interval => (
350 is => 'rw',
351 588 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=14.2
352 return (defined($ENV{SKEID_CONFIG_RELOAD_INTERVAL}) && length($ENV{SKEID_CONFIG_RELOAD_INTERVAL}))
353 ? 0 + $ENV{SKEID_CONFIG_RELOAD_INTERVAL}
354 588 ▶ : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_CONFIG_RELOAD_INTERVAL'} && length $ENV{'SKEID_CONFIG_RELOAD_INTERVAL'} ? : 0 588 588
Condition33%1/3
defined $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"} and length $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"}
!ll&&!rl&&r
58800
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
355 },
356 113 );
357  
358 # When the loader may run next (see config_reload_interval).
359 has _config_next_check_at => (
360 is => 'rw',
361 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
362 113 );
363  
364 # What the last applied config was: the loader's version when it gives one, else a digest of
365 # the loaded structure. A reload that reads the same fingerprint changes nothing (skeid #38).
366 has _config_fingerprint => (
367 is => 'rw',
368 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
369 113 );
370  
371  
372 823 ▶has last_reload_error => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
373 823 ▶has last_reload_error_at => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
374 823 ▶has reload_failures => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
375  
376 # The fingerprint of the config that last failed to apply. Reading the same one again is not
377 # retried: the answer would be the same error (skeid #39).
378 has _failed_fingerprint => (
379 is => 'rw',
380 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
381 113 );
382  
383 # The routing attributes as they were before any config was applied (see BUILD).
384 has _routing_baseline => (
385 is => 'rw',
386 init_arg => undef,
387 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
388 113 );
389  
390 # The sections the last applied config declared (see _apply_config). A section that was declared
391 # and is gone from the next config goes back to its default; one never declared is left alone.
392 has _config_declared => (
393 is => 'rw',
394 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
395 113 );
396  
397 # Digest of the nodes section the node list was last built from. An unchanged section keeps
398 # the node list -- and with it the inventory generation, the running probes and any health an
399 # admin set -- even when another section of the config changed.
400 has _nodes_fingerprint => (
401 is => 'rw',
402 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
403 113 );
404  
405 has _rr_cursor => (
406 is => 'rw',
407 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
408 113 );
409  
410 has _inventory_generation => (
411 is => 'rw',
412 823 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
413 113 );
414  
415 has _route_cache => (
416 is => 'rw',
417 823 ▶ default => sub { { generation => -1, entries => {}, order => [] } },
Subroutine __ANON__: called CC=1 SCAR=0.0
418 113 );
419  
420 # The probe key (see _probe_inventory_key) as of one inventory generation.
421 has _probe_key_cache => (
422 is => 'rw',
423 823 ▶ default => sub { { generation => -1, key => undef } },
Subroutine __ANON__: called CC=1 SCAR=0.0
424 113 );
425  
426 has _inflight => (
427 is => 'rw',
428 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
429 113 );
430  
431 # node_id => normalized capacity reading (see set_capacity_reading). Written by probes off the
432 # request path, read by admission.
433 has _capacity => (
434 is => 'rw',
435 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
436 113 );
437  
438  
439 has capacity_max_age_ms => (
440 is => 'rw',
441 813 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=14.2
442 return (defined($ENV{SKEID_CAPACITY_MAX_AGE_MS}) && length($ENV{SKEID_CAPACITY_MAX_AGE_MS}))
443 ? 0 + $ENV{SKEID_CAPACITY_MAX_AGE_MS}
444 813 ▶ : 5000;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_CAPACITY_MAX_AGE_MS'} && length $ENV{'SKEID_CAPACITY_MAX_AGE_MS'} ? : 0 813 813
Condition33%1/3
defined $ENV{"SKEID_CAPACITY_MAX_AGE_MS"} and length $ENV{"SKEID_CAPACITY_MAX_AGE_MS"}
!ll&&!rl&&r
81300
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
445 },
446 113 );
447  
448  
449 has worker_count => (
450 is => 'rw',
451 814 ▶ default => sub { 1 },
Subroutine __ANON__: called CC=1 SCAR=0.0
452 14 ▶ trigger => sub { $_[0]->_bump_inventory },
Subroutine __ANON__: called CC=1 SCAR=0.0
453 113 );
454  
455  
456 113 has frontend_count => (
457 is => 'rw',
458 builder => '_build_frontend_count',
459 );
460  
461 816 ▶sub _build_frontend_count {
Subroutine _build_frontend_count: called CC=3 SCAR=12.0
462 return (defined($ENV{SKEID_FRONTEND_COUNT}) && length($ENV{SKEID_FRONTEND_COUNT}))
463 ? 0 + $ENV{SKEID_FRONTEND_COUNT}
464 816 ▶ : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_FRONTEND_COUNT'} && length $ENV{'SKEID_FRONTEND_COUNT'} ? : 0 816 816
Condition66%2/3
defined $ENV{"SKEID_FRONTEND_COUNT"} and length $ENV{"SKEID_FRONTEND_COUNT"}
!ll&&!rl&&r
81510
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
465 }
466  
467  
468 823 ▶has registry_enabled => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
469 823 ▶has registry_secret => (is => 'rw', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
470 823 ▶has registry_read_key => (is => 'rw', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
471 823 ▶has registry_ttl_s => (is => 'rw', default => sub { 10 });
Subroutine __ANON__: called CC=1 SCAR=0.0
472 823 ▶has registry_instance_id => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
473 823 ▶has registry_error_window_s => (is => 'rw', default => sub { 60 });
Subroutine __ANON__: called CC=1 SCAR=0.0
474  
475 # node_id => { last_at => epoch, buckets => { epoch_second => count } }. Failed requests, for
476 # the registry snapshot's errors_in_window and last_failure_at. Reported, never consulted by
477 # admission: health is operator state (ADR 0009, ADR 0017).
478 has _failures => (
479 is => 'rw',
480 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
481 113 );
482  
483 # The same shape for requests the client's own fault ended (k99): the registry snapshot's
484 # rejected_in_window. Kept apart from _failures so errors_in_window keeps its meaning.
485 has _rejections => (
486 is => 'rw',
487 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
488 113 );
489  
490 has _stats => (
491 is => 'rw',
492 823 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
493 113 );
494  
495 has _usage_store_obj => (
496 is => 'rw',
497 823 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
498 113 );
499  
500 113 my %FALLBACK_ENGINE_IDS = map { $_ => 1 } qw(
501 aki
502 akiopenai
503 anthropic
504 anthropicbase
505 cerebras
506 deepseek
507 gemini
508 groq
509 huggingface
510 lmstudio
511 lmstudioanthropic
512 lmstudioopenai
513 llamacpp
514 minimax
515 mistral
516 nousresearch
517 ollama
518 ollamaopenai
519 openai
520 openaibase
521 openrouter
522 perplexity
523 remote
524 replicate
525 sglang
526 vllm
527 whisper
528 );
529  
530 # How a routing key of the config sets its attribute. A key removed from the config sets it back
531 # to its value before any config was applied (_routing_baseline, skeid k65).
532 my %ROUTING_SETTINGS = (
533 19 ▶ wait_timeout_ms => [ route_wait_timeout_ms => sub { 0 + $_[0] } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
534 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
535 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
536 # How many Skeid hosts share the nodes. Only the config knows it -- there is nothing to
537 # detect -- and forgetting it over-admits every node by that factor (ADR 0012). Floor at one,
538 # so a stray 0 falls back to today's single-frontend behaviour instead of dividing max_conns
539 # to nothing.
540 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
541 );
542  
543 823 ▶sub BUILD {
Subroutine BUILD: called CC=9 SCAR=22.5
Pod undocumented
544 823 my ($self, $args) = @_;
545 # A key handed to new() is explicit: the config applied next must not replace it.
546 $self->_explicit_admin_api_key("$args->{admin_api_key}")
547 823 ▶ 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"} 8 815 823
Condition66%2/3
defined $args->{"admin_api_key"} and length $args->{"admin_api_key"}
!ll&&!rl&&r
81508
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
548 # What the routing attributes are without a config -- passed to new(), else from the
549 # environment, else built in: a routing key removed from the config goes back to this.
550 823 $self->_routing_baseline({ map { my $attr = $_->[0]; ($attr => $self->$attr) } values %ROUTING_SETTINGS });
551 823 ▶ if ($self->has_config_loader || $self->has_config_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_config_loader or $self->has_config_file) 489 334 823
Condition100%3/3
$self->has_config_loader or $self->has_config_file
l!l&&r!l&&!r
47613334
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
552 489 $self->reload_config;
553 }
554 721 ▶ 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;}) { } 53 668 721
Condition66%2/3
ref $self->usage_store eq "HASH" and keys %{$self->usage_store;}
!ll&&!rl&&r
066853
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
555 53 $self->_configure_usage_store($self->usage_store);
556 } else {
557 668 my $path = $self->usage_db_path;
558 668 ▶ if (defined $path && length $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $path and length $path) 0 668 668
Condition33%1/3
defined $path and length $path
!ll&&!rl&&r
66800
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
559 0 $self->_set_usage_db_path($path);
560 }
561 }
562 }
563  
564  
565 1355 ▶sub add_node {
Subroutine add_node: called CC=23 SCAR=31.6
Pod documented
566 1355 my ($self, %node) = @_;
567 1355 ▶ my $id = $node{id} // croak 'node id required';
Condition50%1/2
$node{"id"} // croak("node id required")
l!l
13550
MC/DC0%0/1
$node{"id"} // croak("node id required")
$node{"id"}
Truth table50%1/2
A
A= $node{"id"}
Aresult
11
00
568 1355 ▶ my $url = $node{url} // croak 'node url required';
Condition50%1/2
$node{"url"} // croak("node url required")
l!l
13550
MC/DC0%0/1
$node{"url"} // croak("node url required")
$node{"url"}
Truth table50%1/2
A
A= $node{"url"}
Aresult
11
00
569  
570 # A registry probe with no secret would forget on every poll and look like a silent
571 # downstream; say so where the operator wrote it (ADR 0017).
572 1355 ▶ 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 1342 1355
Condition75%6/8
ref $node{"capacity"} eq "HASH" and lc(($node{"capacity"}{"probe"} // $node{"capacity"}{"type"}) // "") eq "registry"
!ll&&!rl&&r
13241813
($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
573 && lc($node{capacity}{probe} // $node{capacity}{type} // '') eq 'registry') {
574 13 require Langertha::Skeid::CapacityProbe::Registry;
575 13 Langertha::Skeid::CapacityProbe::Registry->validate_config($node{capacity}, $id);
576 }
577  
578 # An unknown format croaks, like an unknown engine: a TEI node called in the default dialect
579 # answers every request with an error (skeid k92).
580 1349 my $rerank_format = Langertha::Skeid::Protocol::Rerank->normalize_format($node{rerank_format});
581  
582 # The same for the kind of node and the header its key goes in (skeid k94, ADR 0028): a node of
583 # a kind nobody spelled right would be sent the wrong sort of request, and a header name that
584 # is no token could carry a line break upstream.
585 1344 my $kind = Langertha::Skeid::Protocol::Documents->normalize_kind($node{kind});
586 1340 my $key_header = Langertha::Skeid::Protocol::Documents->normalize_key_header($node{api_key_header});
587  
588 # Every check that can croak runs before the removal: a bad re-add must leave the working
589 # node in the inventory (skeid k98).
590 1336 ▶ 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'} ? : 924 412 1336
Condition66%2/3
defined $node{"engine"} and length $node{"engine"}
!ll&&!rl&&r
4120924
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
591 1334 my $tags = $self->normalize_tags($node{tags});
592  
593 1334 $self->remove_node($id);
594 1334 ▶ push @{$self->nodes}, {
Branch: 8 branches
BranchTrueFalseTotal
defined $node{'weight'} ? : 16 1318 1334
defined $node{'max_conns'} ? : 1083 251 1334
exists $node{'healthy'} ? : 806 528 1334
$node{'healthy'} ? : 805 1 806
ref $node{'metadata'} eq 'HASH' ? : 1 1333 1334
defined $node{'api_key_env'} && length $node{'api_key_env'} ? : 108 1226 1334
defined $node{'api_key_ref'} && length $node{'api_key_ref'} ? : 103 1231 1334
ref $node{'capacity'} eq 'HASH' ? : 25 1309 1334
Condition75%6/8
$node{"model"} // ""
l!l
127559
defined $node{"api_key_env"} and length $node{"api_key_env"}
!ll&&!rl&&r
12260108
defined $node{"api_key_ref"} and length $node{"api_key_ref"}
!ll&&!rl&&r
12310103
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
595 id => $id,
596 url => $url,
597 model => ($node{model} // ''),
598 engine => $engine,
599 weight => (defined $node{weight} ? 0 + $node{weight} : 1),
600 max_conns => (defined $node{max_conns} ? 0 + $node{max_conns} : 0),
601 healthy => (exists $node{healthy} ? ($node{healthy} ? 1 : 0) : 1),
602 tags => $tags,
603 metadata => (ref($node{metadata}) eq 'HASH' ? $node{metadata} : {}),
604 (defined($node{api_key_env}) && length($node{api_key_env})
605 ? (api_key_env => "$node{api_key_env}")
606 : ()),
607 (defined($node{api_key_ref}) && length($node{api_key_ref})
608 ? (api_key_ref => "$node{api_key_ref}")
609 : ()),
610 # How this node's capacity is found (ADR 0009). Absent means inflight, which is every
611 # deployment that existed before probes did.
612 1334 ▶ (ref($node{capacity}) eq 'HASH' ? (capacity => { %{$node{capacity}} }) : ()),
Branch: 3 branches
BranchTrueFalseTotal
length $rerank_format ? : 14 1320 1334
length $kind ? : 25 1309 1334
length $key_header ? : 3 1331 1334
613 # The dialect the node's rerank route speaks when it is not the client's (skeid k92).
614 # Absent means the request is relayed as it came.
615 (length($rerank_format) ? (rerank_format => $rerank_format) : ()),
616 # What the node serves when it is not chat completions: `documents` is a docling-serve node,
617 # reached by the documents routes and by nothing else (ADR 0028). Absent means chat, which
618 # is every node there was before the option.
619 (length($kind) ? (kind => $kind) : ()),
620 # The header the node's key is sent in, raw, instead of `Authorization: Bearer` (docling's
621 # `X-Api-Key`). Absent means Authorization.
622 (length($key_header) ? (api_key_header => $key_header) : ()),
623 };
624 1334 $self->_bump_inventory;
625 1334 return 1;
626 }
627  
628  
629 1354 ▶sub remove_node {
Subroutine remove_node: called CC=6 SCAR=18.2
Pod documented
630 1354 my ($self, $id) = @_;
631 1354 ▶ return 0 unless defined $id && length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 0 1354 1354
Condition33%1/3
defined $id and length $id
!ll&&!rl&&r
001354
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
632 1354 ▶ my @keep = grep { ($_->{id} // '') ne $id } @{$self->nodes};
Condition50%1/2
$_->{"id"} // ""
l!l
18520
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
633 1354 my $removed = @{$self->nodes} - @keep;
634 1354 $self->nodes(\@keep);
635 # Or a node re-added under the same id inherits a reading -- or an error history -- about a
636 # different machine.
637 1354 ▶ if ($removed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($removed) 21 1333 1354
638 21 $self->forget_capacity($id);
639 21 delete $self->_failures->{$id};
640 21 delete $self->_rejections->{$id};
641 }
642 1354 ▶ return $removed ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$removed ? : 21 1333 1354
643 }
644  
645 # What the running capacity probes were built from: the worker count (it sets the poll interval,
646 # ADR 0010) and, per node with a capacity block, its id, URL and that block. The inventory
647 # generation is the wrong key for them -- it also moves on a health flip, which has to drop the
648 # route cache but changes nothing a probe polls, and restarting the probes forgets every reading
649 # (skeid #40). The URL is in because a Prometheus probe may derive its endpoint from it, and a
650 # reading about the machine a node id used to point at is not one about the new one.
651 # Recomputed only when the generation has moved, so the per-request check stays an integer
652 # compare.
653 2769 ▶sub _probe_inventory_key {
Subroutine _probe_inventory_key: called CC=7 SCAR=20.2
654 2769 my ($self) = @_;
655 2769 my $generation = $self->_inventory_generation;
656 2769 my $cache = $self->_probe_key_cache;
657 2769 ▶ return $cache->{key} if ($cache->{generation} // -1) == $generation;
Branch: 1 branch
BranchTrueFalseTotal
if ($cache->{"generation"} // -1) == $generation 1938 831 2769
Condition50%1/2
$cache->{"generation"} // -1
l!l
27690
MC/DC0%0/1
$cache->{"generation"} // -1
$cache->{"generation"}
Truth table50%1/2
A
A= $cache->{"generation"}
Aresult
11
00
658  
659 my $key = _config_digest([
660 0 + ($self->worker_count // 1),
661 40 map { [ $_->{id}, $_->{url}, $_->{capacity} ] }
662 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
663 1233 grep { ref($_->{capacity}) eq 'HASH' }
664 831 ▶ @{$self->nodes || []},
Condition50%2/4
$self->worker_count // 1
l!l
8310
$self->nodes || []
l!l
8310
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
665 ]);
666 831 $self->_probe_key_cache({ generation => $generation, key => $key });
667 831 return $key;
668 }
669  
670 3019 ▶sub _bump_inventory {
Subroutine _bump_inventory: called CC=2 SCAR=7.0
671 3019 my ($self) = @_;
672 # Defensive //0: the nodes trigger can fire during construction, before this attribute's own
673 # default has been assigned.
674 3019 ▶ $self->_inventory_generation(($self->_inventory_generation // 0) + 1);
Condition50%1/2
$self->_inventory_generation // 0
l!l
30190
MC/DC0%0/1
$self->_inventory_generation // 0
$self->_inventory_generation
Truth table50%1/2
A
A= $self->_inventory_generation
Aresult
11
00
675 # A cursor names weighted ranges in exactly one inventory generation. Keeping it after a
676 # health, node or worker-share change both retains client-created keys and resumes fairness at
677 # a position that described a different set, so inventory invalidation clears all cursors.
678 3019 $self->_rr_cursor({});
679 3019 return;
680 }
681  
682  
683 18223 ▶sub normalize_tags {
Subroutine normalize_tags: called CC=7 SCAR=19.5
Pod documented
684 18223 my ($self, $value) = @_;
685 18223 ▶ return [] unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 6628 11595 18223
686  
687 11595 ▶ my @raw = ref($value) eq 'ARRAY' ? @$value : split(/[,\s]+/, "$value");
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'ARRAY' ? : 11593 2 11595
688 11595 my (@tags, %seen);
689 11595 for my $tag (@raw) {
690 1105 ▶ next unless defined $tag;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tag 0 1105 1105
691 1105 my $clean = lc "$tag";
692 1105 $clean =~ s/\A\s+//;
693 1105 $clean =~ s/\s+\z//;
694 1105 ▶ next unless length $clean;
Branch: 1 branch
BranchTrueFalseTotal
unless length $clean 0 1105 1105
695 1105 ▶ next if $seen{$clean}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$clean}++ 1 1104 1105
696 1104 push @tags, $clean;
697 }
698 11595 return \@tags;
699 }
700  
701  
702 364 ▶sub list_nodes {
Subroutine list_nodes: called CC=1 SCAR=0.0
Pod documented
703 364 my ($self) = @_;
704 364 return [ map { +{%$_} } @{$self->nodes} ];
705 }
706  
707  
708 46 ▶sub list_models {
Subroutine list_models: called CC=15 SCAR=27.5
Pod documented
709 46 my ($self, %args) = @_;
710 46 my $policy = $self->policy_for_key($args{api_key_id});
711 46 ▶ my $deny = $policy ? $policy->{deny_tags} : [];
Branch: 1 branch
BranchTrueFalseTotal
$policy ? : 6 40 46
712 46 my %entry;
713  
714 46 ▶ for my $n (@{$self->nodes || []}) {
Condition50%1/2
$self->nodes || []
l!l
460
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
715 83 my $model = $n->{model};
716 83 ▶ next unless defined $model && length $model;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and length $model 14 69 83
Condition66%2/3
defined $model and length $model
!ll&&!rl&&r
01469
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
717 # A documents node names no model a client can ask for (ADR 0028).
718 69 ▶ next if length($n->{kind} // '');
Branch: 1 branch
BranchTrueFalseTotal
if length($n->{"kind"} // "") 0 69 69
Condition50%1/2
$n->{"kind"} // ""
l!l
069
MC/DC0%0/1
$n->{"kind"} // ""
$n->{"kind"}
Truth table50%1/2
A
A= $n->{"kind"}
Aresult
11
00
719 69 ▶ next if $self->_node_has_any_tag($n, $deny);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_node_has_any_tag($n, $deny) 3 66 69
720 66 ▶ $entry{$model} //= { model => $model, engine => ($n->{engine} // '') };
Condition75%3/4
$entry{$model} //= {"model", $model, "engine", $n->{"engine"} // ""}
l!l
264
$n->{"engine"} // ""
l!l
640
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
721 }
722 46 my $documents_key = Langertha::Skeid::Protocol::Documents->routing_key;
723 46 ▶ for my $name (keys %{$self->model_aliases || {}}) {
Condition50%1/2
$self->model_aliases || {}
l!l
460
MC/DC0%0/1
$self->model_aliases || {}
$self->model_aliases
Truth table50%1/2
A
A= $self->model_aliases
Aresult
11
00
724 # The alias of the documents routing key tiers documents nodes: it is not a chat model.
725 27 ▶ next if $name eq $documents_key;
Branch: 1 branch
BranchTrueFalseTotal
if $name eq $documents_key 1 26 27
726 26 ▶ $entry{$name} //= { model => $name, engine => '' };
Condition100%2/2
$entry{$name} //= {"model", $name, "engine", ""}
l!l
620
MC/DC100%1/1
$entry{$name} //= {"model", $name, "engine", ""}
$entry{$name}
Truth table100%2/2
A
A= $entry{$name}
Aresult
11
00
727 }
728  
729 return [
730 74 map { $entry{$_} }
731 46 grep { $self->route_plan(model => $_, api_key_id => $args{api_key_id})->{permitted} }
732 sort keys %entry
733 ];
734 }
735  
736  
737 36 ▶sub set_node_health {
Subroutine set_node_health: called CC=10 SCAR=23.2
Pod documented
738 36 my ($self, $id, $healthy) = @_;
739 36 ▶ return 0 unless defined $id && length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 0 36 36
Condition33%1/3
defined $id and length $id
!ll&&!rl&&r
0036
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
740 36 my ($found, $changed) = (0, 0);
741 36 ▶ my $next = $healthy ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$healthy ? : 9 27 36
742 36 for my $n (@{$self->nodes}) {
743 46 ▶ next unless ($n->{id} // '') eq $id;
Branch: 1 branch
BranchTrueFalseTotal
unless ($n->{"id"} // "") eq $id 10 36 46
Condition50%1/2
$n->{"id"} // ""
l!l
460
MC/DC0%0/1
$n->{"id"} // ""
$n->{"id"}
Truth table50%1/2
A
A= $n->{"id"}
Aresult
11
00
744 36 ▶ if (($n->{healthy} ? 1 : 0) != $next) {
Branch: 2 branches
BranchTrueFalseTotal
if (($n->{"healthy"} ? 1 : 0) != $next) 34 2 36
$n->{'healthy'} ? : 27 9 36
745 34 $n->{healthy} = $next;
746 34 $changed = 1;
747 }
748 36 $found = 1;
749 36 last;
750 }
751 # Health is part of eligibility, so flipping it has to drop the derived lists -- otherwise a
752 # node taken out of rotation keeps receiving traffic until something else changes. It is not
753 # part of the probe key, so the capacity probes and their readings stay (skeid #40). Repeating
754 # the current value changes no inventory and must not reset its round-robin cursors.
755 36 ▶ $self->_bump_inventory if $changed;
Branch: 1 branch
BranchTrueFalseTotal
if $changed 34 2 36
756 36 return $found;
757 }
758  
759 # The prompt-cache rates a pricing rule may carry (skeid #28, ADR 0013). Optional: a rule
760 # without them prices every input token at input_per_million, exactly as before.
761 113 my @CACHE_RATE_KEYS = qw(cached_input_per_million cache_write_per_million);
762 113 my $cache_rates_unsupported_warned;
763  
764 # True when the installed Langertha prices prompt-cache reads and writes (Langertha::Cost has
765 # the cache amounts, core ADR 0031). The released 0.503 does not; there the cache rates are
766 # dropped at config load, so a rule prices exactly as a rule without them.
767 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
768  
769  
770 150 ▶sub set_model_pricing {
Subroutine set_model_pricing: called CC=14 SCAR=26.6
Pod documented
771 150 my ($self, $model, $pricing) = @_;
772 150 ▶ croak 'model required' unless defined $model && length $model;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and length $model 0 150 150
Condition33%1/3
defined $model and length $model
!ll&&!rl&&r
00150
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
773 150 ▶ croak 'pricing hash required' unless ref($pricing) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pricing eq "HASH" 0 150 150
774 my %rule = (
775 input_per_million => 0 + ($pricing->{input_per_million} // 0),
776 150 ▶ output_per_million => 0 + ($pricing->{output_per_million} // 0),
Condition75%3/4
$pricing->{"input_per_million"} // 0
l!l
1500
$pricing->{"output_per_million"} // 0
l!l
1455
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
777 );
778 150 my @rates = grep { defined $pricing->{$_} } @CACHE_RATE_KEYS;
779 150 for my $key (@rates) {
780 123 my $rate = $pricing->{$key};
781 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
782 unless !ref($rate) && looks_like_number($rate) && $rate >= 0;
783 }
784 143 ▶ if (@rates && !_core_prices_cache()) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rates and not _core_prices_cache()) 2 141 143
Condition100%3/3
@rates and not _core_prices_cache()
!ll&&!rl&&r
84572
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
785 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
786 . "Langertha cannot price prompt-cache tokens; they are ignored and cached tokens bill "
787 . "at input_per_million\n"
788 unless $cache_rates_unsupported_warned++;
789 2 @rates = ();
790 }
791 143 $rule{$_} = 0 + $pricing->{$_} for @rates;
792 143 $self->model_pricing->{$model} = \%rule;
793 143 return $self->model_pricing->{$model};
794 }
795  
796  
797 674 ▶sub pricing_for_model {
Subroutine pricing_for_model: called CC=3 SCAR=11.0
Pod documented
798 674 my ($self, $model) = @_;
799 return $self->model_pricing->{$model}
800 674 ▶ || $self->model_pricing->{'*'}
Condition100%5/5
$self->model_pricing->{$model} || $self->model_pricing->{'*'} || {'input_per_million', 0, 'output_per_million', 0}
l!l
150524
$self->model_pricing->{$model} or $self->model_pricing->{"*"}
l!l&&r!l&&!r
44106524
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
801 || { input_per_million => 0, output_per_million => 0 };
802 }
803  
804 # The config state a reload replaces. A reload is all or nothing (skeid #29 review): a
805 # config that fails anywhere -- a bad policy, alias or manifest grant -- must not leave the
806 # sections before it applied and the ones after it not, which served every customer a 403
807 # from an emptied manifest map while routing already ran on the new policies.
808 113 my @CONFIG_STATE = qw(
809 model_aliases policies default_policy key_policies key_names nodes
810 route_wait_timeout_ms route_wait_poll_ms trust_key_id_header frontend_count
811 admin_api_key _config_admin_api_key
812 manifest_enabled manifest_available key_manifests client_auth_keys upload_max_bytes
813 documents_max_bytes documents_allow_remote_sources
814 mcp_servers mcp_public_url mcp_max_request_bytes openapi_swagger_ui openapi_cache_dir
815 realtime_idle_timeout realtime_max_session_seconds realtime_max_message_bytes
816 realtime_max_queued_bytes
817 registry_enabled registry_secret registry_read_key registry_ttl_s registry_instance_id registry_error_window_s
818 );
819  
820  
821 5252 ▶sub reload_config {
Subroutine reload_config: called CC=16 SCAR=27.7
Pod documented
822 5252 my ($self) = @_;
823 5252 my ($cfg, $fingerprint);
824 5252 ▶ unless (eval { ($cfg, $fingerprint) = $self->_read_config; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { () = $self->_read_config; 1 } }) 6 5246 5252
825 6 ▶ my $err = $@ || 'config loader failed';
Condition50%1/2
$@ || 'config loader failed'
l!l
60
MC/DC0%0/1
$@ || 'config loader failed'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
826 6 $self->_record_reload_failure($err, undef);
827 6 die $err;
828 }
829  
830 # With a customer_source, the config is two inputs: the file and the snapshot merged into it
831 # (ADR 0026). Either changing is a changed config; neither changing is the no-op below.
832 $fingerprint .= ';customer_source:' . $self->_source_digest
833 5246 ▶ if exists $cfg->{customer_source};
Branch: 1 branch
BranchTrueFalseTotal
if exists $cfg->{"customer_source"} 939 4307 5246
834  
835 # Same config as last applied: nothing to do. Rebuilding would replace the node list, which
836 # bumps the inventory generation, restarts every capacity probe and forgets health an admin
837 # set -- for a config that did not change (skeid #38).
838 5246 my $last = $self->_config_fingerprint;
839 5246 ▶ if (defined($last) && $last eq $fingerprint) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $last and $last eq $fingerprint) 4630 616 5246
Condition100%3/3
defined $last and $last eq $fingerprint
!ll&&!rl&&r
4881284630
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
840 4630 $self->_clear_reload_failure;
841 4630 return $cfg;
842 }
843  
844 # The config that just failed, read again: it would fail the same way, so it is not applied
845 # again -- but it still counts as a failure, which is what the retry back-off grows on.
846 616 my $failed = $self->_failed_fingerprint;
847 616 ▶ 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 600 616
Condition83%5/6
defined $failed and $failed eq $fingerprint and defined $self->last_reload_error
!ll&&!rl&&r
600016
defined $failed and $failed eq $fingerprint
!ll&&!rl&&r
595516
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
848 16 my $err = $self->last_reload_error;
849 16 $self->_record_reload_failure($err, $fingerprint);
850 16 die $err;
851 }
852  
853 600 my %before = map { $_ => $self->$_ } @CONFIG_STATE;
854 600 ▶ my %pricing = %{$self->model_pricing || {}};
Condition50%1/2
$self->model_pricing || {}
l!l
6000
MC/DC0%0/1
$self->model_pricing || {}
$self->model_pricing
Truth table50%1/2
A
A= $self->model_pricing
Aresult
11
00
855 600 my ($generation, $route_cache, $probe_key_cache, $rr_cursor)
856 = ($self->_inventory_generation, $self->_route_cache, $self->_probe_key_cache, $self->_rr_cursor);
857  
858 600 my ($nodes_print, $declared, $notices, $source);
859 600 ▶ if (eval { ($nodes_print, $declared, $notices, $source) = $self->_apply_config($cfg); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { () = $self->_apply_config($cfg); 1 } }) 488 112 600
860 488 $self->_forget_departed_nodes;
861 488 $self->_config_fingerprint($fingerprint);
862 488 $self->_nodes_fingerprint($nodes_print);
863 488 $self->_config_declared($declared);
864 488 $self->_clear_reload_failure;
865 488 push @$notices, $self->_commit_customer_source($source);
866 488 warn 'skeid: ' . $_ . "\n" for @$notices;
867 488 return $cfg;
868 }
869  
870 112 ▶ my $err = $@ || 'config reload failed';
Condition50%1/2
$@ || 'config reload failed'
l!l
1120
MC/DC0%0/1
$@ || 'config reload failed'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
871 112 $self->_record_reload_failure($err, $fingerprint);
872 112 for my $attr (@CONFIG_STATE) {
873 3808 ▶ next if $attr eq 'nodes';
Branch: 1 branch
BranchTrueFalseTotal
if $attr eq "nodes" 112 3696 3808
874 3696 $self->$attr($before{$attr});
875 }
876 112 $self->model_pricing(\%pricing);
877 # Setting nodes bumps the inventory generation. The old list comes back unchanged (the failed
878 # load only built a new array), so its generation, derived caches and fairness cursors come back
879 # with it: an inventory that did not change must not look changed, and a cache left keyed on a
880 # generation number that is about to be reused would answer for a different list.
881 112 ▶ if ($self->nodes != $before{nodes}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->nodes != $before{"nodes"}) 24 88 112
882 24 $self->nodes($before{nodes});
883 24 $self->_inventory_generation($generation);
884 24 $self->_route_cache($route_cache);
885 24 $self->_probe_key_cache($probe_key_cache);
886 24 $self->_rr_cursor($rr_cursor);
887 }
888 112 die $err;
889 }
890  
891 # A reload that drops a node drops what was known about it too, as remove_node does: its
892 # capacity reading and its failure history. Otherwise a node re-added later under the same id
893 # inherits a reading -- or errors -- about whatever machine the id used to point at. Run only
894 # after a reload succeeded, so a failed one that restores the old list loses nothing.
895 488 ▶sub _forget_departed_nodes {
Subroutine _forget_departed_nodes: called CC=4 SCAR=13.9
896 488 my ($self) = @_;
897 488 ▶ my %present = map { (($_->{id} // '') => 1) } @{$self->nodes};
Condition50%1/2
$_->{"id"} // ""
l!l
8550
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
898 488 for my $store ($self->_capacity, $self->_failures, $self->_rejections) {
899 1464 delete $store->{$_} for grep { !$present{$_} } keys %$store;
900 }
901 488 return;
902 }
903  
904 134 ▶sub _record_reload_failure {
Subroutine _record_reload_failure: called CC=2 SCAR=7.0
905 134 my ($self, $err, $fingerprint) = @_;
906 134 $self->last_reload_error("$err");
907 134 $self->last_reload_error_at(time);
908 134 ▶ $self->reload_failures(($self->reload_failures // 0) + 1);
Condition50%1/2
$self->reload_failures // 0
l!l
1340
MC/DC0%0/1
$self->reload_failures // 0
$self->reload_failures
Truth table50%1/2
A
A= $self->reload_failures
Aresult
11
00
909 134 $self->_failed_fingerprint($fingerprint);
910 134 return;
911 }
912  
913 5118 ▶sub _clear_reload_failure {
Subroutine _clear_reload_failure: called CC=1 SCAR=0.0
914 5118 my ($self) = @_;
915 5118 $self->last_reload_error(undef);
916 5118 $self->last_reload_error_at(undef);
917 5118 $self->reload_failures(0);
918 5118 $self->_failed_fingerprint(undef);
919 5118 $self->_config_file_failed_mtime(undef);
920 5118 $self->_config_file_retry_at(undef);
921 5118 return;
922 }
923  
924  
925 79 ▶sub reload_status {
Subroutine reload_status: called CC=4 SCAR=14.1
Pod documented
926 79 my ($self) = @_;
927 79 my $err = $self->last_reload_error;
928 79 ▶ return { ok => 1 } unless defined $err;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err 65 14 79
929 14 (my $message = $err) =~ s/\s+\z//;
930 return {
931 14 ▶ ok => 0,
Condition50%2/4
$self->last_reload_error_at // time
l!l
140
$self->reload_failures // 0
l!l
140
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
932 error => $message,
933 failed_at => strftime('%Y-%m-%dT%H:%M:%SZ', gmtime($self->last_reload_error_at // time)),
934 failures => 0 + ($self->reload_failures // 0),
935 };
936 }
937  
938 # Reads the config source: the loader's answer or the parsed file, plus its fingerprint. A
939 # loader may return ($config, $version); a defined version is the fingerprint, otherwise it is
940 # a digest of the structure (see _config_digest).
941 5252 ▶sub _read_config {
Subroutine _read_config: called CC=10 SCAR=23.5
942 5252 my ($self) = @_;
943 5252 my $cfg = {};
944 5252 my $version;
945  
946 5252 ▶ if ($self->has_config_loader) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->has_config_loader) { } 5226 26 5252
elsif ($self->has_config_file) { } 26 0 26
947 # Counted from the start of the run, so the throttle also holds for a loader that dies.
948 5226 ▶ $self->_config_next_check_at($self->_now + (0 + ($self->config_reload_interval // 0)));
Condition50%1/2
$self->config_reload_interval // 0
l!l
52260
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
949 5226 my ($loaded, $loader_version) = $self->config_loader->($self);
950 5223 ▶ $cfg = $loaded if ref($loaded) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $loaded eq "HASH" 5223 0 5223
951 5223 $version = $loader_version;
952 } elsif ($self->has_config_file) {
953 26 my $file = $self->config_file;
954 # A named config that is not there is an operator error, not an empty config: starting
955 # with no nodes would answer every request 503 with nothing saying why (skeid k68). A file
956 # that vanishes after a good load never gets here -- maybe_reload_config keeps the config.
957 26 ▶ croak 'config file not found: ' . $file unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 1 25 26
958 # Record the version observed before parsing. The file may be atomically replaced after
959 # load_file has read its bytes; recording a later stat would mark that unread replacement
960 # as applied and prevent the next dispatch from loading it.
961 25 my $read_mtime = (stat($file))[9];
962 25 my $ypp = YAML::PP->new;
963 25 my $loaded = $ypp->load_file($file);
964 23 ▶ $cfg = $loaded if ref($loaded) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $loaded eq "HASH" 23 0 23
965 23 ▶ $self->_config_mtime($read_mtime) if defined $read_mtime;
Branch: 1 branch
BranchTrueFalseTotal
if defined $read_mtime 23 0 23
966 }
967  
968 5246 ▶ my $fingerprint = defined($version) && !ref($version)
Branch: 1 branch
BranchTrueFalseTotal
defined $version && !ref($version) ? : 3 5243 5246
Condition66%2/3
defined $version and not ref $version
!ll&&!rl&&r
524303
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
969 ? "version:$version"
970 : 'digest:' . _config_digest($cfg);
971 5246 return ($cfg, $fingerprint);
972 }
973  
974 # A canonical digest of a loaded config structure: hash keys sorted, so two loads of the same
975 # data digest alike whatever order the loader built them in. A code ref or an object other
976 # than a boolean digests by identity -- the same callback digests alike, a fresh closure per
977 # load counts as a change, which reloads rather than missing one.
978 6419 ▶sub _config_digest {
Subroutine _config_digest: called CC=1 SCAR=0.0
979 6419 my ($data) = @_;
980 6419 my $out = '';
981 6419 my $walk;
982 61724 ▶ $walk = sub {
Subroutine __ANON__: called CC=12 SCAR=25.0
983 61724 my ($node) = @_;
984 61724 ▶ if (!defined $node) {
Branch: 5 branches
BranchTrueFalseTotal
if (not defined $node) { } 46 61678 61724
elsif (not ref $node) { } 32962 28716 61678
elsif (builtin::blessed($node) and builtin::reftype($node) eq 'SCALAR') { } 16 28700 28716
elsif (not builtin::blessed($node) and builtin::reftype($node) eq 'HASH') { } 20449 8251 28700
elsif (not builtin::blessed($node) and builtin::reftype($node) eq 'ARRAY') { } 8181 70 8251
985 46 $out .= 'u;';
986 } elsif (!ref $node) {
987 32962 $out .= 's' . length($node) . ':' . $node . ';';
988 ▶ } elsif (blessed($node) && reftype($node) eq 'SCALAR') {
Condition66%2/3
builtin::blessed($node) and builtin::reftype($node) eq "SCALAR"
!ll&&!rl&&r
28700016
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
989 # JSON / YAML booleans: their value is what counts, not which object carries it.
990 16 ▶ $out .= 'b' . (${$node} ? 1 : 0) . ';';
Branch: 1 branch
BranchTrueFalseTotal
${$node;} ? : 16 0 16
991 ▶ } elsif (!blessed($node) && reftype($node) eq 'HASH') {
Condition66%2/3
not builtin::blessed($node) and builtin::reftype($node) eq "HASH"
!ll&&!rl&&r
0825120449
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
992 20449 $out .= 'h{';
993 20449 for my $key (sort keys %$node) {
994 44856 $out .= 's' . length($key) . ':' . $key . ';';
995 44856 $walk->($node->{$key});
996 }
997 20449 $out .= '}';
998 ▶ } elsif (!blessed($node) && reftype($node) eq 'ARRAY') {
Condition66%2/3
not builtin::blessed($node) and builtin::reftype($node) eq "ARRAY"
!ll&&!rl&&r
0708181
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
999 8181 $out .= 'a[';
1000 8181 $walk->($_) for @$node;
1001 8181 $out .= ']';
1002 } else {
1003 70 $out .= 'r' . reftype($node) . ':' . refaddr($node) . ';';
1004 }
1005 6419 };
1006 6419 $walk->($data);
1007 6419 undef $walk;
1008 6419 return sha256_hex($out);
1009 }
1010  
1011 # Applies a config to $self, section by section; reload_config undoes it on a croak. The usage
1012 # store goes last and swaps only once the new store is prepared, so nothing after it can fail.
1013 #
1014 # A section the config declares replaces what is loaded: the file is the declared state. A
1015 # section the previously applied config declared and this one does not goes back to what a
1016 # restart with this config would give (skeid k65) -- except the usage store, see below. A
1017 # section no applied config ever declared is left to whoever set it: nodes pushed through the
1018 # admin API, prices set through pricing.set.
1019 #
1020 # Returns the fingerprint of the nodes section the node list now stands for (undef when the
1021 # config declares none), the sections this config declares, and notices to log once it applied.
1022 600 ▶sub _apply_config {
Subroutine _apply_config: called CC=51 SCAR=39.6
1023 600 my ($self, $cfg) = @_;
1024 600 my $before = $self->_config_declared;
1025 600 my (%declared, @notices);
1026  
1027 # First: the customer source's snapshot is merged into the file's config before any section
1028 # reads it (ADR 0026). Rows are checked against the file, the file wins per key id, and no row
1029 # can fail the load -- only the section itself can. A stale or absent snapshot merges nothing:
1030 # source customers are then refused (fail-closed).
1031 600 my %source;
1032 600 ▶ if (exists $cfg->{customer_source}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $cfg->{"customer_source"}) 54 546 600
1033 54 $declared{customer_source} = 1;
1034 $source{cfg} = Langertha::Skeid::CustomerSource->normalize_config($cfg->{customer_source},
1035 54 usage_store => $cfg->{usage_store});
1036 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
1037 51 my $snapshot = $self->_source_snapshot;
1038 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
1039 29 $source{merge} = Langertha::Skeid::CustomerSource->merge_into($cfg, $snapshot->{rows});
1040 29 $cfg = $source{merge}{config};
1041 }
1042 }
1043  
1044 597 ▶ if (exists $cfg->{pricing}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'pricing'}) { } 130 467 597
elsif ($before->{'pricing'}) { } 2 465 467
1045 130 $declared{pricing} = 1;
1046 # Replaced wholesale, not merged: a model removed from the section loses its price.
1047 130 $self->model_pricing({});
1048 130 ▶ my $pricing = ref($cfg->{pricing}) eq 'HASH' ? $cfg->{pricing} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'pricing'} eq 'HASH' ? : 130 0 130
1049 130 for my $model (keys %$pricing) {
1050 129 my $p = $pricing->{$model};
1051 129 ▶ next unless ref($p) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $p eq "HASH" 0 129 129
1052 129 $self->set_model_pricing($model, $p);
1053 }
1054 } elsif ($before->{pricing}) {
1055 2 $self->model_pricing({});
1056 }
1057  
1058 596 ▶ if (grep { exists $cfg->{$_} } qw( policies default_policy names keys )) {
Branch: 2 branches
BranchTrueFalseTotal
if (grep {exists $cfg->{$_};} 'policies', 'default_policy', 'names', 'keys') { } 140 456 596
elsif ($before->{'policies'}) { } 2 454 456
1059 140 $declared{policies} = 1;
1060 140 $self->_load_policies($cfg);
1061 } elsif ($before->{policies}) {
1062 2 $self->_load_policies({});
1063 }
1064  
1065 # After the policies: client_auth entries may be names: names, resolved through key_names.
1066 # Removed from the file, client authentication is off again -- as a restart without the
1067 # section would have it (skeid k90).
1068 585 ▶ if (exists $cfg->{client_auth}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'client_auth'}) { } 80 505 585
elsif ($before->{'client_auth'}) { } 2 503 505
1069 80 $declared{client_auth} = 1;
1070 80 my @said = $self->_load_client_auth($cfg->{client_auth});
1071 # With a customer source, an empty list in the file is the expected setup: the ids come
1072 # from the source. Every accepted row joins the file's own ids -- a union, so the database
1073 # cannot revoke an id the file lists.
1074 67 ▶ push @notices, @said unless $source{cfg};
Branch: 1 branch
BranchTrueFalseTotal
unless $source{"cfg"} 21 46 67
1075 67 ▶ if ($source{merge}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($source{"merge"}) 26 41 67
1076 26 my %allowed = %{$self->client_auth_keys};
1077 26 $allowed{$_} = 1 for @{$source{merge}{allow}};
1078 26 $self->client_auth_keys(\%allowed);
1079 }
1080 } elsif ($before->{client_auth}) {
1081 2 $self->client_auth_keys(undef);
1082 }
1083 572 ▶ $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 568 572
Condition100%3/3
$source{"cfg"} and not exists $cfg->{"client_auth"}
!ll&&!rl&&r
522464
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
1084  
1085 # The MCP gateway (skeid k103). After the policies as well: a server's keys: may be names:
1086 # names. Removed from the file, the gateway is off again and its routes are unknown paths.
1087 572 ▶ if (exists $cfg->{mcp}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'mcp'}) { } 55 517 572
elsif ($before->{'mcp'}) { } 1 516 517
1088 55 $declared{mcp} = 1;
1089 55 push @notices, $self->_load_mcp($cfg->{mcp});
1090 } elsif ($before->{mcp}) {
1091 1 $self->mcp_servers(undef);
1092 1 $self->mcp_public_url(undef);
1093 1 $self->mcp_max_request_bytes($MCP_MAX_REQUEST_BYTES);
1094 }
1095  
1096 # The OpenAPI document and its optional Swagger UI (skeid k105). Removed from the file, the
1097 # UI is off again and its cache directory forgotten.
1098 544 ▶ if (exists $cfg->{openapi}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'openapi'}) { } 17 527 544
elsif ($before->{'openapi'}) { } 1 526 527
1099 17 $declared{openapi} = 1;
1100 17 $self->_load_openapi($cfg->{openapi});
1101 } elsif ($before->{openapi}) {
1102 1 $self->openapi_swagger_ui(0);
1103 1 $self->openapi_cache_dir(undef);
1104 }
1105  
1106 # The upload limit of the multipart routes (skeid k91). Removed from the file, it is the
1107 # built-in default again.
1108 540 ▶ if (exists $cfg->{uploads}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'uploads'}) { } 18 522 540
elsif ($before->{'uploads'}) { } 2 520 522
1109 18 $declared{uploads} = 1;
1110 18 $self->_load_uploads($cfg->{uploads});
1111 } elsif ($before->{uploads}) {
1112 2 $self->upload_max_bytes($UPLOAD_MAX_BYTES);
1113 2 $self->documents_max_bytes($DOCUMENTS_MAX_BYTES);
1114 }
1115  
1116 # Whether the documents routes pass requests that make the node fetch from an address the
1117 # client names (skeid k94, ADR 0028). Removed from the file, it is refused again.
1118 529 ▶ if (exists $cfg->{documents}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'documents'}) { } 6 523 529
elsif ($before->{'documents'}) { } 0 523 523
1119 6 $declared{documents} = 1;
1120 6 $self->_load_documents($cfg->{documents});
1121 } elsif ($before->{documents}) {
1122 0 $self->documents_allow_remote_sources(0);
1123 }
1124  
1125 # The limits of a realtime session (skeid k95). Removed from the file, the defaults again.
1126 524 ▶ if (exists $cfg->{realtime}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'realtime'}) { } 24 500 524
elsif ($before->{'realtime'}) { } 1 499 500
1127 24 $declared{realtime} = 1;
1128 24 $self->_load_realtime($cfg->{realtime});
1129 } elsif ($before->{realtime}) {
1130 1 $self->_load_realtime({});
1131 }
1132  
1133 513 ▶ if (exists $cfg->{aliases}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'aliases'}) { } 70 443 513
elsif ($before->{'aliases'}) { } 4 439 443
1134 70 $declared{aliases} = 1;
1135 # Replaced wholesale, like nodes: the file is the declared state.
1136 70 $self->model_aliases({});
1137 70 ▶ my $aliases = ref($cfg->{aliases}) eq 'HASH' ? $cfg->{aliases} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'aliases'} eq 'HASH' ? : 70 0 70
1138 70 for my $name (keys %$aliases) {
1139 64 $self->set_model_alias($name, $aliases->{$name});
1140 }
1141 } elsif ($before->{aliases}) {
1142 4 $self->model_aliases({});
1143 }
1144  
1145 513 my $nodes_print = $self->_nodes_fingerprint;
1146 513 ▶ if (exists $cfg->{nodes}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'nodes'}) { } 295 218 513
elsif ($before->{'nodes'}) { } 1 217 218
1147 295 $declared{nodes} = 1;
1148 295 ▶ my $nodes = ref($cfg->{nodes}) eq 'ARRAY' ? $cfg->{nodes} : [];
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'nodes'} eq 'ARRAY' ? : 295 0 295
1149 # An unchanged nodes section keeps the node list as it is (skeid #38).
1150 295 my $print = _config_digest($nodes);
1151 295 ▶ if (!defined($nodes_print) || $print ne $nodes_print) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $nodes_print or $print ne $nodes_print) 253 42 295
Condition100%3/3
not defined $nodes_print or $print ne $nodes_print
l!l&&r!l&&!r
2341942
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
1152 253 $self->nodes([]);
1153 253 for my $n (@$nodes) {
1154 822 ▶ next unless ref($n) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $n eq "HASH" 0 822 822
1155 822 ▶ next unless defined $n->{id} && defined $n->{url};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n->{"id"} and defined $n->{"url"} 0 822 822
Condition33%1/3
defined $n->{"id"} and defined $n->{"url"}
!ll&&!rl&&r
00822
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
1156 822 $self->add_node(%$n);
1157 }
1158 246 $nodes_print = $print;
1159 }
1160 } elsif ($before->{nodes}) {
1161 1 $self->nodes([]);
1162 1 $nodes_print = undef;
1163 }
1164  
1165 506 ▶ my $routing = ref($cfg->{routing}) eq 'HASH' ? $cfg->{routing} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'routing'} eq 'HASH' ? : 30 476 506
1166 506 for my $key (sort keys %ROUTING_SETTINGS) {
1167 2024 my ($attr, $convert) = @{ $ROUTING_SETTINGS{$key} };
1168 2024 ▶ if (defined $routing->{$key}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $routing->{$key}) { } 48 1976 2024
elsif ($$before{'routing.' . $key}) { } 4 1972 1976
1169 48 $declared{'routing.' . $key} = 1;
1170 48 $self->$attr($convert->($routing->{$key}));
1171 } elsif ($before->{'routing.' . $key}) {
1172 4 $self->$attr($self->_routing_baseline->{$attr});
1173 }
1174 }
1175  
1176 506 $self->_config_admin_api_key($self->_admin_api_key_from_config($cfg));
1177 506 $self->_apply_admin_api_key;
1178  
1179 506 $self->_load_registry($cfg);
1180  
1181 # Last: a key's manifest is checked against its routing policy and the aliases.
1182 497 $self->_load_manifest($cfg);
1183  
1184 # A changed usage store is swapped here, the new one prepared before the old one goes. A
1185 # removed one is not: the removal names no destination, so honouring it would stop recording
1186 # usage events -- billing data (ADR 0004) -- on a reload, silently. The running store stays
1187 # until a restart, and the reload says so once (skeid k65).
1188 488 my $usage_cfg = $cfg->{usage_store};
1189 488 ▶ if (ref($usage_cfg) eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $usage_cfg eq 'HASH') { } 5 483 488
elsif (exists $cfg->{'usage_db_path'}) { } 0 483 483
elsif ($before->{'usage_store'}) { } 1 482 483
1190 5 $declared{usage_store} = 1;
1191 5 $self->_configure_usage_store($usage_cfg);
1192 } elsif (exists $cfg->{usage_db_path}) {
1193 0 $declared{usage_store} = 1;
1194 $self->_configure_usage_store({
1195 backend => 'sqlite',
1196 sqlite_path => $cfg->{usage_db_path},
1197 0 });
1198 } elsif ($before->{usage_store}) {
1199 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
1200 1 push @notices, 'usage_store was removed from the config; the running ' . $backend
1201 . ' store stays in force until restart (usage events are billing data, ADR 0004)';
1202 }
1203  
1204 488 return ($nodes_print, \%declared, \@notices, \%source);
1205 }
1206  
1207 # The admin API key a config names (skeid k64). It may be named directly or handed over by
1208 # environment variable, the same way usage_store takes password_env -- a deployment should not
1209 # have to write the key into a file that gets mounted into a container. The first spelling
1210 # present decides, even when it is empty: a config may switch the admin API off. A config that
1211 # names none leaves the key to SKEID_ADMIN_API_KEY.
1212 506 ▶sub _admin_api_key_from_config {
Subroutine _admin_api_key_from_config: called CC=10 SCAR=25.1
1213 506 my ($self, $cfg) = @_;
1214 506 ▶ my $admin = ref($cfg->{admin}) eq 'HASH' ? $cfg->{admin} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'admin'} eq 'HASH' ? : 31 475 506
1215 return exists($cfg->{admin_api_key}) ? ($cfg->{admin_api_key} // '') . ''
1216 : defined($cfg->{admin_api_key_env}) ? $ENV{$cfg->{admin_api_key_env}} // ''
1217 : exists($admin->{api_key}) ? ($admin->{api_key} // '') . ''
1218 506 ▶ : defined($admin->{api_key_env}) ? $ENV{$admin->{api_key_env}} // ''
Branch: 4 branches
BranchTrueFalseTotal
exists $cfg->{'admin_api_key'} ? : 14 492 506
defined $cfg->{'admin_api_key_env'} ? : 0 492 492
exists $admin->{'api_key'} ? : 30 462 492
defined $admin->{'api_key_env'} ? : 1 461 462
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
1219 : $self->_env_admin_api_key;
1220 }
1221  
1222 # The admin API key in force: the explicit one, else the config's.
1223 514 ▶sub _apply_admin_api_key {
Subroutine _apply_admin_api_key: called CC=2 SCAR=6.9
1224 514 my ($self) = @_;
1225 514 my $explicit = $self->_explicit_admin_api_key;
1226 514 ▶ $self->admin_api_key(length($explicit) ? $explicit : $self->_config_admin_api_key);
Branch: 1 branch
BranchTrueFalseTotal
length $explicit ? : 17 497 514
1227 514 return $self->admin_api_key;
1228 }
1229  
1230  
1231 8 ▶sub set_admin_api_key {
Subroutine set_admin_api_key: called CC=2 SCAR=7.1
Pod documented
1232 8 my ($self, $key) = @_;
1233 8 ▶ $self->_explicit_admin_api_key(defined($key) ? "$key" : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $key ? : 8 0 8
1234 8 return $self->_apply_admin_api_key;
1235 }
1236  
1237  
1238 # Longest wait between two retries of a failing config_loader, in seconds.
1239 113 my $RELOAD_BACKOFF_MAX = 60;
1240  
1241 9697 ▶sub maybe_reload_config {
Subroutine maybe_reload_config: called CC=15 SCAR=27.2
Pod documented
1242 9697 my ($self) = @_;
1243  
1244 9697 ▶ if ($self->has_config_loader && !$self->has_config_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_config_loader and not $self->has_config_file) 6501 3196 9697
Condition66%2/3
$self->has_config_loader and not $self->has_config_file
!ll&&!rl&&r
319606501
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
1245 # Loader-based configs are dynamic, but not re-read more often than
1246 # config_reload_interval, and a load that reads what was already applied is a no-op.
1247 6501 my $now = $self->_now;
1248 6501 my $next = $self->_config_next_check_at;
1249 6501 ▶ return 0 if defined($next) && $now < $next;
Branch: 1 branch
BranchTrueFalseTotal
if defined $next and $now < $next 1786 4715 6501
Condition66%2/3
defined $next and $now < $next
!ll&&!rl&&r
047151786
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
1250 4715 return $self->_reload_on_request;
1251 }
1252  
1253 3196 ▶ return 0 unless $self->has_config_file;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_config_file 3134 62 3196
1254 62 my $file = $self->config_file;
1255 62 ▶ unless (-f $file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $file) 6 56 62
1256 # Gone after a good load (a botched deploy, a volume that went away): the config in force
1257 # stays, as it would for a file that fails to parse -- but said once, not silently.
1258 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
1259 unless $self->_config_file_missing;
1260 6 $self->_config_file_missing(1);
1261 6 return 0;
1262 }
1263 56 $self->_config_file_missing(0);
1264  
1265 56 ▶ my $mtime = (stat($file))[9] || 0;
Condition50%1/2
(stat $file)[9] || 0
l!l
560
MC/DC0%0/1
(stat $file)[9] || 0
(stat $file)[9]
Truth table50%1/2
A
A= (stat $file)[9]
Aresult
11
00
1266 56 my $last = $self->_config_mtime;
1267 56 ▶ if (!defined($last) || $mtime > $last) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $last or $mtime > $last) 52 4 56
Condition66%2/3
not defined $last or $mtime > $last
l!l&&r!l&&!r
0524
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
1268 52 my $failed = $self->_config_file_failed_mtime;
1269 52 my $retry = $self->_config_file_retry_at;
1270 52 ▶ 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 13 52
Condition88%8/9
defined $failed and $mtime == $failed and defined $retry and $self->_now < $retry
!ll&&!rl&&r
12139
defined $failed and $mtime == $failed and defined $retry
!ll&&!rl&&r
12040
defined $failed and $mtime == $failed
!ll&&!rl&&r
11140
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
1271 && defined($retry) && $self->_now < $retry;
1272 13 return $self->_reload_on_request($mtime);
1273 }
1274 4 return 0;
1275 }
1276  
1277 # One retry schedule for loader and file failures. A file's next version bypasses this delay in
1278 # maybe_reload_config; the delay applies only while the observed mtime is unchanged.
1279 28 ▶sub _reload_retry_delay {
Subroutine _reload_retry_delay: called CC=5 SCAR=16.2
1280 28 my ($self) = @_;
1281 28 ▶ my $failures = $self->reload_failures // 0;
Condition50%1/2
$self->reload_failures // 0
l!l
280
MC/DC0%0/1
$self->reload_failures // 0
$self->reload_failures
Truth table50%1/2
A
A= $self->reload_failures
Aresult
11
00
1282 28 ▶ my $base = 0 + ($self->config_reload_interval // 0);
Condition50%1/2
$self->config_reload_interval // 0
l!l
280
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
1283 28 ▶ $base = 1 if $base < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $base < 1 11 17 28
1284 28 my $delay = $base * 2 ** ($failures - 1);
1285 28 ▶ $delay = $RELOAD_BACKOFF_MAX if $delay > $RELOAD_BACKOFF_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if $delay > $RELOAD_BACKOFF_MAX 9 19 28
1286 28 return $delay;
1287 }
1288  
1289 # A reload triggered by a request (skeid #39). Its failure is not the request's: the previous
1290 # config is still fully in force, so the request is served under it. Failing it with a 500
1291 # would take every request down until the config is fixed -- with a loader, every one.
1292 4728 ▶sub _reload_on_request {
Subroutine _reload_on_request: called CC=13 SCAR=26.4
1293 4728 my ($self, $file_mtime) = @_;
1294 4728 ▶ my $before = $self->_config_fingerprint // '';
Condition50%1/2
$self->_config_fingerprint // ""
l!l
47280
MC/DC0%0/1
$self->_config_fingerprint // ""
$self->_config_fingerprint
Truth table50%1/2
A
A= $self->_config_fingerprint
Aresult
11
00
1295 4728 my $error_before = $self->last_reload_error;
1296 4728 ▶ if (eval { $self->reload_config; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { $self->reload_config; 1 } }) 4700 28 4728
1297 4700 ▶ return (($self->_config_fingerprint // '') ne $before) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
($self->_config_fingerprint // '') ne $before ? : 70 4630 4700
Condition50%1/2
$self->_config_fingerprint // ""
l!l
47000
MC/DC0%0/1
$self->_config_fingerprint // ""
$self->_config_fingerprint
Truth table50%1/2
A
A= $self->_config_fingerprint
Aresult
11
00
1298 }
1299  
1300 28 ▶ my $err = $@ || 'config reload failed';
Condition50%1/2
$@ || 'config reload failed'
l!l
280
MC/DC0%0/1
$@ || 'config reload failed'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
1301 28 ▶ my $failures = $self->reload_failures // 0;
Condition50%1/2
$self->reload_failures // 0
l!l
280
MC/DC0%0/1
$self->reload_failures // 0
$self->reload_failures
Truth table50%1/2
A
A= $self->reload_failures
Aresult
11
00
1302 28 ▶ if ($self->has_config_loader && $failures > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->has_config_loader and $failures > 0) { } 26 2 28
elsif (defined $file_mtime and $failures > 0) { } 2 0 2
Condition66%2/3
$self->has_config_loader and $failures > 0
!ll&&!rl&&r
2026
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
1303 26 $self->_config_next_check_at($self->_now + $self->_reload_retry_delay);
1304 ▶ } 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
1305 2 $self->_config_file_failed_mtime($file_mtime);
1306 2 $self->_config_file_retry_at($self->_now + $self->_reload_retry_delay);
1307 }
1308 # Logged when the reason is new; the same failure again, retry after retry, is not.
1309 28 ▶ if (!defined($error_before) || $error_before ne $err) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $error_before or $error_before ne $err) 12 16 28
Condition100%3/3
not defined $error_before or $error_before ne $err
l!l&&r!l&&!r
11116
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
1310 12 (my $msg = $err) =~ s/\s+\z//;
1311 12 warn "skeid: config reload failed, keeping the previous config: $msg\n";
1312 }
1313 28 return 0;
1314 }
1315  
1316 11370 ▶sub _now { Time::HiRes::time() }
Subroutine _now: called CC=1 SCAR=0.0
1317  
1318 # --- customer source (ADR 0026) -------------------------------------------------------------
1319  
1320 # What the snapshot contributes to the config fingerprint.
1321 939 ▶sub _source_digest {
Subroutine _source_digest: called CC=3 SCAR=11.0
1322 939 my ($self) = @_;
1323 939 my $snapshot = $self->_source_snapshot;
1324 939 ▶ return 'none' unless $snapshot;
Branch: 1 branch
BranchTrueFalseTotal
unless $snapshot 49 890 939
1325 890 ▶ return $snapshot->{stale} ? 'stale' : $snapshot->{digest};
Branch: 1 branch
BranchTrueFalseTotal
$snapshot->{'stale'} ? : 1 889 890
1326 }
1327  
1328 2 ▶sub _require_customer_source_driver {
Subroutine _require_customer_source_driver: called CC=2 SCAR=7.2
1329 2 my ($self) = @_;
1330 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
1331 2 croak 'customer_source needs DBD::Pg (and DBI), which is not installed: install DBD::Pg, '
1332 . 'or remove the customer_source section';
1333 }
1334  
1335 # Runs once a config applied: the source as the config now declares it. A removed section stops
1336 # the fetcher and drops the snapshot; a changed one restarts the fetcher, the snapshot staying in
1337 # force until the new source answered. Returns the notices to log.
1338 488 ▶sub _commit_customer_source {
Subroutine _commit_customer_source: called CC=14 SCAR=26.4
1339 488 my ($self, $source) = @_;
1340 488 ▶ $source ||= {};
Condition50%1/2
$source ||= {}
l!l
4880
MC/DC0%0/1
$source ||= {}
$source
Truth table50%1/2
A
A= $source
Aresult
11
00
1341 488 my $cfg = $source->{cfg};
1342 488 ▶ unless ($cfg) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cfg) 438 50 488
1343 438 $self->_stop_source_controller;
1344 438 $self->_source_snapshot(undef);
1345 438 $self->_source_report(undef);
1346 438 $self->_source_cfg(undef);
1347 438 $self->_source_cfg_print(undef);
1348 438 return;
1349 }
1350  
1351 50 my @notices;
1352 50 my $merge = $source->{merge};
1353 $self->_source_report($merge ? {
1354 accepted => $merge->{accepted},
1355 rejected => $merge->{rejected},
1356 shadowed => $merge->{shadowed},
1357 names => $merge->{names} || {},
1358 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
1359 50 ▶ if ($merge) {
Branch: 1 branch
BranchTrueFalseTotal
if ($merge) 28 22 50
1360 # By label and reason only: a rejected value may be a key pasted where its id belongs.
1361 28 my @rejected = @{$merge->{rejected}};
1362 28 push @notices, map { "customer_source: $_->{row} rejected: $_->{reason}" } @rejected[0 .. _last(19, @rejected)];
1363 28 ▶ push @notices, 'customer_source: ' . (@rejected - 20) . ' more rows rejected' if @rejected > 20;
Branch: 1 branch
BranchTrueFalseTotal
if @rejected > 20 0 28 28
1364 28 my @shadowed = @{$merge->{shadowed}};
1365 28 push @notices, map { "customer_source: $_ shadowed: the file's keys: entry for that key id wins" }
1366 @shadowed[0 .. _last(19, @shadowed)];
1367 28 ▶ push @notices, 'customer_source: ' . (@shadowed - 20) . ' more rows shadowed' if @shadowed > 20;
Branch: 1 branch
BranchTrueFalseTotal
if @shadowed > 20 0 28 28
1368 }
1369 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
1370 2 $self->_source_gate_warned(1);
1371 2 push @notices, 'customer_source is configured but client_auth is not: source keys are not '
1372 . 'gated, and a revoked key is not refused -- it routes under default_policy. Declare '
1373 . 'client_auth (client_auth: { keys: [] } is enough)';
1374 }
1375 50 ▶ $self->_source_gate_warned(0) unless $source->{no_gate};
Branch: 1 branch
BranchTrueFalseTotal
unless $source->{"no_gate"} 46 4 50
1376  
1377 50 my $print = _config_digest($cfg);
1378 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
1379 50 $self->_source_cfg($cfg);
1380 50 $self->_source_cfg_print($print);
1381 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
1382 50 return @notices;
1383 }
1384  
1385 532 ▶sub _last { my ($max, @list) = @_; return $#list < $max ? $#list : $max }
Subroutine _last: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$#list < $max ? : 532 0 532
1386  
1387 529 ▶sub _start_source_controller {
Subroutine _start_source_controller: called CC=3 SCAR=11.3
1388 529 my ($self) = @_;
1389 529 $self->_stop_source_controller;
1390 529 ▶ my $cfg = $self->_source_cfg or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cfg = $self->_source_cfg or return 22 507 529
1391 my $fetcher = $self->has_customer_source_fetcher
1392 ? $self->customer_source_fetcher->($self, $cfg)
1393 22 ▶ : do {
Branch: 1 branch
BranchTrueFalseTotal
$self->has_customer_source_fetcher ? : 22 0 22
1394 0 require Langertha::Skeid::CustomerSource::DBI;
1395 0 Langertha::Skeid::CustomerSource::DBI->new(config => $cfg);
1396 };
1397 22 my $weak = $self;
1398 22 weaken($weak);
1399 my $ctl = Langertha::Skeid::CustomerSource->new(
1400 config => $cfg,
1401 fetcher => $fetcher,
1402 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
1403 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
1404 22 );
1405 22 $self->_source_ctl($ctl);
1406 22 $ctl->start;
1407 22 return $ctl;
1408 }
1409  
1410 1608 ▶sub _stop_source_controller {
Subroutine _stop_source_controller: called CC=3 SCAR=11.0
1411 1608 my ($self) = @_;
1412 1608 my $ctl = $self->_source_ctl;
1413 1608 ▶ $ctl->stop if $ctl;
Branch: 1 branch
BranchTrueFalseTotal
if $ctl 22 1586 1608
1414 1608 $self->_source_ctl(undef);
1415 1608 my $timer = $self->_source_stale_timer;
1416 1608 ▶ Mojo::IOLoop->remove($timer) if defined $timer;
Branch: 1 branch
BranchTrueFalseTotal
if defined $timer 1 1607 1608
1417 1608 $self->_source_stale_timer(undef);
1418 1608 return;
1419 }
1420  
1421 # A successful fetch. An unchanged snapshot only renews its age: no reload, no inventory bump, no
1422 # probe restart. A changed one is merged by a reload -- in-memory work, run here, from the loop,
1423 # never from a request.
1424 33 ▶sub _source_rows {
Subroutine _source_rows: called CC=4 SCAR=13.9
1425 33 my ($self, $rows) = @_;
1426 33 my $digest = Langertha::Skeid::CustomerSource->snapshot_digest($rows);
1427 33 $self->_arm_source_stale_timer;
1428 33 my $snapshot = $self->_source_snapshot;
1429 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
1430 8 $snapshot->{fetched_at} = $self->_now;
1431 8 return;
1432 }
1433 25 $self->_source_snapshot({ rows => $rows, digest => $digest, fetched_at => $self->_now, stale => 0 });
1434 25 $self->_reload_for_source;
1435 25 return;
1436 }
1437  
1438 13 ▶sub _source_failed {
Subroutine _source_failed: called CC=1 SCAR=0.0
1439 13 my ($self, $err) = @_;
1440 13 $self->_check_source_stale;
1441 13 return;
1442 }
1443  
1444 # max_stale_s: how old the last good snapshot may get while fetches fail. Checked when a fetch
1445 # fails and when the limit runs out after the last success, whichever is first.
1446 33 ▶sub _arm_source_stale_timer {
Subroutine _arm_source_stale_timer: called CC=4 SCAR=14.3
1447 33 my ($self) = @_;
1448 33 my $timer = $self->_source_stale_timer;
1449 33 ▶ Mojo::IOLoop->remove($timer) if defined $timer;
Branch: 1 branch
BranchTrueFalseTotal
if defined $timer 0 33 33
1450 33 $self->_source_stale_timer(undef);
1451 33 ▶ my $max = $self->_source_cfg ? $self->_source_cfg->{max_stale_s} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->_source_cfg ? : 33 0 33
1452 33 ▶ return unless $max > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $max > 0 31 2 33
1453 2 my $weak = $self;
1454 2 weaken($weak);
1455 1 ▶ $self->_source_stale_timer(Mojo::IOLoop->timer($max => sub {
Subroutine __ANON__: called CC=4 SCAR=15.6
1456 1 ▶ return unless $weak;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak 0 1 1
1457 1 $weak->_source_stale_timer(undef);
1458 1 my $ctl = $weak->_source_ctl;
1459 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
1460 2 }));
1461 2 return;
1462 }
1463  
1464 14 ▶sub _check_source_stale {
Subroutine _check_source_stale: called CC=6 SCAR=18.3
1465 14 my ($self) = @_;
1466 14 ▶ my $cfg = $self->_source_cfg or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cfg = $self->_source_cfg or return 14 0 14
1467 14 my $max = $cfg->{max_stale_s};
1468 14 ▶ return unless $max > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $max > 0 11 3 14
1469 3 my $snapshot = $self->_source_snapshot;
1470 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
1471 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
1472 1 warn "skeid: customer_source: the last good snapshot is older than max_stale_s (${max}s); its "
1473 . "rows are dropped until a fetch succeeds\n";
1474 1 $self->_source_snapshot({ %$snapshot, rows => [], stale => 1 });
1475 1 $self->_reload_for_source;
1476 1 return;
1477 }
1478  
1479 # The reload a new snapshot triggers: the existing all-or-nothing reload_config, with the file
1480 # read again and the snapshot in memory. It never dies -- it runs from a loop callback -- and a
1481 # failure is logged when its reason is new, like a reload a request triggers.
1482 26 ▶sub _reload_for_source {
Subroutine _reload_for_source: called CC=7 SCAR=29.9
1483 26 my ($self) = @_;
1484 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
1485 26 my $error_before = $self->last_reload_error;
1486 26 ▶ return if eval { $self->reload_config; 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $self->reload_config; 1 } } 26 0 26
1487 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
1488 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
1489 0 (my $msg = $err) =~ s/\s+\z//;
1490 0 warn "skeid: config reload for a new customer_source snapshot failed, keeping the previous "
1491 . "config: $msg\n";
1492 }
1493 0 return;
1494 }
1495  
1496  
1497 526 ▶sub start_customer_source {
Subroutine start_customer_source: called CC=4 SCAR=14.6
Pod documented
1498 526 my ($self) = @_;
1499 526 ▶ return 1 if $self->_source_started && $self->_source_ctl;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_source_started and $self->_source_ctl 0 526 526
Condition33%1/3
$self->_source_started and $self->_source_ctl
!ll&&!rl&&r
52600
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
1500 526 $self->_source_started(1);
1501 526 ▶ return $self->_start_source_controller ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->_start_source_controller ? : 19 507 526
1502 }
1503  
1504  
1505 14 ▶sub stop_customer_source {
Subroutine stop_customer_source: called CC=1 SCAR=0.0
Pod documented
1506 14 my ($self) = @_;
1507 14 $self->_source_started(0);
1508 14 $self->_stop_source_controller;
1509 14 return;
1510 }
1511  
1512  
1513 6 ▶sub customer_source_startup_fetch {
Subroutine customer_source_startup_fetch: called CC=6 SCAR=18.1
Pod documented
1514 6 my ($self) = @_;
1515 6 ▶ my $ctl = $self->_source_ctl or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $ctl = $self->_source_ctl or return 0 6 0 6
1516 6 my $done = $ctl->completed;
1517 6 $ctl->fetch_now;
1518 6 my $end = $self->_now + $ctl->config->{connect_timeout_s} + 1;
1519 6 ▶ my $tick = Mojo::IOLoop->recurring(0.05 => sub { });
Subroutine __ANON__: called CC=1 SCAR=0.0
1520 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
1521 6 Mojo::IOLoop->remove($tick);
1522 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
1523 }
1524  
1525  
1526 1 ▶sub customer_source_release {
Subroutine customer_source_release: called CC=2 SCAR=7.2
Pod documented
1527 1 my ($self) = @_;
1528 1 my $ctl = $self->_source_ctl;
1529 1 ▶ return unless $ctl;
Branch: 1 branch
BranchTrueFalseTotal
unless $ctl 0 1 1
1530 1 $ctl->release;
1531 1 weaken(my $weak = $self);
1532 1 ▶ Mojo::IOLoop->next_tick(sub {
Subroutine __ANON__: called CC=3 SCAR=13.1
1533 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
1534 1 ▶ $c->fetch_now if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 1 0 1
1535 1 });
1536 1 return;
1537 }
1538  
1539  
1540 284 ▶sub customer_source_status {
Subroutine customer_source_status: called CC=6 SCAR=17.9
Pod documented
1541 284 my ($self) = @_;
1542 284 ▶ my $cfg = $self->_source_cfg or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $cfg = $self->_source_cfg or return undef 231 53 284
1543 231 my $ctl = $self->_source_ctl;
1544 231 ▶ my $status = $ctl ? $ctl->status : {
Branch: 1 branch
BranchTrueFalseTotal
$ctl ? : 231 0 231
1545 ok => 0, last_success_at => undef, failed_at => undef, failures => 0,
1546 error => 'the customer source is not being fetched (not started)',
1547 };
1548 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
1549 231 my @rejected = @{$report->{rejected}};
1550 231 my @shadowed = @{$report->{shadowed}};
1551 231 my $snapshot = $self->_source_snapshot;
1552 return {
1553 %$status,
1554 relation => $cfg->{relation},
1555 listen => $cfg->{listen},
1556 stale => ($snapshot && $snapshot->{stale}) ? 1 : 0,
1557 rows => {
1558 accepted => 0 + $report->{accepted},
1559 rejected => scalar(@rejected),
1560 shadowed => scalar(@shadowed),
1561 },
1562 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
1563 shadowed => [ @shadowed[0 .. _last(49, @shadowed)] ],
1564 };
1565 }
1566  
1567  
1568 7 ▶sub customer_names {
Subroutine customer_names: called CC=3 SCAR=11.4
Pod documented
1569 7 my ($self) = @_;
1570 7 ▶ my $report = $self->_source_report or return {};
Branch: 1 branch
BranchTrueFalseTotal
my $report = $self->_source_report or return {} 7 0 7
1571 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
1572 }
1573  
1574  
1575 7 ▶sub customer_report {
Subroutine customer_report: called CC=3 SCAR=11.1
Pod documented
1576 7 my ($self) = @_;
1577 7 ▶ $self->_source_cfg or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->_source_cfg or return undef 7 0 7
1578 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
1579 7 my @rejected = @{$report->{rejected}};
1580 7 my @shadowed = @{$report->{shadowed}};
1581 return {
1582 accepted => 0 + $report->{accepted},
1583 7 rejected => [ map { +{ %$_ } } @rejected[0 .. _last(49, @rejected)] ],
1584 shadowed => [ @shadowed[0 .. _last(49, @shadowed)] ],
1585 };
1586 }
1587  
1588 # The client-facing faces Skeid serves, as manifest endpoints. Each face's spec -- dialect,
1589 # path under public_url, and the capability flags its translator actually carries upstream --
1590 # lives with that face's translator (ADR 0001: format-specific facts stay in the translator).
1591 my %MANIFEST_FACES = (
1592 18 ▶ openai => sub { Langertha::Skeid::Protocol->openai_manifest_endpoint },
Subroutine __ANON__: called CC=1 SCAR=0.0
1593 18 ▶ anthropic => sub { Langertha::Skeid::Protocol::Anthropic->manifest_endpoint },
Subroutine __ANON__: called CC=1 SCAR=0.0
1594 18 ▶ ollama => sub { Langertha::Skeid::Protocol::Ollama->manifest_endpoint },
Subroutine __ANON__: called CC=1 SCAR=0.0
1595 113 );
1596 113 my @MANIFEST_FACE_ORDER = qw(openai anthropic ollama);
1597 113 my $manifest_unavailable_warned;
1598  
1599 123 ▶sub _is_true {
Subroutine _is_true: called CC=3 SCAR=11.1
1600 123 my ($value) = @_;
1601 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
1602 }
1603  
1604 113 my %REGISTRY_KEYS = map { $_ => 1 } qw(enabled secret_env read_key_env ttl_s instance_id error_window_s);
1605  
1606 # The registry section (ADR 0017). Absent means off, so removing the block disables publishing
1607 # on the next reload. Enabled without a usable secret (set, at least MIN_SECRET_BYTES) or
1608 # without any credential to read it (admin key or read key) is a load error: the route never
1609 # answers unsigned, is unreadable without one of the two, and a config that asked for it should
1610 # not load as if it had not.
1611 506 ▶sub _load_registry {
Subroutine _load_registry: called CC=29 SCAR=35.5
1612 506 my ($self, $cfg) = @_;
1613 506 my $section = $cfg->{registry};
1614 506 my ($enabled, $secret, $read_key, $ttl, $instance, $window) = (0, '', '', 10, undef, 60);
1615  
1616 506 ▶ if (defined $section) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section) 20 486 506
1617 20 ▶ croak 'registry must be a hashref' unless ref($section) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 0 20 20
1618 20 for my $key (sort keys %$section) {
1619 croak "registry: unknown key '$key' (known: " . join(' ', sort keys %REGISTRY_KEYS)
1620 . '; the secret is named by secret_env, never written into the config)'
1621 45 ▶ unless $REGISTRY_KEYS{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless $REGISTRY_KEYS{$key} 2 43 45
1622 }
1623 18 $enabled = _is_true($section->{enabled});
1624  
1625 18 ▶ if (defined $section->{ttl_s}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"ttl_s"}) 2 16 18
1626 croak 'registry.ttl_s must be a positive number of seconds'
1627 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
1628 1 $ttl = 0 + $section->{ttl_s};
1629 }
1630 17 ▶ if (defined $section->{error_window_s}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"error_window_s"}) 0 17 17
1631 croak 'registry.error_window_s must be a positive number of seconds'
1632 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
1633 0 $window = 0 + $section->{error_window_s};
1634 }
1635 17 ▶ if (defined $section->{instance_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"instance_id"}) 1 16 17
1636 croak 'registry.instance_id must be a non-empty string'
1637 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
1638 1 $instance = "$section->{instance_id}";
1639 }
1640  
1641 17 ▶ if ($enabled) {
Branch: 1 branch
BranchTrueFalseTotal
if ($enabled) 16 1 17
1642 16 my $env = $section->{secret_env};
1643 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
1644 . 'signed, never published unsigned'
1645 unless defined($env) && !ref($env) && length($env);
1646 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
1647 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
1648 . 'published unsigned'
1649 unless length $secret;
1650 13 require Langertha::Skeid::Registry;
1651 13 my $min = Langertha::Skeid::Registry->MIN_SECRET_BYTES;
1652 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
1653 . "secret of at least $min bytes (e.g. openssl rand -hex 32)"
1654 if length($secret) < $min;
1655 # The read key opens the snapshot route and nothing else (skeid #49), so a fronting tier
1656 # need not hold the admin key. Named but empty is a mistake, not "no read key".
1657 12 ▶ if (defined $section->{read_key_env}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"read_key_env"}) 4 8 12
1658 4 my $read_env = $section->{read_key_env};
1659 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
1660 if ref($read_env) || !length($read_env);
1661 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
1662 4 ▶ croak "registry.read_key_env names '$read_env', which is not set"
Branch: 1 branch
BranchTrueFalseTotal
unless length $read_key 1 3 4
1663 unless length $read_key;
1664 }
1665 # The fronting tier reads the snapshot with the read key or this Skeid's admin key.
1666 # Without either nobody can, and a registry nobody can read is a config mistake, not a
1667 # choice -- say so at load instead of answering 404 forever.
1668 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
1669 . 'or an admin API key (admin.api_key or admin.api_key_env)'
1670 unless length($read_key) || length($self->admin_api_key // '');
1671 }
1672 }
1673  
1674 497 $self->registry_enabled($enabled);
1675 497 $self->registry_secret($secret);
1676 497 $self->registry_read_key($read_key);
1677 497 $self->registry_ttl_s($ttl);
1678 497 $self->registry_instance_id($instance);
1679 497 $self->registry_error_window_s($window);
1680 497 return 1;
1681 }
1682  
1683 # Resolves the manifest section and every key's manifest: grant once, at config load (ADR
1684 # 0015). Nothing is published that a keys: entry does not list, and what is listed has to be
1685 # something that key's routing policy lets it reach -- a contradiction is a load error, not a
1686 # manifest that promises a model the request path then refuses with 403. Everything is built
1687 # into lexicals and set together at the end; reload_config restores the old state on a croak.
1688 497 ▶sub _load_manifest {
Subroutine _load_manifest: called CC=48 SCAR=40.4
1689 497 my ($self, $cfg) = @_;
1690 497 my ($enabled, $available, %manifests) = (0, 0);
1691 488 ▶ my $commit = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1692 488 $self->manifest_enabled($enabled);
1693 488 $self->manifest_available($available);
1694 488 $self->key_manifests({%manifests});
1695 488 return 1;
1696 497 };
1697  
1698 497 my %grants;
1699 497 ▶ if (ref($cfg->{keys}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg->{"keys"} eq "HASH") 49 448 497
1700 49 for my $label (sort keys %{$cfg->{keys}}) {
1701 93 my $entry = $cfg->{keys}{$label};
1702 93 ▶ next unless ref($entry) eq 'HASH' && exists $entry->{manifest};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" and exists $entry->{"manifest"} 52 41 93
Condition100%3/3
ref $entry eq "HASH" and exists $entry->{"manifest"}
!ll&&!rl&&r
401241
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
1703 41 my $grant = $entry->{manifest};
1704 croak "key '$label': manifest must be a hashref with a models list"
1705 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
1706 41 my (%seen, @models);
1707 41 for my $model (@{$grant->{models}}) {
1708 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
1709 unless defined($model) && !ref($model) && length($model);
1710 80 ▶ push @models, "$model" unless $seen{$model}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$model}++ 80 0 80
1711 }
1712 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
1713 41 $grants{$id} = { label => $label, models => \@models };
1714 }
1715 }
1716  
1717 497 my $section = $cfg->{manifest};
1718 497 ▶ return $commit->() unless defined $section;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $section 476 21 497
1719 21 ▶ croak 'manifest must be a hashref' unless ref($section) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 0 21 21
1720 21 ▶ return $commit->() unless _is_true($section->{enabled});
Branch: 1 branch
BranchTrueFalseTotal
unless _is_true($section->{"enabled"}) 1 20 21
1721  
1722 20 my $public_url = $section->{public_url};
1723 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
1724 . 'Skeid at, never a node URL'
1725 unless defined($public_url) && !ref($public_url) && length($public_url);
1726 19 $public_url =~ s{/+\z}{};
1727 19 my ($issuer) = $public_url =~ m{\A([A-Za-z][A-Za-z0-9+.-]*://[^/?#]+)};
1728 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
1729  
1730 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
1731  
1732 19 my @faces = @MANIFEST_FACE_ORDER;
1733 19 ▶ if (defined $section->{faces}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"faces"}) 2 17 19
1734 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
1735 2 my %want;
1736 2 for my $face (@{$section->{faces}}) {
1737 croak "manifest.faces: unknown face '" . ($face // '') . "' (known: @MANIFEST_FACE_ORDER)"
1738 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
1739 1 $want{$face} = 1;
1740 }
1741 1 @faces = grep { $want{$_} } @MANIFEST_FACE_ORDER;
1742 1 ▶ croak 'manifest.faces must name at least one face' unless @faces;
Branch: 1 branch
BranchTrueFalseTotal
unless @faces 0 1 1
1743 }
1744 18 my %spec = map { $_ => $MANIFEST_FACES{$_}->() } @MANIFEST_FACE_ORDER;
1745  
1746 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
1747 croak 'manifest.capabilities must map model names to capability hashes'
1748 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
1749  
1750 18 $enabled = 1;
1751  
1752 # Core's manifest (Langertha::Manifest, ADR 0029) is newer than the released Langertha this
1753 # dist requires. Without it the route answers 404; the config is still loaded.
1754 18 ▶ unless (eval { require Langertha::Manifest::Builder; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { require Langertha::Manifest::Builder; 1 } }) 0 18 18
1755 0 ▶ warn "skeid: manifest is enabled, but this Langertha has no Langertha::Manifest; "
Branch: 1 branch
BranchTrueFalseTotal
unless $manifest_unavailable_warned++ 0 0 0
1756 . "/.well-known/langertha.json answers 404\n"
1757 unless $manifest_unavailable_warned++;
1758 0 return $commit->();
1759 }
1760  
1761 # A claim no face of Skeid carries could never be published; saying so beats dropping it.
1762 18 my %allowed = map { $_ => 1 } Langertha::Manifest::Builder->model_capabilities;
1763 18 my %carried = map { $_ => 1 } map { @{$spec{$_}{capabilities}} } @MANIFEST_FACE_ORDER;
1764 18 for my $model (sort keys %$declared) {
1765 5 for my $flag (sort keys %{$declared->{$model}}) {
1766 croak "manifest.capabilities.$model: '$flag' is not a model capability a manifest may "
1767 . 'claim (see Langertha::Manifest::Builder->model_capabilities)'
1768 16 ▶ unless $allowed{$flag};
Branch: 1 branch
BranchTrueFalseTotal
unless $allowed{$flag} 1 15 16
1769 croak "manifest.capabilities.$model: '$flag' is not carried by any face Skeid serves"
1770 15 ▶ unless $carried{$flag};
Branch: 1 branch
BranchTrueFalseTotal
unless $carried{$flag} 1 14 15
1771 }
1772 }
1773  
1774 16 for my $id (sort keys %grants) {
1775 27 my $grant = $grants{$id};
1776 27 for my $model (@{$grant->{models}}) {
1777 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
1778 . 'does not let it reach'
1779 unless $self->_manifest_model_reachable($model, $id);
1780 }
1781 23 my $json = eval {
1782 23 my $builder = Langertha::Manifest::Builder->new(
1783 provider_id => $provider_id,
1784 issuer => $issuer,
1785 );
1786 23 $builder->add_auth(id => 'api', type => 'api_key');
1787 23 for my $face (@faces) {
1788 63 my $face_spec = $spec{$face};
1789 63 my %face_carries = map { $_ => 1 } @{$face_spec->{capabilities}};
1790 $builder->add_endpoint(
1791 id => $face,
1792 dialect => $face_spec->{dialect},
1793 base_url => $public_url . $face_spec->{path},
1794 63 auth_ref => 'api',
1795 );
1796 62 for my $model (@{$grant->{models}}) {
1797 # Declared claims over the chat + streaming default, then cut to what this face's
1798 # translator carries: a claim holds "at that endpoint" (core ADR 0029) or not at all.
1799 124 my %caps = (chat => 1, streaming => 1);
1800 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
1801 124 for my $flag (keys %$claims) {
1802 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
1803 }
1804 124 delete $caps{$_} for grep { !$face_carries{$_} } keys %caps;
1805 124 $builder->add_model(id => $model, endpoint_ref => $face, capabilities => \%caps);
1806 }
1807 }
1808 22 $builder->manifest->to_json;
1809 };
1810 23 ▶ unless (defined $json) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $json) 1 22 23
1811 1 (my $err = $@) =~ s/\s+at \S+ line \d+\.?\s*\z//s;
1812 1 croak "key '$grant->{label}': manifest does not validate: $err";
1813 }
1814 22 $manifests{$id} = $json;
1815 }
1816  
1817 11 $available = 1;
1818 11 return $commit->();
1819 }
1820  
1821 # Whether the key could be routed to the model at all: its policy grants the name, and some
1822 # node a permitted tier selects -- deny_tags applied, health ignored (a manifest is a claim,
1823 # not a probe) -- serves it. A raw node model behind a denied tag is as unreachable as an alias
1824 # the policy leaves out (ADR 0008), so it is not published either.
1825 52 ▶sub _manifest_model_reachable {
Subroutine _manifest_model_reachable: called CC=7 SCAR=19.7
1826 52 my ($self, $model, $api_key_id) = @_;
1827 52 my $plan = $self->route_plan(model => $model, api_key_id => $api_key_id);
1828 52 ▶ return 0 unless $plan->{permitted};
Branch: 1 branch
BranchTrueFalseTotal
unless $plan->{"permitted"} 2 50 52
1829 50 for my $tier (@{$plan->{tiers}}) {
1830 50 for my $node (@{$self->select_nodes(tags => $tier->{tags}, deny_tags => $tier->{deny_tags}, kind => '')}) {
1831 62 my $served = $node->{model};
1832 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
1833 }
1834 }
1835 2 return 0;
1836 }
1837  
1838  
1839 17 ▶sub manifest_for_key {
Subroutine manifest_for_key: called CC=4 SCAR=14.6
Pod documented
1840 17 my ($self, $api_key_id) = @_;
1841 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
1842 17 my $id = $self->_configured_key_id($self->key_manifests, $api_key_id);
1843 17 ▶ return defined($id) ? $self->key_manifests->{$id} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $id ? : 14 3 17
1844 }
1845  
1846  
1847 15 ▶sub configure_usage_store {
Subroutine configure_usage_store: called CC=1 SCAR=0.0
Pod documented
1848 15 my ($self, $cfg) = @_;
1849 15 return $self->_configure_usage_store($cfg);
1850 }
1851  
1852  
1853 73 ▶sub _configure_usage_store {
Subroutine _configure_usage_store: called CC=44 SCAR=39.3
1854 73 my ($self, $cfg) = @_;
1855 73 ▶ my $normalized = Langertha::Skeid::UsageStore->normalize_config(
Branch: 1 branch
BranchTrueFalseTotal
$self->has_usage_db_path ? : 73 0 73
1856 $cfg,
1857 default_sqlite_path => ($self->has_usage_db_path ? $self->usage_db_path : undef),
1858 );
1859  
1860 73 ▶ my $old = $self->usage_store || {};
Condition50%1/2
$self->usage_store || {}
l!l
730
MC/DC0%0/1
$self->usage_store || {}
$self->usage_store
Truth table50%1/2
A
A= $self->usage_store
Aresult
11
00
1861 my $same = ref($old) eq 'HASH'
1862 && (($old->{backend} // '') eq ($normalized->{backend} // ''))
1863 && (($old->{dsn} // '') eq ($normalized->{dsn} // ''))
1864 && (($old->{path} // '') eq ($normalized->{path} // ''))
1865 && (($old->{mode} // '') eq ($normalized->{mode} // ''))
1866 && (($old->{user} // '') eq ($normalized->{user} // ''))
1867 && (($old->{password} // '') eq ($normalized->{password} // ''))
1868 && (($old->{schema_file} // '') eq ($normalized->{schema_file} // ''))
1869 && ((($old->{auto_migrate} // 1) ? 1 : 0) == (($normalized->{auto_migrate} // 1) ? 1 : 0))
1870 && (($old->{flush_interval_ms} // 0) == ($normalized->{flush_interval_ms} // 0))
1871 73 ▶ && (($old->{spool_dir} // '') eq ($normalized->{spool_dir} // ''));
Branch: 2 branches
BranchTrueFalseTotal
$old->{'auto_migrate'} // 1 ? : 24 0 24
$normalized->{'auto_migrate'} // 1 ? : 24 0 24
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
51121
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
49222
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
49024
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
49024
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
49024
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
49024
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
43624
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
40330
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "")
!ll&&!rl&&r
182233
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "")
!ll&&!rl&&r
01855
$old->{"backend"} // ""
l!l
5518
$normalized->{"backend"} // ""
l!l
730
$old->{"dsn"} // ""
l!l
649
$normalized->{"dsn"} // ""
l!l
2728
$old->{"path"} // ""
l!l
321
$normalized->{"path"} // ""
l!l
330
$old->{"mode"} // ""
l!l
1911
$normalized->{"mode"} // ""
l!l
255
$old->{"user"} // ""
l!l
519
$normalized->{"user"} // ""
l!l
519
$old->{"password"} // ""
l!l
519
$normalized->{"password"} // ""
l!l
519
$old->{"schema_file"} // ""
l!l
519
$normalized->{"schema_file"} // ""
l!l
519
$old->{"auto_migrate"} // 1
l!l
519
$normalized->{"auto_migrate"} // 1
l!l
519
$old->{"flush_interval_ms"} // 0
l!l
519
$normalized->{"flush_interval_ms"} // 0
l!l
519
$old->{"spool_dir"} // ""
l!l
319
$normalized->{"spool_dir"} // ""
l!l
319
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
1872  
1873 # Rebuild when the config changed, and also when there simply is no store object yet:
1874 # BUILD hands us the caller's raw config as $old, which can compare equal to its own
1875 # normalized form and would otherwise leave the store unbuilt.
1876 73 ▶ my $changed = $same ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$same ? : 21 52 73
1877 73 ▶ if ($changed || !$self->_usage_store_obj) {
Branch: 1 branch
BranchTrueFalseTotal
if ($changed or not $self->_usage_store_obj) 69 4 73
Condition100%3/3
$changed or not $self->_usage_store_obj
l!l&&r!l&&!r
52174
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
1878 # Prepare the new store before letting go of the old one: a store that fails to come up
1879 # fails the reload with the old store still connected (reload_config is all or nothing).
1880 69 my $store = Langertha::Skeid::UsageStore->for_config($normalized);
1881 69 ▶ $store->prepare if $store;
Branch: 1 branch
BranchTrueFalseTotal
if $store 69 0 69
1882 69 ▶ if ($store && $store->can('on_lost')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($store and $store->can("on_lost")) 31 38 69
Condition66%2/3
$store and $store->can("on_lost")
!ll&&!rl&&r
03831
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
1883 31 weaken(my $weak = $self);
1884 31 ▶ $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
1885 }
1886 # The old store flushes what it still holds on the way out: those events were recorded
1887 # while it was the configured destination.
1888 69 $self->_disconnect_usage_store;
1889 69 $self->usage_store($normalized);
1890 69 $self->_usage_store_obj($store);
1891 }
1892  
1893 73 ▶ if ($normalized->{backend} eq 'sqlite') {
Branch: 2 branches
BranchTrueFalseTotal
if ($normalized->{'backend'} eq 'sqlite') { } 33 40 73
elsif ($normalized->{'backend'} ne 'jsonlog') { } 0 40 40
1894 33 $self->usage_db_path($normalized->{path});
1895 } elsif ($normalized->{backend} ne 'jsonlog') {
1896 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
1897 }
1898  
1899 73 return $self->usage_store;
1900 }
1901 0 ▶sub _set_usage_db_path {
Subroutine _set_usage_db_path: not called CC=1 SCAR=6.9
1902 0 my ($self, $path) = @_;
1903 0 return $self->_configure_usage_store({
1904 backend => 'sqlite',
1905 sqlite_path => $path,
1906 });
1907 }
1908  
1909  
1910 31167 ▶sub _num {
Subroutine _num: called CC=2 SCAR=6.9
1911 31167 my ($v) = @_;
1912 31167 ▶ return 0 unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 18067 13100 31167
1913 13100 return 0 + $v;
1914 }
1915  
1916 103 ▶sub _iso8601_now {
Subroutine _iso8601_now: called CC=1 SCAR=0.0
1917 103 return strftime('%Y-%m-%dT%H:%M:%SZ', gmtime());
1918 }
1919  
1920 1336 ▶sub _discover_engine_ids {
Subroutine _discover_engine_ids: called CC=7 SCAR=21.8
1921 1336 my %ids = %FALLBACK_ENGINE_IDS;
1922 1336 ▶ if (Langertha->can('available_engine_ids')) {
Branch: 1 branch
BranchTrueFalseTotal
if ("Langertha"->can("available_engine_ids")) 1336 0 1336
1923 1336 my $found = eval { Langertha->available_engine_ids };
1924 1336 ▶ if (!$@ && ref($found) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $@ and ref $found eq "ARRAY") 1336 0 1336
Condition33%1/3
not $@ and ref $found eq "ARRAY"
!ll&&!rl&&r
001336
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
1925 1336 for my $id (@$found) {
1926 53440 ▶ next unless defined $id && length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 0 53440 53440
Condition33%1/3
defined $id and length $id
!ll&&!rl&&r
0053440
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
1927 53440 $ids{lc $id} = 1;
1928 }
1929 }
1930 }
1931  
1932 1336 return \%ids;
1933 }
1934  
1935  
1936 0 ▶sub supported_engine_ids {
Subroutine supported_engine_ids: not called CC=1 SCAR=6.9
Pod documented
1937 0 my ($self) = @_;
1938 0 my $ids = _discover_engine_ids();
1939 0 return [ sort keys %$ids ];
1940 }
1941  
1942  
1943 13253 ▶sub normalize_engine_id {
Subroutine normalize_engine_id: called CC=4 SCAR=13.9
Pod documented
1944 13253 my ($self, $value) = @_;
1945 13253 ▶ return '' unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 13253 13253
1946  
1947 13253 my $raw = "$value";
1948 13253 $raw =~ s/^\s+//;
1949 13253 $raw =~ s/\s+$//;
1950 13253 ▶ return '' unless length $raw;
Branch: 1 branch
BranchTrueFalseTotal
unless length $raw 11917 1336 13253
1951  
1952 1336 my $id = lc($raw);
1953 1336 $id =~ s/\Alangertha::engine:://;
1954 1336 $id =~ s/\Alangerthax::engine:://;
1955  
1956 1336 my $ids = _discover_engine_ids();
1957 1336 ▶ return $id if $ids->{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $ids->{$id} 1334 2 1336
1958  
1959 2 my $known = join(', ', sort keys %$ids);
1960 2 croak "unknown engine '$raw' (expected one of: $known)";
1961 }
1962  
1963  
1964 1130 ▶sub record_usage {
Subroutine record_usage: called CC=43 SCAR=38.1
Pod documented
1965 1130 my ($self, %args) = @_;
1966  
1967 # Disabled fast path: with no sink at all, the event has nowhere to go, so
1968 # skip building it. record_usage runs once per forwarded request, and a
1969 # deployment that meters nothing should not pay for a normalized event it is
1970 # only going to throw away in _store_usage_event. (karr #15)
1971 1130 ▶ return { ok => 0, enabled => 0, error => 'usage_store not configured' }
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_has_usage_sink 27 1103 1130
1972 unless $self->_has_usage_sink;
1973  
1974 1103 ▶ my $metrics = ref($args{metrics}) eq 'HASH' ? $args{metrics} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $args{'metrics'} eq 'HASH' ? : 1072 31 1103
1975 1103 ▶ my $usage = ref($metrics->{usage}) eq 'HASH' ? $metrics->{usage} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $metrics->{'usage'} eq 'HASH' ? : 1071 32 1103
1976 my $tool_calls = ref($metrics->{tool_names}) eq 'ARRAY'
1977 641 ? scalar(@{$metrics->{tool_names}})
1978 1103 ▶ : _num($metrics->{tool_calls});
Branch: 1 branch
BranchTrueFalseTotal
ref $metrics->{'tool_names'} eq 'ARRAY' ? : 641 462 1103
1979 1103 ▶ 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
71584448
_num($usage->{"input"}) or _num($usage->{"prompt_tokens"})
l!l&&r!l&&!r
6741032
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
1980 1103 ▶ 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
65483555
_num($usage->{"output"}) or _num($usage->{"completion_tokens"})
l!l&&r!l&&!r
6141038
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
1981 1103 ▶ 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
6514448
_num($usage->{"total"}) or _num($metrics->{"total_tokens"})
l!l&&r!l&&!r
67584452
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
1982 # Prompt-cache read count (k27). Read the same way as the token counts above: the normalized
1983 # name first, then the OpenAI wire spelling (nested under prompt_tokens_details on a real
1984 # OpenAI usage payload), then a flat cached_tokens some compatible servers use, then the
1985 # flattened metrics fallback. Pricing it is metrics.normalize's job (skeid #28): the cost
1986 # fields below arrive already priced.
1987 my $cached_tokens = _num($usage->{cached})
1988 || _num($usage->{cached_tokens})
1989 || _num(ref($usage->{prompt_tokens_details}) eq 'HASH' ? $usage->{prompt_tokens_details}{cached_tokens} : undef)
1990 1103 ▶ || _num($metrics->{cached_tokens});
Branch: 1 branch
BranchTrueFalseTotal
ref $usage->{'prompt_tokens_details'} eq 'HASH' ? : 4 996 1000
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
1070996
_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
1034996
_num($usage->{"cached"}) or _num($usage->{"cached_tokens"})
l!l&&r!l&&!r
10301000
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
1991 # Prompt-cache write count (skeid #41), the count cost_cache_write_usd was priced from: the
1992 # normalized name, then the flat metrics value metrics.normalize or the proxy put there.
1993 my $cache_write_tokens = _num($usage->{cache_write})
1994 || _num($usage->{cache_write_tokens})
1995 1103 ▶ || _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
0961007
_num($usage->{"cache_write"}) or _num($usage->{"cache_write_tokens"})
l!l&&r!l&&!r
001103
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
1996 1103 ▶ 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
0137966
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
1997 1103 ▶ 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
0121982
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
1998 1103 ▶ 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
1137965
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
1999 # Prompt-cache amounts (skeid #28), already part of cost_total. 0 when the rule had no cache
2000 # rate or the installed Langertha cannot price them -- the cached tokens are then in cost_input.
2001 1103 ▶ 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
0551048
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
2002 1103 ▶ 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
0541049
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
2003  
2004 my %event = (
2005 created_at => ($args{created_at} // _iso8601_now()),
2006 request_id => ($args{request_id} // ''),
2007 api_format => ($args{api_format} // ''),
2008 endpoint => ($args{endpoint} // ''),
2009 api_key_id => ($args{api_key_id} // ''),
2010 provider => ($args{provider} // ''),
2011 engine => ($args{engine} // ''),
2012 model => ($args{model} // ''),
2013 requested_model => ($args{requested_model} // $args{model} // ''),
2014 node_id => ($args{node_id} // ''),
2015 route_url => ($args{route_url} // ''),
2016 status_code => (_num($args{status_code}) || 0),
2017 ok => ($args{ok} ? 1 : 0),
2018 duration_ms => (_num($args{duration_ms}) || 0),
2019 input_tokens => $input_tokens,
2020 output_tokens => $output_tokens,
2021 total_tokens => $total_tokens,
2022 cached_tokens => $cached_tokens,
2023 cache_write_tokens => $cache_write_tokens,
2024 tool_calls => _num($tool_calls),
2025 cost_input_usd => $cost_input,
2026 cost_output_usd => $cost_output,
2027 cost_total_usd => $cost_total,
2028 cost_cache_read_usd => $cost_cache_read,
2029 cost_cache_write_usd => $cost_cache_write,
2030 error_type => ($args{error_type} // ''),
2031 1103 ▶ error_message => ($args{error_message} // ''),
Branch: 1 branch
BranchTrueFalseTotal
$args{'ok'} ? : 868 235 1103
Condition88%30/34
$args{"created_at"} // _iso8601_now()
l!l&&r!l&&!r
10001030
$args{"request_id"} // ""
l!l
100895
$args{"api_format"} // ""
l!l
107627
$args{"endpoint"} // ""
l!l
104360
$args{"api_key_id"} // ""
l!l
108914
$args{"provider"} // ""
l!l
1001102
$args{"engine"} // ""
l!l
1001102
$args{"model"} // ""
l!l
11030
($args{"requested_model"} // $args{"model"}) // ""
l!l
11030
$args{"requested_model"} // $args{"model"}
l!l&&r!l&&!r
1006970
$args{"node_id"} // ""
l!l
100796
$args{"route_url"} // ""
l!l
1000103
_num($args{'status_code'}) || 0
l!l
109211
_num($args{'duration_ms'}) || 0
l!l
103172
$args{"error_type"} // ""
l!l
1000103
$args{"error_message"} // ""
l!l
1000103
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
2032 );
2033 # UTF-8 bytes of the content a streamed request relayed (skeid #36). Optional and additive: a
2034 # non-streamed event has no such key, which a store records as "not measured". An observation
2035 # beside the token counts -- never used to estimate or replace them.
2036 1103 ▶ $event{content_bytes} = _num($args{content_bytes}) if defined $args{content_bytes};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"content_bytes"} 235 868 1103
2037 # Seconds of audio an audio route's node reported (skeid k91, ADR 0021). Optional and additive
2038 # like content_bytes: absent means the node did not say, which is not a measured zero. Recorded
2039 # as reported, never priced here.
2040 1103 ▶ $event{audio_seconds} = _num($args{audio_seconds}) if defined $args{audio_seconds};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"audio_seconds"} 40 1063 1103
2041 # How many documents a rerank request carried (skeid k92, ADR 0021), counted off the request
2042 # the node answered. Optional and additive like the two above; recorded, never priced.
2043 1103 ▶ $event{documents} = _num($args{documents}) if defined $args{documents};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"documents"} 108 995 1103
2044 # The pages a documents request converted (skeid k94, ADR 0028), read off json_content of the
2045 # answer when it carries one. Optional like audio_seconds: absent is not measured, never 0.
2046 1103 ▶ $event{pages} = _num($args{pages}) if defined $args{pages};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"pages"} 39 1064 1103
2047  
2048 1103 return $self->_store_usage_event(\%event);
2049 }
2050  
2051 1099 ▶sub _store_usage_event {
Subroutine _store_usage_event: called CC=3 SCAR=11.0
2052 1099 my ($self, $event) = @_;
2053 1099 ▶ return $self->store_usage_event->($self, $event) if $self->has_store_usage_event;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_store_usage_event 993 106 1099
2054 106 my $store = $self->_usage_store_obj;
2055 106 ▶ return { ok => 0, enabled => 0, error => 'usage_store not configured' } unless $store;
Branch: 1 branch
BranchTrueFalseTotal
unless $store 0 106 106
2056 106 return $store->store($event);
2057 }
2058  
2059 # A queued event the store could not write (skeid k78): through on_usage_lost when the
2060 # embedding application -- the proxy -- set it, else a warning. Never the DSN, never a key.
2061 1 ▶sub _usage_lost {
Subroutine _usage_lost: called CC=9 SCAR=41.1
2062 1 my ($self, $event, $err) = @_;
2063 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
2064 0 my $cfg = $self->usage_store;
2065 warn 'skeid: usage event lost: request_id=' . ($event->{request_id} // '')
2066 . ' store=' . ((ref($cfg) eq 'HASH' && $cfg->{backend}) || 'custom')
2067 . ' api_key_id=' . ($event->{api_key_id} // '')
2068 . ' model=' . ($event->{model} // '')
2069 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
2070 . ': ' . ($err // 'unknown error') . "\n";
2071 0 return;
2072 }
2073  
2074  
2075 2 ▶sub flush_usage {
Subroutine flush_usage: called CC=3 SCAR=12.0
Pod documented
2076 2 my ($self) = @_;
2077 2 my $store = $self->_usage_store_obj;
2078 2 ▶ return { ok => 1, written => 0 } unless $store && $store->can('flush');
Branch: 1 branch
BranchTrueFalseTotal
unless $store and $store->can("flush") 0 2 2
Condition33%1/3
$store and $store->can("flush")
!ll&&!rl&&r
002
MC/DC0%0/2
$store and $store->can("flush")
$store $store->can("flush")
Truth table33%1/3
A and B
A= $storeB= $store->can("flush")
ABresult
0X0
100
111
2079 2 return $store->flush;
2080 }
2081  
2082 # True when a usage event has somewhere to go: a store_usage_event callback, a
2083 # configured usage store object, or a subclass that overrides _store_usage_event
2084 # (documented in README, exercised by t/14) -- the last is why this cannot be a
2085 # plain attribute check. record_usage consults this before building an event.
2086 1130 ▶sub _has_usage_sink {
Subroutine _has_usage_sink: called CC=5 SCAR=16.1
2087 1130 my ($self) = @_;
2088 1130 ▶ return 1 if $self->has_store_usage_event;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_store_usage_event 993 137 1130
2089 137 ▶ return 1 if $self->_usage_store_obj;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_usage_store_obj 106 31 137
2090 31 my $impl = $self->can('_store_usage_event');
2091 31 ▶ return 1 if $impl && $impl != \&_store_usage_event;
Branch: 1 branch
BranchTrueFalseTotal
if $impl and $impl != \&Langertha::Skeid::_store_usage_event 4 27 31
Condition66%2/3
$impl and $impl != \&Langertha::Skeid::_store_usage_event
!ll&&!rl&&r
0274
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
2092 27 return 0;
2093 }
2094  
2095  
2096 44 ▶sub usage_report {
Subroutine usage_report: called CC=9 SCAR=22.2
Pod documented
2097 44 my ($self, %args) = @_;
2098  
2099 44 my $limit = _num($args{limit});
2100 44 ▶ $limit = 20 if $limit < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $limit < 1 29 15 44
2101 44 ▶ $limit = 500 if $limit > 500;
Branch: 1 branch
BranchTrueFalseTotal
if $limit > 500 0 44 44
2102  
2103 44 my %filters;
2104 44 ▶ $filters{since} = $args{since} if defined $args{since} && length $args{since};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"since"} and length $args{"since"} 1 43 44
Condition66%2/3
defined $args{"since"} and length $args{"since"}
!ll&&!rl&&r
4301
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
2105 44 ▶ $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"} 1 43 44
Condition66%2/3
defined $args{"api_key_id"} and length $args{"api_key_id"}
!ll&&!rl&&r
4301
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
2106 44 ▶ $filters{model} = $args{model} if defined $args{model} && length $args{model};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"model"} and length $args{"model"} 2 42 44
Condition66%2/3
defined $args{"model"} and length $args{"model"}
!ll&&!rl&&r
4202
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
2107 44 $filters{limit} = $limit;
2108  
2109 44 return $self->_query_usage_report(\%filters);
2110 }
2111  
2112 42 ▶sub _query_usage_report {
Subroutine _query_usage_report: called CC=3 SCAR=11.0
2113 42 my ($self, $filters) = @_;
2114 42 ▶ return $self->query_usage_report->($self, $filters) if $self->has_query_usage_report;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_query_usage_report 1 41 42
2115 41 my $store = $self->_usage_store_obj;
2116 41 ▶ return { ok => 0, enabled => 0, error => 'usage_store not configured' } unless $store;
Branch: 1 branch
BranchTrueFalseTotal
unless $store 1 40 41
2117 40 return $store->report($filters);
2118 }
2119 666 ▶sub _usage_object {
Subroutine _usage_object: called CC=4 SCAR=14.6
2120 666 my ($self, %args) = @_;
2121 666 ▶ return Langertha::Usage->from_hash($args{usage}) if ref($args{usage}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $args{"usage"} eq "HASH" 3 663 666
2122 663 ▶ 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 663 663
Condition33%1/3
ref $args{"usage"} and $args{"usage"}->isa("Langertha::Usage")
!ll&&!rl&&r
66300
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
2123 663 return Langertha::Usage->from_response($args{response});
2124 }
2125  
2126  
2127 1 ▶sub estimate_cost {
Subroutine estimate_cost: called CC=3 SCAR=11.6
Pod documented
2128 1 my ($self, %args) = @_;
2129 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
2130 1 my $usage = $self->_usage_object(%args);
2131 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
2132 1 my $pricing = Langertha::Pricing->new( default_rule => $rule );
2133 1 return $pricing->cost_for( $usage, undef )->to_hash;
2134 }
2135  
2136  
2137 665 ▶sub normalize_metrics {
Subroutine normalize_metrics: called CC=14 SCAR=28.4
Pod documented
2138 665 my ($self, %args) = @_;
2139 665 ▶ my $model = $args{model} // '';
Condition50%1/2
$args{"model"} // ""
l!l
6650
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
2140 665 my $usage = $self->_usage_object(%args);
2141 665 ▶ my $rule = $args{pricing} || $self->pricing_for_model($model);
Condition33%1/3
$args{'pricing'} || $self->pricing_for_model($model)
l!l&&r!l&&!r
06650
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
2142 665 my $pricing = Langertha::Pricing->new( default_rule => $rule );
2143 665 my $cost = $pricing->cost_for( $usage, undef );
2144  
2145 665 my @names;
2146 665 ▶ for my $tc ( @{ $args{tool_calls} || [] } ) {
Condition50%1/2
$args{'tool_calls'} || []
l!l
6650
MC/DC0%0/1
$args{'tool_calls'} || []
$args{'tool_calls'}
Truth table50%1/2
A
A= $args{'tool_calls'}
Aresult
11
00
2147 5 ▶ next unless ref($tc) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tc eq "HASH" 0 5 5
2148 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
2149 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
2150 }
2151  
2152 my $record = Langertha::UsageRecord->new(
2153 usage => $usage,
2154 cost => $cost,
2155 provider => $args{provider},
2156 engine => $args{engine},
2157 model => $model,
2158 route => $args{route},
2159 duration_ms => $args{duration_ms},
2160 started_at => $args{started_at},
2161 finished_at => $args{finished_at},
2162 tool_calls => scalar(@names),
2163 tool_names => \@names,
2164 pricing_version => $args{pricing_version},
2165 665 );
2166 665 my $normalized = $record->to_hash;
2167 # The cache read count as the Usage read it, from whichever wire spelling the upstream used
2168 # (skeid #28) -- so the event's cached_tokens is the count its cache cost was priced from.
2169 # Langertha 0.503's Usage has no such count; there the caller reads it off the raw payload.
2170 665 ▶ 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 563 665
Condition66%2/3
$usage->can("cached_tokens") and defined(my $cached = $usage->cached_tokens)
!ll&&!rl&&r
0563102
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
2171 102 $normalized->{cached_tokens} = $cached;
2172 }
2173 # Likewise the cache write count, the one cost_cache_write_usd was priced from (skeid #41).
2174 665 ▶ 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 569 665
Condition66%2/3
$usage->can("cache_write_tokens") and defined(my $written = $usage->cache_write_tokens)
!ll&&!rl&&r
056996
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
2175 96 $normalized->{cache_write_tokens} = $written;
2176 }
2177 665 return $normalized;
2178 }
2179  
2180 5139 ▶sub _route_key {
Subroutine _route_key: called CC=8 SCAR=20.8
2181 5139 my ($self, %args) = @_;
2182 5139 ▶ my $model = $args{model} // '';
Condition50%1/2
$args{"model"} // ""
l!l
51390
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
2183 5139 ▶ my $engine = $self->normalize_engine_id($args{engine} // '');
Condition100%2/2
$args{"engine"} // ""
l!l
38101329
MC/DC100%1/1
$args{"engine"} // ""
$args{"engine"}
Truth table100%2/2
A
A= $args{"engine"}
Aresult
11
00
2184 5139 my $tags = join(',', @{$self->normalize_tags($args{tags})});
2185 5139 my $deny = join(',', @{$self->normalize_tags($args{deny_tags})});
2186 # Tags belong in the key: two selections over the same model address different node sets, and
2187 # a shared round-robin cursor across different-sized sets picks the wrong node. Denied tags
2188 # too -- a key that may not use cloud addresses a smaller set than one that may.
2189 # A kind other than chat addresses a different set of nodes under the same name (a chat model
2190 # may be called `documents` too), so it is part of the key like the tags are.
2191 5139 my $kind = $self->_selector_kind(%args);
2192 5139 ▶ my @kind = length($kind) ? ("=$kind") : ();
Branch: 1 branch
BranchTrueFalseTotal
length $kind ? : 196 4943 5139
2193 5139 ▶ return join('|', $model, $engine, $tags, ($deny ? "-$deny" : ()), @kind)
Branch: 2 branches
BranchTrueFalseTotal
if length $tags or length $deny or @kind 749 4390 5139
$deny ? : 300 449 749
Condition100%6/6
length $tags or length $deny or @kind
l!l&&r!l&&!r
5671824390
length $tags or length $deny
l!l&&r!l&&!r
2762914572
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
2194 if length($tags) || length($deny) || @kind;
2195 4390 return join('|', $model, $engine);
2196 }
2197  
2198 # The kind of node a selection is over: '' for chat, which is what every selection was before the
2199 # option, else a kind of Protocol::Documents.
2200 7773 ▶sub _selector_kind {
Subroutine _selector_kind: called CC=4 SCAR=13.9
2201 7773 my ($self, %args) = @_;
2202 7773 my $kind = $args{kind};
2203 7773 ▶ return '' unless defined($kind) && length($kind) && $kind ne 'chat';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $kind and length $kind and $kind ne "chat" 7493 280 7773
Condition83%5/6
defined $kind and length $kind and $kind ne "chat"
!ll&&!rl&&r
74930280
defined $kind and length $kind
!ll&&!rl&&r
744350280
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
2204 280 return $kind;
2205 }
2206  
2207 4231 ▶sub _node_can_take {
Subroutine _node_can_take: called CC=8 SCAR=21.7
2208 4231 my ($self, $node) = @_;
2209 4231 ▶ return 0 unless ref($node) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $node eq "HASH" 0 4231 4231
2210 4231 ▶ return 0 unless ($node->{healthy} // 0);
Branch: 1 branch
BranchTrueFalseTotal
unless $node->{"healthy"} // 0 0 4231 4231
Condition50%1/2
$node->{"healthy"} // 0
l!l
42310
MC/DC0%0/1
$node->{"healthy"} // 0
$node->{"healthy"}
Truth table50%1/2
A
A= $node->{"healthy"}
Aresult
11
00
2211 4231 ▶ my $id = $node->{id} // '';
Condition50%1/2
$node->{"id"} // ""
l!l
42310
MC/DC0%0/1
$node->{"id"} // ""
$node->{"id"}
Truth table50%1/2
A
A= $node->{"id"}
Aresult
11
00
2212 4231 ▶ return 0 unless length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless length $id 0 4231 4231
2213  
2214 # Both have to agree, and they are not symmetric: max_conns is this process's own guardrail
2215 # and always applies, while a probe may only narrow what it allows. A probe that could widen
2216 # it would turn a stale or broken reading into an overload -- and for a rented node,
2217 # max_conns is a spend limit, not a capacity estimate (ADR 0009).
2218 4231 ▶ return 0 unless $self->_inflight_allows($node);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_inflight_allows($node) 521 3710 4231
2219 3710 ▶ return 0 unless $self->_capacity_allows($id);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_capacity_allows($id) 135 3575 3710
2220 3575 return 1;
2221 }
2222  
2223 4231 ▶sub _inflight_allows {
Subroutine _inflight_allows: called CC=5 SCAR=16.1
2224 4231 my ($self, $node) = @_;
2225 4231 my $max = $self->worker_max_conns($node);
2226 4231 ▶ return 1 if $max <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $max <= 0 632 3599 4231
2227 3599 ▶ return (0 + ($self->_inflight->{$node->{id} // ''} // 0)) < $max ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
0 + ($self->_inflight->{$node->{'id'} // ''} // 0) < $max ? : 3078 521 3599
Condition75%3/4
$self->_inflight->{$node->{"id"} // ""} // 0
l!l
21351464
$node->{"id"} // ""
l!l
35990
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
2228 }
2229  
2230  
2231 4323 ▶sub worker_max_conns {
Subroutine worker_max_conns: called CC=6 SCAR=17.9
Pod documented
2232 4323 my ($self, $node) = @_;
2233 4323 ▶ my $max = 0 + ((ref($node) eq 'HASH' ? $node->{max_conns} : $node) // 0);
Branch: 1 branch
BranchTrueFalseTotal
ref $node eq 'HASH' ? : 4323 0 4323
Condition100%2/2
(ref $node eq "HASH" ? $node->{"max_conns"} : $node) // 0
l!l
43221
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
2234 4323 ▶ return 0 if $max <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $max <= 0 634 3689 4323
2235  
2236 3689 my $divisor = $self->_admission_divisor;
2237 3689 ▶ return $max if $divisor <= 1;
Branch: 1 branch
BranchTrueFalseTotal
if $divisor <= 1 3653 36 3689
2238  
2239 36 my $share = int($max / $divisor);
2240 36 ▶ return $share > 0 ? $share : 1;
Branch: 1 branch
BranchTrueFalseTotal
$share > 0 ? : 34 2 36
2241 }
2242  
2243 # How many processes across the whole deployment share one node's max_conns: the prefork workers
2244 # of this process (worker_count) times the separate Skeid frontends in front of the node
2245 # (frontend_count). max_conns is partitioned across frontends first and then across workers, but
2246 # integer division composes -- floor(floor(max/F)/N) == floor(max/(F*N)) -- so the product is
2247 # the only number admission needs (ADR 0012).
2248 3689 ▶sub _admission_divisor {
Subroutine _admission_divisor: called CC=5 SCAR=17.2
2249 3689 my ($self) = @_;
2250 3689 ▶ my $workers = 0 + ($self->worker_count // 1);
Condition50%1/2
$self->worker_count // 1
l!l
36890
MC/DC0%0/1
$self->worker_count // 1
$self->worker_count
Truth table50%1/2
A
A= $self->worker_count
Aresult
11
00
2251 3689 ▶ my $frontends = 0 + ($self->frontend_count // 1);
Condition50%1/2
$self->frontend_count // 1
l!l
36890
MC/DC0%0/1
$self->frontend_count // 1
$self->frontend_count
Truth table50%1/2
A
A= $self->frontend_count
Aresult
11
00
2252 3689 ▶ $workers = 1 if $workers < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $workers < 1 0 3689 3689
2253 3689 ▶ $frontends = 1 if $frontends < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $frontends < 1 0 3689 3689
2254 3689 return $workers * $frontends;
2255 }
2256  
2257  
2258 6 ▶sub worker_share_warnings {
Subroutine worker_share_warnings: called CC=14 SCAR=26.8
Pod documented
2259 6 my ($self) = @_;
2260 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
2261 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
2262 6 ▶ $workers = 1 if $workers < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $workers < 1 0 6 6
2263 6 ▶ $frontends = 1 if $frontends < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $frontends < 1 0 6 6
2264 6 my $divisor = $workers * $frontends;
2265 6 ▶ return [] if $divisor <= 1;
Branch: 1 branch
BranchTrueFalseTotal
if $divisor <= 1 1 5 6
2266  
2267 # Name the axes that are actually in play, and the matching fix: the operator can only shed
2268 # what they configured. With both dividing, "worker" alone would misname where the surplus
2269 # comes from.
2270 5 my ($split, $fix);
2271 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
2272 1 $split = sprintf('%d frontends x %d workers = %d processes', $frontends, $workers, $divisor);
2273 1 $fix = 'fewer frontends or workers, or raise max_conns';
2274 } elsif ($frontends > 1) {
2275 2 $split = sprintf('%d frontends', $frontends);
2276 2 $fix = 'fewer frontends or raise max_conns';
2277 } else {
2278 2 $split = sprintf('%d workers', $workers);
2279 2 $fix = 'fewer workers or raise max_conns';
2280 }
2281  
2282 5 my @warnings;
2283 5 for my $node (@{$self->nodes}) {
2284 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
2285 5 ▶ next if $max <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $max <= 0 0 5 5
2286 5 ▶ next if $max >= $divisor;
Branch: 1 branch
BranchTrueFalseTotal
if $max >= $divisor 2 3 5
2287 push @warnings, sprintf(
2288 "node '%s': max_conns %d cannot be split across %s; each process will admit 1, "
2289 . "so the node may see up to %d concurrent requests. Use %s.",
2290 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
2291 );
2292 }
2293 5 return \@warnings;
2294 }
2295  
2296 # What a probe says about a node, if anything current. Unknown is a valid answer and means
2297 # "inflight decides" -- which is the entire behaviour of a deployment that configures no probes.
2298 3712 ▶sub _capacity_allows {
Subroutine _capacity_allows: called CC=8 SCAR=21.3
2299 3712 my ($self, $node_id) = @_;
2300 3712 ▶ my $reading = $self->capacity_reading($node_id) or return 1;
Branch: 1 branch
BranchTrueFalseTotal
my $reading = $self->capacity_reading($node_id) or return 1 181 3531 3712
2301  
2302 # A provider that told us to come back later is not busy in the inflight sense: no request of
2303 # ours is outstanding, and admitting one would just buy another 429.
2304 181 ▶ return 0 if $reading->{retry_after} && time < $reading->{retry_after};
Branch: 1 branch
BranchTrueFalseTotal
if $reading->{"retry_after"} and time < $reading->{"retry_after"} 41 140 181
Condition66%2/3
$reading->{"retry_after"} and time < $reading->{"retry_after"}
!ll&&!rl&&r
140041
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
2305  
2306 140 ▶ my $limit = 0 + ($reading->{limit} // 0);
Condition50%1/2
$reading->{"limit"} // 0
l!l
1400
MC/DC0%0/1
$reading->{"limit"} // 0
$reading->{"limit"}
Truth table50%1/2
A
A= $reading->{"limit"}
Aresult
11
00
2307 140 ▶ return 1 if $limit <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $limit <= 0 0 140 140
2308 140 ▶ return (0 + ($reading->{used} // 0)) < $limit ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
0 + ($reading->{'used'} // 0) < $limit ? : 45 95 140
Condition50%1/2
$reading->{"used"} // 0
l!l
1400
MC/DC0%0/1
$reading->{"used"} // 0
$reading->{"used"}
Truth table50%1/2
A
A= $reading->{"used"}
Aresult
11
00
2309 }
2310  
2311 1521 ▶sub _node_has_tags {
Subroutine _node_has_tags: called CC=6 SCAR=18.0
2312 1521 my ($self, $node, $tags) = @_;
2313 1521 ▶ return 1 unless $tags && @$tags;
Branch: 1 branch
BranchTrueFalseTotal
unless $tags and @$tags 1397 124 1521
Condition66%2/3
$tags and @$tags
!ll&&!rl&&r
01397124
MC/DC50%1/2
$tags and @$tags
$tags @$tags
Truth table66%2/3
A and B
A= $tagsB= @$tags
ABresult
0X0
100
111
2314 124 ▶ my %have = map { $_ => 1 } @{$node->{tags} || []};
Condition50%1/2
$node->{'tags'} || []
l!l
1240
MC/DC0%0/1
$node->{'tags'} || []
$node->{'tags'}
Truth table50%1/2
A
A= $node->{'tags'}
Aresult
11
00
2315 124 for my $tag (@$tags) {
2316 126 ▶ return 0 unless $have{$tag};
Branch: 1 branch
BranchTrueFalseTotal
unless $have{$tag} 68 58 126
2317 }
2318 56 return 1;
2319 }
2320  
2321 # The deny side is ANY, not ALL: one forbidden tag on a node is enough to rule it out. A policy
2322 # that denies "cloud" must exclude a node tagged [cloud, groq] without having to name groq too.
2323 1522 ▶sub _node_has_any_tag {
Subroutine _node_has_any_tag: called CC=6 SCAR=18.0
2324 1522 my ($self, $node, $tags) = @_;
2325 1522 ▶ return 0 unless $tags && @$tags;
Branch: 1 branch
BranchTrueFalseTotal
unless $tags and @$tags 1470 52 1522
Condition66%2/3
$tags and @$tags
!ll&&!rl&&r
0147052
MC/DC50%1/2
$tags and @$tags
$tags @$tags
Truth table66%2/3
A and B
A= $tagsB= @$tags
ABresult
0X0
100
111
2326 52 ▶ my %have = map { $_ => 1 } @{$node->{tags} || []};
Condition50%1/2
$node->{'tags'} || []
l!l
520
MC/DC0%0/1
$node->{'tags'} || []
$node->{'tags'}
Truth table50%1/2
A
A= $node->{'tags'}
Aresult
11
00
2327 52 for my $tag (@$tags) {
2328 52 ▶ return 1 if $have{$tag};
Branch: 1 branch
BranchTrueFalseTotal
if $have{$tag} 11 41 52
2329 }
2330 41 return 0;
2331 }
2332  
2333 # The selection cache includes negative requested models, and requested models are client input.
2334 # Keep a small fixed working set rather than turning every spelling ever seen into process-lifetime
2335 # state. FIFO makes eviction deterministic; an evicted route's cursor is removed with it, so that
2336 # route restarts weighted fairness if it is requested again.
2337 113 my $ROUTE_CACHE_MAX_ENTRIES = 256;
2338  
2339 # Everything derived from the inventory -- which nodes are eligible, their round-robin order
2340 # and their weights -- is computed once per selection and reused until the inventory changes.
2341 # Only admission stays per request, because inflight is the one part that moves between two
2342 # requests to the same selection.
2343 3434 ▶sub _route_entry {
Subroutine _route_entry: called CC=31 SCAR=36.2
2344 3434 my ($self, %args) = @_;
2345 3434 my $cache = $self->_route_cache;
2346 3434 ▶ if (($cache->{generation} // -1) != $self->_inventory_generation) {
Branch: 1 branch
BranchTrueFalseTotal
if (($cache->{"generation"} // -1) != $self->_inventory_generation) 491 2943 3434
Condition50%1/2
$cache->{"generation"} // -1
l!l
34340
MC/DC0%0/1
$cache->{"generation"} // -1
$cache->{"generation"}
Truth table50%1/2
A
A= $cache->{"generation"}
Aresult
11
00
2347 491 $cache = { generation => $self->_inventory_generation, entries => {}, order => [] };
2348 491 $self->_route_cache($cache);
2349 }
2350  
2351 3434 my $key = $self->_route_key(%args);
2352 3434 my $entry = $cache->{entries}{$key};
2353 3434 ▶ return $entry if $entry;
Branch: 1 branch
BranchTrueFalseTotal
if $entry 2065 1369 3434
2354  
2355 1369 my $model = $args{model};
2356 1369 ▶ my $engine = $self->normalize_engine_id($args{engine} // '');
Condition100%2/2
$args{"engine"} // ""
l!l
525844
MC/DC100%1/1
$args{"engine"} // ""
$args{"engine"}
Truth table100%2/2
A
A= $args{"engine"}
Aresult
11
00
2357 1369 my $tags = $self->normalize_tags($args{tags});
2358 1369 my $deny = $self->normalize_tags($args{deny_tags});
2359  
2360 # Chat and documents nodes are never each other's: a documents node carries no model name
2361 # Skeid reads, so a chat selection must not take it for one that serves any model, and a
2362 # documents selection takes the nodes of its kind whatever they are called (ADR 0028).
2363 1369 my $kind = $self->_selector_kind(%args);
2364  
2365 my @nodes = grep {
2366 (($_->{kind} // '') eq $kind)
2367 && (length($kind) || !defined($model) || !length($model) || !defined($_->{model}) || !length($_->{model}) || $_->{model} eq $model)
2368 && (!defined($engine) || !length($engine) || !defined($_->{engine}) || !length($_->{engine}) || $_->{engine} eq $engine)
2369 2723 ▶ && (($_->{healthy} // 0) ? 1 : 0)
Branch: 1 branch
BranchTrueFalseTotal
$_->{'healthy'} // 0 ? : 1409 24 1433
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
135561362
($_->{"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
1314411368
($_->{"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
1290241409
($_->{"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
129001433
($_->{"kind"} // "") eq $kind and length $kind || !defined($model) || !length($model) || !defined($_->{"model"}) || !length($_->{"model"}) || $_->{"model"} eq $model
!ll&&!rl&&r
1112791433
$_->{"kind"} // ""
l!l
382685
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
8405931279
length $kind or not defined $model or not length $model or not defined $_->{"model"} or not length $_->{"model"}
l!l&&r!l&&!r
328081872
length $kind or not defined $model or not length $model or not defined $_->{"model"}
l!l&&r!l&&!r
3202680
length $kind or not defined $model or not length $model
l!l&&r!l&&!r
3202680
length $kind or not defined $model
l!l&&r!l&&!r
3202680
not defined $engine && length $engine && defined $_->{"engine"} && length $_->{"engine"} or $_->{"engine"} eq $engine
l!l&&r!l&&!r
143300
defined $engine && length $engine && defined $_->{'engine'} && length $_->{'engine'}
!ll&&!rl&&r
143300
defined $engine and length $engine and defined $_->{"engine"}
!ll&&!rl&&r
143300
defined $engine and length $engine
!ll&&!rl&&r
014330
$_->{"healthy"} // 0
l!l
14330
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
2370 && $self->_node_has_tags($_, $tags)
2371 && !$self->_node_has_any_tag($_, $deny)
2372 1369 ▶ } @{$self->nodes || []};
Condition50%1/2
$self->nodes || []
l!l
13690
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
2373  
2374 1369 ▶ @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
2375 my @weights = map {
2376 1369 ▶ my $w = 0 + ($_->{weight} // 1);
Condition100%2/2
$_->{"weight"} // 1
l!l
13611
MC/DC100%1/1
$_->{"weight"} // 1
$_->{"weight"}
Truth table100%2/2
A
A= $_->{"weight"}
Aresult
11
00
2377 1362 ▶ $w = 1 if $w < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $w < 1 0 1362 1362
2378 1362 int($w);
2379 } @nodes;
2380 1369 my $total_weight = 0;
2381 1369 $total_weight += $_ for @weights;
2382  
2383 1369 my $new_entry = {
2384 nodes => \@nodes,
2385 weights => \@weights,
2386 total_weight => $total_weight,
2387 };
2388  
2389 1369 ▶ my $order = $cache->{order} ||= [];
Condition50%1/2
$cache->{"order"} ||= []
l!l
13690
MC/DC0%0/1
$cache->{"order"} ||= []
$cache->{"order"}
Truth table50%1/2
A
A= $cache->{"order"}
Aresult
11
00
2390 1369 ▶ while (@$order >= $ROUTE_CACHE_MAX_ENTRIES) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$order >= $ROUTE_CACHE_MAX_ENTRIES) 290 1369 1659
2391 290 my $evicted = shift @$order;
2392 290 ▶ next unless exists $cache->{entries}{$evicted};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $cache->{"entries"}{$evicted} 0 290 290
2393 290 delete $cache->{entries}{$evicted};
2394 # The cursor tracks ranges stored by this entry. Keeping it would defeat the bound and would
2395 # resume at stale fairness state if this route key later re-enters the working set.
2396 290 delete $self->_rr_cursor->{$evicted};
2397 }
2398 1369 $cache->{entries}{$key} = $new_entry;
2399 1369 push @$order, $key;
2400 1369 return $new_entry;
2401 }
2402  
2403 # Returns the live node hashrefs, not copies. Callers read them and must not mutate them --
2404 # pick_node builds its own hash for the node it returns.
2405 1731 ▶sub _eligible_nodes {
Subroutine _eligible_nodes: called CC=1 SCAR=0.0
2406 1731 my ($self, %args) = @_;
2407 1731 return $self->_route_entry(%args)->{nodes};
2408 }
2409  
2410  
2411 84 ▶sub set_model_alias {
Subroutine set_model_alias: called CC=14 SCAR=27.2
Pod documented
2412 84 my ($self, $name, $spec) = @_;
2413 84 ▶ croak 'alias name required' unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 84 84
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
0084
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
2414  
2415 my $tiers = ref($spec) eq 'ARRAY' ? $spec
2416 : ref($spec) eq 'HASH' ? $spec->{tiers}
2417 84 ▶ : croak "alias '$name': must be a hashref with tiers, or an arrayref of tiers";
Branch: 2 branches
BranchTrueFalseTotal
ref $spec eq 'ARRAY' ? : 1 83 84
ref $spec eq 'HASH' ? : 82 1 83
2418 83 ▶ croak "alias '$name': tiers must be an arrayref" unless ref($tiers) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tiers eq "ARRAY" 0 83 83
2419 83 ▶ croak "alias '$name': needs at least one tier" unless @$tiers;
Branch: 1 branch
BranchTrueFalseTotal
unless @$tiers 1 82 83
2420  
2421 82 my @normalized;
2422 82 for my $tier (@$tiers) {
2423 91 ▶ croak "alias '$name': each tier must be a hashref" unless ref($tier) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tier eq "HASH" 0 91 91
2424 push @normalized, {
2425 tags => $self->normalize_tags($tier->{tags}),
2426 model => ((defined($tier->{model}) && length($tier->{model})) ? "$tier->{model}" : $name),
2427 engine => $self->normalize_engine_id($tier->{engine} // ''),
2428 91 ▶ wait_ms => (defined($tier->{wait_ms}) && $tier->{wait_ms} > 0 ? 0 + $tier->{wait_ms} : 0),
Branch: 2 branches
BranchTrueFalseTotal
defined $tier->{'model'} && length $tier->{'model'} ? : 87 4 91
defined $tier->{'wait_ms'} && $tier->{'wait_ms'} > 0 ? : 4 87 91
Condition75%6/8
defined $tier->{"model"} and length $tier->{"model"}
!ll&&!rl&&r
4087
$tier->{"engine"} // ""
l!l
091
defined $tier->{"wait_ms"} and $tier->{"wait_ms"} > 0
!ll&&!rl&&r
8344
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/DC100%2/2
defined $tier->{"wait_ms"} and $tier->{"wait_ms"} > 0
defined $tier->{"wait_ms"} $tier->{"wait_ms"} > 0
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 table100%3/3
A and B
A= defined $tier->{"wait_ms"}B= $tier->{"wait_ms"} > 0
ABresult
0X0
100
111
2429 };
2430 }
2431  
2432 82 $self->model_aliases->{$name} = { tiers => \@normalized };
2433 82 return 1;
2434 }
2435  
2436  
2437 3 ▶sub set_policy {
Subroutine set_policy: called CC=3 SCAR=12.0
Pod documented
2438 3 my ($self, $name, $spec) = @_;
2439 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
2440 3 $self->policies->{$name} = $self->resolve_policy($spec, $name);
2441 3 return 1;
2442 }
2443  
2444  
2445 207 ▶sub resolve_policy {
Subroutine resolve_policy: called CC=9 SCAR=22.3
Pod documented
2446 207 my ($self, $spec, $name) = @_;
2447 207 ▶ $spec = {} unless ref($spec) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 0 207 207
2448  
2449 207 ▶ my $allow = $spec->{models} // $spec->{aliases};
Condition66%2/3
$spec->{"models"} // $spec->{"aliases"}
l!l&&r!l&&!r
1000107
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
2450 207 my $allow_models;
2451 207 ▶ if (defined $allow) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $allow) 100 107 207
2452 100 ▶ my @list = ref($allow) eq 'ARRAY' ? @$allow : split(/[,\s]+/, "$allow");
Branch: 1 branch
BranchTrueFalseTotal
ref $allow eq 'ARRAY' ? : 99 1 100
2453 100 ▶ @list = grep { defined && length } @list;
Condition33%1/3
defined $_ && length $_
!ll&&!rl&&r
00125
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
2454 # An explicit '*' is the same as saying nothing, and saying it out loud reads better in a
2455 # config than an absent key.
2456 100 ▶ $allow_models = (grep { $_ eq '*' } @list) ? undef : { map { $_ => 1 } @list };
Branch: 1 branch
BranchTrueFalseTotal
grep({$_ eq '*';} @list) ? : 1 99 100
2457 }
2458  
2459 return {
2460 name => ($name // $spec->{name} // ''),
2461 allow_models => $allow_models,
2462 207 ▶ deny_tags => $self->normalize_tags($spec->{deny_tags}),
Condition80%4/5
($name // $spec->{"name"}) // ""
l!l
1998
$name // $spec->{"name"}
l!l&&r!l&&!r
19908
MC/DC50%1/2
($name // $spec->{"name"}) // ""
$name $spec->{"name"}
Truth table66%2/3
A // B
A= $nameB= $spec->{"name"}
ABresult
1X1
011
000
2463 };
2464 }
2465  
2466 # Key ids before ADR 0016 were the first 12 hex digits of the same digest, so a short id is
2467 # the prefix of the full id of the same key.
2468 113 my $LEGACY_KEY_ID_HEX = 12;
2469 113 my %legacy_key_id_warned;
2470  
2471 # Resolves the whole policy section once, at config load. Nothing here happens per request:
2472 # a request costs one hash lookup, and identical resolutions share a single object, so a
2473 # thousand keys on three profiles are three policy objects and a thousand pointers.
2474 142 ▶sub _load_policies {
Subroutine _load_policies: called CC=30 SCAR=34.1
2475 142 my ($self, $cfg) = @_;
2476  
2477 142 my %policies;
2478 142 ▶ if (ref($cfg->{policies}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg->{"policies"} eq "HASH") 103 39 142
2479 103 for my $name (keys %{$cfg->{policies}}) {
2480 196 $policies{$name} = $self->resolve_policy($cfg->{policies}{$name}, $name);
2481 }
2482 }
2483  
2484 142 my %interned = map { $self->_policy_fingerprint($_) => $_ } values %policies;
2485 53 ▶ my $intern = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
2486 53 my ($policy) = @_;
2487 53 my $print = $self->_policy_fingerprint($policy);
2488 53 ▶ return $interned{$print} ||= $policy;
Condition66%2/3
$interned{$print} ||= $policy
l!l&&r!l&&!r
4850
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
2489 142 };
2490  
2491 142 my $default;
2492 142 ▶ if (defined $cfg->{default_policy} && length $cfg->{default_policy}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cfg->{"default_policy"} and length $cfg->{"default_policy"}) 62 80 142
Condition66%2/3
defined $cfg->{"default_policy"} and length $cfg->{"default_policy"}
!ll&&!rl&&r
80062
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
2493 62 $default = $policies{$cfg->{default_policy}};
2494 62 ▶ croak "default_policy '$cfg->{default_policy}' is not defined in policies" unless $default;
Branch: 1 branch
BranchTrueFalseTotal
unless $default 5 57 62
2495 }
2496  
2497 # names: is a readable-name -> key-id registry that lives in the config, resolved to key ids
2498 # here and never consulted on the request path (karr #17, ADR 0008). A value must be an id
2499 # from `skeid keyid`, never a customer key -- the config still holds no keys. With it, a
2500 # keys: entry may be written by name, and rotating a customer's key is a one-line edit here
2501 # rather than a rewrite of every policy line that named them by id.
2502 137 my %key_names;
2503 137 ▶ if (ref($cfg->{names}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg->{"names"} eq "HASH") 69 68 137
2504 69 for my $name (keys %{$cfg->{names}}) {
2505 115 my $id = $cfg->{names}{$name};
2506 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
2507 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
2508 113 $key_names{$name} = $id;
2509 }
2510 }
2511  
2512 # Resolve a keys: entry's label through the names registry, if it is a known name; otherwise
2513 # it is taken to be a key id already. Two labels resolving to the same id is a config error,
2514 # not a silent last-wins -- it usually means a name and its own id were both listed.
2515 135 my %seen_id;
2516 102 ▶ my $resolve_key_id = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2517 102 my ($label) = @_;
2518 102 ▶ my $id = exists $key_names{$label} ? $key_names{$label} : $label;
Branch: 1 branch
BranchTrueFalseTotal
exists $key_names{$label} ? : 56 46 102
2519 croak "keys entry '$label' resolves to key id '$id', which another entry already claims"
2520 102 ▶ if $seen_id{$id}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen_id{$id}++ 1 101 102
2521 101 return $id;
2522 135 };
2523  
2524 135 my %key_policies;
2525 135 ▶ if (ref($cfg->{keys}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg->{"keys"} eq "HASH") 54 81 135
2526 54 for my $label (keys %{$cfg->{keys}}) {
2527 102 my $key = $resolve_key_id->($label);
2528 101 my $entry = $cfg->{keys}{$label};
2529  
2530 101 ▶ if (!ref($entry)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $entry) 48 53 101
2531 48 my $policy = $policies{$entry};
2532 48 ▶ croak "key '$label' references undefined policy '$entry'" unless $policy;
Branch: 1 branch
BranchTrueFalseTotal
unless $policy 1 47 48
2533 47 $key_policies{$key} = $policy;
2534 47 next;
2535 }
2536  
2537 53 ▶ 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 53 53
2538  
2539 53 my $base = {};
2540 53 ▶ if (defined $entry->{policy} && length $entry->{policy}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $entry->{'policy'} and length $entry->{'policy'}) { } 29 24 53
elsif ($default) { } 22 2 24
Condition66%2/3
defined $entry->{"policy"} and length $entry->{"policy"}
!ll&&!rl&&r
24029
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
2541 29 my $named = $policies{$entry->{policy}};
2542 29 ▶ croak "key '$label' references undefined policy '$entry->{policy}'" unless $named;
Branch: 1 branch
BranchTrueFalseTotal
unless $named 0 29 29
2543 29 $base = $named;
2544 } elsif ($default) {
2545 22 $base = $default;
2546 }
2547  
2548 # Overrides are sparse: an absent field keeps the profile's value, so "same as standard
2549 # but allowed to use cloud" is one line rather than a restated profile.
2550 53 ▶ my $overrides = ref($entry->{overrides}) eq 'HASH' ? $entry->{overrides} : $entry;
Branch: 1 branch
BranchTrueFalseTotal
ref $entry->{'overrides'} eq 'HASH' ? : 0 53 53
2551 my $merged = {
2552 name => ($base->{name} // ''),
2553 allow_models => (exists($overrides->{models}) || exists($overrides->{aliases})
2554 ? $self->resolve_policy($overrides)->{allow_models}
2555 : $base->{allow_models}),
2556 deny_tags => (exists($overrides->{deny_tags})
2557 ? $self->normalize_tags($overrides->{deny_tags})
2558 53 ▶ : ($base->{deny_tags} // [])),
Branch: 2 branches
BranchTrueFalseTotal
exists $overrides->{'models'} || exists $overrides->{'aliases'} ? : 5 48 53
exists $overrides->{'deny_tags'} ? : 2 51 53
Condition85%6/7
$base->{"name"} // ""
l!l
512
exists $overrides->{"models"} or exists $overrides->{"aliases"}
l!l&&r!l&&!r
5048
$base->{"deny_tags"} // []
l!l
492
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
2559 };
2560 53 $key_policies{$key} = $intern->($merged);
2561 }
2562 }
2563  
2564 # Short key ids from before ADR 0016 still name their customer: a request's full id falls
2565 # back to its short prefix (see _configured_key_id). Where one key would match two entries --
2566 # a short id and a full id it is the prefix of -- which one governs is not for Skeid to guess.
2567 133 my %legacy = map { $_ => 1 } grep { _is_legacy_key_id($_) } keys %seen_id;
2568 133 for my $id (sort keys %seen_id) {
2569 99 ▶ next unless $id =~ /\Ak_[0-9a-f]{40}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\Ak_[0-9a-f]{40}\z/ 24 75 99
2570 75 my $short = substr($id, 0, 2 + $LEGACY_KEY_ID_HEX);
2571 croak "key id '$short' is the short form of '$id', and both have a keys entry: one key "
2572 . 'would match both; keep only the full id'
2573 75 ▶ if $legacy{$short};
Branch: 1 branch
BranchTrueFalseTotal
if $legacy{$short} 2 73 75
2574 }
2575 131 _warn_legacy_key_id($_) for sort(keys %legacy), grep { _is_legacy_key_id($_) } values %key_names;
2576  
2577 131 $self->policies(\%policies);
2578 131 $self->default_policy($default);
2579 131 $self->key_policies(\%key_policies);
2580 131 $self->key_names(\%key_names);
2581 131 return 1;
2582 }
2583  
2584 220 ▶sub _is_legacy_key_id {
Subroutine _is_legacy_key_id: called CC=3 SCAR=11.1
2585 220 my ($id) = @_;
2586 220 ▶ 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 199 220
Condition66%2/3
defined $id and $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/
!ll&&!rl&&r
019921
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
2587 }
2588  
2589 19 ▶sub _warn_legacy_key_id {
Subroutine _warn_legacy_key_id: called CC=2 SCAR=6.9
2590 19 my ($id) = @_;
2591 19 ▶ return if $legacy_key_id_warned{$id}++;
Branch: 1 branch
BranchTrueFalseTotal
if $legacy_key_id_warned{$id}++ 11 8 19
2592 8 warn "skeid: key id '$id' is a short key id from before ADR 0016; it still matches the key "
2593 . "whose full id starts with it, but is deprecated: replace it with the full id "
2594 . "`skeid keyid` prints\n";
2595 8 return;
2596 }
2597  
2598 # The id a customer's entry in a config table is filed under: the request's own id, or -- for
2599 # a config still written with short ids -- that id's short prefix. Exact wins, so a full id
2600 # entry is always what a full id finds.
2601 2178 ▶sub _configured_key_id {
Subroutine _configured_key_id: called CC=6 SCAR=17.9
2602 2178 my ($self, $table, $api_key_id) = @_;
2603 2178 ▶ 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 6 2172 2178
Condition66%2/3
defined $api_key_id and length $api_key_id
!ll&&!rl&&r
602172
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
2604 2172 ▶ return $api_key_id if exists $table->{$api_key_id};
Branch: 1 branch
BranchTrueFalseTotal
if exists $table->{$api_key_id} 443 1729 2172
2605 1729 ▶ 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/ 767 962 1729
2606 962 my $short = substr($api_key_id, 0, 2 + $LEGACY_KEY_ID_HEX);
2607 962 ▶ return exists $table->{$short} ? $short : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $table->{$short} ? : 8 954 962
2608 }
2609  
2610 249 ▶sub _policy_fingerprint {
Subroutine _policy_fingerprint: called CC=2 SCAR=6.9
2611 249 my ($self, $policy) = @_;
2612 249 ▶ my $models = defined($policy->{allow_models}) ? join(',', sort keys %{$policy->{allow_models}}) : '*';
Branch: 1 branch
BranchTrueFalseTotal
defined $policy->{'allow_models'} ? : 99 150 249
2613 249 return join("\0", $models, join(',', @{$policy->{deny_tags}}));
2614 }
2615  
2616  
2617 1801 ▶sub key_id_for_key {
Subroutine key_id_for_key: called CC=3 SCAR=11.0
Pod documented
2618 1801 my ($self, $api_key) = @_;
2619 1801 ▶ return 'anonymous' unless defined($api_key) && length($api_key);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $api_key and length $api_key 848 953 1801
Condition66%2/3
defined $api_key and length $api_key
!ll&&!rl&&r
0848953
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
2620 953 return 'k_' . sha1_hex($api_key);
2621 }
2622  
2623  
2624 1290 ▶sub policy_for_key {
Subroutine policy_for_key: called CC=3 SCAR=11.0
Pod documented
2625 1290 my ($self, $api_key_id) = @_;
2626 1290 my $id = $self->_configured_key_id($self->key_policies, $api_key_id);
2627 1290 ▶ return $self->key_policies->{$id} if defined($id) && $self->key_policies->{$id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $id and $self->key_policies->{$id} 117 1173 1290
Condition66%2/3
defined $id and $self->key_policies->{$id}
!ll&&!rl&&r
11730117
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
2628 1173 return $self->default_policy;
2629 }
2630  
2631  
2632 3 ▶sub key_id_for_name {
Subroutine key_id_for_name: called CC=3 SCAR=12.5
Pod documented
2633 3 my ($self, $name) = @_;
2634 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
2635 3 return $self->key_names->{$name};
2636 }
2637  
2638 # The client_auth section (skeid k90), resolved once at config load into a key id set. An entry
2639 # is a names: name or a key id; anything else fails the load (see _key_id_set). Returns the
2640 # notices to log once the config applied.
2641 80 ▶sub _load_client_auth {
Subroutine _load_client_auth: called CC=8 SCAR=20.8
2642 80 my ($self, $section) = @_;
2643 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
2644 78 for my $key (sort keys %$section) {
2645 77 ▶ croak "client_auth: unknown key '$key' (known: keys)" unless $key eq 'keys';
Branch: 1 branch
BranchTrueFalseTotal
unless $key eq "keys" 1 76 77
2646 }
2647 77 my $list = $section->{keys};
2648 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
2649 . 'client routes' unless defined $list;
2650 75 ▶ $list = [ $list ] unless ref $list;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list 1 74 75
2651 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
2652  
2653 74 my $allowed = $self->_key_id_set($list, 'client_auth.keys');
2654 67 $self->client_auth_keys($allowed);
2655 67 ▶ return %$allowed ? () : ('client_auth.keys is empty: no key can use the client routes, every '
Branch: 1 branch
BranchTrueFalseTotal
%$allowed ? : 66 1 67
2656 . 'request on them answers 401');
2657 }
2658  
2659 # A list of customer keys in the config -- client_auth.keys, an MCP server's keys -- resolved
2660 # into a key id set, id to 1. An entry is a names: name or a key id; anything else fails the
2661 # load. The message names the entry by its position and never by its value: a value that is
2662 # neither is most likely a key someone pasted, and a reload error ends up in the log and on
2663 # /skeid/config (ADR 0003). $label is the list's place in the config, for that message. A short
2664 # (pre-ADR 0016) id is kept as it is and warned about once; _configured_key_id matches it.
2665 215 ▶sub _key_id_set {
Subroutine _key_id_set: called CC=13 SCAR=25.7
2666 215 my ($self, $list, $label) = @_;
2667 215 my (%allowed, @legacy);
2668 215 my $position = 0;
2669 215 for my $entry (@$list) {
2670 241 $position++;
2671 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
2672 241 ▶ my $id = defined($name) ? $self->key_names->{$name} : $entry;
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 142 99 241
2673 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
2674 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
2675 8 ▶ croak defined($name)
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 1 7 8
2676 ? "$label entry $position is the names: entry '$name', which does not map to a "
2677 . 'key id (k_ + 40 hex from `skeid keyid`)'
2678 : "$label entry $position is neither a names: entry nor a key id (k_ + 40 hex "
2679 . 'from `skeid keyid`); a key itself never goes into the config';
2680 }
2681 233 ▶ push @legacy, $id unless $full;
Branch: 1 branch
BranchTrueFalseTotal
unless $full 2 231 233
2682 233 $allowed{$id} = 1;
2683 }
2684 207 _warn_legacy_key_id($_) for @legacy;
2685 207 return \%allowed;
2686 }
2687  
2688 # The mcp section (skeid k103, ADR 0022), resolved once at config load into the server table.
2689 # Strict like client_auth and uploads: a misspelled key, a key of the other transport or a URL
2690 # that is none fails the load, and the previous config stays in force. No message repeats a
2691 # value that could be a secret -- a URL, a header value, a keys entry. What the wire allows --
2692 # the transports, a server name, the headers a server may set -- is Protocol::MCP's to know.
2693 # Returns the notices to log once the config applied.
2694 113 my %MCP_KEYS = map { $_ => 1 } qw( public_url servers max_request_bytes );
2695 113 my %MCP_SERVER_KEYS = (
2696 common => [qw( transport description keys )],
2697 relayed => [qw( url api_key_ref api_key_env headers )],
2698 stdio => [qw( command args env )],
2699 );
2700  
2701 55 ▶sub _load_mcp {
Subroutine _load_mcp: called CC=57 SCAR=40.9
2702 55 my ($self, $section) = @_;
2703 55 my $mcp = 'Langertha::Skeid::Protocol::MCP';
2704 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
2705 54 for my $key (sort keys %$section) {
2706 croak "mcp: unknown key '$key' (known: " . join(' ', sort keys %MCP_KEYS) . ')'
2707 84 ▶ unless $MCP_KEYS{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless $MCP_KEYS{$key} 1 83 84
2708 }
2709  
2710 53 my $public_url;
2711 53 ▶ if (defined $section->{public_url}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"public_url"}) 21 32 53
2712 21 my $problem = $mcp->url_problem($section->{public_url});
2713 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
2714 20 ($public_url = "$section->{public_url}") =~ s{/+\z}{};
2715 }
2716  
2717 52 my $max_request = $MCP_MAX_REQUEST_BYTES;
2718 52 ▶ if (exists $section->{max_request_bytes}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $section->{"max_request_bytes"}) 9 43 52
2719 9 my $max = $section->{max_request_bytes};
2720 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
2721 unless defined($max) && !ref($max) && $max =~ /\A[0-9]+\z/ && $max >= 1;
2722 3 $max_request = 0 + $max;
2723 }
2724  
2725 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
2726 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
2727  
2728 45 my (%resolved, @notices);
2729 45 for my $name (sort keys %$servers) {
2730 158 my $problem = $mcp->name_problem($name);
2731 158 ▶ croak "mcp.servers: $problem" if defined $problem;
Branch: 1 branch
BranchTrueFalseTotal
if defined $problem 1 157 158
2732 157 my $at = "mcp.servers.$name";
2733 157 my $entry = $servers->{$name};
2734 157 ▶ croak "$at must be a hash" unless ref($entry) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 1 156 157
2735  
2736 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
2737 156 ▶ croak "$at: unknown transport (known: " . join(' ', $mcp->transports) . ')'
Branch: 1 branch
BranchTrueFalseTotal
unless $mcp->is_transport($transport) 1 155 156
2738 unless $mcp->is_transport($transport);
2739 155 my $relayed = $mcp->is_relayed($transport);
2740 155 ▶ my %own = map { $_ => 1 } @{$MCP_SERVER_KEYS{common}}, @{$MCP_SERVER_KEYS{$relayed ? 'relayed' : 'stdio'}};
Branch: 1 branch
BranchTrueFalseTotal
$relayed ? : 128 27 155
2741 155 ▶ my %other = map { $_ => 1 } @{$MCP_SERVER_KEYS{$relayed ? 'stdio' : 'relayed'}};
Branch: 1 branch
BranchTrueFalseTotal
$relayed ? : 128 27 155
2742 155 for my $key (sort keys %$entry) {
2743 512 ▶ next if $own{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $own{$key} 509 3 512
2744 croak "$at: '$key' " . ($relayed ? 'belongs to a stdio server' : 'does not belong to a stdio server')
2745 3 ▶ if $other{$key};
Branch: 2 branches
BranchTrueFalseTotal
if $other{$key} 2 1 3
$relayed ? : 1 1 2
2746 1 croak "$at: unknown key '$key' (known: " . join(' ', sort keys %own) . ')';
2747 }
2748  
2749 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
2750 152 ▶ croak "$at.description must be a string" if ref $description;
Branch: 1 branch
BranchTrueFalseTotal
if ref $description 1 151 152
2751  
2752 151 my %server = (name => $name, transport => "$transport", description => "$description");
2753 151 ▶ if ($relayed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($relayed) { } 125 26 151
2754 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
2755 124 $problem = $mcp->url_problem($entry->{url});
2756 124 ▶ croak "$at.url $problem" if defined $problem;
Branch: 1 branch
BranchTrueFalseTotal
if defined $problem 3 121 124
2757 121 $server{url} = "$entry->{url}";
2758  
2759 121 for my $source (qw( api_key_ref api_key_env )) {
2760 242 ▶ next unless defined $entry->{$source};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry->{$source} 174 68 242
2761 croak "$at.$source must be a non-empty string"
2762 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
2763 68 $server{$source} = "$entry->{$source}";
2764 }
2765  
2766 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
2767 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
2768 121 for my $header (sort keys %$headers) {
2769 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
2770 unless $header =~ /\A[A-Za-z0-9!#\$%&'*+.^_`|~-]+\z/;
2771 29 $problem = $mcp->config_header_problem($header);
2772 29 ▶ croak "$at.headers: '$header' may not be set here: $problem" if defined $problem;
Branch: 1 branch
BranchTrueFalseTotal
if defined $problem 2 27 29
2773 27 my $value = $headers->{$header};
2774 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
2775 if !defined($value) || ref($value) || $value =~ /[\r\n\0]/;
2776 26 $server{headers}{$header} = "$value";
2777 }
2778 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
2779 } else {
2780 croak "$at needs a command: what the customer runs on its own machine"
2781 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
2782 25 $server{command} = "$entry->{command}";
2783  
2784 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
2785 croak "$at.args must be a list of strings"
2786 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
2787 24 $server{args} = [ map { "$_" } @$args ];
2788  
2789 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
2790 croak "$at.env must be a map of strings"
2791 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
2792 23 $server{env} = { map { $_ => "$env->{$_}" } keys %$env };
2793 }
2794  
2795 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
2796 141 ▶ $list = [ $list ] unless ref $list;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list 2 139 141
2797 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
2798 141 $server{keys} = $self->_key_id_set($list, "$at.keys");
2799 push @notices, "$at is assigned to no key: no customer can reach or see it"
2800 140 ▶ unless %{$server{keys}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$server{"keys"};} 1 139 140
2801  
2802 140 $resolved{$name} = \%server;
2803 }
2804  
2805 27 $self->mcp_servers(\%resolved);
2806 27 $self->mcp_public_url($public_url);
2807 27 $self->mcp_max_request_bytes($max_request);
2808 27 return @notices;
2809 }
2810  
2811 # The uploads section (skeid k91). Strict like client_auth: a misspelled key or a limit that is
2812 # not a positive integer fails the load rather than leaving the default in force unnoticed --
2813 # and 0, which the server underneath reads as "no limit", is refused with the rest.
2814 18 ▶sub _load_uploads {
Subroutine _load_uploads: called CC=11 SCAR=24.1
2815 18 my ($self, $section) = @_;
2816 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
2817 unless ref($section) eq 'HASH';
2818 16 for my $key (sort keys %$section) {
2819 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
2820 unless $key eq 'max_bytes' || $key eq 'documents_max_bytes';
2821 }
2822 14 my %limit = (max_bytes => $UPLOAD_MAX_BYTES, documents_max_bytes => $DOCUMENTS_MAX_BYTES);
2823 14 for my $key (sort keys %limit) {
2824 24 ▶ next unless exists $section->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $section->{$key} 8 16 24
2825 16 my $max = $section->{$key};
2826 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
2827 unless defined($max) && !ref($max) && $max =~ /\A[0-9]+\z/ && $max >= 1;
2828 9 $limit{$key} = 0 + $max;
2829 }
2830 7 $self->upload_max_bytes($limit{max_bytes});
2831 7 $self->documents_max_bytes($limit{documents_max_bytes});
2832 7 return;
2833 }
2834  
2835 # The documents section (skeid k94, ADR 0028). Strict like uploads: an unknown key or a switch
2836 # that is no boolean fails the load rather than leaving the default in force unnoticed. There is
2837 # no model name here: documents nodes are chosen by their kind.
2838 6 ▶sub _load_documents {
Subroutine _load_documents: called CC=9 SCAR=22.2
2839 6 my ($self, $section) = @_;
2840 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
2841 unless ref($section) eq 'HASH';
2842 6 for my $key (sort keys %$section) {
2843 6 ▶ croak "documents: unknown key '$key' (known: allow_remote_sources)"
Branch: 1 branch
BranchTrueFalseTotal
unless $key eq "allow_remote_sources" 1 5 6
2844 unless $key eq 'allow_remote_sources';
2845 }
2846 5 my $allow = 0;
2847 5 ▶ if (defined(my $v = $section->{allow_remote_sources})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $v = $section->{"allow_remote_sources"})) 5 0 5
2848 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
2849 3 my $s = lc "$v";
2850 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
2851 0 elsif ($s =~ /\A(?:0|false|no|off|)\z/) { $allow = 0 }
2852 2 else { croak 'documents.allow_remote_sources must be true or false' }
2853 }
2854 1 $self->documents_allow_remote_sources($allow);
2855 1 return;
2856 }
2857  
2858 # The realtime section (skeid k95, ADR 0029). Strict like uploads: a misspelled key or a value
2859 # that is not an integer of at least 1 fails the load. A key left out is its default, also on a
2860 # reload that drops it.
2861 25 ▶sub _load_realtime {
Subroutine _load_realtime: called CC=10 SCAR=23.0
2862 25 my ($self, $section) = @_;
2863 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
2864 unless ref($section) eq 'HASH';
2865 23 my @known = sort keys %REALTIME_DEFAULT;
2866 23 for my $key (sort keys %$section) {
2867 croak "realtime: unknown key '$key' (known: " . join(', ', @known) . ')'
2868 30 ▶ unless exists $REALTIME_DEFAULT{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $REALTIME_DEFAULT{$key} 1 29 30
2869 }
2870 22 my %value;
2871 22 for my $key (@known) {
2872 70 ▶ my $v = exists $section->{$key} ? $section->{$key} : $REALTIME_DEFAULT{$key};
Branch: 1 branch
BranchTrueFalseTotal
exists $section->{$key} ? : 29 41 70
2873 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
2874 unless defined($v) && !ref($v) && $v =~ /\A[0-9]+\z/ && $v >= 1;
2875 62 $value{$key} = 0 + $v;
2876 }
2877 14 $self->realtime_idle_timeout($value{idle_timeout});
2878 14 $self->realtime_max_session_seconds($value{max_session_seconds});
2879 14 $self->realtime_max_message_bytes($value{max_message_bytes});
2880 14 $self->realtime_max_queued_bytes($value{max_queued_bytes});
2881 14 return;
2882 }
2883  
2884 # The openapi section (skeid k105). Strict like uploads: an unknown key, a switch that is no
2885 # boolean or a cache_dir that is not an absolute path fails the load -- a relative path would
2886 # mean "wherever the process was started".
2887 17 ▶sub _load_openapi {
Subroutine _load_openapi: called CC=14 SCAR=26.6
2888 17 my ($self, $section) = @_;
2889 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
2890 unless ref($section) eq 'HASH';
2891 16 for my $key (sort keys %$section) {
2892 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
2893 unless $key eq 'swagger_ui' || $key eq 'cache_dir';
2894 }
2895  
2896 15 my $ui = 0;
2897 15 ▶ if (defined $section->{swagger_ui}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"swagger_ui"}) 13 2 15
2898 13 my $v = $section->{swagger_ui};
2899 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
2900 13 my $s = lc "$v";
2901 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
2902 1 elsif ($s =~ /\A(?:0|false|no|off|)\z/) { $ui = 0 }
2903 1 else { croak 'openapi.swagger_ui must be true or false' }
2904 }
2905  
2906 14 my $dir = $section->{cache_dir};
2907 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
2908 if defined($dir) && (ref($dir) || $dir !~ m{\A/} || $dir =~ /[\0\n]/);
2909  
2910 13 $self->openapi_swagger_ui($ui);
2911 13 $self->openapi_cache_dir($dir);
2912 13 return;
2913 }
2914  
2915  
2916 1603 ▶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 ? : 252 1351 1603
2917  
2918  
2919 765 ▶sub client_key_allowed {
Subroutine client_key_allowed: called CC=3 SCAR=11.0
Pod documented
2920 765 my ($self, $api_key_id) = @_;
2921 765 my $allowed = $self->client_auth_keys;
2922 765 ▶ return 1 unless defined $allowed;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $allowed 1 764 765
2923 764 ▶ 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 510 764
2924 }
2925  
2926  
2927 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
2928  
2929  
2930 61 ▶sub mcp_server_for_key {
Subroutine mcp_server_for_key: called CC=6 SCAR=19.3
Pod documented
2931 61 my ($self, $name, $api_key_id) = @_;
2932 61 my $servers = $self->mcp_servers;
2933 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
2934 61 ▶ my $server = $servers->{$name} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $server = $servers->{$name} or return undef 57 4 61
2935 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
2936 }
2937  
2938  
2939 9 ▶sub mcp_servers_for_key {
Subroutine mcp_servers_for_key: called CC=2 SCAR=7.0
Pod documented
2940 9 my ($self, $api_key_id) = @_;
2941 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
2942 return [
2943 50 grep { defined $self->_configured_key_id($_->{keys}, $api_key_id) }
2944 9 map { $servers->{$_} } sort keys %$servers
2945 ];
2946 }
2947  
2948  
2949 1215 ▶sub route_plan {
Subroutine route_plan: called CC=14 SCAR=26.5
Pod documented
2950 1215 my ($self, %args) = @_;
2951 1215 ▶ my $model = $args{model} // '';
Condition50%1/2
$args{"model"} // ""
l!l
12150
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
2952 1215 my $policy = $self->policy_for_key($args{api_key_id});
2953 1215 ▶ my $deny = $policy ? $policy->{deny_tags} : [];
Branch: 1 branch
BranchTrueFalseTotal
$policy ? : 289 926 1215
2954 1215 my $kind = $self->_selector_kind(%args);
2955 1215 ▶ my @kind = length($kind) ? (kind => $kind) : ();
Branch: 1 branch
BranchTrueFalseTotal
length $kind ? : 58 1157 1215
2956  
2957 1215 ▶ 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}) 24 1191 1215
Condition100%6/6
$policy and $policy->{"allow_models"} and not $policy->{"allow_models"}{$model}
!ll&&!rl&&r
99819324
$policy and $policy->{"allow_models"}
!ll&&!rl&&r
92672217
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
2958 24 return { tiers => [], permitted => 0, reason => 'model_not_permitted' };
2959 }
2960  
2961 # Every tier carries the kind of the route, whatever an alias says: a documents route plans
2962 # over documents nodes and a chat route over chat nodes, so the alias named like the documents
2963 # routing key tiers the one and finds nothing for the other.
2964 1191 my $alias = $self->model_aliases->{$model};
2965 my @tiers = $alias
2966 178 ▶ ? (map { +{ %$_, deny_tags => $deny, @kind } } @{$alias->{tiers}})
Condition50%2/4
$args{"engine"} // ""
l!l
01031
$self->route_wait_timeout_ms // 0
l!l
10310
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
2967 : ({
2968 tags => [],
2969 model => $model,
2970 1191 ▶ engine => $self->normalize_engine_id($args{engine} // ''),
Branch: 1 branch
BranchTrueFalseTotal
$alias ? : 160 1031 1191
2971 wait_ms => 0 + ($self->route_wait_timeout_ms // 0),
2972 deny_tags => $deny,
2973 @kind,
2974 });
2975  
2976 1191 my $before = scalar @tiers;
2977 1191 ▶ if (@$deny) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$deny) 95 1096 1191
2978 95 my %denied = map { $_ => 1 } @$deny;
2979 @tiers = grep {
2980 95 my $tier = $_;
2981 99 ▶ !grep { $denied{$_} } @{$tier->{tags} || []};
Condition50%1/2
$tier->{'tags'} || []
l!l
990
MC/DC0%0/1
$tier->{'tags'} || []
$tier->{'tags'}
Truth table50%1/2
A
A= $tier->{'tags'}
Aresult
11
00
2982 } @tiers;
2983 }
2984  
2985 1191 ▶ return { tiers => [], permitted => 0, reason => 'all_tiers_denied' }
Branch: 1 branch
BranchTrueFalseTotal
if $before and not @tiers 4 1187 1191
Condition66%2/3
$before and not @tiers
!ll&&!rl&&r
011874
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
2986 if $before && !@tiers;
2987  
2988 1187 return { tiers => \@tiers, permitted => 1, reason => '' };
2989 }
2990  
2991  
2992 54 ▶sub select_nodes {
Subroutine select_nodes: called CC=7 SCAR=19.8
Pod documented
2993 54 my ($self, %args) = @_;
2994 54 my $tags = $self->normalize_tags($args{tags});
2995 54 my $deny = $self->normalize_tags($args{deny_tags});
2996 54 ▶ my $kind = exists($args{kind}) ? $self->_selector_kind(%args) : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'kind'} ? : 50 4 54
2997 return [
2998 83 map { +{%$_} }
2999 grep {
3000 $self->_node_has_tags($_, $tags) && !$self->_node_has_any_tag($_, $deny)
3001 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
3002 }
3003 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
3004 ];
3005 }
3006  
3007  
3008 1703 ▶sub pick_node {
Subroutine pick_node: called CC=10 SCAR=23.0
Pod documented
3009 1703 my ($self, %args) = @_;
3010 1703 my $entry = $self->_route_entry(%args);
3011 1703 my @nodes = @{$entry->{nodes}};
3012 1703 ▶ return unless @nodes;
Branch: 1 branch
BranchTrueFalseTotal
unless @nodes 4 1699 1703
3013  
3014 1699 my @weights = @{$entry->{weights}};
3015 1699 my $total_weight = $entry->{total_weight};
3016 1699 ▶ return unless $total_weight > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $total_weight > 0 0 1699 1699
3017  
3018 1699 my $key = $self->_route_key(%args);
3019 1699 ▶ my $cursor = 0 + ($self->_rr_cursor->{$key} // 0);
Condition100%2/2
$self->_rr_cursor->{$key} // 0
l!l
719980
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
3020 1699 $cursor %= $total_weight;
3021  
3022 # Locate the weighted range containing the cursor without expanding weights into slots. From
3023 # that owner onward, the old slot walk considered nodes in inventory order and, if none admitted
3024 # before the end, wrapped to target zero. Admission is one per-node observation for this
3025 # synchronous selection pass; resampling it once per weight slot describes no new capacity.
3026 # Check each node once and skip the rest of every saturated weight range.
3027 1699 my ($owner, $range_end) = (0, 0);
3028 1699 for my $idx (0 .. $#nodes) {
3029 1738 $range_end += $weights[$idx];
3030 1738 ▶ if ($cursor < $range_end) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cursor < $range_end) 1699 39 1738
3031 1699 $owner = $idx;
3032 1699 last;
3033 }
3034 }
3035  
3036 1699 for my $offset (0 .. $#nodes) {
3037 1764 my $idx = ($owner + $offset) % @nodes;
3038 1764 my $candidate = $nodes[$idx];
3039 1764 ▶ next unless $self->_node_can_take($candidate);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_node_can_take($candidate) 319 1445 1764
3040  
3041 # Before a wrap, the historical cursor advances one weighted slot even when a later node was
3042 # selected because the owning range was saturated. After a wrap, the first target examined is
3043 # slot zero, so its successor is slot one. Keeping both cases preserves partial-saturation
3044 # ordering while avoiding one admission check per skipped slot.
3045 1445 ▶ $self->_rr_cursor->{$key} = $idx < $owner
Branch: 1 branch
BranchTrueFalseTotal
$idx < $owner ? : 6 1439 1445
3046 ? (1 % $total_weight)
3047 : (($cursor + 1) % $total_weight);
3048 1445 my $id = $candidate->{id};
3049 1445 ▶ my $inflight = 0 + ($self->_inflight->{$id} // 0);
Condition100%2/2
$self->_inflight->{$id} // 0
l!l
524921
MC/DC100%1/1
$self->_inflight->{$id} // 0
$self->_inflight->{$id}
Truth table100%2/2
A
A= $self->_inflight->{$id}
Aresult
11
00
3050 return {
3051 1445 %$candidate,
3052 inflight => $inflight,
3053 route_key => $key,
3054 };
3055 }
3056  
3057 254 return;
3058 }
3059  
3060  
3061 1731 ▶sub route_state {
Subroutine route_state: called CC=5 SCAR=16.1
Pod documented
3062 1731 my ($self, %args) = @_;
3063 1731 ▶ my $engine = $self->normalize_engine_id($args{engine} // '');
Condition100%2/2
$args{"engine"} // ""
l!l
1302429
MC/DC100%1/1
$args{"engine"} // ""
$args{"engine"}
Truth table100%2/2
A
A= $args{"engine"}
Aresult
11
00
3064 1731 my $eligible = $self->_eligible_nodes(%args);
3065 1731 my $available = [ grep { $self->_node_can_take($_) } @$eligible ];
3066  
3067 return {
3068 model => ($args{model} // ''),
3069 engine => $engine,
3070 tags => $self->normalize_tags($args{tags}),
3071 1731 ▶ deny_tags => $self->normalize_tags($args{deny_tags}),
Branch: 2 branches
BranchTrueFalseTotal
@$eligible ? : 1288 443 1731
@$available ? : 1023 708 1731
Condition50%1/2
$args{"model"} // ""
l!l
17310
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
3072 eligible_count => scalar(@$eligible),
3073 available_count => scalar(@$available),
3074 has_eligible => @$eligible ? 1 : 0,
3075 has_available => @$available ? 1 : 0,
3076 };
3077 }
3078  
3079  
3080 94 ▶sub set_capacity_reading {
Subroutine set_capacity_reading: called CC=26 SCAR=33.2
Pod documented
3081 94 my ($self, $node_id, %reading) = @_;
3082 94 ▶ croak 'node_id required' unless defined $node_id && length $node_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 94 94
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
0094
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
3083  
3084 94 my $now = time;
3085 my $entry = {
3086 source => ((defined($reading{source}) && length($reading{source})) ? "$reading{source}" : 'custom'),
3087 used => (defined $reading{used} ? 0 + $reading{used} : undef),
3088 limit => (defined $reading{limit} ? 0 + $reading{limit} : undef),
3089 at => (defined $reading{at} ? 0 + $reading{at} : $now),
3090 # Which of a provider's several quotas this reading is about, when it had more than one.
3091 # For reports only -- admission just sees used and limit.
3092 (defined $reading{quota} ? (quota => "$reading{quota}") : ()),
3093 (defined $reading{expires_at} ? (expires_at => 0 + $reading{expires_at}) : ()),
3094 # How often this source reports; it sets how long this reading holds a looser one off.
3095 ((defined($reading{interval_ms}) && $reading{interval_ms} > 0)
3096 94 ▶ ? (interval_ms => 0 + $reading{interval_ms}) : ()),
Branch: 7 branches
BranchTrueFalseTotal
defined $reading{'source'} && length $reading{'source'} ? : 90 4 94
defined $reading{'used'} ? : 80 14 94
defined $reading{'limit'} ? : 80 14 94
defined $reading{'at'} ? : 22 72 94
defined $reading{'quota'} ? : 13 81 94
defined $reading{'expires_at'} ? : 20 74 94
defined $reading{'interval_ms'} && $reading{'interval_ms'} > 0 ? : 31 63 94
Condition66%4/6
defined $reading{"source"} and length $reading{"source"}
!ll&&!rl&&r
4090
defined $reading{"interval_ms"} and $reading{"interval_ms"} > 0
!ll&&!rl&&r
63031
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
3097 };
3098  
3099 94 ▶ 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 80 94
elsif (defined $reading{'retry_after'}) { } 0 80 80
Condition66%2/3
defined $reading{"retry_after_ms"} and $reading{"retry_after_ms"} > 0
!ll&&!rl&&r
80014
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
3100 14 $entry->{retry_after} = $now + ($reading{retry_after_ms} / 1000);
3101 } elsif (defined $reading{retry_after}) {
3102 0 $entry->{retry_after} = 0 + $reading{retry_after};
3103 }
3104  
3105 # Two sources disagreeing about one node: the tighter one decides while it is current.
3106 # Taking the latest instead would let whichever probe polls last lift what the other just
3107 # said. But "tighter" alone lets a reading nobody refreshes -- a passive rate-limit reading
3108 # from the last response before traffic stopped -- block a probe that says the node is empty,
3109 # for as long as capacity_max_age_ms allows (forever with 0). So only a pending backoff, or a
3110 # reading younger than the longer of the two sources' poll intervals, holds the incoming one
3111 # off: within that window neither source has had a full poll since, and the tighter one is
3112 # the safer view of the same moment. Two passive readings (no interval) never hold.
3113 94 my $current = $self->capacity_reading($node_id);
3114 94 ▶ 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 85 94
Condition100%6/6
$current and $current->{"source"} ne $entry->{"source"} and _reading_tightness($current) > _reading_tightness($entry)
!ll&&!rl&&r
8149
$current and $current->{"source"} ne $entry->{"source"}
!ll&&!rl&&r
562513
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
3115 && _reading_tightness($current) > _reading_tightness($entry)) {
3116 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
3117 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
3118 9 ▶ my $hold_s = ($cur_ms > $new_ms ? $cur_ms : $new_ms) / 1000;
Branch: 1 branch
BranchTrueFalseTotal
$cur_ms > $new_ms ? : 4 5 9
3119 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
3120 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
3121 }
3122  
3123 88 $self->_capacity->{$node_id} = $entry;
3124 88 return $entry;
3125 }
3126  
3127 # How much a reading holds admission back: a pending backoff above everything, then the used
3128 # fraction, then nothing for a reading without a limit.
3129 26 ▶sub _reading_tightness {
Subroutine _reading_tightness: called CC=6 SCAR=18.8
3130 26 my ($reading) = @_;
3131 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
3132 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
3133 22 ▶ return 0 if $limit <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $limit <= 0 0 22 22
3134 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
3135 }
3136  
3137  
3138 4276 ▶sub capacity_reading {
Subroutine capacity_reading: called CC=14 SCAR=26.6
Pod documented
3139 4276 my ($self, $node_id) = @_;
3140 4276 ▶ return unless defined($node_id) && length($node_id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 4276 4276
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
004276
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
3141 4276 ▶ my $entry = $self->_capacity->{$node_id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $entry = $self->_capacity->{$node_id} or return 278 3998 4276
3142  
3143 278 ▶ my $backoff_pending = ($entry->{retry_after} && time < $entry->{retry_after}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$entry->{'retry_after'} && time < $entry->{'retry_after'} ? : 61 217 278
Condition100%3/3
$entry->{"retry_after"} and time < $entry->{"retry_after"}
!ll&&!rl&&r
216161
MC/DC100%2/2
$entry->{"retry_after"} and time < $entry->{"retry_after"}
$entry->{"retry_after"} time < $entry->{"retry_after"}
Truth table100%3/3
A and B
A= $entry->{"retry_after"}B= time < $entry->{"retry_after"}
ABresult
0X0
100
111
3144 278 ▶ my $max_age = 0 + ($self->capacity_max_age_ms // 0);
Condition50%1/2
$self->capacity_max_age_ms // 0
l!l
2780
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
3145 278 ▶ 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 277 278
Condition87%7/8
not $backoff_pending and $max_age > 0 and time - ($entry->{"at"} // 0) > $max_age / 1000
!ll&&!rl&&r
732041
not $backoff_pending and $max_age > 0
!ll&&!rl&&r
6112205
$entry->{"at"} // 0
l!l
2050
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
3146 1 delete $self->_capacity->{$node_id};
3147 1 return;
3148 }
3149 # A reading that said how long it may be believed is not believed longer (ADR 0017).
3150 277 ▶ 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 276 277
Condition100%6/6
not $backoff_pending and defined $entry->{"expires_at"} and &Time::HiRes::time() > $entry->{"expires_at"}
!ll&&!rl&&r
224521
not $backoff_pending and defined $entry->{"expires_at"}
!ll&&!rl&&r
6116353
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
3151 1 delete $self->_capacity->{$node_id};
3152 1 return;
3153 }
3154 276 return $entry;
3155 }
3156  
3157  
3158 69 ▶sub forget_capacity {
Subroutine forget_capacity: called CC=7 SCAR=21.1
Pod documented
3159 69 my ($self, $node_id, %args) = @_;
3160 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
3161 69 ▶ if (defined $args{source}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"source"}) 25 44 69
3162 25 my $entry = $self->_capacity->{$node_id};
3163 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
3164 }
3165 52 delete $self->_capacity->{$node_id};
3166 52 return 1;
3167 }
3168 0 %{$self->_capacity} = ();
3169 0 return 1;
3170 }
3171  
3172 # Rate-limit headers, in the spellings the big providers actually use. Ordered: the first one
3173 # present wins, so a provider sending several does not get read twice.
3174 # Providers meter more than one thing at once, and for an LLM API the token budget is usually
3175 # what runs out first -- a node with requests to spare and no tokens left answers 429 all the
3176 # same. Each quota is read separately and the tightest one decides.
3177 #
3178 # Within a quota the order is "most specific first": the first name present wins, so a provider
3179 # sending both a specific and a generic spelling is not counted twice.
3180 113 my @RATELIMIT_QUOTAS = (
3181 {
3182 name => 'requests',
3183 remaining => [qw(
3184 x-ratelimit-remaining-requests
3185 anthropic-ratelimit-requests-remaining
3186 x-ratelimit-remaining
3187 ratelimit-remaining
3188 )],
3189 limit => [qw(
3190 x-ratelimit-limit-requests
3191 anthropic-ratelimit-requests-limit
3192 x-ratelimit-limit
3193 ratelimit-limit
3194 )],
3195 },
3196 {
3197 name => 'tokens',
3198 remaining => [qw(
3199 x-ratelimit-remaining-tokens
3200 anthropic-ratelimit-tokens-remaining
3201 anthropic-ratelimit-input-tokens-remaining
3202 )],
3203 limit => [qw(
3204 x-ratelimit-limit-tokens
3205 anthropic-ratelimit-tokens-limit
3206 anthropic-ratelimit-input-tokens-limit
3207 )],
3208 },
3209 );
3210  
3211  
3212 86 ▶sub capacity_header_names {
Subroutine capacity_header_names: called CC=1 SCAR=0.0
Pod documented
3213 86 return ((map { @{$_->{remaining}}, @{$_->{limit}} } @RATELIMIT_QUOTAS), 'retry-after');
3214 }
3215  
3216  
3217 29 ▶sub observe_response_headers {
Subroutine observe_response_headers: called CC=22 SCAR=31.9
Pod documented
3218 29 my ($self, $node_id, $headers, %args) = @_;
3219 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
3220 29 ▶ return unless ref($headers) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $headers eq "HASH" 0 29 29
3221  
3222 # Case-insensitive: header casing is not something a provider promises.
3223 29 my %h = map { lc($_) => $headers->{$_} } keys %$headers;
3224 29 my %reading = (source => 'ratelimit');
3225 29 my $useful = 0;
3226  
3227 # The tightest quota wins, compared as a fraction because requests and tokens are not the
3228 # same unit. Reporting the roomier one would admit a request the provider is about to refuse.
3229 29 my $tightest = -1;
3230 29 for my $quota (@RATELIMIT_QUOTAS) {
3231 58 my ($remaining) = grep { defined } map { $h{$_} } @{$quota->{remaining}};
3232 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
3233 16 my $left = 0 + $1;
3234  
3235 16 my ($limit) = grep { defined } map { $h{$_} } @{$quota->{limit}};
3236 # The probe contract counts what is used, not what is left; a limit we were not told is
3237 # reconstructed as "one more than we have", which is enough to stop admitting at zero.
3238 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
3239 16 ▶ next unless $total > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $total > 0 0 16 16
3240  
3241 16 my $used = $total - $left;
3242 16 ▶ $used = $total if $used > $total;
Branch: 1 branch
BranchTrueFalseTotal
if $used > $total 0 16 16
3243 16 ▶ $used = 0 if $used < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $used < 0 0 16 16
3244  
3245 16 my $fraction = $used / $total;
3246 16 ▶ next unless $fraction > $tightest;
Branch: 1 branch
BranchTrueFalseTotal
unless $fraction > $tightest 1 15 16
3247 15 $tightest = $fraction;
3248 15 $reading{limit} = $total;
3249 15 $reading{used} = $used;
3250 15 $reading{quota} = $quota->{name};
3251 15 $useful = 1;
3252 }
3253  
3254 29 my $retry = $h{'retry-after'};
3255 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
3256 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
3257 13 my $secs;
3258 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
3259 8 $secs = 0 + $1;
3260 } elsif ($status == 429) {
3261 # A 429 with no Retry-After still means "not now". One second is short enough not to
3262 # strand capacity and long enough to stop hammering.
3263 5 $secs = 1;
3264 }
3265 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
3266 13 $reading{retry_after_ms} = $secs * 1000;
3267 13 $useful = 1;
3268 }
3269 }
3270  
3271 29 ▶ return unless $useful;
Branch: 1 branch
BranchTrueFalseTotal
unless $useful 3 26 29
3272 26 return $self->set_capacity_reading($node_id, %reading);
3273 }
3274  
3275  
3276 1057 ▶sub start_request {
Subroutine start_request: called CC=8 SCAR=21.4
Pod documented
3277 1057 my ($self, $node_id) = @_;
3278 1057 ▶ croak 'node_id required' unless defined $node_id && length $node_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 1057 1057
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
001057
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
3279 1057 ▶ my $node = (grep { ($_->{id} // '') eq $node_id } @{$self->nodes})[0];
Condition50%1/2
$_->{"id"} // ""
l!l
23830
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
3280 1057 ▶ return 0 unless $node && $self->_node_can_take($node);
Branch: 1 branch
BranchTrueFalseTotal
unless $node and $self->_node_can_take($node) 6 1051 1057
Condition66%2/3
$node and $self->_node_can_take($node)
!ll&&!rl&&r
061051
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
3281  
3282 1051 ▶ $self->_inflight->{$node_id} = 1 + ($self->_inflight->{$node_id} // 0);
Condition100%2/2
$self->_inflight->{$node_id} // 0
l!l
549502
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
3283 1051 ▶ $self->_stats->{$node_id}{started} = 1 + ($self->_stats->{$node_id}{started} // 0);
Condition100%2/2
$self->_stats->{$node_id}{"started"} // 0
l!l
549502
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
3284 1051 return 1;
3285 }
3286  
3287  
3288 1043 ▶sub finish_request {
Subroutine finish_request: called CC=14 SCAR=26.6
Pod documented
3289 1043 my ($self, $node_id, %args) = @_;
3290 1043 ▶ croak 'node_id required' unless defined $node_id && length $node_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 1043 1043
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
001043
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
3291 1043 ▶ my $cur = 0 + ($self->_inflight->{$node_id} // 0);
Condition50%1/2
$self->_inflight->{$node_id} // 0
l!l
10430
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
3292 1043 $cur--;
3293 1043 ▶ $cur = 0 if $cur < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cur < 0 0 1043 1043
3294 1043 $self->_inflight->{$node_id} = $cur;
3295  
3296 1043 ▶ if ($args{aborted}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($args{'aborted'}) { } 33 1010 1043
elsif ($args{'rejected'}) { } 31 979 1010
elsif ($args{'ok'}) { } 821 158 979
3297 # The client left. The node did nothing wrong: not an error, not a failure in the window.
3298 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
3299 } elsif ($args{rejected}) {
3300 # The client's to fix: not an error, not a failure in the window, and not the node's ok.
3301 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
3302 31 $self->_record_failure($node_id, $self->_rejections);
3303 } elsif ($args{ok}) {
3304 821 ▶ $self->_stats->{$node_id}{ok} = 1 + ($self->_stats->{$node_id}{ok} // 0);
Condition100%2/2
$self->_stats->{$node_id}{"ok"} // 0
l!l
449372
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
3305 } else {
3306 158 ▶ $self->_stats->{$node_id}{error} = 1 + ($self->_stats->{$node_id}{error} // 0);
Condition100%2/2
$self->_stats->{$node_id}{"error"} // 0
l!l
45113
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
3307 158 $self->_record_failure($node_id);
3308 }
3309  
3310 1043 ▶ if (defined $args{duration_ms}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"duration_ms"}) 999 44 1043
3311 $self->_stats->{$node_id}{duration_ms_total}
3312 999 ▶ = (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
520479
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
3313 }
3314  
3315 1043 return 1;
3316 }
3317  
3318 # One bucket per second, pruned to the window on every write, so a node that fails a lot costs
3319 # at most error_window_s buckets.
3320 189 ▶sub _record_failure {
Subroutine _record_failure: called CC=6 SCAR=18.2
3321 189 my ($self, $node_id, $store) = @_;
3322 189 my $now = Time::HiRes::time();
3323 189 ▶ my $f = ($store || $self->_failures)->{$node_id} //= { buckets => {} };
Condition80%4/5
+($store || $self->_failures)->{$node_id} //= {"buckets", {}}
l!l
64125
$store || $self->_failures
l!l&&r!l&&!r
311580
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
3324 189 $f->{last_at} = $now;
3325 189 $f->{buckets}{int $now}++;
3326 189 ▶ my $oldest = int($now - (0 + ($self->registry_error_window_s || 60)));
Condition50%1/2
$self->registry_error_window_s || 60
l!l
1890
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
3327 189 for my $second (keys %{$f->{buckets}}) {
3328 213 ▶ delete $f->{buckets}{$second} if $second < $oldest;
Branch: 1 branch
BranchTrueFalseTotal
if $second < $oldest 0 213 213
3329 }
3330 189 return;
3331 }
3332  
3333 150 ▶sub _errors_in_window {
Subroutine _errors_in_window: called CC=6 SCAR=18.2
3334 150 my ($self, $node_id, $store) = @_;
3335 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
3336 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
3337 17 my $count = 0;
3338 17 for my $second (keys %{$f->{buckets}}) {
3339 17 ▶ $count += $f->{buckets}{$second} if $second >= $oldest;
Branch: 1 branch
BranchTrueFalseTotal
if $second >= $oldest 17 0 17
3340 }
3341 17 return $count;
3342 }
3343  
3344  
3345 36 ▶sub registry_snapshot {
Subroutine registry_snapshot: called CC=19 SCAR=34.8
Pod documented
3346 36 my ($self) = @_;
3347 36 my $instance = $self->registry_instance_id;
3348 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
3349 35 require Sys::Hostname;
3350 35 $instance = Sys::Hostname::hostname();
3351 }
3352  
3353 36 my @nodes;
3354 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
3355 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
3356 75 my $reading = $self->capacity_reading($id);
3357 75 my $failure = $self->_failures->{$id};
3358 push @nodes, {
3359 id => "$id",
3360 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
3361 healthy => ($node->{healthy} ? 1 : 0),
3362 inflight => 0 + ($self->_inflight->{$id} // 0),
3363 max_conns => 0 + $self->worker_max_conns($node),
3364 errors_in_window => 0 + $self->_errors_in_window($id),
3365 last_failure_at => ($failure && defined $failure->{last_at} ? 0 + $failure->{last_at} : undef),
3366 rejected_in_window => 0 + $self->_errors_in_window($id, $self->_rejections),
3367 ($reading ? (capacity => {
3368 used => (defined $reading->{used} ? 0 + $reading->{used} : undef),
3369 limit => (defined $reading->{limit} ? 0 + $reading->{limit} : undef),
3370 source => "$reading->{source}",
3371 75 ($reading->{retry_after} ? (retry_after => 0 + $reading->{retry_after}) : ()),
3372 }) : ()),
3373 };
3374 }
3375  
3376 return {
3377 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
3378 instance => "$instance",
3379 generated_at => Time::HiRes::time(),
3380 ttl => 0 + ($self->registry_ttl_s || 10),
3381 workers => 0 + ($self->worker_count // 1),
3382 nodes => \@nodes,
3383 };
3384 }
3385  
3386  
3387 333 ▶sub node_metrics {
Subroutine node_metrics: called CC=13 SCAR=25.7
Pod documented
3388 333 my ($self, $node_id) = @_;
3389 333 ▶ if (defined $node_id && length $node_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $node_id and length $node_id) 330 3 333
Condition66%2/3
defined $node_id and length $node_id
!ll&&!rl&&r
30330
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
3390 330 ▶ my $s = $self->_stats->{$node_id} || {};
Condition100%2/2
$self->_stats->{$node_id} || {}
l!l
30228
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
3391 330 my $reading = $self->capacity_reading($node_id);
3392 return {
3393 node_id => $node_id,
3394 inflight => 0 + ($self->_inflight->{$node_id} // 0),
3395 started => 0 + ($s->{started} // 0),
3396 ok => 0 + ($s->{ok} // 0),
3397 error => 0 + ($s->{error} // 0),
3398 aborted => 0 + ($s->{aborted} // 0),
3399 rejected => 0 + ($s->{rejected} // 0),
3400 330 ▶ duration_ms_total => 0 + ($s->{duration_ms_total} // 0),
Branch: 1 branch
BranchTrueFalseTotal
$reading ? : 15 315 330
Condition100%14/14
$self->_inflight->{$node_id} // 0
l!l
30228
$s->{"started"} // 0
l!l
30228
$s->{"ok"} // 0
l!l
120210
$s->{"error"} // 0
l!l
112218
$s->{"aborted"} // 0
l!l
36294
$s->{"rejected"} // 0
l!l
24306
$s->{"duration_ms_total"} // 0
l!l
27258
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
3401 # Present only when a probe has something current to say. A report must not present a
3402 # measured node and an inferred one as equally known (ADR 0009).
3403 ($reading ? (capacity => { %$reading }) : ()),
3404 };
3405 }
3406  
3407 3 my @rows;
3408 3 for my $n (@{$self->nodes}) {
3409 6 push @rows, $self->node_metrics($n->{id});
3410 }
3411 3 return \@rows;
3412 }
3413  
3414  
3415 7759 ▶sub call_function {
Subroutine call_function: called CC=58 SCAR=54.2
Pod documented
3416 7759 my ($self, $name, $args) = @_;
3417 7759 ▶ $args ||= {};
Condition50%1/2
$args ||= {}
l!l
77590
MC/DC0%0/1
$args ||= {}
$args
Truth table50%1/2
A
A= $args
Aresult
11
00
3418 7759 ▶ croak 'function name required' unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 7759 7759
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
007759
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
3419 7759 ▶ croak 'function args must be hashref' unless ref($args) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "HASH" 0 7759 7759
3420  
3421 # Dynamic config refresh on each task/function dispatch. Never dies: a failed reload keeps
3422 # the previous config and is reported by reload_status (skeid #39).
3423 7759 $self->maybe_reload_config;
3424  
3425 7759 ▶ if ($name eq 'metrics.estimate_cost') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "metrics.estimate_cost") 0 7759 7759
3426 0 return $self->estimate_cost(%$args);
3427 }
3428 7759 ▶ if ($name eq 'metrics.normalize') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "metrics.normalize") 664 7095 7759
3429 664 return $self->normalize_metrics(%$args);
3430 }
3431 7095 ▶ if ($name eq 'pricing.set') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "pricing.set") 13 7082 7095
3432 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
3433 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
3434 13 return $self->set_model_pricing($model, $pricing);
3435 }
3436 7082 ▶ if ($name eq 'nodes.add') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.add") 3 7079 7082
3437 3 ▶ return { ok => $self->add_node(%$args) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->add_node(%$args) ? : 1 0 1
3438 }
3439 7079 ▶ if ($name eq 'nodes.remove') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.remove") 0 7079 7079
3440 0 ▶ return { ok => $self->remove_node($args->{id}) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->remove_node($args->{'id'}) ? : 0 0 0
3441 }
3442 7079 ▶ if ($name eq 'nodes.list') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.list") 250 6829 7079
3443 250 return { nodes => $self->list_nodes };
3444 }
3445 6829 ▶ if ($name eq 'nodes.select') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.select") 0 6829 6829
3446 0 return { nodes => $self->select_nodes(tags => $args->{tags}, deny_tags => $args->{deny_tags}) };
3447 }
3448 6829 ▶ if ($name eq 'alias.set') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "alias.set") 0 6829 6829
3449 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
3450 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
3451 }
3452 6829 ▶ if ($name eq 'route.plan') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "route.plan") 1071 5758 6829
3453 return $self->route_plan(
3454 model => ($args->{model} // ''),
3455 engine => $args->{engine},
3456 api_key_id => $args->{api_key_id},
3457 kind => $args->{kind},
3458 1071 ▶ );
Condition50%1/2
$args->{"model"} // ""
l!l
10710
MC/DC0%0/1
$args->{"model"} // ""
$args->{"model"}
Truth table50%1/2
A
A= $args->{"model"}
Aresult
11
00
3459 }
3460 5758 ▶ if ($name eq 'policy.set') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "policy.set") 0 5758 5758
3461 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
3462 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
3463 }
3464 5758 ▶ if ($name eq 'policy.for_key') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "policy.for_key") 0 5758 5758
3465 0 return { policy => $self->policy_for_key($args->{api_key_id}) };
3466 }
3467 5758 ▶ if ($name eq 'nodes.set_health') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.set_health") 17 5741 5758
3468 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
3469 }
3470 5741 ▶ if ($name eq 'nodes.metrics') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.metrics") 1 5740 5741
3471 1 return { metrics => $self->node_metrics($args->{id}) };
3472 }
3473 5740 ▶ if ($name eq 'engines.list') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "engines.list") 0 5740 5740
3474 0 return { engines => $self->supported_engine_ids };
3475 }
3476 5740 ▶ if ($name eq 'route.next') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "route.next") 1254 4486 5740
3477 my $node = $self->pick_node(
3478 model => ($args->{model} // ''),
3479 engine => $self->normalize_engine_id($args->{engine} // ''),
3480 tags => $args->{tags},
3481 deny_tags => $args->{deny_tags},
3482 kind => $args->{kind},
3483 1254 ▶ );
Condition50%2/4
$args->{"model"} // ""
l!l
12540
$args->{"engine"} // ""
l!l
01254
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
3484 1254 return { node => $node };
3485 }
3486 4486 ▶ if ($name eq 'route.state') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "route.state") 1302 3184 4486
3487 1302 ▶ my $engine = $self->normalize_engine_id($args->{engine} // '');
Condition50%1/2
$args->{"engine"} // ""
l!l
01302
MC/DC0%0/1
$args->{"engine"} // ""
$args->{"engine"}
Truth table50%1/2
A
A= $args->{"engine"}
Aresult
11
00
3488 return $self->route_state(
3489 model => ($args->{model} // ''),
3490 engine => $engine,
3491 tags => $args->{tags},
3492 deny_tags => $args->{deny_tags},
3493 kind => $args->{kind},
3494 1302 ▶ );
Condition50%1/2
$args->{"model"} // ""
l!l
13020
MC/DC0%0/1
$args->{"model"} // ""
$args->{"model"}
Truth table50%1/2
A
A= $args->{"model"}
Aresult
11
00
3495 }
3496 3184 ▶ if ($name eq 'capacity.set') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "capacity.set") 0 3184 3184
3497 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
3498 0 return { capacity => $self->set_capacity_reading($id, %$args) };
3499 }
3500 3184 ▶ if ($name eq 'capacity.get') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "capacity.get") 0 3184 3184
3501 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
3502 0 return { capacity => $self->capacity_reading($id) };
3503 }
3504 3184 ▶ if ($name eq 'capacity.observe') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "capacity.observe") 7 3177 3184
3505 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
3506 return { capacity => $self->observe_response_headers(
3507 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
3508 }
3509 3177 ▶ if ($name eq 'capacity.forget') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "capacity.forget") 0 3177 3177
3510 0 ▶ return { ok => $self->forget_capacity($args->{id}) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->forget_capacity($args->{'id'}) ? : 0 0 0
3511 }
3512 3177 ▶ if ($name eq 'request.start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "request.start") 1000 2177 3177
3513 1000 ▶ my $id = $args->{id} // croak 'request.start: id required';
Condition50%1/2
$args->{"id"} // croak("request.start: id required")
l!l
10000
MC/DC0%0/1
$args->{"id"} // croak("request.start: id required")
$args->{"id"}
Truth table50%1/2
A
A= $args->{"id"}
Aresult
11
00
3514 1000 ▶ return { ok => $self->start_request($id) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->start_request($id) ? : 1000 0 1000
3515 }
3516 2177 ▶ if ($name eq 'request.finish') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "request.finish") 999 1178 2177
3517 999 ▶ my $id = $args->{id} // croak 'request.finish: id required';
Condition50%1/2
$args->{"id"} // croak("request.finish: id required")
l!l
9990
MC/DC0%0/1
$args->{"id"} // croak("request.finish: id required")
$args->{"id"}
Truth table50%1/2
A
A= $args->{"id"}
Aresult
11
00
3518 999 ▶ return { ok => $self->finish_request($id, %$args) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->finish_request($id, %$args) ? : 999 0 999
3519 }
3520 1178 ▶ if ($name eq 'config.reload') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "config.reload") 1 1177 1178
3521 1 return { config => $self->reload_config };
3522 }
3523 1177 ▶ if ($name eq 'config.status') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "config.status") 9 1168 1177
3524 9 return $self->reload_status;
3525 }
3526 1168 ▶ if ($name eq 'usage.record') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "usage.record") 1124 44 1168
3527 1124 return $self->record_usage(%$args);
3528 }
3529 44 ▶ if ($name eq 'usage.report') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "usage.report") 43 1 44
3530 43 return $self->usage_report(%$args);
3531 }
3532 1 ▶ if ($name eq 'usage.configure') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "usage.configure") 1 0 1
3533 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
3534 1 return { usage_store => $self->configure_usage_store($store) };
3535 }
3536  
3537 0 croak "unknown function: $name";
3538 }
3539  
3540 627 ▶sub DEMOLISH {
Subroutine DEMOLISH: called CC=2 SCAR=7.1
Pod undocumented
3541 627 my ($self, $global) = @_;
3542 # The customer source's timers hold only weak references; this takes them off the loop.
3543 627 ▶ $self->_stop_source_controller unless $global;
Branch: 1 branch
BranchTrueFalseTotal
unless $global 627 0 627
3544 627 $self->_disconnect_usage_store;
3545 }
3546  
3547 696 ▶sub _disconnect_usage_store {
Subroutine _disconnect_usage_store: called CC=2 SCAR=6.9
3548 696 my ($self) = @_;
3549 696 ▶ my $store = $self->_usage_store_obj or return;
Branch: 1 branch
BranchTrueFalseTotal
my $store = $self->_usage_store_obj or return 67 629 696
3550 67 $store->disconnect;
3551 67 $self->_usage_store_obj(undef);
3552 67 return;
3553 }
3554  
3555  
3556 113 1;
3557  
3558 __END__
« lib/Langertha/Skeid/Protocol/Anthropic.pm ↑ Summary lib/Langertha/Skeid/UsageStore/JsonLog.pm »