Skip to content

Commit

Permalink
Use Microsoft ILogger abstraction [breaking change]
Browse files Browse the repository at this point in the history
  • Loading branch information
Marfusios committed Sep 6, 2023
1 parent d5ffb85 commit 508e547
Show file tree
Hide file tree
Showing 11 changed files with 117 additions and 119 deletions.
7 changes: 3 additions & 4 deletions src/Websocket.Client/IWebsocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using Websocket.Client.Models;

namespace Websocket.Client
{
Expand Down Expand Up @@ -56,7 +55,7 @@ public interface IWebsocketClient : IDisposable
/// Get or set the name of the current websocket client instance.
/// For logging purpose (in case you use more parallel websocket clients and want to distinguish between them)
/// </summary>
string Name { get; set; }
string? Name { get; set; }

/// <summary>
/// Returns true if Start() method was called at least once. False if not started or disposed
Expand All @@ -83,13 +82,13 @@ public interface IWebsocketClient : IDisposable
/// Returns currently used native websocket client.
/// Use with caution, on every reconnection there will be a new instance.
/// </summary>
ClientWebSocket NativeClient { get; }
ClientWebSocket? NativeClient { get; }

/// <summary>
/// Sets used encoding for sending and receiving text messages.
/// Default: UTF8
/// </summary>
Encoding MessageEncoding { get; set; }
Encoding? MessageEncoding { get; set; }

/// <summary>
/// Start listening to the websocket stream on the background thread.
Expand Down
10 changes: 5 additions & 5 deletions src/Websocket.Client/Models/DisconnectionInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class DisconnectionInfo
/// Info about happened disconnection
/// </summary>
public DisconnectionInfo(DisconnectionType type, WebSocketCloseStatus? closeStatus,
string closeStatusDescription, string subProtocol, Exception exception)
string? closeStatusDescription, string? subProtocol, Exception? exception)
{
Type = type;
CloseStatus = closeStatus;
Expand All @@ -35,17 +35,17 @@ public DisconnectionInfo(DisconnectionType type, WebSocketCloseStatus? closeStat
/// <summary>
/// Allows the remote endpoint to describe the reason why the connection was closed
/// </summary>
public string CloseStatusDescription { get; }
public string? CloseStatusDescription { get; }

/// <summary>
/// The subprotocol that was negotiated during the opening handshake
/// </summary>
public string SubProtocol { get; }
public string? SubProtocol { get; }

/// <summary>
/// Exception that cause disconnection, can be null
/// </summary>
public Exception Exception { get; }
public Exception? Exception { get; }


/// <summary>
Expand All @@ -62,7 +62,7 @@ public DisconnectionInfo(DisconnectionType type, WebSocketCloseStatus? closeStat
/// <summary>
/// Simple factory method
/// </summary>
public static DisconnectionInfo Create(DisconnectionType type, WebSocket client, Exception exception)
public static DisconnectionInfo Create(DisconnectionType type, WebSocket? client, Exception? exception)
{
return new DisconnectionInfo(type, client?.CloseStatus, client?.CloseStatusDescription,
client?.SubProtocol, exception);
Expand Down
2 changes: 1 addition & 1 deletion src/Websocket.Client/Models/DisconnectionType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public enum DisconnectionType
/// <summary>
/// Type used when connection to websocket was lost by not receiving any message in given time-range
/// </summary>
NoMessageReceived = 2,
NoMessageReceived = 2,

/// <summary>
/// Type used when connection or reconnection returned error
Expand Down
6 changes: 2 additions & 4 deletions src/Websocket.Client/Models/ReconnectionInfo.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using System;

// ReSharper disable once CheckNamespace
namespace Websocket.Client.Models
// ReSharper disable once CheckNamespace
namespace Websocket.Client
{
/// <summary>
/// Info about happened reconnection
Expand Down
12 changes: 6 additions & 6 deletions src/Websocket.Client/ResponseMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace Websocket.Client
/// </summary>
public class ResponseMessage
{
private ResponseMessage(byte[] binary, string text, WebSocketMessageType messageType)
private ResponseMessage(byte[]? binary, string? text, WebSocketMessageType messageType)
{
Binary = binary;
Text = text;
Expand All @@ -17,12 +17,12 @@ private ResponseMessage(byte[] binary, string text, WebSocketMessageType message
/// <summary>
/// Received text message (only if type = WebSocketMessageType.Text)
/// </summary>
public string Text { get; }
public string? Text { get; }

/// <summary>
/// Received text message (only if type = WebSocketMessageType.Binary)
/// </summary>
public byte[] Binary { get; }
public byte[]? Binary { get; }

/// <summary>
/// Current message type (Text or Binary)
Expand All @@ -36,7 +36,7 @@ public override string ToString()
{
if (MessageType == WebSocketMessageType.Text)
{
return Text;
return Text ?? string.Empty;
}

return $"Type binary, length: {Binary?.Length}";
Expand All @@ -45,15 +45,15 @@ public override string ToString()
/// <summary>
/// Create text response message
/// </summary>
public static ResponseMessage TextMessage(string data)
public static ResponseMessage TextMessage(string? data)
{
return new ResponseMessage(null, data, WebSocketMessageType.Text);
}

/// <summary>
/// Create binary response message
/// </summary>
public static ResponseMessage BinaryMessage(byte[] data)
public static ResponseMessage BinaryMessage(byte[]? data)
{
return new ResponseMessage(data, null, WebSocketMessageType.Binary);
}
Expand Down
8 changes: 3 additions & 5 deletions src/Websocket.Client/Websocket.Client.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netstandard2.0;netstandard2.1;net6;net7</TargetFrameworks>
<TargetFrameworks>netstandard2.1;net6;net7</TargetFrameworks>
<PackageId>Websocket.Client</PackageId>
<Authors>Mariusz Kotas</Authors>
<Description>Client for websocket API with built-in reconnection and error handling</Description>
Expand All @@ -24,13 +24,11 @@

<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="LibLog" Version="5.0.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageReference Include="System.Reactive" Version="6.0.0" />
<PackageReference Include="System.Threading.Channels" Version="7.0.0" />
</ItemGroup>
Expand Down
20 changes: 10 additions & 10 deletions src/Websocket.Client/WebsocketClient.Reconnecting.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Websocket.Client.Logging;
using Microsoft.Extensions.Logging;

namespace Websocket.Client
{
Expand Down Expand Up @@ -32,7 +32,7 @@ private async Task ReconnectInternal(bool failFast)
{
if (!IsStarted)
{
Logger.Debug(L("Client not started, ignoring reconnection.."));
_logger.LogDebug(L("Client not started, ignoring reconnection.."), Name);
return;
}

Expand All @@ -46,15 +46,15 @@ private async Task ReconnectInternal(bool failFast)
}
}

private async Task ReconnectSynchronized(ReconnectionType type, bool failFast, Exception causedException)
private async Task ReconnectSynchronized(ReconnectionType type, bool failFast, Exception? causedException)
{
using (await _locker.LockAsync())
{
await Reconnect(type, failFast, causedException);
}
}

private async Task Reconnect(ReconnectionType type, bool failFast, Exception causedException)
private async Task Reconnect(ReconnectionType type, bool failFast, Exception? causedException)
{
IsRunning = false;
if (_disposing || !IsStarted)
Expand All @@ -73,18 +73,18 @@ private async Task Reconnect(ReconnectionType type, bool failFast, Exception cau
if (disInfo.CancelReconnection)
{
// reconnection canceled by user, do nothing
Logger.Info(L($"Reconnecting canceled by user, exiting."));
_logger.LogInformation(L("Reconnecting canceled by user, exiting."), Name);
}
}

_cancellation.Cancel();
_cancellation?.Cancel();
try
{
_client?.Abort();
}
catch (Exception e)
{
Logger.Error(e, L($"Exception while aborting client. " + $"Error: '{e.Message}'"));
_logger.LogError(e, L("Exception while aborting client. Error: '{error}'"), Name, e.Message);
}
_client?.Dispose();

Expand All @@ -96,7 +96,7 @@ private async Task Reconnect(ReconnectionType type, bool failFast, Exception cau
return;
}

Logger.Debug(L("Reconnecting..."));
_logger.LogDebug(L("Reconnecting..."), Name);
_cancellation = new CancellationTokenSource();
await StartClient(_url, _cancellation.Token, type, failFast).ConfigureAwait(false);
_reconnecting = false;
Expand All @@ -114,7 +114,7 @@ private void DeactivateLastChance()
_lastChanceTimer = null;
}

private void LastChance(object state)
private void LastChance(object? state)
{
if (!IsReconnectionEnabled || ReconnectTimeout == null)
{
Expand All @@ -127,7 +127,7 @@ private void LastChance(object state)
var diffMs = Math.Abs(DateTime.UtcNow.Subtract(_lastReceivedMsg).TotalMilliseconds);
if (diffMs > timeoutMs)
{
Logger.Debug(L($"Last message received more than {timeoutMs:F} ms ago. Hard restart.."));
_logger.LogDebug(L("Last message received more than {timeoutMs} ms ago. Hard restart.."), Name, timeoutMs.ToString("F"));

DeactivateLastChance();
_ = ReconnectSynchronized(ReconnectionType.NoMessageReceived, false, null);
Expand Down
35 changes: 18 additions & 17 deletions src/Websocket.Client/WebsocketClient.Sending.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Websocket.Client.Logging;
using Microsoft.Extensions.Logging;

namespace Websocket.Client
{
Expand Down Expand Up @@ -109,7 +110,7 @@ private async Task SendTextFromQueue()
}
catch (Exception e)
{
Logger.Error(e, L($"Failed to send text message: '{message}'. Error: {e.Message}"));
_logger.LogError(e, L("Failed to send text message: '{message}'. Error: {error}"), Name, message, e.Message);
}
}
}
Expand All @@ -124,13 +125,13 @@ private async Task SendTextFromQueue()
}
catch (Exception e)
{
if (_cancellationTotal.IsCancellationRequested || _disposing)
if (_cancellationTotal?.IsCancellationRequested == true || _disposing)
{
// disposing/canceling, do nothing and exit
return;
}

Logger.Trace(L($"Sending text thread failed, error: {e.Message}. Creating a new sending thread."));
_logger.LogTrace(L("Sending text thread failed, error: {error}. Creating a new sending thread."), Name, e.Message);
StartBackgroundThreadForSendingText();
}

Expand All @@ -150,7 +151,7 @@ private async Task SendBinaryFromQueue()
}
catch (Exception e)
{
Logger.Error(e, L($"Failed to send binary message: '{message}'. Error: {e.Message}"));
_logger.LogError(e, L("Failed to send binary message: '{message}'. Error: {error}"), Name, message, e.Message);
}
}
}
Expand All @@ -165,26 +166,26 @@ private async Task SendBinaryFromQueue()
}
catch (Exception e)
{
if (_cancellationTotal.IsCancellationRequested || _disposing)
if (_cancellationTotal?.IsCancellationRequested == true || _disposing)
{
// disposing/canceling, do nothing and exit
return;
}

Logger.Trace(L($"Sending binary thread failed, error: {e.Message}. Creating a new sending thread."));
_logger.LogTrace(L("Sending binary thread failed, error: {error}. Creating a new sending thread."), Name, e.Message);
StartBackgroundThreadForSendingBinary();
}

}

private void StartBackgroundThreadForSendingText()
{
_ = Task.Factory.StartNew(_ => SendTextFromQueue(), TaskCreationOptions.LongRunning, _cancellationTotal.Token);
_ = Task.Factory.StartNew(_ => SendTextFromQueue(), TaskCreationOptions.LongRunning, _cancellationTotal?.Token ?? CancellationToken.None);
}

private void StartBackgroundThreadForSendingBinary()
{
_ = Task.Factory.StartNew(_ => SendBinaryFromQueue(), TaskCreationOptions.LongRunning, _cancellationTotal.Token);
_ = Task.Factory.StartNew(_ => SendBinaryFromQueue(), TaskCreationOptions.LongRunning, _cancellationTotal?.Token ?? CancellationToken.None);
}

private async Task SendInternalSynchronized(string message)
Expand All @@ -199,15 +200,15 @@ private async Task SendInternal(string message)
{
if (!IsClientConnected())
{
Logger.Debug(L($"Client is not connected to server, cannot send: {message}"));
_logger.LogDebug(L("Client is not connected to server, cannot send: {message}"), Name, message);
return;
}

Logger.Trace(L($"Sending: {message}"));
_logger.LogTrace(L("Sending: {message}"), Name, message);
var buffer = GetEncoding().GetBytes(message);
var messageSegment = new ArraySegment<byte>(buffer);
await _client
.SendAsync(messageSegment, WebSocketMessageType.Text, true, _cancellation.Token)
await _client!
.SendAsync(messageSegment, WebSocketMessageType.Text, true, _cancellation?.Token ?? CancellationToken.None)
.ConfigureAwait(false);
}

Expand All @@ -223,14 +224,14 @@ private async Task SendInternal(ArraySegment<byte> message)
{
if (!IsClientConnected())
{
Logger.Debug(L($"Client is not connected to server, cannot send binary, length: {message.Count}"));
_logger.LogDebug(L("Client is not connected to server, cannot send binary, length: {length}"), Name, message.Count);
return;
}

Logger.Trace(L($"Sending binary, length: {message.Count}"));
_logger.LogTrace(L("Sending binary, length: {length}"), Name, message.Count);

await _client
.SendAsync(message, WebSocketMessageType.Binary, true, _cancellation.Token)
await _client!
.SendAsync(message, WebSocketMessageType.Binary, true, _cancellation?.Token ?? CancellationToken.None)
.ConfigureAwait(false);
}
}
Expand Down
Loading

0 comments on commit 508e547

Please sign in to comment.