Skip to content

Commit

Permalink
Merge branch 'balderdashy:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
CyBot authored Jan 29, 2024
2 parents 82e8a52 + 6aedc51 commit 6a79989
Show file tree
Hide file tree
Showing 11 changed files with 94 additions and 82 deletions.
10 changes: 7 additions & 3 deletions lib/initialize.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,9 @@ module.exports = function ToInitialize(app) {
// Now start socket.io
var io = SocketIO(sailsHttpServer, (function _createOptsObj() {
var opts = {
allowEIO3: true,// Allows support for Engine.io v3 clients.
path: app.config.sockets.path,
wsEngine: 'ws'
wsEngine: require('ws').Server,// [?]: https://socket.io/docs/v4/migrating-from-3-x-to-4-0/#wsengine-option
};
if (typeof app.config.sockets.serveClient !== 'undefined') {
opts.serveClient = app.config.sockets.serveClient;
Expand Down Expand Up @@ -138,7 +139,9 @@ module.exports = function ToInitialize(app) {
opts.cookie = app.config.sockets.cookie;
}
if (app.config.sockets.onlyAllowOrigins) {
opts.origins = function(origin, cb) {
// As of Socket.io v3.X, the origins option was changed to origin, and is now nested in a dictionary named cors.
opts.cors = {};// [?]: https://socket.io/docs/v4/migrating-from-2-x-to-3-0/#cors-handling
opts.cors.origin = function(origin, cb) {
// If the socket's origin is in the `onlyAllowOrigins` array, allow the connection to continue.
if (_.contains(app.config.sockets.onlyAllowOrigins, origin)) {
return cb(null, true);
Expand Down Expand Up @@ -179,7 +182,8 @@ module.exports = function ToInitialize(app) {
});

// Set up event listeners each time a new socket connects
io.on('connect', onConnect);
// Note: as of Socket.io 3.x, this event's name changed ('connect' » 'connection')
io.on('connection', onConnect);


// Expose low-level, generic socket methods as `sails.sockets.*`
Expand Down
13 changes: 7 additions & 6 deletions lib/prepare-adapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ module.exports = function (app){
var prepareDriver = require('./prepare-driver')(app);
var connectToAdminBus = require('./connect-to-admin-bus')(app);

var MINIMUM_SIO_REDIS_VERSION = '5.2.0';
// Latest socket.io-redis version that will create redis clients on behalf of the user.
var MINIMUM_SIO_REDIS_VERSION = '6.0.0';

return function prepareAdapter(cb){

Expand Down Expand Up @@ -113,19 +114,19 @@ module.exports = function (app){

// Initialize the socket.io adapter (e.g. socket.io-redis or @sailshq/socket.io-redis)
var sioAdapter = SocketIOAdapter(adapterConfig);
// See https://github.com/Automattic/socket.io-redis/issues/21#issuecomment-60315678
// Attach the adapter to socket.io.
app.io.adapter(sioAdapter);

// See https://github.com/socketio/socket.io-redis-adapter/issues/21#issuecomment-60334627
try {
sioAdapter.prototype.on('error', function (e){
app.io.of('/').adapter.on('error', function(e){
app.log.verbose('Socket.io adapter emitted error event:',e);
});
}
catch (e) {
app.log.error('Error building socket.io adapter:',e);
}

// Attach the adapter to socket.io.
app.io.adapter(sioAdapter);

// Set up a connection to the admin bus.
var adminAdapterConfig = _.defaults(_.clone(app.config.sockets.adminAdapterOptions), _.omit(app.config.sockets.adapterOptions, 'pubClient', 'subClient'));
return connectToAdminBus({
Expand Down
34 changes: 18 additions & 16 deletions lib/sails.sockets/add-room-members-to-rooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ module.exports = function(app) {

// If we were sent a socket ID as a room name, and the socket happens to
// be connected to this server, take a shortcut
if (app.io.sockets.connected[sourceRoom]) {
return doJoin(app.io.sockets.connected[sourceRoom], cb);
if (app.io.of('/').sockets.has(sourceRoom)) {
doJoin(app.io.of('/').sockets.get(sourceRoom));
return cb();
}

// Broadcast an admin message telling all other connected servers to
Expand All @@ -47,29 +48,30 @@ module.exports = function(app) {


// Look up all members of sourceRoom
return app.io.sockets.in(sourceRoom).clients(function(err, sourceRoomSocketIds) {
if (err) {return cb(err);}
return (function(iifeDone) { app.io.in(sourceRoom).allSockets().then(function(sourceRoomSocketIds) {iifeDone(undefined, sourceRoomSocketIds);}).catch(function(err) { iifeDone(err);});})(function(err, sourceRoomSocketIds) {
if (err) { return cb(err); }
// Loop through the socket IDs from the room
async.each(sourceRoomSocketIds, function(socketId, nextSocketId) {
// Check if the socket is connected to this server (since .clients() may someday work cross-server)
if (app.io.sockets.connected[socketId]) {
sourceRoomSocketIds.forEach(function(socketId) {
// Check if the socket is connected to this server
if (app.io.of('/').sockets.has(socketId)) {
// If so, subscribe it to destRooms
return doJoin(app.io.sockets.connected[socketId], nextSocketId);
doJoin(app.io.of('/').sockets.get(socketId));
}
// If not, just continue
return nextSocketId();
}, cb);
});
});
cb();
});//_∏_

function doJoin(socket, cb) {
return async.each(destRooms, function(destRoom, nextRoom) {

function doJoin(socket) {
destRooms.forEach(function(destRoom) {
// Ensure destRoom is a string
if (!_.isString(destRoom)) {
app.log.warn("Skipping non-string value for room name to add in `addRoomMembersToRooms`: ", destRoom);
return nextRoom();
} else {
socket.join(destRoom);
}
return socket.join(destRoom, nextRoom);
}, cb);
});
}

};
Expand Down
7 changes: 2 additions & 5 deletions lib/sails.sockets/broadcast-to-room.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,11 @@ module.exports = function (app){
roomNames = [roomNames];
}

// Tell the emitter each room to emit to
// Send the broadcast to the specified rooms.
_.each(roomNames, function(roomName) {
emitter.in(roomName);
emitter.to(roomName).emit(eventName, data);
});

// Send the broadcast
emitter.emit(eventName, data);

};

};
2 changes: 1 addition & 1 deletion lib/sails.sockets/get-socket-by-id.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ module.exports = function (app){
}

// Look for a socket with the specified ID in the default namespace
var foundSocket = app.io.sockets.connected[id];
var foundSocket = app.io.of('/').sockets.get(id);
if (!foundSocket) {
throw ERRORPACK.NO_SUCH_SOCKET('Cannot find socket with id=`%s`', id);
}
Expand Down
18 changes: 10 additions & 8 deletions lib/sails.sockets/join-room.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@ module.exports = function(app) {
sockets = [sockets];
}

async.each(sockets, function(socket, nextSocket) {
sockets.forEach((socket)=> {
// If a string was sent, try to look up a socket with that ID
if (typeof socket !== 'object' && socket !== null) {
// If we don't find one, it could be on another server, so use
// the cross-server "addRoomMembersToRooms"
if (!app.io.sockets.connected[socket]) {
return app.sockets.addRoomMembersToRooms(socket, roomName, nextSocket);
if (!app.io.of('/').sockets.has(socket)) {
return app.sockets.addRoomMembersToRooms(socket, roomName);
}
// Otherwise get the socket object and continue
socket = app.io.sockets.connected[socket];
socket = app.io.of('/').sockets.get(socket);
}

// If it's not a valid socket object, bail
Expand All @@ -45,12 +45,14 @@ module.exports = function(app) {
return;
}
// Join up!
socket.join(roomName, nextSocket);

}, cb);
socket.join(roomName);
});

// Call the callback once all sockets have joined
cb();
// The value returned from this function is currently used by the Sails PubSub hook.
// FUTURE: When https://github.com/balderdashy/sails/pull/7311/files is merged, this return value can be removed.
return true;

};

};
30 changes: 15 additions & 15 deletions lib/sails.sockets/leave-all-rooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,26 +44,26 @@ module.exports = function(app) {
}

// Look up all members of sourceRoom
return app.io.sockets.in(sourceRoom).clients(function(err, sourceRoomSocketIds) {
if (err) {return cb(err);}
return (function(iifeDone) { app.io.in(sourceRoom).allSockets().then(function(sourceRoomSocketIds) {iifeDone(undefined, sourceRoomSocketIds);}).catch(function(err) { iifeDone(err);});})(function(err, sourceRoomSocketIds) {
if (err) { return cb(err); }
// Loop through the socket IDs from the room
async.each(sourceRoomSocketIds, function(socketId, nextSocketId) {
// Check if the socket is connected to this server (since .clients() may someday work cross-server)
if (app.io.sockets.connected[socketId]) {
sourceRoomSocketIds.forEach((socketId) => {
// Check if the socket is connected to this server
if (app.io.of('/').sockets.has(socketId)) {
// If so, unsubscribe it from all rooms it is currently subscribed to
var socket = app.io.sockets.connected[socketId];
var destRooms = _.keys(socket.rooms);
return async.each(destRooms, function(destRoom, nextRoom) {
var socket = app.io.of('/').sockets.get(socketId);
// Create an array from the set of socket rooms.
var destRooms = Array.from(socket.rooms);
destRooms.forEach((destRoom) => {
// Don't unsubscribe a socket from its own room unless we're explicitly asked to
if (options.includeSocketRooms !== true && destRoom == socketId) {return nextRoom();}
if (options.includeSocketRooms !== true && destRoom == socketId) {return;}
// Don't unsubscribe a socket from its the source room unless we're explicitly asked to
if (options.includeSourceRoom !== true && destRoom == sourceRoom) {return nextRoom();}
return socket.leave(destRoom, nextRoom);
}, nextSocketId);
if (options.includeSourceRoom !== true && destRoom == sourceRoom) {return;}
socket.leave(destRoom);
}); // For each destRoom.
}
// If not, just continue
return nextSocketId();
}, cb);
});
cb();
});

};
Expand Down
16 changes: 10 additions & 6 deletions lib/sails.sockets/leave-room.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,16 @@ module.exports = function(app) {
sockets = [sockets];
}

async.each(sockets, function(socket, nextSocket) {
sockets.forEach((socket)=> {
// If a string was sent, try to look up a socket with that ID
if (typeof socket !== 'object' && socket !== null) {
// If we don't find one, it could be on another server, so use
// the cross-server "removeRoomMembersFromRooms"
if (!app.io.sockets.connected[socket]) {
return app.sockets.removeRoomMembersFromRooms(socket, roomName, nextSocket);
if (!app.io.of('/').sockets.has(socket)) {
return app.sockets.removeRoomMembersFromRooms(socket, roomName);
}
// Otherwise get the socket object and continue
socket = app.io.sockets.connected[socket];
socket = app.io.of('/').sockets.get(socket);
}

// If it's not a valid socket object, bail
Expand All @@ -44,9 +44,13 @@ module.exports = function(app) {
return;
}
// See ya!
socket.leave(roomName, nextSocket);
}, cb);
socket.leave(roomName);
});

// Call the callback once all sockets have left
cb();
// The value returned from this function is currently used by the Sails PubSub hook.
// FUTURE: When https://github.com/balderdashy/sails/pull/7311/files is merged, this return value can be removed.
return true;
};
};
36 changes: 19 additions & 17 deletions lib/sails.sockets/remove-room-members-from-rooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ module.exports = function(app) {

// If we were sent a socket ID as a room name, and the socket happens to
// be connected to this server, take a shortcut
if (app.io.sockets.connected[sourceRoom]) {
return doLeave(app.io.sockets.connected[sourceRoom], cb);
if (app.io.of('/').sockets.has(sourceRoom)) {
doLeave(app.io.of('/').sockets.get(sourceRoom));
return cb();
}

// Broadcast an admin message telling all other connected servers to
Expand All @@ -46,29 +47,30 @@ module.exports = function(app) {
}

// Look up all members of sourceRoom
return app.io.sockets.in(sourceRoom).clients(function(err, sourceRoomSocketIds) {
if (err) {return cb(err);}
return (function(iifeDone) { app.io.in(sourceRoom).allSockets().then(function(sourceRoomSocketIds) {iifeDone(undefined, sourceRoomSocketIds);}).catch(function(err) { iifeDone(err);});})(function(err, sourceRoomSocketIds) {
if (err) { return cb(err); }
// Loop through the socket IDs from the room
async.each(sourceRoomSocketIds, function(socketId, nextSocketId) {
// Check if the socket is connected to this server (since .clients() may someday work cross-server)
if (app.io.sockets.connected[socketId]) {
sourceRoomSocketIds.forEach(function(socketId) {
// Check if the socket is connected to this server
if (app.io.of('/').sockets.has(socketId)) {
// If so, unsubscribe it from destRooms
return doLeave(app.io.sockets.connected[socketId], nextSocketId);
doLeave(app.io.of('/').sockets.get(socketId));
}
// If not, just continue
return nextSocketId();
}, cb);
});
});
cb();
});//_∏_

function doLeave(socket, cb) {
return async.each(destRooms, function(destRoom, nextRoom) {

function doLeave(socket) {
destRooms.forEach(function(destRoom) {
// Ensure destRoom is a string
if (!_.isString(destRoom)) {
app.log.warn("Skipping non-string value for room name to add in `removeRoomMembersFromRooms`: ", destRoom);
return nextRoom();
app.log.warn("Skipping non-string value for room name to add in `addRoomMembersToRooms`: ", destRoom);
} else {
socket.leave(destRoom);
}
return socket.leave(destRoom, nextRoom);
}, cb);
});
}

};
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "sails-hook-sockets",
"version": "2.0.4",
"version": "3.0.0",
"description": "Implements socket.io support in Sails",
"keywords": [
"socket.io",
Expand All @@ -16,7 +16,7 @@
"machinepack-urls": "^6.0.2-0",
"proxy-addr": "1.1.5",
"semver": "7.5.2",
"socket.io": "2.5.0",
"socket.io": "4.7.2",
"uid2": "0.0.3"
},
"devDependencies": {
Expand All @@ -28,7 +28,7 @@
"sails": "^1.0.0-12",
"sails.io.js": "^1.0.0",
"socket.io-client": "2.0.3",
"socket.io-redis": "5.2.0"
"socket.io-redis": "6.1.0"
},
"scripts": {
"test": "node ./node_modules/mocha/bin/mocha test --timeout 5000"
Expand Down
4 changes: 2 additions & 2 deletions test/sails.sockets.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,8 @@ describe('low-level socket methods:', function (){
if (err) {return res.serverError(err);}
var socket = sails.sockets.parseSocket(req.socket);
// Return the list of rooms this socket is assigned to.
// Since socket.io v1.4, rooms is an object
var rooms = _.keys(socket.rooms);
// Since socket.io v3.x, rooms is an set
var rooms = Array.from(socket.rooms);
return res.json(rooms);
});
});
Expand Down

0 comments on commit 6a79989

Please sign in to comment.