server.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. #ifndef SERVER_H
  2. #define SERVER_H
  3. #include <memory>
  4. #include <string>
  5. #include <thread>
  6. #include <atomic>
  7. #include <functional>
  8. #include <nlohmann/json.hpp>
  9. #include "generation_queue.h"
  10. #include "model_manager.h"
  11. // Forward declarations
  12. class ModelManager;
  13. class GenerationQueue;
  14. class UserManager;
  15. class AuthMiddleware;
  16. namespace httplib {
  17. class Server;
  18. class Request;
  19. class Response;
  20. }
  21. /**
  22. * @brief HTTP server class for handling REST API requests
  23. *
  24. * This class implements the HTTP server that exposes the stable-diffusion.cpp
  25. * functionality through a REST API. It handles incoming requests, validates
  26. * parameters, and coordinates with the model manager and generation queue.
  27. * The server runs in a separate thread to handle HTTP requests independently
  28. * from the generation process.
  29. */
  30. class Server {
  31. public:
  32. /**
  33. * @brief Construct a new Server object
  34. *
  35. * @param modelManager Pointer to the model manager instance
  36. * @param generationQueue Pointer to the generation queue instance
  37. * @param outputDir Directory where generated output files are stored
  38. * @param uiDir Directory containing static web UI files (optional)
  39. */
  40. Server(ModelManager* modelManager, GenerationQueue* generationQueue, const std::string& outputDir = "./output", const std::string& uiDir = "");
  41. /**
  42. * @brief Destroy the Server object
  43. */
  44. virtual ~Server();
  45. /**
  46. * @brief Start the HTTP server
  47. *
  48. * @param host The host address to bind to
  49. * @param port The port number to listen on
  50. * @return true if the server started successfully, false otherwise
  51. */
  52. bool start(const std::string& host = "0.0.0.0", int port = 8080);
  53. /**
  54. * @brief Stop the HTTP server
  55. */
  56. void stop();
  57. /**
  58. * @brief Check if the server is running
  59. *
  60. * @return true if the server is running, false otherwise
  61. */
  62. bool isRunning() const;
  63. /**
  64. * @brief Wait for the server thread to finish
  65. */
  66. void waitForStop();
  67. /**
  68. * @brief Set authentication components
  69. */
  70. void setAuthComponents(std::shared_ptr<UserManager> userManager, std::shared_ptr<AuthMiddleware> authMiddleware);
  71. private:
  72. /**
  73. * @brief Register all API endpoints
  74. */
  75. void registerEndpoints();
  76. /**
  77. * @brief Register authentication endpoints
  78. */
  79. void registerAuthEndpoints();
  80. /**
  81. * @brief Set up CORS headers for responses
  82. */
  83. void setupCORS();
  84. /**
  85. * @brief Health check endpoint handler
  86. */
  87. void handleHealthCheck(const httplib::Request& req, httplib::Response& res);
  88. /**
  89. * @brief API status endpoint handler
  90. */
  91. void handleApiStatus(const httplib::Request& req, httplib::Response& res);
  92. /**
  93. * @brief Models list endpoint handler
  94. */
  95. void handleModelsList(const httplib::Request& req, httplib::Response& res);
  96. /**
  97. * @brief Hash models endpoint handler
  98. */
  99. void handleHashModels(const httplib::Request& req, httplib::Response& res);
  100. /**
  101. * @brief Convert/quantize model endpoint handler
  102. */
  103. void handleConvertModel(const httplib::Request& req, httplib::Response& res);
  104. // Enhanced model management endpoints
  105. /**
  106. * @brief Get detailed information about a specific model
  107. */
  108. void handleModelInfo(const httplib::Request& req, httplib::Response& res);
  109. /**
  110. * @brief Load a specific model by ID
  111. */
  112. void handleLoadModelById(const httplib::Request& req, httplib::Response& res);
  113. /**
  114. * @brief Unload a specific model by ID
  115. */
  116. void handleUnloadModelById(const httplib::Request& req, httplib::Response& res);
  117. /**
  118. * @brief List all available model types
  119. */
  120. void handleModelTypes(const httplib::Request& req, httplib::Response& res);
  121. /**
  122. * @brief List model directories and their contents
  123. */
  124. void handleModelDirectories(const httplib::Request& req, httplib::Response& res);
  125. /**
  126. * @brief Force refresh of model cache
  127. */
  128. void handleRefreshModels(const httplib::Request& req, httplib::Response& res);
  129. /**
  130. * @brief Get statistics about loaded models
  131. */
  132. void handleModelStats(const httplib::Request& req, httplib::Response& res);
  133. /**
  134. * @brief Batch operations on multiple models
  135. */
  136. void handleBatchModels(const httplib::Request& req, httplib::Response& res);
  137. /**
  138. * @brief Validate model files and format
  139. */
  140. void handleValidateModel(const httplib::Request& req, httplib::Response& res);
  141. /**
  142. * @brief Check model compatibility with current configuration
  143. */
  144. void handleCheckCompatibility(const httplib::Request& req, httplib::Response& res);
  145. /**
  146. * @brief Get system requirements for specific models
  147. */
  148. void handleModelRequirements(const httplib::Request& req, httplib::Response& res);
  149. /**
  150. * @brief Queue status endpoint handler
  151. */
  152. void handleQueueStatus(const httplib::Request& req, httplib::Response& res);
  153. /**
  154. * @brief Job status endpoint handler
  155. */
  156. void handleJobStatus(const httplib::Request& req, httplib::Response& res);
  157. /**
  158. * @brief Cancel job endpoint handler
  159. */
  160. void handleCancelJob(const httplib::Request& req, httplib::Response& res);
  161. /**
  162. * @brief Clear queue endpoint handler
  163. */
  164. void handleClearQueue(const httplib::Request& req, httplib::Response& res);
  165. /**
  166. * @brief Download job output file endpoint handler
  167. */
  168. void handleDownloadOutput(const httplib::Request& req, httplib::Response& res);
  169. // Specialized generation endpoints
  170. /**
  171. * @brief Text-to-image generation endpoint handler
  172. */
  173. void handleText2Img(const httplib::Request& req, httplib::Response& res);
  174. /**
  175. * @brief Image-to-image generation endpoint handler
  176. */
  177. void handleImg2Img(const httplib::Request& req, httplib::Response& res);
  178. /**
  179. * @brief ControlNet generation endpoint handler
  180. */
  181. void handleControlNet(const httplib::Request& req, httplib::Response& res);
  182. /**
  183. * @brief Upscaler endpoint handler
  184. */
  185. void handleUpscale(const httplib::Request& req, httplib::Response& res);
  186. /**
  187. * @brief Inpainting endpoint handler
  188. */
  189. void handleInpainting(const httplib::Request& req, httplib::Response& res);
  190. // Utility endpoints
  191. /**
  192. * @brief List available sampling methods endpoint handler
  193. */
  194. void handleSamplers(const httplib::Request& req, httplib::Response& res);
  195. /**
  196. * @brief List available schedulers endpoint handler
  197. */
  198. void handleSchedulers(const httplib::Request& req, httplib::Response& res);
  199. /**
  200. * @brief Get parameter schema and validation rules endpoint handler
  201. */
  202. void handleParameters(const httplib::Request& req, httplib::Response& res);
  203. /**
  204. * @brief Validate generation parameters endpoint handler
  205. */
  206. void handleValidate(const httplib::Request& req, httplib::Response& res);
  207. /**
  208. * @brief Estimate generation time and memory usage endpoint handler
  209. */
  210. void handleEstimate(const httplib::Request& req, httplib::Response& res);
  211. /**
  212. * @brief Get/set server configuration endpoint handler
  213. */
  214. void handleConfig(const httplib::Request& req, httplib::Response& res);
  215. /**
  216. * @brief System information and capabilities endpoint handler
  217. */
  218. void handleSystem(const httplib::Request& req, httplib::Response& res);
  219. /**
  220. * @brief System restart endpoint handler
  221. */
  222. void handleSystemRestart(const httplib::Request& req, httplib::Response& res);
  223. // Authentication endpoint handlers
  224. /**
  225. * @brief Login endpoint handler
  226. */
  227. void handleLogin(const httplib::Request& req, httplib::Response& res);
  228. /**
  229. * @brief Logout endpoint handler
  230. */
  231. void handleLogout(const httplib::Request& req, httplib::Response& res);
  232. /**
  233. * @brief Token validation endpoint handler
  234. */
  235. void handleValidateToken(const httplib::Request& req, httplib::Response& res);
  236. /**
  237. * @brief Token refresh endpoint handler
  238. */
  239. void handleRefreshToken(const httplib::Request& req, httplib::Response& res);
  240. /**
  241. * @brief Get current user endpoint handler
  242. */
  243. void handleGetCurrentUser(const httplib::Request& req, httplib::Response& res);
  244. /**
  245. * @brief Send JSON response with proper headers
  246. */
  247. void sendJsonResponse(httplib::Response& res, const nlohmann::json& json, int status_code = 200);
  248. /**
  249. * @brief Send error response with proper headers
  250. */
  251. void sendErrorResponse(httplib::Response& res, const std::string& message, int status_code = 400,
  252. const std::string& error_code = "", const std::string& request_id = "");
  253. /**
  254. * @brief Validate generation parameters
  255. */
  256. std::pair<bool, std::string> validateGenerationParameters(const nlohmann::json& params);
  257. /**
  258. * @brief Parse sampling method from string
  259. */
  260. SamplingMethod parseSamplingMethod(const std::string& method);
  261. /**
  262. * @brief Parse scheduler from string
  263. */
  264. Scheduler parseScheduler(const std::string& scheduler);
  265. /**
  266. * @brief Generate unique request ID
  267. */
  268. std::string generateRequestId();
  269. /**
  270. * @brief Get sampling method as string
  271. */
  272. std::string samplingMethodToString(SamplingMethod method);
  273. /**
  274. * @brief Get scheduler as string
  275. */
  276. std::string schedulerToString(Scheduler scheduler);
  277. /**
  278. * @brief Estimate generation time based on parameters
  279. */
  280. uint64_t estimateGenerationTime(const GenerationRequest& request);
  281. /**
  282. * @brief Estimate memory usage based on parameters
  283. */
  284. size_t estimateMemoryUsage(const GenerationRequest& request);
  285. /**
  286. * @brief Get model capabilities based on type
  287. */
  288. nlohmann::json getModelCapabilities(ModelType type);
  289. /**
  290. * @brief Get statistics for each model type
  291. */
  292. nlohmann::json getModelTypeStatistics();
  293. // Additional helper methods for model management
  294. /**
  295. * @brief Get model compatibility information
  296. */
  297. nlohmann::json getModelCompatibility(const ModelManager::ModelInfo& modelInfo);
  298. /**
  299. * @brief Get model requirements based on type
  300. */
  301. nlohmann::json getModelRequirements(ModelType type);
  302. /**
  303. * @brief Get recommended usage parameters for model type
  304. */
  305. nlohmann::json getRecommendedUsage(ModelType type);
  306. /**
  307. * @brief Load image from base64 or file path
  308. * @return tuple of (data, width, height, channels, success, error_message)
  309. */
  310. std::tuple<std::vector<uint8_t>, int, int, int, bool, std::string>
  311. loadImageFromInput(const std::string& input);
  312. /**
  313. * @brief Get model type from directory name
  314. */
  315. std::string getModelTypeFromDirectoryName(const std::string& dirName);
  316. /**
  317. * @brief Get description for model directory
  318. */
  319. std::string getDirectoryDescription(const std::string& dirName);
  320. /**
  321. * @brief Get contents of a directory
  322. */
  323. nlohmann::json getDirectoryContents(const std::string& dirPath);
  324. /**
  325. * @brief Get largest model from collection
  326. */
  327. nlohmann::json getLargestModel(const std::map<std::string, ModelManager::ModelInfo>& allModels);
  328. /**
  329. * @brief Get smallest model from collection
  330. */
  331. nlohmann::json getSmallestModel(const std::map<std::string, ModelManager::ModelInfo>& allModels);
  332. /**
  333. * @brief Validate model file and format
  334. */
  335. nlohmann::json validateModelFile(const std::string& modelPath, const std::string& modelType);
  336. /**
  337. * @brief Check model compatibility with system
  338. */
  339. nlohmann::json checkModelCompatibility(const ModelManager::ModelInfo& modelInfo, const std::string& systemInfo);
  340. /**
  341. * @brief Calculate specific requirements for model configuration
  342. */
  343. nlohmann::json calculateSpecificRequirements(const std::string& modelType, const std::string& resolution, const std::string& batchSize);
  344. /**
  345. * @brief Server thread function
  346. */
  347. void serverThreadFunction(const std::string& host, int port);
  348. ModelManager* m_modelManager; ///< Pointer to model manager
  349. GenerationQueue* m_generationQueue; ///< Pointer to generation queue
  350. std::unique_ptr<httplib::Server> m_httpServer; ///< HTTP server instance
  351. std::thread m_serverThread; ///< Thread for running the server
  352. std::atomic<bool> m_isRunning; ///< Flag indicating if server is running
  353. std::atomic<bool> m_startupFailed; ///< Flag indicating if server startup failed
  354. std::string m_host; ///< Host address
  355. int m_port; ///< Port number
  356. std::string m_outputDir; ///< Output directory for generated files
  357. std::string m_uiDir; ///< Directory containing static web UI files
  358. std::string m_currentlyLoadedModel; ///< Currently loaded model name
  359. mutable std::mutex m_currentModelMutex; ///< Mutex for thread-safe access to current model
  360. std::shared_ptr<UserManager> m_userManager; ///< User manager instance
  361. std::shared_ptr<AuthMiddleware> m_authMiddleware; ///< Authentication middleware instance
  362. };
  363. #endif // SERVER_H