serviceadmin.js 14.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright 2016 Adobe Systems Incorporated
 * All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 */

/**
 * The service admin is a singleton that offers a global registry for name based services.
 *
 * @module screens/player/shared/serviceadmin
 */
define('screens/player/shared/serviceadmin', ['underscore', 'eventemitter'], function(_, EventEmitter) {
    'use strict';

    /**
     * @typedef STATE
     */
    var STATE = Object.freeze({
        INVALID: 0,
        REGISTERED: 1,
        STARTING: 2,
        STARTED: 3,
        STOPPING: 4,
        STOPPED: 5,
        ABORTED: 6
    });

    var EVENTS = Object.freeze({

        /**
         * Event when service admin was started.
         * @event serviceadmin-started
         */
        SERVICE_ADMIN_STARTED: 'serviceadmin-started',

        /**
         * Event when service admin was stopped.
         * @event serviceadmin-stopped
         */
        SERVICE_ADMIN_STOPPED: 'serviceadmin-stopped',

        /**
         * Event when a service was registered
         * @event service-registered
         */
        SERVICE_REGISTERED: 'service-registered',

        /**
         * Event when a service is starting
         * @event service-starting
         */
        SERVICE_STARTING: 'service-starting',

        /**
         * Event when a service was started
         * @event service-started
         */
        SERVICE_STARTED: 'service-started',

        /**
         * Event when a service is stopping
         * @event service-stopping
         */
        SERVICE_STOPPING: 'service-stopping',

        /**
         * Event when a service was stopped
         * @event service-stopped
         */
        SERVICE_STOPPED: 'service-stopped',

        /**
         * Event when a service was aborted
         * @event service-aborted
         */
        SERVICE_ABORTED: 'service-aborted'

    });


    /**
     * Comparator for Service Entries.
     * @param {number} s1 left entry to compare
     * @param {number} s2 right entry to compare
     * @returns {number} the comparison result
     */
    function RANK_COMPARATOR(s1, s2) {
        return s2.rank - s1.rank;
    }

    /**
     * Creates a service entry processor that transitions the service from the current to a final state
     * @param {STATE} transientState the state the service gets during transition
     * @param {STATE} finalState the final state
     * @param {STATE} errorState the error state
     * @param {String} funcName Name of the transition function. eg 'activate'.
     * @returns {Function} the transition function processor
     * @see ServiceAdmin#start
     * @see ServiceAdmin#stop
     * @private
     */
    function createSvcEntryProcessor(transientState, finalState, errorState, funcName) {
        return function processSvcEntry(entry) {
            entry.state = transientState;

            if (!_.isFunction(entry.svc[funcName])) {
                entry.state = finalState;
                entry.completedActivation = Promise.resolve();
                return entry.completedActivation;
            }
            var p = entry.svc[funcName]();
            if (!p || !p.then || !_.isFunction(p.then)) {
                p = Promise.resolve();
            }
            entry.completedActivation = p.then(function() {
                entry.state = finalState;
            }, function() {
                entry.state = errorState;
            });
            return entry.completedActivation;
        };
    }

    /**
     * The service admin.
     *
     * @classdesc Simple service admin
     * @class ServiceAdmin
     * @singleton
     * @extends EventEmitter
     */
    var ServiceAdmin = function() {

        /**
         * Array of entries of all registered services.
         * @type {Array}
         * @private
         */
        var _services = [];

        /**
         * Map from service names to service entries
         * @type {Object}
         * @private
         */
        var _servicesByName = {};

        /**
         * Indicates if the service admin was started
         * @type {boolean}
         * @private
         */
        var _started = false;

        /**
         * Indicates if the service admin starting is currently in progress
         * @type {boolean}
         * @private
         */
        var _isStarting = false;

        /**
         * internal function that returns the list of service entries for a given name.
         * @param {String} name Service name
         * @param {boolean} create If true, create the list if missing.
         * @returns {Array} Array of service entries
         * @private
         */
        function _getServiceList(name, create) {
            var list = _servicesByName[name];
            if (!list) {
                if (!create) {
                    return null;
                }
                list = _servicesByName[name] = [];
            }
            return list;
        }

        function _addEntryToServices(entry, serviceNames) {
            _services.push(entry);

            // register service names
            _.each(serviceNames, function(name) {
                var list = _getServiceList(name, true);
                list.push(entry);
                list.sort(RANK_COMPARATOR);

                // in case the service admin is already started
                // the service will need to get started if the priority matches
                if (_started) {
                    createSvcEntryProcessor(
                        STATE.STARTING, STATE.STARTED, STATE.ABORTED, 'activate'
                    )(entry);
                }
            });
        }

        return _.create(EventEmitter.prototype, _.assign({'_super': EventEmitter.prototype},
            /** @lends module:screens/player/shared/serviceadmin.ServiceAdmin.prototype */ {

            /**
             * Registers a new service. The name can be optional, but can also be provisioned with {@link Service#name}
             * @param {Service} service The service to register
             * @param {String|Array} [names] optional name(s) of services
             */
            register: function(service, names) {
                var self = this;
                // sanitize service names
                var serviceNames = Array.prototype.concat([], names || service.serviceName || 'anonymous' + _.now());

                // check if service is already registered
                if (_.find(_services, function(info) {
                        return info.svc === service;
                    })) {
                    throw new Error('service already registered: ', serviceNames);
                }

                // check if service with same id already exists
                if (service.serviceId && _.find(_services, function(info) {
                        return info.svc && (info.svc.serviceId === service.serviceId);
                    })) {
                    throw new Error('service with same id already registered: ', service.serviceId);
                }

                // create service entry and remember it
                var entry = {
                    svc: service,
                    rank: service.serviceRanking || 0
                };

                // observe state changes with a property
                var _state;
                Object.defineProperty(entry, 'state', {
                    get: function() {
                        return _state;
                    },
                    set: function(val) {
                        var s = _.invert(STATE);
                        if (s[val]) {
                            _state = val;
                            self.emit(EVENTS['SERVICE_' + s[val]], {
                                state: val,
                                service: this.svc
                            });
                        }
                    }
                });
                entry.state = STATE.REGISTERED;

                if (_isStarting) {
                    this.on(EVENTS.SERVICE_ADMIN_STARTED, function(data) {
                        _addEntryToServices(entry, serviceNames);
                    });
                } else {
                    _addEntryToServices(entry, serviceNames);
                }
            },

            /**
             * Enables to execute a function once a service is started.
             * The function is called every time the given service is started.
             * @param {String} name Name of the service to wait for
             * @param {Function} callback to be executed
             */
            onServiceStart: function(name, callback) {
                var svc = this.getService(name);

                if (svc) {
                    callback(svc);
                }

                this.on(EVENTS.SERVICE_STARTED, function(data) {
                    if (data.service.serviceName === name || data.service.serviceName.indexOf(name) > -1) {
                        callback(data.service);
                    }
                });
            },

            /**
             * Enables to execute a function once the highest ranked service is started.
             * The function is called every time the highest ranked service changed
             * @param {String} name Name of the service to wait for
             * @param {Function} callback to be executed
             */
            onServiceHighestRankedStart: function(name, callback) {
                var self = this;

                function always(promise, cb) {
                    return promise.then(cb, cb);
                }

                this.onServiceStart(name, function(service) {

                    // we need to make sure that not a higher ranked service
                    // is still booting
                    var services = _getServiceList(name);

                    // gather all higher ranked services
                    // and wait for them to finish their transition
                    var promiseChain = Promise.resolve();

                    _.every(services, function(entry) {
                        if (entry.svc === service) {
                            return false;
                        }

                        var nextPromise = function() {
                            return entry.completedActivation;
                        };

                        promiseChain = always(promiseChain, nextPromise);

                        return true;
                    });

                    // when this callback is called then all services
                    // have completed their transition
                    always(promiseChain, function() {
                        var highestRank = self.getService(name);
                        if (highestRank === service) {
                            callback(service);
                        }
                    });
                });
            },

            /**
             * Returns the state of the service with the given name.
             * @param {String} name Name of the service state to retrieve
             * @returns {Number} Service state
             */
            getServiceState: function(name) {
                var list = _getServiceList(name);
                if (!list || list.length === 0) {
                    return STATE.INVALID;
                }
                return list[0].state;
            },

            /**
             * Returns the best service with the given name that is started.
             * @param {String} name Name of the service state to retrieve
             * @returns {Service} the service
             */
            getService: function(name) {
                var e = _.find(_getServiceList(name), function(entry) {
                    return entry.state === STATE.STARTED;
                });
                return e ? e.svc : null;
            },

            /**
             * Returns the array of service with the given name that are started.
             * @param {String} name Name of the service state to retrieve
             * @returns {Array} the service list
             */
            getServices: function(name) {
                var services = [];
                _.each(_getServiceList(name), function(entry) {
                    if (entry.state === STATE.STARTED) {
                        services.push(entry.svc);
                    }
                });
                return services;
            },

            /**
             * Starts the service admin and call the {@link Service#activate} method on all registered services.
             * @return {Promise} a promise that resolves when all services are started.
             */
            start: function() {
                var self = this;
                _isStarting = true;
                var transitionProcessor = createSvcEntryProcessor(
                    STATE.STARTING, STATE.STARTED, STATE.ABORTED, 'activate'
                );
                return Promise.all(_.map(_services, transitionProcessor)).then(function() {
                    _isStarting = false;
                    _started = true;
                    self.emit(EVENTS.SERVICE_ADMIN_STARTED);
                });
            },

            /**
             * Stops the service admin and calls the {@link Service#deactivate} method on all activated services
             * @return {Promise} a promise that resolves when all services are stopped.
             */
            stop: function() {
                var self = this;
                var transitionProcessor = createSvcEntryProcessor(
                    STATE.STOPPING, STATE.STOPPED, STATE.ABORTED, 'deactivate'
                );
                return Promise.all(_.map(_services, transitionProcessor)).then(function() {
                    _started = false;
                    self.emit(EVENTS.SERVICE_ADMIN_STOPPED);
                });
            },

            /**
             * Creates a new pristine service admin instance that does not conflict with the globally
             * exported one. Mainly used for testing.
             *
             * @returns {ServiceAdmin} a new service admin instance.
             */
            noConflict: function() {
                var serviceAdmin = new ServiceAdmin();
                serviceAdmin.STATE = STATE;
                serviceAdmin.EVENTS = EVENTS;
                return serviceAdmin;
            }

        }));
    };

    var _instance = new ServiceAdmin();
    _instance.STATE = STATE;
    _instance.EVENTS = EVENTS;
    return _instance;

});