1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-13 19:12:20 -05:00
denoland-deno/cli/js/ops/dispatch_json.ts

95 lines
2.3 KiB
TypeScript
Raw Normal View History

2020-01-02 15:13:47 -05:00
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
2020-07-06 21:45:39 -04:00
import * as util from "../util.ts";
import { core } from "../core.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.
}
// Using an object without a prototype because `Map` was causing GC problems.
2020-07-06 21:45:39 -04:00
const promiseTable: Record<
number,
util.Resolvable<JsonResponse>
> = Object.create(null);
let _nextPromiseId = 1;
function nextPromiseId(): number {
return _nextPromiseId++;
}
function decode(ui8: Uint8Array): JsonResponse {
2020-07-06 21:45:39 -04:00
return JSON.parse(core.decode(ui8));
}
function encode(args: object): Uint8Array {
2020-07-06 21:45:39 -04:00
return core.encode(JSON.stringify(args));
}
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[res.promiseId!];
util.assert(promise != null);
delete promiseTable[res.promiseId!];
promise.resolve(res);
}
export function sendSync(
2020-02-25 09:14:27 -05:00
opName: string,
args: object = {},
...zeroCopy: Uint8Array[]
): Ok {
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);
}
export async function sendAsync(
2020-02-25 09:14:27 -05:00
opName: string,
args: object = {},
...zeroCopy: Uint8Array[]
): Promise<Ok> {
util.log("sendAsync", opName);
const promiseId = nextPromiseId();
args = Object.assign(args, { promiseId });
const promise = util.createResolvable<Ok>();
const argsUi8 = encode(args);
const buf = core.dispatchByName(opName, argsUi8, ...zeroCopy);
2020-07-06 21:45:39 -04:00
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);
}