blib/lib/YAHC.pm untested

filter: Statementstmt 0.0% 0 / 427 Branchbran 0.0% 0 / 224 Conditioncond 0.0% 0 / 129 Subroutinesub 0.0% 0 / 66 Podpod 0.0% 0 / 56 totaltotal 0.0% 0 / 902 CC 113 SCAR 41.0
CC
113
Cov
0%
_set_read_state
210.0
_set_user_action_state
132.0
_set_write_state
110.0
CRAP 60.1
1 package YAHC;
2  
3 use strict;
4 use warnings;
5  
6 our $VERSION = '0.001';
7  
8 use EV;
9 use Time::HiRes;
10 use Exporter 'import';
11 use Scalar::Util qw/weaken/;
12 use Fcntl qw/F_GETFL F_SETFL O_NONBLOCK/;
13 use POSIX qw/EINPROGRESS EINTR EAGAIN EWOULDBLOCK strftime/;
14 use Socket qw/PF_INET SOCK_STREAM $CRLF SOL_SOCKET SO_ERROR SO_RCVTIMEO SO_SNDTIMEO inet_aton pack_sockaddr_in/;
15  
16 sub YAHC::Error::NO_ERROR () { 0 }
17 sub YAHC::Error::REQUEST_TIMEOUT () { 1 << 0 }
18 sub YAHC::Error::CONNECT_TIMEOUT () { 1 << 1 }
19 sub YAHC::Error::READ_TIMEOUT () { 1 << 2 }
20 sub YAHC::Error::WRITE_TIMEOUT () { 1 << 3 }
21 sub YAHC::Error::CONNECT_ERROR () { 1 << 4 }
22 sub YAHC::Error::READ_ERROR () { 1 << 5 }
23 sub YAHC::Error::WRITE_ERROR () { 1 << 6 }
24 sub YAHC::Error::REQUEST_ERROR () { 1 << 7 }
25 sub YAHC::Error::RESPONSE_ERROR () { 1 << 8 }
26 sub YAHC::Error::CALLBACK_ERROR () { 1 << 9 }
27 sub YAHC::Error::INTERNAL_ERROR () { 1 << 31 }
28  
29 sub YAHC::State::INITIALIZED () { 1 << 0 }
30 sub YAHC::State::RESOLVE_DNS () { 1 << 1 }
31 sub YAHC::State::WAIT_SYNACK () { 1 << 2 }
32 sub YAHC::State::CONNECTED () { 1 << 3 }
33 sub YAHC::State::WRITING () { 1 << 4 }
34 sub YAHC::State::READING () { 1 << 5 }
35 sub YAHC::State::USER_ACTION () { 1 << 15 }
36 sub YAHC::State::COMPLETED () { 1 << 30 } # terminal state
37  
38 use constant {
39 HTTP_PORT => 80,
40 TCP_READ_CHUNK => 65536,
41 RUN_UNTIL_ALL_CONNECTED => 'run until all connected',
42 RUN_UNTIL_ALL_SENT_REQUEST => 'run until all sent request',
43 };
44  
45 our @EXPORT_OK = qw/
46 yahc_reinit_conn
47 yahc_conn_last_error
48 yahc_conn_id
49 yahc_conn_state
50 yahc_conn_errors
51 yahc_conn_timeline
52 yahc_conn_request
53 yahc_conn_response
54 /;
55  
56 our %EXPORT_TAGS = (all => \@EXPORT_OK);
57  
58 ################################################################################
59 # User facing functons
60 ################################################################################
61  
62 sub new {
63 my ($class, $args) = @_;
64  
65 die 'YAHC: ->new() expect args to be a hashref' if defined $args and ref($args) ne 'HASH';
66 die 'YAHC: please do `my ($yahc, $yahc_storage) = YAHC::new()` and keep both these objects in the same scope' unless wantarray;
67  
68 # wrapping target selection here allows all client share same list
69 # and more importantly to share index within the list
70 $args->{_target} = YAHC::Request::_wrap_target_selection($args->{host}) if $args->{host};
71  
72 # this's a radical way of avoiding circular references.
73 # let's see how it plays out in practise.
74 my %storage = (
75 watchers => {},
76 callbacks => {},
77 connections => {},
78 );
79  
80 my $self = bless {
81 loop => new EV::Loop,
82 pid => $$, # store pid to detect forks
83 storage => \%storage,
84 watchers => $storage{watchers},
85 callbacks => $storage{callbacks},
86 connections => $storage{connections},
87 last_connection_id => $$ * 1000,
88  
89 debug => delete $args->{debug},
90 timeline => delete $args->{timeline},
91 pool_args => $args,
92 }, $class;
93  
94 weaken($self->{storage});
95 weaken($self->{watchers});
96 weaken($self->{callbacks});
97 weaken($self->{connections});
98 return $self, \%storage;
99 }
100  
101 sub request {
102 my ($self, @args) = @_;
103 my ($conn_id, $request);
104 die 'YAHC: new_request() expects arguments' unless @args;
105 die 'YAHC: storage object is destroyed' unless $self->{storage};
106  
107 if (@args == 1) {
108 $conn_id = 'connection_' . $self->{last_connection_id}++;
109 $request = $args[0];
110 } else {
111 ($conn_id, $request) = @args;
112 }
113  
114 die "YAHC: Connection with name '$conn_id' already exists"
115 if exists $self->{connections}{$conn_id};
116  
117 my $cb = delete $request->{callback};
118 my $debug = delete $request->{debug};
119  
120 my $conn = {
121 id => $conn_id,
122 request => $request,
123 response => { status_code => 0 },
124 attempt => 0,
125 retries => $request->{connection_retries} || 0,
126 state => YAHC::State::INITIALIZED(),
127 debug => $debug || $self->{debug},
128 selected_target => [],
129 };
130  
131 my $pool_args = $self->{pool_args};
132 $request->{_target} = _wrap_target_selection($request->{host}) if $request->{host};
133 do { $request->{$_} ||= $pool_args->{$_} if $pool_args->{$_} } foreach (qw/host port/);
134 die 'YAHC: host must be defined' unless $request->{host};
135  
136 $self->{watchers}{$conn_id} = {};
137 $self->{callbacks}{$conn_id} = $cb;
138 $self->{connections}{$conn_id} = $conn;
139  
140 $self->_set_request_timer($conn_id) if $conn->{request}{request_timeout};
141 $self->_set_init_state($conn_id);
142 return $conn;
143 }
144  
145 sub run { $_[0]->_run(0, $_[1]) }
146 sub run_once { $_[0]->_run(EV::RUN_ONCE) }
147 sub run_tick { $_[0]->_run(EV::RUN_NOWAIT) }
148  
149 ################################################################################
150 # Routines to manipulate connections (also user facing)
151 ################################################################################
152  
153 sub yahc_reinit_conn {
154 my ($conn, $args) = @_;
155 $conn->{attempt} = 0;
156 $conn->{state} = YAHC::State::INITIALIZED();
157 return unless defined $args && ref($args) eq 'HASH';
158  
159 my $request = $conn->{request};
160 do { $request->{$_} = $args->{$_} if $args->{$_} } foreach (keys %$args);
161 $request->{_target} = _wrap_target_selection($args->{host}) if $args->{host};
162 }
163  
164 sub yahc_conn_last_error {
165 my $conn = shift;
166 return unless $conn->{errors} && @{ $conn->{errors} };
167 return wantarray ? @{ $conn->{errors}[-1] } : $conn->{errors}[-1];
168 }
169  
170 sub yahc_conn_id { $_[0]->{id} }
171 sub yahc_conn_state { $_[0]->{state} }
172 sub yahc_conn_errors { $_[0]->{errors} }
173 sub yahc_conn_timeline { $_[0]->{timeline} }
174 sub yahc_conn_request { $_[0]->{request} }
175 sub yahc_conn_response { $_[0]->{response} }
176  
177 ################################################################################
178 # Internals
179 ################################################################################
180  
181 sub _run {
182 my ($self, $how, $stop_condition) = @_;
183 die 'YAHC: storage object is destroyed' unless $self->{storage};
184  
185 if ($self->{pid} != $$) {
186 _log_message('Reinitializing event loop after forking') if $self->{debug};
187 $self->{pid} = $$;
188 $self->{loop}->loop_fork;
189 }
190  
191 if (defined $stop_condition) {
192 if ($stop_condition eq RUN_UNTIL_ALL_CONNECTED) {
193 $self->{stop_condition} = {
194 condition => RUN_UNTIL_ALL_CONNECTED,
195 expected_state => YAHC::State::CONNECTED(),
196 connections => { map { $_->id => 1 } grep { $_->state < YAHC::State::CONNECTED() } values %{ $self->{connections } } },
197 };
198 } elsif ($stop_condition eq RUN_UNTIL_ALL_SENT_REQUEST) {
199 $self->{stop_condition} = {
200 condition => RUN_UNTIL_ALL_SENT_REQUEST,
201 expected_state => YAHC::State::READING(),
202 connections => { map { $_->id => 1 } grep { $_->state < YAHC::State::WRITING() } values %{ $self->{connections } } },
203 };
204 } else {
205 die "unknown stop_condition";
206 }
207  
208 } else {
209 delete $self->{stop_condition};
210 }
211  
212 my $loop = $self->{loop};
213 $loop->now_update;
214 return $loop->run($how || 0) unless $self->{debug}; # shortcut
215  
216 my $iterations = $loop->iteration;
217 _log_message('pid %d entering event loop%s', $$, $stop_condition ? " and $stop_condition" : '');
218 $loop->run($how || 0);
219 _log_message('pid %d exited from event loop after %d iterations', $$, $loop->iteration - $iterations);
220 }
221  
222 sub _break {
223 my ($self, $reason) = @_;
224 _log_message('pid %d breaking event loop because %s', $$, ($reason || 'no reason')) if $self->{debug};
225 $self->{loop}->break(EV::BREAK_ONE)
226 }
227  
228 sub _check_stop_condition {
229 my ($self, $conn) = @_;
230 my $stop_condition = $self->{stop_condition};
231 return if !$stop_condition || $conn->{state} < $stop_condition->{expected_state};
232  
233 delete $stop_condition->{connections}{$conn->id};
234 my $awaiting_connections = scalar keys %{ $stop_condition->{connections} };
235  
236 if ($awaiting_connections == 0) {
237 $self->_break(sprintf("stop condition '%s' is met", $stop_condition->{condition}));
238 } else {
239 _log_message("Still have %d connections awaiting stop condition '%s'",
240 $awaiting_connections, $stop_condition->{condition});
241 }
242 }
243  
244 ################################################################################
245 # IO routines
246 ################################################################################
247  
248 sub _set_init_state {
249 my ($self, $conn_id) = @_;
250  
251 my $conn = $self->{connections}{$conn_id};
252 my $watchers = $self->{watchers}{$conn_id};
253 die "YAHC: unknown connection id $conn_id" unless $conn && $watchers;
254  
255 $conn->{response} = { status_code => 0 };
256 $conn->{state} = YAHC::State::INITIALIZED();
257 _register_in_timeline($conn, "connection %s new state %s",
258 $conn_id, _strstate($conn->{state})) if $conn->{debug};
259  
260 my $continue = 1;
261 while ($continue) {
262 if (my $w = delete $watchers->{io}) {
263 $w->stop;
264 shutdown($w->fh, 2);
265 }
266  
267 my $attempt = $conn->{attempt}++;
268 if ($attempt > $conn->{retries}) {
269 $self->_set_user_action_state($conn_id, YAHC::Error::CONNECT_ERROR(), "connection_retries limit reached");
270 return;
271 }
272  
273 eval {
274 my ($host, $ip, $port) = _get_next_target($conn);
275 _register_in_timeline($conn, "Target $host:$port ($ip:$port) chosen for attempt #$attempt") if $conn->{debug};
276  
277 my $sock = _build_socket_and_connect($ip, $port, $conn->{request});
278 $self->_set_wait_synack_state($conn_id, $sock, $ip, $host, $port);
279 $self->_set_connection_timer($conn_id) if $conn->{request}{connect_timeout};
280 $continue = 0;
281 1;
282 } or do {
283 my $error = $@ || 'zombie error';
284 _register_error($conn, YAHC::Error::CONNECT_ERROR(), "Connection attempt #$attempt for $conn_id has failed: $error");
285 #$self->_set_set_init_state_timer($conn_id); # trigger background timer which will do reconnection attempt # TODO
286 #$continue = 0;
287 };
288 }
289 }
290  
291 sub _set_wait_synack_state {
292 my ($self, $conn_id, $sock, $ip, $host, $port) = @_;
293  
294 my $conn = $self->{connections}{$conn_id};
295 my $watchers = $self->{watchers}{$conn_id};
296 die "YAHC: unknown connection id $conn_id" unless $conn && $watchers;
297 _assert_state($conn, YAHC::State::INITIALIZED()) if $conn->{debug};
298  
299 $conn->{state} = YAHC::State::WAIT_SYNACK();
300 _register_in_timeline($conn, "connection %s new state %s",
301 $conn_id, _strstate($conn->{state})) if $conn->{debug};
302  
303 $self->_check_stop_condition($conn) if $self->{stop_condition};
304  
305 my $wait_synack_cb = $self->_get_safe_wrapper($conn_id, sub {
306 my $sockopt = getsockopt($sock, SOL_SOCKET, SO_ERROR);
307 if (!$sockopt) {
308 _register_error($conn, YAHC::Error::CONNECT_ERROR(), "Failed to do getsockopt(): $!");
309 $self->_set_init_state($conn_id);
310 return;
311 }
312  
313 if (my $err = unpack("L", $sockopt)) {
314 my $strerror = POSIX::strerror($err) || '<unknown POSIX error>';
315 _register_error($conn, YAHC::Error::CONNECT_ERROR(), "Failed to connect to $host:$port ($ip:$port): $strerror");
316 $self->_set_init_state($conn_id);
317 return;
318 }
319  
320 $conn->{state} = YAHC::State::CONNECTED();
321 _register_in_timeline($conn, "connection %s new state %s",
322 $conn_id, _strstate($conn->{state})) if $conn->{debug};
323  
324 $self->_set_write_state($conn_id);
325 });
326  
327 $watchers->{io} = $self->{loop}->io($sock, EV::WRITE, $wait_synack_cb);
328 }
329  
330 sub _set_write_state {
331 my ($self, $conn_id) = @_;
332  
333 my $conn = $self->{connections}{$conn_id};
334 my $watcher = $self->{watchers}{$conn_id}{io};
335 die "YAHC: unknown connection id $conn_id" unless $conn && $watcher;
336 _assert_connected($conn) if $conn->{debug};
337  
338 $conn->{state} = YAHC::State::WRITING();
339 _register_in_timeline($conn, "connection %s new state %s",
340 $conn_id, _strstate($conn->{state})) if $conn->{debug};
341  
342 $self->_check_stop_condition($conn) if $self->{stop_condition};
343  
344 my $fd = fileno($watcher->fh);
345 my $buf = _build_http_message($conn);
346 my $length = length($buf);
347  
348 _register_in_timeline($conn, "sending request of $length bytes") if $conn->{debug};
349  
350 my $write_cb = $self->_get_safe_wrapper($conn_id, sub {
351 my $wlen = POSIX::write($fd, $buf, $length);
352  
353 if (!$wlen) {
354 return if $! == EWOULDBLOCK || $! == EAGAIN || $! == EINTR;
355  
356 my $error = !defined $wlen
357 ? "Failed to send TCP data: $!"
358 : "Bizzare!!! syswrite returned 0"; # wlen == 0
359  
360 _register_error($conn, YAHC::Error::WRITE_ERROR(), $error);
361 $self->_set_init_state($conn_id);
362 } else {
363 substr($buf, 0, $wlen, '');
364 $length -= $wlen;
365 $self->_set_read_state($conn_id) if $length == 0;
366 }
367 });
368  
369 $watcher->cb($write_cb);
370 $watcher->events(EV::WRITE);
371 }
372  
373 sub _set_read_state {
374 my ($self, $conn_id) = @_;
375  
376 my $conn = $self->{connections}{$conn_id};
377 my $watcher = $self->{watchers}{$conn_id}{io};
378 die "YAHC: unknown connection id $conn_id" unless $conn && $watcher;
379 _assert_connected($conn) if $conn->{debug};
380  
381 $conn->{state} = YAHC::State::READING();
382 _register_in_timeline($conn, "connection %s new state %s",
383 $conn_id, _strstate($conn->{state})) if $conn->{debug};
384  
385 $self->_check_stop_condition($conn) if $self->{stop_condition};
386  
387 my $buf = '';
388 my $neck_pos = 0;
389 my $decapitated = 0;
390 my $content_length = 0;
391 my $fd = fileno($watcher->fh);
392  
393 my $read_cb = $self->_get_safe_wrapper($conn_id, sub {
394 my $rlen = POSIX::read($fd, my $b = '', TCP_READ_CHUNK);
395  
396 if (!$rlen) {
397 return if $! == EWOULDBLOCK || $! == EAGAIN || $! == EINTR;
398 if (not defined $rlen) {
399 _register_error($conn, YAHC::Error::READ_ERROR(), "Failed to receive TCP data: $!");
400 } elsif ($content_length > 0) { # i.e. rlen == 0 and $content_length > 0
401 register_error($conn, YAHC::Error::READ_ERROR(), "Premature EOF, expect %d bytes more", $content_length - length($buf));
402 } else { # i.e. rlen == 0
403 register_error($conn, YAHC::Error::READ_ERROR(), "Premature EOF");
404 }
405  
406 $self->_set_init_state($conn_id);
407 } else {
408 $buf .= $b;
409 if (!$decapitated && ($neck_pos = index($buf, "${CRLF}${CRLF}")) > 0) {
410 my $headers = _parse_http_headers($conn, substr($buf, 0, $neck_pos, ''));
411 if (not defined $headers) {
412 $self->_set_user_action_state($conn_id, YAHC::Error::RESPONSE_ERROR(), "unsuported HTTP reponse");
413 return;
414 }
415  
416 $decapitated = 1;
417 $content_length = $headers->{'Content-Length'};
418 substr($buf, 0, 4, ''); # 4 = length("$CRLF$CRLF")
419 _register_in_timeline($conn, "headers parsed: content-length='%d' content-type='%s'",
420 $content_length, $headers->{'Content-Type'} || '<no-content-type>') if $conn->{debug};
421 }
422  
423 if ($decapitated && length($buf) >= $content_length) {
424 $buf = substr($buf, 0, $content_length) if length($buf) > $content_length;
425 $conn->{response}{body} = $buf;
426 $self->_set_user_action_state($conn_id);
427 }
428 }
429 });
430  
431 $watcher->cb($read_cb);
432 $watcher->events(EV::READ);
433 }
434  
435 sub _set_user_action_state {
436 my ($self, $conn_id, $error, $strerror) = @_;
437 $error ||= YAHC::Error::NO_ERROR();
438 $strerror ||= '<no strerror>';
439  
440 # this state may be used in critical places,
441 # so it should *NEVER* throw exception
442 my $conn = $self->{connections}{$conn_id}
443 or warn "YAHC: try to _set_user_action_state() for unknown connection $conn_id",
444 return;
445  
446 $conn->{state} = YAHC::State::USER_ACTION();
447 _register_in_timeline($conn, "connection %s new state %s",
448 $conn_id, _strstate($conn->{state})) if $conn->{debug};
449 _register_error($conn, $error, $strerror) if $error;
450  
451 my $cb = $self->{callbacks}{$conn_id};
452 return $self->_set_completed_state($conn_id) unless $cb; # shortcut
453  
454 eval {
455 _register_in_timeline($conn, "call callback%s", $error ? " error=$error, strerror='$strerror'" : '') if $conn->{debug};
456 $cb->($conn, $error, $strerror);
457 1;
458 } or do {
459 my $error = $@ || 'zombie error';
460 _register_error($conn, YAHC::Error::CALLBACK_ERROR(), $error);
461 warn "YAHC: exception in callback: $error";
462 };
463  
464 if ($error == YAHC::Error::INTERNAL_ERROR()) {
465 _register_in_timeline($conn, "unrecoverable error appeared, forcing completion") if $conn->{debug};
466 $self->_set_completed_state($conn_id);
467 return;
468 }
469  
470 my $state = $conn->{state};
471 _register_in_timeline($conn, "after invoking callback state is %s", _strstate($state)) if $conn->{debug};
472  
473 if ($state == YAHC::State::INITIALIZED()) {
474 $self->_set_init_state($conn_id); # TODO eval
475 } elsif ($state == YAHC::State::USER_ACTION() || $state == YAHC::State::COMPLETED()) {
476 $self->_set_completed_state($conn_id);
477 } else {
478 _register_error($conn, YAHC::Error::CALLBACK_ERROR(), "callback set unsupported state");
479 $self->_set_completed_state($conn_id);
480 }
481 }
482  
483 sub _set_completed_state {
484 my ($self, $conn_id) = @_;
485  
486 # this's a terminal state,
487 # so setting this state should *NEVER* fail
488 delete $self->{callbacks}{$conn_id};
489 my $watchers = delete $self->{watchers}{$conn_id};
490 my $conn = $self->{connections}{$conn_id}
491 or warn "YAHC: try to _set_completed_state() for unknown connection $conn_id",
492 return;
493  
494 $conn->{state} = YAHC::State::COMPLETED();
495 _register_in_timeline($conn, "connection %s new state %s",
496 $conn_id, _strstate($conn->{state})) if $conn->{debug};
497  
498 if (my $w = delete $watchers->{io}) {
499 $w->stop;
500 shutdown($w->fh, 2)
501 }
502  
503 $_->stop foreach (values %{ $watchers || {} });
504  
505 eval { $self->_check_stop_condition($conn) } if $self->{stop_condition};
506 }
507  
508 sub _build_socket_and_connect {
509 my ($ip, $port, $timeouts) = @_;
510  
511 my $sock;
512 socket($sock, PF_INET, SOCK_STREAM, 0) or die "YAHC: Failed to construct TCP socket: $!";
513  
514 my $flags = fcntl($sock, F_GETFL, 0) or die "YAHC: Failed to get fcntl F_GETFL flag: $!";
515 fcntl($sock, F_SETFL, $flags | O_NONBLOCK) or die "YAHC: Failed to set fcntl O_NONBLOCK flag: $!";
516  
517 if (my $read_timeout = $timeouts->{read_timeout}) {
518 my $read_struct = pack('l!l!', $read_timeout, 0);
519 setsockopt($sock, SOL_SOCKET, SO_RCVTIMEO, $read_struct)
520 or die "YAHC: Failed to set setsockopt(SO_RCVTIMEO): $!";
521 }
522  
523 if (my $write_timeout = $timeouts->{write_timeout}) {
524 my $write_struct = pack('l!l!', $write_timeout, 0);
525 setsockopt($sock, SOL_SOCKET, SO_SNDTIMEO, $write_struct )
526 or die "YAHC: Failed to set setsockopt(SO_SNDTIMEO): $!";
527 }
528  
529 my $ip_addr = inet_aton($ip);
530 my $addr = pack_sockaddr_in($port, $ip_addr);
531 if (!connect($sock, $addr) && $! != EINPROGRESS) {
532 die "YAHC: Failed to connect to $ip: $!";
533 }
534  
535 return $sock;
536 }
537  
538 sub _get_next_target {
539 my $conn = shift;
540 my ($host, $ip, $port) = $conn->{request}{_target}->();
541  
542 # TODO STATE_RESOLVE_DNS
543 ($host, $port) = ($1, $2) if $host =~ m/^(.+):([0-9]+)$/o;
544 $ip = $host if $host =~ m/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/o;
545 $ip = inet_ntoa(gethostbyname($host) or die "Failed to resolve $host: $!") unless $ip;
546 $port ||= $conn->{request}{port} || HTTP_PORT;
547  
548 return @{ $conn->{selected_target} = [ $host, $ip, $port ] };
549 }
550  
551 ################################################################################
552 # Timers
553 ################################################################################
554  
555 sub _set_request_timer {
556 my ($self, $conn_id) = @_;
557  
558 my $conn = $self->{connections}{$conn_id};
559 my $watchers = $self->{watchers}{$conn_id};
560 die "YAHC: unknown connection id $conn_id" unless $conn && $watchers;
561  
562 if (my $timer = delete $watchers->{connection_timer}) {
563 $timer->stop;
564 }
565  
566 my $timeout = $conn->{request}{request_timeout};
567 return unless defined $timeout;
568  
569 my $request_timer_cb = $self->_get_safe_wrapper($conn_id, sub {
570 if ($conn->{state} < YAHC::State::USER_ACTION()) {
571 my $error = sprintf("Request timeout of %.3fs has reached", $timeout);
572 $self->_set_user_action_state($conn_id, YAHC::Error::REQUEST_TIMEOUT(), $error);
573 } else {
574 _register_in_timeline($conn, "delete request timer") if $conn->{debug};
575 }
576 });
577  
578 _register_in_timeline($conn, "setting request timeout to %.3fs", $timeout) if $conn->{debug};
579 $watchers->{request_timer} = $self->{loop}->timer($timeout, 0, $request_timer_cb);
580 $watchers->{request_timer}->priority(2); # set max priority
581 }
582  
583 sub _set_connection_timer {
584 my ($self, $conn_id) = @_;
585  
586 my $conn = $self->{connections}{$conn_id};
587 my $watchers = $self->{watchers}{$conn_id};
588 die "YAHC: unknown connection id $conn_id" unless $conn && $watchers;
589  
590 if (my $timer = delete $watchers->{connection_timer}) {
591 $timer->stop;
592 }
593  
594 my $timeout = $conn->{request}{connect_timeout};
595 return unless $timeout;
596  
597 my $connection_timer_cb = $self->_get_safe_wrapper($conn_id, sub {
598 if ($conn->{state} < YAHC::State::CONNECTED()) {
599 _register_in_timeline($conn, "connection timeout of %.3fs has reached", $timeout) if $conn->{debug};
600 $self->_set_init_state($conn_id);
601 } else {
602 _register_in_timeline($conn, "delete connection timer") if $conn->{debug};
603 }
604 });
605  
606 _register_in_timeline($conn, "setting connection timeout to %.3fs", $timeout) if $conn->{debug};
607 $watchers->{connection_timer} = $self->{loop}->timer($timeout, 0, $connection_timer_cb);
608 $watchers->{connection_timer}->priority(-2); # set lowest priority
609 }
610  
611 ################################################################################
612 # HTTP functions
613 ################################################################################
614  
615 # copy-paste from Hijk
616 sub _build_http_message {
617 my $conn = shift;
618 my $request = $conn->{request};
619 my $path_and_qs = ($request->{path} || "/") . (defined $request->{query_string} ? ("?" . $request->{query_string}) : "");
620  
621 return join(
622 $CRLF,
623 ($request->{method} || "GET") . " $path_and_qs " . ($request->{protocol} || "HTTP/1.1"),
624 "Host: " . $conn->{selected_target}[0],
625 $request->{body} ? ("Content-Length: " . length($request->{body})) : (),
626 $request->{head} ? (
627 map {
628 $request->{head}[2*$_] . ": " . $request->{head}[2*$_+1]
629 } 0..$#{$request->{head}}/2
630 ) : (),
631 "",
632 $request->{body} ? $request->{body} : ()
633 ) . $CRLF;
634 }
635  
636 sub _parse_http_headers {
637 my $conn = shift;
638 my $proto = substr($_[0], 0, 8);
639 my $status_code = substr($_[0], 9, 3);
640 substr($_[0], 0, index($_[0], $CRLF) + 2, ''); # 2 = length($CRLF)
641  
642 my %headers;
643 for (split /${CRLF}/o, $_[0]) {
644 my ($key, $value) = split(/: /, $_, 2);
645 $headers{$key} = $value;
646 }
647  
648 $conn->{response} = {
649 proto => $proto,
650 status_code => $status_code,
651 headers => \%headers,
652 };
653  
654 return \%headers;
655 }
656  
657 ################################################################################
658 # Helpers
659 ################################################################################
660  
661 sub _wrap_target_selection {
662 my $host = shift;
663 my $ref = ref($host);
664  
665 return sub { $host } if $ref eq '';
666 return $host if $ref eq 'CODE';
667  
668 my $idx = 0;
669 return sub { $host->[$idx++ % @$host]; } if $ref eq 'ARRAY';
670 die "YAHC: unsupported host format";
671 }
672  
673 sub _get_safe_wrapper {
674 my ($self, $conn_id, $sub) = @_;
675 return sub { eval {
676 $sub->(@_);
677 1;
678 } or do {
679 my $error = $@ || 'zombie error';
680 $self->_set_user_action_state($conn_id, YAHC::Error::INTERNAL_ERROR(), "Exception callback: $error");
681 }};
682 }
683  
684 sub _register_in_timeline {
685 my ($conn, $format, @arguments) = @_;
686 my $event = sprintf("$format", @arguments);
687 $event =~ s/\s+$//g;
688 _log_message("YAHC connection '%s': %s", $conn->{id}, $event) if $conn->{debug};
689 push @{ $conn->{timeline} ||= [] }, [ $event, Time::HiRes::time ];
690 }
691  
692 sub _register_error {
693 my ($conn, $error, $format, @arguments) = @_;
694 my $strerror = sprintf("$format", @arguments);
695 $strerror =~ s/\s+$//g;
696 _register_in_timeline($conn, "error=$error ($strerror)") if $conn->{debug};
697 push @{ $conn->{errors} ||= [] }, [ $error, $strerror, Time::HiRes::time ];
698 }
699  
700 sub _assert_state {
701 my ($conn, $expected_state) = @_;
702 return $conn->{state} == $expected_state;
703 die sprintf("YAHC connection '%s' is in unexpected state %s, expected %s",
704 $conn->{id}, _strstate($conn->{state}), _strstate($expected_state));
705 }
706  
707 sub _assert_connected {
708 my $conn = shift;
709 return if $conn->{state} >= YAHC::State::CONNECTED() && $conn->{state} < YAHC::State::COMPLETED();
710 die sprintf("YAHC connection '%s' expected to be in connected state, but it's in %s",
711 $conn->{id}, _strstate($conn->{state}));
712 }
713  
714 sub _strstate {
715 my $state = shift;
716 return 'STATE_INIT' if $state eq YAHC::State::INITIALIZED();
717 return 'STATE_RESOLVE_DNS' if $state eq YAHC::State::RESOLVE_DNS();
718 return 'STATE_WAIT_SYNACK' if $state eq YAHC::State::WAIT_SYNACK();
719 return 'STATE_CONNECTED' if $state eq YAHC::State::CONNECTED();
720 return 'STATE_WRITING' if $state eq YAHC::State::WRITING();
721 return 'STATE_READING' if $state eq YAHC::State::READING();
722 return 'STATE_USER_ACTION' if $state eq YAHC::State::USER_ACTION();
723 return 'STATE_COMPLETED' if $state eq YAHC::State::COMPLETED();
724 return "<unknown state $state>";
725 }
726  
727 sub _log_message {
728 my $format = shift;
729 printf STDERR "[%s] [$$] $format\n", POSIX::strftime('%F %T', localtime), @_;
730 }
731  
732 1;
733  
734 __END__