diff --git a/src/client/spark_websocket/Core/WebsocketConnectionGateway.cs b/src/client/spark_websocket/Core/WebsocketConnectionGateway.cs index 696b541aa..13bba2eb2 100644 --- a/src/client/spark_websocket/Core/WebsocketConnectionGateway.cs +++ b/src/client/spark_websocket/Core/WebsocketConnectionGateway.cs @@ -303,7 +303,7 @@ namespace bts.websocket_core { 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 client_id: {id}"; + var log_txt = $"WebSocketHandler.ProcessWebSocketRequestAsync close request"; gtwy.HandleDisconnection(id, log_txt); return; } @@ -323,7 +323,7 @@ namespace bts.websocket_core { } catch (WebSocketException ex) { var ex_str = ex.ToString(); - var log_txt = $"WebsocketGateway.ProcessWebSocketRequestAsync connection closed client_id: {id} Error: {ex_str}"; + 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 } diff --git a/src/client/spark_websocket/Core/WebsocketDataSync.cs b/src/client/spark_websocket/Core/WebsocketDataSync.cs index ce1d05173..1001a7bfc 100644 --- a/src/client/spark_websocket/Core/WebsocketDataSync.cs +++ b/src/client/spark_websocket/Core/WebsocketDataSync.cs @@ -1,4 +1,64 @@ namespace bts.websocket_core { + /// + /// class to manage thread safe client store, will change this to blocking collection + /// + class ClientsStore { + private Dictionary Clients { get; init; } + private object _clientsAccessLock; + public ClientsStore() { + Clients = new Dictionary(); + _clientsAccessLock = new object(); + } + /// + /// adds client to dictionary is thread safe + /// + /// + public void AddClient(WebsocketClientID client_id) { + lock (_clientsAccessLock) { + Clients.Add(client_id, new ClientState(0)); + } + } + /// + /// removes client from dictionary is thread safe + /// + /// + public void RemoveClient(WebsocketClientID client_id) { + lock (_clientsAccessLock) { + if (Clients.ContainsKey(client_id)) + Clients.Remove(client_id); + } + } + public IEnumerator> GetEnumerator() { + lock (_clientsAccessLock) { + return Clients.GetEnumerator(); + } + } + public ClientState this[WebsocketClientID clientId] { + get { + lock (_clientsAccessLock) { + if (Clients.TryGetValue(clientId, out var clientState)) { + return clientState; + } else { + throw new ArgumentException($"{nameof(clientId)} not found in the Clients dictionary"); + } + } + } + set { + lock (_clientsAccessLock) { + if (Clients.ContainsKey(clientId)) { + Clients[clientId] = value; + } else { + throw new ArgumentException($"{nameof(clientId)} not found in the Clients dictionary"); + } + } + } + } + public int Count() { + lock (_clientsAccessLock) { + return Clients.Count; + } + } + } /// /// Immutable to store the state of the client /// @@ -16,89 +76,55 @@ namespace bts.websocket_core { /// it over to the business layer CURRENT VERSION IS JUST TO SHOW HOW TO USE GATEWAY /// public class WebsocketDataSync : IWebsocketDataSync { - WebsocketConnectionGateway? Gateway; + WebsocketConnectionGateway? gateway; + WebsocketConnectionGateway Gateway { + get { + return (WebsocketConnectionGateway)Helpers.GetNonNull(gateway); + } + set { + bts.Log.assert(gateway == null); + gateway = value; + } + } /// /// stores the current connected clients, can be converted the concurrent dictionary /// - private Dictionary? clients; - /// - /// to access the dictionary - /// - private static object _clientsAccessLock = new object(); + private ClientsStore? clients = null; + private ClientsStore Clients { + get { + return (ClientsStore)Helpers.GetNonNull(clients); + } + set { + bts.Log.assert(clients == null); + clients = value; + } + } /// /// Thread that will broadcast messages to all connected messages /// private Thread? broadcast; + private Thread Broadcast { + get { + return (Thread)Helpers.GetNonNull(broadcast); + } + set { + bts.Log.assert(broadcast == null); + broadcast = value; + } + } /// /// number of messages after which broadcast thread will disconnect that particular socket /// public uint BROADCAST_LIMIT { get; } = 20; - /// - /// will update getter to c# convention - /// - /// non nullable version - private WebsocketConnectionGateway GetGateway() => (WebsocketConnectionGateway)GetNonNull(Gateway); - /// - /// will update getter to c# convention - /// - /// non nullable version - private Dictionary GetClients() => (Dictionary)GetNonNull(clients); - /// - /// adds client to dictionary is thread safe - /// - /// - void AddClient(WebsocketClientID client_id) { - lock (_clientsAccessLock) { - GetClients().Add(client_id, new ClientState(0)); - } - } - /// - /// removes client from dictionary is thread safe - /// - /// - void RemoveClient(WebsocketClientID client_id) { - lock (_clientsAccessLock) { - if (GetClients().ContainsKey(client_id)) - GetClients().Remove(client_id); - } - } - /// - /// will update getter to c# convention - /// - /// non nullable version - private Thread GetBroadcast() => (Thread)GetNonNull(broadcast); - /// - /// 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(); - } - } + + /// /// Should be called in the start, stores pointer for gtwy and creates dictionary for clients, starts broadcast thread /// /// public void init(WebsocketConnectionGateway gtwy) { Gateway = gtwy; - clients = new Dictionary(); + clients = new ClientsStore(); broadcast = new Thread(() => BroadcastToClients()); broadcast.Start(); } @@ -110,20 +136,23 @@ namespace bts.websocket_core { while (true) { List messages = new List(); List toRemove = new List(); - lock (_clientsAccessLock) { - foreach (var client in GetClients()) { - messages.Add(new WebsocketOutgoingMessage(client.Key, $"New Message number: {client.Value.MessageCount}, clients connected: {GetClients().Count}")); - GetClients()[client.Key] = client.Value.IncrementMessages(client.Value); - if (GetClients()[client.Key].MessageCount == BROADCAST_LIMIT) { + + foreach (var client in Clients) { + try { + messages.Add(new WebsocketOutgoingMessage(client.Key, $"New Message number: {client.Value.MessageCount}, clients connected: {Clients.Count()}")); + Clients[client.Key] = client.Value.IncrementMessages(client.Value); + if (Clients[client.Key].MessageCount == BROADCAST_LIMIT) { toRemove.Add(client.Key); } + } catch (ArgumentException) { + continue; } } //example on how to send multiple messages to multiple sockets - GetGateway().send_to_clients(messages); + Gateway.send_to_clients(messages); foreach (var key in toRemove) { ///example on how to disconnect, this should ideally happen in its own thread - GetGateway().HandleDisconnection(key, "closing client"); + Gateway.HandleDisconnection(key, "closing client"); } Thread.Sleep(duration); } @@ -132,18 +161,18 @@ namespace bts.websocket_core { // Called when a new client is connected public void handle_connection(WebsocketClientID client_id, WebsocketIncomingMessage? optional_message) { - AddClient(client_id); + Clients.AddClient(client_id); var log_txt = $"WebsocketDataSync.handle_connection client_id: {client_id} " + $"message: {(optional_message == null ? "null" : optional_message.ToString())}"; bts.Log.Gen.info(log_txt); System.Console.WriteLine(log_txt); - if (IsNotNull(optional_message)) { + if (optional_message != null) { handle_client_message(optional_message); } } // Called when a client is disconnected public void handle_disconnection(WebsocketClientID client_id) { - RemoveClient(client_id); + Clients.RemoveClient(client_id); var log_txt = $"WebsocketDataSync.handle_disconnection client_id: {client_id}"; bts.Log.Gen.info(log_txt); System.Console.WriteLine(log_txt); @@ -154,7 +183,7 @@ namespace bts.websocket_core { bts.Log.Gen.info(log_txt); System.Console.WriteLine(log_txt); //example to show how to send messages to clients - GetGateway().send_to_clients(new List() { new WebsocketOutgoingMessage(message.sender_client_id, message.message_body + " RESPONSE") }); + Gateway.send_to_clients(new List() { new WebsocketOutgoingMessage(message.sender_client_id, message.message_body + " RESPONSE") }); } }