blib/lib/YAHC.pm untested

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