lib/Langertha/Skeid/Proxy.pm

filter: Statementstmt 98.0% 1557 / 1588 Branchbran 88.8% 700 / 788 Conditioncond 67.0% 517 / 771 MC/DCmcdc 41.6% 174 / 418 Subroutinesub 97.7% 215 / 220 Podpod 100% 2 / 2 totaltotal 83.5% 3165 / 3787 CC 719 SCAR 27.5
CC
719
Cov
88%
__ANON__
90.0
_record_usage_event
62.1
__ANON__
42.1
CRAP 15.6
« lib/Langertha/Skeid/Protocol/Ollama.pm ↑ Summary lib/Langertha/Skeid/Registry.pm »
1 package Langertha::Skeid::Proxy;
2 99 our $VERSION = '0.005';
3 # ABSTRACT: Multi-format LLM proxy (OpenAI, Anthropic, Ollama) powered by Langertha::Skeid routing
4 99 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 99 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 99 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 99 ▶use Mojolicious;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 99 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 99 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 99 ▶use JSON::MaybeXS qw(decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 99 ▶use Scalar::Util qw(blessed weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 99 ▶use Mojo::Util qw(decode encode);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 99 ▶use Langertha::Skeid;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 99 ▶use Langertha::Skeid::CapacityProbe;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 99 ▶use Langertha::Skeid::OpenAPI;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 99 ▶use Langertha::Skeid::Registry;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 99 ▶use Langertha::Skeid::SwaggerUI;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 99 ▶use Langertha::Skeid::Secret;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 99 ▶use Langertha::Skeid::Proxy::Realtime;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 99 ▶use Langertha::Skeid::Proxy::RelayContent;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 99 ▶use Langertha::Skeid::Protocol;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 99 ▶use Langertha::Skeid::Protocol::Anthropic;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 99 ▶use Langertha::Skeid::Protocol::Anthropic::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 99 ▶use Langertha::Skeid::Protocol::Audio;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 99 ▶use Langertha::Skeid::Protocol::Documents;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 99 ▶use Langertha::Skeid::Protocol::MCP;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 99 ▶use Langertha::Skeid::Protocol::Ollama;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 99 ▶use Langertha::Skeid::Protocol::Ollama::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 99 ▶use Langertha::Skeid::Protocol::RawBody;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 99 ▶use Langertha::Skeid::Protocol::Realtime;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 99 ▶use Langertha::Skeid::Protocol::Rerank;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 99 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
33  
34  
35 # What the request limit of an upload route allows on top of uploads.max_bytes (skeid k91): the
36 # request's head, which the server counts into its message size and caps well below this itself
37 # (100 lines of 8 KiB). The body alone is checked exactly when the route runs.
38 99 my $UPLOAD_HEAD_ALLOWANCE = 1048576;
39  
40 552 ▶sub build_app {
Subroutine build_app: called CC=31 SCAR=36.6
Pod documented
41 552 my ($class, %opts) = @_;
42  
43 # Auto-detect OpenBao KeyBroker: a token file (skeid k127), or AppRole credentials.
44 552 ▶ my @skeid_opts = ($opts{config_file} ? (config_file => $opts{config_file}) : ());
Branch: 1 branch
BranchTrueFalseTotal
$opts{'config_file'} ? : 2 550 552
45 552 ▶ if (defined($ENV{OPENBAO_TOKEN_FILE}) && length($ENV{OPENBAO_TOKEN_FILE})) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $ENV{'OPENBAO_TOKEN_FILE'} and length $ENV{'OPENBAO_TOKEN_FILE'}) { } 3 549 552
elsif ($ENV{'OPENBAO_ROLE_ID'} and $ENV{'OPENBAO_SECRET_ID'}) { } 0 1098 1098
Condition66%2/3
defined $ENV{"OPENBAO_TOKEN_FILE"} and length $ENV{"OPENBAO_TOKEN_FILE"}
!ll&&!rl&&r
54903
MC/DC50%1/2
defined $ENV{"OPENBAO_TOKEN_FILE"} and length $ENV{"OPENBAO_TOKEN_FILE"}
defined $ENV{"OPENBAO_TOKEN_FILE"} length $ENV{"OPENBAO_TOKEN_FILE"}
Truth table66%2/3
A and B
A= defined $ENV{"OPENBAO_TOKEN_FILE"}B= length $ENV{"OPENBAO_TOKEN_FILE"}
ABresult
0X0
100
111
46 # Loud, not a warning: a process told to take its token from a file that does not work must
47 # not start without keys, and must not quietly use AppRole values someone also left set.
48 die "OPENBAO_TOKEN_FILE and OPENBAO_ROLE_ID/OPENBAO_SECRET_ID are both set; set one\n"
49 3 ▶ if $ENV{OPENBAO_ROLE_ID} || $ENV{OPENBAO_SECRET_ID};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"OPENBAO_ROLE_ID"} or $ENV{"OPENBAO_SECRET_ID"} 1 2 3
Condition66%2/3
$ENV{"OPENBAO_ROLE_ID"} or $ENV{"OPENBAO_SECRET_ID"}
l!l&&r!l&&!r
102
MC/DC50%1/2
$ENV{"OPENBAO_ROLE_ID"} or $ENV{"OPENBAO_SECRET_ID"}
$ENV{"OPENBAO_ROLE_ID"} $ENV{"OPENBAO_SECRET_ID"}
Truth table66%2/3
A or B
A= $ENV{"OPENBAO_ROLE_ID"}B= $ENV{"OPENBAO_SECRET_ID"}
ABresult
1X1
011
000
50 2 require Langertha::Skeid::KeyBroker::OpenBao;
51 push @skeid_opts, key_broker => Langertha::Skeid::KeyBroker::OpenBao->new(
52 addr => $ENV{OPENBAO_ADDR} // 'http://127.0.0.1:8200',
53 token_file => $ENV{OPENBAO_TOKEN_FILE},
54 2 ▶ );
Condition50%1/2
$ENV{"OPENBAO_ADDR"} // "http://127.0.0.1:8200"
l!l
20
MC/DC0%0/1
$ENV{"OPENBAO_ADDR"} // "http://127.0.0.1:8200"
$ENV{"OPENBAO_ADDR"}
Truth table50%1/2
A
A= $ENV{"OPENBAO_ADDR"}
Aresult
11
00
55 ▶ } elsif ($ENV{OPENBAO_ROLE_ID} && $ENV{OPENBAO_SECRET_ID}) {
Condition33%1/3
$ENV{"OPENBAO_ROLE_ID"} and $ENV{"OPENBAO_SECRET_ID"}
!ll&&!rl&&r
54900
MC/DC0%0/2
$ENV{"OPENBAO_ROLE_ID"} and $ENV{"OPENBAO_SECRET_ID"}
$ENV{"OPENBAO_ROLE_ID"} $ENV{"OPENBAO_SECRET_ID"}
Truth table33%1/3
A and B
A= $ENV{"OPENBAO_ROLE_ID"}B= $ENV{"OPENBAO_SECRET_ID"}
ABresult
0X0
100
111
56 0 eval {
57 0 require Langertha::Skeid::KeyBroker::OpenBao;
58 push @skeid_opts, key_broker => Langertha::Skeid::KeyBroker::OpenBao->new(
59 addr => $ENV{OPENBAO_ADDR} // 'http://127.0.0.1:8200',
60 role_id => $ENV{OPENBAO_ROLE_ID},
61 secret_id => $ENV{OPENBAO_SECRET_ID},
62 0 ▶ );
Condition0%0/2
$ENV{"OPENBAO_ADDR"} // "http://127.0.0.1:8200"
l!l
00
MC/DC0%0/1
$ENV{"OPENBAO_ADDR"} // "http://127.0.0.1:8200"
$ENV{"OPENBAO_ADDR"}
Truth table0%0/2
A
A= $ENV{"OPENBAO_ADDR"}
Aresult
11
00
63 };
64 0 ▶ warn "Failed to initialize OpenBao KeyBroker: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
65 }
66  
67 # The explicit admin API key goes into new(), so it is in force for the first config already
68 # (a registry block checks for it); an existing Skeid gets it set (skeid k64).
69 push @skeid_opts, admin_api_key => $opts{admin_api_key}
70 550 ▶ if defined($opts{admin_api_key}) && length($opts{admin_api_key});
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"admin_api_key"} and length $opts{"admin_api_key"} 7 543 550
Condition66%2/3
defined $opts{"admin_api_key"} and length $opts{"admin_api_key"}
!ll&&!rl&&r
54307
MC/DC50%1/2
defined $opts{"admin_api_key"} and length $opts{"admin_api_key"}
defined $opts{"admin_api_key"} length $opts{"admin_api_key"}
Truth table66%2/3
A and B
A= defined $opts{"admin_api_key"}B= length $opts{"admin_api_key"}
ABresult
0X0
100
111
71 550 ▶ my $skeid = $opts{skeid} || Langertha::Skeid->new(@skeid_opts);
Condition100%3/3
$opts{'skeid'} || 'Langertha::Skeid'->new(@skeid_opts)
l!l&&r!l&&!r
54721
MC/DC0%0/2
$opts{'skeid'} || 'Langertha::Skeid'->new(@skeid_opts)
$opts{'skeid'} 'Langertha::Skeid'->new(@skeid_opts)
Truth table66%2/3
A || B
A= $opts{'skeid'}B= 'Langertha::Skeid'->new(@skeid_opts)
ABresult
1X1
011
000
72 549 ▶ $skeid->set_admin_api_key($opts{admin_api_key}) if exists $opts{admin_api_key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"admin_api_key"} 7 542 549
73 # How many processes share these nodes. Set before anything reads max_conns or starts a
74 # timer, since both are divided by it (ADR 0010).
75 549 ▶ if (defined $opts{worker_count} && $opts{worker_count} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"worker_count"} and $opts{"worker_count"} > 0) 0 549 549
Condition33%1/3
defined $opts{"worker_count"} and $opts{"worker_count"} > 0
!ll&&!rl&&r
54900
MC/DC0%0/2
defined $opts{"worker_count"} and $opts{"worker_count"} > 0
defined $opts{"worker_count"} $opts{"worker_count"} > 0
Truth table33%1/3
A and B
A= defined $opts{"worker_count"}B= $opts{"worker_count"} > 0
ABresult
0X0
100
111
76 0 $skeid->worker_count(0 + $opts{worker_count});
77 }
78  
79 # Renew the vault token on a timer rather than when a request discovers it expired. A request
80 # that has to renew first pays the round-trip in its own latency, and it is the request least
81 # able to afford it -- the first one after a quiet period.
82 549 ▶ if ($skeid->has_key_broker && $skeid->key_broker->can('start_renewal')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skeid->has_key_broker and $skeid->key_broker->can("start_renewal")) 1 548 549
Condition100%3/3
$skeid->has_key_broker and $skeid->key_broker->can("start_renewal")
!ll&&!rl&&r
464841
MC/DC100%2/2
$skeid->has_key_broker and $skeid->key_broker->can("start_renewal")
$skeid->has_key_broker $skeid->key_broker->can("start_renewal")
Truth table100%3/3
A and B
A= $skeid->has_key_brokerB= $skeid->key_broker->can("start_renewal")
ABresult
0X0
100
111
83 1 $skeid->key_broker->start_renewal;
84 }
85  
86 # Capacity probes (ADR 0009). Held by the app, because a probe that goes out of scope stops
87 # polling. Nodes with no capacity block get none, which is plain inflight admission.
88 549 my $probes = Langertha::Skeid::CapacityProbe->start_for_skeid($skeid);
89 549 my $probe_key = $skeid->_probe_inventory_key;
90  
91 # The customer source's fetcher (ADR 0026): on the loop, never on the request path. Its
92 # connections open with the first fetch, in the process that runs the loop.
93 549 $skeid->start_customer_source;
94  
95 549 my $app = Mojolicious->new;
96 549 $app->secrets(['skeid-proxy']);
97  
98 # A write-behind usage store (usage_store.flush_interval_ms) writes after the request was
99 # answered, so its failures cannot come back through _record_usage_event; they come here and
100 # get the same log line (skeid k78). Weak: the app holds the skeid, the skeid holds this.
101 549 weaken(my $weak_app = $app);
102 1 ▶ $skeid->on_usage_lost(sub {
Subroutine __ANON__: called CC=4 SCAR=22.5
103 1 my ($skeid, $event, $err) = @_;
104 1 ▶ return _log_lost_usage_event($weak_app, $skeid, $event, $err) if $weak_app;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_app 1 0 1
105 0 ▶ warn 'skeid: usage event lost: request_id=' . ($event->{request_id} // '') . ': '
Condition0%0/4
$event->{"request_id"} // ""
l!l
00
$err // "unknown error"
l!l
00
MC/DC0%0/1
$event->{"request_id"} // ""
$event->{"request_id"}
MC/DC0%0/1
$err // "unknown error"
$err
Truth table0%0/2
A
A= $event->{"request_id"}
Aresult
11
00
Truth table0%0/2
A
A= $err
Aresult
11
00
106 . ($err // 'unknown error') . "\n";
107 0 return;
108 549 });
109 549 $app->ua->connect_timeout(10);
110 # One number for how long an upstream may take and how long it may be silent: a model that
111 # thinks sends nothing until its first token, and Mojo::UserAgent closes a connection that
112 # was silent for 40s whatever the request timeout allows. The client's side follows the same
113 # number per request, see _extend_client_timeout.
114 my $upstream_timeout
115 = (defined($ENV{SKEID_UPSTREAM_TIMEOUT}) && $ENV{SKEID_UPSTREAM_TIMEOUT} =~ /^\d+$/
116 && $ENV{SKEID_UPSTREAM_TIMEOUT} > 0)
117 ? 0 + $ENV{SKEID_UPSTREAM_TIMEOUT}
118 549 ▶ : 300;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_UPSTREAM_TIMEOUT'} && $ENV{'SKEID_UPSTREAM_TIMEOUT'} =~ /^\d+$/ && $ENV{'SKEID_UPSTREAM_TIMEOUT'} > 0 ? : 1 548 549
Condition100%6/6
defined $ENV{"SKEID_UPSTREAM_TIMEOUT"} and $ENV{"SKEID_UPSTREAM_TIMEOUT"} =~ /^\d+$/ and $ENV{"SKEID_UPSTREAM_TIMEOUT"} > 0
!ll&&!rl&&r
54711
defined $ENV{"SKEID_UPSTREAM_TIMEOUT"} and $ENV{"SKEID_UPSTREAM_TIMEOUT"} =~ /^\d+$/
!ll&&!rl&&r
54342
MC/DC100%3/3
defined $ENV{"SKEID_UPSTREAM_TIMEOUT"} and $ENV{"SKEID_UPSTREAM_TIMEOUT"} =~ /^\d+$/ and $ENV{"SKEID_UPSTREAM_TIMEOUT"} > 0
defined $ENV{"SKEID_UPSTREAM_TIMEOUT"} $ENV{"SKEID_UPSTREAM_TIMEOUT"} =~ /^\d+$/ $ENV{"SKEID_UPSTREAM_TIMEOUT"} > 0
Truth table100%4/4
A and B and C
A= defined $ENV{"SKEID_UPSTREAM_TIMEOUT"}B= $ENV{"SKEID_UPSTREAM_TIMEOUT"} =~ /^\d+$/C= $ENV{"SKEID_UPSTREAM_TIMEOUT"} > 0
ABCresult
0XX0
10X0
1100
1111
119 549 $app->ua->request_timeout($upstream_timeout);
120 549 $app->ua->inactivity_timeout($upstream_timeout);
121 # Mojo::UserAgent pools 5 upstream connections by default. A proxy serving more concurrent
122 # requests than that reconnects for the surplus on every request, which shows up as latency
123 # that grows with concurrency for no visible reason. Sized for the concurrency a single
124 # Skeid process can actually sustain, not for the number of nodes.
125 $app->ua->max_connections(
126 (defined($ENV{SKEID_UPSTREAM_POOL}) && $ENV{SKEID_UPSTREAM_POOL} =~ /^\d+$/)
127 ? 0 + $ENV{SKEID_UPSTREAM_POOL}
128 549 ▶ : 100
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_UPSTREAM_POOL'} && $ENV{'SKEID_UPSTREAM_POOL'} =~ /^\d+$/ ? : 0 549 549
Condition33%1/3
defined $ENV{"SKEID_UPSTREAM_POOL"} and $ENV{"SKEID_UPSTREAM_POOL"} =~ /^\d+$/
!ll&&!rl&&r
54900
MC/DC0%0/2
defined $ENV{"SKEID_UPSTREAM_POOL"} and $ENV{"SKEID_UPSTREAM_POOL"} =~ /^\d+$/
defined $ENV{"SKEID_UPSTREAM_POOL"} $ENV{"SKEID_UPSTREAM_POOL"} =~ /^\d+$/
Truth table33%1/3
A and B
A= defined $ENV{"SKEID_UPSTREAM_POOL"}B= $ENV{"SKEID_UPSTREAM_POOL"} =~ /^\d+$/
ABresult
0X0
100
111
129 );
130 549 ▶ $app->helper(skeid => sub { $skeid });
Subroutine __ANON__: called CC=1 SCAR=0.0
131 # The open realtime sessions of this app (skeid k95, ADR 0029): what a graceful stop closes.
132 549 my $realtime = Langertha::Skeid::Proxy::Realtime->new(skeid => $skeid, log => $app->log);
133 549 ▶ $app->helper(realtime => sub { $realtime });
Subroutine __ANON__: called CC=1 SCAR=0.0
134  
135 # A config reload replaces the whole inventory, so probes have to follow it or they keep
136 # polling for nodes that are gone and never start for new ones. They follow the probe key,
137 # not the inventory generation: a health flip moves the generation but not what a probe
138 # polls, and a restart makes every probe forget its own reading (skeid #40) -- readings from
139 # other sources, such as a rate-limit backoff, survive it. The key is recomputed only when the
140 # generation has moved, so an unchanged inventory costs an integer compare per request.
141 2413 ▶ $app->hook(before_dispatch => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
142 2413 my $key = $skeid->_probe_inventory_key;
143 2413 ▶ return if $key eq $probe_key;
Branch: 1 branch
BranchTrueFalseTotal
if $key eq $probe_key 2408 5 2413
144 5 $probe_key = $key;
145 5 $_->stop for values %$probes;
146 5 $probes = Langertha::Skeid::CapacityProbe->start_for_skeid($skeid);
147 549 });
148  
149 # The request's id is fixed here, before anything can fail or hang up: the client gets it back
150 # as x-request-id whatever the answer turns out to be, and the usage event and the lost-event
151 # log line carry the same one. It lives in the stash because a request whose client is gone
152 # has no transaction to read it from any more.
153 2413 ▶ $app->hook(before_dispatch => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
154 2413 my ($c) = @_;
155 2413 my $id = _request_id($c);
156 2413 $c->stash('skeid.request_id' => $id);
157 2413 $c->res->headers->header('x-request-id' => $id);
158 549 });
159  
160 # The upload routes get their own request limit (uploads.max_bytes, skeid k91), set the moment
161 # the request's head is parsed and before any of its body is: see _limit_upload. The
162 # transaction is held weakly -- the listener sits on its own request content, and a connection
163 # that closes before the head is complete would otherwise keep both alive.
164 2493 ▶ $app->hook(after_build_tx => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
165 2493 my ($tx, $app) = @_;
166 2493 weaken $tx;
167 2493 ▶ $tx->req->content->once(body => sub { _limit_upload($app, $tx) if $tx });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $tx 2378 0 2378
168 549 });
169  
170 # Swagger UI assets: fetched on the first request for the UI, only when the config switches
171 # it on (skeid k105, ADR 0025). Nothing is fetched at build. The object is injectable (the
172 # swagger_ui option of build_app) so a test never reaches the network.
173 549 ▶ my $swagger_ui = $opts{swagger_ui} || Langertha::Skeid::SwaggerUI->new;
Condition66%2/3
$opts{'swagger_ui'} || 'Langertha::Skeid::SwaggerUI'->new
l!l&&r!l&&!r
105390
MC/DC0%0/2
$opts{'swagger_ui'} || 'Langertha::Skeid::SwaggerUI'->new
$opts{'swagger_ui'} 'Langertha::Skeid::SwaggerUI'->new
Truth table66%2/3
A || B
A= $opts{'swagger_ui'}B= 'Langertha::Skeid::SwaggerUI'->new
ABresult
1X1
011
000
174 549 ▶ $app->helper(swagger_ui => sub { $swagger_ui });
Subroutine __ANON__: called CC=1 SCAR=0.0
175  
176 # Every route is registered from route_table, and the OpenAPI documents are built from the
177 # same entries: a route without an entry cannot exist, which t/78-route-table.t proves by
178 # walking the router. A group names the bridge the entry sits behind. Bridges are made when
179 # the first entry of their group comes, so the order of the table is the order of matching.
180 #
181 # Client routes sit behind _authorize_client (skeid k90): a bridge, so only these routes are
182 # gated and an unknown path stays a 404. Each face's bridge sets what its 401 needs before the
183 # gate can render it -- the error dialect, the manifest's cache headers.
184 549 my $r = $app->routes;
185 my %make_bridge = (
186 549 ▶ root => sub { $r },
Subroutine __ANON__: called CC=1 SCAR=0.0
187 549 ▶ manifest => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
188 32 ▶ $r->under(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
189 32 my ($c) = @_;
190 32 _manifest_cache_headers($c);
191 32 return _authorize_client($c);
192 549 });
193 },
194 549 ▶ openai => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
195 549 ▶ $r->under(sub { _authorize_client($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
196 },
197 # Every error this request produces, wherever it is rendered -- the gate's 401 included --
198 # has to be Anthropic-shaped (core karr #224). _render_error reads this.
199 549 ▶ anthropic => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
200 214 ▶ $r->under(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
201 214 my ($c) = @_;
202 214 $c->stash('skeid.error_format' => 'anthropic');
203 214 return _authorize_client($c);
204 549 });
205 },
206 # Every error on these routes has to be Ollama-shaped, {"error": "<string>"}: an Ollama
207 # client decodes the error as a string and fails on the OpenAI object (skeid #47).
208 549 ▶ ollama => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
209 317 ▶ $r->under(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
210 317 my ($c) = @_;
211 317 $c->stash('skeid.error_format' => 'ollama');
212 317 return _authorize_client($c);
213 549 });
214 },
215 # The MCP bridge answers as an unknown path while the config has no mcp: section, before
216 # the client gate can turn that 404 into a 401.
217 549 ▶ mcp => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
218 549 ▶ $r->under(sub { _authorize_mcp_client($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
219 },
220 549 ▶ admin => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
221 549 ▶ $r->under(sub { _authorize_admin($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
222 },
223 549 );
224 549 my %bridge;
225 549 for my $entry ($class->route_table) {
226 my $make = $make_bridge{$entry->{group}}
227 18666 ▶ or croak "route table: unknown group '$entry->{group}' of $entry->{id}";
Branch: 1 branch
BranchTrueFalseTotal
my $make = $make_bridge{$entry->{"group"}} or croak(qq[route table: unknown group '$entry->{"group"}' of $entry->{"id"}]) 18666 0 18666
228 18666 ▶ my $parent = $bridge{$entry->{group}} //= $make->();
Condition66%2/3
$bridge{$entry->{"group"}} //= &$make()
l!l&&r!l&&!r
1482338430
MC/DC0%0/2
$bridge{$entry->{"group"}} //= &$make()
$bridge{$entry->{"group"}} &$make()
Truth table66%2/3
A //= B
A= $bridge{$entry->{"group"}}B= &$make()
ABresult
1X1
011
000
229 # A WebSocket route matches only an upgrade request (ADR 0029); everything else is as for
230 # any route: behind its group's bridge, so the client gate answers before an upgrade.
231 18666 ▶ if ($entry->{websocket}) { $parent->websocket($_ => $entry->{handler}) for @{$entry->{paths}} }
Branch: 1 branch
BranchTrueFalseTotal
if ($entry->{'websocket'}) { } 549 18117 18666
232 18117 else { $parent->any($entry->{methods} => $_ => $entry->{handler}) for @{$entry->{paths}} }
233 }
234  
235 549 return $app;
236 }
237  
238  
239 99 my @ROUTE_TABLE;
240  
241 567 ▶sub route_table {
Subroutine route_table: called CC=2 SCAR=6.9
Pod documented
242 567 my ($class) = @_;
243 567 ▶ @ROUTE_TABLE = $class->_build_route_table unless @ROUTE_TABLE;
Branch: 1 branch
BranchTrueFalseTotal
unless @ROUTE_TABLE 73 494 567
244 567 return @ROUTE_TABLE;
245 }
246  
247 73 ▶sub _build_route_table {
Subroutine _build_route_table: called CC=8 SCAR=21.4
248 73 my ($class) = @_;
249 73 my @t;
250 73 ▶ my $add = sub { push @t, { methods => ['GET'], document => 'client', @_ } };
Subroutine __ANON__: called CC=1 SCAR=0.0
251  
252 # Still 'ok' while a config reload is failing: the proxy serves under the config it kept, so
253 # it is not unhealthy, and a probe that restarted it would lose that config. The reload
254 # state is shown without its message, which can name customers; that is on /skeid/config.
255 $add->(id => 'health', group => 'root', paths => ['/health'], tag => 'Service', public => 1,
256 summary => 'Liveness and config reload state',
257 54 ▶ handler => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
258 54 my ($c) = @_;
259 54 my $reload = $c->skeid->reload_status;
260 54 delete $reload->{error};
261 # The customer source likewise: whether it fetches, never why not (ADR 0026).
262 54 my $source = $c->skeid->customer_source_status;
263 $source &&= {
264 ok => $source->{ok},
265 54 ▶ ($source->{failures} ? (failed_at => $source->{failed_at}, failures => $source->{failures}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$source->{'failures'} ? : 1 2 3
Condition100%2/2
$source &&= {"ok", $source->{"ok"}, $source->{"failures"} ? ("failed_at", $source->{"failed_at"}, "failures", $source->{"failures"}) : ()}
!ll
513
MC/DC100%1/1
$source &&= {"ok", $source->{"ok"}, $source->{"failures"} ? ("failed_at", $source->{"failed_at"}, "failures", $source->{"failures"}) : ()}
$source
Truth table100%2/2
A
A= $source
Aresult
00
11
266 };
267 54 ▶ $c->render(json => { status => 'ok', proxy => 'skeid', config_reload => $reload,
Branch: 1 branch
BranchTrueFalseTotal
$source ? : 3 51 54
268 ($source ? (customer_source => $source) : ()) });
269 73 });
270  
271 # Provider manifest (skeid #29, ADR 0015): per customer key, never the whole catalog.
272 $add->(id => 'manifest', group => 'manifest', paths => ['/.well-known/langertha.json'],
273 tag => 'Manifest', requires => 'manifest',
274 summary => 'Provider manifest for the presented key',
275 73 ▶ handler => sub { _handle_manifest($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
276  
277 # OpenAI format
278 $add->(id => 'models', group => 'openai', paths => ['/v1/models'], tag => 'OpenAI',
279 summary => 'List the models this key may use', response => 'ModelList',
280 27 ▶ handler => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
281 27 my ($c) = @_;
282 my @data = map {
283 +{
284 id => $_->{model},
285 37 object => 'model',
286 created => int(time),
287 owned_by => 'skeid',
288 }
289 27 } @{$c->skeid->list_models(api_key_id => _request_api_key_id($c))};
290 27 $c->render(json => { object => 'list', data => \@data });
291 73 });
292  
293 $add->(id => 'chat_completions', group => 'openai', methods => ['POST'],
294 paths => ['/v1/chat/completions'], tag => 'OpenAI', request => 'ChatCompletionRequest',
295 stream => 1, summary => 'Chat completion',
296 73 ▶ handler => sub { _handle_openai_chat($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
297  
298 $add->(id => 'embeddings', group => 'openai', methods => ['POST'], paths => ['/v1/embeddings'],
299 tag => 'OpenAI', request => 'EmbeddingsRequest', summary => 'Embeddings',
300 73 ▶ handler => sub { _handle_openai_embeddings($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
301  
302 # Audio (skeid k91): relayed in the upstream's own shape, not translated (ADR 0021).
303 73 for my $endpoint (Langertha::Skeid::Protocol::Audio->routes) {
304 146 (my $id = $endpoint) =~ s{[^A-Za-z0-9]+}{_}g;
305 $add->(id => 'audio' . $id, group => 'openai', methods => ['POST'], paths => [$endpoint],
306 tag => 'OpenAI', request => 'AudioRequest', request_type => 'multipart', stream => 1,
307 summary => 'Audio ' . ($endpoint =~ /translations/ ? 'translation' : 'transcription'),
308 description => 'Relayed to the node as the multipart form was sent; the answer is the node\'s own.',
309 146 ▶ handler => sub { _handle_openai_audio($_[0], $endpoint) });
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$endpoint =~ /translations/ ? : 73 73 146
310 }
311  
312 # Rerank (skeid k92): /v1/rerank and its alias /rerank, one route. Relayed like audio, except
313 # to a node whose rerank_format names another upstream dialect.
314 73 for my $endpoint (Langertha::Skeid::Protocol::Rerank->routes) {
315 146 (my $id = $endpoint) =~ s{[^A-Za-z0-9]+}{_}g;
316 $add->(id => 'rerank' . $id, group => 'openai', methods => ['POST'], paths => [$endpoint],
317 tag => 'OpenAI', request => 'RerankRequest', summary => 'Rerank documents',
318 146 ▶ handler => sub { _handle_openai_rerank($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
319 }
320  
321 # Documents (skeid k94, ADR 0028): docling-serve's synchronous conversion, under its own paths.
322 # Relayed like audio; planned over the nodes of kind `documents`, not by a model name.
323 73 for my $endpoint (Langertha::Skeid::Protocol::Documents->routes) {
324 146 my $file = $endpoint =~ /file\z/;
325 146 (my $id = $endpoint) =~ s{[^A-Za-z0-9]+}{_}g;
326 $add->(id => 'documents' . $id, group => 'openai', methods => ['POST'], paths => [$endpoint],
327 tag => 'Documents', summary => 'Convert ' . ($file ? 'uploaded files' : 'sources') . ' to a document',
328 request => ($file ? 'DocumentsFileRequest' : 'DocumentsSourceRequest'),
329 ($file ? (request_type => 'multipart') : ()),
330 description => 'docling-serve\'s own call, relayed to a node of kind documents; the answer '
331 . '(JSON, or a zip) is the node\'s. Authorised under the model name documents.',
332 146 ▶ handler => sub { _handle_documents($_[0], $endpoint) });
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 3 branches
BranchTrueFalseTotal
$file ? : 73 73 146
$file ? : 73 73 146
$file ? : 73 73 146
333 }
334  
335 # Realtime transcription (skeid k95, ADR 0029): a WebSocket, relayed as a session. Not a
336 # request/answer route, so it has its own handler and not a $relay of the proxy functions.
337 $add->(id => 'realtime', group => 'openai', paths => [Langertha::Skeid::Protocol::Realtime->route],
338 tag => 'OpenAI', websocket => 1,
339 query => [
340 { name => 'model', required => 1, description => 'The model of the session; the key\'s policy applies to it.' },
341 { name => 'intent', description => 'Passed to the node, as sent (transcription).' },
342 ],
343 summary => 'Realtime transcription (WebSocket)',
344 description => 'Upgrades to a WebSocket relayed to the node\'s realtime endpoint; the events of '
345 . 'both directions are the node\'s own, nothing is translated. A key can also be sent in the '
346 . '"openai-insecure-api-key.<key>" subprotocol, beside "realtime". One session holds one slot '
347 . 'of its node until it closes, and is recorded as one usage event.',
348 73 ▶ handler => sub { _handle_openai_realtime($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
349  
350 # The description of the client routes themselves. Behind the client gate like /v1/models:
351 # the examples carry model names, and those are per key.
352 $add->(id => 'openapi', group => 'openai', paths => ['/openapi.json'], tag => 'Service',
353 summary => 'This OpenAPI 3.1 document',
354 73 ▶ handler => sub { _handle_openapi($_[0], 'client') });
Subroutine __ANON__: called CC=1 SCAR=0.0
355  
356 # Anthropic format.
357 $add->(id => 'messages', group => 'anthropic', methods => ['POST'], paths => ['/v1/messages'],
358 tag => 'Anthropic', request => 'AnthropicMessagesRequest', stream => 1,
359 summary => 'Anthropic Messages',
360 73 ▶ handler => sub { _handle_anthropic_messages($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
361  
362 # Ollama format.
363 $add->(id => 'ollama_chat', group => 'ollama', methods => ['POST'], paths => ['/api/chat'],
364 tag => 'Ollama', request => 'OllamaChatRequest', stream => 1, summary => 'Ollama chat',
365 73 ▶ handler => sub { _handle_ollama($_[0], 'chat') });
Subroutine __ANON__: called CC=1 SCAR=0.0
366  
367 $add->(id => 'ollama_generate', group => 'ollama', methods => ['POST'], paths => ['/api/generate'],
368 tag => 'Ollama', request => 'OllamaGenerateRequest', stream => 1, summary => 'Ollama generate',
369 73 ▶ handler => sub { _handle_ollama($_[0], 'generate') });
Subroutine __ANON__: called CC=1 SCAR=0.0
370  
371 # Ollama embeddings (skeid k116): translated to the node's OpenAI /embeddings, like the chat face.
372 $add->(id => 'ollama_embed', group => 'ollama', methods => ['POST'], paths => ['/api/embed'],
373 tag => 'Ollama', request => 'OllamaEmbedRequest', summary => 'Ollama embeddings',
374 73 ▶ handler => sub { _handle_ollama_embeddings($_[0], 'embed') });
Subroutine __ANON__: called CC=1 SCAR=0.0
375  
376 $add->(id => 'ollama_embeddings', group => 'ollama', methods => ['POST'], paths => ['/api/embeddings'],
377 tag => 'Ollama', request => 'OllamaEmbeddingsRequest', summary => 'Ollama embeddings, one prompt (older route)',
378 73 ▶ handler => sub { _handle_ollama_embeddings($_[0], 'embeddings') });
Subroutine __ANON__: called CC=1 SCAR=0.0
379  
380 $add->(id => 'ollama_tags', group => 'ollama', paths => ['/api/tags'], tag => 'Ollama',
381 summary => 'The models this key may use, Ollama shaped',
382 15 ▶ handler => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
383 15 my ($c) = @_;
384 15 $c->render(json => Langertha::Skeid::Protocol::Ollama->tags_from_models(
385 $c->skeid->list_models(api_key_id => _request_api_key_id($c))));
386 73 });
387  
388 $add->(id => 'ollama_ps', group => 'ollama', paths => ['/api/ps'], tag => 'Ollama',
389 summary => 'Always an empty list',
390 73 ▶ handler => sub { $_[0]->render(json => { models => [] }) });
Subroutine __ANON__: called CC=1 SCAR=0.0
391  
392 # MCP gateway (skeid k103, ADR 0022): the MCP servers assigned to the presented key, listed
393 # and relayed. The relaxed placeholder takes a name with a dot in it; what follows the name
394 # is the sub-path, for an upstream with more than one endpoint.
395 $add->(id => 'mcp_servers', group => 'mcp', paths => [Langertha::Skeid::Protocol::MCP->listing_path],
396 tag => 'MCP', requires => 'mcp', summary => 'The MCP servers assigned to this key',
397 73 ▶ handler => sub { _handle_mcp_servers($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
398  
399 $add->(id => 'mcp_relay', group => 'mcp', methods => [qw( GET POST DELETE )],
400 paths => ['/mcp/#mcp_server', '/mcp/#mcp_server/*mcp_path'], tag => 'MCP', requires => 'mcp',
401 summary => 'Relay MCP Streamable HTTP to an assigned MCP server', stream => 1,
402 73 ▶ handler => sub { _handle_mcp($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
403  
404 # Skeid-to-Skeid registry (skeid #18, ADR 0017). Registered before the /skeid admin block so
405 # it is not behind _authorize_admin: it also takes the registry read key (skeid #49), which
406 # that block must never accept.
407 $add->(id => 'registry_snapshot', group => 'root', paths => ['/skeid/registry/snapshot'],
408 document => 'admin', requires => 'registry', tag => 'Registry',
409 summary => 'Signed capacity snapshot, for a fronting Skeid',
410 description => 'Takes the admin key or the registry read key. The body is signed in '
411 . 'X-Skeid-Registry-Signature.',
412 73 ▶ handler => sub { _handle_registry_snapshot($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
413  
414 # Lightweight admin API for live control-plane updates.
415 $add->(id => 'admin_nodes', group => 'admin', paths => ['/skeid/nodes'], document => 'admin',
416 tag => 'Admin', summary => 'List nodes', response => 'NodeList',
417 60 ▶ handler => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
418 60 my ($c) = @_;
419 60 $c->render(json => { nodes => $c->skeid->list_nodes });
420 73 });
421  
422 $add->(id => 'admin_nodes_add', group => 'admin', methods => ['POST'], paths => ['/skeid/nodes'],
423 document => 'admin', tag => 'Admin', summary => 'Add or replace a node',
424 1 ▶ handler => sub {
Subroutine __ANON__: called CC=5 SCAR=17.6
425 1 my ($c) = @_;
426 1 ▶ my $body = $c->req->json || {};
Condition50%1/2
$c->req->json || {}
l!l
10
MC/DC0%0/1
$c->req->json || {}
$c->req->json
Truth table50%1/2
A
A= $c->req->json
Aresult
11
00
427 1 my $ok = eval { $c->skeid->call_function('nodes.add', $body)->{ok} };
428 1 ▶ if (!$ok || $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ok or $@) 1 0 1
Condition33%1/3
not $ok or $@
l!l&&r!l&&!r
100
MC/DC0%0/2
not $ok or $@
not $ok $@
Truth table33%1/3
not(A) or B
A= not $okB= $@
ABresult
1X1
011
000
429 1 ▶ my $msg = $@ ? "$@" : 'invalid node payload';
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 1 0 1
430 1 $msg =~ s/\s+$//;
431 1 $c->render(json => { error => { message => $msg, type => 'invalid_request_error' } }, status => 400);
432 1 return;
433 }
434 0 $c->render(json => { ok => 1, nodes => $c->skeid->list_nodes });
435 73 });
436  
437 $add->(id => 'admin_node_health', group => 'admin', methods => ['POST'],
438 paths => ['/skeid/nodes/:id/health'], document => 'admin', tag => 'Admin',
439 summary => 'Set a node healthy or unhealthy',
440 16 ▶ handler => sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
441 16 my ($c) = @_;
442 16 ▶ my $body = $c->req->json || {};
Condition50%1/2
$c->req->json || {}
l!l
160
MC/DC0%0/1
$c->req->json || {}
$c->req->json
Truth table50%1/2
A
A= $c->req->json
Aresult
11
00
443 16 my $id = $c->param('id');
444 my $ok = $c->skeid->call_function('nodes.set_health', {
445 id => $id,
446 healthy => ($body->{healthy} ? 1 : 0),
447 16 ▶ })->{ok};
Branch: 1 branch
BranchTrueFalseTotal
$body->{'healthy'} ? : 6 10 16
448 16 ▶ $c->render(json => { ok => $ok ? 1 : 0 });
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 16 0 16
449 73 });
450  
451 $add->(id => 'admin_config', group => 'admin', paths => ['/skeid/config'], document => 'admin',
452 tag => 'Admin', summary => 'Config reload status',
453 15 ▶ handler => sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
454 15 my ($c) = @_;
455 15 my $reload = $c->skeid->call_function('config.status', {});
456 15 my $source = $c->skeid->customer_source_status;
457 15 my $node_files = $c->skeid->node_files_status;
458 15 my $catch_all = $c->skeid->catch_all;
459 $c->render(json => {
460 reload => $reload,
461 # The catch-all in effect (ADR 0033): the kinds configured, absent when there is none.
462 (%$catch_all ? (catch_all => {%$catch_all}) : ()),
463 # Each node's trust zone (ADR 0032): which nodes hear the client's headers.
464 24 ▶ nodes => [ map { +{ id => $_->{id}, trust => ($_->{trust} // 'external') } }
Condition50%1/2
$_->{"trust"} // "external"
l!l
240
MC/DC0%0/1
$_->{"trust"} // "external"
$_->{"trust"}
Truth table50%1/2
A
A= $_->{"trust"}
Aresult
11
00
465 15 ▶ @{$c->skeid->nodes} ],
Branch: 3 branches
BranchTrueFalseTotal
%$catch_all ? : 3 12 15
$node_files ? : 1 14 15
$source ? : 7 8 15
466 ($node_files ? (node_files => $node_files) : ()),
467 ($source ? (
468 customer_source => $source,
469 customer_names => $c->skeid->customer_names,
470 customer_report => $c->skeid->customer_report,
471 ) : ()),
472 });
473 73 });
474  
475 $add->(id => 'admin_metrics_nodes', group => 'admin', paths => ['/skeid/metrics/nodes'],
476 document => 'admin', tag => 'Admin', summary => 'Per-node counters',
477 0 ▶ handler => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
478 0 my ($c) = @_;
479 0 $c->render(json => { metrics => $c->skeid->node_metrics });
480 73 });
481  
482 $add->(id => 'admin_metrics_keys', group => 'admin', paths => ['/skeid/metrics/keys'],
483 document => 'admin', tag => 'Admin', summary => 'Per-key counters: requests refused for the key\'s rate',
484 1 ▶ handler => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
485 1 my ($c) = @_;
486 1 $c->render(json => { metrics => $c->skeid->key_metrics });
487 73 });
488  
489 # Erasure and retention (skeid k122): delete the usage events of a set of key ids, or before a
490 # time. Synchronous like the usage report: it is an operator call, not a request path.
491 $add->(id => 'admin_usage_purge', group => 'admin', methods => ['POST'], paths => ['/skeid/usage/purge'],
492 document => 'admin', tag => 'Admin', summary => 'Delete usage events of key ids, or before a time',
493 3 ▶ handler => sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
494 3 my ($c) = @_;
495 3 my $body = $c->req->json;
496 3 ▶ $body = {} unless ref($body) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 0 3 3
497 3 my ($request, $error) = Langertha::Skeid::UsageStore->purge_request($body);
498 3 ▶ unless ($request) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($request) 1 2 3
499 1 $c->render(json => { ok => 0, error => $error }, status => 400);
500 1 return;
501 }
502 2 my $result = $c->skeid->purge_usage(%$request);
503 2 ▶ $c->render(json => $result, status => ($result->{ok} ? 200 : 503));
Branch: 1 branch
BranchTrueFalseTotal
$result->{'ok'} ? : 2 0 2
504 73 });
505  
506 $add->(id => 'admin_usage', group => 'admin', paths => ['/skeid/usage'], document => 'admin',
507 tag => 'Admin', summary => 'Usage report',
508 0 ▶ handler => sub {
Subroutine __ANON__: not called CC=9 SCAR=45.0
509 0 my ($c) = @_;
510 0 ▶ my $report = $c->skeid->call_function('usage.report', {
Branch: 3 branches
BranchTrueFalseTotal
defined $c->param('since') && length $c->param('since') ? : 0 0 0
defined $c->param('api_key_id') && length $c->param('api_key_id') ? : 0 0 0
defined $c->param('model') && length $c->param('model') ? : 0 0 0
Condition0%0/11
defined $c->param("since") and length $c->param("since")
!ll&&!rl&&r
000
defined $c->param("api_key_id") and length $c->param("api_key_id")
!ll&&!rl&&r
000
defined $c->param("model") and length $c->param("model")
!ll&&!rl&&r
000
$c->param("limit") // 50
l!l
00
MC/DC0%0/2
defined $c->param("since") and length $c->param("since")
defined $c->param("since") length $c->param("since")
MC/DC0%0/2
defined $c->param("api_key_id") and length $c->param("api_key_id")
defined $c->param("api_key_id") length $c->param("api_key_id")
MC/DC0%0/2
defined $c->param("model") and length $c->param("model")
defined $c->param("model") length $c->param("model")
MC/DC0%0/1
$c->param("limit") // 50
$c->param("limit")
Truth table0%0/3
A and B
A= defined $c->param("since")B= length $c->param("since")
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= defined $c->param("api_key_id")B= length $c->param("api_key_id")
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= defined $c->param("model")B= length $c->param("model")
ABresult
0X0
100
111
Truth table0%0/2
A
A= $c->param("limit")
Aresult
11
00
511 (defined($c->param('since')) && length($c->param('since')) ? (since => $c->param('since')) : ()),
512 (defined($c->param('api_key_id')) && length($c->param('api_key_id')) ? (api_key_id => $c->param('api_key_id')) : ()),
513 (defined($c->param('model')) && length($c->param('model')) ? (model => $c->param('model')) : ()),
514 limit => ($c->param('limit') // 50),
515 });
516 0 ▶ my $status = ($report->{ok} ? 200 : 400);
Branch: 1 branch
BranchTrueFalseTotal
$report->{'ok'} ? : 0 0 0
517 0 $c->render(status => $status, json => $report);
518 73 });
519  
520 $add->(id => 'admin_openapi', group => 'admin', paths => ['/skeid/openapi.json'],
521 document => 'admin', tag => 'Admin', summary => 'The OpenAPI 3.1 document of the admin routes',
522 73 ▶ handler => sub { _handle_openapi($_[0], 'admin') });
Subroutine __ANON__: called CC=1 SCAR=0.0
523  
524 # The Swagger UI (skeid k105): off unless openapi.swagger_ui, an unknown path then. No
525 # document lists it; it carries no data, so it is outside the client gate -- the browser
526 # that loads it has no key yet. The description it shows is behind the gate.
527 $add->(id => 'docs', group => 'root', paths => ['/docs'], document => undef,
528 73 ▶ handler => sub { _handle_docs($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
529 $add->(id => 'docs_file', group => 'root', paths => ['/docs/#file'], document => undef,
530 73 ▶ handler => sub { _handle_docs($_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
531  
532 73 return @t;
533 }
534  
535 # Whether the config has the section an entry's route needs.
536 216 ▶sub _route_enabled {
Subroutine _route_enabled: called CC=9 SCAR=22.1
537 216 my ($skeid, $entry) = @_;
538 216 my $need = $entry->{requires};
539 216 ▶ return 1 unless defined $need;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $need 188 28 216
540 28 ▶ return $skeid->manifest_enabled && $skeid->manifest_available ? 1 : 0 if $need eq 'manifest';
Branch: 2 branches
BranchTrueFalseTotal
if $need eq "manifest" 8 20 28
$skeid->manifest_enabled && $skeid->manifest_available ? : 1 7 8
Condition66%2/3
$skeid->manifest_enabled and $skeid->manifest_available
!ll&&!rl&&r
701
MC/DC50%1/2
$skeid->manifest_enabled and $skeid->manifest_available
$skeid->manifest_enabled $skeid->manifest_available
Truth table66%2/3
A and B
A= $skeid->manifest_enabledB= $skeid->manifest_available
ABresult
0X0
100
111
541 20 ▶ return $skeid->mcp_enabled ? 1 : 0 if $need eq 'mcp';
Branch: 2 branches
BranchTrueFalseTotal
if $need eq "mcp" 16 4 20
$skeid->mcp_enabled ? : 4 12 16
542 4 ▶ return $skeid->registry_enabled ? 1 : 0 if $need eq 'registry';
Branch: 2 branches
BranchTrueFalseTotal
if $need eq "registry" 4 0 4
$skeid->registry_enabled ? : 2 2 4
543 0 return 0;
544 }
545  
546 # GET /openapi.json and GET /skeid/openapi.json: the document of the routes the config enables
547 # (ADR 0025). The model names in the examples are the ones /v1/models lists for this caller.
548 12 ▶sub _handle_openapi {
Subroutine _handle_openapi: called CC=6 SCAR=17.9
549 12 my ($c, $kind) = @_;
550 12 my $skeid = $c->skeid;
551 12 ▶ my @entries = grep { ($_->{document} // '') eq $kind && _route_enabled($skeid, $_) }
Condition100%5/5
($_->{'document'} // '') eq $kind && _route_enabled($skeid, $_)
!ll&&!rl&&r
19221195
$_->{"document"} // ""
l!l
38424
MC/DC100%2/2
($_->{'document'} // '') eq $kind && _route_enabled($skeid, $_)
$_->{"document"} _route_enabled($skeid, $_)
Truth table100%3/3
A && B
A= $_->{"document"}B= _route_enabled($skeid, $_)
ABresult
0X0
100
111
552 Langertha::Skeid::Proxy->route_table;
553 my @models = $kind eq 'client'
554 12 ▶ ? map { $_->{model} } @{$skeid->list_models(api_key_id => _request_api_key_id($c))}
Branch: 1 branch
BranchTrueFalseTotal
$kind eq 'client' ? : 8 4 12
555 : ();
556 12 ▶ _manifest_cache_headers($c) if $kind eq 'client';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "client" 8 4 12
557 12 ▶ $c->res->headers->header('Cache-Control' => 'no-store') if $kind eq 'admin';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "admin" 4 8 12
558 12 $c->render(json => Langertha::Skeid::OpenAPI->document(
559 kind => $kind,
560 entries => \@entries,
561 models => \@models,
562 client_auth => $skeid->client_auth_enabled,
563 version => $Langertha::Skeid::Proxy::VERSION,
564 ));
565 }
566  
567 # /docs and /docs/<file>: the Swagger UI, from the cache directory (skeid k105). Unknown path
568 # unless the config switches it on; the assets are fetched on the first request that needs them,
569 # without blocking the loop. A fetch that fails answers 502, and 503 while the failure is
570 # remembered -- the client is told, never left waiting, and no request starts a second download
571 # within the window.
572 25 ▶sub _handle_docs {
Subroutine _handle_docs: called CC=7 SCAR=19.5
573 25 my ($c) = @_;
574 25 my $skeid = $c->skeid;
575 25 $skeid->maybe_reload_config;
576 25 ▶ return $c->render(status => 404, text => 'Not Found') unless $skeid->openapi_swagger_ui;
Branch: 1 branch
BranchTrueFalseTotal
unless $skeid->openapi_swagger_ui 4 21 25
577  
578 21 my $ui = $c->app->swagger_ui;
579 21 my $file = $c->stash('file');
580 21 ▶ if (defined $file && $file eq 'init.js') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file and $file eq "init.js") 1 20 21
Condition100%3/3
defined $file and $file eq "init.js"
!ll&&!rl&&r
1551
MC/DC100%2/2
defined $file and $file eq "init.js"
defined $file $file eq "init.js"
Truth table100%3/3
A and B
A= defined $fileB= $file eq "init.js"
ABresult
0X0
100
111
581 1 $c->res->headers->content_type('application/javascript; charset=utf-8');
582 1 return $c->render(data => $ui->init_js);
583 }
584 20 ▶ return $c->render(status => 404, text => 'Not Found') if defined($file) && !$ui->is_asset($file);
Branch: 1 branch
BranchTrueFalseTotal
if defined $file and not $ui->is_asset($file) 2 18 20
Condition100%3/3
defined $file and not $ui->is_asset($file)
!ll&&!rl&&r
1532
MC/DC100%2/2
defined $file and not $ui->is_asset($file)
defined $file not $ui->is_asset($file)
Truth table100%3/3
A and not(B)
A= defined $fileB= not $ui->is_asset($file)
ABresult
0X0
100
111
585  
586 18 ▶ my $dir = $skeid->openapi_cache_dir // $ui->default_cache_dir;
Condition33%1/3
$skeid->openapi_cache_dir // $ui->default_cache_dir
l!l&&r!l&&!r
1800
MC/DC0%0/2
$skeid->openapi_cache_dir // $ui->default_cache_dir
$skeid->openapi_cache_dir $ui->default_cache_dir
Truth table33%1/3
A // B
A= $skeid->openapi_cache_dirB= $ui->default_cache_dir
ABresult
1X1
011
000
587 18 $c->render_later;
588 18 ▶ $ui->ensure($dir, sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
589 18 my ($ok, $kind, $message) = @_;
590 18 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 7 11 18
591 # The message names the pinned URL and the check that failed, nothing of a response.
592 7 ▶ $c->app->log->error('swagger ui: ' . $message) if $kind eq 'fetch';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "fetch" 5 2 7
593 7 ▶ $c->res->headers->header('Retry-After' => $ui->retry_after) if $kind eq 'backoff';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "backoff" 2 5 7
594 7 ▶ return _render_error($c, ($kind eq 'backoff' ? 503 : 502),
Branch: 1 branch
BranchTrueFalseTotal
$kind eq 'backoff' ? : 2 5 7
595 'The Swagger UI assets could not be fetched', 'upstream_error', 'swagger_ui_unavailable');
596 }
597 11 ▶ unless (defined $file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $file) 9 2 11
598 9 $c->res->headers->content_type('text/html; charset=utf-8');
599 9 return $c->render(data => $ui->index_html);
600 }
601 2 $c->res->headers->cache_control('public, max-age=3600');
602 2 $c->reply->file($ui->asset_path($dir, $file));
603 18 });
604 18 return;
605 }
606  
607 # GET /skeid/registry/snapshot (skeid #18, ADR 0017): a fronting tier's CapacityProbe::Registry
608 # pulls this. 404 unless registry.enabled, and never unsigned. No store may keep it: a cached
609 # snapshot is a stale one.
610 27 ▶sub _handle_registry_snapshot {
Subroutine _handle_registry_snapshot: called CC=7 SCAR=19.7
611 27 my ($c) = @_;
612 27 ▶ return unless _authorize_registry_read($c);
Branch: 1 branch
BranchTrueFalseTotal
unless _authorize_registry_read($c) 4 23 27
613 23 my $skeid = $c->skeid;
614 23 $c->res->headers->header('Cache-Control' => 'no-store');
615 23 ▶ unless ($skeid->registry_enabled) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($skeid->registry_enabled) 3 20 23
616 3 $c->render(status => 404,
617 json => { error => { message => 'No registry snapshot is published here', type => 'not_found' } });
618 3 return;
619 }
620 20 my ($body, $signature) = eval { Langertha::Skeid::Registry->signed_snapshot($skeid) };
621 20 ▶ unless (defined $body) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $body) 1 19 20
622 1 ▶ my $err = $@ || 'unknown error';
Condition50%1/2
$@ || 'unknown error'
l!l
10
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
623 1 ▶ unless (length($skeid->registry_secret // '')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length($skeid->registry_secret // "")) 0 1 1
Condition50%1/2
$skeid->registry_secret // ""
l!l
10
MC/DC0%0/1
$skeid->registry_secret // ""
$skeid->registry_secret
Truth table50%1/2
A
A= $skeid->registry_secret
Aresult
11
00
624 0 $c->render(status => 503,
625 json => { error => { message => 'Registry secret is not set', type => 'unavailable' } });
626 0 return;
627 }
628 # Anything else is a bug in building the snapshot. The operator gets the cause in the
629 # log; the caller gets nothing that could describe this process's internals.
630 1 $err =~ s/\s+\z//;
631 1 $c->app->log->error("registry snapshot failed: $err");
632 1 $c->render(status => 500,
633 json => { error => { message => 'Registry snapshot could not be built', type => 'server_error' } });
634 1 return;
635 }
636 19 $c->res->headers->header(Langertha::Skeid::Registry->SIGNATURE_HEADER => $signature);
637 19 $c->render(data => $body, format => 'json');
638 }
639  
640 137 ▶sub _authorize_admin {
Subroutine _authorize_admin: called CC=8 SCAR=20.8
641 137 my ($c) = @_;
642 137 $c->skeid->maybe_reload_config;
643  
644 137 ▶ my $admin_api_key = $c->skeid->admin_api_key // '';
Condition50%1/2
$c->skeid->admin_api_key // ""
l!l
1370
MC/DC0%0/1
$c->skeid->admin_api_key // ""
$c->skeid->admin_api_key
Truth table50%1/2
A
A= $c->skeid->admin_api_key
Aresult
11
00
645 137 ▶ if (!length($admin_api_key)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $admin_api_key) 7 130 137
646 7 $c->render(status => 404, text => 'Not Found');
647 7 return undef;
648 }
649  
650 130 ▶ my $auth = $c->req->headers->authorization // '';
Condition100%2/2
$c->req->headers->authorization // ""
l!l
1228
MC/DC100%1/1
$c->req->headers->authorization // ""
$c->req->headers->authorization
Truth table100%2/2
A
A= $c->req->headers->authorization
Aresult
11
00
651 130 my ($scheme, $token) = $auth =~ /\A(\S+)\s+(.+)\z/;
652 130 ▶ my $ok = defined($scheme) && lc($scheme) eq 'bearer' && defined($token)
Condition88%8/9
defined $scheme && lc $scheme eq 'bearer' && defined $token && 'Langertha::Skeid::Secret'->equal($token, $admin_api_key)
!ll&&!rl&&r
1119100
defined $scheme and lc $scheme eq "bearer" and defined $token
!ll&&!rl&&r
110119
defined $scheme and lc $scheme eq "bearer"
!ll&&!rl&&r
101119
MC/DC75%3/4
defined $scheme && lc $scheme eq 'bearer' && defined $token && 'Langertha::Skeid::Secret'->equal($token, $admin_api_key)
defined $scheme lc $scheme eq "bearer" defined $token 'Langertha::Skeid::Secret'->equal($token, $admin_api_key)
Truth table80%4/5
A and B and C && D
A= defined $schemeB= lc $scheme eq "bearer"C= defined $tokenD= 'Langertha::Skeid::Secret'->equal($token, $admin_api_key)
ABCDresult
0XXX0
10XX0
110X0
11100
11111
653 && Langertha::Skeid::Secret->equal($token, $admin_api_key);
654 130 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 30 100 130
655 30 $c->res->headers->header('WWW-Authenticate' => 'Bearer realm="skeid-admin"');
656 30 $c->render(
657 status => 401,
658 json => {
659 error => {
660 type => 'unauthorized',
661 message => 'Missing or invalid admin bearer token',
662 },
663 },
664 );
665 30 return undef;
666 }
667 100 return 1;
668 }
669  
670 # The snapshot route's gate: the admin API key (compat) or the registry read key, each compared
671 # in constant time. 404 when neither is configured, like every closed /skeid route; 401 with the
672 # admin route's challenge otherwise.
673 27 ▶sub _authorize_registry_read {
Subroutine _authorize_registry_read: called CC=10 SCAR=23.8
674 27 my ($c) = @_;
675 27 my $skeid = $c->skeid;
676 27 $skeid->maybe_reload_config;
677  
678 27 ▶ my @accepted = grep { length } ($skeid->admin_api_key // '', $skeid->registry_read_key // '');
Condition50%2/4
$skeid->admin_api_key // ""
l!l
270
$skeid->registry_read_key // ""
l!l
270
MC/DC0%0/1
$skeid->admin_api_key // ""
$skeid->admin_api_key
MC/DC0%0/1
$skeid->registry_read_key // ""
$skeid->registry_read_key
Truth table50%1/2
A
A= $skeid->admin_api_key
Aresult
11
00
Truth table50%1/2
A
A= $skeid->registry_read_key
Aresult
11
00
679 27 ▶ unless (@accepted) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@accepted) 0 27 27
680 0 $c->render(status => 404, text => 'Not Found');
681 0 return undef;
682 }
683  
684 27 ▶ my $auth = $c->req->headers->authorization // '';
Condition100%2/2
$c->req->headers->authorization // ""
l!l
243
MC/DC100%1/1
$c->req->headers->authorization // ""
$c->req->headers->authorization
Truth table100%2/2
A
A= $c->req->headers->authorization
Aresult
11
00
685 27 my ($scheme, $token) = $auth =~ /\A(\S+)\s+(.+)\z/;
686 27 my $ok = 0;
687 27 ▶ if (defined($scheme) && lc($scheme) eq 'bearer' && defined($token)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $scheme and lc $scheme eq "bearer" and defined $token) 24 3 27
Condition66%4/6
defined $scheme and lc $scheme eq "bearer" and defined $token
!ll&&!rl&&r
3024
defined $scheme and lc $scheme eq "bearer"
!ll&&!rl&&r
3024
MC/DC33%1/3
defined $scheme and lc $scheme eq "bearer" and defined $token
defined $scheme lc $scheme eq "bearer" defined $token
Truth table50%2/4
A and B and C
A= defined $schemeB= lc $scheme eq "bearer"C= defined $token
ABCresult
0XX0
10X0
1100
1111
688 # No short-circuit: both candidates are compared whichever one matches.
689 24 $ok |= Langertha::Skeid::Secret->equal($token, $_) for @accepted;
690 }
691 27 ▶ return 1 if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 23 4 27
692  
693 4 $c->res->headers->header('WWW-Authenticate' => 'Bearer realm="skeid-admin"');
694 4 $c->render(
695 status => 401,
696 json => {
697 error => {
698 type => 'unauthorized',
699 message => 'Missing or invalid registry bearer token',
700 },
701 },
702 );
703 4 return undef;
704 }
705  
706 # The client routes' gate (skeid k90), run by their bridges before anything else of the request:
707 # before the body is parsed, a node is admitted (request.start), a key resolved, an upstream
708 # called or a usage event written -- a refused request has nothing to give back. It reloads the
709 # config first, so switching client authentication on or off or rotating an id holds from the
710 # next request on every client route, a GET included. That is what the reload throttle
711 # (config_reload_interval) and the no-op on an unchanged config are for: an anonymous GET does
712 # not rerun the loader, nor restart the node probes, per request. Off without client_auth.
713 # The identity is the one routing uses, so with routing.trust_key_id_header the header's id is
714 # what must be on the list. A refusal is not logged -- the routes are public, and a line per
715 # rejected request would be anybody's to flood -- and its body names neither the key nor its id.
716 1506 ▶sub _authorize_client {
Subroutine _authorize_client: called CC=5 SCAR=16.1
717 1506 my ($c) = @_;
718 1506 my $skeid = $c->skeid;
719 1506 $skeid->maybe_reload_config;
720 1506 ▶ return 1 unless $skeid->client_auth_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $skeid->client_auth_enabled 1270 236 1506
721  
722 236 my $api_key_id = _request_api_key_id($c);
723 236 ▶ return 1 if $skeid->client_key_allowed($api_key_id);
Branch: 1 branch
BranchTrueFalseTotal
if $skeid->client_key_allowed($api_key_id) 147 89 236
724  
725 89 ▶ my $missing = !defined($api_key_id) || $api_key_id eq 'anonymous';
Condition66%2/3
!defined($api_key_id) || $api_key_id eq 'anonymous'
l!l&&r!l&&!r
04148
MC/DC50%1/2
!defined($api_key_id) || $api_key_id eq 'anonymous'
!defined($api_key_id) $api_key_id eq 'anonymous'
Truth table66%2/3
not(A) || B
A= !defined($api_key_id)B= $api_key_id eq 'anonymous'
ABresult
1X1
011
000
726 89 $c->res->headers->header('WWW-Authenticate' => 'Bearer realm="skeid"');
727 89 ▶ _render_error($c, 401, ($missing ? 'Missing API key' : 'Invalid API key'),
Branch: 1 branch
BranchTrueFalseTotal
$missing ? : 41 48 89
728 'invalid_request_error', 'invalid_api_key');
729 89 return undef;
730 }
731  
732 # What a key is shown depends on who presents it, so no cache may hand one key's answer to
733 # another: every answer -- the client gate's 401 included -- is private, not stored, and varies on
734 # each header that can carry the identity. Set by the route's bridge, before the gate.
735 46 ▶sub _manifest_cache_headers {
Subroutine _manifest_cache_headers: called CC=1 SCAR=0.0
736 46 my ($c) = @_;
737 46 my $headers = $c->res->headers;
738 46 $headers->header('Cache-Control' => 'private, no-store');
739 46 $headers->header(Vary => 'Authorization, X-Api-Key, X-Skeid-Key-Id, X-Api-Key-Id');
740 46 return;
741 }
742  
743 # The config is reloaded by the client gate before this runs (see _authorize_client), throttled
744 # by config_reload_interval and a no-op when nothing changed. 404 when nothing is published
745 # (disabled, or a Langertha without Langertha::Manifest), 401 without a key (ADR 0015: no
746 # anonymous manifest, not even a minimal one), 403 for a key without a manifest: grant, else the
747 # manifest built for that key id.
748 28 ▶sub _handle_manifest {
Subroutine _handle_manifest: called CC=6 SCAR=17.9
749 28 my ($c) = @_;
750 28 my $skeid = $c->skeid;
751  
752 28 my $headers = $c->res->headers;
753  
754 28 ▶ unless ($skeid->manifest_enabled && $skeid->manifest_available) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($skeid->manifest_enabled and $skeid->manifest_available) 6 22 28
Condition66%2/3
$skeid->manifest_enabled and $skeid->manifest_available
!ll&&!rl&&r
6022
MC/DC50%1/2
$skeid->manifest_enabled and $skeid->manifest_available
$skeid->manifest_enabled $skeid->manifest_available
Truth table66%2/3
A and B
A= $skeid->manifest_enabledB= $skeid->manifest_available
ABresult
0X0
100
111
755 6 $c->render(status => 404,
756 json => { error => { message => 'No provider manifest is published here', type => 'not_found' } });
757 6 return;
758 }
759  
760 22 my $api_key_id = _request_api_key_id($c);
761 22 ▶ if (!defined($api_key_id) || $api_key_id eq 'anonymous') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $api_key_id or $api_key_id eq "anonymous") 5 17 22
Condition66%2/3
not defined $api_key_id or $api_key_id eq "anonymous"
l!l&&r!l&&!r
0517
MC/DC50%1/2
not defined $api_key_id or $api_key_id eq "anonymous"
not defined $api_key_id $api_key_id eq "anonymous"
Truth table66%2/3
not(A) or B
A= not defined $api_key_idB= $api_key_id eq "anonymous"
ABresult
1X1
011
000
762 5 $headers->header('WWW-Authenticate' => 'Bearer realm="skeid"');
763 5 $c->render(status => 401,
764 json => { error => { message => 'An API key is required for the provider manifest', type => 'unauthorized' } });
765 5 return;
766 }
767  
768 17 my $json = $skeid->manifest_for_key($api_key_id);
769 17 ▶ unless (defined $json) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $json) 3 14 17
770 3 $c->render(status => 403,
771 json => { error => { message => 'No provider manifest is published for this key', type => 'permission_error' } });
772 3 return;
773 }
774  
775 14 $c->render(data => $json, format => 'json');
776 14 return;
777 }
778  
779 # The client's connection is silent while the upstream works, and the server closes a connection
780 # that was silent for its inactivity timeout (30s unless the server was told otherwise). So a
781 # request that calls an upstream gets, on top of that, what the upstream may take: the client
782 # outlasts the upstream and is still there for the answer, or for the error. Read from the user
783 # agent rather than kept beside it, so the two sides cannot drift apart. It holds for this
784 # request only: the server sets its own timeout again for the next one on the connection. A
785 # timeout of 0 is none, on either side, and stays none.
786 1297 ▶sub _extend_client_timeout {
Subroutine _extend_client_timeout: called CC=5 SCAR=17.8
787 1297 my ($c) = @_;
788 1297 ▶ my $stream = Mojo::IOLoop->stream($c->tx->connection // '') or return;
Branch: 1 branch
BranchTrueFalseTotal
my $stream = "Mojo::IOLoop"->stream($c->tx->connection // "") or return 1297 0 1297
Condition50%1/2
$c->tx->connection // ""
l!l
12970
MC/DC0%0/1
$c->tx->connection // ""
$c->tx->connection
Truth table50%1/2
A
A= $c->tx->connection
Aresult
11
00
789 1297 my $own = $stream->timeout;
790 1297 my $upstream = $c->app->ua->request_timeout;
791 1297 ▶ $stream->timeout(($own && $upstream) ? $own + $upstream : 0);
Branch: 1 branch
BranchTrueFalseTotal
$own && $upstream ? : 1297 0 1297
Condition33%1/3
$own and $upstream
!ll&&!rl&&r
001297
MC/DC0%0/2
$own and $upstream
$own $upstream
Truth table33%1/3
A and B
A= $ownB= $upstream
ABresult
0X0
100
111
792 1297 return;
793 }
794  
795 326 ▶sub _handle_openai_chat {
Subroutine _handle_openai_chat: called CC=3 SCAR=11.0
796 326 my ($c) = @_;
797 326 _extend_client_timeout($c);
798 326 my $body = $c->req->json;
799 326 ▶ unless (ref($body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $body eq "HASH") 2 324 326
800 2 $c->render(json => { error => { message => 'Invalid JSON body', type => 'invalid_request_error' } }, status => 400);
801 2 return;
802 }
803  
804 324 ▶ my ($model, %names) = _catch_all($c, $body->{model} // '', 'chat');
Condition100%2/2
$body->{"model"} // ""
l!l
3231
MC/DC100%1/1
$body->{"model"} // ""
$body->{"model"}
Truth table100%2/2
A
A= $body->{"model"}
Aresult
11
00
805 324 my $api_key_id = _request_api_key_id($c);
806 324 ▶ _begin_route_async($c, $model, $api_key_id, sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
807 324 my ($route, $node_id, $started, $tier) = @_;
808 324 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 43 281 324
809  
810 # The alias layer means the model the client asked for and the model the node is asked for
811 # are two different strings (ADR 0008). The upstream body carries the served model; the
812 # usage event carries both, or cost attribution silently loses which product was used.
813 281 my $served_model = _served_model($tier, $model);
814 281 ▶ $body->{model} = $served_model if ref($body) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $body eq "HASH" 281 0 281
815  
816 281 my $url = _endpoint_url_for_node($route->{url}, '/chat/completions');
817 my $meta = {
818 api_format => 'openai',
819 endpoint => '/v1/chat/completions',
820 api_key_id => $api_key_id,
821 provider => 'skeid',
822 engine => ($route->{engine} // 'openaibase'),
823 model => $served_model,
824 %names,
825 281 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
2810
$route->{"url"} // ""
l!l
2810
MC/DC0%0/1
$route->{"engine"} // "openaibase"
$route->{"engine"}
MC/DC0%0/1
$route->{"url"} // ""
$route->{"url"}
Truth table50%1/2
A
A= $route->{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $route->{"url"}
Aresult
11
00
826 };
827  
828 281 my $relay = _verbatim_relay($c, $served_model);
829  
830 281 ▶ if ($body->{stream}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body->{"stream"}) 72 209 281
831 72 _proxy_openai_stream($c, $url, $body, $node_id, $started, $meta, undef, $relay);
832 72 return;
833 }
834  
835 209 $c->render_later;
836 209 ▶ _proxy_openai_json_async($c, $url, $body, $node_id, $started, $meta, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
837 209 my ($res, $err, $status) = @_;
838 209 ▶ return if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 29 180 209
839 180 _render_upstream_response($c, $res, $node_id);
840 209 }, undef, $relay);
841 324 }, %names);
842 }
843  
844 78 ▶sub _handle_openai_embeddings {
Subroutine _handle_openai_embeddings: called CC=3 SCAR=11.2
845 78 my ($c) = @_;
846 78 _extend_client_timeout($c);
847 78 my $body = $c->req->json;
848 78 ▶ unless (ref($body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $body eq "HASH") 0 78 78
849 0 $c->render(json => { error => { message => 'Invalid JSON body', type => 'invalid_request_error' } }, status => 400);
850 0 return;
851 }
852  
853 78 ▶ my ($model, %names) = _catch_all($c, $body->{model} // '', 'embeddings');
Condition50%1/2
$body->{"model"} // ""
l!l
780
MC/DC0%0/1
$body->{"model"} // ""
$body->{"model"}
Truth table50%1/2
A
A= $body->{"model"}
Aresult
11
00
854 78 my $api_key_id = _request_api_key_id($c);
855 78 ▶ _begin_route_async($c, $model, $api_key_id, sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
856 78 my ($route, $node_id, $started, $tier) = @_;
857 78 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 10 68 78
858  
859 # The alias layer means the model the client asked for and the model the node is asked for
860 # are two different strings (ADR 0008). The upstream body carries the served model; the
861 # usage event carries both, or cost attribution silently loses which product was used.
862 68 my $served_model = _served_model($tier, $model);
863 68 ▶ $body->{model} = $served_model if ref($body) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $body eq "HASH" 68 0 68
864  
865 68 my $url = _endpoint_url_for_node($route->{url}, '/embeddings');
866 my $meta = {
867 api_format => 'openai',
868 endpoint => '/v1/embeddings',
869 api_key_id => $api_key_id,
870 provider => 'skeid',
871 engine => ($route->{engine} // 'openaibase'),
872 model => $served_model,
873 %names,
874 68 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
680
$route->{"url"} // ""
l!l
680
MC/DC0%0/1
$route->{"engine"} // "openaibase"
$route->{"engine"}
MC/DC0%0/1
$route->{"url"} // ""
$route->{"url"}
Truth table50%1/2
A
A= $route->{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $route->{"url"}
Aresult
11
00
875 };
876 68 $c->render_later;
877 68 ▶ _proxy_openai_json_async($c, $url, $body, $node_id, $started, $meta, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
878 68 my ($res, $err, $status) = @_;
879 68 ▶ return if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 8 60 68
880 60 _render_upstream_response($c, $res, $node_id);
881 68 }, undef, _verbatim_relay($c, $served_model));
882 78 }, %names);
883 }
884  
885 # Runs once per request, when its head is parsed and its body is still on the wire (the request
886 # content's `body` event). An upload route gets its own limit there, because afterwards is too
887 # late for either thing it is for (skeid k91):
888 #
889 # - uploads.max_bytes replaces the server's request limit, which is 16 MiB and so below the
890 # default upload limit. A request that declares a larger body is cut off at once: the limit is
891 # set below what was already read, the parser stops, and the route answers 413 without the body
892 # having been received. A body of undeclared length (chunked) is cut off when it passes the
893 # limit plus the head allowance, so it is never buffered whole either.
894 # - A caller the client gate is going to refuse is cut off the same way, so its 401 does not
895 # cost an upload spooled to disk first. The gate itself still runs and renders the 401.
896 #
897 # Which limit a route has is the route table below: the audio routes the uploads.max_bytes, the
898 # documents routes (a form, and base64 in JSON for /v1/convert/source) uploads.documents_max_bytes.
899 # A new upload route is an entry there, or it runs under the server's 16 MiB.
900 #
901 # The limit is read off the Skeid here, after picking up a changed config, so a reload holds
902 # from the next upload. Every other route keeps the server's own limit: nothing is set for it.
903 # A failure here leaves the server's limit in force and the route's own checks to decide.
904 my %UPLOAD_ROUTE = (
905 198 (map { $_ => 'upload_max_bytes' } Langertha::Skeid::Protocol::Audio->routes),
906 99 (map { $_ => 'documents_max_bytes' } Langertha::Skeid::Protocol::Documents->routes),
907 );
908  
909 2378 ▶sub _limit_upload {
Subroutine _limit_upload: called CC=13 SCAR=25.9
910 2378 my ($app, $tx) = @_;
911 2378 my $req = $tx->req;
912 2378 (my $path = $req->url->path->to_route) =~ s{/\z}{};
913 2378 ▶ return _limit_mcp_request($app, $tx) if $path =~ m{\A/mcp/};
Branch: 1 branch
BranchTrueFalseTotal
if $path =~ m[\A/mcp/] 73 2305 2378
914 2305 ▶ return unless uc($req->method // '') eq 'POST';
Branch: 1 branch
BranchTrueFalseTotal
unless uc($req->method // "") eq "POST" 519 1786 2305
Condition50%1/2
$req->method // ""
l!l
23050
MC/DC0%0/1
$req->method // ""
$req->method
Truth table50%1/2
A
A= $req->method
Aresult
11
00
915 1786 ▶ my $limit = $UPLOAD_ROUTE{$path} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $limit = $UPLOAD_ROUTE{$path} or return 180 1606 1786
916  
917 180 my $done = eval {
918 180 my $c = $app->build_controller($tx);
919 180 my $skeid = $c->skeid;
920 180 $skeid->maybe_reload_config;
921  
922 180 ▶ if ($skeid->client_auth_enabled && !$skeid->client_key_allowed(_request_api_key_id($c))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skeid->client_auth_enabled and not $skeid->client_key_allowed(_request_api_key_id($c))) 9 171 180
Condition100%3/3
$skeid->client_auth_enabled and not $skeid->client_key_allowed(_request_api_key_id($c))
!ll&&!rl&&r
16929
MC/DC100%2/2
$skeid->client_auth_enabled and not $skeid->client_key_allowed(_request_api_key_id($c))
$skeid->client_auth_enabled not $skeid->client_key_allowed(_request_api_key_id($c))
Truth table100%3/3
A and not(B)
A= $skeid->client_auth_enabledB= not $skeid->client_key_allowed(_request_api_key_id($c))
ABresult
0X0
100
111
923 9 $req->max_message_size(1);
924 9 return 1;
925 }
926  
927 171 my $max = $skeid->$limit;
928 171 my $declared = $req->headers->content_length;
929 171 ▶ if (!$req->content->is_chunked && defined($declared) && $declared =~ /\A[0-9]+\z/ && $declared > $max) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $req->content->is_chunked and defined $declared and $declared =~ /\A[0-9]+\z/ and $declared > $max) 8 163 171
Condition77%7/9
not $req->content->is_chunked and defined $declared and $declared =~ /\A[0-9]+\z/ and $declared > $max
!ll&&!rl&&r
21618
not $req->content->is_chunked and defined $declared and $declared =~ /\A[0-9]+\z/
!ll&&!rl&&r
20169
not $req->content->is_chunked and defined $declared
!ll&&!rl&&r
20169
MC/DC50%2/4
not $req->content->is_chunked and defined $declared and $declared =~ /\A[0-9]+\z/ and $declared > $max
not $req->content->is_chunked defined $declared $declared =~ /\A[0-9]+\z/ $declared > $max
Truth table60%3/5
not(A) and B and C and D
A= not $req->content->is_chunkedB= defined $declaredC= $declared =~ /\A[0-9]+\z/D= $declared > $max
ABCDresult
0XXX0
10XX0
110X0
11100
11111
930 8 $req->max_message_size(1);
931 8 return 1;
932 }
933 163 $req->max_message_size($max + $UPLOAD_HEAD_ALLOWANCE);
934 163 1;
935 };
936 180 ▶ $app->log->error('Setting the upload limit failed: ' . ($@ || 'unknown error')) unless $done;
Branch: 1 branch
BranchTrueFalseTotal
unless $done 0 180 180
Condition0%0/2
$@ || 'unknown error'
l!l
00
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
937 180 return;
938 }
939  
940 # The body limit of the MCP routes: mcp.max_request_bytes, not the server's own. Set on the
941 # request as its body begins, like the upload limit. A body over it is cut off and _handle_mcp
942 # answers 413. A failure here leaves the server's limit in force.
943 73 ▶sub _limit_mcp_request {
Subroutine _limit_mcp_request: called CC=3 SCAR=11.4
944 73 my ($app, $tx) = @_;
945 73 my $done = eval {
946 73 my $skeid = $app->build_controller($tx)->skeid;
947 73 $skeid->maybe_reload_config;
948 73 $tx->req->max_message_size($skeid->mcp_max_request_bytes);
949 73 1;
950 };
951 73 ▶ $app->log->error('Setting the MCP request limit failed: ' . ($@ || 'unknown error')) unless $done;
Branch: 1 branch
BranchTrueFalseTotal
unless $done 0 73 73
Condition0%0/2
$@ || 'unknown error'
l!l
00
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
952 73 return;
953 }
954  
955 # POST /v1/audio/transcriptions and /v1/audio/translations (skeid k91). The request is a
956 # multipart form and the answer is whatever the node's transcription endpoint says -- JSON, plain
957 # text, subtitles or an event stream. Neither is translated (ADR 0021): the form goes upstream
958 # part for part as the client sent it, the answer comes back byte for byte. Skeid reads two
959 # fields of the form, `model` to route by and `stream` to pick the relay, and writes one, `model`
960 # again, when an alias tier serves another model than the one asked for (ADR 0008). What the
961 # form and the answers look like on the wire is Langertha::Skeid::Protocol::Audio's to know.
962 84 ▶sub _handle_openai_audio {
Subroutine _handle_openai_audio: called CC=17 SCAR=28.4
963 84 my ($c, $endpoint) = @_;
964 84 my $audio = 'Langertha::Skeid::Protocol::Audio';
965 84 _extend_client_timeout($c);
966 84 my $req = $c->req;
967  
968 # Before anything is read off the body: a request cut off by _limit_upload has no complete
969 # form. The body size is checked again, exactly, for what the limit set there lets through.
970 84 my $max = $c->skeid->upload_max_bytes;
971 84 ▶ if ($req->is_limit_exceeded || ($req->body_size // 0) > $max) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->is_limit_exceeded or ($req->body_size // 0) > $max) 6 78 84
Condition80%4/5
$req->is_limit_exceeded or ($req->body_size // 0) > $max
l!l&&r!l&&!r
5178
$req->body_size // 0
l!l
790
MC/DC0%0/2
$req->is_limit_exceeded or ($req->body_size // 0) > $max
$req->is_limit_exceeded $req->body_size
Truth table66%2/3
A or B
A= $req->is_limit_exceededB= $req->body_size
ABresult
1X1
011
000
972 6 _render_error($c, 413, "Maximum content size limit ($max bytes) exceeded", 'invalid_request_error');
973 6 return;
974 }
975  
976 78 my $content = $req->content;
977 78 ▶ unless ($content->is_multipart) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($content->is_multipart) 2 76 78
978 2 _render_error($c, 400, 'Expected a multipart/form-data body', 'invalid_request_error');
979 2 return;
980 }
981  
982 # One `model` field, no more: with two, Skeid would route -- and apply the key's policy -- by
983 # one while the node may well serve the other.
984 76 my ($field, $problem) = $audio->form_fields($content);
985 76 ▶ my @models = @{$field->{model} || []};
Condition100%2/2
$field->{'model'} || []
l!l
742
MC/DC100%1/1
$field->{'model'} || []
$field->{'model'}
Truth table100%2/2
A
A= $field->{'model'}
Aresult
11
00
986 76 ▶ my $model = @models == 1 ? $models[0]{value} : undef;
Branch: 1 branch
BranchTrueFalseTotal
@models == 1 ? : 66 10 76
987 76 ▶ $model = decode('UTF-8', $model) // $model if defined $model;
Branch: 1 branch
BranchTrueFalseTotal
if defined $model 65 11 76
Condition33%1/3
decode("UTF-8", $model) // $model
l!l&&r!l&&!r
6500
MC/DC0%0/2
decode("UTF-8", $model) // $model
decode("UTF-8", $model) $model
Truth table33%1/3
A // B
A= decode("UTF-8", $model)B= $model
ABresult
1X1
011
000
988 76 ▶ $problem //= !@models ? "The 'model' form field is required"
Branch: 3 branches
BranchTrueFalseTotal
!@models ? : 1 74 75
@models > 1 ? : 8 66 74
!(defined $model && length $model) ? : 2 64 66
Condition100%5/5
$problem //= !@models ? "The 'model' form field is required" : (@models > 1 ? "The 'model' form field may be given only once" : (!(defined $model && length $model) ? "The 'model' form field is empty or too long" : undef))
l!l
175
defined $model && length $model
!ll&&!rl&&r
1164
MC/DC100%1/1
$problem //= !@models ? "The 'model' form field is required" : (@models > 1 ? "The 'model' form field may be given only once" : (!(defined $model && length $model) ? "The 'model' form field is empty or too long" : undef))
$problem
MC/DC100%2/2
defined $model && length $model
defined $model length $model
Truth table100%2/2
A
A= $problem
Aresult
11
00
Truth table100%3/3
A && B
A= defined $modelB= length $model
ABresult
0X0
100
111
989 : @models > 1 ? "The 'model' form field may be given only once"
990 : !(defined($model) && length($model)) ? "The 'model' form field is empty or too long"
991 : undef;
992 76 ▶ if (defined $problem) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $problem) 12 64 76
993 12 _render_error($c, 400, $problem, 'invalid_request_error');
994 12 return;
995 }
996  
997 # The last `stream` field decides, as it does for the node that parses the same form.
998 64 ▶ my $streamed = @{$field->{stream} || []} ? $audio->is_true($field->{stream}[-1]{value}) : 0;
Branch: 1 branch
BranchTrueFalseTotal
@{$field->{'stream'} or [];} ? : 28 36 64
Condition100%2/2
$field->{'stream'} || []
l!l
2836
MC/DC100%1/1
$field->{'stream'} || []
$field->{'stream'}
Truth table100%2/2
A
A= $field->{'stream'}
Aresult
11
00
999  
1000 64 my $api_key_id = _request_api_key_id($c);
1001 64 ▶ _begin_route_async($c, $model, $api_key_id, sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
1002 64 my ($route, $node_id, $started, $tier) = @_;
1003 64 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 3 61 64
1004  
1005 # Requested and served model are two strings once an alias is in play (ADR 0008): the form
1006 # that goes upstream carries the served one, the usage event carries both.
1007 61 my $served_model = _served_model($tier, $model);
1008 61 ▶ my %replace = $served_model eq $model ? () : ($models[0]{index} => encode('UTF-8', $served_model));
Branch: 1 branch
BranchTrueFalseTotal
$served_model eq $model ? : 59 2 61
1009  
1010 61 my $url = _endpoint_url_for_node($route->{url}, $audio->upstream_path($endpoint));
1011 my $meta = {
1012 api_format => 'openai',
1013 endpoint => $endpoint,
1014 api_key_id => $api_key_id,
1015 provider => 'skeid',
1016 engine => ($route->{engine} // 'openaibase'),
1017 model => $served_model,
1018 requested_model => $model,
1019 61 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
610
$route->{"url"} // ""
l!l
610
MC/DC0%0/1
$route->{"engine"} // "openaibase"
$route->{"engine"}
MC/DC0%0/1
$route->{"url"} // ""
$route->{"url"}
Truth table50%1/2
A
A= $route->{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $route->{"url"}
Aresult
11
00
1020 };
1021 my $relay = {
1022 # The upstream form is built from the parts the server already parsed: a part is its
1023 # headers and an asset, and an upload above 256 KiB is an asset on disk, so the file is
1024 # streamed from there and never copied into memory. The client's Content-Type travels in
1025 # the forwarded headers and its boundary is the one the body is written with.
1026 59 ▶ request => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1027 59 my ($ua, $url, $headers) = @_;
1028 59 return $ua->build_tx(POST => $url, $headers,
1029 multipart => $audio->upstream_parts($content, \%replace));
1030 },
1031 47 ▶ units => sub { $audio->usage_units(@_) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1032 54 ▶ delta_text => sub { $audio->delta_text(@_) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1033 61 };
1034 61 my $body = { model => $served_model };
1035  
1036 61 ▶ if ($streamed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($streamed) 19 42 61
1037 19 _proxy_openai_stream($c, $url, $body, $node_id, $started, $meta, undef, $relay);
1038 19 return;
1039 }
1040  
1041 42 $c->render_later;
1042 42 ▶ _proxy_openai_json_async($c, $url, $body, $node_id, $started, $meta, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1043 42 my ($res, $err, $status) = @_;
1044 42 ▶ return if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 4 38 42
1045 38 _render_upstream_response($c, $res, $node_id);
1046 42 }, undef, $relay);
1047 64 });
1048 }
1049  
1050 # POST /v1/convert/file and POST /v1/convert/source (skeid k94, ADR 0028): docling-serve's
1051 # synchronous conversion under its own paths, relayed in its own shape like the audio routes
1052 # (ADR 0021) -- a form goes upstream part for part, a source body is decoded once and written
1053 # again so the node reads exactly what Skeid did, and the answer (JSON, or a zip) comes back byte
1054 # for byte. There is no `model` field: the route is planned over the nodes of kind `documents`
1055 # under the routing key `documents`, which is what a key's policy grants. Skeid refuses what makes
1056 # the node fetch from an address the client names, unless documents.allow_remote_sources: that
1057 # is a server-side request from inside the cluster network. The wire is
1058 # Langertha::Skeid::Protocol::Documents's to know.
1059 87 ▶sub _handle_documents {
Subroutine _handle_documents: called CC=10 SCAR=23.0
1060 87 my ($c, $endpoint) = @_;
1061 87 my $docs = 'Langertha::Skeid::Protocol::Documents';
1062 87 _extend_client_timeout($c);
1063 87 my $req = $c->req;
1064 87 my $skeid = $c->skeid;
1065  
1066 # A request cut off by _limit_upload has no complete body. The size is checked again,
1067 # exactly, for what the limit set there lets through.
1068 87 my $max = $skeid->documents_max_bytes;
1069 87 ▶ if ($req->is_limit_exceeded || ($req->body_size // 0) > $max) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->is_limit_exceeded or ($req->body_size // 0) > $max) 4 83 87
Condition60%3/5
$req->is_limit_exceeded or ($req->body_size // 0) > $max
l!l&&r!l&&!r
4083
$req->body_size // 0
l!l
830
MC/DC0%0/2
$req->is_limit_exceeded or ($req->body_size // 0) > $max
$req->is_limit_exceeded $req->body_size
Truth table66%2/3
A or B
A= $req->is_limit_exceededB= $req->body_size
ABresult
1X1
011
000
1070 4 _render_error($c, 413, "Maximum content size limit ($max bytes) exceeded", 'invalid_request_error');
1071 4 return;
1072 }
1073  
1074 83 my ($remote, $count, $body, $content);
1075 83 ▶ if ($endpoint =~ /file\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($endpoint =~ /file\z/) { } 58 25 83
1076 58 $content = $req->content;
1077 58 ▶ unless ($content->is_multipart) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($content->is_multipart) 1 57 58
1078 1 _render_error($c, 400, 'Expected a multipart/form-data body', 'invalid_request_error');
1079 1 return;
1080 }
1081 57 my ($names, $problem) = $docs->form_remote_fields($content);
1082 57 ▶ if (defined $problem) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $problem) 1 56 57
1083 1 _render_error($c, 400, $problem, 'invalid_request_error');
1084 1 return;
1085 }
1086 56 $remote = $names;
1087 56 $count = $docs->document_count($content);
1088 }
1089 else {
1090 25 $body = $req->json;
1091 25 ▶ unless (ref($body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $body eq "HASH") 5 20 25
1092 5 _render_error($c, 400, 'Expected a JSON object', 'invalid_request_error');
1093 5 return;
1094 }
1095 20 $remote = $docs->json_remote_fields($body, $req->body);
1096 20 $count = $docs->document_count($body);
1097 }
1098  
1099 # Before admission, so it costs no slot and no event. The message names the field and never
1100 # what it holds: the value is an address the caller chose.
1101 76 ▶ if (@$remote && !$skeid->documents_allow_remote_sources) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$remote and not $skeid->documents_allow_remote_sources) 17 59 76
Condition100%3/3
@$remote and not $skeid->documents_allow_remote_sources
!ll&&!rl&&r
57217
MC/DC100%2/2
@$remote and not $skeid->documents_allow_remote_sources
@$remote not $skeid->documents_allow_remote_sources
Truth table100%3/3
A and not(B)
A= @$remoteB= not $skeid->documents_allow_remote_sources
ABresult
0X0
100
111
1102 17 _render_error($c, 400,
1103 "The '$remote->[0]' field is not accepted: requests that make the node fetch from or call "
1104 . 'an address are disabled (documents.allow_remote_sources)', 'invalid_request_error');
1105 17 return;
1106 }
1107  
1108 59 my $routing_key = $docs->routing_key;
1109 59 my $api_key_id = _request_api_key_id($c);
1110 59 ▶ _begin_route_async($c, $routing_key, $api_key_id, sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
1111 59 my ($route, $node_id, $started, $tier) = @_;
1112 59 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 5 54 59
1113  
1114 54 my $url = _endpoint_url_for_node($route->{url}, $docs->upstream_path($endpoint));
1115 my $meta = {
1116 api_format => $docs->api_format,
1117 endpoint => $endpoint,
1118 api_key_id => $api_key_id,
1119 provider => 'skeid',
1120 engine => ($route->{engine} // 'openaibase'),
1121 model => $routing_key,
1122 requested_model => $routing_key,
1123 54 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
540
$route->{"url"} // ""
l!l
540
MC/DC0%0/1
$route->{"engine"} // "openaibase"
$route->{"engine"}
MC/DC0%0/1
$route->{"url"} // ""
$route->{"url"}
Truth table50%1/2
A
A= $route->{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $route->{"url"}
Aresult
11
00
1124 };
1125 my $relay = {
1126 # The form is built from the parts the server parsed: a part is its headers and an asset,
1127 # and a file above 256 KiB is an asset on disk, sent from there and never copied. The
1128 # client's Content-Type, boundary included, travels in the forwarded headers.
1129 43 ▶ ($content ? (request => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1130 43 my ($ua, $url, $headers) = @_;
1131 43 return $ua->build_tx(POST => $url, $headers,
1132 multipart => Langertha::Skeid::Protocol::Audio->upstream_parts($content, {}));
1133 }) : ()),
1134 # Not decoded past what is worth the CPU of the event loop; and no tokens to read.
1135 max_parse_bytes => $docs->max_parse_bytes,
1136 47 ▶ usage => sub { return },
Subroutine __ANON__: called CC=1 SCAR=0.0
1137 47 ▶ units => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1138 47 my ($payload, $res) = @_;
1139 47 ▶ return unless $res->is_success;
Branch: 1 branch
BranchTrueFalseTotal
unless $res->is_success 0 47 47
1140 47 my $pages = $docs->pages($payload, $res);
1141 47 ▶ return (documents => $count, (defined $pages ? (pages => $pages) : ()));
Branch: 1 branch
BranchTrueFalseTotal
defined $pages ? : 36 11 47
1142 },
1143 54 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
$content ? : 44 10 54
1144  
1145 54 $c->render_later;
1146 54 ▶ _proxy_openai_json_async($c, $url, ($body // {}), $node_id, $started, $meta, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1147 54 my ($res, $err, $status) = @_;
1148 54 ▶ return if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 7 47 54
1149 47 _render_upstream_response($c, $res, $node_id);
1150 54 ▶ }, undef, $relay);
Condition100%2/2
$body // {}
l!l
1044
MC/DC100%1/1
$body // {}
$body
Truth table100%2/2
A
A= $body
Aresult
11
00
1151 59 }, kind => 'documents');
1152 }
1153  
1154 # GET /v1/realtime (skeid k95, ADR 0029): live transcription over the OpenAI realtime protocol.
1155 # The handshake is an ordinary request that has a slot and a node to get -- the client gate has
1156 # run already (a bridge, so a refused key is a plain 401 and no socket), the model comes from the
1157 # query, the key's policy, tiers and admission apply, and route_wait happens before the upgrade.
1158 # The node is opened FIRST: only a node that took the WebSocket handshake gets a client that is
1159 # upgraded, so a node that refuses is an HTTP 502 and not an accepted-then-closed socket. From the
1160 # upgrade on the session is Langertha::Skeid::Proxy::Realtime's; this function ends with handing
1161 # it both transactions, and its finish callback is the only place request.finish and the usage
1162 # event happen for a session that got that far (once, on whichever path the session ends).
1163 100 ▶sub _handle_openai_realtime {
Subroutine _handle_openai_realtime: called CC=2 SCAR=6.9
1164 100 my ($c) = @_;
1165 100 my $protocol = 'Langertha::Skeid::Protocol::Realtime';
1166 100 _extend_client_timeout($c);
1167 100 $c->render_later;
1168  
1169 100 my ($model, $problem) = $protocol->query_model($c->req->url->query);
1170 100 ▶ if (defined $problem) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $problem) 4 96 100
1171 4 _render_error($c, 400, $problem, 'invalid_request_error');
1172 4 return;
1173 }
1174  
1175 96 my $api_key_id = _request_api_key_id($c);
1176 96 ▶ _begin_route_async($c, $model, $api_key_id, sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1177 96 my ($route, $node_id, $started, $tier) = @_;
1178 96 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 4 92 96
1179  
1180 92 my $served_model = _served_model($tier, $model);
1181 my $meta = {
1182 api_format => 'openai',
1183 endpoint => $protocol->route,
1184 api_key_id => $api_key_id,
1185 provider => 'skeid',
1186 engine => ($route->{engine} // 'openaibase'),
1187 model => $served_model,
1188 requested_model => $model,
1189 92 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
920
$route->{"url"} // ""
l!l
920
MC/DC0%0/1
$route->{"engine"} // "openaibase"
$route->{"engine"}
MC/DC0%0/1
$route->{"url"} // ""
$route->{"url"}
Truth table50%1/2
A
A= $route->{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $route->{"url"}
Aresult
11
00
1190 };
1191 my $url = $protocol->upstream_url(
1192 92 _endpoint_url_for_node($route->{url}, $protocol->upstream_path), $served_model,
1193 $c->req->url->query);
1194  
1195 # What the client sent for the handshake of its own connection is not the node's: its
1196 # Sec-WebSocket-* headers (the subprotocol list may carry the browser's key -- never passed
1197 # on, ADR 0003), its Origin and its cookies stay here. The user agent makes the node's own.
1198 92 my %fwd_headers = _forward_headers($c, $node_id);
1199 92 delete @fwd_headers{ grep { /\A(?:sec-websocket-|origin\z|cookie\z)/i } keys %fwd_headers };
1200  
1201 92 ▶ _inject_node_auth_async(\%fwd_headers, $c->skeid, $node_id, sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1202 92 my ($no_key) = @_;
1203  
1204 # The client left while the node's key was being resolved: nothing went upstream, the
1205 # slot goes back and nothing is metered, as for a request that was not forwarded.
1206 92 ▶ if (_client_gone($c)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_client_gone($c)) 0 92 92
1207 0 $c->skeid->call_function('request.finish', {
1208 id => $node_id, ok => 0, aborted => 1, duration_ms => _duration_ms($started),
1209 });
1210 0 return;
1211 }
1212 92 ▶ if (defined $no_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $no_key) 1 91 92
1213 1 _refuse_unkeyed_node($c, $node_id, $started, $meta, $no_key);
1214 1 return;
1215 }
1216  
1217 91 my $client = $c->tx;
1218 91 my $up_tx = $c->app->ua->build_websocket_tx($url => \%fwd_headers);
1219 91 my $settled = 0; # set by whichever comes first: the node's answer or the client leaving
1220 91 ▶ my $handshake = $client->can('handshake') ? $client->handshake : $client;
Branch: 1 branch
BranchTrueFalseTotal
$client->can('handshake') ? : 91 0 91
1221  
1222 # The client hangs up while the node is being opened. Its upgrade request is the
1223 # transaction that closes (the WebSocket one does not exist yet), and the node's is
1224 # cancelled -- a node that sees the handshake finish would otherwise hold a session
1225 # for nobody. The slot is given back and the request recorded, as for a plain request.
1226 91 ▶ $handshake->once(finish => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1227 91 ▶ return if $settled;
Branch: 1 branch
BranchTrueFalseTotal
if $settled 90 1 91
1228 1 $settled = 1;
1229 1 my $duration_ms = _duration_ms($started);
1230 1 $c->skeid->call_function('request.finish', {
1231 id => $node_id, ok => 0, aborted => 1, duration_ms => $duration_ms,
1232 });
1233 1 _record_usage_event($c, {
1234 %$meta, _client_abort_event(), node_id => $node_id, duration_ms => $duration_ms,
1235 metrics => {},
1236 });
1237 1 _cancel_upstream($up_tx);
1238 91 });
1239  
1240 91 ▶ $c->app->ua->start($up_tx => sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
1241 91 my ($ua, $tx) = @_;
1242 91 ▶ return if $settled;
Branch: 1 branch
BranchTrueFalseTotal
if $settled 1 90 91
1243 90 $settled = 1;
1244 90 my $duration_ms = _duration_ms($started);
1245 90 _observe_capacity($c, $node_id, $tx->res);
1246  
1247 # The node did not take the handshake: HTTP 502 in the client's shape, no socket. A
1248 # 4xx of the node (its key, its capacity) is Skeid's problem to the client, not theirs.
1249 90 ▶ unless ($tx->is_websocket) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tx->is_websocket) 1 89 90
1250 1 ▶ my $err = $tx->error || {};
Condition50%1/2
$tx->error || {}
l!l
10
MC/DC0%0/1
$tx->error || {}
$tx->error
Truth table50%1/2
A
A= $tx->error
Aresult
11
00
1251 1 $c->skeid->call_function('request.finish', {
1252 id => $node_id, ok => 0, duration_ms => $duration_ms,
1253 });
1254 _record_usage_event($c, {
1255 %$meta,
1256 node_id => $node_id,
1257 status_code => 502,
1258 ok => 0,
1259 duration_ms => $duration_ms,
1260 error_type => 'upstream_error',
1261 error_message => 'The node refused the realtime handshake: '
1262 1 ▶ . ($err->{code} ? $err->{code} . ' ' : '') . ($err->{message} // 'no WebSocket'),
Branch: 1 branch
BranchTrueFalseTotal
$err->{'code'} ? : 1 0 1
Condition50%1/2
$err->{"message"} // "no WebSocket"
l!l
10
MC/DC0%0/1
$err->{"message"} // "no WebSocket"
$err->{"message"}
Truth table50%1/2
A
A= $err->{"message"}
Aresult
11
00
1263 metrics => {},
1264 });
1265 1 _render_error($c, 502, 'The node did not accept the realtime connection', 'upstream_error');
1266 1 return;
1267 }
1268  
1269 # Upgrade the client now, choosing the one subprotocol Skeid ever answers with -- never
1270 # the entry that carries a key. From here the session owns both ends.
1271 89 $client->with_protocols($protocol->subprotocol);
1272 89 $c->res->headers->header('x-skeid-node' => $node_id);
1273 89 $c->rendered(101);
1274  
1275 89 my $skeid = $c->skeid;
1276 $c->app->realtime->start_session(
1277 client => $client,
1278 upstream => $tx,
1279 requested_model => $model,
1280 served_model => $served_model,
1281 started => $started,
1282 limits => {
1283 idle_timeout => $skeid->realtime_idle_timeout,
1284 max_session_seconds => $skeid->realtime_max_session_seconds,
1285 max_message_bytes => $skeid->realtime_max_message_bytes,
1286 max_queued_bytes => $skeid->realtime_max_queued_bytes,
1287 },
1288 89 ▶ finish => sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
1289 89 my ($result) = @_;
1290 $skeid->call_function('request.finish', {
1291 id => $node_id,
1292 ok => $result->{ok},
1293 ($result->{aborted} ? (aborted => 1) : ()),
1294 ($result->{rejected} ? (rejected => 1) : ()),
1295 duration_ms => $result->{duration_ms},
1296 89 ▶ });
Branch: 2 branches
BranchTrueFalseTotal
$result->{'aborted'} ? : 17 72 89
$result->{'rejected'} ? : 5 84 89
1297 # One event for the whole session (ADR 0029): the usage blocks of its completed
1298 # transcriptions summed, priced like any other answer's, and the duration.
1299 my $metrics = ref($result->{usage}) eq 'HASH'
1300 ? _stream_metrics($c, $meta, { model => $served_model }, $result->{duration_ms},
1301 $result->{usage})
1302 89 ▶ : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $result->{'usage'} eq 'HASH' ? : 6 83 89
1303 _record_usage_event($c, {
1304 %$meta,
1305 node_id => $node_id,
1306 status_code => $result->{status_code},
1307 ok => $result->{ok},
1308 duration_ms => $result->{duration_ms},
1309 error_type => $result->{error_type},
1310 error_message => $result->{error_message},
1311 metrics => $metrics,
1312 (defined $result->{audio_seconds} ? (audio_seconds => $result->{audio_seconds}) : ()),
1313 89 ▶ (defined $result->{content_bytes} ? (content_bytes => $result->{content_bytes}) : ()),
Branch: 2 branches
BranchTrueFalseTotal
defined $result->{'audio_seconds'} ? : 3 86 89
defined $result->{'content_bytes'} ? : 5 84 89
1314 });
1315 },
1316 89 );
1317 91 });
1318 92 });
1319 96 });
1320 96 return;
1321 }
1322  
1323 # POST /v1/rerank and POST /rerank (skeid k92). A JSON body in the shape Cohere, vLLM, Jina and
1324 # infinity share, routed by its `model` like a chat request. To a node that speaks that shape
1325 # the body is relayed with only `model` replaced, and the answer comes back byte for byte (ADR
1326 # 0021). A node marked `rerank_format` speaks another dialect and is translated in both
1327 # directions -- on the upstream side, the one place Skeid does that. Either way the wire's names
1328 # are Langertha::Skeid::Protocol::Rerank's to know.
1329 107 ▶sub _handle_openai_rerank {
Subroutine _handle_openai_rerank: called CC=2 SCAR=7.0
1330 107 my ($c) = @_;
1331 107 my $rerank = 'Langertha::Skeid::Protocol::Rerank';
1332 107 _extend_client_timeout($c);
1333 107 my $body = $c->req->json;
1334 107 ▶ if (defined(my $problem = $rerank->request_problem($body))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $problem = $rerank->request_problem($body))) 33 74 107
1335 33 _render_error($c, 400, $problem, 'invalid_request_error');
1336 33 return;
1337 }
1338  
1339 74 my $model = $body->{model};
1340 74 my $documents = $rerank->document_count($body);
1341 74 my $api_key_id = _request_api_key_id($c);
1342 74 ▶ _begin_route_async($c, $model, $api_key_id, sub {
Subroutine __ANON__: called CC=10 SCAR=23.2
1343 74 my ($route, $node_id, $started, $tier) = @_;
1344 74 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 6 68 74
1345  
1346 # Requested and served model are two strings once an alias is in play (ADR 0008): the body
1347 # that goes upstream carries the served one, the usage event carries both.
1348 68 my $served_model = _served_model($tier, $model);
1349 68 ▶ my $format = $route->{rerank_format} // '';
Condition100%2/2
$route->{"rerank_format"} // ""
l!l
3038
MC/DC100%1/1
$route->{"rerank_format"} // ""
$route->{"rerank_format"}
Truth table100%2/2
A
A= $route->{"rerank_format"}
Aresult
11
00
1350 my $meta = {
1351 api_format => 'openai',
1352 endpoint => $rerank->endpoint,
1353 api_key_id => $api_key_id,
1354 provider => 'skeid',
1355 engine => ($route->{engine} // 'openaibase'),
1356 model => $served_model,
1357 requested_model => $model,
1358 68 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
680
$route->{"url"} // ""
l!l
680
MC/DC0%0/1
$route->{"engine"} // "openaibase"
$route->{"engine"}
MC/DC0%0/1
$route->{"url"} // ""
$route->{"url"}
Truth table50%1/2
A
A= $route->{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $route->{"url"}
Aresult
11
00
1359 };
1360  
1361 # Which dialect the request has to be put in is known only now, with the node. A request
1362 # this node's dialect cannot carry -- a document that is not text, for a node that takes
1363 # texts -- is the client's to fix, but it holds a slot already.
1364 68 my $upstream_body = eval { $rerank->request_to_upstream($body, $served_model, $format) };
1365 68 ▶ unless (ref($upstream_body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $upstream_body eq "HASH") 6 62 68
1366 6 my $err = $@;
1367 6 ▶ my $message = blessed($err) && $err->isa('Langertha::Skeid::Protocol::Refusal')
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($err) && $err->isa('Langertha::Skeid::Protocol::Refusal') ? : 6 0 6
Condition33%1/3
builtin::blessed($err) and $err->isa("Langertha::Skeid::Protocol::Refusal")
!ll&&!rl&&r
006
MC/DC0%0/2
builtin::blessed($err) and $err->isa("Langertha::Skeid::Protocol::Refusal")
builtin::blessed($err) $err->isa("Langertha::Skeid::Protocol::Refusal")
Truth table33%1/3
A and B
A= builtin::blessed($err)B= $err->isa("Langertha::Skeid::Protocol::Refusal")
ABresult
0X0
100
111
1368 ? $err->message : 'Invalid request';
1369 6 _refuse_unsendable_request($c, $node_id, $started, $meta, $message);
1370 6 return;
1371 }
1372  
1373 my $url = $rerank->at_server_root($format)
1374 ? _root_url_for_node($route->{url}, $rerank->upstream_path)
1375 62 ▶ : _endpoint_url_for_node($route->{url}, $rerank->upstream_path);
Branch: 1 branch
BranchTrueFalseTotal
$rerank->at_server_root($format) ? : 24 38 62
1376 my $relay = {
1377 # Tokens are reported in three places, none of them where a chat answer has them.
1378 52 ▶ usage => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1379 52 my ($payload, $res) = @_;
1380 52 return $rerank->usage($payload, $res->headers, $format);
1381 },
1382 # Counted off the request, so it needs nothing from the node but its answer.
1383 52 ▶ units => sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
1384 52 my ($payload, $res) = @_;
1385 52 ▶ return $res->is_success ? (documents => $documents) : ();
Branch: 1 branch
BranchTrueFalseTotal
$res->is_success ? : 52 0 52
1386 },
1387 22 ▶ (length($format) ? (answer => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1388 22 my ($payload, $res) = @_;
1389 22 return $rerank->response_from_upstream($payload, $res->headers, $body, $served_model, $format);
1390 62 ▶ }) : ()),
Branch: 1 branch
BranchTrueFalseTotal
length $format ? : 24 38 62
1391 };
1392  
1393 62 $c->render_later;
1394 62 ▶ _proxy_openai_json_async($c, $url, $upstream_body, $node_id, $started, $meta, sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1395 62 my ($res, $err, $status, $upstream, $payload) = @_;
1396 62 ▶ return if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 10 52 62
1397 52 ▶ return _render_upstream_response($c, $res, $node_id) unless length $format;
Branch: 1 branch
BranchTrueFalseTotal
unless length $format 31 21 52
1398 21 ▶ $c->res->code($status || 200);
Condition50%1/2
$status || 200
l!l
210
MC/DC0%0/1
$status || 200
$status
Truth table50%1/2
A
A= $status
Aresult
11
00
1399 21 $c->res->headers->header('x-skeid-node' => $node_id);
1400 21 $c->render(json => $payload);
1401 62 }, undef, $relay);
1402 74 });
1403 }
1404  
1405 208 ▶sub _handle_anthropic_messages {
Subroutine _handle_anthropic_messages: called CC=7 SCAR=19.5
1406 208 my ($c) = @_;
1407 208 _extend_client_timeout($c);
1408 208 my $body = $c->req->json;
1409 208 ▶ unless (ref($body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $body eq "HASH") 2 206 208
1410 2 _render_error($c, 400, 'Invalid JSON body', 'invalid_request_error');
1411 2 return;
1412 }
1413  
1414 206 ▶ my $wants_stream = $body->{stream} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$body->{'stream'} ? : 76 130 206
1415  
1416 # Translation reads the client's body, so a failure there is the client's malformed request
1417 # -- a provider built-in tool skeid cannot forward, or a shape the translator cannot read.
1418 # Uncaught it escapes as Mojolicious' HTML 500; answer a 400 an Anthropic SDK can parse, before
1419 # anything is routed or metered (core karr #216).
1420 206 my $openai_body = eval { Langertha::Skeid::Protocol::Anthropic->request_to_openai($body) };
1421 206 ▶ unless ($openai_body) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($openai_body) 10 196 206
1422 # A deliberate refusal carries a message written for the client. Any other exception can quote
1423 # the request, so its text is neither sent nor logged (k75, k82).
1424 10 my $err = $@;
1425 10 ▶ my $msg = blessed($err) && $err->isa('Langertha::Skeid::Protocol::Refusal')
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($err) && $err->isa('Langertha::Skeid::Protocol::Refusal') ? : 7 3 10
Condition66%2/3
builtin::blessed($err) and $err->isa("Langertha::Skeid::Protocol::Refusal")
!ll&&!rl&&r
037
MC/DC50%1/2
builtin::blessed($err) and $err->isa("Langertha::Skeid::Protocol::Refusal")
builtin::blessed($err) $err->isa("Langertha::Skeid::Protocol::Refusal")
Truth table66%2/3
A and B
A= builtin::blessed($err)B= $err->isa("Langertha::Skeid::Protocol::Refusal")
ABresult
0X0
100
111
1426 ? $err->message : 'Invalid request';
1427 10 _render_error($c, 400, $msg, 'invalid_request_error');
1428 10 return;
1429 }
1430 196 ▶ my ($model, %names) = _catch_all($c, $openai_body->{model} // '', 'chat');
Condition50%1/2
$openai_body->{"model"} // ""
l!l
1960
MC/DC0%0/1
$openai_body->{"model"} // ""
$openai_body->{"model"}
Truth table50%1/2
A
A= $openai_body->{"model"}
Aresult
11
00
1431 196 my $api_key_id = _request_api_key_id($c);
1432  
1433 196 ▶ _begin_route_async($c, $model, $api_key_id, sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
1434 196 my ($route, $node_id, $started, $tier) = @_;
1435 196 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 8 188 196
1436  
1437 # The alias layer means the model the client asked for and the model the node is asked for
1438 # are two different strings (ADR 0008). The upstream body carries the served model; the
1439 # usage event carries both, or cost attribution silently loses which product was used.
1440 188 my $served_model = _served_model($tier, $model);
1441 188 $openai_body->{model} = $served_model;
1442  
1443 188 my $url = _endpoint_url_for_node($route->{url}, '/chat/completions');
1444 my $meta = {
1445 api_format => 'anthropic',
1446 endpoint => '/v1/messages',
1447 api_key_id => $api_key_id,
1448 provider => 'skeid',
1449 engine => ($route->{engine} // 'openaibase'),
1450 model => $served_model,
1451 %names,
1452 188 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
1880
$route->{"url"} // ""
l!l
1880
MC/DC0%0/1
$route->{"engine"} // "openaibase"
$route->{"engine"}
MC/DC0%0/1
$route->{"url"} // ""
$route->{"url"}
Truth table50%1/2
A
A= $route->{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $route->{"url"}
Aresult
11
00
1453 };
1454  
1455 188 ▶ if ($wants_stream) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wants_stream) 72 116 188
1456 # Ask upstream for a stream in the one dialect Skeid speaks to nodes, and rewrite it at
1457 # the client edge (ADR 0001). include_usage because Anthropic clients read token counts
1458 # from message_delta, and an OpenAI stream omits usage unless asked.
1459 72 $openai_body->{stream} = \1;
1460 72 $openai_body->{stream_options} = { include_usage => \1 };
1461 72 _proxy_openai_stream($c, $url, $openai_body, $node_id, $started, $meta,
1462 Langertha::Skeid::Protocol::Anthropic::Stream->new(model => $model),
1463 _schema_relay($c, $openai_body, 'input_schema'));
1464 72 return;
1465 }
1466  
1467 116 delete $openai_body->{stream};
1468 116 $c->render_later;
1469 116 ▶ _proxy_openai_json_async($c, $url, $openai_body, $node_id, $started, $meta, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1470 116 my ($res, $err, $status, $upstream, $payload) = @_;
1471 116 ▶ return if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 12 104 116
1472 104 ▶ $c->res->code($status || 200);
Condition50%1/2
$status || 200
l!l
1040
MC/DC0%0/1
$status || 200
$status
Truth table50%1/2
A
A= $status
Aresult
11
00
1473 104 $c->res->headers->header('x-skeid-node' => $node_id);
1474 104 $c->render(json => $payload);
1475 105 ▶ }, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1476 # response_from_openai reads a decoded OpenAI response ($upstream->{choices}, ...); the
1477 # raw Mojo $res would read as all-undef and yield a well-formed but empty envelope (karr #26).
1478 105 return Langertha::Skeid::Protocol::Anthropic->response_from_openai($_[0], $model);
1479 116 }, _schema_relay($c, $openai_body, 'input_schema'));
1480 196 }, %names);
1481 }
1482  
1483 # Serves both Ollama completion routes. /api/chat and /api/generate differ only at the edge --
1484 # generate's prompt/system/images become one chat conversation on the way up, and the answer
1485 # carries `response` instead of `message` on the way back (skeid #43) -- so they share the
1486 # route, admission, metering and pricing below and cannot drift apart.
1487 99 my %OLLAMA_FACE = (
1488 chat => {
1489 endpoint => '/api/chat',
1490 request => 'request_to_openai',
1491 response => 'response_from_openai',
1492 shape => 'chat',
1493 },
1494 generate => {
1495 endpoint => '/api/generate',
1496 request => 'generate_request_to_openai',
1497 response => 'generate_response_from_openai',
1498 shape => 'generate',
1499 },
1500 );
1501  
1502 267 ▶sub _handle_ollama {
Subroutine _handle_ollama: called CC=6 SCAR=17.9
1503 267 my ($c, $kind) = @_;
1504 267 _extend_client_timeout($c);
1505 267 my $face = $OLLAMA_FACE{$kind};
1506 267 my $body = $c->req->json;
1507 267 ▶ unless (ref($body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $body eq "HASH") 4 263 267
1508 4 _render_error($c, 400, 'Invalid JSON body', 'invalid_request_error');
1509 4 return;
1510 }
1511  
1512 # Ollama defaults stream to true when the field is absent, unlike everyone else. A client
1513 # that omits it is asking for a stream and will sit waiting for newline-delimited JSON.
1514 263 ▶ my $wants_stream = exists $body->{stream} ? ($body->{stream} ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $body->{'stream'} ? : 224 39 263
$body->{'stream'} ? : 70 154 224
1515  
1516 263 my $request_method = $face->{request};
1517 # A body the translator cannot read is the client's malformed request. Uncaught it escapes as
1518 # Mojolicious' HTML 500; answer a 400 in Ollama's shape before anything is routed or metered.
1519 # The exception's text stays out of the answer and the log, as with a dying response translator.
1520 263 my $openai_body = eval { Langertha::Skeid::Protocol::Ollama->$request_method($body) };
1521 263 ▶ unless (ref($openai_body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $openai_body eq "HASH") 4 259 263
1522 4 _render_error($c, 400, 'Invalid request', 'invalid_request_error');
1523 4 return;
1524 }
1525 259 ▶ my ($model, %names) = _catch_all($c, $openai_body->{model} // '', 'chat');
Condition50%1/2
$openai_body->{"model"} // ""
l!l
2590
MC/DC0%0/1
$openai_body->{"model"} // ""
$openai_body->{"model"}
Truth table50%1/2
A
A= $openai_body->{"model"}
Aresult
11
00
1526 259 my $api_key_id = _request_api_key_id($c);
1527  
1528 259 ▶ _begin_route_async($c, $model, $api_key_id, sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
1529 259 my ($route, $node_id, $started, $tier) = @_;
1530 259 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 14 245 259
1531  
1532 # The alias layer means the model the client asked for and the model the node is asked for
1533 # are two different strings (ADR 0008). The upstream body carries the served model; the
1534 # usage event carries both, or cost attribution silently loses which product was used.
1535 245 my $served_model = _served_model($tier, $model);
1536 245 $openai_body->{model} = $served_model;
1537  
1538 245 my $url = _endpoint_url_for_node($route->{url}, '/chat/completions');
1539 my $meta = {
1540 api_format => 'ollama',
1541 endpoint => $face->{endpoint},
1542 api_key_id => _request_api_key_id($c),
1543 provider => 'skeid',
1544 engine => ($route->{engine} // 'openaibase'),
1545 model => $served_model,
1546 %names,
1547 245 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
2450
$route->{"url"} // ""
l!l
2450
MC/DC0%0/1
$route->{"engine"} // "openaibase"
$route->{"engine"}
MC/DC0%0/1
$route->{"url"} // ""
$route->{"url"}
Truth table50%1/2
A
A= $route->{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $route->{"url"}
Aresult
11
00
1548 };
1549  
1550 245 ▶ if ($wants_stream) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wants_stream) 104 141 245
1551 104 $openai_body->{stream} = \1;
1552 104 $openai_body->{stream_options} = { include_usage => \1 };
1553 _proxy_openai_stream($c, $url, $openai_body, $node_id, $started, $meta,
1554 104 Langertha::Skeid::Protocol::Ollama::Stream->new(model => $model, shape => $face->{shape}),
1555 _schema_relay($c, $openai_body, 'function', 'parameters'));
1556 104 return;
1557 }
1558  
1559 141 delete $openai_body->{stream};
1560 141 $c->render_later;
1561 141 ▶ _proxy_openai_json_async($c, $url, $openai_body, $node_id, $started, $meta, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1562 141 my ($res, $err, $status, $upstream, $payload) = @_;
1563 141 ▶ return if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 23 118 141
1564 118 ▶ $c->res->code($status || 200);
Condition50%1/2
$status || 200
l!l
1180
MC/DC0%0/1
$status || 200
$status
Truth table50%1/2
A
A= $status
Aresult
11
00
1565 118 $c->res->headers->header('x-skeid-node' => $node_id);
1566 118 $c->render(json => $payload);
1567 120 ▶ }, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1568 # See the Anthropic path above: the translator needs the decoded upstream body, not the
1569 # Mojo response object, or every field reads undef and the client gets empty content (karr #26).
1570 120 my $response_method = $face->{response};
1571 120 return Langertha::Skeid::Protocol::Ollama->$response_method($_[0]);
1572 141 }, _schema_relay($c, $openai_body, 'function', 'parameters'));
1573 259 }, %names);
1574 }
1575  
1576 # POST /api/embed and /api/embeddings (skeid k116). Both go to the node's OpenAI /embeddings and
1577 # come back in Ollama's shape; they differ only at the edge, like /api/chat and /api/generate.
1578 99 my %OLLAMA_EMBED_FACE = (
1579 embed => {
1580 endpoint => '/api/embed',
1581 request => 'embed_request_to_openai',
1582 response => 'embed_response_from_openai',
1583 },
1584 embeddings => {
1585 endpoint => '/api/embeddings',
1586 request => 'embeddings_request_to_openai',
1587 response => 'embeddings_response_from_openai',
1588 },
1589 );
1590  
1591 11 ▶sub _handle_ollama_embeddings {
Subroutine _handle_ollama_embeddings: called CC=4 SCAR=14.0
1592 11 my ($c, $kind) = @_;
1593 11 _extend_client_timeout($c);
1594 11 my $face = $OLLAMA_EMBED_FACE{$kind};
1595 11 my $body = $c->req->json;
1596 11 ▶ unless (ref($body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $body eq "HASH") 0 11 11
1597 0 _render_error($c, 400, 'Invalid JSON body', 'invalid_request_error');
1598 0 return;
1599 }
1600  
1601 # As on /api/chat: a body the translator cannot read is the client's 400, before anything is
1602 # routed or metered, and the exception's text stays out of the answer.
1603 11 my $request_method = $face->{request};
1604 11 my $openai_body = eval { Langertha::Skeid::Protocol::Ollama->$request_method($body) };
1605 11 ▶ unless (ref($openai_body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $openai_body eq "HASH") 2 9 11
1606 2 _render_error($c, 400, 'Invalid request', 'invalid_request_error');
1607 2 return;
1608 }
1609 9 ▶ my ($model, %names) = _catch_all($c, $openai_body->{model} // '', 'embeddings');
Condition50%1/2
$openai_body->{"model"} // ""
l!l
90
MC/DC0%0/1
$openai_body->{"model"} // ""
$openai_body->{"model"}
Truth table50%1/2
A
A= $openai_body->{"model"}
Aresult
11
00
1610 9 my $api_key_id = _request_api_key_id($c);
1611  
1612 9 ▶ _begin_route_async($c, $model, $api_key_id, sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1613 9 my ($route, $node_id, $started, $tier) = @_;
1614 9 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 2 7 9
1615  
1616 7 my $served_model = _served_model($tier, $model);
1617 7 $openai_body->{model} = $served_model;
1618  
1619 7 my $url = _endpoint_url_for_node($route->{url}, '/embeddings');
1620 my $meta = {
1621 api_format => 'ollama',
1622 endpoint => $face->{endpoint},
1623 api_key_id => $api_key_id,
1624 provider => 'skeid',
1625 engine => ($route->{engine} // 'openaibase'),
1626 model => $served_model,
1627 %names,
1628 7 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
70
$route->{"url"} // ""
l!l
70
MC/DC0%0/1
$route->{"engine"} // "openaibase"
$route->{"engine"}
MC/DC0%0/1
$route->{"url"} // ""
$route->{"url"}
Truth table50%1/2
A
A= $route->{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $route->{"url"}
Aresult
11
00
1629 };
1630  
1631 7 $c->render_later;
1632 7 ▶ _proxy_openai_json_async($c, $url, $openai_body, $node_id, $started, $meta, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1633 7 my ($res, $err, $status, $upstream, $payload) = @_;
1634 7 ▶ return if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 1 6 7
1635 6 ▶ $c->res->code($status || 200);
Condition50%1/2
$status || 200
l!l
60
MC/DC0%0/1
$status || 200
$status
Truth table50%1/2
A
A= $status
Aresult
11
00
1636 6 $c->res->headers->header('x-skeid-node' => $node_id);
1637 6 $c->render(json => $payload);
1638 6 ▶ }, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1639 6 my $response_method = $face->{response};
1640 6 return Langertha::Skeid::Protocol::Ollama->$response_method($_[0], $model);
1641 7 });
1642 9 }, %names);
1643 }
1644  
1645 # The catch-all (skeid k129, ADR 0033): on a chat or an embeddings route -- $route_kind, the kind
1646 # of the route and not a node kind -- an unknown model name is bent to the configured target,
1647 # once, before anything is planned. Returns the name to route under and the names the usage event
1648 # carries: requested_model is what the client sent, routed_model the target and only there on a
1649 # bent request. From here on the request is an ordinary request for the target, so the policy,
1650 # the rate, admission and the answer all see the target.
1651 866 ▶sub _catch_all {
Subroutine _catch_all: called CC=2 SCAR=6.9
1652 866 my ($c, $requested, $route_kind) = @_;
1653 866 my $target = $c->skeid->catch_all_target($requested, $route_kind);
1654 866 ▶ return ($requested, requested_model => $requested) unless defined $target;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $target 838 28 866
1655 28 return ($target, requested_model => $requested, routed_model => $target);
1656 }
1657  
1658 # Walks the tiers of a requested model (ADR 0008) until one admits the request.
1659 #
1660 # The two ways a tier can fail are not the same and must not be treated the same. A tier with
1661 # no eligible node is skipped immediately -- waiting cannot conjure a node that does not exist.
1662 # A tier whose nodes are all busy is waited on for its own wait_ms, because capacity comes back.
1663 # Only when every tier is exhausted does the request fail, and which failure it is depends on
1664 # whether any tier ever had an eligible node: none did means the model is unroutable (503),
1665 # some did means everything was busy (429).
1666 #
1667 # $cb is called with ($route, $node_id, $started, $tier) on success and with nothing on failure,
1668 # after the error has been rendered.
1669 1162 ▶sub _begin_route_async {
Subroutine _begin_route_async: called CC=17 SCAR=29.0
1670 1162 my ($c, $model, $api_key_id, $cb, %route) = @_;
1671 1162 ▶ $cb ||= sub { };
Subroutine __ANON__: not called CC=1 SCAR=1.2
Condition33%1/3
$cb ||= sub { }
l!l&&r!l&&!r
116200
MC/DC0%0/2
$cb ||= sub { }
$cb sub { }
Truth table33%1/3
A ||= B
A= $cbB= sub { }
ABresult
1X1
011
000
1672 # What the route is over besides a model name: `documents` plans over the nodes of that kind
1673 # (ADR 0028). Chat routes pass nothing. A route the catch-all can bend passes the names of
1674 # its usage event (see _catch_all), for the one event that is written here.
1675 1162 ▶ my @kind = length($route{kind} // '') ? (kind => $route{kind}) : ();
Branch: 1 branch
BranchTrueFalseTotal
length($route{'kind'} // '') ? : 59 1103 1162
Condition100%2/2
$route{"kind"} // ""
l!l
591103
MC/DC100%1/1
$route{"kind"} // ""
$route{"kind"}
Truth table100%2/2
A
A= $route{"kind"}
Aresult
11
00
1676 1162 ▶ my $wait_poll_ms = 0 + ($c->skeid->route_wait_poll_ms // 25);
Condition50%1/2
$c->skeid->route_wait_poll_ms // 25
l!l
11620
MC/DC0%0/1
$c->skeid->route_wait_poll_ms // 25
$c->skeid->route_wait_poll_ms
Truth table50%1/2
A
A= $c->skeid->route_wait_poll_ms
Aresult
11
00
1677 1162 ▶ $wait_poll_ms = 1 if $wait_poll_ms < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $wait_poll_ms < 1 0 1162 1162
1678  
1679 1162 ▶ my $decision = $c->skeid->call_function('route.plan', {
Condition50%1/2
$model // ""
l!l
11620
MC/DC0%0/1
$model // ""
$model
Truth table50%1/2
A
A= $model
Aresult
11
00
1680 model => ($model // ''),
1681 api_key_id => $api_key_id,
1682 @kind,
1683 });
1684  
1685 # The key's policy does not grant this model, or grants it but forbids every tier that serves
1686 # it. Both are permission answers, and neither improves by retrying -- so neither may be
1687 # reported as a capacity problem.
1688 1162 ▶ if (!$decision->{permitted}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($decision->{"permitted"}) 20 1142 1162
1689 20 _render_error($c, 403, "Model '$model' is not available for this key", 'permission_error');
1690 20 $cb->();
1691 20 return;
1692 }
1693  
1694 # The key's request rate (skeid k125): over it, refused before anything is routed or admitted.
1695 1142 my $rate = $c->skeid->rate_admit($api_key_id);
1696 1142 ▶ unless ($rate->{ok}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rate->{"ok"}) 2 1140 1142
1697 2 _refuse_rate_limited($c, $model, $api_key_id, $rate->{retry_after}, \%route);
1698 2 $cb->();
1699 2 return;
1700 }
1701  
1702 1140 ▶ my $plan = $decision->{tiers} || [];
Condition50%1/2
$decision->{'tiers'} || []
l!l
11400
MC/DC0%0/1
$decision->{'tiers'} || []
$decision->{'tiers'}
Truth table50%1/2
A
A= $decision->{'tiers'}
Aresult
11
00
1703 1140 my $started = time;
1704 1140 my $saw_eligible = 0;
1705 1140 my $last_node_id = '';
1706 1140 my $index = 0;
1707 1140 my $tier_deadline = 0;
1708  
1709 1140 my $tick;
1710 my $wait_timer;
1711 73 ▶ my $fail = sub {
Subroutine __ANON__: called CC=12 SCAR=25.0
1712 # Nothing eligible can mean two different things once a policy is in play: the model is
1713 # unroutable, or it is routable and this key is not allowed at the nodes that serve it.
1714 # Only the failure path pays for telling them apart.
1715 73 ▶ if (!$saw_eligible && grep { @{$_->{deny_tags} || []} } @$plan) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $saw_eligible and grep {@{$_->{"deny_tags"} or [];};} @$plan) 15 58 73
Condition80%4/5
not $saw_eligible and grep {@{$_->{"deny_tags"} or [];};} @$plan
!ll&&!rl&&r
243415
$_->{'deny_tags'} || []
l!l
500
MC/DC100%2/2
not $saw_eligible and grep {@{$_->{"deny_tags"} or [];};} @$plan
not $saw_eligible grep {@{$_->{"deny_tags"} or [];};} @$plan
MC/DC0%0/1
$_->{'deny_tags'} || []
$_->{'deny_tags'}
Truth table100%3/3
not(A) and B
A= not $saw_eligibleB= grep {@{$_->{"deny_tags"} or [];};} @$plan
ABresult
0X0
100
111
Truth table50%1/2
A
A= $_->{'deny_tags'}
Aresult
11
00
1716 15 my $without_deny = 0;
1717 15 for my $tier (@$plan) {
1718 my $state = $c->skeid->call_function('route.state', {
1719 model => ($tier->{model} // ''),
1720 15 ▶ tags => ($tier->{tags} || []),
Condition50%2/4
$tier->{"model"} // ""
l!l
150
$tier->{'tags'} || []
l!l
150
MC/DC0%0/1
$tier->{"model"} // ""
$tier->{"model"}
MC/DC0%0/1
$tier->{'tags'} || []
$tier->{'tags'}
Truth table50%1/2
A
A= $tier->{"model"}
Aresult
11
00
Truth table50%1/2
A
A= $tier->{'tags'}
Aresult
11
00
1721 @kind,
1722 });
1723 15 ▶ $without_deny = 1, last if ref($state) eq 'HASH' && $state->{has_eligible};
Branch: 1 branch
BranchTrueFalseTotal
if ref $state eq "HASH" and $state->{"has_eligible"} 10 5 15
Condition66%2/3
ref $state eq "HASH" and $state->{"has_eligible"}
!ll&&!rl&&r
0510
MC/DC50%1/2
ref $state eq "HASH" and $state->{"has_eligible"}
ref $state eq "HASH" $state->{"has_eligible"}
Truth table66%2/3
A and B
A= ref $state eq "HASH"B= $state->{"has_eligible"}
ABresult
0X0
100
111
1724 }
1725 15 ▶ if ($without_deny) {
Branch: 1 branch
BranchTrueFalseTotal
if ($without_deny) 10 5 15
1726 10 _render_error($c, 403, "Model '$model' is not available for this key", 'permission_error');
1727 10 undef $tick;
1728 10 $cb->();
1729 10 return;
1730 }
1731 }
1732  
1733 63 ▶ if (!$saw_eligible) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $saw_eligible) { } 39 24 63
1734 39 _render_error($c, 503, "No healthy node available for model '$model'", 'model_not_found');
1735 } else {
1736 24 my $waited_ms = int((time - $started) * 1000);
1737 24 ▶ my $msg = length($last_node_id)
Branch: 1 branch
BranchTrueFalseTotal
length $last_node_id ? : 0 24 24
1738 ? "Timed out waiting for free capacity on node '$last_node_id' (waited ${waited_ms}ms)"
1739 : "Timed out waiting for free capacity for model '$model' (waited ${waited_ms}ms)";
1740 24 _render_error($c, 429, $msg, 'rate_limit_error');
1741 }
1742 63 undef $tick;
1743 63 $cb->();
1744 63 return;
1745 1140 };
1746  
1747 1463 ▶ $tick = sub {
Subroutine __ANON__: called CC=16 SCAR=28.7
1748 1463 ▶ return $fail->() if $index > $#$plan;
Branch: 1 branch
BranchTrueFalseTotal
if $index > $plan->$#* 73 1390 1463
1749  
1750 1390 my $tier = $plan->[$index];
1751 my %selector = (
1752 model => ($tier->{model} // ''),
1753 tags => ($tier->{tags} || []),
1754 deny_tags => ($tier->{deny_tags} || []),
1755 1390 ▶ (length($tier->{engine} // '') ? (engine => $tier->{engine}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
length($tier->{'engine'} // '') ? : 0 1390 1390
Condition50%4/8
$tier->{"model"} // ""
l!l
13900
$tier->{'tags'} || []
l!l
13900
$tier->{'deny_tags'} || []
l!l
13900
$tier->{"engine"} // ""
l!l
13900
MC/DC0%0/1
$tier->{"model"} // ""
$tier->{"model"}
MC/DC0%0/1
$tier->{'tags'} || []
$tier->{'tags'}
MC/DC0%0/1
$tier->{'deny_tags'} || []
$tier->{'deny_tags'}
MC/DC0%0/1
$tier->{"engine"} // ""
$tier->{"engine"}
Truth table50%1/2
A
A= $tier->{"model"}
Aresult
11
00
Truth table50%1/2
A
A= $tier->{'tags'}
Aresult
11
00
Truth table50%1/2
A
A= $tier->{'deny_tags'}
Aresult
11
00
Truth table50%1/2
A
A= $tier->{"engine"}
Aresult
11
00
1756 @kind,
1757 );
1758  
1759 1390 my $state = $c->skeid->call_function('route.state', \%selector);
1760 1390 ▶ if (ref($state) eq 'HASH' && $state->{has_eligible}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $state eq "HASH" and $state->{"has_eligible"}) 1337 53 1390
Condition66%2/3
ref $state eq "HASH" and $state->{"has_eligible"}
!ll&&!rl&&r
0531337
MC/DC50%1/2
ref $state eq "HASH" and $state->{"has_eligible"}
ref $state eq "HASH" $state->{"has_eligible"}
Truth table66%2/3
A and B
A= ref $state eq "HASH"B= $state->{"has_eligible"}
ABresult
0X0
100
111
1761 1337 $saw_eligible = 1;
1762  
1763 1337 my $route = $c->skeid->call_function('route.next', \%selector)->{node};
1764 1337 ▶ if ($route && ref($route) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($route and ref $route eq "HASH") 1065 272 1337
Condition66%2/3
$route and ref $route eq "HASH"
!ll&&!rl&&r
27201065
MC/DC50%1/2
$route and ref $route eq "HASH"
$route ref $route eq "HASH"
Truth table66%2/3
A and B
A= $routeB= ref $route eq "HASH"
ABresult
0X0
100
111
1765 1065 my $node_id = $route->{id};
1766 1065 ▶ $last_node_id = $node_id if defined $node_id;
Branch: 1 branch
BranchTrueFalseTotal
if defined $node_id 1065 0 1065
1767 1065 ▶ if ($c->skeid->call_function('request.start', { id => $node_id })->{ok}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->skeid->call_function("request.start", {"id", $node_id})->{"ok"}) 1065 0 1065
1768 # Break the recursive callback's self-reference before control moves into the upstream
1769 # lifecycle. The active call frame keeps it alive until this invocation returns.
1770 1065 undef $tick;
1771 1065 $cb->($route, $node_id, $started, $tier);
1772 1065 return;
1773 }
1774 }
1775  
1776 # Eligible but nothing free: this tier is worth waiting on, up to its own window.
1777 272 ▶ if (time < $tier_deadline) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Langertha::Skeid::Proxy::time() < $tier_deadline) 244 28 272
1778 244 $wait_timer = Mojo::IOLoop->timer($wait_poll_ms / 1000, $tick);
1779 244 return;
1780 }
1781 }
1782  
1783 81 $index++;
1784 81 ▶ $tier_deadline = time + (($plan->[$index] ? ($plan->[$index]{wait_ms} // 0) : 0) / 1000);
Branch: 1 branch
BranchTrueFalseTotal
$plan->[$index] ? : 8 73 81
Condition50%1/2
$plan->[$index]{"wait_ms"} // 0
l!l
80
MC/DC0%0/1
$plan->[$index]{"wait_ms"} // 0
$plan->[$index]{"wait_ms"}
Truth table50%1/2
A
A= $plan->[$index]{"wait_ms"}
Aresult
11
00
1785 81 $tick->();
1786 81 return;
1787 1140 };
1788  
1789 # A client that hangs up while its request waits for capacity stops waiting: the next poll
1790 # would take a slot for nobody and never give it back. $tick is set exactly as long as
1791 # admission is undecided, which tells this finish from the one every answered request emits
1792 # as well. Nothing is rendered, there is nobody to read it. A stand-in controller has no
1793 # transaction.
1794 # On a WebSocket route that has not been upgraded the transaction that closes when the client
1795 # leaves is the handshake's, not the WebSocket one the controller holds (skeid k95).
1796 1140 ▶ if ($c->can('tx') && $c->tx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->can("tx") and $c->tx) 1137 3 1140
Condition66%2/3
$c->can("tx") and $c->tx
!ll&&!rl&&r
301137
MC/DC50%1/2
$c->can("tx") and $c->tx
$c->can("tx") $c->tx
Truth table66%2/3
A and B
A= $c->can("tx")B= $c->tx
ABresult
0X0
100
111
1797 1137 my $tx = $c->tx;
1798 1137 ▶ $tx = $tx->handshake if $tx->is_websocket && !$tx->established && $tx->can('handshake');
Branch: 1 branch
BranchTrueFalseTotal
if $tx->is_websocket and not $tx->established and $tx->can("handshake") 95 1042 1137
Condition66%4/6
$tx->is_websocket and not $tx->established and $tx->can("handshake")
!ll&&!rl&&r
1042095
$tx->is_websocket and not $tx->established
!ll&&!rl&&r
1042095
MC/DC33%1/3
$tx->is_websocket and not $tx->established and $tx->can("handshake")
$tx->is_websocket not $tx->established $tx->can("handshake")
Truth table50%2/4
A and not(B) and C
A= $tx->is_websocketB= not $tx->establishedC= $tx->can("handshake")
ABCresult
0XX0
10X0
1100
1111
1799 1137 ▶ $tx->on(finish => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1800 1137 ▶ return unless $tick;
Branch: 1 branch
BranchTrueFalseTotal
unless $tick 1135 2 1137
1801 2 ▶ Mojo::IOLoop->remove($wait_timer) if defined $wait_timer;
Branch: 1 branch
BranchTrueFalseTotal
if defined $wait_timer 2 0 2
1802 2 undef $tick;
1803 2 $cb->();
1804 1137 });
1805 }
1806  
1807 1140 ▶ $tier_deadline = time + ((@$plan ? ($plan->[0]{wait_ms} // 0) : 0) / 1000);
Branch: 1 branch
BranchTrueFalseTotal
@$plan ? : 1140 0 1140
Condition50%1/2
$plan->[0]{"wait_ms"} // 0
l!l
11400
MC/DC0%0/1
$plan->[0]{"wait_ms"} // 0
$plan->[0]{"wait_ms"}
Truth table50%1/2
A
A= $plan->[0]{"wait_ms"}
Aresult
11
00
1808 1140 $tick->();
1809 1140 return;
1810 }
1811  
1812 # True once the client of this request cannot be answered any more: its transaction was closed,
1813 # or is destroyed already -- the controller holds it weakly. Only asked before anything was
1814 # rendered, because a transaction that was answered is finished as well.
1815 1087 ▶sub _client_gone {
Subroutine _client_gone: called CC=3 SCAR=11.0
1816 1087 my ($c) = @_;
1817 1087 my $tx = $c->tx;
1818 1087 ▶ return (!$tx || $tx->is_finished) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
!$tx || $tx->is_finished ? : 3 1084 1087
Condition66%2/3
not $tx or $tx->is_finished
l!l&&r!l&&!r
301084
MC/DC50%1/2
not $tx or $tx->is_finished
not $tx $tx->is_finished
Truth table66%2/3
not(A) or B
A= not $txB= $tx->is_finished
ABresult
1X1
011
000
1819 }
1820  
1821 # Ends an upstream transaction in flight by closing its connection. The user agent then drops
1822 # the connection instead of pooling it and runs the transaction's completion callback, and the
1823 # node sees the connection close, which is what makes it stop generating. A transaction that
1824 # is still connecting is closed as soon as it has a connection -- one tick later, because the
1825 # user agent is in the middle of setting that connection up when it announces it. A finished
1826 # transaction is left alone: its connection may be serving another request by now.
1827 22 ▶sub _cancel_upstream {
Subroutine _cancel_upstream: called CC=2 SCAR=6.9
1828 22 my ($tx) = @_;
1829 22 ▶ my $close = sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
1830 22 my ($id) = @_;
1831 22 ▶ return if $tx->is_finished;
Branch: 1 branch
BranchTrueFalseTotal
if $tx->is_finished 0 22 22
1832 22 ▶ my $stream = Mojo::IOLoop->stream($id) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $stream = "Mojo::IOLoop"->stream($id) or return 22 0 22
1833 22 $stream->close;
1834 22 return;
1835 22 };
1836 22 ▶ if (defined(my $id = $tx->connection)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $id = $tx->connection)) 21 1 22
1837 21 $close->($id);
1838 21 return;
1839 }
1840 1 ▶ $tx->once(connection => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1841 1 my (undef, $id) = @_;
1842 1 ▶ Mojo::IOLoop->next_tick(sub { $close->($id) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1843 1 });
1844 1 return;
1845 }
1846  
1847 # A status that says the request, not the node, was at fault (k99, ADR 0024). 401, 403 and 429
1848 # are not here: they speak of the node's key or capacity and stay node errors.
1849 98 ▶sub _client_fault {
Subroutine _client_fault: called CC=3 SCAR=11.0
1850 98 my ($status) = @_;
1851 98 ▶ return (defined $status && $status =~ /\A(?:400|404|413|422)\z/) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $status && $status =~ /\A(?:400|404|413|422)\z/ ? : 20 78 98
Condition100%3/3
defined $status and $status =~ /\A(?:400|404|413|422)\z/
!ll&&!rl&&r
96920
MC/DC100%2/2
defined $status and $status =~ /\A(?:400|404|413|422)\z/
defined $status $status =~ /\A(?:400|404|413|422)\z/
Truth table100%3/3
A and B
A= defined $statusB= $status =~ /\A(?:400|404|413|422)\z/
ABresult
0X0
100
111
1852 }
1853  
1854 # What a request its client abandoned records (ADR 0004): failed, under the status nginx made
1855 # the convention for "client closed request" -- no answer was delivered, and 499 can be told
1856 # from every status a node or Skeid itself answers with.
1857 14 ▶sub _client_abort_event {
Subroutine _client_abort_event: called CC=1 SCAR=0.0
1858 return (
1859 14 status_code => 499,
1860 ok => 0,
1861 error_type => 'client_abort',
1862 error_message => 'Client closed the connection before the response was complete',
1863 );
1864 }
1865  
1866 # $translate is an optional coderef that turns the decoded upstream answer into what the client
1867 # gets. It runs before the request is finished and metered, so a translator that dies is one
1868 # failed request -- one usage event with ok => 0, an error in the face's own shape -- and the
1869 # callback gets the translated payload as its fifth argument, or nothing after an error.
1870 #
1871 # $relay is what a route relayed in the upstream's own shape brings (ADR 0021), all optional:
1872 # `request`, a code ref called with the user agent, the URL and the upstream headers that builds
1873 # the upstream transaction instead of the JSON one made from $body; `units`, a code ref that
1874 # reads the route's own usage units off the decoded answer and returns them as event fields;
1875 # and, for a stream, `delta_text`, which returns the text of a frame in the route's own dialect.
1876 # Two more for an answer that is not chat-shaped (rerank, skeid k92), both called with the
1877 # decoded answer -- whatever JSON it is -- and the upstream response: `usage` returns the usage
1878 # block to meter, or nothing, where the answer reports its tokens somewhere else than a chat
1879 # answer does; `answer` is $translate for a node whose own dialect is not the client's, and
1880 # fails the same way.
1881 699 ▶sub _proxy_openai_json_async {
Subroutine _proxy_openai_json_async: called CC=4 SCAR=13.9
1882 699 my ($c, $url, $body, $node_id, $started, $meta, $cb, $translate, $relay) = @_;
1883 699 ▶ $meta ||= {};
Condition50%1/2
$meta ||= {}
l!l
6990
MC/DC0%0/1
$meta ||= {}
$meta
Truth table50%1/2
A
A= $meta
Aresult
11
00
1884 699 ▶ $cb ||= sub { };
Subroutine __ANON__: not called CC=1 SCAR=1.2
Condition33%1/3
$cb ||= sub { }
l!l&&r!l&&!r
69900
MC/DC0%0/2
$cb ||= sub { }
$cb sub { }
Truth table33%1/3
A ||= B
A= $cbB= sub { }
ABresult
1X1
011
000
1885 699 ▶ $relay ||= {};
Condition100%2/2
$relay ||= {}
l!l
437262
MC/DC100%1/1
$relay ||= {}
$relay
Truth table100%2/2
A
A= $relay
Aresult
11
00
1886  
1887 699 my %fwd_headers = _forward_headers($c, $node_id);
1888 699 ▶ _inject_node_auth_async(\%fwd_headers, $c->skeid, $node_id, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1889 699 my ($no_key) = @_;
1890  
1891 # The client hung up while the node key was being resolved, whether or not it resolved -- asked
1892 # before the refusal, which would meter and answer a transaction nobody holds any more. Nothing went upstream: the slot
1893 # is given back and nothing is metered, as for every request that was not forwarded.
1894 699 ▶ if (_client_gone($c)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_client_gone($c)) 2 697 699
1895 2 $c->skeid->call_function('request.finish', {
1896 id => $node_id,
1897 ok => 0,
1898 aborted => 1,
1899 duration_ms => _duration_ms($started),
1900 });
1901 2 $cb->(undef, 1, 499);
1902 2 return;
1903 }
1904  
1905 697 ▶ if (defined $no_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $no_key) 34 663 697
1906 34 _refuse_unkeyed_node($c, $node_id, $started, $meta, $no_key);
1907 34 $cb->(undef, 1, 503);
1908 34 return;
1909 }
1910 663 my $tx = _upstream_tx($c, $url, \%fwd_headers, $body, $relay);
1911  
1912 # Set by whichever comes first, the upstream's completion or the client hanging up, so that
1913 # request.finish and the usage event happen once.
1914 663 my $closed = 0;
1915  
1916 663 ▶ $c->tx->on(finish => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1917 663 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 656 7 663
1918 7 $closed = 1;
1919 7 my $duration_ms = _duration_ms($started);
1920 7 $c->skeid->call_function('request.finish', {
1921 id => $node_id,
1922 ok => 0,
1923 aborted => 1,
1924 duration_ms => $duration_ms,
1925 });
1926 7 _record_usage_event($c, {
1927 %$meta,
1928 _client_abort_event(),
1929 node_id => $node_id,
1930 duration_ms => $duration_ms,
1931 metrics => {},
1932 });
1933 7 _cancel_upstream($tx);
1934 7 $cb->(undef, 1, 499);
1935 663 });
1936  
1937 663 ▶ $c->app->ua->start($tx => sub {
Subroutine __ANON__: called CC=25 SCAR=32.3
1938 663 my ($ua, $done) = @_;
1939 # The client hung up and its request was closed then; this is the cancelled transaction.
1940 663 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 7 656 663
1941 656 $closed = 1;
1942 656 my $duration_ms = _duration_ms($started);
1943 656 my $res = $done->res;
1944  
1945 # Mojo reports an HTTP 4xx/5xx through tx->error too. Observe the response that actually
1946 # arrived before taking that error return, so a 429's Retry-After can gate the next request.
1947 # A transport failure has no useful status or headers and _observe_capacity records nothing.
1948 656 _observe_capacity($c, $node_id, $res);
1949  
1950 656 ▶ if (my $err = $done->error) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $done->error) 47 609 656
1951 $c->skeid->call_function('request.finish', {
1952 id => $node_id,
1953 ok => 0,
1954 47 ▶ _client_fault($err->{code}) ? (rejected => 1) : (),
Branch: 1 branch
BranchTrueFalseTotal
_client_fault($err->{'code'}) ? : 13 34 47
1955 duration_ms => $duration_ms,
1956 });
1957 _record_usage_event($c, {
1958 %$meta,
1959 node_id => $node_id,
1960 status_code => ($err->{code} || 502),
1961 ok => 0,
1962 duration_ms => $duration_ms,
1963 error_type => 'upstream_error',
1964 47 ▶ error_message => ($err->{message} // 'unknown'),
Condition75%3/4
$err->{'code'} || 502
l!l
389
$err->{"message"} // "unknown"
l!l
470
MC/DC100%1/1
$err->{'code'} || 502
$err->{'code'}
MC/DC0%0/1
$err->{"message"} // "unknown"
$err->{"message"}
Truth table100%2/2
A
A= $err->{'code'}
Aresult
11
00
Truth table50%1/2
A
A= $err->{"message"}
Aresult
11
00
1965 metrics => {},
1966 });
1967 47 ▶ _render_error($c, ($err->{code} || 502),
Condition100%2/2
$err->{'code'} || 502
l!l
389
MC/DC100%1/1
$err->{'code'} || 502
$err->{'code'}
Truth table100%2/2
A
A= $err->{'code'}
Aresult
11
00
1968 'Upstream error: ' . _upstream_error_message($err, $done->res->body), 'upstream_error');
1969 47 ▶ $cb->(undef, 1, ($err->{code} || 502));
Condition100%2/2
$err->{'code'} || 502
l!l
389
MC/DC100%1/1
$err->{'code'} || 502
$err->{'code'}
Truth table100%2/2
A
A= $err->{'code'}
Aresult
11
00
1970 47 return;
1971 }
1972  
1973 609 ▶ my $status = $res->code // 200;
Condition50%1/2
$res->code // 200
l!l
6090
MC/DC0%0/1
$res->code // 200
$res->code
Truth table50%1/2
A
A= $res->code
Aresult
11
00
1974 # A route that names a bound leaves a larger answer undecoded (a converted document is
1975 # megabytes, and decoding it is CPU on the loop); its units then say nothing.
1976 my $payload = (defined($relay->{max_parse_bytes}) && ($res->body_size // 0) > $relay->{max_parse_bytes})
1977 609 ▶ ? undef : eval { $res->json };
Branch: 1 branch
BranchTrueFalseTotal
defined $relay->{'max_parse_bytes'} && ($res->body_size // 0) > $relay->{'max_parse_bytes'} ? : 1 608 609
Condition80%4/5
defined $relay->{"max_parse_bytes"} and ($res->body_size // 0) > $relay->{"max_parse_bytes"}
!ll&&!rl&&r
562461
$res->body_size // 0
l!l
470
MC/DC50%1/2
defined $relay->{"max_parse_bytes"} and ($res->body_size // 0) > $relay->{"max_parse_bytes"}
defined $relay->{"max_parse_bytes"} $res->body_size
Truth table66%2/3
A and B
A= defined $relay->{"max_parse_bytes"}B= $res->body_size
ABresult
0X0
100
111
1978  
1979 609 my $translated;
1980 609 ▶ if ($translate || $relay->{answer}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($translate or $relay->{"answer"}) 253 356 609
Condition100%3/3
$translate or $relay->{"answer"}
l!l&&r!l&&!r
23122356
MC/DC100%2/2
$translate or $relay->{"answer"}
$translate $relay->{"answer"}
Truth table100%3/3
A or B
A= $translateB= $relay->{"answer"}
ABresult
1X1
011
000
1981 253 $translated = eval {
1982 $relay->{answer}
1983 253 ▶ ? $relay->{answer}->($payload, $res)
Branch: 2 branches
BranchTrueFalseTotal
$relay->{'answer'} ? : 22 231 253
ref $payload eq 'HASH' ? : 230 1 231
1984 : $translate->(ref($payload) eq 'HASH' ? $payload : {});
1985 };
1986 253 ▶ unless (defined $translated) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $translated) 4 249 253
1987 4 $c->app->log->error('Translating the answer of node ' . $node_id . ' failed');
1988 4 $c->skeid->call_function('request.finish', {
1989 id => $node_id,
1990 ok => 0,
1991 duration_ms => $duration_ms,
1992 });
1993 4 _record_usage_event($c, {
1994 %$meta,
1995 node_id => $node_id,
1996 status_code => 500,
1997 ok => 0,
1998 duration_ms => $duration_ms,
1999 error_type => 'translation_error',
2000 error_message => 'Response translation failed',
2001 metrics => {},
2002 });
2003 4 _render_error($c, 500, 'Response translation failed', 'api_error');
2004 4 $cb->(undef, 1, 500);
2005 4 return;
2006 }
2007 }
2008  
2009 605 ▶ $c->skeid->call_function('request.finish', {
Branch: 1 branch
BranchTrueFalseTotal
$status < 500 ? : 605 0 605
2010 id => $node_id,
2011 ok => ($status < 500) ? 1 : 0,
2012 duration_ms => $duration_ms,
2013 });
2014  
2015 605 my $metrics = {};
2016 605 ▶ if ($relay->{usage}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($relay->{'usage'}) { } 99 506 605
elsif (ref $payload eq 'HASH') { } 502 4 506
2017 99 my $usage = $relay->{usage}->($payload, $res);
2018 99 ▶ $metrics = _priced_metrics($c, $meta, $body, $duration_ms, { usage => $usage })
Branch: 1 branch
BranchTrueFalseTotal
if ref $usage eq "HASH" 50 49 99
2019 if ref($usage) eq 'HASH';
2020 } elsif (ref($payload) eq 'HASH') {
2021 502 ▶ my $tool_calls = eval { [ map { $_->to_hash } Langertha::ToolCall->extract('openai', $payload) ] } || [];
Condition50%1/2
eval { do { [map({$_->to_hash;} 'Langertha::ToolCall'->extract('openai', $payload))] } } || []
l!l
5020
MC/DC0%0/1
eval { do { [map({$_->to_hash;} 'Langertha::ToolCall'->extract('openai', $payload))] } } || []
eval { do { [map({$_->to_hash;} 'Langertha::ToolCall'->extract('openai', $payload))] } }
Truth table50%1/2
A
A= eval { do { [map({$_->to_hash;} 'Langertha::ToolCall'->extract('openai', $payload))] } }
Aresult
11
00
2022 502 $metrics = _priced_metrics($c, $meta, $body, $duration_ms, $payload, $tool_calls);
2023 }
2024  
2025 _record_usage_event($c, {
2026 %$meta,
2027 node_id => $node_id,
2028 status_code => $status,
2029 ok => ($status < 500) ? 1 : 0,
2030 duration_ms => $duration_ms,
2031 metrics => $metrics,
2032 finish_reason => _payload_finish_reason($payload),
2033 605 ▶ ($relay->{units} ? $relay->{units}->($payload, $res) : ()),
Branch: 2 branches
BranchTrueFalseTotal
$status < 500 ? : 605 0 605
$relay->{'units'} ? : 137 468 605
2034 });
2035  
2036 605 ▶ $cb->($res, 0, $status, (ref($payload) eq 'HASH' ? $payload : {}), $translated);
Branch: 1 branch
BranchTrueFalseTotal
ref $payload eq 'HASH' ? : 576 29 605
2037 663 });
2038 699 });
2039  
2040 699 return;
2041 }
2042  
2043 # $stream is an optional translator (Protocol::*::Stream). Without one the upstream's bytes are
2044 # relayed untouched, which is what an OpenAI client wants and the only path that cannot lose
2045 # anything in translation. With one, each OpenAI chunk is decoded and re-emitted in the
2046 # client's own format -- the same edge-translation seam as the non-streaming path (ADR 0001).
2047 # $relay is as for _proxy_openai_json_async.
2048 267 ▶sub _proxy_openai_stream {
Subroutine _proxy_openai_stream: called CC=3 SCAR=11.0
2049 267 my ($c, $url, $body, $node_id, $started, $meta, $stream, $relay) = @_;
2050 267 ▶ $meta ||= {};
Condition50%1/2
$meta ||= {}
l!l
2670
MC/DC0%0/1
$meta ||= {}
$meta
Truth table50%1/2
A
A= $meta
Aresult
11
00
2051 267 ▶ $relay ||= {};
Condition100%2/2
$relay ||= {}
l!l
93174
MC/DC100%1/1
$relay ||= {}
$relay
Truth table100%2/2
A
A= $relay
Aresult
11
00
2052  
2053 267 my %fwd_headers = _forward_headers($c, $node_id);
2054  
2055 # render_later before the key resolution, not after: a cold cache means the callback runs on
2056 # a later tick, and Mojolicious would have rendered an empty response by then.
2057 267 $c->render_later;
2058  
2059 267 ▶ _inject_node_auth_async(\%fwd_headers, $c->skeid, $node_id, sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
2060 267 my ($no_key) = @_;
2061  
2062 # The client hung up while the node key was being resolved, whether or not it resolved -- asked
2063 # before the refusal, which would meter and answer a transaction nobody holds any more. Nothing
2064 # went upstream: the slot is given back and nothing is metered, as for every request that was
2065 # not forwarded. Nothing is set up yet, so there is nothing to take apart.
2066 267 ▶ if (_client_gone($c)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_client_gone($c)) 1 266 267
2067 1 $c->skeid->call_function('request.finish', {
2068 id => $node_id,
2069 ok => 0,
2070 aborted => 1,
2071 duration_ms => _duration_ms($started),
2072 });
2073 1 return;
2074 }
2075  
2076 266 ▶ return _refuse_unkeyed_node($c, $node_id, $started, $meta, $no_key) if defined $no_key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $no_key 25 241 266
2077 241 my $tx = _upstream_tx($c, $url, \%fwd_headers, $body, $relay);
2078 # Mojolicious would parse an unchunked, exactly-text/event-stream body into its own `sse`
2079 # events and never emit `read` -- the relay would forward nothing (skeid karr #30).
2080 241 $tx->res->content(Langertha::Skeid::Proxy::RelayContent->new);
2081  
2082 241 my $headers_sent = 0;
2083 241 my $had_error = 0;
2084 # Taken now: the header goes out before the first byte, and the request may be past its
2085 # transaction by then.
2086 241 my $request_id = _request_id($c);
2087 # A translator that can report errors in its own format (Anthropic, Ollama) takes the failure
2088 # paths too: an upstream error status before the stream opens becomes a plain HTTP error in
2089 # the client's shape, a failure after it becomes an in-band error event (core karr #224).
2090 241 ▶ my $stream_errors = $stream && $stream->can('error_event');
Condition66%2/3
$stream && $stream->can('error_event')
!ll&&!rl&&r
830158
MC/DC50%1/2
$stream && $stream->can('error_event')
$stream $stream->can('error_event')
Truth table66%2/3
A && B
A= $streamB= $stream->can('error_event')
ABresult
0X0
100
111
2091 241 my $upstream_failed = 0;
2092 241 my $upstream_error_body = '';
2093 241 my $status = 200;
2094 # The upstream's own usage block, verbatim, so a stream is priced by the same metrics.normalize
2095 # call as a non-streamed answer (skeid #41). undef until a frame carries one.
2096 241 my $upstream_usage;
2097 241 my $accumulated_content_bytes = 0;
2098 # The usage contract (skeid k121): how the answer ended, and when its first token came.
2099 241 my ($finish_reason, $ttft_ms);
2100 241 ▶ my $answer_facts = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2101 241 ▶ return (finish_reason => $finish_reason, (defined($ttft_ms) ? (ttft_ms => $ttft_ms) : ()));
Branch: 1 branch
BranchTrueFalseTotal
defined $ttft_ms ? : 215 26 241
2102 241 };
2103 # UTF-8 bytes of the content this stream relayed or translated, for the usage event (skeid #36).
2104 # A relayed stream counts off the OpenAI deltas it read along; a translated one takes its
2105 # translator's own count -- the text it actually wrote in the client's format. An observation
2106 # recorded beside the token counts, never a substitute for them.
2107 241 ▶ my $content_bytes = sub { $stream ? 0 + ((($stream->usage)[2]) // 0) : $accumulated_content_bytes };
Subroutine __ANON__: called CC=3 SCAR=11.1
Branch: 1 branch
BranchTrueFalseTotal
$stream ? : 158 83 241
Condition50%1/2
($stream->usage)[2] // 0
l!l
1580
MC/DC0%0/1
($stream->usage)[2] // 0
($stream->usage)[2]
Truth table50%1/2
A
A= ($stream->usage)[2]
Aresult
11
00
2108 # The route's own usage units (ADR 0021), read off the usage the stream carried so far -- the
2109 # same block a non-streamed answer would have carried. Nothing until a frame had one.
2110 241 ▶ my $units = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2111 241 ▶ return () unless $relay->{units} && ref($upstream_usage) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $relay->{"units"} and ref $upstream_usage eq "HASH" 232 9 241
Condition100%3/3
$relay->{"units"} and ref $upstream_usage eq "HASH"
!ll&&!rl&&r
22399
MC/DC100%2/2
$relay->{"units"} and ref $upstream_usage eq "HASH"
$relay->{"units"} ref $upstream_usage eq "HASH"
Truth table100%3/3
A and B
A= $relay->{"units"}B= ref $upstream_usage eq "HASH"
ABresult
0X0
100
111
2112 9 return $relay->{units}->({ usage => $upstream_usage });
2113 241 };
2114  
2115 # Upstream chunks arrive faster than they can be written out, so they are queued and drained
2116 # one at a time. Writing each chunk directly would end the response after the first one:
2117 # a dynamic Mojolicious response with no drain callback is finished once its write queue
2118 # empties, and every later chunk then hits a destroyed transaction. The client sees headers,
2119 # no body, and no error.
2120 241 my @queue;
2121 241 my $draining = 0;
2122 241 my $upstream_done = 0;
2123 241 my $finished = 0;
2124  
2125 241 my $drain;
2126 961 ▶ $drain = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
2127 961 ▶ if (!@queue) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@queue) 435 526 961
2128 435 $draining = 0;
2129 435 ▶ if ($upstream_done && !$finished) {
Branch: 1 branch
BranchTrueFalseTotal
if ($upstream_done and not $finished) 187 248 435
Condition66%2/3
$upstream_done and not $finished
!ll&&!rl&&r
2480187
MC/DC50%1/2
$upstream_done and not $finished
$upstream_done not $finished
Truth table66%2/3
A and not(B)
A= $upstream_doneB= not $finished
ABresult
0X0
100
111
2130 187 $finished = 1;
2131 187 $c->finish;
2132 # write_chunk retains its last drain callback. Clear the recursive callback scalar once
2133 # the queue is complete so that callback cannot retain the controller through $drain.
2134 187 undef $drain;
2135 }
2136 435 return;
2137 }
2138 526 $draining = 1;
2139 526 my $chunk = shift @queue;
2140 526 ▶ $c->write_chunk($chunk => sub { $drain->() if $drain });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $drain 525 0 525
2141 241 };
2142  
2143 # SSE frames do not respect read boundaries: one read can carry half a frame, and the half
2144 # that completes it arrives in the next. Parsing per read would silently drop the split
2145 # frame -- usually the last one, which is the one carrying usage.
2146 241 my $pending = '';
2147  
2148 # Set by whichever comes first, the upstream's completion, the client hanging up or a
2149 # translator that died, so that request.finish and the usage event happen once.
2150 241 my $closed = 0;
2151  
2152 # A translator that dies on a chunk ends the request here, not in the upstream callback the
2153 # exception would escape from: the upstream is cancelled, the slot given back, one failed usage
2154 # event written, and the client answered in its own face's error shape -- an HTTP error when
2155 # nothing was queued for it yet, an in-band error event when the stream is open. The
2156 # exception's text is neither logged nor sent: it is the translator's own and may quote the
2157 # request.
2158 241 my $wrote = 0;
2159 7 ▶ my $fail_translation = sub {
Subroutine __ANON__: called CC=10 SCAR=25.3
2160 7 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 0 7 7
2161 7 $closed = 1;
2162 7 $tx->res->content->unsubscribe('read');
2163 7 my $duration_ms = _duration_ms($started);
2164 7 $c->skeid->call_function('request.finish', {
2165 id => $node_id,
2166 ok => 0,
2167 duration_ms => $duration_ms,
2168 });
2169 7 _record_usage_event($c, {
2170 %$meta,
2171 node_id => $node_id,
2172 status_code => 500,
2173 ok => 0,
2174 duration_ms => $duration_ms,
2175 error_type => 'translation_error',
2176 error_message => 'Stream translation failed',
2177 content_bytes => $content_bytes->(),
2178 $answer_facts->(),
2179 metrics => _stream_metrics($c, $meta, $body, $duration_ms, $upstream_usage),
2180 $units->(),
2181 });
2182 7 _cancel_upstream($tx);
2183 7 $upstream_done = 1;
2184 7 ▶ if (!$wrote) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($wrote) 4 3 7
2185 4 $c->res->headers->remove($_) for @{$c->res->headers->names};
2186 4 $c->res->headers->header('x-request-id' => $request_id);
2187 4 _render_error($c, 500, 'Stream translation failed', 'api_error');
2188 4 undef $drain;
2189 4 return;
2190 }
2191 3 ▶ my $frame = eval { $stream_errors ? $stream->error_event(500, 'Stream translation failed') : '' };
Branch: 1 branch
BranchTrueFalseTotal
$stream_errors ? : 3 0 3
2192 3 ▶ push @queue, $frame if defined $frame && length $frame;
Branch: 1 branch
BranchTrueFalseTotal
if defined $frame and length $frame 3 0 3
Condition33%1/3
defined $frame and length $frame
!ll&&!rl&&r
003
MC/DC0%0/2
defined $frame and length $frame
defined $frame length $frame
Truth table33%1/3
A and B
A= defined $frameB= length $frame
ABresult
0X0
100
111
2193 3 ▶ $drain->() unless $draining;
Branch: 1 branch
BranchTrueFalseTotal
unless $draining 3 0 3
2194 3 ▶ if (!$draining && !$finished) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $draining || $finished) 0 3 3
Condition33%1/3
$draining || $finished
l!l&&r!l&&!r
300
MC/DC0%0/2
$draining || $finished
$draining $finished
Truth table33%1/3
A || B
A= $drainingB= $finished
ABresult
1X1
011
000
2195 0 $finished = 1;
2196 0 $c->finish;
2197 0 undef $drain;
2198 }
2199 241 };
2200  
2201 639 ▶ $tx->res->content->unsubscribe('read')->on(read => sub {
Subroutine __ANON__: called CC=41 SCAR=37.4
2202 639 my ($content, $bytes) = @_;
2203 # Kept only to lift the upstream's own error message into the error the client gets.
2204 639 ▶ return $upstream_error_body .= $bytes if $upstream_failed;
Branch: 1 branch
BranchTrueFalseTotal
if $upstream_failed 0 639 639
2205 639 ▶ unless ($headers_sent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($headers_sent) 236 403 639
2206 236 ▶ $status = $tx->res->code // 200;
Condition50%1/2
$tx->res->code // 200
l!l
2360
MC/DC0%0/1
$tx->res->code // 200
$tx->res->code
Truth table50%1/2
A
A= $tx->res->code
Aresult
11
00
2207 # The upstream refused before streaming anything. Opening an SSE response for it would
2208 # hand the client a 4xx/5xx event stream with no events in it; leave the response unsent
2209 # and let the completion callback answer it as an error, as the non-streaming path does.
2210 236 ▶ if ($stream_errors && $status >= 400) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream_errors and $status >= 400) 11 225 236
Condition100%3/3
$stream_errors and $status >= 400
!ll&&!rl&&r
8114411
MC/DC100%2/2
$stream_errors and $status >= 400
$stream_errors $status >= 400
Truth table100%3/3
A and B
A= $stream_errorsB= $status >= 400
ABresult
0X0
100
111
2211 11 $upstream_failed = 1;
2212 11 $upstream_error_body .= $bytes;
2213 11 return;
2214 }
2215 225 $c->res->code($status);
2216 225 for my $name (@{$tx->res->headers->names}) {
2217 949 my $lc = lc($name);
2218 949 ▶ next if _skip_response_header($lc);
Branch: 1 branch
BranchTrueFalseTotal
if _skip_response_header($lc) 227 722 949
2219 # A translated stream is not the upstream's media type any more. Relaying
2220 # text/event-stream to an Ollama client tells it to parse something it does not speak.
2221 722 ▶ next if $stream && $lc eq 'content-type';
Branch: 1 branch
BranchTrueFalseTotal
if $stream and $lc eq "content-type" 144 578 722
Condition100%3/3
$stream and $lc eq "content-type"
!ll&&!rl&&r
267311144
MC/DC100%2/2
$stream and $lc eq "content-type"
$stream $lc eq "content-type"
Truth table100%3/3
A and B
A= $streamB= $lc eq "content-type"
ABresult
0X0
100
111
2222 578 $c->res->headers->header($name => $tx->res->headers->header($name));
2223 }
2224 225 ▶ $c->res->headers->header('content-type' => $stream->content_type) if $stream;
Branch: 1 branch
BranchTrueFalseTotal
if $stream 144 81 225
2225 225 $c->res->headers->header('x-skeid-node' => $node_id);
2226 225 $c->res->headers->header('x-request-id' => $request_id);
2227 225 $headers_sent = 1;
2228 }
2229  
2230 # Parse SSE lines and accumulate usage + content bytes. Without a translator the relayed
2231 # bytes are never modified -- this reads along, it does not rewrite.
2232 628 $pending .= $bytes;
2233 628 my $translated = '';
2234 628 ▶ while ($pending =~ s/\A([^\n]*)\n//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pending =~ s/\A([^\n]*)\n//) 1989 621 2610
2235 1989 my $line = $1;
2236 # SSE makes the space after the colon optional: `data:{...}` is as valid as `data: {...}`.
2237 1989 ▶ next unless $line =~ /^data:\s?(.*?)\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /^data:\s?(.*?)\s*$/ 993 996 1989
2238 996 my $payload = $1;
2239 996 ▶ next unless length $payload;
Branch: 1 branch
BranchTrueFalseTotal
unless length $payload 0 996 996
2240  
2241 # OpenAI closes with a literal [DONE] sentinel, which is not JSON and has no equivalent
2242 # in either target format -- the translated stream ends with its own closing events.
2243 996 ▶ next if $payload eq '[DONE]';
Branch: 1 branch
BranchTrueFalseTotal
if $payload eq "[DONE]" 181 815 996
2244  
2245 815 my $json = eval { decode_json($payload) };
2246 815 ▶ next unless $json && ref($json) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $json and ref $json eq "HASH" 0 815 815
Condition33%1/3
$json and ref $json eq "HASH"
!ll&&!rl&&r
00815
MC/DC0%0/2
$json and ref $json eq "HASH"
$json ref $json eq "HASH"
Truth table33%1/3
A and B
A= $jsonB= ref $json eq "HASH"
ABresult
0X0
100
111
2247  
2248 815 ▶ my $choice = ref($json->{choices}) eq 'ARRAY' ? $json->{choices}[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $json->{'choices'} eq 'ARRAY' ? : 801 14 815
2249 815 ▶ if (ref($choice) eq 'HASH' && (my $delta = $choice->{delta})) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $choice eq "HASH" and my $delta = $choice->{"delta"}) 732 83 815
Condition66%2/3
ref $choice eq "HASH" and my $delta = $choice->{"delta"}
!ll&&!rl&&r
830732
MC/DC50%1/2
ref $choice eq "HASH" and my $delta = $choice->{"delta"}
ref $choice eq "HASH" my $delta = $choice->{"delta"}
Truth table66%2/3
A and B
A= ref $choice eq "HASH"B= my $delta = $choice->{"delta"}
ABresult
0X0
100
111
2250 732 ▶ if (my $delta_content = $delta->{content}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $delta_content = $delta->{"content"}) 578 154 732
2251 578 $accumulated_content_bytes += Langertha::Skeid::Protocol::utf8_length($delta_content);
2252 }
2253 $ttft_ms //= _duration_ms($started)
2254 2928 ▶ if ref($delta) eq 'HASH' && grep { defined($_) && length($_) }
Branch: 1 branch
BranchTrueFalseTotal
ref $delta->{'tool_calls'} eq 'ARRAY' && @{$delta->{'tool_calls'};} ? : 26 706 732
Condition83%5/6
defined $_ && length $_
!ll&&!rl&&r
23204604
ref $delta->{"tool_calls"} eq "ARRAY" and @{$delta->{"tool_calls"};}
!ll&&!rl&&r
706026
MC/DC100%2/2
defined $_ && length $_
defined $_ length $_
MC/DC50%1/2
ref $delta->{"tool_calls"} eq "ARRAY" and @{$delta->{"tool_calls"};}
ref $delta->{"tool_calls"} eq "ARRAY" @{$delta->{"tool_calls"};}
Truth table100%3/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= ref $delta->{"tool_calls"} eq "ARRAY"B= @{$delta->{"tool_calls"};}
ABresult
0X0
100
111
2255 $delta->{content}, $delta->{reasoning_content}, $delta->{reasoning},
2256 732 ▶ (ref($delta->{tool_calls}) eq 'ARRAY' && @{$delta->{tool_calls}} ? 'tool_calls' : undef);
Branch: 1 branch
BranchTrueFalseTotal
if ref $delta eq "HASH" and grep {defined $_ and length $_;} $delta->{"content"}, $delta->{"reasoning_content"}, $delta->{"reasoning"}, ref $delta->{"tool_calls"} eq "ARRAY" && @{$delta->{"tool_calls"};} ? "tool_calls" : undef 603 129 732
Condition66%4/6
ref $delta eq "HASH" and grep {defined $_ and length $_;} $delta->{"content"}, $delta->{"reasoning_content"}, $delta->{"reasoning"}, ref $delta->{"tool_calls"} eq "ARRAY" && @{$delta->{"tool_calls"};} ? "tool_calls" : undef
!ll&&!rl&&r
0129603
$ttft_ms //= _duration_ms($started)
l!l&&r!l&&!r
3922110
MC/DC50%1/2
ref $delta eq "HASH" and grep {defined $_ and length $_;} $delta->{"content"}, $delta->{"reasoning_content"}, $delta->{"reasoning"}, ref $delta->{"tool_calls"} eq "ARRAY" && @{$delta->{"tool_calls"};} ? "tool_calls" : undef
ref $delta eq "HASH" grep {defined $_ and length $_;} $delta->{"content"}, $delta->{"reasoning_content"}, $delta->{"reasoning"}, ref $delta->{"tool_calls"} eq "ARRAY" && @{$delta->{"tool_calls"};} ? "tool_calls" : undef
MC/DC0%0/2
$ttft_ms //= _duration_ms($started)
$ttft_ms _duration_ms($started)
Truth table66%2/3
A and B
A= ref $delta eq "HASH"B= grep {defined $_ and length $_;} $delta->{"content"}, $delta->{"reasoning_content"}, $delta->{"reasoning"}, ref $delta->{"tool_calls"} eq "ARRAY" && @{$delta->{"tool_calls"};} ? "tool_calls" : undef
ABresult
0X0
100
111
Truth table66%2/3
A //= B
A= $ttft_msB= _duration_ms($started)
ABresult
1X1
011
000
2257 }
2258 $finish_reason = $choice->{finish_reason}
2259 815 ▶ if ref($choice) eq 'HASH' && defined($choice->{finish_reason}) && !ref($choice->{finish_reason});
Branch: 1 branch
BranchTrueFalseTotal
if ref $choice eq "HASH" and defined $choice->{"finish_reason"} and not ref $choice->{"finish_reason"} 112 703 815
Condition83%5/6
ref $choice eq "HASH" and defined $choice->{"finish_reason"} and not ref $choice->{"finish_reason"}
!ll&&!rl&&r
7030112
ref $choice eq "HASH" and defined $choice->{"finish_reason"}
!ll&&!rl&&r
83620112
MC/DC66%2/3
ref $choice eq "HASH" and defined $choice->{"finish_reason"} and not ref $choice->{"finish_reason"}
ref $choice eq "HASH" defined $choice->{"finish_reason"} not ref $choice->{"finish_reason"}
Truth table75%3/4
A and B and not(C)
A= ref $choice eq "HASH"B= defined $choice->{"finish_reason"}C= not ref $choice->{"finish_reason"}
ABCresult
0XX0
10X0
1100
1111
2260 815 ▶ if ($relay->{delta_text}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($relay->{"delta_text"}) 54 761 815
2261 54 my $text = $relay->{delta_text}->($json);
2262 54 ▶ if (defined($text) && length($text)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $text and length $text) 8 46 54
Condition66%2/3
defined $text and length $text
!ll&&!rl&&r
4608
MC/DC50%1/2
defined $text and length $text
defined $text length $text
Truth table66%2/3
A and B
A= defined $textB= length $text
ABresult
0X0
100
111
2263 8 $accumulated_content_bytes += Langertha::Skeid::Protocol::utf8_length($text);
2264 8 ▶ $ttft_ms //= _duration_ms($started);
Condition66%2/3
$ttft_ms //= _duration_ms($started)
l!l&&r!l&&!r
440
MC/DC0%0/2
$ttft_ms //= _duration_ms($started)
$ttft_ms _duration_ms($started)
Truth table66%2/3
A //= B
A= $ttft_msB= _duration_ms($started)
ABresult
1X1
011
000
2265 }
2266 }
2267  
2268 815 ▶ if (ref($json->{usage}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $json->{"usage"} eq "HASH") 212 603 815
2269 212 $upstream_usage = _merge_usage($upstream_usage, $json->{usage});
2270 }
2271  
2272 815 ▶ if ($stream) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream) 413 402 815
2273 413 my $out = eval { $stream->delta($json) };
2274 413 ▶ unless (defined $out) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $out) 7 406 413
2275 7 $c->app->log->error('Translating a stream chunk failed for node ' . $node_id);
2276 7 return $fail_translation->();
2277 }
2278 406 $translated .= $out;
2279 }
2280 }
2281  
2282 # The first read event fires with an empty chunk as soon as the upstream headers are
2283 # parsed, and writing an empty chunk finalizes a Mojolicious response. Relaying it would
2284 # end the stream before its first token -- headers, no body, no error.
2285 621 ▶ if ($stream) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream) { } 356 265 621
2286 356 ▶ return unless length $translated;
Branch: 1 branch
BranchTrueFalseTotal
unless length $translated 127 229 356
2287 229 $wrote = 1;
2288 229 push @queue, $translated;
2289 } else {
2290 265 ▶ return unless length $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless length $bytes 20 245 265
2291 245 $wrote = 1;
2292 245 push @queue, $bytes;
2293 }
2294 474 ▶ $drain->() unless $draining;
Branch: 1 branch
BranchTrueFalseTotal
unless $draining 375 99 474
2295 241 });
2296  
2297 241 ▶ $c->tx->on(finish => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2298 # Also emitted when the answer is complete, and then there is nothing left to do here. When
2299 # the client hung up, what is queued has no reader and the drain callback that would take
2300 # the next chunk does not run again: drop the queue and the callback's self-reference, or
2301 # they keep the controller alive.
2302 241 @queue = ();
2303 241 $finished = 1;
2304 241 undef $drain;
2305 241 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 236 5 241
2306 5 $closed = 1;
2307 5 $tx->res->content->unsubscribe('read');
2308  
2309 # Billed from what the stream reported before the client left; the node spent that, whoever
2310 # read it (ADR 0004).
2311 5 my $duration_ms = _duration_ms($started);
2312 5 $c->skeid->call_function('request.finish', {
2313 id => $node_id,
2314 ok => 0,
2315 aborted => 1,
2316 duration_ms => $duration_ms,
2317 });
2318 5 _record_usage_event($c, {
2319 %$meta,
2320 _client_abort_event(),
2321 node_id => $node_id,
2322 duration_ms => $duration_ms,
2323 content_bytes => $content_bytes->(),
2324 $answer_facts->(),
2325 metrics => _stream_metrics($c, $meta, $body, $duration_ms, $upstream_usage),
2326 $units->(),
2327 });
2328 5 _cancel_upstream($tx);
2329 241 });
2330  
2331 241 ▶ $c->app->ua->start($tx => sub {
Subroutine __ANON__: called CC=38 SCAR=37.0
2332 241 my ($ua, $tx_done) = @_;
2333  
2334 # The read listener closes over both the upstream transaction and the client controller.
2335 # Completion means no further bytes can arrive, so remove it before returning from any path;
2336 # otherwise the completed transaction owns the listener that owns the transaction forever.
2337 241 $tx_done->res->content->unsubscribe('read');
2338  
2339 # The client hung up and its request was closed then; this is the cancelled transaction.
2340 241 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 12 229 241
2341 229 $closed = 1;
2342  
2343 # As on the JSON path, an HTTP error is still a response whose capacity headers matter.
2344 # Observe it before the pre-stream error return; transport failures contribute nothing.
2345 229 _observe_capacity($c, $node_id, $tx_done->res);
2346  
2347 229 ▶ if (my $err = $tx_done->error) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $tx_done->error) 44 185 229
2348 44 $had_error = 1;
2349 44 ▶ unless ($headers_sent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($headers_sent) 16 28 44
2350 16 my $duration_ms = _duration_ms($started);
2351 16 ▶ my $err_status = $err->{code} || 502;
Condition100%2/2
$err->{'code'} || 502
l!l
115
MC/DC100%1/1
$err->{'code'} || 502
$err->{'code'}
Truth table100%2/2
A
A= $err->{'code'}
Aresult
11
00
2352 16 ▶ $c->skeid->call_function('request.finish', {
Branch: 1 branch
BranchTrueFalseTotal
_client_fault($err_status) ? : 3 13 16
2353 id => $node_id,
2354 ok => 0,
2355 _client_fault($err_status) ? (rejected => 1) : (),
2356 duration_ms => $duration_ms,
2357 });
2358 _record_usage_event($c, {
2359 %$meta,
2360 node_id => $node_id,
2361 status_code => $err_status,
2362 ok => 0,
2363 duration_ms => $duration_ms,
2364 error_type => 'upstream_error',
2365 16 ▶ error_message => ($err->{message} // 'unknown'),
Condition50%1/2
$err->{"message"} // "unknown"
l!l
160
MC/DC0%0/1
$err->{"message"} // "unknown"
$err->{"message"}
Truth table50%1/2
A
A= $err->{"message"}
Aresult
11
00
2366 content_bytes => $content_bytes->(),
2367 $answer_facts->(),
2368 metrics => _stream_metrics($c, $meta, $body, _duration_ms($started), $upstream_usage),
2369 $units->(),
2370 });
2371 16 _render_error($c, $err_status,
2372 'Upstream error: ' . _upstream_error_message($err, $upstream_error_body), 'upstream_error');
2373 16 undef $drain;
2374 16 return;
2375 }
2376 }
2377  
2378 # The stream is open, so the status is already sent. Mojo::UserAgent reports an upstream
2379 # that hangs up mid-body as no error at all once the status line has arrived, so the body's
2380 # own framing (the chunked terminator, Content-Length) is the witness for that case; a
2381 # close-delimited body cannot be told apart from a complete one. A cut stream failed on
2382 # every face: the usage event and request.finish must not mean something different
2383 # depending on the client's dialect (ADR 0004).
2384 213 my $cut = 0;
2385 213 ▶ if ($headers_sent && !$had_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($headers_sent and not $had_error) 185 28 213
Condition66%2/3
$headers_sent and not $had_error
!ll&&!rl&&r
028185
MC/DC50%1/2
$headers_sent and not $had_error
$headers_sent not $had_error
Truth table66%2/3
A and not(B)
A= $headers_sentB= not $had_error
ABresult
0X0
100
111
2386 185 my $content = $tx_done->res->content;
2387 185 ▶ my $framed = $content->is_chunked || length($content->headers->content_length // '');
Condition80%4/5
$content->is_chunked || length($content->headers->content_length // '')
l!l&&r!l&&!r
01778
$content->headers->content_length // ""
l!l
1778
MC/DC50%1/2
$content->is_chunked || length($content->headers->content_length // '')
$content->is_chunked $content->headers->content_length
Truth table66%2/3
A || B
A= $content->is_chunkedB= $content->headers->content_length
ABresult
1X1
011
000
2388 185 ▶ $cut = $framed && !$content->is_finished;
Condition66%2/3
$framed && !$content->is_finished
!ll&&!rl&&r
81770
MC/DC0%0/2
$framed && !$content->is_finished
$framed !$content->is_finished
Truth table66%2/3
A && not(B)
A= $framedB= !$content->is_finished
ABresult
0X0
100
111
2389 185 ▶ $had_error = 1 if $cut;
Branch: 1 branch
BranchTrueFalseTotal
if $cut 0 185 185
2390 }
2391  
2392 # A translator that can say so in-band ends a failed stream with its error event instead of
2393 # a closing sequence that would read as a complete answer.
2394 213 ▶ if ($stream_errors && $headers_sent) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream_errors and $headers_sent) 135 78 213
Condition66%2/3
$stream_errors and $headers_sent
!ll&&!rl&&r
780135
MC/DC50%1/2
$stream_errors and $headers_sent
$stream_errors $headers_sent
Truth table66%2/3
A and B
A= $stream_errorsB= $headers_sent
ABresult
0X0
100
111
2395 135 ▶ if ($had_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($had_error) 14 121 135
2396 14 ▶ my $reason = $cut ? 'Premature connection close' : ($tx_done->error->{message} // 'unknown');
Branch: 1 branch
BranchTrueFalseTotal
$cut ? : 0 14 14
Condition50%1/2
$tx_done->error->{"message"} // "unknown"
l!l
140
MC/DC0%0/1
$tx_done->error->{"message"} // "unknown"
$tx_done->error->{"message"}
Truth table50%1/2
A
A= $tx_done->error->{"message"}
Aresult
11
00
2397 14 my $frame = $stream->error_event(500, "Upstream error: $reason");
2398 14 ▶ if (length $frame) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $frame) 14 0 14
2399 14 push @queue, $frame;
2400 14 ▶ $drain->() unless $draining;
Branch: 1 branch
BranchTrueFalseTotal
unless $draining 12 2 14
2401 }
2402 }
2403 }
2404  
2405 # Finalize a translated stream before closing admission or recording its Usage event: a
2406 # translator can discover a terminal error only when it sees that no more upstream frames
2407 # are coming. Its tail is queued like any other chunk so it still lands after deltas already
2408 # in flight. Keep an unexpected finalizer exception inside the callback boundary and use the
2409 # translator's existing in-band error shape without reflecting internal details.
2410 213 ▶ if ($stream && $headers_sent) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream and $headers_sent) 135 78 213
Condition66%2/3
$stream and $headers_sent
!ll&&!rl&&r
780135
MC/DC50%1/2
$stream and $headers_sent
$stream $headers_sent
Truth table66%2/3
A and B
A= $streamB= $headers_sent
ABresult
0X0
100
111
2411 135 my $tail = '';
2412 135 my $finalized = eval {
2413 135 $tail = $stream->finish;
2414 134 1;
2415 };
2416 135 ▶ unless ($finalized) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($finalized) 1 134 135
2417 1 $had_error = 1;
2418 1 ▶ $tail = eval { $stream_errors
Branch: 1 branch
BranchTrueFalseTotal
$stream_errors ? : 1 0 1
2419 ? $stream->error_event(500, 'Stream translation failed')
2420 : '' };
2421 }
2422 135 ▶ $tail = '' unless defined $tail;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tail 0 135 135
2423 135 ▶ if (length $tail) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $tail) 116 19 135
2424 116 push @queue, $tail;
2425 116 ▶ $drain->() unless $draining;
Branch: 1 branch
BranchTrueFalseTotal
unless $draining 46 70 116
2426 }
2427 }
2428  
2429 # An upstream that reported its failure inside the stream, or a translator that could only
2430 # detect one while finalizing, was answered with an error event; the request still failed.
2431 213 ▶ $had_error = 1 if $stream && $stream->can('errored') && $stream->errored;
Branch: 1 branch
BranchTrueFalseTotal
if $stream and $stream->can("errored") and $stream->errored 21 192 213
Condition83%5/6
$stream and $stream->can("errored") and $stream->errored
!ll&&!rl&&r
7811421
$stream and $stream->can("errored")
!ll&&!rl&&r
780135
MC/DC66%2/3
$stream and $stream->can("errored") and $stream->errored
$stream $stream->can("errored") $stream->errored
Truth table75%3/4
A and B and C
A= $streamB= $stream->can("errored")C= $stream->errored
ABCresult
0XX0
10X0
1100
1111
2432  
2433 213 my $duration_ms = _duration_ms($started);
2434 213 ▶ $c->skeid->call_function('request.finish', {
Branch: 2 branches
BranchTrueFalseTotal
$had_error || $status >= 500 ? : 35 178 213
$had_error && _client_fault($status) ? : 4 209 213
Condition83%5/6
$had_error or $status >= 500
l!l&&r!l&&!r
350178
$had_error and _client_fault($status)
!ll&&!rl&&r
178314
MC/DC50%1/2
$had_error or $status >= 500
$had_error $status >= 500
MC/DC100%2/2
$had_error and _client_fault($status)
$had_error _client_fault($status)
Truth table66%2/3
A or B
A= $had_errorB= $status >= 500
ABresult
1X1
011
000
Truth table100%3/3
A and B
A= $had_errorB= _client_fault($status)
ABresult
0X0
100
111
2435 id => $node_id,
2436 ok => ($had_error || $status >= 500) ? 0 : 1,
2437 # An upstream 4xx relayed after the headers went out is still the client's to fix.
2438 ($had_error && _client_fault($status)) ? (rejected => 1) : (),
2439 duration_ms => $duration_ms,
2440 });
2441  
2442 # Priced from whatever usage the stream carried, also when it was cut: a cut stream still
2443 # spent what its frames reported, and one that reported nothing records zero (ADR 0004).
2444 213 ▶ _record_usage_event($c, {
Branch: 1 branch
BranchTrueFalseTotal
$had_error || $status >= 500 ? : 35 178 213
Condition66%2/3
$had_error or $status >= 500
l!l&&r!l&&!r
350178
MC/DC50%1/2
$had_error or $status >= 500
$had_error $status >= 500
Truth table66%2/3
A or B
A= $had_errorB= $status >= 500
ABresult
1X1
011
000
2445 %$meta,
2446 node_id => $node_id,
2447 status_code => $status,
2448 ok => ($had_error || $status >= 500) ? 0 : 1,
2449 duration_ms => $duration_ms,
2450 content_bytes => $content_bytes->(),
2451 $answer_facts->(),
2452 metrics => _stream_metrics($c, $meta, $body, $duration_ms, $upstream_usage),
2453 $units->(),
2454 });
2455  
2456 # Only finish once the queue has drained, or the tail of the stream is cut off. If the
2457 # drain loop is still running it will finish for us when it empties.
2458 213 $upstream_done = 1;
2459 213 ▶ if (!$draining && !$finished) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $draining || $finished) 28 185 213
Condition66%2/3
$draining || $finished
l!l&&r!l&&!r
185028
MC/DC50%1/2
$draining || $finished
$draining $finished
Truth table66%2/3
A || B
A= $drainingB= $finished
ABresult
1X1
011
000
2460 28 $finished = 1;
2461 28 $c->finish;
2462 28 undef $drain;
2463 }
2464 241 });
2465 267 });
2466 }
2467  
2468 # The request of a route on the OpenAI face, whose node speaks the wire the client spoke: the
2469 # client's own bytes with only `model` replaced (Langertha::Skeid::Protocol::RawBody), never the
2470 # decoded body encoded again. Re-encoding sorts the keys of every object, and a node renders
2471 # tool definitions into the prompt in the order they arrive -- so it would hand the model a
2472 # prompt the client did not write, and its prompt cache a prefix it has not seen.
2473 #
2474 # undef, and with it the encoded body, only for bytes the scanner cannot follow.
2475 349 ▶sub _verbatim_relay {
Subroutine _verbatim_relay: called CC=2 SCAR=6.9
2476 349 my ($c, $served_model) = @_;
2477 349 my $bytes = Langertha::Skeid::Protocol::RawBody::with_top_level($c->req->body, model => $served_model);
2478 349 ▶ return undef unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 1 348 349
2479 327 ▶ return { request => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2480 327 my ($ua, $url, $headers) = @_;
2481 327 return $ua->build_tx(POST => $url, $headers, $bytes);
2482 348 } };
2483 }
2484  
2485 # The request of a translated route (the Anthropic and Ollama faces): the translated body, with
2486 # each tool's JSON schema written as the client spelled it and the tool definition around it in
2487 # the order the function-calling wire spells it. The body is new, so it cannot go up as the
2488 # client's bytes -- but the tool definitions are what a node renders into the prompt verbatim,
2489 # and those are kept (Langertha::Skeid::Protocol::RawBody). @path is where a tool carries its
2490 # schema on the client's wire.
2491 #
2492 # The body is encoded when the request is built, after the caller has set `model` and `stream`
2493 # on it. undef for a request without tools; a body whose tools no longer line up with the
2494 # client's goes up encoded as before.
2495 433 ▶sub _schema_relay {
Subroutine _schema_relay: called CC=2 SCAR=6.9
2496 433 my ($c, $openai_body, @path) = @_;
2497 433 ▶ my $texts = Langertha::Skeid::Protocol::RawBody::tool_schemas($c->req->body, @path) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $texts = Langertha::Skeid::Protocol::RawBody::tool_schemas($c->req->body, @path) or return undef 5 428 433
2498 5 ▶ return { request => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
2499 5 my ($ua, $url, $headers) = @_;
2500 5 my $bytes = Langertha::Skeid::Protocol::RawBody::encode_with_schemas($openai_body, $texts);
2501 5 ▶ return $ua->build_tx(POST => $url, $headers, json => $openai_body) unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 5 5
2502 5 delete @{$headers}{ grep { lc($_) eq 'content-type' } keys %$headers };
2503 5 return $ua->build_tx(POST => $url, { %$headers, 'Content-Type' => 'application/json' }, $bytes);
2504 5 } };
2505 }
2506  
2507 # The upstream request of an admitted call: the one JSON POST every translated route makes (ADR
2508 # 0001), or what a relayed route's own `request` builder returns (ADR 0021).
2509 904 ▶sub _upstream_tx {
Subroutine _upstream_tx: called CC=3 SCAR=11.0
2510 904 my ($c, $url, $headers, $body, $relay) = @_;
2511 904 my $ua = $c->app->ua;
2512 904 ▶ return $relay->{request}->($ua, $url, $headers) if $relay && $relay->{request};
Branch: 1 branch
BranchTrueFalseTotal
if $relay and $relay->{"request"} 434 470 904
Condition66%2/3
$relay and $relay->{"request"}
!ll&&!rl&&r
0470434
MC/DC50%1/2
$relay and $relay->{"request"}
$relay $relay->{"request"}
Truth table66%2/3
A and B
A= $relayB= $relay->{"request"}
ABresult
0X0
100
111
2513 470 return $ua->build_tx(POST => $url, $headers, json => $body);
2514 }
2515  
2516 # Renders an error in the shape of the face the client called. The Anthropic Messages face
2517 # gets Anthropic's envelope, {type: "error", error: {type, message}}, with the type taken from
2518 # the HTTP status, because that is what an Anthropic SDK parses and raises on (core karr #224).
2519 # The Ollama face gets Ollama's {error: "<message>"}, a plain string, because that is what the
2520 # Ollama clients decode (skeid #47). Every other face keeps the OpenAI shape it always had, with
2521 # $openai_type as its type and $openai_code, when given, as its code (OpenAI's own 401 carries
2522 # invalid_api_key). The face is read off the stash, which the /v1/messages and /api/* bridges
2523 # set; a controller without one (a unit test's stand-in) is an OpenAI face.
2524 470 ▶sub _render_error {
Subroutine _render_error: called CC=11 SCAR=24.0
2525 470 my ($c, $status, $message, $openai_type, $openai_code) = @_;
2526 # A refused WebSocket handshake is a plain HTTP answer: the upgrade headers the server
2527 # prepared for a 101 do not belong on it (skeid k95).
2528 470 ▶ my $handshake = $c->can('tx') ? $c->tx : undef;
Branch: 1 branch
BranchTrueFalseTotal
$c->can('tx') ? : 468 2 470
2529 470 ▶ if ($handshake && $handshake->is_websocket && !$handshake->established) {
Branch: 1 branch
BranchTrueFalseTotal
if ($handshake and $handshake->is_websocket and not $handshake->established) 13 457 470
Condition83%5/6
$handshake and $handshake->is_websocket and not $handshake->established
!ll&&!rl&&r
457013
$handshake and $handshake->is_websocket
!ll&&!rl&&r
245513
MC/DC66%2/3
$handshake and $handshake->is_websocket and not $handshake->established
$handshake $handshake->is_websocket not $handshake->established
Truth table75%3/4
A and B and not(C)
A= $handshakeB= $handshake->is_websocketC= not $handshake->established
ABCresult
0XX0
10X0
1100
1111
2530 13 $c->res->headers->remove($_) for qw( Upgrade Connection Sec-WebSocket-Accept );
2531 }
2532 470 ▶ my $format = $c->can('stash') ? ($c->stash('skeid.error_format') // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
$c->can('stash') ? : 468 2 470
Condition100%2/2
$c->stash("skeid.error_format") // ""
l!l
142326
MC/DC100%1/1
$c->stash("skeid.error_format") // ""
$c->stash("skeid.error_format")
Truth table100%2/2
A
A= $c->stash("skeid.error_format")
Aresult
11
00
2533 470 ▶ if ($format eq 'anthropic') {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq "anthropic") 51 419 470
2534 51 $c->render(json => Langertha::Skeid::Protocol::Anthropic->error_body($status, $message),
2535 status => $status);
2536 51 return;
2537 }
2538 419 ▶ if ($format eq 'ollama') {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq "ollama") 91 328 419
2539 91 $c->render(json => Langertha::Skeid::Protocol::Ollama->error_body($message), status => $status);
2540 91 return;
2541 }
2542 328 ▶ $c->render(json => { error => {
Branch: 1 branch
BranchTrueFalseTotal
defined $openai_code ? : 78 250 328
2543 message => $message,
2544 type => $openai_type,
2545 defined($openai_code) ? ( code => $openai_code ) : (),
2546 } }, status => $status);
2547 328 return;
2548 }
2549  
2550 # The message to put after "Upstream error: ". Mojo sets $err->{message} to the HTTP reason
2551 # phrase for a 4xx/5xx ("Bad Request"); the upstream usually said more in its own body, in the
2552 # OpenAI dialect every node speaks (ADR 0001), and that is what the client needs to act on.
2553 63 ▶sub _upstream_error_message {
Subroutine _upstream_error_message: called CC=9 SCAR=22.3
2554 63 my ($err, $body) = @_;
2555 63 ▶ my $json = (defined($body) && length($body)) ? eval { decode_json($body) } : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $body && length $body ? : 49 14 63
Condition66%2/3
defined $body and length $body
!ll&&!rl&&r
01449
MC/DC50%1/2
defined $body and length $body
defined $body length $body
Truth table66%2/3
A and B
A= defined $bodyB= length $body
ABresult
0X0
100
111
2556 63 ▶ if (ref($json) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $json eq "HASH") 49 14 63
2557 49 my $e = $json->{error};
2558 49 ▶ my $msg = ref($e) eq 'HASH' ? $e->{message} : $e;
Branch: 1 branch
BranchTrueFalseTotal
ref $e eq 'HASH' ? : 44 5 49
2559 49 ▶ return "$msg" if defined($msg) && !ref($msg) && length($msg);
Branch: 1 branch
BranchTrueFalseTotal
if defined $msg and not ref $msg and length $msg 46 3 49
Condition66%4/6
defined $msg and not ref $msg and length $msg
!ll&&!rl&&r
3046
defined $msg and not ref $msg
!ll&&!rl&&r
3046
MC/DC33%1/3
defined $msg and not ref $msg and length $msg
defined $msg not ref $msg length $msg
Truth table50%2/4
A and not(B) and C
A= defined $msgB= not ref $msgC= length $msg
ABCresult
0XX0
10X0
1100
1111
2560 }
2561 17 ▶ return $err->{message} // 'unknown';
Condition50%1/2
$err->{"message"} // "unknown"
l!l
170
MC/DC0%0/1
$err->{"message"} // "unknown"
$err->{"message"}
Truth table50%1/2
A
A= $err->{"message"}
Aresult
11
00
2562 }
2563  
2564 356 ▶sub _render_upstream_response {
Subroutine _render_upstream_response: called CC=3 SCAR=11.0
2565 356 my ($c, $res, $node_id) = @_;
2566  
2567 356 $c->res->code($res->code);
2568 356 for my $name (@{$res->headers->names}) {
2569 1703 my $lc = lc($name);
2570 1703 ▶ next if _skip_response_header($lc);
Branch: 1 branch
BranchTrueFalseTotal
if _skip_response_header($lc) 382 1321 1703
2571 1321 $c->res->headers->header($name => $res->headers->header($name));
2572 }
2573 356 $c->res->headers->header('x-skeid-node' => $node_id);
2574 356 $c->res->headers->header('x-request-id' => _request_id($c));
2575 356 $c->res->body($res->body);
2576 356 $c->rendered;
2577 }
2578  
2579 # Hop-by-hop headers describe the client's connection to Skeid, not the request. Forwarding
2580 # them upstream is wrong per RFC 7230 and expensive here in particular: a client that sends
2581 # `Connection: close` -- most benchmark tools and plenty of HTTP libraries do -- made Skeid
2582 # tear down its own upstream connection after every single request, so the connection pool
2583 # never held anything and each request paid for a fresh TCP handshake.
2584 99 my %HOP_BY_HOP = map { $_ => 1 } qw(
2585 connection
2586 keep-alive
2587 proxy-authenticate
2588 proxy-authorization
2589 te
2590 trailer
2591 transfer-encoding
2592 upgrade
2593 );
2594  
2595 # An upstream response header Skeid does not relay to the client: hop-by-hop headers describe
2596 # the node's connection to Skeid, not the client's (a relayed `Connection: close` makes Skeid
2597 # drop the customer's keep-alive connection), and the body is re-framed and never re-encoded
2598 # here. One filter for the JSON, stream and MCP relays (skeid k107). `$lc` is the lowercased name.
2599 2652 ▶sub _skip_response_header {
Subroutine _skip_response_header: called CC=4 SCAR=13.9
2600 2652 my ($lc) = @_;
2601 2652 ▶ return $HOP_BY_HOP{$lc} || $lc eq 'content-length' || $lc eq 'content-encoding' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$HOP_BY_HOP{$lc} || $lc eq 'content-length' || $lc eq 'content-encoding' ? : 609 2043 2652
Condition83%5/6
$HOP_BY_HOP{$lc} or $lc eq "content-length" or $lc eq "content-encoding"
l!l&&r!l&&!r
60902043
$HOP_BY_HOP{$lc} or $lc eq "content-length"
l!l&&r!l&&!r
1344752043
MC/DC66%2/3
$HOP_BY_HOP{$lc} or $lc eq "content-length" or $lc eq "content-encoding"
$HOP_BY_HOP{$lc} $lc eq "content-length" $lc eq "content-encoding"
Truth table75%3/4
A or B or C
A= $HOP_BY_HOP{$lc}B= $lc eq "content-length"C= $lc eq "content-encoding"
ABCresult
1XX1
01X1
0011
0000
2602 }
2603  
2604 # The client headers an external node is sent (skeid k128, ADR 0032): how the body is framed,
2605 # what answer is wanted, and the provider protocol headers that change what the provider does.
2606 # An allowlist, because the headers a deployment adds in front of Skeid are not known here.
2607 99 my %EXTERNAL_HEADER = map { $_ => 1 } qw(
2608 content-type
2609 accept
2610 anthropic-version
2611 anthropic-beta
2612 openai-beta
2613 );
2614  
2615 # What an external node is told about the software calling it -- and nothing about the client's.
2616 99 my $EXTERNAL_USER_AGENT = 'Langertha-Skeid';
2617  
2618 # The client headers that go to the node $node_id, by the node's trust (ADR 0032). The node's
2619 # own key is not here: _inject_node_auth_async sets it on what this returns. A node that left
2620 # the inventory is treated as external -- what it was cannot be known, and the narrower set is
2621 # the one that leaks nothing (its key resolution refuses the request anyway).
2622 1058 ▶sub _forward_headers {
Subroutine _forward_headers: called CC=19 SCAR=29.4
2623 1058 my ($c, $node_id) = @_;
2624 1058 my $node = _node_by_id($c->skeid, $node_id);
2625 1058 ▶ my $internal = $node && ($node->{trust} // '') eq 'internal';
Condition80%4/5
$node && ($node->{'trust'} // '') eq 'internal'
!ll&&!rl&&r
9111038
$node->{"trust"} // ""
l!l
10490
MC/DC50%1/2
$node && ($node->{'trust'} // '') eq 'internal'
$node $node->{"trust"}
Truth table66%2/3
A && B
A= $nodeB= $node->{"trust"}
ABresult
0X0
100
111
2626 1058 my %fwd_headers;
2627 # The correlation header (skeid k121) is the caller's id for Skeid's usage row; a node --
2628 # possibly a cloud provider's -- has no use for it and is not told.
2629 1058 ▶ my $correlation = lc($c->skeid->correlation_header // '');
Condition100%2/2
$c->skeid->correlation_header // ""
l!l
221036
MC/DC100%1/1
$c->skeid->correlation_header // ""
$c->skeid->correlation_header
Truth table100%2/2
A
A= $c->skeid->correlation_header
Aresult
11
00
2630 1058 for my $name (@{$c->req->headers->names}) {
2631 6235 my $lc = lc($name);
2632 6235 ▶ next if length($correlation) && $lc eq $correlation;
Branch: 1 branch
BranchTrueFalseTotal
if length $correlation and $lc eq $correlation 17 6218 6235
Condition100%3/3
length $correlation and $lc eq $correlation
!ll&&!rl&&r
582339517
MC/DC100%2/2
length $correlation and $lc eq $correlation
length $correlation $lc eq $correlation
Truth table100%3/3
A and B
A= length $correlationB= $lc eq $correlation
ABresult
0X0
100
111
2633 6218 ▶ if ($internal) {
Branch: 1 branch
BranchTrueFalseTotal
if ($internal) { } 5933 285 6218
2634 5933 ▶ next if $HOP_BY_HOP{$lc};
Branch: 1 branch
BranchTrueFalseTotal
if $HOP_BY_HOP{$lc} 182 5751 5933
2635 5751 ▶ next if $lc eq 'host' || $lc eq 'content-length' || $lc eq 'accept-encoding';
Branch: 1 branch
BranchTrueFalseTotal
if $lc eq "host" or $lc eq "content-length" or $lc eq "accept-encoding" 3001 2750 5751
Condition100%6/6
$lc eq "host" or $lc eq "content-length" or $lc eq "accept-encoding"
l!l&&r!l&&!r
198510162750
$lc eq "host" or $lc eq "content-length"
l!l&&r!l&&!r
10389473766
MC/DC100%3/3
$lc eq "host" or $lc eq "content-length" or $lc eq "accept-encoding"
$lc eq "host" $lc eq "content-length" $lc eq "accept-encoding"
Truth table100%4/4
A or B or C
A= $lc eq "host"B= $lc eq "content-length"C= $lc eq "accept-encoding"
ABCresult
1XX1
01X1
0011
0000
2636 # The body is in hand, so nothing is expected of the node. A node that answered `Expect:
2637 # 100-continue` with its `100 Continue` would have the user agent start a fresh response
2638 # object, one the stream relay is not listening on (skeid k96).
2639 2750 ▶ next if $lc eq 'expect';
Branch: 1 branch
BranchTrueFalseTotal
if $lc eq "expect" 4 2746 2750
2640 # Who the client is and where it called from is not the node's to know, even an internal
2641 # one's: its address in any spelling, and its cookies.
2642 2746 ▶ next if $lc =~ /\Ax-forwarded-/ || $lc eq 'forwarded' || $lc eq 'x-real-ip' || $lc eq 'cookie';
Branch: 1 branch
BranchTrueFalseTotal
if $lc =~ /\Ax-forwarded-/ or $lc eq "forwarded" or $lc eq "x-real-ip" or $lc eq "cookie" 42 2704 2746
Condition100%9/9
$lc =~ /\Ax-forwarded-/ or $lc eq "forwarded" or $lc eq "x-real-ip" or $lc eq "cookie"
l!l&&r!l&&!r
3572704
$lc =~ /\Ax-forwarded-/ or $lc eq "forwarded" or $lc eq "x-real-ip"
l!l&&r!l&&!r
2872711
$lc =~ /\Ax-forwarded-/ or $lc eq "forwarded"
l!l&&r!l&&!r
2172718
MC/DC100%4/4
$lc =~ /\Ax-forwarded-/ or $lc eq "forwarded" or $lc eq "x-real-ip" or $lc eq "cookie"
$lc =~ /\Ax-forwarded-/ $lc eq "forwarded" $lc eq "x-real-ip" $lc eq "cookie"
Truth table100%5/5
A or B or C or D
A= $lc =~ /\Ax-forwarded-/B= $lc eq "forwarded"C= $lc eq "x-real-ip"D= $lc eq "cookie"
ABCDresult
1XXX1
01XX1
001X1
00011
00000
2643 }
2644 else {
2645 285 ▶ next unless $EXTERNAL_HEADER{$lc};
Branch: 1 branch
BranchTrueFalseTotal
unless $EXTERNAL_HEADER{$lc} 228 57 285
2646 }
2647 2761 $fwd_headers{$name} = $c->req->headers->header($name);
2648 }
2649 # Without a User-Agent Mojo::UserAgent names itself; an external node gets Skeid's name instead.
2650 1058 ▶ $fwd_headers{'User-Agent'} = $EXTERNAL_USER_AGENT unless $internal;
Branch: 1 branch
BranchTrueFalseTotal
unless $internal 20 1038 1058
2651 1058 return %fwd_headers;
2652 }
2653  
2654 # The node of the inventory with this id, or undef.
2655 2132 ▶sub _node_by_id {
Subroutine _node_by_id: called CC=3 SCAR=11.2
2656 2132 my ($skeid, $node_id) = @_;
2657 2132 ▶ return unless defined $node_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id 0 2132 2132
2658 2132 ▶ my ($node) = grep { ($_->{id} // '') eq $node_id } @{$skeid->nodes};
Condition50%1/2
$_->{"id"} // ""
l!l
48230
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
2659 2132 return $node;
2660 }
2661  
2662 # Sets the upstream Authorization header for the selected node, from the KeyBroker
2663 # (api_key_ref) or from the environment (api_key_env), overriding whatever the client sent.
2664 # The callback runs exactly once, and always. It is called with nothing when the request may go
2665 # upstream: the node's key is in place, or the node names no key source -- an internal node then
2666 # forwards the client's header untouched, any other goes without one. It is called with a reason when the node names a key source and
2667 # none produced a key, or when the node is no longer in the inventory and what it named cannot
2668 # be known -- the caller must then refuse the request (_refuse_unkeyed_node) rather than call
2669 # the node, because the only credential left in the headers is the customer's own, and the
2670 # pass-through would hand it to the provider (ADR 0003). The reason names the node, the key
2671 # reference and the variable, never a key, and is for the log and the usage event.
2672 #
2673 # Wherever the client's header is not what goes upstream -- a key was injected, or the request
2674 # is refused -- the client's credentials are taken out of the headers first, in any spelling.
2675 #
2676 # Async because resolution can mean a vault round-trip, and this sits between routing and the
2677 # upstream call -- doing it synchronously stalls every other in-flight request for that
2678 # round-trip (ADR 0005). key_async answers from cache without touching the loop, so the
2679 # blocking case is a cold cache, and even then only one request per reference pays for it.
2680 1074 ▶sub _inject_node_auth_async {
Subroutine _inject_node_auth_async: called CC=3 SCAR=11.0
2681 1074 my ($headers_ref, $skeid, $node_id, $cb) = @_;
2682 1074 ▶ $cb ||= sub { };
Subroutine __ANON__: not called CC=1 SCAR=1.2
Condition33%1/3
$cb ||= sub { }
l!l&&r!l&&!r
107400
MC/DC0%0/2
$cb ||= sub { }
$cb sub { }
Truth table33%1/3
A ||= B
A= $cbB= sub { }
ABresult
1X1
011
000
2683  
2684 1074 my $node = _node_by_id($skeid, $node_id);
2685 1074 ▶ unless ($node) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($node) 10 1064 1074
2686 10 _drop_client_credentials($headers_ref);
2687 10 return $cb->("node '$node_id' is no longer in the inventory, its key source is unknown");
2688 }
2689  
2690 1064 ▶ _upstream_key_async($skeid, $node, sub {
Subroutine __ANON__: called CC=9 SCAR=22.1
2691 1064 my ($key, $reason) = @_;
2692  
2693 1064 ▶ if (defined $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key) 102 962 1064
2694 102 _drop_client_credentials($headers_ref);
2695 # The header the node names carries the raw key; without one it is a Bearer token.
2696 102 my $header = $node->{api_key_header};
2697 102 ▶ if (defined($header) && length($header)) { $headers_ref->{$header} = $key }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $header and length $header) { } 2 100 102
Condition66%2/3
defined $header and length $header
!ll&&!rl&&r
10002
MC/DC50%1/2
defined $header and length $header
defined $header length $header
Truth table66%2/3
A and B
A= defined $headerB= length $header
ABresult
0X0
100
111
2698 100 else { $headers_ref->{Authorization} = "Bearer $key" }
2699 102 return $cb->();
2700 }
2701  
2702 # A node with no key of its own: the documented pass-through, for an internal node only
2703 # (ADR 0032) -- an external one cannot load without a key source, and one put into the
2704 # inventory past that check still never gets the client's credential. Nor does a node from a
2705 # node file (ADR 0031): its URL was chosen by a less trusted writer, and the client's
2706 # credential (with client_auth, the customer's Skeid key) is not that writer's to collect.
2707 962 ▶ unless (defined $reason) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $reason) 904 58 962
2708 _drop_client_credentials($headers_ref)
2709 904 ▶ if length($node->{node_file} // '') || ($node->{trust} // '') ne 'internal';
Branch: 1 branch
BranchTrueFalseTotal
if length($node->{"node_file"} // "") or ($node->{"trust"} // "") ne "internal" 1 903 904
Condition71%5/7
length($node->{"node_file"} // "") or ($node->{"trust"} // "") ne "internal"
l!l&&r!l&&!r
10903
$node->{"node_file"} // ""
l!l
1903
$node->{"trust"} // ""
l!l
9030
MC/DC0%0/2
length($node->{"node_file"} // "") or ($node->{"trust"} // "") ne "internal"
$node->{"node_file"} $node->{"trust"}
Truth table66%2/3
A or B
A= $node->{"node_file"}B= $node->{"trust"}
ABresult
1X1
011
000
2710 904 return $cb->();
2711 }
2712  
2713 # A key source was named and produced nothing. Take the client's credentials out of what
2714 # would go upstream as well, so a caller that ignored the reason still could not leak them.
2715 58 _drop_client_credentials($headers_ref);
2716 58 $cb->($reason);
2717 1064 });
2718 1064 return;
2719 }
2720  
2721 # Resolves the upstream key of $source -- a node, or an MCP server (skeid k103): whatever names
2722 # its key by api_key_ref and api_key_env. The broker is asked first, the variable stands in when
2723 # the reference resolves nothing. The callback runs exactly once, and always: with the key; with
2724 # nothing when $source names no key source; with undef and a reason when it names one and none
2725 # produced a key. The reason names the key reference and the variable, never a key, and is for
2726 # the log and the usage event (ADR 0003).
2727 1093 ▶sub _upstream_key_async {
Subroutine _upstream_key_async: called CC=7 SCAR=19.5
2728 1093 my ($skeid, $source, $cb) = @_;
2729  
2730 1093 my $ref = $source->{api_key_ref};
2731 1093 ▶ $ref = undef unless defined($ref) && length($ref);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ref and length $ref 1003 90 1093
Condition66%2/3
defined $ref and length $ref
!ll&&!rl&&r
1003090
MC/DC50%1/2
defined $ref and length $ref
defined $ref length $ref
Truth table66%2/3
A and B
A= defined $refB= length $ref
ABresult
0X0
100
111
2732 1093 my $env_name = $source->{api_key_env};
2733 1093 ▶ $env_name = undef unless defined($env_name) && length($env_name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $env_name and length $env_name 976 117 1093
Condition66%2/3
defined $env_name and length $env_name
!ll&&!rl&&r
9760117
MC/DC50%1/2
defined $env_name and length $env_name
defined $env_name length $env_name
Truth table66%2/3
A and B
A= defined $env_nameB= length $env_name
ABresult
0X0
100
111
2734  
2735 1093 ▶ my $apply = sub {
Subroutine __ANON__: called CC=12 SCAR=24.9
2736 1093 my ($key, $ref_failure) = @_;
2737  
2738 # Fallback: env var
2739 1093 ▶ if (!defined($key) || !length($key)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $key and length $key) 1047 46 1093
Condition66%2/3
defined $key and length $key
!ll&&!rl&&r
1047046
MC/DC50%1/2
defined $key and length $key
defined $key length $key
Truth table66%2/3
A and B
A= defined $keyB= length $key
ABresult
0X0
100
111
2740 1047 ▶ if (defined $env_name) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $env_name) 117 930 1047
2741 117 ▶ $key = $ENV{$env_name} // '';
Condition100%2/2
$ENV{$env_name} // ""
l!l
9126
MC/DC100%1/1
$ENV{$env_name} // ""
$ENV{$env_name}
Truth table100%2/2
A
A= $ENV{$env_name}
Aresult
11
00
2742 }
2743 }
2744  
2745 1093 ▶ return $cb->($key) if defined($key) && length($key);
Branch: 1 branch
BranchTrueFalseTotal
if defined $key and length $key 127 966 1093
Condition100%3/3
defined $key and length $key
!ll&&!rl&&r
93036127
MC/DC100%2/2
defined $key and length $key
defined $key length $key
Truth table100%3/3
A and B
A= defined $keyB= length $key
ABresult
0X0
100
111
2746 966 ▶ return $cb->() unless defined($ref) || defined($env_name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ref or defined $env_name 907 59 966
Condition100%3/3
defined $ref or defined $env_name
l!l&&r!l&&!r
3425907
MC/DC100%2/2
defined $ref or defined $env_name
defined $ref defined $env_name
Truth table100%3/3
A or B
A= defined $refB= defined $env_name
ABresult
1X1
011
000
2747  
2748 $cb->(undef, join('; ',
2749 (defined($ref) ? "api_key_ref '$ref' $ref_failure" : ()),
2750 (defined($env_name)
2751 59 ▶ ? "api_key_env '$env_name' is " . (defined($ENV{$env_name}) ? 'empty' : 'not set')
Branch: 3 branches
BranchTrueFalseTotal
defined $ref ? : 34 25 59
defined $env_name ? : 36 23 59
defined $ENV{$env_name} ? : 10 26 36
2752 : ()),
2753 ));
2754 1093 };
2755  
2756 1093 ▶ if (defined($ref) && $skeid->has_key_broker) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ref and $skeid->has_key_broker) 80 1013 1093
Condition100%3/3
defined $ref and $skeid->has_key_broker
!ll&&!rl&&r
10031080
MC/DC100%2/2
defined $ref and $skeid->has_key_broker
defined $ref $skeid->has_key_broker
Truth table100%3/3
A and B
A= defined $refB= $skeid->has_key_broker
ABresult
0X0
100
111
2757 80 ▶ $skeid->key_broker->key_async($ref, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2758 80 my ($key, $error) = @_;
2759 # The reference may be logged; what it resolves to may not, and neither may a vault
2760 # response body that might carry it (ADR 0003).
2761 80 ▶ warn "KeyBroker resolve failed for '$ref': $error"
Branch: 1 branch
BranchTrueFalseTotal
if defined $error and not defined $key 32 48 80
Condition66%2/3
defined $error and not defined $key
!ll&&!rl&&r
48032
MC/DC50%1/2
defined $error and not defined $key
defined $error not defined $key
Truth table66%2/3
A and not(B)
A= defined $errorB= not defined $key
ABresult
0X0
100
111
2762 if defined($error) && !defined($key);
2763 80 $apply->($key, 'did not resolve');
2764 80 });
2765 80 return;
2766 }
2767  
2768 1013 $apply->(undef, 'has no key broker to resolve it');
2769 1013 return;
2770 }
2771  
2772 # Header names are case-insensitive and Mojolicious hands an unknown one on as the client
2773 # spelled it, so `X-Api-Key` is as much the client's key as `x-api-key`. An exact-case delete
2774 # lets it travel upstream beside the node's own key.
2775 171 ▶sub _drop_client_credentials {
Subroutine _drop_client_credentials: called CC=2 SCAR=6.9
2776 171 my ($headers_ref) = @_;
2777 171 delete @{$headers_ref}{
2778 171 ▶ grep { lc($_) eq 'authorization' || lc($_) eq 'x-api-key' } keys %$headers_ref
Condition100%3/3
lc $_ eq 'authorization' || lc $_ eq 'x-api-key'
l!l&&r!l&&!r
12882364
MC/DC100%2/2
lc $_ eq 'authorization' || lc $_ eq 'x-api-key'
lc $_ eq 'authorization' lc $_ eq 'x-api-key'
Truth table100%3/3
A || B
A= lc $_ eq 'authorization'B= lc $_ eq 'x-api-key'
ABresult
1X1
011
000
2779 };
2780 171 return;
2781 }
2782  
2783 # The answer to a request whose node names a key source that produced no key: no upstream call,
2784 # and everything an admitted request is owed -- its request.finish, one usage event, an error in
2785 # the shape of the face that was called. 503, not 502: no upstream was asked, so nothing came
2786 # back bad; this Skeid cannot serve the request until its broker or its environment is put
2787 # right, and a client may retry. The client is told no more than that -- the reason carries a
2788 # key reference, which belongs in the log and the usage event, not in a customer's answer.
2789 60 ▶sub _refuse_unkeyed_node {
Subroutine _refuse_unkeyed_node: called CC=1 SCAR=0.0
2790 60 my ($c, $node_id, $started, $meta, $reason) = @_;
2791 60 my $duration_ms = _duration_ms($started);
2792 60 $c->app->log->error("No upstream key for node '$node_id', request refused: $reason");
2793 60 $c->skeid->call_function('request.finish', {
2794 id => $node_id,
2795 ok => 0,
2796 duration_ms => $duration_ms,
2797 });
2798 60 _record_usage_event($c, {
2799 %$meta,
2800 node_id => $node_id,
2801 status_code => 503,
2802 ok => 0,
2803 duration_ms => $duration_ms,
2804 error_type => 'upstream_key_unavailable',
2805 error_message => $reason,
2806 metrics => {},
2807 });
2808 60 _render_error($c, 503, 'The upstream key for this model is not available',
2809 'upstream_key_unavailable');
2810 60 return;
2811 }
2812  
2813 # A request over its key's rate (skeid k125): 429 with Retry-After in the face's shape, and one
2814 # usage event without content, so the refusals of a runaway caller show where its usage does.
2815 # No node was picked, so there is no slot to give back.
2816 2 ▶sub _refuse_rate_limited {
Subroutine _refuse_rate_limited: called CC=8 SCAR=22.3
2817 2 my ($c, $model, $api_key_id, $retry_after, $names) = @_;
2818 2 ▶ $names ||= {};
Condition50%1/2
$names ||= {}
l!l
20
MC/DC0%0/1
$names ||= {}
$names
Truth table50%1/2
A
A= $names
Aresult
11
00
2819 2 ▶ my $format = $c->stash('skeid.error_format') // '';
Condition100%2/2
$c->stash("skeid.error_format") // ""
l!l
11
MC/DC100%1/1
$c->stash("skeid.error_format") // ""
$c->stash("skeid.error_format")
Truth table100%2/2
A
A= $c->stash("skeid.error_format")
Aresult
11
00
2820 _record_usage_event($c, {
2821 api_format => (length($format) ? $format : 'openai'),
2822 endpoint => $c->req->url->path->to_string,
2823 api_key_id => $api_key_id,
2824 provider => 'skeid',
2825 model => ($model // ''),
2826 # A bent request (ADR 0033) keeps the name the client sent and says what it was routed under.
2827 requested_model => ($names->{requested_model} // $model // ''),
2828 2 ▶ (defined($names->{routed_model}) ? (routed_model => $names->{routed_model}) : ()),
Branch: 2 branches
BranchTrueFalseTotal
length $format ? : 1 1 2
defined $names->{'routed_model'} ? : 0 2 2
Condition42%3/7
$model // ""
l!l
20
($names->{"requested_model"} // $model) // ""
l!l
20
$names->{"requested_model"} // $model
l!l&&r!l&&!r
200
MC/DC0%0/1
$model // ""
$model
MC/DC0%0/2
($names->{"requested_model"} // $model) // ""
$names->{"requested_model"} $model
Truth table50%1/2
A
A= $model
Aresult
11
00
Truth table33%1/3
A // B
A= $names->{"requested_model"}B= $model
ABresult
1X1
011
000
2829 status_code => 429,
2830 ok => 0,
2831 duration_ms => 0,
2832 error_type => 'key_rate_limited',
2833 error_message => 'Request rate of the key exceeded',
2834 metrics => {},
2835 });
2836 2 $c->res->headers->header('Retry-After' => $retry_after);
2837 2 _render_error($c, 429, "Request rate limit of this key exceeded; retry after ${retry_after}s",
2838 'rate_limit_exceeded', 'key_rate_limited');
2839 2 return;
2840 }
2841  
2842 # The answer to a request that holds a slot on a node and cannot be put to it: the body is in a
2843 # shape the node's dialect has no place for, which only shows once the node is known (rerank to a
2844 # `rerank_format` node, skeid k92). As for an unkeyed node, no upstream call and everything an
2845 # admitted request is owed -- its request.finish, one usage event, an error in the face's shape
2846 # -- but 400: the request is the client's to change, and no retry will get it through.
2847 # $message is written for the client and quotes nothing of the request.
2848 6 ▶sub _refuse_unsendable_request {
Subroutine _refuse_unsendable_request: called CC=1 SCAR=0.0
2849 6 my ($c, $node_id, $started, $meta, $message) = @_;
2850 6 my $duration_ms = _duration_ms($started);
2851 6 $c->skeid->call_function('request.finish', {
2852 id => $node_id,
2853 ok => 0,
2854 rejected => 1,
2855 duration_ms => $duration_ms,
2856 });
2857 6 _record_usage_event($c, {
2858 %$meta,
2859 node_id => $node_id,
2860 status_code => 400,
2861 ok => 0,
2862 duration_ms => $duration_ms,
2863 error_type => 'invalid_request_error',
2864 error_message => $message,
2865 metrics => {},
2866 });
2867 6 _render_error($c, 400, $message, 'invalid_request_error');
2868 6 return;
2869 }
2870  
2871 # The bridge of the MCP routes (skeid k103, ADR 0022). Three answers before a handler runs, in
2872 # this order. Without an mcp: section the routes do not exist: the answer is the one an unknown
2873 # path gets, and it comes before the client gate, so a Skeid that has no MCP servers does not
2874 # start answering 401 where it answered 404. Then the client gate, as on every client route.
2875 # Then a key at all, also while client authentication is off: an MCP server is assigned to a
2876 # customer key id, `anonymous` can hold none, and a caller that forgot its key is better told
2877 # so than shown an empty list.
2878 85 ▶sub _authorize_mcp_client {
Subroutine _authorize_mcp_client: called CC=5 SCAR=16.1
2879 85 my ($c) = @_;
2880 85 my $skeid = $c->skeid;
2881 85 $skeid->maybe_reload_config;
2882 85 ▶ unless ($skeid->mcp_enabled) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($skeid->mcp_enabled) 14 71 85
2883 14 $c->reply->not_found;
2884 14 return undef;
2885 }
2886 71 ▶ return undef unless _authorize_client($c);
Branch: 1 branch
BranchTrueFalseTotal
unless _authorize_client($c) 6 65 71
2887  
2888 65 my $api_key_id = _request_api_key_id($c);
2889 65 ▶ return 1 if defined($api_key_id) && $api_key_id ne 'anonymous';
Branch: 1 branch
BranchTrueFalseTotal
if defined $api_key_id and $api_key_id ne "anonymous" 60 5 65
Condition66%2/3
defined $api_key_id and $api_key_id ne "anonymous"
!ll&&!rl&&r
0560
MC/DC50%1/2
defined $api_key_id and $api_key_id ne "anonymous"
defined $api_key_id $api_key_id ne "anonymous"
Truth table66%2/3
A and B
A= defined $api_key_idB= $api_key_id ne "anonymous"
ABresult
0X0
100
111
2890  
2891 5 $c->res->headers->header('WWW-Authenticate' => 'Bearer realm="skeid"');
2892 5 _render_error($c, 401, 'Missing API key', 'invalid_request_error', 'invalid_api_key');
2893 5 return undef;
2894 }
2895  
2896 # GET /v1/mcp/servers: the servers assigned to the presented key, and only what a client needs
2897 # to connect -- the public URL of a relayed server, the command of a stdio one. Whose answer it
2898 # is depends on the key, so it carries the manifest's cache headers. The public URL is the
2899 # config's, else the one this request came in on.
2900 6 ▶sub _handle_mcp_servers {
Subroutine _handle_mcp_servers: called CC=2 SCAR=6.9
2901 6 my ($c) = @_;
2902 6 my $mcp = 'Langertha::Skeid::Protocol::MCP';
2903 6 my $skeid = $c->skeid;
2904 6 _manifest_cache_headers($c);
2905  
2906 6 my $base = $skeid->mcp_public_url;
2907 6 ▶ unless (defined $base) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $base) 1 5 6
2908 1 my $abs = $c->req->url->to_abs;
2909 1 $base = $abs->scheme . '://' . $abs->host_port;
2910 }
2911 $c->render(json => {
2912 object => 'list',
2913 6 data => [ map { $mcp->listing_entry($_, $base) } @{$skeid->mcp_servers_for_key(_request_api_key_id($c))} ],
2914 });
2915 6 return;
2916 }
2917  
2918 # POST|GET|DELETE /mcp/<name>[/<path>] (skeid k103): relayed to the MCP server of that name, if
2919 # it is assigned to the presented key. Everything that is not such a server is one 404 -- an
2920 # unknown name, another key's server, a stdio entry, a sub-path that climbs -- so a key cannot
2921 # learn which names exist. Skeid reads nothing of the request (ADR 0022): the body goes up as
2922 # the bytes it came in, with the headers Protocol::MCP lets through, the server's static
2923 # headers and the server's own key. The client's credentials are never among them.
2924 54 ▶sub _handle_mcp {
Subroutine _handle_mcp: called CC=6 SCAR=17.9
2925 54 my ($c) = @_;
2926 54 my $mcp = 'Langertha::Skeid::Protocol::MCP';
2927 54 my $skeid = $c->skeid;
2928 54 my $req = $c->req;
2929  
2930 54 my $api_key_id = _request_api_key_id($c);
2931 54 my $server = $skeid->mcp_server_for_key($c->stash('mcp_server'), $api_key_id);
2932 my $url = ($server && $mcp->is_relayed($server->{transport}))
2933 54 ▶ ? $mcp->upstream_url($server->{url}, $c->stash('mcp_path'), $req->url->query)
Branch: 1 branch
BranchTrueFalseTotal
$server && $mcp->is_relayed($server->{'transport'}) ? : 37 17 54
Condition100%3/3
$server and $mcp->is_relayed($server->{"transport"})
!ll&&!rl&&r
14337
MC/DC100%2/2
$server and $mcp->is_relayed($server->{"transport"})
$server $mcp->is_relayed($server->{"transport"})
Truth table100%3/3
A and B
A= $serverB= $mcp->is_relayed($server->{"transport"})
ABresult
0X0
100
111
2934 : undef;
2935 54 ▶ unless ($url) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($url) 23 31 54
2936 23 _render_error($c, 404, 'No MCP server of this name is available for this key', 'not_found');
2937 23 return;
2938 }
2939  
2940 # A body cut off at the server's request limit is not the body the client sent.
2941 31 ▶ if ($req->is_limit_exceeded) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->is_limit_exceeded) 2 29 31
2942 2 _render_error($c, 413, 'Maximum message size exceeded', 'invalid_request_error');
2943 2 return;
2944 }
2945  
2946 29 _extend_client_timeout($c);
2947 # Before the key resolution: a cold broker cache answers on a later tick.
2948 29 $c->render_later;
2949 29 my $started = time;
2950 my $meta = {
2951 api_format => 'mcp',
2952 endpoint => $mcp->endpoint($server->{name}),
2953 api_key_id => $api_key_id,
2954 provider => 'skeid',
2955 route_url => $server->{url},
2956 29 };
2957 29 ▶ my %headers = ($mcp->request_headers($req->headers), %{$server->{headers} || {}});
Condition50%1/2
$server->{'headers'} || {}
l!l
290
MC/DC0%0/1
$server->{'headers'} || {}
$server->{'headers'}
Truth table50%1/2
A
A= $server->{'headers'}
Aresult
11
00
2958  
2959 29 ▶ _upstream_key_async($skeid, $server, sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
2960 29 my ($key, $no_key) = @_;
2961  
2962 # The client hung up while the key was being resolved: nothing went upstream, nothing is
2963 # metered, as on every other route.
2964 29 ▶ return if _client_gone($c);
Branch: 1 branch
BranchTrueFalseTotal
if _client_gone($c) 0 29 29
2965  
2966 # A key source was named and produced no key: the server is not called without it.
2967 29 ▶ if (defined $no_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $no_key) 1 28 29
2968 1 $c->app->log->error("No upstream key for MCP server '$server->{name}', request refused: $no_key");
2969 1 _record_usage_event($c, {
2970 %$meta,
2971 status_code => 503,
2972 ok => 0,
2973 duration_ms => _duration_ms($started),
2974 error_type => 'upstream_key_unavailable',
2975 error_message => $no_key,
2976 metrics => {},
2977 });
2978 1 _render_error($c, 503, 'The upstream key for this MCP server is not available',
2979 'upstream_key_unavailable');
2980 1 return;
2981 }
2982  
2983 28 ▶ $headers{Authorization} = "Bearer $key" if defined $key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key 25 3 28
2984 28 _relay_mcp($c, $server, $url, \%headers, $meta, $started);
2985 29 });
2986 29 return;
2987 }
2988  
2989 # The relay of one MCP request. Its own function, not _proxy_openai_stream: there is no node --
2990 # no slot to give back, no capacity headers, no usage frame to read along -- and an answer's
2991 # shape is not known before it arrives: one JSON body, an event stream, or nothing (202).
2992 # So every answer is relayed the same way, as it arrives. The response is opened -- status and
2993 # headers written out -- the moment the upstream's headers are parsed, before any body byte: a
2994 # standing GET stream is open for the client before its first event. Every chunk is then written
2995 # as it was read. Mojolicious buffers what the client has not taken yet and keeps the order.
2996 #
2997 # Two answers are not relayed, because they are about this gateway and not for its client. An
2998 # upstream 401: towards the client 401 says "your Skeid key is not let in", and an MCP client
2999 # acts on it; the upstream's 401 is about the key Skeid presented. And a redirect: its Location
3000 # is an upstream URL, which a customer is never shown, and Skeid follows none -- the server's
3001 # key would travel along. Both are the operator's to fix: logged, answered 502.
3002 #
3003 # One usage event per request, written when it ends. An event stream has no end that could be
3004 # checked without reading MCP, so however it ends -- the client leaves, the upstream closes it,
3005 # the time limit cuts it -- it is recorded under the status it was opened with. Any other answer
3006 # is held to its framing, and a client that leaves before it is complete is a 499.
3007 28 ▶sub _relay_mcp {
Subroutine _relay_mcp: called CC=2 SCAR=7.0
3008 28 my ($c, $server, $url, $headers, $meta, $started) = @_;
3009 28 my $mcp = 'Langertha::Skeid::Protocol::MCP';
3010  
3011 28 my $body = $c->req->body;
3012 28 ▶ my $tx = $c->app->ua->build_tx($c->req->method => $url => $headers => (length($body) ? ($body) : ()));
Branch: 1 branch
BranchTrueFalseTotal
length $body ? : 24 4 28
3013 # As for every relayed stream: the bytes, not Mojolicious' own SSE events (skeid karr #30).
3014 28 $tx->res->content(Langertha::Skeid::Proxy::RelayContent->new);
3015 # A standing stream has no size: the user agent's response limit (2 GiB by default) would cut
3016 # it at its sum, however long it lived. The time limits bound it, not its length.
3017 28 $tx->res->max_message_size(0);
3018  
3019 # Taken now: the request may be past its transaction when the answer opens.
3020 28 my $request_id = _request_id($c);
3021 28 my ($opened, $event_stream, $status) = (0, 0, 0);
3022 # Why the upstream's answer is not relayed, once its status says so: see above.
3023 27 ▶ my $unrelayed = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
3024 27 my ($code) = @_;
3025 27 ▶ return undef unless defined $code;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $code 1 26 27
3026 26 ▶ return 'unauthorized' if $code == 401;
Branch: 1 branch
BranchTrueFalseTotal
if $code == 401 1 25 26
3027 25 ▶ return 'redirect' if $code >= 300 && $code < 400;
Branch: 1 branch
BranchTrueFalseTotal
if $code >= 300 and $code < 400 1 24 25
Condition100%3/3
$code >= 300 and $code < 400
!ll&&!rl&&r
2221
MC/DC100%2/2
$code >= 300 and $code < 400
$code >= 300 $code < 400
Truth table100%3/3
A and B
A= $code >= 300B= $code < 400
ABresult
0X0
100
111
3028 24 return undef;
3029 28 };
3030 28 my $refused;
3031 # Set by whichever comes first, the upstream's completion or the client hanging up, so that
3032 # the usage event is written once.
3033 28 my $closed = 0;
3034  
3035 28 ▶ my $record = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3036 28 my (%event) = @_;
3037 28 _record_usage_event($c, { %$meta, duration_ms => _duration_ms($started), metrics => {}, %event });
3038 28 };
3039 24 ▶ my $open = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
3040 24 my ($res) = @_;
3041 24 $status = $res->code;
3042 24 $c->res->code($status);
3043 24 for my $name (@{$res->headers->names}) {
3044 135 ▶ next unless $mcp->response_header_allowed($name);
Branch: 1 branch
BranchTrueFalseTotal
unless $mcp->response_header_allowed($name) 90 45 135
3045 45 $c->res->headers->header($name => $res->headers->header($name));
3046 }
3047 24 $c->res->headers->header('x-request-id' => $request_id);
3048 24 $opened = 1;
3049 28 };
3050  
3051 67 ▶ $tx->res->content->unsubscribe('read')->on(read => sub {
Subroutine __ANON__: called CC=6 SCAR=18.2
3052 67 my ($content, $bytes) = @_;
3053 67 ▶ return if $closed || $refused;
Branch: 1 branch
BranchTrueFalseTotal
if $closed or $refused 0 67 67
Condition33%1/3
$closed or $refused
l!l&&r!l&&!r
0067
MC/DC0%0/2
$closed or $refused
$closed $refused
Truth table33%1/3
A or B
A= $closedB= $refused
ABresult
1X1
011
000
3054 67 ▶ unless ($opened) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opened) 22 45 67
3055 # The first read comes with the upstream's headers, with or without a first chunk.
3056 22 ▶ return if defined($refused = $unrelayed->($tx->res->code));
Branch: 1 branch
BranchTrueFalseTotal
if defined($refused = &$unrelayed($tx->res->code)) 1 21 22
3057 21 $open->($tx->res);
3058 21 $event_stream = $mcp->is_event_stream($tx->res->headers->content_type);
3059 21 $c->write_chunk;
3060 }
3061 66 ▶ $c->write_chunk($bytes) if length $bytes;
Branch: 1 branch
BranchTrueFalseTotal
if length $bytes 61 5 66
3062 28 });
3063  
3064 28 ▶ $c->tx->on(finish => sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
3065 # Also emitted when the answer is complete, and then there is nothing left to do here.
3066 28 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 26 2 28
3067 2 $closed = 1;
3068 2 $tx->res->content->unsubscribe('read');
3069 2 ▶ $record->(($opened && $event_stream)
Branch: 2 branches
BranchTrueFalseTotal
$opened && $event_stream ? : 1 1 2
$status < 500 ? : 1 0 1
Condition66%2/3
$opened and $event_stream
!ll&&!rl&&r
101
MC/DC50%1/2
$opened and $event_stream
$opened $event_stream
Truth table66%2/3
A and B
A= $openedB= $event_stream
ABresult
0X0
100
111
3070 ? (status_code => $status, ok => ($status < 500 ? 1 : 0))
3071 : _client_abort_event());
3072 2 _cancel_upstream($tx);
3073 28 });
3074  
3075 28 ▶ $c->app->ua->start($tx => sub {
Subroutine __ANON__: called CC=31 SCAR=35.3
3076 28 my ($ua, $done) = @_;
3077 # The read listener closes over the upstream transaction and the client controller: remove
3078 # it on every path, or the completed transaction owns the listener that owns it.
3079 28 $done->res->content->unsubscribe('read');
3080  
3081 # The client hung up and its request was closed then; this is the cancelled transaction.
3082 28 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 2 26 28
3083 26 $closed = 1;
3084  
3085 26 my $res = $done->res;
3086 26 my $err = $done->error;
3087 26 my $code = $res->code;
3088 # Mojo reports an HTTP 4xx/5xx as an error with a code; one without is the connection's.
3089 26 ▶ my $broken = ($err && !$err->{code}) ? ($err->{message} // 'unknown') : undef;
Branch: 1 branch
BranchTrueFalseTotal
$err && !$err->{'code'} ? : 2 24 26
Condition80%4/5
$err and not $err->{"code"}
!ll&&!rl&&r
2132
$err->{"message"} // "unknown"
l!l
20
MC/DC100%2/2
$err and not $err->{"code"}
$err not $err->{"code"}
MC/DC0%0/1
$err->{"message"} // "unknown"
$err->{"message"}
Truth table100%3/3
A and not(B)
A= $errB= not $err->{"code"}
ABresult
0X0
100
111
Truth table50%1/2
A
A= $err->{"message"}
Aresult
11
00
3090  
3091 26 ▶ $refused //= $unrelayed->($code) unless $opened;
Branch: 1 branch
BranchTrueFalseTotal
unless $opened 6 20 26
Condition100%3/3
$refused //= &$unrelayed($code)
l!l&&r!l&&!r
114
MC/DC100%2/2
$refused //= &$unrelayed($code)
$refused &$unrelayed($code)
Truth table100%3/3
A //= B
A= $refusedB= &$unrelayed($code)
ABresult
1X1
011
000
3092 26 ▶ if (defined($refused) && $refused eq 'unauthorized') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $refused and $refused eq "unauthorized") 1 25 26
Condition100%3/3
defined $refused and $refused eq "unauthorized"
!ll&&!rl&&r
2411
MC/DC100%2/2
defined $refused and $refused eq "unauthorized"
defined $refused $refused eq "unauthorized"
Truth table100%3/3
A and B
A= defined $refusedB= $refused eq "unauthorized"
ABresult
0X0
100
111
3093 $c->app->log->error("MCP server '$server->{name}' answered 401 to the key Skeid presented ("
3094 1 ▶ . (join(', ', map { "$_ '$server->{$_}'" } grep { defined $server->{$_} } qw( api_key_ref api_key_env ))
Condition50%1/2
join(', ', map({"$_ '$server->{$_}'";} grep({defined $server->{$_};} 'api_key_ref', 'api_key_env'))) || 'it names no key source'
l!l
10
MC/DC0%0/1
join(', ', map({"$_ '$server->{$_}'";} grep({defined $server->{$_};} 'api_key_ref', 'api_key_env'))) || 'it names no key source'
join(', ', map({"$_ '$server->{$_}'";} grep({defined $server->{$_};} 'api_key_ref', 'api_key_env')))
Truth table50%1/2
A
A= join(', ', map({"$_ '$server->{$_}'";} grep({defined $server->{$_};} 'api_key_ref', 'api_key_env')))
Aresult
11
00
3095 || 'it names no key source') . ')');
3096 1 $record->(status_code => 502, ok => 0, error_type => 'upstream_unauthorized',
3097 error_message => 'The MCP server answered 401 to the upstream key');
3098 1 _render_error($c, 502, 'Upstream error: the MCP server did not accept the gateway\'s credential',
3099 'upstream_error');
3100 1 return;
3101 }
3102 25 ▶ if (defined $refused) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $refused) 1 24 25
3103 1 ▶ my $location = $res->headers->location // '';
Condition50%1/2
$res->headers->location // ""
l!l
10
MC/DC0%0/1
$res->headers->location // ""
$res->headers->location
Truth table50%1/2
A
A= $res->headers->location
Aresult
11
00
3104 1 $c->app->log->error("MCP server '$server->{name}' answered $code with a redirect to '$location': "
3105 . 'no redirect is followed, configure the URL it leads to');
3106 1 $record->(status_code => 502, ok => 0, error_type => 'upstream_redirect',
3107 error_message => "The MCP server answered $code with a redirect");
3108 1 _render_error($c, 502, 'Upstream error: the MCP server answered with a redirect', 'upstream_error');
3109 1 return;
3110 }
3111  
3112 24 ▶ unless ($opened) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opened) 4 20 24
3113 # No answer, or one whose connection broke before its body began.
3114 4 ▶ if (!defined($code) || defined($broken)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $code or defined $broken) 1 3 4
Condition66%2/3
not defined $code or defined $broken
l!l&&r!l&&!r
103
MC/DC50%1/2
not defined $code or defined $broken
not defined $code defined $broken
Truth table66%2/3
not(A) or B
A= not defined $codeB= defined $broken
ABresult
1X1
011
000
3115 1 ▶ my $message = $broken // 'unknown';
Condition50%1/2
$broken // "unknown"
l!l
10
MC/DC0%0/1
$broken // "unknown"
$broken
Truth table50%1/2
A
A= $broken
Aresult
11
00
3116 1 $record->(status_code => 502, ok => 0, error_type => 'upstream_error', error_message => $message);
3117 1 _render_error($c, 502, "Upstream error: $message", 'upstream_error');
3118 1 return;
3119 }
3120 # An answer without a body (202, 204): no read ever came.
3121 3 $open->($res);
3122 3 ▶ $record->(status_code => $status, ok => ($status < 500 ? 1 : 0));
Branch: 1 branch
BranchTrueFalseTotal
$status < 500 ? : 3 0 3
3123 3 $c->rendered;
3124 3 return;
3125 }
3126  
3127 # The answer is open, so its status is sent. An event stream ends however it ends. Anything
3128 # else is held to its framing: Mojo::UserAgent reports an upstream that hangs up mid-body as
3129 # no error at all once the status line has arrived.
3130 20 my $cut;
3131 20 ▶ unless ($event_stream) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($event_stream) 17 3 20
3132 17 my $content = $res->content;
3133 17 ▶ my $framed = $content->is_chunked || length($content->headers->content_length // '');
Condition40%2/5
$content->is_chunked || length($content->headers->content_length // '')
l!l&&r!l&&!r
0170
$content->headers->content_length // ""
l!l
170
MC/DC0%0/2
$content->is_chunked || length($content->headers->content_length // '')
$content->is_chunked $content->headers->content_length
Truth table33%1/3
A || B
A= $content->is_chunkedB= $content->headers->content_length
ABresult
1X1
011
000
3134 17 ▶ $cut = $broken // (($framed && !$content->is_finished) ? 'Premature connection close' : undef);
Branch: 1 branch
BranchTrueFalseTotal
$framed && !$content->is_finished ? : 0 17 17
Condition40%2/5
$broken // ($framed && !$content->is_finished ? "Premature connection close" : undef)
l!l
017
$framed and not $content->is_finished
!ll&&!rl&&r
0170
MC/DC0%0/1
$broken // ($framed && !$content->is_finished ? "Premature connection close" : undef)
$broken
Truth table50%1/2
A
A= $broken
Aresult
11
00
3135 }
3136 # An event stream has no framing to check, but a time limit cutting it is told by the user
3137 # agent: that one is not a clean end, whatever status it was opened with.
3138 20 ▶ my $timeout = ($event_stream && defined($broken) && $broken =~ /timeout/i) ? $broken : undef;
Branch: 1 branch
BranchTrueFalseTotal
$event_stream && defined $broken && $broken =~ /timeout/i ? : 1 19 20
Condition83%5/6
$event_stream and defined $broken and $broken =~ /timeout/i
!ll&&!rl&&r
1901
$event_stream and defined $broken
!ll&&!rl&&r
1721
MC/DC66%2/3
$event_stream and defined $broken and $broken =~ /timeout/i
$event_stream defined $broken $broken =~ /timeout/i
Truth table75%3/4
A and B and C
A= $event_streamB= defined $brokenC= $broken =~ /timeout/i
ABCresult
0XX0
10X0
1100
1111
3139 20 ▶ $record->(
Branch: 3 branches
BranchTrueFalseTotal
!(defined $cut || defined $timeout) && $status < 500 ? : 18 2 20
defined $cut ? : 0 20 20
defined $timeout ? : 1 19 20
Condition83%5/6
not defined $cut || defined $timeout and $status < 500
!ll&&!rl&&r
1118
defined $cut || defined $timeout
l!l&&r!l&&!r
0119
MC/DC66%2/3
not defined $cut || defined $timeout and $status < 500
defined $cut defined $timeout $status < 500
Truth table75%3/4
not(A || B) and C
A= defined $cutB= defined $timeoutC= $status < 500
ABCresult
1XX0
01X0
0000
0011
3140 status_code => $status,
3141 ok => (!defined($cut) && !defined($timeout) && $status < 500) ? 1 : 0,
3142 (defined($cut) ? (error_type => 'upstream_error', error_message => $cut) : ()),
3143 (defined($timeout) ? (error_type => 'upstream_timeout', error_message => $timeout) : ()),
3144 );
3145 20 $c->finish;
3146 28 });
3147 28 return;
3148 }
3149  
3150 # The free capacity probe (ADR 0009): a commercial provider will not tell us its queue depth,
3151 # but it puts its rate-limit state on every response we already have in hand. Reading it costs
3152 # no extra request -- which is the whole reason this is worth doing on the request path at all.
3153 #
3154 # Pulls the handful of headers by name rather than walking all of them; this runs per response.
3155 99 my @CAPACITY_HEADERS = Langertha::Skeid->capacity_header_names;
3156  
3157 975 ▶sub _observe_capacity {
Subroutine _observe_capacity: called CC=10 SCAR=23.5
3158 975 my ($c, $node_id, $res) = @_;
3159 975 ▶ return unless defined($node_id) && length($node_id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 975 975
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
00975
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
3160 975 ▶ return unless $res;
Branch: 1 branch
BranchTrueFalseTotal
unless $res 0 975 975
3161 975 ▶ my $headers = $res->headers or return;
Branch: 1 branch
BranchTrueFalseTotal
my $headers = $res->headers or return 975 0 975
3162  
3163 975 my %found;
3164 975 for my $name (@CAPACITY_HEADERS) {
3165 14625 my $value = $headers->header($name);
3166 14625 ▶ $found{$name} = $value if defined $value;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 7 14618 14625
3167 }
3168 975 ▶ my $status = $res->code // 0;
Condition100%2/2
$res->code // 0
l!l
96114
MC/DC100%1/1
$res->code // 0
$res->code
Truth table100%2/2
A
A= $res->code
Aresult
11
00
3169 975 ▶ return unless %found || $status == 429;
Branch: 1 branch
BranchTrueFalseTotal
unless %found or $status == 429 968 7 975
Condition100%3/3
%found or $status == 429
l!l&&r!l&&!r
52968
MC/DC100%2/2
%found or $status == 429
%found $status == 429
Truth table100%3/3
A or B
A= %foundB= $status == 429
ABresult
1X1
011
000
3170  
3171 7 $c->skeid->call_function('capacity.observe', {
3172 id => $node_id,
3173 headers => \%found,
3174 status => $status,
3175 });
3176 7 return;
3177 }
3178  
3179 1839 ▶sub _extract_request_api_key {
Subroutine _extract_request_api_key: called CC=7 SCAR=19.5
3180 1839 my ($c) = @_;
3181 1839 my $auth = $c->req->headers->authorization;
3182 1839 my $x_api_key = $c->req->headers->header('x-api-key');
3183 1839 ▶ my $raw = defined($auth) ? $auth : (defined($x_api_key) ? $x_api_key : '');
Branch: 2 branches
BranchTrueFalseTotal
defined $auth ? : 826 1013 1839
defined $x_api_key ? : 101 912 1013
3184 # A browser cannot set a header on a WebSocket: the realtime route takes its key from the
3185 # subprotocol list as a last resort (skeid k95), only ever for the one route, and never
3186 # before a header. It is read here and answered nowhere.
3187 1839 ▶ if (!length($raw) && $c->req->url->path->to_route =~ m{\A/v1/realtime/?\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not length $raw and $c->req->url->path->to_route =~ m[\A/v1/realtime/?\z]) 88 1751 1839
Condition100%3/3
not length $raw and $c->req->url->path->to_route =~ m[\A/v1/realtime/?\z]
!ll&&!rl&&r
92782488
MC/DC100%2/2
not length $raw and $c->req->url->path->to_route =~ m[\A/v1/realtime/?\z]
not length $raw $c->req->url->path->to_route =~ m[\A/v1/realtime/?\z]
Truth table100%3/3
not(A) and B
A= not length $rawB= $c->req->url->path->to_route =~ m[\A/v1/realtime/?\z]
ABresult
0X0
100
111
3188 88 my $key = Langertha::Skeid::Protocol::Realtime->subprotocol_key(
3189 $c->req->headers->sec_websocket_protocol);
3190 88 ▶ return ($key, $key) if defined $key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key 6 82 88
3191 }
3192 1833 ▶ my $api_key = $raw // '';
Condition50%1/2
$raw // ""
l!l
18330
MC/DC0%0/1
$raw // ""
$raw
Truth table50%1/2
A
A= $raw
Aresult
11
00
3193 1833 $api_key =~ s/^Bearer\s+//i;
3194 1833 return ($raw, $api_key);
3195 }
3196  
3197 # Who the caller is. Everything downstream hangs off this: the routing policy that decides
3198 # which nodes they may reach, and the usage event they get billed for. So it may only be
3199 # derived from something the caller had to prove -- the key they presented.
3200 #
3201 # x-skeid-key-id is honoured only when the deployment says it authenticates the caller before
3202 # Skeid sees the request (routing.trust_key_id_header). Believing it unconditionally would let
3203 # any client name itself into another customer's policy, and into another customer's bill.
3204 1848 ▶sub _request_api_key_id {
Subroutine _request_api_key_id: called CC=5 SCAR=16.8
3205 1848 my ($c) = @_;
3206  
3207 1848 ▶ if ($c->skeid->trust_key_id_header) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->skeid->trust_key_id_header) 9 1839 1848
3208 9 ▶ my $forced = $c->req->headers->header('x-skeid-key-id')
Condition66%2/3
$c->req->headers->header("x-skeid-key-id") // $c->req->headers->header("x-api-key-id")
l!l&&r!l&&!r
720
MC/DC0%0/2
$c->req->headers->header("x-skeid-key-id") // $c->req->headers->header("x-api-key-id")
$c->req->headers->header("x-skeid-key-id") $c->req->headers->header("x-api-key-id")
Truth table66%2/3
A // B
A= $c->req->headers->header("x-skeid-key-id")B= $c->req->headers->header("x-api-key-id")
ABresult
1X1
011
000
3209 // $c->req->headers->header('x-api-key-id');
3210 9 ▶ return $forced if defined($forced) && length($forced);
Branch: 1 branch
BranchTrueFalseTotal
if defined $forced and length $forced 9 0 9
Condition33%1/3
defined $forced and length $forced
!ll&&!rl&&r
009
MC/DC0%0/2
defined $forced and length $forced
defined $forced length $forced
Truth table33%1/3
A and B
A= defined $forcedB= length $forced
ABresult
0X0
100
111
3211 }
3212  
3213 1839 my (undef, $api_key) = _extract_request_api_key($c);
3214 1839 return $c->skeid->key_id_for_key($api_key);
3215 }
3216  
3217 # The id taken when the request arrived; a client's own x-request-id is taken over, else one is
3218 # made up. Before that hook ran (a bare controller) it is worked out from the request, and once
3219 # the transaction is gone it must come from the stash.
3220 4130 ▶sub _request_id {
Subroutine _request_id: called CC=5 SCAR=16.2
3221 4130 my ($c) = @_;
3222 4130 my $kept = $c->stash('skeid.request_id');
3223 4130 ▶ return $kept if defined($kept) && length($kept);
Branch: 1 branch
BranchTrueFalseTotal
if defined $kept and length $kept 1717 2413 4130
Condition66%2/3
defined $kept and length $kept
!ll&&!rl&&r
241301717
MC/DC50%1/2
defined $kept and length $kept
defined $kept length $kept
Truth table66%2/3
A and B
A= defined $keptB= length $kept
ABresult
0X0
100
111
3224 2413 my $rid = $c->req->headers->header('x-request-id');
3225 2413 ▶ return $rid if defined($rid) && length($rid);
Branch: 1 branch
BranchTrueFalseTotal
if defined $rid and length $rid 48 2365 2413
Condition66%2/3
defined $rid and length $rid
!ll&&!rl&&r
2365048
MC/DC50%1/2
defined $rid and length $rid
defined $rid length $rid
Truth table66%2/3
A and B
A= defined $ridB= length $rid
ABresult
0X0
100
111
3226 2365 return 'req_' . int(time * 1000) . '_' . int(rand(1_000_000));
3227 }
3228  
3229 # finish_reason in the usage contract's words (skeid k121): stop, length, content_filter,
3230 # tool_calls, error or other. A failed request is `error`, whatever came before; a request whose
3231 # answer has no finish reason (embeddings, audio, rerank, documents) has none. A client that hung
3232 # up is not a failed answer: it keeps the reason the stream had reached, else `other`, so the
3233 # error rate counts what went wrong upstream, not callers that left.
3234 99 my %FINISH_REASON = (
3235 stop => 'stop', length => 'length', content_filter => 'content_filter',
3236 tool_calls => 'tool_calls', function_call => 'tool_calls',
3237 );
3238  
3239 1095 ▶sub _finish_reason_field {
Subroutine _finish_reason_field: called CC=16 SCAR=28.1
3240 1095 my ($args) = @_;
3241 1095 ▶ if (($args->{error_type} // '') eq 'client_abort') {
Branch: 1 branch
BranchTrueFalseTotal
if (($args->{"error_type"} // "") eq "client_abort") 33 1062 1095
Condition100%2/2
$args->{"error_type"} // ""
l!l
254841
MC/DC100%1/1
$args->{"error_type"} // ""
$args->{"error_type"}
Truth table100%2/2
A
A= $args->{"error_type"}
Aresult
11
00
3242 33 my $raw = $args->{finish_reason};
3243 return (finish_reason => (defined($raw) && !ref($raw) && length($raw)
3244 33 ▶ ? ($FINISH_REASON{lc $raw} // 'other') : 'other'));
Branch: 1 branch
BranchTrueFalseTotal
defined $raw && !ref($raw) && length $raw ? : 1 32 33
Condition62%5/8
defined $raw and not ref $raw and length $raw
!ll&&!rl&&r
3201
defined $raw and not ref $raw
!ll&&!rl&&r
3201
$FINISH_REASON{lc $raw} // "other"
l!l
10
MC/DC33%1/3
defined $raw and not ref $raw and length $raw
defined $raw not ref $raw length $raw
MC/DC0%0/1
$FINISH_REASON{lc $raw} // "other"
$FINISH_REASON{lc $raw}
Truth table50%2/4
A and not(B) and C
A= defined $rawB= not ref $rawC= length $raw
ABCresult
0XX0
10X0
1100
1111
Truth table50%1/2
A
A= $FINISH_REASON{lc $raw}
Aresult
11
00
3245 }
3246 return (finish_reason => 'error')
3247 1062 ▶ if !$args->{ok} && (($args->{status_code} // 0) >= 400 || length($args->{error_type} // ''));
Branch: 1 branch
BranchTrueFalseTotal
if not $args->{"ok"} and ($args->{"status_code"} // 0) >= 400 || length($args->{"error_type"} // "") 171 891 1062
Condition90%9/10
not $args->{"ok"} and ($args->{"status_code"} // 0) >= 400 || length($args->{"error_type"} // "")
!ll&&!rl&&r
86526171
($args->{"status_code"} // 0) >= 400 or length($args->{"error_type"} // "")
l!l&&r!l&&!r
170126
$args->{"status_code"} // 0
l!l
1970
$args->{"error_type"} // ""
l!l
126
MC/DC33%1/3
not $args->{"ok"} and ($args->{"status_code"} // 0) >= 400 || length($args->{"error_type"} // "")
not $args->{"ok"} $args->{"status_code"} $args->{"error_type"}
Truth table50%2/4
not(A) and B or C
A= not $args->{"ok"}B= $args->{"status_code"}C= $args->{"error_type"}
ABCresult
0XX0
1000
11X1
1011
3248 891 my $raw = $args->{finish_reason};
3249 891 ▶ return () unless defined($raw) && !ref($raw) && length($raw);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw and not ref $raw and length $raw 378 513 891
Condition66%4/6
defined $raw and not ref $raw and length $raw
!ll&&!rl&&r
3780513
defined $raw and not ref $raw
!ll&&!rl&&r
3780513
MC/DC33%1/3
defined $raw and not ref $raw and length $raw
defined $raw not ref $raw length $raw
Truth table50%2/4
A and not(B) and C
A= defined $rawB= not ref $rawC= length $raw
ABCresult
0XX0
10X0
1100
1111
3250 513 ▶ return (finish_reason => ($FINISH_REASON{lc $raw} // 'other'));
Condition100%2/2
$FINISH_REASON{lc $raw} // "other"
l!l
5121
MC/DC100%1/1
$FINISH_REASON{lc $raw} // "other"
$FINISH_REASON{lc $raw}
Truth table100%2/2
A
A= $FINISH_REASON{lc $raw}
Aresult
11
00
3251 }
3252  
3253 # The finish reason of a non-streamed OpenAI answer, if it has one.
3254 605 ▶sub _payload_finish_reason {
Subroutine _payload_finish_reason: called CC=6 SCAR=18.0
3255 605 my ($payload) = @_;
3256 605 ▶ return undef unless ref($payload) eq 'HASH' && ref($payload->{choices}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $payload eq "HASH" and ref $payload->{"choices"} eq "ARRAY" 103 502 605
Condition100%3/3
ref $payload eq "HASH" and ref $payload->{"choices"} eq "ARRAY"
!ll&&!rl&&r
2974502
MC/DC100%2/2
ref $payload eq "HASH" and ref $payload->{"choices"} eq "ARRAY"
ref $payload eq "HASH" ref $payload->{"choices"} eq "ARRAY"
Truth table100%3/3
A and B
A= ref $payload eq "HASH"B= ref $payload->{"choices"} eq "ARRAY"
ABresult
0X0
100
111
3257 502 my $choice = $payload->{choices}[0];
3258 502 ▶ return undef unless ref($choice) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $choice eq "HASH" 0 502 502
3259 502 my $reason = $choice->{finish_reason};
3260 502 ▶ return (defined($reason) && !ref($reason)) ? $reason : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $reason && !ref($reason) ? : 401 101 502
Condition66%2/3
defined $reason and not ref $reason
!ll&&!rl&&r
1010401
MC/DC50%1/2
defined $reason and not ref $reason
defined $reason not ref $reason
Truth table66%2/3
A and not(B)
A= defined $reasonB= not ref $reason
ABresult
0X0
100
111
3261 }
3262  
3263 # The caller's correlation id (skeid k121): the header routing.correlation_header names, passed
3264 # through unchanged when it is 8 to 64 of [A-Za-z0-9._-]; anything else is not recorded.
3265 1092 ▶sub _correlation_field {
Subroutine _correlation_field: called CC=5 SCAR=16.1
3266 1092 my ($c) = @_;
3267 1092 my $header = $c->skeid->correlation_header;
3268 1092 ▶ return () unless defined($header) && length($header);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $header and length $header 1070 22 1092
Condition66%2/3
defined $header and length $header
!ll&&!rl&&r
1070022
MC/DC50%1/2
defined $header and length $header
defined $header length $header
Truth table66%2/3
A and B
A= defined $headerB= length $header
ABresult
0X0
100
111
3269 22 my $value = $c->req->headers->header($header);
3270 22 ▶ return () unless defined($value) && $value =~ /\A[A-Za-z0-9._-]{8,64}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and $value =~ /\A[A-Za-z0-9._-]{8,64}\z/ 6 16 22
Condition100%3/3
defined $value and $value =~ /\A[A-Za-z0-9._-]{8,64}\z/
!ll&&!rl&&r
5116
MC/DC100%2/2
defined $value and $value =~ /\A[A-Za-z0-9._-]{8,64}\z/
defined $value $value =~ /\A[A-Za-z0-9._-]{8,64}\z/
Truth table100%3/3
A and B
A= defined $valueB= $value =~ /\A[A-Za-z0-9._-]{8,64}\z/
ABresult
0X0
100
111
3271 16 return (correlation_id => $value);
3272 }
3273  
3274 1092 ▶sub _record_usage_event {
Subroutine _record_usage_event: called CC=40 SCAR=41.3
3275 1092 my ($c, $args) = @_;
3276 1092 ▶ $args ||= {};
Condition50%1/2
$args ||= {}
l!l
10920
MC/DC0%0/1
$args ||= {}
$args
Truth table50%1/2
A
A= $args
Aresult
11
00
3277 1092 ▶ my $metrics = ref($args->{metrics}) eq 'HASH' ? $args->{metrics} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $args->{'metrics'} eq 'HASH' ? : 1092 0 1092
3278 1092 ▶ my $usage = ref($metrics->{usage}) eq 'HASH' ? $metrics->{usage} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $metrics->{'usage'} eq 'HASH' ? : 0 1092 1092
3279 my $safe_metrics = {
3280 %$metrics,
3281 usage => {
3282 input => 0 + ($usage->{input} // $usage->{prompt_tokens} // 0),
3283 output => 0 + ($usage->{output} // $usage->{completion_tokens} // 0),
3284 total => 0 + ($usage->{total} // 0),
3285 # This reshaping drops prompt_tokens_details, so the cache count has to be carried across
3286 # it explicitly or record_usage never sees it. Both paths carry it as a flat
3287 # metrics->{cached_tokens}, from metrics.normalize or the raw payload (k27, skeid #41).
3288 1092 ▶ cached => (_cached_tokens($usage) || 0 + ($metrics->{cached_tokens} // 0)),
Condition52%9/17
($usage->{"input"} // $usage->{"prompt_tokens"}) // 0
l!l
01092
$usage->{"input"} // $usage->{"prompt_tokens"}
l!l&&r!l&&!r
001092
($usage->{"output"} // $usage->{"completion_tokens"}) // 0
l!l
01092
$usage->{"output"} // $usage->{"completion_tokens"}
l!l&&r!l&&!r
001092
$usage->{"total"} // 0
l!l
01092
_cached_tokens($usage) || 0 + ($metrics->{'cached_tokens'} // 0)
l!l&&r!l&&!r
0102990
$metrics->{"cached_tokens"} // 0
l!l
102990
MC/DC0%0/2
($usage->{"input"} // $usage->{"prompt_tokens"}) // 0
$usage->{"input"} $usage->{"prompt_tokens"}
MC/DC0%0/2
($usage->{"output"} // $usage->{"completion_tokens"}) // 0
$usage->{"output"} $usage->{"completion_tokens"}
MC/DC0%0/1
$usage->{"total"} // 0
$usage->{"total"}
MC/DC50%1/2
_cached_tokens($usage) || 0 + ($metrics->{'cached_tokens'} // 0)
_cached_tokens($usage) 0 + ($metrics->{'cached_tokens'} // 0)
MC/DC100%1/1
$metrics->{"cached_tokens"} // 0
$metrics->{"cached_tokens"}
Truth table33%1/3
A // B
A= $usage->{"input"}B= $usage->{"prompt_tokens"}
ABresult
1X1
011
000
Truth table33%1/3
A // B
A= $usage->{"output"}B= $usage->{"completion_tokens"}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $usage->{"total"}
Aresult
11
00
Truth table66%2/3
A || B
A= _cached_tokens($usage)B= 0 + ($metrics->{'cached_tokens'} // 0)
ABresult
1X1
011
000
Truth table100%2/2
A
A= $metrics->{"cached_tokens"}
Aresult
11
00
3289 },
3290 };
3291  
3292 1092 my $request_id = _request_id($c);
3293 1092 my $recorded = eval {
3294 $c->skeid->call_function('usage.record', {
3295 created_at => Langertha::Skeid::Protocol::iso8601_now(),
3296 request_id => $request_id,
3297 api_format => ($args->{api_format} // ''),
3298 requested_model => ($args->{requested_model} // $args->{model} // ''),
3299 endpoint => ($args->{endpoint} // ''),
3300 api_key_id => ($args->{api_key_id} // 'anonymous'),
3301 provider => ($args->{provider} // 'skeid'),
3302 engine => ($args->{engine} // ''),
3303 model => ($args->{model} // ''),
3304 node_id => ($args->{node_id} // ''),
3305 route_url => ($args->{route_url} // ''),
3306 status_code => 0 + ($args->{status_code} // 0),
3307 ok => ($args->{ok} ? 1 : 0),
3308 duration_ms => 0 + ($args->{duration_ms} // 0),
3309 error_type => ($args->{error_type} // ''),
3310 error_message => ($args->{error_message} // ''),
3311 # Streamed requests only; absent otherwise, so the event says "not measured" (skeid #36).
3312 (defined($args->{content_bytes}) ? (content_bytes => 0 + $args->{content_bytes}) : ()),
3313 # Audio routes only, and only when the node reported it (skeid k91, ADR 0021).
3314 (defined($args->{audio_seconds}) ? (audio_seconds => 0 + $args->{audio_seconds}) : ()),
3315 # The rerank route only, and only for a request the node answered (skeid k92).
3316 (defined($args->{documents}) ? (documents => 0 + $args->{documents}) : ()),
3317 # The documents routes, when the answer carried a page count (skeid k94, ADR 0028).
3318 (defined($args->{pages}) ? (pages => 0 + $args->{pages}) : ()),
3319 # The usage contract (skeid k121): how the answer ended, when its first token came (streams
3320 # only), and the caller's correlation id when the config names its header.
3321 _finish_reason_field($args),
3322 # Only a request the catch-all bent: the target it was routed under (skeid k129, ADR 0033).
3323 (defined($args->{routed_model}) ? (routed_model => $args->{routed_model}) : ()),
3324 1092 ▶ (defined($args->{ttft_ms}) ? (ttft_ms => 0 + $args->{ttft_ms}) : ()),
Branch: 7 branches
BranchTrueFalseTotal
$args->{'ok'} ? : 865 227 1092
defined $args->{'content_bytes'} ? : 246 846 1092
defined $args->{'audio_seconds'} ? : 32 1060 1092
defined $args->{'documents'} ? : 99 993 1092
defined $args->{'pages'} ? : 36 1056 1092
defined $args->{'routed_model'} ? : 23 1069 1092
defined $args->{'ttft_ms'} ? : 215 877 1092
Condition75%22/29
$args->{"api_format"} // ""
l!l
10920
($args->{"requested_model"} // $args->{"model"}) // ""
l!l
106329
$args->{"requested_model"} // $args->{"model"}
l!l&&r!l&&!r
1063029
$args->{"endpoint"} // ""
l!l
10920
$args->{"api_key_id"} // "anonymous"
l!l
10920
$args->{"provider"} // "skeid"
l!l
10920
$args->{"engine"} // ""
l!l
106131
$args->{"model"} // ""
l!l
106329
$args->{"node_id"} // ""
l!l
106131
$args->{"route_url"} // ""
l!l
10902
$args->{"status_code"} // 0
l!l
10920
$args->{"duration_ms"} // 0
l!l
10920
$args->{"error_type"} // ""
l!l
251841
$args->{"error_message"} // ""
l!l
251841
MC/DC0%0/1
$args->{"api_format"} // ""
$args->{"api_format"}
MC/DC50%1/2
($args->{"requested_model"} // $args->{"model"}) // ""
$args->{"requested_model"} $args->{"model"}
MC/DC0%0/1
$args->{"endpoint"} // ""
$args->{"endpoint"}
MC/DC0%0/1
$args->{"api_key_id"} // "anonymous"
$args->{"api_key_id"}
MC/DC0%0/1
$args->{"provider"} // "skeid"
$args->{"provider"}
MC/DC100%1/1
$args->{"engine"} // ""
$args->{"engine"}
MC/DC100%1/1
$args->{"model"} // ""
$args->{"model"}
MC/DC100%1/1
$args->{"node_id"} // ""
$args->{"node_id"}
MC/DC100%1/1
$args->{"route_url"} // ""
$args->{"route_url"}
MC/DC0%0/1
$args->{"status_code"} // 0
$args->{"status_code"}
MC/DC0%0/1
$args->{"duration_ms"} // 0
$args->{"duration_ms"}
MC/DC100%1/1
$args->{"error_type"} // ""
$args->{"error_type"}
MC/DC100%1/1
$args->{"error_message"} // ""
$args->{"error_message"}
Truth table50%1/2
A
A= $args->{"api_format"}
Aresult
11
00
Truth table66%2/3
A // B
A= $args->{"requested_model"}B= $args->{"model"}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $args->{"endpoint"}
Aresult
11
00
Truth table50%1/2
A
A= $args->{"api_key_id"}
Aresult
11
00
Truth table50%1/2
A
A= $args->{"provider"}
Aresult
11
00
Truth table100%2/2
A
A= $args->{"engine"}
Aresult
11
00
Truth table100%2/2
A
A= $args->{"model"}
Aresult
11
00
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 table50%1/2
A
A= $args->{"status_code"}
Aresult
11
00
Truth table50%1/2
A
A= $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
3325 _correlation_field($c),
3326 metrics => $safe_metrics,
3327 });
3328 };
3329 1092 my $err;
3330 1092 ▶ if ($@) {
Branch: 2 branches
BranchTrueFalseTotal
if ($@) { } 0 1092 1092
elsif (ref $recorded eq 'HASH' and not $recorded->{'ok'} and $recorded->{'enabled'} // 1) { } 3 2152 2155
3331 0 $err = "$@";
3332 0 $recorded = { ok => 0, error => $err };
3333 ▶ } elsif (ref($recorded) eq 'HASH' && !$recorded->{ok} && ($recorded->{enabled} // 1)) {
Condition87%7/8
ref $recorded eq "HASH" and not $recorded->{"ok"} and $recorded->{"enabled"} // 1
!ll&&!rl&&r
1063263
ref $recorded eq "HASH" and not $recorded->{"ok"}
!ll&&!rl&&r
0106329
$recorded->{"enabled"} // 1
l!l
263
MC/DC66%2/3
ref $recorded eq "HASH" and not $recorded->{"ok"} and $recorded->{"enabled"} // 1
ref $recorded eq "HASH" not $recorded->{"ok"} $recorded->{"enabled"}
Truth table75%3/4
A and not(B) and C
A= ref $recorded eq "HASH"B= not $recorded->{"ok"}C= $recorded->{"enabled"}
ABCresult
0XX0
10X0
1100
1111
3334 # A store reports a failed write in its answer (the JsonLog contract); no sink at all
3335 # answers enabled => 0 and has nothing to lose.
3336 3 ▶ $err = $recorded->{error} // 'unknown error';
Condition50%1/2
$recorded->{"error"} // "unknown error"
l!l
30
MC/DC0%0/1
$recorded->{"error"} // "unknown error"
$recorded->{"error"}
Truth table50%1/2
A
A= $recorded->{"error"}
Aresult
11
00
3337 }
3338 1092 ▶ if (defined $err) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $err) 3 1089 1092
3339 _log_lost_usage_event($c->app, $c->skeid, {
3340 request_id => $request_id,
3341 api_key_id => ($args->{api_key_id} // 'anonymous'),
3342 model => $args->{model},
3343 status_code => $args->{status_code},
3344 3 ▶ }, $err);
Condition50%1/2
$args->{"api_key_id"} // "anonymous"
l!l
30
MC/DC0%0/1
$args->{"api_key_id"} // "anonymous"
$args->{"api_key_id"}
Truth table50%1/2
A
A= $args->{"api_key_id"}
Aresult
11
00
3345 }
3346  
3347 1092 return $recorded;
3348 }
3349  
3350 # The event is the billing unit (ADR 0004) and it is gone: say so at a level production keeps,
3351 # with what an operator needs to reconcile it by hand. The request id and the key id, never the
3352 # key -- the key id is a digest (ADR 0016), the key is a secret (ADR 0003). One line for both
3353 # ways an event is lost: a write that failed while the request waited, and a queued one a
3354 # write-behind flush could not write later (skeid k78).
3355 4 ▶sub _log_lost_usage_event {
Subroutine _log_lost_usage_event: called CC=6 SCAR=19.9
3356 4 my ($app, $skeid, $event, $err) = @_;
3357 4 ▶ $err //= 'unknown error';
Condition50%1/2
$err //= "unknown error"
l!l
40
MC/DC0%0/1
$err //= "unknown error"
$err
Truth table50%1/2
A
A= $err
Aresult
11
00
3358 4 $err =~ s/\s+$//;
3359 $app->log->error('usage event lost: request_id=' . ($event->{request_id} // '')
3360 . ' store=' . _usage_sink_name($skeid)
3361 . ' api_key_id=' . ($event->{api_key_id} // 'anonymous')
3362 . ' model=' . ($event->{model} // '')
3363 4 ▶ . ' status=' . ($event->{status_code} // 0)
Condition50%4/8
$event->{"request_id"} // ""
l!l
40
$event->{"api_key_id"} // "anonymous"
l!l
40
$event->{"model"} // ""
l!l
40
$event->{"status_code"} // 0
l!l
40
MC/DC0%0/1
$event->{"request_id"} // ""
$event->{"request_id"}
MC/DC0%0/1
$event->{"api_key_id"} // "anonymous"
$event->{"api_key_id"}
MC/DC0%0/1
$event->{"model"} // ""
$event->{"model"}
MC/DC0%0/1
$event->{"status_code"} // 0
$event->{"status_code"}
Truth table50%1/2
A
A= $event->{"request_id"}
Aresult
11
00
Truth table50%1/2
A
A= $event->{"api_key_id"}
Aresult
11
00
Truth table50%1/2
A
A= $event->{"model"}
Aresult
11
00
Truth table50%1/2
A
A= $event->{"status_code"}
Aresult
11
00
3364 . ': ' . $err);
3365 4 return;
3366 }
3367  
3368 # Which sink a lost usage event was meant for, for the log line: the store's backend name, or
3369 # how the embedding application took the event over. Never the DSN or path, which may carry
3370 # credentials.
3371 4 ▶sub _usage_sink_name {
Subroutine _usage_sink_name: called CC=5 SCAR=17.5
3372 4 my ($skeid) = @_;
3373 4 ▶ return 'store_usage_event' if $skeid->has_store_usage_event;
Branch: 1 branch
BranchTrueFalseTotal
if $skeid->has_store_usage_event 1 3 4
3374 3 my $cfg = $skeid->usage_store;
3375 3 ▶ return (ref($cfg) eq 'HASH' && length($cfg->{backend} // '')) ? $cfg->{backend} : 'custom';
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg eq 'HASH' && length($cfg->{'backend'} // '') ? : 3 0 3
Condition40%2/5
ref $cfg eq "HASH" and length($cfg->{"backend"} // "")
!ll&&!rl&&r
003
$cfg->{"backend"} // ""
l!l
30
MC/DC0%0/2
ref $cfg eq "HASH" and length($cfg->{"backend"} // "")
ref $cfg eq "HASH" $cfg->{"backend"}
Truth table33%1/3
A and B
A= ref $cfg eq "HASH"B= $cfg->{"backend"}
ABresult
0X0
100
111
3376 }
3377  
3378 # The prompt-cache read count off a raw OpenAI-shaped upstream usage hash (k27). OpenAI nests it
3379 # under prompt_tokens_details.cached_tokens; some OpenAI-compatible servers expose a flat
3380 # cached_tokens, an Anthropic-spelled block cache_read_input_tokens, and a caller of usage.record may pass it as `cached`. Missing -> 0, the
3381 # same fault-tolerance the other token reads here have. This reads a count off a response Skeid
3382 # already holds -- every upstream answers in the OpenAI dialect (ADR 0001) -- it does not
3383 # translate a client format. Both paths prefer the count metrics.normalize reads through
3384 # Langertha::Usage and prices (skeid #28, #41); this is the fallback on Langertha 0.503.
3385 1716 ▶sub _cached_tokens {
Subroutine _cached_tokens: called CC=7 SCAR=19.5
3386 1716 my ($usage) = @_;
3387 1716 ▶ return 0 unless ref($usage) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $usage eq "HASH" 31 1685 1716
3388 1685 my $details = $usage->{prompt_tokens_details};
3389 return 0 + ($usage->{cached}
3390 // $usage->{cached_tokens}
3391 // (ref($details) eq 'HASH' ? $details->{cached_tokens} : undef)
3392 // $usage->{cache_read_input_tokens}
3393 1685 ▶ // 0);
Branch: 1 branch
BranchTrueFalseTotal
ref $details eq 'HASH' ? : 1 1682 1683
Condition90%10/11
((($usage->{"cached"} // $usage->{"cached_tokens"}) // (ref $details eq "HASH" ? $details->{"cached_tokens"} : undef)) // $usage->{"cache_read_input_tokens"}) // 0
l!l
31682
(($usage->{"cached"} // $usage->{"cached_tokens"}) // (ref $details eq "HASH" ? $details->{"cached_tokens"} : undef)) // $usage->{"cache_read_input_tokens"}
l!l&&r!l&&!r
301682
($usage->{"cached"} // $usage->{"cached_tokens"}) // (ref $details eq "HASH" ? $details->{"cached_tokens"} : undef)
l!l&&r!l&&!r
211682
$usage->{"cached"} // $usage->{"cached_tokens"}
l!l&&r!l&&!r
111683
MC/DC75%3/4
((($usage->{"cached"} // $usage->{"cached_tokens"}) // (ref $details eq "HASH" ? $details->{"cached_tokens"} : undef)) // $usage->{"cache_read_input_tokens"}) // 0
$usage->{"cached"} $usage->{"cached_tokens"} (ref $details eq "HASH" ? $details->{"cached_tokens"} : undef) $usage->{"cache_read_input_tokens"}
Truth table80%4/5
A // B // C // D
A= $usage->{"cached"}B= $usage->{"cached_tokens"}C= (ref $details eq "HASH" ? $details->{"cached_tokens"} : undef)D= $usage->{"cache_read_input_tokens"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
3394 }
3395  
3396 # Prices an upstream answer: its usage block goes through metrics.normalize (Langertha::Usage +
3397 # Langertha::Pricing), the one pricing path for every face, streamed or not (skeid #28, #41).
3398 # $payload is the decoded upstream body, or for a stream a body holding only the usage block
3399 # the stream carried -- the same usage, so the same cost.
3400 720 ▶sub _priced_metrics {
Subroutine _priced_metrics: called CC=12 SCAR=27.5
3401 720 my ($c, $meta, $body, $duration_ms, $payload, $tool_calls) = @_;
3402 720 my $metrics = eval {
3403 $c->skeid->call_function('metrics.normalize', {
3404 provider => ($meta->{provider} || 'skeid'),
3405 engine => ($meta->{engine} || 'openaibase'),
3406 model => ($meta->{model} || ($body->{model} // '')),
3407 720 ▶ route => ($meta->{endpoint} || ''),
Condition46%6/13
$meta->{'provider'} || 'skeid'
l!l
7200
$meta->{'engine'} || 'openaibase'
l!l
7200
$meta->{'model'} || ($body->{'model'} // '')
l!l&&r!l&&!r
72000
$body->{"model"} // ""
l!l
00
$meta->{'endpoint'} || ''
l!l
7200
$tool_calls || []
l!l
502218
MC/DC0%0/1
$meta->{'provider'} || 'skeid'
$meta->{'provider'}
MC/DC0%0/1
$meta->{'engine'} || 'openaibase'
$meta->{'engine'}
MC/DC0%0/2
$meta->{'model'} || ($body->{'model'} // '')
$meta->{'model'} $body->{"model"}
MC/DC0%0/1
$meta->{'endpoint'} || ''
$meta->{'endpoint'}
MC/DC100%1/1
$tool_calls || []
$tool_calls
Truth table50%1/2
A
A= $meta->{'provider'}
Aresult
11
00
Truth table50%1/2
A
A= $meta->{'engine'}
Aresult
11
00
Truth table33%1/3
A || B
A= $meta->{'model'}B= $body->{"model"}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $meta->{'endpoint'}
Aresult
11
00
Truth table100%2/2
A
A= $tool_calls
Aresult
11
00
3408 duration_ms => $duration_ms,
3409 response => $payload,
3410 tool_calls => ($tool_calls || []),
3411 });
3412 };
3413 720 ▶ $metrics = {} unless ref($metrics) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $metrics eq "HASH" 0 720 720
3414 # metrics.normalize reports the prompt-cache counts off Langertha::Usage, from every wire
3415 # spelling it knows (skeid #28). Langertha 0.503's Usage has no such counts, so there they are
3416 # pulled straight off the raw upstream usage and carried flat, the way input/output survive
3417 # as metrics->{*_tokens} (k27).
3418 720 ▶ if (!defined $metrics->{cached_tokens}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $metrics->{"cached_tokens"}) 618 102 720
3419 618 my $cached = _cached_tokens($payload->{usage});
3420 618 ▶ $metrics->{cached_tokens} = $cached if $cached;
Branch: 1 branch
BranchTrueFalseTotal
if $cached 0 618 618
3421 }
3422 720 ▶ if (!defined $metrics->{cache_write_tokens}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $metrics->{"cache_write_tokens"}) 624 96 720
3423 624 my $written = _cache_write_tokens($payload->{usage});
3424 624 ▶ $metrics->{cache_write_tokens} = $written if $written;
Branch: 1 branch
BranchTrueFalseTotal
if $written 0 624 624
3425 }
3426 720 return $metrics;
3427 }
3428  
3429 # A stream's metrics: its verbatim usage priced exactly as a non-streamed body carrying it would
3430 # be. A stream that carried no usage has nothing to price -- no token count or cost is invented.
3431 247 ▶sub _stream_metrics {
Subroutine _stream_metrics: called CC=2 SCAR=6.9
3432 247 my ($c, $meta, $body, $duration_ms, $usage) = @_;
3433 247 ▶ return {} unless ref($usage) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $usage eq "HASH" 79 168 247
3434 168 return _priced_metrics($c, $meta, $body, $duration_ms, { usage => $usage });
3435 }
3436  
3437 # Folds one stream frame's usage block into what the stream reported so far, key by key, a later
3438 # frame's value replacing an earlier one (nested blocks such as prompt_tokens_details likewise).
3439 # Usage counts on a stream are running totals, never increments: OpenAI's final frame carries
3440 # the whole request, a server that reports on every chunk repeats the growing total, and a wire
3441 # that splits the block (input on the first frame, output on the last) is completed rather
3442 # than lost. Summing frames would bill the same tokens twice.
3443 248 ▶sub _merge_usage {
Subroutine _merge_usage: called CC=6 SCAR=17.9
3444 248 my ($into, $frame) = @_;
3445 248 ▶ my %merged = ref($into) eq 'HASH' ? %$into : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $into eq 'HASH' ? : 86 162 248
3446 248 for my $key (keys %$frame) {
3447 764 my $value = $frame->{$key};
3448 764 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 764 764
3449 $merged{$key} = (ref($value) eq 'HASH' && ref($merged{$key}) eq 'HASH')
3450 764 ▶ ? _merge_usage($merged{$key}, $value)
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'HASH' && ref $merged{$key} eq 'HASH' ? : 36 728 764
Condition100%3/3
ref $value eq "HASH" and ref $merged{$key} eq "HASH"
!ll&&!rl&&r
6854336
MC/DC100%2/2
ref $value eq "HASH" and ref $merged{$key} eq "HASH"
ref $value eq "HASH" ref $merged{$key} eq "HASH"
Truth table100%3/3
A and B
A= ref $value eq "HASH"B= ref $merged{$key} eq "HASH"
ABresult
0X0
100
111
3451 : $value;
3452 }
3453 248 return \%merged;
3454 }
3455  
3456 # The prompt-cache write count off a raw upstream usage hash, for a Langertha that cannot read it
3457 # itself (0.503): OpenAI Chat nests it under prompt_tokens_details.cache_write_tokens, an
3458 # Anthropic-shaped block carries cache_creation_input_tokens. Missing -> 0. A count, never priced
3459 # here -- pricing is Langertha::Pricing's (skeid #41).
3460 624 ▶sub _cache_write_tokens {
Subroutine _cache_write_tokens: called CC=6 SCAR=19.6
3461 624 my ($usage) = @_;
3462 624 ▶ return 0 unless ref($usage) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $usage eq "HASH" 30 594 624
3463 594 my $details = $usage->{prompt_tokens_details};
3464 return 0 + ((ref($details) eq 'HASH' ? $details->{cache_write_tokens} : undef)
3465 // $usage->{cache_write_tokens}
3466 // $usage->{cache_creation_input_tokens}
3467 594 ▶ // 0);
Branch: 1 branch
BranchTrueFalseTotal
ref $details eq 'HASH' ? : 6 588 594
Condition37%3/8
(((ref $details eq "HASH" ? $details->{"cache_write_tokens"} : undef) // $usage->{"cache_write_tokens"}) // $usage->{"cache_creation_input_tokens"}) // 0
l!l
0594
((ref $details eq "HASH" ? $details->{"cache_write_tokens"} : undef) // $usage->{"cache_write_tokens"}) // $usage->{"cache_creation_input_tokens"}
l!l&&r!l&&!r
00594
(ref $details eq "HASH" ? $details->{"cache_write_tokens"} : undef) // $usage->{"cache_write_tokens"}
l!l&&r!l&&!r
00594
MC/DC0%0/3
(((ref $details eq "HASH" ? $details->{"cache_write_tokens"} : undef) // $usage->{"cache_write_tokens"}) // $usage->{"cache_creation_input_tokens"}) // 0
(ref $details eq "HASH" ? $details->{"cache_write_tokens"} : undef) $usage->{"cache_write_tokens"} $usage->{"cache_creation_input_tokens"}
Truth table25%1/4
A // B // C
A= (ref $details eq "HASH" ? $details->{"cache_write_tokens"} : undef)B= $usage->{"cache_write_tokens"}C= $usage->{"cache_creation_input_tokens"}
ABCresult
1XX1
01X1
0011
0000
3468 }
3469  
3470 # The model a tier asks its nodes for. Falls back to what the client requested, which is what
3471 # makes an aliasless deployment behave exactly as it did before tiers existed.
3472 1010 ▶sub _served_model {
Subroutine _served_model: called CC=4 SCAR=15.6
3473 1010 my ($tier, $requested) = @_;
3474 1010 ▶ return $requested unless ref($tier) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tier eq "HASH" 0 1010 1010
3475 1010 my $model = $tier->{model};
3476 1010 ▶ return (defined($model) && length($model)) ? $model : $requested;
Branch: 1 branch
BranchTrueFalseTotal
defined $model && length $model ? : 1010 0 1010
Condition33%1/3
defined $model and length $model
!ll&&!rl&&r
001010
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
3477 }
3478  
3479 1036 ▶sub _endpoint_url_for_node {
Subroutine _endpoint_url_for_node: called CC=6 SCAR=19.1
3480 1036 my ($base, $path) = @_;
3481 1036 ▶ $base //= '';
Condition50%1/2
$base //= ""
l!l
10360
MC/DC0%0/1
$base //= ""
$base
Truth table50%1/2
A
A= $base
Aresult
11
00
3482 1036 ▶ $path //= '';
Condition50%1/2
$path //= ""
l!l
10360
MC/DC0%0/1
$path //= ""
$path
Truth table50%1/2
A
A= $path
Aresult
11
00
3483 1036 $base =~ s{/\z}{};
3484  
3485 1036 ▶ return $base . $path if $base =~ m{/v1\z} && $path =~ m{^/};
Branch: 1 branch
BranchTrueFalseTotal
if $base =~ m[/v1\z] and $path =~ m[^/] 967 69 1036
Condition66%2/3
$base =~ m[/v1\z] and $path =~ m[^/]
!ll&&!rl&&r
690967
MC/DC50%1/2
$base =~ m[/v1\z] and $path =~ m[^/]
$base =~ m[/v1\z] $path =~ m[^/]
Truth table66%2/3
A and B
A= $base =~ m[/v1\z]B= $path =~ m[^/]
ABresult
0X0
100
111
3486 69 ▶ return $base . '/v1' . $path if $path =~ m{^/};
Branch: 1 branch
BranchTrueFalseTotal
if $path =~ m[^/] 69 0 69
3487 0 return $base . '/v1/' . $path;
3488 }
3489  
3490 # The URL of a route a node serves at its server root rather than below /v1 (a TEI node's
3491 # /rerank): a node URL is a base, and one written with a trailing /v1 names the same server.
3492 24 ▶sub _root_url_for_node {
Subroutine _root_url_for_node: called CC=2 SCAR=7.0
3493 24 my ($base, $path) = @_;
3494 24 ▶ $base //= '';
Condition50%1/2
$base //= ""
l!l
240
MC/DC0%0/1
$base //= ""
$base
Truth table50%1/2
A
A= $base
Aresult
11
00
3495 24 $base =~ s{/\z}{};
3496 24 $base =~ s{/v1\z}{};
3497 24 return $base . $path;
3498 }
3499  
3500 1324 ▶sub _duration_ms {
Subroutine _duration_ms: called CC=1 SCAR=0.0
3501 1324 my ($started) = @_;
3502 1324 return int((time - $started) * 1000);
3503 }
3504  
3505  
3506 99 1;
3507  
3508 __END__
« lib/Langertha/Skeid/Protocol/Ollama.pm ↑ Summary lib/Langertha/Skeid/Registry.pm »