*Implement a protocol manager to register protomux based protocols and add it to the plugin api

This commit is contained in:
Derrick Hammer 2022-12-30 01:00:45 -05:00
parent 90ef9e3386
commit 1b78d0e696
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
2 changed files with 53 additions and 1 deletions

View File

@ -13,7 +13,11 @@ import pluginCore from "./plugins/core";
import type Config from "@lumeweb/cfg"; import type Config from "@lumeweb/cfg";
import EventEmitter2 from "eventemitter2"; import EventEmitter2 from "eventemitter2";
import log from "../log.js"; import log from "../log.js";
import { get as getSwarm } from "./swarm.js"; import {
get as getSwarm,
getProtocolManager,
ProtocolManager,
} from "./swarm.js";
import { get as getSSl, SSLManager } from "./ssl.js"; import { get as getSSl, SSLManager } from "./ssl.js";
import type { HDKey } from "micro-ed25519-hdkey"; import type { HDKey } from "micro-ed25519-hdkey";
@ -86,6 +90,10 @@ class PluginAPI extends EventEmitter2 {
return getSSl(); return getSSl();
} }
get protocols(): ProtocolManager {
return getProtocolManager();
}
public loadPlugin( public loadPlugin(
moduleName: string moduleName: string
): (moduleName: string) => Promise<Plugin> { ): (moduleName: string) => Promise<Plugin> {

View File

@ -5,6 +5,8 @@
import Hyperswarm from "hyperswarm"; import Hyperswarm from "hyperswarm";
// @ts-ignore // @ts-ignore
import DHT from "@hyperswarm/dht"; import DHT from "@hyperswarm/dht";
// @ts-ignore
import Protomux from "protomux";
// @ts-ignore // @ts-ignore
import sodium from "sodium-universal"; import sodium from "sodium-universal";
@ -20,6 +22,7 @@ sodium.crypto_generichash(LUMEWEB_TOPIC_HASH, LUMEWEB);
export type SecretStream = any; export type SecretStream = any;
let node: Hyperswarm; let node: Hyperswarm;
let protocolManager: ProtocolManager;
export async function start() { export async function start() {
const keyPair = getKeyPair(); const keyPair = getKeyPair();
@ -51,3 +54,44 @@ export async function start() {
export function get(): Hyperswarm { export function get(): Hyperswarm {
return node; return node;
} }
export class ProtocolManager {
private _protocols: Map<string, Function> = new Map<string, Function>();
private _swarm;
constructor(swarm: any) {
this._swarm = swarm;
this._swarm.on("connection", (peer: any) => {
for (const protocol of this._protocols) {
Protomux.from(peer).pair(
protocol[0],
this.handler.bind(this, protocol[0], peer)
);
}
});
}
private handler(protocol: string, peer: any) {
if (this._protocols.has(protocol)) {
this._protocols.get(protocol)?.(peer, Protomux.from(peer));
}
}
public register(name: string, handler: Function): boolean {
if (this._protocols.has(name)) {
return false;
}
this._protocols.set(name, handler);
return true;
}
}
export function getProtocolManager(): ProtocolManager {
if (!protocolManager) {
protocolManager = new ProtocolManager(get());
}
return protocolManager;
}