blib/lib/YAHC.pm untested

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