forked from livekit/python-sdks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_stream.py
More file actions
357 lines (307 loc) · 11.9 KB
/
data_stream.py
File metadata and controls
357 lines (307 loc) · 11.9 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# Copyright 2023 LiveKit, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import asyncio
import uuid
import datetime
from collections.abc import Callable
from dataclasses import dataclass
from typing import AsyncIterator, Optional, Dict, List
from ._proto.room_pb2 import DataStream as proto_DataStream
from ._proto import ffi_pb2 as proto_ffi
from ._proto import room_pb2 as proto_room
from ._ffi_client import FfiClient
from ._utils import split_utf8
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .participant import LocalParticipant
STREAM_CHUNK_SIZE = 15_000
@dataclass
class BaseStreamInfo:
stream_id: str
mime_type: str
topic: str
timestamp: int
size: Optional[int]
attributes: Optional[Dict[str, str]] # Optional for the attributes dictionary
@dataclass
class TextStreamInfo(BaseStreamInfo):
attachments: List[str]
class TextStreamReader:
def __init__(
self,
header: proto_DataStream.Header,
) -> None:
self._header = header
self._info = TextStreamInfo(
stream_id=header.stream_id,
mime_type=header.mime_type,
topic=header.topic,
timestamp=header.timestamp,
size=header.total_length,
attributes=dict(header.attributes),
attachments=list(header.text_header.attached_stream_ids),
)
self._queue: asyncio.Queue[proto_DataStream.Chunk | None] = asyncio.Queue()
async def _on_chunk_update(self, chunk: proto_DataStream.Chunk):
await self._queue.put(chunk)
async def _on_stream_close(self, trailer: proto_DataStream.Trailer):
self.info.attributes = self.info.attributes or {}
self.info.attributes.update(trailer.attributes)
await self._queue.put(None)
def __aiter__(self) -> AsyncIterator[str]:
return self
async def __anext__(self) -> str:
item = await self._queue.get()
if item is None:
raise StopAsyncIteration
decodedStr = item.content.decode()
return decodedStr
@property
def info(self) -> TextStreamInfo:
return self._info
async def read_all(self) -> str:
final_string = ""
async for chunk in self:
final_string += chunk
return final_string
@dataclass
class ByteStreamInfo(BaseStreamInfo):
name: str
class ByteStreamReader:
def __init__(self, header: proto_DataStream.Header, capacity: int = 0) -> None:
self._header = header
self._info = ByteStreamInfo(
stream_id=header.stream_id,
mime_type=header.mime_type,
topic=header.topic,
timestamp=header.timestamp,
size=header.total_length,
attributes=dict(header.attributes),
name=header.byte_header.name,
)
self._queue: asyncio.Queue[proto_DataStream.Chunk | None] = asyncio.Queue(capacity)
async def _on_chunk_update(self, chunk: proto_DataStream.Chunk):
await self._queue.put(chunk)
async def _on_stream_close(self, trailer: proto_DataStream.Trailer):
self.info.attributes = self.info.attributes or {}
self.info.attributes.update(trailer.attributes)
await self._queue.put(None)
def __aiter__(self) -> AsyncIterator[bytes]:
return self
async def __anext__(self) -> bytes:
item = await self._queue.get()
if item is None:
raise StopAsyncIteration
return item.content
@property
def info(self) -> ByteStreamInfo:
return self._info
class BaseStreamWriter:
def __init__(
self,
local_participant: LocalParticipant,
topic: str = "",
attributes: Optional[Dict[str, str]] = {},
stream_id: str | None = None,
total_size: int | None = None,
mime_type: str = "",
destination_identities: Optional[List[str]] = None,
sender_identity: str | None = None,
):
self._local_participant = local_participant
if stream_id is None:
stream_id = str(uuid.uuid4())
timestamp = int(datetime.datetime.now().timestamp() * 1000)
self._header = proto_DataStream.Header(
stream_id=stream_id,
timestamp=timestamp,
mime_type=mime_type,
topic=topic,
attributes=attributes,
total_length=total_size,
)
self._next_chunk_index: int = 0
self._destination_identities = destination_identities
self._sender_identity = sender_identity or self._local_participant.identity
self._closed = False
async def _send_header(self):
req = proto_ffi.FfiRequest(
send_stream_header=proto_room.SendStreamHeaderRequest(
header=self._header,
local_participant_handle=self._local_participant._ffi_handle.handle,
destination_identities=self._destination_identities,
sender_identity=self._sender_identity,
)
)
queue = FfiClient.instance.queue.subscribe()
try:
resp = FfiClient.instance.request(req)
cb: proto_ffi.FfiEvent = await queue.wait_for(
lambda e: e.send_stream_header.async_id == resp.send_stream_header.async_id
)
finally:
FfiClient.instance.queue.unsubscribe(queue)
if cb.send_stream_header.error:
raise ConnectionError(cb.send_stream_header.error)
async def _send_chunk(self, chunk: proto_DataStream.Chunk):
if self._closed:
raise RuntimeError(f"Cannot send chunk after stream is closed: {chunk}")
req = proto_ffi.FfiRequest(
send_stream_chunk=proto_room.SendStreamChunkRequest(
chunk=chunk,
local_participant_handle=self._local_participant._ffi_handle.handle,
sender_identity=self._local_participant.identity,
destination_identities=self._destination_identities,
)
)
queue = FfiClient.instance.queue.subscribe()
try:
resp = FfiClient.instance.request(req)
cb: proto_ffi.FfiEvent = await queue.wait_for(
lambda e: e.send_stream_chunk.async_id == resp.send_stream_chunk.async_id
)
finally:
FfiClient.instance.queue.unsubscribe(queue)
if cb.send_stream_chunk.error:
raise ConnectionError(cb.send_stream_chunk.error)
async def _send_trailer(self, trailer: proto_DataStream.Trailer):
req = proto_ffi.FfiRequest(
send_stream_trailer=proto_room.SendStreamTrailerRequest(
trailer=trailer,
local_participant_handle=self._local_participant._ffi_handle.handle,
sender_identity=self._local_participant.identity,
)
)
queue = FfiClient.instance.queue.subscribe()
try:
resp = FfiClient.instance.request(req)
cb: proto_ffi.FfiEvent = await queue.wait_for(
lambda e: e.send_stream_trailer.async_id == resp.send_stream_trailer.async_id
)
finally:
FfiClient.instance.queue.unsubscribe(queue)
if cb.send_stream_chunk.error:
raise ConnectionError(cb.send_stream_trailer.error)
async def aclose(self, *, reason: str = "", attributes: Optional[Dict[str, str]] = None):
if self._closed:
raise RuntimeError("Stream already closed")
self._closed = True
await self._send_trailer(
trailer=proto_DataStream.Trailer(
stream_id=self._header.stream_id, reason=reason, attributes=attributes
)
)
class TextStreamWriter(BaseStreamWriter):
def __init__(
self,
local_participant: LocalParticipant,
*,
topic: str = "",
attributes: Optional[Dict[str, str]] = {},
stream_id: str | None = None,
total_size: int | None = None,
reply_to_id: str | None = None,
destination_identities: Optional[List[str]] = None,
sender_identity: str | None = None,
) -> None:
super().__init__(
local_participant,
topic,
attributes,
stream_id,
total_size,
mime_type="text/plain",
destination_identities=destination_identities,
sender_identity=sender_identity,
)
self._header.text_header.operation_type = proto_DataStream.OperationType.CREATE
if reply_to_id:
self._header.text_header.reply_to_stream_id = reply_to_id
self._info = TextStreamInfo(
stream_id=self._header.stream_id,
mime_type=self._header.mime_type,
topic=self._header.topic,
timestamp=self._header.timestamp,
size=self._header.total_length,
attributes=dict(self._header.attributes),
attachments=list(self._header.text_header.attached_stream_ids),
)
self._write_lock = asyncio.Lock()
async def write(self, text: str):
async with self._write_lock:
for chunk in split_utf8(text, STREAM_CHUNK_SIZE):
content = chunk
chunk_index = self._next_chunk_index
self._next_chunk_index += 1
chunk_msg = proto_DataStream.Chunk(
stream_id=self._header.stream_id,
chunk_index=chunk_index,
content=content,
)
await self._send_chunk(chunk_msg)
@property
def info(self) -> TextStreamInfo:
return self._info
class ByteStreamWriter(BaseStreamWriter):
def __init__(
self,
local_participant: LocalParticipant,
*,
name: str,
topic: str = "",
attributes: Optional[Dict[str, str]] = None,
stream_id: str | None = None,
total_size: int | None = None,
mime_type: str = "application/octet-stream",
destination_identities: Optional[List[str]] = None,
) -> None:
super().__init__(
local_participant,
topic,
attributes,
stream_id,
total_size,
mime_type=mime_type,
destination_identities=destination_identities,
)
self._header.byte_header.name = name
self._info = ByteStreamInfo(
stream_id=self._header.stream_id,
mime_type=self._header.mime_type,
topic=self._header.topic,
timestamp=self._header.timestamp,
size=self._header.total_length,
attributes=dict(self._header.attributes),
name=self._header.byte_header.name,
)
self._write_lock = asyncio.Lock()
async def write(self, data: bytes):
async with self._write_lock:
chunked_data = [
data[i : i + STREAM_CHUNK_SIZE] for i in range(0, len(data), STREAM_CHUNK_SIZE)
]
for chunk in chunked_data:
chunk_msg = proto_DataStream.Chunk(
stream_id=self._header.stream_id,
chunk_index=self._next_chunk_index,
content=chunk,
)
await self._send_chunk(chunk_msg)
self._next_chunk_index += 1
@property
def info(self) -> ByteStreamInfo:
return self._info
TextStreamHandler = Callable[[TextStreamReader, str], None]
ByteStreamHandler = Callable[[ByteStreamReader, str], None]