blib/lib/SignalWire/Agents/Relay/Client.pm

filter: Statementstmt 48.8% 169 / 346 Branchbran 33.0% 43 / 130 Conditioncond 32.4% 35 / 108 MC/DCmcdc 11.6% 7 / 60 Subroutinesub 63.3% 38 / 60 Podpod 0.0% 0 / 13 totaltotal 40.7% 292 / 717 CC 116 SCAR 36.8
CC
116
Cov
42%
send_message
156.0
dial
156.0
authenticate
56.0
CRAP 39.8
« blib/lib/SignalWire/Agents/REST/HttpClient.pm ↑ Summary blib/lib/SignalWire/Agents/Relay/Call.pm »
1 package SignalWire::Agents::Relay::Client;
2 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 3 ▶use JSON qw(encode_json decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use IO::Socket::SSL;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use Protocol::WebSocket::Client;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use SignalWire::Agents::Relay::Constants qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
10 PROTOCOL_VERSION
11 CALL_TERMINAL_STATES
12 DIAL_STATE_ANSWERED DIAL_STATE_FAILED
13 MESSAGE_TERMINAL_STATES
14 3 );
15 3 ▶use SignalWire::Agents::Relay::Event;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 3 ▶use SignalWire::Agents::Relay::Call;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 3 ▶use SignalWire::Agents::Relay::Message;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 3 ▶use SignalWire::Agents::Logging;
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 3 my $logger = SignalWire::Agents::Logging->get_logger('relay_client');
21  
22 3 has 'project' => ( is => 'ro', required => 1 );
23 3 has 'token' => ( is => 'ro', required => 1 );
24 3 has 'host' => ( is => 'ro', required => 1 );
25 19 ▶has 'contexts' => ( is => 'rw', default => sub { [] } );
Subroutine __ANON__: called CC=1 SCAR=0.0
26 20 ▶has 'agent' => ( is => 'ro', default => sub { 'signalwire-agents-perl/1.0' } );
Subroutine __ANON__: called CC=1 SCAR=0.0
27  
28 # Connection state
29 20 ▶has 'protocol' => ( is => 'rw', default => sub { '' } );
Subroutine __ANON__: called CC=1 SCAR=0.0
30 20 ▶has 'authorization_state' => ( is => 'rw', default => sub { '' } );
Subroutine __ANON__: called CC=1 SCAR=0.0
31 20 ▶has 'connected' => ( is => 'rw', default => sub { 0 } );
Subroutine __ANON__: called CC=1 SCAR=0.0
32 20 ▶has 'session_id' => ( is => 'rw', default => sub { '' } );
Subroutine __ANON__: called CC=1 SCAR=0.0
33  
34 # Correlation maps
35 20 ▶has '_pending' => ( is => 'rw', default => sub { {} } ); # rpc_id => { resolve => sub, reject => sub }
Subroutine __ANON__: called CC=1 SCAR=0.0
36 20 ▶has '_calls' => ( is => 'rw', default => sub { {} } ); # call_id => Call
Subroutine __ANON__: called CC=1 SCAR=0.0
37 20 ▶has '_pending_dials' => ( is => 'rw', default => sub { {} } ); # tag => { resolve => sub, reject => sub }
Subroutine __ANON__: called CC=1 SCAR=0.0
38 20 ▶has '_messages' => ( is => 'rw', default => sub { {} } ); # message_id => Message
Subroutine __ANON__: called CC=1 SCAR=0.0
39  
40 # WebSocket internals
41 20 ▶has '_socket' => ( is => 'rw', default => sub { undef } );
Subroutine __ANON__: called CC=1 SCAR=0.0
42 20 ▶has '_ws' => ( is => 'rw', default => sub { undef } );
Subroutine __ANON__: called CC=1 SCAR=0.0
43  
44 # Reconnect state
45 20 ▶has '_reconnect_attempts' => ( is => 'rw', default => sub { 0 } );
Subroutine __ANON__: called CC=1 SCAR=0.0
46 20 ▶has '_max_backoff' => ( is => 'ro', default => sub { 30 } );
Subroutine __ANON__: called CC=1 SCAR=0.0
47  
48 # Callbacks
49 20 ▶has '_on_call' => ( is => 'rw', default => sub { undef } );
Subroutine __ANON__: called CC=1 SCAR=0.0
50 20 ▶has '_on_message' => ( is => 'rw', default => sub { undef } );
Subroutine __ANON__: called CC=1 SCAR=0.0
51 20 ▶has '_on_event' => ( is => 'rw', default => sub { undef } );
Subroutine __ANON__: called CC=1 SCAR=0.0
52  
53 # --- UUID generation ---
54 0 ▶sub _generate_uuid {
Subroutine _generate_uuid: not called CC=1 SCAR=6.9
55 0 my @hex = map { sprintf('%02x', int(rand(256))) } 1..16;
56 0 $hex[6] = sprintf('%02x', (hex($hex[6]) & 0x0f) | 0x40);
57 0 $hex[8] = sprintf('%02x', (hex($hex[8]) & 0x3f) | 0x80);
58 0 return join('-',
59 join('', @hex[0..3]),
60 join('', @hex[4..5]),
61 join('', @hex[6..7]),
62 join('', @hex[8..9]),
63 join('', @hex[10..15]),
64 );
65 }
66  
67 # --- Public API: register handlers ---
68  
69 2 ▶sub on_call {
Subroutine on_call: called CC=1 SCAR=0.0
Pod undocumented
70 2 my ($self, $cb) = @_;
71 2 $self->_on_call($cb);
72 2 return $self;
73 }
74  
75 3 ▶sub on_message {
Subroutine on_message: called CC=1 SCAR=0.0
Pod undocumented
76 3 my ($self, $cb) = @_;
77 3 $self->_on_message($cb);
78 3 return $self;
79 }
80  
81 1 ▶sub on_event {
Subroutine on_event: called CC=1 SCAR=0.0
Pod undocumented
82 1 my ($self, $cb) = @_;
83 1 $self->_on_event($cb);
84 1 return $self;
85 }
86  
87 # --- Connection ---
88  
89 0 ▶sub connect_ws {
Subroutine connect_ws: not called CC=4 SCAR=30.0
Pod undocumented
90 0 my ($self) = @_;
91  
92 0 my $host = $self->host;
93 0 my $port = 443;
94  
95 0 $logger->debug("Connecting to wss://$host");
96  
97 0 my $socket = IO::Socket::SSL->new(
98 PeerHost => $host,
99 PeerPort => $port,
100 SSL_verify_mode => SSL_VERIFY_PEER,
101 Timeout => 10,
102 );
103 0 ▶ unless ($socket) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($socket) 0 0 0
104 0 $logger->error("SSL connection failed: $! $IO::Socket::SSL::SSL_ERROR");
105 0 return 0;
106 }
107  
108 0 my $ws = Protocol::WebSocket::Client->new(url => "wss://$host");
109  
110 0 ▶ $ws->on(write => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
111 0 my ($ws_client, $buf) = @_;
112 0 syswrite($socket, $buf);
113 0 });
114  
115 0 ▶ $ws->on(connect => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
116 0 $logger->debug("WebSocket connected");
117 0 });
118  
119 0 ▶ $ws->on(error => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
120 0 my ($ws_client, $error) = @_;
121 0 $logger->error("WebSocket error: $error");
122 0 });
123  
124 0 ▶ $ws->on(read => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
125 0 my ($ws_client, $message) = @_;
126 0 $self->_handle_message($message);
127 0 });
128  
129 0 $self->_socket($socket);
130 0 $self->_ws($ws);
131  
132 # Initiate the WebSocket handshake
133 0 $ws->connect;
134  
135 # Read the handshake response
136 0 my $buf = '';
137 0 ▶ while (my $bytes = sysread($socket, $buf, 4096, length($buf))) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $bytes = sysread($socket, $buf, 4096, length $buf)) 0 0 0
138 0 $ws->read($buf);
139 0 $buf = '';
140 0 ▶ last if $ws->{hs}->is_done;
Branch: 1 branch
BranchTrueFalseTotal
if $ws->{"hs"}->is_done 0 0 0
141 }
142  
143 0 $self->connected(1);
144 0 $self->_reconnect_attempts(0);
145 0 return 1;
146 }
147  
148 0 ▶sub authenticate {
Subroutine authenticate: not called CC=7 SCAR=40.3
Pod undocumented
149 0 my ($self) = @_;
150  
151 0 my %params = (
152 version => PROTOCOL_VERSION,
153 agent => $self->agent,
154 event_acks => JSON::true,
155 authentication => {
156 project => $self->project,
157 token => $self->token,
158 },
159 );
160  
161 # Add contexts if any
162 0 ▶ if (@{$self->contexts}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->contexts;}) 0 0 0
163 0 $params{contexts} = $self->contexts;
164 }
165  
166 # Add protocol for session resume
167 0 ▶ if ($self->protocol) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->protocol) 0 0 0
168 0 $params{protocol} = $self->protocol;
169 }
170  
171 # Add authorization_state for fast re-auth
172 0 ▶ if ($self->authorization_state) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->authorization_state) 0 0 0
173 0 $params{authorization_state} = $self->authorization_state;
174 }
175  
176 0 my $result = $self->execute('signalwire.connect', \%params);
177  
178 0 ▶ if (ref $result eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $result eq "HASH") 0 0 0
179 0 ▶ $self->protocol($result->{protocol}) if $result->{protocol};
Branch: 1 branch
BranchTrueFalseTotal
if $result->{"protocol"} 0 0 0
180 0 ▶ $self->session_id($result->{session_id}) if $result->{session_id};
Branch: 1 branch
BranchTrueFalseTotal
if $result->{"session_id"} 0 0 0
181 }
182  
183 0 return $result;
184 }
185  
186 # --- JSON-RPC execute ---
187  
188 0 ▶sub execute {
Subroutine execute: not called CC=7 SCAR=40.3
Pod undocumented
189 0 my ($self, $method, $params) = @_;
190 0 ▶ $params //= {};
Condition0%0/2
$params //= {}
l!l
00
MC/DC0%0/1
$params //= {}
$params
Truth table0%0/2
A
A= $params
Aresult
11
00
191  
192 0 my $id = _generate_uuid();
193  
194 # Add protocol to params (except for signalwire.connect itself)
195 0 ▶ if ($method ne 'signalwire.connect' && $self->protocol) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method ne "signalwire.connect" and $self->protocol) 0 0 0
Condition0%0/3
$method ne "signalwire.connect" and $self->protocol
!ll&&!rl&&r
000
MC/DC0%0/2
$method ne "signalwire.connect" and $self->protocol
$method ne "signalwire.connect" $self->protocol
Truth table0%0/3
A and B
A= $method ne "signalwire.connect"B= $self->protocol
ABresult
0X0
100
111
196 0 $params->{protocol} = $self->protocol;
197 }
198  
199 0 my $request = {
200 jsonrpc => '2.0',
201 id => $id,
202 method => $method,
203 params => $params,
204 };
205  
206 # Register pending
207 0 my $result;
208 0 my $done = 0;
209 0 my $error;
210 $self->_pending->{$id} = {
211 0 ▶ resolve => sub { $result = $_[0]; $done = 1 },
Subroutine __ANON__: not called CC=1 SCAR=6.9
212 0 ▶ reject => sub { $error = $_[0]; $done = 1 },
Subroutine __ANON__: not called CC=1 SCAR=6.9
213 0 };
214  
215 0 $self->_send($request);
216  
217 # Poll for response (synchronous in this implementation)
218 0 my $timeout = 30;
219 0 my $start = time();
220 0 ▶ while (!$done && (time() - $start) < $timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $done and time - $start < $timeout) 0 0 0
Condition0%0/3
not $done and time - $start < $timeout
!ll&&!rl&&r
000
MC/DC0%0/2
not $done and time - $start < $timeout
not $done time - $start < $timeout
Truth table0%0/3
not(A) and B
A= not $doneB= time - $start < $timeout
ABresult
0X0
100
111
221 0 $self->_read_once();
222 }
223  
224 0 delete $self->_pending->{$id};
225  
226 0 ▶ if ($error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error) 0 0 0
227 0 die "RELAY error: $error";
228 }
229  
230 0 return $result;
231 }
232  
233 # --- Messaging ---
234  
235 0 ▶sub send_message {
Subroutine send_message: not called CC=12 SCAR=50.5
Pod undocumented
236 0 my ($self, %opts) = @_;
237  
238 0 my %params;
239 0 for my $key (qw(context to_number from_number body media tags region)) {
240 0 ▶ $params{$key} = $opts{$key} if exists $opts{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{$key} 0 0 0
241 }
242  
243 0 my $result = $self->execute('messaging.send', \%params);
244  
245 0 ▶ if (ref $result eq 'HASH' && $result->{message_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $result eq "HASH" and $result->{"message_id"}) 0 0 0
Condition0%0/3
ref $result eq "HASH" and $result->{"message_id"}
!ll&&!rl&&r
000
MC/DC0%0/2
ref $result eq "HASH" and $result->{"message_id"}
ref $result eq "HASH" $result->{"message_id"}
Truth table0%0/3
A and B
A= ref $result eq "HASH"B= $result->{"message_id"}
ABresult
0X0
100
111
246 my $msg = SignalWire::Agents::Relay::Message->new(
247 message_id => $result->{message_id},
248 context => $opts{context} // '',
249 direction => 'outbound',
250 from_number => $opts{from_number} // '',
251 to_number => $opts{to_number} // '',
252 body => $opts{body} // '',
253 media => $opts{media} // [],
254 0 ▶ tags => $opts{tags} // [],
Condition0%0/12
$opts{"context"} // ""
l!l
00
$opts{"from_number"} // ""
l!l
00
$opts{"to_number"} // ""
l!l
00
$opts{"body"} // ""
l!l
00
$opts{"media"} // []
l!l
00
$opts{"tags"} // []
l!l
00
MC/DC0%0/1
$opts{"context"} // ""
$opts{"context"}
MC/DC0%0/1
$opts{"from_number"} // ""
$opts{"from_number"}
MC/DC0%0/1
$opts{"to_number"} // ""
$opts{"to_number"}
MC/DC0%0/1
$opts{"body"} // ""
$opts{"body"}
MC/DC0%0/1
$opts{"media"} // []
$opts{"media"}
MC/DC0%0/1
$opts{"tags"} // []
$opts{"tags"}
Truth table0%0/2
A
A= $opts{"context"}
Aresult
11
00
Truth table0%0/2
A
A= $opts{"from_number"}
Aresult
11
00
Truth table0%0/2
A
A= $opts{"to_number"}
Aresult
11
00
Truth table0%0/2
A
A= $opts{"body"}
Aresult
11
00
Truth table0%0/2
A
A= $opts{"media"}
Aresult
11
00
Truth table0%0/2
A
A= $opts{"tags"}
Aresult
11
00
255 state => 'queued',
256 );
257 0 $self->_messages->{$result->{message_id}} = $msg;
258  
259 0 ▶ if ($opts{on_completed}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"on_completed"}) 0 0 0
260 0 $msg->on_completed($opts{on_completed});
261 }
262  
263 0 return $msg;
264 }
265  
266 0 return $result;
267 }
268  
269 # --- Context management ---
270  
271 0 ▶sub receive {
Subroutine receive: not called CC=1 SCAR=6.9
Pod undocumented
272 0 my ($self, @contexts) = @_;
273 0 return $self->execute('signalwire.receive', { contexts => \@contexts });
274 }
275  
276 0 ▶sub unreceive {
Subroutine unreceive: not called CC=1 SCAR=6.9
Pod undocumented
277 0 my ($self, @contexts) = @_;
278 0 return $self->execute('signalwire.unreceive', { contexts => \@contexts });
279 }
280  
281 # --- Dial ---
282  
283 0 ▶sub dial {
Subroutine dial: not called CC=12 SCAR=50.5
Pod undocumented
284 0 my ($self, %opts) = @_;
285 0 ▶ my $tag = $opts{tag} || _generate_uuid();
Condition0%0/3
$opts{'tag'} || _generate_uuid()
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{'tag'} || _generate_uuid()
$opts{'tag'} _generate_uuid()
Truth table0%0/3
A || B
A= $opts{'tag'}B= _generate_uuid()
ABresult
1X1
011
000
286 0 ▶ my $timeout = delete $opts{timeout} || 120;
Condition0%0/2
delete $opts{'timeout'} || 120
l!l
00
MC/DC0%0/1
delete $opts{'timeout'} || 120
delete $opts{'timeout'}
Truth table0%0/2
A
A= delete $opts{'timeout'}
Aresult
11
00
287 0 my $on_completed = delete $opts{on_completed};
288  
289 0 my %params = ( tag => $tag );
290 0 ▶ $params{devices} = $opts{devices} if $opts{devices};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"devices"} 0 0 0
291 0 ▶ $params{region} = $opts{region} if $opts{region};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"region"} 0 0 0
292 0 ▶ $params{max_price_per_minute} = $opts{max_price_per_minute} if exists $opts{max_price_per_minute};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"max_price_per_minute"} 0 0 0
293  
294 # Register pending dial BEFORE sending RPC
295 0 my $call;
296 0 my $done = 0;
297 0 my $dial_error;
298 $self->_pending_dials->{$tag} = {
299 0 ▶ resolve => sub { $call = $_[0]; $done = 1 },
Subroutine __ANON__: not called CC=1 SCAR=6.9
300 0 ▶ reject => sub { $dial_error = $_[0]; $done = 1 },
Subroutine __ANON__: not called CC=1 SCAR=6.9
301 0 };
302  
303 # Send the RPC -- response is just {code:200, message:"Dialing"}
304 0 eval { $self->execute('calling.dial', \%params) };
305 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
306 0 delete $self->_pending_dials->{$tag};
307 0 die $@;
308 }
309  
310 # Wait for calling.call.dial event to resolve
311 0 my $start = time();
312 0 ▶ while (!$done && (time() - $start) < $timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $done and time - $start < $timeout) 0 0 0
Condition0%0/3
not $done and time - $start < $timeout
!ll&&!rl&&r
000
MC/DC0%0/2
not $done and time - $start < $timeout
not $done time - $start < $timeout
Truth table0%0/3
not(A) and B
A= not $doneB= time - $start < $timeout
ABresult
0X0
100
111
313 0 $self->_read_once();
314 }
315  
316 0 delete $self->_pending_dials->{$tag};
317  
318 0 ▶ if ($dial_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dial_error) 0 0 0
319 0 die "Dial failed: $dial_error";
320 }
321  
322 0 ▶ if ($call && $on_completed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($call and $on_completed) 0 0 0
Condition0%0/3
$call and $on_completed
!ll&&!rl&&r
000
MC/DC0%0/2
$call and $on_completed
$call $on_completed
Truth table0%0/3
A and B
A= $callB= $on_completed
ABresult
0X0
100
111
323 0 ▶ $call->on(sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
324 0 my ($c, $event) = @_;
325 0 ▶ if ($event->event_type eq 'calling.call.state' && $event->call_state eq 'ended') {
Branch: 1 branch
BranchTrueFalseTotal
if ($event->event_type eq "calling.call.state" and $event->call_state eq "ended") 0 0 0
Condition0%0/3
$event->event_type eq "calling.call.state" and $event->call_state eq "ended"
!ll&&!rl&&r
000
MC/DC0%0/2
$event->event_type eq "calling.call.state" and $event->call_state eq "ended"
$event->event_type eq "calling.call.state" $event->call_state eq "ended"
Truth table0%0/3
A and B
A= $event->event_type eq "calling.call.state"B= $event->call_state eq "ended"
ABresult
0X0
100
111
326 0 eval { $on_completed->($c) };
327 0 ▶ warn "dial on_completed error: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
328 }
329 0 });
330 }
331  
332 0 return $call;
333 }
334  
335 # --- Internal: send a JSON-RPC message ---
336  
337 0 ▶sub _send {
Subroutine _send: not called CC=2 SCAR=17.9
338 0 my ($self, $msg) = @_;
339 0 my $json = encode_json($msg);
340 0 $logger->debug("SEND: $json");
341 0 my $ws = $self->_ws;
342 0 ▶ if ($ws) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ws) 0 0 0
343 0 $ws->write($json);
344 }
345 }
346  
347 # --- Internal: read one frame from WebSocket ---
348  
349 0 ▶sub _read_once {
Subroutine _read_once: not called CC=7 SCAR=40.3
350 0 my ($self) = @_;
351 0 my $socket = $self->_socket;
352 0 ▶ return unless $socket;
Branch: 1 branch
BranchTrueFalseTotal
unless $socket 0 0 0
353  
354 0 my $buf = '';
355 0 my $ready = '';
356 0 vec($ready, fileno($socket), 1) = 1;
357 0 ▶ if (select($ready, undef, undef, 0.1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (select $ready, undef, undef, "0.1") 0 0 0
358 0 my $bytes = sysread($socket, $buf, 4096);
359 0 ▶ if ($bytes && $bytes > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($bytes and $bytes > 0) { } 0 0 0
elsif (not defined $bytes or $bytes == 0) { } 0 0 0
Condition0%0/3
$bytes and $bytes > 0
!ll&&!rl&&r
000
MC/DC0%0/2
$bytes and $bytes > 0
$bytes $bytes > 0
Truth table0%0/3
A and B
A= $bytesB= $bytes > 0
ABresult
0X0
100
111
360 0 $self->_ws->read($buf);
361 ▶ } elsif (!defined $bytes || $bytes == 0) {
Condition0%0/3
not defined $bytes or $bytes == 0
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $bytes or $bytes == 0
not defined $bytes $bytes == 0
Truth table0%0/3
not(A) or B
A= not defined $bytesB= $bytes == 0
ABresult
1X1
011
000
362 # Connection lost
363 0 $self->connected(0);
364 }
365 }
366 }
367  
368 # --- Internal: handle an incoming WebSocket message ---
369  
370 4 ▶sub _handle_message {
Subroutine _handle_message: called CC=13 SCAR=28.6
371 4 my ($self, $raw) = @_;
372 4 $logger->debug("RECV: $raw");
373  
374 4 my $msg;
375 4 eval { $msg = decode_json($raw) };
376 4 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 4 4
377 0 $logger->error("JSON parse error: $@");
378 0 return;
379 }
380  
381 # JSON-RPC response (has "result" or "error", matched by "id")
382 4 ▶ if (exists $msg->{result} || exists $msg->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $msg->{"result"} or exists $msg->{"error"}) 2 2 4
Condition100%3/3
exists $msg->{"result"} or exists $msg->{"error"}
l!l&&r!l&&!r
112
MC/DC100%2/2
exists $msg->{"result"} or exists $msg->{"error"}
exists $msg->{"result"} exists $msg->{"error"}
Truth table100%3/3
A or B
A= exists $msg->{"result"}B= exists $msg->{"error"}
ABresult
1X1
011
000
383 2 ▶ my $id = $msg->{id} // '';
Condition50%1/2
$msg->{"id"} // ""
l!l
20
MC/DC0%0/1
$msg->{"id"} // ""
$msg->{"id"}
Truth table50%1/2
A
A= $msg->{"id"}
Aresult
11
00
384 2 ▶ if (my $pending = delete $self->_pending->{$id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pending = delete $self->_pending->{$id}) 2 0 2
385 2 ▶ if (exists $msg->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $msg->{'error'}) { } 1 1 2
386 1 $pending->{reject}->($msg->{error});
387 } else {
388 1 $pending->{resolve}->($msg->{result});
389 }
390 }
391 2 return;
392 }
393  
394 # Server-initiated method call
395 2 ▶ my $method = $msg->{method} // '';
Condition50%1/2
$msg->{"method"} // ""
l!l
20
MC/DC0%0/1
$msg->{"method"} // ""
$msg->{"method"}
Truth table50%1/2
A
A= $msg->{"method"}
Aresult
11
00
396  
397 2 ▶ if ($method eq 'signalwire.event') {
Branch: 3 branches
BranchTrueFalseTotal
if ($method eq 'signalwire.event') { } 1 1 2
elsif ($method eq 'signalwire.ping') { } 1 0 1
elsif ($method eq 'signalwire.disconnect') { } 0 0 0
398 # ACK the event immediately
399 1 $self->_send_ack($msg->{id});
400 1 ▶ $self->_handle_event($msg->{params} // {});
Condition50%1/2
$msg->{"params"} // {}
l!l
10
MC/DC0%0/1
$msg->{"params"} // {}
$msg->{"params"}
Truth table50%1/2
A
A= $msg->{"params"}
Aresult
11
00
401 }
402 elsif ($method eq 'signalwire.ping') {
403 1 $self->_send_ack($msg->{id});
404 }
405 elsif ($method eq 'signalwire.disconnect') {
406 0 $self->_send_ack($msg->{id});
407 0 ▶ $self->_handle_disconnect($msg->{params} // {});
Condition0%0/2
$msg->{"params"} // {}
l!l
00
MC/DC0%0/1
$msg->{"params"} // {}
$msg->{"params"}
Truth table0%0/2
A
A= $msg->{"params"}
Aresult
11
00
408 }
409 }
410  
411 # --- Internal: send an ACK ---
412  
413 2 ▶sub _send_ack {
Subroutine _send_ack: called CC=1 SCAR=0.0
414 2 my ($self, $id) = @_;
415 2 $self->_send({
416 jsonrpc => '2.0',
417 id => $id,
418 result => {},
419 });
420 }
421  
422 # --- Internal: handle events ---
423  
424 18 ▶sub _handle_event {
Subroutine _handle_event: called CC=26 SCAR=35.0
425 18 my ($self, $outer_params) = @_;
426 18 ▶ my $event_type = $outer_params->{event_type} // '';
Condition50%1/2
$outer_params->{"event_type"} // ""
l!l
180
MC/DC0%0/1
$outer_params->{"event_type"} // ""
$outer_params->{"event_type"}
Truth table50%1/2
A
A= $outer_params->{"event_type"}
Aresult
11
00
427 18 ▶ my $inner_params = $outer_params->{params} // {};
Condition50%1/2
$outer_params->{"params"} // {}
l!l
180
MC/DC0%0/1
$outer_params->{"params"} // {}
$outer_params->{"params"}
Truth table50%1/2
A
A= $outer_params->{"params"}
Aresult
11
00
428  
429 # Parse into typed event object
430 18 my $event = SignalWire::Agents::Relay::Event->parse_event($event_type, $inner_params);
431  
432 # Fire global event callback
433 18 ▶ if (my $cb = $self->_on_event) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = $self->_on_event) 0 18 18
434 0 eval { $cb->($event) };
435 0 ▶ warn "on_event callback error: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
436 }
437  
438 # --- Authorization state ---
439 18 ▶ if ($event_type eq 'signalwire.authorization.state') {
Branch: 1 branch
BranchTrueFalseTotal
if ($event_type eq "signalwire.authorization.state") 1 17 18
440 1 ▶ $self->authorization_state($inner_params->{authorization_state} // '');
Condition50%1/2
$inner_params->{"authorization_state"} // ""
l!l
10
MC/DC0%0/1
$inner_params->{"authorization_state"} // ""
$inner_params->{"authorization_state"}
Truth table50%1/2
A
A= $inner_params->{"authorization_state"}
Aresult
11
00
441 1 return;
442 }
443  
444 # --- Inbound call ---
445 17 ▶ if ($event_type eq 'calling.call.receive') {
Branch: 1 branch
BranchTrueFalseTotal
if ($event_type eq "calling.call.receive") 1 16 17
446 1 $self->_handle_inbound_call($event, $inner_params);
447 1 return;
448 }
449  
450 # --- Inbound message ---
451 16 ▶ if ($event_type eq 'messaging.receive') {
Branch: 1 branch
BranchTrueFalseTotal
if ($event_type eq "messaging.receive") 2 14 16
452 2 $self->_handle_inbound_message($event);
453 2 return;
454 }
455  
456 # --- Message state ---
457 14 ▶ if ($event_type eq 'messaging.state') {
Branch: 1 branch
BranchTrueFalseTotal
if ($event_type eq "messaging.state") 4 10 14
458 4 ▶ my $message_id = $inner_params->{message_id} // '';
Condition50%1/2
$inner_params->{"message_id"} // ""
l!l
40
MC/DC0%0/1
$inner_params->{"message_id"} // ""
$inner_params->{"message_id"}
Truth table50%1/2
A
A= $inner_params->{"message_id"}
Aresult
11
00
459 4 ▶ if (my $msg = $self->_messages->{$message_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $msg = $self->_messages->{$message_id}) 4 0 4
460 4 $msg->dispatch_event($event);
461 4 ▶ if ($msg->completed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($msg->completed) 2 2 4
462 2 delete $self->_messages->{$message_id};
463 }
464 }
465 4 return;
466 }
467  
468 # --- Dial completion ---
469 10 ▶ if ($event_type eq 'calling.call.dial') {
Branch: 1 branch
BranchTrueFalseTotal
if ($event_type eq "calling.call.dial") 5 5 10
470 5 $self->_handle_dial_event($event, $inner_params);
471 5 return;
472 }
473  
474 # --- State events during dial (call not registered yet) ---
475 5 ▶ my $call_id = $inner_params->{call_id} // '';
Condition50%1/2
$inner_params->{"call_id"} // ""
l!l
50
MC/DC0%0/1
$inner_params->{"call_id"} // ""
$inner_params->{"call_id"}
Truth table50%1/2
A
A= $inner_params->{"call_id"}
Aresult
11
00
476 5 ▶ my $tag = $inner_params->{tag} // '';
Condition100%2/2
$inner_params->{"tag"} // ""
l!l
23
MC/DC100%1/1
$inner_params->{"tag"} // ""
$inner_params->{"tag"}
Truth table100%2/2
A
A= $inner_params->{"tag"}
Aresult
11
00
477  
478 5 ▶ if ($event_type eq 'calling.call.state' && $tag && exists $self->_pending_dials->{$tag}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($event_type eq "calling.call.state" and $tag and exists $self->_pending_dials->{$tag}) 2 3 5
Condition66%4/6
$event_type eq "calling.call.state" and $tag and exists $self->_pending_dials->{$tag}
!ll&&!rl&&r
302
$event_type eq "calling.call.state" and $tag
!ll&&!rl&&r
032
MC/DC33%1/3
$event_type eq "calling.call.state" and $tag and exists $self->_pending_dials->{$tag}
$event_type eq "calling.call.state" $tag exists $self->_pending_dials->{$tag}
Truth table50%2/4
A and B and C
A= $event_type eq "calling.call.state"B= $tagC= exists $self->_pending_dials->{$tag}
ABCresult
0XX0
10X0
1100
1111
479 2 ▶ if (!exists $self->_calls->{$call_id} && $call_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $self->_calls->{$call_id} and $call_id) 2 0 2
Condition33%1/3
not exists $self->_calls->{$call_id} and $call_id
!ll&&!rl&&r
002
MC/DC0%0/2
not exists $self->_calls->{$call_id} and $call_id
not exists $self->_calls->{$call_id} $call_id
Truth table33%1/3
not(A) and B
A= not exists $self->_calls->{$call_id}B= $call_id
ABresult
0X0
100
111
480 # Create the Call object so events route correctly
481 my $call = SignalWire::Agents::Relay::Call->new(
482 call_id => $call_id,
483 node_id => $inner_params->{node_id} // '',
484 tag => $tag,
485 device => $inner_params->{device} // {},
486 2 ▶ _client => $self,
Condition50%2/4
$inner_params->{"node_id"} // ""
l!l
20
$inner_params->{"device"} // {}
l!l
20
MC/DC0%0/1
$inner_params->{"node_id"} // ""
$inner_params->{"node_id"}
MC/DC0%0/1
$inner_params->{"device"} // {}
$inner_params->{"device"}
Truth table50%1/2
A
A= $inner_params->{"node_id"}
Aresult
11
00
Truth table50%1/2
A
A= $inner_params->{"device"}
Aresult
11
00
487 );
488 2 $self->_calls->{$call_id} = $call;
489 }
490 }
491  
492 # --- Normal routing by call_id ---
493 5 ▶ if ($call_id && (my $call = $self->_calls->{$call_id})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($call_id and my $call = $self->_calls->{$call_id}) 4 1 5
Condition66%2/3
$call_id and my $call = $self->_calls->{$call_id}
!ll&&!rl&&r
014
MC/DC50%1/2
$call_id and my $call = $self->_calls->{$call_id}
$call_id my $call = $self->_calls->{$call_id}
Truth table66%2/3
A and B
A= $call_idB= my $call = $self->_calls->{$call_id}
ABresult
0X0
100
111
494 4 $call->dispatch_event($event);
495  
496 # Clean up ended calls
497 4 ▶ if ($call->state eq 'ended') {
Branch: 1 branch
BranchTrueFalseTotal
if ($call->state eq "ended") 1 3 4
498 1 delete $self->_calls->{$call_id};
499 }
500 }
501 }
502  
503 # --- Internal: handle inbound call ---
504  
505 1 ▶sub _handle_inbound_call {
Subroutine _handle_inbound_call: called CC=10 SCAR=26.2
506 1 my ($self, $event, $params) = @_;
507 1 ▶ my $call_id = $params->{call_id} // '';
Condition50%1/2
$params->{"call_id"} // ""
l!l
10
MC/DC0%0/1
$params->{"call_id"} // ""
$params->{"call_id"}
Truth table50%1/2
A
A= $params->{"call_id"}
Aresult
11
00
508 1 ▶ return unless $call_id;
Branch: 1 branch
BranchTrueFalseTotal
unless $call_id 0 1 1
509  
510 my $call = SignalWire::Agents::Relay::Call->new(
511 call_id => $call_id,
512 node_id => $params->{node_id} // '',
513 tag => $params->{tag} // '',
514 device => $params->{device} // {},
515 context => $params->{context} // '',
516 1 ▶ state => $params->{call_state} // 'ringing',
Condition50%5/10
$params->{"node_id"} // ""
l!l
10
$params->{"tag"} // ""
l!l
01
$params->{"device"} // {}
l!l
10
$params->{"context"} // ""
l!l
10
$params->{"call_state"} // "ringing"
l!l
10
MC/DC0%0/1
$params->{"node_id"} // ""
$params->{"node_id"}
MC/DC0%0/1
$params->{"tag"} // ""
$params->{"tag"}
MC/DC0%0/1
$params->{"device"} // {}
$params->{"device"}
MC/DC0%0/1
$params->{"context"} // ""
$params->{"context"}
MC/DC0%0/1
$params->{"call_state"} // "ringing"
$params->{"call_state"}
Truth table50%1/2
A
A= $params->{"node_id"}
Aresult
11
00
Truth table50%1/2
A
A= $params->{"tag"}
Aresult
11
00
Truth table50%1/2
A
A= $params->{"device"}
Aresult
11
00
Truth table50%1/2
A
A= $params->{"context"}
Aresult
11
00
Truth table50%1/2
A
A= $params->{"call_state"}
Aresult
11
00
517 _client => $self,
518 );
519 1 $self->_calls->{$call_id} = $call;
520  
521 1 ▶ if (my $cb = $self->_on_call) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = $self->_on_call) 1 0 1
522 1 eval { $cb->($call) };
523 1 ▶ warn "on_call callback error: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
524 }
525 }
526  
527 # --- Internal: handle inbound message ---
528  
529 2 ▶sub _handle_inbound_message {
Subroutine _handle_inbound_message: called CC=3 SCAR=11.3
530 2 my ($self, $event) = @_;
531  
532 2 ▶ if (my $cb = $self->_on_message) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = $self->_on_message) 2 0 2
533 2 eval { $cb->($event) };
534 2 ▶ warn "on_message callback error: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 2 2
535 }
536 }
537  
538 # --- Internal: handle dial completion event ---
539  
540 5 ▶sub _handle_dial_event {
Subroutine _handle_dial_event: called CC=11 SCAR=26.7
541 5 my ($self, $event, $params) = @_;
542 5 ▶ my $tag = $params->{tag} // '';
Condition50%1/2
$params->{"tag"} // ""
l!l
50
MC/DC0%0/1
$params->{"tag"} // ""
$params->{"tag"}
Truth table50%1/2
A
A= $params->{"tag"}
Aresult
11
00
543 5 ▶ my $dial_state = $params->{dial_state} // '';
Condition50%1/2
$params->{"dial_state"} // ""
l!l
50
MC/DC0%0/1
$params->{"dial_state"} // ""
$params->{"dial_state"}
Truth table50%1/2
A
A= $params->{"dial_state"}
Aresult
11
00
544 5 ▶ my $call_info = $params->{call} // {};
Condition100%2/2
$params->{"call"} // {}
l!l
32
MC/DC100%1/1
$params->{"call"} // {}
$params->{"call"}
Truth table100%2/2
A
A= $params->{"call"}
Aresult
11
00
545  
546 5 my $pending = $self->_pending_dials->{$tag};
547 5 ▶ return unless $pending;
Branch: 1 branch
BranchTrueFalseTotal
unless $pending 1 4 5
548  
549 4 ▶ if ($dial_state eq DIAL_STATE_ANSWERED) {
Branch: 2 branches
BranchTrueFalseTotal
if ($dial_state eq 'answered') { } 2 2 4
elsif ($dial_state eq 'failed') { } 2 0 2
550 2 ▶ my $call_id = $call_info->{call_id} // '';
Condition50%1/2
$call_info->{"call_id"} // ""
l!l
20
MC/DC0%0/1
$call_info->{"call_id"} // ""
$call_info->{"call_id"}
Truth table50%1/2
A
A= $call_info->{"call_id"}
Aresult
11
00
551 2 my $call = $self->_calls->{$call_id};
552 2 ▶ unless ($call) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($call) 0 2 2
553 $call = SignalWire::Agents::Relay::Call->new(
554 call_id => $call_id,
555 node_id => $call_info->{node_id} // '',
556 tag => $tag,
557 device => $call_info->{device} // {},
558 0 ▶ dial_winner => 1,
Condition0%0/4
$call_info->{"node_id"} // ""
l!l
00
$call_info->{"device"} // {}
l!l
00
MC/DC0%0/1
$call_info->{"node_id"} // ""
$call_info->{"node_id"}
MC/DC0%0/1
$call_info->{"device"} // {}
$call_info->{"device"}
Truth table0%0/2
A
A= $call_info->{"node_id"}
Aresult
11
00
Truth table0%0/2
A
A= $call_info->{"device"}
Aresult
11
00
559 state => 'answered',
560 _client => $self,
561 );
562 0 $self->_calls->{$call_id} = $call;
563 }
564 2 $call->state('answered');
565 2 $call->dial_winner(1);
566 2 $pending->{resolve}->($call);
567 }
568 elsif ($dial_state eq DIAL_STATE_FAILED) {
569 2 $pending->{reject}->("Dial failed");
570 }
571 }
572  
573 # --- Internal: handle server disconnect ---
574  
575 2 ▶sub _handle_disconnect {
Subroutine _handle_disconnect: called CC=3 SCAR=11.0
576 2 my ($self, $params) = @_;
577 2 ▶ my $restart = $params->{restart} || 0;
Condition100%2/2
$params->{'restart'} || 0
l!l
11
MC/DC100%1/1
$params->{'restart'} || 0
$params->{'restart'}
Truth table100%2/2
A
A= $params->{'restart'}
Aresult
11
00
578  
579 2 ▶ if ($restart) {
Branch: 1 branch
BranchTrueFalseTotal
if ($restart) 1 1 2
580 # Clear session state, connect fresh
581 1 $self->protocol('');
582 1 $self->authorization_state('');
583 }
584  
585 2 $self->connected(0);
586 # The client should reconnect (handled by the event loop)
587 }
588  
589 # --- Reconnection ---
590  
591 0 ▶sub reconnect {
Subroutine reconnect: not called CC=7 SCAR=40.3
Pod undocumented
592 0 my ($self) = @_;
593  
594 # Reject all pending requests
595 0 for my $id (keys %{$self->_pending}) {
596 0 my $p = delete $self->_pending->{$id};
597 0 ▶ $p->{reject}->("Disconnected") if $p;
Branch: 1 branch
BranchTrueFalseTotal
if $p 0 0 0
598 }
599  
600 # Reject all pending dials
601 0 for my $tag (keys %{$self->_pending_dials}) {
602 0 my $p = delete $self->_pending_dials->{$tag};
603 0 ▶ $p->{reject}->("Disconnected") if $p;
Branch: 1 branch
BranchTrueFalseTotal
if $p 0 0 0
604 }
605  
606 # Exponential backoff: 1s, 2s, 4s, ... up to max_backoff
607 0 my $attempts = $self->_reconnect_attempts;
608 0 my $delay = 2 ** $attempts;
609 0 ▶ $delay = $self->_max_backoff if $delay > $self->_max_backoff;
Branch: 1 branch
BranchTrueFalseTotal
if $delay > $self->_max_backoff 0 0 0
610  
611 0 $logger->info("Reconnecting in ${delay}s (attempt " . ($attempts + 1) . ")");
612 0 select(undef, undef, undef, $delay);
613  
614 0 $self->_reconnect_attempts($attempts + 1);
615  
616 0 ▶ if ($self->connect_ws) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->connect_ws) 0 0 0
617 0 return $self->authenticate;
618 }
619  
620 0 return undef;
621 }
622  
623 # --- Disconnect ---
624  
625 0 ▶sub disconnect_ws {
Subroutine disconnect_ws: not called CC=2 SCAR=17.9
Pod undocumented
626 0 my ($self) = @_;
627 0 $self->connected(0);
628 0 ▶ if ($self->_socket) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_socket) 0 0 0
629 0 close($self->_socket);
630 0 $self->_socket(undef);
631 }
632 0 $self->_ws(undef);
633 }
634  
635 # --- Run event loop ---
636  
637 0 ▶sub run {
Subroutine run: not called CC=2 SCAR=17.9
Pod undocumented
638 0 my ($self) = @_;
639 0 ▶ while ($self->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->connected) 0 0 0
640 0 $self->_read_once();
641 }
642 }
643  
644 3 1;
« blib/lib/SignalWire/Agents/REST/HttpClient.pm ↑ Summary blib/lib/SignalWire/Agents/Relay/Call.pm »