| 1 | package Net::Async::Crawl4AI; | ||
| 2 | # ABSTRACT: IO::Async Crawl4AI client with an async strategy chain | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use parent 'IO::Async::Notifier'; | ||
| 6 | |||
| 7 | use Carp qw( croak ); | ||
| 8 | use Scalar::Util qw( blessed ); | ||
| 9 | use Time::HiRes (); | ||
| 10 | use URI (); | ||
| 11 | use WWW::Crawl4AI (); | ||
| 12 | use WWW::Crawl4AI::Request (); | ||
| 13 | use WWW::Crawl4AI::Result (); | ||
| 14 | use WWW::Crawl4AI::Error (); | ||
| 15 | use Net::Async::HTTP (); | ||
| 16 | use Future (); | ||
| 17 | use Future::Utils qw( repeat fmap_void ); | ||
| 18 | |||
| 19 | our $VERSION = '0.001'; | ||
| 20 | |||
| 21 | |||
| 22 | # Keys forwarded straight to the underlying WWW::Crawl4AI orchestrator. | ||
| 23 | my @WWW_KEYS = qw( | ||
| 24 | base_url api_token cloakbrowser_url proxy_url callback | ||
| 25 | fallback timeout min_markdown client | ||
| 26 | ); | ||
| 27 | |||
| 28 | sub _init { | ||
| 29 | my ( $self, $args ) = @_; | ||
| 30 | $self->SUPER::_init($args); | ||
| 31 | $self->{crawl4ai} = delete $args->{crawl4ai} if exists $args->{crawl4ai}; | ||
| 32 | $self->{crawl4ai} ||= WWW::Crawl4AI->new( | ||
| 33 | map { exists $args->{$_} ? ( $_ => delete $args->{$_} ) : () } @WWW_KEYS | ||
| 34 | ); | ||
| 35 | $self->{poll_interval} = exists $args->{poll_interval} ? delete $args->{poll_interval} : 2; | ||
| 36 | $self->{http} = delete $args->{http}; | ||
| 37 | $self->{delay_sub} = delete $args->{delay_sub}; | ||
| 38 | return; | ||
| 39 | } | ||
| 40 | |||
| 41 | sub configure_unknown { | ||
| 42 | my ( $self, %args ) = @_; | ||
| 43 | delete @args{ @WWW_KEYS, qw( crawl4ai poll_interval http delay_sub ) }; | ||
| 44 | return unless %args; | ||
| 45 | croak "Unknown configuration keys: " . join( ',', sort keys %args ); | ||
| 46 | } | ||
| 47 | |||
| 48 | sub crawl4ai { $_[0]->{crawl4ai} } | ||
| 49 | |||
| 50 | |||
| 51 | sub client { $_[0]->{crawl4ai}->client } | ||
| 52 | |||
| 53 | |||
| 54 | sub poll_interval { @_ > 1 ? ( $_[0]->{poll_interval} = $_[1] ) : $_[0]->{poll_interval} } | ||
| 55 | |||
| 56 | |||
| 57 | sub available_backends { $_[0]->{crawl4ai}->available_backends } | ||
| 58 | |||
| 59 | |||
| 60 | sub http { | ||
| 61 | my ( $self ) = @_; | ||
| 62 | return $self->{http} if $self->{http}; | ||
| 63 | my $http = Net::Async::HTTP->new( | ||
| 64 | user_agent => $self->client->user_agent_string, | ||
| 65 | max_connections_per_host => 4, | ||
| 66 | ); | ||
| 67 | $self->add_child($http); | ||
| 68 | return $self->{http} = $http; | ||
| 69 | } | ||
| 70 | |||
| 71 | |||
| 72 | sub _add_to_loop { | ||
| 73 | my ( $self, $loop ) = @_; | ||
| 74 | $self->SUPER::_add_to_loop($loop); | ||
| 75 | $self->http; # build + parent the Net::Async::HTTP child eagerly | ||
| 76 | } | ||
| 77 | |||
| 78 | #---------------------------------------------------------------------- | ||
| 79 | # Request dispatch + retry (Future-based mirror of the client's policy) | ||
| 80 | #---------------------------------------------------------------------- | ||
| 81 | |||
| 82 | sub _delay_future { | ||
| 83 | my ( $self, $seconds ) = @_; | ||
| 84 | return $self->{delay_sub}->($seconds) if $self->{delay_sub}; | ||
| 85 | return $self->loop->delay_future( after => $seconds ); | ||
| 86 | } | ||
| 87 | |||
| 88 | sub do_request { | ||
| 89 | my ( $self, $request, $backend ) = @_; | ||
| 90 | croak "do_request requires an HTTP::Request" unless $self->client->is_request($request); | ||
| 91 | return $self->_do_request_with_retry( $request, $backend, 1 ); | ||
| 92 | } | ||
| 93 | |||
| 94 | |||
| 95 | sub _retry_delay { | ||
| 96 | my ( $self, $attempt, $response ) = @_; | ||
| 97 | my $backoff = $self->client->retry_backoff; | ||
| 98 | my $delay = $backoff->[ $attempt - 1 ] // $backoff->[-1] // 1; | ||
| 99 | if ( $response && ( my $ra = $response->header('Retry-After') ) ) { | ||
| 100 | $delay = $ra if $ra =~ /^\d+$/; | ||
| 101 | } | ||
| 102 | return $delay; | ||
| 103 | } | ||
| 104 | |||
| 105 | sub _do_request_with_retry { | ||
| 106 | my ( $self, $request, $backend, $attempt ) = @_; | ||
| 107 | my $client = $self->client; | ||
| 108 | my $max = $client->max_attempts; | ||
| 109 | return $self->http->do_request( request => $request, fail_on_error => 0 )->then( | ||
| 110 | sub { | ||
| 111 | my ( $response ) = @_; | ||
| 112 | return Future->done($response) if $response->is_success; | ||
| 113 | my $code = $response->code; | ||
| 114 | my $retryable = $client->_retry_status_set->{$code}; | ||
| 115 | if ( $retryable && $attempt < $max ) { | ||
| 116 | my $delay = $self->_retry_delay( $attempt, $response ); | ||
| 117 | $client->on_retry->( $attempt, $delay, $response ) if $client->on_retry; | ||
| 118 | return $self->_delay_future($delay) | ||
| 119 | ->then( sub { $self->_do_request_with_retry( $request, $backend, $attempt + 1 ) } ); | ||
| 120 | } | ||
| 121 | # Non-retryable / exhausted non-2xx: hand the response back so the | ||
| 122 | # endpoint's parser raises the proper api error (with status_code). | ||
| 123 | return Future->done($response); | ||
| 124 | }, | ||
| 125 | sub { | ||
| 126 | my ( $err ) = @_; # transport-level failure from Net::Async::HTTP | ||
| 127 | if ( $attempt < $max ) { | ||
| 128 | my $delay = $self->_retry_delay( $attempt, undef ); | ||
| 129 | $client->on_retry->( $attempt, $delay, $err ) if $client->on_retry; | ||
| 130 | return $self->_delay_future($delay) | ||
| 131 | ->then( sub { $self->_do_request_with_retry( $request, $backend, $attempt + 1 ) } ); | ||
| 132 | } | ||
| 133 | return Future->fail( | ||
| 134 | WWW::Crawl4AI::Error->new( | ||
| 135 | type => 'transport', | ||
| 136 | message => "Crawl4AI transport error: $err", | ||
| 137 | status_code => 0, | ||
| 138 | backend => $backend, | ||
| 139 | attempt => $attempt, | ||
| 140 | ), | ||
| 141 | 'crawl4ai', | ||
| 142 | ); | ||
| 143 | }, | ||
| 144 | ); | ||
| 145 | } | ||
| 146 | |||
| 147 | # Dispatch $http_req, then run $parse->($response). Parser exceptions become a | ||
| 148 | # failed Future carrying a WWW::Crawl4AI::Error. | ||
| 149 | sub _parsed { | ||
| 150 | my ( $self, $http_req, $parse, $backend ) = @_; | ||
| 151 | return $self->do_request( $http_req, $backend )->then( sub { | ||
| 152 | my ( $res ) = @_; | ||
| 153 | my $out = eval { $parse->($res) }; | ||
| 154 | if ( my $e = $@ ) { | ||
| 155 | my $err = ( blessed($e) && $e->isa('WWW::Crawl4AI::Error') ) | ||
| 156 | ? $e | ||
| 157 | : WWW::Crawl4AI::Error->new( | ||
| 158 | type => 'api', message => "$e", response => $res, backend => $backend ); | ||
| 159 | return Future->fail( $err, 'crawl4ai' ); | ||
| 160 | } | ||
| 161 | return Future->done($out); | ||
| 162 | } ); | ||
| 163 | } | ||
| 164 | |||
| 165 | #---------------------------------------------------------------------- | ||
| 166 | # Low-level Future endpoints | ||
| 167 | #---------------------------------------------------------------------- | ||
| 168 | |||
| 169 | sub crawl_once { | ||
| 170 | my ( $self, $request, $backend ) = @_; | ||
| 171 | my $client = $self->client; | ||
| 172 | return $self->_parsed( | ||
| 173 | $client->crawl_request($request), | ||
| 174 | sub { $client->parse_crawl_response( $_[0], $backend ) }, | ||
| 175 | $backend, | ||
| 176 | ); | ||
| 177 | } | ||
| 178 | |||
| 179 | |||
| 180 | sub md { | ||
| 181 | my ( $self, $url, %opts ) = @_; | ||
| 182 | my $client = $self->client; | ||
| 183 | my $request = ( blessed($url) && $url->isa('WWW::Crawl4AI::Request') ) | ||
| 184 | ? $url | ||
| 185 | : WWW::Crawl4AI::Request->new( urls => $url, %opts ); | ||
| 186 | return $self->_parsed( | ||
| 187 | $client->md_request($request), | ||
| 188 | sub { $client->parse_md_response( $_[0] ) }, | ||
| 189 | ); | ||
| 190 | } | ||
| 191 | |||
| 192 | |||
| 193 | sub job_submit { | ||
| 194 | my ( $self, $request ) = @_; | ||
| 195 | my $client = $self->client; | ||
| 196 | return $self->_parsed( | ||
| 197 | $client->job_submit_request($request), | ||
| 198 | sub { $client->parse_job_submit_response( $_[0] ) }, | ||
| 199 | ); | ||
| 200 | } | ||
| 201 | |||
| 202 | |||
| 203 | sub job_status { | ||
| 204 | my ( $self, $task_id ) = @_; | ||
| 205 | my $client = $self->client; | ||
| 206 | return $self->_parsed( | ||
| 207 | $client->job_status_request($task_id), | ||
| 208 | sub { $client->parse_job_status_response( $_[0] ) }, | ||
| 209 | ); | ||
| 210 | } | ||
| 211 | |||
| 212 | |||
| 213 | sub health { | ||
| 214 | my ( $self ) = @_; | ||
| 215 | my $client = $self->client; | ||
| 216 | return $self->do_request( $client->health_request )->then( | ||
| 217 | sub { Future->done( $client->parse_health_response( $_[0] ) ? 1 : 0 ) }, | ||
| 218 | sub { Future->done(0) }, | ||
| 219 | ); | ||
| 220 | } | ||
| 221 | |||
| 222 | |||
| 223 | sub screenshot { | ||
| 224 | my ( $self, $url, %opts ) = @_; | ||
| 225 | my $client = $self->client; | ||
| 226 | return $self->_parsed( | ||
| 227 | $client->screenshot_request( $url, %opts ), | ||
| 228 | sub { $client->parse_screenshot_response( $_[0] ) }, | ||
| 229 | ); | ||
| 230 | } | ||
| 231 | |||
| 232 | |||
| 233 | sub pdf { | ||
| 234 | my ( $self, $url, %opts ) = @_; | ||
| 235 | my $client = $self->client; | ||
| 236 | return $self->_parsed( | ||
| 237 | $client->pdf_request( $url, %opts ), | ||
| 238 | sub { $client->parse_pdf_response( $_[0] ) }, | ||
| 239 | ); | ||
| 240 | } | ||
| 241 | |||
| 242 | sub html { | ||
| 243 | my ( $self, $url ) = @_; | ||
| 244 | my $client = $self->client; | ||
| 245 | return $self->_parsed( | ||
| 246 | $client->html_request($url), | ||
| 247 | sub { $client->parse_html_response( $_[0] ) }, | ||
| 248 | ); | ||
| 249 | } | ||
| 250 | |||
| 251 | sub execute_js { | ||
| 252 | my ( $self, $url, $scripts ) = @_; | ||
| 253 | my $client = $self->client; | ||
| 254 | return $self->_parsed( | ||
| 255 | $client->execute_js_request( $url, $scripts ), | ||
| 256 | sub { $client->parse_execute_js_response( $_[0] ) }, | ||
| 257 | ); | ||
| 258 | } | ||
| 259 | |||
| 260 | sub llm { | ||
| 261 | my ( $self, $url, $query, %opts ) = @_; | ||
| 262 | my $client = $self->client; | ||
| 263 | return $self->_parsed( | ||
| 264 | $client->llm_request( $url, $query, %opts ), | ||
| 265 | sub { $client->parse_llm_response( $_[0] ) }, | ||
| 266 | ); | ||
| 267 | } | ||
| 268 | |||
| 269 | sub token { | ||
| 270 | my ( $self, $email, %opts ) = @_; | ||
| 271 | my $client = $self->client; | ||
| 272 | return $self->_parsed( | ||
| 273 | $client->token_request( $email, %opts ), | ||
| 274 | sub { $client->parse_token_response( $_[0] ) }, | ||
| 275 | ); | ||
| 276 | } | ||
| 277 | |||
| 278 | #---------------------------------------------------------------------- | ||
| 279 | # Job flow helper | ||
| 280 | #---------------------------------------------------------------------- | ||
| 281 | |||
| 282 | sub crawl_job_and_wait { | ||
| 283 | my ( $self, $request, %opts ) = @_; | ||
| 284 | my $interval = delete $opts{poll_interval}; | ||
| 285 | my $req = ( blessed($request) && $request->isa('WWW::Crawl4AI::Request') ) | ||
| 286 | ? $request | ||
| 287 | : WWW::Crawl4AI::Request->new( urls => $request, %opts ); | ||
| 288 | return $self->job_submit($req)->then( sub { | ||
| 289 | my ( $job ) = @_; | ||
| 290 | $self->_poll_job( $job->{task_id}, $interval ); | ||
| 291 | } ); | ||
| 292 | } | ||
| 293 | |||
| 294 | |||
| 295 | sub _poll_job { | ||
| 296 | my ( $self, $task_id, $interval ) = @_; | ||
| 297 | $interval = $self->poll_interval unless defined $interval; | ||
| 298 | croak "not added to a loop yet" unless $self->loop || $self->{delay_sub}; | ||
| 299 | return repeat { | ||
| 300 | $self->job_status($task_id)->then( sub { | ||
| 301 | my ( $status ) = @_; | ||
| 302 | return Future->done($status) if ( $status->{status} // '' ) eq 'COMPLETED'; | ||
| 303 | return $self->_delay_future($interval)->then( sub { Future->done($status) } ); | ||
| 304 | } ); | ||
| 305 | } until => sub { | ||
| 306 | my ( $f ) = @_; | ||
| 307 | return 1 if $f->is_failed; # parser fails the Future on a FAILED job | ||
| 308 | return ( $f->get->{status} // '' ) eq 'COMPLETED'; | ||
| 309 | }; | ||
| 310 | } | ||
| 311 | |||
| 312 | #---------------------------------------------------------------------- | ||
| 313 | # Async strategy chain — the headline async API | ||
| 314 | #---------------------------------------------------------------------- | ||
| 315 | |||
| 316 | sub _elapsed { sprintf( '%.3f', Time::HiRes::time() - $_[0] ) + 0 } | ||
| 317 | |||
| 318 | # Run a single strategy asynchronously, resolving to a normalized page (or | ||
| 319 | # undef). crawl4ai-backed strategies dispatch through Net::Async::HTTP; the | ||
| 320 | # external_callback strategy hands the URL to the user coderef, which may return | ||
| 321 | # a hashref or a Future of one. | ||
| 322 | sub _run_strategy_future { | ||
| 323 | my ( $self, $strategy, $url, %opts ) = @_; | ||
| 324 | my $www = $self->crawl4ai; | ||
| 325 | |||
| 326 | if ( $strategy->can('build_request') ) { | ||
| 327 | my $req = $strategy->build_request( $www, $url, %opts ); | ||
| 328 | return $self->crawl_once( $req, $strategy->name )->then( sub { Future->done( $_[0]->[0] ) } ); | ||
| 329 | } | ||
| 330 | |||
| 331 | if ( $strategy->name eq 'external_callback' ) { | ||
| 332 | my $ret = $www->callback->( $url, %opts ); | ||
| 333 | my $normalize = sub { | ||
| 334 | my ( $page ) = @_; | ||
| 335 | return undef unless ref $page eq 'HASH'; | ||
| 336 | $page->{url} //= $url; | ||
| 337 | $page->{final_url} //= $page->{url}; | ||
| 338 | return $page; | ||
| 339 | }; | ||
| 340 | return $ret->then( sub { Future->done( $normalize->( $_[0] ) ) } ) | ||
| 341 | if blessed($ret) && $ret->isa('Future'); | ||
| 342 | return Future->done( $normalize->($ret) ); | ||
| 343 | } | ||
| 344 | |||
| 345 | # Any other custom strategy: run its sync crawl, allowing a Future return. | ||
| 346 | my $page = $strategy->crawl( $www, $url, %opts ); | ||
| 347 | return $page if blessed($page) && $page->isa('Future'); | ||
| 348 | return Future->done($page); | ||
| 349 | } | ||
| 350 | |||
| 351 | sub crawl { | ||
| 352 | my ( $self, @args ) = @_; | ||
| 353 | my $www = $self->crawl4ai; | ||
| 354 | my ( $url, %opts ) = $www->_normalize_args(@args); | ||
| 355 | croak "crawl needs a url" unless defined $url && length $url; | ||
| 356 | |||
| 357 | my $detect = $www->_detect_opts(%opts); | ||
| 358 | my @strategies = @{ $www->strategies }; | ||
| 359 | return Future->done( $www->_failed_result( $url, [] ) ) unless @strategies; | ||
| 360 | |||
| 361 | my @attempts; | ||
| 362 | my $i = 0; | ||
| 363 | return ( | ||
| 364 | repeat { | ||
| 365 | my $strategy = $strategies[ $i++ ]; | ||
| 366 | my $t0 = Time::HiRes::time(); | ||
| 367 | $self->_run_strategy_future( $strategy, $url, %opts )->then( | ||
| 368 | sub { | ||
| 369 | push @attempts, $www->_attempt_for( $strategy, $_[0], undef, _elapsed($t0), $detect ); | ||
| 370 | Future->done( $attempts[-1] ); | ||
| 371 | }, | ||
| 372 | sub { | ||
| 373 | push @attempts, $www->_attempt_for( $strategy, undef, $_[0], _elapsed($t0), $detect ); | ||
| 374 | Future->done( $attempts[-1] ); | ||
| 375 | }, | ||
| 376 | ); | ||
| 377 | } while => sub { | ||
| 378 | my $attempt = $_[0]->get; | ||
| 379 | return 0 if $attempt->ok; | ||
| 380 | return $i < @strategies ? 1 : 0; | ||
| 381 | } | ||
| 382 | )->then( sub { | ||
| 383 | my ( $winner ) = grep { $_->ok } @attempts; | ||
| 384 | return Future->done( | ||
| 385 | $winner | ||
| 386 | ? WWW::Crawl4AI::Result->from_attempt( $winner, attempts => \@attempts ) | ||
| 387 | : $www->_failed_result( $url, \@attempts ) | ||
| 388 | ); | ||
| 389 | } ); | ||
| 390 | } | ||
| 391 | |||
| 392 | |||
| 393 | sub markdown { my ( $self, @args ) = @_; return $self->crawl(@args) } | ||
| 394 | |||
| 395 | sub deep_crawl { | ||
| 396 | my ( $self, @args ) = @_; | ||
| 397 | my $www = $self->crawl4ai; | ||
| 398 | my ( $start, %opts ) = $www->_normalize_args(@args); | ||
| 399 | croak "deep_crawl needs a url" unless defined $start && length $start; | ||
| 400 | |||
| 401 | my $max_pages = exists $opts{max_pages} ? delete $opts{max_pages} : 25; | ||
| 402 | my $max_depth = exists $opts{max_depth} ? delete $opts{max_depth} : 2; | ||
| 403 | my $same_host = exists $opts{same_host} ? delete $opts{same_host} : 1; | ||
| 404 | my $concurrency = exists $opts{concurrency} ? delete $opts{concurrency} : 4; | ||
| 405 | my $on_page = delete $opts{on_page}; | ||
| 406 | my $url_filter = delete $opts{url_filter}; | ||
| 407 | |||
| 408 | my $start_host; # locked onto the host the start URL actually resolved to | ||
| 409 | my %seen = ( $www->_canon_url($start) => 1 ); | ||
| 410 | my $seq = 0; | ||
| 411 | my %collected; # enqueue index => result, so the result list comes out in | ||
| 412 | # breadth-first order regardless of which order a concurrent | ||
| 413 | # frontier happens to complete in | ||
| 414 | |||
| 415 | # Crawl one frontier level concurrently, gather the next level, recurse. | ||
| 416 | my $process_level; | ||
| 417 | $process_level = sub { | ||
| 418 | my ( $frontier ) = @_; | ||
| 419 | my $remaining = $max_pages - keys %collected; | ||
| 420 | return Future->done unless @$frontier && $remaining > 0; | ||
| 421 | # Trim to the budget up front so we never fire requests we'd only discard. | ||
| 422 | $frontier = [ @{$frontier}[ 0 .. $remaining - 1 ] ] if @$frontier > $remaining; | ||
| 423 | |||
| 424 | my @next; | ||
| 425 | my $level = fmap_void { | ||
| 426 | my ( $node ) = @_; | ||
| 427 | $self->crawl( $node->{url}, %opts )->then( sub { | ||
| 428 | my ( $result ) = @_; | ||
| 429 | $collected{ $node->{seq} } = $result; | ||
| 430 | $on_page->( $result, $node->{depth} ) if $on_page; | ||
| 431 | # Take the host from the start URL's actual final_url (depth 0), so a | ||
| 432 | # scheme-less start or a redirect to www. doesn't reject every link. | ||
| 433 | $start_host //= lc( eval { URI->new( $result->final_url // $node->{url} )->host } // '' ); | ||
| 434 | if ( $node->{depth} < $max_depth && $result->ok ) { | ||
| 435 | for my $url ( @{ $result->urls } ) { | ||
| 436 | my $canon = $www->_canon_url($url); | ||
| 437 | next if $seen{$canon}++; | ||
| 438 | if ($same_host) { | ||
| 439 | my $host = lc( eval { URI->new($url)->host } // '' ); | ||
| 440 | next unless $host eq $start_host; | ||
| 441 | } | ||
| 442 | next if $url_filter && !$url_filter->($url); | ||
| 443 | push @next, { url => $url, depth => $node->{depth} + 1, seq => $seq++ }; | ||
| 444 | } | ||
| 445 | } | ||
| 446 | Future->done; | ||
| 447 | } ); | ||
| 448 | } foreach => [ @$frontier ], concurrent => $concurrency; | ||
| 449 | |||
| 450 | return $level->then( sub { $process_level->( \@next ) } ); | ||
| 451 | }; | ||
| 452 | |||
| 453 | my $f = $process_level->( [ { url => $start, depth => 0, seq => $seq++ } ] ) | ||
| 454 | ->then( sub { Future->done( [ @collected{ sort { $a <=> $b } keys %collected } ] ) } ); | ||
| 455 | $f->on_ready( sub { undef $process_level } ); # break the self-referential cycle | ||
| 456 | return $f; | ||
| 457 | } | ||
| 458 | |||
| 459 | |||
| 460 | |||
| 461 | 1; | ||
| 462 | |||
| 463 | __END__ |