/**
* Test SessionManager functionality
*/
import { SessionManager } from './core/SessionManager.js';
import { PythonRuntime } from './runtimes/PythonRuntime.js';
import type { SessionConfig } from './types/index.js';
async function testSessionManager() {
console.log('š§Ŗ Testing SessionManager...\n');
console.log('=' .repeat(60));
const manager = SessionManager.getInstance();
const runtime = new PythonRuntime();
try {
// 1. Initialize
console.log('\n1ļøā£ Initializing SessionManager...');
await manager.initialize(5000); // 5s GC interval for testing
console.log(' ā
SessionManager initialized');
// 2. Create session
console.log('\n2ļøā£ Creating session "test-python"...');
const config: SessionConfig = {
language: 'python',
packages: ['requests'],
env: { TEST_VAR: 'hello' },
ttl: 300, // 5 minutes
};
const session1 = await manager.create('test-python', config);
console.log(` ā
Session created: ${session1.id.substring(0, 8)}`);
console.log(` ā
Name: ${session1.name}`);
console.log(` ā
Language: ${session1.language}`);
console.log(` ā
State: ${session1.state}`);
console.log(` ā
Container: ${session1.container.id.substring(0, 12)}`);
console.log(` ā
Expires: ${session1.expiresAt?.toISOString()}`);
// 3. Execute code in session
console.log('\n3ļøā£ Executing code in session...');
const result1 = await runtime.execute(
'print("Hello from session test-python!")',
{
container: session1.container,
timeout: 5000,
env: session1.metadata.env,
}
);
if (result1.exitCode === 0) {
console.log(` ā
Output: ${result1.stdout.trim()}`);
} else {
console.log(` ā ļø Error: ${result1.stderr}`);
}
// 4. Get session by name
console.log('\n4ļøā£ Getting session by name...');
const retrieved = await manager.get('test-python');
if (retrieved) {
console.log(` ā
Retrieved session: ${retrieved.id.substring(0, 8)}`);
console.log(` ā
Same ID: ${retrieved.id === session1.id}`);
} else {
console.log(' ā Session not found');
}
// 5. List sessions
console.log('\n5ļøā£ Listing all sessions...');
const sessions = await manager.list();
console.log(` ā
Total sessions: ${sessions.length}`);
sessions.forEach(s => {
console.log(` - ${s.name} (${s.language}, ${s.state})`);
});
// 6. Create second session
console.log('\n6ļøā£ Creating second session "test-js"...');
const session2 = await manager.create('test-js', {
language: 'javascript',
ttl: 60, // 1 minute
});
console.log(` ā
Session created: ${session2.id.substring(0, 8)}`);
// List again
const sessions2 = await manager.list();
console.log(` ā
Total sessions now: ${sessions2.length}`);
// 7. Pause session
console.log('\n7ļøā£ Pausing session "test-python"...');
await manager.pause(session1.id);
const paused = await manager.get(session1.id);
console.log(` ā
State after pause: ${paused?.state}`);
// 8. Resume session
console.log('\n8ļøā£ Resuming session "test-python"...');
await manager.resume(session1.id);
const resumed = await manager.get(session1.id);
console.log(` ā
State after resume: ${resumed?.state}`);
// 9. Extend TTL
console.log('\n9ļøā£ Extending session TTL by 60 seconds...');
const beforeExtend = session1.expiresAt;
await manager.extend(session1.id, 60);
const afterExtend = await manager.get(session1.id);
console.log(` ā
Before: ${beforeExtend?.toISOString()}`);
console.log(` ā
After: ${afterExtend?.expiresAt?.toISOString()}`);
// 10. Test session count
console.log('\nš Session statistics...');
console.log(` ā
Total sessions: ${manager.getCount()}`);
console.log(` ā
Active: ${manager.getByState('active').length}`);
console.log(` ā
Paused: ${manager.getByState('paused').length}`);
console.log(` ā
Stopped: ${manager.getByState('stopped').length}`);
// 11. Test cleanup (won't do anything since sessions not expired)
console.log('\n1ļøā£1ļøā£ Testing garbage collection...');
await manager.cleanup();
console.log(` ā
Sessions after GC: ${manager.getCount()} (no change expected)`);
// 12. Test expired session cleanup
console.log('\n1ļøā£2ļøā£ Testing expired session cleanup...');
console.log(' Creating session with 2 second TTL...');
const shortSession = await manager.create('short-lived', {
language: 'bash',
ttl: 2, // 2 seconds
});
console.log(` ā
Session created: ${shortSession.id.substring(0, 8)}`);
console.log(` ā³ Waiting 3 seconds for expiration...`);
await new Promise(resolve => setTimeout(resolve, 3000));
console.log(' Running cleanup...');
await manager.cleanup();
const afterCleanup = await manager.get('short-lived');
console.log(` ā
Session after cleanup: ${afterCleanup ? 'EXISTS (error!)' : 'REMOVED (correct!)'}`);
// 13. Destroy remaining sessions
console.log('\n1ļøā£3ļøā£ Destroying remaining sessions...');
const remaining = await manager.list();
console.log(` Sessions to destroy: ${remaining.length}`);
for (const s of remaining) {
try {
await manager.destroy(s.id);
console.log(` ā
Destroyed: ${s.name}`);
} catch (error: any) {
console.log(` ā ļø ${s.name} already destroyed (by GC)`);
}
}
console.log(` ā
Sessions after destroy: ${manager.getCount()}`);
console.log('\n' + '='.repeat(60));
console.log('\nš All SessionManager tests passed!\n');
} catch (error: any) {
console.error('\nā Test failed:', error.message);
if (error.stack) {
console.error(error.stack);
}
process.exit(1);
} finally {
// Shutdown
console.log('š§¹ Shutting down SessionManager...');
await manager.shutdown();
console.log(' ā
SessionManager shut down\n');
}
}
testSessionManager();