All files / packages/tao-utils/src Transceiver.js

3% Statements 3/100
0% Branches 0/55
0% Functions 0/24
3% Lines 3/100
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      1x   1x         1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
import { Network } from '@tao.js/core';
 
// for backwards compatibility
const MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
 
let transceiverId = 0;
function newTransceiverId() {
  return (transceiverId = ++transceiverId % MAX_SAFE_INTEGER);
}
 
let signalId = 0;
function newSignalId() {
  return (signalId = ++signalId % MAX_SAFE_INTEGER);
}
 
function transceiverControl(transceiverId, resolve, reject) {
  return { transceiverId, signal: { id: newSignalId(), resolve, reject } };
}
 
/**
 * Like a Transponder, a Transceiver converts Signals on a Network to Promises.
 * Unlike a Transponder, a Transceiver allows the handlers attached to it to control
 * the behavior of the Promise.
 *
 * If a Handler returns an AppCtx, then it will be chained like a standard handler.
 *
 * If a Handler returns something other than an AppCtx it will behave as the following:
 * - returning truthy value from an InterceptHandler will REJECT the Promise
 * - returning any value not `null` or `undefined` from an AsyncHandler or InlineHandler
 *   it will be used to RESOLVE the Promise
 * - throwing an Error in any Handler will REJECT the Promise
 *
 * A signal to a Promise can only happen once, so the first thing that happens
 * will conclude the Promise despite other handlers that may be continue to be
 * called depending on how you set up your Handlers
 *
 * @export
 * @class Transceiver
 */
export default class Transceiver {
  constructor(network, id, timeoutMs = 0, promise = Promise) {
    this._transceiverId =
      typeof id === 'function'
        ? id(newTransceiverId())
        : id || newTransceiverId();
    this._signals = new Network();
    this._signals.use(this.handleSignalAppCon);
    this._network =
      typeof network.use === 'function' ? network : network._network;
    this._timeoutMs = timeoutMs;
    this._promise = promise;
    this._cloneWithId = typeof id === 'function' ? id : undefined;
  }
 
  setCtx = ({ t, term, a, action, o, orient }, data) => {
    const transceiverId = this._transceiverId;
    const timeoutMs = this._timeoutMs;
    const promise = this._promise;
 
    return new promise((resolve, reject) => {
      if (timeoutMs) {
        setTimeout(() => {
          reject(`reached timeout of: ${timeoutMs}ms`);
        }, timeoutMs);
      }
      this._network.setCtxControl(
        { t, term, a, action, o, orient },
        data,
        transceiverControl(transceiverId, resolve, reject),
        this.forwardAppCtx
      );
    });
  };
 
  setAppCtx = ac => {
    const transceiverId = this._transceiverId;
    const timeoutMs = this._timeoutMs;
    const promise = this._promise;
 
    return new promise((resolve, reject) => {
      if (timeoutMs) {
        setTimeout(() => {
          reject(`reached timeout of: ${timeoutMs}ms`);
        }, timeoutMs);
      }
      this._network.setAppCtxControl(
        ac,
        transceiverControl(transceiverId, resolve, reject),
        this.forwardAppCtx
      );
    });
  };
 
  forwardAppCtx = (ac, control) => {
    if (control.transceiverId === this._transceiverId) {
      this._signals.setAppCtxControl(ac, control, this.forwardAppCtx);
    }
    this._network.setAppCtxControl(ac, control, this.forwardAppCtx);
  };
 
  handleSignalAppCon = (handler, ac, forwardAppCtx, control) => {
    if (
      control.transceiverId === this._transceiverId &&
      control.signal &&
      !control.signalled
    ) {
      try {
        this.captureSignal(handler, ac, forwardAppCtx, control).catch(
          handleErr => {
            if (!control.signalled) {
              control.signalled = true;
              control.signal.reject(handleErr);
            }
          }
        );
      } catch (handleErr) {
        if (!control.signalled) {
          control.signalled = true;
          control.signal.reject(handleErr);
        }
      }
    }
    // ALERT: handler will have already handled the AppCon before now
    // return handler.handleAppCon(ac, forwardAppCtx, control);
  };
 
