修改工单流程页面,订单列表增加工单按钮
This commit is contained in:
1 parent
f9dcae4610
commit
10bb0803d9
44 files changed
+5920
-1291
No files matched your search
@@ -0,0 +1,115 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
internal static class AsyncHelpers
|
||||
{
|
||||
// General-purpose timeout logic that uses a timed CancellationToken instead of
|
||||
// Task.Delay. The cancellationToken that is passed in is for explicitly cancelling
|
||||
// the operation from elsewhere; DoWithTimeout wraps this to create a token that can
|
||||
// also be cancelled by a timeout, and passes that token to taskFn.
|
||||
//
|
||||
// This method will only work if taskFn actually responds to the cancellation token
|
||||
// by throwing an OperationCanceledException. If taskFn ignores the token, timeouts
|
||||
// will not happen.
|
||||
internal static async Task<T> DoWithTimeout<T>(
|
||||
TimeSpan timeout,
|
||||
CancellationToken cancellationToken,
|
||||
Func<CancellationToken, Task<T>> taskFn
|
||||
)
|
||||
{
|
||||
using (var timeoutCancellation = new CancellationTokenSource(timeout))
|
||||
{
|
||||
using (var combinedCancellation = CancellationTokenSource.CreateLinkedTokenSource(
|
||||
cancellationToken, timeoutCancellation.Token))
|
||||
{
|
||||
Task<T> task = null;
|
||||
try
|
||||
{
|
||||
task = taskFn(combinedCancellation.Token);
|
||||
var result = await task;
|
||||
return result;
|
||||
}
|
||||
catch (AggregateException e) when (e.InnerException is OperationCanceledException)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw e.InnerException;
|
||||
}
|
||||
throw new ReadTimeoutException();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
throw new ReadTimeoutException();
|
||||
}
|
||||
}
|
||||
}
|
||||
// We never need to call SuppressExceptions(task) in this method, because the act
|
||||
// of awaiting the task - whether it completes normally or throws an exception -
|
||||
// makes it "observed". The timeout isn't happening in a different task, it's
|
||||
// causing this task to throw an OperationCanceledException, after which point it
|
||||
// can't generate any other exceptions.
|
||||
}
|
||||
|
||||
// Take a task that can't be terminated early with a CancellationToken, and wrap it in a task
|
||||
// that can. If you cancel the wrapped task, the inner task will still continue, but we're
|
||||
// assuming that in these situations we'll eventually be closing the underlying socket which
|
||||
// will terminate any pending I/O.
|
||||
internal static Task<T> AllowCancellation<T>(Task<T> originalTask, CancellationToken cancellationToken)
|
||||
{
|
||||
var cancellableTask = originalTask.ContinueWith(
|
||||
completedTask => completedTask.GetAwaiter().GetResult(),
|
||||
cancellationToken,
|
||||
TaskContinuationOptions.ExecuteSynchronously,
|
||||
TaskScheduler.Default
|
||||
);
|
||||
|
||||
// Now, if originalTask either completes successfully or fails with an exception, anyone who
|
||||
// was waiting on cancellableTask will get the result or the exception.
|
||||
//
|
||||
// But if cancellationToken gets cancelled, cancellableTask will stop and throw an
|
||||
// OperationCancelledException, just as cancellable I/O operation normally would. The
|
||||
// caller is no longer blocked - even though originalTask may still be executing.
|
||||
//
|
||||
// Normally it would be a problem that originalTask could still be hanging around, but
|
||||
// in our case if things are getting cancelled it means the connection is going to be
|
||||
// closed soon, causing any lingering I/O tasks that use that connection to fail. We
|
||||
// just need to use SuppressExceptions to make sure those failures are discarded rather
|
||||
// than causing an "unobserved exception" situation.
|
||||
|
||||
cancellableTask.ContinueWith(
|
||||
completedTask =>
|
||||
{
|
||||
SuppressExceptions(originalTask);
|
||||
},
|
||||
TaskContinuationOptions.OnlyOnCanceled
|
||||
);
|
||||
return cancellableTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a continuation to a task so that if the task throws an uncaught exception, the exception
|
||||
/// is not "unobserved" (which can be a fatal error in some versions of .NET). We must do this
|
||||
/// whenever we're going to discard a task without awaiting it, if there's any possibility that
|
||||
/// it could throw an exception.
|
||||
/// </summary>
|
||||
/// <param name="task">a task we are not going to await</param>
|
||||
internal static void SuppressExceptions(Task task)
|
||||
{
|
||||
task.ContinueWith(
|
||||
t =>
|
||||
{
|
||||
// Simply accessing the Exception property makes this exception observed.
|
||||
var e = t.Exception;
|
||||
},
|
||||
TaskContinuationOptions.OnlyOnFaulted
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Internal implementation of a buffered text line parser for UTF-8 data.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This is used as follows. 1. The caller puts some data into the byte buffer. 2. The caller
|
||||
/// calls ScanToEndOfLine; if it returns true, the <c>lineOut</c> parameter is set to point
|
||||
/// to the content of the line (not including the line ending character(s)). If it returns
|
||||
/// false, put more data into the buffer and try again.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Since in UTF-8 all multi-byte characters use values greater than 127 for all of their
|
||||
/// bytes, this logic doesn't need to do any UTF-8 decoding or even know how many bytes are
|
||||
/// in a character; it just looks for the line-ending sequences CR, LF, or CR+LF.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal struct ByteArrayLineScanner
|
||||
{
|
||||
private readonly byte[] _buffer;
|
||||
private readonly int _capacity;
|
||||
private int _count;
|
||||
private int _startPos;
|
||||
|
||||
public byte[] Buffer => _buffer;
|
||||
public int Capacity => _capacity;
|
||||
public int Count => _count;
|
||||
public int Available => _capacity - _count;
|
||||
|
||||
private MemoryStream _partialLine;
|
||||
|
||||
public ByteArrayLineScanner(int capacity)
|
||||
{
|
||||
_buffer = new byte[capacity];
|
||||
_capacity = capacity;
|
||||
_count = 0;
|
||||
_partialLine = null;
|
||||
_startPos = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The caller calls this method after having already added <c>count</c> more bytes at the
|
||||
/// end of the buffer. We do it this way instead of having an <c>AddBytes(byte[], int)</c>
|
||||
/// method because we don't want to allocate a second buffer just to be the destination for
|
||||
/// a read operation.
|
||||
/// </summary>
|
||||
/// <param name="count">number of bytes added</param>
|
||||
public void AddedBytes(int count)
|
||||
{
|
||||
_count += count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Searches for the next line ending and, if successful, provides the line data.
|
||||
/// </summary>
|
||||
/// <param name="lineOut">if successful, this is set to point to the bytes for the line
|
||||
/// <i>not</i> including any CR/LF; whenever possible this is a reference to the underlying
|
||||
/// buffer, not a copy, so the caller should read/copy it before doing anything else to the
|
||||
/// buffer</param>
|
||||
/// <returns>true if a full line was read, false if we need more data first</returns>
|
||||
public bool ScanToEndOfLine(out Utf8ByteSpan lineOut)
|
||||
{
|
||||
if (_startPos == _count)
|
||||
{
|
||||
_startPos = _count = 0;
|
||||
lineOut = new Utf8ByteSpan();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_startPos == 0 && _partialLine != null && _partialLine.Position > 0
|
||||
&& _partialLine.GetBuffer()[_partialLine.Position - 1] == '\r')
|
||||
{
|
||||
// This is an edge case where the very last byte we previously saw was a CR, and we didn't know
|
||||
// whether the next byte would be LF or not, but we had to dump the buffer into _partialLine
|
||||
// because it was completely full. So, now we can return the line that's already in _partialLine,
|
||||
// but if the first byte in the buffer is LF we should skip past it.
|
||||
if (_buffer[_startPos] == '\n')
|
||||
{
|
||||
_startPos++;
|
||||
}
|
||||
lineOut = new Utf8ByteSpan(_partialLine.GetBuffer(), 0,
|
||||
(int)_partialLine.Position - 1); // don't include the CR
|
||||
_partialLine = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
int startedAt = _startPos, pos = _startPos;
|
||||
|
||||
while (pos < _count)
|
||||
{
|
||||
var b = _buffer[pos];
|
||||
if (b == '\n') // LF by itself terminates a line
|
||||
{
|
||||
_startPos = pos + 1; // next line will start after the LF
|
||||
break;
|
||||
}
|
||||
if (b == '\r')
|
||||
{
|
||||
if (pos < (_count - 1))
|
||||
{
|
||||
_startPos = pos + 1; // next line will start after the CR--
|
||||
if (_buffer[pos + 1] == '\n') // --unless there was an LF right after that
|
||||
{
|
||||
_startPos++;
|
||||
}
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
// CR by itself and CR+LF are both valid line endings in SSE, so if the very
|
||||
// last character we saw was a CR, we can't know when the line is fully read
|
||||
// until we've gotten more data. So we'll need to treat this as an incomplete
|
||||
// line.
|
||||
pos++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
pos++;
|
||||
}
|
||||
|
||||
if (pos == _count) // we didn't find a line terminator
|
||||
{
|
||||
lineOut = new Utf8ByteSpan();
|
||||
if (_count < _capacity)
|
||||
{
|
||||
// There's still room in the buffer, so we'll re-scan the line once they add more bytes
|
||||
return false;
|
||||
}
|
||||
// We need to dump the incomplete line into _partialLine so we can make room in the buffer
|
||||
var partialCount = pos - _startPos;
|
||||
if (_partialLine is null)
|
||||
{
|
||||
_partialLine = new MemoryStream(partialCount);
|
||||
}
|
||||
_partialLine.Write(_buffer, _startPos, partialCount);
|
||||
|
||||
// Clear the main buffer
|
||||
_startPos = _count = 0;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_partialLine != null && _partialLine.Position > 0)
|
||||
{
|
||||
_partialLine.Write(_buffer, startedAt, pos - startedAt);
|
||||
lineOut = new Utf8ByteSpan(_partialLine.GetBuffer(), 0, (int)_partialLine.Position);
|
||||
_partialLine = null;
|
||||
|
||||
// If there are still bytes in the main buffer, move them over to make more room. It's
|
||||
// safe for us to do this before the caller has looked at lineOut, because lineOut is now
|
||||
// a reference to the separate _partialLine buffer, not to the main buffer.
|
||||
if (_startPos < _count)
|
||||
{
|
||||
System.Buffer.BlockCopy(_buffer, _startPos, _buffer, 0, _count - _startPos);
|
||||
}
|
||||
_count -= _startPos;
|
||||
_startPos = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
lineOut = new Utf8ByteSpan(_buffer, startedAt, pos - startedAt);
|
||||
if (_startPos == _count)
|
||||
{
|
||||
// If we've scanned all the data in the buffer, reset _startPos and _count to indicate
|
||||
// that the entire buffer is available for the next read. It's safe for us to do this
|
||||
// before the caller has looked at lineOut, because we're not actually modifying any
|
||||
// bytes in the buffer. It's the caller's responsibility not to modify the buffer
|
||||
// until it has already done whatever needs to be done with the lineOut data.
|
||||
_startPos = _count = 0;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides data recieved in the EventSource <see cref="EventSource.CommentReceived"/> event.
|
||||
/// </summary>
|
||||
/// <seealso cref="System.EventArgs" />
|
||||
public class CommentReceivedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the comment received in the Server Sent Event.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The comment.
|
||||
/// </value>
|
||||
public string Comment { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CommentReceivedEventArgs"/> class.
|
||||
/// </summary>
|
||||
/// <param name="comment">The comment received in the Server Sent Event.</param>
|
||||
public CommentReceivedEventArgs(string comment)
|
||||
{
|
||||
Comment = comment;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// An immutable class containing configuration properties for <see cref="EventSource"/>.
|
||||
/// </summary>
|
||||
/// <seealso cref="EventSource.EventSource(Configuration)"/>
|
||||
/// <seealso cref="ConfigurationBuilder"/>
|
||||
public sealed class Configuration
|
||||
{
|
||||
#region Constants
|
||||
|
||||
/// <summary>
|
||||
/// The default value for <see cref="ConfigurationBuilder.InitialRetryDelay(TimeSpan)"/>:
|
||||
/// one second.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan DefaultInitialRetryDelay = TimeSpan.FromSeconds(1);
|
||||
|
||||
/// <summary>
|
||||
/// The default value for <see cref="ConfigurationBuilder.MaxRetryDelay(TimeSpan)"/>:
|
||||
/// 30 seconds.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan DefaultMaxRetryDelay = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>
|
||||
/// The default value for <see cref="ConfigurationBuilder.ResponseStartTimeout(TimeSpan)"/>:
|
||||
/// 10 seconds.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan DefaultResponseStartTimeout = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>
|
||||
/// Obsolete name for <see cref="DefaultResponseStartTimeout"/>.
|
||||
/// </summary>
|
||||
[Obsolete("Use DefaultResponseStartTimeout")]
|
||||
public static readonly TimeSpan DefaultConnectionTimeout = DefaultResponseStartTimeout;
|
||||
|
||||
/// <summary>
|
||||
/// The default value for <see cref="ConfigurationBuilder.ReadTimeout(TimeSpan)"/>:
|
||||
/// 5 minutes.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan DefaultReadTimeout = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>
|
||||
/// The default value for <see cref="ConfigurationBuilder.BackoffResetThreshold(TimeSpan)"/>:
|
||||
/// one minute.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan DefaultBackoffResetThreshold = TimeSpan.FromMinutes(1);
|
||||
|
||||
/// <summary>
|
||||
/// The logger name that will be used if you specified a logging implementation but did not
|
||||
/// provide a specific logger instance.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.LogAdapter(ILogAdapter)"/>
|
||||
public const string DefaultLoggerName = "EventSource";
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// The amount of time a connection must stay open before the EventSource resets its backoff delay.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A connection that stays open for at least this long also discards any temporary bounds set
|
||||
/// by <see cref="IEventSource.SetTemporaryRetryDelayBounds(TimeSpan, TimeSpan)"/>.
|
||||
/// </remarks>
|
||||
/// <seealso cref="ConfigurationBuilder.BackoffResetThreshold(TimeSpan)"/>
|
||||
public TimeSpan BackoffResetThreshold { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Obsolete name for <see cref="ResponseStartTimeout"/>.
|
||||
/// </summary>
|
||||
[Obsolete("Use ResponseStartTimeout")]
|
||||
public TimeSpan ConnectionTimeout => ResponseStartTimeout;
|
||||
|
||||
/// <summary>
|
||||
/// The HttpClient that will be used as the HTTP client, or null for a new HttpClient.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.HttpClient(HttpClient)"/>
|
||||
public HttpClient HttpClient { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The HttpMessageHandler that will be used for the HTTP client, or null for the default handler.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.HttpMessageHandler(HttpMessageHandler)"/>
|
||||
public HttpMessageHandler HttpMessageHandler { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Delegate hook invoked before an HTTP request has been performed.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.HttpRequestModifier(Action{HttpRequestMessage})"/>
|
||||
public Action<HttpRequestMessage> HttpRequestModifier { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The initial amount of time to wait before attempting to reconnect to the EventSource API.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.InitialRetryDelay(TimeSpan)"/>
|
||||
public TimeSpan InitialRetryDelay { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last event identifier.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.LastEventId(string)"/>
|
||||
public string LastEventId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The logger to be used for all EventSource log output.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is never null; if logging is not configured, it will be <c>LaunchDarkly.Logging.Logs.None</c>.
|
||||
/// </remarks>
|
||||
/// <seealso cref="ConfigurationBuilder.Logger(Logger)"/>
|
||||
|
||||
/// <summary>
|
||||
/// The maximum amount of time to wait before attempting to reconnect.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.MaxRetryDelay(TimeSpan)"/>
|
||||
public TimeSpan MaxRetryDelay { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The HTTP method that will be used when connecting to the EventSource API.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.Method(HttpMethod)"/>
|
||||
public HttpMethod Method { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether to use UTF-8 byte arrays internally if possible when reading the stream.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.PreferDataAsUtf8Bytes(bool)"/>
|
||||
public bool PreferDataAsUtf8Bytes { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The timeout when reading from the EventSource API.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.ReadTimeout(TimeSpan)"/>
|
||||
public TimeSpan ReadTimeout { get; }
|
||||
|
||||
/// <summary>
|
||||
/// A factory for HTTP request body content, if the HTTP method is one that allows a request body.
|
||||
/// is one that allows a request body. This is in the form of a factory function because the request
|
||||
/// may need to be sent more than once.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.RequestBodyFactory(Func{HttpContent})"/>
|
||||
public Func<HttpContent> RequestBodyFactory { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The request headers to be sent with each EventSource HTTP request.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.RequestHeader(string, string)"/>
|
||||
/// <seealso cref="ConfigurationBuilder.RequestHeaders(IDictionary{string, string})"/>
|
||||
public IDictionary<string, string> RequestHeaders { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The maximum amount of time to wait between starting an HTTP request and receiving the response
|
||||
/// headers.
|
||||
/// </summary>
|
||||
/// <seealso cref="ConfigurationBuilder.ResponseStartTimeout(TimeSpan)"/>
|
||||
public TimeSpan ResponseStartTimeout { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="System.Uri"/> used when connecting to an EventSource API.
|
||||
/// </summary>
|
||||
public Uri Uri { get; }
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Constructor
|
||||
|
||||
internal Configuration(ConfigurationBuilder builder)
|
||||
{
|
||||
Uri = builder._uri;
|
||||
|
||||
|
||||
|
||||
BackoffResetThreshold = builder._backoffResetThreshold;
|
||||
HttpClient = builder._httpClient;
|
||||
HttpMessageHandler = (builder._httpClient != null) ? null : builder._httpMessageHandler;
|
||||
InitialRetryDelay = builder._initialRetryDelay;
|
||||
LastEventId = builder._lastEventId;
|
||||
MaxRetryDelay = builder._maxRetryDelay;
|
||||
Method = builder._method;
|
||||
PreferDataAsUtf8Bytes = builder._preferDataAsUtf8Bytes;
|
||||
ReadTimeout = builder._readTimeout;
|
||||
RequestHeaders = new Dictionary<string, string>(builder._requestHeaders);
|
||||
ResponseStartTimeout = builder._responseStartTimeout;
|
||||
RequestBodyFactory = builder._requestBodyFactory;
|
||||
HttpRequestModifier = builder._httpRequestModifier;
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Provides a new <see cref="ConfigurationBuilder"/> for constructing a configuration.
|
||||
/// </summary>
|
||||
/// <param name="uri">the EventSource URI</param>
|
||||
/// <returns>a new builder instance</returns>
|
||||
/// <exception cref="ArgumentNullException">if the URI is null</exception>
|
||||
public static ConfigurationBuilder Builder(Uri uri) =>
|
||||
new ConfigurationBuilder(uri);
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// A standard Builder pattern for constructing a <see cref="Configuration"/> instance.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Initialize a builder by calling <c>new ConfigurationBuilder(uri)</c> or
|
||||
/// <c>Configuration.Builder(uri)</c>. The URI is always required; all other properties
|
||||
/// are set to defaults. Use the builder's setter methods to modify any desired properties;
|
||||
/// setter methods can be chained. Then call <c>Build()</c> to construct the final immutable
|
||||
/// <c>Configuration</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// All setter methods will throw <c>ArgumentException</c> if called with an invalid value,
|
||||
/// so it is never possible for <c>Build()</c> to fail.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public class ConfigurationBuilder
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
internal readonly Uri _uri;
|
||||
internal TimeSpan _initialRetryDelay = Configuration.DefaultInitialRetryDelay;
|
||||
internal TimeSpan _backoffResetThreshold = Configuration.DefaultBackoffResetThreshold;
|
||||
internal string _lastEventId;
|
||||
internal IDictionary<string, string> _requestHeaders = new Dictionary<string, string>();
|
||||
internal HttpMessageHandler _httpMessageHandler;
|
||||
internal HttpClient _httpClient;
|
||||
internal TimeSpan _maxRetryDelay = Configuration.DefaultMaxRetryDelay;
|
||||
internal HttpMethod _method = HttpMethod.Get;
|
||||
internal bool _preferDataAsUtf8Bytes = false;
|
||||
internal TimeSpan _readTimeout = Configuration.DefaultReadTimeout;
|
||||
internal Func<HttpContent> _requestBodyFactory;
|
||||
internal TimeSpan _responseStartTimeout = Configuration.DefaultResponseStartTimeout;
|
||||
internal Action<HttpRequestMessage> _httpRequestModifier;
|
||||
#endregion
|
||||
|
||||
#region Constructor
|
||||
|
||||
internal ConfigurationBuilder(Uri uri)
|
||||
{
|
||||
if (uri == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(uri));
|
||||
}
|
||||
this._uri = uri;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Constructs a <see cref="Configuration"/> instance based on the current builder properies.
|
||||
/// </summary>
|
||||
/// <returns>the configuration</returns>
|
||||
public Configuration Build() =>
|
||||
new Configuration(this);
|
||||
|
||||
/// <summary>
|
||||
/// Obsolete name for <see cref="ResponseStartTimeout(TimeSpan)"/>.
|
||||
/// </summary>
|
||||
/// <param name="responseStartTimeout">the timeout</param>
|
||||
/// <returns>the builder</returns>
|
||||
[Obsolete("Use ResponseStartTimeout")]
|
||||
public ConfigurationBuilder ConnectionTimeout(TimeSpan responseStartTimeout) =>
|
||||
ResponseStartTimeout(responseStartTimeout);
|
||||
|
||||
/// <summary>
|
||||
/// Sets a delegate hook invoked before an HTTP request is performed. This may be useful if you
|
||||
/// want to modify some properties of the request that EventSource doesn't already have an option for.
|
||||
/// </summary>
|
||||
/// <param name="httpRequestModifier">code that will be called with the request before it is sent</param>
|
||||
/// <returns>the builder</returns>
|
||||
public ConfigurationBuilder HttpRequestModifier(Action<HttpRequestMessage> httpRequestModifier)
|
||||
{
|
||||
this._httpRequestModifier = httpRequestModifier;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the initial amount of time to wait before attempting to reconnect to the EventSource API.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// If the connection fails more than once, the retry delay will increase from this value using
|
||||
/// a backoff algorithm.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A server-directed reconnection time received via the SSE <c>retry:</c> field supersedes
|
||||
/// this value, as do bounds installed by
|
||||
/// <see cref="IEventSource.SetTemporaryRetryDelayBounds(TimeSpan, TimeSpan)"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is <see cref="Configuration.DefaultInitialRetryDelay"/>. Negative values
|
||||
/// are changed to zero.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The actual duration of each delay will vary slightly because there is a random jitter
|
||||
/// factor to avoid clients all reconnecting at once.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="initialRetryDelay">the initial retry delay</param>
|
||||
/// <returns>the builder</returns>
|
||||
/// <seealso cref="MaxRetryDelay(TimeSpan)"/>
|
||||
public ConfigurationBuilder InitialRetryDelay(TimeSpan initialRetryDelay)
|
||||
{
|
||||
_initialRetryDelay = FiniteTimeSpan(initialRetryDelay);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the maximum amount of time to wait before attempting to reconnect.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <c>EventSource</c> uses an exponential backoff algorithm (with random jitter) so that
|
||||
/// the delay between reconnections starts at <see cref="InitialRetryDelay(TimeSpan)"/> but
|
||||
/// increases with each subsequent attempt. <c>MaxRetryDelay</c> sets a limit on how long
|
||||
/// the delay can be.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is <see cref="Configuration.DefaultMaxRetryDelay"/>. Negative values
|
||||
/// are changed to zero.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="maxRetryDelay">the maximum retry delay</param>
|
||||
/// <returns>the builder</returns>
|
||||
/// <seealso cref="InitialRetryDelay(TimeSpan)"/>
|
||||
public ConfigurationBuilder MaxRetryDelay(TimeSpan maxRetryDelay)
|
||||
{
|
||||
_maxRetryDelay = FiniteTimeSpan(maxRetryDelay);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the amount of time a connection must stay open before the EventSource resets its backoff delay.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// If a connection fails before the threshold has elapsed, the delay before reconnecting will be greater
|
||||
/// than the last delay; if it fails after the threshold, the delay will start over at the initial minimum
|
||||
/// value. This prevents long delays from occurring on connections that are only rarely restarted.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A connection that stays open for at least this long also discards any bounds set by
|
||||
/// <see cref="IEventSource.SetTemporaryRetryDelayBounds(TimeSpan, TimeSpan)"/>, restoring
|
||||
/// <see cref="InitialRetryDelay(TimeSpan)"/> and <see cref="MaxRetryDelay(TimeSpan)"/>. A
|
||||
/// server-directed reconnection time received via the SSE <c>retry:</c> field is not
|
||||
/// discarded.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is <see cref="Configuration.DefaultBackoffResetThreshold"/>. Negative
|
||||
/// values are changed to zero.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="backoffResetThreshold">the threshold time</param>
|
||||
/// <returns>the builder</returns>
|
||||
public ConfigurationBuilder BackoffResetThreshold(TimeSpan backoffResetThreshold)
|
||||
{
|
||||
_backoffResetThreshold = FiniteTimeSpan(backoffResetThreshold);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the maximum amount of time EventSource will wait between starting an HTTP request and
|
||||
/// receiving the response headers.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This is the same as the <c>Timeout</c> property in .NET's <c>HttpClient</c>. The default value is
|
||||
/// <see cref="Configuration.DefaultConnectionTimeout"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// It is <i>not</i> the same as a TCP connection timeout. A connection timeout would include only the
|
||||
/// time of establishing the connection, not the time it takes for the server to prepare the beginning
|
||||
/// of the response. .NET does not consistently support a connection timeout, but if you are using .NET
|
||||
/// Core or .NET 5+ you can implement it by using <c>SocketsHttpHandler</c> as your
|
||||
/// <see cref="HttpMessageHandler(System.Net.Http.HttpMessageHandler)"/> and setting the
|
||||
/// <c>ConnectTimeout</c> property there.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="responseStartTimeout">the timeout</param>
|
||||
/// <returns></returns>
|
||||
public ConfigurationBuilder ResponseStartTimeout(TimeSpan responseStartTimeout)
|
||||
{
|
||||
_responseStartTimeout = TimeSpanCanBeInfinite(responseStartTimeout);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the timeout when reading from the EventSource API.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The connection will be automatically dropped and restarted if the server sends no data within
|
||||
/// this interval. This prevents keeping a stale connection that may no longer be working. It is common
|
||||
/// for SSE servers to send a simple comment line (":") as a heartbeat to prevent timeouts.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is <see cref="Configuration.DefaultReadTimeout"/>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public ConfigurationBuilder ReadTimeout(TimeSpan readTimeout)
|
||||
{
|
||||
_readTimeout = TimeSpanCanBeInfinite(readTimeout);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the last event identifier.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Setting this value will cause EventSource to add a "Last-Event-ID" header in its HTTP request.
|
||||
/// This normally corresponds to the <see cref="MessageEvent.LastEventId"/> field of a previously
|
||||
/// received event.
|
||||
/// </remarks>
|
||||
/// <param name="lastEventId">the event identifier</param>
|
||||
/// <returns>the builder</returns>
|
||||
public ConfigurationBuilder LastEventId(string lastEventId)
|
||||
{
|
||||
_lastEventId = lastEventId;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the logging implementation to be used for all EventSource log output.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This uses the <c>ILogAdapter</c> abstraction from the <c>LaunchDarkly.Logging</c> library,
|
||||
/// which provides several basic implementations such as <c>Logs.ToConsole</c> and an integration
|
||||
/// with the .NET Core logging framework. For more about this and about adapters to other logging
|
||||
/// frameworks, see <a href="https://github.com/launchdarkly/dotnet-logging"><c>LaunchDarkly.Logging</c></a>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <c>LaunchDarkly.Logging</c> defines logging levels of Debug, Info, Warn, and Error. If you do not
|
||||
/// want detailed Debug-level logging, use the <c>Level()</c> modifier to set a minimum level of Info
|
||||
/// or above, as shown in the code example (unless you are using an adapter to another logging
|
||||
/// framework that has its own way of doing log filtering).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Log messages will use <see cref="Configuration.DefaultLoggerName"/> as the logger name. If you
|
||||
/// want to specify a different logger name, use <see cref="Logger(Logging.Logger)"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// If you don't specify <see cref="LogAdapter(ILogAdapter)"/> or <see cref="Logger(Logging.Logger)"/>,
|
||||
/// EventSource will not do any logging.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <example>
|
||||
/// using LaunchDarkly.Logging;
|
||||
///
|
||||
/// // Send log output to the console (standard error), suppressing Debug messages
|
||||
/// var config = new ConfigurationBuilder(uri).
|
||||
/// LogAdapter(Logs.ToConsole.Level(LogLevel.Info)).
|
||||
/// Build();
|
||||
/// </example>
|
||||
/// <param name="logAdapter">a <c>LaunchDarkly.Logging.ILogAdapter</c></param>
|
||||
/// <returns>the builder</returns>
|
||||
public ConfigurationBuilder LogAdapter()
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a custom logger to be used for all EventSource log output.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This uses the <c>Logger</c> type from the <c>LaunchDarkly.Logging</c> library,
|
||||
/// which provides several basic implementations such as <c>Logs.ToConsole</c> and an integration
|
||||
/// with the .NET Core logging framework. For more about this and about adapters to other logging
|
||||
/// frameworks, see <a href="https://github.com/launchdarkly/dotnet-logging"><c>LaunchDarkly.Logging</c></a>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// If you don't specify <see cref="LogAdapter(ILogAdapter)"/> or <see cref="Logger(Logging.Logger)"/>,
|
||||
/// EventSource will not do any logging.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <example>
|
||||
/// using LaunchDarkly.Logging;
|
||||
///
|
||||
/// // Define a logger that sends output to the console (standard output), suppressing
|
||||
/// // Debug messages, and using a logger name of "EventStream"
|
||||
/// var logger = Logs.ToConsole.Level(LogLevel.Info).Logger("EventStream");
|
||||
/// var config = new ConfigurationBuilder(uri).
|
||||
/// Logger(logger).
|
||||
/// Build();
|
||||
/// </example>
|
||||
/// <param name="logger">a <c>LaunchDarkly.Logging.Logger</c> instance</param>
|
||||
/// <returns>the builder</returns>
|
||||
public ConfigurationBuilder Logger()
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Specifies whether to use UTF-8 byte arrays internally if possible when
|
||||
/// reading the stream.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// As described in <see cref="MessageEvent"/>, in some applications it may be
|
||||
/// preferable to store and process event data as UTF-8 byte arrays rather than
|
||||
/// strings. By default, <c>EventSource</c> will use the <c>string</c> type when
|
||||
/// processing the event stream; if you then use <see cref="MessageEvent.DataUtf8Bytes"/>
|
||||
/// to get the data, it will be converted to a byte array as needed. However, if
|
||||
/// you set <c>PreferDataAsUtf8Bytes</c> to <see langword="true"/>, the event data
|
||||
/// will be stored internally as a UTF-8 byte array so that if you read
|
||||
/// <see cref="MessageEvent.DataUtf8Bytes"/>, you will get the same array with no
|
||||
/// extra copying or conversion. Therefore, for greatest efficiency you should set
|
||||
/// this to <see langword="true"/> if you intend to process the data as UTF-8. Note
|
||||
/// that Server-Sent Event streams always use UTF-8 encoding, as required by the
|
||||
/// SSE specification.
|
||||
/// </remarks>
|
||||
/// <param name="preferDataAsUtf8Bytes">true if you intend to request the event
|
||||
/// data as UTF-8 bytes</param>
|
||||
/// <returns>the builder</returns>
|
||||
public ConfigurationBuilder PreferDataAsUtf8Bytes(bool preferDataAsUtf8Bytes)
|
||||
{
|
||||
_preferDataAsUtf8Bytes = preferDataAsUtf8Bytes;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the request headers to be sent with each EventSource HTTP request.
|
||||
/// </summary>
|
||||
/// <param name="headers">the headers (null is equivalent to an empty dictionary)</param>
|
||||
/// <returns>the builder</returns>
|
||||
public ConfigurationBuilder RequestHeaders(IDictionary<string, string> headers)
|
||||
{
|
||||
_requestHeaders = headers is null ? new Dictionary<string, string>() :
|
||||
new Dictionary<string, string>(headers);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a request header to be sent with each EventSource HTTP request.
|
||||
/// </summary>
|
||||
/// <param name="name">the header name</param>
|
||||
/// <param name="value">the header value </param>
|
||||
/// <returns>the builder</returns>
|
||||
public ConfigurationBuilder RequestHeader(string name, string value)
|
||||
{
|
||||
if (name != null)
|
||||
{
|
||||
_requestHeaders[name] = value;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <c>HttpMessageHandler</c> that will be used for the HTTP client, or null for the default handler.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If you have specified a custom HTTP client instance with <see cref="HttpClient"/>, then
|
||||
/// <see cref="HttpMessageHandler(HttpMessageHandler)"/> is ignored.
|
||||
/// </remarks>
|
||||
/// <param name="handler">the message handler implementation</param>
|
||||
/// <returns>the builder</returns>
|
||||
public ConfigurationBuilder HttpMessageHandler(HttpMessageHandler handler)
|
||||
{
|
||||
this._httpMessageHandler = handler;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Specifies that EventSource should use a specific HttpClient instance for HTTP requests.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Normally, EventSource creates its own HttpClient and disposes of it when you dispose of the
|
||||
/// EventSource. If you provide your own HttpClient using this method, you are responsible for
|
||||
/// managing the HttpClient's lifecycle-- EventSource will not dispose of it.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// EventSource will not modify this client's properties, so if you call <see cref="HttpMessageHandler"/>
|
||||
/// or <see cref="ConnectionTimeout"/>, those methods will be ignored.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="client">an HttpClient instance, or null to use the default behavior</param>
|
||||
/// <returns>the builder</returns>
|
||||
public ConfigurationBuilder HttpClient(HttpClient client)
|
||||
{
|
||||
this._httpClient = client;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the HTTP method that will be used when connecting to the EventSource API.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// By default, this is <see cref="HttpMethod.Get"/>.
|
||||
/// </remarks>
|
||||
public ConfigurationBuilder Method(HttpMethod method)
|
||||
{
|
||||
this._method = method ?? throw new ArgumentNullException(nameof(method));
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a factory for HTTP request body content, if the HTTP method is one that allows a request body.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is in the form of a factory function because the request may need to be sent more than once.
|
||||
/// </remarks>
|
||||
/// <param name="factory">the factory function, or null for none</param>
|
||||
/// <returns>the builder</returns>
|
||||
public ConfigurationBuilder RequestBodyFactory(Func<HttpContent> factory)
|
||||
{
|
||||
this._requestBodyFactory = factory;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Equivalent <see cref="RequestBodyFactory(Func{HttpContent})"/>, but for content
|
||||
/// that is a simple string.
|
||||
/// </summary>
|
||||
/// <param name="bodyString">the content</param>
|
||||
/// <param name="contentType">the Content-Type header</param>
|
||||
/// <returns>the builder</returns>
|
||||
public ConfigurationBuilder RequestBody(string bodyString, string contentType)
|
||||
{
|
||||
return RequestBodyFactory(() => new StringContent(bodyString, Encoding.UTF8, contentType));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private methods
|
||||
|
||||
// Canonicalizes the value so all negative numbers become InfiniteTimeSpan
|
||||
private static TimeSpan TimeSpanCanBeInfinite(TimeSpan t) =>
|
||||
t < TimeSpan.Zero ? Timeout.InfiniteTimeSpan : t;
|
||||
|
||||
// Replaces all negative times with zero
|
||||
private static TimeSpan FiniteTimeSpan(TimeSpan t) =>
|
||||
t < TimeSpan.Zero ? TimeSpan.Zero : t;
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// An internal class used to hold static values used when processing Server Sent Events.
|
||||
/// </summary>
|
||||
internal static class Constants
|
||||
{
|
||||
/// <summary>
|
||||
/// The HTTP header name for Accept.
|
||||
/// </summary>
|
||||
internal static string AcceptHttpHeader = "Accept";
|
||||
|
||||
/// <summary>
|
||||
/// The HTTP header name for the last event identifier.
|
||||
/// </summary>
|
||||
internal static string LastEventIdHttpHeader = "Last-Event-ID";
|
||||
|
||||
/// <summary>
|
||||
/// The HTTP header value for the Content Type.
|
||||
/// </summary>
|
||||
internal static string EventStreamContentType = "text/event-stream";
|
||||
|
||||
/// <summary>
|
||||
/// The event type name for a Retry in a Server Sent Event.
|
||||
/// </summary>
|
||||
internal static string RetryField = "retry";
|
||||
|
||||
/// <summary>
|
||||
/// The largest reconnection time honored from a Server Sent Event retry field.
|
||||
/// </summary>
|
||||
internal const long MaxServerDirectedRetryDelayMillis = 3_600_000;
|
||||
|
||||
/// <summary>
|
||||
/// The identifier field name in a Server Sent Event.
|
||||
/// </summary>
|
||||
internal static string IdField = "id";
|
||||
|
||||
/// <summary>
|
||||
/// The event type field name in a Server Sent Event.
|
||||
/// </summary>
|
||||
internal static string EventField = "event";
|
||||
|
||||
/// <summary>
|
||||
/// The data field name in a Server Sent Event.
|
||||
/// </summary>
|
||||
internal static string DataField = "data";
|
||||
|
||||
/// <summary>
|
||||
/// The message field name in a Server Sent Event.
|
||||
/// </summary>
|
||||
internal static string MessageField = "message";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// An internal class containing helper methods to parse Server Sent Event data.
|
||||
/// </summary>
|
||||
internal static class EventParser
|
||||
{
|
||||
/// <summary>
|
||||
/// The result returned by <see cref="ParseLineString(string)"/> or <see cref="ParseLineUtf8Bytes(Utf8ByteSpan)"/>.
|
||||
/// </summary>
|
||||
internal struct Result
|
||||
{
|
||||
internal string FieldName { get; set; } // null means it's a comment
|
||||
internal string ValueString { get; set; }
|
||||
internal Utf8ByteSpan ValueBytes { get; set; }
|
||||
|
||||
internal string GetValueAsString() => ValueString is null ? ValueBytes.GetString() : ValueString;
|
||||
|
||||
internal bool IsComment => FieldName is null;
|
||||
internal bool IsDataField => FieldName == "data";
|
||||
internal bool IsEventField => FieldName == "event";
|
||||
internal bool IsIdField => FieldName == "id";
|
||||
internal bool IsRetryField => FieldName == "retry";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to parse a single non-empty line of SSE content that was read as a string. Empty lines
|
||||
/// should not be not passed to this method.
|
||||
/// </summary>
|
||||
/// <param name="line">a line that was read from the stream, not including any trailing CR/LF</param>
|
||||
/// <returns>a <see cref="Result"/> containing the parsed field or comment; <c>ValueString</c> will
|
||||
/// be set rather than <c>ValueBytes</c></returns>
|
||||
internal static Result ParseLineString(string line)
|
||||
{
|
||||
var colonPos = line.IndexOf(':');
|
||||
if (colonPos == 0) // comment
|
||||
{
|
||||
return new Result { ValueString = line };
|
||||
}
|
||||
if (colonPos < 0) // field name without a value - assume empty value
|
||||
{
|
||||
return new Result { FieldName = line, ValueString = "" };
|
||||
}
|
||||
int valuePos = colonPos + 1;
|
||||
if (valuePos < line.Length && line[valuePos] == ' ')
|
||||
{
|
||||
valuePos++; // trim a single leading space from the value, if present
|
||||
}
|
||||
return new Result
|
||||
{
|
||||
FieldName = line.Substring(0, colonPos),
|
||||
ValueString = line.Substring(valuePos)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to parse a single non-empty line of SSE content that was read as UTF-8 bytes. Empty lines
|
||||
/// should not be not passed to this method.
|
||||
/// </summary>
|
||||
/// <param name="line">a line that was read from the stream, not including any trailing CR/LF</param>
|
||||
/// <returns>a <see cref="Result"/> containing the parsed field or comment; <c>ValueBytes</c>
|
||||
/// will be set rather than <c>ValueString</c></returns>
|
||||
public static Result ParseLineUtf8Bytes(Utf8ByteSpan line)
|
||||
{
|
||||
if (line.Length > 0 && line.Data[line.Offset] == ':') // comment
|
||||
{
|
||||
return new Result { ValueBytes = line };
|
||||
}
|
||||
int colonPos = 0;
|
||||
for (; colonPos < line.Length && line.Data[line.Offset + colonPos] != ':'; colonPos++) { }
|
||||
string fieldName = Encoding.UTF8.GetString(line.Data, line.Offset, colonPos);
|
||||
if (colonPos == line.Length) // field name without a value - assume empty value
|
||||
{
|
||||
return new Result {
|
||||
FieldName = fieldName,
|
||||
ValueBytes = new Utf8ByteSpan()
|
||||
};
|
||||
}
|
||||
int valuePos = colonPos + 1;
|
||||
if (valuePos < line.Length && line.Data[line.Offset + valuePos] == ' ')
|
||||
{
|
||||
valuePos++; // trim a single leading space from the value, if present
|
||||
}
|
||||
return new Result
|
||||
{
|
||||
FieldName = fieldName,
|
||||
ValueBytes = new Utf8ByteSpan(line.Data, line.Offset + valuePos, line.Length - valuePos)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides an EventSource client for consuming Server-Sent Events. Additional details on the Server-Sent Events spec
|
||||
/// can be found at https://html.spec.whatwg.org/multipage/server-sent-events.html
|
||||
/// </summary>
|
||||
public class EventSource : IEventSource, IDisposable
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private readonly Configuration _configuration;
|
||||
private readonly HttpClient _httpClient;
|
||||
|
||||
private List<string> _eventDataStringBuffer;
|
||||
private MemoryStream _eventDataUtf8ByteBuffer;
|
||||
private string _eventName;
|
||||
private string _lastEventId;
|
||||
private readonly ExponentialBackoffWithDecorrelation _backOff;
|
||||
private readonly TimeSpan _configuredInitialRetryDelay;
|
||||
private readonly TimeSpan _configuredMaxRetryDelay;
|
||||
private CancellationTokenSource _currentRequestToken;
|
||||
private readonly CancellationTokenSource _shutdownTokenSource = new CancellationTokenSource();
|
||||
private static readonly TimeSpan MaxSleepTime = TimeSpan.FromMilliseconds(int.MaxValue);
|
||||
private readonly Stopwatch _connectionTimer = new Stopwatch();
|
||||
private ReadyState _readyState;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Events
|
||||
|
||||
/// <inheritdoc/>
|
||||
public event EventHandler<StateChangedEventArgs> Opened;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public event EventHandler<StateChangedEventArgs> Closed;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public event EventHandler<CommentReceivedEventArgs> CommentReceived;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public event EventHandler<ExceptionEventArgs> Error;
|
||||
|
||||
#endregion Public Events
|
||||
|
||||
#region Public Properties
|
||||
|
||||
/// <inheritdoc/>
|
||||
public ReadyState ReadyState
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
return _readyState;
|
||||
}
|
||||
}
|
||||
private set
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
_readyState = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal TimeSpan BackOffDelay
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
// Exposed for tests, so that retry-bounds behavior can be asserted directly
|
||||
internal ExponentialBackoffWithDecorrelation BackOff => _backOff;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EventSource" /> class.
|
||||
/// </summary>
|
||||
/// <param name="configuration">the configuration</param>
|
||||
public EventSource(Configuration configuration)
|
||||
{
|
||||
_readyState = ReadyState.Raw;
|
||||
|
||||
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
|
||||
|
||||
|
||||
_configuredInitialRetryDelay = _configuration.InitialRetryDelay;
|
||||
_configuredMaxRetryDelay = _configuration.MaxRetryDelay;
|
||||
|
||||
_backOff = new ExponentialBackoffWithDecorrelation(_configuredInitialRetryDelay,
|
||||
_configuredMaxRetryDelay);
|
||||
|
||||
_httpClient = _configuration.HttpClient ?? CreateHttpClient();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shortcut for initializing an <see cref="EventSource"/> with only a stream URI
|
||||
/// and no custom properties.
|
||||
/// </summary>
|
||||
/// <param name="uri">the stream URI</param>
|
||||
/// <exception cref="ArgumentNullException">if the URI is null</exception>
|
||||
public EventSource(Uri uri) : this(Configuration.Builder(uri).Build()) {}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task StartAsync()
|
||||
{
|
||||
bool firstTime = true;
|
||||
while (ReadyState != ReadyState.Shutdown)
|
||||
{
|
||||
if (!firstTime)
|
||||
{
|
||||
if (_connectionTimer.IsRunning)
|
||||
{
|
||||
if (_connectionTimer.Elapsed >= _configuration.BackoffResetThreshold)
|
||||
{
|
||||
// Sustained healthy operation reverts any temporary bounds and resets
|
||||
// n. Reverting takes precedence over bounds that were
|
||||
// set during the preceding fault window.
|
||||
ClearTemporaryRetryDelayBounds();
|
||||
_backOff.ResetBackoffN();
|
||||
}
|
||||
_connectionTimer.Reset();
|
||||
}
|
||||
await MaybeWaitWithBackOff();
|
||||
}
|
||||
firstTime = false;
|
||||
|
||||
CancellationTokenSource newRequestTokenSource = null;
|
||||
CancellationToken cancellationToken;
|
||||
lock (this)
|
||||
{
|
||||
if (_readyState == ReadyState.Shutdown)
|
||||
{
|
||||
// in case Close() was called in between the previous ReadyState check and the creation of the new token
|
||||
return;
|
||||
}
|
||||
newRequestTokenSource = new CancellationTokenSource();
|
||||
_currentRequestToken?.Dispose();
|
||||
_currentRequestToken = newRequestTokenSource;
|
||||
}
|
||||
|
||||
if (ReadyState == ReadyState.Connecting || ReadyState == ReadyState.Open)
|
||||
{
|
||||
throw new InvalidOperationException(string.Format(Resources.ErrorAlreadyStarted, ReadyState));
|
||||
}
|
||||
|
||||
SetReadyState(ReadyState.Connecting);
|
||||
cancellationToken = newRequestTokenSource.Token;
|
||||
|
||||
try
|
||||
{
|
||||
await ConnectToEventSourceAsync(cancellationToken);
|
||||
|
||||
// ConnectToEventSourceAsync normally doesn't return, unless it detects that the request has been cancelled.
|
||||
Close(ReadyState.Closed);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
CancelCurrentRequest();
|
||||
|
||||
// If the user called Close(), ReadyState = Shutdown, so errors are irrelevant.
|
||||
if (ReadyState != ReadyState.Shutdown)
|
||||
{
|
||||
Exception realException = e;
|
||||
if (realException is AggregateException ae && ae.InnerExceptions.Count == 1)
|
||||
{
|
||||
realException = ae.InnerException;
|
||||
}
|
||||
if (realException is OperationCanceledException oe)
|
||||
{
|
||||
// This exception could either be the result of us explicitly cancelling a request, in which case we don't
|
||||
// need to do anything else, or it could be that the request timed out.
|
||||
if (oe.CancellationToken.IsCancellationRequested)
|
||||
{
|
||||
realException = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
realException = new TimeoutException();
|
||||
}
|
||||
}
|
||||
|
||||
if (realException != null)
|
||||
{
|
||||
OnError(new ExceptionEventArgs(realException));
|
||||
}
|
||||
Close(ReadyState.Closed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task MaybeWaitWithBackOff() {
|
||||
TimeSpan sleepTime = _backOff.GetNextBackOff();
|
||||
if (sleepTime > MaxSleepTime)
|
||||
{
|
||||
// Task.Delay throws for anything above the platform timer ceiling, and this method
|
||||
// runs outside the reconnect loop's exception handling, so an unclamped value
|
||||
// would fault StartAsync and stop the stream permanently.
|
||||
sleepTime = MaxSleepTime;
|
||||
}
|
||||
if (sleepTime > TimeSpan.Zero)
|
||||
{
|
||||
BackOffDelay = sleepTime;
|
||||
try
|
||||
{
|
||||
await Task.Delay(sleepTime, _shutdownTokenSource.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Cancellation happened during the wait, likely intentional close
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Restart(bool resetBackoffDelay)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (_readyState != ReadyState.Open)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (resetBackoffDelay)
|
||||
{
|
||||
_backOff.ResetBackoffN();
|
||||
}
|
||||
}
|
||||
CancelCurrentRequest();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void SetTemporaryRetryDelayBounds(TimeSpan initialDelay, TimeSpan maxDelay)
|
||||
{
|
||||
_backOff.SetBounds(initialDelay, maxDelay);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void ClearTemporaryRetryDelayBounds()
|
||||
{
|
||||
_backOff.SetBounds(_configuredInitialRetryDelay, _configuredMaxRetryDelay);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the connection to the SSE server. The <c>EventSource</c> cannot be reopened after this.
|
||||
/// </summary>
|
||||
public void Close()
|
||||
{
|
||||
if (ReadyState != ReadyState.Shutdown)
|
||||
{
|
||||
Close(ReadyState.Shutdown);
|
||||
}
|
||||
CancelCurrentRequest();
|
||||
_shutdownTokenSource.Cancel();
|
||||
|
||||
// do not dispose httpClient if it is user provided
|
||||
if (_configuration.HttpClient == null)
|
||||
{
|
||||
_httpClient.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Equivalent to calling <see cref="Close()"/>.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
}
|
||||
|
||||
private void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
private HttpClient CreateHttpClient()
|
||||
{
|
||||
var client =_configuration.HttpMessageHandler is null ?
|
||||
new HttpClient() :
|
||||
new HttpClient(_configuration.HttpMessageHandler, false);
|
||||
client.Timeout = _configuration.ResponseStartTimeout;
|
||||
return client;
|
||||
}
|
||||
|
||||
private void CancelCurrentRequest()
|
||||
{
|
||||
CancellationTokenSource requestTokenSource = null;
|
||||
lock (this)
|
||||
{
|
||||
requestTokenSource = _currentRequestToken;
|
||||
_currentRequestToken = null;
|
||||
}
|
||||
if (requestTokenSource != null)
|
||||
{
|
||||
requestTokenSource.Cancel();
|
||||
requestTokenSource.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
internal virtual EventSourceService GetEventSourceService(Configuration configuration)
|
||||
{
|
||||
return new EventSourceService(configuration, _httpClient);
|
||||
}
|
||||
|
||||
private async Task ConnectToEventSourceAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_eventDataStringBuffer = null;
|
||||
_eventDataUtf8ByteBuffer = null;
|
||||
|
||||
var svc = GetEventSourceService(_configuration);
|
||||
|
||||
svc.ConnectionOpened += (o, e) => {
|
||||
_connectionTimer.Restart();
|
||||
SetReadyState(ReadyState.Open, OnOpened, e.Headers);
|
||||
};
|
||||
svc.ConnectionClosed += (o, e) => { SetReadyState(ReadyState.Closed, OnClosed); };
|
||||
|
||||
await svc.GetDataAsync(
|
||||
ProcessResponseLineString,
|
||||
ProcessResponseLineUtf8,
|
||||
_lastEventId,
|
||||
cancellationToken
|
||||
);
|
||||
}
|
||||
|
||||
private void Close(ReadyState state)
|
||||
{
|
||||
SetReadyState(state, OnClosed);
|
||||
}
|
||||
|
||||
private void ProcessResponseLineString(string content)
|
||||
{
|
||||
if (content == null)
|
||||
{
|
||||
// StreamReader may emit a null if the stream has been closed; there's nothing to
|
||||
// be done at this level in that case
|
||||
return;
|
||||
}
|
||||
if (content.Length == 0)
|
||||
{
|
||||
DispatchEvent();
|
||||
}
|
||||
else
|
||||
{
|
||||
HandleParsedLine(EventParser.ParseLineString(content));
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessResponseLineUtf8(Utf8ByteSpan content)
|
||||
{
|
||||
if (content.Length == 0)
|
||||
{
|
||||
DispatchEvent();
|
||||
}
|
||||
else
|
||||
{
|
||||
HandleParsedLine(EventParser.ParseLineUtf8Bytes(content));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void SetReadyState(ReadyState state, Action<StateChangedEventArgs> action = null,
|
||||
IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers = null)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (_readyState == state || _readyState == ReadyState.Shutdown)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_readyState = state;
|
||||
}
|
||||
|
||||
if (action != null)
|
||||
{
|
||||
action(new StateChangedEventArgs(state, headers));
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleParsedLine(EventParser.Result result)
|
||||
{
|
||||
if (result.IsComment)
|
||||
{
|
||||
OnCommentReceived(new CommentReceivedEventArgs(result.GetValueAsString()));
|
||||
}
|
||||
else if (result.IsDataField)
|
||||
{
|
||||
if (result.ValueString != null)
|
||||
{
|
||||
if (_eventDataStringBuffer is null)
|
||||
{
|
||||
_eventDataStringBuffer = new List<string>(2);
|
||||
}
|
||||
_eventDataStringBuffer.Add(result.ValueString);
|
||||
_eventDataStringBuffer.Add("\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_eventDataUtf8ByteBuffer is null)
|
||||
{
|
||||
_eventDataUtf8ByteBuffer = new MemoryStream(result.ValueBytes.Length + 1);
|
||||
}
|
||||
_eventDataUtf8ByteBuffer.Write(result.ValueBytes.Data, result.ValueBytes.Offset, result.ValueBytes.Length);
|
||||
_eventDataUtf8ByteBuffer.WriteByte((byte)'\n');
|
||||
}
|
||||
}
|
||||
else if (result.IsEventField)
|
||||
{
|
||||
_eventName = result.GetValueAsString();
|
||||
}
|
||||
else if (result.IsIdField)
|
||||
{
|
||||
_lastEventId = result.GetValueAsString();
|
||||
}
|
||||
else if (result.IsRetryField)
|
||||
{
|
||||
if (long.TryParse(result.GetValueAsString(), out var retry))
|
||||
{
|
||||
// Clamp while the value is still an integer.
|
||||
var millis = Math.Max(0,
|
||||
Math.Min(retry, Constants.MaxServerDirectedRetryDelayMillis));
|
||||
_backOff.SetServerDirectedMinDelay(TimeSpan.FromMilliseconds(millis));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void DispatchEvent()
|
||||
{
|
||||
var name = _eventName ?? Constants.MessageField;
|
||||
_eventName = null;
|
||||
MessageEvent message;
|
||||
|
||||
if (_eventDataStringBuffer != null)
|
||||
{
|
||||
if (_eventDataStringBuffer.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// remove last item which is always a trailing newline
|
||||
_eventDataStringBuffer.RemoveAt(_eventDataStringBuffer.Count - 1);
|
||||
var dataString = string.Concat(_eventDataStringBuffer);
|
||||
message = new MessageEvent(name, dataString, _lastEventId, _configuration.Uri);
|
||||
|
||||
_eventDataStringBuffer.Clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_eventDataUtf8ByteBuffer is null || _eventDataUtf8ByteBuffer.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var dataSpan = new Utf8ByteSpan(_eventDataUtf8ByteBuffer.GetBuffer(), 0,
|
||||
(int)_eventDataUtf8ByteBuffer.Length - 1); // remove trailing newline
|
||||
message = new MessageEvent(name, dataSpan, _lastEventId, _configuration.Uri);
|
||||
|
||||
// We've now taken ownership of the original buffer; null out the previous
|
||||
// reference to it so a new one will be created next time
|
||||
_eventDataUtf8ByteBuffer = null;
|
||||
}
|
||||
|
||||
OnMessageReceived(new MessageReceivedEventArgs(message));
|
||||
}
|
||||
|
||||
private void OnOpened(StateChangedEventArgs e) =>
|
||||
Opened?.Invoke(this, e);
|
||||
|
||||
private void OnClosed(StateChangedEventArgs e) =>
|
||||
Closed?.Invoke(this, e);
|
||||
|
||||
private void OnMessageReceived(MessageReceivedEventArgs e) =>
|
||||
MessageReceived?.Invoke(this, e);
|
||||
|
||||
private void OnCommentReceived(CommentReceivedEventArgs e) =>
|
||||
CommentReceived?.Invoke(this, e);
|
||||
|
||||
private void OnError(ExceptionEventArgs e) =>
|
||||
Error?.Invoke(this, e);
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Event arguments for the EventSourceService opened event.
|
||||
/// </summary>
|
||||
internal class EventSourceOpenedEventArgs: EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// Construct new event arguments.
|
||||
/// </summary>
|
||||
/// <param name="headers">headers from the HTTP response</param>
|
||||
public EventSourceOpenedEventArgs(IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers)
|
||||
{
|
||||
Headers = headers;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Response headers from the underlying HTTP request.
|
||||
/// </summary>
|
||||
public IEnumerable<KeyValuePair<string,IEnumerable<string>>> Headers { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using static LaunchDarkly.EventSource.AsyncHelpers;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
internal class EventSourceService
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
// Must be >= 4096 to bypass Xamarin.Android.Net.AndroidMessageHandler's
|
||||
// BufferedStream-4096 small-count code path, which stalls SSE reads for
|
||||
// ~60 s waiting for the next server keepalive. See SDK-2755.
|
||||
private const int ReadBufferSize = 8192;
|
||||
|
||||
private readonly Configuration _configuration;
|
||||
private readonly HttpClient _httpClient;
|
||||
|
||||
private const string UserAgentProduct = "DotNetClient";
|
||||
internal static readonly string UserAgentVersion = ((AssemblyInformationalVersionAttribute)typeof(EventSource)
|
||||
.GetTypeInfo()
|
||||
.Assembly
|
||||
.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)))
|
||||
.InformationalVersion;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Events
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when the connection to the EventSource API has been opened.
|
||||
/// </summary>
|
||||
public event EventHandler<EventSourceOpenedEventArgs> ConnectionOpened;
|
||||
/// <summary>
|
||||
/// Occurs when the connection to the EventSource API has been closed.
|
||||
/// </summary>
|
||||
public event EventHandler<EventArgs> ConnectionClosed;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Constructors
|
||||
|
||||
internal EventSourceService(Configuration configuration, HttpClient httpClient)
|
||||
{
|
||||
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
|
||||
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Initiates the request to the EventSource API and parses Server Sent Events received by the API.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="System.Threading.Tasks.Task"/> A task that represents the work queued to execute in the ThreadPool.</returns>
|
||||
public async Task GetDataAsync(
|
||||
Action<string> processResponseLineString,
|
||||
Action<Utf8ByteSpan> processResponseLineUTF8,
|
||||
string lastEventId,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await ConnectToEventSourceApi(processResponseLineString, processResponseLineUTF8, lastEventId, cancellationToken);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
private async Task ConnectToEventSourceApi(
|
||||
Action<string> processResponseLineString,
|
||||
Action<Utf8ByteSpan> processResponseLineUTF8,
|
||||
string lastEventId,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
|
||||
var request = CreateHttpRequestMessage(_configuration.Uri, lastEventId);
|
||||
|
||||
this._configuration.HttpRequestModifier?.Invoke(request);
|
||||
|
||||
using (var response = await _httpClient.SendAsync(request,
|
||||
HttpCompletionOption.ResponseHeadersRead,
|
||||
cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
ValidateResponse(response);
|
||||
|
||||
using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
|
||||
{
|
||||
var encoding = DetectEncoding(response);
|
||||
if (encoding != Encoding.UTF8)
|
||||
{
|
||||
throw new EventSourceServiceCancelledException(
|
||||
string.Format(Resources.ErrorWrongEncoding, encoding.HeaderName));
|
||||
}
|
||||
|
||||
OnConnectionOpened(response.Headers);
|
||||
|
||||
if (_configuration.PreferDataAsUtf8Bytes)
|
||||
{
|
||||
await ProcessResponseFromUtf8StreamAsync(processResponseLineUTF8, stream, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
using (var reader = new StreamReader(stream, Encoding.UTF8,
|
||||
detectEncodingFromByteOrderMarks: true, bufferSize: ReadBufferSize))
|
||||
{
|
||||
await ProcessResponseFromReaderAsync(processResponseLineString, reader, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OnConnectionClosed();
|
||||
}
|
||||
}
|
||||
|
||||
private Encoding DetectEncoding(HttpResponseMessage response)
|
||||
{
|
||||
var charset = response.Content.Headers.ContentType?.CharSet;
|
||||
if (charset != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Encoding.GetEncoding(charset);
|
||||
}
|
||||
catch (ArgumentException) { }
|
||||
}
|
||||
return Encoding.UTF8;
|
||||
}
|
||||
|
||||
protected virtual async Task ProcessResponseFromReaderAsync(
|
||||
Action<string> processResponse,
|
||||
StreamReader reader,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var line = await DoWithTimeout(_configuration.ReadTimeout, cancellationToken,
|
||||
token => AllowCancellation(reader.ReadLineAsync(), token));
|
||||
if (line == null)
|
||||
{
|
||||
// this means the stream is done, i.e. the connection was closed
|
||||
return;
|
||||
}
|
||||
processResponse(line);
|
||||
}
|
||||
}
|
||||
|
||||
protected async Task ProcessResponseFromUtf8StreamAsync(
|
||||
Action<Utf8ByteSpan> processResponseLine,
|
||||
Stream stream,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var lineScanner = new ByteArrayLineScanner(ReadBufferSize);
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// Note that even though Stream.ReadAsync has an overload that takes a CancellationToken, that
|
||||
// does not actually work for network sockets (https://stackoverflow.com/questions/12421989/networkstream-readasync-with-a-cancellation-token-never-cancels).
|
||||
// So we must use AsyncHelpers.AllowCancellation to wrap it in a cancellable task.
|
||||
int bytesRead = await DoWithTimeout(_configuration.ReadTimeout, cancellationToken,
|
||||
token => AllowCancellation(stream.ReadAsync(lineScanner.Buffer, lineScanner.Count, lineScanner.Available), token));
|
||||
if (bytesRead == 0)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return;
|
||||
}
|
||||
lineScanner.AddedBytes(bytesRead);
|
||||
while (lineScanner.ScanToEndOfLine(out var lineSpan))
|
||||
{
|
||||
processResponseLine(lineSpan);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private HttpRequestMessage CreateHttpRequestMessage(Uri uri, string lastEventId)
|
||||
{
|
||||
var request = new HttpRequestMessage(_configuration.Method ?? HttpMethod.Get, uri);
|
||||
|
||||
// Add all headers provided in the Configuration Headers. This allows a consumer to provide any request headers to the EventSource API
|
||||
if (_configuration.RequestHeaders != null)
|
||||
{
|
||||
foreach (var item in _configuration.RequestHeaders)
|
||||
{
|
||||
try
|
||||
{
|
||||
request.Headers.Add(item.Key, item.Value);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
// Avoid showing the Authorization header value in the exception message
|
||||
if (item.Key.Equals("Authorization", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new FormatException("The Authorization header is invalid.");
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add the request body, if any.
|
||||
if (_configuration.RequestBodyFactory != null)
|
||||
{
|
||||
HttpContent requestBody = _configuration.RequestBodyFactory();
|
||||
if (requestBody != null)
|
||||
{
|
||||
request.Content = requestBody;
|
||||
}
|
||||
}
|
||||
|
||||
// If the lastEventId was provided, include it as a header to the API request.
|
||||
if (!string.IsNullOrWhiteSpace(lastEventId))
|
||||
{
|
||||
request.Headers.Remove(Constants.LastEventIdHttpHeader);
|
||||
request.Headers.Add(Constants.LastEventIdHttpHeader, lastEventId);
|
||||
}
|
||||
|
||||
// If we haven't set the LastEventId header and if the EventSource Configuration was provided with a LastEventId,
|
||||
// include it as a header to the API request.
|
||||
if (!string.IsNullOrWhiteSpace(_configuration.LastEventId) && !request.Headers.Contains(Constants.LastEventIdHttpHeader))
|
||||
request.Headers.Add(Constants.LastEventIdHttpHeader, _configuration.LastEventId);
|
||||
|
||||
if (request.Headers.UserAgent.Count == 0)
|
||||
request.Headers.UserAgent.ParseAdd(UserAgentProduct + "/" + UserAgentVersion);
|
||||
|
||||
// Add the Accept Header if it wasn't provided in the Configuration
|
||||
if (!request.Headers.Contains(Constants.AcceptHttpHeader))
|
||||
request.Headers.Add(Constants.AcceptHttpHeader, Constants.EventStreamContentType);
|
||||
|
||||
request.Headers.ExpectContinue = false;
|
||||
request.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true };
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
private void ValidateResponse(HttpResponseMessage response)
|
||||
{
|
||||
// Any non-2xx response status is an error. A 204 (no content) is also an error.
|
||||
if (!response.IsSuccessStatusCode || response.StatusCode == System.Net.HttpStatusCode.NoContent)
|
||||
{
|
||||
throw new EventSourceServiceUnsuccessfulResponseException((int)response.StatusCode, response.Headers);
|
||||
}
|
||||
|
||||
if (response.Content == null)
|
||||
{
|
||||
throw new EventSourceServiceCancelledException(Resources.ErrorEmptyResponse);
|
||||
}
|
||||
|
||||
if (response.Content.Headers.ContentType.MediaType != Constants.EventStreamContentType)
|
||||
{
|
||||
throw new EventSourceServiceCancelledException(
|
||||
string.Format(Resources.ErrorWrongContentType, response.Content.Headers.ContentType));
|
||||
}
|
||||
}
|
||||
|
||||
private void OnConnectionOpened(HttpHeaders headers)
|
||||
{
|
||||
ConnectionOpened?.Invoke(this, new EventSourceOpenedEventArgs(headers));
|
||||
}
|
||||
|
||||
private void OnConnectionClosed()
|
||||
{
|
||||
ConnectionClosed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// General superclass for exceptions that caused the EventSource to disconnect or fail to establish
|
||||
/// a connection.
|
||||
/// </summary>
|
||||
public class EventSourceServiceCancelledException : Exception
|
||||
{
|
||||
|
||||
#region Public Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance.
|
||||
/// </summary>
|
||||
/// <param name="message">the exception message</param>
|
||||
public EventSourceServiceCancelledException(string message) : base(message) { }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance with an inner exception.
|
||||
/// </summary>
|
||||
/// <param name="message">the exception message</param>
|
||||
/// <param name="innerException">the inner exception</param>
|
||||
public EventSourceServiceCancelledException(string message, Exception innerException) :
|
||||
base(message, innerException)
|
||||
{ }
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Indicates that the EventSource was able to establish an HTTP connection, but received a
|
||||
/// non-successful status code.
|
||||
/// </summary>
|
||||
public class EventSourceServiceUnsuccessfulResponseException : EventSourceServiceCancelledException
|
||||
{
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// The HTTP status code of the response.
|
||||
/// </summary>
|
||||
public int StatusCode { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The HTTP headers from the response.
|
||||
/// </summary>
|
||||
public IEnumerable<KeyValuePair<string, IEnumerable<string>>> Headers { get; }
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">the HTTP status code of the response</param>
|
||||
public EventSourceServiceUnsuccessfulResponseException(int statusCode) :
|
||||
this(statusCode, new Dictionary<string, IEnumerable<string>>())
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance with headers.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">the HTTP status code of the response</param>
|
||||
/// <param name="headers">the HTTP headers from the response</param>
|
||||
public EventSourceServiceUnsuccessfulResponseException(int statusCode, IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers) :
|
||||
base(string.Format(Resources.ErrorHttpStatus, statusCode))
|
||||
{
|
||||
StatusCode = statusCode;
|
||||
Headers = headers ?? new Dictionary<string, IEnumerable<string>>();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides exception data raised in the EventSource <see cref="EventSource.Error" /> event.
|
||||
/// </summary>
|
||||
/// <seealso cref="System.EventArgs" />
|
||||
public class ExceptionEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the <see cref="System.Exception"/> that represents the error that occurred.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The exception.
|
||||
/// </value>
|
||||
public Exception Exception { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ExceptionEventArgs"/> class.
|
||||
/// </summary>
|
||||
/// <param name="ex">A <see cref="System.Exception"/> that represents the error that occurred.</param>
|
||||
public ExceptionEventArgs(Exception ex)
|
||||
{
|
||||
Exception = ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
using System;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
internal sealed class ExponentialBackoffWithDecorrelation
|
||||
{
|
||||
private readonly object _lock = new object();
|
||||
private readonly Random _randomSource;
|
||||
|
||||
private TimeSpan _minimumDelay;
|
||||
private TimeSpan _maximumDelay;
|
||||
private int _backoffN;
|
||||
private TimeSpan? _serverDirectedMinDelay;
|
||||
|
||||
public ExponentialBackoffWithDecorrelation(TimeSpan minimumDelay, TimeSpan maximumDelay)
|
||||
: this(minimumDelay, maximumDelay, new Random())
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs an instance with a caller-supplied <see cref="Random"/>, so that tests can
|
||||
/// make jitter deterministic.
|
||||
/// </summary>
|
||||
internal ExponentialBackoffWithDecorrelation(TimeSpan minimumDelay, TimeSpan maximumDelay,
|
||||
Random randomSource)
|
||||
{
|
||||
_minimumDelay = NonNegative(minimumDelay);
|
||||
_maximumDelay = NonNegative(maximumDelay);
|
||||
_randomSource = randomSource ?? new Random();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the next backoff duration, advancing n.
|
||||
/// </summary>
|
||||
public TimeSpan GetNextBackOff()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
long unjittered = GetUnjitteredMillisecondsForN(_backoffN);
|
||||
|
||||
// Random.Next takes an int bound. 2^31 milliseconds is far longer than any
|
||||
// reconnect delay we would use, so saturating here cannot affect a realistic
|
||||
// delay.
|
||||
int jitterBound = (int)Math.Min(unjittered, int.MaxValue);
|
||||
long delayMillis = unjittered / 2
|
||||
+ (jitterBound > 0 ? _randomSource.Next(jitterBound) / 2 : 0);
|
||||
|
||||
_backoffN++;
|
||||
return TimeSpan.FromMilliseconds(delayMillis);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the delay in whole milliseconds for a given backoff <c>n</c>, before jitter is
|
||||
/// applied: <c>minimumDelay * 2^n</c>, limited to the maximum.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The caller must hold the lock. This reads the bounds without taking it because it is the
|
||||
/// inner core of <see cref="GetNextBackOff"/>, which already holds it; taking it here would
|
||||
/// only be a re-entrant acquisition on the hot path. Anything needing a synchronized read of
|
||||
/// the bounds on its own should use the accessors below, which take the lock themselves.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <c>n</c> is compared against the ceiling rather than used to compute a value that is
|
||||
/// then clamped, so no intermediate ever exceeds the maximum. That matters because
|
||||
/// <c>n</c> is unbounded: a long outage keeps incrementing it, and computing
|
||||
/// <c>minimumDelay * 2^n</c> directly would overflow.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal long GetUnjitteredMillisecondsForN(int n)
|
||||
{
|
||||
long min = (_serverDirectedMinDelay ?? _minimumDelay).Ticks
|
||||
/ TimeSpan.TicksPerMillisecond;
|
||||
long max = _maximumDelay.Ticks / TimeSpan.TicksPerMillisecond;
|
||||
|
||||
if (min <= 0 || max <= 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
if (n <= 0)
|
||||
{
|
||||
return min > max ? max : min;
|
||||
}
|
||||
|
||||
// Shifting the ceiling down cannot overflow, whereas shifting the minimum up can.
|
||||
// The n >= 63 test is required rather than defensive: C# masks a 64-bit shift count
|
||||
// to its low 6 bits, so `max >> 64` would silently mean `max >> 0`.
|
||||
if (n >= 63 || min > (max >> n))
|
||||
{
|
||||
return max;
|
||||
}
|
||||
return min << n;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies a server-directed reconnection time received via the SSE <c>retry:</c> field,
|
||||
/// replacing the minimum delay used to compute subsequent backoffs.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The override takes precedence over both the configured minimum and any minimum
|
||||
/// installed by <see cref="SetBounds"/>. It is sticky: it survives bounds changes and
|
||||
/// <see cref="ResetBackoffN"/>, and is replaced only by a later server-directed value.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The maximum is never affected, so the ceiling that bounds reconnection keeps applying.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// n resets, so the next attempt uses the directed value itself rather than continuing to
|
||||
/// double from wherever the progression had reached.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Negative values become zero. No upper bound is applied here; a caller taking a value
|
||||
/// from an untrusted source is responsible for capping it first.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="minDelay">the server-directed reconnection time</param>
|
||||
public void SetServerDirectedMinDelay(TimeSpan minDelay)
|
||||
{
|
||||
var value = NonNegative(minDelay);
|
||||
lock (_lock)
|
||||
{
|
||||
_serverDirectedMinDelay = value;
|
||||
_backoffN = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the delay bounds.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the new bounds differ from the current ones, n resets so that the
|
||||
/// next delay starts from the new minimum. If they are the same, this does nothing, which
|
||||
/// makes repeated calls with identical values idempotent -- a caller that reapplies the
|
||||
/// same bounds on every failure will not pin the delay at the minimum.
|
||||
/// </remarks>
|
||||
/// <param name="minimumDelay">the new minimum delay; negative values become zero</param>
|
||||
/// <param name="maximumDelay">the new maximum delay; negative values become zero</param>
|
||||
public void SetBounds(TimeSpan minimumDelay, TimeSpan maximumDelay)
|
||||
{
|
||||
var min = NonNegative(minimumDelay);
|
||||
var max = NonNegative(maximumDelay);
|
||||
lock (_lock)
|
||||
{
|
||||
if (min == _minimumDelay && max == _maximumDelay)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_minimumDelay = min;
|
||||
_maximumDelay = max;
|
||||
_backoffN = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets n so the next delay starts from the current minimum, without
|
||||
/// changing the bounds.
|
||||
/// </summary>
|
||||
public void ResetBackoffN()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_backoffN = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Accessors for tests.
|
||||
|
||||
internal int GetBackoffN()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _backoffN;
|
||||
}
|
||||
}
|
||||
|
||||
internal TimeSpan? GetServerDirectedMinDelay()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _serverDirectedMinDelay;
|
||||
}
|
||||
}
|
||||
|
||||
internal TimeSpan GetMinimumDelay()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _minimumDelay;
|
||||
}
|
||||
}
|
||||
|
||||
internal TimeSpan GetMaximumDelay()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _maximumDelay;
|
||||
}
|
||||
}
|
||||
|
||||
// Matches the clamping behavior of ConfigurationBuilder's retry-delay setters: a negative
|
||||
// duration becomes zero rather than throwing.
|
||||
private static TimeSpan NonNegative(TimeSpan t) => t < TimeSpan.Zero ? TimeSpan.Zero : t;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// This interface defines the public members of <see cref="EventSource"/>.
|
||||
/// </summary>
|
||||
public interface IEventSource
|
||||
{
|
||||
#region Public Events
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when the connection to the EventSource API has been opened.
|
||||
/// </summary>
|
||||
event EventHandler<StateChangedEventArgs> Opened;
|
||||
/// <summary>
|
||||
/// Occurs when the connection to the EventSource API has been closed.
|
||||
/// </summary>
|
||||
event EventHandler<StateChangedEventArgs> Closed;
|
||||
/// <summary>
|
||||
/// Occurs when a Server Sent Event from the EventSource API has been received.
|
||||
/// </summary>
|
||||
event EventHandler<MessageReceivedEventArgs> MessageReceived;
|
||||
/// <summary>
|
||||
/// Occurs when a comment has been received from the EventSource API.
|
||||
/// </summary>
|
||||
event EventHandler<CommentReceivedEventArgs> CommentReceived;
|
||||
/// <summary>
|
||||
/// Occurs when an error has happened when the EventSource is open and processing Server Sent Events.
|
||||
/// </summary>
|
||||
event EventHandler<ExceptionEventArgs> Error;
|
||||
|
||||
#endregion Public Events
|
||||
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// Gets the state of the EventSource connection.
|
||||
/// </summary>
|
||||
ReadyState ReadyState { get; }
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Initiates a connection to the SSE server and begins parsing events.
|
||||
/// </summary>
|
||||
/// <returns>a <see cref="Task"/> that will be completed only when the
|
||||
/// <c>EventSource</c> is closed</returns>
|
||||
/// <exception cref="InvalidOperationException">if the method was called again after the
|
||||
/// stream connection was already active</exception>
|
||||
Task StartAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Triggers the same "close and retry" behavior as if an error had been encountered on the stream.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// If the stream is currently active, this closes the connection, waits for some amount of time
|
||||
/// as determined by the usual backoff behavior (and <paramref name="resetBackoffDelay"/>), and
|
||||
/// then attempts to reconnect. If the stream is not yet connected, is already waiting to
|
||||
/// reconnect, or has been permanently shut down, this has no effect.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The method returns immediately without waiting for the reconnection to happen. You will
|
||||
/// receive <see cref="Closed"/> and <see cref="Opened"/> events when it does happen (or an
|
||||
/// <see cref="Error"/> event if the new connection attempt fails).
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="resetBackoffDelay">true if the delay before reconnection should be reset to
|
||||
/// the lowest level of the currently active bounds, which could be the temporary bounds if
|
||||
/// <see cref="SetTemporaryRetryDelayBounds(TimeSpan, TimeSpan)"/> is in effect; false if it
|
||||
/// should increase according to the usual exponential backoff logic</param>
|
||||
void Restart(bool resetBackoffDelay);
|
||||
|
||||
/// <summary>
|
||||
/// Temporarily replaces the bounds used to compute reconnection delays.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The configured <see cref="ConfigurationBuilder.InitialRetryDelay(TimeSpan)"/> and
|
||||
/// <see cref="ConfigurationBuilder.MaxRetryDelay(TimeSpan)"/> normally govern the
|
||||
/// exponential backoff between reconnection attempts. This method installs different
|
||||
/// bounds at runtime, so a caller can slow reconnection down without reconfiguring or
|
||||
/// recreating the <c>EventSource</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The bounds are <i>temporary</i>: they remain in effect until either a connection stays
|
||||
/// open for at least
|
||||
/// <see cref="ConfigurationBuilder.BackoffResetThreshold(TimeSpan)"/>, at which point the
|
||||
/// configured bounds are restored automatically, or
|
||||
/// <see cref="ClearTemporaryRetryDelayBounds"/> is called.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Changing the bounds resets the backoff level, so the next delay is computed from the new
|
||||
/// <paramref name="initialDelay"/> rather than continuing to grow from where it left off.
|
||||
/// Calling this with bounds that are already in effect does nothing, so it is safe to call
|
||||
/// repeatedly.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Negative values are changed to zero. If <paramref name="initialDelay"/> is greater than
|
||||
/// <paramref name="maxDelay"/>, delays are limited to <paramref name="maxDelay"/>. No
|
||||
/// argument causes this method to throw, and no argument can cause a later reconnect to
|
||||
/// fail.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A server-directed reconnection time received via the SSE <c>retry:</c> field supersedes
|
||||
/// <paramref name="initialDelay"/>, and the configured
|
||||
/// <see cref="ConfigurationBuilder.InitialRetryDelay(TimeSpan)"/> along with it. Such a
|
||||
/// value does not affect <paramref name="maxDelay"/>, so the ceiling set here continues to
|
||||
/// bound reconnection.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// It is safe to call this from any thread, including from an
|
||||
/// <see cref="Error"/> handler.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="initialDelay">the lowest delay to use while these bounds are in effect,
|
||||
/// unless a server-directed <c>retry:</c> value supersedes it</param>
|
||||
/// <param name="maxDelay">the highest delay to use while these bounds are in effect</param>
|
||||
/// <seealso cref="ClearTemporaryRetryDelayBounds"/>
|
||||
void SetTemporaryRetryDelayBounds(TimeSpan initialDelay, TimeSpan maxDelay);
|
||||
|
||||
/// <summary>
|
||||
/// Discards any bounds installed by
|
||||
/// <see cref="SetTemporaryRetryDelayBounds(TimeSpan, TimeSpan)"/>, restoring the configured
|
||||
/// <see cref="ConfigurationBuilder.MaxRetryDelay(TimeSpan)"/> and, unless a server-directed
|
||||
/// <c>retry:</c> value is in effect, the configured
|
||||
/// <see cref="ConfigurationBuilder.InitialRetryDelay(TimeSpan)"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Restoring the configured bounds resets the backoff level. If no temporary bounds
|
||||
/// are in effect this does nothing. The count of reconnection attempts is not reset.
|
||||
/// Calling this is not required as the configured bounds are also restored automatically
|
||||
/// after a connection stays open for
|
||||
/// <see cref="ConfigurationBuilder.BackoffResetThreshold(TimeSpan)"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A server-directed reconnection time received via the SSE <c>retry:</c> field is not
|
||||
/// discarded and continues to supersede
|
||||
/// <see cref="ConfigurationBuilder.InitialRetryDelay(TimeSpan)"/>, so the configured
|
||||
/// minimum may not be the one actually in use afterwards. Only a later <c>retry:</c> value
|
||||
/// replaces it. <see cref="ConfigurationBuilder.MaxRetryDelay(TimeSpan)"/> is unaffected
|
||||
/// and is always restored.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <seealso cref="SetTemporaryRetryDelayBounds(TimeSpan, TimeSpan)"/>
|
||||
void ClearTemporaryRetryDelayBounds();
|
||||
|
||||
/// <summary>
|
||||
/// Closes the connection to the SSE server. The <c>EventSource</c> cannot be reopened after this.
|
||||
/// </summary>
|
||||
void Close();
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
using System;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents the Server-Sent Event message received from a stream.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// An SSE event consists of an event name (defaulting to "message" if not specified),
|
||||
/// a data string, and an optional "ID" string that the server may provide.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The event name and ID properties are always stored as strings. By default, the
|
||||
/// data property is also stored as a string. However, in some applications, it may
|
||||
/// be desirable to represent the data as a UTF-8 byte array (for instance, if you are
|
||||
/// using the <c>System.Text.Json</c> API to parse JSON data).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Since strings in .NET use two-byte UTF-16 characters, if you have a large block of
|
||||
/// UTF-8 data it is considerably more efficient to process it in its original form
|
||||
/// rather than converting it to or from a string. <see cref="EventSource"/> stores
|
||||
/// data as strings by default, but you set <see cref="ConfigurationBuilder.PreferDataAsUtf8Bytes(bool)"/>
|
||||
/// it can store the raw UTF-8 data instead. In either case, <c>MessageEvent</c> will
|
||||
/// convert types transparently so that you can read either <see cref="MessageEvent.Data"/>
|
||||
/// or <see cref="MessageEvent.DataUtf8Bytes"/>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public struct MessageEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// The default value of <see cref="Name"/> if the SSE stream did not specify an
|
||||
/// <c>event:</c> field.
|
||||
/// </summary>
|
||||
public const string DefaultName = "message";
|
||||
|
||||
#region Private Fields
|
||||
|
||||
private readonly string _name;
|
||||
private readonly string _dataString;
|
||||
private readonly Utf8ByteSpan _dataUtf8Bytes;
|
||||
private readonly string _lastEventId;
|
||||
private readonly Uri _origin;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MessageEvent"/> class.
|
||||
/// </summary>
|
||||
/// <param name="name">the event name</param>
|
||||
/// <param name="data">the data received in the server-sent event</param>
|
||||
/// <param name="lastEventId">the last event identifier, or null</param>
|
||||
/// <param name="origin">the origin URI of the stream</param>
|
||||
public MessageEvent(string name, string data, string lastEventId, Uri origin)
|
||||
{
|
||||
_name = name;
|
||||
_dataString = data;
|
||||
_dataUtf8Bytes = new Utf8ByteSpan();
|
||||
_lastEventId = lastEventId;
|
||||
_origin = origin;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MessageEvent"/> class,
|
||||
/// providing the data as a UTF-8 byte span.
|
||||
/// </summary>
|
||||
/// <param name="name">the event name</param>
|
||||
/// <param name="dataUtf8Bytes">the data received in the server-sent event;
|
||||
/// the <c>MessageEvent</c> will store a reference to the byte array, rather than
|
||||
/// copying it, so it should not be modified afterward by the caller
|
||||
/// </param>
|
||||
/// <param name="lastEventId">the last event identifier, or null</param>
|
||||
/// <param name="origin">the origin URI of the stream</param>
|
||||
public MessageEvent(string name, Utf8ByteSpan dataUtf8Bytes, string lastEventId, Uri origin)
|
||||
{
|
||||
_name = name;
|
||||
_dataString = null;
|
||||
_dataUtf8Bytes = dataUtf8Bytes;
|
||||
_lastEventId = lastEventId;
|
||||
_origin = origin;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MessageEvent" /> class.
|
||||
/// </summary>
|
||||
/// <param name="name">the event name</param>
|
||||
/// <param name="data">the data received in the server-sent event</param>
|
||||
/// <param name="origin">the origin URI of the stream</param>
|
||||
/// <remarks>
|
||||
/// The <see cref="LastEventId" /> will be initialized to null.
|
||||
/// </remarks>
|
||||
public MessageEvent(string name, string data, Uri origin) : this(name, data, null, origin) { }
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// The event name.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This can be specified by the server in the <c>event:</c> field in the SSE data, as in
|
||||
/// <c>event: my-event-name</c>. If there is no <c>event:</c> field, the default name
|
||||
/// is <see cref="DefaultName"/>.
|
||||
/// </remarks>
|
||||
public string Name => _name;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the data received in the event as a string.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This is the value of the <c>data:</c> field in the SSE data; if there are multiple
|
||||
/// <c>data:</c> lines for a single event, they are concatenated with <c>"\n"</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// If the data was originally stored as a string, the same string is returned.
|
||||
/// If it was stored as a UTF-8 byte array, the bytes are copied to a new string.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public string Data => _dataString is null ? _dataUtf8Bytes.GetString() : _dataString;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the data received in the event as a UTF-8 byte span.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This is the value of the <c>data:</c> field in the SSE data; if there are multiple
|
||||
/// <c>data:</c> lines for a single event, they are concatenated with <c>"\n"</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// If the data was originally stored as UTF-8 bytes, the returned value refers to
|
||||
/// the same array, offset, and length (it is the caller's responsibility not to
|
||||
/// modify the byte array). If it was originally stored as a string, the string
|
||||
/// is copied to a new byte array.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public Utf8ByteSpan DataUtf8Bytes => _dataString is null ? _dataUtf8Bytes :
|
||||
new Utf8ByteSpan(_dataString);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last event identifier received in the server-sent event.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is the value of the <c>id:</c> field in the SSE data. If there is no such
|
||||
/// field, it is null. You can use a previously received <see cref="LastEventId"/>
|
||||
/// value with <see cref="ConfigurationBuilder.LastEventId(string)"/> when starting
|
||||
/// a new <see cref="EventSource"/> to tell the server what the last event you
|
||||
/// received was, although not all servers support this.
|
||||
/// </remarks>
|
||||
public string LastEventId => _lastEventId;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the origin URI of the stream that generated the server-sent event.
|
||||
/// </summary>
|
||||
public Uri Origin => _origin;
|
||||
|
||||
/// <summary>
|
||||
/// True if the event data is stored internally as UTF-8 bytes.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The data can be accessed with either <see cref="Data"/> or <see cref="DataUtf8Bytes"/>
|
||||
/// regardless of the value of this property. The property only indicates the <i>original</i>
|
||||
/// format of the data, so, for instance, if it is <see langword="true"/> then
|
||||
/// reading <see cref="Data"/> will have more overhead (due to copying) than
|
||||
/// reading <see cref="DataUtf8Bytes"/>.
|
||||
/// </remarks>
|
||||
public bool IsDataUtf8Bytes => _dataString is null;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method is potentially inefficient and should be used only in testing.
|
||||
/// </remarks>
|
||||
/// <param name="obj">the <see cref="System.Object" /> to compare with this instance</param>
|
||||
/// <returns><see langword="true"/> if the instances are equal</returns>
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
if (!(obj is MessageEvent that) ||
|
||||
!object.Equals(Name, that.Name) ||
|
||||
!object.Equals(LastEventId, that.LastEventId) ||
|
||||
!object.Equals(Origin, that.Origin))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (this._dataString != null)
|
||||
{
|
||||
return that._dataString != null ?
|
||||
this._dataString == that._dataString :
|
||||
that._dataUtf8Bytes.Equals(this._dataString);
|
||||
|
||||
}
|
||||
return that._dataString != null ?
|
||||
this._dataUtf8Bytes.Equals(that._dataString) :
|
||||
this._dataUtf8Bytes.Equals(that._dataUtf8Bytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a hash code for this instance.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
|
||||
/// This method is potentially inefficient and should be used only in testing.
|
||||
/// </returns>
|
||||
public override int GetHashCode()
|
||||
{
|
||||
int hash = 17;
|
||||
|
||||
hash = hash * 31 + (_dataString != null ? _dataString.GetHashCode() : _dataUtf8Bytes.GetString().GetHashCode());
|
||||
hash = hash * 31 + (_lastEventId != null ? _lastEventId.GetHashCode() : 0);
|
||||
hash = hash * 31 + (_origin != null ? _origin.GetHashCode() : 0);
|
||||
return hash;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// The parameter type for a <see cref="EventSource.MessageReceived"/> event handler.
|
||||
/// </summary>
|
||||
/// <seealso cref="System.EventArgs" />
|
||||
public class MessageReceivedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see cref="MessageEvent"/> representing the event that was received from the
|
||||
/// SSE stream.
|
||||
/// </summary>
|
||||
public MessageEvent Message { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Shortcut for getting the <see cref="MessageEvent.Name"/> property of the event.
|
||||
/// </summary>
|
||||
public string EventName => Message.Name;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance.
|
||||
/// </summary>
|
||||
/// <param name="message">the <see cref="MessageEvent"/> received from the stream</param>
|
||||
public MessageReceivedEventArgs(MessageEvent message)
|
||||
{
|
||||
Message = message;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// An exception that indicates that the configured read timeout elapsed without receiving
|
||||
/// any new data from the server.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Socket connections can fail silently, in which case an EventSource client without a read
|
||||
/// timeout would hang forever waiting for new data. A read timeout allows you to make a new
|
||||
/// stream connection in this case. The server can send periodic comment lines (":\n") to
|
||||
/// keep the client from timing out if the connection is still working.
|
||||
/// </remarks>
|
||||
public class ReadTimeoutException : Exception
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override string Message => Resources.ErrorReadTimeout;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents the state of the connection in the <see cref="EventSource"/> class.
|
||||
/// </summary>
|
||||
public enum ReadyState
|
||||
{
|
||||
/// <summary>
|
||||
/// The initial state of the connection.
|
||||
/// </summary>
|
||||
Raw,
|
||||
/// <summary>
|
||||
/// The connection has not yet been established, or it was closed and is reconnecting.
|
||||
/// </summary>
|
||||
Connecting,
|
||||
/// <summary>
|
||||
/// The connection is open and is processing events as it receives them.
|
||||
/// </summary>
|
||||
Open,
|
||||
/// <summary>
|
||||
/// The connection is closed. This could also occur when an error is received.
|
||||
/// </summary>
|
||||
Closed,
|
||||
/// <summary>
|
||||
/// The connection has been shutdown explicitly by the consumer using the <see cref="EventSource.Close()"/> method.
|
||||
/// </summary>
|
||||
Shutdown
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace LaunchDarkly.EventSource {
|
||||
using System;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// A strongly-typed resource class, for looking up localized strings, etc.
|
||||
/// This class was generated by MSBuild using the GenerateResource task.
|
||||
/// To add or remove a member, edit your .resx file then rerun MSBuild.
|
||||
/// </summary>
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Build.Tasks.StronglyTypedResourceBuilder", "15.1.0.0")]
|
||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
internal class Resources {
|
||||
|
||||
private static global::System.Resources.ResourceManager resourceMan;
|
||||
|
||||
private static global::System.Globalization.CultureInfo resourceCulture;
|
||||
|
||||
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
|
||||
internal Resources() {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the cached ResourceManager instance used by this class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Resources.ResourceManager ResourceManager {
|
||||
get {
|
||||
if (object.ReferenceEquals(resourceMan, null)) {
|
||||
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LaunchDarkly.EventSource.Resources", typeof(Resources).Assembly);
|
||||
resourceMan = temp;
|
||||
}
|
||||
return resourceMan;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Overrides the current thread's CurrentUICulture property for all
|
||||
/// resource lookups using this strongly typed resource class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Globalization.CultureInfo Culture {
|
||||
get {
|
||||
return resourceCulture;
|
||||
}
|
||||
set {
|
||||
resourceCulture = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Invalid attempt to call Start() while the connection state is {0}.
|
||||
/// </summary>
|
||||
internal static string ErrorAlreadyStarted {
|
||||
get {
|
||||
return ResourceManager.GetString("ErrorAlreadyStarted", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to HTTP response had no body.
|
||||
/// </summary>
|
||||
internal static string ErrorEmptyResponse {
|
||||
get {
|
||||
return ResourceManager.GetString("ErrorEmptyResponse", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Unexpected HTTP status code {0} from server.
|
||||
/// </summary>
|
||||
internal static string ErrorHttpStatus {
|
||||
get {
|
||||
return ResourceManager.GetString("ErrorHttpStatus", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Read timeout elapsed with no new data from server; connection may have been silently dropped.
|
||||
/// </summary>
|
||||
internal static string ErrorReadTimeout {
|
||||
get {
|
||||
return ResourceManager.GetString("ErrorReadTimeout", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Unexpected HTTP content type "{0}"; should be "text/event-stream".
|
||||
/// </summary>
|
||||
internal static string ErrorWrongContentType {
|
||||
get {
|
||||
return ResourceManager.GetString("ErrorWrongContentType", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Unexpected character encoding {0}; should be UTF-8.
|
||||
/// </summary>
|
||||
internal static string ErrorWrongEncoding {
|
||||
get {
|
||||
return ResourceManager.GetString("ErrorWrongEncoding", resourceCulture);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="ErrorReadTimeout" xml:space="preserve">
|
||||
<value>Read timeout elapsed with no new data from server; connection may have been silently dropped</value>
|
||||
</data>
|
||||
<data name="ErrorAlreadyStarted" xml:space="preserve">
|
||||
<value>Invalid attempt to call Start() while the connection state is {0}</value>
|
||||
</data>
|
||||
<data name="ErrorHttpStatus" xml:space="preserve">
|
||||
<value>Unexpected HTTP status code {0} from server</value>
|
||||
</data>
|
||||
<data name="ErrorWrongContentType" xml:space="preserve">
|
||||
<value>Unexpected HTTP content type "{0}"; should be "text/event-stream"</value>
|
||||
</data>
|
||||
<data name="ErrorWrongEncoding" xml:space="preserve">
|
||||
<value>Unexpected character encoding {0}; should be UTF-8</value>
|
||||
</data>
|
||||
<data name="ErrorEmptyResponse" xml:space="preserve">
|
||||
<value>HTTP response had no body</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides data for the state of the <see cref="EventSource"/> connection.
|
||||
/// </summary>
|
||||
/// <seealso cref="System.EventArgs" />
|
||||
public class StateChangedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the state of the EventSource connection.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// One of the <see cref="EventSource.ReadyState"/> values, which represents the state of the EventSource connection.
|
||||
/// </value>
|
||||
public ReadyState ReadyState { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Get the response headers. Only populated for <see cref="ReadyState.Open"/>.
|
||||
/// <value>
|
||||
/// A collection of header values when the ReadyState is Open, or null.
|
||||
/// </value>
|
||||
/// </summary>
|
||||
public IEnumerable<KeyValuePair<string,IEnumerable<string>>> Headers { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StateChangedEventArgs"/> class.
|
||||
/// </summary>
|
||||
/// <param name="readyState">One of the <see cref="EventSource.ReadyState"/> values, which represents the state of the EventSource connection.</param>
|
||||
/// <param name="headers">Response headers when the <see cref="StateChangedEventArgs.ReadyState"/> is <see cref="ReadyState.Open"/>. Otherwise null.</param>
|
||||
public StateChangedEventArgs(ReadyState readyState, IEnumerable<KeyValuePair<string,IEnumerable<string>>> headers = null)
|
||||
{
|
||||
ReadyState = readyState;
|
||||
Headers = headers;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace LaunchDarkly.EventSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Points to a span of UTF-8-encoded text in a buffer.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is similar to the <c>Span</c> type in .NET 5. It is used internally by
|
||||
/// <c>EventSource</c> to store event data if the stream is using UTF-8 encoding.
|
||||
/// If so, reading <see cref="MessageEvent.DataUtf8Bytes"/> will return the same
|
||||
/// byte array, to avoid unnecessary copying.
|
||||
/// </remarks>
|
||||
public struct Utf8ByteSpan
|
||||
{
|
||||
/// <summary>
|
||||
/// The byte array containing the data. May be null if <see cref="Length"/> is zero.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It is the caller's responsibility not to modify the array.
|
||||
/// </remarks>
|
||||
public byte[] Data { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The offset of the first relevant byte of data within the array. This may be
|
||||
/// greater than zero if the span represents a subset of a larger buffer.
|
||||
/// </summary>
|
||||
public int Offset { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The number of bytes of relevant data within the array. This may be less than
|
||||
/// <c>Data.Length</c> if the span represents a subset of a larger buffer.
|
||||
/// </summary>
|
||||
public int Length { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructs a new instance.
|
||||
/// </summary>
|
||||
/// <param name="data">The byte array containing the data.</param>
|
||||
/// <param name="offset">The offset of the first relevant byte of data within the array.</param>
|
||||
/// <param name="length">The number of bytes of relevant data within the array.</param>
|
||||
public Utf8ByteSpan(byte[] data, int offset, int length)
|
||||
{
|
||||
Data = length == 0 ? null : data;
|
||||
Offset = offset;
|
||||
Length = length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs a new instance by copying a string.
|
||||
/// </summary>
|
||||
/// <param name="s">A string to convert to UTF-8 bytes.</param>
|
||||
public Utf8ByteSpan(string s)
|
||||
{
|
||||
Data = s.Length == 0 ? null : Encoding.UTF8.GetBytes(s);
|
||||
Offset = 0;
|
||||
Length = Data is null ? 0 : Data.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the UTF-8 byte data to a string.
|
||||
/// </summary>
|
||||
/// <returns>A new string.</returns>
|
||||
public string GetString() => Data is null ? "" : Encoding.UTF8.GetString(Data, Offset, Length);
|
||||
|
||||
/// <summary>
|
||||
/// Tests whether the bytes in this span are the same as another span.
|
||||
/// </summary>
|
||||
/// <param name="other">Another <c>Utf8ByteSpan</c>.</param>
|
||||
/// <returns>True if the two spans have the same length and the same
|
||||
/// data, starting from each one's <c>Offset</c>.</returns>
|
||||
public bool Equals(Utf8ByteSpan other)
|
||||
{
|
||||
var len = Length;
|
||||
if (len != other.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
int offset = Offset, otherOffset = other.Offset;
|
||||
byte[] data = Data, otherData = other.Data;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
if (data[i + offset] != otherData[i + otherOffset])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tests whether the bytes in this span are the same as the UTF-8 encoding
|
||||
/// of the specified string.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method is potentially inefficient and should be used only in testing.
|
||||
/// </remarks>
|
||||
/// <param name="s">A string.</param>
|
||||
/// <returns>True if the bytes are equivalent.</returns>
|
||||
public bool Equals(string s)
|
||||
{
|
||||
byte[] data = Data;
|
||||
int offset = Offset, len = Length;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
if (data[offset + i] > 127)
|
||||
{
|
||||
// There are multi-byte characters in the span, so we can't do a 1:1 comparison of bytes
|
||||
return GetString().Equals(s);
|
||||
}
|
||||
}
|
||||
// There are no multi-byte characters, so we don't need to convert to or from a UTF-16 string
|
||||
if (len != s.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
if ((char)data[offset + i] != s[i])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user