Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Need some help using #10

Open
max-degterev opened this issue Jul 6, 2014 · 11 comments
Open

Need some help using #10

max-degterev opened this issue Jul 6, 2014 · 11 comments

Comments

@max-degterev
Copy link

Hi! I have this server file:

#=========================================================================================
# Application setup
#=========================================================================================
config = require('config')
cluster = require('cluster')
_ = require('underscore')
app = require('express')()
http = require('http').Server(app)
socket = require('socket.io')(http, serveClient: false)

env = require('env')
pkg = require('./package')
helpers = require('app/javascripts/shared/helpers')
log = helpers.log

passport = require('passport')
session = require('express-session')
mongoose = require('mongoose')
MongoStore = require('connect-mongostore')(session)


#=========================================================================================
# Forking
#=========================================================================================
if cluster.isMaster
  for i in [1..config.workers]
    log("Starting worker #{i}")
    cluster.fork()

  cluster.on 'exit', (worker, code, signal)->
    log("Worker #{worker.process.pid} died")

    if config.debug
      process.exit()
    else
      cluster.fork()

else



  #=======================================================================================
  # Instantiate server
  #=======================================================================================
  domain = require('domain').create()
  domain.on 'error', (err)->
    log(err.stack || err, 'red')

    killtimer = setTimeout ->
      process.exit(1)
    , config.death_timeout
    killtimer.unref()

  domain.run ->
    server = require('./app/javascripts/server')
    unless config.debug
      assetsHashMap = {}
      for key, value of require('./public/assets/hashmap.json')
        assetsHashMap[key.replace('.min', '')] = value

    mongoose.connect("mongodb://#{config.mongodb.host}/#{config.mongodb.database}", server: socketOptions: keepAlive: 1)
    mongoose.connection.on('error', (e)-> log("MongoDB operation failed: #{e}"))


    #=====================================================================================
    # Template globals
    #=====================================================================================
    generateTemplateGlobals = ->
      app.locals.pretty = config.debug
      app.locals.config = _.omit(_.clone(config), config.server_only_keys...)
      app.locals._ = _
      app.locals.helpers = helpers


    #=====================================================================================
    # Global middleware
    #=====================================================================================
    normalizeUrl = (req, res, next)->
      try
        decodeURIComponent(req.originalUrl)
      catch
        url = '/'
        log("malformed URL, redirecting to #{url}")
        return res.redirect(301, url)

      [href, qs...] = req.originalUrl.split('?')

      if qs.length > 1 # should be 1?2, [2].length = 1
        url = href + '?' + qs.join('&')
        log("malformed URL, redirecting to #{url}")
        return res.redirect(301, url)

      next()

    getAsset = (name)->
      name = assetsHashMap[name] unless config.debug
      "/assets/#{name}"

    injectGetAsset = (req, res, next)->
      req.app.locals.getAsset = getAsset
      next()

    generateEnv = (req, res, next)->
      res.locals.env.rendered = (new Date).toUTCString()
      res.locals.env.lang = require('./config/lang_en_us')
      res.locals.env.version = pkg.version

      next()

    updateUserSession = (req, res, next)->
      # env.csrf = req.csrfToken()
      req.session._updated = (new Date).toUTCString() # forcing cookie to refresh itself
      req.session.touch()
      next()

    preRouteMiddleware = ->
      morgan = require('morgan')

      if config.debug
        app.use(morgan('dev'))
      else
        app.use(morgan('default'))

      app.use(normalizeUrl)

      app.use(require('serve-favicon')(__dirname + '/public/favicon.ico'))
      app.use(require('serve-static')(__dirname + '/public', redirect: false))

      app.use(require('body-parser').json())
      app.use(require('cookie-parser')())

      app.use session
        key: 'sid'
        secret: config.session.secret
        cookie: maxAge: config.session.lifetime
        store: new MongoStore(mongooseConnection: mongoose.connection)
        saveUninitialized: false
        resave: true

      app.use(passport.initialize())
      app.use(passport.session())

      app.use(injectGetAsset)
      app.use(env.create)
      app.use(generateEnv)
      app.use(updateUserSession)

    postRouteMiddleware = ->
      if config.debug
        app.use(require('errorhandler')(dumpExceptions: true, showStack: true))
      else
        app.use(require('compression')())


    #=====================================================================================
    # Start listening
    #=====================================================================================
    app.enable('trust proxy') # usually sitting behind nginx
    app.disable('x-powered-by')

    app.set('port', config.port)
    app.set('views', "#{__dirname}/app/templates")
    app.set('view engine', 'jade')
    app.set('json spaces', 2) if config.debug
    app.set('socket', socket)

    mongoose.connection.once 'open', ->
      log('MongoDB connection established', 'cyan')

      generateTemplateGlobals()

      preRouteMiddleware()
      server.use(app) # Fire up the server, all the routes go here
      postRouteMiddleware()

      app_root = "http://#{config.hostname}:#{config.port}"

      if config.ip
        http.listen(app.get('port'), config.ip, -> log("Server listening on #{app_root} (bound to ip: #{config.ip})", 'cyan'))
      else
        http.listen(app.get('port'), -> log("Server listening on #{app_root} (unbound)", 'cyan'))

