server.h 15 KB

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