2021-10-30 17:26:41 +00:00
|
|
|
import Globals from './globals';
|
|
|
|
|
2021-11-18 01:26:32 +00:00
|
|
|
import { Resource, ShouldNeverHappenError } from './data-types';
|
2021-10-30 17:26:41 +00:00
|
|
|
|
|
|
|
export default class ResourceRAMCache {
|
2021-11-18 01:26:32 +00:00
|
|
|
private data = new Map<string, { resource: Resource, lastUsed: Date }>(); // (guildId, resourceId) -> { resource, lastUsed }
|
|
|
|
private size = 0;
|
2021-10-30 17:26:41 +00:00
|
|
|
|
2021-11-18 01:26:32 +00:00
|
|
|
public putResource(guildId: number, resource: Resource): void {
|
|
|
|
if (resource.data.length > Globals.MAX_RESOURCE_SIZE) { // skip resources if they would flood the cache
|
2021-11-07 16:50:30 +00:00
|
|
|
return;
|
|
|
|
}
|
2021-11-18 01:26:32 +00:00
|
|
|
let id = `s#${guildId}/r#${resource.id}`;
|
|
|
|
this.data.set(id, { resource: resource, lastUsed: new Date() });
|
|
|
|
this.size += resource.data.length;
|
2021-11-22 03:01:40 +00:00
|
|
|
if (this.size > Globals.MAX_GUILD_RESOURCE_CACHE_SIZE) { // TODO: this feature needs to be tested
|
2021-11-18 01:26:32 +00:00
|
|
|
let entries = Array.from(this.data.entries())
|
2021-11-07 16:50:30 +00:00
|
|
|
.map(([ key, value ]) => { return { id: key, value: value }; })
|
|
|
|
.sort((a, b) => b.value.lastUsed.getTime() - a.value.lastUsed.getTime()); // oldest last (for pop)
|
2021-11-22 03:01:40 +00:00
|
|
|
while (this.size > Globals.MAX_GUILD_RESOURCE_CACHE_SIZE) {
|
2021-11-07 16:50:30 +00:00
|
|
|
let entry = entries.pop();
|
|
|
|
if (entry === undefined) throw new ShouldNeverHappenError('No entry in the array but the ram cache still has a size...');
|
2021-11-18 01:26:32 +00:00
|
|
|
this.data.delete(entry.id);
|
|
|
|
this.size -= entry.value.resource.data.length;
|
2021-11-07 16:50:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-10-30 17:26:41 +00:00
|
|
|
|
2021-11-18 01:26:32 +00:00
|
|
|
public getResource(guildId: number, resourceId: string): Resource | null {
|
|
|
|
let id = `s#${guildId}/r#${resourceId}`;
|
|
|
|
let v = this.data.get(id);
|
2021-11-07 16:50:30 +00:00
|
|
|
if (!v) return null;
|
|
|
|
v.lastUsed = new Date();
|
|
|
|
return v.resource;
|
|
|
|
}
|
2021-10-30 17:26:41 +00:00
|
|
|
}
|