// Copyright 2011 Software Freedom Conservancy. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @license Portions of this code are from the Dojo toolkit, received under the * BSD License: * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Dojo Foundation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview A promise implementation based on the CommonJS promise/A and * promise/B proposals. For more information, see * http://wiki.commonjs.org/wiki/Promises. */ goog.provide('webdriver.promise'); goog.provide('webdriver.promise.ControlFlow'); goog.provide('webdriver.promise.ControlFlow.Timer'); goog.provide('webdriver.promise.Deferred'); goog.provide('webdriver.promise.Promise'); goog.require('goog.array'); goog.require('goog.debug.Error'); goog.require('goog.object'); goog.require('webdriver.EventEmitter'); goog.require('webdriver.stacktrace.Snapshot'); /** * Represents the eventual value of a completed operation. Each promise may be * in one of three states: pending, resolved, or rejected. Each promise starts * in the pending state and may make a single transition to either a * fulfilled or failed state. * *
This class is based on the Promise/A proposal from CommonJS. Additional * functions are provided for API compatibility with Dojo Deferred objects. * * @constructor * @template T * @see http://wiki.commonjs.org/wiki/Promises/A */ webdriver.promise.Promise = function() { }; /** * Cancels the computation of this promise's value, rejecting the promise in the * process. * @param {*} reason The reason this promise is being cancelled. If not an * {@code Error}, one will be created using the value's string * representation. */ webdriver.promise.Promise.prototype.cancel = function(reason) { throw new TypeError('Unimplemented function: "cancel"'); }; /** @return {boolean} Whether this promise's value is still being computed. */ webdriver.promise.Promise.prototype.isPending = function() { throw new TypeError('Unimplemented function: "isPending"'); }; /** * Registers listeners for when this instance is resolved. This function most * overridden by subtypes. * * @param {?(function(T): (R|webdriver.promise.Promise.
* // Synchronous API:
* try {
* doSynchronousWork();
* } catch (ex) {
* console.error(ex);
* }
*
* // Asynchronous promise API:
* doAsynchronousWork().thenCatch(function(ex) {
* console.error(ex);
* });
*
*
* @param {function(*): (R|webdriver.promise.Promise.
* // Synchronous API:
* try {
* doSynchronousWork();
* } finally {
* cleanUp();
* }
*
* // Asynchronous promise API:
* doAsynchronousWork().thenFinally(cleanUp);
*
*
* Note: similar to the {@code finally} clause, if the registered
* callback returns a rejected promise or throws an error, it will silently
* replace the rejection error (if any) from this promise:
*
* try {
* throw Error('one');
* } finally {
* throw Error('two'); // Hides Error: one
* }
*
* webdriver.promise.rejected(Error('one'))
* .thenFinally(function() {
* throw Error('two'); // Hides Error: one
* });
*
*
*
* @param {function(): (R|webdriver.promise.Promise.If this Deferred is rejected and there are no listeners registered before * the next turn of the event loop, the rejection will be passed to the * {@link webdriver.promise.ControlFlow} as an unhandled failure. * *
If this Deferred is cancelled, the cancellation reason will be forward to
* the Deferred's canceller function (if provided). The canceller may return a
* truth-y value to override the reason provided for rejection.
*
* @param {Function=} opt_canceller Function to call when cancelling the
* computation of this instance's value.
* @param {webdriver.promise.ControlFlow=} opt_flow The control flow
* this instance was created under. This should only be provided during
* unit tests.
* @constructor
* @extends {webdriver.promise.Promise. If the return value of the mapping function is a promise, this function
* will wait for it to be fulfilled before inserting it into the new array.
*
* If the mapping function throws or returns a rejected promise, the
* promise returned by this function will be rejected with the same reason.
* Only the first failure will be reported; all subsequent errors will be
* silently ignored.
*
* @param {!(Array. If the return value of the filter function is a promise, this function
* will wait for it to be fulfilled before determining whether to insert the
* element into the new array.
*
* If the filter function throws or returns a rejected promise, the promise
* returned by this function will be rejected with the same reason. Only the
* first failure will be reported; all subsequent errors will be silently
* ignored.
*
* @param {!(Array. Each task scheduled within this flow may return a
* {@link webdriver.promise.Promise} to indicate it is an asynchronous
* operation. The ControlFlow will wait for such promises to be resolved before
* marking the task as completed.
*
* Tasks and each callback registered on a {@link webdriver.promise.Deferred}
* will be run in their own ControlFlow frame. Any tasks scheduled within a
* frame will have priority over previously scheduled tasks. Furthermore, if
* any of the tasks in the frame fails, the remainder of the tasks in that frame
* will be discarded and the failure will be propagated to the user through the
* callback/task's promised result.
*
* Each time a ControlFlow empties its task queue, it will fire an
* {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Conversely,
* whenever the flow terminates due to an unhandled error, it will remove all
* remaining tasks in its queue and fire an
* {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION} event. If
* there are no listeners registered with the flow, the error will be
* rethrown to the global error handler.
*
* @param {webdriver.promise.ControlFlow.Timer=} opt_timer The timer object
* to use. Should only be set for testing.
* @constructor
* @extends {webdriver.EventEmitter}
*/
webdriver.promise.ControlFlow = function(opt_timer) {
webdriver.EventEmitter.call(this);
/**
* The timer used by this instance.
* @type {webdriver.promise.ControlFlow.Timer}
*/
this.timer = opt_timer || webdriver.promise.ControlFlow.defaultTimer;
/**
* A list of recent tasks. Each time a new task is started, or a frame is
* completed, the previously recorded task is removed from this list. If
* there are multiple tasks, task N+1 is considered a sub-task of task
* N.
* @private {!Array.}
*/
this.history_ = [];
};
goog.inherits(webdriver.promise.ControlFlow, webdriver.EventEmitter);
/**
* @typedef {{clearInterval: function(number),
* clearTimeout: function(number),
* setInterval: function(!Function, number): number,
* setTimeout: function(!Function, number): number}}
*/
webdriver.promise.ControlFlow.Timer;
/**
* The default timer object, which uses the global timer functions.
* @type {webdriver.promise.ControlFlow.Timer}
*/
webdriver.promise.ControlFlow.defaultTimer = (function() {
// The default timer functions may be defined as free variables for the
// current context, so do not reference them using "window" or
// "goog.global". Also, we must invoke them in a closure, and not using
// bind(), so we do not get "TypeError: Illegal invocation" (WebKit) or
// "Invalid calling object" (IE) errors.
return {
clearInterval: wrap(clearInterval),
clearTimeout: wrap(clearTimeout),
setInterval: wrap(setInterval),
setTimeout: wrap(setTimeout)
};
function wrap(fn) {
return function() {
// Cannot use .call() or .apply() since we do not know which variable
// the function is bound to, and using the wrong one will generate
// an error.
return fn(arguments[0], arguments[1]);
};
}
})();
/**
* Events that may be emitted by an {@link webdriver.promise.ControlFlow}.
* @enum {string}
*/
webdriver.promise.ControlFlow.EventType = {
/** Emitted when all tasks have been successfully executed. */
IDLE: 'idle',
/** Emitted whenever a new task has been scheduled. */
SCHEDULE_TASK: 'scheduleTask',
/**
* Emitted whenever a control flow aborts due to an unhandled promise
* rejection. This event will be emitted along with the offending rejection
* reason. Upon emitting this event, the control flow will empty its task
* queue and revert to its initial state.
*/
UNCAUGHT_EXCEPTION: 'uncaughtException'
};
/**
* How often, in milliseconds, the event loop should run.
* @type {number}
* @const
*/
webdriver.promise.ControlFlow.EVENT_LOOP_FREQUENCY = 10;
/**
* Tracks the active execution frame for this instance. Lazily initialized
* when the first task is scheduled.
* @private {webdriver.promise.Frame_}
*/
webdriver.promise.ControlFlow.prototype.activeFrame_ = null;
/**
* A reference to the frame in which new tasks should be scheduled. If
* {@code null}, tasks will be scheduled within the active frame. When forcing
* a function to run in the context of a new frame, this pointer is used to
* ensure tasks are scheduled within the newly created frame, even though it
* won't be active yet.
* @private {webdriver.promise.Frame_}
* @see {#runInNewFrame_}
*/
webdriver.promise.ControlFlow.prototype.schedulingFrame_ = null;
/**
* Timeout ID set when the flow is about to shutdown without any errors
* being detected. Upon shutting down, the flow will emit an
* {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Idle events
* always follow a brief timeout in order to catch latent errors from the last
* completed task. If this task had a callback registered, but no errback, and
* the task fails, the unhandled failure would not be reported by the promise
* system until the next turn of the event loop:
*
* // Schedule 1 task that fails.
* var result = webriver.promise.controlFlow().schedule('example',
* function() { return webdriver.promise.rejected('failed'); });
* // Set a callback on the result. This delays reporting the unhandled
* // failure for 1 turn of the event loop.
* result.then(goog.nullFunction);
*
* @private {?number}
*/
webdriver.promise.ControlFlow.prototype.shutdownId_ = null;
/**
* Interval ID for this instance's event loop.
* @private {?number}
*/
webdriver.promise.ControlFlow.prototype.eventLoopId_ = null;
/**
* The number of "pending" promise rejections.
*
* Each time a promise is rejected and is not handled by a listener, it will
* schedule a 0-based timeout to check if it is still unrejected in the next
* turn of the JS-event loop. This allows listeners to attach to, and handle,
* the rejected promise at any point in same turn of the event loop that the
* promise was rejected.
*
* When this flow's own event loop triggers, it will not run if there
* are any outstanding promise rejections. This allows unhandled promises to
* be reported before a new task is started, ensuring the error is reported to
* the current task queue.
*
* @private {number}
*/
webdriver.promise.ControlFlow.prototype.pendingRejections_ = 0;
/**
* The number of aborted frames since the last time a task was executed or a
* frame completed successfully.
* @private {number}
*/
webdriver.promise.ControlFlow.prototype.numAbortedFrames_ = 0;
/**
* Resets this instance, clearing its queue and removing all event listeners.
*/
webdriver.promise.ControlFlow.prototype.reset = function() {
this.activeFrame_ = null;
this.clearHistory();
this.removeAllListeners();
this.cancelShutdown_();
this.cancelEventLoop_();
};
/**
* Returns a summary of the recent task activity for this instance. This
* includes the most recently completed task, as well as any parent tasks. In
* the returned summary, the task at index N is considered a sub-task of the
* task at index N+1.
* @return {!Array. Condition functions may schedule sub-tasks with this instance, however,
* their execution time will be factored into whether a wait has timed out.
*
* In the event a condition returns a Promise, the polling loop will wait for
* it to be resolved before evaluating whether the condition has been satisfied.
* The resolution time for a promise is factored into whether a wait has timed
* out.
*
* If the condition function throws, or returns a rejected promise, the
* wait task will fail.
*
* @param {!Function} condition The condition function to poll.
* @param {number} timeout How long to wait, in milliseconds, for the condition
* to hold before timing out.
* @param {string=} opt_message An optional error message to include if the
* wait times out; defaults to the empty string.
* @return {!webdriver.promise.Promise} A promise that will be resolved when the
* condition has been satisified. The promise shall be rejected if the wait
* times out waiting for the condition.
*/
webdriver.promise.ControlFlow.prototype.wait = function(
condition, timeout, opt_message) {
var sleep = Math.min(timeout, 100);
var self = this;
return this.execute(function() {
var startTime = goog.now();
var waitResult = new webdriver.promise.Deferred();
var waitFrame = self.activeFrame_;
waitFrame.isWaiting = true;
pollCondition();
return waitResult.promise;
function pollCondition() {
self.runInNewFrame_(condition, function(value) {
var elapsed = goog.now() - startTime;
if (!!value) {
waitFrame.isWaiting = false;
waitResult.fulfill(value);
} else if (elapsed >= timeout) {
waitResult.reject(new Error((opt_message ? opt_message + '\n' : '') +
'Wait timed out after ' + elapsed + 'ms'));
} else {
self.timer.setTimeout(pollCondition, sleep);
}
}, waitResult.reject, true);
}
}, opt_message);
};
/**
* Schedules a task that will wait for another promise to resolve. The resolved
* promise's value will be returned as the task result.
* @param {!webdriver.promise.Promise} promise The promise to wait on.
* @return {!webdriver.promise.Promise} A promise that will resolve when the
* task has completed.
*/
webdriver.promise.ControlFlow.prototype.await = function(promise) {
return this.execute(function() {
return promise;
});
};
/**
* Schedules the interval for this instance's event loop, if necessary.
* @private
*/
webdriver.promise.ControlFlow.prototype.scheduleEventLoopStart_ = function() {
if (!this.eventLoopId_) {
this.eventLoopId_ = this.timer.setInterval(
goog.bind(this.runEventLoop_, this),
webdriver.promise.ControlFlow.EVENT_LOOP_FREQUENCY);
}
};
/**
* Cancels the event loop, if necessary.
* @private
*/
webdriver.promise.ControlFlow.prototype.cancelEventLoop_ = function() {
if (this.eventLoopId_) {
this.timer.clearInterval(this.eventLoopId_);
this.eventLoopId_ = null;
}
};
/**
* Executes the next task for the current frame. If the current frame has no
* more tasks, the frame's result will be resolved, returning control to the
* frame's creator. This will terminate the flow if the completed frame was at
* the top of the stack.
* @private
*/
webdriver.promise.ControlFlow.prototype.runEventLoop_ = function() {
// If we get here and there are pending promise rejections, then those
// promises are queued up to run as soon as this (JS) event loop terminates.
// Short-circuit our loop to give those promises a chance to run. Otherwise,
// we might start a new task only to have it fail because of one of these
// pending rejections.
if (this.pendingRejections_) {
return;
}
// If the flow aborts due to an unhandled exception after we've scheduled
// another turn of the execution loop, we can end up in here with no tasks
// left. This is OK, just quietly return.
if (!this.activeFrame_) {
this.commenceShutdown_();
return;
}
var task;
if (this.activeFrame_.getPendingTask() || !(task = this.getNextTask_())) {
// Either the current frame is blocked on a pending task, or we don't have
// a task to finish because we've completed a frame. When completing a
// frame, we must abort the event loop to allow the frame's promise's
// callbacks to execute.
return;
}
var activeFrame = this.activeFrame_;
activeFrame.setPendingTask(task);
var markTaskComplete = goog.bind(function() {
this.history_.push(/** @type {!webdriver.promise.Task_} */ (task));
activeFrame.setPendingTask(null);
}, this);
this.trimHistory_();
var self = this;
this.runInNewFrame_(task.execute, function(result) {
markTaskComplete();
task.fulfill(result);
}, function(error) {
markTaskComplete();
if (!webdriver.promise.isError_(error) &&
!webdriver.promise.isPromise(error)) {
error = Error(error);
}
task.reject(self.annotateError(/** @type {!Error} */ (error)));
}, true);
};
/**
* @return {webdriver.promise.Task_} The next task to execute, or
* {@code null} if a frame was resolved.
* @private
*/
webdriver.promise.ControlFlow.prototype.getNextTask_ = function() {
var firstChild = this.activeFrame_.getFirstChild();
if (!firstChild) {
if (!this.activeFrame_.isWaiting) {
this.resolveFrame_(this.activeFrame_);
}
return null;
}
if (firstChild instanceof webdriver.promise.Frame_) {
this.activeFrame_ = firstChild;
return this.getNextTask_();
}
firstChild.getParent().removeChild(firstChild);
return firstChild;
};
/**
* @param {!webdriver.promise.Frame_} frame The frame to resolve.
* @private
*/
webdriver.promise.ControlFlow.prototype.resolveFrame_ = function(frame) {
if (this.activeFrame_ === frame) {
// Frame parent is always another frame, but the compiler is not smart
// enough to recognize this.
this.activeFrame_ =
/** @type {webdriver.promise.Frame_} */ (frame.getParent());
}
if (frame.getParent()) {
frame.getParent().removeChild(frame);
}
this.trimHistory_();
frame.fulfill();
if (!this.activeFrame_) {
this.commenceShutdown_();
}
};
/**
* Aborts the current frame. The frame, and all of the tasks scheduled within it
* will be discarded. If this instance does not have an active frame, it will
* immediately terminate all execution.
* @param {*} error The reason the frame is being aborted; typically either
* an Error or string.
* @private
*/
webdriver.promise.ControlFlow.prototype.abortFrame_ = function(error) {
// Annotate the error value if it is Error-like.
if (webdriver.promise.isError_(error)) {
this.annotateError(/** @type {!Error} */ (error));
}
this.numAbortedFrames_++;
if (!this.activeFrame_) {
this.abortNow_(error);
return;
}
// Frame parent is always another frame, but the compiler is not smart
// enough to recognize this.
var parent = /** @type {webdriver.promise.Frame_} */ (
this.activeFrame_.getParent());
if (parent) {
parent.removeChild(this.activeFrame_);
}
var frame = this.activeFrame_;
this.activeFrame_ = parent;
frame.reject(error);
};
/**
* Executes a function in a new frame. If the function does not schedule any new
* tasks, the frame will be discarded and the function's result returned
* immediately. Otherwise, a promise will be returned. This promise will be
* resolved with the function's result once all of the tasks scheduled within
* the function have been completed. If the function's frame is aborted, the
* returned promise will be rejected.
*
* @param {!Function} fn The function to execute.
* @param {function(*)} callback The function to call with a successful result.
* @param {function(*)} errback The function to call if there is an error.
* @param {boolean=} opt_activate Whether the active frame should be updated to
* the newly created frame so tasks are treated as sub-tasks.
* @private
*/
webdriver.promise.ControlFlow.prototype.runInNewFrame_ = function(
fn, callback, errback, opt_activate) {
var newFrame = new webdriver.promise.Frame_(this),
self = this,
oldFrame = this.activeFrame_;
try {
if (!this.activeFrame_) {
this.activeFrame_ = newFrame;
} else {
this.activeFrame_.addChild(newFrame);
}
// Activate the new frame to force tasks to be treated as sub-tasks of
// the parent frame.
if (opt_activate) {
this.activeFrame_ = newFrame;
}
try {
this.schedulingFrame_ = newFrame;
webdriver.promise.pushFlow_(this);
var result = fn();
} finally {
webdriver.promise.popFlow_();
this.schedulingFrame_ = null;
}
newFrame.lockFrame();
// If there was nothing scheduled in the new frame we can discard the
// frame and return immediately.
if (!newFrame.children_.length) {
removeNewFrame();
webdriver.promise.asap(result, callback, errback);
return;
}
newFrame.then(function() {
webdriver.promise.asap(result, callback, errback);
}, function(e) {
if (result instanceof webdriver.promise.Promise && result.isPending()) {
result.cancel(e);
e = result;
}
errback(e);
});
} catch (ex) {
removeNewFrame(new webdriver.promise.CanceledTaskError_(ex));
errback(ex);
}
/**
* @param {webdriver.promise.CanceledTaskError_=} opt_err If provided, the
* error that triggered the removal of this frame.
*/
function removeNewFrame(opt_err) {
var parent = newFrame.getParent();
if (parent) {
parent.removeChild(newFrame);
}
if (opt_err) {
newFrame.cancelRemainingTasks(opt_err);
}
self.activeFrame_ = oldFrame;
}
};
/**
* Commences the shutdown sequence for this instance. After one turn of the
* event loop, this object will emit the
* {@link webdriver.promise.ControlFlow.EventType.IDLE} event to signal
* listeners that it has completed. During this wait, if another task is
* scheduled, the shutdown will be aborted.
* @private
*/
webdriver.promise.ControlFlow.prototype.commenceShutdown_ = function() {
if (!this.shutdownId_) {
// Go ahead and stop the event loop now. If we're in here, then there are
// no more frames with tasks to execute. If we waited to cancel the event
// loop in our timeout below, the event loop could trigger *before* the
// timeout, generating an error from there being no frames.
// If #execute is called before the timeout below fires, it will cancel
// the timeout and restart the event loop.
this.cancelEventLoop_();
var self = this;
self.shutdownId_ = self.timer.setTimeout(function() {
self.shutdownId_ = null;
self.emit(webdriver.promise.ControlFlow.EventType.IDLE);
}, 0);
}
};
/**
* Cancels the shutdown sequence if it is currently scheduled.
* @private
*/
webdriver.promise.ControlFlow.prototype.cancelShutdown_ = function() {
if (this.shutdownId_) {
this.timer.clearTimeout(this.shutdownId_);
this.shutdownId_ = null;
}
};
/**
* Aborts this flow, abandoning all remaining tasks. If there are
* listeners registered, an {@code UNCAUGHT_EXCEPTION} will be emitted with the
* offending {@code error}, otherwise, the {@code error} will be rethrown to the
* global error handler.
* @param {*} error Object describing the error that caused the flow to
* abort; usually either an Error or string value.
* @private
*/
webdriver.promise.ControlFlow.prototype.abortNow_ = function(error) {
this.activeFrame_ = null;
this.cancelShutdown_();
this.cancelEventLoop_();
var listeners = this.listeners(
webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION);
if (!listeners.length) {
this.timer.setTimeout(function() {
throw error;
}, 0);
} else {
this.emit(webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION,
error);
}
};
/**
* A single node in an {@link webdriver.promise.ControlFlow}'s task tree.
* @param {!webdriver.promise.ControlFlow} flow The flow this instance belongs
* to.
* @constructor
* @extends {webdriver.promise.Deferred}
* @private
*/
webdriver.promise.Node_ = function(flow) {
webdriver.promise.Deferred.call(this, null, flow);
};
goog.inherits(webdriver.promise.Node_, webdriver.promise.Deferred);
/**
* This node's parent.
* @private {webdriver.promise.Node_}
*/
webdriver.promise.Node_.prototype.parent_ = null;
/** @return {webdriver.promise.Node_} This node's parent. */
webdriver.promise.Node_.prototype.getParent = function() {
return this.parent_;
};
/**
* @param {webdriver.promise.Node_} parent This node's new parent.
*/
webdriver.promise.Node_.prototype.setParent = function(parent) {
this.parent_ = parent;
};
/**
* @return {!webdriver.promise.Node_} The root of this node's tree.
*/
webdriver.promise.Node_.prototype.getRoot = function() {
var root = this;
while (root.parent_) {
root = root.parent_;
}
return root;
};
/**
* An execution frame within a {@link webdriver.promise.ControlFlow}. Each
* frame represents the execution context for either a
* {@link webdriver.promise.Task_} or a callback on a
* {@link webdriver.promise.Deferred}.
*
* Each frame may contain sub-frames. If child N is a sub-frame, then the
* items queued within it are given priority over child N+1.
*
* @param {!webdriver.promise.ControlFlow} flow The flow this instance belongs
* to.
* @constructor
* @extends {webdriver.promise.Node_}
* @private
*/
webdriver.promise.Frame_ = function(flow) {
webdriver.promise.Node_.call(this, flow);
var reject = goog.bind(this.reject, this);
var cancelRemainingTasks = goog.bind(this.cancelRemainingTasks, this);
/** @override */
this.reject = function(e) {
cancelRemainingTasks(new webdriver.promise.CanceledTaskError_(e));
reject(e);
};
/**
* @private {!Array.}
*/
this.children_ = [];
};
goog.inherits(webdriver.promise.Frame_, webdriver.promise.Node_);
/**
* The task currently being executed within this frame.
* @private {webdriver.promise.Task_}
*/
webdriver.promise.Frame_.prototype.pendingTask_ = null;
/**
* Whether this frame is active. A frame is considered active once one of its
* descendants has been removed for execution.
*
* Adding a sub-frame as a child to an active frame is an indication that
* a callback to a {@link webdriver.promise.Deferred} is being invoked and any
* tasks scheduled within it should have priority over previously scheduled
* tasks:
* Once a frame becomes {@link #isActive_ active}, any new frames which are
* added represent callbacks on a {@link webdriver.promise.Deferred}, whose
* tasks must be given priority over previously scheduled tasks.
*
* @private {boolean}
*/
webdriver.promise.Frame_.prototype.isLocked_ = false;
/**
* A reference to the last node inserted in this frame.
* @private {webdriver.promise.Node_}
*/
webdriver.promise.Frame_.prototype.lastInsertedChild_ = null;
/**
* Marks all of the tasks that are descendants of this frame in the execution
* tree as cancelled. This is necessary for callbacks scheduled asynchronous.
* For example:
*
* var someResult;
* webdriver.promise.createFlow(function(flow) {
* someResult = flow.execute(function() {});
* throw Error();
* }).addErrback(function(err) {
* console.log('flow failed: ' + err);
* someResult.then(function() {
* console.log('task succeeded!');
* }, function(err) {
* console.log('task failed! ' + err);
* });
* });
* // flow failed: Error: boom
* // task failed! CanceledTaskError: Task discarded due to a previous
* // task failure: Error: boom
*
* @param {!webdriver.promise.CanceledTaskError_} error The cancellation
* error.
*/
webdriver.promise.Frame_.prototype.cancelRemainingTasks = function(error) {
goog.array.forEach(this.children_, function(child) {
if (child instanceof webdriver.promise.Frame_) {
child.cancelRemainingTasks(error);
} else {
// None of the previously registered listeners should be notified that
// the task is being canceled, however, we need at least one errback
// to prevent the cancellation from bubbling up.
child.removeAll();
child.thenCatch(goog.nullFunction);
child.cancel(error);
}
});
};
/**
* @return {webdriver.promise.Task_} The task currently executing
* within this frame, if any.
*/
webdriver.promise.Frame_.prototype.getPendingTask = function() {
return this.pendingTask_;
};
/**
* @param {webdriver.promise.Task_} task The task currently
* executing within this frame, if any.
*/
webdriver.promise.Frame_.prototype.setPendingTask = function(task) {
this.pendingTask_ = task;
};
/** Locks this frame. */
webdriver.promise.Frame_.prototype.lockFrame = function() {
this.isLocked_ = true;
};
/**
* Adds a new node to this frame.
* @param {!(webdriver.promise.Frame_|webdriver.promise.Task_)} node
* The node to insert.
*/
webdriver.promise.Frame_.prototype.addChild = function(node) {
if (this.lastInsertedChild_ &&
this.lastInsertedChild_ instanceof webdriver.promise.Frame_ &&
!this.lastInsertedChild_.isLocked_) {
this.lastInsertedChild_.addChild(node);
return;
}
node.setParent(this);
if (this.isActive_ && node instanceof webdriver.promise.Frame_) {
var index = 0;
if (this.lastInsertedChild_ instanceof
webdriver.promise.Frame_) {
index = goog.array.indexOf(this.children_, this.lastInsertedChild_) + 1;
}
goog.array.insertAt(this.children_, node, index);
this.lastInsertedChild_ = node;
return;
}
this.lastInsertedChild_ = node;
this.children_.push(node);
};
/**
* @return {(webdriver.promise.Frame_|webdriver.promise.Task_)} This frame's
* fist child.
*/
webdriver.promise.Frame_.prototype.getFirstChild = function() {
this.isActive_ = true;
this.lastInsertedChild_ = null;
return this.children_[0];
};
/**
* Removes a child from this frame.
* @param {!(webdriver.promise.Frame_|webdriver.promise.Task_)} child
* The child to remove.
*/
webdriver.promise.Frame_.prototype.removeChild = function(child) {
var index = goog.array.indexOf(this.children_, child);
child.setParent(null);
goog.array.removeAt(this.children_, index);
if (this.lastInsertedChild_ === child) {
this.lastInsertedChild_ = null;
}
};
/** @override */
webdriver.promise.Frame_.prototype.toString = function() {
return '[' + goog.array.map(this.children_, function(child) {
return child.toString();
}).join(', ') + ']';
};
/**
* A task to be executed by a {@link webdriver.promise.ControlFlow}.
*
* @param {!webdriver.promise.ControlFlow} flow The flow this instances belongs
* to.
* @param {!Function} fn The function to call when the task executes. If it
* returns a {@code webdriver.promise.Promise}, the flow will wait
* for it to be resolved before starting the next task.
* @param {string} description A description of the task for debugging.
* @param {!webdriver.stacktrace.Snapshot} snapshot A snapshot of the stack
* when this task was scheduled.
* @constructor
* @extends {webdriver.promise.Node_}
* @private
*/
webdriver.promise.Task_ = function(flow, fn, description, snapshot) {
webdriver.promise.Node_.call(this, flow);
/**
* Executes this task.
* @type {!Function}
*/
this.execute = fn;
/** @private {string} */
this.description_ = description;
/** @private {!webdriver.stacktrace.Snapshot} */
this.snapshot_ = snapshot;
};
goog.inherits(webdriver.promise.Task_, webdriver.promise.Node_);
/** @return {string} This task's description. */
webdriver.promise.Task_.prototype.getDescription = function() {
return this.description_;
};
/** @override */
webdriver.promise.Task_.prototype.toString = function() {
var stack = this.snapshot_.getStacktrace();
var ret = this.description_;
if (stack.length) {
if (this.description_) {
ret += '\n';
}
ret += stack.join('\n');
}
return ret;
};
/**
* Special error used to signal when a task is canceled because a previous
* task in the same frame failed.
* @param {*} err The error that caused the task cancellation.
* @constructor
* @extends {goog.debug.Error}
* @private
*/
webdriver.promise.CanceledTaskError_ = function(err) {
goog.base(this, 'Task discarded due to a previous task failure: ' + err);
};
goog.inherits(webdriver.promise.CanceledTaskError_, goog.debug.Error);
/** @override */
webdriver.promise.CanceledTaskError_.prototype.name = 'CanceledTaskError';
/**
* The default flow to use if no others are active.
* @private {!webdriver.promise.ControlFlow}
*/
webdriver.promise.defaultFlow_ = new webdriver.promise.ControlFlow();
/**
* A stack of active control flows, with the top of the stack used to schedule
* commands. When there are multiple flows on the stack, the flow at index N
* represents a callback triggered within a task owned by the flow at index
* N-1.
* @private {!Array.}
*/
webdriver.promise.activeFlows_ = [];
/**
* Changes the default flow to use when no others are active.
* @param {!webdriver.promise.ControlFlow} flow The new default flow.
* @throws {Error} If the default flow is not currently active.
*/
webdriver.promise.setDefaultFlow = function(flow) {
if (webdriver.promise.activeFlows_.length) {
throw Error('You may only change the default flow while it is active');
}
webdriver.promise.defaultFlow_ = flow;
};
/**
* @return {!webdriver.promise.ControlFlow} The currently active control flow.
*/
webdriver.promise.controlFlow = function() {
return /** @type {!webdriver.promise.ControlFlow} */ (
goog.array.peek(webdriver.promise.activeFlows_) ||
webdriver.promise.defaultFlow_);
};
/**
* @param {!webdriver.promise.ControlFlow} flow The new flow.
* @private
*/
webdriver.promise.pushFlow_ = function(flow) {
webdriver.promise.activeFlows_.push(flow);
};
/** @private */
webdriver.promise.popFlow_ = function() {
webdriver.promise.activeFlows_.pop();
};
/**
* Creates a new control flow. The provided callback will be invoked as the
* first task within the new flow, with the flow as its sole argument. Returns
* a promise that resolves to the callback result.
* @param {function(!webdriver.promise.ControlFlow)} callback The entry point
* to the newly created flow.
* @return {!webdriver.promise.Promise} A promise that resolves to the callback
* result.
*/
webdriver.promise.createFlow = function(callback) {
var flow = new webdriver.promise.ControlFlow(
webdriver.promise.defaultFlow_.timer);
return flow.execute(function() {
return callback(flow);
});
};
*
* @param {*} value The value to fully resolve.
* @return {!webdriver.promise.Promise} A promise for a fully resolved version
* of the input value.
*/
webdriver.promise.fullyResolved = function(value) {
if (webdriver.promise.isPromise(value)) {
return webdriver.promise.when(value, webdriver.promise.fullyResolveValue_);
}
return webdriver.promise.fullyResolveValue_(value);
};
/**
* @param {*} value The value to fully resolve. If a promise, assumed to
* already be resolved.
* @return {!webdriver.promise.Promise} A promise for a fully resolved version
* of the input value.
* @private
*/
webdriver.promise.fullyResolveValue_ = function(value) {
switch (goog.typeOf(value)) {
case 'array':
return webdriver.promise.fullyResolveKeys_(
/** @type {!Array} */ (value));
case 'object':
if (webdriver.promise.isPromise(value)) {
// We get here when the original input value is a promise that
// resolves to itself. When the user provides us with such a promise,
// trust that it counts as a "fully resolved" value and return it.
// Of course, since it's already a promise, we can just return it
// to the user instead of wrapping it in another promise.
return /** @type {!webdriver.promise.Promise} */ (value);
}
if (goog.isNumber(value.nodeType) &&
goog.isObject(value.ownerDocument) &&
goog.isNumber(value.ownerDocument.nodeType)) {
// DOM node; return early to avoid infinite recursion. Should we
// only support objects with a certain level of nesting?
return webdriver.promise.fulfilled(value);
}
return webdriver.promise.fullyResolveKeys_(
/** @type {!Object} */ (value));
default: // boolean, function, null, number, string, undefined
return webdriver.promise.fulfilled(value);
}
};
/**
* @param {!(Array|Object)} obj the object to resolve.
* @return {!webdriver.promise.Promise} A promise that will be resolved with the
* input object once all of its values have been fully resolved.
* @private
*/
webdriver.promise.fullyResolveKeys_ = function(obj) {
var isArray = goog.isArray(obj);
var numKeys = isArray ? obj.length : goog.object.getCount(obj);
if (!numKeys) {
return webdriver.promise.fulfilled(obj);
}
var numResolved = 0;
var deferred = new webdriver.promise.Deferred();
// In pre-IE9, goog.array.forEach will not iterate properly over arrays
// containing undefined values because "index in array" returns false
// when array[index] === undefined (even for x = [undefined, 1]). To get
// around this, we need to use our own forEach implementation.
// DO NOT REMOVE THIS UNTIL WE NO LONGER SUPPORT IE8. This cannot be
// reproduced in IE9 by changing the browser/document modes, it requires an
// actual pre-IE9 browser. Yay, IE!
var forEachKey = !isArray ? goog.object.forEach : function(arr, fn) {
var n = arr.length;
for (var i = 0; i < n; ++i) {
fn.call(null, arr[i], i, arr);
}
};
forEachKey(obj, function(partialValue, key) {
var type = goog.typeOf(partialValue);
if (type != 'array' && type != 'object') {
maybeResolveValue();
return;
}
webdriver.promise.fullyResolved(partialValue).then(
function(resolvedValue) {
obj[key] = resolvedValue;
maybeResolveValue();
},
deferred.reject);
});
return deferred.promise;
function maybeResolveValue() {
if (++numResolved == numKeys) {
deferred.fulfill(obj);
}
}
};
//////////////////////////////////////////////////////////////////////////////
//
// webdriver.promise.ControlFlow
//
//////////////////////////////////////////////////////////////////////////////
/**
* Handles the execution of scheduled tasks, each of which may be an
* asynchronous operation. The control flow will ensure tasks are executed in
* the ordered scheduled, starting each task only once those before it have
* completed.
*
*
* var value = {};
* value['self'] = value;
* webdriver.promise.fullyResolved(value); // Stack overflow.
*
*
* @private {boolean}
*/
webdriver.promise.Frame_.prototype.isActive_ = false;
/**
* Whether this frame is currently locked. A locked frame represents a callback
* or task function which has run to completion and scheduled all of its tasks.
*
*
* var flow = webdriver.promise.controlFlow();
* flow.execute('start here', goog.nullFunction).then(function() {
* flow.execute('this should execute 2nd', goog.nullFunction);
* });
* flow.execute('this should execute last', goog.nullFunction);
*