createSession method
Creates a new session for a proxy and domain
Implementation
ProxySession createSession({
required Proxy proxy,
required String domain,
String? userAgent,
Map<String, String>? cookies,
Map<String, String>? headers,
}) {
// Clean up old sessions
_cleanupSessions();
// Check if we already have a session for this proxy and domain
final existingSession = getSession(proxy: proxy, domain: domain);
if (existingSession != null && existingSession.isActive) {
logger?.info(
'Using existing session for ${proxy.host}:${proxy.port} on $domain',
);
existingSession.updateLastAccessTime();
return existingSession;
}
// Check if we have too many sessions for this proxy
final proxyKey = '${proxy.host}:${proxy.port}';
final proxySessions = _sessionsByProxy[proxyKey] ?? [];
if (proxySessions.length >= maxSessionsPerProxy) {
// Remove the oldest session
logger?.info('Removing oldest session for ${proxy.host}:${proxy.port}');
final oldestSession = proxySessions.reduce(
(a, b) => a.lastAccessTime.isBefore(b.lastAccessTime) ? a : b,
);
_removeSession(oldestSession);
}
// Create a new session
final sessionId = _generateSessionId();
final session = ProxySession(
proxy: proxy,
sessionId: sessionId,
userAgent: userAgent ?? _generateUserAgent(),
cookies: cookies,
headers: headers,
);
// Add the session to the maps
_sessionsById[sessionId] = session;
_sessionsByProxy.putIfAbsent(proxyKey, () => []).add(session);
_sessionsByDomain
.putIfAbsent(domain, () => {})
.putIfAbsent(proxyKey, () => session);
logger?.info(
'Created new session for ${proxy.host}:${proxy.port} on $domain',
);
return session;
}