I tried to modify it like this to use your module:

#=========================================================================================
# Application setup
#=========================================================================================
config = require('config')
cluster = require('cluster')
_ = require('underscore')

app = http = socket = null
sticky = require('sticky-session')

env = require('env')
pkg = require('./package')
helpers = require('app/javascripts/shared/helpers')
log = helpers.log

passport = require('passport')
session = require('express-session')
mongoose = require('mongoose')
MongoStore = require('connect-mongostore')(session)


#=========================================================================================
# Forking
#=========================================================================================
stickyHttp = sticky config.workers, ->
  app = require('express')()
  http = require('http').Server(app)
  socket = require('socket.io')(http, serveClient: false)


  #=======================================================================================
  # Instantiate server
  #=======================================================================================
  domain = require('domain').create()
  domain.on 'error', (err)->
    log(err.stack || err, 'red')

    killtimer = setTimeout ->
      process.exit(1)
    , config.death_timeout
    killtimer.unref()

  domain.run ->
    server = require('./app/javascripts/server')
    unless config.debug
      assetsHashMap = {}
      for key, value of require('./public/assets/hashmap.json')
        assetsHashMap[key.replace('.min', '')] = value

    mongoose.connect("mongodb://#{config.mongodb.host}/#{config.mongodb.database}", server: socketOptions: keepAlive: 1)
    mongoose.connection.on('error', (e)-> log("MongoDB operation failed: #{e}"))


    #=====================================================================================
    # Template globals
    #=====================================================================================
    generateTemplateGlobals = ->
      app.locals.pretty = config.debug
      app.locals.config = _.omit(_.clone(config), config.server_only_keys...)
      app.locals._ = _
      app.locals.helpers = helpers


    #=====================================================================================
    # Global middleware
    #=====================================================================================
    normalizeUrl = (req, res, next)->
      try
        decodeURIComponent(req.originalUrl)
      catch
        url = '/'
        log("malformed URL, redirecting to #{url}")
        return res.redirect(301, url)

      [href, qs...] = req.originalUrl.split('?')

      if qs.length > 1 # should be 1?2, [2].length = 1
        url = href + '?' + qs.join('&')
        log("malformed URL, redirecting to #{url}")
        return res.redirect(301, url)

      next()

    getAsset = (name)->
      name = assetsHashMap[name] unless config.debug
      "/assets/#{name}"

    injectGetAsset = (req, res, next)->
      req.app.locals.getAsset = getAsset
      next()

    generateEnv = (req, res, next)->
      res.locals.env.rendered = (new Date).toUTCString()
      res.locals.env.lang = require('./config/lang_en_us')
      res.locals.env.version = pkg.version

      next()

    updateUserSession = (req, res, next)->
      # env.csrf = req.csrfToken()
      req.session._updated = (new Date).toUTCString() # forcing cookie to refresh itself
      req.session.touch()
      next()

    preRouteMiddleware = ->
      morgan = require('morgan')

      if config.debug
        app.use(morgan('dev'))
      else
        app.use(morgan('default'))

      app.use(normalizeUrl)

      app.use(require('serve-favicon')(__dirname + '/public/favicon.ico'))
      app.use(require('serve-static')(__dirname + '/public', redirect: false))

      app.use(require('body-parser').json())
      app.use(require('cookie-parser')())

      app.use session
        key: 'sid'
        secret: config.session.secret
        cookie: maxAge: config.session.lifetime
        store: new MongoStore(mongooseConnection: mongoose.connection)
        saveUninitialized: false
        resave: true

      app.use(passport.initialize())
      app.use(passport.session())

      app.use(injectGetAsset)
      app.use(env.create)
      app.use(generateEnv)
      app.use(updateUserSession)

    postRouteMiddleware = ->
      if config.debug
        app.use(require('errorhandler')(dumpExceptions: true, showStack: true))
      else
        app.use(require('compression')())


    #=====================================================================================
    # Start listening
    #=====================================================================================
    app.enable('trust proxy') # usually sitting behind nginx
    app.disable('x-powered-by')

    app.set('port', config.port)
    app.set('views', "#{__dirname}/app/templates")
    app.set('view engine', 'jade')
    app.set('json spaces', 2) if config.debug
    app.set('socket', socket)

    mongoose.connection.once 'open', ->
      log('MongoDB connection established', 'cyan')

      generateTemplateGlobals()

      preRouteMiddleware()
      server.use(app) # Fire up the server, all the routes go here
      postRouteMiddleware()

      app_root = "http://#{config.hostname}:#{config.port}"

      if config.ip
        stickyHttp.listen(app.get('port'), config.ip, -> log("Server listening on #{app_root} (bound to ip: #{config.ip})", 'cyan'))
      else
        stickyHttp.listen(app.get('port'), -> log("Server listening on #{app_root} (unbound)", 'cyan'))

  http

