forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-stream-request.test.ts
More file actions
200 lines (174 loc) · 5.85 KB
/
Copy pathuse-stream-request.test.ts
File metadata and controls
200 lines (174 loc) · 5.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict'
import { describe, test } from 'node:test'
import type { ChatCompletionRequest } from '../types'
import { createStreamRequestController } from './use-stream-request'
function deferred<T>() {
let resolve!: (value: T) => void
const promise = new Promise<T>((promiseResolve) => {
resolve = promiseResolve
})
return { promise, resolve }
}
class FakeStreamSource {
readyState = 0
closed = false
streamed = false
private listeners = new Map<
string,
Array<(event: Event & { data?: string; readyState?: number }) => void>
>()
addEventListener(
type: string,
listener: (event: Event & { data?: string; readyState?: number }) => void
) {
const listeners = this.listeners.get(type) ?? []
listeners.push(listener)
this.listeners.set(type, listeners)
}
close() {
this.closed = true
}
stream() {
this.streamed = true
}
emit(type: string, data?: string) {
for (const listener of this.listeners.get(type) ?? []) {
listener({ data, readyState: this.readyState } as Event & {
data?: string
readyState?: number
})
}
}
}
const payload: ChatCompletionRequest = {
model: 'test-model',
messages: [{ role: 'user', content: 'hello' }],
stream: true,
}
const noopCallbacks = {
onUpdate: () => undefined,
onComplete: () => undefined,
onError: () => undefined,
}
describe('latest-wins stream request coordination', () => {
test('only creates a stream for the latest header request', async () => {
const firstHeaders = deferred<Record<string, string>>()
const secondHeaders = deferred<Record<string, string>>()
let headerRequest = 0
const sources: FakeStreamSource[] = []
const controller = createStreamRequestController({
getHeaders: () => {
headerRequest += 1
return headerRequest === 1
? firstHeaders.promise
: secondHeaders.promise
},
createSource: () => {
const source = new FakeStreamSource()
sources.push(source)
return source
},
setStreaming: () => undefined,
})
const first = controller.send(payload, noopCallbacks)
const second = controller.send(payload, noopCallbacks)
firstHeaders.resolve({ Authorization: 'Bearer stale' })
await first
assert.equal(sources.length, 0)
secondHeaders.resolve({ Authorization: 'Bearer current' })
await second
assert.equal(sources.length, 1)
assert.equal(sources[0]?.streamed, true)
})
test('stop cancels a request that is still waiting for headers', async () => {
const headers = deferred<Record<string, string>>()
let sourceCount = 0
const controller = createStreamRequestController({
getHeaders: () => headers.promise,
createSource: () => {
sourceCount += 1
return new FakeStreamSource()
},
setStreaming: () => undefined,
})
const request = controller.send(payload, noopCallbacks)
controller.stop()
headers.resolve({ Authorization: 'Bearer ignored' })
await request
assert.equal(sourceCount, 0)
})
test('dispose cancels a pending header request without a state update', async () => {
const headers = deferred<Record<string, string>>()
const streamingStates: boolean[] = []
let sourceCount = 0
const controller = createStreamRequestController({
getHeaders: () => headers.promise,
createSource: () => {
sourceCount += 1
return new FakeStreamSource()
},
setStreaming: (streaming) => streamingStates.push(streaming),
})
const request = controller.send(payload, noopCallbacks)
controller.dispose()
headers.resolve({ Authorization: 'Bearer ignored' })
await request
assert.equal(sourceCount, 0)
assert.deepEqual(streamingStates, [false])
})
test('closes the previous source and ignores all of its later events', async () => {
const nextHeaders = deferred<Record<string, string>>()
let headerRequest = 0
const sources: FakeStreamSource[] = []
const updates: string[] = []
const controller = createStreamRequestController({
getHeaders: () => {
headerRequest += 1
if (headerRequest === 1) {
return Promise.resolve({ Authorization: 'Bearer first' })
}
return nextHeaders.promise
},
createSource: () => {
const source = new FakeStreamSource()
sources.push(source)
return source
},
setStreaming: () => undefined,
})
const callbacks = {
onUpdate: (_type: 'reasoning' | 'content', chunk: string) =>
updates.push(chunk),
onComplete: () => undefined,
onError: () => undefined,
}
await controller.send(payload, callbacks)
const second = controller.send(payload, callbacks)
assert.equal(sources[0]?.closed, true)
sources[0]?.emit(
'message',
JSON.stringify({ choices: [{ delta: { content: 'stale' } }] })
)
nextHeaders.resolve({ Authorization: 'Bearer second' })
await second
sources[1]?.emit(
'message',
JSON.stringify({ choices: [{ delta: { content: 'current' } }] })
)
assert.deepEqual(updates, ['current'])
})
})