PageRenderTime 50ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Mojo/Promise.pm

https://github.com/kraih/mojo
Perl | 541 lines | 404 code | 123 blank | 14 comment | 42 complexity | 7e79d93741275241bee3b90992181367 MD5 | raw file
Possible License(s): AGPL-3.0
  1. package Mojo::Promise;
  2. use Mojo::Base -base;
  3. use Carp qw(carp);
  4. use Mojo::Exception;
  5. use Mojo::IOLoop;
  6. use Scalar::Util qw(blessed);
  7. use constant DEBUG => $ENV{MOJO_PROMISE_DEBUG} || 0;
  8. has ioloop => sub { Mojo::IOLoop->singleton }, weak => 1;
  9. sub AWAIT_CHAIN_CANCEL { }
  10. sub AWAIT_CLONE { _await('clone', @_) }
  11. sub AWAIT_DONE { shift->resolve(@_) }
  12. sub AWAIT_FAIL { shift->reject(@_) }
  13. sub AWAIT_GET {
  14. my $self = shift;
  15. my @results = @{$self->{results} // []};
  16. die $results[0] unless $self->{status} eq 'resolve';
  17. return wantarray ? @results : $results[0];
  18. }
  19. sub AWAIT_IS_CANCELLED {undef}
  20. sub AWAIT_IS_READY {
  21. my $self = shift;
  22. $self->{handled} = 1;
  23. return !!$self->{results} && !@{$self->{resolve}} && !@{$self->{reject}};
  24. }
  25. sub AWAIT_NEW_DONE { _await('resolve', @_) }
  26. sub AWAIT_NEW_FAIL { _await('reject', @_) }
  27. sub AWAIT_ON_CANCEL { }
  28. sub AWAIT_ON_READY {
  29. shift->_finally(0, @_)->catch(sub { });
  30. }
  31. sub AWAIT_WAIT {
  32. my $self = shift;
  33. $self->catch(sub { })->wait;
  34. return $self->AWAIT_GET;
  35. }
  36. sub DESTROY {
  37. my $self = shift;
  38. return if $self->{handled} || ($self->{status} // '') ne 'reject' || !$self->{results};
  39. carp "Unhandled rejected promise: @{$self->{results}}";
  40. warn $self->{debug}->message("-- Destroyed promise\n")->verbose(1)->to_string if DEBUG;
  41. }
  42. sub all { _all(2, @_) }
  43. sub all_settled { _all(0, @_) }
  44. sub any { _all(3, @_) }
  45. sub catch { shift->then(undef, shift) }
  46. sub clone { $_[0]->new->ioloop($_[0]->ioloop) }
  47. sub finally { shift->_finally(1, @_) }
  48. sub map {
  49. my ($class, $options, $cb, @items) = (shift, ref $_[0] eq 'HASH' ? shift : {}, @_);
  50. return $class->all(map { $_->$cb } @items) if !$options->{concurrency} || @items <= $options->{concurrency};
  51. my @start = map { $_->$cb } splice @items, 0, $options->{concurrency};
  52. my @wait = map { $start[0]->clone } 0 .. $#items;
  53. my $start_next = sub {
  54. return () unless my $item = shift @items;
  55. my ($start_next, $chain) = (__SUB__, shift @wait);
  56. $_->$cb->then(sub { $chain->resolve(@_); $start_next->() }, sub { $chain->reject(@_); @items = () }) for $item;
  57. return ();
  58. };
  59. $_->then($start_next, sub { }) for @start;
  60. return $class->all(@start, @wait);
  61. }
  62. sub new {
  63. my $self = shift->SUPER::new;
  64. $self->{debug} = Mojo::Exception->new->trace if DEBUG;
  65. shift->(sub { $self->resolve(@_) }, sub { $self->reject(@_) }) if @_;
  66. return $self;
  67. }
  68. sub race { _all(1, @_) }
  69. sub reject { shift->_settle('reject', @_) }
  70. sub resolve { shift->_settle('resolve', @_) }
  71. sub then {
  72. my ($self, $resolve, $reject) = @_;
  73. my $new = $self->clone;
  74. $self->{handled} = 1;
  75. push @{$self->{resolve}}, sub { _then_cb($new, $resolve, 'resolve', @_) };
  76. push @{$self->{reject}}, sub { _then_cb($new, $reject, 'reject', @_) };
  77. $self->_defer if $self->{results};
  78. return $new;
  79. }
  80. sub timer { shift->_timer('resolve', @_) }
  81. sub timeout { shift->_timer('reject', @_) }
  82. sub wait {
  83. my $self = shift;
  84. return if (my $loop = $self->ioloop)->is_running;
  85. my $done;
  86. $self->_finally(0, sub { $done++; $loop->stop })->catch(sub { });
  87. $loop->start until $done;
  88. }
  89. sub _all {
  90. my ($type, $class, @promises) = @_;
  91. my $all = $promises[0]->clone;
  92. my $results = [];
  93. my $remaining = scalar @promises;
  94. for my $i (0 .. $#promises) {
  95. # "race"
  96. if ($type == 1) {
  97. $promises[$i]->then(sub { $all->resolve(@_); () }, sub { $all->reject(@_); () });
  98. }
  99. # "all"
  100. elsif ($type == 2) {
  101. $promises[$i]->then(
  102. sub {
  103. $results->[$i] = [@_];
  104. $all->resolve(@$results) if --$remaining <= 0;
  105. return ();
  106. },
  107. sub { $all->reject(@_); () }
  108. );
  109. }
  110. # "any"
  111. elsif ($type == 3) {
  112. $promises[$i]->then(
  113. sub { $all->resolve(@_); () },
  114. sub {
  115. $results->[$i] = [@_];
  116. $all->reject(@$results) if --$remaining <= 0;
  117. return ();
  118. }
  119. );
  120. }
  121. # "all_settled"
  122. else {
  123. $promises[$i]->then(
  124. sub {
  125. $results->[$i] = {status => 'fulfilled', value => [@_]};
  126. $all->resolve(@$results) if --$remaining <= 0;
  127. return ();
  128. },
  129. sub {
  130. $results->[$i] = {status => 'rejected', reason => [@_]};
  131. $all->resolve(@$results) if --$remaining <= 0;
  132. return ();
  133. }
  134. );
  135. }
  136. }
  137. return $all;
  138. }
  139. sub _await {
  140. my ($method, $class) = (shift, shift);
  141. my $promise = $class->$method(@_);
  142. $promise->{cycle} = $promise;
  143. return $promise;
  144. }
  145. sub _defer {
  146. my $self = shift;
  147. return unless my $results = $self->{results};
  148. my $cbs = $self->{status} eq 'resolve' ? $self->{resolve} : $self->{reject};
  149. @{$self}{qw(cycle resolve reject)} = (undef, [], []);
  150. $self->ioloop->next_tick(sub { $_->(@$results) for @$cbs });
  151. }
  152. sub _finally {
  153. my ($self, $handled, $finally) = @_;
  154. my $new = $self->clone;
  155. my $cb = sub {
  156. my @results = @_;
  157. $new->resolve($finally->())->then(sub {@results});
  158. };
  159. my $before = $self->{handled};
  160. $self->catch($cb);
  161. my $next = $self->then($cb);
  162. delete $self->{handled} if !$before && !$handled;
  163. return $next;
  164. }
  165. sub _settle {
  166. my ($self, $status, @results) = @_;
  167. my $thenable = blessed $results[0] && $results[0]->can('then');
  168. unless (ref $self) {
  169. return $results[0] if $thenable && $status eq 'resolve' && $results[0]->isa('Mojo::Promise');
  170. $self = $self->new;
  171. }
  172. if ($thenable && $status eq 'resolve') {
  173. $results[0]->then(sub { $self->resolve(@_); () }, sub { $self->reject(@_); () });
  174. }
  175. elsif (!$self->{results}) {
  176. @{$self}{qw(results status)} = (\@results, $status);
  177. $self->_defer;
  178. }
  179. return $self;
  180. }
  181. sub _then_cb {
  182. my ($new, $cb, $method, @results) = @_;
  183. return $new->$method(@results) unless defined $cb;
  184. my @res;
  185. return $new->reject($@) unless eval { @res = $cb->(@results); 1 };
  186. return $new->resolve(@res);
  187. }
  188. sub _timer {
  189. my ($self, $method, $after, @results) = @_;
  190. $self = $self->new unless ref $self;
  191. $results[0] = 'Promise timeout' if $method eq 'reject' && !@results;
  192. $self->ioloop->timer($after => sub { $self->$method(@results) });
  193. return $self;
  194. }
  195. 1;
  196. =encoding utf8
  197. =head1 NAME
  198. Mojo::Promise - Promises/A+
  199. =head1 SYNOPSIS
  200. use Mojo::Promise;
  201. use Mojo::UserAgent;
  202. # Wrap continuation-passing style APIs with promises
  203. my $ua = Mojo::UserAgent->new;
  204. sub get_p {
  205. my $promise = Mojo::Promise->new;
  206. $ua->get(@_ => sub ($ua, $tx) {
  207. my $err = $tx->error;
  208. if (!$err || $err->{code}) { $promise->resolve($tx) }
  209. else { $promise->reject($err->{message}) }
  210. });
  211. return $promise;
  212. }
  213. # Perform non-blocking operations sequentially
  214. get_p('https://mojolicious.org')->then(sub ($mojo) {
  215. say $mojo->res->code;
  216. return get_p('https://metacpan.org');
  217. })->then(sub ($cpan) {
  218. say $cpan->res->code;
  219. })->catch(sub ($err) {
  220. warn "Something went wrong: $err";
  221. })->wait;
  222. # Synchronize non-blocking operations (all)
  223. my $mojo = get_p('https://mojolicious.org');
  224. my $cpan = get_p('https://metacpan.org');
  225. Mojo::Promise->all($mojo, $cpan)->then(sub ($mojo, $cpan) {
  226. say $mojo->[0]->res->code;
  227. say $cpan->[0]->res->code;
  228. })->catch(sub ($err) {
  229. warn "Something went wrong: $err";
  230. })->wait;
  231. # Synchronize non-blocking operations (race)
  232. my $mojo = get_p('https://mojolicious.org');
  233. my $cpan = get_p('https://metacpan.org');
  234. Mojo::Promise->race($mojo, $cpan)->then(sub ($tx) {
  235. say $tx->req->url, ' won!';
  236. })->catch(sub ($err) {
  237. warn "Something went wrong: $err";
  238. })->wait;
  239. =head1 DESCRIPTION
  240. L<Mojo::Promise> is a Perl-ish implementation of L<Promises/A+|https://promisesaplus.com> and a superset of L<ES6
  241. Promises|https://duckduckgo.com/?q=\mdn%20Promise>.
  242. =head1 STATES
  243. A promise is an object representing the eventual completion or failure of a non-blocking operation. It allows
  244. non-blocking functions to return values, like blocking functions. But instead of immediately returning the final value,
  245. the non-blocking function returns a promise to supply the value at some point in the future.
  246. A promise can be in one of three states:
  247. =over 2
  248. =item pending
  249. Initial state, neither fulfilled nor rejected.
  250. =item fulfilled
  251. Meaning that the operation completed successfully.
  252. =item rejected
  253. Meaning that the operation failed.
  254. =back
  255. A pending promise can either be fulfilled with a value or rejected with a reason. When either happens, the associated
  256. handlers queued up by a promise's L</"then"> method are called.
  257. =head1 ATTRIBUTES
  258. L<Mojo::Promise> implements the following attributes.
  259. =head2 ioloop
  260. my $loop = $promise->ioloop;
  261. $promise = $promise->ioloop(Mojo::IOLoop->new);
  262. Event loop object to control, defaults to the global L<Mojo::IOLoop> singleton. Note that this attribute is weakened.
  263. =head1 METHODS
  264. L<Mojo::Promise> inherits all methods from L<Mojo::Base> and implements the following new ones.
  265. =head2 all
  266. my $new = Mojo::Promise->all(@promises);
  267. Returns a new L<Mojo::Promise> object that either fulfills when all of the passed L<Mojo::Promise> objects have
  268. fulfilled or rejects as soon as one of them rejects. If the returned promise fulfills, it is fulfilled with the values
  269. from the fulfilled promises in the same order as the passed promises.
  270. =head2 all_settled
  271. my $new = Mojo::Promise->all_settled(@promises);
  272. Returns a new L<Mojo::Promise> object that fulfills when all of the passed L<Mojo::Promise> objects have fulfilled or
  273. rejected, with hash references that describe the outcome of each promise.
  274. =head2 any
  275. my $new = Mojo::Promise->any(@promises);
  276. Returns a new L<Mojo::Promise> object that fulfills as soon as one of the passed L<Mojo::Promise> objects fulfills,
  277. with the value from that promise.
  278. =head2 catch
  279. my $new = $promise->catch(sub {...});
  280. Appends a rejection handler callback to the promise, and returns a new L<Mojo::Promise> object resolving to the return
  281. value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled.
  282. # Longer version
  283. my $new = $promise->then(undef, sub {...});
  284. # Pass along the rejection reason
  285. $promise->catch(sub (@reason) {
  286. warn "Something went wrong: $reason[0]";
  287. return @reason;
  288. });
  289. # Change the rejection reason
  290. $promise->catch(sub (@reason) { "This is bad: $reason[0]" });
  291. =head2 clone
  292. my $new = $promise->clone;
  293. Return a new L<Mojo::Promise> object cloned from this promise that is still pending.
  294. =head2 finally
  295. my $new = $promise->finally(sub {...});
  296. Appends a fulfillment and rejection handler to the promise, and returns a new L<Mojo::Promise> object resolving to the
  297. original fulfillment value or rejection reason.
  298. # Do something on fulfillment and rejection
  299. $promise->finally(sub { say "We are done!" });
  300. =head2 map
  301. my $new = Mojo::Promise->map(sub {...}, @items);
  302. my $new = Mojo::Promise->map({concurrency => 3}, sub {...}, @items);
  303. Apply a function that returns a L<Mojo::Promise> to each item in a list of items while optionally limiting concurrency.
  304. Returns a L<Mojo::Promise> that collects the results in the same manner as L</all>. If any item's promise is rejected,
  305. any remaining items which have not yet been mapped will not be.
  306. # Perform 3 requests at a time concurrently
  307. Mojo::Promise->map({concurrency => 3}, sub { $ua->get_p($_) }, @urls)
  308. ->then(sub{ say $_->[0]->res->dom->at('title')->text for @_ });
  309. These options are currently available:
  310. =over 2
  311. =item concurrency
  312. concurrency => 3
  313. The maximum number of items that are in progress at the same time.
  314. =back
  315. =head2 new
  316. my $promise = Mojo::Promise->new;
  317. my $promise = Mojo::Promise->new(sub {...});
  318. Construct a new L<Mojo::Promise> object.
  319. # Wrap a continuation-passing style API
  320. my $promise = Mojo::Promise->new(sub ($resolve, $reject) {
  321. Mojo::IOLoop->timer(5 => sub {
  322. if (int rand 2) { $resolve->('Lucky!') }
  323. else { $reject->('Unlucky!') }
  324. });
  325. });
  326. =head2 race
  327. my $new = Mojo::Promise->race(@promises);
  328. Returns a new L<Mojo::Promise> object that fulfills or rejects as soon as one of the passed L<Mojo::Promise> objects
  329. fulfills or rejects, with the value or reason from that promise.
  330. =head2 reject
  331. my $new = Mojo::Promise->reject(@reason);
  332. $promise = $promise->reject(@reason);
  333. Build rejected L<Mojo::Promise> object or reject the promise with one or more rejection reasons.
  334. # Longer version
  335. my $promise = Mojo::Promise->new->reject(@reason);
  336. =head2 resolve
  337. my $new = Mojo::Promise->resolve(@value);
  338. $promise = $promise->resolve(@value);
  339. Build resolved L<Mojo::Promise> object or resolve the promise with one or more fulfillment values.
  340. # Longer version
  341. my $promise = Mojo::Promise->new->resolve(@value);
  342. =head2 then
  343. my $new = $promise->then(sub {...});
  344. my $new = $promise->then(sub {...}, sub {...});
  345. my $new = $promise->then(undef, sub {...});
  346. Appends fulfillment and rejection handlers to the promise, and returns a new L<Mojo::Promise> object resolving to the
  347. return value of the called handler.
  348. # Pass along the fulfillment value or rejection reason
  349. $promise->then(
  350. sub (@value) {
  351. say "The result is $value[0]";
  352. return @value;
  353. },
  354. sub (@reason) {
  355. warn "Something went wrong: $reason[0]";
  356. return @reason;
  357. }
  358. );
  359. # Change the fulfillment value or rejection reason
  360. $promise->then(
  361. sub (@value) { return "This is good: $value[0]" },
  362. sub (@reason) { return "This is bad: $reason[0]" }
  363. );
  364. =head2 timer
  365. my $new = Mojo::Promise->timer(5 => 'Success!');
  366. $promise = $promise->timer(5 => 'Success!');
  367. $promise = $promise->timer(5);
  368. Create a new L<Mojo::Promise> object with a timer or attach a timer to an existing promise. The promise will be
  369. resolved after the given amount of time in seconds with or without a value.
  370. =head2 timeout
  371. my $new = Mojo::Promise->timeout(5 => 'Timeout!');
  372. $promise = $promise->timeout(5 => 'Timeout!');
  373. $promise = $promise->timeout(5);
  374. Create a new L<Mojo::Promise> object with a timeout or attach a timeout to an existing promise. The promise will be
  375. rejected after the given amount of time in seconds with a reason, which defaults to C<Promise timeout>.
  376. =head2 wait
  377. $promise->wait;
  378. Start L</"ioloop"> and stop it again once the promise has been fulfilled or rejected, does nothing when L</"ioloop"> is
  379. already running.
  380. =head1 DEBUGGING
  381. You can set the C<MOJO_PROMISE_DEBUG> environment variable to get some advanced diagnostics information printed to
  382. C<STDERR>.
  383. MOJO_PROMISE_DEBUG=1
  384. =head1 SEE ALSO
  385. L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
  386. =cut