blib/lib/YAHC.pm untested

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