wasm-rdp/filegateway/session_pool.js
2024-05-08 22:56:40 +08:00

73 lines
1.9 KiB
JavaScript

/**
* Represents a pool of sessions.
* @class
*/
/**
* Represents a pool of sessions.
* @template T - The type of session value.
*/
class SessionPool {
/**
* Creates a new SessionPool instance.
* @constructor
* @param {number} expirationTime - The expiration time for sessions in milliseconds.
*/
constructor(expirationTime) {
this.sessions = new Map();
this.expirationTime = expirationTime;
// Set up a timer to clean up expired sessions
setInterval(() => this.cleanupSessions(), expirationTime);
}
/**
* Retrieves a session from the pool.
* @param {string} key - The key of the session to retrieve.
* @returns {T | null} The session value if it exists and is not expired, otherwise null.
*/
getSession(key) {
const now = Date.now();
const session = this.sessions.get(key);
// If the session exists and is not expired, return it
if (session && session.expiration > now) {
session.expiration = now + this.expirationTime
return session.value;
}
return null;
}
/**
* Creates a new session in the pool.
* @param {string} key - The key of the session to create.
* @param {T} session - The session value.
* @param {Function} off - The function to call when the session is removed from the pool.
*/
createSession(key, session, off) {
this.sessions.set(key, {
expiration: Date.now() + this.expirationTime,
value: session,
off
});
}
/**
* Cleans up expired sessions from the pool.
*/
async cleanupSessions() {
const now = Date.now();
for (const [key, session] of this.sessions) {
if (session.expiration <= now) {
this.sessions.delete(key);
try {
await session.off(session.value)
} catch(e) {
console.error("cleanupSessions: ", e);
}
}
}
}
}
module.exports = SessionPool