reuse LRU Cache for session cache

This commit is contained in:
Bruno Windels 2021-03-05 17:01:38 +01:00
parent f0c0c3e084
commit 4e0bd16a4e
2 changed files with 21 additions and 25 deletions

View file

@ -14,15 +14,16 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import {BaseLRUCache} from "../../../../utils/LRUCache.js";
const DEFAULT_CACHE_SIZE = 10; const DEFAULT_CACHE_SIZE = 10;
/** /**
* Cache of unpickled inbound megolm session. * Cache of unpickled inbound megolm session.
*/ */
export class SessionCache { export class SessionCache extends BaseLRUCache {
constructor(size) { constructor(limit) {
this._size = typeof size === "number" ? size : DEFAULT_CACHE_SIZE; limit = typeof limit === "number" ? limit : DEFAULT_CACHE_SIZE;
this._sessions = []; super(limit);
} }
/** /**
@ -32,37 +33,28 @@ export class SessionCache {
* @return {SessionInfo?} * @return {SessionInfo?}
*/ */
get(roomId, senderKey, sessionId) { get(roomId, senderKey, sessionId) {
const idx = this._sessions.findIndex(s => { return this._get(s => {
return s.roomId === roomId && return s.roomId === roomId &&
s.senderKey === senderKey && s.senderKey === senderKey &&
sessionId === s.session.session_id(); sessionId === s.sessionId;
}); });
if (idx !== -1) {
const sessionInfo = this._sessions[idx];
// move to top
if (idx > 0) {
this._sessions.splice(idx, 1);
this._sessions.unshift(sessionInfo);
}
return sessionInfo;
}
} }
add(sessionInfo) { add(sessionInfo) {
sessionInfo.retain(); sessionInfo.retain();
// add new at top this._set(sessionInfo, s => {
this._sessions.unshift(sessionInfo); return s.roomId === sessionInfo.roomId &&
if (this._sessions.length > this._size) { s.senderKey === sessionInfo.senderKey &&
// free sessions we're about to remove s.sessionId === sessionInfo.sessionId;
for (let i = this._size; i < this._sessions.length; i += 1) { });
this._sessions[i].release();
}
this._sessions = this._sessions.slice(0, this._size);
} }
_onEvictEntry(sessionInfo) {
sessionInfo.release();
} }
dispose() { dispose() {
for (const sessionInfo of this._sessions) { for (const sessionInfo of this._entries) {
sessionInfo.release(); sessionInfo.release();
} }
} }

View file

@ -27,6 +27,10 @@ export class SessionInfo {
this._refCounter = 0; this._refCounter = 0;
} }
get sessionId() {
return this.session?.session_id();
}
retain() { retain() {
this._refCounter += 1; this._refCounter += 1;
} }