public
Last active

RedisStore + Socket.io not working together. Code works fine on single core, as soon as worker threads are added messages are lost. Sub/Pub is happening but messages not passed to connected sockets. Vanilla Redis install running on localhost and default port. Socket.io version 9.10, redis node 8.15 ubuntu 11.04 redis 2.7.6. Error seems to be that processes drop the redis connections. See 'sample redis monitor output'.

  • Download Gist
app.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
/* OOPA ROOPA WEB APP
** Author : Kenley Tomlin
** Email : kenleytomlin@gmail.com
** Date : 2012/12/07 (latest update)
**
** Version 0.0.3 - Added redisStore to socket io's config. Scaling the app to work with multiple cores.
** Version 0.0.2 - Removed https server from node, nginx now serves certificates and proxies to node.
** Version 0.0.1 - Added a redirect app that catches the missing 'www.' from the url and redirects the user to http://www.ooparoopa.com
*/
 
var fs = require('fs');
var http = require('http');
var express = require('express');
var io = require('socket.io');
var os = require('os');
var cluster = require('cluster');
 
var workerArr = {}; //Object containing worker processes.
var rssWarn = (250 * 1024 * 1024); //250 mbs, used to check that a single process isn't hogging too much ram
 
if(cluster.isMaster)
{
for(var i = 0;i < 2; i++)
{
createWorker(); //This function creates workers for us.
}
 
setInterval(function () {
var now = new Date().getTime();
 
for(id in workerArr)
{
if(workerArr.hasOwnProperty(id) && workerArr[id].lastCb + 5000 < now)
{
console.log('Long running worker ' + id + ' killed');
workerArr[id].worker.destroy();
delete workerArr[id];
createWorker();
}
}
},1000);
}
else
{
//WORKER PROCESSES - MAIN APPLICATION
 
var app = express();
 
var httpServer = http.createServer(app).listen(8888);
io = io.listen(httpServer);
//We need the database object and connection to pass to the virtual host apps
var Database = require('./lib/Database');
var db = new Database();
db.connect('mongodb://localhost/ooparoopa');
//The virtual host apps. One for the admin one for the frontend site
var adminSiteApp = require('./adminsite/app')(db);
var mallSiteApp = require('./mallsite/app')(db,io);
 
 
app.use(express.vhost('testadmin.ooparoopa.com', adminSiteApp))
.use(express.vhost('testweb.ooparoopa.com', mallSiteApp));
 
console.log('Server Started On Port : 8888');
 
setInterval(function report() {
process.send({ cmd: 'reportMem', memory : process.memoryUsage(), process : process.pid });
}, 1000);
}
 
function createWorker () {
var worker = cluster.fork();
 
console.log('Created worker: ' + worker.process.pid);
//Allow some boot time
workerArr[worker.process.pid] = { worker: worker, lastCb : new Date().getTime() - 1000 };
worker.on('message',function (m) {
if(m.cmd === 'reportMem')
{
workerArr[m.process].lastCb = new Date().getTime();
if(m.memory.rss > rssWarn)
{
console.log('Worker ' + m.process + ' using too much memory');
}
}
});
}
mallsite_Config.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
var mongoStore = require('session-mongoose');
var connect = require('../node_modules/express/node_modules/connect');
var redisStore = require('socket.io/lib/stores/redis');
var redis = require('redis');
var pub = redis.createClient({ host : 'localhost', port :'6379' });
var sub = redis.createClient({ host : 'localhost', port : '6379'});
var client = redis.createClient({ host : 'localhost', port : '6379'});
var cookie = require('cookie');
var store;
 
module.exports = function(app,express,io){
app.configure(function(){
 
var mongooseSessionStore = new mongoStore({
url: "mongodb://localhost/ooparoopa",
interval: 240000
});
 
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser({keepExtensions : true, uploadDir : __dirname + '/tempuploads'}));
app.use(express.methodOverride());
app.use(express.compress());
app.use(express.static( __dirname +'/public'));
app.use(express.logger());
app.use(express.cookieParser());
app.use(connect.limit('5mb'));
 
app.use(express.session( { cookie: {maxAge: 1800000}, key : 'express.sid', store: store = mongooseSessionStore, secret: "ooparoopamustmakedollars"} ) );
 
app.use(app.router);
app.enable('trust-proxy'); //Trust NGINX proxies
});
 
