Skip to content

Commit

Permalink
refactor: 标准化与提高缓存策略
Browse files Browse the repository at this point in the history
  • Loading branch information
MliKiowa committed Jan 13, 2025
1 parent 7c8cbc0 commit 607dd68
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
49 changes: 43 additions & 6 deletions src/common/file-uuid.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Peer } from '@/core';
import { LRUCache } from './lru-cache';
import { randomUUID } from 'crypto';

interface FileUUIDData {
Expand All @@ -11,11 +10,49 @@ interface FileUUIDData {
fileUUID?: string;
}

class TimeBasedCache<K, V> {
private cache: Map<K, { value: V, timestamp: number }>;
private ttl: number;

constructor(ttl: number) {
this.cache = new Map();
this.ttl = ttl;
}

public put(key: K, value: V): void {
const timestamp = Date.now();
this.cache.set(key, { value, timestamp });
this.cleanup();
}

public get(key: K): V | undefined {
const entry = this.cache.get(key);
if (entry) {
const currentTime = Date.now();
if (currentTime - entry.timestamp < this.ttl) {
return entry.value;
} else {
this.cache.delete(key);
}
}
return undefined;
}

private cleanup(): void {
const currentTime = Date.now();
for (const [key, entry] of this.cache.entries()) {
if (currentTime - entry.timestamp >= this.ttl) {
this.cache.delete(key);
}
}
}
}

class FileUUIDManager {
private cache: LRUCache<string, FileUUIDData>;
private cache: TimeBasedCache<string, FileUUIDData>;

constructor(capacity: number) {
this.cache = new LRUCache<string, FileUUIDData>(capacity);
constructor(ttl: number) {
this.cache = new TimeBasedCache<string, FileUUIDData>(ttl);
}

public encode(data: FileUUIDData, endString: string = "", customUUID?: string): string {
Expand All @@ -32,8 +69,8 @@ class FileUUIDManager {
export class FileNapCatOneBotUUIDWrap {
private manager: FileUUIDManager;

constructor(capacity: number = 100) {
this.manager = new FileUUIDManager(capacity);
constructor(ttl: number = 86400000) {
this.manager = new FileUUIDManager(ttl);
}

public encodeModelId(peer: Peer, modelId: string, fileId: string, fileUUID: string = "", endString: string = "", customUUID?: string): string {
Expand Down
2 changes: 1 addition & 1 deletion src/common/message-unique.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class MessageUniqueWrapper {
private readonly msgDataMap: LimitedHashTable<string, number>;
private readonly msgIdMap: LimitedHashTable<string, number>;

constructor(maxMap: number = 1000) {
constructor(maxMap: number = 5000) {
this.msgIdMap = new LimitedHashTable<string, number>(maxMap);
this.msgDataMap = new LimitedHashTable<string, number>(maxMap);
}
Expand Down

0 comments on commit 607dd68

Please sign in to comment.