forked from ravendb/ravendb
/
ObservableLineStream.cs
171 lines (155 loc) · 4.81 KB
/
ObservableLineStream.cs
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
// -----------------------------------------------------------------------
// <copyright file="EventSourceStream.cs" company="Hibernating Rhinos LTD">
// Copyright (c) Hibernating Rhinos LTD. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Raven.Abstractions.Extensions;
using Raven.Abstractions.Util;
using Raven.Database.Util;
namespace Raven.Client.Connection
{
public class ObservableLineStream : IObservable<string>, IDisposable
{
private readonly Stream stream;
private readonly byte[] buffer = new byte[8192];
private int posInBuffer;
private readonly Action onDispose;
private readonly ConcurrentSet<IObserver<string>> subscribers = new ConcurrentSet<IObserver<string>>();
public ObservableLineStream(Stream stream, Action onDispose)
{
this.stream = stream;
this.onDispose = onDispose;
}
public void Start()
{
ReadAsync()
.ContinueWith(task =>
{
var read = task.Result;
if(read == 0)// will force reopening of the connection
throw new EndOfStreamException();
// find \r\n in newly read range
var startPos = 0;
byte prev = 0;
bool foundLines = false;
for (int i = posInBuffer; i < posInBuffer + read; i++)
{
if (prev == '\r' && buffer[i] == '\n')
{
foundLines = true;
var oldStartPos = startPos;
// yeah, we found a line, let us give it to the users
startPos = i + 1;
// is it an empty line?
if (oldStartPos == i - 2)
{
continue; // ignore and continue
}
// first 5 bytes should be: 'd','a','t','a',':'
// if it isn't, ignore and continue
if (buffer.Length - oldStartPos < 5 ||
buffer[oldStartPos] != 'd' ||
buffer[oldStartPos + 1] != 'a' ||
buffer[oldStartPos + 2] != 't' ||
buffer[oldStartPos + 3] != 'a' ||
buffer[oldStartPos + 4] != ':')
{
continue;
}
var data = Encoding.UTF8.GetString(buffer, oldStartPos + 5, i - oldStartPos - 6);
foreach (var subscriber in subscribers)
{
subscriber.OnNext(data);
}
}
prev = buffer[i];
}
posInBuffer += read;
if(startPos >= posInBuffer) // read to end
{
posInBuffer = 0;
return;
}
if (foundLines == false)
return;
// move remaining to the start of buffer, then reset
Array.Copy(buffer, startPos, buffer, 0, posInBuffer - startPos);
posInBuffer -= startPos;
})
.ContinueWith(task =>
{
if(task.IsFaulted)
{
try
{
stream.Dispose();
}
catch (Exception)
{
// explicitly ignoring this
}
var aggregateException = task.Exception;
var exception = aggregateException.ExtractSingleInnerException();
if (exception is ObjectDisposedException)
return; // this isn't an error
var we = exception as WebException;
if (we != null && we.Status == WebExceptionStatus.RequestCanceled)
return; // not an error, actually
foreach (var subscriber in subscribers)
{
subscriber.OnError(aggregateException);
}
return;
}
Start(); // read more lines
});
}
#if SILVERLIGHT
private Task<int> ReadAsync()
{
try
{
return stream.ReadAsync(buffer, posInBuffer, buffer.Length - posInBuffer);
}
catch (Exception e)
{
return new CompletedTask<int>(e);
}
}
#else
private Task<int> ReadAsync()
{
try
{
return Task.Factory.FromAsync<int>(
(callback, state) => stream.BeginRead(buffer, posInBuffer, buffer.Length - posInBuffer, callback, state),
stream.EndRead,
null);
}
catch (Exception e)
{
return new CompletedTask<int>(e);
}
}
#endif
public IDisposable Subscribe(IObserver<string> observer)
{
subscribers.TryAdd(observer);
return new DisposableAction(() => subscribers.TryRemove(observer));
}
public void Dispose()
{
foreach (var subscriber in subscribers)
{
subscriber.OnCompleted();
}
onDispose();
}
}
}