From 5ff33b7ac3efa450194c0d641253ed9e03f2c4e3 Mon Sep 17 00:00:00 2001 From: Bradley Matusiak Date: Sat, 25 Nov 2023 18:54:46 -0500 Subject: [PATCH] WS ws.path fix (#1343) * Update wire.js * Update wire.js * Update wire.js --- lib/wire.js | 42 +++++++++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 17 deletions(-) diff --git a/lib/wire.js b/lib/wire.js index fcc78995..870976e3 100644 --- a/lib/wire.js +++ b/lib/wire.js @@ -49,35 +49,43 @@ 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; - } - + } 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) { + this.to.next(root); + 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 +});