fix: wrap streaming reader in try/finally to release lock and prevent resource leaks

Partially addresses #112. The streaming reader in openaiStreamToAnthropic
had no error handling - if an error occurred during streaming, the reader
lock was never released. Wrapped the while loop in try/finally to ensure
reader.releaseLock() is always called.
This commit is contained in:
salmanrajz
2026-04-02 12:12:24 +04:00
parent 5b20fe783d
commit e494015e9a

View File

@@ -412,15 +412,16 @@ async function* openaiStreamToAnthropic(
const decoder = new TextDecoder() const decoder = new TextDecoder()
let buffer = '' let buffer = ''
while (true) { try {
const { done, value } = await reader.read() while (true) {
if (done) break const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true }) buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n') const lines = buffer.split('\n')
buffer = lines.pop() ?? '' buffer = lines.pop() ?? ''
for (const line of lines) { for (const line of lines) {
const trimmed = line.trim() const trimmed = line.trim()
if (!trimmed || trimmed === 'data: [DONE]') continue if (!trimmed || trimmed === 'data: [DONE]') continue
if (!trimmed.startsWith('data: ')) continue if (!trimmed.startsWith('data: ')) continue
@@ -566,6 +567,9 @@ async function* openaiStreamToAnthropic(
hasEmittedFinalUsage = true hasEmittedFinalUsage = true
} }
} }
}
} finally {
reader.releaseLock()
} }
yield { type: 'message_stop' } yield { type: 'message_stop' }