blib/lib/YAHC.pm untested

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