Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/dock-review-followups.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@conciv/extension-recorder': patch
'@conciv/contract': patch
---

Every queued recorder stop now finishes its session, events whose upload failed during a stop stay queued ahead of the next session's, failed recorder controls are logged, and node RPC links keep the caller's abort signal so an aborted stream really closes.
9 changes: 9 additions & 0 deletions packages/contract/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,18 @@ export type RpcClient = ContractRouterClient<typeof contract, RpcClientContext>

export type RpcClientOptions = {headers?: Record<string, string>}

export function abortableFetch(
request: Request,
init: RequestInit,
options: {signal?: AbortSignal | undefined},
): Promise<Response> {
return fetch(request, {...init, signal: options.signal ?? null})
}

export function makeRpcClient(apiBase: string, options: RpcClientOptions = {}): RpcClient {
const link = new RPCLink<RpcClientContext>({
url: `${apiBase}/rpc`,
fetch: abortableFetch,
...(options.headers ? {headers: options.headers} : {}),
})
return createORPCClient(link)
Expand Down
37 changes: 37 additions & 0 deletions packages/contract/test/contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import {DraftRowSchema, MarkerRowSchema, SessionMetaSchema} from '../src/rows.js
import type {SessionMeta} from '../src/rows.js'
import {makeBrowserRpcClient, makeRpcClient, type RpcClient} from '../src/client.js'
import {createServer, type Server} from 'node:http'
import {setImmediate} from 'node:timers/promises'
import {setFlagsFromString} from 'node:v8'
import {runInNewContext} from 'node:vm'
import {CONCIV_SESSION_HEADER} from '@conciv/protocol/chat-types'
import {closeBrowserRpcConnection, dynamicBrowserRpcLink} from '../src/browser-transport.js'

Expand All @@ -24,6 +27,40 @@ describe('client', () => {
}
})

it('ends an aborted event stream after the request behind it was collected', async () => {
const server = createServer((_request, response) => {
response.writeHead(200, {'content-type': 'text/event-stream'})
response.write(`event: message\ndata: ${JSON.stringify({json: {type: 'probe'}})}\n\n`)
})
const port = await new Promise<number>((resolve) => {
server.listen(0, '127.0.0.1', () => {
const address = server.address()
resolve(typeof address === 'object' && address !== null ? address.port : 0)
})
})
try {
const abort = new AbortController()
const events = await makeRpcClient(`http://127.0.0.1:${port}`).chat.events(
{sessionId: 'conciv_probe'},
{signal: abort.signal},
)
await events.next()
setFlagsFromString('--expose-gc')
const collect: unknown = runInNewContext('gc')
if (typeof collect !== 'function') throw new Error('gc unavailable')
collect()
await setImmediate()
collect()
await setImmediate()
const ended = events.next()
abort.abort()
await expect(ended).rejects.toThrow()
} finally {
server.closeAllConnections()
await new Promise((resolve) => server.close(resolve))
}
}, 5_000)

it('is typed by the contract', () => {
expectTypeOf<Awaited<ReturnType<RpcClient['sessions']['list']>>>().toEqualTypeOf<SessionMeta[]>()
})
Expand Down
4 changes: 2 additions & 2 deletions packages/extension/src/ext-rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {createORPCClient} from '@orpc/client'
import {RPCLink} from '@orpc/client/fetch'
import {ClientRetryPlugin, type ClientRetryPluginContext} from '@orpc/client/plugins'
import type {AnyRouter, RouterClient} from '@orpc/server'
import {dynamicBrowserRpcLink, type SessionAccessor} from '@conciv/contract'
import {abortableFetch, dynamicBrowserRpcLink, type SessionAccessor} from '@conciv/contract'
import {CONCIV_SESSION_HEADER} from '@conciv/protocol/chat-types'

export type ExtRpcContext = ClientRetryPluginContext
Expand All @@ -19,8 +19,8 @@ function nodeFetchClient<TRouter extends AnyRouter>(
): RouterClient<TRouter, ExtRpcContext> {
const link = new RPCLink<ExtRpcContext>({
url: `${apiBase}/rpc/ext/${extensionSlug}`,
fetch: abortableFetch,
headers: () => sessionHeaders(session),
fetch: (request, init, options) => fetch(request, {...init, signal: options.signal}),
plugins: [new ClientRetryPlugin<ExtRpcContext>()],
})
return createORPCClient(link)
Expand Down
11 changes: 8 additions & 3 deletions packages/extensions/recorder/src/client/boot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import {RECORDER_NAME, type RecorderControl} from '../shared/protocol.js'
import type {RecorderRouter} from '../server.js'
import {loadCaptureLibrary, type CaptureLibrary} from './capture.js'
import {createCaptureSession, type CaptureSession} from './capture-session.js'
import {createFlusher} from './flusher.js'
import type {RecorderStore} from './recorder-store.js'

export function bootRecorder(apiBase: string, store: RecorderStore): () => void {
const rpc = makeExtRpcClient<RecorderRouter>(apiBase, RECORDER_NAME)
const clientId = store.clientId()
const abort = new AbortController()
const flusher = createFlusher({send: (events) => rpc.flush({clientId, events}).then(() => undefined)})
let session: CaptureSession | undefined

const sessionBlocked = (): boolean => session !== undefined || abort.signal.aborted || !store.live()
Expand All @@ -21,7 +23,7 @@ export function bootRecorder(apiBase: string, store: RecorderStore): () => void
library,
config,
reloadConfig: () => rpc.config(undefined),
send: (events) => rpc.flush({clientId, events}).then(() => undefined),
flusher,
onFailed: () => store.setStatus('failed'),
})
store.setStatus('recording')
Expand All @@ -40,7 +42,7 @@ export function bootRecorder(apiBase: string, store: RecorderStore): () => void

