all files / oja-next/ index.js

100% Statements 235/235
97.96% Branches 96/98
100% Functions 32/32
100% Lines 229/229
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 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528    1× 1× 1×       115× 9× 9×     106×       1×                                               178× 178× 13×   13× 6×   13×   165× 6× 3× 6×   159×   158× 158×     1×       18× 1×   17× 14× 14×   17× 17×       10× 10× 9× 9×   9× 9× 9× 14×         9× 9×     9×       10×   1× 8×   10×             15×                             190× 29× 26×   6× 6× 12×     6×     1× 1×     12×     17× 32× 32×     17× 6× 17× 17×         161× 133× 65× 3× 1×   3×     62×   133×   28×                   12×   12× 12× 2× 2×   10×                   5× 5× 5× 5×   1× 30× 8× 8×   22× 22× 2×       5× 5×   5×   31× 22×   9× 1×   8× 8×                 310×   184× 184× 184× 184× 184×     126× 126× 126× 126× 126×     126×       184× 178×       184×             15× 9× 9× 9×   9×   15× 32× 23×   32×     15×               344× 94×   344×   2× 1× 1× 1×           2×   342× 342× 67×               158× 158×   158×       186× 186×   186×       220× 220×   220× 220×     220× 29× 29×       191×     218× 191×     216× 216×         216×               107×   93× 70×     93×   107×           184× 184×       186×   2×   184× 22× 22×     162× 169×             24× 24× 24×   24× 214× 40×   174× 17×   174× 24× 24×   150×     24× 3× 3× 3×   24×       175× 18×     175×       37× 37× 24×         174× 17× 17× 17×   174×           33×   33× 33×             30× 1×   29× 29× 29×   29×       12× 12× 2×     10× 1×     9×         12× 18×   4×   18× 18× 1×     17× 17×     11×       19× 19× 2×             4× 4×       4×       1× 1× 1× 1× 1×  
'use strict';
 
const Assert = require('assert');
const EventEmitter = require('events').EventEmitter;
const Readable = require('stream').Readable;
 
class Flow {
    constructor(baseFlow) {
        if (baseFlow) {
            this.eventContext = baseFlow.eventContext;
            return;
        }
        // eslint-disable-next-line no-use-before-define
        this.eventContext = new EventContext();
    }
 
    setMaxListeners(value) {
        this.eventContext._emitter.setMaxListeners(value);
    }
 
    /*
       Define a publisher with the given topic.
       define(topics[, callback])
       It supports the following calling styles
       - define('topic') defines publisher with the given topic.
            * If define return non-empty value (promise, eventemitter, object, etc.),
            it is assumed to be a result that gets published to the flow under the topic name.
       - define(['A', 'B']) defines publisher with the given topics.
       - define('topic', callback) defines a publisher for in-line functions.
            * If callback is provided, it makes calls callback(publisher, runtime),
            where runtime is the reference to the flow object to allow further access to the flow inside arrow function
            * If callback return data, it is assumes to be the result and it gets published under topic.
       - define('topic', data) defines static data that gets published under the given topic immediately.
            * Notable side-effect: if one calls flow.define('foo', data) multiple time it is
            eqivaalent to emitting events
 
       Publisher API:
       - pub(data) publishes data under the assigned topic or publisher topic.
         It handles promises, events, plain data
    */
    define(topics, cb) {
        const publisher = this.eventContext.stageContext(topics);
        if (typeof cb === 'function') {
            const ret = cb(publisher, this);
            // keep cb returns something, treat is as a response
            if (ret !== undefined) {
                publisher.pub(ret);
            }
            return this; // to allow cascading style
        }
        if (cb instanceof Promise) {
            cb.then(data => publisher.pub(data))
                .catch(err => publisher.pub(err));
            return this;
        }
        if (cb !== undefined) {
            // assume it is a response
            publisher.pub(cb);
            return this;
        }
        // otherwise, it is sync mode, hence return publisher
        return publisher;
    }
 
    catch(callback) {
        if (arguments.length !== 1) {
            throw new Error('Invalid arguments');
        }
        this._catchHandler = err => {
            this._catchHandler = () => {};
            callback(err);
        };
        this.consume('error', this._catchHandler);
        return this;
    }
 
    timeout(topics, ms) {
        topics = Array.isArray(topics) ? topics : [topics];
        const timer = setTimeout(() => {
            const state = this.state();
            const pendingTopics = state.pending;
 
            const unresolved = [];
            const pending = [];
            pendingTopics.forEach(tp => {
                topics.indexOf(tp) !== -1 ?
                    unresolved.push(tp) :
                    pending.push(tp);
            });
 
            const queueState = `queue state ${JSON.stringify(state.queue)}`;
            const msg = `Topic/s (${unresolved.join(',')}) timed out, pending topics (${
                pending.join(',') || 'none'}), ${queueState}`;
 
            this.define('error',
                new Error(msg));
        }, ms);
 
        this
            .consume(topics)
            .then(() => clearTimeout(timer))
            .catch(() => clearTimeout(timer));
 
        return this;
    }
 
