syndicate-js/examples/example-simple-chat/src/wsRelay.ts

48 lines
2.1 KiB
TypeScript

/// SPDX-License-Identifier: GPL-3.0-or-later
/// SPDX-FileCopyrightText: Copyright © 2016-2021 Tony Garnock-Jones <tonyg@leastfixedpoint.com>
import { Ref, Relay, Turn, Supervisor, SupervisorRestartPolicy } from "@syndicate-lang/core";
import * as G from "./gen/wsRelay";
export * from "./gen/wsRelay";
export function boot(ds: Ref) {
spawn named 'wsRelay' {
at ds {
during G.ViaRelay({ "addr": $addrValue }) => spawn named ['wsRelay', addrValue] {
let counter = 0;
new Supervisor({
restartPolicy: SupervisorRestartPolicy.ALWAYS,
}, () => ['wsRelay', addrValue, counter++], () => {
const facet = Turn.activeFacet;
facet.preventInertCheck();
const addr = G.toRelayAddress(addrValue);
if (addr !== void 0) {
const ws = new WebSocket(addr.url);
ws.binaryType = 'arraybuffer';
ws.onclose = () => facet.turn(() => { stop {} });
ws.onerror = () => facet.turn(() =>
Turn.active.crash(new Error("WebSocket error")));
ws.onopen = () => facet.turn(() => {
const relay = new Relay.Relay({
debug: true,
trustPeer: true,
packetWriter: bs => ws.send(bs),
setup(r: Relay.Relay) {
ws.onmessage = e => facet.turn(() =>
r.accept(new Uint8Array(e.data)));
},
initialOid: 0,
});
during G.ViaRelay({ "addr": addrValue, "assertion": $a }) => {
at relay.peer! {
assert a;
}
}
});
}
});
}
}
}
}