You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.4 KiB
JavaScript

"use strict";
const debug = require("debug")("promistream:dynamic:stream-pool");
const unreachable = require("@joepie91/unreachable")("@promistream/dynamic");
const valueID = require("./value-id");
// TODO: Separate out into own package + update `unreachable` label accordingly
// TODO: Validation
module.exports = function createStreamPool() {
let pool = new WeakMap();
let streamTypes = new Map();
return {
acquire: function (streamFactory) {
if (!pool.has(streamFactory)) {
pool.set(streamFactory, []);
}
let availableStreams = pool.get(streamFactory);
if (availableStreams.length === 0) {
debug(`Ran out of streams for type ${valueID(streamFactory)}, creating a new one...`);
let newStream = streamFactory();
streamTypes.set(newStream, streamFactory);
// TODO: Periodic cleanup and activity tracking for instances
availableStreams.push(newStream);
} else {
debug(`Reusing stream from pool for type ${valueID(streamFactory)}`);
}
let acquiredStream = availableStreams.shift();
if (acquiredStream.reset != null) {
acquiredStream.reset();
}
return acquiredStream;
},
release: function (stream) {
let streamFactory = streamTypes.get(stream);
if (streamFactory != null) {
let availableStreams = pool.get(streamFactory);
availableStreams.push(stream);
} else {
throw unreachable(`Specified stream does not belong to the pool`);
}
}
};
};