app.configure('development',function(){
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
 
app.configure('production', function(){
app.use(express.errorHandler());
});
 
io.configure(function () {
 
io.enable('browser client minification');
io.enable('browser client etag');
io.enable('browser client gzip');
 
io.set('log level', 3);
 
io.set('transports', ['xhr-polling']);
 
io.set('polling duration',10);
 
io.set('heartbeat interval', 20);
io.set('heartbeat timeout', 60);
 
io.set('store',new redisStore({
redis : redis,
redisPub : pub,
redisSub : sub,
redisClient : client
}));
 
 
io.set('authorization', function (data,accept) {
console.log(data)
if(data.headers.cookie) {
data.cookie = connect.utils.parseSignedCookies(cookie.parse(decodeURIComponent(data.headers.cookie)),"ooparoopamustmakedollars");
 
data.sessionID = data.cookie['express.sid'];
 
store.load(data.sessionID, function (err,session) {
console.log(session);
if (err || !session) return accept('Error',false);
 
data.session = session;
return accept(null,true);
});
}
else
{
return accept('No Cookie Transmitted', false);
}
});
});
 
app.use(function (req,res,next) { //404 page handler
if(err.status == 404)
{
res.render('error/error404',{
title : 'Error 404',
pageCategory : 'Error404',
pageName : 'error404',
});
}
next();
});
 
app.use(function (err,req,res,next) {
if(err.status == 505)
{
res.render('error/error505',{
title : 'Error 505',
pageCategory : 'Error 505',
pageName : 'error505',
});
}
next();
});
 
app.use(function (err,req,res,next) {
if(err.status == 413) //Entity too large error handling
{
if(req.route.path === '/mall/createGame/finalize' || req.route.path === '/mall/editGame/finalize')
{
res.json({ success : false, msg : 'Post parameters exceed allowed length' });
}
else if(
req.route.path === '/mall/createGame/imageUpload'
|| req.route.path === '/mall/editGame/imageUpload'
|| req.path.route === '/mall/editGame/thumbUpload'
|| req.path.route === '/mall/createGame/thumbUpload') //Handle image uploads that are too large
{
res.status(err.status).send(); //Set the response of the response to 413
}
}
next();
});
};
mallsite_app.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
module.exports = function(db,io) {
var express = require('express');
var app = express();
 
//Load config
var config = require('./Config')(app,express,io);
 
//Static pages routes
var MallStaticPages = require('./lib/MallStaticPages');
var mallStaticPages = new MallStaticPages();
mallStaticPages.initPages(app,db);
//Sign up pages routes and logic
var MallSignUpPages = require('./lib/MallSignUpPages');
var mallSignUpPages = new MallSignUpPages();
mallSignUpPages.initPages(app,db);
 
var MallAdminPages = require('./lib/MallAdminPages');
var mallAdminPages = new MallAdminPages();
mallAdminPages.initPages(app,db);
 
var PointsManager = require('./lib/PointsManager');
var pointsManager = new PointsManager();
pointsManager.init(app,db);
 
var ReservationPages = require('./lib/ReservationPages');
var reservationPages = new ReservationPages();
reservationPages.initPages(app,db,io);
 
var MallCreateGame = require('./lib/MallCreateGame');
var mallCreateGame = new MallCreateGame();
mallCreateGame.initPages(app,db);
 
var MallPaymentPages = require('./lib/MallPaymentPages');
var mallPaymentPages = new MallPaymentPages();
mallPaymentPages.initPages(app,db);
 
var MallGameFinishedMail = require('./lib/MallGameFinishedMail');
var mallGameFinishedMail = new MallGameFinishedMail();
mallGameFinishedMail.initQueue(db);
 
return app;
}
mallsite_lib_reservationPages.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
var CheckLogin = require('../../lib/Tools/CheckLogin');
var Schedule = require('../../lib/Schedule');
var ResMall = require('./Res/ResMall');
 
var selectedSlots = [];
 
var getKeys = function(array) {
var keys = [];
for(var key in array)
{
keys.push(key);
}
return keys;
}
 
var ReservationPages = module.exports = function () {};
 
ReservationPages.prototype = {
 
db : null,
io : null,
 
 
initPages : function (app,db,io) {
 
this.db = db;
this.io = io;
var self = this;
 
//ROUTING
 
//RESERVATION PAGE ROUTE
 
app.get('/mall/reservation', function (req,res) { self.reservationPage (req,res); } );
 
//SOCKET IO EVENTS
 
//CONNECTION
io.of('/mall/reservation').on('connection', function (socket) { self.reservationConnect (socket); } );
},
 
checkLogin : function (req,res) {
if (req.session && req.session.loggedIn === true)
return true;
res.redirect('/login');
return false;
},
 
reservationPage : function (req,res) {
if(!CheckLogin.checkLoginMall(req,res)) return;
 
var Settings = this.db.model('Settings');
Settings.find().select('startDay startHour lastDay lastHour cancelDay cancelHour slotPrice slotDiscount').exec(function (err,settingData) {
if(err)
{
 
}
else
{
var settingData = settingData[0]; //Make it easier to work with this
 
var midnightGameDay = new Date(Schedule.midnightGameDay(settingData['startDay']));
 
var startDay = new Date(midnightGameDay.getTime() + (settingData.startHour * Schedule.HOUR_IN_MILLISECONDS)); //The time and date that the first game can be reserved
var lastDay = new Date(midnightGameDay.getTime() + (settingData.lastHour * Schedule.HOUR_IN_MILLISECONDS) + (settingData.lastDay * Schedule.DAY_IN_MILLISECONDS)); //The time and date that the last game be reserved today.
 
var slotP = []; //this will contain the prices of each slot per hour.
var y = 0;
for(var x = 0;x < settingData.slotPrice.length;x++)
{
if(settingData.slotPrice[x].finishDate.getTime() >= startDay.getTime())
{
console.log('x');
console.log(x);
slotP.push(settingData.slotPrice[x]);
}
}
 
res.render('mall/reservation', {
title : '경기 개최하기',
pageCategory : 'Game Slot Reservation',
pageName : 'reservation',
loginStatus : req.session.loggedIn,
data : { startDay : startDay.toString(), lastDay : lastDay.toString(), cancelDay : settingData.cancelDay, cancelHour : settingData.cancelHour, slotPrice : slotP, slotDiscount : settingData.slotDiscount }
});
}
});
},
 
reservationConnect : function (socket) {
var Reservation = this.db.model('Reservation');
var Game = this.db.model('Game');
var Settings = this.db.model('Settings');
var Transaction = this.db.model('Transaction');
var Mall = this.db.model('Mall');
var self = this;
 
//console.log('socket');
//console.log(socket);
console.log(socket.handshake.session);
//socket.handshake.session.touch().save();
socket.join(socket.handshake.session._id);
 
if(socket.handshake.session && socket.handshake.session.loggedIn === true)
{
console.log('connectionOk');
self.io.sockets.in(socket.handshake.session._id).emit('connectionOk');
 
socket.on('selectDay', function (data) {
 
var selectedSlotDate = new Date(data.day);
 
Game.find().select('closeTime').where('mallId').ne(socket.handshake.session._id).where('closeTime').gte( selectedSlotDate.getTime() - Schedule.HOUR_IN_MILLISECONDS).lte(selectedSlotDate.getTime() + (Schedule.HOUR_IN_MILLISECONDS * 24)).exec(function (err,gameData) {
if(err)
{
console.log(err);
}
else
{
var x = 0;
var gameD = [];
gameData.forEach(function (game) {
var closeTime = game.closeTime.toString();
gameD[x] = closeTime;
x++;
});
self.io.sockets.in(socket.handshake.session._id).emit('gameList',{ data : gameD });
}
});
Game.find().select('closeTime').where('mallId').equals(socket.handshake.session._id).where('closeTime').gte(selectedSlotDate.getTime() - Schedule.HOUR_IN_MILLISECONDS).lte(selectedSlotDate.getTime() + (Schedule.HOUR_IN_MILLISECONDS * 24)).exec(function (err,myGameData) {
if(err)
{
console.log(err);
}
else
{
var x =0;
var myGameD = [];
myGameData.forEach(function (game) {
var closeTime = game.closeTime.toString();
var closeTime = closeTime;
myGameD[x] = closeTime;
x++;
});
self.io.sockets.in(socket.handshake.session._id).emit('myGameList', { data : myGameD });
}
});
Reservation.find().select('closeTime').where('mallId').ne(socket.handshake.session._id).where('closeTime').gte(selectedSlotDate.getTime() - Schedule.HOUR_IN_MILLISECONDS).where('closeTime').lte(selectedSlotDate.getTime() + (Schedule.HOUR_IN_MILLISECONDS * 24)).exec(function (err,reservationData) {
if(err)
{
console.log(err);
}
else
{
var x = 0;
var reservationD = [];
reservationData.forEach(function (game) {
var closeTime = game.closeTime.toString();
reservationD[x] = closeTime;
x++;
});
 
self.io.sockets.in(socket.handshake.session._id).emit('reserveList', { data : reservationD });
}
});
Reservation.find().select('closeTime').where('mallId').equals(socket.handshake.session._id).where('closeTime').gte(selectedSlotDate.getTime() - Schedule.HOUR_IN_MILLISECONDS).where('closeTime').lte(selectedSlotDate.getTime() + (Schedule.HOUR_IN_MILLISECONDS * 24)).exec(function (err,myReservationData) {
if(err)
{
console.log(err);
}
else
{
var x = 0;
var myReservationD = [];
myReservationData.forEach(function (game) { //For IE as it doesn't support ISO date strings!
var closeTime = game.closeTime.toString();
myReservationD[x] = closeTime;
x++;
});
self.io.sockets.in(socket.handshake.session._id).emit('myReserveList', { data : myReservationD });
}
});
});
 
socket.on('selectSlot', function (dat) {
var now = Date.now();
if((socket.handshake.session && socket.handshake.session.loggedIn === true) && (new Date(socket.handshake.session.cookie._expires).getTime() > now))
{
var resCheckFin = false;
var gameCheckFin = false;
var selectedSlotDate = new Date(dat.slotTime);
socket.handshake.session.touch().save();
var keys = getKeys(selectedSlots);
Reservation.find().select('closeTime').where('closeTime').equals(selectedSlotDate.getTime()).exec(function (err,reservationData) {
if(err)
{
console.log(err);
}
else
{
if(reservationData.length > 0)
{
self.io.sockets.in(socket.handshake.session._id).emit('slotUnavailable');
}
else
{
resCheckFin = true;
checkArray(resCheckFin,gameCheckFin);
}
}
});
 
Game.find().select('closeTime').where('closeTime').equals(selectedSlotDate.getTime()).exec(function (err,gameData) {
if(err)
{
console.log(err);
}
else
{
if(gameData.length > 0)
{
self.io.sockets.in(socket.handshake.session._id).emit('slotUnavailable');
}
else
{
gameCheckFin = true;
checkArray(resCheckFin,gameCheckFin);
}
}
});
 
var checkArray = function (resCheckFin,gameCheckFin)
{
if(gameCheckFin === true && resCheckFin === true)
{
var unavailable = 0;
for(var mkey in selectedSlots)
{
if(selectedSlots[mkey].selectedSlot !== null)
{
if(mkey !== socket.handshake.session._id)
{
if(selectedSlots[mkey].selectedSlot.getTime() === selectedSlotDate.getTime())
{
self.io.sockets.in(socket.handshake.session._id).emit('slotUnavailable');
unavailable ++;
}
}
}
}
if(unavailable === 0)
{
var keys = getKeys(this.selectedSlots);
if(keys.indexOf(socket.handshake.session._id)=== -1)
{
var newMall = ResMall.initMall(socket.handshake.session._id,selectedSlotDate);
selectedSlots[socket.handshake.session._id] = newMall;
}
else
{
selectedSlots[socket.handshake.session._id].slotTime = selectedSlotDate;
}
self.io.sockets.in(socket.handshake.session._id).emit('slotAvailable');
self.io.of('/mall/reservation').emit('slotSelected', { data : { slotTime : selectedSlotDate.toString() } });
}
}
};
}
else
{
//socket.emit('sessionTimeout',function (){
//});
}
});
 
socket.on('slotDiselected', function (data) {
var now = Date.now();
if((socket.handshake.session && socket.handshake.session.loggedIn === true) && (new Date(socket.handshake.session.cookie._expires).getTime() > now))
{
//socket.handshake.session.touch().save();
var keys = getKeys(selectedSlots);
if(keys.indexOf(socket.handshake.session._id) !== -1)
{
self.io.of('/mall/reservation').emit('slotDiselected', { data : { slotTime : selectedSlots[socket.handshake.session._id].selectedSlot.toString() } });
selectedSlots[socket.handshake.session._id].selectedSlot = null;
}
}
else
{
//socket.emit('sessionTimeout',function (){
// socket.handshake.session.destroy();
// socket.disconnect();
//});
}
});
 
socket.on('reserveSlot', function (data) {
var now = Date.now();
if((socket.handshake.session && socket.handshake.session.loggedIn === true) && (new Date(socket.handshake.session.cookie._expires).getTime() > now))
{
//socket.handshake.session.touch().save();
var resCheckFin = false;
var gameCheckFin = false;
var resSuccess = true;
var dedPntsSuccess = false;
var tranSuccess = false;
var resSave = false;
var selectedSlotDate = new Date(data.slotTime);
var keys = getKeys(selectedSlots);
 
console.log(selectedSlotDate);
 
console.log(keys.indexOf(socket.handshake.session._id));
if(keys.indexOf(socket.handshake.session._id)!== -1)
{
if(selectedSlots[socket.handshake.session._id].selectedSlot.getTime() === selectedSlotDate.getTime())
{
Reservation.find().select('closeTime').where('closeTime').equals(selectedSlotDate.getTime()).exec(function (err,reservationData) {
if(err)
{
console.log(err);
}
else
{
if(reservationData.length > 0)
{
self.io.sockets.in(socket.handshake.session._id).emit('reservationFail');
}
else
{
resCheckFin = true;
checkArray(resCheckFin,gameCheckFin);
}
}
});
Game.find().select('closeTime').where('closeTime').equals(selectedSlotDate.getTime()).exec(function (err,gameData) {
if(err)
{
console.log(err);
}
else
{
if(gameData.length > 0)
{
self.io.sockets.in(socket.handshake.session._id).emit('reservationFail');
}
else
{
gameCheckFin = true;
checkArray(resCheckFin,gameCheckFin);
}
}
});
}
else
{
self.io.sockets.in(socket.handshake.session._id).emit('reservationFail');
}
 
var calculateSlotPrice = function ()
{
Settings.find().select('slotPrice startDay lastDay lastHour slotDiscount').exec(function (err,settingsData) {
if(err)
{
console.log(err);
}
else
{
var slotPrice;
var slotPriceFound = false;
for(var i = 0;i < settingsData[0].slotPrice.length;i++)
{
if(slotPriceFound === true)
{
break;
}
if(settingsData[0].slotPrice[i].startDate.getTime() <= selectedSlotDate.getTime() && settingsData[0].slotPrice[i].finishDate.getTime() >= selectedSlotDate.getTime())
{
 
for(var y = 0;y < settingsData[0].slotPrice[i].slotPrice.length;y++)
{
console.log( settingsData[0].slotPrice[i].slotPrice);
if(settingsData[0].slotPrice[i].slotPrice[y].time == selectedSlotDate.getHours())
{
slotPrice = settingsData[0].slotPrice[i].slotPrice[y].price - settingsData[0].slotDiscount; //FIXED
slotPriceFound = true;
break;
}
}
}
}
 
deductPoints(slotPrice);
}
});
};
 
var deductPoints = function (slotPrice) {
 
Mall.findOne().select('pointsBalance').where('_id').equals(socket.handshake.session._id).exec(function (err,mallData) {
if(err)
{
console.log(err);
}
else
{
if(mallData.pointsBalance < slotPrice)
{
self.io.sockets.in(socket.handshake.session._id).emit('pointBalanceLow',{ msg : '우파루파머니가 부족합니다. 충전하시겠습니까?' });
self.io.of('/mall/reservation').emit('slotDiselected', { data : { slotTime : selectedSlotDate.selectedSlot.toString() } });
}
else
{
var newTransaction = new Transaction({ type : 1, amount : slotPrice, mallId : socket.handshake.session._id, details : '슬롯 구매 - ' + selectedSlotDate.toString() });
newTransaction.save(function (err) {
if(err)
{
self.io.sockets.in(socket.handshake.session._id).emit('reservationFail');
}
else
{
tranSuccess = true;
reservationFinished(dedPntsSuccess,tranSuccess,resSave);
}
});
var newRes = new Reservation({ closeTime : selectedSlotDate, mallId : socket.handshake.session._id, slotPrice : slotPrice });
newRes.save(function (err,newResDoc) {
if(err)
{
console.log(err);
}
else
{
resSave = true;
reservationFinished(dedPntsSuccess,tranSuccess,resSave);
}
});
mallData.pointsBalance = mallData.pointsBalance - slotPrice;
mallData.save(function (err) {
if(err)
{
console.log(err);
}
else
{
dedPntsSuccess = true;
reservationFinished(dedPntsSuccess,tranSuccess,resSave);
}
});
}
}
});
};
 
var reservationFinished = function (dedPntsSuccess,tranSuccess,resSave) {
if(dedPntsSuccess === true && tranSuccess === true && resSave === true)
{
self.io.sockets.in(socket.handshake.session._id).emit('reservationSuccess', { data : { slotTime : selectedSlotDate.toString() } });
self.io.of('/mall/reservation').emit('slotReserved', { data : { slotTime : selectedSlotDate.toString() } });
}
}
 
var checkArray = function (resCheckFin,gameCheckFin) {
if(resCheckFin === true && gameCheckFin === true)
{
for(var mKey in selectedSlots)
{
if(selectedSlots[mKey].selectedSlot !== null)
{
if(selectedSlots[mKey].selectedSlot.getTime() === selectedSlotDate.getTime() && mKey !== socket.handshake.session._id)
{
self.io.sockets.in(socket.handshake.session._id).emit('reservationFail')
resSuccess = false;
}
}
}
if(resSuccess === true)
{
calculateSlotPrice();
}
}
};
}
}
else
{
//socket.emit('sessionTimeout',function (){
//socket.handshake.session.destroy();
//socket.disconnect();
//});
}
});
 
socket.on('slotCancel',function (data) {
var now = Date.now();
 
var refundPoints = function (slotPrice) {
console.log(slotPrice);
Mall.update({ _id : socket.handshake.session._id },{ $inc : { pointsBalance : slotPrice } }, function (err,numAffected,raw) {
if(err)
{
console.log(err);
}
});
self.io.of('/mall/reservation').emit('slotCancelled',{ data : { slotTime : selectedSlotDate.toString() } });
};
 
if((socket.handshake.session && socket.handshake.session.loggedIn === true) && (new Date(socket.handshake.session.cookie._expires).getTime() > now))
{
//socket.handshake.session.touch().save();
var selectedSlotDate = new Date(data.slotTime);
Settings.find().select('cancelDay cancelHour').exec(function (err,settingData) {
if(err)
{
console.log(err);
}
else
{
var settingData = settingData[0];
var dateObj = new Date();
var cancelDate = new Date(selectedSlotDate.getTime() - ((settingData.cancelDay * Schedule.DAY_IN_MILLISECONDS))); // + ((settingData.cancelHour) * Schedule.HOUR_IN_MILLISECONDS)));
cancelDate = new Date(cancelDate.getTime() - ((cancelDate.getHours() * Schedule.HOUR_IN_MILLISECONDS) + (cancelDate.getMinutes() * Schedule.MINUTE_IN_MILLISECONDS)));
cancelDate = new Date(cancelDate.getTime() + (settingData.cancelHour * Schedule.HOUR_IN_MILLISECONDS));
if(selectedSlotDate.getHours() < settingData.lastHour && selectedSlot.getHours() < settingData.startHour)
{
cancelDate = cancelDate.getTime() - Schedule.DAY_IN_MILLISECONDS;
}
 
if(dateObj.getTime() < cancelDate.getTime())
{
Reservation.findOneAndRemove().where('mallId').equals(socket.handshake.session._id).where('closeTime').equals(selectedSlotDate.getTime()).exec(function (err,reservationData) {
if(err)
{
console.log(err);
}
else
{
if(selectedSlots[socket.handshake.session._id])
{
selectedSlots[socket.handshake.session._id].selectedSlot = null;
}
refundPoints(reservationData.slotPrice);
}
var tranDetail = '슬롯 예약 취소 - ' + reservationData.closeTime.toString();
var newTransaction = new Transaction({ type : 2, amount : reservationData.slotPrice, details : tranDetail, mallId : socket.handshake.session._id });
newTransaction.save(function (err) {
if(err)
{
console.log(err);
}
});
});
 
}
else
{
self.io.sockets.in(socket.handshake.session._id).emit('slotCancelledFail');
}
}
});
}
else
{
//socket.emit('sessionTimeout',function (){
//socket.handshake.session.destroy();
//socket.disconnect();
//});
}
});
 
socket.on('gameCancel',function (data) {
var now = Date.now();
var selectedSlotDate = new Date(data.slotTime);
 
var uploadToWorker = function (gameData) {
 
var connection = require('amqp').createConnection({ host : 'localhost'});
connection.on('ready', function () {
 
var exchange = connection.exchange('ooparoopa');
var queue = connection.queue('prizeImageDelete');
 
queue.on('queueDeclareOk', function (args) {
queue.bind(exchange,'#prizeImageDelete');
queue.on('queueBindOk', function () {
exchange.publish('#prizeImageDelete', gameData);
});
});
});
};
 
if((socket.handshake.session && socket.handshake.session.loggedIn === true) && (new Date(socket.handshake.session.cookie._expires).getTime() > now))
{
//socket.handshake.session.touch().save();
var selectedSlotData = new Date(data.slotTime);
Game.findOneAndRemove().where('mallId').equals(socket.handshake.session._id).where('closeTime').equals(selectedSlotDate.getTime()).exec(function (err,gameData) {
if(err)
{
console.log(err);
}
else
{
console.log(gameData);
var pointRefund = gameData.slotPrice + gameData.gamePrice;
Mall.update({ _id : socket.handshake.session._id }, { $inc : { pointsBalance : pointRefund } }, function (err,numAffected,raw) {
if(err)
{
console.log(err);
}
});
var newTransaction = new Transaction({ type : 2, amount : pointRefund, mallId : socket.handshake.session._id, details : '경기취소 - ' + selectedSlotDate.toString() });
newTransaction.save(function (err) {
if(err)
{
console.log(err);
}
});
uploadToWorker(gameData);
self.io.of('/mall/reservation').emit('gameCancelled', { data : { slotTime : selectedSlotDate.toString() } });
}
});
}
else
{
//socket.emit('sessionTimeout',function () {
// socket.handshake.session.destroy();
// socket.disconnect();
//});
}
});
}
else
{
//socket.emit('sessionTimeout',function (){
// socket.handshake.session.destroy();
// socket.disconnect();
//});
}
}
}
sample redis monitor output
1 2 3 4 5 6 7
1355285492.579041 [0 127.0.0.1:42277] "publish" "close" "{\"nodeId\":1056825330,\"args\":[\"3tOPQ_40Lkh5vNTDRDLe\"]}"
1355285492.579074 [0 127.0.0.1:42280] "unsubscribe" "dispatch:3tOPQ_40Lkh5vNTDRDLe"
1355285492.579094 [0 127.0.0.1:42280] "subscribe" "dispatch:3tOPQ_40Lkh5vNTDRDLe"
1355285492.579883 [0 127.0.0.1:42279] "subscribe" "dispatch:3tOPQ_40Lkh5vNTDRDLe"
1355285500.270337 [0 127.0.0.1:42279] "unsubscribe" "disconnect-force:BhK2BCKMWgzowu4ERDLh"
1355285500.270377 [0 127.0.0.1:42279] "unsubscribe" "heartbeat-clear:BhK2BCKMWgzowu4ERDLh"
1355285500.270397 [0 127.0.0.1:42278] "publish" "close" "{\"nodeId\":1251962569,\"args\":[\"BhK2BCKMWgzowu4ERDLh\"]}"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.