< Summary

Information
Class: LiveKit.Rtc.ByteStreamReader
Assembly: LivekitRtc
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/DataStream.cs
Line coverage
83%
Covered lines: 102
Uncovered lines: 20
Coverable lines: 122
Total lines: 1297
Line coverage: 83.6%
Branch coverage
73%
Covered branches: 25
Total branches: 34
Branch coverage: 73.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)75%44100%
get_Info()100%11100%
Start(...)100%11100%
OnReaderEvent(...)66.66%121286.66%
Fail(...)0%620%
ThrowIfFailed()50%3237.5%
ReadAsync()75%5455.55%
ReadAllAsync()100%44100%
GetAsyncEnumerator()100%22100%
Dispose()100%22100%
DisposeAsync()100%22100%

File(s)

/home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/DataStream.cs

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using System.Collections.Generic;
 5using System.Diagnostics.CodeAnalysis;
 6using System.Runtime.CompilerServices;
 7using System.Text;
 8using System.Threading;
 9using System.Threading.Channels;
 10using System.Threading.Tasks;
 11using Google.Protobuf;
 12using LiveKit.Proto;
 13using LiveKit.Rtc.Internal;
 14
 15namespace LiveKit.Rtc
 16{
 17    /// <summary>
 18    /// Constants of the data streams.
 19    /// </summary>
 20    public static class DataStreamConstants
 21    {
 22        /// <summary>
 23        /// Maximum size in bytes of one data stream chunk; longer writes are split.
 24        /// </summary>
 25        public const int StreamChunkSize = 15000;
 26    }
 27
 28    /// <summary>
 29    /// Base information for a data stream.
 30    /// </summary>
 31    public class BaseStreamInfo
 32    {
 33        /// <summary>
 34        /// Gets the stream ID.
 35        /// </summary>
 36        public string StreamId { get; }
 37
 38        /// <summary>
 39        /// Gets the MIME type.
 40        /// </summary>
 41        public string MimeType { get; }
 42
 43        /// <summary>
 44        /// Gets the topic.
 45        /// </summary>
 46        public string Topic { get; }
 47
 48        /// <summary>
 49        /// Gets the timestamp in milliseconds.
 50        /// </summary>
 51        public long Timestamp { get; }
 52
 53        /// <summary>
 54        /// Gets the total size if known.
 55        /// </summary>
 56        public long? Size { get; }
 57
 58        /// <summary>
 59        /// Gets the stream attributes.
 60        /// </summary>
 61        public Dictionary<string, string> Attributes { get; internal set; }
 62
 63        /// <summary>
 64        /// Initializes base stream info.
 65        /// </summary>
 66        /// <param name="streamId">Unique ID of the stream.</param>
 67        /// <param name="mimeType">MIME type of the content.</param>
 68        /// <param name="topic">Topic the stream was sent on.</param>
 69        /// <param name="timestamp">Send time, in milliseconds since the Unix epoch.</param>
 70        /// <param name="size">Total size in bytes, or null when unknown.</param>
 71        /// <param name="attributes">Custom attributes, or null.</param>
 72        protected BaseStreamInfo(
 73            string streamId,
 74            string mimeType,
 75            string topic,
 76            long timestamp,
 77            long? size,
 78            Dictionary<string, string>? attributes
 79        )
 80        {
 81            StreamId = streamId;
 82            MimeType = mimeType;
 83            Topic = topic;
 84            Timestamp = timestamp;
 85            Size = size;
 86            Attributes = attributes ?? new Dictionary<string, string>();
 87        }
 88    }
 89
 90    /// <summary>
 91    /// Information for a text stream.
 92    /// </summary>
 93    public class TextStreamInfo : BaseStreamInfo
 94    {
 95        /// <summary>
 96        /// Gets the attached stream IDs.
 97        /// </summary>
 98        public IReadOnlyList<string> Attachments { get; }
 99
 100        /// <summary>
 101        /// Initializes text stream info.
 102        /// </summary>
 103        /// <param name="streamId">Unique ID of the stream.</param>
 104        /// <param name="mimeType">MIME type of the content.</param>
 105        /// <param name="topic">Topic the stream was sent on.</param>
 106        /// <param name="timestamp">Send time, in milliseconds since the Unix epoch.</param>
 107        /// <param name="size">Total size in bytes, or null when unknown.</param>
 108        /// <param name="attributes">Custom attributes, or null.</param>
 109        /// <param name="attachments">IDs of the attached byte streams, or null.</param>
 110        public TextStreamInfo(
 111            string streamId,
 112            string mimeType,
 113            string topic,
 114            long timestamp,
 115            long? size,
 116            Dictionary<string, string>? attributes,
 117            IReadOnlyList<string>? attachments
 118        )
 119            : base(streamId, mimeType, topic, timestamp, size, attributes)
 120        {
 121            Attachments = attachments ?? Array.Empty<string>();
 122        }
 123    }
 124
 125    /// <summary>
 126    /// Information for a byte stream.
 127    /// </summary>
 128    public class ByteStreamInfo : BaseStreamInfo
 129    {
 130        /// <summary>
 131        /// Gets the stream name.
 132        /// </summary>
 133        public string Name { get; }
 134
 135        /// <summary>
 136        /// Initializes byte stream info.
 137        /// </summary>
 138        /// <param name="streamId">Unique ID of the stream.</param>
 139        /// <param name="mimeType">MIME type of the content.</param>
 140        /// <param name="topic">Topic the stream was sent on.</param>
 141        /// <param name="timestamp">Send time, in milliseconds since the Unix epoch.</param>
 142        /// <param name="size">Total size in bytes, or null when unknown.</param>
 143        /// <param name="attributes">Custom attributes, or null.</param>
 144        /// <param name="name">File name of the content; empty when null.</param>
 145        public ByteStreamInfo(
 146            string streamId,
 147            string mimeType,
 148            string topic,
 149            long timestamp,
 150            long? size,
 151            Dictionary<string, string>? attributes,
 152            string name
 153        )
 154            : base(streamId, mimeType, topic, timestamp, size, attributes)
 155        {
 156            Name = name ?? string.Empty;
 157        }
 158    }
 159
 160    /// <summary>
 161    /// Reader for text data streams.
 162    /// Implements IAsyncEnumerable for modern async iteration patterns.
 163    /// </summary>
 164    public class TextStreamReader : IAsyncDisposable, IDisposable, IAsyncEnumerable<string>
 165    {
 166        private readonly Channel<string> _channel;
 167        private readonly TextStreamInfo _info;
 168        private readonly NativeStreamReading _reading;
 169        private Exception? _error;
 170        private bool _disposed;
 171
 172        /// <summary>
 173        /// Identity of the participant sending the stream.
 174        /// </summary>
 175        internal string SenderIdentity { get; }
 176
 177        /// <summary>
 178        /// Initializes a new text stream reader.
 179        /// </summary>
 180        /// <param name="info">The stream info of the native reader.</param>
 181        /// <param name="senderIdentity">Identity of the participant sending the stream.</param>
 182        /// <param name="onEnded">Runs once when the stream ends, fails or the reader is disposed.</param>
 183        internal TextStreamReader(
 184            Proto.TextStreamInfo info,
 185            string senderIdentity,
 186            Action<TextStreamReader>? onEnded = null
 187        )
 188        {
 189            _channel = Channel.CreateUnbounded<string>(
 190                new UnboundedChannelOptions { SingleReader = false, SingleWriter = true }
 191            );
 192            _info = new TextStreamInfo(
 193                info.StreamId,
 194                info.MimeType,
 195                info.Topic,
 196                info.Timestamp,
 197                info.HasTotalLength ? (long?)info.TotalLength : null,
 198                new Dictionary<string, string>(info.Attributes),
 199                new List<string>(info.AttachedStreamIds)
 200            );
 201            SenderIdentity = senderIdentity;
 202            _reading = new NativeStreamReading(() => onEnded?.Invoke(this));
 203        }
 204
 205        /// <summary>
 206        /// Gets the stream info.
 207        /// </summary>
 208        public TextStreamInfo Info => _info;
 209
 210        /// <summary>
 211        /// Starts reading the native reader, which this takes over.
 212        /// </summary>
 213        /// <param name="reader">The native reader of the stream.</param>
 214        internal void Start(FfiHandle reader) =>
 215            _reading.Start(
 216                reader,
 217                new FfiRequest
 218                {
 219                    TextReadIncremental = new TextStreamReaderReadIncrementalRequest
 220                    {
 221                        ReaderHandle = reader.HandleId,
 222                    },
 223                },
 224                OnReaderEvent
 225            );
 226
 227        // On the FFI callback thread
 228        private void OnReaderEvent(FfiEvent ffiEvent)
 229        {
 230            var readerEvent = ffiEvent.TextStreamReaderEvent;
 231            switch (readerEvent.DetailCase)
 232            {
 233                case TextStreamReaderEvent.DetailOneofCase.ChunkReceived:
 234                    var content = readerEvent.ChunkReceived.Content;
 235                    if (!string.IsNullOrEmpty(content))
 236                        _channel.Writer.TryWrite(content);
 237                    break;
 238                case TextStreamReaderEvent.DetailOneofCase.Eos:
 239                    foreach (var attr in readerEvent.Eos.Attributes)
 240                        _info.Attributes[attr.Key] = attr.Value;
 241                    if (readerEvent.Eos.Error != null)
 242                        _error ??= new StreamException(readerEvent.Eos.Error.Description);
 243                    _reading.Stop();
 244                    _channel.Writer.TryComplete();
 245                    break;
 246            }
 247        }
 248
 249        /// <summary>
 250        /// Ends the stream abnormally (the room went away): pending and future reads throw
 251        /// <see cref="StreamException"/> once the buffered chunks are consumed.
 252        /// </summary>
 253        /// <param name="error">Why the stream ended.</param>
 254        internal void Fail(Exception error)
 255        {
 256            _error ??= error;
 257            _reading.Stop();
 258            _channel.Writer.TryComplete();
 259        }
 260
 261        private void ThrowIfFailed()
 262        {
 263            if (_error != null)
 264            {
 265                throw new StreamException(
 266                    $"Data stream {_info.StreamId} ended abnormally: {_error.Message}",
 267                    _error
 268                );
 269            }
 270        }
 271
 272        /// <summary>
 273        /// Reads the next chunk of text.
 274        /// </summary>
 275        /// <param name="cancellationToken">Cancellation token.</param>
 276        /// <returns>The next text chunk, or null if the stream is complete.</returns>
 277        /// <exception cref="StreamException">The sender or the room went away before the stream was closed.</exception>
 278        public async ValueTask<string?> ReadAsync(CancellationToken cancellationToken = default)
 279        {
 280            try
 281            {
 282                if (await _channel.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))
 283                {
 284                    if (_channel.Reader.TryRead(out var text))
 285                    {
 286                        return text;
 287                    }
 288                }
 289                ThrowIfFailed();
 290                return null;
 291            }
 292            catch (OperationCanceledException)
 293            {
 294                return null;
 295            }
 296            catch (ChannelClosedException)
 297            {
 298                ThrowIfFailed();
 299                return null;
 300            }
 301        }
 302
 303        /// <summary>
 304        /// Reads all remaining text from the stream.
 305        /// </summary>
 306        /// <param name="cancellationToken">Cancellation token.</param>
 307        /// <returns>The complete text content.</returns>
 308        public async ValueTask<string> ReadAllAsync(CancellationToken cancellationToken = default)
 309        {
 310            var sb = new StringBuilder();
 311            await foreach (
 312                var chunk in this.WithCancellation(cancellationToken).ConfigureAwait(false)
 313            )
 314            {
 315                sb.Append(chunk);
 316            }
 317            return sb.ToString();
 318        }
 319
 320        /// <summary>
 321        /// Returns an async enumerator for iterating over text chunks.
 322        /// </summary>
 323        /// <param name="cancellationToken">Cancellation token.</param>
 324        /// <returns>An async enumerator of text chunks.</returns>
 325        public async IAsyncEnumerator<string> GetAsyncEnumerator(
 326            CancellationToken cancellationToken = default
 327        )
 328        {
 329            await foreach (
 330                var chunk in _channel.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)
 331            )
 332            {
 333                yield return chunk;
 334            }
 335            ThrowIfFailed();
 336        }
 337
 338        /// <summary>
 339        /// Stops receiving: the chunks already received can still be read, then reads return null. Later
 340        /// chunks are dropped.
 341        /// </summary>
 342        public void Dispose()
 343        {
 344            if (_disposed)
 345                return;
 346            _disposed = true;
 347            _reading.Stop();
 348            _channel.Writer.TryComplete();
 349
 350            GC.SuppressFinalize(this);
 351        }
 352
 353        /// <summary>
 354        /// Stops receiving: the chunks already received can still be read, then reads return null. Later
 355        /// chunks are dropped.
 356        /// </summary>
 357        /// <returns>A completed task.</returns>
 358        public ValueTask DisposeAsync()
 359        {
 360            if (_disposed)
 361                return default;
 362            _disposed = true;
 363            _reading.Stop();
 364            _channel.Writer.TryComplete();
 365
 366            GC.SuppressFinalize(this);
 367            return default;
 368        }
 369    }
 370
 371    /// <summary>
 372    /// Reader for byte data streams.
 373    /// Implements IAsyncEnumerable for modern async iteration patterns.
 374    /// </summary>
 375    public class ByteStreamReader
 376        : IAsyncDisposable,
 377            IDisposable,
 378            IAsyncEnumerable<ReadOnlyMemory<byte>>
 379    {
 380        private readonly Channel<byte[]> _channel;
 381        private readonly ByteStreamInfo _info;
 382        private readonly NativeStreamReading _reading;
 383        private Exception? _error;
 384        private bool _disposed;
 385
 386        /// <summary>
 387        /// Identity of the participant sending the stream.
 388        /// </summary>
 389        internal string SenderIdentity { get; }
 390
 391        /// <summary>
 392        /// Initializes a new byte stream reader.
 393        /// </summary>
 394        /// <param name="info">The stream info of the native reader.</param>
 395        /// <param name="senderIdentity">Identity of the participant sending the stream.</param>
 396        /// <param name="onEnded">Runs once when the stream ends, fails or the reader is disposed.</param>
 18397        internal ByteStreamReader(
 18398            Proto.ByteStreamInfo info,
 18399            string senderIdentity,
 18400            Action<ByteStreamReader>? onEnded = null
 18401        )
 18402        {
 403            // Unbounded: the chunks are written on the FFI callback thread, which must not wait
 18404            _channel = Channel.CreateUnbounded<byte[]>(
 18405                new UnboundedChannelOptions { SingleReader = false, SingleWriter = true }
 18406            );
 18407            _info = new ByteStreamInfo(
 18408                info.StreamId,
 18409                info.MimeType,
 18410                info.Topic,
 18411                info.Timestamp,
 18412                info.HasTotalLength ? (long?)info.TotalLength : null,
 18413                new Dictionary<string, string>(info.Attributes),
 18414                info.Name
 18415            );
 416            SenderIdentity = senderIdentity;
 36417            _reading = new NativeStreamReading(() => onEnded?.Invoke(this));
 18418        }
 419
 420        /// <summary>
 421        /// Gets the stream info.
 422        /// </summary>
 40423        public ByteStreamInfo Info => _info;
 424
 425        /// <summary>
 426        /// Starts reading the native reader, which this takes over.
 427        /// </summary>
 428        /// <param name="reader">The native reader of the stream.</param>
 429        internal void Start(FfiHandle reader) =>
 18430            _reading.Start(
 18431                reader,
 18432                new FfiRequest
 18433                {
 18434                    ByteReadIncremental = new ByteStreamReaderReadIncrementalRequest
 18435                    {
 18436                        ReaderHandle = reader.HandleId,
 18437                    },
 18438                },
 18439                OnReaderEvent
 18440            );
 441
 442        // On the FFI callback thread
 443        private void OnReaderEvent(FfiEvent ffiEvent)
 664444        {
 664445            var readerEvent = ffiEvent.ByteStreamReaderEvent;
 664446            switch (readerEvent.DetailCase)
 447            {
 448                case ByteStreamReaderEvent.DetailOneofCase.ChunkReceived:
 648449                    var content = readerEvent.ChunkReceived.Content;
 648450                    if (!content.IsEmpty)
 648451                        _channel.Writer.TryWrite(content.ToByteArray());
 648452                    break;
 453                case ByteStreamReaderEvent.DetailOneofCase.Eos:
 48454                    foreach (var attr in readerEvent.Eos.Attributes)
 0455                        _info.Attributes[attr.Key] = attr.Value;
 16456                    if (readerEvent.Eos.Error != null)
 0457                        _error ??= new StreamException(readerEvent.Eos.Error.Description);
 16458                    _reading.Stop();
 16459                    _channel.Writer.TryComplete();
 16460                    break;
 461            }
 664462        }
 463
 464        /// <summary>
 465        /// Ends the stream abnormally (the room went away): pending and future reads throw
 466        /// <see cref="StreamException"/> once the buffered chunks are consumed.
 467        /// </summary>
 468        /// <param name="error">Why the stream ended.</param>
 469        internal void Fail(Exception error)
 0470        {
 0471            _error ??= error;
 0472            _reading.Stop();
 0473            _channel.Writer.TryComplete();
 0474        }
 475
 476        private void ThrowIfFailed()
 17477        {
 17478            if (_error != null)
 0479            {
 0480                throw new StreamException(
 0481                    $"Data stream {_info.StreamId} ended abnormally: {_error.Message}",
 0482                    _error
 0483                );
 484            }
 17485        }
 486
 487        /// <summary>
 488        /// Reads the next chunk of bytes.
 489        /// </summary>
 490        /// <param name="cancellationToken">Cancellation token.</param>
 491        /// <returns>The next byte chunk, or null if the stream is complete.</returns>
 492        /// <exception cref="StreamException">The sender or the room went away before the stream was closed.</exception>
 493        public async ValueTask<ReadOnlyMemory<byte>?> ReadAsync(
 494            CancellationToken cancellationToken = default
 495        )
 7496        {
 497            try
 7498            {
 7499                if (await _channel.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))
 4500                {
 4501                    if (_channel.Reader.TryRead(out var data))
 4502                    {
 4503                        return data;
 504                    }
 0505                }
 3506                ThrowIfFailed();
 3507                return null;
 508            }
 0509            catch (OperationCanceledException)
 0510            {
 0511                return null;
 512            }
 0513            catch (ChannelClosedException)
 0514            {
 0515                ThrowIfFailed();
 0516                return null;
 517            }
 7518        }
 519
 520        /// <summary>
 521        /// Reads all remaining bytes from the stream.
 522        /// </summary>
 523        /// <param name="cancellationToken">Cancellation token.</param>
 524        /// <returns>The complete byte content.</returns>
 525        public async ValueTask<byte[]> ReadAllAsync(CancellationToken cancellationToken = default)
 12526        {
 12527            var chunks = new List<byte[]>();
 12528            int totalLength = 0;
 529
 12530            await foreach (
 1294531                var chunk in this.WithCancellation(cancellationToken).ConfigureAwait(false)
 532            )
 635533            {
 635534                var array = chunk.ToArray();
 635535                chunks.Add(array);
 635536                totalLength += array.Length;
 635537            }
 538
 12539            var result = new byte[totalLength];
 12540            int offset = 0;
 1306541            foreach (var chunk in chunks)
 635542            {
 635543                Buffer.BlockCopy(chunk, 0, result, offset, chunk.Length);
 635544                offset += chunk.Length;
 635545            }
 12546            return result;
 12547        }
 548
 549        /// <summary>
 550        /// Returns an async enumerator for iterating over byte chunks.
 551        /// </summary>
 552        /// <param name="cancellationToken">Cancellation token.</param>
 553        /// <returns>An async enumerator of byte chunks.</returns>
 554        public async IAsyncEnumerator<ReadOnlyMemory<byte>> GetAsyncEnumerator(
 555            CancellationToken cancellationToken = default
 556        )
 14557        {
 14558            await foreach (
 1314559                var chunk in _channel.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)
 560            )
 643561            {
 643562                yield return chunk;
 643563            }
 14564            ThrowIfFailed();
 14565        }
 566
 567        /// <summary>
 568        /// Stops receiving: the chunks already received can still be read, then reads return null. Later
 569        /// chunks are dropped.
 570        /// </summary>
 571        public void Dispose()
 2572        {
 2573            if (_disposed)
 1574                return;
 1575            _disposed = true;
 1576            _reading.Stop();
 1577            _channel.Writer.TryComplete();
 578
 1579            GC.SuppressFinalize(this);
 2580        }
 581
 582        /// <summary>
 583        /// Stops receiving: the chunks already received can still be read, then reads return null. Later
 584        /// chunks are dropped.
 585        /// </summary>
 586        /// <returns>A completed task.</returns>
 587        public ValueTask DisposeAsync()
 2588        {
 2589            if (_disposed)
 1590                return default;
 1591            _disposed = true;
 1592            _reading.Stop();
 1593            _channel.Writer.TryComplete();
 594
 1595            GC.SuppressFinalize(this);
 1596            return default;
 2597        }
 598    }
 599
 600    /// <summary>
 601    /// Handler for text streams.
 602    /// </summary>
 603    /// <param name="reader">The text stream reader.</param>
 604    /// <param name="participantIdentity">The sender's identity.</param>
 605    public delegate void TextStreamHandler(TextStreamReader reader, string participantIdentity);
 606
 607    /// <summary>
 608    /// Handler for byte streams.
 609    /// </summary>
 610    /// <param name="reader">The byte stream reader.</param>
 611    /// <param name="participantIdentity">The sender's identity.</param>
 612    public delegate void ByteStreamHandler(ByteStreamReader reader, string participantIdentity);
 613
 614    /// <summary>
 615    /// Internal registry for managing stream handlers by topic.
 616    /// Provides a cleaner abstraction for handler registration and dispatch.
 617    /// </summary>
 618    internal sealed class StreamHandlerRegistry
 619    {
 620        private readonly Dictionary<string, TextStreamHandler> _textStreamHandlers =
 621            new Dictionary<string, TextStreamHandler>();
 622        private readonly Dictionary<string, ByteStreamHandler> _byteStreamHandlers =
 623            new Dictionary<string, ByteStreamHandler>();
 624        private readonly object _lock = new object();
 625
 626        /// <summary>
 627        /// Registers a handler for incoming text streams on a specific topic.
 628        /// </summary>
 629        /// <param name="topic">The topic to listen for.</param>
 630        /// <param name="handler">The handler to invoke when a stream is received.</param>
 631        /// <exception cref="StreamException">Thrown when a handler for this topic is already registered.</exception>
 632        internal void RegisterTextStreamHandler(string topic, TextStreamHandler handler)
 633        {
 634            lock (_lock)
 635            {
 636                if (!_textStreamHandlers.TryAdd(topic, handler))
 637                {
 638                    throw new StreamException(
 639                        $"A text stream handler for topic '{topic}' has already been registered."
 640                    );
 641                }
 642            }
 643        }
 644
 645        /// <summary>
 646        /// Registers a handler for incoming byte streams on a specific topic.
 647        /// </summary>
 648        /// <param name="topic">The topic to listen for.</param>
 649        /// <param name="handler">The handler to invoke when a stream is received.</param>
 650        /// <exception cref="StreamException">Thrown when a handler for this topic is already registered.</exception>
 651        internal void RegisterByteStreamHandler(string topic, ByteStreamHandler handler)
 652        {
 653            lock (_lock)
 654            {
 655                if (!_byteStreamHandlers.TryAdd(topic, handler))
 656                {
 657                    throw new StreamException(
 658                        $"A byte stream handler for topic '{topic}' has already been registered."
 659                    );
 660                }
 661            }
 662        }
 663
 664        /// <summary>
 665        /// Unregisters a text stream handler for a specific topic.
 666        /// </summary>
 667        /// <param name="topic">The topic to unregister.</param>
 668        internal void UnregisterTextStreamHandler(string topic)
 669        {
 670            lock (_lock)
 671            {
 672                _textStreamHandlers.Remove(topic);
 673            }
 674        }
 675
 676        /// <summary>
 677        /// Unregisters a byte stream handler for a specific topic.
 678        /// </summary>
 679        /// <param name="topic">The topic to unregister.</param>
 680        internal void UnregisterByteStreamHandler(string topic)
 681        {
 682            lock (_lock)
 683            {
 684                _byteStreamHandlers.Remove(topic);
 685            }
 686        }
 687
 688        /// <summary>
 689        /// Gets the text stream handler registered for a topic.
 690        /// </summary>
 691        /// <param name="topic">The topic of the stream.</param>
 692        /// <param name="handler">The handler, or null when none is registered.</param>
 693        /// <returns>True if a handler is registered for the topic.</returns>
 694        internal bool TryGetTextStreamHandler(
 695            string topic,
 696            [NotNullWhen(true)] out TextStreamHandler? handler
 697        )
 698        {
 699            lock (_lock)
 700            {
 701                return _textStreamHandlers.TryGetValue(topic, out handler);
 702            }
 703        }
 704
 705        /// <summary>
 706        /// Gets the byte stream handler registered for a topic.
 707        /// </summary>
 708        /// <param name="topic">The topic of the stream.</param>
 709        /// <param name="handler">The handler, or null when none is registered.</param>
 710        /// <returns>True if a handler is registered for the topic.</returns>
 711        internal bool TryGetByteStreamHandler(
 712            string topic,
 713            [NotNullWhen(true)] out ByteStreamHandler? handler
 714        )
 715        {
 716            lock (_lock)
 717            {
 718                return _byteStreamHandlers.TryGetValue(topic, out handler);
 719            }
 720        }
 721    }
 722
 723    /// <summary>
 724    /// Links a stream reader to the native reader of its stream, which decompresses the content,
 725    /// delivers the one inlined in the header of a short stream, enforces
 726    /// <see cref="DataStreamOptions.MaxPayloadByteLength"/> and reports the end of the stream.
 727    /// </summary>
 728    internal sealed class NativeStreamReading
 729    {
 730        private readonly object _lock = new object();
 731        private readonly Action _onEnded;
 732        private ulong _readerHandle;
 733        private bool _stopped;
 734
 735        /// <summary>
 736        /// Initializes the link.
 737        /// </summary>
 738        /// <param name="onEnded">Runs once, on the first <see cref="Stop"/>.</param>
 739        internal NativeStreamReading(Action onEnded)
 740        {
 741            _onEnded = onEnded;
 742        }
 743
 744        /// <summary>
 745        /// Routes the reader events to <paramref name="onEvent"/> and sends the incremental read
 746        /// request, which takes the native reader over. A reader stopped before drops it instead.
 747        /// </summary>
 748        /// <param name="reader">The native reader.</param>
 749        /// <param name="request">The incremental read request of the reader.</param>
 750        /// <param name="onEvent">Receives the reader events on the FFI callback thread.</param>
 751        internal void Start(FfiHandle reader, FfiRequest request, Action<FfiEvent> onEvent)
 752        {
 753            lock (_lock)
 754            {
 755                if (_stopped)
 756                {
 757                    reader.Dispose();
 758                    return;
 759                }
 760                _readerHandle = reader.HandleId;
 761                FfiClient.Instance.AddStreamHandler(_readerHandle, onEvent);
 762            }
 763
 764            try
 765            {
 766                FfiClient.Instance.SendRequest(request);
 767            }
 768            catch
 769            {
 770                // The request did not take the reader: it is still ours to drop
 771                FfiClient.Instance.RemoveStreamHandler(reader.HandleId);
 772                reader.Dispose();
 773                throw;
 774            }
 775            reader.MarkConsumed();
 776        }
 777
 778        /// <summary>
 779        /// Stops routing the reader events. The native reader keeps reading until the stream ends,
 780        /// and its later events are dropped.
 781        /// </summary>
 782        internal void Stop()
 783        {
 784            lock (_lock)
 785            {
 786                if (_stopped)
 787                    return;
 788                _stopped = true;
 789                if (_readerHandle != FfiHandle.InvalidHandle)
 790                    FfiClient.Instance.RemoveStreamHandler(_readerHandle);
 791            }
 792            _onEnded();
 793        }
 794    }
 795
 796    /// <summary>
 797    /// Exception thrown for stream-related errors.
 798    /// </summary>
 799    public class StreamException : Exception
 800    {
 801        /// <summary>
 802        /// Initializes a new stream exception.
 803        /// </summary>
 804        /// <param name="message">Description of the error.</param>
 805        public StreamException(string message)
 806            : base(message) { }
 807
 808        /// <summary>
 809        /// Initializes a new stream exception with an inner exception.
 810        /// </summary>
 811        /// <param name="message">Description of the error.</param>
 812        /// <param name="innerException">The underlying error.</param>
 813        public StreamException(string message, Exception innerException)
 814            : base(message, innerException) { }
 815    }
 816
 817    /// <summary>
 818    /// Writer for text data streams.
 819    /// </summary>
 820    public class TextStreamWriter : IAsyncDisposable, IDisposable
 821    {
 822        private readonly LocalParticipant _participant;
 823        private readonly TextStreamInfo _info;
 824        private readonly string[] _destinationIdentities;
 825        private readonly string _senderIdentity;
 826        private int _nextChunkIndex;
 827        private bool _closed;
 828        private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
 829
 830        internal TextStreamWriter(
 831            LocalParticipant participant,
 832            string streamId,
 833            string topic,
 834            string mimeType,
 835            long timestamp,
 836            long? totalSize,
 837            Dictionary<string, string>? attributes,
 838            string[]? destinationIdentities,
 839            string? senderIdentity
 840        )
 841        {
 842            _participant = participant;
 843            _destinationIdentities = destinationIdentities ?? Array.Empty<string>();
 844            _senderIdentity = senderIdentity ?? participant.Identity;
 845            _info = new TextStreamInfo(
 846                streamId,
 847                mimeType,
 848                topic,
 849                timestamp,
 850                totalSize,
 851                attributes,
 852                null
 853            );
 854        }
 855
 856        /// <summary>
 857        /// Gets the stream info.
 858        /// </summary>
 859        public TextStreamInfo Info => _info;
 860
 861        /// <summary>
 862        /// Writes text to the stream.
 863        /// </summary>
 864        /// <param name="text">Text to send; long texts are split into chunks on character boundaries.</param>
 865        /// <param name="cancellationToken">Cancels the send.</param>
 866        /// <returns>A task that completes once every chunk has been sent.</returns>
 867        public async Task WriteAsync(string text, CancellationToken cancellationToken = default)
 868        {
 869            if (_closed)
 870                throw new InvalidOperationException("Cannot write to a closed stream");
 871
 872            if (string.IsNullOrEmpty(text))
 873                return;
 874
 875            await _writeLock.WaitAsync(cancellationToken);
 876            try
 877            {
 878                var bytes = Encoding.UTF8.GetBytes(text);
 879                for (int offset = 0; offset < bytes.Length; )
 880                {
 881                    var length = Math.Min(
 882                        DataStreamConstants.StreamChunkSize,
 883                        bytes.Length - offset
 884                    );
 885                    // Never split a multi-byte character across chunks (receivers decode each chunk
 886                    // on its own): back off to the last character boundary, like the other SDKs
 887                    if (offset + length < bytes.Length)
 888                    {
 889                        var boundary = length;
 890                        while (boundary > 0 && (bytes[offset + boundary] & 0xC0) == 0x80)
 891                        {
 892                            boundary--;
 893                        }
 894                        if (boundary > 0)
 895                        {
 896                            length = boundary;
 897                        }
 898                    }
 899                    var chunk = new byte[length];
 900                    Buffer.BlockCopy(bytes, offset, chunk, 0, length);
 901
 902                    await SendChunkAsync(ByteString.CopyFrom(chunk), cancellationToken);
 903                    offset += length;
 904                }
 905            }
 906            finally
 907            {
 908                _writeLock.Release();
 909            }
 910        }
 911
 912        private async Task SendChunkAsync(ByteString content, CancellationToken cancellationToken)
 913        {
 914            var request = new FfiRequest
 915            {
 916                SendStreamChunk = new SendStreamChunkRequest
 917                {
 918                    LocalParticipantHandle = _participant.Handle.HandleId,
 919                    SenderIdentity = _senderIdentity,
 920                    Chunk = new DataStream.Types.Chunk
 921                    {
 922                        StreamId = _info.StreamId,
 923                        ChunkIndex = (ulong)_nextChunkIndex++,
 924                        Content = content,
 925                    },
 926                },
 927            };
 928
 929            if (_destinationIdentities.Length > 0)
 930            {
 931                request.SendStreamChunk.DestinationIdentities.AddRange(_destinationIdentities);
 932            }
 933
 934            var response = FfiClient.Instance.SendRequest(request);
 935            var asyncId = response.SendStreamChunk?.AsyncId ?? 0;
 936
 937            var chunkEvent = await FfiClient.Instance.WaitForEventAsync(
 938                e =>
 939                    e.MessageCase == FfiEvent.MessageOneofCase.SendStreamChunk
 940                    && e.SendStreamChunk?.AsyncId == asyncId,
 941                TimeSpan.FromSeconds(30),
 942                cancellationToken
 943            );
 944
 945            if (chunkEvent.SendStreamChunk?.HasError == true)
 946            {
 947                throw new RoomException(
 948                    $"Failed to send stream chunk: {chunkEvent.SendStreamChunk.Error}"
 949                );
 950            }
 951        }
 952
 953        /// <summary>
 954        /// Closes the stream.
 955        /// </summary>
 956        /// <param name="reason">Optional reason sent to the readers in the stream trailer.</param>
 957        /// <param name="attributes">Attributes to update on the stream, sent in the trailer.</param>
 958        /// <returns>A task that completes once the server has acknowledged the trailer.</returns>
 959        public Task CloseAsync(string? reason = null, Dictionary<string, string>? attributes = null)
 960        {
 961            return CloseAsync(reason, attributes, CancellationToken.None);
 962        }
 963
 964        /// <summary>
 965        /// Closes the stream, with a token to abandon the wait for the server's acknowledgement.
 966        /// </summary>
 967        /// <param name="reason">Optional reason sent to the readers in the stream trailer.</param>
 968        /// <param name="attributes">Attributes to update on the stream, sent in the trailer.</param>
 969        /// <param name="cancellationToken">Abandons the wait for the server's acknowledgement; the stream is closed any
 970        /// <returns>A task that completes once the server has acknowledged the trailer.</returns>
 971        public async Task CloseAsync(
 972            string? reason,
 973            Dictionary<string, string>? attributes,
 974            CancellationToken cancellationToken
 975        )
 976        {
 977            if (_closed)
 978                return;
 979
 980            _closed = true;
 981
 982            var request = new FfiRequest
 983            {
 984                SendStreamTrailer = new SendStreamTrailerRequest
 985                {
 986                    LocalParticipantHandle = _participant.Handle.HandleId,
 987                    SenderIdentity = _senderIdentity,
 988                    Trailer = new DataStream.Types.Trailer
 989                    {
 990                        StreamId = _info.StreamId,
 991                        Reason = reason ?? string.Empty,
 992                    },
 993                },
 994            };
 995
 996            if (_destinationIdentities.Length > 0)
 997            {
 998                request.SendStreamTrailer.DestinationIdentities.AddRange(_destinationIdentities);
 999            }
 1000
 1001            if (attributes != null)
 1002            {
 1003                foreach (var kvp in attributes)
 1004                {
 1005                    request.SendStreamTrailer.Trailer.Attributes.Add(kvp.Key, kvp.Value);
 1006                }
 1007            }
 1008
 1009            var response = FfiClient.Instance.SendRequest(request);
 1010            var asyncId = response.SendStreamTrailer?.AsyncId ?? 0;
 1011
 1012            var trailerEvent = await FfiClient.Instance.WaitForEventAsync(
 1013                e =>
 1014                    e.MessageCase == FfiEvent.MessageOneofCase.SendStreamTrailer
 1015                    && e.SendStreamTrailer?.AsyncId == asyncId,
 1016                TimeSpan.FromSeconds(30),
 1017                cancellationToken
 1018            );
 1019
 1020            if (trailerEvent.SendStreamTrailer?.HasError == true)
 1021            {
 1022                throw new RoomException(
 1023                    $"Failed to send stream trailer: {trailerEvent.SendStreamTrailer.Error}"
 1024                );
 1025            }
 1026        }
 1027
 1028        /// <summary>
 1029        /// Closes the stream if it is still open (the trailer is sent; a failure is logged) and releases the writer.
 1030        /// </summary>
 1031        public void Dispose()
 1032        {
 1033            if (!_closed)
 1034            {
 1035                // Send the trailer so the readers complete (the request itself goes out
 1036                // synchronously); Dispose cannot throw, so a failure is only logged
 1037                _ = CloseAsync()
 1038                    .ContinueWith(
 1039                        t =>
 1040                            Console.Error.WriteLine(
 1041                                $"[WARN] Data stream {_info.StreamId}: closing on Dispose failed: {t.Exception?.GetBaseE
 1042                            ),
 1043                        TaskContinuationOptions.OnlyOnFaulted
 1044                    );
 1045            }
 1046            _writeLock?.Dispose();
 1047        }
 1048
 1049        /// <summary>
 1050        /// Closes the stream if it is still open and releases the writer.
 1051        /// </summary>
 1052        /// <returns>A task that completes once the stream is closed.</returns>
 1053        public async ValueTask DisposeAsync()
 1054        {
 1055            if (!_closed)
 1056            {
 1057                await CloseAsync();
 1058            }
 1059            _writeLock?.Dispose();
 1060        }
 1061    }
 1062
 1063    /// <summary>
 1064    /// Writer for byte data streams.
 1065    /// </summary>
 1066    public class ByteStreamWriter : IAsyncDisposable, IDisposable
 1067    {
 1068        private readonly LocalParticipant _participant;
 1069        private readonly ByteStreamInfo _info;
 1070        private readonly string[] _destinationIdentities;
 1071        private readonly string _senderIdentity;
 1072        private int _nextChunkIndex;
 1073        private bool _closed;
 1074        private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
 1075
 1076        internal ByteStreamWriter(
 1077            LocalParticipant participant,
 1078            string streamId,
 1079            string topic,
 1080            string mimeType,
 1081            long timestamp,
 1082            long? totalSize,
 1083            Dictionary<string, string>? attributes,
 1084            string name,
 1085            string[]? destinationIdentities,
 1086            string? senderIdentity
 1087        )
 1088        {
 1089            _participant = participant;
 1090            _destinationIdentities = destinationIdentities ?? Array.Empty<string>();
 1091            _senderIdentity = senderIdentity ?? participant.Identity;
 1092            _info = new ByteStreamInfo(
 1093                streamId,
 1094                mimeType,
 1095                topic,
 1096                timestamp,
 1097                totalSize,
 1098                attributes,
 1099                name
 1100            );
 1101        }
 1102
 1103        /// <summary>
 1104        /// Gets the stream info.
 1105        /// </summary>
 1106        public ByteStreamInfo Info => _info;
 1107
 1108        /// <summary>
 1109        /// Writes bytes to the stream.
 1110        /// </summary>
 1111        /// <param name="data">Bytes to send; large arrays are split into chunks.</param>
 1112        /// <param name="cancellationToken">Cancels the send.</param>
 1113        /// <returns>A task that completes once every chunk has been sent.</returns>
 1114        public async Task WriteAsync(byte[] data, CancellationToken cancellationToken = default)
 1115        {
 1116            if (_closed)
 1117                throw new InvalidOperationException("Cannot write to a closed stream");
 1118
 1119            if (data == null || data.Length == 0)
 1120                return;
 1121
 1122            await _writeLock.WaitAsync(cancellationToken);
 1123            try
 1124            {
 1125                for (
 1126                    int offset = 0;
 1127                    offset < data.Length;
 1128                    offset += DataStreamConstants.StreamChunkSize
 1129                )
 1130                {
 1131                    var length = Math.Min(
 1132                        DataStreamConstants.StreamChunkSize,
 1133                        data.Length - offset
 1134                    );
 1135                    var chunk = new byte[length];
 1136                    Buffer.BlockCopy(data, offset, chunk, 0, length);
 1137
 1138                    await SendChunkAsync(ByteString.CopyFrom(chunk), cancellationToken);
 1139                }
 1140            }
 1141            finally
 1142            {
 1143                _writeLock.Release();
 1144            }
 1145        }
 1146
 1147        private async Task SendChunkAsync(ByteString content, CancellationToken cancellationToken)
 1148        {
 1149            var request = new FfiRequest
 1150            {
 1151                SendStreamChunk = new SendStreamChunkRequest
 1152                {
 1153                    LocalParticipantHandle = _participant.Handle.HandleId,
 1154                    SenderIdentity = _senderIdentity,
 1155                    Chunk = new DataStream.Types.Chunk
 1156                    {
 1157                        StreamId = _info.StreamId,
 1158                        ChunkIndex = (ulong)_nextChunkIndex++,
 1159                        Content = content,
 1160                    },
 1161                },
 1162            };
 1163
 1164            if (_destinationIdentities.Length > 0)
 1165            {
 1166                request.SendStreamChunk.DestinationIdentities.AddRange(_destinationIdentities);
 1167            }
 1168
 1169            var response = FfiClient.Instance.SendRequest(request);
 1170            var asyncId = response.SendStreamChunk?.AsyncId ?? 0;
 1171
 1172            var chunkEvent = await FfiClient.Instance.WaitForEventAsync(
 1173                e =>
 1174                    e.MessageCase == FfiEvent.MessageOneofCase.SendStreamChunk
 1175                    && e.SendStreamChunk?.AsyncId == asyncId,
 1176                TimeSpan.FromSeconds(30),
 1177                cancellationToken
 1178            );
 1179
 1180            if (chunkEvent.SendStreamChunk?.HasError == true)
 1181            {
 1182                throw new RoomException(
 1183                    $"Failed to send stream chunk: {chunkEvent.SendStreamChunk.Error}"
 1184                );
 1185            }
 1186        }
 1187
 1188        /// <summary>
 1189        /// Closes the stream.
 1190        /// </summary>
 1191        /// <param name="reason">Optional reason sent to the readers in the stream trailer.</param>
 1192        /// <param name="attributes">Attributes to update on the stream, sent in the trailer.</param>
 1193        /// <returns>A task that completes once the server has acknowledged the trailer.</returns>
 1194        public Task CloseAsync(string? reason = null, Dictionary<string, string>? attributes = null)
 1195        {
 1196            return CloseAsync(reason, attributes, CancellationToken.None);
 1197        }
 1198
 1199        /// <summary>
 1200        /// Closes the stream, with a token to abandon the wait for the server's acknowledgement.
 1201        /// </summary>
 1202        /// <param name="reason">Optional reason sent to the readers in the stream trailer.</param>
 1203        /// <param name="attributes">Attributes to update on the stream, sent in the trailer.</param>
 1204        /// <param name="cancellationToken">Abandons the wait for the server's acknowledgement; the stream is closed any
 1205        /// <returns>A task that completes once the server has acknowledged the trailer.</returns>
 1206        public async Task CloseAsync(
 1207            string? reason,
 1208            Dictionary<string, string>? attributes,
 1209            CancellationToken cancellationToken
 1210        )
 1211        {
 1212            if (_closed)
 1213                return;
 1214
 1215            _closed = true;
 1216
 1217            var request = new FfiRequest
 1218            {
 1219                SendStreamTrailer = new SendStreamTrailerRequest
 1220                {
 1221                    LocalParticipantHandle = _participant.Handle.HandleId,
 1222                    SenderIdentity = _senderIdentity,
 1223                    Trailer = new DataStream.Types.Trailer
 1224                    {
 1225                        StreamId = _info.StreamId,
 1226                        Reason = reason ?? string.Empty,
 1227                    },
 1228                },
 1229            };
 1230
 1231            if (_destinationIdentities.Length > 0)
 1232            {
 1233                request.SendStreamTrailer.DestinationIdentities.AddRange(_destinationIdentities);
 1234            }
 1235
 1236            if (attributes != null)
 1237            {
 1238                foreach (var kvp in attributes)
 1239                {
 1240                    request.SendStreamTrailer.Trailer.Attributes.Add(kvp.Key, kvp.Value);
 1241                }
 1242            }
 1243
 1244            var response = FfiClient.Instance.SendRequest(request);
 1245            var asyncId = response.SendStreamTrailer?.AsyncId ?? 0;
 1246
 1247            var trailerEvent = await FfiClient.Instance.WaitForEventAsync(
 1248                e =>
 1249                    e.MessageCase == FfiEvent.MessageOneofCase.SendStreamTrailer
 1250                    && e.SendStreamTrailer?.AsyncId == asyncId,
 1251                TimeSpan.FromSeconds(30),
 1252                cancellationToken
 1253            );
 1254
 1255            if (trailerEvent.SendStreamTrailer?.HasError == true)
 1256            {
 1257                throw new RoomException(
 1258                    $"Failed to send stream trailer: {trailerEvent.SendStreamTrailer.Error}"
 1259                );
 1260            }
 1261        }
 1262
 1263        /// <summary>
 1264        /// Closes the stream if it is still open (the trailer is sent; a failure is logged) and releases the writer.
 1265        /// </summary>
 1266        public void Dispose()
 1267        {
 1268            if (!_closed)
 1269            {
 1270                // Send the trailer so the readers complete (the request itself goes out
 1271                // synchronously); Dispose cannot throw, so a failure is only logged
 1272                _ = CloseAsync()
 1273                    .ContinueWith(
 1274                        t =>
 1275                            Console.Error.WriteLine(
 1276                                $"[WARN] Data stream {_info.StreamId}: closing on Dispose failed: {t.Exception?.GetBaseE
 1277                            ),
 1278                        TaskContinuationOptions.OnlyOnFaulted
 1279                    );
 1280            }
 1281            _writeLock?.Dispose();
 1282        }
 1283
 1284        /// <summary>
 1285        /// Closes the stream if it is still open and releases the writer.
 1286        /// </summary>
 1287        /// <returns>A task that completes once the stream is closed.</returns>
 1288        public async ValueTask DisposeAsync()
 1289        {
 1290            if (!_closed)
 1291            {
 1292                await CloseAsync();
 1293            }
 1294            _writeLock?.Dispose();
 1295        }
 1296    }
 1297}