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