Skip to content

Commit

Permalink
feat(link): add _onAttach deferred attach handler
Browse files Browse the repository at this point in the history
  • Loading branch information
mbroadst committed Aug 2, 2015
1 parent e77a5be commit f442604
Showing 1 changed file with 19 additions and 13 deletions.
32 changes: 19 additions & 13 deletions lib/link.js
Expand Up @@ -22,6 +22,8 @@ function Link(session, handle, linkPolicy) {
this.attached = false;
this.remoteHandle = undefined;

this._onAttach = [];

var self = this;
var stateMachine = {
'DETACHED': {
Expand Down Expand Up @@ -69,14 +71,14 @@ Link.MessageReceived = 'message';
Link.ErrorReceived = 'error';

// On link credit changed.
Link.CreditChange = 'link:creditChange';
Link.CreditChange = 'creditChange';


// On completion of detach.
Link.Attached = 'link:attached';
Link.Attached = 'attached';

// On completion of detach.
Link.Detached = 'link:detached';
Link.Detached = 'detached';

// public api
Link.prototype.attach = function() {
Expand Down Expand Up @@ -113,6 +115,13 @@ Link.prototype.detach = function() {
};

// private api
Link.prototype._resolveAttachPromises = function(err, link) {
while (this._onAttach.length) {
var attachPromise = this._onAttach.shift();
attachPromise(err, link);
}
};

Link.prototype._attachReceived = function(attachFrame) {
this.linkSM.attachReceived();
// process params.
Expand All @@ -121,12 +130,10 @@ Link.prototype._attachReceived = function(attachFrame) {
debug('Rx attach CH=[' + this.session.channel + '=>' + attachFrame.channel + '], Handle=[' + this.handle + '=>' + attachFrame.handle + ']');
this.attached = true;

// @todo: Session should listen for Link.Attached
this.session._linkAttached(this);
this.emit(Link.Attached, this);
this._resolveAttachPromises(null, this);

this._checkCredit();

this.emit(Link.Attached, this);
};

// default implementation does nothing
Expand All @@ -151,17 +158,16 @@ Link.prototype._detached = function(frame) {
}

if (this.remoteHandle !== undefined) {
this.session._linksByRemoteHandle[this.remoteHandle] = undefined;
delete this.session._linksByRemoteHandle[this.remoteHandle];
this.remoteHandle = undefined;
}

this.session._linksByName[this.policy.options.name] = undefined;
this.session._allocatedHandles[this.policy.options.handle] = undefined;
delete this.session._linksByName[this.policy.options.name];
delete this.session._allocatedHandles[this.policy.options.handle];
this.attached = false;
this.emit(Link.Detached, { closed: frame.closed, error: frame.error });

// @todo: Session should listen for Link.Detached
this.session._linkDetached(this);
this.emit(Link.Detached, { closed: frame.closed, error: frame.error });
this._resolveAttachPromises(frame.error ? frame.error : 'link closed');
};

module.exports = Link;

0 comments on commit f442604

Please sign in to comment.