keymetrics / pm2-io-apm

PM2.io APM for Node.JS
Apache License 2.0
147 stars 39 forks source link

entrypoint: implement spec #60

Closed vmarchaud closed 6 years ago

Unitech commented 6 years ago
const Entrypoint = require('@pm2/pm2.io').Entrypoint

class App extends Entrypoint {

  // The .onStart is called by Entrypoint when initializing the app
  onStart(cb) {
      this.server = http.createServer((req, res) => {
        res.send('Hello')
      })

      // The cb send process.send('ready') to PM2 
      // if we manage to retrieve the http instance we could bind it to
      // https://github.com/hunterloftis/stoppable
      this.server.listen(8000, cb)
  }

  // The .onStop is called when the app will exit (exception, rejection, sigint, sigstop...)
  onStop(cb) {

  }

  // Just a method to cleanly list metrics
  metrics() {
     this.meter('stuff-metrics', () => {
       return 42
     })
  }

  // To cleanly list diagnostics
  diagnostics() {
     this.on('getEnv', (cb) => {
       cb(null, process.env)
     })
  }
}

 module.exports = new Entrypoint
class Entrypoint {
  constructor () {
     this.io = io.init(this.conf())

     this.onStart(err => () {
       this.metrics()
       this.diagnostics()
       this.io.onExit((err) => {
         this.onStop(err, () => {
           this.io.destroy()
         })
       })
       process.send('ready')
     })
  },

  onStart () {
    throw new Error('Entrypoint onStart() not specified')
  },  

  onStop () {
    throw new Error('Entrypoint onStop() not specified')
  },

  conf () {
    return { defaultConf }
  }
}

// wait_ready? listen_timeout? kill_timeout? // this.io.waitFor('app') pour onStart demare app // auto require de pm2 lightweight // ipc pubsub

This is a simple draft, based on my intuition, @vmarchaud @wallet77 feedback welcome on this api design

wallet77 commented 6 years ago

@vmarchaud @Unitech

I think onSotp and onStart should exists by default and just execute the callback : onStart/onStop (cb) { cb() }

In this case user can override only onStop for example.

wallet77 commented 6 years ago

Done : https://github.com/keymetrics/pm2-io-apm/pull/91