Skip to content

Commit

Permalink
Protocol wire-tapping.
Browse files Browse the repository at this point in the history
  • Loading branch information
molefrog committed May 23, 2023
1 parent e15d964 commit 4767d25
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
12 changes: 8 additions & 4 deletions src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

export const VERSION = "0";

export const ALL: unique symbol = Symbol.for("*");

// node with higher ID wins the election (must be unique and comparable)
export type ID = string;

Expand Down Expand Up @@ -38,7 +40,7 @@ export interface Channel {
}

export type CreateChannel = (
id: ID,
id: ID | typeof ALL,
options?: { version: string },
) => Channel;

Expand All @@ -49,25 +51,27 @@ export type CreateChannel = (
* @returns a newly created Channel
*/
export const multicast: CreateChannel = (
id: ID,
id,
options: { version: string } = { version: VERSION },
) => {
const bcast = new BroadcastChannel(`use-leader_${options.version}`);
const wiretap = id === ALL; // can listen to everyone's messages

return {
emit(params) {
const message: Message = Object.assign(
{ ver: options.version, snd: id },
{ ver: options.version, snd: String(id) },
params,
);

bcast.postMessage(message);
},

listen(fn) {
const handler = ({ data: msg }: MessageEvent<Message>) => {
if (typeof msg !== "object") return;
// this message is for someone else, ignoring
if (msg.rcv && msg.rcv !== id) return;
if (!wiretap && msg.rcv && msg.rcv !== id) return;

fn(msg);
};
Expand Down
16 changes: 7 additions & 9 deletions web/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useState } from "preact/hooks";
import { nanoid } from "nanoid";

import { useLeader } from "../src/use-leader.ts";
import { multicast, ALL } from "../src/protocol.ts";

const IAmLeader = ({ leader = null }) => {
const Label = () => {
Expand Down Expand Up @@ -100,23 +101,20 @@ const App = () => {
};

/** Logger */
const bcast = new BroadcastChannel(`use-leader_0`);
bcast.onmessage = (e) => {
const { snd, evt, rcv } = e.data;

const channel = multicast(ALL);

channel.listen(({ snd, evt, rcv }) => {
const translate = {
"πŸ™‹β€": "elect",
"πŸ™…β€": "disag",
"πŸ¦Έβ€": "leadr",
"πŸ’€": "xdead",
};

if (rcv) {
console.log(`${evt} ${snd} -> ${rcv} :: ${translate[evt]} `);
} else {
console.log(`${evt} ${snd} :: ${translate[evt]}`);
}
};
const transfer = [snd, rcv].filter(Boolean).join(" -> ");
console.log(`${evt} ${transfer} :: ${translate[evt]} `);
});

/** mono screen utils */
const WIDTH = 40;
Expand Down

0 comments on commit 4767d25

Please sign in to comment.