summaryrefslogtreecommitdiff
path: root/cli/js/dispatch_json.ts
blob: 63789044cb4722eaed4abe17521b13101c3c6c4f (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
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as util from "./util.ts";
import { TextEncoder, TextDecoder } from "./text_encoding.ts";
import { core } from "./core.ts";
import { OPS_CACHE } from "./runtime.ts";
import { ErrorKind, getErrorClass } from "./errors.ts";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Ok = any;

interface JsonError {
  kind: ErrorKind;
  message: string;
}

interface JsonResponse {
  ok?: Ok;
  err?: JsonError;
  promiseId?: number; // Only present in async messages.
}

const promiseTable = new Map<number, util.Resolvable<JsonResponse>>();
let _nextPromiseId = 1;

function nextPromiseId(): number {
  return _nextPromiseId++;
}

function decode(ui8: Uint8Array): JsonResponse {
  const s = new TextDecoder().decode(ui8);
  return JSON.parse(s) as JsonResponse;
}

function encode(args: object): Uint8Array {
  const s = JSON.stringify(args);
  return new TextEncoder().encode(s);
}

function unwrapResponse(res: JsonResponse): Ok {
  if (res.err != null) {
    throw new (getErrorClass(res.err.kind))(res.err.message);
  }
  util.assert(res.ok != null);
  return res.ok;
}

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

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

export function sendSync(
  opName: string,
  args: object = {},
  zeroCopy?: Uint8Array
): Ok {
  const opId = OPS_CACHE[opName];
  util.log("sendSync", opName, opId);
  const argsUi8 = encode(args);
  const resUi8 = core.dispatch(opId, argsUi8, zeroCopy);
  util.assert(resUi8 != null);

  const res = decode(resUi8);
  util.assert(res.promiseId == null);
  return unwrapResponse(res);
}

export async function sendAsync(
  opName: string,
  args: object = {},
  zeroCopy?: Uint8Array
): Promise<Ok> {
  const opId = OPS_CACHE[opName];
  util.log("sendAsync", opName, opId);
  const promiseId = nextPromiseId();
  args = Object.assign(args, { promiseId });
  const promise = util.createResolvable<Ok>();

  const argsUi8 = encode(args);
  const buf = core.dispatch(opId, argsUi8, zeroCopy);
  if (buf) {
    // Sync result.
    const res = decode(buf);
    promise.resolve(res);
  } else {
    // Async result.
    promiseTable.set(promiseId, promise);
  }

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