mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Refactor SSE event handling and consolidate notification contexts
This commit is contained in:
1 parent
9851ec06e0
commit
f7fd3176d4
30 files changed
+2226
-988
No files matched your search
@@ -0,0 +1,48 @@
|
||||
type SessionKeyedItem = { id: string; sessionID: string }
|
||||
type SessionKeyedState<T> = Record<string, T[]>
|
||||
type StateSetter<T> = React.Dispatch<React.SetStateAction<SessionKeyedState<T>>>
|
||||
|
||||
export function addToSessionKeyedState<T extends SessionKeyedItem>(
|
||||
setter: StateSetter<T>,
|
||||
item: T
|
||||
): void {
|
||||
setter(prev => {
|
||||
const sessionID = item.sessionID
|
||||
const existing = prev[sessionID] ?? []
|
||||
const existingIndex = existing.findIndex(i => i.id === item.id)
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
const updated = [...existing]
|
||||
updated[existingIndex] = item
|
||||
return { ...prev, [sessionID]: updated }
|
||||
}
|
||||
return { ...prev, [sessionID]: [...existing, item] }
|
||||
})
|
||||
}
|
||||
|
||||
export function removeFromSessionKeyedState<T extends SessionKeyedItem>(
|
||||
setter: StateSetter<T>,
|
||||
id: string,
|
||||
sessionID?: string
|
||||
): void {
|
||||
setter(prev => {
|
||||
if (sessionID) {
|
||||
const existing = prev[sessionID]
|
||||
if (!existing) return prev
|
||||
const filtered = existing.filter(i => i.id !== id)
|
||||
if (filtered.length === 0) {
|
||||
const { [sessionID]: _removed, ...rest } = prev
|
||||
void _removed
|
||||
return rest
|
||||
}
|
||||
return { ...prev, [sessionID]: filtered }
|
||||
}
|
||||
|
||||
const newState: SessionKeyedState<T> = {}
|
||||
for (const [sid, items] of Object.entries(prev)) {
|
||||
const filtered = items.filter(i => i.id !== id)
|
||||
if (filtered.length > 0) newState[sid] = filtered
|
||||
}
|
||||
return newState
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
import { DEFAULTS } from '@opencode-manager/shared/config'
|
||||
|
||||
type SSEEventHandler = (data: unknown) => void
|
||||
type SSEStatusHandler = (connected: boolean) => void
|
||||
|
||||
interface SSESubscriber {
|
||||
id: string
|
||||
onMessage: SSEEventHandler
|
||||
onStatusChange?: SSEStatusHandler
|
||||
}
|
||||
|
||||
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS } = DEFAULTS.SSE
|
||||
|
||||
class SSEManager {
|
||||
private static instance: SSEManager
|
||||
private eventSource: EventSource | null = null
|
||||
private subscribers: Map<string, SSESubscriber> = new Map()
|
||||
private directories: Set<string> = new Set()
|
||||
private pendingDirectories: Set<string> = new Set()
|
||||
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
private reconnectDelay: number = RECONNECT_DELAY_MS
|
||||
private isConnected = false
|
||||
private subscriberIdCounter = 0
|
||||
private clientId: string | null = null
|
||||
|
||||
private constructor() {}
|
||||
|
||||
static getInstance(): SSEManager {
|
||||
if (!SSEManager.instance) {
|
||||
SSEManager.instance = new SSEManager()
|
||||
}
|
||||
return SSEManager.instance
|
||||
}
|
||||
|
||||
subscribe(
|
||||
onMessage: SSEEventHandler,
|
||||
onStatusChange?: SSEStatusHandler
|
||||
): () => void {
|
||||
const id = `sub_${++this.subscriberIdCounter}`
|
||||
const subscriber: SSESubscriber = {
|
||||
id,
|
||||
onMessage,
|
||||
onStatusChange
|
||||
}
|
||||
|
||||
this.subscribers.set(id, subscriber)
|
||||
|
||||
if (onStatusChange) {
|
||||
onStatusChange(this.isConnected)
|
||||
}
|
||||
|
||||
if (this.subscribers.size === 1) {
|
||||
this.connect()
|
||||
}
|
||||
|
||||
return () => this.unsubscribe(id)
|
||||
}
|
||||
|
||||
private unsubscribe(id: string): void {
|
||||
this.subscribers.delete(id)
|
||||
|
||||
if (this.subscribers.size === 0) {
|
||||
this.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
addDirectory(directory: string): () => void {
|
||||
if (this.directories.has(directory)) {
|
||||
return () => this.cleanupDirectory(directory)
|
||||
}
|
||||
|
||||
this.directories.add(directory)
|
||||
|
||||
if (this.clientId && this.isConnected) {
|
||||
this.subscribeToDirectory(directory)
|
||||
} else {
|
||||
this.pendingDirectories.add(directory)
|
||||
if (!this.eventSource) {
|
||||
this.reconnect()
|
||||
}
|
||||
}
|
||||
|
||||
return () => this.cleanupDirectory(directory)
|
||||
}
|
||||
|
||||
private cleanupDirectory(directory: string): void {
|
||||
this.directories.delete(directory)
|
||||
this.pendingDirectories.delete(directory)
|
||||
|
||||
if (this.clientId && this.isConnected) {
|
||||
fetch('/api/sse/unsubscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
|
||||
}).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
private subscribeToDirectory(directory: string): void {
|
||||
fetch('/api/sse/subscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
|
||||
}).then(res => {
|
||||
if (!res.ok) {
|
||||
this.reconnect()
|
||||
}
|
||||
}).catch(() => {
|
||||
this.reconnect()
|
||||
})
|
||||
}
|
||||
|
||||
private flushPendingDirectories(): void {
|
||||
if (this.pendingDirectories.size === 0) return
|
||||
if (!this.clientId || !this.isConnected) return
|
||||
|
||||
const dirs = Array.from(this.pendingDirectories)
|
||||
this.pendingDirectories.clear()
|
||||
|
||||
fetch('/api/sse/subscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: this.clientId, directories: dirs })
|
||||
}).then(res => {
|
||||
if (!res.ok) {
|
||||
dirs.forEach(d => this.pendingDirectories.add(d))
|
||||
this.reconnect()
|
||||
}
|
||||
}).catch(() => {
|
||||
dirs.forEach(d => this.pendingDirectories.add(d))
|
||||
this.reconnect()
|
||||
})
|
||||
}
|
||||
|
||||
removeDirectory(directory: string): void {
|
||||
if (!this.directories.has(directory)) return
|
||||
|
||||
this.directories.delete(directory)
|
||||
|
||||
if (this.clientId && this.isConnected) {
|
||||
fetch('/api/sse/unsubscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
|
||||
}).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
getDirectories(): string[] {
|
||||
return Array.from(this.directories)
|
||||
}
|
||||
|
||||
private buildUrl(): string {
|
||||
const url = new URL('/api/sse/stream', window.location.origin)
|
||||
if (this.directories.size > 0) {
|
||||
url.searchParams.set('directories', Array.from(this.directories).join(','))
|
||||
}
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
private connect(): void {
|
||||
if (this.eventSource) return
|
||||
|
||||
const url = this.buildUrl()
|
||||
this.eventSource = new EventSource(url)
|
||||
|
||||
this.eventSource.onopen = () => {
|
||||
this.isConnected = true
|
||||
this.reconnectDelay = RECONNECT_DELAY_MS
|
||||
this.notifyStatusChange(true)
|
||||
}
|
||||
|
||||
this.eventSource.onerror = () => {
|
||||
this.isConnected = false
|
||||
this.clientId = null
|
||||
this.notifyStatusChange(false)
|
||||
|
||||
if (this.eventSource) {
|
||||
this.eventSource.close()
|
||||
this.eventSource = null
|
||||
}
|
||||
|
||||
if (this.subscribers.size > 0) {
|
||||
this.scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
this.eventSource.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data)
|
||||
this.broadcast(data)
|
||||
} catch {
|
||||
// Ignore parse errors
|
||||
}
|
||||
}
|
||||
|
||||
this.eventSource.addEventListener('connected', (event) => {
|
||||
try {
|
||||
const data = JSON.parse((event as MessageEvent).data)
|
||||
if (data.clientId) {
|
||||
this.clientId = data.clientId
|
||||
}
|
||||
this.isConnected = true
|
||||
this.notifyStatusChange(true)
|
||||
this.flushPendingDirectories()
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private disconnect(): void {
|
||||
if (this.reconnectTimeout) {
|
||||
clearTimeout(this.reconnectTimeout)
|
||||
this.reconnectTimeout = null
|
||||
}
|
||||
|
||||
if (this.eventSource) {
|
||||
this.eventSource.close()
|
||||
this.eventSource = null
|
||||
}
|
||||
|
||||
this.isConnected = false
|
||||
this.clientId = null
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (this.reconnectTimeout) return
|
||||
|
||||
this.reconnectTimeout = setTimeout(() => {
|
||||
this.reconnectTimeout = null
|
||||
this.reconnectDelay = Math.min(this.reconnectDelay * 2, MAX_RECONNECT_DELAY_MS)
|
||||
this.connect()
|
||||
}, this.reconnectDelay)
|
||||
}
|
||||
|
||||
private notifyStatusChange(connected: boolean): void {
|
||||
this.subscribers.forEach(sub => {
|
||||
if (sub.onStatusChange) {
|
||||
try {
|
||||
sub.onStatusChange(connected)
|
||||
} catch {
|
||||
// Ignore callback errors
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private broadcast(data: unknown): void {
|
||||
this.subscribers.forEach(sub => {
|
||||
try {
|
||||
sub.onMessage(data)
|
||||
} catch {
|
||||
// Ignore callback errors
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
reconnect(): void {
|
||||
if (this.subscribers.size === 0) return
|
||||
|
||||
this.reconnectDelay = RECONNECT_DELAY_MS
|
||||
this.disconnect()
|
||||
this.connect()
|
||||
}
|
||||
|
||||
getConnectionStatus(): boolean {
|
||||
return this.isConnected
|
||||
}
|
||||
}
|
||||
|
||||
export const sseManager = SSEManager.getInstance()
|
||||
|
||||
export function subscribeToSSE(
|
||||
onMessage: SSEEventHandler,
|
||||
onStatusChange?: SSEStatusHandler
|
||||
): () => void {
|
||||
return sseManager.subscribe(onMessage, onStatusChange)
|
||||
}
|
||||
|
||||
export function addSSEDirectory(directory: string): () => void {
|
||||
return sseManager.addDirectory(directory)
|
||||
}
|
||||
|
||||
export function removeSSEDirectory(directory: string): void {
|
||||
sseManager.removeDirectory(directory)
|
||||
}
|
||||
|
||||
export function reconnectSSE(): void {
|
||||
sseManager.reconnect()
|
||||
}
|
||||
|
||||
export function isSSEConnected(): boolean {
|
||||
return sseManager.getConnectionStatus()
|
||||
}
|
||||
Reference in new issue
Block a user