lib/App/teai/Dash.pm

filter: Statementstmt 14.0% 61 / 433 Branchbran 0.0% 0 / 214 Conditioncond 0.0% 0 / 124 MC/DCmcdc 0.0% 0 / 69 Subroutinesub 14.0% 14 / 100 Podpod 100% 3 / 3 totaltotal 8.2% 78 / 943 CC 179 SCAR 40.8
CC
179
Cov
8%
_request
420.0
run
132.0
_listen
90.0
CRAP 59.4
« lib/App/teai/Hook.pm ↑ Summary lib/App/teai/MCP/Tools.pm »
1 package App::teai::Dash;
2 2 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use Cpanel::JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use Digest::SHA ();
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use Encode ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use EV;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use App::teai::Err;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use App::teai::Bus ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use App::teai::Config ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use App::teai::Presence ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶use App::teai::Wire ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 2 our $VERSION = '0.08';
16 2 our @PAGES = qw(App::teai::Dash::Sessions App::teai::Dash::Mail App::teai::Dash::Threads App::teai::Dash::Rounds);
17  
18 2 my $MAX_BODY = 4194304;
19 2 my $READ_TIMEOUT = 30;
20 2 my $POLL = 5;
21 2 my $KEEPALIVE = 15;
22 2 my $SHUTDOWN_BOUND = 2;
23 2 my $RESCAN = 1;
24 2 my $PREVIEW = 160;
25 2 my $RETRY_MS = 2000;
26 2 my $RESULT_TTL = 600;
27 2 my $RESULT_MAX = 100;
28 2 my %EXIT = (INT => 130, TERM => 143);
29 2 my $CSP = "default-src 'self'; frame-ancestors 'none'; form-action 'self'";
30 2 my @SECURE = (
31 'Cache-Control' => 'no-store', 'Content-Security-Policy' => $CSP,
32 'Referrer-Policy' => 'no-referrer', 'X-Content-Type-Options' => 'nosniff',
33 );
34 2 my $JSON = Cpanel::JSON::XS->new->utf8->canonical;
35 2 my %ESC = ('&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', "'" => '&#39;');
36 2 my $LISTEN = qr/\A(\[[^\]]*\]|[^:\[\]]+):([0-9]{1,5})\z/;
37 2 my $IPV4 = qr/\A([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\z/;
38  
39 2 my $APP_JS = <<'JS';
40 (function () {
41 'use strict';
42 var list = document.getElementById('events');
43 var watch = document.body.getAttribute('data-watch') || '';
44 var slow = watch === 'any' || watch.indexOf('thread:') === 0;
45 var loaded = Date.now();
46 var touched = false, timer = null, es = null, hiddenAt = document.hidden ? Date.now() : 0;
47 document.addEventListener('input', function () { touched = true; });
48 function busy() {
49 var a = document.activeElement;
50 return touched || !!(a && /^(INPUT|TEXTAREA|SELECT|BUTTON)$/.test(a.tagName));
51 }
52 function wanted(type, d) {
53 if (watch === 'any') return type === 'msg';
54 if (watch === 'presence') return type === 'presence';
55 if (watch.indexOf('thread:') === 0) return type === 'msg' && d.thread === watch.slice(7);
56 if (watch.indexOf('to:') === 0) return type === 'msg' && d.to === watch.slice(3);
57 return false;
58 }
59 function seen(type, d, text) {
60 if (list) {
61 var li = document.createElement('li');
62 li.textContent = text;
63 list.insertBefore(li, list.firstChild);
64 while (list.children.length > 20) list.removeChild(list.lastChild);
65 }
66 if (!wanted(type, d) || timer) return;
67 var wait = slow ? Math.max(2000, 10000 - (Date.now() - loaded)) : 2000;
68 timer = setTimeout(function () { timer = null; if (!busy()) { close(); location.reload(); } }, wait);
69 }
70 function open() {
71 if (es) return;
72 es = new EventSource('/events');
73 es.addEventListener('msg', function (e) {
74 var d = JSON.parse(e.data);
75 seen('msg', d, '#' + d.seq + ' ' + d.time + ' ' + d.from + ' -> ' + d.to + ' ' + d.kind
76 + (d.thread ? ' thread=' + d.thread : '') + (d.re ? ' re=' + d.re : '') + ': ' + d.preview);
77 });
78 es.addEventListener('presence', function (e) {
79 var d = JSON.parse(e.data), live = 0;
80 Object.keys(d).forEach(function (s) { if (d[s].live && d[s].live.length) live++; });
81 seen('presence', d, 'presence: ' + live + ' live');
82 });
83 }
84 function close() {
85 if (es) { es.close(); es = null; }
86 }
87 function refresh() {
88 if (watch && !busy()) { close(); location.reload(); return true; }
89 return false;
90 }
91 document.addEventListener('visibilitychange', function () {
92 if (document.hidden) { hiddenAt = Date.now(); close(); return; }
93 var away = hiddenAt ? Date.now() - hiddenAt : 0;
94 hiddenAt = 0;
95 if (away > 2000 && refresh()) return;
96 open();
97 });
98 window.addEventListener('pagehide', close);
99 window.addEventListener('pageshow', function (e) {
100 if (!document.hidden) hiddenAt = 0;
101 if (e.persisted && refresh()) return;
102 if (!document.hidden) open();
103 });
104 if (!document.hidden) open();
105 })();
106 JS
107  
108 2 my $APP_CSS = <<'CSS';
109 :root { color-scheme: light dark; --fg: #1d1f21; --bg: #fafafa; --muted: #666; --line: #ddd; --accent: #2a6fdb; --warn: #b3261e; }
110 @media (prefers-color-scheme: dark) { :root { --fg: #e4e4e4; --bg: #17181a; --muted: #9a9a9a; --line: #333; --accent: #7aa7ff; --warn: #ff8a80; } }
111 body { margin: 0 auto; max-width: 80rem; padding: 0 1rem 2rem; font: 15px/1.45 system-ui, sans-serif; color: var(--fg); background: var(--bg); }
112 header { display: flex; flex-wrap: wrap; gap: .5rem 2rem; align-items: baseline; justify-content: space-between; border-bottom: 1px solid var(--line); padding: .6rem 0; }
113 nav a { margin-right: 1rem; color: var(--accent); text-decoration: none; }
114 a { color: var(--accent); }
115 h1 { font-size: 1.3rem; }
116 h2 { font-size: 1.05rem; }
117 .who, .note, .counts, .head, .pending { color: var(--muted); }
118 .error { color: var(--warn); font-weight: 600; }
119 .scroll { overflow-x: auto; }
120 table { border-collapse: collapse; width: 100%; }
121 th, td { text-align: left; padding: .3rem .5rem; border-bottom: 1px solid var(--line); vertical-align: top; white-space: nowrap; }
122 td form { display: inline; }
123 .head { font: 13px/1.4 ui-monospace, monospace; }
124 pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: .3rem 0; padding: .5rem; border-left: 3px solid var(--line); }
125 article { border-bottom: 1px solid var(--line); padding: .4rem 0; }
126 label { display: block; margin: .5rem 0; }
127 input[type=text], textarea, select { font: inherit; width: 100%; box-sizing: border-box; padding: .3rem; }
128 input[type=checkbox] { margin-right: .4rem; }
129 textarea { min-height: 12rem; }
130 button { font: inherit; padding: .2rem .8rem; }
131 footer { margin-top: 2rem; border-top: 1px solid var(--line); color: var(--muted); font-size: 13px; }
132 footer ol { padding-left: 1.2rem; font-family: ui-monospace, monospace; }
133 CSS
134  
135 0 ▶sub esc ($text) { ($text // '') =~ s/([&<>"'])/$ESC{$1}/gr }
Subroutine esc: not called CC=2 SCAR=17.9
Pod documented
Condition0%0/2
$text // ""
l!l
00
MC/DC0%0/1
$text // ""
$text
Truth table0%0/2
A
A= $text
Aresult
11
00
136  
137 0 ▶sub _loopback ($addr) {
Subroutine _loopback: not called CC=6 SCAR=37.4
138 0 ▶ return 0 unless defined $addr;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $addr 0 0 0
139 0 $addr =~ s/\A::ffff://i;
140 0 ▶ return 1 if $addr eq '::1';
Branch: 1 branch
BranchTrueFalseTotal
if $addr eq "::1" 0 0 0
141 0 ▶ my @o = $addr =~ $IPV4 or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my(@o) = $addr =~ /$IPV4/u or return 0 0 0 0
142 0 ▶ return $o[0] == 127 && !grep({ $_ > 255 } @o) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$o[0] == 127 && !grep({$_ > 255;} @o) ? : 0 0 0
Condition0%0/3
$o[0] == 127 and not grep({$_ > 255;} @o)
!ll&&!rl&&r
000
MC/DC0%0/2
$o[0] == 127 and not grep({$_ > 255;} @o)
$o[0] == 127 not grep({$_ > 255;} @o)
Truth table0%0/3
A and not(B)
A= $o[0] == 127B= not grep({$_ > 255;} @o)
ABresult
0X0
100
111
143 }
144  
145 0 ▶sub _listen ($text) {
Subroutine _listen: not called CC=9 SCAR=45.0
146 0 ▶ my $bad = sub { App::teai::Err::fail(2, "invalid listen address '$text'") };
Subroutine __ANON__: not called CC=1 SCAR=6.9
147 0 ▶ my ($host, $port) = $text =~ $LISTEN or $bad->();
Branch: 1 branch
BranchTrueFalseTotal
() = $text =~ /$LISTEN/u or &$bad() 0 0 0
148 0 ▶ $bad->() if $port > 65535;
Branch: 1 branch
BranchTrueFalseTotal
if $port > 65535 0 0 0
149 0 my $bind;
150 0 ▶ if (my @o = $host =~ $IPV4) {
Branch: 3 branches
BranchTrueFalseTotal
if (my(@o) = $host =~ /$IPV4/u) { } 0 0 0
elsif ($host eq '[::1]') { } 0 0 0
elsif (lc $host eq 'localhost') { } 0 0 0
151 0 ▶ $bad->() if grep { $_ > 255 } @o;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$_ > 255;} @o 0 0 0
152 0 ▶ $bind = join '.', map { $_ + 0 } @o if $o[0] == 127;
Branch: 1 branch
BranchTrueFalseTotal
if $o[0] == 127 0 0 0
153 }
154 0 elsif ($host eq '[::1]') { $bind = '::1' }
155 0 elsif (lc $host eq 'localhost') { $bind = '127.0.0.1' }
156 0 ▶ App::teai::Err::fail(2, "dash listens on loopback only, not $text") unless defined $bind;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bind 0 0 0
157 0 return ($host, $bind, $port + 0);
158 }
159  
160 0 ▶sub _json ($v) { $JSON->encode($v) =~ s/([<>&'])/sprintf '\\u%04x', ord $1/ger }
Subroutine _json: not called CC=1 SCAR=6.9
161  
162 0 ▶sub _secs ($knob, $default) {
Subroutine _secs: not called CC=4 SCAR=30.0
163 0 my $v = $ENV{$knob};
164 0 ▶ return defined $v && $v =~ /\A(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)\z/ && $v > 0 ? $v : $default;
Branch: 1 branch
BranchTrueFalseTotal
defined $v && $v =~ /\A(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)\z/u && $v > 0 ? : 0 0 0
Condition0%0/6
defined $v and $v =~ /\A(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)\z/u and $v > 0
!ll&&!rl&&r
000
defined $v and $v =~ /\A(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)\z/u
!ll&&!rl&&r
000
MC/DC0%0/3
defined $v and $v =~ /\A(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)\z/u and $v > 0
defined $v $v =~ /\A(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)\z/u $v > 0
Truth table0%0/4
A and B and C
A= defined $vB= $v =~ /\A(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)\z/uC= $v > 0
ABCresult
0XX0
10X0
1100
1111
165 }
166  
167 0 ▶sub _any_loopback () {
Subroutine _any_loopback: not called CC=2 SCAR=17.9
168 0 while (1) {
169 0 my $addr = sprintf '127.%d.%d.%d', int rand 256, int rand 256, 1 + int rand 254;
170 0 ▶ return "$addr:0" unless $addr eq '127.0.0.1';
Branch: 1 branch
BranchTrueFalseTotal
unless $addr eq "127.0.0.1" 0 0 0
171 }
172 }
173  
174 0 ▶sub _random_hex ($path = '/dev/urandom') {
Subroutine _random_hex: not called CC=6 SCAR=37.4
175 0 ▶ open my $fh, '<:raw', $path or App::teai::Err::fail(3, "cannot read $path: $!");
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or App::teai::Err::fail(3, "cannot read ${path}: $!") 0 0 0
176 0 my $n = read $fh, my $raw, 16;
177 0 ▶ App::teai::Err::fail(3, "cannot read $path: " . (defined $n ? 'short read' : $!)) unless ($n // 0) == 16;
Branch: 2 branches
BranchTrueFalseTotal
unless ($n // 0) == 16 0 0 0
defined $n ? : 0 0 0
Condition0%0/2
$n // 0
l!l
00
MC/DC0%0/1
$n // 0
$n
Truth table0%0/2
A
A= $n
Aresult
11
00
178 0 return unpack 'H32', $raw;
179 }
180  
181 0 ▶sub _log ($e) {
Subroutine _log: not called CC=2 SCAR=17.9
182 0 my ($line) = split /\n/, App::teai::Bus::_text($e);
183 0 ▶ print STDERR 'teai: dash callback died: ', $line // '', "\n";
Condition0%0/2
$line // ""
l!l
00
MC/DC0%0/1
$line // ""
$line
Truth table0%0/2
A
A= $line
Aresult
11
00
184 }
185  
186 0 ▶sub _read_id ($file) {
Subroutine _read_id: not called CC=5 SCAR=34.0
187 0 ▶ open my $fh, '<', $file or do {
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or do { return undef if $!{"ENOENT"}; App::teai::Err::fail(3, "cannot read ${file}: $!") } 0 0 0
188 0 ▶ return undef if $!{ENOENT};
Branch: 1 branch
BranchTrueFalseTotal
if $!{"ENOENT"} 0 0 0
189 0 App::teai::Err::fail(3, "cannot read $file: $!");
190 };
191 0 my $n = read $fh, my $text, 256;
192 0 ▶ App::teai::Err::fail(3, "cannot read $file: $!") unless defined $n;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 0 0 0
193 0 ▶ return $text =~ /\A([A-Za-z0-9_-]{1,64})\n?\z/ ? $1 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$text =~ /\A([A-Za-z0-9_-]{1,64})\n?\z/u ? : 0 0 0
194 }
195  
196 0 ▶sub _write_id ($file, $id) {
Subroutine _write_id: not called CC=7 SCAR=40.3
197 0 my $tmp = "$file.$$.tmp";
198 0 my $line = "$id\n";
199 0 unlink $tmp;
200 0 my $fh;
201 0 ▶ my $ok = sysopen($fh, $tmp, O_WRONLY | O_CREAT | O_EXCL, 0600) && chmod(0600, $tmp)
Condition0%0/14
sysopen($fh, $tmp, 193, 384) && chmod(0600, $tmp) && (syswrite($fh, $line) // -1) == length $line && close $fh && rename($tmp, $file)
!ll&&!rl&&r
000
sysopen $fh, $tmp, 193, 384 and chmod 0600, $tmp and (syswrite($fh, $line) // -1) == length $line and close $fh
!ll&&!rl&&r
000
sysopen $fh, $tmp, 193, 384 and chmod 0600, $tmp and (syswrite($fh, $line) // -1) == length $line
!ll&&!rl&&r
000
sysopen $fh, $tmp, 193, 384 and chmod 0600, $tmp
!ll&&!rl&&r
000
syswrite($fh, $line) // -1
l!l
00
MC/DC0%0/5
sysopen($fh, $tmp, 193, 384) && chmod(0600, $tmp) && (syswrite($fh, $line) // -1) == length $line && close $fh && rename($tmp, $file)
sysopen $fh, $tmp, 193, 384 chmod 0600, $tmp syswrite($fh, $line) close $fh rename($tmp, $file)
Truth table0%0/6
A and B and C and D && E
A= sysopen $fh, $tmp, 193, 384B= chmod 0600, $tmpC= syswrite($fh, $line)D= close $fhE= rename($tmp, $file)
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
202 && (syswrite($fh, $line) // -1) == length $line && close($fh) && rename($tmp, $file);
203 0 ▶ return if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
204 0 my $e = "$!";
205 0 unlink $tmp;
206 0 App::teai::Err::fail(3, "cannot write $file: $e");
207 }
208  
209 0 ▶sub _operator ($bus, $project) {
Subroutine _operator: not called CC=8 SCAR=42.8
210 0 my $file = App::teai::Config::state_dir() . '/operator';
211 0 my $old = _read_id($file);
212 0 my $attrs = { agent => 'shell', project => $project, role => 'operator' };
213 0 ▶ if (defined $old && !$bus->await(sub ($done) { $bus->removed($old, $done) })) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if (defined $old and not $bus->await(sub ($done) { $bus->removed($old, $done); } )) 0 0 0
Condition0%0/3
defined $old and not $bus->await(sub ($done) { $bus->removed($old, $done); } )
!ll&&!rl&&r
000
MC/DC0%0/2
defined $old and not $bus->await(sub ($done) { $bus->removed($old, $done); } )
defined $old not $bus->await(sub ($done) { $bus->removed($old, $done); } )
Truth table0%0/3
A and not(B)
A= defined $oldB= not $bus->await(sub ($done) { $bus->removed($old, $done); } )
ABresult
0X0
100
111
214 0 ▶ my $kept = eval { $bus->await(sub ($done) { own_inbox($bus, $old, $attrs, $done) }) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
215 0 ▶ return $old if $kept;
Branch: 1 branch
BranchTrueFalseTotal
if $kept 0 0 0
216 0 my $e = $@;
217 0 ▶ die $e unless ref $e && eval { $e->isa('App::teai::Err') } && $e->{removed};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $e and eval { do { $e->isa("App::teai::Err") } } and $e->{"removed"} 0 0 0
Condition0%0/6
ref $e and eval { do { $e->isa("App::teai::Err") } } and $e->{"removed"}
!ll&&!rl&&r
000
ref $e and eval { do { $e->isa("App::teai::Err") } }
!ll&&!rl&&r
000
MC/DC0%0/3
ref $e and eval { do { $e->isa("App::teai::Err") } } and $e->{"removed"}
ref $e eval { do { $e->isa("App::teai::Err") } } $e->{"removed"}
Truth table0%0/4
A and B and C
A= ref $eB= eval { do { $e->isa("App::teai::Err") } }C= $e->{"removed"}
ABCresult
0XX0
10X0
1100
1111
218 }
219 0 ▶ my $new = $bus->await(sub ($done) { $bus->new_session($attrs, $done) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
220 0 _write_id($file, $new);
221 0 ▶ print STDERR "teai: the operator session $old was removed; using $new\n" if defined $old;
Branch: 1 branch
BranchTrueFalseTotal
if defined $old 0 0 0
222 0 return $new;
223 }
224  
225 0 ▶sub own_inbox ($bus, $id, $attrs, $cb) {
Subroutine own_inbox: not called CC=1 SCAR=6.9
Pod documented
226 0 ▶ my $set = sub ($what) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
227 0 ▶ $bus->set_session_attrs($id, $attrs, sub ($ok, $e = undef) {
Subroutine __ANON__: not called CC=5 SCAR=34.0
228 0 ▶ return $cb->(undef, $e) if defined $e;
Branch: 1 branch
BranchTrueFalseTotal
if defined $e 0 0 0
229 0 ▶ return $cb->(1) if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
230 0 ▶ $cb->(undef, eval { App::teai::Err::fail(3, "the inbox of the operator session $id went away while it was $what") } // $@);
Condition0%0/3
eval { do { App::teai::Err::fail(3, "the inbox of the operator session $id went away while it was $what") } } // $@
l!l&&r!l&&!r
000
MC/DC0%0/2
eval { do { App::teai::Err::fail(3, "the inbox of the operator session $id went away while it was $what") } } // $@
eval { do { App::teai::Err::fail(3, "the inbox of the operator session $id went away while it was $what") } } $@
Truth table0%0/3
A // B
A= eval { do { App::teai::Err::fail(3, "the inbox of the operator session $id went away while it was $what") } }B= $@
ABresult
1X1
011
000
231 0 });
232 0 };
233 0 ▶ $bus->consumer_info($id, sub ($info, $err = undef) {
Subroutine __ANON__: not called CC=8 SCAR=42.8
234 0 ▶ return $cb->(undef, $err) if defined $err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $err 0 0 0
235 0 ▶ if ($info) {
Branch: 1 branch
BranchTrueFalseTotal
if ($info) 0 0 0
236 0 ▶ my $have = App::teai::Bus::attrs_of(ref $info->{config} eq 'HASH' ? $info->{config}{metadata} : undef);
Branch: 1 branch
BranchTrueFalseTotal
ref $info->{'config'} eq 'HASH' ? : 0 0 0
237 0 ▶ return $cb->(1) unless grep { ($have->{$_} // '') ne ($attrs->{$_} // '') } keys %$attrs;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {($have->{$_} // "") ne ($attrs->{$_} // "");} keys %$attrs 0 0 0
Condition0%0/4
$have->{$_} // ""
l!l
00
$attrs->{$_} // ""
l!l
00
MC/DC0%0/1
$have->{$_} // ""
$have->{$_}
MC/DC0%0/1
$attrs->{$_} // ""
$attrs->{$_}
Truth table0%0/2
A
A= $have->{$_}
Aresult
11
00
Truth table0%0/2
A
A= $attrs->{$_}
Aresult
11
00
238 0 return $set->('updated');
239 }
240 0 ▶ $bus->ensure_consumer($id, sub ($ok, $e = undef) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
241 0 ▶ return $cb->(undef, $e) if defined $e;
Branch: 1 branch
BranchTrueFalseTotal
if defined $e 0 0 0
242 0 $set->('created');
243 0 });
244 0 });
245 }
246  
247 0 ▶sub run (%o) {
Subroutine run: not called CC=11 SCAR=48.8
Pod documented
248 0 ▶ my $listen = $o{listen} // _any_loopback();
Condition0%0/3
$o{"listen"} // _any_loopback()
l!l&&r!l&&!r
000
MC/DC0%0/2
$o{"listen"} // _any_loopback()
$o{"listen"} _any_loopback()
Truth table0%0/3
A // B
A= $o{"listen"}B= _any_loopback()
ABresult
1X1
011
000
249 0 my ($host, $bind, $port) = _listen($listen);
250 0 ▶ eval { require Feersum; Feersum->VERSION('1.509'); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Feersum; "Feersum"->VERSION("1.509"); 1 } } or App::teai::Err::fail(2, "dash needs the Feersum module: install Feersum") 0 0 0
251 or App::teai::Err::fail(2, 'dash needs the Feersum module: install Feersum');
252 0 my $project = App::teai::_need_project($o{project});
253 0 require IO::Socket::IP;
254 0 for my $page (@PAGES) {
255 0 (my $file = "$page.pm") =~ s{::}{/}g;
256 0 require $file;
257 }
258 0 my $bus = App::teai::Bus->new(%{ $o{config} }, reconnect => 1);
259 0 my $operator = _operator($bus, $project);
260 0 ▶ my $sock = IO::Socket::IP->new(LocalHost => $bind, LocalPort => $port, Listen => 128, ReuseAddr => 1)
Branch: 1 branch
BranchTrueFalseTotal
my $sock = "IO::Socket::IP"->new("LocalHost", $bind, "LocalPort", $port, "Listen", 128, "ReuseAddr", 1) or App::teai::Err::fail(3, "cannot listen on ${listen}: " . ($@ || $!)) 0 0 0
Condition0%0/3
$@ || $!
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ || $!
$@ $!
Truth table0%0/3
A || B
A= $@B= $!
ABresult
1X1
011
000
261 or App::teai::Err::fail(3, "cannot listen on $listen: " . ($@ || $!));
262 0 $port = $sock->sockport;
263 0 ▶ my $url_host = $bind eq '::1' ? '[::1]' : $bind;
Branch: 1 branch
BranchTrueFalseTotal
$bind eq '::1' ? : 0 0 0
264 my $self = bless {
265 bus => $bus, operator => $operator, project => $project, port => $port,
266 token => _random_hex(), secret => _random_hex(),
267 0 hosts => { map { (lc("$_:$port") => 1) } '127.0.0.1', 'localhost', '[::1]', $url_host, $host },
268 clients => {}, client_n => 0, results => {}, result_order => [],
269 }, __PACKAGE__;
270 $self->{routes} = [
271 0 ▶ [ GET => qr{\A/events\z}, sub ($c) { $c->{dash}->_events($c) }, 'local' ],
Subroutine __ANON__: not called CC=1 SCAR=6.9
272 0 ▶ [ GET => qr{\A/app\.js\z}, sub ($c) { $c->_static('application/javascript; charset=utf-8', $APP_JS) }, 'local' ],
Subroutine __ANON__: not called CC=1 SCAR=6.9
273 0 ▶ [ GET => qr{\A/app\.css\z}, sub ($c) { $c->_static('text/css; charset=utf-8', $APP_CSS) }, 'local' ],
Subroutine __ANON__: not called CC=1 SCAR=6.9
274 0 ▶ [ GET => qr{\A/result/([^/]+)\z}, sub ($c, $id) { $c->{dash}->_result($c, $id) }, 'local' ],
Subroutine __ANON__: not called CC=1 SCAR=6.9
275 0 map { $_->routes } @PAGES,
276 ];
277 0 Scalar::Util::weaken(my $weak = $self);
278 0 my $f = $self->{feersum} = Feersum->new_instance;
279 0 $f->use_socket($sock);
280 0 ▶ $f->request_handler(sub ($req) { $weak->_request($req) if $weak });
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
281 0 $f->max_body_len($MAX_BODY);
282 0 $f->read_timeout($READ_TIMEOUT);
283 0 $self->_follow('new');
284 0 ▶ $self->{poll_t} = EV::timer 0, _secs(TEAI_TEST_DASH_POLL => $POLL), sub { $weak->_poll if $weak };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
285 0 my $keep = _secs(TEAI_TEST_DASH_KEEPALIVE => $KEEPALIVE);
286 0 ▶ $self->{keep_t} = EV::timer $keep, $keep, sub { $weak->_send(": keepalive\n\n") if $weak };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
287 0 for my $name (sort keys %EXIT) {
288 0 ▶ $self->{sig}{$name} = EV::signal $name, sub { $weak->_shutdown($EXIT{$name}) if $weak };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
289 }
290 0 ▶ App::teai::_write_stdout("http://$url_host:$port/?t=$self->{token}\n") or App::teai::Err::fail(3, "write failed: $!");
Branch: 1 branch
BranchTrueFalseTotal
App::teai::_write_stdout(qq[http://${url_host}:$port/?t=$self->{"token"}\n]) or App::teai::Err::fail(3, "write failed: $!") 0 0 0
291 0 ▶ local $EV::DIED = sub { _log($@) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
292 0 ▶ until (defined $self->{exit}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"exit"}) 0 0 0
293 0 ▶ eval { EV::run(EV::RUN_ONCE); 1 } or _log($@);
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &EV::run(2); 1 } } or _log($@) 0 0 0
294 }
295 0 return $self->{exit};
296 }
297  
298 0 ▶sub _shutdown ($self, $code) {
Subroutine _shutdown: not called CC=8 SCAR=42.8
299 0 ▶ return if $self->{stopping}++;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stopping"}++ 0 0 0
300 0 ▶ $self->{bound_t} = EV::timer $SHUTDOWN_BOUND, 0, sub { $self->{exit} //= $code };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Condition0%0/3
$self->{"exit"} //= $code
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"exit"} //= $code
$self->{"exit"} $code
Truth table0%0/3
A //= B
A= $self->{"exit"}B= $code
ABresult
1X1
011
000
301 0 undef $self->{$_} for qw(poll_t keep_t rescan_t);
302 0 my $scan = delete $self->{scan};
303 0 ▶ $scan->cancel if $scan;
Branch: 1 branch
BranchTrueFalseTotal
if $scan 0 0 0
304 0 $self->_drop($_) for keys %{ $self->{clients} };
305 0 ▶ for my $cb (map { splice @$_ } values %{ delete $self->{closing} // {} }) {
Condition0%0/2
delete $self->{"closing"} // {}
l!l
00
MC/DC0%0/1
delete $self->{"closing"} // {}
delete $self->{"closing"}
Truth table0%0/2
A
A= delete $self->{"closing"}
Aresult
11
00
306 0 ▶ eval { $cb->(); 1 } or _log($@);
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$cb(); 1 } } or _log($@) 0 0 0
307 }
308 0 my $left = 2;
309 0 ▶ my $end = sub (@) { $self->{exit} //= $code unless --$left };
Subroutine __ANON__: not called CC=3 SCAR=24.8
Branch: 1 branch
BranchTrueFalseTotal
unless --$left 0 0 0
Condition0%0/3
$self->{"exit"} //= $code
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"exit"} //= $code
$self->{"exit"} $code
Truth table0%0/3
A //= B
A= $self->{"exit"}B= $code
ABresult
1X1
011
000
310 0 $self->{feersum}->graceful_shutdown($end);
311 0 $self->{bus}->flush($end);
312 }
313  
314 0 ▶sub _cookie ($header, $name) {
Subroutine _cookie: not called CC=5 SCAR=34.0
315 0 ▶ for my $part (split /\s*;\s*/, $header // '') {
Condition0%0/2
$header // ""
l!l
00
MC/DC0%0/1
$header // ""
$header
Truth table0%0/2
A
A= $header
Aresult
11
00
316 0 my ($k, $v) = split /=/, $part, 2;
317 0 ▶ return $v if defined $v && $k eq $name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v and $k eq $name 0 0 0
Condition0%0/3
defined $v and $k eq $name
!ll&&!rl&&r
000
MC/DC0%0/2
defined $v and $k eq $name
defined $v $k eq $name
Truth table0%0/3
A and B
A= defined $vB= $k eq $name
ABresult
0X0
100
111
318 }
319 0 return undef;
320 }
321  
322 0 ▶sub _same ($given, $want) {
Subroutine _same: not called CC=4 SCAR=30.0
323 0 ▶ return 0 unless defined $given && defined $want;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $given and defined $want 0 0 0
Condition0%0/3
defined $given and defined $want
!ll&&!rl&&r
000
MC/DC0%0/2
defined $given and defined $want
defined $given defined $want
Truth table0%0/3
A and B
A= defined $givenB= defined $want
ABresult
0X0
100
111
324 0 my ($g, $w) = map { Digest::SHA::sha1(Encode::encode('UTF-8', $_)) } $given, $want;
325 0 ▶ return $g eq $w ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$g eq $w ? : 0 0 0
326 }
327  
328 0 ▶sub _unescape ($s) {
Subroutine _unescape: not called CC=2 SCAR=17.9
329 0 ▶ my $bytes = ($s // '') =~ tr/+/ /r =~ s/%([0-9A-Fa-f]{2})/chr hex $1/ger;
Condition0%0/2
$s // ""
l!l
00
MC/DC0%0/1
$s // ""
$s
Truth table0%0/2
A
A= $s
Aresult
11
00
330 0 return (App::teai::Wire::text_in($bytes))[0];
331 }
332  
333 0 ▶sub _form ($s) {
Subroutine _form: not called CC=3 SCAR=24.8
334 0 my %p;
335 0 ▶ for my $pair (grep { length } split /&/, $s // '') {
Condition0%0/2
$s // ""
l!l
00
MC/DC0%0/1
$s // ""
$s
Truth table0%0/2
A
A= $s
Aresult
11
00
336 0 my ($k, $v) = split /=/, $pair, 2;
337 0 push @{ $p{ _unescape($k) } }, _unescape($v);
338 }
339 0 return \%p;
340 }
341  
342 0 ▶sub _body ($req) {
Subroutine _body: not called CC=5 SCAR=34.0
343 0 ▶ return '' unless ($req->header('content-type') // '') =~ m{\Aapplication/x-www-form-urlencoded\s*(?:;|\z)}i;
Branch: 1 branch
BranchTrueFalseTotal
unless ($req->header("content-type") // "") =~ m[\Aapplication/x-www-form-urlencoded\s*(?:;|\z)]iu 0 0 0
Condition0%0/2
$req->header("content-type") // ""
l!l
00
MC/DC0%0/1
$req->header("content-type") // ""
$req->header("content-type")
Truth table0%0/2
A
A= $req->header("content-type")
Aresult
11
00
344 0 ▶ my $in = $req->input or return '';
Branch: 1 branch
BranchTrueFalseTotal
my $in = $req->input or return "" 0 0 0
345 0 my $body = '';
346 0 ▶ while ($in->read(my $chunk, 65536)) { $body .= $chunk }
Branch: 1 branch
BranchTrueFalseTotal
if ($in->read(my $chunk, 65536)) 0 0 0
347 0 $in->close;
348 0 return $body;
349 }
350  
351 0 ▶sub _token_for ($self, $path) { Digest::SHA::sha1_hex(Encode::encode('UTF-8', "$self->{secret} $path")) }
Subroutine _token_for: not called CC=1 SCAR=6.9
352  
353 0 ▶sub _respond ($self, $req, $status, $headers, $bytes) {
Subroutine _respond: not called CC=1 SCAR=6.9
354 0 eval { $req->send_response($status, [ @SECURE, @$headers ], \$bytes); 1 };
355 }
356  
357 0 ▶sub _plain ($self, $req, $status, $text, @headers) {
Subroutine _plain: not called CC=1 SCAR=6.9
358 0 $self->_respond($req, $status, [ 'Content-Type' => 'text/plain; charset=utf-8', @headers ], $text);
359 }
360  
361 0 ▶sub _request ($self, $req) {
Subroutine _request: not called CC=20 SCAR=60.4
362 0 my ($method, $path) = ($req->method, $req->path);
363 return $self->_plain($req, 403, 'forbidden')
364 0 ▶ if $self->{stopping} || !_loopback($req->remote_address) || !$self->{hosts}{ lc($req->header('host') // '') };
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stopping"} or not _loopback($req->remote_address) or not $self->{"hosts"}{lc($req->header("host") // "")} 0 0 0
Condition0%0/8
$self->{"stopping"} or not _loopback($req->remote_address) or not $self->{"hosts"}{lc($req->header("host") // "")}
l!l&&r!l&&!r
000
$self->{"stopping"} or not _loopback($req->remote_address)
l!l&&r!l&&!r
000
$req->header("host") // ""
l!l
00
MC/DC0%0/3
$self->{"stopping"} or not _loopback($req->remote_address) or not $self->{"hosts"}{lc($req->header("host") // "")}
$self->{"stopping"} not _loopback($req->remote_address) not $self->{"hosts"}{lc($req->header("host") // "")}
MC/DC0%0/1
$req->header("host") // ""
$req->header("host")
Truth table0%0/4
A or not(B) or not(C)
A= $self->{"stopping"}B= not _loopback($req->remote_address)C= not $self->{"hosts"}{lc($req->header("host") // "")}
ABCresult
1XX1
01X1
0011
0000
Truth table0%0/2
A
A= $req->header("host")
Aresult
11
00
365 0 ▶ if ($method eq 'GET' && $path eq '/' && (my $t = _form($req->query)->{t})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "GET" and $path eq "/" and my $t = _form($req->query)->{"t"}) 0 0 0
Condition0%0/6
$method eq "GET" and $path eq "/" and my $t = _form($req->query)->{"t"}
!ll&&!rl&&r
000
$method eq "GET" and $path eq "/"
!ll&&!rl&&r
000
MC/DC0%0/3
$method eq "GET" and $path eq "/" and my $t = _form($req->query)->{"t"}
$method eq "GET" $path eq "/" my $t = _form($req->query)->{"t"}
Truth table0%0/4
A and B and C
A= $method eq "GET"B= $path eq "/"C= my $t = _form($req->query)->{"t"}
ABCresult
0XX0
10X0
1100
1111
366 0 ▶ return $self->_plain($req, 403, 'forbidden') unless _same($t->[0], $self->{token});
Branch: 1 branch
BranchTrueFalseTotal
unless _same($t->[0], $self->{"token"}) 0 0 0
367 0 return $self->_plain($req, 303, 'see /', Location => '/',
368 'Set-Cookie' => "teai_dash_$self->{port}=$self->{token}; Path=/; HttpOnly; SameSite=Lax");
369 }
370 return $self->_plain($req, 403, 'forbidden')
371 0 ▶ unless _same(_cookie($req->header('cookie'), "teai_dash_$self->{port}"), $self->{token});
Branch: 1 branch
BranchTrueFalseTotal
unless _same(_cookie($req->header("cookie"), qq[teai_dash_$self->{"port"}]), $self->{"token"}) 0 0 0
372 0 my ($route, @caps, %allow);
373 0 for my $r (@{ $self->{routes} }) {
374 0 ▶ next unless $path =~ $r->[1];
Branch: 1 branch
BranchTrueFalseTotal
unless $path =~ /$r->[1]/u 0 0 0
375 0 my @got = @{^CAPTURE};
376 0 $allow{ $r->[0] } = 1;
377 0 ▶ next unless $r->[0] eq $method;
Branch: 1 branch
BranchTrueFalseTotal
unless $r->[0] eq $method 0 0 0
378 0 ($route, @caps) = ($r, @got);
379 0 last;
380 }
381 0 ▶ return $self->_plain($req, 404, 'not found') unless %allow;
Branch: 1 branch
BranchTrueFalseTotal
unless %allow 0 0 0
382 0 ▶ return $self->_plain($req, 405, 'method not allowed', Allow => join ', ', sort keys %allow) unless $route;
Branch: 1 branch
BranchTrueFalseTotal
unless $route 0 0 0
383 0 ▶ my $params = _form($method eq 'POST' ? _body($req) : $req->query);
Branch: 1 branch
BranchTrueFalseTotal
$method eq 'POST' ? : 0 0 0
384 return $self->_plain($req, 403, 'forbidden')
385 0 ▶ if $method eq 'POST' && !_same(($params->{f} // [])->[0], $self->_token_for($path));
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "POST" and not _same(+($params->{"f"} // [])->[0], $self->_token_for($path)) 0 0 0
Condition0%0/5
$method eq "POST" and not _same(+($params->{"f"} // [])->[0], $self->_token_for($path))
!ll&&!rl&&r
000
$params->{"f"} // []
l!l
00
MC/DC0%0/2
$method eq "POST" and not _same(+($params->{"f"} // [])->[0], $self->_token_for($path))
$method eq "POST" not _same(+($params->{"f"} // [])->[0], $self->_token_for($path))
MC/DC0%0/1
$params->{"f"} // []
$params->{"f"}
Truth table0%0/3
A and not(B)
A= $method eq "POST"B= not _same(+($params->{"f"} // [])->[0], $self->_token_for($path))
ABresult
0X0
100
111
Truth table0%0/2
A
A= $params->{"f"}
Aresult
11
00
386 0 my $c = App::teai::Dash::Ctx->new(dash => $self, req => $req, path => $path, params => $params);
387 0 ▶ my $go = sub { eval { $route->[2]->($c, @caps); 1 } or $c->fail($@) };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $route->[2]->($c, @caps); 1 } } or $c->fail($@) 0 0 0
388 0 ▶ return $go->() if $route->[3];
Branch: 1 branch
BranchTrueFalseTotal
if $route->[3] 0 0 0
389 0 ▶ $self->{bus}->when_up(App::teai::Bus::now(), $go, sub ($e) { $c->fail($e) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
390 }
391  
392 0 ▶sub _layout ($self, $title, $html, $watch) {
Subroutine _layout: not called CC=3 SCAR=24.8
393 0 my $nav = join '', map { '<a href="' . esc($_->[1]) . '">' . esc($_->[0]) . '</a>' }
394 0 ▶ map { $_->can('nav') ? $_->nav : () } @PAGES;
Branch: 1 branch
BranchTrueFalseTotal
$_->can('nav') ? : 0 0 0
395 0 ▶ my $w = defined $watch ? ' data-watch="' . esc($watch) . '"' : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $watch ? : 0 0 0
396 0 my $t = esc($title);
397 return qq{<!doctype html>\n<html lang="en"><head><meta charset="utf-8">}
398 . qq{<meta name="viewport" content="width=device-width, initial-scale=1">}
399 . qq{<title>$t - teai dash</title><link rel="stylesheet" href="/app.css"><script src="/app.js" defer></script></head>\n}
400 . qq{<body$w><header><nav>$nav</nav><p class="who">operator } . esc($self->{operator})
401 0 . ', project ' . esc($self->{project}) . qq{</p></header>\n<main><h1>$t</h1>\n$html\n</main>\n}
402 . qq{<footer><h2>Live</h2><ol id="events"></ol></footer></body></html>\n};
403 }
404  
405 0 ▶sub _prune_results ($self, $now = App::teai::Bus::now()) {
Subroutine _prune_results: not called CC=5 SCAR=34.0
406 0 my ($order, $store) = @$self{qw(result_order results)};
407 0 ▶ delete $store->{ shift @$order } while @$order && $now - $store->{ $order->[0] }{at} >= $RESULT_TTL;
Branch: 1 branch
BranchTrueFalseTotal
@$order and $now - $$store{$order->[0]}{"at"} >= $RESULT_TTL and do { delete $$store{shift @$order} } 0 0 0
Condition0%0/3
@$order and $now - $$store{$order->[0]}{"at"} >= $RESULT_TTL
!ll&&!rl&&r
000
MC/DC0%0/2
@$order and $now - $$store{$order->[0]}{"at"} >= $RESULT_TTL
@$order $now - $$store{$order->[0]}{"at"} >= $RESULT_TTL
Truth table0%0/3
A and B
A= @$orderB= $now - $$store{$order->[0]}{"at"} >= $RESULT_TTL
ABresult
0X0
100
111
408 0 ▶ delete $store->{ shift @$order } while @$order > $RESULT_MAX;
Branch: 1 branch
BranchTrueFalseTotal
@$order > $RESULT_MAX and do { delete $$store{shift @$order} } 0 0 0
409 }
410  
411 0 ▶sub _store_result ($self, $status, $title, $html, $now = App::teai::Bus::now()) {
Subroutine _store_result: not called CC=2 SCAR=17.9
412 0 my $id = _random_hex();
413 0 $self->{results}{$id} = { status => $status, title => $title, html => $html, at => $now };
414 0 push @{ $self->{result_order} }, $id;
415 0 $self->_prune_results($now);
416 0 return $id;
417 }
418  
419 0 ▶sub _get_result ($self, $id, $now = App::teai::Bus::now()) {
Subroutine _get_result: not called CC=2 SCAR=17.9
420 0 $self->_prune_results($now);
421 0 return $self->{results}{$id};
422 }
423  
424 0 ▶sub _result ($self, $c, $id) {
Subroutine _result: not called CC=2 SCAR=17.9
425 0 my $r = $self->_get_result($id);
426 0 ▶ return $c->page(404, 'Not found', qq{<p>This result has expired or was not found.</p>\n<p><a href="/">sessions</a></p>})
Branch: 1 branch
BranchTrueFalseTotal
unless $r 0 0 0
427 unless $r;
428 0 $c->page($r->{status}, $r->{title}, $r->{html});
429 }
430  
431 0 ▶sub _events ($self, $c) {
Subroutine _events: not called CC=2 SCAR=17.9
432 0 my $req = $c->{req};
433 0 my $w = $req->start_streaming(200, [ @SECURE, 'Content-Type' => 'text/event-stream; charset=utf-8' ]);
434 0 $c->{done} = 1;
435 0 my $id = ++$self->{client_n};
436 0 $self->{clients}{$id} = $w;
437 0 ▶ $self->_poll if keys %{ $self->{clients} } == 1;
Branch: 1 branch
BranchTrueFalseTotal
if keys %{$$self{"clients"};} == 1 0 0 0
438 0 Scalar::Util::weaken(my $weak = $self);
439 0 ▶ my $drop = sub { $weak->_drop($id) if $weak };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
440 0 ▶ $w->on_eof(sub (@) { $drop->() });
Subroutine __ANON__: not called CC=1 SCAR=6.9
441 0 $req->response_guard(App::teai::Dash::Guard->new($drop));
442 0 $w->write("retry: $RETRY_MS\n\n");
443 }
444  
445 0 ▶sub _drop ($self, $id) {
Subroutine _drop: not called CC=2 SCAR=17.9
446 0 ▶ my $w = delete $self->{clients}{$id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $w = delete $self->{"clients"}{$id} or return 0 0 0
447 0 eval { $w->close };
448 }
449  
450 0 ▶sub _send ($self, $text) {
Subroutine _send: not called CC=4 SCAR=30.0
451 0 for my $id (sort { $a <=> $b } keys %{ $self->{clients} }) {
452 0 ▶ my $w = $self->{clients}{$id} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $w = $self->{"clients"}{$id} or next 0 0 0
453 0 ▶ eval { $w->write($text); 1 } or $self->_drop($id);
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $w->write($text); 1 } } or $self->_drop($id) 0 0 0
454 }
455 }
456  
457 0 ▶sub _follow ($self, $from) {
Subroutine _follow: not called CC=1 SCAR=6.9
458 0 Scalar::Util::weaken(my $weak = $self);
459 $self->{scan} = $self->{bus}->scan(
460 filter => 'teai.>', from => $from, follow => 'forever', label => 'dash',
461 0 ▶ record => sub ($r) { $weak->_record($r) if $weak; 0 },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
462 0 ▶ done => sub ($n, $e = undef) {
Subroutine __ANON__: not called CC=5 SCAR=34.0
463 0 ▶ return unless $weak && !$weak->{stopping};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak and not $weak->{"stopping"} 0 0 0
Condition0%0/3
$weak and not $weak->{"stopping"}
!ll&&!rl&&r
000
MC/DC0%0/2
$weak and not $weak->{"stopping"}
$weak not $weak->{"stopping"}
Truth table0%0/3
A and not(B)
A= $weakB= not $weak->{"stopping"}
ABresult
0X0
100
111
464 0 delete $weak->{scan};
465 0 ▶ my $next = defined $weak->{last} ? $weak->{last} + 1 : 'new';
Branch: 1 branch
BranchTrueFalseTotal
defined $weak->{'last'} ? : 0 0 0
466 0 ▶ $weak->{rescan_t} = EV::timer $RESCAN, 0, sub { $weak->_follow($next) if $weak && !$weak->{stopping} };
Subroutine __ANON__: not called CC=3 SCAR=24.8
Branch: 1 branch
BranchTrueFalseTotal
if $weak and not $weak->{"stopping"} 0 0 0
Condition0%0/3
$weak and not $weak->{"stopping"}
!ll&&!rl&&r
000
MC/DC0%0/2
$weak and not $weak->{"stopping"}
$weak not $weak->{"stopping"}
Truth table0%0/3
A and not(B)
A= $weakB= not $weak->{"stopping"}
ABresult
0X0
100
111
467 },
468 0 );
469 }
470  
471 0 ▶sub _record ($self, $r) {
Subroutine _record: not called CC=3 SCAR=24.8
472 0 $self->{last} = $r->{seq};
473 0 ▶ return unless %{ $self->{clients} };
Branch: 1 branch
BranchTrueFalseTotal
unless %{$self->{"clients"};} 0 0 0
474 0 ▶ my $body = $r->{body} // '';
Condition0%0/2
$r->{"body"} // ""
l!l
00
MC/DC0%0/1
$r->{"body"} // ""
$r->{"body"}
Truth table0%0/2
A
A= $r->{"body"}
Aresult
11
00
475 my %data = (
476 bytes => length(Encode::encode('UTF-8', $body)), preview => substr($body =~ s/\s+/ /gr, 0, $PREVIEW),
477 0 map { $_ => $r->{$_} } qw(from kind re seq thread time to via),
478 );
479 0 $self->_send("event: msg\nid: $r->{seq}\ndata: " . _json(\%data) . "\n\n");
480 }
481  
482 0 ▶sub _poll ($self) {
Subroutine _poll: not called CC=5 SCAR=34.0
483 0 ▶ return if $self->{polling} || $self->{stopping};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"polling"} or $self->{"stopping"} 0 0 0
Condition0%0/3
$self->{"polling"} or $self->{"stopping"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"polling"} or $self->{"stopping"}
$self->{"polling"} $self->{"stopping"}
Truth table0%0/3
A or B
A= $self->{"polling"}B= $self->{"stopping"}
ABresult
1X1
011
000
484 0 ▶ if (!%{ $self->{clients} }) { delete $self->{presence}; return }
Branch: 1 branch
BranchTrueFalseTotal
unless (%{$self->{"clients"};}) 0 0 0
485 0 $self->{polling} = 1;
486 0 Scalar::Util::weaken(my $weak = $self);
487 0 ▶ my $got = sub ($list, $err = undef) {
Subroutine __ANON__: not called CC=8 SCAR=42.8
488 0 ▶ return unless $weak;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak 0 0 0
489 0 $weak->{polling} = 0;
490 0 ▶ return if defined $err || $weak->{stopping};
Branch: 1 branch
BranchTrueFalseTotal
if defined $err or $weak->{"stopping"} 0 0 0
Condition0%0/3
defined $err or $weak->{"stopping"}
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $err or $weak->{"stopping"}
defined $err $weak->{"stopping"}
Truth table0%0/3
A or B
A= defined $errB= $weak->{"stopping"}
ABresult
1X1
011
000
491 my %plain = map {
492 0 my $p = $list->{$_};
493 0 ▶ ($_ => { %$p, (defined $p->{error} ? (error => App::teai::Bus::_text($p->{error})) : ()) });
Branch: 1 branch
BranchTrueFalseTotal
defined $p->{'error'} ? : 0 0 0
494 } keys %$list;
495 0 my $now = _json({ map { my %p = %{ $plain{$_} }; delete $p{seen}; ($_ => \%p) } keys %plain });
496 0 my $was = $weak->{presence};
497 0 $weak->{presence} = $now;
498 0 ▶ $weak->_send("event: presence\ndata: " . _json(\%plain) . "\n\n") if defined $was && $was ne $now;
Branch: 1 branch
BranchTrueFalseTotal
if defined $was and $was ne $now 0 0 0
Condition0%0/3
defined $was and $was ne $now
!ll&&!rl&&r
000
MC/DC0%0/2
defined $was and $was ne $now
defined $was $was ne $now
Truth table0%0/3
A and B
A= defined $wasB= $was ne $now
ABresult
0X0
100
111
499 0 };
500 0 ▶ return if eval { App::teai::Presence::list($self->{bus}, $got); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { App::teai::Presence::list($self->{"bus"}, $got); 1 } } 0 0 0
501 0 $self->{polling} = 0;
502 0 _log($@);
503 }
504  
505 package # hide
506 App::teai::Dash::Guard;
507 2 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
508  
509 0 ▶sub new ($class, $cb) { bless { cb => $cb }, $class }
Subroutine new: not called CC=1 SCAR=6.9
510 0 ▶sub DESTROY ($self) { $self->{cb}->() if ${^GLOBAL_PHASE} ne 'DESTRUCT' }
Subroutine DESTROY: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} ne "DESTRUCT" 0 0 0
511  
512 package App::teai::Dash::Ctx;
513 2 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
514  
515 0 ▶sub new ($class, %a) { bless {%a}, $class }
Subroutine new: not called CC=1 SCAR=6.9
516 0 ▶sub bus ($c) { $c->{dash}{bus} }
Subroutine bus: not called CC=1 SCAR=6.9
517 0 ▶sub operator ($c) { $c->{dash}{operator} }
Subroutine operator: not called CC=1 SCAR=6.9
518 0 ▶sub project ($c) { $c->{dash}{project} }
Subroutine project: not called CC=1 SCAR=6.9
519 0 ▶sub param ($c, $name) { my $v = $c->{params}{$name}; $v ? $v->[0] : undef }
Subroutine param: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
$v ? : 0 0 0
520 0 ▶sub params ($c, $name) { @{ $c->{params}{$name} // [] } }
Subroutine params: not called CC=2 SCAR=17.9
Condition0%0/2
$c->{"params"}{$name} // []
l!l
00
MC/DC0%0/1
$c->{"params"}{$name} // []
$c->{"params"}{$name}
Truth table0%0/2
A
A= $c->{"params"}{$name}
Aresult
11
00
521  
522 0 ▶sub form ($c, $action, $hidden, $inner, $button) {
Subroutine form: not called CC=3 SCAR=24.8
523 0 my $esc = \&App::teai::Dash::esc;
524 return join '', '<form method="post" action="', $esc->($action), '">',
525 0 (map { '<input type="hidden" name="' . $esc->($_) . '" value="' . $esc->($hidden->{$_}) . '">' }
526 0 ▶ sort keys %{ $hidden // {} }),
Condition0%0/4
$hidden // {}
l!l
00
$inner // ""
l!l
00
MC/DC0%0/1
$hidden // {}
$hidden
MC/DC0%0/1
$inner // ""
$inner
Truth table0%0/2
A
A= $hidden
Aresult
11
00
Truth table0%0/2
A
A= $inner
Aresult
11
00
527 0 '<input type="hidden" name="f" value="', $c->{dash}->_token_for($action), '">',
528 $inner // '', '<button type="submit">', $esc->($button), '</button></form>';
529 }
530  
531 0 ▶sub page ($c, $status, $title, $html, %o) {
Subroutine page: not called CC=2 SCAR=17.9
532 0 ▶ return if $c->{done}++;
Branch: 1 branch
BranchTrueFalseTotal
if $c->{"done"}++ 0 0 0
533 $c->{dash}->_respond($c->{req}, $status, [ 'Content-Type' => 'text/html; charset=utf-8' ],
534 0 Encode::encode('UTF-8', $c->{dash}->_layout($title, $html, $o{watch})));
535 }
536  
537 0 ▶sub result ($c, $status, $title, $html) {
Subroutine result: not called CC=2 SCAR=17.9
538 0 ▶ return if $c->{done}++;
Branch: 1 branch
BranchTrueFalseTotal
if $c->{"done"}++ 0 0 0
539 0 my $id = $c->{dash}->_store_result($status, $title, $html);
540 0 $c->{dash}->_plain($c->{req}, 303, "see /result/$id", Location => "/result/$id");
541 }
542  
543 0 ▶sub _fail_page ($err, $html = '') {
Subroutine _fail_page: not called CC=7 SCAR=40.3
544 0 ▶ my $code = ref $err && eval { $err->isa('App::teai::Err') } ? App::teai::Err::code($err) : 3;
Branch: 1 branch
BranchTrueFalseTotal
ref $err && eval { do { $err->isa('App::teai::Err') } } ? : 0 0 0
Condition0%0/3
ref $err and eval { do { $err->isa("App::teai::Err") } }
!ll&&!rl&&r
000
MC/DC0%0/2
ref $err and eval { do { $err->isa("App::teai::Err") } }
ref $err eval { do { $err->isa("App::teai::Err") } }
Truth table0%0/3
A and B
A= ref $errB= eval { do { $err->isa("App::teai::Err") } }
ABresult
0X0
100
111
545 0 ▶ my $status = $code == 1 || $code == 2 ? 400 : $code == 4 ? 409 : 502;
Branch: 2 branches
BranchTrueFalseTotal
$code == 1 || $code == 2 ? : 0 0 0
$code == 4 ? : 0 0 0
Condition0%0/3
$code == 1 or $code == 2
l!l&&r!l&&!r
000
MC/DC0%0/2
$code == 1 or $code == 2
$code == 1 $code == 2
Truth table0%0/3
A or B
A= $code == 1B= $code == 2
ABresult
1X1
011
000
546 0 return ($status, 'Error',
547 '<p class="error">' . App::teai::Dash::esc('teai: ' . App::teai::Bus::_text($err)) . "</p>\n$html");
548 }
549  
550 0 ▶sub fail ($c, $err, $html = '') { $c->page(_fail_page($err, $html)) }
Subroutine fail: not called CC=2 SCAR=17.9
551  
552 0 ▶sub fail_result ($c, $err, $html = '') { $c->result(_fail_page($err, $html)) }
Subroutine fail_result: not called CC=2 SCAR=17.9
553  
554 0 ▶sub fail_after ($c, $err, $html = '') {
Subroutine fail_after: not called CC=3 SCAR=24.8
555 0 my ($status, $title, $body) = _fail_page($err, $html);
556 0 ▶ $status >= 500 ? $c->result($status, $title, $body) : $c->page($status, $title, $body);
Branch: 1 branch
BranchTrueFalseTotal
$status >= 500 ? : 0 0 0
557 }
558  
559 0 ▶sub cb ($c, $code) {
Subroutine cb: not called CC=1 SCAR=6.9
560 0 ▶ return sub (@args) {
Subroutine __ANON__: not called CC=5 SCAR=34.0
561 0 my $want = wantarray;
562 0 my @r;
563 0 ▶ eval { if ($want) { @r = $code->(@args) } else { $r[0] = $code->(@args) } 1 }
Branch: 2 branches
BranchTrueFalseTotal
if ($want) { } 0 0 0
$c->{'done'} ? : 0 0 0
564 0 ▶ or $c->{done} ? App::teai::Dash::_log($@) : $c->fail($@);
Branch: 1 branch
BranchTrueFalseTotal
eval { do { if ($want) { @r = &$code(@args); } else { $r[0] = &$code(@args); } ; 1 } } or $c->{"done"} ? App::teai::Dash::_log($@) : $c->fail($@) 0 0 0
565 0 ▶ return $want ? @r : $r[0];
Branch: 1 branch
BranchTrueFalseTotal
$want ? : 0 0 0
566 0 };
567 }
568  
569 0 ▶sub hold ($c, $start, $then) {
Subroutine hold: not called CC=2 SCAR=17.9
570 0 my ($h, $over);
571 0 ▶ $h = $start->($c->cb(sub (@r) { $over = 1; undef $h; $then->(@r) }));
Subroutine __ANON__: not called CC=1 SCAR=6.9
572 0 ▶ undef $h if $over;
Branch: 1 branch
BranchTrueFalseTotal
if $over 0 0 0
573 0 ▶ $c->on_close(sub { my $x = $h; undef $h; $x->cancel if $x });
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $x 0 0 0
574 }
575  
576 0 ▶sub own_inbox ($c, $then) {
Subroutine own_inbox: not called CC=1 SCAR=6.9
577 0 my $attrs = { agent => 'shell', project => $c->project, role => 'operator' };
578 0 ▶ App::teai::Dash::own_inbox($c->bus, $c->operator, $attrs, $c->cb(sub ($ok, $e = undef) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
579 0 ▶ defined $e ? $c->fail($e) : $then->();
Branch: 1 branch
BranchTrueFalseTotal
defined $e ? : 0 0 0
580 0 }));
581 }
582  
583 0 ▶sub on_close ($c, $cb) {
Subroutine on_close: not called CC=3 SCAR=24.8
584 0 push @{ $c->{closing} }, $cb;
585 0 ▶ return if $c->{guarded}++;
Branch: 1 branch
BranchTrueFalseTotal
if $c->{"guarded"}++ 0 0 0
586 0 my $list = $c->{closing};
587 0 my $key = Scalar::Util::refaddr($list);
588 0 Scalar::Util::weaken(my $dash = $c->{dash});
589 0 ▶ $dash->{closing}{$key} = $list if $dash;
Branch: 1 branch
BranchTrueFalseTotal
if $dash 0 0 0
590 0 ▶ $c->{req}->response_guard(App::teai::Dash::Guard->new(sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
591 0 ▶ delete $dash->{closing}{$key} if $dash;
Branch: 1 branch
BranchTrueFalseTotal
if $dash 0 0 0
592 0 ▶ for my $cb (splice @$list) { eval { $cb->(); 1 } or App::teai::Dash::_log($@) }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$cb(); 1 } } or App::teai::Dash::_log($@) 0 0 0
593 0 }));
594 }
595  
596 0 ▶sub _static ($c, $type, $text) {
Subroutine _static: not called CC=2 SCAR=17.9
597 0 ▶ return if $c->{done}++;
Branch: 1 branch
BranchTrueFalseTotal
if $c->{"done"}++ 0 0 0
598 0 $c->{dash}->_respond($c->{req}, 200, [ 'Content-Type' => $type ], $text);
599 }
600  
601 package App::teai::Dash;
602  
603 2 1;
604 __END__
« lib/App/teai/Hook.pm ↑ Summary lib/App/teai/MCP/Tools.pm »