blib/lib/YAHC.pm untested

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