relay/src/relay.ts

73 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-06-27 17:53:00 +00:00
// @ts-ignore
import DHT from "@hyperswarm/dht";
// @ts-ignore
2022-07-19 22:31:15 +00:00
import { relay } from "@hyperswarm/dht-relay";
2022-06-27 17:53:00 +00:00
// @ts-ignore
import Stream from "@hyperswarm/dht-relay/ws";
2022-07-19 22:31:15 +00:00
import express, { Express } from "express";
2022-07-05 19:02:07 +00:00
import config from "./config.js";
import * as http from "http";
import * as https from "https";
2022-07-19 22:31:15 +00:00
import { get as getDHT } from "./dht.js";
import WS from "ws";
// @ts-ignore
2022-07-24 00:24:19 +00:00
import log from "loglevel";
import { AddressInfo } from "net";
// @ts-ignore
import promiseRetry from "promise-retry";
import { getSslContext } from "./ssl.js";
2022-06-27 21:52:20 +00:00
export async function start() {
2022-07-26 00:35:21 +00:00
const relayPort = config.uint("port");
2022-07-19 22:31:15 +00:00
const dht = await getDHT();
2022-06-27 17:53:00 +00:00
const statusCodeServer = http.createServer(function (req, res) {
// @ts-ignore
res.writeHead(req.headers["x-status"] ?? 200, {
"Content-Type": "text/plain",
});
res.end();
});
await new Promise((resolve) => {
statusCodeServer.listen(25252, "0.0.0.0", function () {
const address = statusCodeServer.address() as AddressInfo;
log.info(
"Status Code Server started on ",
`${address.address}:${address.port}`
);
resolve(null);
});
});
let relayServer: https.Server | http.Server;
if (config.bool("ssl")) {
relayServer = https.createServer({
SNICallback(servername, cb) {
cb(null, getSslContext());
},
});
} else {
relayServer = http.createServer();
}
let wsServer = new WS.Server({ server: relayServer });
wsServer.on("connection", (socket: any) => {
relay(dht, new Stream(false, socket));
});
await new Promise((resolve) => {
relayServer.listen(relayPort, "0.0.0.0", function () {
const address = relayServer.address() as AddressInfo;
log.info(
"DHT Relay Server started on ",
`${address.address}:${address.port}`
);
resolve(null);
});
});
}