blib/lib/YAHC.pm untested

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