const stopSession = async (): Promise<void> => {
const active = session
if (!active || store.live()) return
if (!active) return
session = undefined
store.setStatus('idle')
await active.finish()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Expand All @@ -61,7 +63,9 @@ export function bootRecorder(apiBase: string, store: RecorderStore): () => void

const consumeControl = (message: RecorderControl): void => {
if (message.live !== undefined) store.setLive(message.live)
applying.tail = applying.tail.then(() => handleControl(message)).catch(() => undefined)
applying.tail = applying.tail
.then(() => handleControl(message))
.catch((error: unknown) => console.error('[conciv] recorder control failed', error))
}

const controlLoop = async (): Promise<void> => {
Expand All @@ -81,5 +85,6 @@ export function bootRecorder(apiBase: string, store: RecorderStore): () => void
const active = session
session = undefined
void active?.finish()
flusher.dispose()
}
}
10 changes: 5 additions & 5 deletions packages/extensions/recorder/src/client/capture-session.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type {RecorderConfig, RrwebEvent} from '../shared/protocol.js'
import type {RecorderConfig} from '../shared/protocol.js'
import {startCapture, takeFreshSnapshot, type CaptureLibrary} from './capture.js'
import {createFlusher} from './flusher.js'
import type {Flusher} from './flusher.js'
import {createVisibilityPauser} from './visibility-pauser.js'

export type CaptureSession = {
Expand All @@ -13,10 +13,10 @@ export function createCaptureSession(opts: {
library: CaptureLibrary
config: RecorderConfig
reloadConfig: () => Promise<RecorderConfig>
send: (events: RrwebEvent[]) => Promise<void>
flusher: Flusher
onFailed: () => void
}): CaptureSession {
const flusher = createFlusher({send: opts.send})
const flusher = opts.flusher
flusher.setLive(true)
let generation = 0
let stopRecord: (() => void) | undefined = startCapture(opts.library, opts.config, (event) => flusher.push(event))
Expand Down Expand Up @@ -65,8 +65,8 @@ export function createCaptureSession(opts: {
stopRecord?.()
stopRecord = undefined
for (const off of offListeners) off()
flusher.setLive(false)
await flusher.flushNow()
flusher.dispose()
},
}
}
31 changes: 22 additions & 9 deletions packages/extensions/recorder/test/recorder.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {mountToolCard} from '@conciv/extension-testkit/card-harness'
import {CardChromeProvider, INERT_TOOL_CTX} from '@conciv/ui-kit-chat/tools'
import {loadCaptureLibrary} from '../src/client/capture.js'
import {createCaptureSession} from '../src/client/capture-session.js'
import {createFlusher} from '../src/client/flusher.js'
import type {RecorderConfig, RrwebEvent} from '../src/shared/protocol.js'
import {RecordingToolCard} from '../src/tool/card.js'

Expand Down Expand Up @@ -32,16 +33,19 @@ describe('capture session', () => {
vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout']})
let releaseConfig: (value: RecorderConfig) => void = () => {}
const sentByStopped: RrwebEvent[][] = []
const stoppedFlusher = createFlusher({
send: async (events) => {
sentByStopped.push(events)
},
})
const stoppedSession = createCaptureSession({
library: await loadCaptureLibrary(),
config,
reloadConfig: () =>
new Promise((resolve) => {
releaseConfig = resolve
}),
send: async (events) => {
sentByStopped.push(events)
},
flusher: stoppedFlusher,
onFailed: () => {},
})
setVisibility('hidden')
Expand All @@ -51,13 +55,16 @@ describe('capture session', () => {
const flushesAfterFinish = sentByStopped.length

const sentByNext: RrwebEvent[][] = []
const nextFlusher = createFlusher({
send: async (events) => {
sentByNext.push(events)
},
})
const nextSession = createCaptureSession({
library: await loadCaptureLibrary(),
config,
reloadConfig: () => Promise.resolve(config),
send: async (events) => {
sentByNext.push(events)
},
flusher: nextFlusher,
onFailed: () => {},
})
await nextSession.flushNow()
Expand All @@ -71,18 +78,23 @@ describe('capture session', () => {
expect(snapshotCount(sentByNext)).toBeGreaterThan(snapshotsBefore)
expect(sentByStopped.length).toBe(flushesAfterFinish)
await nextSession.finish()
nextFlusher.dispose()
stoppedFlusher.dispose()
})

it('a resume with no interleaved stop re-attaches the recorder', async () => {
vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout']})
const sent: RrwebEvent[][] = []
const flusher = createFlusher({
send: async (events) => {
sent.push(events)
},
})
const session = createCaptureSession({
library: await loadCaptureLibrary(),
config,
reloadConfig: () => Promise.resolve(config),
send: async (events) => {
sent.push(events)
},
flusher: flusher,
onFailed: () => {},
})
setVisibility('hidden')
Expand All @@ -95,6 +107,7 @@ describe('capture session', () => {
await session.flushNow()
expect(snapshotCount(sent)).toBeGreaterThan(snapshotsBefore)
await session.finish()
flusher.dispose()
})
})
})
Expand Down
Loading
Loading