    /*
        Returns a list of topics that have not been resolved yet
    */
    state() {
        return this.eventContext.state();
    }
 
    /*
        Consumes given topics:
        consume(topics[, callback])
        API:
        - consume(topics) returns a map of promises mapped to each topic
        - consume(topic) returns a promise for the given topic
        - consume(topics, callback(input, runtime)) returns a map of resolved
            values for the given topics, where runtime is a reference to the flow instance
        - consume(topic, callback(data, runtime)) returns resolved value for the given topic,
            where runtime is a reference to the flow instance
    */
    consume(topics, cb) {
        if (Array.isArray(topics)) {
            if (cb) {
                Promise.all(topics.map(topic => this.eventContext.get(topic)))
                    .then(values => {
                        const ret = {};
                        values.map((val, index) => {
                            ret[topics[index]] = val;
                        });
                        // unlink any error in cb from promise flow to let it fail
                        setImmediate(() => cb(ret, this));
                    })
                    .catch(err => {
                        Eif (this._catchHandler) {
                            return this._catchHandler(err);
                        }
                    });
                return this; // for cascading style
            }
 
            const promises = topics.reduce((memo, topic) => {
                memo.push(this.eventContext.get(topic));
                return memo;
            }, []);
 
            return Promise.all(promises)
                .then(results => results.reduce((memo, data, index) => {
                    memo[topics[index]] = data;
                    return memo;
                }, {}));
        }
 
        // handle single topics
        if (cb) {
            this.eventContext.on(topics, data => {
                if (data instanceof Promise) {
                    data.then(cb).catch(err => {
                        this.define('error', err);
                    });
                    return;
                }
 
                cb(data, this);
            });
            return this;
        }
        return this.eventContext.get(topics);
    }
 
    /*
        Consumes stream for the given topic.
        Returns as readable stream
        The end of stream should be marked as undefined data
    */
    consumeStream(topic, callback) {
        // let's monitor end of stream to show in pending list if timeout happens
        this.consume(`${topic }:end`).catch(() => {});
        // eslint-disable-next-line no-use-before-define
        const stream = new ReadableStream(topic, this.eventContext);
        if (callback) {
            callback(stream);
            return this;
        }
        return stream;
    }
 
    /*
        Returns a reader for the given topic.
        It is useful when reading stream of events for the given topic.
        At the end of stream an undefined value will be returned.
        The reader returns a promise for async/await pattern.
    */
    getReader(topic) {
        const pending = [];
        const resolved = [];
        let completed = false;
        const stream = this.consumeStream(topic);
 
        function publish(data) {
            if (pending.length) {
                const resolve = pending.shift();
                return resolve(data);
            }
            resolved.push(data);
            if (data === undefined) {
                completed = true;
            }
        }
 
        stream.on('data', publish);
        stream.once('end', publish);
 
        return {
            next() {
                if (resolved.length) {
                    return Promise.resolve(resolved.shift());
                }
                if (completed) {
                    return Promise.reject(new Error(`The reader(${topic}) is already closed`));
                }
                return new Promise(resolve => {
                    pending.push(resolve);
                });
            }
        };
    }
}
 
class EventContext {
    constructor(context) {
        if (context instanceof EventContext) {
            // share the same context
            this._resolved = context._resolved;
            this._context = context._context;
            this._emitter = context._emitter;
            this._queue = context._queue;
            return;
        }
        // new context
        this._resolved = {};
        this._context = {};
        this._queue = {};
        Object.assign(this._context, context);
        this._emitter = new EventEmitter();
        // increase limit to accomodate big networks of components where
        // everyone listens to error
        this._emitter.setMaxListeners(20);
    }
 
    stageContext(topics) {
        if (topics && !Array.isArray(topics)) {
            topics = [].slice.call(arguments);
        }
 
        // eslint-disable-next-line no-use-before-define
        return new StageContext(this, topics);
    }
 
    /*
        Returns a list of topics that have not been resolved yet
    */
    state() {
        const queueState = Object.keys(this._queue).reduce((memo, topic) => {
            const queue = this._queue[topic];
            Eif (queue && queue.length) {
                memo[topic] = queue.length;
            }
            return memo;
        }, {});
        const pending = Object.keys(this._resolved).reduce((memo, name) => {
            if (!this._resolved[name]) {
                memo.push(name);
            }
            return memo;
        }, []);
 
        return {
            queue: queueState,
            pending: pending
        };
    }
 
