All files / packages/tao/src Kernel.js

92% Statements 69/75
94.74% Branches 36/38
87.1% Functions 27/31
91.55% Lines 65/71
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                                28x 144x                     56x 42x 42x   41x 26x 26x 41x   56x 73x         90x 90x 45x                                                       21x   2x     19x   15x     36x                           22x 56x 23x   35x   25x 36x         88x 19x   38x 50x   16x   47x 19x         35x       70x         32x         36x         32x           5x       16x 16x 28x 35x 33x 32x 93x               91x 18x               22x 20x 6x 1x           1x     14x         21x       19x       20x 18x       79x 77x       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 Network from './Network';
import AppCtxRoot from './AppCtxRoot';
import AppCtx from './AppCtx';
// import AppCtxHandlers from './AppCtxHandlers';
import { isIterable, concatIterables, _cleanAC } from './utils';
 
function _removeHandlers(network, acList, handlers, type) {
  handlers.forEach(handler =>
    acList.forEach(ac => network.removeHandler(ac, handler, type))
  );
}
 
function _createPromiseHandler(
  network,
  acList,
  promiseFn,
  timeoutHook,
  handlerType
) {
  let owner = this;
  if (!owner.handlers) {
    owner.handlers = [];
  }
  const acHandler = (ac, data) => {
    timeoutHook && timeoutHook();
    _removeHandlers(network, acList, owner.handlers, handlerType);
    promiseFn({ tao: ac, data });
  };
  owner.handlers.push(acHandler);
  return acHandler;
}
 
export default class Kernel {
  constructor(canSetWildcard = false) {
    this._network = new Network();
    this._network.use(this.handleAppCon);
    this._canSetWildcard = canSetWildcard;
  }
 
  get canSetWildcard() {
    return this._canSetWildcard;
  }
 
  clone(canSetWildcard) {
    const cloned = new Kernel(
      typeof canSetWildcard !== 'undefined'
        ? canSetWildcard
        : this._canSetWildcard
    );
    cloned._network = this._network.clone();
    return cloned;
  }
 
  /**
   * What if a Channel is a separate thing that operates a Kernel and uses bridges to the
   * main signal network which is the Kernel from which the Channel is made?
   *
   * @returns
   * @memberof Kernel
   */
  channel(id, bridge) {
    const network = this;
    const channel = new Kernel();
    // QQQ: does this mean Kernel has to keep track of all bridges?
    let debridge = network.inlineBridge(
      channel,
      control => control.channelId === id,
      bridge
    );
    return {
      setCtx({ t, a, o }, data) {
        network.setAppCtxControl(new AppCtx(t, a, o, data), { channelId: id });
      },
      dispose() {
        debridge();
      }
    };
 
    // const channelled = new Kernel();
    // channelled._handlers = this._handlers;
    // channelled._leaves = this._leaves;
    // channelled._wildcards = this._wildcards;
    // channelled._canSetWildcard = this._canSetWildcard;
    // return channelled;
  }
 
  setCtx({ t, term, a, action, o, orient }, data) {
    // get the hash for the ac
    const acIn = _cleanAC({ t, term, a, action, o, orient });
    const isWild = AppCtxRoot.isWildcard(acIn);
    if (!this._canSetWildcard && isWild) {
      // Ignore or Throw Error?
      return;
    }
    this._network.setCtxControl(acIn, data, {}, (ac, control) =>
      this.forwardAppCtx(ac, control)
    );
  }
 
  setAppCtx(appCtx) {
    if (!(appCtx instanceof AppCtx)) {
      throw new Error(`'appCtx' not an instance of AppCtx`);
    }
    const isWild = appCtx.isWildcard;
    if (!this._canSetWildcard && isWild) {
      // Ignore or Throw Error?
      return;
    }
    this._network.setAppCtxControl(appCtx, {}, (ac, control) =>
      this.forwardAppCtx(ac, control)
    );
  }
 
  forwardAppCtx(ac, control) {
    this.setAppCtx(ac, control);
  }
 
  handleAppCon(handler, ac, forwardAppCtx, control) {
    return handler.handleAppCon(ac, forwardAppCtx, control);
  }
 
  asPromiseHook({ resolveOn = [], rejectOn = [] }, timeoutMs = 0) {
    // return this._network.asPromiseHook({ resolveOn, rejectOn }, timeoutMs);
    const resolvers = isIterable(resolveOn)
      ? resolveOn
      : resolveOn
      ? [resolveOn]
      : [];
    const rejectors = isIterable(rejectOn)
      ? rejectOn
      : rejectOn
      ? [rejectOn]
      : [];
    if (
      !resolvers.length &&
      !resolvers.size &&
      !rejectors.length &&
      !rejectors.size
    ) {
      throw new Error(
        'asPromiseHook must be provided with a way to settle the Promise: `resolveOn` or `rejectOn` must have a value'
      );
    }
    const allAcs = concatIterables(resolvers, rejectors);
    return ({ t, term, a, action, o, orient }, data) =>
      new Promise((resolve, reject) => {
        let to = null;
        const clearTO = () => to && clearTimeout(to);
        const handlerOwner = {};
        const resolveHandler = _createPromiseHandler.call(
          handlerOwner,
          this._network,
          allAcs,
          resolve,
          clearTO,
          INLINE
        );
        resolvers.forEach(ac => this.addInlineHandler(ac, resolveHandler));
        const rejectHandler = _createPromiseHandler.call(
          handlerOwner,
          this._network,
          allAcs,
          reject,
          clearTO,
          INLINE
        );
        rejectors.forEach(ac => this.addInlineHandler(ac, rejectHandler));
        if (timeoutMs > 0) {
          to = setTimeout(() => {
            _removeHandlers(
              this._network,
              allAcs,
              handlerOwner.handlers,
              INLINE
            );
            reject(TIMEOUT_REJECT);
          }, timeoutMs);
        }
        this.setCtx({ t, term, a, action, o, orient }, data);
      });
  }
 
  addInterceptHandler({ t, term, a, action, o, orient }, handler) {
    this._network.addInterceptHandler(
      { t, term, a, action, o, orient },
      handler
    );
    return this;
  }
 
  addAsyncHandler({ t, term, a, action, o, orient }, handler) {
    this._network.addAsyncHandler({ t, term, a, action, o, orient }, handler);
    return this;
  }
 
  addInlineHandler({ t, term, a, action, o, orient }, handler) {
    this._network.addInlineHandler({ t, term, a, action, o, orient }, handler);
    return this;
  }
 
  removeInterceptHandler({ t, term, a, action, o, orient }, handler) {
    this._network.removeInterceptHandler(
      { t, term, a, action, o, orient },
      handler
    );
    return this;
  }
 
  removeAsyncHandler({ t, term, a, action, o, orient }, handler) {
    this._network.removeAsyncHandler(
      { t, term, a, action, o, orient },
      handler
    );
    return this;
  }
 
  removeInlineHandler({ t, term, a, action, o, orient }, handler) {
    this._network.removeInlineHandler(
      { t, term, a, action, o, orient },
      handler
    );
    return this;
  }
}