-
Notifications
You must be signed in to change notification settings - Fork 253
Expand file tree
/
Copy pathStreamReader.ts
More file actions
177 lines (151 loc) · 5.16 KB
/
StreamReader.ts
File metadata and controls
177 lines (151 loc) · 5.16 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
import type { DataStream_Chunk } from '@livekit/protocol';
import type { BaseStreamInfo, ByteStreamInfo, TextStreamChunk, TextStreamInfo } from './types';
import { bigIntToNumber } from './utils';
abstract class BaseStreamReader<T extends BaseStreamInfo> {
protected reader: ReadableStream<DataStream_Chunk>;
protected totalByteSize?: number;
protected _info: T;
protected bytesReceived: number;
get info() {
return this._info;
}
constructor(info: T, stream: ReadableStream<DataStream_Chunk>, totalByteSize?: number) {
this.reader = stream;
this.totalByteSize = totalByteSize;
this._info = info;
this.bytesReceived = 0;
}
protected abstract handleChunkReceived(chunk: DataStream_Chunk): void;
onProgress?: (progress: number | undefined) => void;
abstract readAll(): Promise<string | Array<Uint8Array>>;
}
export class ByteStreamReader extends BaseStreamReader<ByteStreamInfo> {
protected handleChunkReceived(chunk: DataStream_Chunk) {
this.bytesReceived += chunk.content.byteLength;
const currentProgress = this.totalByteSize
? this.bytesReceived / this.totalByteSize
: undefined;
this.onProgress?.(currentProgress);
}
onProgress?: (progress: number | undefined) => void;
[Symbol.asyncIterator]() {
const reader = this.reader.getReader();
return {
next: async (): Promise<IteratorResult<Uint8Array>> => {
try {
const { done, value } = await reader.read();
if (done) {
return { done: true, value: undefined as any };
} else {
this.handleChunkReceived(value);
return { done: false, value: value.content };
}
} catch (error) {
// TODO handle errors
return { done: true, value: undefined };
}
},
async return(): Promise<IteratorResult<Uint8Array>> {
reader.releaseLock();
return { done: true, value: undefined };
},
};
}
async readAll(): Promise<Array<Uint8Array>> {
let chunks: Set<Uint8Array> = new Set();
for await (const chunk of this) {
chunks.add(chunk);
}
return Array.from(chunks);
}
}
/**
* A class to read chunks from a ReadableStream and provide them in a structured format.
*/
export class TextStreamReader extends BaseStreamReader<TextStreamInfo> {
private receivedChunks: Map<number, DataStream_Chunk>;
/**
* A TextStreamReader instance can be used as an AsyncIterator that returns the entire string
* that has been received up to the current point in time.
*/
constructor(
info: TextStreamInfo,
stream: ReadableStream<DataStream_Chunk>,
totalChunkCount?: number,
) {
super(info, stream, totalChunkCount);
this.receivedChunks = new Map();
}
protected handleChunkReceived(chunk: DataStream_Chunk) {
const index = bigIntToNumber(chunk.chunkIndex);
const previousChunkAtIndex = this.receivedChunks.get(index);
if (previousChunkAtIndex && previousChunkAtIndex.version > chunk.version) {
// we have a newer version already, dropping the old one
return;
}
this.receivedChunks.set(index, chunk);
this.bytesReceived += chunk.content.byteLength;
const currentProgress = this.totalByteSize
? this.bytesReceived / this.totalByteSize
: undefined;
this.onProgress?.(currentProgress);
}
/**
* @param progress - progress of the stream between 0 and 1. Undefined for streams of unknown size
*/
onProgress?: (progress: number | undefined) => void;
/**
* Async iterator implementation to allow usage of `for await...of` syntax.
* Yields structured chunks from the stream.
*
*/
[Symbol.asyncIterator]() {
const reader = this.reader.getReader();
const decoder = new TextDecoder();
return {
next: async (): Promise<IteratorResult<TextStreamChunk>> => {
try {
const { done, value } = await reader.read();
if (done) {
return { done: true, value: undefined };
} else {
this.handleChunkReceived(value);
return {
done: false,
value: {
index: bigIntToNumber(value.chunkIndex),
current: decoder.decode(value.content),
collected: Array.from(this.receivedChunks.values())
.sort((a, b) => bigIntToNumber(a.chunkIndex) - bigIntToNumber(b.chunkIndex))
.map((chunk) => decoder.decode(chunk.content))
.join(''),
},
};
}
} catch (error) {
// TODO handle errors
return { done: true, value: undefined };
}
},
async return(): Promise<IteratorResult<TextStreamChunk>> {
reader.releaseLock();
return { done: true, value: undefined };
},
};
}
async readAll(): Promise<string> {
let latestString: string = '';
for await (const { collected } of this) {
latestString = collected;
}
return latestString;
}
}
export type ByteStreamHandler = (
reader: ByteStreamReader,
participantInfo: { identity: string },
) => void;
export type TextStreamHandler = (
reader: TextStreamReader,
participantInfo: { identity: string },
) => void;