Server starts, but it doesn't accept connections. Your examples, and the module itself are a bit cryptic. How do I set it up in my example? 👍

@indutny
Copy link
Owner

indutny commented Jul 6, 2014

Sorry, I don't maintain this library anymore. If you know someone or wish to work on it - let me know, I'll give you the proper rights!

@paulbjensen
Copy link

Hi,

We're using this library in production at my current employer (Axisto Media) for one of our core applications. I would be happy to help maintain this for you.

@indutny
Copy link
Owner

indutny commented Jul 7, 2014

@paulbjensen I've just given the rights to @tlhunter , if you wish to cooperate - you could try reaching him out. Thank you, anyway!

@paulbjensen
Copy link

No worries, glad to see it's getting maintained. It was a great find when I
was trying to figure out how to use socket.io with Node's cluster API way
back.

My main point of focus is getting it working on Node 0.10. I'll be happy to
submit a PR if I manage to make progress on that.

Regards,

Paul Jensen

On 7 July 2014 11:24, Fedor Indutny [email protected] wrote:

@paulbjensen https://github.com/paulbjensen I've just given the rights
to @tlhunter https://github.com/tlhunter , if you wish to cooperate -
you could try reaching him out. Thank you, anyway!


Reply to this email directly or view it on GitHub
#10 (comment)
.

Paul Jensen
07914 171 345

@max-degterev
Copy link
Author

Wait what? It's not compatible with 0.10.x node? How about latest release of socket? ExpressJS?

@paulbjensen
Copy link

I should add a caveat to my comment.

We're running a legacy Node.js application (Node 0.8), and we use
sticky-session along with an old version of engine.io (via a wrapper module
we wrote to replace NowJS).

In trying to get the legacy app to Node 0.10, we encountered timeouts
rendering pages (Node 0.10 on Mac OS X Mavericks). The version of engine.io
in use was still relatively old.

The timeouts sounds exactly like what is happening here:
#9

On 7 July 2014 16:08, Max [email protected] wrote:

Wait what? It's not compatible with 0.10.x node? How about latest release
of socket? ExpressJS?


Reply to this email directly or view it on GitHub
#10 (comment)
.

Paul Jensen
07914 171 345

@tlhunter
Copy link

tlhunter commented Jul 9, 2014

I'm going to try and figure out this ticket (as well as the other open ones), although I won't be getting to it until this weekend.

@paulbjensen if you want to submit a PR, I'm sure it'll expedite the process ;)

@elad
Copy link

elad commented Oct 28, 2014

@suprMax - since there haven't been any updates on this issue you might want to look at my writeup on the subject. I too found the examples a bit cryptic but also needed a less intrusive solution. In the process, we found a bug that might be a contributing factor to what you're seeing.

@max-degterev
Copy link
Author

@elad thanks! I will def take a look! I'm stuck with running one process w/o any workers at the moment. It totally sucks :(

@mukulgupta2507
Copy link

@suprMax

Were you able to find any solution for this ? I'm also facing a similar issue. Please revert if you have some updated info on this.

Thanks

@max-degterev
Copy link
Author

@mukulgupta2507 since I'm older and wiser now, I do 👍 Look at passenger or nginx config options. I did it last time with some smart nginx trickery. Passenger will replace whole load balancing for you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants