diff options
author | Ryan Dahl <ry@tinyclouds.org> | 2018-07-06 11:20:35 -0400 |
---|---|---|
committer | Ryan Dahl <ry@tinyclouds.org> | 2018-07-06 12:22:11 -0400 |
commit | fe404dfce901356dc7a5d38ba70029c72a946f27 (patch) | |
tree | b8ed0d3417e920da1fd4e6278046184d8205a237 /js/dispatch.ts | |
parent | 21e1425656ccebb8d31da95acd83991fb7d728fd (diff) |
Import ts file from prototype without change
From commit 559453cf6cc88283bcf8fdeccd387458f5c63165
Excluding v8worker.d.ts, main.ts, and deno.d.ts.
Updates tslint.json to be original settings.
Diffstat (limited to 'js/dispatch.ts')
-rw-r--r-- | js/dispatch.ts | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/js/dispatch.ts b/js/dispatch.ts new file mode 100644 index 000000000..a83e5a0e5 --- /dev/null +++ b/js/dispatch.ts @@ -0,0 +1,73 @@ +// Copyright 2018 Ryan Dahl <ry@tinyclouds.org> +// All rights reserved. MIT License. +import { typedArrayToArrayBuffer } from "./util"; +import { _global } from "./globals"; +import { deno as pb } from "./msg.pb"; + +export type MessageCallback = (msg: Uint8Array) => void; +//type MessageStructCallback = (msg: pb.IMsg) => void; + +const send = V8Worker2.send; +const channels = new Map<string, MessageCallback[]>(); + +export function sub(channel: string, cb: MessageCallback): void { + let subscribers = channels.get(channel); + if (!subscribers) { + subscribers = []; + channels.set(channel, subscribers); + } + subscribers.push(cb); +} + +/* +export function subMsg(channel: string, cb: MessageStructCallback): void { + sub(channel, (payload: Uint8Array) => { + const msg = pb.Msg.decode(payload); + if (msg.error != null) { + f.onError(new Error(msg.error)); + } else { + cb(msg); + } + }); +} + */ + +export function pub(channel: string, payload: Uint8Array): null | ArrayBuffer { + const msg = pb.BaseMsg.fromObject({ channel, payload }); + const ui8 = pb.BaseMsg.encode(msg).finish(); + const ab = typedArrayToArrayBuffer(ui8); + return send(ab); +} + +// Internal version of "pub". +// TODO add internal version of "sub" +export function pubInternal(channel: string, obj: pb.IMsg): null | pb.Msg { + const msg = pb.Msg.fromObject(obj); + const ui8 = pb.Msg.encode(msg).finish(); + const resBuf = pub(channel, ui8); + if (resBuf != null && resBuf.byteLength > 0) { + const res = pb.Msg.decode(new Uint8Array(resBuf)); + if (res != null && res.error != null && res.error.length > 0) { + throw Error(res.error); + } + return res; + } else { + return null; + } +} + +V8Worker2.recv((ab: ArrayBuffer) => { + const msg = pb.BaseMsg.decode(new Uint8Array(ab)); + const subscribers = channels.get(msg.channel); + if (subscribers == null) { + throw Error(`No subscribers for channel "${msg.channel}".`); + } + + for (const subscriber of subscribers) { + subscriber(msg.payload); + } +}); + +// Delete the V8Worker2 from the global object, so that no one else can receive +// messages. +_global["V8Worker2"] = null; |