Clean up speech model stream listeners (#3849)
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import { mkdtempSync, rmSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { PassThrough } from 'stream'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ModelManager } from './model-manager'
|
||||
|
||||
const { httpsGetMock } = vi.hoisted(() => ({
|
||||
httpsGetMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: {
|
||||
getPath: () => '/tmp/orca-speech-models-test'
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('https', async () => {
|
||||
const actual = await vi.importActual('https')
|
||||
return { ...(actual as Record<string, unknown>), get: httpsGetMock }
|
||||
})
|
||||
|
||||
type ModelManagerInternals = {
|
||||
downloadFile: (
|
||||
url: string,
|
||||
dest: string,
|
||||
expectedSize: number,
|
||||
modelId: string,
|
||||
isAborted: () => boolean,
|
||||
signal?: AbortSignal
|
||||
) => Promise<void>
|
||||
}
|
||||
|
||||
describe('ModelManager stream cleanup', () => {
|
||||
beforeEach(() => {
|
||||
httpsGetMock.mockReset()
|
||||
})
|
||||
|
||||
it('removes response progress listeners after a model download finishes', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-'))
|
||||
try {
|
||||
const response = new PassThrough() as PassThrough & {
|
||||
statusCode: number
|
||||
headers: Record<string, string>
|
||||
}
|
||||
response.statusCode = 200
|
||||
response.headers = { 'content-length': '4' }
|
||||
const request = {
|
||||
destroy: vi.fn(() => request),
|
||||
setTimeout: vi.fn(() => request),
|
||||
on: vi.fn(() => request),
|
||||
off: vi.fn(() => request)
|
||||
}
|
||||
httpsGetMock.mockImplementation((_url: URL, cb: (response: unknown) => void) => {
|
||||
cb(response)
|
||||
return request
|
||||
})
|
||||
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
|
||||
|
||||
const download = manager.downloadFile(
|
||||
'https://example.com/model.tar.bz2',
|
||||
join(dir, 'model.tar.bz2'),
|
||||
4,
|
||||
'm',
|
||||
() => false
|
||||
)
|
||||
response.write(Buffer.from('ab'))
|
||||
response.end(Buffer.from('cd'))
|
||||
|
||||
await expect(download).resolves.toBeUndefined()
|
||||
expect(response.listenerCount('data')).toBe(0)
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -347,7 +347,10 @@ export class ModelManager {
|
||||
|
||||
const fileStream = createWriteStream(dest)
|
||||
|
||||
response.on('data', (chunk: Buffer) => {
|
||||
const cleanupResponseProgressListener = (): void => {
|
||||
response.off('data', onResponseData)
|
||||
}
|
||||
const onResponseData = (chunk: Buffer): void => {
|
||||
if (isAborted()) {
|
||||
request?.destroy(new Error('Aborted'))
|
||||
response.destroy()
|
||||
@@ -357,17 +360,22 @@ export class ModelManager {
|
||||
downloaded += chunk.length
|
||||
const progress = Math.min(0.9, downloaded / totalSize)
|
||||
this.updateState(modelId, 'downloading', progress)
|
||||
})
|
||||
}
|
||||
|
||||
response.on('data', onResponseData)
|
||||
pipeline(response, fileStream)
|
||||
.then(() => {
|
||||
cleanupResponseProgressListener()
|
||||
if (isAborted()) {
|
||||
rejectOnce(new Error('Aborted'))
|
||||
} else {
|
||||
resolveOnce()
|
||||
}
|
||||
})
|
||||
.catch(rejectOnce)
|
||||
.catch((error: Error) => {
|
||||
cleanupResponseProgressListener()
|
||||
rejectOnce(error)
|
||||
})
|
||||
}
|
||||
|
||||
request = signal
|
||||
@@ -386,19 +394,49 @@ export class ModelManager {
|
||||
return new Promise((resolve, reject) => {
|
||||
const hash = createHash('sha256')
|
||||
const stream = createReadStream(archivePath)
|
||||
let settled = false
|
||||
|
||||
stream.on('data', (chunk) => hash.update(chunk))
|
||||
stream.on('error', reject)
|
||||
stream.on('end', () => {
|
||||
const cleanup = (): void => {
|
||||
stream.off('data', onData)
|
||||
stream.off('error', onError)
|
||||
stream.off('end', onEnd)
|
||||
}
|
||||
const settleResolve = (): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
cleanup()
|
||||
resolve()
|
||||
}
|
||||
const settleReject = (error: Error): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
cleanup()
|
||||
reject(error)
|
||||
}
|
||||
const onData = (chunk: Buffer): void => {
|
||||
hash.update(chunk)
|
||||
}
|
||||
const onError = (error: Error): void => {
|
||||
settleReject(error)
|
||||
}
|
||||
const onEnd = (): void => {
|
||||
const actualSha256 = hash.digest('hex')
|
||||
if (actualSha256 !== expectedSha256.toLowerCase()) {
|
||||
// Why: these archives feed native model parsers; filename checks do
|
||||
// not protect against compromised or redirected release assets.
|
||||
reject(new Error('Downloaded model archive failed integrity verification'))
|
||||
settleReject(new Error('Downloaded model archive failed integrity verification'))
|
||||
return
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
settleResolve()
|
||||
}
|
||||
|
||||
stream.on('data', onData)
|
||||
stream.on('error', onError)
|
||||
stream.on('end', onEnd)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user