Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/Server/Server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ Server::Server(int port) : port(port), serverSocket(INVALID_SOCKET),

eventLoop = makeEventLoop();

userSessionManager.set_on_session_expired(
[this](SocketType sock)
{ onSessionExpired(sock); });

#ifdef _WIN32
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
Expand Down Expand Up @@ -134,6 +138,9 @@ void Server::stop()
std::cout << "[SERVER] Stop requested...\n";

running = false;
for (auto &[sock, conn] : connections)
CloseSocket(sock);
connections.clear();
userSessionManager.close_all_sessions();
CloseSocket(serverSocket);
// Forces accept() loop to unblock by breaking the file descriptor channel
Expand All @@ -154,6 +161,18 @@ void Server::runEventLoop()

while (running)
{
// Close all the expired connections
{
std::vector<SocketType> close;
{
std::lock_guard<std::mutex> lock(expiredMutex);
close.swap(expiredSockets);
}
for (auto &sock : close){
std::cout << "[SERVER] Closing expired connection, socket " << sock << "\n";
closeConnection(sock);
}
}
int numEvents = eventLoop->wait(events);
if (numEvents == -1)
continue; // wait() itself failed, try again
Expand Down Expand Up @@ -298,4 +317,11 @@ void Server::messageHandler(SocketType clientSocket, const SessionKey &sessionKe
std::string response = "No command was received\n";
send(clientSocket, response.c_str(), response.length(), 0);
}
}

void Server::onSessionExpired(SocketType sock)
{
std::cout << "[SERVER] Session expired, queuing socket " << sock << " for close\n";
std::lock_guard<std::mutex> lock(expiredMutex);
expiredSockets.push_back(sock);
}
10 changes: 9 additions & 1 deletion src/Server/Server.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
#include <mutex>
#include <unordered_set>

#include "UserSessionBackgroundWorker.h"
#include "../Worker/UserSessionBackgroundWorker.h"
#include "../RAM/HashMap.h"
#include "../Storage/Persistence.h"
#include "../Worker/ThreadPool.h"
Expand Down Expand Up @@ -42,6 +42,8 @@ class Server
std::thread eventLoopThread; /** Thread that runs runEventLoop() */
std::mutex busyMutex; /** Guards busySockets */
std::unordered_set<SocketType> busySockets; /** Sockets with a recv job already queued/running */
std::mutex expiredMutex; /** Mutex to guard the expiredSockets vector */
std::vector<SocketType> expiredSockets; /** Notifys the event loop of connections to remove */

/**
* @brief Runs continuously on eventLoopThread: waits for socket readiness
Expand Down Expand Up @@ -91,6 +93,12 @@ class Server
* @param sessionKey The session tied to this client.
*/
void messageHandler(SocketType clientSocket, const SessionKey &sessionKey);

/**
* @brief Adds sockets that are expired into the expired vector to be removed later by eventloop
* @param sock which is the client socket that is to be removed
*/
void onSessionExpired(SocketType sock);
};

#endif
14 changes: 13 additions & 1 deletion src/UserSession/UserSession.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ void UserSessionManager::cleanup_expired_sessions() {

for (auto it = users_sessions.begin(); it != users_sessions.end(); ) {
if (it->second->is_expired()) {
// Notify Server before erasing so it can tear down
if(on_session_expired)
on_session_expired(it->second->get_socket());
it = users_sessions.erase(it); // Terminate Will call Automatically
} else {
++it;
Expand All @@ -56,6 +59,11 @@ void UserSessionManager::close_all_sessions() {
}


void UserSessionManager::set_on_session_expired(std::function<void(SocketType)> cb) {
on_session_expired = std::move(cb);
}


// --- UserSession Implementation ---

UserSessionManager::UserSession::UserSession(SocketType socket, const sockaddr_in& client_addr, std::chrono::seconds max_idle)
Expand All @@ -79,7 +87,11 @@ void UserSessionManager::UserSession::update_last_activity_time() {
}

void UserSessionManager::UserSession::terminate_session() {
CloseSocket(user_socket);
/** Socket closure is Server's responsibility (see closeConnection()).
Closing it here would race Server's connections/eventLoop bookkeeping. */


// CloseSocket(user_socket);
}

bool UserSessionManager::UserSession::is_expired() const {
Expand Down
20 changes: 19 additions & 1 deletion src/UserSession/UserSession.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include <shared_mutex>
#include <string>
#include <unordered_map>
#include <functional>


/**
Expand Down Expand Up @@ -88,7 +89,17 @@ class UserSessionManager {
*/
void close_all_sessions();

/**
* @brief Registers a callback fired when a session expires from idle timeout.
* @param cb Invoked with the session's socket, before the session is erased.
*/
void set_on_session_expired(std::function<void(SocketType)> cb);

private:

/** @brief Fired from cleanup_expired_sessions() so Server can tear down the connection. */
std::function<void(SocketType)> on_session_expired;

/**
* @class UserSession
* @brief Represents an individual user's active session state.
Expand Down Expand Up @@ -121,7 +132,8 @@ class UserSessionManager {
void update_last_activity_time();

/**
* @brief Gracefully shuts down and terminates the network session.
* @brief Releases session state. Does not close the socket -
* Server owns socket lifetime and closes it via closeConnection().
*/
void terminate_session();

Expand All @@ -133,6 +145,12 @@ class UserSessionManager {
const std::string& get_ip_str() const { return cached_ip_str; }
const std::string& get_port_str() const { return cached_port_str; }

/**
* @brief Gets the socket owned by this session.
* @return The session's socket.
*/
SocketType get_socket() const { return user_socket; }

private:
SocketType user_socket; /**< The network socket for this specific user. */
std::chrono::steady_clock::time_point last_activity_time; /**< Timestamp of the last recorded user activity. */
Expand Down
2 changes: 1 addition & 1 deletion src/Worker/UserSessionBackgroundWorker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ void UserSessionBackgroundWorker::run() {
if (!active) {
break;
}
std::cout << "UserSessionBackgroundWorker::run()" << std::endl;
std::cout << "[USBM] Running looking for idle connections" << std::endl;
lock.unlock();
this->user_sessions.cleanup_expired_sessions();
}
Expand Down