receiver.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*!
  2. * Cluster - receiver mixin
  3. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  4. * MIT Licensed
  5. */
  6. module.exports = function(obj){
  7. /**
  8. * Initialize buffer.
  9. */
  10. obj._buf = '';
  11. /**
  12. * Frame incoming command, buffering the given `chunk`
  13. * until a frame is complete. Frames are delimited by a
  14. * line feed.
  15. *
  16. * @param {String} chunk
  17. * @api private
  18. */
  19. obj.frame = function(chunk){
  20. for (var i = 0, len = chunk.length; i < len; ++i) {
  21. if ('\n' == chunk[i]) {
  22. var worker
  23. , obj = JSON.parse(this._buf);
  24. this._buf = '';
  25. if ('number' == typeof obj.id) worker = this.children[obj.id];
  26. this.invoke(obj.method, obj.args, worker);
  27. } else {
  28. this._buf += chunk[i];
  29. }
  30. }
  31. };
  32. /**
  33. * Invoke `method` with the given `args`.
  34. *
  35. * @param {String} method
  36. * @param {Mixed} args
  37. * @param {Worker} worker
  38. * @api private
  39. */
  40. obj.invoke = function(method, args, worker){
  41. if (!method) return;
  42. if (!Array.isArray(args)) args = [args];
  43. if (worker) args.unshift(worker);
  44. if (!this[method]) throw new Error('method ' + method + '() does not exist');
  45. this[method].apply(this, args);
  46. };
  47. };