feat: add SessionManager for multi-frontend session handling
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
import type { Message } from '../models/types.js';
|
||||
import type { SessionStore } from './store.js';
|
||||
|
||||
export interface Session {
|
||||
id: string;
|
||||
addMessage(message: Message): void;
|
||||
getHistory(): Message[];
|
||||
clear(): void;
|
||||
}
|
||||
|
||||
export class ManagedSession implements Session {
|
||||
constructor(
|
||||
public readonly id: string,
|
||||
private store: SessionStore,
|
||||
private history: Message[] = []
|
||||
) {}
|
||||
|
||||
addMessage(message: Message): void {
|
||||
this.history.push(message);
|
||||
this.store.addMessage(this.id, message);
|
||||
}
|
||||
|
||||
getHistory(): Message[] {
|
||||
return [...this.history];
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.history = [];
|
||||
this.store.clearSession(this.id);
|
||||
}
|
||||
|
||||
setHistory(messages: Message[]): void {
|
||||
this.history = [...messages];
|
||||
}
|
||||
}
|
||||
|
||||
export class SessionManager {
|
||||
private sessions: Map<string, ManagedSession> = new Map();
|
||||
|
||||
constructor(private store: SessionStore) {}
|
||||
|
||||
private makeSessionId(frontend: string, userId: string): string {
|
||||
return `${frontend}:${userId}`;
|
||||
}
|
||||
|
||||
getSession(frontend: string, userId: string): ManagedSession {
|
||||
const id = this.makeSessionId(frontend, userId);
|
||||
|
||||
let session = this.sessions.get(id);
|
||||
if (!session) {
|
||||
const history = this.store.getMessages(id);
|
||||
session = new ManagedSession(id, this.store, history);
|
||||
this.sessions.set(id, session);
|
||||
}
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
transferSession(
|
||||
fromFrontend: string,
|
||||
fromUserId: string,
|
||||
toFrontend: string,
|
||||
toUserId: string
|
||||
): void {
|
||||
const fromSession = this.getSession(fromFrontend, fromUserId);
|
||||
const toSession = this.getSession(toFrontend, toUserId);
|
||||
|
||||
const history = fromSession.getHistory();
|
||||
|
||||
// Clear target and copy history
|
||||
toSession.clear();
|
||||
for (const message of history) {
|
||||
toSession.addMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
listSessions(): string[] {
|
||||
return Array.from(this.sessions.keys());
|
||||
}
|
||||
|
||||
closeSession(frontend: string, userId: string): void {
|
||||
const id = this.makeSessionId(frontend, userId);
|
||||
this.sessions.delete(id);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user