    repub(type, handler) {
        // mark if any new topics have been added and marko them as non-resolved
        if (type !== 'error' && this._resolved[type] === undefined) {
            this._resolved[type] = false;
        }
        if (type === '*') {
            // re-publish all events
            Object.keys(this._queue).forEach(name => {
                const evts = this._queue[name];
                evts.forEach(evt => {
                    handler({
                        name: name,
                        data: evt
                    });
                });
            });
            return;
        }
        const queue = this._queue[type];
        if (queue) {
            queue.forEach(evt => handler(evt));
        }
    }
 
    /*
      Add a listener for a stream parameter.
    */
    on(type, handler) {
        this.repub(type, handler);
        this._emitter.on(type, handler);
 
        return this;
    }
 
    once(type, handler) {
        this.repub(type, handler);
        this._emitter.once(type, handler);
 
        return this;
    }
 
    emit(name, value) {
        this._queue[name] = this._queue[name] || [];
        this._queue[name].push(value);
 
        const doEmit = () => {
            this._emitter.emit(name, value);
        };
 
        if (name === 'error') {
            this._context._lastError = value;
            doEmit();
        }
        else {
            // mark as resolved
            this._resolved[name] = true;
        }
 
        if (!this._context._lastError) {
            doEmit();
        }
 
        setImmediate(() => {
            this._emitter.emit('*', {
                name: name,
                data: value
            });
        });
        return this;
    }
 
    /*
      Returns value from the context.
      If value is not yet published, it will return a promise
    */
    get(name) {
        const value = this._context[name] = this._context[name] || new Promise((resolve, reject) => {
            // this.once(name, resolve);
            this.once(name, data => {
                resolve(data);
            });
 
            this.once('error', reject);
        });
        return value;
    }
}
 
class StageContext extends EventContext {
    constructor(eventContext, topics) {
        super(eventContext);
        this.topics = topics;
    }
 
    pub(data) {
        if (this._context._lastError) {
            // flow is already broken
            return;
        }
        if (data instanceof Error) {
            this._context._lastError = data;
            return setImmediate(() => super.emit('error', data));
        }
        // otherwise publish normally
        (this.topics || ['data']).forEach(topic => {
            super.emit(topic, data);
        });
    }
}
 
class ReadableStream extends Readable {
    constructor(topic, emitter) {
        super({ objectMode: true });
        this.topic = topic;
        this.emitter = emitter;
        // then init, this is a first time
        emitter.on(topic, data => {
            if (this._stopped) {
                return;
            }
            if (data === undefined || data === null) {
                this._stopped = true;
            }
            if (this._paused) {
                this._buffer.push(data);
                return;
            }
            this._continue(data);
        });
 
        this.once('error', err => {
            this._stopped = true;
            emitter.emit(`${topic }:end`);
            emitter.emit('error', err);
        });
        this._buffer = [];
    }
 
    push(data) {
        if (data === null) {
            this._stopped = true;
        }
 
        return super.push(data);
    }
 
    _read() {
        this._paused = false;
        while (!this._paused && this._buffer.length) {
            this._continue(this._buffer.shift());
        }
    }
 
    _continue(data) {
        if (data === undefined || data === null) {
            data = null; // mark stop down the stream
            this._stopped = true;
            this.emitter.emit(`${this.topic }:end`);
        }
        this._paused = !this.push(data);
    }
}
 
class Action extends Flow {
    constructor() {
        super();
 
        this.actions = [];
        this.executed = false;
    }
 
    execute() {}
 
    activate() {
        // starts the action
        if (this.executed) {
            return this;
        }
        this.executed = true;
        this.execute();
        this.actions.forEach(action => action.activate());
 
        return this;
    }
 
    add(action) {
        let actions = [];
        if (arguments.length > 1) {
            actions = actions.concat([].slice.call(arguments));
        }
        else {
            if (Array.isArray(arguments[0])) {
                actions = actions.concat(arguments[0]);
            }
            else {
                actions.push(arguments[0]);
            }
        }
 
        // eslint-disable-next-line no-shadow
        actions.forEach(action => {
            if (typeof action === 'function') {
                // eslint-disable-next-line no-use-before-define
                action = new FunctionAction(action);
            }
            Assert.ok(action instanceof Action, 'The action beeing added does not of Action type');
            if (action.executed) {
                throw new Error('The action should not be in progress when it is added to the other action');
            }
            // remap to basec context
            action.setEventContext(this.eventContext);
            this.actions.push(action);
        });
 
        return this;
    }
 
    setEventContext(eventContext) {
        this.eventContext = eventContext;
        this.actions.forEach(action => {
            action.setEventContext(eventContext);
        });
    }
}
 
class FunctionAction extends Action {
    constructor(fun) {
        super();
        this.fun = fun;
    }
 
    execute() {
        return this.fun(this);
    }
}
 
module.exports.Flow = Flow;
module.exports.Action = Action;
module.exports.EventContext = EventContext;
module.exports.StageContext = StageContext;
module.exports.ReadableStream = ReadableStream;