diff --git a/src/client/spark_websocket/Core/WebsocketConnectionGateway.cs b/src/client/spark_websocket/Core/WebsocketConnectionGateway.cs index 812da36db..87dda6cd6 100644 --- a/src/client/spark_websocket/Core/WebsocketConnectionGateway.cs +++ b/src/client/spark_websocket/Core/WebsocketConnectionGateway.cs @@ -46,58 +46,86 @@ namespace bts.websocket_core { connections = new ConcurrentDictionary(); } } - // class SocketsHandler { - // private WebApplication? app = null; - // private WebsocketServerParams? _server_params = null; + class SocketsHandler { + private Action GetLogger(string base_text) => ((string additional_message) => { + base_text += additional_message; + bts.Log.Gen.info(base_text); + Console.WriteLine(base_text); + }); + private T getObject(T? obj) => obj!; - // public void start_listening(WebsocketServerParams server_params) { - // // start listening, assert that init has been called already - // bts.Log.assert(_server_params == null); - // bts.Log.assert(app == null); + private static bool IsNotNull([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? obj) => obj != null; - - // _server_params = server_params; - // var builder = WebApplication.CreateBuilder(); - // builder.WebHost.UseUrls(_server_params.Uri); - // app = builder.Build(); - // app.UseWebSockets(_server_params.get_ws_options()); - - // app.Map(_server_params.Default_end_point, async context => { - // if (context.WebSockets.IsWebSocketRequest) { - // using (var ws = await context.WebSockets.AcceptWebSocketAsync()) { - // await ProcessWebSocketConnectionAsync(ws); - // } - // } else { - // context.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; - // } - // }); - // app.RunAsync(); - - // } - - - // } - - /// - /// Handles all websocket related processing, interfaces with datasync, gets initial paramters from WebsocketServerParams - /// - - public class WebsocketConnectionGateway : IWebsocketConnectionGateway { - - - private WebsocketServerParams? _server_params = null; - private WebApplication? app = null; - private IWebsocketDataSync? _sync = null; - private IWebsocketDataSync Sync { - get { - return (IWebsocketDataSync)GetNonNull(_sync); + private object GetNonNull(object? obj) { + if (IsNotNull(obj)) { + return getObject(obj); + } else { + bts.Log.assert(false); + return new Object(); } - set { - bts.Log.assert(_sync == null); - _sync = value; - } - } + static bool IsSocketStateOpen(WebSocket? ws) => ws != null && ws.State != WebSocketState.Closed && ws.State != WebSocketState.Aborted && ws.State != WebSocketState.None; + public static bool IsClosedProperly(WebSocket ws) => ws.CloseStatus == WebSocketCloseStatus.NormalClosure; + WebsocketClientID createID(WebSocket ws) { + var id = new WebsocketClientID(); + var sck = new Connection(ws); + Connections.AddConnection(id, sck); + return id; + } + private WebSocket? GetSocket(WebsocketClientID id, string error_message) { + var log = GetLogger(error_message); + var socket = Connections.GetSocket(id); + if (socket == null) { + log(" failed as could not find socket in dictionary"); + gtwy.HandleDisconnection(id, error_message);//fix this + return null; + } + if (!IsSocketStateOpen(socket)) { + log(" failed as Socket closed"); + gtwy.HandleDisconnection(id, error_message);//fix this + return null; + } + return socket; + } + private bool SocketExist(WebsocketClientID id, string error_message) { + var log = GetLogger(error_message); + var socket = Connections.GetSocket(id); + var que = Connections.GetSocketQueue(id); + if (socket == null || que == null) { + log("could not find socket in dictionary"); + gtwy.NotifyDisconnection(id); + return false; + } + return true; + } + + + public bool NeedsDisconnect(WebsocketClientID id, string error_message) { + var log = GetLogger(error_message); + var socket = Connections.GetSocket(id); + if (IsSocketStateOpen(socket)) { + return true; + } + if (socket == null) { + log(" could not find socket in dictionary"); + gtwy.NotifyDisconnection(id); + return false; + } + if (IsClosedProperly(socket)) { + log(" closed properly by other thread"); + Connections.RemoveConnection(id); + return false; + } + log(" closed improperly by other thread"); + gtwy.NotifyDisconnection(id); + Connections.RemoveConnection(id); + return false; + } + private WebApplication? app = null; + private WebsocketServerParams? _server_params = null; + + private WebsocketConnectionGateway gtwy; + private ConnectionsDictionary? connections = null; private ConnectionsDictionary Connections { get { @@ -109,122 +137,13 @@ namespace bts.websocket_core { } } - /// - /// To Avoid null reference warning, only called when object is not null, should only be called inside getNonNull, is separate function so can be changed later on - /// - /// non nullable version of object - private T getObject(T? obj) { - return obj!; - } - - /// - /// as explained in c# documentation this can be used to instruct the compiler that obj is not null, for now this is redundant - /// - /// - /// - private static bool IsNotNull([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? obj) => obj != null; - - /// - /// will assert that object is not null and return the non nullable version - /// - /// non nullable version of object - private object GetNonNull(object? obj) { - if (IsNotNull(obj)) { - return getObject(obj); - } else { - bts.Log.assert(false); - return new Object(); - } - } - public static bool IsSocketOpen(WebSocket? ws) => ws != null && ws.State != WebSocketState.Closed && ws.State != WebSocketState.Aborted && ws.State != WebSocketState.None; - - private WebSocket? GetSocket(WebsocketClientID id, string error_message) { - var log = GetLogger(error_message); - var socket = Connections.GetSocket(id); - if (socket == null) { - log(" failed as could not find socket in dictionary"); - HandleDisconnection(id, error_message); - return null; - } - if (!IsSocketOpen(socket)) { - log(" failed as Socket closed"); - HandleDisconnection(id, error_message); - return null; - } - return socket; - } - private Action GetLogger(string base_text) => ((string additional_message) => { - base_text += additional_message; - bts.Log.Gen.info(base_text); - Console.WriteLine(base_text); - }); - /// - /// creates ID and adds it to clients, in case of collision just updates the previous value - /// - WebsocketClientID createID(WebSocket ws) { - var id = new WebsocketClientID(); - var sck = new Connection(ws); - Connections.AddConnection(id, sck); - return id; - } - - /// - /// Should be called in the start, stores pointer for sync and creates dictionary for clients, does not start server - /// - /// - public void init(IWebsocketDataSync sync) { - // first call - Sync = sync; + public SocketsHandler(WebsocketConnectionGateway gateway) { + gtwy = gateway; Connections = new ConnectionsDictionary(); } - - /// - /// Manages client disconnection, does the following three things: - /// 1. tries sending close request to client - /// 2. removes client from dictionary of active clients - /// 3. asks sync to handle disconnection - /// - public void HandleDisconnection(WebsocketClientID id, string optional_message = "") { - var log = GetLogger($"WebsocketGateway.HandleDisconnection tried closing client_id: {id} with message: {optional_message}"); - var socket = Connections.GetSocket(id); - var que = Connections.GetSocketQueue(id); - if (socket == null || que == null) { - log(" failed as could not find socket in dictionary"); - Sync.handle_disconnection(id); - return; - } - if (!IsSocketOpen(socket)) { - if (socket.CloseStatus == WebSocketCloseStatus.NormalClosure) { - log(" already closed properly by other thread"); - return; - } - log(" already closed "); - Sync.handle_disconnection(id); - Connections.RemoveConnection(id); - return; - } - que.Enqueue(Tuple.Create(MessageType.Close, "")); - log(" added to que"); - return; - } - /// - /// tries to send request to client to disconnect - /// - /// id of client to whom the Disconnect message should be sent - /// - /// task that completes if client disconnects or if there is an error - - /// - /// should be called after init - /// creates server using the server params provided and starts listening for socket based requests on that URI - /// keeps running async - /// - /// public void start_listening(WebsocketServerParams server_params) { // start listening, assert that init has been called already - bts.Log.assert(_sync != null); bts.Log.assert(_server_params == null); - bts.Log.assert(connections != null); bts.Log.assert(app == null); @@ -246,35 +165,22 @@ namespace bts.websocket_core { app.RunAsync(); } - /// - /// sends the list of messafes to respectives sockets, does not wait for messages to be sent - /// - /// list of messages each containing a string based message and client ID - public void send_to_clients( - IEnumerable messages) { - var tasks = new List(); - foreach (var om in messages) { - var q = Connections.GetSocketQueue(om.receiver_client_id); - if (q != null) { - q.Enqueue(Tuple.Create(MessageType.Message, om.message_body)); - } - } - } - /// - /// After adding new socket to dictionary send the new client id to sync to store and process - /// while socket stays open this keeps waiting for requests - /// - /// - /// Task that keeps waiting for requests until the socket is closed public async Task ProcessWebSocketConnectionAsync(WebSocket ws) { var id = createID(ws); - Sync.handle_connection(id, null);//for now thinking this is async/ no IO + await gtwy.HandleConnection(id, null); // this should be async? var pushTask = Task.Run(() => ProcessWebSocketQueueAsync(id)); await ProcessWebSocketRequestAsync(id); await pushTask; } - public async Task ProcessWebSocketQueueAsync(WebsocketClientID id) { - var socket = GetSocket(id, "WebsocketGateway.ProcessWebSocketQueueAsync could not process"); + public void AddToQueue(WebsocketClientID id, Tuple mes) { + var que = Connections.GetSocketQueue(id); + if (que == null) { + return; + } + que.Enqueue(mes); + } + private async Task ProcessWebSocketQueueAsync(WebsocketClientID id) { + var socket = GetSocket(id, "SocketsHandler.ProcessWebSocketQueueAsync could not process"); var que = Connections.GetSocketQueue(id); if (socket == null || que == null) { return; @@ -287,60 +193,15 @@ namespace bts.websocket_core { if (message.Item1 == MessageType.Close) { await SendDisconnectRequestAsync(id, message.Item2); Connections.RemoveConnection(id); - Sync.handle_disconnection(id); + gtwy.NotifyDisconnection(id); return; } else if (message.Item1 == MessageType.Message) { await SendWebSocketRequestAsync(id, message.Item2); } - } while (IsSocketOpen(socket)); + } while (IsSocketStateOpen(socket)); } - /// - /// 1. makes sure state is consistent - /// 2. listens for request - /// 3. if request is the close, calls handleDisconnection - /// 4. otherwise sends request to sync to process - /// catches exception of client closes without handshake - /// - /// id of client from whom the message is to be recieved - /// Task that runs until socket is open - public async Task ProcessWebSocketRequestAsync(WebsocketClientID id) { - var socket = GetSocket(id, "WebsocketGateway.ProcessWebSocketRequestAsync could not process"); - if (socket == null) { - return; - } - try { - ArraySegment buffer = new ArraySegment(new byte[256]); - WebSocketReceiveResult result; - string request = ""; - do { - result = await socket.ReceiveAsync(buffer, CancellationToken.None); - if (result.MessageType == WebSocketMessageType.Close) { - var log_txt = $"WebsocketGateway.ProcessWebSocketRequestAsync close request client_id: {id}"; - HandleDisconnection(id, log_txt); - return; - } - if (buffer.Array != null)// added because of warning - { - request += Encoding.UTF8.GetString(buffer.Array, 0, result.Count); - } else { - bts.Log.assert(false);//this should never happen - } - if (result.EndOfMessage) { - Sync.handle_client_message(new WebsocketIncomingMessage(id, request)); - request = ""; - } - } while (IsSocketOpen(socket)); - - } catch (WebSocketException ex) { - var ex_str = ex.ToString(); - var log_txt = $"WebsocketGateway.ProcessWebSocketRequestAsync connection closed client_id: {id} Error: {ex_str}"; - HandleDisconnection(id, log_txt); - } catch (OperationCanceledException) {//not sure about this read that this should just be ignored - } - } - public async Task SendDisconnectRequestAsync(WebsocketClientID id, string message) { - var log = GetLogger($"WebsocketGateway.SendDisconnectRequestAsync tried closing client_id: {id} with message: {message}"); + var log = GetLogger($"SocketsHandler.SendDisconnectRequestAsync tried closing client_id: {id} with message: {message}"); var sckt = Connections.GetSocket(id); if (sckt == null) { log(" failed as could not find socket in dictionary"); @@ -353,15 +214,43 @@ namespace bts.websocket_core { log(" failed as client didnt respond"); } } + public async Task ProcessWebSocketRequestAsync(WebsocketClientID id) { + var socket = GetSocket(id, "SocketsHandler.ProcessWebSocketRequestAsync could not process"); + if (socket == null) { + return; + } + try { + ArraySegment buffer = new ArraySegment(new byte[256]); + WebSocketReceiveResult result; + string request = ""; + do { + result = await socket.ReceiveAsync(buffer, CancellationToken.None); + if (result.MessageType == WebSocketMessageType.Close) { + var log_txt = $"SocketsHandler.ProcessWebSocketRequestAsync close request client_id: {id}"; + gtwy.HandleDisconnection(id, log_txt); + return; + } + if (buffer.Array != null)// added because of warning + { + request += Encoding.UTF8.GetString(buffer.Array, 0, result.Count); + } else { + bts.Log.assert(false);//this should never happen + } + if (result.EndOfMessage) { + gtwy.HandleMessage(new WebsocketIncomingMessage(id, request)); + request = ""; + } + } while (IsSocketStateOpen(socket)); - /// - /// sends message iver socket correspoding to id - /// - /// id of client to whom the message should be sent - /// message to be sent - /// + } catch (WebSocketException ex) { + var ex_str = ex.ToString(); + var log_txt = $"WebsocketGateway.ProcessWebSocketRequestAsync connection closed client_id: {id} Error: {ex_str}"; + gtwy.HandleDisconnection(id, log_txt); + } catch (OperationCanceledException) {//not sure about this read that this should just be ignored + } + } public async Task SendWebSocketRequestAsync(WebsocketClientID id, string message) { - var socket = GetSocket(id, "WebsocketGateway.SendWebSocketRequestAsync could not send Request"); + var socket = GetSocket(id, "SocketsHandler.SendWebSocketRequestAsync could not send Request"); if (socket == null) { return; } @@ -369,11 +258,109 @@ namespace bts.websocket_core { await socket.SendAsync(System.Text.Encoding.ASCII.GetBytes(message), System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None); } catch (WebSocketException ex) { var ex_str = ex.ToString(); - var log_txt = $"WebsocketGateway.SendWebSocketRequestAsync connection closed client_id: {id} Error: {ex_str}"; - HandleDisconnection(id, log_txt); + var log_txt = $"SocketsHandler.SendWebSocketRequestAsync connection closed client_id: {id} Error: {ex_str}"; + gtwy.HandleDisconnection(id, log_txt); return; } } + + } + + /// + /// Handles all websocket related processing, interfaces with datasync, gets initial paramters from WebsocketServerParams + /// + + public class WebsocketConnectionGateway : IWebsocketConnectionGateway { + + + private WebsocketServerParams? _server_params = null; + private IWebsocketDataSync? _sync = null; + private IWebsocketDataSync Sync { + get { + return (IWebsocketDataSync)GetNonNull(_sync); + } + set { + bts.Log.assert(_sync == null); + _sync = value; + } + + } + private SocketsHandler? networkHandler = null; + private SocketsHandler NetworkHandler { + get { + return (SocketsHandler)GetNonNull(networkHandler); + } + set { + bts.Log.assert(networkHandler == null); + networkHandler = value; + } + } + + + private T getObject(T? obj) { + return obj!; + } + + private static bool IsNotNull([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? obj) => obj != null; + + + private object GetNonNull(object? obj) { + if (IsNotNull(obj)) { + return getObject(obj); + } else { + bts.Log.assert(false); + return new Object(); + } + } + + private Action GetLogger(string base_text) => ((string additional_message) => { + base_text += additional_message; + bts.Log.Gen.info(base_text); + Console.WriteLine(base_text); + }); + + /// Should be called in the start, stores pointer for sync and creates dictionary for clients, does not start server + /// + /// + public void init(IWebsocketDataSync sync) { + // first call + Sync = sync; + NetworkHandler = new SocketsHandler(this); + } + public void HandleMessage(WebsocketIncomingMessage message) => Sync.handle_client_message(message); + public void NotifyDisconnection(WebsocketClientID id) => Sync.handle_disconnection(id); + public async Task HandleConnection(WebsocketClientID id, WebsocketIncomingMessage? optional_message) => await Task.Run(() => Sync.handle_connection(id, optional_message)); + + + public void HandleDisconnection(WebsocketClientID id, string optional_message = "") { + if (!NetworkHandler.NeedsDisconnect(id, $"WebsocketGateway.HandleDisconnection tried closing client_id: {id}")) { + return; + } + //add to que here + var log = GetLogger($"WebsocketGateway.HandleDisconnection tried closing client_id: {id} with message: {optional_message}"); + NetworkHandler.AddToQueue(id, Tuple.Create(MessageType.Close, "")); + log(" added to que"); + return; + } + + public void start_listening(WebsocketServerParams server_params) { + // start listening, assert that init has been called already + bts.Log.assert(_sync != null); + bts.Log.assert(_server_params == null); + + NetworkHandler.start_listening(server_params); + + } + + public void send_to_clients( + IEnumerable messages) { + foreach (var om in messages) { + NetworkHandler.AddToQueue(om.receiver_client_id, Tuple.Create(MessageType.Message, om.message_body)); + } + } + + + } } \ No newline at end of file