summaryrefslogtreecommitdiff
path: root/cli/tsc/10_dispatch_json.js
blob: 7989f556834283058916b69a1ca09ec4c1f4c692 (plain)
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
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

((window) => {
  const core = window.Deno.core;
  const util = window.__bootstrap.util;

  // Using an object without a prototype because `Map` was causing GC problems.
  const promiseTable = Object.create(null);
  let _nextPromiseId = 1;

  function nextPromiseId() {
    return _nextPromiseId++;
  }

  function decode(ui8) {
    return JSON.parse(core.decode(ui8));
  }

  function encode(args) {
    return core.encode(JSON.stringify(args));
  }

  function unwrapResponse(res) {
    if (res.err != null) {
      throw new (core.getErrorClass(res.err.className))(res.err.message);
    }
    util.assert(res.ok != null);
    return res.ok;
  }

  function asyncMsgFromRust(resUi8) {
    const res = decode(resUi8);
    util.assert(res.promiseId != null);

    const promise = promiseTable[res.promiseId];
    util.assert(promise != null);
    delete promiseTable[res.promiseId];
    promise.resolve(res);
  }

  function sendSync(
    opName,
    args = {},
    ...zeroCopy
  ) {
    util.log("sendSync", opName);
    const argsUi8 = encode(args);
    const resUi8 = core.dispatchByName(opName, argsUi8, ...zeroCopy);
    util.assert(resUi8 != null);
    const res = decode(resUi8);
    util.assert(res.promiseId == null);
    return unwrapResponse(res);
  }

  async function sendAsync(
    opName,
    args = {},
    ...zeroCopy
  ) {
    util.log("sendAsync", opName);
    const promiseId = nextPromiseId();
    args = Object.assign(args, { promiseId });
    const promise = util.createResolvable();
    const argsUi8 = encode(args);
    const buf = core.dispatchByName(opName, argsUi8, ...zeroCopy);
    if (buf != null) {
      // Sync result.
      const res = decode(buf);
      promise.resolve(res);
    } else {
      // Async result.
      promiseTable[promiseId] = promise;
    }

    const res = await promise;
    return unwrapResponse(res);
  }

  window.__bootstrap.dispatchJson = {
    asyncMsgFromRust,
    sendSync,
    sendAsync,
  };
})(this);