From 22a23806cf5c93e74131ecf1f7c973cdc803cc8f Mon Sep 17 00:00:00 2001 From: Bradley Matusiak Date: Thu, 23 Nov 2023 19:21:09 -0500 Subject: [PATCH] Update wire.js --- lib/wire.js | 41 +++++++++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/lib/wire.js b/lib/wire.js index fcc78995..90e2f13d 100644 --- a/lib/wire.js +++ b/lib/wire.js @@ -49,35 +49,44 @@ var Gun = require('../gun'); */ -Gun.on('opt', function(root){ +Gun.on('opt', function (root) { var opt = root.opt; - if(false === opt.ws || opt.once){ + if (false === opt.ws || opt.once) { this.to.next(root); return; - } + } + var url = require('url'); opt.mesh = opt.mesh || Gun.Mesh(root); opt.WebSocket = opt.WebSocket || require('ws'); var ws = opt.ws = opt.ws || {}; ws.path = ws.path || '/gun'; // if we DO need an HTTP server, then choose ws specific one or GUN default one. - if(!ws.noServer){ - ws.server = ws.server || opt.web; - if(!ws.server){ this.to.next(root); return } // ugh, bug fix for @jamierez & unstoppable ryan. + if (!opt.web || ws.noServer) { + return;// no server no sockets } - ws.web = ws.web || new opt.WebSocket.Server(ws); // we still need a WS server. - ws.web.on('connection', function(wire, req){ var peer; - wire.headers = wire.headers || (req||'').headers || ''; + ws.noServer = true;//workaround for ws.path + ws.web = ws.web || new opt.WebSocket.Server(ws); + opt.web.on('upgrade', (req, socket, head) => { + if (req.url == ws.path) { + ws.web.handleUpgrade(req, socket, head, function done(ws) { + open(ws, req); + }); + } + }); + function open(wire, req) { + var peer; + wire.headers = wire.headers || (req || '').headers || ''; console.STAT && ((console.STAT.sites || (console.STAT.sites = {}))[wire.headers.origin] = 1); - opt.mesh.hi(peer = {wire: wire}); - wire.on('message', function(msg){ + opt.mesh.hi(peer = { wire: wire }); + wire.on('message', function (msg) { opt.mesh.hear(msg.data || msg, peer); }); - wire.on('close', function(){ + wire.on('close', function () { opt.mesh.bye(peer); }); - wire.on('error', function(e){}); - setTimeout(function heart(){ if(!opt.peers[peer.id]){ return } try{ wire.send("[]") }catch(e){} ;setTimeout(heart, 1000 * 20) }, 1000 * 20); // Some systems, like Heroku, require heartbeats to not time out. // TODO: Make this configurable? // TODO: PERF: Find better approach than try/timeouts? - }); + wire.on('error', function (e) { }); + setTimeout(function heart() { if (!opt.peers[peer.id]) { return } try { wire.send("[]") } catch (e) { }; setTimeout(heart, 1000 * 20) }, 1000 * 20); // Some systems, like Heroku, require heartbeats to not time out. // TODO: Make this configurable? // TODO: PERF: Find better approach than try/timeouts? + } this.to.next(root); -}); \ No newline at end of file +});