All files / packages/tao/src Network.js

94.21% Statements 114/121
78.69% Branches 48/61
88% Functions 22/25
94.02% Lines 110/117
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                            6x                                         138x 60x 22x     78x 50x           438x 52x   438x 68x         438x 264x   438x       138x 94x   138x                   244x 148x 218x 145x 145x 49x   119x   119x 46x 46x 96x 96x   96x   96x 96x 96x     146x 98x 169x   169x 163x 157x 79x 151x 70x     141x 141x       135x               129x 84x 129x 129x 84x 6x   78x                         45x 45x         45x         45x       45x     45x 64x           19x         2x 19x 19x 19x   33x     33x       33x                   25x 52x       52x 33x   40x 38x 21x   39x 37x   37x 98x 96x           110x 72x         105x     33x 105x 12x               37x 39x 37x 39x           25x 19x             19x 19x       20x 18x             18x 18x       79x 77x             77x 77x       72x 72x 72x           72x       6x           4x       6x           4x       6x           4x      
// need this when running in Node.js environment
// import { clearTimeout } from 'timers';
import {
  WILDCARD,
  INTERCEPT,
  ASYNC,
  INLINE
  // TIMEOUT_REJECT
} from './constants';
import AppCtxRoot from './AppCtxRoot';
import AppCtx from './AppCtx';
import AppCtxHandlers from './AppCtxHandlers';
import { _cleanAC, _validateHandler } from './utils';
 
const NOOP = () => {};
 
// // Private methods for TAO
// function _cleanAC({ t, term, a, action, o, orient }) {
//   return {
//     term: term || t,
//     action: action || a,
//     orient: orient || o
//   };
// }
 
// function _validateHandler(handler) {
//   if (!handler) {
//     throw new Error('cannot do anything with missing handler');
//   }
//   if (typeof handler !== 'function') {
//     throw new Error('handler must be a function');
//   }
// }
 
function _appendLeaves(leavesFrom, leavesTo, taoism) {
  if (taoism) {
    if (leavesFrom.has(taoism) && leavesFrom.get(taoism).size) {
      leavesFrom.get(taoism).forEach(leaf => leavesTo.add(leaf));
    }
  } else {
    leavesFrom.forEach(leaves => {
      leaves.forEach(leaf => leavesTo.add(leaf));
    });
  }
}
 
function _appendWildcards(wildcardsFrom, wildcardsTo, taoism) {
  if (wildcardsFrom.has(taoism)) {
    wildcardsFrom.get(taoism).forEach(wc => wildcardsTo.add(wc));
  }
  if (wildcardsFrom.has(WILDCARD)) {
    wildcardsFrom.get(WILDCARD).forEach(wc => wildcardsTo.add(wc));
  }
}
 
function _addLeaf(leaves, taoism, ach) {
  if (!leaves.has(taoism)) {
    leaves.set(taoism, new Set());
  }
  leaves.get(taoism).add(ach);
}
 
function _addWildcard(wildcards, taoism, ach) {
  if (!wildcards.has(taoism)) {
    wildcards.set(taoism, new Set());
  }
  wildcards.get(taoism).add(ach);
}
 
function _addACHandler(
  tao,
  taoHandlers,
  taoLeaves,
  taoWildcards,
  { term, action, orient }
) {
  const t = term || WILDCARD;
  const a = action || WILDCARD;
  const o = orient || WILDCARD;
  const acKey = AppCtxRoot.getKey(t, a, o);
  if (taoHandlers.has(acKey)) {
    return taoHandlers.get(acKey);
  }
  const ach = new AppCtxHandlers(t, a, o);
 
  if (ach.isWildcard) {
    let leaves = new Set();
    _appendLeaves(taoLeaves.t, leaves, term);
    _appendLeaves(taoLeaves.a, leaves, action);
    _appendLeaves(taoLeaves.o, leaves, orient);
 
    ach.addLeafHandlers(leaves);
 
    _addWildcard(taoWildcards.t, t, ach);
    _addWildcard(taoWildcards.a, a, ach);
    _addWildcard(taoWildcards.o, o, ach);
  } else {
    //!ach.isWildcard
    _addLeaf(taoLeaves.t, term, ach);
    _addLeaf(taoLeaves.a, action, ach);
    _addLeaf(taoLeaves.o, orient, ach);
 
    let wildcards = new Set();
    _appendWildcards(taoWildcards.t, wildcards, term);
    _appendWildcards(taoWildcards.a, wildcards, action);
    _appendWildcards(taoWildcards.o, wildcards, orient);
    for (let wc of wildcards) {
      wc.addLeafHandler(ach);
    }
  }
  taoHandlers.set(acKey, ach);
  return ach;
}
 
function _removeHandler(taoHandlers, { term, action, orient }, handler, type) {
  _validateHandler(handler);
  // guard is currently impossible to hit so removing to get 100% test coverage
  // type = type || INLINE;
  // if (type !== ASYNC && type !== INLINE && type !== INTERCEPT) {
  //   throw new Error(
  //     `${type} not a known handler type - try ${ASYNC}, ${INLINE} or ${INTERCEPT}`
  //   );
  // }
  const t = term || WILDCARD;
  const a = action || WILDCARD;
  const o = orient || WILDCARD;
  const acKey = AppCtxRoot.getKey(t, a, o);
  if (!taoHandlers.has(acKey)) {
    return;
  }
  taoHandlers.get(acKey)[`remove${type}Handler`](handler);
}
 
// function _removeHandlers(taoHandlers, acList, handlers, type) {
//   handlers.forEach(handler =>
//     acList.forEach(ac =>
//       _removeHandler(taoHandlers, _cleanAC(ac), handler, type)
//     )
//   );
// }
 
