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
}
///
/// 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)
///
public class WebsocketConnectionGateway : IWebsocketConnectionGateway {
///
/// Represents a connection to a client through a WebSocket.
///
public class Connection {
///
/// The WebSocket instance associated with this connection.
///
public WebSocket Ws { get; }
///
/// A queue that holds outgoing messages to be sent to the client.
///
public ConcurrentQueue> OutgoingQueue { get; } = new();
///
/// Initializes a new instance of the class.
///
/// The WebSocket associated with this connection.
public Connection(WebSocket websocket) {
Ws = websocket;
}
}
///
/// wrapper for concurrent Dictionary
/// Stores all the alive connection
/// Additions and removals done by gateway
/// websockethandler can access but not change anything
///
class WebSocketConnectionStore {
private ConcurrentDictionary Connections { get; } = new();
///
/// Adds a new connection to the connections dictionary using the given id and connection object
///
/// The id to use as the key for the new connection
/// The connection object to add to the dictionary
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;
}
}
///
/// Removes a connection from the connections dictionary using the given id
///
/// The id of the connection to remove
public void RemoveConnection(WebsocketClientID id) {
if (Connections.TryRemove(id, out Connection? conn)) {
conn.Ws.Dispose();
}
}
///
/// Retrieves the Connection object associated with the given id
///
/// The id of the connection to retrieve
/// The Connection object associated with the given id, or null if the id is not found
public Connection? GetConnection(WebsocketClientID id) => Connections.GetValueOrDefault(id);
///
/// Retrieves the Connection object associated with the given id
///
/// The id of the connection to retrieve
/// The Connection object associated with the given id, or null if the id is not found
public WebSocket? GetSocket(WebsocketClientID id) => Connections.GetValueOrDefault(id)?.Ws;
///
/// Get the outgoing message queue for a specific client connection identified by the given id.
///
/// The unique identifier for the client connection.
/// A concurrent queue of message tuples if the connection is found, null otherwise.
public ConcurrentQueue>? GetSocketQueue(WebsocketClientID id) =>
Connections.GetValueOrDefault(id)?.OutgoingQueue;
///
/// Check if the store contains a connection with the specified id.
///
/// The unique identifier for the client connection.
/// True if the connection is found, false otherwise.
public bool ContainsKey(WebsocketClientID id) => Connections.ContainsKey(id);
}
///
/// 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,
///
class WebSocketHandler {
///
/// 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.
///
/// The client ID to use to retrieve the WebSocket from the WebSocketConnectionStore.
/// The error message to log if the WebSocket is not found or not open.
/// The connected WebSocket or null if it was not found or not open.
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;
}
///
/// Determines if a WebSocket connection needs to be disconnected
///
/// The unique identifier of the WebSocket client
/// The Connection object of the WebSocket client
/// The error message to be logged in case of improper connection closure
/// True if the connection needs to be disconnected, False otherwise
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(connections);
set {
bts.Log.isnull(connections);
connections = value;
}
}
///
/// Initializes a new instance of the class
///
/// Websocket connection gateway
/// Connections dictionary
public WebSocketHandler(WebsocketConnectionGateway gateway, WebSocketConnectionStore conns) {
gtwy = gateway;
Connections = conns;
}
///
/// 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.
///
/// The WebSocket connection to be processed
/// A task that represents the asynchronous operation
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));
}
///
/// Adds a message to the queue of a specific websocket client.
///
/// The unique identifier of the client
/// The message to be added to the queue
/// True if succesfull otherwise fasle
public bool AddToQueue(WebsocketClientID id, Tuple mes) {
var que = Connections.GetSocketQueue(id);
if (que == null) {
return false;
}
que.Enqueue(mes);
return true;
}
///
/// Processes the messages in the WebSocket queue for a specific client.
/// will keep running until socket is open
///
/// The unique identifier of the client
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);
}
}
}
///
/// Sends a disconnect request to a websocket client, with an optional message.
///
/// The unique identifier of the client to send the request to
/// An optional message for the logger
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}");
}
}
///
/// recieves messages from a specific websocket client identified by its id. keeps running until socket remains open
///
/// The unique identifier of the client
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 buffer = new ArraySegment(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
}
}
///
/// Sends a message to a specific websocket client identified by its id.
///
/// The unique identifier of the client to receive the message
/// The message to be sent
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? Disconnected;
public event Action? Connected;
public event Action? MessageReceived;
private WebApplication? app = null;
private WebsocketServerConfig? _server_params = null;
private WebSocketConnectionStore Connections { get; } = new();
///
/// creates a new connections dictionary and a new WebSocketHandler.
///
private WebSocketHandler _WebSocketHandler { get; }
public WebsocketConnectionGateway() {
_WebSocketHandler = new WebSocketHandler(this, Connections);
}
///
/// Creates a unique identifier for a websocket client and adds the client's connection to the list of active connections.
///
/// The connection of the client
/// A unique identifier for the client
private WebsocketClientID createID(Connection conn) {
var id = new WebsocketClientID();
Connections.AddConnection(id, conn);
return id;
}
///
/// forwards an incoming message from a websocket client to sync.
///
/// The incoming message to be handled
public void HandleMessage(WebsocketIncomingMessage message) =>
MessageReceived?.Invoke(message);
///
/// Notifies of a client disconnection and removes the client's connection from the list of active connections.
///
/// The unique identifier of the disconnected client
public void NotifyDisconnection(WebsocketClientID id) {
Disconnected?.Invoke(id);
Connections.RemoveConnection(id);
}
///
/// Handles a new websocket connection and returns a unique identifier for the client.
///
/// The new connection to be handled
/// An optional message associated with the connection
/// A unique identifier for the client
public async Task HandleConnection(Connection conn, WebsocketIncomingMessage? optional_message) {
var id = createID(conn);
await Task.Run(() => Connected?.Invoke(id, optional_message));
return id;
}
///
/// Handles disconnection of a websocket client.
///
/// The unique identifier of the client to be disconnected
/// An optional message to add to the logger
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");
}
///
/// Starts listening for incoming websocket connections. need to call init before this
///
/// The parameters for the websocket server includind the URL and endpoint,
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();
}
///
/// Sends a message to a list of websocket clients.
///
/// A collection of websocket messages to be sent to the clients
public void send_to_clients(
IEnumerable 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;
}
}
}
}