1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-25 08:39:09 -05:00
denoland-deno/js/dispatch.ts

90 lines
2.2 KiB
TypeScript
Raw Normal View History

2019-01-21 14:03:30 -05:00
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { core } from "./core";
import * as flatbuffers from "./flatbuffers";
import * as msg from "gen/cli/msg_generated";
import * as errors from "./errors";
import * as util from "./util";
let nextCmdId = 0;
2018-10-03 21:18:23 -04:00
const promiseTable = new Map<number, util.Resolvable<msg.Base>>();
export function handleAsyncMsgFromRust(ui8: Uint8Array): void {
const bb = new flatbuffers.ByteBuffer(ui8);
const base = msg.Base.getRootAsBase(bb);
const cmdId = base.cmdId();
const promise = promiseTable.get(cmdId);
util.assert(promise != null, `Expecting promise in table. ${cmdId}`);
promiseTable.delete(cmdId);
const err = errors.maybeError(base);
if (err != null) {
promise!.reject(err);
} else {
promise!.resolve(base);
}
}
function sendInternal(
builder: flatbuffers.Builder,
innerType: msg.Any,
inner: flatbuffers.Offset,
zeroCopy: undefined | ArrayBufferView,
sync = true
): [number, null | Uint8Array] {
const cmdId = nextCmdId++;
const message = msg.Base.createBase(
builder,
cmdId,
sync,
0,
0,
innerType,
inner
);
builder.finish(message);
const control = builder.asUint8Array();
const response = core.dispatch(control, zeroCopy);
builder.inUse = false;
return [cmdId, response];
}
// @internal
export function sendAsync(
builder: flatbuffers.Builder,
2018-10-03 21:18:23 -04:00
innerType: msg.Any,
inner: flatbuffers.Offset,
data?: ArrayBufferView
2018-10-03 21:18:23 -04:00
): Promise<msg.Base> {
const [cmdId, response] = sendInternal(
builder,
innerType,
inner,
data,
false
);
util.assert(response == null);
2018-10-03 21:18:23 -04:00
const promise = util.createResolvable<msg.Base>();
promiseTable.set(cmdId, promise);
return promise;
}
// @internal
export function sendSync(
builder: flatbuffers.Builder,
2018-10-03 21:18:23 -04:00
innerType: msg.Any,
inner: flatbuffers.Offset,
data?: ArrayBufferView
2018-10-03 21:18:23 -04:00
): null | msg.Base {
const [cmdId, response] = sendInternal(builder, innerType, inner, data, true);
util.assert(cmdId >= 0);
if (response == null || response.length === 0) {
return null;
} else {
const bb = new flatbuffers.ByteBuffer(response);
2018-10-03 21:18:23 -04:00
const baseRes = msg.Base.getRootAsBase(bb);
errors.maybeThrowError(baseRes);
return baseRes;
}
}