Is there something like Meteor.shutdown()?

There is Meteor.startup() to run code on server startup. But is there also something like Meteor.shutdown() for cleanup tasks when the server receives a SIGTERM (or SIGINT)?

NodeJS has this:

process.on('SIGTERM', () => {
  // .. do some cleanup here
}

Maybe you can create something like this:

Meteor.shutdown = function shutdown(callback) {
  callback = Meteor.wrapFn(callback);
  
  var bootstrap = global.__meteor_bootstrap__;
  if (bootstrap) {
    if (bootstrap.shutdownHooks) {
      bootstrap.shutdownHooks.push(callback);
    } else {
      bootstrap.shutdownHooks = [callback];
    }
  } 
};

process.on('SIGTERM', () => {
  var bootstrap = global.__meteor_bootstrap__;
  if (bootstrap && bootstrap.shutdownHooks) {
    bootstrap.shutdownHooks.map((callback) => {
      callback();
    }
  } 
}
3 Likes

@minhna do you have experience with this? Is it hard-blocking until all operations are “done”? Also is it compatible with mongodb transactions?

Unfortunately I don’t have. It’s just an idea in my head.

@waldgeist @minhna @jkuester

I’ve prototyped a Meteor.shutdown(fn) API symmetric to Meteor.startup(fn) and opened a draft PR against devel:

feat(meteor): add Meteor.shutdown() lifecycle hook by dupontbertrand · Pull Request #14434 · meteor/meteor · GitHub

The prototype handles per-hook timeout, error containment, ordering, and a single process.exit — the bits that are easy to get wrong when implemented per-app on top of raw process.on('SIGTERM', …).

A few API decisions (name, hook ordering, timeout semantics, additional signals) deserve community input before it lands — they’re laid out in the PR description. Feedback welcome in the PR :pray:

4 Likes