1 | 'use strict';
|
---|
2 |
|
---|
3 | var Functor = require('./functor'),
|
---|
4 | Pledge = require('./pledge');
|
---|
5 |
|
---|
6 | var Cell = function(tuple) {
|
---|
7 | this._ext = tuple[0];
|
---|
8 | this._session = tuple[1];
|
---|
9 |
|
---|
10 | this._functors = {
|
---|
11 | incoming: new Functor(this._session, 'processIncomingMessage'),
|
---|
12 | outgoing: new Functor(this._session, 'processOutgoingMessage')
|
---|
13 | };
|
---|
14 | };
|
---|
15 |
|
---|
16 | Cell.prototype.pending = function(direction) {
|
---|
17 | var functor = this._functors[direction];
|
---|
18 | if (!functor._stopped) functor.pending += 1;
|
---|
19 | };
|
---|
20 |
|
---|
21 | Cell.prototype.incoming = function(error, message, callback, context) {
|
---|
22 | this._exec('incoming', error, message, callback, context);
|
---|
23 | };
|
---|
24 |
|
---|
25 | Cell.prototype.outgoing = function(error, message, callback, context) {
|
---|
26 | this._exec('outgoing', error, message, callback, context);
|
---|
27 | };
|
---|
28 |
|
---|
29 | Cell.prototype.close = function() {
|
---|
30 | this._closed = this._closed || new Pledge();
|
---|
31 | this._doClose();
|
---|
32 | return this._closed;
|
---|
33 | };
|
---|
34 |
|
---|
35 | Cell.prototype._exec = function(direction, error, message, callback, context) {
|
---|
36 | this._functors[direction].call(error, message, function(err, msg) {
|
---|
37 | if (err) err.message = this._ext.name + ': ' + err.message;
|
---|
38 | callback.call(context, err, msg);
|
---|
39 | this._doClose();
|
---|
40 | }, this);
|
---|
41 | };
|
---|
42 |
|
---|
43 | Cell.prototype._doClose = function() {
|
---|
44 | var fin = this._functors.incoming,
|
---|
45 | fout = this._functors.outgoing;
|
---|
46 |
|
---|
47 | if (!this._closed || fin.pending + fout.pending !== 0) return;
|
---|
48 | if (this._session) this._session.close();
|
---|
49 | this._session = null;
|
---|
50 | this._closed.done();
|
---|
51 | };
|
---|
52 |
|
---|
53 | module.exports = Cell;
|
---|