export default class Network {
  constructor() {
    this._handlers = new Map();
    this._leaves = {
      t: new Map(),
      a: new Map(),
      o: new Map()
    };
    this._wildcards = {
      t: new Map(),
      a: new Map(),
      o: new Map()
    };
    this._middleware = new Set();
  }
 
  use(middleware) {
    Iif (typeof middleware !== 'function') {
      throw new Error('middleware must be a function');
    }
    Eif (!this._middleware.has(middleware)) {
      this._middleware.add(middleware);
    }
  }
 
  stop(middleware) {
    if (this._middleware.has(middleware)) {
      this._middleware.delete(middleware);
    }
  }
 
  clone() {
    const cloned = new Network();
    for (let trigram of this._handlers.values()) {
      for (let interceptHandler of trigram.interceptHandlers) {
        cloned.addInterceptHandler(trigram, interceptHandler);
      }
      for (let asyncHandler of trigram.asyncHandlers) {
        cloned.addAsyncHandler(trigram, asyncHandler);
      }
      for (let inlineHandler of trigram.inlineHandlers) {
        cloned.addInlineHandler(trigram, inlineHandler);
      }
    }
    return cloned;
  }
 
  setCtxControl(
    { t, term, a, action, o, orient },
    data,
    control = {},
    forwardAppCtx = NOOP
  ) {
    // get the hash for the ac
    const acIn = _cleanAC({ t, term, a, action, o, orient });
    const isWild = AppCtxRoot.isWildcard(acIn);
    // console.log('setCtxControl::trigram:', { t, a, o, term, action, orient });
    // console.log('setCtxControl::control:', control);
    // console.log('setCtxControl::forwardAppCtx:', typeof forwardAppCtx);
    Iif (typeof forwardAppCtx !== 'function') {
      forwardAppCtx = NOOP;
    }
    const acKey = AppCtxRoot.getKey(acIn.term, acIn.action, acIn.orient);
    if (!this._handlers.has(acKey) && !isWild) {
      _addACHandler(this, this._handlers, this._leaves, this._wildcards, acIn);
    }
    Eif (this._handlers.has(acKey)) {
      const appCtx = new AppCtx(acIn.term, acIn.action, acIn.orient, data);
      // why not forward the call to setAppCtx? -> b/c don't want to execute check against existing again
      const handler = this._handlers.get(acKey);
      for (let middleware of this._middleware) {
        middleware(handler, appCtx, forwardAppCtx, control);
      }
    }
  }
 
  setAppCtxControl(appCtx, control = {}, forwardAppCtx) {
    Iif (!(appCtx instanceof AppCtx)) {
      throw new Error(`'appCtx' not an instance of AppCtx`);
    }
    // console.log('setAppCtxControl::appCtx:', appCtx.unwrapCtx());
    // console.log('setAppCtxControl::control:', control);
    // console.log('setAppCtxControl::forwardAppCtx:', typeof forwardAppCtx);
    Iif (typeof forwardAppCtx !== 'function') {
      forwardAppCtx = NOOP;
    }
    const isWild = appCtx.isWildcard;
    if (!this._handlers.has(appCtx.key) && !isWild) {
      _addACHandler(
        this,
        this._handlers,
        this._leaves,
        this._wildcards,
        _cleanAC(appCtx)
      );
    }
    Eif (this._handlers.has(appCtx.key)) {
      const handler = this._handlers.get(appCtx.key);
      for (let middleware of this._middleware) {
        middleware(handler, appCtx, forwardAppCtx, control);
      }
    }
  }
 
  addInterceptHandler({ t, term, a, action, o, orient }, handler) {
    _validateHandler(handler);
    const ach = _addACHandler(
      this,
      this._handlers,
      this._leaves,
      this._wildcards,
      _cleanAC({ t, term, a, action, o, orient })
    );
    ach.addInterceptHandler(handler);
    return this;
  }
 
  addAsyncHandler({ t, term, a, action, o, orient }, handler) {
    _validateHandler(handler);
    const ach = _addACHandler(
      this,
      this._handlers,
      this._leaves,
      this._wildcards,
      _cleanAC({ t, term, a, action, o, orient })
    );
    ach.addAsyncHandler(handler);
    return this;
  }
 
  addInlineHandler({ t, term, a, action, o, orient }, handler) {
    _validateHandler(handler);
    const ach = _addACHandler(
      this,
      this._handlers,
      this._leaves,
      this._wildcards,
      _cleanAC({ t, term, a, action, o, orient })
    );
    ach.addInlineHandler(handler);
    return this;
  }
 
  removeHandler({ t, term, a, action, o, orient }, handler, type) {
    const ac = _cleanAC({ t, term, a, action, o, orient });
    Eif (type) {
      _removeHandler(this._handlers, ac, handler, type);
    } else {
      for (let t of [INTERCEPT, ASYNC, INLINE]) {
        _removeHandler(this._handlers, ac, handler, t);
      }
    }
    return this;
  }
 
  removeInterceptHandler({ t, term, a, action, o, orient }, handler) {
    _removeHandler(
      this._handlers,
      _cleanAC({ t, term, a, action, o, orient }),
      handler,
      INTERCEPT
    );
    return this;
  }
 
  removeAsyncHandler({ t, term, a, action, o, orient }, handler) {
    _removeHandler(
      this._handlers,
      _cleanAC({ t, term, a, action, o, orient }),
      handler,
      ASYNC
    );
    return this;
  }
 
  removeInlineHandler({ t, term, a, action, o, orient }, handler) {
    _removeHandler(
      this._handlers,
      _cleanAC({ t, term, a, action, o, orient }),
      handler,
      INLINE
    );
    return this;
  }
}