5f16f22016-11-05Martin Nilsson #pike __REAL_VERSION__
9654f72016-04-12Henrik Grubbström (Grubba) //! Module for handling multiple concurrent events.
31dd442016-06-15Henrik Grubbström (Grubba) //! //! The @[Future] and @[Promise] API was inspired by //! @url{https://github.com/couchdeveloper/FutureLib@}.
c60ad22016-04-13Henrik Grubbström (Grubba) 
9654f72016-04-12Henrik Grubbström (Grubba) protected enum State { STATE_PENDING = 0, STATE_FULFILLED, STATE_REJECTED, }; protected Thread.Mutex mux = Thread.Mutex(); protected Thread.Condition cond = Thread.Condition();
7affa12017-02-24Martin Nilsson //! Global failure callback, called when a promise without failure //! callback fails. This is useful to log exceptions, so they are not //! just silently caught and ignored.
c76f642017-02-24Martin Nilsson void on_failure(function(mixed : void) f)
7affa12017-02-24Martin Nilsson { global_on_failure = f; }
c76f642017-02-24Martin Nilsson protected function(mixed : void) global_on_failure;
7affa12017-02-24Martin Nilsson 
76c6142017-11-28Stephen R. van den Berg //! @param enable //! Setting this to @expr{false@} causes all @[Concurrent] callbacks
d4eb912017-11-28Stephen R. van den Berg //! (except for timeouts) //! to be called directly, without using a backend. //! //! @note //! (Un)setting this typically alters the order in which some callbacks //! are called (depending on what happens in a callback).
76c6142017-11-28Stephen R. van den Berg final void use_backend(int enable) { callout = enable ? call_out : callnow; } private mixed callnow(function(mixed ...:void) f, int|float delay, mixed ... args) {
d813ed2017-11-30Stephen R. van den Berg  mixed err = catch (f(@args)); if (err) master()->handle_error(err); return 0;
76c6142017-11-28Stephen R. van den Berg } protected function(function(mixed ...:void), int|float, mixed ...:mixed) callout = call_out;
9654f72016-04-12Henrik Grubbström (Grubba) //! Value that will be provided asynchronously //! sometime in the future. //! //! @seealso //! @[Promise] class Future { mixed result = UNDEFINED; State state;
4ad02b2017-11-27Stephen R. van den Berg  protected array(array(function(mixed, mixed ...: void)|mixed))
bf700d2016-10-26Henrik Grubbström (Grubba)  success_cbs = ({});
4ad02b2017-11-27Stephen R. van den Berg  protected array(array(function(mixed, mixed ...: void)|mixed))
bf700d2016-10-26Henrik Grubbström (Grubba)  failure_cbs = ({});
9654f72016-04-12Henrik Grubbström (Grubba) 
6b01882016-11-09Stephen R. van den Berg  //! Wait for fulfillment and return the value.
9654f72016-04-12Henrik Grubbström (Grubba)  //! //! @throws //! Throws on rejection. mixed get() { State s = state; mixed res = result; if (!s) {
e32dd02017-11-27Stephen R. van den Berg  Thread.MutexKey key = mux->lock();
9654f72016-04-12Henrik Grubbström (Grubba)  while (!state) { cond->wait(key); } s = state; res = result; } if (s == STATE_REJECTED) { throw(res); } return res; } //! Register a callback that is to be called on fulfillment.
bf700d2016-10-26Henrik Grubbström (Grubba)  //! //! @param cb //! Function to be called. The first argument will be the //! result of the @[Future]. //! //! @param extra //! Any extra context needed for @[cb]. They will be provided //! as arguments two and onwards when @[cb] is called. //! //! @note //! @[cb] will always be called from the main backend. //! //! @seealso //! @[on_failure()]
47c3112016-05-10Pontus Östlund  this_program on_success(function(mixed, mixed ... : void) cb, mixed ... extra)
9654f72016-04-12Henrik Grubbström (Grubba)  {
0831fe2017-11-28Stephen R. van den Berg  switch (state) { case STATE_FULFILLED: callout(cb, 0, result, @extra); break; case STATE_PENDING: // Rely on interpreter lock to add to success_cbs before state changes // again success_cbs += ({ ({ cb, @extra }) });
9654f72016-04-12Henrik Grubbström (Grubba)  }
079bac2017-11-25Stephen R. van den Berg  return this_program::this;
9654f72016-04-12Henrik Grubbström (Grubba)  } //! Register a callback that is to be called on failure.
bf700d2016-10-26Henrik Grubbström (Grubba)  //! //! @param cb //! Function to be called. The first argument will be the //! failure result of the @[Future]. //! //! @param extra //! Any extra context needed for @[cb]. They will be provided //! as arguments two and onwards when @[cb] is called. //! //! @note //! @[cb] will always be called from the main backend. //! //! @seealso //! @[on_success()]
47c3112016-05-10Pontus Östlund  this_program on_failure(function(mixed, mixed ... : void) cb, mixed ... extra)
9654f72016-04-12Henrik Grubbström (Grubba)  {
0831fe2017-11-28Stephen R. van den Berg  switch (state) { case STATE_REJECTED: callout(cb, 0, result, @extra); break; case STATE_PENDING: // Rely on interpreter lock to add to failure_cbs before state changes // again failure_cbs += ({ ({ cb, @extra }) });
9654f72016-04-12Henrik Grubbström (Grubba)  }
079bac2017-11-25Stephen R. van den Berg  return this_program::this;
9654f72016-04-12Henrik Grubbström (Grubba)  }
c60ad22016-04-13Henrik Grubbström (Grubba)  //! Apply @[fun] with @[val] followed by the contents of @[ctx], //! and update @[p] with the result. protected void apply(mixed val, Promise p, function(mixed, mixed ... : mixed) fun, array(mixed) ctx) { mixed err = catch { p->success(fun(val, @ctx)); return; }; p->failure(err); } //! Apply @[fun] with @[val] followed by the contents of @[ctx], //! and update @[p] with the eventual result. protected void apply_flat(mixed val, Promise p, function(mixed, mixed ... : Future) fun, array(mixed) ctx) { mixed err = catch { Future f = fun(val, @ctx); if (!objectp(f) || !f->on_failure || !f->on_success) { error("Expected %O to return a Future. Got: %O.\n", fun, f); } f->on_failure(p->failure); f->on_success(p->success); return; }; p->failure(err); } //! Apply @[fun] with @[val] followed by the contents of @[ctx],
ccbf012016-12-01Stephen R. van den Berg  //! and update @[p] with the eventual result. protected void apply_smart(mixed val, Promise p, function(mixed, mixed ... : mixed|Future) fun, array(mixed) ctx) { mixed err = catch { mixed|Future f = fun(val, @ctx); if (!objectp(f) || !functionp(f->on_failure) || !functionp(f->on_success)) { p->success(f); return; } f->on_failure(p->failure); f->on_success(p->success); return; }; p->failure(err); } //! Apply @[fun] with @[val] followed by the contents of @[ctx],
c60ad22016-04-13Henrik Grubbström (Grubba)  //! and update @[p] with @[val] if @[fun] didn't return false. //! If @[fun] returned false fail @[p] with @[UNDEFINED]. protected void apply_filter(mixed val, Promise p, function(mixed, mixed ... : int(0..1)) fun, array(mixed) ctx) { mixed err = catch { if (fun(val, @ctx)) { p->success(val); } else { p->failure(UNDEFINED); } return; }; p->failure(err); }
6b266a2017-12-04Stephen R. van den Berg  //! This specifies a callback that is only called on success, and //! allows you to alter the future. //! //! @param fun //! Function to be called. The first argument will be the //! @b{success@} result of @b{this@} @[Future]. //! The return value will be the success result of the new @[Future]. //! //! @param extra //! Any extra context needed for //! @expr{fun@}. They will be provided //! as arguments two and onwards when the callback is called. //! //! @returns //! The new @[Future].
cf8af82017-11-24Stephen R. van den Berg  //! //! @note //! This method is used if your @[fun] returns a regular value (i.e. //! @b{not@} a @[Future]). //! //! @seealso
079bac2017-11-25Stephen R. van den Berg  //! @[map_with()], @[transform()], @[recover()]
c60ad22016-04-13Henrik Grubbström (Grubba)  this_program map(function(mixed, mixed ... : mixed) fun, mixed ... extra) { Promise p = Promise(); on_failure(p->failure); on_success(apply, p, fun, extra); return p->future(); }
6b266a2017-12-04Stephen R. van den Berg  //! This specifies a callback that is only called on success, and //! allows you to alter the future. //! //! @param fun //! Function to be called. The first argument will be the //! @b{success@} result of @b{this@} @[Future]. //! The return value must be a @[Future] that promises //! the new result. //! //! @param extra //! Any extra context needed for //! @expr{fun@}. They will be provided //! as arguments two and onwards when the callback is called. //! //! @returns //! The new @[Future].
cf8af82017-11-24Stephen R. van den Berg  //! //! @note //! This method is used if your @[fun] returns a @[Future] again. //! //! @seealso
079bac2017-11-25Stephen R. van den Berg  //! @[map()], @[transform_with()], @[recover_with()], @[flat_map] this_program map_with(function(mixed, mixed ... : this_program) fun,
c60ad22016-04-13Henrik Grubbström (Grubba)  mixed ... extra) { Promise p = Promise(); on_failure(p->failure); on_success(apply_flat, p, fun, extra); return p->future(); }
079bac2017-11-25Stephen R. van den Berg  //! This is an alias for @[map_with()]. //! //! @seealso //! @[map_with()] inline this_program flat_map(function(mixed, mixed ... : this_program) fun, mixed ... extra) { return map_with(fun, @extra); }
6b266a2017-12-04Stephen R. van den Berg  //! This specifies a callback that is only called on failure, and //! allows you to alter the future into a success. //! //! @param fun //! Function to be called. The first argument will be the //! @b{failure@} result of @b{this@} @[Future]. //! The return value will be the success result of the new @[Future]. //! //! @param extra //! Any extra context needed for //! @expr{fun@}. They will be provided //! as arguments two and onwards when the callback is called. //! //! @returns //! The new @[Future].
9e94d72017-11-24Stephen R. van den Berg  //! //! @note
8d71e62017-12-04Stephen R. van den Berg  //! This method is used if your callbacks return a regular value (i.e.
9e94d72017-11-24Stephen R. van den Berg  //! @b{not@} a @[Future]). //! //! @seealso //! @[recover_with()], @[map()], @[transform()]
c60ad22016-04-13Henrik Grubbström (Grubba)  this_program recover(function(mixed, mixed ... : mixed) fun, mixed ... extra) { Promise p = Promise(); on_success(p->success); on_failure(apply, p, fun, extra); return p->future(); }
6b266a2017-12-04Stephen R. van den Berg  //! This specifies a callback that is only called on failure, and //! allows you to alter the future into a success. //! //! @param fun //! Function to be called. The first argument will be the //! @b{failure@} result of @b{this@} @[Future]. //! The return value must be a @[Future] that promises //! the new success result. //! //! @param extra //! Any extra context needed for //! @expr{fun@}. They will be provided //! as arguments two and onwards when the callback is called. //! //! @returns //! The new @[Future].
9e94d72017-11-24Stephen R. van den Berg  //! //! @note
8d71e62017-12-04Stephen R. van den Berg  //! This method is used if your callbacks return a @[Future] again.
9e94d72017-11-24Stephen R. van den Berg  //! //! @seealso
079bac2017-11-25Stephen R. van den Berg  //! @[recover()], @[map_with()], @[transform_with()]
c60ad22016-04-13Henrik Grubbström (Grubba)  this_program recover_with(function(mixed, mixed ... : this_program) fun, mixed ... extra) { Promise p = Promise(); on_success(p->success); on_failure(apply_flat, p, fun, extra); return p->future(); } //! Return a @[Future] that either will by fulfilled by the //! fulfilled result of this @[Future] if applying @[fun] //! with the result followed by @[extra] returns true, //! or will fail with @[UNDEFINED] if it returns false. this_program filter(function(mixed, mixed ... : int(0..1)) fun, mixed ... extra) { Promise p = Promise(); on_failure(p->failure); on_success(apply_filter, p, fun, extra); return p->future(); }
8d71e62017-12-04Stephen R. van den Berg  //! This specifies callbacks that allows you to alter the future.
c60ad22016-04-13Henrik Grubbström (Grubba)  //!
8d71e62017-12-04Stephen R. van den Berg  //! @param success //! Function to be called. The first argument will be the //! @b{success@} result of @b{this@} @[Future]. //! The return value will be the success result of the new @[Future]. //! //! @param failure //! Function to be called. The first argument will be the //! @b{failure@} result of @b{this@} @[Future]. //! The return value will be the success result of the new @[Future]. //! If this callback is omitted, it will default to the same callback as //! @expr{success@}. //! //! @param extra //! Any extra context needed for //! @expr{success@} and @expr{failure@}. They will be provided //! as arguments two and onwards when the callbacks are called. //! //! @returns //! The new @[Future].
c60ad22016-04-13Henrik Grubbström (Grubba)  //!
cf8af82017-11-24Stephen R. van den Berg  //! @note
8d71e62017-12-04Stephen R. van den Berg  //! This method is used if your callbacks return a regular value (i.e.
cf8af82017-11-24Stephen R. van den Berg  //! @b{not@} a @[Future]). //!
c60ad22016-04-13Henrik Grubbström (Grubba)  //! @seealso
9e94d72017-11-24Stephen R. van den Berg  //! @[transform_with()], @[map()], @[recover()]
c60ad22016-04-13Henrik Grubbström (Grubba)  this_program transform(function(mixed, mixed ... : mixed) success, function(mixed, mixed ... : mixed)|void failure, mixed ... extra) { Promise p = Promise(); on_success(apply, p, success, extra); on_failure(apply, p, failure || success, extra); return p->future(); }
8d71e62017-12-04Stephen R. van den Berg  //! This specifies callbacks that allows you to alter the future. //! //! @param success //! Function to be called. The first argument will be the //! @b{success@} result of @b{this@} @[Future]. //! The return value must be a @[Future] that promises //! the new result. //! //! @param failure //! Function to be called. The first argument will be the //! @b{failure@} result of @b{this@} @[Future]. //! The return value must be a @[Future] that promises //! the new success result. //! If this callback is omitted, it will default to the same callback as //! @expr{success@}.
c60ad22016-04-13Henrik Grubbström (Grubba)  //!
8d71e62017-12-04Stephen R. van den Berg  //! @param extra //! Any extra context needed for //! @expr{success@} and @expr{failure@}. They will be provided //! as arguments two and onwards when the callbacks are called. //! //! @returns //! The new @[Future].
c60ad22016-04-13Henrik Grubbström (Grubba)  //!
cf8af82017-11-24Stephen R. van den Berg  //! @note
8d71e62017-12-04Stephen R. van den Berg  //! This method is used if your callbacks return a @[Future] again.
cf8af82017-11-24Stephen R. van den Berg  //!
c60ad22016-04-13Henrik Grubbström (Grubba)  //! @seealso
079bac2017-11-25Stephen R. van den Berg  //! @[transform()], @[map_with()], @[recover_with]
cf8af82017-11-24Stephen R. van den Berg  this_program transform_with(function(mixed, mixed ... : this_program) success, function(mixed, mixed ... : this_program)|void failure,
c60ad22016-04-13Henrik Grubbström (Grubba)  mixed ... extra) { Promise p = Promise(); on_success(apply_flat, p, success, extra); on_failure(apply_flat, p, failure || success, extra); return p->future(); }
aa51262016-04-18Henrik Grubbström (Grubba) 
30697c2017-12-04Stephen R. van den Berg  //! @param others //! The other futures (results) you want to append. //!
6b01882016-11-09Stephen R. van den Berg  //! @returns
30697c2017-12-04Stephen R. van den Berg  //! A new @[Future] that will be fulfilled with an
aa51262016-04-18Henrik Grubbström (Grubba)  //! array of the fulfilled result of this object followed
30697c2017-12-04Stephen R. van den Berg  //! by the fulfilled results of other futures.
aa51262016-04-18Henrik Grubbström (Grubba)  //! //! @seealso //! @[results()]
30697c2017-12-04Stephen R. van den Berg  this_program zip(array(this_program) others)
aa51262016-04-18Henrik Grubbström (Grubba)  {
ae447a2017-11-27Martin Nilsson  if (sizeof(others)) return results(({ this_program::this }) + others); return this_program::this;
aa51262016-04-18Henrik Grubbström (Grubba)  }
30697c2017-12-04Stephen R. van den Berg  inline variant this_program zip(this_program ... others) { return zip(others); }
3bce162016-06-02Henrik Grubbström (Grubba) 
6e27292016-11-18Stephen R. van den Berg  //! JavaScript Promise API close but not identical equivalent
ccbf012016-12-01Stephen R. van den Berg  //! of a combined @[transform()] and @[transform_with()].
6e27292016-11-18Stephen R. van den Berg  //!
6b01882016-11-09Stephen R. van den Berg  //! @param onfulfilled //! Function to be called on fulfillment. The first argument will be the //! result of @b{this@} @[Future]. //! The return value will be the result of the new @[Future].
ccbf012016-12-01Stephen R. van den Berg  //! If the return value already is a @[Future], pass it as-is.
6b01882016-11-09Stephen R. van den Berg  //! //! @param onrejected //! Function to be called on failure. The first argument will be the //! failure result of @b{this@} @[Future]. //! The return value will be the failure result of the new @[Future].
ccbf012016-12-01Stephen R. van den Berg  //! If the return value already is a @[Future], pass it as-is.
6b01882016-11-09Stephen R. van den Berg  //! //! @param extra //! Any extra context needed for @expr{onfulfilled@} and //! @expr{onrejected@}. They will be provided //! as arguments two and onwards when the callbacks are called. //! //! @returns //! The new @[Future]. //! //! @seealso
ccbf012016-12-01Stephen R. van den Berg  //! @[transform()], @[transform_with()], @[thencatch()], //! @[on_success()], @[Promise.success()], //! @[on_failure()], @[Promise.failure()],
6b01882016-11-09Stephen R. van den Berg  //! @url{https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise@}
1d407b2016-11-18Stephen R. van den Berg  this_program then(void|function(mixed, mixed ... : mixed) onfulfilled,
6b01882016-11-09Stephen R. van den Berg  void|function(mixed, mixed ... : mixed) onrejected,
6e27292016-11-18Stephen R. van den Berg  mixed ... extra) {
6b01882016-11-09Stephen R. van den Berg  Promise p = Promise();
6e27292016-11-18Stephen R. van den Berg  if (onfulfilled)
ccbf012016-12-01Stephen R. van den Berg  on_success(apply_smart, p, onfulfilled, extra);
6e27292016-11-18Stephen R. van den Berg  else on_success(p->success); if (onrejected)
ccbf012016-12-01Stephen R. van den Berg  on_failure(apply_smart, p, onrejected, extra);
6e27292016-11-18Stephen R. van den Berg  else on_failure(p->failure);
6b01882016-11-09Stephen R. van den Berg  return p->future(); }
ccbf012016-12-01Stephen R. van den Berg  //! JavaScript Promise API equivalent of a combination of @[recover()] //! and @[recover_with()].
6e27292016-11-18Stephen R. van den Berg  //!
6b01882016-11-09Stephen R. van den Berg  //! @param onrejected //! Function to be called. The first argument will be the //! failure result of @b{this@} @[Future]. //! The return value will the failure result of the new @[Future].
ccbf012016-12-01Stephen R. van den Berg  //! If the return value already is a @[Future], pass it as-is.
6b01882016-11-09Stephen R. van den Berg  //! //! @param extra //! Any extra context needed for //! @expr{onrejected@}. They will be provided //! as arguments two and onwards when the callback is called. //! //! @returns //! The new @[Future]. //! //! @seealso
ccbf012016-12-01Stephen R. van den Berg  //! @[recover()], @[recover_with()], @[then()], @[on_failure()], //! @[Promise.failure()],
6b01882016-11-09Stephen R. van den Berg  //! @url{https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise@}
6e27292016-11-18Stephen R. van den Berg  inline this_program thencatch(function(mixed, mixed ... : mixed) onrejected,
6b01882016-11-09Stephen R. van den Berg  mixed ... extra) {
ccbf012016-12-01Stephen R. van den Berg  return then(0, onrejected, @extra);
6b01882016-11-09Stephen R. van den Berg  }
bf700d2016-10-26Henrik Grubbström (Grubba)  //! Return a @[Future] that will either be fulfilled with the fulfilled //! result of this @[Future], or be failed after @[seconds] have expired.
3bce162016-06-02Henrik Grubbström (Grubba)  this_program timeout(int|float seconds) { Promise p = Promise(); on_failure(p->failure); on_success(p->success);
82356b2016-10-26Henrik Grubbström (Grubba)  call_out(p->try_failure, seconds, ({ "Timeout.\n", backtrace() }));
3bce162016-06-02Henrik Grubbström (Grubba)  return p->future(); }
18b8b22017-06-08Martin Nilsson  protected string _sprintf(int t) { return t=='O' && sprintf("%O(%s,%O)", this_program, ([ STATE_PENDING : "pending", STATE_REJECTED : "rejected", STATE_FULFILLED : "fulfilled" ])[state], result); }
9654f72016-04-12Henrik Grubbström (Grubba) }
d0704d2017-11-27Martin Nilsson class AggregateState {
5845562017-11-26Stephen R. van den Berg  private Promise promise;
d4dd112017-11-27Stephen R. van den Berg  private int(0..) promises;
5845562017-11-26Stephen R. van den Berg  private int(0..) succeeded, failed;
d4dd112017-11-27Stephen R. van den Berg  final array(mixed) results;
2ea94f2017-11-27Stephen R. van den Berg  final int(0..) min_failures; final int(-1..) max_failures;
5845562017-11-26Stephen R. van den Berg  final mixed accumulator; final function(mixed, mixed, mixed ... : mixed) fold_fun; final array(mixed) extra;
d0704d2017-11-27Martin Nilsson  private void create(Promise p) {
5845562017-11-26Stephen R. van den Berg  if (p->_materialised || p->_materialised++) error("Cannot materialise a Promise more than once.\n"); promise = p; }
d0704d2017-11-27Martin Nilsson  final void materialise() { if (promise->_astate) {
5845562017-11-26Stephen R. van den Berg  promise->_astate = 0;
d0704d2017-11-27Martin Nilsson  if (results) {
5845562017-11-26Stephen R. van den Berg  promises = sizeof(results); array(Future) futures = results; if (fold_fun) results = 0;
d0704d2017-11-27Martin Nilsson  foreach(futures; int idx; Future f) {
5845562017-11-26Stephen R. van den Berg  f->on_failure(cb_failure, idx); f->on_success(cb_success, idx); } } } }
d0704d2017-11-27Martin Nilsson  private void fold_one(mixed val) {
5845562017-11-26Stephen R. van den Berg  mixed err = catch (accumulator = fold_fun(val, accumulator, @extra));
51fd612017-11-27Martin Nilsson  if (err && promise) promise->failure(err);
5845562017-11-26Stephen R. van den Berg  }
d0704d2017-11-27Martin Nilsson  private void fold(function(mixed:void) failsucc) {
d4dd112017-11-27Stephen R. van den Berg  failsucc(fold_fun ? accumulator : results);
ac24ac2017-11-27Stephen R. van den Berg  results = 0; // Free memory
5845562017-11-26Stephen R. van den Berg  }
d0704d2017-11-27Martin Nilsson  private void cb_failure(mixed value, int idx) {
5845562017-11-26Stephen R. van den Berg  Promise p; // Cache it, to cover a failure race
d0704d2017-11-27Martin Nilsson  if (p = promise) {
e32dd02017-11-27Stephen R. van den Berg  Thread.MutexKey key = mux->lock();
d0704d2017-11-27Martin Nilsson  do { if (!p->state) {
5845562017-11-26Stephen R. van den Berg  ++failed;
d0704d2017-11-27Martin Nilsson  if (max_failures < failed && max_failures >= 0) {
5845562017-11-26Stephen R. van den Berg  key = 0; p->try_failure(value); break; } int success = succeeded + failed == promises; key = 0; if (results) results[idx] = value; else fold_one(value);
d0704d2017-11-27Martin Nilsson  if (success) {
2ea94f2017-11-27Stephen R. van den Berg  fold(failed >= min_failures ? p->success : p->failure);
5845562017-11-26Stephen R. van den Berg  break; }
d0704d2017-11-27Martin Nilsson  }
5845562017-11-26Stephen R. van den Berg  return; } while (0);
ac24ac2017-11-27Stephen R. van den Berg  promise = 0; // Free backreference
5845562017-11-26Stephen R. van den Berg  } }
d0704d2017-11-27Martin Nilsson  private void cb_success(mixed value, int idx) {
5845562017-11-26Stephen R. van den Berg  Promise p; // Cache it, to cover a failure race
d0704d2017-11-27Martin Nilsson  if (p = promise) {
e32dd02017-11-27Stephen R. van den Berg  Thread.MutexKey key = mux->lock();
d0704d2017-11-27Martin Nilsson  do { if (!p->state) {
5845562017-11-26Stephen R. van den Berg  ++succeeded;
d0704d2017-11-27Martin Nilsson  if (promises - min_failures < succeeded) {
5845562017-11-26Stephen R. van den Berg  key = 0; p->try_failure(value); break; } int success = succeeded + failed == promises; key = 0; if (results) results[idx] = value; else fold_one(value);
d0704d2017-11-27Martin Nilsson  if (success) {
5845562017-11-26Stephen R. van den Berg  fold(p->success); break; }
d0704d2017-11-27Martin Nilsson  }
5845562017-11-26Stephen R. van den Berg  return; } while (0);
ac24ac2017-11-27Stephen R. van den Berg  promise = 0; // Free backreference
5845562017-11-26Stephen R. van den Berg  } } }
9654f72016-04-12Henrik Grubbström (Grubba) //! Promise to provide a @[Future] value. //!
c60ad22016-04-13Henrik Grubbström (Grubba) //! Objects of this class are typically kept internal to the //! code that provides the @[Future] value. The only thing //! that is directly returned to the user is the return //! value from @[future()]. //!
9654f72016-04-12Henrik Grubbström (Grubba) //! @seealso
c60ad22016-04-13Henrik Grubbström (Grubba) //! @[Future], @[future()]
9654f72016-04-12Henrik Grubbström (Grubba) class Promise { inherit Future;
5845562017-11-26Stephen R. van den Berg  final int _materialised;
d0704d2017-11-27Martin Nilsson  final AggregateState _astate;
d15f0c2017-11-24Stephen R. van den Berg 
dbf05a2016-12-03Stephen R. van den Berg  //! Creates a new promise, optionally initialised from a traditional callback //! driven method via @expr{executor(resolve, reject, extra ... )@}. //! //! @seealso //! @url{https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise@} protected void create(void| function(function(mixed:void),
d0704d2017-11-27Martin Nilsson  function(mixed:void), mixed ...:void) executor, mixed ... extra) {
dbf05a2016-12-03Stephen R. van den Berg  if (executor) executor(success, failure, @extra); }
d0704d2017-11-27Martin Nilsson  Future on_success(function(mixed, mixed ... : void) cb, mixed ... extra) { if (_astate)
0831fe2017-11-28Stephen R. van den Berg  _astate->materialise();
5845562017-11-26Stephen R. van den Berg  return ::on_success(cb, @extra); }
d0704d2017-11-27Martin Nilsson  Future on_failure(function(mixed, mixed ... : void) cb, mixed ... extra) { if (_astate)
0831fe2017-11-28Stephen R. van den Berg  _astate->materialise();
5845562017-11-26Stephen R. van den Berg  return ::on_failure(cb, @extra); }
d0704d2017-11-27Martin Nilsson  mixed get() { if (_astate)
0831fe2017-11-28Stephen R. van den Berg  _astate->materialise();
5845562017-11-26Stephen R. van den Berg  return ::get(); }
9654f72016-04-12Henrik Grubbström (Grubba)  //! The future value that we promise. Future future() { return Future::this; }
4ad02b2017-11-27Stephen R. van den Berg  protected this_program finalise(State newstate, mixed value, int try, array(array(function(mixed, mixed ...: void)|array(mixed))) cbs,
d0704d2017-11-27Martin Nilsson  void|function(mixed : void) globalfailure) {
4ad02b2017-11-27Stephen R. van den Berg  Thread.MutexKey key = mux->lock();
d0704d2017-11-27Martin Nilsson  if (!state) {
4ad02b2017-11-27Stephen R. van den Berg  state = newstate;
9654f72016-04-12Henrik Grubbström (Grubba)  result = value;
4ad02b2017-11-27Stephen R. van den Berg  key = 0;
9654f72016-04-12Henrik Grubbström (Grubba)  cond->broadcast();
d0704d2017-11-27Martin Nilsson  if (sizeof(cbs)) {
4ad02b2017-11-27Stephen R. van den Berg  foreach(cbs; ; array cb) if (cb)
76c6142017-11-28Stephen R. van den Berg  callout(cb[0], 0, value, @cb[1..]);
d0704d2017-11-27Martin Nilsson  } else if (globalfailure)
76c6142017-11-28Stephen R. van den Berg  callout(globalfailure, 0, value);
595ce02017-12-01Stephen R. van den Berg  failure_cbs = success_cbs = 0; // Free memory and references
d0704d2017-11-27Martin Nilsson  } else {
4ad02b2017-11-27Stephen R. van den Berg  key = 0; if (!try) error("Promise has already been finalised.\n");
9654f72016-04-12Henrik Grubbström (Grubba)  }
4ad02b2017-11-27Stephen R. van den Berg  return this_program::this;
9654f72016-04-12Henrik Grubbström (Grubba)  }
4ad02b2017-11-27Stephen R. van den Berg  //! @decl this_program success(mixed value) //!
bf700d2016-10-26Henrik Grubbström (Grubba)  //! Fulfill the @[Future]. //! //! @param value //! Result of the @[Future]. //!
82356b2016-10-26Henrik Grubbström (Grubba)  //! @throws //! Throws an error if the @[Future] already has been fulfilled //! or failed. //! //! Mark the @[Future] as fulfilled, and schedule the @[on_success()] //! callbacks to be called as soon as possible.
bf700d2016-10-26Henrik Grubbström (Grubba)  //! //! @seealso
82356b2016-10-26Henrik Grubbström (Grubba)  //! @[try_success()], @[try_failure()], @[failure()], @[on_success()]
4ad02b2017-11-27Stephen R. van den Berg  this_program success(mixed value, void|int try)
9654f72016-04-12Henrik Grubbström (Grubba)  {
4ad02b2017-11-27Stephen R. van den Berg  return finalise(STATE_FULFILLED, value, try, success_cbs);
82356b2016-10-26Henrik Grubbström (Grubba)  } //! Fulfill the @[Future] if it hasn't been fulfilled or failed already. //! //! @param value //! Result of the @[Future]. //! //! Mark the @[Future] as fulfilled if it hasn't already been fulfilled //! or failed, and in that case schedule the @[on_success()] callbacks //! to be called as soon as possible. //! //! @seealso //! @[success()], @[try_failure()], @[failure()], @[on_success()]
4ad02b2017-11-27Stephen R. van den Berg  inline this_program try_success(mixed value)
82356b2016-10-26Henrik Grubbström (Grubba)  {
4ad02b2017-11-27Stephen R. van den Berg  return state ? this_program::this : success(value, 1);
9654f72016-04-12Henrik Grubbström (Grubba)  }
4ad02b2017-11-27Stephen R. van den Berg  //! @decl this_program failure(mixed value) //!
dd2f1a2016-05-31Henrik Grubbström (Grubba)  //! Reject the @[Future] value.
bf700d2016-10-26Henrik Grubbström (Grubba)  //! //! @param value //! Failure result of the @[Future]. //!
82356b2016-10-26Henrik Grubbström (Grubba)  //! @throws //! Throws an error if the @[Future] already has been fulfilled //! or failed. //!
bf700d2016-10-26Henrik Grubbström (Grubba)  //! Mark the @[Future] as failed, and schedule the @[on_failure()] //! callbacks to be called as soon as possible. //! //! @seealso
82356b2016-10-26Henrik Grubbström (Grubba)  //! @[try_failure()], @[success()], @[on_failure()]
4ad02b2017-11-27Stephen R. van den Berg  this_program failure(mixed value, void|int try)
dd2f1a2016-05-31Henrik Grubbström (Grubba)  {
4ad02b2017-11-27Stephen R. van den Berg  return finalise(STATE_REJECTED, value, try, failure_cbs, global_on_failure);
dd2f1a2016-05-31Henrik Grubbström (Grubba)  }
bf700d2016-10-26Henrik Grubbström (Grubba)  //! Maybe reject the @[Future] value. //! //! @param value //! Failure result of the @[Future]. //! //! Mark the @[Future] as failed if it hasn't already been fulfilled,
82356b2016-10-26Henrik Grubbström (Grubba)  //! and in that case schedule the @[on_failure()] callbacks to be //! called as soon as possible.
bf700d2016-10-26Henrik Grubbström (Grubba)  //! //! @seealso //! @[failure()], @[success()], @[on_failure()]
4ad02b2017-11-27Stephen R. van den Berg  inline this_program try_failure(mixed value)
126bb32016-06-01Henrik Grubbström (Grubba)  {
4ad02b2017-11-27Stephen R. van den Berg  return state ? this_program::this : failure(value, 1);
126bb32016-06-01Henrik Grubbström (Grubba)  }
d0704d2017-11-27Martin Nilsson  inline private void fill_astate() {
5845562017-11-26Stephen R. van den Berg  if (!_astate)
d0704d2017-11-27Martin Nilsson  _astate = AggregateState(this);
5845562017-11-26Stephen R. van den Berg  }
2ea94f2017-11-27Stephen R. van den Berg  //! Add futures to the list of futures which the current object depends upon.
d15f0c2017-11-24Stephen R. van den Berg  //! //! If called without arguments it will produce a new @[Future] //! from a new @[Promise] which is implictly added to the dependency list.
0d613e2017-11-23Stephen R. van den Berg  //! //! @param futures
e32dd02017-11-27Stephen R. van den Berg  //! The list of @expr{futures@} we want to add to the list we depend upon.
0d613e2017-11-23Stephen R. van den Berg  //!
d15f0c2017-11-24Stephen R. van den Berg  //! @returns //! The new @[Promise]. //!
9379002017-11-27Stephen R. van den Berg  //! @note //! Can be called multiple times to add more. //! //! @note //! Once the promise has been materialised (when either @[on_success()], //! @[on_failure()] or @[get()] has been called on this object), it is //! not possible to call @[depend()] anymore. //!
0d613e2017-11-23Stephen R. van den Berg  //! @seealso
2ea94f2017-11-27Stephen R. van den Berg  //! @[fold()], @[first_completed()], @[max_failures()], @[min_failures()],
5845562017-11-26Stephen R. van den Berg  //! @[any_results()], @[Concurrent.results()], @[Concurrent.all()]
d15f0c2017-11-24Stephen R. van den Berg  this_program depend(array(Future) futures)
4d37ce2017-11-22Stephen R. van den Berg  {
d15f0c2017-11-24Stephen R. van den Berg  if (sizeof(futures)) {
5845562017-11-26Stephen R. van den Berg  fill_astate(); _astate->results += futures;
4d37ce2017-11-22Stephen R. van den Berg  }
079bac2017-11-25Stephen R. van den Berg  return this_program::this;
4d37ce2017-11-22Stephen R. van den Berg  }
d15f0c2017-11-24Stephen R. van den Berg  inline variant this_program depend(Future ... futures)
4d37ce2017-11-22Stephen R. van den Berg  { return depend(futures); }
d15f0c2017-11-24Stephen R. van den Berg  variant this_program depend() { Promise p = Promise(); depend(p->future()); return p; }
4d37ce2017-11-22Stephen R. van den Berg 
0d613e2017-11-23Stephen R. van den Berg  //! @param initial //! Initial value of the accumulator. //! //! @param fun //! Function to apply. The first argument is the result of
d15f0c2017-11-24Stephen R. van den Berg  //! one of the @[futures]. The second argument is the current value //! of the accumulator. //! //! @param extra //! Any extra context needed for @[fun]. They will be provided //! as arguments three and onwards when @[fun] is called. //! //! @returns //! The new @[Promise].
0d613e2017-11-23Stephen R. van den Berg  //! //! @note //! If @[fun] throws an error it will fail the @[Future]. //! //! @note //! @[fun] may be called in any order, and will be called
2ea94f2017-11-27Stephen R. van den Berg  //! once for every @[Future] it depends upon, unless one of the
0d613e2017-11-23Stephen R. van den Berg  //! calls fails in which case no further calls will be //! performed. //! //! @seealso
5845562017-11-26Stephen R. van den Berg  //! @[depend()], @[Concurrent.fold()] this_program fold(mixed initial, function(mixed, mixed, mixed ... : mixed) fun, mixed ... extra) { if (_astate) { _astate->accumulator = initial; _astate->fold_fun = fun; _astate->extra = extra; _astate->materialise(); } else
4d37ce2017-11-22Stephen R. van den Berg  success(initial);
5845562017-11-26Stephen R. van den Berg  return this_program::this; }
4d37ce2017-11-22Stephen R. van den Berg 
5845562017-11-26Stephen R. van den Berg  //! It evaluates to the first future that completes of the list
2ea94f2017-11-27Stephen R. van den Berg  //! of futures it depends upon.
5845562017-11-26Stephen R. van den Berg  //! //! @returns //! The new @[Promise]. //! //! @seealso //! @[depend()], @[Concurrent.first_completed()] this_program first_completed() { if (_astate) { _astate->results->on_failure(try_failure); _astate->results->on_success(try_success); _astate = 0; } else success(0); return this_program::this; }
4d37ce2017-11-22Stephen R. van den Berg 
5845562017-11-26Stephen R. van den Berg  //! @param max //! Specifies the maximum number of failures to be accepted in
d4eb912017-11-28Stephen R. van den Berg  //! the list of futures this promise depends upon. //! //! @expr{-1@} means unlimited. //! //! Defaults to @expr{0@}.
5845562017-11-26Stephen R. van den Berg  //! //! @returns //! The new @[Promise]. //! //! @seealso
2ea94f2017-11-27Stephen R. van den Berg  //! @[depend()], @[min_failures()], @[any_results()] this_program max_failures(int(-1..) max)
5845562017-11-26Stephen R. van den Berg  { fill_astate();
2ea94f2017-11-27Stephen R. van den Berg  _astate->max_failures = max;
5845562017-11-26Stephen R. van den Berg  return this_program::this; }
4d37ce2017-11-22Stephen R. van den Berg 
5845562017-11-26Stephen R. van den Berg  //! @param min //! Specifies the minimum number of failures to be required in //! the list of futures this promise depends upon. Defaults //! to @expr{0@}. //! //! @returns //! The new @[Promise]. //! //! @seealso
2ea94f2017-11-27Stephen R. van den Berg  //! @[depend()], @[max_failures()] this_program min_failures(int(0..) min)
5845562017-11-26Stephen R. van den Berg  { fill_astate();
2ea94f2017-11-27Stephen R. van den Berg  _astate->min_failures = min;
079bac2017-11-25Stephen R. van den Berg  return this_program::this;
4d37ce2017-11-22Stephen R. van den Berg  }
5845562017-11-26Stephen R. van den Berg  //! Sets the number of failures to be accepted in the list of futures //! this promise
2ea94f2017-11-27Stephen R. van den Berg  //! depends upon to unlimited. It is equivalent to @expr{max_failures(-1)@}.
5845562017-11-26Stephen R. van den Berg  //! //! @returns //! The new @[Promise]. //! //! @seealso
2ea94f2017-11-27Stephen R. van den Berg  //! @[depend()], @[max_failures()]
5845562017-11-26Stephen R. van den Berg  this_program any_results()
4d37ce2017-11-22Stephen R. van den Berg  {
2ea94f2017-11-27Stephen R. van den Berg  return max_failures(-1);
4d37ce2017-11-22Stephen R. van den Berg  }
c071bc2017-11-05Henrik Grubbström (Grubba)  protected void _destruct()
9654f72016-04-12Henrik Grubbström (Grubba)  {
4ad02b2017-11-27Stephen R. van den Berg  if (!state) try_failure(({ "Promise broken.\n", backtrace() }));
9654f72016-04-12Henrik Grubbström (Grubba)  } }
aa51262016-04-18Henrik Grubbström (Grubba) 
6b01882016-11-09Stephen R. van den Berg //! @returns //! A @[Future] that represents the first //! of the @expr{futures@} that completes. //! //! @seealso
5845562017-11-26Stephen R. van den Berg //! @[race()], @[Promise.first_completed()]
1d407b2016-11-18Stephen R. van den Berg variant Future first_completed(array(Future) futures)
aa51262016-04-18Henrik Grubbström (Grubba) {
5845562017-11-26Stephen R. van den Berg  return Promise()->depend(futures)->first_completed()->future();
aa51262016-04-18Henrik Grubbström (Grubba) }
1d407b2016-11-18Stephen R. van den Berg variant inline Future first_completed(Future ... futures) { return first_completed(futures); }
aa51262016-04-18Henrik Grubbström (Grubba) 
6e27292016-11-18Stephen R. van den Berg //! JavaScript Promise API equivalent of @[first_completed()].
6b01882016-11-09Stephen R. van den Berg //! //! @seealso
5845562017-11-26Stephen R. van den Berg //! @[first_completed()], @[Promise.first_completed()]
6b01882016-11-09Stephen R. van den Berg //! @url{https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise@}
1d407b2016-11-18Stephen R. van den Berg variant inline Future race(array(Future) futures) { return first_completed(futures); } variant inline Future race(Future ... futures)
6b01882016-11-09Stephen R. van den Berg { return first_completed(futures); } //! @returns //! A @[Future] that represents the array of all the completed @expr{futures@}. //! //! @seealso
5845562017-11-26Stephen R. van den Berg //! @[all()], @[Promise.depend()]
1d407b2016-11-18Stephen R. van den Berg variant Future results(array(Future) futures)
aa51262016-04-18Henrik Grubbström (Grubba) {
e32dd02017-11-27Stephen R. van den Berg  return Promise()->depend(futures)->future();
aa51262016-04-18Henrik Grubbström (Grubba) }
1d407b2016-11-18Stephen R. van den Berg inline variant Future results(Future ... futures) { return results(futures); }
aa51262016-04-18Henrik Grubbström (Grubba) 
6b01882016-11-09Stephen R. van den Berg //! JavaScript Promise API equivalent of @[results()]. //! //! @seealso
5845562017-11-26Stephen R. van den Berg //! @[results()], @[Promise.depend()]
6b01882016-11-09Stephen R. van den Berg //! @url{https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise@}
6e27292016-11-18Stephen R. van den Berg inline variant Future all(array(Future) futures) { return results(futures); } inline variant Future all(Future ... futures)
6b01882016-11-09Stephen R. van den Berg { return results(futures); } //! @returns //! A new @[Future] that has already failed for the specified @expr{reason@}. //! //! @seealso //! @[Future.on_failure()], @[Promise.failure()] //! @url{https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise@} Future reject(mixed reason) {
e32dd02017-11-27Stephen R. van den Berg  return Promise()->failure(reason)->future();
6b01882016-11-09Stephen R. van den Berg } //! @returns //! A new @[Future] that has already been fulfilled with @expr{value@} //! as result. If @expr{value@} is an object which already
6e27292016-11-18Stephen R. van den Berg //! has @[on_failure] and @[on_success] methods, return it unchanged.
6b01882016-11-09Stephen R. van den Berg //! //! @note //! This function can be used to ensure values are futures. //! //! @seealso //! @[Future.on_success()], @[Promise.success()] //! @url{https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise@} Future resolve(mixed value) {
ae447a2017-11-27Martin Nilsson  if (objectp(value) && value->on_failure && value->on_success) return value; return Promise()->success(value)->future();
6b01882016-11-09Stephen R. van den Berg }
aa51262016-04-18Henrik Grubbström (Grubba) //! Return a @[Future] that represents the array of mapping @[fun]
6b01882016-11-09Stephen R. van den Berg //! over the results of the completed @[futures].
aa51262016-04-18Henrik Grubbström (Grubba) Future traverse(array(Future) futures, function(mixed, mixed ... : mixed) fun, mixed ... extra) { return results(futures->map(fun, @extra)); } //! Return a @[Future] that represents the accumulated results of //! applying @[fun] to the results of the @[futures] in turn. //! //! @param initial //! Initial value of the accumulator. //! //! @param fun //! Function to apply. The first argument is the result of //! one of the @[futures], the second the current accumulated //! value, and any further from @[extra]. //! //! @note
8e14552016-10-26Henrik Grubbström (Grubba) //! If @[fun] throws an error it will fail the @[Future]. //! //! @note //! @[fun] may be called in any order, and will be called //! once for every @[Future] in @[futures], unless one of //! calls fails in which case no further calls will be //! performed.
aa51262016-04-18Henrik Grubbström (Grubba) Future fold(array(Future) futures, mixed initial, function(mixed, mixed, mixed ... : mixed) fun, mixed ... extra) {
e32dd02017-11-27Stephen R. van den Berg  return Promise()->depend(futures)->fold(initial, fun, extra)->future();
aa51262016-04-18Henrik Grubbström (Grubba) }