  // TODO: refactor AppCtxHandlers to allow an override of behavior
  captureSignal = async (handler, ac, setAppCtx, control) => {
    const { t, a, o, data } = ac;
    /*
     * Intercept Handlers
     * always occur first
     * have the ability to prevent other handlers from firing on this AC
     * optionally can return a single AC that will be set as the new AC instead of the incoming AC
     *
     * If handler returns truthy value that is not an AppCtx then it will
     * be used to REJECT a signal promise that is part of the message
     * control
     */
    for (let interceptH of handler.interceptHandlers) {
      // using the decorator pattern to call these?
      let intercepted = await interceptH({ t, a, o }, data);
      if (!intercepted) {
        continue;
      }
      if (intercepted instanceof AppCtx) {
        try {
          setAppCtx(intercepted, control);
        } catch (interceptErr) {
          if (!control.signalled) {
            control.signalled = true;
            control.signal.reject(interceptErr);
          }
        }
      } else if (!control.signalled) {
        control.signalled = true;
        control.signal.reject(intercepted);
      }
      return;
    }
    /*
     * Async Handlers
     * designed to kick off asynchronous handling of an AC outside of the current
     * control loop
     * fire if all Intercept Handlers don't intercept the fired AC
     * work inside of their own execution context
     * can return an AC that will be set as a context inside the async exec ctx
     * TODO: look into how redux-sagas is implemented and may be a way to use
     * generators instead of Promises
     * TODO: would ServiceWorkers make sense for this? tao-sw package
     *
     * If handler returns anything that is not an AppCtx then it will
     * be used to RESOLVE a signal promise that is part of the message
     * control
     * If handler or chained handlers throw anything then it will be
     * used to REJECT a signal promise that is part of the message
     * control
     */
    for (let asyncH of handler.asyncHandlers) {
      (() => {
        Promise.resolve(asyncH({ t, a, o }, data))
          .then(nextAc => {
            if (nextAc != null) {
              if (nextAc instanceof AppCtx) {
                setAppCtx(nextAc, control);
              } else if (!control.signalled) {
                control.signalled = true;
                control.signal.resolve(nextAc);
              }
            }
          })
          .catch(asyncErr => {
            if (!control.signalled) {
              control.signalled = true;
              control.signal.reject(asyncErr);
            }
          });
      })();
    }
    /*
     * Inline Handlers
     * fire if all Intercept Handlers don't intercept the fired AC
     * fired after all Async handlers are fired off
     * work inside the same execution context as the caller
     * can return an AC that will be set immediately in the TAO
     * TODO: should these returns be spooled up then iterated to allow
     * all handlers to handle this context before any new ones are set?
     * YES: currently implemented that way
     *
     * If handler returns anything that is not an AppCtx then it will
     * be used to RESOLVE a signal promise that is part of the message
     * control
     * If handler or chained handlers throw anything then it will be
     * used to REJECT a signal promise that is part of the message
     * control
     */
    const nextSpool = [];
    let firstResolve = null;
    for (let inlineH of handler.inlineHandlers) {
      let nextInlineAc = await inlineH({ t, a, o }, data);
      if (nextInlineAc != null) {
        if (nextInlineAc instanceof AppCtx) {
          nextSpool.push(nextInlineAc);
        } else if (!firstResolve) {
          firstResolve = nextInlineAc;
        }
      }
    }
    if (!control.signalled && firstResolve) {
      control.signalled = true;
      control.signal.resolve(firstResolve);
    }
    if (nextSpool.length) {
      for (let nextAc of nextSpool) {
        try {
          setAppCtx(nextAc, control);
        } catch (inlineErr) {
          if (!control.signalled) {
            control.signalled = true;
            control.signal.reject(inlineErr);
          }
        }
      }
    }
  };
 
  addSignalHandler = ({ t, term, a, action, o, orient }, handler) => {
    this._signals.addInlineHandler({ t, term, a, action, o, orient }, handler);
  };
 
  addInterceptHandler({ t, term, a, action, o, orient }, handler) {
    this._signals.addInterceptHandler(
      { t, term, a, action, o, orient },
      handler
    );
  }
 
  addAsyncHandler({ t, term, a, action, o, orient }, handler) {
    this._signals.addAsyncHandler({ t, term, a, action, o, orient }, handler);
  }
 
  addInlineHandler({ t, term, a, action, o, orient }, handler) {
    this._signals.addInlineHandler({ t, term, a, action, o, orient }, handler);
  }
 
  removeInterceptHandler({ t, term, a, action, o, orient }, handler) {
    this._signals.removeInterceptHandler(
      { t, term, a, action, o, orient },
      handler
    );
  }
 
  removeAsyncHandler({ t, term, a, action, o, orient }, handler) {
    this._signals.removeAsyncHandler(
      { t, term, a, action, o, orient },
      handler
    );
  }
 
  removeInlineHandler({ t, term, a, action, o, orient }, handler) {
    this._signals.removeInlineHandler(
      { t, term, a, action, o, orient },
      handler
    );
  }
}