Spaces:
Running
Running
File size: 9,408 Bytes
548a458 350d89b 548a458 350d89b 548a458 350d89b 548a458 350d89b 548a458 | 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 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | import { WorkerClient } from "./WorkerClient.js";
import { ResourceStore } from "./resourceStore.js";
import type { Config } from "../config.js";
import { newId } from "../utils/ids.js";
import { ToolError } from "../utils/errors.js";
export interface CreateSessionOptions {
initialFiles?: Record<string, string>;
cwd?: string;
ttlSeconds?: number;
capabilities?: {
network?: boolean;
python?: boolean;
javascript?: boolean;
};
ownerTokenHash?: string;
}
export interface SessionRecord {
id: string;
worker: WorkerClient;
cwd: string;
initialFiles: Record<string, string>;
capabilities: { network: boolean; python: boolean; javascript: boolean };
createdAt: number;
lastActiveAt: number;
expiresAt: number;
idleTtlMs: number;
valid: boolean;
invalidReason?: string;
execQueue: Promise<unknown>;
ownerTokenHash?: string;
}
export class SessionManager {
private sessions = new Map<string, SessionRecord>();
private resources: ResourceStore;
private sweepTimer: NodeJS.Timeout | null = null;
private draining = false;
constructor(private readonly cfg: Config) {
this.resources = new ResourceStore(
cfg.maxExecsRetainedSession,
cfg.maxResourceBytesSession,
cfg.maxResourceBytesGlobal,
);
}
get resourceStore() {
return this.resources;
}
get config() {
return this.cfg;
}
count(): number {
return this.sessions.size;
}
startSweeper() {
if (this.sweepTimer) return;
this.sweepTimer = setInterval(() => this.sweep(), this.cfg.sessionSweepIntervalSeconds * 1000);
// Don't keep the event loop alive only for sweeping
if (typeof this.sweepTimer.unref === "function") this.sweepTimer.unref();
}
stopSweeper() {
if (this.sweepTimer) clearInterval(this.sweepTimer);
this.sweepTimer = null;
}
setDraining(value: boolean) {
this.draining = value;
}
isDraining() {
return this.draining;
}
async createSession(opts: CreateSessionOptions): Promise<SessionRecord> {
if (this.draining) {
throw new ToolError("INTERNAL", "Server is draining; cannot create sessions");
}
if (this.sessions.size >= this.cfg.maxSessions) {
throw new ToolError("QUOTA_EXCEEDED", `Max sessions reached (${this.cfg.maxSessions})`);
}
if (opts.ownerTokenHash) {
let perTokenCount = 0;
for (const s of this.sessions.values()) {
if (s.ownerTokenHash === opts.ownerTokenHash) perTokenCount++;
}
if (perTokenCount >= this.cfg.maxSessionsPerToken) {
throw new ToolError(
"QUOTA_EXCEEDED",
`Max sessions per token reached (${this.cfg.maxSessionsPerToken})`,
);
}
}
const cwd = opts.cwd ?? "/home/user";
// Default each capability to "whatever the server allows". Callers can still
// explicitly opt out by passing `false`. They cannot opt in beyond what the server allows.
const askedNetwork = opts.capabilities?.network ?? this.cfg.enableNetwork;
const askedPython = opts.capabilities?.python ?? this.cfg.enablePython;
const askedJs = opts.capabilities?.javascript ?? this.cfg.enableJavaScript;
const capabilities = {
network: askedNetwork && this.cfg.enableNetwork,
python: askedPython && this.cfg.enablePython,
javascript: askedJs && this.cfg.enableJavaScript,
};
const ttlSeconds = Math.min(
Math.max(opts.ttlSeconds ?? this.cfg.sessionIdleTtlSeconds, 30),
this.cfg.sessionIdleTtlSeconds * 4,
);
const id = newId("jb");
const worker = new WorkerClient({ workerMaxOldGenMb: this.cfg.workerMaxOldGenMb });
try {
await worker.init({
sessionId: id,
cwd,
initialFiles: opts.initialFiles ?? {},
capabilities,
networkConfig: capabilities.network
? {
dangerouslyAllowFullInternetAccess:
this.cfg.dangerouslyAllowFullInternetAccess,
allowedUrlPrefixes: this.cfg.allowedUrlPrefixes,
allowedMethods: this.cfg.allowedMethods,
}
: undefined,
executionLimits: {
maxCallDepth: 50,
maxCommandCount: 5000,
maxLoopIterations: 5000,
maxAwkIterations: 5000,
maxSedIterations: 5000,
},
maxSessionFsBytes: this.cfg.maxSessionFsBytes,
maxSingleFileBytes: this.cfg.maxSingleFileBytes,
maxWriteBatchBytes: this.cfg.maxWriteBatchBytes,
maxReadBytesPerCall: this.cfg.maxReadBytesPerCall,
maxCapturedOutputBytesExec: this.cfg.maxCapturedOutputBytesExec,
});
} catch (e) {
await worker.terminate("init_failed");
throw e;
}
const now = Date.now();
const rec: SessionRecord = {
id,
worker,
cwd,
initialFiles: opts.initialFiles ?? {},
capabilities,
createdAt: now,
lastActiveAt: now,
expiresAt: now + ttlSeconds * 1000,
idleTtlMs: ttlSeconds * 1000,
valid: true,
execQueue: Promise.resolve(),
ownerTokenHash: opts.ownerTokenHash,
};
this.sessions.set(id, rec);
return rec;
}
get(id: string): SessionRecord | null {
const s = this.sessions.get(id);
if (!s) return null;
if (Date.now() > s.expiresAt) {
void this.delete(id, "expired");
return null;
}
if (!s.valid) {
return s; // caller will see invalid
}
return s;
}
require(id: string): SessionRecord {
const s = this.get(id);
if (!s) throw new ToolError("UNKNOWN_SESSION", `Unknown or expired session_id`);
if (!s.valid)
throw new ToolError(
"SESSION_INVALID",
`Session is invalid: ${s.invalidReason ?? "terminated"}`,
);
return s;
}
touch(id: string) {
const s = this.sessions.get(id);
if (!s) return;
s.lastActiveAt = Date.now();
s.expiresAt = s.lastActiveAt + s.idleTtlMs;
}
async delete(id: string, reason: string = "deleted"): Promise<boolean> {
const s = this.sessions.get(id);
if (!s) return false;
this.sessions.delete(id);
this.resources.deleteSession(id);
await s.worker.terminate(reason);
return true;
}
async reset(id: string, mode: "empty" | "initial_files"): Promise<SessionRecord> {
const s = this.require(id);
const initialFiles = mode === "initial_files" ? s.initialFiles : {};
await s.worker.terminate("reset");
const newWorker = new WorkerClient({ workerMaxOldGenMb: this.cfg.workerMaxOldGenMb });
try {
await newWorker.init({
sessionId: s.id,
cwd: s.cwd,
initialFiles,
capabilities: s.capabilities,
networkConfig: s.capabilities.network
? {
dangerouslyAllowFullInternetAccess:
this.cfg.dangerouslyAllowFullInternetAccess,
allowedUrlPrefixes: this.cfg.allowedUrlPrefixes,
allowedMethods: this.cfg.allowedMethods,
}
: undefined,
executionLimits: {
maxCallDepth: 50,
maxCommandCount: 5000,
maxLoopIterations: 5000,
maxAwkIterations: 5000,
maxSedIterations: 5000,
},
maxSessionFsBytes: this.cfg.maxSessionFsBytes,
maxSingleFileBytes: this.cfg.maxSingleFileBytes,
maxWriteBatchBytes: this.cfg.maxWriteBatchBytes,
maxReadBytesPerCall: this.cfg.maxReadBytesPerCall,
maxCapturedOutputBytesExec: this.cfg.maxCapturedOutputBytesExec,
});
} catch (e) {
await newWorker.terminate("reset_init_failed");
this.sessions.delete(s.id);
throw e;
}
s.worker = newWorker;
s.lastActiveAt = Date.now();
s.expiresAt = s.lastActiveAt + s.idleTtlMs;
s.valid = true;
s.invalidReason = undefined;
s.execQueue = Promise.resolve();
this.resources.deleteSession(s.id);
return s;
}
invalidate(id: string, reason: string) {
const s = this.sessions.get(id);
if (!s) return;
s.valid = false;
s.invalidReason = reason;
this.resources.deleteSession(id);
void s.worker.terminate(reason);
}
// Serialize exec calls per session.
runOnSessionQueue<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {
const s = this.require(sessionId);
const next = s.execQueue.then(fn, fn);
s.execQueue = next.catch(() => undefined);
return next;
}
sweep() {
const now = Date.now();
for (const s of Array.from(this.sessions.values())) {
if (now > s.expiresAt || !s.valid) {
void this.delete(s.id, !s.valid ? `invalid:${s.invalidReason}` : "expired");
}
}
this.resources.sweepExpired();
}
async shutdown(graceMs: number): Promise<void> {
this.setDraining(true);
this.stopSweeper();
// Wait for in-flight execs per session
const deadline = Date.now() + graceMs;
while (Date.now() < deadline) {
let inflight = 0;
for (const s of this.sessions.values()) {
// Probe queue
const start = Date.now();
let resolved = false;
await Promise.race([
s.execQueue.then(() => {
resolved = true;
}),
new Promise((r) => setTimeout(r, 50)),
]);
if (!resolved && Date.now() - start >= 50) inflight++;
}
if (inflight === 0) break;
}
for (const s of Array.from(this.sessions.values())) {
await this.delete(s.id, "shutdown");
}
}
}
|