blib/lib/Langertha/Skeid/Proxy.pm

filter: Statementstmt 96.9% 853 / 880 Branchbran 83.4% 337 / 404 Conditioncond 59.7% 269 / 450 MC/DCmcdc 32.5% 80 / 246 Subroutinesub 95.4% 105 / 110 Podpod 100% 1 / 1 totaltotal 78.6% 1645 / 2091 CC 394 SCAR 28.8
CC
394
Cov
84%
__ANON__
90.0
_record_usage_event
80.4
__ANON__
36.6
CRAP 17.8
« blib/lib/Langertha/Skeid/CapacityProbe/Registry.pm ↑ Summary blib/lib/Langertha/Skeid/Registry.pm »
1 package Langertha::Skeid::Proxy;
2 47 our $VERSION = '0.003';
3 # ABSTRACT: Multi-format LLM proxy (OpenAI, Anthropic, Ollama) powered by Langertha::Skeid routing
4 47 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 47 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 47 ▶use Mojolicious;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 47 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 47 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 47 ▶use JSON::MaybeXS qw(decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 47 ▶use Scalar::Util qw(blessed weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 47 ▶use Langertha::Skeid;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 47 ▶use Langertha::Skeid::CapacityProbe;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 47 ▶use Langertha::Skeid::Registry;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 47 ▶use Langertha::Skeid::Secret;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 47 ▶use Langertha::Skeid::Proxy::RelayContent;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 47 ▶use Langertha::Skeid::Protocol;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 47 ▶use Langertha::Skeid::Protocol::Anthropic;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 47 ▶use Langertha::Skeid::Protocol::Anthropic::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 47 ▶use Langertha::Skeid::Protocol::Ollama;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 47 ▶use Langertha::Skeid::Protocol::Ollama::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 47 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23  
24 324 ▶sub build_app {
Subroutine build_app: called CC=19 SCAR=33.2
Pod documented
25 324 my ($class, %opts) = @_;
26  
27 # Auto-detect OpenBao KeyBroker if OPENBAO_ROLE_ID is set
28 324 ▶ my @skeid_opts = ($opts{config_file} ? (config_file => $opts{config_file}) : ());
Branch: 1 branch
BranchTrueFalseTotal
$opts{'config_file'} ? : 1 323 324
29 324 ▶ if ($ENV{OPENBAO_ROLE_ID} && $ENV{OPENBAO_SECRET_ID}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"OPENBAO_ROLE_ID"} and $ENV{"OPENBAO_SECRET_ID"}) 0 324 324
Condition33%1/3
$ENV{"OPENBAO_ROLE_ID"} and $ENV{"OPENBAO_SECRET_ID"}
!ll&&!rl&&r
32400
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
30 0 eval {
31 0 require Langertha::Skeid::KeyBroker::OpenBao;
32 push @skeid_opts, key_broker => Langertha::Skeid::KeyBroker::OpenBao->new(
33 addr => $ENV{OPENBAO_ADDR} // 'http://127.0.0.1:8200',
34 role_id => $ENV{OPENBAO_ROLE_ID},
35 secret_id => $ENV{OPENBAO_SECRET_ID},
36 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
37 };
38 0 ▶ warn "Failed to initialize OpenBao KeyBroker: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
39 }
40  
41 # The explicit admin API key goes into new(), so it is in force for the first config already
42 # (a registry block checks for it); an existing Skeid gets it set (skeid k64).
43 push @skeid_opts, admin_api_key => $opts{admin_api_key}
44 324 ▶ 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"} 4 320 324
Condition66%2/3
defined $opts{"admin_api_key"} and length $opts{"admin_api_key"}
!ll&&!rl&&r
32004
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
45 324 ▶ my $skeid = $opts{skeid} || Langertha::Skeid->new(@skeid_opts);
Condition66%2/3
$opts{'skeid'} || 'Langertha::Skeid'->new(@skeid_opts)
l!l&&r!l&&!r
32310
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
46 324 ▶ $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"} 4 320 324
47 # How many processes share these nodes. Set before anything reads max_conns or starts a
48 # timer, since both are divided by it (ADR 0010).
49 324 ▶ if (defined $opts{worker_count} && $opts{worker_count} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"worker_count"} and $opts{"worker_count"} > 0) 0 324 324
Condition33%1/3
defined $opts{"worker_count"} and $opts{"worker_count"} > 0
!ll&&!rl&&r
32400
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
50 0 $skeid->worker_count(0 + $opts{worker_count});
51 }
52  
53 # Renew the vault token on a timer rather than when a request discovers it expired. A request
54 # that has to renew first pays the round-trip in its own latency, and it is the request least
55 # able to afford it -- the first one after a quiet period.
56 324 ▶ 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")) 0 324 324
Condition66%2/3
$skeid->has_key_broker and $skeid->key_broker->can("start_renewal")
!ll&&!rl&&r
259650
MC/DC0%0/2
$skeid->has_key_broker and $skeid->key_broker->can("start_renewal")
$skeid->has_key_broker $skeid->key_broker->can("start_renewal")
Truth table66%2/3
A and B
A= $skeid->has_key_brokerB= $skeid->key_broker->can("start_renewal")
ABresult
0X0
100
111
57 0 $skeid->key_broker->start_renewal;
58 }
59  
60 # Capacity probes (ADR 0009). Held by the app, because a probe that goes out of scope stops
61 # polling. Nodes with no capacity block get none, which is plain inflight admission.
62 324 my $probes = Langertha::Skeid::CapacityProbe->start_for_skeid($skeid);
63 324 my $probe_key = $skeid->_probe_inventory_key;
64  
65 324 my $app = Mojolicious->new;
66 324 $app->secrets(['skeid-proxy']);
67  
68 # A write-behind usage store (usage_store.flush_interval_ms) writes after the request was
69 # answered, so its failures cannot come back through _record_usage_event; they come here and
70 # get the same log line (skeid k78). Weak: the app holds the skeid, the skeid holds this.
71 324 weaken(my $weak_app = $app);
72 1 ▶ $skeid->on_usage_lost(sub {
Subroutine __ANON__: called CC=4 SCAR=22.5
73 1 my ($skeid, $event, $err) = @_;
74 1 ▶ return _log_lost_usage_event($weak_app, $skeid, $event, $err) if $weak_app;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_app 1 0 1
75 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
76 . ($err // 'unknown error') . "\n";
77 0 return;
78 324 });
79 324 $app->ua->connect_timeout(10);
80 # One number for how long an upstream may take and how long it may be silent: a model that
81 # thinks sends nothing until its first token, and Mojo::UserAgent closes a connection that
82 # was silent for 40s whatever the request timeout allows. The client's side follows the same
83 # number per request, see _extend_client_timeout.
84 my $upstream_timeout
85 = (defined($ENV{SKEID_UPSTREAM_TIMEOUT}) && $ENV{SKEID_UPSTREAM_TIMEOUT} =~ /^\d+$/
86 && $ENV{SKEID_UPSTREAM_TIMEOUT} > 0)
87 ? 0 + $ENV{SKEID_UPSTREAM_TIMEOUT}
88 324 ▶ : 300;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_UPSTREAM_TIMEOUT'} && $ENV{'SKEID_UPSTREAM_TIMEOUT'} =~ /^\d+$/ && $ENV{'SKEID_UPSTREAM_TIMEOUT'} > 0 ? : 1 323 324
Condition100%6/6
defined $ENV{"SKEID_UPSTREAM_TIMEOUT"} and $ENV{"SKEID_UPSTREAM_TIMEOUT"} =~ /^\d+$/ and $ENV{"SKEID_UPSTREAM_TIMEOUT"} > 0
!ll&&!rl&&r
32211
defined $ENV{"SKEID_UPSTREAM_TIMEOUT"} and $ENV{"SKEID_UPSTREAM_TIMEOUT"} =~ /^\d+$/
!ll&&!rl&&r
31842
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
89 324 $app->ua->request_timeout($upstream_timeout);
90 324 $app->ua->inactivity_timeout($upstream_timeout);
91 # Mojo::UserAgent pools 5 upstream connections by default. A proxy serving more concurrent
92 # requests than that reconnects for the surplus on every request, which shows up as latency
93 # that grows with concurrency for no visible reason. Sized for the concurrency a single
94 # Skeid process can actually sustain, not for the number of nodes.
95 $app->ua->max_connections(
96 (defined($ENV{SKEID_UPSTREAM_POOL}) && $ENV{SKEID_UPSTREAM_POOL} =~ /^\d+$/)
97 ? 0 + $ENV{SKEID_UPSTREAM_POOL}
98 324 ▶ : 100
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_UPSTREAM_POOL'} && $ENV{'SKEID_UPSTREAM_POOL'} =~ /^\d+$/ ? : 0 324 324
Condition33%1/3
defined $ENV{"SKEID_UPSTREAM_POOL"} and $ENV{"SKEID_UPSTREAM_POOL"} =~ /^\d+$/
!ll&&!rl&&r
32400
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
99 );
100 324 ▶ $app->helper(skeid => sub { $skeid });
Subroutine __ANON__: called CC=1 SCAR=0.0
101  
102 # A config reload replaces the whole inventory, so probes have to follow it or they keep
103 # polling for nodes that are gone and never start for new ones. They follow the probe key,
104 # not the inventory generation: a health flip moves the generation but not what a probe
105 # polls, and a restart makes every probe forget its own reading (skeid #40) -- readings from
106 # other sources, such as a rate-limit backoff, survive it. The key is recomputed only when the
107 # generation has moved, so an unchanged inventory costs an integer compare per request.
108 863 ▶ $app->hook(before_dispatch => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
109 863 my $key = $skeid->_probe_inventory_key;
110 863 ▶ return if $key eq $probe_key;
Branch: 1 branch
BranchTrueFalseTotal
if $key eq $probe_key 858 5 863
111 5 $probe_key = $key;
112 5 $_->stop for values %$probes;
113 5 $probes = Langertha::Skeid::CapacityProbe->start_for_skeid($skeid);
114 324 });
115  
116 # The request's id is fixed here, before anything can fail or hang up: the client gets it back
117 # as x-request-id whatever the answer turns out to be, and the usage event and the lost-event
118 # log line carry the same one. It lives in the stash because a request whose client is gone
119 # has no transaction to read it from any more.
120 863 ▶ $app->hook(before_dispatch => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
121 863 my ($c) = @_;
122 863 my $id = _request_id($c);
123 863 $c->stash('skeid.request_id' => $id);
124 863 $c->res->headers->header('x-request-id' => $id);
125 324 });
126  
127 324 my $r = $app->routes;
128  
129 # Still 'ok' while a config reload is failing: the proxy serves under the config it kept, so
130 # it is not unhealthy, and a probe that restarted it would lose that config. The reload
131 # state is shown without its message, which can name customers; that is on /skeid/config.
132 37 ▶ $r->get('/health' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
133 37 my ($c) = @_;
134 37 my $reload = $c->skeid->reload_status;
135 37 delete $reload->{error};
136 37 $c->render(json => { status => 'ok', proxy => 'skeid', config_reload => $reload });
137 324 });
138  
139 # Provider manifest (skeid #29, ADR 0015): per customer key, never the whole catalog.
140 24 ▶ $r->get('/.well-known/langertha.json' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
141 24 my ($c) = @_;
142 24 _handle_manifest($c);
143 324 });
144  
145 # OpenAI format
146 5 ▶ $r->get('/v1/models' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
147 5 my ($c) = @_;
148 my @data = map {
149 +{
150 id => $_->{model},
151 9 object => 'model',
152 created => int(time),
153 owned_by => 'skeid',
154 }
155 5 } @{$c->skeid->list_models(api_key_id => _request_api_key_id($c))};
156 5 $c->render(json => { object => 'list', data => \@data });
157 324 });
158  
159 172 ▶ $r->post('/v1/chat/completions' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
160 172 my ($c) = @_;
161 172 _handle_openai_chat($c);
162 324 });
163  
164 17 ▶ $r->post('/v1/embeddings' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
165 17 my ($c) = @_;
166 17 _handle_openai_embeddings($c);
167 324 });
168  
169 # Anthropic format
170 126 ▶ $r->post('/v1/messages' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
171 126 my ($c) = @_;
172 # Every error this request produces, wherever it is rendered, has to be Anthropic-shaped
173 # (core karr #224). _render_error reads this.
174 126 $c->stash('skeid.error_format' => 'anthropic');
175 126 _handle_anthropic_messages($c);
176 324 });
177  
178 # Ollama format. Every error on these routes has to be Ollama-shaped, {"error": "<string>"}:
179 # an Ollama client decodes the error as a string and fails on the OpenAI object (skeid #47).
180 # _render_error reads this.
181 221 ▶ my $ollama = $r->under('/api' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
182 221 my ($c) = @_;
183 221 $c->stash('skeid.error_format' => 'ollama');
184 221 return 1;
185 324 });
186  
187 117 ▶ $ollama->post('/chat' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
188 117 my ($c) = @_;
189 117 _handle_ollama($c, 'chat');
190 324 });
191  
192 95 ▶ $ollama->post('/generate' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
193 95 my ($c) = @_;
194 95 _handle_ollama($c, 'generate');
195 324 });
196  
197 7 ▶ $ollama->get('/tags' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
198 7 my ($c) = @_;
199 7 $c->render(json => Langertha::Skeid::Protocol::Ollama->tags_from_models(
200 $c->skeid->list_models(api_key_id => _request_api_key_id($c))));
201 324 });
202  
203 2 ▶ $ollama->get('/ps' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
204 2 my ($c) = @_;
205 2 $c->render(json => { models => [] });
206 324 });
207  
208 # Skeid-to-Skeid registry (skeid #18, ADR 0017): a fronting tier's CapacityProbe::Registry
209 # pulls this. 404 unless registry.enabled, and never unsigned. No store may keep it: a cached
210 # snapshot is a stale one. It is registered before the /skeid admin block so it is not behind
211 # _authorize_admin: it also takes the registry read key (skeid #49), which that block must
212 # never accept -- the read key opens this one route and nothing else.
213 24 ▶ $r->get('/skeid/registry/snapshot' => sub {
Subroutine __ANON__: called CC=7 SCAR=19.7
214 24 my ($c) = @_;
215 24 ▶ return unless _authorize_registry_read($c);
Branch: 1 branch
BranchTrueFalseTotal
unless _authorize_registry_read($c) 3 21 24
216 21 my $skeid = $c->skeid;
217 21 $c->res->headers->header('Cache-Control' => 'no-store');
218 21 ▶ unless ($skeid->registry_enabled) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($skeid->registry_enabled) 2 19 21
219 2 $c->render(status => 404,
220 json => { error => { message => 'No registry snapshot is published here', type => 'not_found' } });
221 2 return;
222 }
223 19 my ($body, $signature) = eval { Langertha::Skeid::Registry->signed_snapshot($skeid) };
224 19 ▶ unless (defined $body) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $body) 1 18 19
225 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
226 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
227 0 $c->render(status => 503,
228 json => { error => { message => 'Registry secret is not set', type => 'unavailable' } });
229 0 return;
230 }
231 # Anything else is a bug in building the snapshot. The operator gets the cause in the
232 # log; the caller gets nothing that could describe this process's internals.
233 1 $err =~ s/\s+\z//;
234 1 $c->app->log->error("registry snapshot failed: $err");
235 1 $c->render(status => 500,
236 json => { error => { message => 'Registry snapshot could not be built', type => 'server_error' } });
237 1 return;
238 }
239 18 $c->res->headers->header(Langertha::Skeid::Registry->SIGNATURE_HEADER => $signature);
240 18 $c->render(data => $body, format => 'json');
241 324 });
242  
243 # Lightweight admin API for live control-plane updates.
244 100 ▶ my $admin = $r->under('/skeid' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
245 100 my ($c) = @_;
246 100 return _authorize_admin($c);
247 324 });
248  
249 58 ▶ $admin->get('/nodes' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
250 58 my ($c) = @_;
251 58 $c->render(json => { nodes => $c->skeid->list_nodes });
252 324 });
253  
254 1 ▶ $admin->post('/nodes' => sub {
Subroutine __ANON__: called CC=5 SCAR=17.6
255 1 my ($c) = @_;
256 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
257 1 my $ok = eval { $c->skeid->call_function('nodes.add', $body)->{ok} };
258 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
259 1 ▶ my $msg = $@ ? "$@" : 'invalid node payload';
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 1 0 1
260 1 $msg =~ s/\s+$//;
261 1 $c->render(json => { error => { message => $msg, type => 'invalid_request_error' } }, status => 400);
262 1 return;
263 }
264 0 $c->render(json => { ok => 1, nodes => $c->skeid->list_nodes });
265 324 });
266  
267 13 ▶ $admin->post('/nodes/:id/health' => sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
268 13 my ($c) = @_;
269 13 ▶ my $body = $c->req->json || {};
Condition50%1/2
$c->req->json || {}
l!l
130
MC/DC0%0/1
$c->req->json || {}
$c->req->json
Truth table50%1/2
A
A= $c->req->json
Aresult
11
00
270 13 my $id = $c->param('id');
271 my $ok = $c->skeid->call_function('nodes.set_health', {
272 id => $id,
273 healthy => ($body->{healthy} ? 1 : 0),
274 13 ▶ })->{ok};
Branch: 1 branch
BranchTrueFalseTotal
$body->{'healthy'} ? : 6 7 13
275 13 ▶ $c->render(json => { ok => $ok ? 1 : 0 });
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 13 0 13
276 324 });
277  
278 1 ▶ $admin->get('/config' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
279 1 my ($c) = @_;
280 1 $c->render(json => { reload => $c->skeid->call_function('config.status', {}) });
281 324 });
282  
283 0 ▶ $admin->get('/metrics/nodes' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
284 0 my ($c) = @_;
285 0 $c->render(json => { metrics => $c->skeid->node_metrics });
286 324 });
287  
288 0 ▶ $admin->get('/usage' => sub {
Subroutine __ANON__: not called CC=9 SCAR=45.0
289 0 my ($c) = @_;
290 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
291 (defined($c->param('since')) && length($c->param('since')) ? (since => $c->param('since')) : ()),
292 (defined($c->param('api_key_id')) && length($c->param('api_key_id')) ? (api_key_id => $c->param('api_key_id')) : ()),
293 (defined($c->param('model')) && length($c->param('model')) ? (model => $c->param('model')) : ()),
294 limit => ($c->param('limit') // 50),
295 });
296 0 ▶ my $status = ($report->{ok} ? 200 : 400);
Branch: 1 branch
BranchTrueFalseTotal
$report->{'ok'} ? : 0 0 0
297 0 $c->render(status => $status, json => $report);
298 324 });
299  
300 324 return $app;
301 }
302  
303 100 ▶sub _authorize_admin {
Subroutine _authorize_admin: called CC=8 SCAR=20.8
304 100 my ($c) = @_;
305 100 $c->skeid->maybe_reload_config;
306  
307 100 ▶ my $admin_api_key = $c->skeid->admin_api_key // '';
Condition50%1/2
$c->skeid->admin_api_key // ""
l!l
1000
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
308 100 ▶ if (!length($admin_api_key)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $admin_api_key) 6 94 100
309 6 $c->render(status => 404, text => 'Not Found');
310 6 return undef;
311 }
312  
313 94 ▶ my $auth = $c->req->headers->authorization // '';
Condition100%2/2
$c->req->headers->authorization // ""
l!l
913
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
314 94 my ($scheme, $token) = $auth =~ /\A(\S+)\s+(.+)\z/;
315 94 ▶ 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
61573
defined $scheme and lc $scheme eq "bearer" and defined $token
!ll&&!rl&&r
6088
defined $scheme and lc $scheme eq "bearer"
!ll&&!rl&&r
5188
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
316 && Langertha::Skeid::Secret->equal($token, $admin_api_key);
317 94 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 21 73 94
318 21 $c->res->headers->header('WWW-Authenticate' => 'Bearer realm="skeid-admin"');
319 21 $c->render(
320 status => 401,
321 json => {
322 error => {
323 type => 'unauthorized',
324 message => 'Missing or invalid admin bearer token',
325 },
326 },
327 );
328 21 return undef;
329 }
330 73 return 1;
331 }
332  
333 # The snapshot route's gate: the admin API key (compat) or the registry read key, each compared
334 # in constant time. 404 when neither is configured, like every closed /skeid route; 401 with the
335 # admin route's challenge otherwise.
336 24 ▶sub _authorize_registry_read {
Subroutine _authorize_registry_read: called CC=10 SCAR=23.8
337 24 my ($c) = @_;
338 24 my $skeid = $c->skeid;
339 24 $skeid->maybe_reload_config;
340  
341 24 ▶ my @accepted = grep { length } ($skeid->admin_api_key // '', $skeid->registry_read_key // '');
Condition50%2/4
$skeid->admin_api_key // ""
l!l
240
$skeid->registry_read_key // ""
l!l
240
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
342 24 ▶ unless (@accepted) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@accepted) 0 24 24
343 0 $c->render(status => 404, text => 'Not Found');
344 0 return undef;
345 }
346  
347 24 ▶ my $auth = $c->req->headers->authorization // '';
Condition100%2/2
$c->req->headers->authorization // ""
l!l
222
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
348 24 my ($scheme, $token) = $auth =~ /\A(\S+)\s+(.+)\z/;
349 24 my $ok = 0;
350 24 ▶ if (defined($scheme) && lc($scheme) eq 'bearer' && defined($token)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $scheme and lc $scheme eq "bearer" and defined $token) 22 2 24
Condition66%4/6
defined $scheme and lc $scheme eq "bearer" and defined $token
!ll&&!rl&&r
2022
defined $scheme and lc $scheme eq "bearer"
!ll&&!rl&&r
2022
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
351 # No short-circuit: both candidates are compared whichever one matches.
352 22 $ok |= Langertha::Skeid::Secret->equal($token, $_) for @accepted;
353 }
354 24 ▶ return 1 if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 21 3 24
355  
356 3 $c->res->headers->header('WWW-Authenticate' => 'Bearer realm="skeid-admin"');
357 3 $c->render(
358 status => 401,
359 json => {
360 error => {
361 type => 'unauthorized',
362 message => 'Missing or invalid registry bearer token',
363 },
364 },
365 );
366 3 return undef;
367 }
368  
369 # What a key is shown depends on who presents it, so no cache may hand one key's answer to
370 # another: every answer -- 404/401/403 included -- is private, not stored, and varies on each
371 # header that can carry the identity. It does not reload the config: a public route anybody can
372 # hit must not be a way to rerun the loader (and restart the node probes) per anonymous GET;
373 # like /v1/models it serves what the last load resolved. 404 when nothing is published (disabled, or a Langertha without
374 # Langertha::Manifest), 401 without a key (ADR 0015: no anonymous manifest, not even a minimal
375 # one), 403 for a key without a manifest: grant, else the manifest built for that key id.
376 24 ▶sub _handle_manifest {
Subroutine _handle_manifest: called CC=6 SCAR=17.9
377 24 my ($c) = @_;
378 24 my $skeid = $c->skeid;
379  
380 24 my $headers = $c->res->headers;
381 24 $headers->header('Cache-Control' => 'private, no-store');
382 24 $headers->header(Vary => 'Authorization, X-Api-Key, X-Skeid-Key-Id, X-Api-Key-Id');
383  
384 24 ▶ unless ($skeid->manifest_enabled && $skeid->manifest_available) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($skeid->manifest_enabled and $skeid->manifest_available) 2 22 24
Condition66%2/3
$skeid->manifest_enabled and $skeid->manifest_available
!ll&&!rl&&r
2022
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
385 2 $c->render(status => 404,
386 json => { error => { message => 'No provider manifest is published here', type => 'not_found' } });
387 2 return;
388 }
389  
390 22 my $api_key_id = _request_api_key_id($c);
391 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
392 5 $headers->header('WWW-Authenticate' => 'Bearer realm="skeid"');
393 5 $c->render(status => 401,
394 json => { error => { message => 'An API key is required for the provider manifest', type => 'unauthorized' } });
395 5 return;
396 }
397  
398 17 my $json = $skeid->manifest_for_key($api_key_id);
399 17 ▶ unless (defined $json) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $json) 3 14 17
400 3 $c->render(status => 403,
401 json => { error => { message => 'No provider manifest is published for this key', type => 'permission_error' } });
402 3 return;
403 }
404  
405 14 $c->render(data => $json, format => 'json');
406 14 return;
407 }
408  
409 # The client's connection is silent while the upstream works, and the server closes a connection
410 # that was silent for its inactivity timeout (30s unless the server was told otherwise). So a
411 # request that calls an upstream gets, on top of that, what the upstream may take: the client
412 # outlasts the upstream and is still there for the answer, or for the error. Read from the user
413 # agent rather than kept beside it, so the two sides cannot drift apart. It holds for this
414 # request only: the server sets its own timeout again for the next one on the connection. A
415 # timeout of 0 is none, on either side, and stays none.
416 527 ▶sub _extend_client_timeout {
Subroutine _extend_client_timeout: called CC=5 SCAR=17.8
417 527 my ($c) = @_;
418 527 ▶ my $stream = Mojo::IOLoop->stream($c->tx->connection // '') or return;
Branch: 1 branch
BranchTrueFalseTotal
my $stream = "Mojo::IOLoop"->stream($c->tx->connection // "") or return 527 0 527
Condition50%1/2
$c->tx->connection // ""
l!l
5270
MC/DC0%0/1
$c->tx->connection // ""
$c->tx->connection
Truth table50%1/2
A
A= $c->tx->connection
Aresult
11
00
419 527 my $own = $stream->timeout;
420 527 my $upstream = $c->app->ua->request_timeout;
421 527 ▶ $stream->timeout(($own && $upstream) ? $own + $upstream : 0);
Branch: 1 branch
BranchTrueFalseTotal
$own && $upstream ? : 527 0 527
Condition33%1/3
$own and $upstream
!ll&&!rl&&r
00527
MC/DC0%0/2
$own and $upstream
$own $upstream
Truth table33%1/3
A and B
A= $ownB= $upstream
ABresult
0X0
100
111
422 527 return;
423 }
424  
425 172 ▶sub _handle_openai_chat {
Subroutine _handle_openai_chat: called CC=3 SCAR=11.0
426 172 my ($c) = @_;
427 172 _extend_client_timeout($c);
428 172 my $body = $c->req->json;
429 172 ▶ unless (ref($body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $body eq "HASH") 2 170 172
430 2 $c->render(json => { error => { message => 'Invalid JSON body', type => 'invalid_request_error' } }, status => 400);
431 2 return;
432 }
433  
434 170 ▶ my $model = $body->{model} // '';
Condition50%1/2
$body->{"model"} // ""
l!l
1700
MC/DC0%0/1
$body->{"model"} // ""
$body->{"model"}
Truth table50%1/2
A
A= $body->{"model"}
Aresult
11
00
435 170 my $api_key_id = _request_api_key_id($c);
436 170 ▶ _begin_route_async($c, $model, $api_key_id, sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
437 170 my ($route, $node_id, $started, $tier) = @_;
438 170 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 18 152 170
439  
440 # The alias layer means the model the client asked for and the model the node is asked for
441 # are two different strings (ADR 0008). The upstream body carries the served model; the
442 # usage event carries both, or cost attribution silently loses which product was used.
443 152 my $served_model = _served_model($tier, $model);
444 152 ▶ $body->{model} = $served_model if ref($body) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $body eq "HASH" 152 0 152
445  
446 152 my $url = _endpoint_url_for_node($route->{url}, '/chat/completions');
447 my $meta = {
448 api_format => 'openai',
449 endpoint => '/v1/chat/completions',
450 api_key_id => $api_key_id,
451 provider => 'skeid',
452 engine => ($route->{engine} // 'openaibase'),
453 model => $served_model,
454 requested_model => $model,
455 152 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
1520
$route->{"url"} // ""
l!l
1520
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
456 };
457  
458 152 ▶ if ($body->{stream}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body->{"stream"}) 54 98 152
459 54 _proxy_openai_stream($c, $url, $body, $node_id, $started, $meta);
460 54 return;
461 }
462  
463 98 $c->render_later;
464 98 ▶ _proxy_openai_json_async($c, $url, $body, $node_id, $started, $meta, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
465 98 my ($res, $err, $status) = @_;
466 98 ▶ return if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 15 83 98
467 83 _render_upstream_response($c, $res, $node_id);
468 98 });
469 170 });
470 }
471  
472 17 ▶sub _handle_openai_embeddings {
Subroutine _handle_openai_embeddings: called CC=3 SCAR=11.2
473 17 my ($c) = @_;
474 17 _extend_client_timeout($c);
475 17 my $body = $c->req->json;
476 17 ▶ unless (ref($body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $body eq "HASH") 0 17 17
477 0 $c->render(json => { error => { message => 'Invalid JSON body', type => 'invalid_request_error' } }, status => 400);
478 0 return;
479 }
480  
481 17 ▶ my $model = $body->{model} // '';
Condition50%1/2
$body->{"model"} // ""
l!l
170
MC/DC0%0/1
$body->{"model"} // ""
$body->{"model"}
Truth table50%1/2
A
A= $body->{"model"}
Aresult
11
00
482 17 my $api_key_id = _request_api_key_id($c);
483 17 ▶ _begin_route_async($c, $model, $api_key_id, sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
484 17 my ($route, $node_id, $started, $tier) = @_;
485 17 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 1 16 17
486  
487 # The alias layer means the model the client asked for and the model the node is asked for
488 # are two different strings (ADR 0008). The upstream body carries the served model; the
489 # usage event carries both, or cost attribution silently loses which product was used.
490 16 my $served_model = _served_model($tier, $model);
491 16 ▶ $body->{model} = $served_model if ref($body) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $body eq "HASH" 16 0 16
492  
493 16 my $url = _endpoint_url_for_node($route->{url}, '/embeddings');
494 my $meta = {
495 api_format => 'openai',
496 endpoint => '/v1/embeddings',
497 api_key_id => $api_key_id,
498 provider => 'skeid',
499 engine => ($route->{engine} // 'openaibase'),
500 model => $served_model,
501 requested_model => $model,
502 16 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
160
$route->{"url"} // ""
l!l
160
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
503 };
504 16 $c->render_later;
505 16 ▶ _proxy_openai_json_async($c, $url, $body, $node_id, $started, $meta, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
506 16 my ($res, $err, $status) = @_;
507 16 ▶ return if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 6 10 16
508 10 _render_upstream_response($c, $res, $node_id);
509 16 });
510 17 });
511 }
512  
513 126 ▶sub _handle_anthropic_messages {
Subroutine _handle_anthropic_messages: called CC=7 SCAR=19.5
514 126 my ($c) = @_;
515 126 _extend_client_timeout($c);
516 126 my $body = $c->req->json;
517 126 ▶ unless (ref($body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $body eq "HASH") 2 124 126
518 2 _render_error($c, 400, 'Invalid JSON body', 'invalid_request_error');
519 2 return;
520 }
521  
522 124 ▶ my $wants_stream = $body->{stream} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$body->{'stream'} ? : 68 56 124
523  
524 # Translation reads the client's body, so a failure there is the client's malformed request
525 # -- a provider built-in tool skeid cannot forward, or a shape the translator cannot read.
526 # Uncaught it escapes as Mojolicious' HTML 500; answer a 400 an Anthropic SDK can parse, before
527 # anything is routed or metered (core karr #216).
528 124 my $openai_body = eval { Langertha::Skeid::Protocol::Anthropic->request_to_openai($body) };
529 124 ▶ unless ($openai_body) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($openai_body) 10 114 124
530 # A deliberate refusal carries a message written for the client. Any other exception can quote
531 # the request, so its text is neither sent nor logged (k75, k82).
532 10 my $err = $@;
533 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
534 ? $err->message : 'Invalid request';
535 10 _render_error($c, 400, $msg, 'invalid_request_error');
536 10 return;
537 }
538 114 ▶ my $model = $openai_body->{model} // '';
Condition50%1/2
$openai_body->{"model"} // ""
l!l
1140
MC/DC0%0/1
$openai_body->{"model"} // ""
$openai_body->{"model"}
Truth table50%1/2
A
A= $openai_body->{"model"}
Aresult
11
00
539 114 my $api_key_id = _request_api_key_id($c);
540  
541 114 ▶ _begin_route_async($c, $model, $api_key_id, sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
542 114 my ($route, $node_id, $started, $tier) = @_;
543 114 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 7 107 114
544  
545 # The alias layer means the model the client asked for and the model the node is asked for
546 # are two different strings (ADR 0008). The upstream body carries the served model; the
547 # usage event carries both, or cost attribution silently loses which product was used.
548 107 my $served_model = _served_model($tier, $model);
549 107 $openai_body->{model} = $served_model;
550  
551 107 my $url = _endpoint_url_for_node($route->{url}, '/chat/completions');
552 my $meta = {
553 api_format => 'anthropic',
554 endpoint => '/v1/messages',
555 api_key_id => $api_key_id,
556 provider => 'skeid',
557 engine => ($route->{engine} // 'openaibase'),
558 model => $served_model,
559 requested_model => $model,
560 107 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
1070
$route->{"url"} // ""
l!l
1070
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
561 };
562  
563 107 ▶ if ($wants_stream) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wants_stream) 64 43 107
564 # Ask upstream for a stream in the one dialect Skeid speaks to nodes, and rewrite it at
565 # the client edge (ADR 0001). include_usage because Anthropic clients read token counts
566 # from message_delta, and an OpenAI stream omits usage unless asked.
567 64 $openai_body->{stream} = \1;
568 64 $openai_body->{stream_options} = { include_usage => \1 };
569 64 _proxy_openai_stream($c, $url, $openai_body, $node_id, $started, $meta,
570 Langertha::Skeid::Protocol::Anthropic::Stream->new(model => $model));
571 64 return;
572 }
573  
574 43 delete $openai_body->{stream};
575 43 $c->render_later;
576 43 ▶ _proxy_openai_json_async($c, $url, $openai_body, $node_id, $started, $meta, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
577 43 my ($res, $err, $status, $upstream, $payload) = @_;
578 43 ▶ return if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 11 32 43
579 32 ▶ $c->res->code($status || 200);
Condition50%1/2
$status || 200
l!l
320
MC/DC0%0/1
$status || 200
$status
Truth table50%1/2
A
A= $status
Aresult
11
00
580 32 $c->res->headers->header('x-skeid-node' => $node_id);
581 32 $c->render(json => $payload);
582 33 ▶ }, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
583 # response_from_openai reads a decoded OpenAI response ($upstream->{choices}, ...); the
584 # raw Mojo $res would read as all-undef and yield a well-formed but empty envelope (karr #26).
585 33 return Langertha::Skeid::Protocol::Anthropic->response_from_openai($_[0], $model);
586 43 });
587 114 });
588 }
589  
590 # Serves both Ollama completion routes. /api/chat and /api/generate differ only at the edge --
591 # generate's prompt/system/images become one chat conversation on the way up, and the answer
592 # carries `response` instead of `message` on the way back (skeid #43) -- so they share the
593 # route, admission, metering and pricing below and cannot drift apart.
594 47 my %OLLAMA_FACE = (
595 chat => {
596 endpoint => '/api/chat',
597 request => 'request_to_openai',
598 response => 'response_from_openai',
599 shape => 'chat',
600 },
601 generate => {
602 endpoint => '/api/generate',
603 request => 'generate_request_to_openai',
604 response => 'generate_response_from_openai',
605 shape => 'generate',
606 },
607 );
608  
609 212 ▶sub _handle_ollama {
Subroutine _handle_ollama: called CC=6 SCAR=17.9
610 212 my ($c, $kind) = @_;
611 212 _extend_client_timeout($c);
612 212 my $face = $OLLAMA_FACE{$kind};
613 212 my $body = $c->req->json;
614 212 ▶ unless (ref($body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $body eq "HASH") 4 208 212
615 4 _render_error($c, 400, 'Invalid JSON body', 'invalid_request_error');
616 4 return;
617 }
618  
619 # Ollama defaults stream to true when the field is absent, unlike everyone else. A client
620 # that omits it is asking for a stream and will sit waiting for newline-delimited JSON.
621 208 ▶ my $wants_stream = exists $body->{stream} ? ($body->{stream} ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $body->{'stream'} ? : 169 39 208
$body->{'stream'} ? : 69 100 169
622  
623 208 my $request_method = $face->{request};
624 # A body the translator cannot read is the client's malformed request. Uncaught it escapes as
625 # Mojolicious' HTML 500; answer a 400 in Ollama's shape before anything is routed or metered.
626 # The exception's text stays out of the answer and the log, as with a dying response translator.
627 208 my $openai_body = eval { Langertha::Skeid::Protocol::Ollama->$request_method($body) };
628 208 ▶ unless (ref($openai_body) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $openai_body eq "HASH") 4 204 208
629 4 _render_error($c, 400, 'Invalid request', 'invalid_request_error');
630 4 return;
631 }
632 204 ▶ my $model = $openai_body->{model} // '';
Condition50%1/2
$openai_body->{"model"} // ""
l!l
2040
MC/DC0%0/1
$openai_body->{"model"} // ""
$openai_body->{"model"}
Truth table50%1/2
A
A= $openai_body->{"model"}
Aresult
11
00
633 204 my $api_key_id = _request_api_key_id($c);
634  
635 204 ▶ _begin_route_async($c, $model, $api_key_id, sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
636 204 my ($route, $node_id, $started, $tier) = @_;
637 204 ▶ return unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 13 191 204
638  
639 # The alias layer means the model the client asked for and the model the node is asked for
640 # are two different strings (ADR 0008). The upstream body carries the served model; the
641 # usage event carries both, or cost attribution silently loses which product was used.
642 191 my $served_model = _served_model($tier, $model);
643 191 $openai_body->{model} = $served_model;
644  
645 191 my $url = _endpoint_url_for_node($route->{url}, '/chat/completions');
646 my $meta = {
647 api_format => 'ollama',
648 endpoint => $face->{endpoint},
649 api_key_id => _request_api_key_id($c),
650 provider => 'skeid',
651 engine => ($route->{engine} // 'openaibase'),
652 model => $served_model,
653 requested_model => $model,
654 191 ▶ route_url => ($route->{url} // ''),
Condition50%2/4
$route->{"engine"} // "openaibase"
l!l
1910
$route->{"url"} // ""
l!l
1910
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
655 };
656  
657 191 ▶ if ($wants_stream) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wants_stream) 103 88 191
658 103 $openai_body->{stream} = \1;
659 103 $openai_body->{stream_options} = { include_usage => \1 };
660 _proxy_openai_stream($c, $url, $openai_body, $node_id, $started, $meta,
661 103 Langertha::Skeid::Protocol::Ollama::Stream->new(model => $model, shape => $face->{shape}));
662 103 return;
663 }
664  
665 88 delete $openai_body->{stream};
666 88 $c->render_later;
667 88 ▶ _proxy_openai_json_async($c, $url, $openai_body, $node_id, $started, $meta, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
668 88 my ($res, $err, $status, $upstream, $payload) = @_;
669 88 ▶ return if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 22 66 88
670 66 ▶ $c->res->code($status || 200);
Condition50%1/2
$status || 200
l!l
660
MC/DC0%0/1
$status || 200
$status
Truth table50%1/2
A
A= $status
Aresult
11
00
671 66 $c->res->headers->header('x-skeid-node' => $node_id);
672 66 $c->render(json => $payload);
673 68 ▶ }, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
674 # See the Anthropic path above: the translator needs the decoded upstream body, not the
675 # Mojo response object, or every field reads undef and the client gets empty content (karr #26).
676 68 my $response_method = $face->{response};
677 68 return Langertha::Skeid::Protocol::Ollama->$response_method($_[0]);
678 88 });
679 204 });
680 }
681  
682 # Walks the tiers of a requested model (ADR 0008) until one admits the request.
683 #
684 # The two ways a tier can fail are not the same and must not be treated the same. A tier with
685 # no eligible node is skipped immediately -- waiting cannot conjure a node that does not exist.
686 # A tier whose nodes are all busy is waited on for its own wait_ms, because capacity comes back.
687 # Only when every tier is exhausted does the request fail, and which failure it is depends on
688 # whether any tier ever had an eligible node: none did means the model is unroutable (503),
689 # some did means everything was busy (429).
690 #
691 # $cb is called with ($route, $node_id, $started, $tier) on success and with nothing on failure,
692 # after the error has been rendered.
693 508 ▶sub _begin_route_async {
Subroutine _begin_route_async: called CC=11 SCAR=24.5
694 508 my ($c, $model, $api_key_id, $cb) = @_;
695 508 ▶ $cb ||= sub { };
Subroutine __ANON__: not called CC=1 SCAR=1.2
Condition33%1/3
$cb ||= sub {
l!l&&r!l&&!r
50800
MC/DC0%0/2
$cb ||= sub { }
$cb sub { }
Truth table33%1/3
A ||= B
A= $cbB= sub { }
ABresult
1X1
011
000
696 508 ▶ my $wait_poll_ms = 0 + ($c->skeid->route_wait_poll_ms // 25);
Condition50%1/2
$c->skeid->route_wait_poll_ms // 25
l!l
5080
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
697 508 ▶ $wait_poll_ms = 1 if $wait_poll_ms < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $wait_poll_ms < 1 0 508 508
698  
699 508 ▶ my $decision = $c->skeid->call_function('route.plan', {
Condition50%1/2
$model // ""
l!l
5080
MC/DC0%0/1
$model // ""
$model
Truth table50%1/2
A
A= $model
Aresult
11
00
700 model => ($model // ''),
701 api_key_id => $api_key_id,
702 });
703  
704 # The key's policy does not grant this model, or grants it but forbids every tier that serves
705 # it. Both are permission answers, and neither improves by retrying -- so neither may be
706 # reported as a capacity problem.
707 508 ▶ if (!$decision->{permitted}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($decision->{"permitted"}) 8 500 508
708 8 _render_error($c, 403, "Model '$model' is not available for this key", 'permission_error');
709 8 $cb->();
710 8 return;
711 }
712  
713 500 ▶ my $plan = $decision->{tiers} || [];
Condition50%1/2
$decision->{'tiers'} || []
l!l
5000
MC/DC0%0/1
$decision->{'tiers'} || []
$decision->{'tiers'}
Truth table50%1/2
A
A= $decision->{'tiers'}
Aresult
11
00
714 500 my $started = time;
715 500 my $saw_eligible = 0;
716 500 my $last_node_id = '';
717 500 my $index = 0;
718 500 my $tier_deadline = 0;
719  
720 500 my $tick;
721 my $wait_timer;
722 32 ▶ my $fail = sub {
Subroutine __ANON__: called CC=12 SCAR=25.0
723 # Nothing eligible can mean two different things once a policy is in play: the model is
724 # unroutable, or it is routable and this key is not allowed at the nodes that serve it.
725 # Only the failure path pays for telling them apart.
726 32 ▶ if (!$saw_eligible && grep { @{$_->{deny_tags} || []} } @$plan) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $saw_eligible and grep {@{$_->{"deny_tags"} or [];};} @$plan) 10 22 32
Condition80%4/5
not $saw_eligible and grep {@{$_->{"deny_tags"} or [];};} @$plan
!ll&&!rl&&r
16610
$_->{'deny_tags'} || []
l!l
160
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
727 10 my $without_deny = 0;
728 10 for my $tier (@$plan) {
729 my $state = $c->skeid->call_function('route.state', {
730 model => ($tier->{model} // ''),
731 10 ▶ tags => ($tier->{tags} || []),
Condition50%2/4
$tier->{"model"} // ""
l!l
100
$tier->{'tags'} || []
l!l
100
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
732 });
733 10 ▶ $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"} 5 5 10
Condition66%2/3
ref $state eq "HASH" and $state->{"has_eligible"}
!ll&&!rl&&r
055
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
734 }
735 10 ▶ if ($without_deny) {
Branch: 1 branch
BranchTrueFalseTotal
if ($without_deny) 5 5 10
736 5 _render_error($c, 403, "Model '$model' is not available for this key", 'permission_error');
737 5 undef $tick;
738 5 $cb->();
739 5 return;
740 }
741 }
742  
743 27 ▶ if (!$saw_eligible) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $saw_eligible) { } 11 16 27
744 11 _render_error($c, 503, "No healthy node available for model '$model'", 'model_not_found');
745 } else {
746 16 my $waited_ms = int((time - $started) * 1000);
747 16 ▶ my $msg = length($last_node_id)
Branch: 1 branch
BranchTrueFalseTotal
length $last_node_id ? : 0 16 16
748 ? "Timed out waiting for free capacity on node '$last_node_id' (waited ${waited_ms}ms)"
749 : "Timed out waiting for free capacity for model '$model' (waited ${waited_ms}ms)";
750 16 _render_error($c, 429, $msg, 'rate_limit_error');
751 }
752 27 undef $tick;
753 27 $cb->();
754 27 return;
755 500 };
756  
757 668 ▶ $tick = sub {
Subroutine __ANON__: called CC=16 SCAR=28.7
758 668 ▶ return $fail->() if $index > $#$plan;
Branch: 1 branch
BranchTrueFalseTotal
if $index > $plan->$#* 32 636 668
759  
760 636 my $tier = $plan->[$index];
761 my %selector = (
762 model => ($tier->{model} // ''),
763 tags => ($tier->{tags} || []),
764 deny_tags => ($tier->{deny_tags} || []),
765 636 ▶ (length($tier->{engine} // '') ? (engine => $tier->{engine}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
length($tier->{'engine'} // '') ? : 0 636 636
Condition50%4/8
$tier->{"model"} // ""
l!l
6360
$tier->{'tags'} || []
l!l
6360
$tier->{'deny_tags'} || []
l!l
6360
$tier->{"engine"} // ""
l!l
6360
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
766 );
767  
768 636 my $state = $c->skeid->call_function('route.state', \%selector);
769 636 ▶ if (ref($state) eq 'HASH' && $state->{has_eligible}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $state eq "HASH" and $state->{"has_eligible"}) 619 17 636
Condition66%2/3
ref $state eq "HASH" and $state->{"has_eligible"}
!ll&&!rl&&r
017619
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
770 619 $saw_eligible = 1;
771  
772 619 my $route = $c->skeid->call_function('route.next', \%selector)->{node};
773 619 ▶ if ($route && ref($route) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($route and ref $route eq "HASH") 467 152 619
Condition66%2/3
$route and ref $route eq "HASH"
!ll&&!rl&&r
1520467
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
774 467 my $node_id = $route->{id};
775 467 ▶ $last_node_id = $node_id if defined $node_id;
Branch: 1 branch
BranchTrueFalseTotal
if defined $node_id 467 0 467
776 467 ▶ 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"}) 467 0 467
777 # Break the recursive callback's self-reference before control moves into the upstream
778 # lifecycle. The active call frame keeps it alive until this invocation returns.
779 467 undef $tick;
780 467 $cb->($route, $node_id, $started, $tier);
781 467 return;
782 }
783 }
784  
785 # Eligible but nothing free: this tier is worth waiting on, up to its own window.
786 152 ▶ if (time < $tier_deadline) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Langertha::Skeid::Proxy::time() < $tier_deadline) 133 19 152
787 133 $wait_timer = Mojo::IOLoop->timer($wait_poll_ms / 1000, $tick);
788 133 return;
789 }
790 }
791  
792 36 $index++;
793 36 ▶ $tier_deadline = time + (($plan->[$index] ? ($plan->[$index]{wait_ms} // 0) : 0) / 1000);
Branch: 1 branch
BranchTrueFalseTotal
$plan->[$index] ? : 4 32 36
Condition50%1/2
$plan->[$index]{"wait_ms"} // 0
l!l
40
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
794 36 $tick->();
795 36 return;
796 500 };
797  
798 # A client that hangs up while its request waits for capacity stops waiting: the next poll
799 # would take a slot for nobody and never give it back. $tick is set exactly as long as
800 # admission is undecided, which tells this finish from the one every answered request emits
801 # as well. Nothing is rendered, there is nobody to read it. A stand-in controller has no
802 # transaction.
803 500 ▶ if ($c->can('tx') && $c->tx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->can("tx") and $c->tx) 497 3 500
Condition66%2/3
$c->can("tx") and $c->tx
!ll&&!rl&&r
30497
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
804 467 ▶ $c->tx->on(finish => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
805 467 ▶ return unless $tick;
Branch: 1 branch
BranchTrueFalseTotal
unless $tick 466 1 467
806 1 ▶ Mojo::IOLoop->remove($wait_timer) if defined $wait_timer;
Branch: 1 branch
BranchTrueFalseTotal
if defined $wait_timer 1 0 1
807 1 undef $tick;
808 1 $cb->();
809 497 });
810 }
811  
812 500 ▶ $tier_deadline = time + ((@$plan ? ($plan->[0]{wait_ms} // 0) : 0) / 1000);
Branch: 1 branch
BranchTrueFalseTotal
@$plan ? : 500 0 500
Condition50%1/2
$plan->[0]{"wait_ms"} // 0
l!l
5000
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
813 500 $tick->();
814 500 return;
815 }
816  
817 # True once the client of this request cannot be answered any more: its transaction was closed,
818 # or is destroyed already -- the controller holds it weakly. Only asked before anything was
819 # rendered, because a transaction that was answered is finished as well.
820 466 ▶sub _client_gone {
Subroutine _client_gone: called CC=3 SCAR=11.0
821 466 my ($c) = @_;
822 466 my $tx = $c->tx;
823 466 ▶ return (!$tx || $tx->is_finished) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
!$tx || $tx->is_finished ? : 3 463 466
Condition66%2/3
not $tx or $tx->is_finished
l!l&&r!l&&!r
30463
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
824 }
825  
826 # Ends an upstream transaction in flight by closing its connection. The user agent then drops
827 # the connection instead of pooling it and runs the transaction's completion callback, and the
828 # node sees the connection close, which is what makes it stop generating. A transaction that
829 # is still connecting is closed as soon as it has a connection -- one tick later, because the
830 # user agent is in the middle of setting that connection up when it announces it. A finished
831 # transaction is left alone: its connection may be serving another request by now.
832 13 ▶sub _cancel_upstream {
Subroutine _cancel_upstream: called CC=2 SCAR=6.9
833 13 my ($tx) = @_;
834 13 ▶ my $close = sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
835 13 my ($id) = @_;
836 13 ▶ return if $tx->is_finished;
Branch: 1 branch
BranchTrueFalseTotal
if $tx->is_finished 0 13 13
837 13 ▶ my $stream = Mojo::IOLoop->stream($id) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $stream = "Mojo::IOLoop"->stream($id) or return 13 0 13
838 13 $stream->close;
839 13 return;
840 13 };
841 13 ▶ if (defined(my $id = $tx->connection)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $id = $tx->connection)) 12 1 13
842 12 $close->($id);
843 12 return;
844 }
845 1 ▶ $tx->once(connection => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
846 1 my (undef, $id) = @_;
847 1 ▶ Mojo::IOLoop->next_tick(sub { $close->($id) });
Subroutine __ANON__: called CC=1 SCAR=0.0
848 1 });
849 1 return;
850 }
851  
852 # What a request its client abandoned records (ADR 0004): failed, under the status nginx made
853 # the convention for "client closed request" -- no answer was delivered, and 499 can be told
854 # from every status a node or Skeid itself answers with.
855 6 ▶sub _client_abort_event {
Subroutine _client_abort_event: called CC=1 SCAR=0.0
856 return (
857 6 status_code => 499,
858 ok => 0,
859 error_type => 'client_abort',
860 error_message => 'Client closed the connection before the response was complete',
861 );
862 }
863  
864 # $translate is an optional coderef that turns the decoded upstream answer into what the client
865 # gets. It runs before the request is finished and metered, so a translator that dies is one
866 # failed request -- one usage event with ok => 0, an error in the face's own shape -- and the
867 # callback gets the translated payload as its fifth argument, or nothing after an error.
868 245 ▶sub _proxy_openai_json_async {
Subroutine _proxy_openai_json_async: called CC=3 SCAR=11.0
869 245 my ($c, $url, $body, $node_id, $started, $meta, $cb, $translate) = @_;
870 245 ▶ $meta ||= {};
Condition50%1/2
$meta ||= {}
l!l
2450
MC/DC0%0/1
$meta ||= {}
$meta
Truth table50%1/2
A
A= $meta
Aresult
11
00
871 245 ▶ $cb ||= sub { };
Subroutine __ANON__: not called CC=1 SCAR=1.2
Condition33%1/3
$cb ||= sub {
l!l&&r!l&&!r
24500
MC/DC0%0/2
$cb ||= sub { }
$cb sub { }
Truth table33%1/3
A ||= B
A= $cbB= sub { }
ABresult
1X1
011
000
872  
873 245 my %fwd_headers = _forward_headers($c);
874 245 ▶ _inject_node_auth_async(\%fwd_headers, $c->skeid, $node_id, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
875 245 my ($no_key) = @_;
876  
877 # The client hung up while the node key was being resolved, whether or not it resolved -- asked
878 # before the refusal, which would meter and answer a transaction nobody holds any more. Nothing went upstream: the slot
879 # is given back and nothing is metered, as for every request that was not forwarded.
880 245 ▶ if (_client_gone($c)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_client_gone($c)) 2 243 245
881 2 $c->skeid->call_function('request.finish', {
882 id => $node_id,
883 ok => 0,
884 aborted => 1,
885 duration_ms => _duration_ms($started),
886 });
887 2 $cb->(undef, 1, 499);
888 2 return;
889 }
890  
891 243 ▶ if (defined $no_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $no_key) 30 213 243
892 30 _refuse_unkeyed_node($c, $node_id, $started, $meta, $no_key);
893 30 $cb->(undef, 1, 503);
894 30 return;
895 }
896 213 my $tx = $c->app->ua->build_tx(POST => $url, \%fwd_headers, json => $body);
897  
898 # Set by whichever comes first, the upstream's completion or the client hanging up, so that
899 # request.finish and the usage event happen once.
900 213 my $closed = 0;
901  
902 213 ▶ $c->tx->on(finish => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
903 213 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 211 2 213
904 2 $closed = 1;
905 2 my $duration_ms = _duration_ms($started);
906 2 $c->skeid->call_function('request.finish', {
907 id => $node_id,
908 ok => 0,
909 aborted => 1,
910 duration_ms => $duration_ms,
911 });
912 2 _record_usage_event($c, {
913 %$meta,
914 _client_abort_event(),
915 node_id => $node_id,
916 duration_ms => $duration_ms,
917 metrics => {},
918 });
919 2 _cancel_upstream($tx);
920 2 $cb->(undef, 1, 499);
921 213 });
922  
923 213 ▶ $c->app->ua->start($tx => sub {
Subroutine __ANON__: called CC=16 SCAR=27.8
924 213 my ($ua, $done) = @_;
925 # The client hung up and its request was closed then; this is the cancelled transaction.
926 213 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 2 211 213
927 211 $closed = 1;
928 211 my $duration_ms = _duration_ms($started);
929 211 my $res = $done->res;
930  
931 # Mojo reports an HTTP 4xx/5xx through tx->error too. Observe the response that actually
932 # arrived before taking that error return, so a 429's Retry-After can gate the next request.
933 # A transport failure has no useful status or headers and _observe_capacity records nothing.
934 211 _observe_capacity($c, $node_id, $res);
935  
936 211 ▶ if (my $err = $done->error) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $done->error) 17 194 211
937 17 $c->skeid->call_function('request.finish', {
938 id => $node_id,
939 ok => 0,
940 duration_ms => $duration_ms,
941 });
942 _record_usage_event($c, {
943 %$meta,
944 node_id => $node_id,
945 status_code => ($err->{code} || 502),
946 ok => 0,
947 duration_ms => $duration_ms,
948 error_type => 'upstream_error',
949 17 ▶ error_message => ($err->{message} // 'unknown'),
Condition75%3/4
$err->{'code'} || 502
l!l
125
$err->{"message"} // "unknown"
l!l
170
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
950 metrics => {},
951 });
952 17 ▶ _render_error($c, ($err->{code} || 502),
Condition100%2/2
$err->{'code'} || 502
l!l
125
MC/DC100%1/1
$err->{'code'} || 502
$err->{'code'}
Truth table100%2/2
A
A= $err->{'code'}
Aresult
11
00
953 'Upstream error: ' . _upstream_error_message($err, $done->res->body), 'upstream_error');
954 17 ▶ $cb->(undef, 1, ($err->{code} || 502));
Condition100%2/2
$err->{'code'} || 502
l!l
125
MC/DC100%1/1
$err->{'code'} || 502
$err->{'code'}
Truth table100%2/2
A
A= $err->{'code'}
Aresult
11
00
955 17 return;
956 }
957  
958 194 ▶ my $status = $res->code // 200;
Condition50%1/2
$res->code // 200
l!l
1940
MC/DC0%0/1
$res->code // 200
$res->code
Truth table50%1/2
A
A= $res->code
Aresult
11
00
959 194 my $payload = eval { $res->json };
960  
961 194 my $translated;
962 194 ▶ if ($translate) {
Branch: 1 branch
BranchTrueFalseTotal
if ($translate) 101 93 194
963 101 ▶ $translated = eval { $translate->(ref($payload) eq 'HASH' ? $payload : {}) };
Branch: 1 branch
BranchTrueFalseTotal
ref $payload eq 'HASH' ? : 100 1 101
964 101 ▶ unless (defined $translated) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $translated) 3 98 101
965 3 $c->app->log->error('Translating the answer of node ' . $node_id . ' failed');
966 3 $c->skeid->call_function('request.finish', {
967 id => $node_id,
968 ok => 0,
969 duration_ms => $duration_ms,
970 });
971 3 _record_usage_event($c, {
972 %$meta,
973 node_id => $node_id,
974 status_code => 500,
975 ok => 0,
976 duration_ms => $duration_ms,
977 error_type => 'translation_error',
978 error_message => 'Response translation failed',
979 metrics => {},
980 });
981 3 _render_error($c, 500, 'Response translation failed', 'api_error');
982 3 $cb->(undef, 1, 500);
983 3 return;
984 }
985 }
986  
987 191 ▶ $c->skeid->call_function('request.finish', {
Branch: 1 branch
BranchTrueFalseTotal
$status < 500 ? : 191 0 191
988 id => $node_id,
989 ok => ($status < 500) ? 1 : 0,
990 duration_ms => $duration_ms,
991 });
992  
993 191 my $metrics = {};
994 191 ▶ if (ref($payload) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $payload eq "HASH") 190 1 191
995 190 ▶ my $tool_calls = eval { [ map { $_->to_hash } Langertha::ToolCall->extract('openai', $payload) ] } || [];
Condition50%1/2
eval { || []
l!l
1900
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
996 190 $metrics = _priced_metrics($c, $meta, $body, $duration_ms, $payload, $tool_calls);
997 }
998  
999 191 ▶ _record_usage_event($c, {
Branch: 1 branch
BranchTrueFalseTotal
$status < 500 ? : 191 0 191
1000 %$meta,
1001 node_id => $node_id,
1002 status_code => $status,
1003 ok => ($status < 500) ? 1 : 0,
1004 duration_ms => $duration_ms,
1005 metrics => $metrics,
1006 });
1007  
1008 191 ▶ $cb->($res, 0, $status, (ref($payload) eq 'HASH' ? $payload : {}), $translated);
Branch: 1 branch
BranchTrueFalseTotal
ref $payload eq 'HASH' ? : 190 1 191
1009 213 });
1010 245 });
1011  
1012 245 return;
1013 }
1014  
1015 # $stream is an optional translator (Protocol::*::Stream). Without one the upstream's bytes are
1016 # relayed untouched, which is what an OpenAI client wants and the only path that cannot lose
1017 # anything in translation. With one, each OpenAI chunk is decoded and re-emitted in the
1018 # client's own format -- the same edge-translation seam as the non-streaming path (ADR 0001).
1019 221 ▶sub _proxy_openai_stream {
Subroutine _proxy_openai_stream: called CC=2 SCAR=7.0
1020 221 my ($c, $url, $body, $node_id, $started, $meta, $stream) = @_;
1021 221 ▶ $meta ||= {};
Condition50%1/2
$meta ||= {}
l!l
2210
MC/DC0%0/1
$meta ||= {}
$meta
Truth table50%1/2
A
A= $meta
Aresult
11
00
1022  
1023 221 my %fwd_headers = _forward_headers($c);
1024  
1025 # render_later before the key resolution, not after: a cold cache means the callback runs on
1026 # a later tick, and Mojolicious would have rendered an empty response by then.
1027 221 $c->render_later;
1028  
1029 221 ▶ _inject_node_auth_async(\%fwd_headers, $c->skeid, $node_id, sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1030 221 my ($no_key) = @_;
1031  
1032 # The client hung up while the node key was being resolved, whether or not it resolved -- asked
1033 # before the refusal, which would meter and answer a transaction nobody holds any more. Nothing
1034 # went upstream: the slot is given back and nothing is metered, as for every request that was
1035 # not forwarded. Nothing is set up yet, so there is nothing to take apart.
1036 221 ▶ if (_client_gone($c)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_client_gone($c)) 1 220 221
1037 1 $c->skeid->call_function('request.finish', {
1038 id => $node_id,
1039 ok => 0,
1040 aborted => 1,
1041 duration_ms => _duration_ms($started),
1042 });
1043 1 return;
1044 }
1045  
1046 220 ▶ return _refuse_unkeyed_node($c, $node_id, $started, $meta, $no_key) if defined $no_key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $no_key 24 196 220
1047 196 my $tx = $c->app->ua->build_tx(POST => $url, \%fwd_headers, json => $body);
1048 # Mojolicious would parse an unchunked, exactly-text/event-stream body into its own `sse`
1049 # events and never emit `read` -- the relay would forward nothing (skeid karr #30).
1050 196 $tx->res->content(Langertha::Skeid::Proxy::RelayContent->new);
1051  
1052 196 my $headers_sent = 0;
1053 196 my $had_error = 0;
1054 # Taken now: the header goes out before the first byte, and the request may be past its
1055 # transaction by then.
1056 196 my $request_id = _request_id($c);
1057 # A translator that can report errors in its own format (Anthropic, Ollama) takes the failure
1058 # paths too: an upstream error status before the stream opens becomes a plain HTTP error in
1059 # the client's shape, a failure after it becomes an in-band error event (core karr #224).
1060 196 ▶ my $stream_errors = $stream && $stream->can('error_event');
Condition66%2/3
$stream && $stream->can('error_event')
!ll&&!rl&&r
470149
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
1061 196 my $upstream_failed = 0;
1062 196 my $upstream_error_body = '';
1063 196 my $status = 200;
1064 # The upstream's own usage block, verbatim, so a stream is priced by the same metrics.normalize
1065 # call as a non-streamed answer (skeid #41). undef until a frame carries one.
1066 196 my $upstream_usage;
1067 196 my $accumulated_content_bytes = 0;
1068 # UTF-8 bytes of the content this stream relayed or translated, for the usage event (skeid #36).
1069 # A relayed stream counts off the OpenAI deltas it read along; a translated one takes its
1070 # translator's own count -- the text it actually wrote in the client's format. An observation
1071 # recorded beside the token counts, never a substitute for them.
1072 196 ▶ 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 ? : 149 47 196
Condition50%1/2
($stream->usage)[2] // 0
l!l
1490
MC/DC0%0/1
($stream->usage)[2] // 0
($stream->usage)[2]
Truth table50%1/2
A
A= ($stream->usage)[2]
Aresult
11
00
1073  
1074 # Upstream chunks arrive faster than they can be written out, so they are queued and drained
1075 # one at a time. Writing each chunk directly would end the response after the first one:
1076 # a dynamic Mojolicious response with no drain callback is finished once its write queue
1077 # empties, and every later chunk then hits a destroyed transaction. The client sees headers,
1078 # no body, and no error.
1079 196 my @queue;
1080 196 my $draining = 0;
1081 196 my $upstream_done = 0;
1082 196 my $finished = 0;
1083  
1084 196 my $drain;
1085 879 ▶ $drain = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1086 879 ▶ if (!@queue) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@queue) 403 476 879
1087 403 $draining = 0;
1088 403 ▶ if ($upstream_done && !$finished) {
Branch: 1 branch
BranchTrueFalseTotal
if ($upstream_done and not $finished) 148 255 403
Condition66%2/3
$upstream_done and not $finished
!ll&&!rl&&r
2550148
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
1089 148 $finished = 1;
1090 148 $c->finish;
1091 # write_chunk retains its last drain callback. Clear the recursive callback scalar once
1092 # the queue is complete so that callback cannot retain the controller through $drain.
1093 148 undef $drain;
1094 }
1095 403 return;
1096 }
1097 476 $draining = 1;
1098 476 my $chunk = shift @queue;
1099 476 ▶ $c->write_chunk($chunk => sub { $drain->() if $drain });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $drain 475 0 475
1100 196 };
1101  
1102 # SSE frames do not respect read boundaries: one read can carry half a frame, and the half
1103 # that completes it arrives in the next. Parsing per read would silently drop the split
1104 # frame -- usually the last one, which is the one carrying usage.
1105 196 my $pending = '';
1106  
1107 # Set by whichever comes first, the upstream's completion, the client hanging up or a
1108 # translator that died, so that request.finish and the usage event happen once.
1109 196 my $closed = 0;
1110  
1111 # A translator that dies on a chunk ends the request here, not in the upstream callback the
1112 # exception would escape from: the upstream is cancelled, the slot given back, one failed usage
1113 # event written, and the client answered in its own face's error shape -- an HTTP error when
1114 # nothing was queued for it yet, an in-band error event when the stream is open. The
1115 # exception's text is neither logged nor sent: it is the translator's own and may quote the
1116 # request.
1117 196 my $wrote = 0;
1118 7 ▶ my $fail_translation = sub {
Subroutine __ANON__: called CC=10 SCAR=25.3
1119 7 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 0 7 7
1120 7 $closed = 1;
1121 7 $tx->res->content->unsubscribe('read');
1122 7 my $duration_ms = _duration_ms($started);
1123 7 $c->skeid->call_function('request.finish', {
1124 id => $node_id,
1125 ok => 0,
1126 duration_ms => $duration_ms,
1127 });
1128 7 _record_usage_event($c, {
1129 %$meta,
1130 node_id => $node_id,
1131 status_code => 500,
1132 ok => 0,
1133 duration_ms => $duration_ms,
1134 error_type => 'translation_error',
1135 error_message => 'Stream translation failed',
1136 content_bytes => $content_bytes->(),
1137 metrics => _stream_metrics($c, $meta, $body, $duration_ms, $upstream_usage),
1138 });
1139 7 _cancel_upstream($tx);
1140 7 $upstream_done = 1;
1141 7 ▶ if (!$wrote) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($wrote) 4 3 7
1142 4 $c->res->headers->remove($_) for @{$c->res->headers->names};
1143 4 $c->res->headers->header('x-request-id' => $request_id);
1144 4 _render_error($c, 500, 'Stream translation failed', 'api_error');
1145 4 undef $drain;
1146 4 return;
1147 }
1148 3 ▶ my $frame = eval { $stream_errors ? $stream->error_event(500, 'Stream translation failed') : '' };
Branch: 1 branch
BranchTrueFalseTotal
$stream_errors ? : 3 0 3
1149 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
1150 3 ▶ $drain->() unless $draining;
Branch: 1 branch
BranchTrueFalseTotal
unless $draining 3 0 3
1151 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
1152 0 $finished = 1;
1153 0 $c->finish;
1154 0 undef $drain;
1155 }
1156 196 };
1157  
1158 600 ▶ $tx->res->content->unsubscribe('read')->on(read => sub {
Subroutine __ANON__: called CC=27 SCAR=33.0
1159 600 my ($content, $bytes) = @_;
1160 # Kept only to lift the upstream's own error message into the error the client gets.
1161 600 ▶ return $upstream_error_body .= $bytes if $upstream_failed;
Branch: 1 branch
BranchTrueFalseTotal
if $upstream_failed 0 600 600
1162 600 ▶ unless ($headers_sent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($headers_sent) 191 409 600
1163 191 ▶ $status = $tx->res->code // 200;
Condition50%1/2
$tx->res->code // 200
l!l
1910
MC/DC0%0/1
$tx->res->code // 200
$tx->res->code
Truth table50%1/2
A
A= $tx->res->code
Aresult
11
00
1164 # The upstream refused before streaming anything. Opening an SSE response for it would
1165 # hand the client a 4xx/5xx event stream with no events in it; leave the response unsent
1166 # and let the completion callback answer it as an error, as the non-streaming path does.
1167 191 ▶ if ($stream_errors && $status >= 400) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream_errors and $status >= 400) 11 180 191
Condition100%3/3
$stream_errors and $status >= 400
!ll&&!rl&&r
4513511
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
1168 11 $upstream_failed = 1;
1169 11 $upstream_error_body .= $bytes;
1170 11 return;
1171 }
1172 180 $c->res->code($status);
1173 180 for my $name (@{$tx->res->headers->names}) {
1174 757 my $lc = lc($name);
1175 757 ▶ next if $lc eq 'content-length' || $lc eq 'transfer-encoding' || $lc eq 'content-encoding';
Branch: 1 branch
BranchTrueFalseTotal
if $lc eq "content-length" or $lc eq "transfer-encoding" or $lc eq "content-encoding" 178 579 757
Condition83%5/6
$lc eq "content-length" or $lc eq "transfer-encoding" or $lc eq "content-encoding"
l!l&&r!l&&!r
1780579
$lc eq "content-length" or $lc eq "transfer-encoding"
l!l&&r!l&&!r
8692579
MC/DC66%2/3
$lc eq "content-length" or $lc eq "transfer-encoding" or $lc eq "content-encoding"
$lc eq "content-length" $lc eq "transfer-encoding" $lc eq "content-encoding"
Truth table75%3/4
A or B or C
A= $lc eq "content-length"B= $lc eq "transfer-encoding"C= $lc eq "content-encoding"
ABCresult
1XX1
01X1
0011
0000
1176 # A translated stream is not the upstream's media type any more. Relaying
1177 # text/event-stream to an Ollama client tells it to parse something it does not speak.
1178 579 ▶ next if $stream && $lc eq 'content-type';
Branch: 1 branch
BranchTrueFalseTotal
if $stream and $lc eq "content-type" 135 444 579
Condition100%3/3
$stream and $lc eq "content-type"
!ll&&!rl&&r
144300135
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
1179 444 $c->res->headers->header($name => $tx->res->headers->header($name));
1180 }
1181 180 ▶ $c->res->headers->header('content-type' => $stream->content_type) if $stream;
Branch: 1 branch
BranchTrueFalseTotal
if $stream 135 45 180
1182 180 $c->res->headers->header('x-skeid-node' => $node_id);
1183 180 $c->res->headers->header('x-request-id' => $request_id);
1184 180 $headers_sent = 1;
1185 }
1186  
1187 # Parse SSE lines and accumulate usage + content bytes. Without a translator the relayed
1188 # bytes are never modified -- this reads along, it does not rewrite.
1189 589 $pending .= $bytes;
1190 589 my $translated = '';
1191 589 ▶ while ($pending =~ s/\A([^\n]*)\n//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pending =~ s/\A([^\n]*)\n//) 1691 582 2273
1192 1691 my $line = $1;
1193 1691 ▶ next unless $line =~ /^data: (.+?)\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /^data: (.+?)\s*$/ 842 849 1691
1194 849 my $payload = $1;
1195  
1196 # OpenAI closes with a literal [DONE] sentinel, which is not JSON and has no equivalent
1197 # in either target format -- the translated stream ends with its own closing events.
1198 849 ▶ next if $payload eq '[DONE]';
Branch: 1 branch
BranchTrueFalseTotal
if $payload eq "[DONE]" 149 700 849
1199  
1200 700 my $json = eval { decode_json($payload) };
1201 700 ▶ next unless $json && ref($json) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $json and ref $json eq "HASH" 0 700 700
Condition33%1/3
$json and ref $json eq "HASH"
!ll&&!rl&&r
00700
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
1202  
1203 700 ▶ if (my $delta = $json->{choices}[0]{delta}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $delta = $json->{"choices"}[0]{"delta"}) 640 60 700
1204 640 ▶ if (my $delta_content = $delta->{content}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $delta_content = $delta->{"content"}) 506 134 640
1205 506 $accumulated_content_bytes += Langertha::Skeid::Protocol::utf8_length($delta_content);
1206 }
1207 }
1208  
1209 700 ▶ if (ref($json->{usage}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $json->{"usage"} eq "HASH") 190 510 700
1210 190 $upstream_usage = _merge_usage($upstream_usage, $json->{usage});
1211 }
1212  
1213 700 ▶ if ($stream) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream) 384 316 700
1214 384 my $out = eval { $stream->delta($json) };
1215 384 ▶ unless (defined $out) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $out) 7 377 384
1216 7 $c->app->log->error('Translating a stream chunk failed for node ' . $node_id);
1217 7 return $fail_translation->();
1218 }
1219 377 $translated .= $out;
1220 }
1221 }
1222  
1223 # The first read event fires with an empty chunk as soon as the upstream headers are
1224 # parsed, and writing an empty chunk finalizes a Mojolicious response. Relaying it would
1225 # end the stream before its first token -- headers, no body, no error.
1226 582 ▶ if ($stream) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream) { } 352 230 582
1227 352 ▶ return unless length $translated;
Branch: 1 branch
BranchTrueFalseTotal
unless length $translated 130 222 352
1228 222 $wrote = 1;
1229 222 push @queue, $translated;
1230 } else {
1231 230 ▶ return unless length $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless length $bytes 19 211 230
1232 211 $wrote = 1;
1233 211 push @queue, $bytes;
1234 }
1235 433 ▶ $drain->() unless $draining;
Branch: 1 branch
BranchTrueFalseTotal
unless $draining 343 90 433
1236 196 });
1237  
1238 166 ▶ $c->tx->on(finish => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1239 # Also emitted when the answer is complete, and then there is nothing left to do here. When
1240 # the client hung up, what is queued has no reader and the drain callback that would take
1241 # the next chunk does not run again: drop the queue and the callback's self-reference, or
1242 # they keep the controller alive.
1243 166 @queue = ();
1244 166 $finished = 1;
1245 166 undef $drain;
1246 166 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 162 4 166
1247 4 $closed = 1;
1248 4 $tx->res->content->unsubscribe('read');
1249  
1250 # Billed from what the stream reported before the client left; the node spent that, whoever
1251 # read it (ADR 0004).
1252 4 my $duration_ms = _duration_ms($started);
1253 4 $c->skeid->call_function('request.finish', {
1254 id => $node_id,
1255 ok => 0,
1256 aborted => 1,
1257 duration_ms => $duration_ms,
1258 });
1259 4 _record_usage_event($c, {
1260 %$meta,
1261 _client_abort_event(),
1262 node_id => $node_id,
1263 duration_ms => $duration_ms,
1264 content_bytes => $content_bytes->(),
1265 metrics => _stream_metrics($c, $meta, $body, $duration_ms, $upstream_usage),
1266 });
1267 4 _cancel_upstream($tx);
1268 196 });
1269  
1270 196 ▶ $c->app->ua->start($tx => sub {
Subroutine __ANON__: called CC=35 SCAR=36.0
1271 196 my ($ua, $tx_done) = @_;
1272  
1273 # The read listener closes over both the upstream transaction and the client controller.
1274 # Completion means no further bytes can arrive, so remove it before returning from any path;
1275 # otherwise the completed transaction owns the listener that owns the transaction forever.
1276 196 $tx_done->res->content->unsubscribe('read');
1277  
1278 # The client hung up and its request was closed then; this is the cancelled transaction.
1279 196 ▶ return if $closed;
Branch: 1 branch
BranchTrueFalseTotal
if $closed 11 185 196
1280 185 $closed = 1;
1281  
1282 # As on the JSON path, an HTTP error is still a response whose capacity headers matter.
1283 # Observe it before the pre-stream error return; transport failures contribute nothing.
1284 185 _observe_capacity($c, $node_id, $tx_done->res);
1285  
1286 185 ▶ if (my $err = $tx_done->error) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $tx_done->error) 17 168 185
1287 17 $had_error = 1;
1288 17 ▶ unless ($headers_sent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($headers_sent) 16 1 17
1289 16 my $duration_ms = _duration_ms($started);
1290 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
1291 16 $c->skeid->call_function('request.finish', {
1292 id => $node_id,
1293 ok => 0,
1294 duration_ms => $duration_ms,
1295 });
1296 _record_usage_event($c, {
1297 %$meta,
1298 node_id => $node_id,
1299 status_code => $err_status,
1300 ok => 0,
1301 duration_ms => $duration_ms,
1302 error_type => 'upstream_error',
1303 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
1304 content_bytes => $content_bytes->(),
1305 metrics => _stream_metrics($c, $meta, $body, _duration_ms($started), $upstream_usage),
1306 });
1307 16 _render_error($c, $err_status,
1308 'Upstream error: ' . _upstream_error_message($err, $upstream_error_body), 'upstream_error');
1309 16 undef $drain;
1310 16 return;
1311 }
1312 }
1313  
1314 # The stream is open, so the status is already sent. Mojo::UserAgent reports an upstream
1315 # that hangs up mid-body as no error at all once the status line has arrived, so the body's
1316 # own framing (the chunked terminator, Content-Length) is the witness for that case; a
1317 # close-delimited body cannot be told apart from a complete one. A cut stream failed on
1318 # every face: the usage event and request.finish must not mean something different
1319 # depending on the client's dialect (ADR 0004).
1320 169 my $cut = 0;
1321 169 ▶ if ($headers_sent && !$had_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($headers_sent and not $had_error) 168 1 169
Condition66%2/3
$headers_sent and not $had_error
!ll&&!rl&&r
01168
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
1322 168 my $content = $tx_done->res->content;
1323 168 ▶ my $framed = $content->is_chunked || length($content->headers->content_length // '');
Condition100%5/5
$content->is_chunked || length($content->headers->content_length // '')
l!l&&r!l&&!r
141522
$content->headers->content_length // ""
l!l
1522
MC/DC100%2/2
$content->is_chunked || length($content->headers->content_length // '')
$content->is_chunked $content->headers->content_length
Truth table100%3/3
A || B
A= $content->is_chunkedB= $content->headers->content_length
ABresult
1X1
011
000
1324 168 ▶ $cut = $framed && !$content->is_finished;
Condition100%3/3
$framed && !$content->is_finished
!ll&&!rl&&r
214818
MC/DC100%2/2
$framed && !$content->is_finished
$framed !$content->is_finished
Truth table100%3/3
A && not(B)
A= $framedB= !$content->is_finished
ABresult
0X0
100
111
1325 168 ▶ $had_error = 1 if $cut;
Branch: 1 branch
BranchTrueFalseTotal
if $cut 18 150 168
1326 }
1327  
1328 # A translator that can say so in-band ends a failed stream with its error event instead of
1329 # a closing sequence that would read as a complete answer.
1330 169 ▶ if ($stream_errors && $headers_sent) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream_errors and $headers_sent) 126 43 169
Condition66%2/3
$stream_errors and $headers_sent
!ll&&!rl&&r
430126
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
1331 126 ▶ if ($had_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($had_error) 14 112 126
1332 14 ▶ my $reason = $cut ? 'Premature connection close' : ($tx_done->error->{message} // 'unknown');
Branch: 1 branch
BranchTrueFalseTotal
$cut ? : 14 0 14
Condition0%0/2
$tx_done->error->{"message"} // "unknown"
l!l
00
MC/DC0%0/1
$tx_done->error->{"message"} // "unknown"
$tx_done->error->{"message"}
Truth table0%0/2
A
A= $tx_done->error->{"message"}
Aresult
11
00
1333 14 my $frame = $stream->error_event(500, "Upstream error: $reason");
1334 14 ▶ if (length $frame) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $frame) 14 0 14
1335 14 push @queue, $frame;
1336 14 ▶ $drain->() unless $draining;
Branch: 1 branch
BranchTrueFalseTotal
unless $draining 13 1 14
1337 }
1338 }
1339 }
1340  
1341 # Finalize a translated stream before closing admission or recording its Usage event: a
1342 # translator can discover a terminal error only when it sees that no more upstream frames
1343 # are coming. Its tail is queued like any other chunk so it still lands after deltas already
1344 # in flight. Keep an unexpected finalizer exception inside the callback boundary and use the
1345 # translator's existing in-band error shape without reflecting internal details.
1346 169 ▶ if ($stream && $headers_sent) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream and $headers_sent) 126 43 169
Condition66%2/3
$stream and $headers_sent
!ll&&!rl&&r
430126
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
1347 126 my $tail = '';
1348 126 my $finalized = eval {
1349 126 $tail = $stream->finish;
1350 125 1;
1351 };
1352 126 ▶ unless ($finalized) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($finalized) 1 125 126
1353 1 $had_error = 1;
1354 1 ▶ $tail = eval { $stream_errors
Branch: 1 branch
BranchTrueFalseTotal
$stream_errors ? : 1 0 1
1355 ? $stream->error_event(500, 'Stream translation failed')
1356 : '' };
1357 }
1358 126 ▶ $tail = '' unless defined $tail;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tail 0 126 126
1359 126 ▶ if (length $tail) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $tail) 107 19 126
1360 107 push @queue, $tail;
1361 107 ▶ $drain->() unless $draining;
Branch: 1 branch
BranchTrueFalseTotal
unless $draining 45 62 107
1362 }
1363 }
1364  
1365 # An upstream that reported its failure inside the stream, or a translator that could only
1366 # detect one while finalizing, was answered with an error event; the request still failed.
1367 169 ▶ $had_error = 1 if $stream && $stream->can('errored') && $stream->errored;
Branch: 1 branch
BranchTrueFalseTotal
if $stream and $stream->can("errored") and $stream->errored 21 148 169
Condition83%5/6
$stream and $stream->can("errored") and $stream->errored
!ll&&!rl&&r
4310521
$stream and $stream->can("errored")
!ll&&!rl&&r
430126
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
1368  
1369 169 my $duration_ms = _duration_ms($started);
1370 169 ▶ $c->skeid->call_function('request.finish', {
Branch: 1 branch
BranchTrueFalseTotal
$had_error || $status >= 500 ? : 26 143 169
Condition66%2/3
$had_error or $status >= 500
l!l&&r!l&&!r
260143
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
1371 id => $node_id,
1372 ok => ($had_error || $status >= 500) ? 0 : 1,
1373 duration_ms => $duration_ms,
1374 });
1375  
1376 # Priced from whatever usage the stream carried, also when it was cut: a cut stream still
1377 # spent what its frames reported, and one that reported nothing records zero (ADR 0004).
1378 169 ▶ _record_usage_event($c, {
Branch: 1 branch
BranchTrueFalseTotal
$had_error || $status >= 500 ? : 26 143 169
Condition66%2/3
$had_error or $status >= 500
l!l&&r!l&&!r
260143
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
1379 %$meta,
1380 node_id => $node_id,
1381 status_code => $status,
1382 ok => ($had_error || $status >= 500) ? 0 : 1,
1383 duration_ms => $duration_ms,
1384 content_bytes => $content_bytes->(),
1385 metrics => _stream_metrics($c, $meta, $body, $duration_ms, $upstream_usage),
1386 });
1387  
1388 # Only finish once the queue has drained, or the tail of the stream is cut off. If the
1389 # drain loop is still running it will finish for us when it empties.
1390 169 $upstream_done = 1;
1391 169 ▶ if (!$draining && !$finished) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $draining || $finished) 23 146 169
Condition66%2/3
$draining || $finished
l!l&&r!l&&!r
146023
MC/DC50%1/2
$draining || $finished
$draining $finished
Truth table66%2/3
A || B
A= $drainingB= $finished
ABresult
1X1
011
000
1392 23 $finished = 1;
1393 23 $c->finish;
1394 23 undef $drain;
1395 }
1396 196 });
1397 221 });
1398 }
1399  
1400 # Renders an error in the shape of the face the client called. The Anthropic Messages face
1401 # gets Anthropic's envelope, {type: "error", error: {type, message}}, with the type taken from
1402 # the HTTP status, because that is what an Anthropic SDK parses and raises on (core karr #224).
1403 # The Ollama face gets Ollama's {error: "<message>"}, a plain string, because that is what the
1404 # Ollama clients decode (skeid #47). Every other face keeps the OpenAI shape it always had, with
1405 # $openai_type as its type. The face is read off the stash, which the /v1/messages and /api/*
1406 # routes set; a controller without one (a unit test's stand-in) is an OpenAI face.
1407 154 ▶sub _render_error {
Subroutine _render_error: called CC=5 SCAR=16.1
1408 154 my ($c, $status, $message, $openai_type) = @_;
1409 154 ▶ my $format = $c->can('stash') ? ($c->stash('skeid.error_format') // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
$c->can('stash') ? : 152 2 154
Condition100%2/2
$c->stash("skeid.error_format") // ""
l!l
10943
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
1410 154 ▶ if ($format eq 'anthropic') {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq "anthropic") 43 111 154
1411 43 $c->render(json => Langertha::Skeid::Protocol::Anthropic->error_body($status, $message),
1412 status => $status);
1413 43 return;
1414 }
1415 111 ▶ if ($format eq 'ollama') {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq "ollama") 66 45 111
1416 66 $c->render(json => Langertha::Skeid::Protocol::Ollama->error_body($message), status => $status);
1417 66 return;
1418 }
1419 45 $c->render(json => { error => { message => $message, type => $openai_type } }, status => $status);
1420 45 return;
1421 }
1422  
1423 # The message to put after "Upstream error: ". Mojo sets $err->{message} to the HTTP reason
1424 # phrase for a 4xx/5xx ("Bad Request"); the upstream usually said more in its own body, in the
1425 # OpenAI dialect every node speaks (ADR 0001), and that is what the client needs to act on.
1426 33 ▶sub _upstream_error_message {
Subroutine _upstream_error_message: called CC=9 SCAR=24.1
1427 33 my ($err, $body) = @_;
1428 33 ▶ my $json = (defined($body) && length($body)) ? eval { decode_json($body) } : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $body && length $body ? : 23 10 33
Condition66%2/3
defined $body and length $body
!ll&&!rl&&r
01023
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
1429 33 ▶ if (ref($json) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $json eq "HASH") 23 10 33
1430 23 my $e = $json->{error};
1431 23 ▶ my $msg = ref($e) eq 'HASH' ? $e->{message} : $e;
Branch: 1 branch
BranchTrueFalseTotal
ref $e eq 'HASH' ? : 23 0 23
1432 23 ▶ return "$msg" if defined($msg) && !ref($msg) && length($msg);
Branch: 1 branch
BranchTrueFalseTotal
if defined $msg and not ref $msg and length $msg 23 0 23
Condition33%2/6
defined $msg and not ref $msg and length $msg
!ll&&!rl&&r
0023
defined $msg and not ref $msg
!ll&&!rl&&r
0023
MC/DC0%0/3
defined $msg and not ref $msg and length $msg
defined $msg not ref $msg length $msg
Truth table25%1/4
A and not(B) and C
A= defined $msgB= not ref $msgC= length $msg
ABCresult
0XX0
10X0
1100
1111
1433 }
1434 10 ▶ return $err->{message} // 'unknown';
Condition50%1/2
$err->{"message"} // "unknown"
l!l
100
MC/DC0%0/1
$err->{"message"} // "unknown"
$err->{"message"}
Truth table50%1/2
A
A= $err->{"message"}
Aresult
11
00
1435 }
1436  
1437 93 ▶sub _render_upstream_response {
Subroutine _render_upstream_response: called CC=5 SCAR=16.2
1438 93 my ($c, $res, $node_id) = @_;
1439  
1440 93 $c->res->code($res->code);
1441 93 for my $name (@{$res->headers->names}) {
1442 416 my $lc = lc($name);
1443 416 ▶ next if $lc eq 'content-length' || $lc eq 'transfer-encoding' || $lc eq 'content-encoding';
Branch: 1 branch
BranchTrueFalseTotal
if $lc eq "content-length" or $lc eq "transfer-encoding" or $lc eq "content-encoding" 93 323 416
Condition66%4/6
$lc eq "content-length" or $lc eq "transfer-encoding" or $lc eq "content-encoding"
l!l&&r!l&&!r
930323
$lc eq "content-length" or $lc eq "transfer-encoding"
l!l&&r!l&&!r
930323
MC/DC33%1/3
$lc eq "content-length" or $lc eq "transfer-encoding" or $lc eq "content-encoding"
$lc eq "content-length" $lc eq "transfer-encoding" $lc eq "content-encoding"
Truth table50%2/4
A or B or C
A= $lc eq "content-length"B= $lc eq "transfer-encoding"C= $lc eq "content-encoding"
ABCresult
1XX1
01X1
0011
0000
1444 323 $c->res->headers->header($name => $res->headers->header($name));
1445 }
1446 93 $c->res->headers->header('x-skeid-node' => $node_id);
1447 93 $c->res->headers->header('x-request-id' => _request_id($c));
1448 93 $c->res->body($res->body);
1449 93 $c->rendered;
1450 }
1451  
1452 # Hop-by-hop headers describe the client's connection to Skeid, not the request. Forwarding
1453 # them upstream is wrong per RFC 7230 and expensive here in particular: a client that sends
1454 # `Connection: close` -- most benchmark tools and plenty of HTTP libraries do -- made Skeid
1455 # tear down its own upstream connection after every single request, so the connection pool
1456 # never held anything and each request paid for a fresh TCP handshake.
1457 47 my %HOP_BY_HOP = map { $_ => 1 } qw(
1458 connection
1459 keep-alive
1460 proxy-authenticate
1461 proxy-authorization
1462 te
1463 trailer
1464 transfer-encoding
1465 upgrade
1466 );
1467  
1468 466 ▶sub _forward_headers {
Subroutine _forward_headers: called CC=6 SCAR=17.9
1469 466 my ($c) = @_;
1470 466 my %fwd_headers;
1471 466 for my $name (@{$c->req->headers->names}) {
1472 2592 my $lc = lc($name);
1473 2592 ▶ next if $HOP_BY_HOP{$lc};
Branch: 1 branch
BranchTrueFalseTotal
if $HOP_BY_HOP{$lc} 0 2592 2592
1474 2592 ▶ 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" 1388 1204 2592
Condition100%6/6
$lc eq "host" or $lc eq "content-length" or $lc eq "accept-encoding"
l!l&&r!l&&!r
9324561204
$lc eq "host" or $lc eq "content-length"
l!l&&r!l&&!r
4664661660
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
1475 1204 $fwd_headers{$name} = $c->req->headers->header($name);
1476 }
1477 466 return %fwd_headers;
1478 }
1479  
1480 # Sets the upstream Authorization header for the selected node, from the KeyBroker
1481 # (api_key_ref) or from the environment (api_key_env), overriding whatever the client sent.
1482 # The callback runs exactly once, and always. It is called with nothing when the request may go
1483 # upstream: the node's key is in place, or the node names no key source and forwards the
1484 # client's header untouched. It is called with a reason when the node names a key source and
1485 # none produced a key, or when the node is no longer in the inventory and what it named cannot
1486 # be known -- the caller must then refuse the request (_refuse_unkeyed_node) rather than call
1487 # the node, because the only credential left in the headers is the customer's own, and the
1488 # pass-through would hand it to the provider (ADR 0003). The reason names the node, the key
1489 # reference and the variable, never a key, and is for the log and the usage event.
1490 #
1491 # Wherever the client's header is not what goes upstream -- a key was injected, or the request
1492 # is refused -- the client's credentials are taken out of the headers first, in any spelling.
1493 #
1494 # Async because resolution can mean a vault round-trip, and this sits between routing and the
1495 # upstream call -- doing it synchronously stalls every other in-flight request for that
1496 # round-trip (ADR 0005). key_async answers from cache without touching the loop, so the
1497 # blocking case is a cold cache, and even then only one request per reference pays for it.
1498 482 ▶sub _inject_node_auth_async {
Subroutine _inject_node_auth_async: called CC=10 SCAR=23.1
1499 482 my ($headers_ref, $skeid, $node_id, $cb) = @_;
1500 482 ▶ $cb ||= sub { };
Subroutine __ANON__: not called CC=1 SCAR=1.2
Condition33%1/3
$cb ||= sub {
l!l&&r!l&&!r
48200
MC/DC0%0/2
$cb ||= sub { }
$cb sub { }
Truth table33%1/3
A ||= B
A= $cbB= sub { }
ABresult
1X1
011
000
1501  
1502 482 ▶ my ($node) = grep { ($_->{id} // '') eq $node_id } @{$skeid->nodes};
Condition50%1/2
$_->{"id"} // ""
l!l
14970
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
1503 482 ▶ unless ($node) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($node) 10 472 482
1504 10 _drop_client_credentials($headers_ref);
1505 10 return $cb->("node '$node_id' is no longer in the inventory, its key source is unknown");
1506 }
1507  
1508 472 my $ref = $node->{api_key_ref};
1509 472 ▶ $ref = undef unless defined($ref) && length($ref);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ref and length $ref 383 89 472
Condition66%2/3
defined $ref and length $ref
!ll&&!rl&&r
383089
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
1510 472 my $env_name = $node->{api_key_env};
1511 472 ▶ $env_name = undef unless defined($env_name) && length($env_name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $env_name and length $env_name 405 67 472
Condition66%2/3
defined $env_name and length $env_name
!ll&&!rl&&r
405067
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
1512  
1513 472 ▶ my $apply = sub {
Subroutine __ANON__: called CC=12 SCAR=24.9
1514 472 my ($key, $ref_failure) = @_;
1515  
1516 # Fallback: env var
1517 472 ▶ if (!defined($key) || !length($key)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $key and length $key) 427 45 472
Condition66%2/3
defined $key and length $key
!ll&&!rl&&r
427045
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
1518 427 ▶ if (defined $env_name) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $env_name) 67 360 427
1519 67 ▶ $key = $ENV{$env_name} // '';
Condition100%2/2
$ENV{$env_name} // ""
l!l
4819
MC/DC100%1/1
$ENV{$env_name} // ""
$ENV{$env_name}
Truth table100%2/2
A
A= $ENV{$env_name}
Aresult
11
00
1520 }
1521 }
1522  
1523 472 ▶ if (defined($key) && length($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key and length $key) 83 389 472
Condition100%3/3
defined $key and length $key
!ll&&!rl&&r
3602983
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
1524 83 _drop_client_credentials($headers_ref);
1525 83 $headers_ref->{Authorization} = "Bearer $key";
1526 83 return $cb->();
1527 }
1528  
1529 # A node with no key of its own: the documented pass-through.
1530 389 ▶ return $cb->() unless defined($ref) || defined($env_name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ref or defined $env_name 337 52 389
Condition100%3/3
defined $ref or defined $env_name
l!l&&r!l&&!r
3418337
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
1531  
1532 # A key source was named and produced nothing. Take the client's credentials out of what
1533 # would go upstream as well, so a caller that ignored the reason still could not leak them.
1534 52 _drop_client_credentials($headers_ref);
1535 $cb->(join('; ',
1536 (defined($ref) ? "api_key_ref '$ref' $ref_failure" : ()),
1537 (defined($env_name)
1538 52 ▶ ? "api_key_env '$env_name' is " . (defined($ENV{$env_name}) ? 'empty' : 'not set')
Branch: 3 branches
BranchTrueFalseTotal
defined $ref ? : 34 18 52
defined $env_name ? : 29 23 52
defined $ENV{$env_name} ? : 10 19 29
1539 : ()),
1540 ));
1541 472 };
1542  
1543 472 ▶ if (defined($ref) && $skeid->has_key_broker) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ref and $skeid->has_key_broker) 79 393 472
Condition100%3/3
defined $ref and $skeid->has_key_broker
!ll&&!rl&&r
3831079
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
1544 79 ▶ $skeid->key_broker->key_async($ref, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1545 79 my ($key, $error) = @_;
1546 # The reference may be logged; what it resolves to may not, and neither may a vault
1547 # response body that might carry it (ADR 0003).
1548 79 ▶ warn "KeyBroker resolve failed for '$ref': $error"
Branch: 1 branch
BranchTrueFalseTotal
if defined $error and not defined $key 32 47 79
Condition66%2/3
defined $error and not defined $key
!ll&&!rl&&r
47032
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
1549 if defined($error) && !defined($key);
1550 79 $apply->($key, 'did not resolve');
1551 79 });
1552 79 return;
1553 }
1554  
1555 393 $apply->(undef, 'has no key broker to resolve it');
1556 393 return;
1557 }
1558  
1559 # Header names are case-insensitive and Mojolicious hands an unknown one on as the client
1560 # spelled it, so `X-Api-Key` is as much the client's key as `x-api-key`. An exact-case delete
1561 # lets it travel upstream beside the node's own key.
1562 145 ▶sub _drop_client_credentials {
Subroutine _drop_client_credentials: called CC=2 SCAR=6.9
1563 145 my ($headers_ref) = @_;
1564 145 delete @{$headers_ref}{
1565 145 ▶ 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
12276282
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
1566 };
1567 145 return;
1568 }
1569  
1570 # The answer to a request whose node names a key source that produced no key: no upstream call,
1571 # and everything an admitted request is owed -- its request.finish, one usage event, an error in
1572 # the shape of the face that was called. 503, not 502: no upstream was asked, so nothing came
1573 # back bad; this Skeid cannot serve the request until its broker or its environment is put
1574 # right, and a client may retry. The client is told no more than that -- the reason carries a
1575 # key reference, which belongs in the log and the usage event, not in a customer's answer.
1576 54 ▶sub _refuse_unkeyed_node {
Subroutine _refuse_unkeyed_node: called CC=1 SCAR=0.0
1577 54 my ($c, $node_id, $started, $meta, $reason) = @_;
1578 54 my $duration_ms = _duration_ms($started);
1579 54 $c->app->log->error("No upstream key for node '$node_id', request refused: $reason");
1580 54 $c->skeid->call_function('request.finish', {
1581 id => $node_id,
1582 ok => 0,
1583 duration_ms => $duration_ms,
1584 });
1585 54 _record_usage_event($c, {
1586 %$meta,
1587 node_id => $node_id,
1588 status_code => 503,
1589 ok => 0,
1590 duration_ms => $duration_ms,
1591 error_type => 'upstream_key_unavailable',
1592 error_message => $reason,
1593 metrics => {},
1594 });
1595 54 _render_error($c, 503, 'The upstream key for this model is not available',
1596 'upstream_key_unavailable');
1597 54 return;
1598 }
1599  
1600 # The free capacity probe (ADR 0009): a commercial provider will not tell us its queue depth,
1601 # but it puts its rate-limit state on every response we already have in hand. Reading it costs
1602 # no extra request -- which is the whole reason this is worth doing on the request path at all.
1603 #
1604 # Pulls the handful of headers by name rather than walking all of them; this runs per response.
1605 47 my @CAPACITY_HEADERS = Langertha::Skeid->capacity_header_names;
1606  
1607 396 ▶sub _observe_capacity {
Subroutine _observe_capacity: called CC=10 SCAR=23.8
1608 396 my ($c, $node_id, $res) = @_;
1609 396 ▶ return unless defined($node_id) && length($node_id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 396 396
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
00396
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
1610 396 ▶ return unless $res;
Branch: 1 branch
BranchTrueFalseTotal
unless $res 0 396 396
1611 396 ▶ my $headers = $res->headers or return;
Branch: 1 branch
BranchTrueFalseTotal
my $headers = $res->headers or return 396 0 396
1612  
1613 396 my %found;
1614 396 for my $name (@CAPACITY_HEADERS) {
1615 5940 my $value = $headers->header($name);
1616 5940 ▶ $found{$name} = $value if defined $value;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 7 5933 5940
1617 }
1618 396 ▶ my $status = $res->code // 0;
Condition100%2/2
$res->code // 0
l!l
38610
MC/DC100%1/1
$res->code // 0
$res->code
Truth table100%2/2
A
A= $res->code
Aresult
11
00
1619 396 ▶ return unless %found || $status == 429;
Branch: 1 branch
BranchTrueFalseTotal
unless %found or $status == 429 391 5 396
Condition66%2/3
%found or $status == 429
l!l&&r!l&&!r
50391
MC/DC50%1/2
%found or $status == 429
%found $status == 429
Truth table66%2/3
A or B
A= %foundB= $status == 429
ABresult
1X1
011
000
1620  
1621 5 $c->skeid->call_function('capacity.observe', {
1622 id => $node_id,
1623 headers => \%found,
1624 status => $status,
1625 });
1626 5 return;
1627 }
1628  
1629 728 ▶sub _extract_request_api_key {
Subroutine _extract_request_api_key: called CC=4 SCAR=13.9
1630 728 my ($c) = @_;
1631 728 my $auth = $c->req->headers->authorization;
1632 728 my $x_api_key = $c->req->headers->header('x-api-key');
1633 728 ▶ my $raw = defined($auth) ? $auth : (defined($x_api_key) ? $x_api_key : '');
Branch: 2 branches
BranchTrueFalseTotal
defined $auth ? : 266 462 728
defined $x_api_key ? : 62 400 462
1634 728 ▶ my $api_key = $raw // '';
Condition50%1/2
$raw // ""
l!l
7280
MC/DC0%0/1
$raw // ""
$raw
Truth table50%1/2
A
A= $raw
Aresult
11
00
1635 728 $api_key =~ s/^Bearer\s+//i;
1636 728 return ($raw, $api_key);
1637 }
1638  
1639 # Who the caller is. Everything downstream hangs off this: the routing policy that decides
1640 # which nodes they may reach, and the usage event they get billed for. So it may only be
1641 # derived from something the caller had to prove -- the key they presented.
1642 #
1643 # x-skeid-key-id is honoured only when the deployment says it authenticates the caller before
1644 # Skeid sees the request (routing.trust_key_id_header). Believing it unconditionally would let
1645 # any client name itself into another customer's policy, and into another customer's bill.
1646 730 ▶sub _request_api_key_id {
Subroutine _request_api_key_id: called CC=5 SCAR=17.5
1647 730 my ($c) = @_;
1648  
1649 730 ▶ if ($c->skeid->trust_key_id_header) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->skeid->trust_key_id_header) 2 728 730
1650 2 ▶ my $forced = $c->req->headers->header('x-skeid-key-id')
Condition33%1/3
$c->req->headers->header("x-skeid-key-id") // $c->req->headers->header("x-api-key-id")
l!l&&r!l&&!r
200
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 table33%1/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
1651 // $c->req->headers->header('x-api-key-id');
1652 2 ▶ return $forced if defined($forced) && length($forced);
Branch: 1 branch
BranchTrueFalseTotal
if defined $forced and length $forced 2 0 2
Condition33%1/3
defined $forced and length $forced
!ll&&!rl&&r
002
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
1653 }
1654  
1655 728 my (undef, $api_key) = _extract_request_api_key($c);
1656 728 return $c->skeid->key_id_for_key($api_key);
1657 }
1658  
1659 # The id taken when the request arrived; a client's own x-request-id is taken over, else one is
1660 # made up. Before that hook ran (a bare controller) it is worked out from the request, and once
1661 # the transaction is gone it must come from the stash.
1662 1615 ▶sub _request_id {
Subroutine _request_id: called CC=5 SCAR=16.2
1663 1615 my ($c) = @_;
1664 1615 my $kept = $c->stash('skeid.request_id');
1665 1615 ▶ return $kept if defined($kept) && length($kept);
Branch: 1 branch
BranchTrueFalseTotal
if defined $kept and length $kept 752 863 1615
Condition66%2/3
defined $kept and length $kept
!ll&&!rl&&r
8630752
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
1666 863 my $rid = $c->req->headers->header('x-request-id');
1667 863 ▶ return $rid if defined($rid) && length($rid);
Branch: 1 branch
BranchTrueFalseTotal
if defined $rid and length $rid 20 843 863
Condition66%2/3
defined $rid and length $rid
!ll&&!rl&&r
843020
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
1668 843 return 'req_' . int(time * 1000) . '_' . int(rand(1_000_000));
1669 }
1670  
1671 463 ▶sub _record_usage_event {
Subroutine _record_usage_event: called CC=35 SCAR=43.9
1672 463 my ($c, $args) = @_;
1673 463 ▶ $args ||= {};
Condition50%1/2
$args ||= {}
l!l
4630
MC/DC0%0/1
$args ||= {}
$args
Truth table50%1/2
A
A= $args
Aresult
11
00
1674 463 ▶ my $metrics = ref($args->{metrics}) eq 'HASH' ? $args->{metrics} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $args->{'metrics'} eq 'HASH' ? : 463 0 463
1675 463 ▶ my $usage = ref($metrics->{usage}) eq 'HASH' ? $metrics->{usage} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $metrics->{'usage'} eq 'HASH' ? : 0 463 463
1676 my $safe_metrics = {
1677 %$metrics,
1678 usage => {
1679 input => 0 + ($usage->{input} // $usage->{prompt_tokens} // 0),
1680 output => 0 + ($usage->{output} // $usage->{completion_tokens} // 0),
1681 total => 0 + ($usage->{total} // 0),
1682 # This reshaping drops prompt_tokens_details, so the cache count has to be carried across
1683 # it explicitly or record_usage never sees it. Both paths carry it as a flat
1684 # metrics->{cached_tokens}, from metrics.normalize or the raw payload (k27, skeid #41).
1685 463 ▶ cached => (_cached_tokens($usage) || 0 + ($metrics->{cached_tokens} // 0)),
Condition52%9/17
($usage->{"input"} // $usage->{"prompt_tokens"}) // 0
l!l
0463
$usage->{"input"} // $usage->{"prompt_tokens"}
l!l&&r!l&&!r
00463
($usage->{"output"} // $usage->{"completion_tokens"}) // 0
l!l
0463
$usage->{"output"} // $usage->{"completion_tokens"}
l!l&&r!l&&!r
00463
$usage->{"total"} // 0
l!l
0463
_cached_tokens($usage) || 0 + ($metrics->{'cached_tokens'} // 0)
l!l&&r!l&&!r
0101362
$metrics->{"cached_tokens"} // 0
l!l
101362
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
1686 },
1687 };
1688  
1689 463 my $request_id = _request_id($c);
1690 463 my $recorded = eval {
1691 $c->skeid->call_function('usage.record', {
1692 created_at => Langertha::Skeid::Protocol::iso8601_now(),
1693 request_id => $request_id,
1694 api_format => ($args->{api_format} // ''),
1695 requested_model => ($args->{requested_model} // $args->{model} // ''),
1696 endpoint => ($args->{endpoint} // ''),
1697 api_key_id => ($args->{api_key_id} // 'anonymous'),
1698 provider => ($args->{provider} // 'skeid'),
1699 engine => ($args->{engine} // ''),
1700 model => ($args->{model} // ''),
1701 node_id => ($args->{node_id} // ''),
1702 route_url => ($args->{route_url} // ''),
1703 status_code => 0 + ($args->{status_code} // 0),
1704 ok => ($args->{ok} ? 1 : 0),
1705 duration_ms => 0 + ($args->{duration_ms} // 0),
1706 error_type => ($args->{error_type} // ''),
1707 error_message => ($args->{error_message} // ''),
1708 # Streamed requests only; absent otherwise, so the event says "not measured" (skeid #36).
1709 463 ▶ (defined($args->{content_bytes}) ? (content_bytes => 0 + $args->{content_bytes}) : ()),
Branch: 2 branches
BranchTrueFalseTotal
$args->{'ok'} ? : 334 129 463
defined $args->{'content_bytes'} ? : 196 267 463
Condition55%16/29
$args->{"api_format"} // ""
l!l
4630
($args->{"requested_model"} // $args->{"model"}) // ""
l!l
4630
$args->{"requested_model"} // $args->{"model"}
l!l&&r!l&&!r
46300
$args->{"endpoint"} // ""
l!l
4630
$args->{"api_key_id"} // "anonymous"
l!l
4630
$args->{"provider"} // "skeid"
l!l
4630
$args->{"engine"} // ""
l!l
4630
$args->{"model"} // ""
l!l
4630
$args->{"node_id"} // ""
l!l
4630
$args->{"route_url"} // ""
l!l
4630
$args->{"status_code"} // 0
l!l
4630
$args->{"duration_ms"} // 0
l!l
4630
$args->{"error_type"} // ""
l!l
103360
$args->{"error_message"} // ""
l!l
103360
MC/DC0%0/1
$args->{"api_format"} // ""
$args->{"api_format"}
MC/DC0%0/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/DC0%0/1
$args->{"engine"} // ""
$args->{"engine"}
MC/DC0%0/1
$args->{"model"} // ""
$args->{"model"}
MC/DC0%0/1
$args->{"node_id"} // ""
$args->{"node_id"}
MC/DC0%0/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 table33%1/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 table50%1/2
A
A= $args->{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $args->{"model"}
Aresult
11
00
Truth table50%1/2
A
A= $args->{"node_id"}
Aresult
11
00
Truth table50%1/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
1710 metrics => $safe_metrics,
1711 });
1712 };
1713 463 my $err;
1714 463 ▶ if ($@) {
Branch: 2 branches
BranchTrueFalseTotal
if ($@) { } 0 463 463
elsif (ref $recorded eq 'HASH' and not $recorded->{'ok'} and $recorded->{'enabled'} // 1) { } 3 896 899
1715 0 $err = "$@";
1716 0 $recorded = { ok => 0, error => $err };
1717 ▶ } 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
436243
ref $recorded eq "HASH" and not $recorded->{"ok"}
!ll&&!rl&&r
043627
$recorded->{"enabled"} // 1
l!l
243
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
1718 # A store reports a failed write in its answer (the JsonLog contract); no sink at all
1719 # answers enabled => 0 and has nothing to lose.
1720 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
1721 }
1722 463 ▶ if (defined $err) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $err) 3 460 463
1723 _log_lost_usage_event($c->app, $c->skeid, {
1724 request_id => $request_id,
1725 api_key_id => ($args->{api_key_id} // 'anonymous'),
1726 model => $args->{model},
1727 status_code => $args->{status_code},
1728 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
1729 }
1730  
1731 463 return $recorded;
1732 }
1733  
1734 # The event is the billing unit (ADR 0004) and it is gone: say so at a level production keeps,
1735 # with what an operator needs to reconcile it by hand. The request id and the key id, never the
1736 # key -- the key id is a digest (ADR 0016), the key is a secret (ADR 0003). One line for both
1737 # ways an event is lost: a write that failed while the request waited, and a queued one a
1738 # write-behind flush could not write later (skeid k78).
1739 4 ▶sub _log_lost_usage_event {
Subroutine _log_lost_usage_event: called CC=6 SCAR=19.9
1740 4 my ($app, $skeid, $event, $err) = @_;
1741 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
1742 4 $err =~ s/\s+$//;
1743 $app->log->error('usage event lost: request_id=' . ($event->{request_id} // '')
1744 . ' store=' . _usage_sink_name($skeid)
1745 . ' api_key_id=' . ($event->{api_key_id} // 'anonymous')
1746 . ' model=' . ($event->{model} // '')
1747 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
1748 . ': ' . $err);
1749 4 return;
1750 }
1751  
1752 # Which sink a lost usage event was meant for, for the log line: the store's backend name, or
1753 # how the embedding application took the event over. Never the DSN or path, which may carry
1754 # credentials.
1755 4 ▶sub _usage_sink_name {
Subroutine _usage_sink_name: called CC=5 SCAR=17.5
1756 4 my ($skeid) = @_;
1757 4 ▶ return 'store_usage_event' if $skeid->has_store_usage_event;
Branch: 1 branch
BranchTrueFalseTotal
if $skeid->has_store_usage_event 1 3 4
1758 3 my $cfg = $skeid->usage_store;
1759 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
1760 }
1761  
1762 # The prompt-cache read count off a raw OpenAI-shaped upstream usage hash (k27). OpenAI nests it
1763 # under prompt_tokens_details.cached_tokens; some OpenAI-compatible servers expose a flat
1764 # cached_tokens, an Anthropic-spelled block cache_read_input_tokens, and a caller of usage.record may pass it as `cached`. Missing -> 0, the
1765 # same fault-tolerance the other token reads here have. This reads a count off a response Skeid
1766 # already holds -- every upstream answers in the OpenAI dialect (ADR 0001) -- it does not
1767 # translate a client format. Both paths prefer the count metrics.normalize reads through
1768 # Langertha::Usage and prices (skeid #28, #41); this is the fallback on Langertha 0.503.
1769 698 ▶sub _cached_tokens {
Subroutine _cached_tokens: called CC=7 SCAR=19.5
1770 698 my ($usage) = @_;
1771 698 ▶ return 0 unless ref($usage) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $usage eq "HASH" 1 697 698
1772 697 my $details = $usage->{prompt_tokens_details};
1773 return 0 + ($usage->{cached}
1774 // $usage->{cached_tokens}
1775 // (ref($details) eq 'HASH' ? $details->{cached_tokens} : undef)
1776 // $usage->{cache_read_input_tokens}
1777 697 ▶ // 0);
Branch: 1 branch
BranchTrueFalseTotal
ref $details eq 'HASH' ? : 1 694 695
Condition90%10/11
((($usage->{"cached"} // $usage->{"cached_tokens"}) // (ref $details eq "HASH" ? $details->{"cached_tokens"} : undef)) // $usage->{"cache_read_input_tokens"}) // 0
l!l
3694
(($usage->{"cached"} // $usage->{"cached_tokens"}) // (ref $details eq "HASH" ? $details->{"cached_tokens"} : undef)) // $usage->{"cache_read_input_tokens"}
l!l&&r!l&&!r
30694
($usage->{"cached"} // $usage->{"cached_tokens"}) // (ref $details eq "HASH" ? $details->{"cached_tokens"} : undef)
l!l&&r!l&&!r
21694
$usage->{"cached"} // $usage->{"cached_tokens"}
l!l&&r!l&&!r
11695
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
1778 }
1779  
1780 # Prices an upstream answer: its usage block goes through metrics.normalize (Langertha::Usage +
1781 # Langertha::Pricing), the one pricing path for every face, streamed or not (skeid #28, #41).
1782 # $payload is the decoded upstream body, or for a stream a body holding only the usage block
1783 # the stream carried -- the same usage, so the same cost.
1784 330 ▶sub _priced_metrics {
Subroutine _priced_metrics: called CC=12 SCAR=27.5
1785 330 my ($c, $meta, $body, $duration_ms, $payload, $tool_calls) = @_;
1786 330 my $metrics = eval {
1787 $c->skeid->call_function('metrics.normalize', {
1788 provider => ($meta->{provider} || 'skeid'),
1789 engine => ($meta->{engine} || 'openaibase'),
1790 model => ($meta->{model} || ($body->{model} // '')),
1791 330 ▶ route => ($meta->{endpoint} || ''),
Condition46%6/13
$meta->{'provider'} || 'skeid'
l!l
3300
$meta->{'engine'} || 'openaibase'
l!l
3300
$meta->{'model'} || ($body->{'model'} // '')
l!l&&r!l&&!r
33000
$body->{"model"} // ""
l!l
00
$meta->{'endpoint'} || ''
l!l
3300
$tool_calls || []
l!l
190140
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
1792 duration_ms => $duration_ms,
1793 response => $payload,
1794 tool_calls => ($tool_calls || []),
1795 });
1796 };
1797 330 ▶ $metrics = {} unless ref($metrics) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $metrics eq "HASH" 0 330 330
1798 # metrics.normalize reports the prompt-cache counts off Langertha::Usage, from every wire
1799 # spelling it knows (skeid #28). Langertha 0.503's Usage has no such counts, so there they are
1800 # pulled straight off the raw upstream usage and carried flat, the way input/output survive
1801 # as metrics->{*_tokens} (k27).
1802 330 ▶ if (!defined $metrics->{cached_tokens}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $metrics->{"cached_tokens"}) 229 101 330
1803 229 my $cached = _cached_tokens($payload->{usage});
1804 229 ▶ $metrics->{cached_tokens} = $cached if $cached;
Branch: 1 branch
BranchTrueFalseTotal
if $cached 0 229 229
1805 }
1806 330 ▶ if (!defined $metrics->{cache_write_tokens}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $metrics->{"cache_write_tokens"}) 234 96 330
1807 234 my $written = _cache_write_tokens($payload->{usage});
1808 234 ▶ $metrics->{cache_write_tokens} = $written if $written;
Branch: 1 branch
BranchTrueFalseTotal
if $written 0 234 234
1809 }
1810 330 return $metrics;
1811 }
1812  
1813 # A stream's metrics: its verbatim usage priced exactly as a non-streamed body carrying it would
1814 # be. A stream that carried no usage has nothing to price -- no token count or cost is invented.
1815 196 ▶sub _stream_metrics {
Subroutine _stream_metrics: called CC=2 SCAR=6.9
1816 196 my ($c, $meta, $body, $duration_ms, $usage) = @_;
1817 196 ▶ return {} unless ref($usage) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $usage eq "HASH" 56 140 196
1818 140 return _priced_metrics($c, $meta, $body, $duration_ms, { usage => $usage });
1819 }
1820  
1821 # Folds one stream frame's usage block into what the stream reported so far, key by key, a later
1822 # frame's value replacing an earlier one (nested blocks such as prompt_tokens_details likewise).
1823 # Usage counts on a stream are running totals, never increments: OpenAI's final frame carries
1824 # the whole request, a server that reports on every chunk repeats the growing total, and a wire
1825 # that splits the block (input on the first frame, output on the last) is completed rather
1826 # than lost. Summing frames would bill the same tokens twice.
1827 226 ▶sub _merge_usage {
Subroutine _merge_usage: called CC=6 SCAR=17.9
1828 226 my ($into, $frame) = @_;
1829 226 ▶ my %merged = ref($into) eq 'HASH' ? %$into : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $into eq 'HASH' ? : 86 140 226
1830 226 for my $key (keys %$frame) {
1831 697 my $value = $frame->{$key};
1832 697 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 697 697
1833 $merged{$key} = (ref($value) eq 'HASH' && ref($merged{$key}) eq 'HASH')
1834 697 ▶ ? _merge_usage($merged{$key}, $value)
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'HASH' && ref $merged{$key} eq 'HASH' ? : 36 661 697
Condition100%3/3
ref $value eq "HASH" and ref $merged{$key} eq "HASH"
!ll&&!rl&&r
6184336
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
1835 : $value;
1836 }
1837 226 return \%merged;
1838 }
1839  
1840 # The prompt-cache write count off a raw upstream usage hash, for a Langertha that cannot read it
1841 # itself (0.503): OpenAI Chat nests it under prompt_tokens_details.cache_write_tokens, an
1842 # Anthropic-shaped block carries cache_creation_input_tokens. Missing -> 0. A count, never priced
1843 # here -- pricing is Langertha::Pricing's (skeid #41).
1844 234 ▶sub _cache_write_tokens {
Subroutine _cache_write_tokens: called CC=6 SCAR=20.7
1845 234 my ($usage) = @_;
1846 234 ▶ return 0 unless ref($usage) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $usage eq "HASH" 0 234 234
1847 234 my $details = $usage->{prompt_tokens_details};
1848 return 0 + ((ref($details) eq 'HASH' ? $details->{cache_write_tokens} : undef)
1849 // $usage->{cache_write_tokens}
1850 // $usage->{cache_creation_input_tokens}
1851 234 ▶ // 0);
Branch: 1 branch
BranchTrueFalseTotal
ref $details eq 'HASH' ? : 5 229 234
Condition37%3/8
(((ref $details eq "HASH" ? $details->{"cache_write_tokens"} : undef) // $usage->{"cache_write_tokens"}) // $usage->{"cache_creation_input_tokens"}) // 0
l!l
0234
((ref $details eq "HASH" ? $details->{"cache_write_tokens"} : undef) // $usage->{"cache_write_tokens"}) // $usage->{"cache_creation_input_tokens"}
l!l&&r!l&&!r
00234
(ref $details eq "HASH" ? $details->{"cache_write_tokens"} : undef) // $usage->{"cache_write_tokens"}
l!l&&r!l&&!r
00234
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
1852 }
1853  
1854 # The model a tier asks its nodes for. Falls back to what the client requested, which is what
1855 # makes an aliasless deployment behave exactly as it did before tiers existed.
1856 466 ▶sub _served_model {
Subroutine _served_model: called CC=4 SCAR=15.6
1857 466 my ($tier, $requested) = @_;
1858 466 ▶ return $requested unless ref($tier) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tier eq "HASH" 0 466 466
1859 466 my $model = $tier->{model};
1860 466 ▶ return (defined($model) && length($model)) ? $model : $requested;
Branch: 1 branch
BranchTrueFalseTotal
defined $model && length $model ? : 466 0 466
Condition33%1/3
defined $model and length $model
!ll&&!rl&&r
00466
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
1861 }
1862  
1863 468 ▶sub _endpoint_url_for_node {
Subroutine _endpoint_url_for_node: called CC=6 SCAR=19.1
1864 468 my ($base, $path) = @_;
1865 468 ▶ $base //= '';
Condition50%1/2
$base //= ""
l!l
4680
MC/DC0%0/1
$base //= ""
$base
Truth table50%1/2
A
A= $base
Aresult
11
00
1866 468 ▶ $path //= '';
Condition50%1/2
$path //= ""
l!l
4680
MC/DC0%0/1
$path //= ""
$path
Truth table50%1/2
A
A= $path
Aresult
11
00
1867 468 $base =~ s{/\z}{};
1868  
1869 468 ▶ return $base . $path if $base =~ m{/v1\z} && $path =~ m{^/};
Branch: 1 branch
BranchTrueFalseTotal
if $base =~ m[/v1\z] and $path =~ m[^/] 467 1 468
Condition66%2/3
$base =~ m[/v1\z] and $path =~ m[^/]
!ll&&!rl&&r
10467
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
1870 1 ▶ return $base . '/v1' . $path if $path =~ m{^/};
Branch: 1 branch
BranchTrueFalseTotal
if $path =~ m[^/] 1 0 1
1871 0 return $base . '/v1/' . $path;
1872 }
1873  
1874 482 ▶sub _duration_ms {
Subroutine _duration_ms: called CC=1 SCAR=0.0
1875 482 my ($started) = @_;
1876 482 return int((time - $started) * 1000);
1877 }
1878  
1879  
1880 47 1;
1881  
1882 __END__
1883  
1884 =pod
1885  
1886 =encoding UTF-8
1887  
1888 =head1 NAME
1889  
1890 Langertha::Skeid::Proxy - Multi-format LLM proxy (OpenAI, Anthropic, Ollama) powered by Langertha::Skeid routing
1891  
1892 =head1 VERSION
1893  
1894 version 0.003
1895  
1896 =head1 SYNOPSIS
1897  
1898 use Langertha::Skeid::Proxy;
1899 use Mojo::Server::Daemon;
1900  
1901 my $app = Langertha::Skeid::Proxy->build_app(config_file => '/etc/skeid/skeid.yaml');
1902 Mojo::Server::Daemon->new(app => $app, listen => ['http://127.0.0.1:8090'])->run;
1903  
1904 # or simply
1905 skeid serve --config /etc/skeid/skeid.yaml --listen 127.0.0.1:8090
1906  
1907 =head1 DESCRIPTION
1908  
1909 The Mojolicious application in front of L<Langertha::Skeid>. It speaks three client formats --
1910 OpenAI, Anthropic and Ollama -- and makes one kind of upstream call, an OpenAI-shaped C<POST> to
1911 the node routing picked (ADR 0001); the translation lives in L<Langertha::Skeid::Protocol> and
1912 its per-format modules. Everything else -- nodes, routing, admission, pricing, usage -- is the
1913 control plane's, driven through L<Langertha::Skeid/call_function>, and is configured there (see
1914 L<Langertha::Skeid/CONFIGURATION>). C<skeid serve> runs it.
1915  
1916 The request path is asynchronous throughout (ADR 0005): waiting for capacity is a timer, key
1917 resolution goes through L<Langertha::Skeid::KeyBroker/key_async>, and the upstream call never
1918 blocks the loop.
1919  
1920 =head2 Client routes
1921  
1922 No Skeid credential is needed on these; see L</Customer identity>.
1923  
1924 GET /health {status: ok, proxy: skeid, config_reload: {...}}
1925 GET /.well-known/langertha.json provider manifest for the presented key
1926 GET /v1/models OpenAI: node models and alias names, once each
1927 POST /v1/chat/completions OpenAI chat; a stream is relayed byte for byte
1928 POST /v1/embeddings OpenAI embeddings
1929 POST /v1/messages Anthropic Messages, streamed or not
1930 POST /api/chat Ollama chat; streams unless "stream": false
1931 POST /api/generate Ollama generate; streams unless "stream": false
1932 GET /api/tags Ollama: the same names as /v1/models
1933 GET /api/ps Ollama: always an empty list
1934  
1935 C</health> stays C<ok> while a config reload is failing -- the proxy serves under the config it
1936 kept -- and shows the reload state without its message. C</v1/models> and C</api/tags> list the
1937 node models and the alias names, each once, so a client can discover what it may put in
1938 C<model>. The list follows the policy of the key presented (no key: the default policy): a name
1939 the key's C<models> do not grant, an alias with every tier denied and a model only denied nodes
1940 serve are left out. Unhealthy nodes are included. A node without a C<model> is not listed -- it matches any
1941 requested name, so no name reaches it in particular. The manifest route answers C<404> unless
1942 the config enables it, C<401> without a key and C<403> for a key without a grant; see
1943 L<Langertha::Skeid/Provider Manifest>.
1944  
1945 =head2 Registry route
1946  
1947 GET /skeid/registry/snapshot signed capacity snapshot, for a fronting Skeid
1948  
1949 Bearer token: the admin API key or the registry read key (C<registry.read_key_env>), and nothing
1950 else accepts the read key. C<404> when neither is configured or the registry is not enabled,
1951 C<401> for a wrong token, C<503> while the signing secret is missing. The body is signed in C<X-Skeid-Registry-Signature> and sent
1952 C<Cache-Control: no-store>. See L<Langertha::Skeid/registry_enabled> and ADR 0017.
1953  
1954 =head2 Admin routes
1955  
1956 Bearer token: the admin API key (L<Langertha::Skeid/admin>). Without one configured every
1957 C</skeid/*> route answers C<404>; a missing or wrong token answers C<401>.
1958  
1959 GET /skeid/nodes {nodes}
1960 POST /skeid/nodes body: a node, as a config nodes entry -> {ok, nodes}, or 400
1961 POST /skeid/nodes/:id/health body: {"healthy": true|false} -> {ok}
1962 GET /skeid/config {reload}: the config reload status, with its message
1963 GET /skeid/metrics/nodes {metrics}: per-node counters, never billed
1964 GET /skeid/usage ?since=&api_key_id=&model=&limit= (default 50) -> the report
1965  
1966 Changes made here live in this process only: a changed C<nodes> section in the config replaces
1967 them, and under C<--workers> each write reaches one worker (ADR 0010).
1968  
1969 =head2 Customer identity
1970  
1971 Skeid does not authenticate customers. The key a client presents (C<Authorization: Bearer>, else
1972 C<x-api-key>) derives the customer key id (L<Langertha::Skeid/key_id_for_key>; no key is
1973 C<anonymous>), which selects the routing policy and is recorded on the usage event. With
1974 C<routing.trust_key_id_header> a C<x-skeid-key-id> (or C<x-api-key-id>) header names the key id
1975 instead.
1976  
1977 =head2 The upstream call
1978  
1979 The node URL gets C</v1> added unless it ends in it, then C</chat/completions> or
1980 C</embeddings>; the body carries the served model (an alias tier's C<model>), everything else as
1981 the client sent it or as translated. The client's headers go upstream except the hop-by-hop
1982 ones, C<Host>, C<Content-Length> and C<Accept-Encoding>. When the node has a key of its own --
1983 C<api_key_ref> through the key broker, else C<api_key_env> -- it replaces C<Authorization> and
1984 the client's C<Authorization> and C<x-api-key> are dropped, however the client spelled them. A
1985 node that names neither forwards the client's own key. A node that names one and gets no key
1986 from it -- the broker fails or is not running, the variable is unset or empty -- is not called
1987 at all, and neither is one that left the inventory after it was selected: the request is
1988 refused with C<503> (see L</Errors>), so the client's key never stands in for the node's. An answer that came from a node carries
1989 C<x-skeid-node> with the node id. Rate-limit headers and C<429>s on every response feed
1990 L<Langertha::Skeid/observe_response_headers>.
1991  
1992 Each admitted request gets its C<request.finish> on every path and one usage event, failures
1993 included.
1994  
1995 =head2 A client that hangs up
1996  
1997 A client that closes its connection before the answer is complete ends its request at that
1998 moment. While it waits for capacity it stops waiting and takes no slot. Once a node was called,
1999 the upstream connection is closed -- which is how the node learns to stop generating -- and is
2000 not returned to the pool; the slot is given back with a C<request.finish> marked C<aborted> -- counted apart, not as a node
2001 error, so the node's error counter and the registry snapshot's C<errors_in_window> stay untouched --
2002 and the one usage event is written with C<ok = 0>, C<status_code> 499 and C<error_type>
2003 C<client_abort>, priced from the usage the stream had reported until then (nothing, for a
2004 request that was not streamed). A client that leaves while the node's key is still being
2005 resolved gives its slot back too, but nothing was forwarded, so no usage event is written.
2006 When the node had already finished and only the rest of the answer was still being written
2007 out, the request stays what it was: finished and metered by the node's answer.
2008  
2009 =head2 Errors
2010  
2011 A request no node may serve for this key is C<403 permission_error>; a model no healthy node
2012 serves is C<503 model_not_found>; eligible nodes that stay full past the wait are
2013 C<429 rate_limit_error>; an upstream failure is its status (or C<502>) with type
2014 C<upstream_error>; a node whose own key cannot be resolved is
2015 C<503 upstream_key_unavailable>, logged with the key reference and recorded as a failed usage
2016 event. The body is shaped for the face that was called: OpenAI's
2017 C<{error: {message, type}}>, Anthropic's envelope
2018 (L<Langertha::Skeid::Protocol::Anthropic/error_body>) on C</v1/messages>, and Ollama's
2019 C<{error: "..."}> on C</api/*>. A stream that fails after it opened ends with the face's in-band
2020 error event where it has one.
2021  
2022 =head1 METHODS
2023  
2024 =head2 build_app
2025  
2026 my $app = Langertha::Skeid::Proxy->build_app(%options);
2027  
2028 Builds the L<Mojolicious> application. Options:
2029  
2030 =over 4
2031  
2032 =item * C<config_file> -- the config to build a L<Langertha::Skeid> from.
2033  
2034 =item * C<skeid> -- an existing L<Langertha::Skeid> to serve instead; C<config_file> and the
2035 OpenBao detection below are then not used.
2036  
2037 =item * C<admin_api_key> -- the explicit admin API key (L<Langertha::Skeid/set_admin_api_key>):
2038 it wins over the config's, on every reload. Empty leaves the key to the config and
2039 C<SKEID_ADMIN_API_KEY>.
2040  
2041 =item * C<worker_count> -- how many prefork workers share the nodes (L<Langertha::Skeid/worker_count>),
2042 set before any admission or probe timer reads it.
2043  
2044 =back
2045  
2046 The Skeid's L<Langertha::Skeid/on_usage_lost> is set to this app's C<usage event lost> log line,
2047 so a usage event a write-behind store could not write is logged like one whose synchronous write
2048 failed. An embedding application that wants its own hook sets it after C<build_app>.
2049  
2050 With both C<OPENBAO_ROLE_ID> and C<OPENBAO_SECRET_ID> set, a
2051 L<Langertha::Skeid::KeyBroker::OpenBao> at C<OPENBAO_ADDR> (default C<http://127.0.0.1:8200>)
2052 becomes the key broker; if its login fails the proxy warns and runs without one. A broker that
2053 can renew its token starts renewing on a timer. The capacity probes of every node are started
2054 and restarted whenever the probed part of the inventory changes.
2055  
2056 Upstream connections time out after 10s to connect, and at most C<SKEID_UPSTREAM_POOL>
2057 (default 100) are kept. An upstream request may take C<SKEID_UPSTREAM_TIMEOUT> seconds (default
2058 300; a positive integer, anything else counts as unset) and may be silent for all of them --
2059 the time to the first token is silence on the wire. The client's connection is given the same
2060 time on top of the server's own inactivity timeout, on the routes that call an upstream and for
2061 that request only: the proxy never closes a request its upstream is still working on, and is
2062 still there to answer when the upstream timed out. Every other route stays under the server's
2063 timeout. The client's side is read from the user agent when a request arrives, so whoever
2064 changes C<< $app->ua->request_timeout >> afterwards changes both sides, and should set
2065 C<< $app->ua->inactivity_timeout >> to match.
2066  
2067 The app has a C<skeid> helper returning the control plane.
2068  
2069 =head1 SEE ALSO
2070  
2071 =over 4
2072  
2073 =item * L<Langertha::Skeid> -- the control plane and its configuration
2074  
2075 =item * L<skeid> -- the command that runs this app
2076  
2077 =item * L<Langertha::Skeid::Protocol::Anthropic>, L<Langertha::Skeid::Protocol::Ollama> -- the
2078 translated faces
2079  
2080 =item * L<Langertha::Skeid::KeyBroker::OpenBao> -- upstream keys from OpenBao
2081  
2082 =back
2083  
2084 =head1 SUPPORT
2085  
2086 =head2 Issues
2087  
2088 Please report bugs and feature requests on GitHub at
2089 L<https://github.com/Getty/langertha-skeid/issues>.
2090  
2091 =head2 IRC
2092  
2093 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
2094  
2095 =head1 CONTRIBUTING
2096  
2097 Contributions are welcome! Please fork the repository and submit a pull request.
2098  
2099 =head1 AUTHOR
2100  
2101 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
2102  
2103 =head1 COPYRIGHT AND LICENSE
2104  
2105 This software is copyright (c) 2026 by Torsten Raudssus.
2106  
2107 This is free software; you can redistribute it and/or modify it under
2108 the same terms as the Perl 5 programming language system itself.
2109  
2110 =cut
« blib/lib/Langertha/Skeid/CapacityProbe/Registry.pm ↑ Summary blib/lib/Langertha/Skeid/Registry.pm »