mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
section 1: Phase 1: Shared reconnecting OpenCode event subscription and
This commit is contained in:
1 parent
af37ac3a8b
commit
01d8f0825a
4 files changed
+683
-23
No files matched your search
@@ -1,12 +1,29 @@
|
||||
import { EventSource } from 'eventsource'
|
||||
import { openCodeLocation, sessionIDFromEvent, type OpenCodeApi, type V2Event } from '@opencode-manager/shared/opencode'
|
||||
import {
|
||||
openCodeLocation,
|
||||
sessionIDFromEvent,
|
||||
type FormInfo,
|
||||
type OpenCodeApi,
|
||||
type V2Event,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
const MULTILINE_PATTERN = /[\r\n]/
|
||||
|
||||
export type ReplayEventType = 'permission.asked' | 'form.created' | 'session.status'
|
||||
type PermissionAskedEvent = Extract<V2Event, { type: 'permission.asked' }>
|
||||
type FormCreatedEvent = Extract<V2Event, { type: 'form.created' }>
|
||||
type SessionStatusEvent = Extract<V2Event, { type: 'session.status' }>
|
||||
|
||||
export type ReplayEventBuilder = (type: ReplayEventType, directory: string, data: unknown) => V2Event
|
||||
export type ReplayEvent = PermissionAskedEvent | FormCreatedEvent | SessionStatusEvent
|
||||
|
||||
export type ReplayEventType = ReplayEvent['type']
|
||||
|
||||
type ReplayEventArguments =
|
||||
| [type: PermissionAskedEvent['type'], directory: string, data: PermissionAskedEvent['data']]
|
||||
| [type: FormCreatedEvent['type'], directory: string, data: { form: FormInfo }]
|
||||
| [type: SessionStatusEvent['type'], directory: string, data: SessionStatusEvent['data']]
|
||||
|
||||
export type ReplayEventBuilder = (...args: ReplayEventArguments) => ReplayEvent
|
||||
|
||||
export interface RoutedOpenCodeEvent {
|
||||
event: V2Event
|
||||
@@ -81,29 +98,24 @@ export function applySessionActivity(busySessions: Set<string>, event: V2Event):
|
||||
|
||||
export function createReplayEventBuilder(idPrefix: string): ReplayEventBuilder {
|
||||
let count = 0
|
||||
return (type, directory, data) => {
|
||||
return (...args) => {
|
||||
count += 1
|
||||
return {
|
||||
id: `${idPrefix}${count}`,
|
||||
created: Date.now(),
|
||||
type,
|
||||
location: { directory },
|
||||
data,
|
||||
} as V2Event
|
||||
const base = { id: `${idPrefix}${count}`, created: Date.now() }
|
||||
switch (args[0]) {
|
||||
case 'permission.asked':
|
||||
return { ...base, type: args[0], location: { directory: args[1] }, data: args[2] }
|
||||
case 'form.created':
|
||||
return { ...base, type: args[0], location: { directory: args[1] }, data: args[2] as FormCreatedEvent['data'] }
|
||||
case 'session.status':
|
||||
return { ...base, type: args[0], location: { directory: args[1] }, data: args[2] }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function parseOpenCodeEvent(data: string, sessionDirectories: Map<string, string>): RoutedOpenCodeEvent | null {
|
||||
let event: V2Event
|
||||
try {
|
||||
event = JSON.parse(data) as V2Event
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!event?.type) return null
|
||||
|
||||
const payloadJson = MULTILINE_PATTERN.test(data) ? JSON.stringify(event) : data
|
||||
function resolveEventRouting(
|
||||
event: V2Event,
|
||||
sessionDirectories: Map<string, string>,
|
||||
): Omit<RoutedOpenCodeEvent, 'payloadJson'> {
|
||||
const directory = event.location?.directory
|
||||
const sessionID = sessionIDFromEvent(event)
|
||||
const forkParentId = event.type === 'session.forked' ? event.data.parentID : undefined
|
||||
@@ -117,7 +129,36 @@ export function parseOpenCodeEvent(data: string, sessionDirectories: Map<string,
|
||||
sessionDirectories.set(sessionID, rememberedDirectory)
|
||||
}
|
||||
|
||||
return { event, payloadJson, directory, resolvedDirectory }
|
||||
return { event, directory, resolvedDirectory }
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the directory a parsed event belongs to and updates the remembered session directories.
|
||||
*
|
||||
* @param event Parsed event received from an OpenCode server.
|
||||
* @param sessionDirectories Session directories remembered across events, updated in place.
|
||||
* @returns The event with its serialized payload and resolved directories.
|
||||
*/
|
||||
export function routeOpenCodeEvent(
|
||||
event: V2Event,
|
||||
sessionDirectories: Map<string, string>,
|
||||
): RoutedOpenCodeEvent {
|
||||
return { ...resolveEventRouting(event, sessionDirectories), payloadJson: JSON.stringify(event) }
|
||||
}
|
||||
|
||||
export function parseOpenCodeEvent(data: string, sessionDirectories: Map<string, string>): RoutedOpenCodeEvent | null {
|
||||
let event: V2Event
|
||||
try {
|
||||
event = JSON.parse(data) as V2Event
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!event?.type) return null
|
||||
|
||||
const routed = resolveEventRouting(event, sessionDirectories)
|
||||
const payloadJson = MULTILINE_PATTERN.test(data) ? JSON.stringify(event) : data
|
||||
return { ...routed, payloadJson }
|
||||
}
|
||||
|
||||
export async function collectPendingReplayEvents(request: PendingReplayRequest): Promise<PendingReplayEvents> {
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { DEFAULTS } from '@opencode-manager/shared/config'
|
||||
import type { OpenCodeApi, V2Event } from '@opencode-manager/shared/opencode'
|
||||
import { logger } from '../utils/logger'
|
||||
import { nextBackoffDelay } from './opencode-event-routing'
|
||||
|
||||
export interface OpenCodeEventSubscriptionOptions {
|
||||
api: () => OpenCodeApi
|
||||
label: string
|
||||
onOpen: () => void
|
||||
onEvent: (event: V2Event) => void
|
||||
onDisconnect: (error: unknown) => void
|
||||
reconnectDelayMs?: number
|
||||
maxReconnectDelayMs?: number
|
||||
stallThresholdMs?: number
|
||||
watchdogTickMs?: number
|
||||
}
|
||||
|
||||
export interface OpenCodeEventSubscription {
|
||||
close: () => void
|
||||
reconnect: () => void
|
||||
}
|
||||
|
||||
interface SubscriptionAttempt {
|
||||
controller: AbortController
|
||||
watchdog: ReturnType<typeof setInterval> | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to an OpenCode event stream and owns its reconnect, backoff and stall detection.
|
||||
*
|
||||
* Every attempt yields a fresh subscription. The first `server.connected` event marks the attempt
|
||||
* as established, every event reaches `onEvent` in order, and an attempt that ends, throws or
|
||||
* exceeds the stall threshold disconnects, waits the current backoff delay and reconnects with the
|
||||
* delay doubled up to `maxReconnectDelayMs`.
|
||||
*
|
||||
* @param options Stream access, callbacks and optional timing overrides.
|
||||
* @returns Handles to close the subscription or force an immediate reconnect.
|
||||
*/
|
||||
export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOptions): OpenCodeEventSubscription {
|
||||
const reconnectDelayMs = options.reconnectDelayMs ?? DEFAULTS.SSE.RECONNECT_DELAY_MS
|
||||
const maxReconnectDelayMs = options.maxReconnectDelayMs ?? DEFAULTS.SSE.MAX_RECONNECT_DELAY_MS
|
||||
const stallThresholdMs = options.stallThresholdMs ?? DEFAULTS.SSE.STALL_THRESHOLD_MS
|
||||
const watchdogTickMs = options.watchdogTickMs ?? DEFAULTS.SSE.WATCHDOG_TICK_MS
|
||||
|
||||
let closed = false
|
||||
let currentDelay = reconnectDelayMs
|
||||
let loopToken = 0
|
||||
let currentAttempt: SubscriptionAttempt | null = null
|
||||
let delayTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let resolveDelay: (() => void) | null = null
|
||||
|
||||
const stopAttempt = (): void => {
|
||||
const attempt = currentAttempt
|
||||
currentAttempt = null
|
||||
if (!attempt) return
|
||||
if (attempt.watchdog) {
|
||||
clearInterval(attempt.watchdog)
|
||||
attempt.watchdog = null
|
||||
}
|
||||
attempt.controller.abort()
|
||||
}
|
||||
|
||||
const stopDelay = (): void => {
|
||||
if (delayTimer) {
|
||||
clearTimeout(delayTimer)
|
||||
delayTimer = null
|
||||
}
|
||||
const resolve = resolveDelay
|
||||
resolveDelay = null
|
||||
resolve?.()
|
||||
}
|
||||
|
||||
const wait = (delayMs: number): Promise<void> => new Promise((resolve) => {
|
||||
resolveDelay = resolve
|
||||
delayTimer = setTimeout(() => {
|
||||
delayTimer = null
|
||||
resolveDelay = null
|
||||
resolve()
|
||||
}, delayMs)
|
||||
})
|
||||
|
||||
const run = async (token: number): Promise<void> => {
|
||||
while (!closed && token === loopToken) {
|
||||
const attempt: SubscriptionAttempt = { controller: new AbortController(), watchdog: null }
|
||||
currentAttempt = attempt
|
||||
let lastActivityAt = Date.now()
|
||||
let opened = false
|
||||
let stallError: Error | null = null
|
||||
let failure: unknown
|
||||
|
||||
attempt.watchdog = setInterval(() => {
|
||||
if (Date.now() - lastActivityAt <= stallThresholdMs) return
|
||||
stallError = new Error(`${options.label}: OpenCode event stream stalled`)
|
||||
attempt.controller.abort(stallError)
|
||||
}, watchdogTickMs)
|
||||
|
||||
try {
|
||||
const stream = options.api().event.subscribe({
|
||||
signal: attempt.controller.signal,
|
||||
onActivity: () => {
|
||||
lastActivityAt = Date.now()
|
||||
},
|
||||
})
|
||||
|
||||
for await (const event of stream) {
|
||||
if (closed || token !== loopToken) break
|
||||
if (!opened && event.type === 'server.connected') {
|
||||
opened = true
|
||||
currentDelay = reconnectDelayMs
|
||||
options.onOpen()
|
||||
}
|
||||
try {
|
||||
options.onEvent(event)
|
||||
} catch (error) {
|
||||
logger.error(`${options.label}: failed to handle ${event.type} event`, error)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
failure = error
|
||||
} finally {
|
||||
if (attempt.watchdog) {
|
||||
clearInterval(attempt.watchdog)
|
||||
attempt.watchdog = null
|
||||
}
|
||||
if (currentAttempt === attempt) currentAttempt = null
|
||||
}
|
||||
|
||||
if (closed || token !== loopToken) return
|
||||
|
||||
options.onDisconnect(stallError ?? failure)
|
||||
await wait(currentDelay)
|
||||
if (closed || token !== loopToken) return
|
||||
currentDelay = nextBackoffDelay(currentDelay, maxReconnectDelayMs)
|
||||
}
|
||||
}
|
||||
|
||||
void run(loopToken)
|
||||
|
||||
return {
|
||||
close: () => {
|
||||
if (closed) return
|
||||
closed = true
|
||||
loopToken += 1
|
||||
stopDelay()
|
||||
stopAttempt()
|
||||
},
|
||||
reconnect: () => {
|
||||
if (closed) return
|
||||
loopToken += 1
|
||||
stopDelay()
|
||||
stopAttempt()
|
||||
currentDelay = reconnectDelayMs
|
||||
void run(loopToken)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { V2Event } from '@opencode-manager/shared/opencode'
|
||||
import { createReplayEventBuilder, routeOpenCodeEvent } from '../../src/services/opencode-event-routing'
|
||||
|
||||
const locatedStatus = {
|
||||
id: 'evt_status_located',
|
||||
created: 1,
|
||||
type: 'session.status',
|
||||
location: { directory: '/work/alpha' },
|
||||
data: { sessionID: 'ses_1', status: { type: 'busy' } },
|
||||
} satisfies V2Event
|
||||
|
||||
const unlocatedStatus = {
|
||||
id: 'evt_status_unlocated',
|
||||
created: 2,
|
||||
type: 'session.status',
|
||||
data: { sessionID: 'ses_1', status: { type: 'idle' } },
|
||||
} satisfies V2Event
|
||||
|
||||
const forkedSession = {
|
||||
id: 'evt_forked',
|
||||
created: 3,
|
||||
type: 'session.forked',
|
||||
durable: { aggregateID: 'ses_1', seq: 1, version: 2 },
|
||||
data: {
|
||||
sessionID: 'ses_child',
|
||||
parentID: 'ses_1',
|
||||
boundary: { type: 'before', messageID: 'msg_1' },
|
||||
},
|
||||
} satisfies V2Event
|
||||
|
||||
const childStatus = {
|
||||
id: 'evt_status_child',
|
||||
created: 4,
|
||||
type: 'session.status',
|
||||
data: { sessionID: 'ses_child', status: { type: 'busy' } },
|
||||
} satisfies V2Event
|
||||
|
||||
const deletedSession = {
|
||||
id: 'evt_deleted',
|
||||
created: 5,
|
||||
type: 'session.deleted',
|
||||
durable: { aggregateID: 'ses_child', seq: 2, version: 2 },
|
||||
data: { sessionID: 'ses_child' },
|
||||
} satisfies V2Event
|
||||
|
||||
describe('routeOpenCodeEvent', () => {
|
||||
it('serializes the event payload and remembers its directory by session', () => {
|
||||
const directories = new Map<string, string>()
|
||||
|
||||
const routed = routeOpenCodeEvent(locatedStatus, directories)
|
||||
|
||||
expect(routed.event).toBe(locatedStatus)
|
||||
expect(routed.payloadJson).toBe(JSON.stringify(locatedStatus))
|
||||
expect(routed.directory).toBe('/work/alpha')
|
||||
expect(routed.resolvedDirectory).toBe('/work/alpha')
|
||||
expect(directories.get('ses_1')).toBe('/work/alpha')
|
||||
})
|
||||
|
||||
it('resolves a session directory remembered from an earlier event', () => {
|
||||
const directories = new Map<string, string>([['ses_1', '/work/alpha']])
|
||||
|
||||
const routed = routeOpenCodeEvent(unlocatedStatus, directories)
|
||||
|
||||
expect(routed.directory).toBeUndefined()
|
||||
expect(routed.resolvedDirectory).toBe('/work/alpha')
|
||||
})
|
||||
|
||||
it('inherits the parent directory for a forked session', () => {
|
||||
const directories = new Map<string, string>([['ses_1', '/work/alpha']])
|
||||
|
||||
const routed = routeOpenCodeEvent(forkedSession, directories)
|
||||
|
||||
expect(routed.directory).toBeUndefined()
|
||||
expect(routed.resolvedDirectory).toBe('/work/alpha')
|
||||
expect(directories.get('ses_child')).toBe('/work/alpha')
|
||||
})
|
||||
|
||||
it('forgets the directory of a deleted session', () => {
|
||||
const directories = new Map<string, string>([['ses_child', '/work/alpha']])
|
||||
|
||||
const routed = routeOpenCodeEvent(deletedSession, directories)
|
||||
expect(routed.resolvedDirectory).toBe('/work/alpha')
|
||||
expect(directories.has('ses_child')).toBe(false)
|
||||
|
||||
const afterDelete = routeOpenCodeEvent(childStatus, directories)
|
||||
expect(afterDelete.resolvedDirectory).toBeUndefined()
|
||||
expect(directories.has('ses_child')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('createReplayEventBuilder', () => {
|
||||
it('builds typed replay events with incremental ids', () => {
|
||||
const buildReplayEvent = createReplayEventBuilder('replay_')
|
||||
|
||||
const permission = buildReplayEvent('permission.asked', '/work/alpha', {
|
||||
id: 'perm_1',
|
||||
sessionID: 'ses_1',
|
||||
action: 'edit',
|
||||
resources: ['/work/alpha/file.ts'],
|
||||
})
|
||||
const form = buildReplayEvent('form.created', '/work/alpha', {
|
||||
form: {
|
||||
id: 'form_1',
|
||||
sessionID: 'ses_1',
|
||||
title: 'Question',
|
||||
fields: [{ key: 'answer', type: 'string' }],
|
||||
},
|
||||
})
|
||||
const status = buildReplayEvent('session.status', '/work/alpha', {
|
||||
sessionID: 'ses_1',
|
||||
status: { type: 'idle' },
|
||||
})
|
||||
|
||||
expect(permission.type).toBe('permission.asked')
|
||||
expect(permission.location?.directory).toBe('/work/alpha')
|
||||
expect(form.type).toBe('form.created')
|
||||
expect(status.type).toBe('session.status')
|
||||
expect([permission.id, form.id, status.id]).toEqual(['replay_1', 'replay_2', 'replay_3'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,342 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { ClientError, type OpenCodeApi, type V2Event } from '@opencode-manager/shared/opencode'
|
||||
import { subscribeOpenCodeEvents } from '../../src/services/opencode-event-subscription'
|
||||
|
||||
const serverConnected = {
|
||||
id: 'evt_connected',
|
||||
type: 'server.connected',
|
||||
data: {},
|
||||
} satisfies V2Event
|
||||
|
||||
const sessionBusy = {
|
||||
id: 'evt_busy',
|
||||
created: 1,
|
||||
type: 'session.status',
|
||||
data: { sessionID: 'ses_1', status: { type: 'busy' } },
|
||||
} satisfies V2Event
|
||||
|
||||
interface ControlledEventStream {
|
||||
iterable: AsyncIterable<V2Event>
|
||||
signal: AbortSignal
|
||||
push: (event: V2Event) => void
|
||||
end: () => void
|
||||
fail: (error: unknown) => void
|
||||
}
|
||||
|
||||
interface FakeSubscription {
|
||||
stream: ControlledEventStream
|
||||
onActivity: (() => void) | undefined
|
||||
}
|
||||
|
||||
function createControlledEventStream(): ControlledEventStream {
|
||||
const queue: V2Event[] = []
|
||||
let finished = false
|
||||
let failure: { value: unknown } | null = null
|
||||
let signal: AbortSignal
|
||||
let notify: (() => void) | null = null
|
||||
|
||||
const wake = (): void => {
|
||||
const current = notify
|
||||
notify = null
|
||||
current?.()
|
||||
}
|
||||
|
||||
const iterable: AsyncIterable<V2Event> = {
|
||||
[Symbol.asyncIterator]: () => ({
|
||||
async next() {
|
||||
for (;;) {
|
||||
if (queue.length > 0) return { value: queue.shift()!, done: false }
|
||||
if (failure) {
|
||||
const current = failure.value
|
||||
failure = null
|
||||
throw current
|
||||
}
|
||||
if (finished) return { value: undefined, done: true }
|
||||
await new Promise<void>((resolve) => {
|
||||
notify = resolve
|
||||
})
|
||||
}
|
||||
},
|
||||
}),
|
||||
}
|
||||
|
||||
return {
|
||||
iterable,
|
||||
get signal() {
|
||||
return signal
|
||||
},
|
||||
set signal(next: AbortSignal) {
|
||||
signal = next
|
||||
next.addEventListener('abort', () => {
|
||||
failure = { value: next.reason ?? new Error('aborted') }
|
||||
wake()
|
||||
}, { once: true })
|
||||
},
|
||||
push: (event) => {
|
||||
queue.push(event)
|
||||
wake()
|
||||
},
|
||||
end: () => {
|
||||
finished = true
|
||||
wake()
|
||||
},
|
||||
fail: (error) => {
|
||||
failure = { value: error }
|
||||
wake()
|
||||
},
|
||||
} as ControlledEventStream
|
||||
}
|
||||
|
||||
function createFakeApi(): { api: OpenCodeApi; subscriptions: FakeSubscription[] } {
|
||||
const subscriptions: FakeSubscription[] = []
|
||||
const api = {
|
||||
event: {
|
||||
subscribe: (options: { signal?: AbortSignal; onActivity?: () => void }) => {
|
||||
const stream = createControlledEventStream()
|
||||
stream.signal = options.signal!
|
||||
subscriptions.push({ stream, onActivity: options.onActivity })
|
||||
return stream.iterable
|
||||
},
|
||||
},
|
||||
} as unknown as OpenCodeApi
|
||||
return { api, subscriptions }
|
||||
}
|
||||
|
||||
const flush = async (): Promise<void> => {
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('subscribeOpenCodeEvents', () => {
|
||||
it('opens once on server.connected and forwards events in order', async () => {
|
||||
const { api, subscriptions } = createFakeApi()
|
||||
const onOpen = vi.fn()
|
||||
const received: string[] = []
|
||||
const onDisconnect = vi.fn()
|
||||
|
||||
const subscription = subscribeOpenCodeEvents({
|
||||
api: () => api,
|
||||
label: 'test',
|
||||
onOpen,
|
||||
onEvent: (event) => {
|
||||
received.push(event.type)
|
||||
},
|
||||
onDisconnect,
|
||||
})
|
||||
|
||||
expect(subscriptions).toHaveLength(1)
|
||||
|
||||
subscriptions[0]!.stream.push(serverConnected)
|
||||
subscriptions[0]!.stream.push(sessionBusy)
|
||||
await flush()
|
||||
|
||||
expect(onOpen).toHaveBeenCalledTimes(1)
|
||||
expect(received).toEqual(['server.connected', 'session.status'])
|
||||
expect(onDisconnect).not.toHaveBeenCalled()
|
||||
|
||||
subscription.close()
|
||||
})
|
||||
|
||||
it('keeps streaming when an event handler throws', async () => {
|
||||
const { api, subscriptions } = createFakeApi()
|
||||
const received: string[] = []
|
||||
const onDisconnect = vi.fn()
|
||||
|
||||
const subscription = subscribeOpenCodeEvents({
|
||||
api: () => api,
|
||||
label: 'test',
|
||||
onOpen: () => undefined,
|
||||
onEvent: (event) => {
|
||||
received.push(event.type)
|
||||
if (event.type === 'server.connected') throw new Error('handler failure')
|
||||
},
|
||||
onDisconnect,
|
||||
})
|
||||
|
||||
subscriptions[0]!.stream.push(serverConnected)
|
||||
subscriptions[0]!.stream.push(sessionBusy)
|
||||
await flush()
|
||||
|
||||
expect(received).toEqual(['server.connected', 'session.status'])
|
||||
expect(onDisconnect).not.toHaveBeenCalled()
|
||||
|
||||
subscription.close()
|
||||
})
|
||||
|
||||
it('reconnects after the stream ends once the reconnect delay elapses', async () => {
|
||||
const { api, subscriptions } = createFakeApi()
|
||||
const onOpen = vi.fn()
|
||||
const onDisconnect = vi.fn()
|
||||
|
||||
const subscription = subscribeOpenCodeEvents({
|
||||
api: () => api,
|
||||
label: 'test',
|
||||
onOpen,
|
||||
onEvent: () => undefined,
|
||||
onDisconnect,
|
||||
reconnectDelayMs: 100,
|
||||
maxReconnectDelayMs: 1000,
|
||||
})
|
||||
|
||||
subscriptions[0]!.stream.push(serverConnected)
|
||||
await flush()
|
||||
expect(onOpen).toHaveBeenCalledTimes(1)
|
||||
|
||||
subscriptions[0]!.stream.end()
|
||||
await flush()
|
||||
expect(onDisconnect).toHaveBeenCalledTimes(1)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(99)
|
||||
expect(subscriptions).toHaveLength(1)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(subscriptions).toHaveLength(2)
|
||||
|
||||
subscriptions[1]!.stream.push(serverConnected)
|
||||
await flush()
|
||||
expect(onOpen).toHaveBeenCalledTimes(2)
|
||||
|
||||
subscription.close()
|
||||
})
|
||||
|
||||
it('doubles the reconnect delay after a thrown transport error and caps it', async () => {
|
||||
const { api, subscriptions } = createFakeApi()
|
||||
const onDisconnect = vi.fn()
|
||||
|
||||
const subscription = subscribeOpenCodeEvents({
|
||||
api: () => api,
|
||||
label: 'test',
|
||||
onOpen: () => undefined,
|
||||
onEvent: () => undefined,
|
||||
onDisconnect,
|
||||
reconnectDelayMs: 100,
|
||||
maxReconnectDelayMs: 150,
|
||||
})
|
||||
|
||||
subscriptions[0]!.stream.fail(new ClientError('Transport'))
|
||||
await flush()
|
||||
expect(onDisconnect).toHaveBeenCalledTimes(1)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(99)
|
||||
expect(subscriptions).toHaveLength(1)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(subscriptions).toHaveLength(2)
|
||||
|
||||
subscriptions[1]!.stream.fail(new ClientError('UnexpectedStatus'))
|
||||
await flush()
|
||||
expect(onDisconnect).toHaveBeenCalledTimes(2)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(149)
|
||||
expect(subscriptions).toHaveLength(2)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(subscriptions).toHaveLength(3)
|
||||
|
||||
subscription.close()
|
||||
})
|
||||
|
||||
it('aborts a stalled attempt and starts a new one', async () => {
|
||||
const { api, subscriptions } = createFakeApi()
|
||||
const onDisconnect = vi.fn()
|
||||
|
||||
const subscription = subscribeOpenCodeEvents({
|
||||
api: () => api,
|
||||
label: 'test',
|
||||
onOpen: () => undefined,
|
||||
onEvent: () => undefined,
|
||||
onDisconnect,
|
||||
reconnectDelayMs: 10,
|
||||
stallThresholdMs: 100,
|
||||
watchdogTickMs: 50,
|
||||
})
|
||||
|
||||
subscriptions[0]!.stream.push(serverConnected)
|
||||
await flush()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
expect(subscriptions[0]!.stream.signal.aborted).toBe(false)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50)
|
||||
expect(subscriptions[0]!.stream.signal.aborted).toBe(true)
|
||||
expect(onDisconnect).toHaveBeenCalledTimes(1)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(10)
|
||||
expect(subscriptions).toHaveLength(2)
|
||||
|
||||
subscription.close()
|
||||
})
|
||||
|
||||
it('stops reconnecting after close', async () => {
|
||||
const { api, subscriptions } = createFakeApi()
|
||||
const onDisconnect = vi.fn()
|
||||
|
||||
const subscription = subscribeOpenCodeEvents({
|
||||
api: () => api,
|
||||
label: 'test',
|
||||
onOpen: () => undefined,
|
||||
onEvent: () => undefined,
|
||||
onDisconnect,
|
||||
reconnectDelayMs: 100,
|
||||
})
|
||||
|
||||
subscriptions[0]!.stream.push(serverConnected)
|
||||
await flush()
|
||||
subscriptions[0]!.stream.end()
|
||||
await flush()
|
||||
expect(onDisconnect).toHaveBeenCalledTimes(1)
|
||||
|
||||
subscription.close()
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
|
||||
expect(subscriptions).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('reconnect aborts the current attempt and restarts with the base delay', async () => {
|
||||
const { api, subscriptions } = createFakeApi()
|
||||
|
||||
const subscription = subscribeOpenCodeEvents({
|
||||
api: () => api,
|
||||
label: 'test',
|
||||
onOpen: () => undefined,
|
||||
onEvent: () => undefined,
|
||||
onDisconnect: () => undefined,
|
||||
reconnectDelayMs: 100,
|
||||
maxReconnectDelayMs: 1000,
|
||||
})
|
||||
|
||||
subscriptions[0]!.stream
|
||||
.fail(new ClientError('Transport'))
|
||||
await flush()
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
expect(subscriptions).toHaveLength(2)
|
||||
|
||||
subscription.reconnect()
|
||||
expect(subscriptions).toHaveLength(3)
|
||||
expect(subscriptions[1]!.stream.signal.aborted).toBe(true)
|
||||
|
||||
subscriptions[2]!.stream.end()
|
||||
await flush()
|
||||
await vi.advanceTimersByTimeAsync(99)
|
||||
expect(subscriptions).toHaveLength(3)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(subscriptions).toHaveLength(4)
|
||||
|
||||
subscription.close()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user