blib/lib/YAHC.pm untested

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