-
Notifications
You must be signed in to change notification settings - Fork 583
Expand file tree
/
Copy pathsession.ts
More file actions
190 lines (169 loc) · 4.5 KB
/
session.ts
File metadata and controls
190 lines (169 loc) · 4.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
/**
* Session Persistence Store
*
* Tracks model selections per session to prevent model switching mid-task.
* When a session is active, the router will continue using the same model
* instead of re-routing each request.
*/
export type SessionEntry = {
model: string;
tier: string;
routingProfile?: "free" | "eco" | "auto" | "premium";
createdAt: number;
lastUsedAt: number;
requestCount: number;
};
export type SessionConfig = {
/** Enable session persistence (default: false) */
enabled: boolean;
/** Session timeout in ms (default: 30 minutes) */
timeoutMs: number;
/** Header name for session ID (default: X-Session-ID) */
headerName: string;
};
export const DEFAULT_SESSION_CONFIG: SessionConfig = {
enabled: false,
timeoutMs: 30 * 60 * 1000, // 30 minutes
headerName: "x-session-id",
};
/**
* Session persistence store for maintaining model selections.
*/
export class SessionStore {
private sessions: Map<string, SessionEntry> = new Map();
private config: SessionConfig;
private cleanupInterval: ReturnType<typeof setInterval> | null = null;
constructor(config: Partial<SessionConfig> = {}) {
this.config = { ...DEFAULT_SESSION_CONFIG, ...config };
// Start cleanup interval (every 5 minutes)
if (this.config.enabled) {
this.cleanupInterval = setInterval(() => this.cleanup(), 5 * 60 * 1000);
}
}
/**
* Get the pinned model for a session, if any.
*/
getSession(sessionId: string): SessionEntry | undefined {
if (!this.config.enabled || !sessionId) {
return undefined;
}
const entry = this.sessions.get(sessionId);
if (!entry) {
return undefined;
}
// Check if session has expired
const now = Date.now();
if (now - entry.lastUsedAt > this.config.timeoutMs) {
this.sessions.delete(sessionId);
return undefined;
}
return entry;
}
/**
* Pin a model to a session.
*/
setSession(
sessionId: string,
model: string,
tier: string,
routingProfile?: "free" | "eco" | "auto" | "premium",
): void {
if (!this.config.enabled || !sessionId) {
return;
}
const existing = this.sessions.get(sessionId);
const now = Date.now();
if (existing) {
existing.lastUsedAt = now;
existing.requestCount++;
// Update model if different (e.g., fallback)
if (existing.model !== model) {
existing.model = model;
existing.tier = tier;
}
existing.routingProfile = routingProfile;
} else {
this.sessions.set(sessionId, {
model,
tier,
routingProfile,
createdAt: now,
lastUsedAt: now,
requestCount: 1,
});
}
}
/**
* Touch a session to extend its timeout.
*/
touchSession(sessionId: string): void {
if (!this.config.enabled || !sessionId) {
return;
}
const entry = this.sessions.get(sessionId);
if (entry) {
entry.lastUsedAt = Date.now();
entry.requestCount++;
}
}
/**
* Clear a specific session.
*/
clearSession(sessionId: string): void {
this.sessions.delete(sessionId);
}
/**
* Clear all sessions.
*/
clearAll(): void {
this.sessions.clear();
}
/**
* Get session stats for debugging.
*/
getStats(): { count: number; sessions: Array<{ id: string; model: string; age: number }> } {
const now = Date.now();
const sessions = Array.from(this.sessions.entries()).map(([id, entry]) => ({
id: id.slice(0, 8) + "...",
model: entry.model,
age: Math.round((now - entry.createdAt) / 1000),
}));
return { count: this.sessions.size, sessions };
}
/**
* Clean up expired sessions.
*/
private cleanup(): void {
const now = Date.now();
for (const [id, entry] of this.sessions) {
if (now - entry.lastUsedAt > this.config.timeoutMs) {
this.sessions.delete(id);
}
}
}
/**
* Stop the cleanup interval.
*/
close(): void {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
this.cleanupInterval = null;
}
}
}
/**
* Generate a session ID from request headers or create a default.
*/
export function getSessionId(
headers: Record<string, string | string[] | undefined>,
headerName: string = DEFAULT_SESSION_CONFIG.headerName,
): string | undefined {
const value = headers[headerName] || headers[headerName.toLowerCase()];
if (typeof value === "string" && value.length > 0) {
return value;
}
if (Array.isArray(value) && value.length > 0) {
return value[0];
}
return undefined;
}