refactor: Add handy WebsocketExtensions

* IsSocketStateOpen
* IsClosedProperly
This commit is contained in:
John Colvin committed 2024-02-09 23:05:37 -06:00
1 parent ca028c58ed
commit e4d20be735
3 files changed
+493 -469

No files matched your search

@@ -1,469 +1,478 @@
using Bts.Websocket;
using System.Net.WebSockets;
using System.Text;
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace bts.websocket_core {
public enum MessageType {
Message,
Close
}
/// <summary>
/// gateway between sync and socket logic
/// 1. keeps all active clients in the store(updates store if sync or handler informs)
/// 2. listens for connections (upon connection passes to handler)
/// 3. gets messages from sync forwards to handler
/// 4. updates store and sync about any changes in connections (when told by handler)
/// </summary>
public class WebsocketConnectionGateway : IWebsocketConnectionGateway {
/// <summary>
/// Represents a connection to a client through a WebSocket.
/// </summary>
public class Connection {
/// <summary>
/// The WebSocket instance associated with this connection.
/// </summary>
public WebSocket Ws { get; }
/// <summary>
/// A queue that holds outgoing messages to be sent to the client.
/// </summary>
public ConcurrentQueue<Tuple<MessageType, string>> OutgoingQueue { get; } = new();
/// <summary>
/// Initializes a new instance of the <see cref="Connection"/> class.
/// </summary>
/// <param name="websocket">The WebSocket associated with this connection.</param>
public Connection(WebSocket websocket) {
Ws = websocket;
}
}
/// <summary>
/// wrapper for concurrent Dictionary
/// Stores all the alive connection
/// Additions and removals done by gateway
/// websockethandler can access but not change anything
/// </summary>
class WebSocketConnectionStore {
private ConcurrentDictionary<WebsocketClientID, Connection> Connections { get; } = new();
/// <summary>
/// Adds a new connection to the connections dictionary using the given id and connection object
/// </summary>
/// <param name="id">The id to use as the key for the new connection</param>
/// <param name="conn">The connection object to add to the dictionary</param>
public void AddConnection(WebsocketClientID id, Connection conn) {
if (!Connections.TryAdd(id, conn)) {
var log_txt = $"WebsocketDataSync.createID client_id: {id.ToString()} Already exits";
bts.Log.Gen.warn(log_txt);
Connections[id] = conn;
}
}
/// <summary>
/// Removes a connection from the connections dictionary using the given id
/// </summary>
/// <param name="id">The id of the connection to remove</param>
public void RemoveConnection(WebsocketClientID id) {
if (Connections.TryRemove(id, out Connection? conn)) {
conn.Ws.Dispose();
}
}
/// <summary>
/// Retrieves the Connection object associated with the given id
/// </summary>
/// <param name="id">The id of the connection to retrieve</param>
/// <returns>The Connection object associated with the given id, or null if the id is not found</returns>
public Connection? GetConnection(WebsocketClientID id) => Connections.GetValueOrDefault(id);
/// <summary>
/// Retrieves the Connection object associated with the given id
/// </summary>
/// <param name="id">The id of the connection to retrieve</param>
/// <returns>The Connection object associated with the given id, or null if the id is not found</returns>
public WebSocket? GetSocket(WebsocketClientID id) => Connections.GetValueOrDefault(id)?.Ws;
/// <summary>
/// Get the outgoing message queue for a specific client connection identified by the given id.
/// </summary>
/// <param name="id">The unique identifier for the client connection.</param>
/// <returns>A concurrent queue of message tuples if the connection is found, null otherwise.</returns>
public ConcurrentQueue<Tuple<MessageType, string>>? GetSocketQueue(WebsocketClientID id) =>
Connections.GetValueOrDefault(id)?.OutgoingQueue;
/// <summary>
/// Check if the store contains a connection with the specified id.
/// </summary>
/// <param name="id">The unique identifier for the client connection.</param>
/// <returns>True if the connection is found, false otherwise.</returns>
public bool ContainsKey(WebsocketClientID id) => Connections.ContainsKey(id);
}
/// <summary>
/// is controlled by gateway:
/// once a new connection is made the gateway passes the socket to this and this
/// handles everything:
/// 1. keeps a queue of messages to send for each client (gateway can add to the queue),
/// 2. keeps listening for messages from clients (sends the gateway the messages),
/// 3. handles if client drop/wants to disconnect (informs gateway in either case),
/// 4. handles sending disconnect messages to client (gateway can add disconnect message to que)
/// can access the store but not change anything in it,
/// </summary>
class WebSocketHandler {
private static bool IsSocketStateOpen(WebSocket? ws) => ws != null && ws.State != WebSocketState.Closed && ws.State != WebSocketState.Aborted && ws.State != WebSocketState.None;
private static bool IsClosedProperly(WebSocket ws) => ws.CloseStatus == WebSocketCloseStatus.NormalClosure;
/// <summary>
/// GetConnectedWebSocket attempts to retrieve a connected WebSocket from the WebSocketConnectionStore using the provided client ID.
/// If the socket is not found or is not in an open state, it logs an error message and calls the HandleDisconnection method on the
/// WebsocketConnectionGateway.
/// </summary>
/// <param name="id">The client ID to use to retrieve the WebSocket from the WebSocketConnectionStore.</param>
/// <param name="error_message">The error message to log if the WebSocket is not found or not open.</param>
/// <returns>The connected WebSocket or null if it was not found or not open.</returns>
private WebSocket? GetConnectedWebSocket(WebsocketClientID id, string error_message) {
LoggerContext logger = new(Log.Gen, error_message, "");
var socket = Connections.GetSocket(id);
if (IsSocketStateOpen(socket)) {
return socket;
}
if (socket != null) {
logger.warn(" failed as Socket closed");
} else {
logger.warn(" failed as could not find socket in dictionary");
}
gtwy.HandleDisconnection(id, error_message);
return null;
}
/// <summary>
/// Determines if a WebSocket connection needs to be disconnected
/// </summary>
/// <param name="id">The unique identifier of the WebSocket client</param>
/// <param name="conn">The Connection object of the WebSocket client</param>
/// <param name="error_message">The error message to be logged in case of improper connection closure</param>
/// <returns>True if the connection needs to be disconnected, False otherwise</returns>
public bool ShouldDisconnect(WebsocketClientID id, Connection conn, string error_message) {
LoggerContext logger = new(Log.Gen, error_message, "");
var socket = conn.Ws;
if (IsSocketStateOpen(socket)) {
return true;
}
if (!IsClosedProperly(socket)) {
logger.info(" closed improperly by other thread");
gtwy.NotifyDisconnection(id);
}
return false;
}
private WebsocketConnectionGateway gtwy;
private WebSocketConnectionStore? connections = null;
private WebSocketConnectionStore Connections {
get => Log.notnull<WebSocketConnectionStore>(connections);
set {
bts.Log.isnull(connections);
connections = value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketHandler"/> class
/// </summary>
/// <param name="gateway">Websocket connection gateway</param>
/// <param name="conns">Connections dictionary</param>
public WebSocketHandler(WebsocketConnectionGateway gateway, WebSocketConnectionStore conns) {
gtwy = gateway;
Connections = conns;
}
/// <summary>
/// Processes a new WebSocket connection asynchronously by first handling the connection with the gateway,
/// then running two tasks concurrently: one for processing incoming requests and one for processing messages in the queue.
/// </summary>
/// <param name="ws">The WebSocket connection to be processed</param>
/// <returns>A task that represents the asynchronous operation</returns>
public async Task ProcessWebSocketConnectionAsync(WebSocket ws) {
var id = await gtwy.HandleConnection(new Connection(ws), null);
var pushTask = Task.Run(() => ProcessWebSocketQueueAsync(id));
await ProcessWebSocketRequestAsync(id);
await pushTask;
// await Task.WhenAll(ProcessWebSocketQueueAsync(id), ProcessWebSocketRequestAsync(id));
}
/// <summary>
/// Adds a message to the queue of a specific websocket client.
/// </summary>
/// <param name="id">The unique identifier of the client</param>
/// <param name="mes">The message to be added to the queue</param>
/// <returns> True if succesfull otherwise fasle </returns>
public bool AddToQueue(WebsocketClientID id, Tuple<MessageType, string> mes) {
var que = Connections.GetSocketQueue(id);
if (que == null) {
return false;
}
que.Enqueue(mes);
return true;
}
/// <summary>
/// Processes the messages in the WebSocket queue for a specific client.
/// will keep running until socket is open
/// </summary>
/// <param name="id">The unique identifier of the client</param>
private async Task ProcessWebSocketQueueAsync(WebsocketClientID id) {
// Get the socket for the client
var socket = GetConnectedWebSocket(id, "WebSocketHandler.ProcessWebSocketQueueAsync could not process");
// Get the queue for the client
var que = Connections.GetSocketQueue(id);
// If either the socket or the queue is null, return
if (socket == null || que == null) {
return;
}
while (IsSocketStateOpen(socket)) {
// Try to dequeue a message from the queue
if (!que.TryDequeue(out var message)) {
// If the queue is empty, wait for 100 milliseconds before trying again
await Task.Delay(TimeSpan.FromMilliseconds(100));
continue;
}
// If the message is a close request
if (message.Item1 == MessageType.Close) {
// Send a disconnect request to the client
await SendDisconnectRequestAsync(id, message.Item2);
// Notify the gateway of the client's disconnection
gtwy.NotifyDisconnection(id);
break;
}
// If the message is a regular message
else if (message.Item1 == MessageType.Message) {
// Send the message to the client
await SendWebSocketRequestAsync(id, message.Item2);
}
}
}
/// <summary>
/// Sends a disconnect request to a websocket client, with an optional message.
/// </summary>
/// <param name="id">The unique identifier of the client to send the request to</param>
/// <param name="message">An optional message for the logger</param>
private async Task SendDisconnectRequestAsync(WebsocketClientID id, string message) {
LoggerContext logger = new(Log.Gen, $"WebSocketHandler.SendDisconnectRequestAsync tried closing client_id: {id} with message: {message}", "");
// Get the socket of the client
var sckt = Connections.GetSocket(id);
if (sckt == null) {
logger.info(" failed as could not find socket in dictionary");
return;
}
try {
// send a close message to the socket, using the close status 1000, which is a normal closure status
await sckt.CloseAsync((WebSocketCloseStatus)1000, "", CancellationToken.None);
logger.info(" done succesfully");
} catch (WebSocketException ex) {
logger.info($" failed as client didnt respond, Exception: {ex.Message}");
}
}
/// <summary>
/// recieves messages from a specific websocket client identified by its id. keeps running until socket remains open
/// </summary>
/// <param name="id">The unique identifier of the client</param>
private async Task ProcessWebSocketRequestAsync(WebsocketClientID id) {
// Get the socket for the given client ID
var socket = GetConnectedWebSocket(id, "WebSocketHandler.ProcessWebSocketRequestAsync could not process");
// If the socket is null, return
if (socket == null) {
return;
}
try {
// Create a buffer to receive the incoming message
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[256]);
WebSocketReceiveResult result;
string request = "";
while (IsSocketStateOpen(socket)) {
// Receive the message
result = await socket.ReceiveAsync(buffer, CancellationToken.None);
// If the message is a close request, handle the disconnection and return
if (result.MessageType == WebSocketMessageType.Close) {
var log_txt = $"WebSocketHandler.ProcessWebSocketRequestAsync close request";
gtwy.HandleDisconnection(id, log_txt);
return;
}
if (buffer.Array != null)// added because of warning
{
// Append the received message to the request string
request += Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
} else {
bts.Log.assert(false);//this should never happen
}
// If the message is the end of the message, handle the message and reset the request string
if (result.EndOfMessage) {
gtwy.HandleMessage(new WebsocketIncomingMessage(id, request));
request = "";
}
}
} catch (WebSocketException ex) {
var ex_str = ex.ToString();
var log_txt = $"WebsocketGateway.ProcessWebSocketRequestAsync connection closed Error: {ex_str}";
gtwy.HandleDisconnection(id, log_txt);
} catch (OperationCanceledException) {//not sure about this, read that this should just be ignored
}
}
/// <summary>
/// Sends a message to a specific websocket client identified by its id.
/// </summary>
/// <param name="id">The unique identifier of the client to receive the message</param>
/// <param name="message">The message to be sent</param>
public async Task SendWebSocketRequestAsync(WebsocketClientID id, string message) {
// Get the socket of the client
var socket = GetConnectedWebSocket(id, "WebSocketHandler.SendWebSocketRequestAsync could not send Request");
if (socket == null) {
return;
}
try {
// Send the message
await socket.SendAsync(Encoding.ASCII.GetBytes(message), WebSocketMessageType.Text, true, CancellationToken.None);
} catch (WebSocketException ex) {
// Handle the exception and disconnect the client
var ex_str = ex.ToString();
var log_txt = $"WebSocketHandler.SendWebSocketRequestAsync connection closed client_id: {id} Error: {ex_str}";
gtwy.HandleDisconnection(id, log_txt);
}
}
}
public event Action<WebsocketClientID>? Disconnected;
public event Action<WebsocketClientID, WebsocketIncomingMessage?>? Connected;
public event Action<WebsocketIncomingMessage>? MessageReceived;
private WebApplication? app = null;
private WebsocketServerConfig? _server_params = null;
private WebSocketConnectionStore Connections { get; } = new();
/// <summary>
/// creates a new connections dictionary and a new WebSocketHandler.
/// </summary>
private WebSocketHandler _WebSocketHandler { get; }
public WebsocketConnectionGateway() {
_WebSocketHandler = new WebSocketHandler(this, Connections);
}
/// <summary>
/// Creates a unique identifier for a websocket client and adds the client's connection to the list of active connections.
/// </summary>
/// <param name="conn">The connection of the client</param>
/// <returns>A unique identifier for the client</returns>
private WebsocketClientID createID(Connection conn) {
var id = new WebsocketClientID();
Connections.AddConnection(id, conn);
return id;
}
/// <summary>
/// forwards an incoming message from a websocket client to sync.
/// </summary>
/// <param name="message">The incoming message to be handled</param>
public void HandleMessage(WebsocketIncomingMessage message) =>
MessageReceived?.Invoke(message);
/// <summary>
/// Notifies of a client disconnection and removes the client's connection from the list of active connections.
/// </summary>
/// <param name="id">The unique identifier of the disconnected client</param>
public void NotifyDisconnection(WebsocketClientID id) {
Disconnected?.Invoke(id);
Connections.RemoveConnection(id);
}
/// <summary>
/// Handles a new websocket connection and returns a unique identifier for the client.
/// </summary>
/// <param name="conn">The new connection to be handled</param>
/// <param name="optional_message">An optional message associated with the connection</param>
/// <returns>A unique identifier for the client</returns>
public async Task<WebsocketClientID> HandleConnection(Connection conn, WebsocketIncomingMessage? optional_message) {
var id = createID(conn);
await Task.Run(() => Connected?.Invoke(id, optional_message));
return id;
}
/// <summary>
/// Handles disconnection of a websocket client.
/// </summary>
/// <param name="id">The unique identifier of the client to be disconnected</param>
/// <param name="optional_message">An optional message to add to the logger</param>
public void HandleDisconnection(WebsocketClientID id, string optional_message = "") {
LoggerContext logger = new(Log.Gen, $"WebsocketGateway.HandleDisconnection tried closing client_id: {id} with message: {optional_message}", "");
// Get the connection of the client
var conn = Connections.GetConnection(id);
if (conn == null) {
// If the client connection is not found, log the error and notify sync about the disconnection through the Sync object
logger.warn(" could not find socket in dictionary");
Disconnected?.Invoke(id);
return;
}
// Check if the connection needs to be disconnected
if (!_WebSocketHandler.ShouldDisconnect(id, conn, $"WebsocketGateway.HandleDisconnection tried closing client_id: {id}")) {
// If the connection does not need to be disconnected, remove it from the Connections dictionary
Connections.RemoveConnection(id);
return;
}
// Add the disconnection message to the WebSocketHandler's message queue
if (_WebSocketHandler.AddToQueue(id, Tuple.Create(MessageType.Close, "")))
logger.info(" added to que");
}
/// <summary>
/// Starts listening for incoming websocket connections. need to call init before this
/// </summary>
/// <param name="server_params">The parameters for the websocket server includind the URL and endpoint,</param>
public Task start_listening(WebsocketServerConfig server_params) {
// start listening, assert that init has been called already
bts.Log.isnull(_server_params);
bts.Log.isnull(app);
_server_params = server_params;
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls(_server_params.Uri());
// var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddLogging(builder => {
builder.AddFilter("Microsoft", Microsoft.Extensions.Logging.LogLevel.Warning)
.AddFilter("System", Microsoft.Extensions.Logging.LogLevel.Warning)
.AddFilter("NToastNotify", Microsoft.Extensions.Logging.LogLevel.Warning)
.AddConsole();
});
// builder.Services.AddCors(options => {
// options.AddPolicy(MyAllowSpecificOrigins,
// policy => policy
// .WithOrigins("http://localhost:3000")
// .AllowAnyHeader()
// .AllowAnyMethod());
// });
app = builder.Build();
app.UseWebSockets(_server_params.get_ws_options());
// app.Use(async (context, next) => {
// context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
// context.Response.Headers.Add("Access-Control-Allow-Headers", "*");
// await next();
// });
app.Map(_server_params.DefaultEndPoint, async context => {
if (context.WebSockets.IsWebSocketRequest) {
using (var ws = await context.WebSockets.AcceptWebSocketAsync()) {
await _WebSocketHandler.ProcessWebSocketConnectionAsync(ws);
}
} else {
context.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
}
});
return app.RunAsync();
}
/// <summary>
/// Sends a message to a list of websocket clients.
/// </summary>
/// <param name="messages">A collection of websocket messages to be sent to the clients</param>
public void send_to_clients(
IEnumerable<WebsocketOutgoingMessage> messages) {
foreach (var om in messages) {
// Add the message to the WebSocketHandler's message queue
if (!_WebSocketHandler.AddToQueue(om.receiver_client_id, Tuple.Create(MessageType.Message, om.message_body)))
break;
}
}
}
}
using Bts.Websocket;
using System.Net.WebSockets;
using System.Text;
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace bts.websocket_core {
public enum MessageType {
Message,
Close
}
/// <summary>
/// gateway between sync and socket logic
/// 1. keeps all active clients in the store(updates store if sync or handler informs)
/// 2. listens for connections (upon connection passes to handler)
/// 3. gets messages from sync forwards to handler
/// 4. updates store and sync about any changes in connections (when told by handler)
/// </summary>
public class WebsocketConnectionGateway : IWebsocketConnectionGateway {
/// <summary>
/// Represents a connection to a client through a WebSocket.
/// </summary>
public class Connection {
/// <summary>
/// The WebSocket instance associated with this connection.
/// </summary>
public WebSocket Ws { get; }
/// <summary>
/// A queue that holds outgoing messages to be sent to the client.
/// </summary>
public ConcurrentQueue<Tuple<MessageType, string>> OutgoingQueue { get; } = new();
/// <summary>
/// Initializes a new instance of the <see cref="Connection"/> class.
/// </summary>
/// <param name="websocket">The WebSocket associated with this connection.</param>
public Connection(WebSocket websocket) {
Ws = websocket;
}
}
/// <summary>
/// wrapper for concurrent Dictionary
/// Stores all the alive connection
/// Additions and removals done by gateway
/// websockethandler can access but not change anything
/// </summary>
class WebSocketConnectionStore {
private ConcurrentDictionary<WebsocketClientID, Connection> Connections { get; } = new();
/// <summary>
/// Adds a new connection to the connections dictionary using the given id and connection object
/// </summary>
/// <param name="id">The id to use as the key for the new connection</param>
/// <param name="conn">The connection object to add to the dictionary</param>
public void AddConnection(WebsocketClientID id, Connection conn) {
if (!Connections.TryAdd(id, conn)) {
var log_txt = $"WebsocketDataSync.createID client_id: {id.ToString()} Already exits";
bts.Log.Gen.warn(log_txt);
Connections[id] = conn;
}
}
/// <summary>
/// Removes a connection from the connections dictionary using the given id
/// </summary>
/// <param name="id">The id of the connection to remove</param>
public void RemoveConnection(WebsocketClientID id) {
if (Connections.TryRemove(id, out Connection? conn)) {
conn.Ws.Dispose();
}
}
/// <summary>
/// Retrieves the Connection object associated with the given id
/// </summary>
/// <param name="id">The id of the connection to retrieve</param>
/// <returns>The Connection object associated with the given id, or null if the id is not found</returns>
public Connection? GetConnection(WebsocketClientID id) => Connections.GetValueOrDefault(id);
/// <summary>
/// Retrieves the Connection object associated with the given id
/// </summary>
/// <param name="id">The id of the connection to retrieve</param>
/// <returns>The Connection object associated with the given id, or null if the id is not found</returns>
public WebSocket? GetSocket(WebsocketClientID id) => Connections.GetValueOrDefault(id)?.Ws;
/// <summary>
/// Get the outgoing message queue for a specific client connection identified by the given id.
/// </summary>
/// <param name="id">The unique identifier for the client connection.</param>
/// <returns>A concurrent queue of message tuples if the connection is found, null otherwise.</returns>
public ConcurrentQueue<Tuple<MessageType, string>>? GetSocketQueue(WebsocketClientID id) =>
Connections.GetValueOrDefault(id)?.OutgoingQueue;
/// <summary>
/// Check if the store contains a connection with the specified id.
/// </summary>
/// <param name="id">The unique identifier for the client connection.</param>
/// <returns>True if the connection is found, false otherwise.</returns>
public bool ContainsKey(WebsocketClientID id) => Connections.ContainsKey(id);
}
/// <summary>
/// is controlled by gateway:
/// once a new connection is made the gateway passes the socket to this and this
/// handles everything:
/// 1. keeps a queue of messages to send for each client (gateway can add to the queue),
/// 2. keeps listening for messages from clients (sends the gateway the messages),
/// 3. handles if client drop/wants to disconnect (informs gateway in either case),
/// 4. handles sending disconnect messages to client (gateway can add disconnect message to que)
/// can access the store but not change anything in it,
/// </summary>
class WebSocketHandler {
/// <summary>
/// GetConnectedWebSocket attempts to retrieve a connected WebSocket from the WebSocketConnectionStore using the provided client ID.
/// If the socket is not found or is not in an open state, it logs an error message and calls the HandleDisconnection method on the
/// WebsocketConnectionGateway.
/// </summary>
/// <param name="id">The client ID to use to retrieve the WebSocket from the WebSocketConnectionStore.</param>
/// <param name="error_message">The error message to log if the WebSocket is not found or not open.</param>
/// <returns>The connected WebSocket or null if it was not found or not open.</returns>
private WebSocket? GetConnectedWebSocket(WebsocketClientID id, string error_message) {
var socket = Connections.GetSocket(id);
if (socket?.IsOpen() ?? false) {
return socket;
}
Log.Gen.warn(
$"GetConnectedWebsocket failed: {(socket is null ?
"could not find socket in dictionary" :
"socket is closed")}");
gtwy.HandleDisconnection(id, error_message);
return null;
}
/// <summary>
/// Determines if a WebSocket connection needs to be disconnected
/// </summary>
/// <param name="id">The unique identifier of the WebSocket client</param>
/// <param name="conn">The Connection object of the WebSocket client</param>
/// <param name="error_message">The error message to be logged in case of improper connection closure</param>
/// <returns>True if the connection needs to be disconnected, False otherwise</returns>
public bool ShouldDisconnect(WebsocketClientID id, Connection conn, string error_message) {
LoggerContext logger = new(Log.Gen, error_message, "");
var socket = conn.Ws;
if (socket is null) {
return false;
}
if (socket.IsOpen()) {
return true;
}
if (!socket.IsClosedProperly()) {
logger.info(" closed improperly by other thread");
gtwy.NotifyDisconnection(id);
}
return false;
}
private WebsocketConnectionGateway gtwy;
private WebSocketConnectionStore? connections = null;
private WebSocketConnectionStore Connections {
get => Log.notnull<WebSocketConnectionStore>(connections);
set {
bts.Log.isnull(connections);
connections = value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketHandler"/> class
/// </summary>
/// <param name="gateway">Websocket connection gateway</param>
/// <param name="conns">Connections dictionary</param>
public WebSocketHandler(WebsocketConnectionGateway gateway, WebSocketConnectionStore conns) {
gtwy = gateway;
Connections = conns;
}
/// <summary>
/// Processes a new WebSocket connection asynchronously by first handling the connection with the gateway,
/// then running two tasks concurrently: one for processing incoming requests and one for processing messages in the queue.
/// </summary>
/// <param name="ws">The WebSocket connection to be processed</param>
/// <returns>A task that represents the asynchronous operation</returns>
public async Task ProcessWebSocketConnectionAsync(WebSocket ws) {
var id = await gtwy.HandleConnection(new Connection(ws), null);
var pushTask = Task.Run(() => ProcessWebSocketQueueAsync(id));
await ProcessWebSocketRequestAsync(id);
await pushTask;
// await Task.WhenAll(ProcessWebSocketQueueAsync(id), ProcessWebSocketRequestAsync(id));
}
/// <summary>
/// Adds a message to the queue of a specific websocket client.
/// </summary>
/// <param name="id">The unique identifier of the client</param>
/// <param name="mes">The message to be added to the queue</param>
/// <returns> True if succesfull otherwise fasle </returns>
public bool AddToQueue(WebsocketClientID id, Tuple<MessageType, string> mes) {
var que = Connections.GetSocketQueue(id);
if (que == null) {
return false;
}
que.Enqueue(mes);
return true;
}
/// <summary>
/// Processes the messages in the WebSocket queue for a specific client.
/// will keep running until socket is open
/// </summary>
/// <param name="id">The unique identifier of the client</param>
private async Task ProcessWebSocketQueueAsync(WebsocketClientID id) {
// Get the socket for the client
var socket = GetConnectedWebSocket(id, "WebSocketHandler.ProcessWebSocketQueueAsync could not process");
// Get the queue for the client
var que = Connections.GetSocketQueue(id);
// If either the socket or the queue is null, return
if (socket == null || que == null) {
return;
}
while (socket.IsOpen()) {
// Try to dequeue a message from the queue
if (!que.TryDequeue(out var message)) {
// If the queue is empty, wait for 100 milliseconds before trying again
await Task.Delay(TimeSpan.FromMilliseconds(100));
continue;
}
// If the message is a close request
if (message.Item1 == MessageType.Close) {
// Send a disconnect request to the client
await SendDisconnectRequestAsync(id, message.Item2);
// Notify the gateway of the client's disconnection
gtwy.NotifyDisconnection(id);
break;
}
// If the message is a regular message
else if (message.Item1 == MessageType.Message) {
// Send the message to the client
await SendWebSocketRequestAsync(id, message.Item2);
}
}
}
/// <summary>
/// Sends a disconnect request to a websocket client, with an optional message.
/// </summary>
/// <param name="id">The unique identifier of the client to send the request to</param>
/// <param name="message">An optional message for the logger</param>
private async Task SendDisconnectRequestAsync(WebsocketClientID id, string message) {
LoggerContext logger = new(Log.Gen, $"WebSocketHandler.SendDisconnectRequestAsync tried closing client_id: {id} with message: {message}", "");
// Get the socket of the client
var sckt = Connections.GetSocket(id);
if (sckt == null) {
logger.info(" failed as could not find socket in dictionary");
return;
}
try {
// send a close message to the socket, using the close status 1000, which is a normal closure status
await sckt.CloseAsync((WebSocketCloseStatus)1000, "", CancellationToken.None);
logger.info(" done succesfully");
} catch (WebSocketException ex) {
logger.info($" failed as client didnt respond, Exception: {ex.Message}");
}
}
/// <summary>
/// recieves messages from a specific websocket client identified by its id. keeps running until socket remains open
/// </summary>
/// <param name="id">The unique identifier of the client</param>
private async Task ProcessWebSocketRequestAsync(WebsocketClientID id) {
// Get the socket for the given client ID
var socket = GetConnectedWebSocket(id, "WebSocketHandler.ProcessWebSocketRequestAsync could not process");
// If the socket is null, return
if (socket == null) {
return;
}
try {
// Create a buffer to receive the incoming message
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[256]);
WebSocketReceiveResult result;
string request = "";
while (socket.IsOpen()) {
// Receive the message
result = await socket.ReceiveAsync(buffer, CancellationToken.None);
// If the message is a close request, handle the disconnection and return
if (result.MessageType == WebSocketMessageType.Close) {
var log_txt = $"WebSocketHandler.ProcessWebSocketRequestAsync close request";
gtwy.HandleDisconnection(id, log_txt);
return;
}
if (buffer.Array != null)// added because of warning
{
// Append the received message to the request string
request += Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
} else {
bts.Log.assert(false);//this should never happen
}
// If the message is the end of the message, handle the message and reset the request string
if (result.EndOfMessage) {
gtwy.HandleMessage(new WebsocketIncomingMessage(id, request));
request = "";
}
}
} catch (WebSocketException ex) {
var ex_str = ex.ToString();
var log_txt = $"WebsocketGateway.ProcessWebSocketRequestAsync connection closed Error: {ex_str}";
gtwy.HandleDisconnection(id, log_txt);
} catch (OperationCanceledException) {//not sure about this, read that this should just be ignored
}
}
/// <summary>
/// Sends a message to a specific websocket client identified by its id.
/// </summary>
/// <param name="id">The unique identifier of the client to receive the message</param>
/// <param name="message">The message to be sent</param>
public async Task SendWebSocketRequestAsync(WebsocketClientID id, string message) {
// Get the socket of the client
var socket = GetConnectedWebSocket(id, "WebSocketHandler.SendWebSocketRequestAsync could not send Request");
if (socket == null) {
return;
}
try {
// Send the message
await socket.SendAsync(Encoding.ASCII.GetBytes(message), WebSocketMessageType.Text, true, CancellationToken.None);
} catch (WebSocketException ex) {
// Handle the exception and disconnect the client
var ex_str = ex.ToString();
var log_txt = $"WebSocketHandler.SendWebSocketRequestAsync connection closed client_id: {id} Error: {ex_str}";
gtwy.HandleDisconnection(id, log_txt);
}
}
}
public event Action<WebsocketClientID>? Disconnected;
public event Action<WebsocketClientID, WebsocketIncomingMessage?>? Connected;
public event Action<WebsocketIncomingMessage>? MessageReceived;
private WebApplication? app = null;
private WebsocketServerConfig? _server_params = null;
private WebSocketConnectionStore Connections { get; } = new();
/// <summary>
/// creates a new connections dictionary and a new WebSocketHandler.
/// </summary>
private WebSocketHandler _WebSocketHandler { get; }
public WebsocketConnectionGateway() {
_WebSocketHandler = new WebSocketHandler(this, Connections);
}
/// <summary>
/// Creates a unique identifier for a websocket client and adds the client's connection to the list of active connections.
/// </summary>
/// <param name="conn">The connection of the client</param>
/// <returns>A unique identifier for the client</returns>
private WebsocketClientID createID(Connection conn) {
var id = new WebsocketClientID();
Connections.AddConnection(id, conn);
return id;
}
/// <summary>
/// forwards an incoming message from a websocket client to sync.
/// </summary>
/// <param name="message">The incoming message to be handled</param>
public void HandleMessage(WebsocketIncomingMessage message) =>
MessageReceived?.Invoke(message);
/// <summary>
/// Notifies of a client disconnection and removes the client's connection from the list of active connections.
/// </summary>
/// <param name="id">The unique identifier of the disconnected client</param>
public void NotifyDisconnection(WebsocketClientID id) {
Disconnected?.Invoke(id);
Connections.RemoveConnection(id);
}
/// <summary>
/// Handles a new websocket connection and returns a unique identifier for the client.
/// </summary>
/// <param name="conn">The new connection to be handled</param>
/// <param name="optional_message">An optional message associated with the connection</param>
/// <returns>A unique identifier for the client</returns>
public async Task<WebsocketClientID> HandleConnection(Connection conn, WebsocketIncomingMessage? optional_message) {
var id = createID(conn);
await Task.Run(() => Connected?.Invoke(id, optional_message));
return id;
}
/// <summary>
/// Handles disconnection of a websocket client.
/// </summary>
/// <param name="id">The unique identifier of the client to be disconnected</param>
/// <param name="optional_message">An optional message to add to the logger</param>
public void HandleDisconnection(WebsocketClientID id, string optional_message = "") {
LoggerContext logger = new(Log.Gen, $"WebsocketGateway.HandleDisconnection tried closing client_id: {id} with message: {optional_message}", "");
// Get the connection of the client
var conn = Connections.GetConnection(id);
if (conn == null) {
// If the client connection is not found, log the error and notify sync about the disconnection through the Sync object
logger.warn(" could not find socket in dictionary");
Disconnected?.Invoke(id);
return;
}
// Check if the connection needs to be disconnected
if (!_WebSocketHandler.ShouldDisconnect(id, conn, $"WebsocketGateway.HandleDisconnection tried closing client_id: {id}")) {
// If the connection does not need to be disconnected, remove it from the Connections dictionary
Connections.RemoveConnection(id);
return;
}
// Add the disconnection message to the WebSocketHandler's message queue
if (_WebSocketHandler.AddToQueue(id, Tuple.Create(MessageType.Close, "")))
logger.info(" added to que");
}
/// <summary>
/// Starts listening for incoming websocket connections. need to call init before this
/// </summary>
/// <param name="server_params">The parameters for the websocket server includind the URL and endpoint,</param>
public Task start_listening(WebsocketServerConfig server_params) {
// start listening, assert that init has been called already
bts.Log.isnull(_server_params);
bts.Log.isnull(app);
_server_params = server_params;
var builder = WebApplication.CreateBuilder();
var localServerParams = _server_params.Clone();
localServerParams.Scheme = "http";
var localUri = localServerParams.Uri();
builder.WebHost.UseUrls(localUri);
var publicServerParams = _server_params.Clone();
publicServerParams.Scheme = "https";
publicServerParams.Host = "192.168.50.94";
var publicUri = publicServerParams.Uri();
builder.WebHost.UseUrls(publicUri);
// var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddLogging(builder => {
builder.AddFilter("Microsoft", Microsoft.Extensions.Logging.LogLevel.Warning)
.AddFilter("System", Microsoft.Extensions.Logging.LogLevel.Warning)
.AddFilter("NToastNotify", Microsoft.Extensions.Logging.LogLevel.Warning)
.AddConsole();
});
// builder.Services.AddCors(options => {
// options.AddPolicy(MyAllowSpecificOrigins,
// policy => policy
// .WithOrigins("http://localhost:3000")
// .AllowAnyHeader()
// .AllowAnyMethod());
// });
app = builder.Build();
app.UseWebSockets(_server_params.get_ws_options());
// app.Use(async (context, next) => {
// context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
// context.Response.Headers.Add("Access-Control-Allow-Headers", "*");
// await next();
// });
app.Map(_server_params.DefaultEndPoint, async context => {
if (context.WebSockets.IsWebSocketRequest) {
using (var ws = await context.WebSockets.AcceptWebSocketAsync()) {
await _WebSocketHandler.ProcessWebSocketConnectionAsync(ws);
}
} else {
context.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
}
});
return app.RunAsync();
}
/// <summary>
/// Sends a message to a list of websocket clients.
/// </summary>
/// <param name="messages">A collection of websocket messages to be sent to the clients</param>
public void send_to_clients(
IEnumerable<WebsocketOutgoingMessage> messages) {
foreach (var om in messages) {
// Add the message to the WebSocketHandler's message queue
if (!_WebSocketHandler.AddToQueue(om.receiver_client_id, Tuple.Create(MessageType.Message, om.message_body)))
break;
}
}
}
}
@@ -0,0 +1,14 @@
namespace Bts.Websocket;
using System.Net.WebSockets;
public static class WebsocketExtensions {
public static bool IsOpen(this WebSocket ws) =>
ws.State switch {
WebSocketState.None or WebSocketState.Closed or WebSocketState.Aborted => false,
_ => true
};
public static bool IsClosedProperly(this WebSocket ws) =>
ws.CloseStatus == WebSocketCloseStatus.NormalClosure;
}
+1
View File
@@ -0,0 +1 @@
using System.Text.Json;