diffusion
Version:
Diffusion JavaScript client
86 lines (70 loc) • 2.44 kB
JavaScript
var HashMap = require('hashmap');
var Arrays = require('util/array');
var ErrorReason = require('../../errors/error-reason');
/*
* Internal registry for Subscription streams.
*/
module.exports = function StreamRegistry(topicCache) {
var streams = new HashMap();
var fallbacks = [];
var self = this;
this.add = function(selector, stream) {
var existing = streams.get(selector);
if (existing) {
existing.push(stream);
} else {
streams.set(selector, [stream]);
}
topicCache.newStream(selector, stream, self);
stream.onOpen();
};
this.addFallback = function(stream) {
fallbacks.push(stream);
};
this.getFallbacks = function(specification) {
return fallbacks.filter(function(fallback) {
return fallback.selects(specification);
});
};
this.remove = function(stream) {
Arrays.remove(fallbacks, stream);
streams.forEach(function(existing, selector) {
if (Arrays.remove(existing, stream)) {
topicCache.removeStream(stream, self);
}
if (existing.length === 0) {
streams.remove(selector);
}
});
};
this.streamsFor = function(topic, specification) {
var combined = [];
if (streams.count() > 0) {
streams.forEach(function(existing, selector) {
if (selector.selects(topic)) {
combined = combined.concat(existing
.filter(function(stream) {
return stream.selects(specification);
}).map(function(stream) {
return stream.adapter?stream.adapter(specification):stream;
})
);
}
});
}
return combined;
};
this.close = function() {
// Session is closing down, don't notify fallback streams of any subscription
// from other value streams.
topicCache.clear();
streams.values().forEach(function(streamArray) {
streamArray.forEach(function(stream) {
stream.onSubscriptionError(ErrorReason.SESSION_CLOSED);
});
});
fallbacks.forEach(function(stream) {
stream.onSubscriptionError(ErrorReason.SESSION_CLOSED);
});
};
};