story-research-zapwall/lib/relaySessionManager.ts
2026-01-06 20:59:59 +01:00

106 lines
3.0 KiB
TypeScript

/**
* Relay session manager
* Tracks which relays are active/inactive during the current browser session
* Relays that fail (connection or publish errors) are moved to the bottom of the priority list
* All relays are reset to active on page load
*/
import { getEnabledRelays } from './config'
class RelaySessionManager {
private failedRelays: Set<string> = new Set() // Relays that have failed (moved to bottom)
/**
* Initialize: reset all relays to active at session start
*/
public async initialize(): Promise<void> {
this.failedRelays.clear()
console.log('[RelaySessionManager] Session initialized - all relays active')
}
/**
* Get active relays (enabled relays, with failed ones moved to the bottom)
* Failed relays are still active but prioritized last
*/
public async getActiveRelays(): Promise<string[]> {
const enabledRelays = await getEnabledRelays()
// Separate working relays from failed ones
const workingRelays: string[] = []
const failedRelaysList: string[] = []
for (const relay of enabledRelays) {
if (this.failedRelays.has(relay)) {
failedRelaysList.push(relay)
} else {
workingRelays.push(relay)
}
}
// Return working relays first, then failed ones at the bottom
return [...workingRelays, ...failedRelaysList]
}
/**
* Mark a relay as failed (move it to the bottom of the priority list)
*/
public markRelayFailed(relayUrl: string): void {
if (!this.failedRelays.has(relayUrl)) {
this.failedRelays.add(relayUrl)
console.warn(`[RelaySessionManager] Relay moved to bottom of priority list: ${relayUrl}`)
}
}
/**
* Check if a relay has failed (is at the bottom of the list)
*/
public isRelayFailed(relayUrl: string): boolean {
return this.failedRelays.has(relayUrl)
}
/**
* Get list of failed relays for this session
*/
public getFailedRelays(): string[] {
return Array.from(this.failedRelays)
}
/**
* Get count of active relays (including failed ones at the bottom)
*/
public async getActiveRelayCount(): Promise<number> {
const activeRelays = await this.getActiveRelays()
return activeRelays.length
}
/**
* Legacy method name for compatibility (now moves to bottom instead of deactivating)
*/
public markRelayInactive(relayUrl: string): void {
this.markRelayFailed(relayUrl)
}
/**
* Legacy method name for compatibility (failed relays are still "active" but at bottom)
*/
public isRelayActive(_relayUrl: string): boolean {
// All enabled relays are considered "active", even if failed
// They're just at the bottom of the priority list
return true
}
/**
* Legacy method name for compatibility
*/
public getInactiveRelays(): string[] {
return this.getFailedRelays()
}
}
export const relaySessionManager = new RelaySessionManager()
// Initialize on module load (page load)
if (typeof window !== 'undefined') {
void relaySessionManager.initialize()
}