| 363 | } |
| 364 | |
| 365 | void RestServer::Stop() |
| 366 | { |
| 367 | std::unique_ptr<std::thread> threadToJoin; |
| 368 | bool wasRunning = false; |
| 369 | std::string tempDirToCleanup; |
| 370 | |
| 371 | { |
| 372 | std::lock_guard<std::mutex> lock(m_Mutex); |
| 373 | |
| 374 | wasRunning = m_Running; |
| 375 | |
| 376 | // Signal server to stop accepting connections (idempotent, safe to call always) |
| 377 | // Note: httplib::Server::stop() is safe to call and does not throw. |
| 378 | // It sets an internal flag that causes listen() to return. |
| 379 | if (m_Server) |
| 380 | { |
| 381 | m_Server->stop(); |
| 382 | } |
| 383 | |
| 384 | // Move thread out so we can join outside the lock |
| 385 | threadToJoin = std::move(m_ServerThread); |
| 386 | } |
| 387 | |
| 388 | // Join thread outside of lock to avoid deadlock |
| 389 | // The server thread will exit after listen() returns |
| 390 | if (threadToJoin && threadToJoin->joinable()) |
| 391 | { |
| 392 | threadToJoin->join(); |
| 393 | } |
| 394 | |
| 395 | { |
| 396 | std::lock_guard<std::mutex> lock(m_Mutex); |
| 397 | // Clean up server resources |
| 398 | m_Running = false; |
| 399 | m_RunningConfig = std::nullopt; |
| 400 | m_StartTime = std::nullopt; |
| 401 | m_Server.reset(); |
| 402 | m_HealthController.reset(); |
| 403 | m_DataStorageController.reset(); |
| 404 | m_SwaggerController.reset(); |
| 405 | m_RenderingController.reset(); |
| 406 | |
| 407 | // Clear request tracking, log, and rate limit data |
| 408 | m_ClientIPs.clear(); |
| 409 | m_RequestLog.clear(); |
| 410 | ++m_RequestLogVersion; |
| 411 | m_RateLimitMap.clear(); |
| 412 | m_RateLimitCheckCount = 0; |
| 413 | |
| 414 | // Copy and clear temp directory path while holding the lock |
| 415 | // to prevent race condition if Start() is called concurrently |
| 416 | tempDirToCleanup = std::move(m_TempDirectory); |
| 417 | m_TempDirectory.clear(); |
| 418 | } |
| 419 | |
| 420 | // Clean up temp directory outside lock (may take time) |
| 421 | this->CleanupTempDirectory(tempDirToCleanup); |
| 422 | |