server.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. /**
  170. * @brief Get job output by job ID endpoint handler
  171. */
  172. void handleJobOutput(const httplib::Request& req, httplib::Response& res);
  173. /**
  174. * @brief Download image from URL and return as base64 endpoint handler
  175. */
  176. void handleDownloadImageFromUrl(const httplib::Request& req, httplib::Response& res);
  177. /**
  178. * @brief Resize image endpoint handler
  179. */
  180. void handleImageResize(const httplib::Request& req, httplib::Response& res);
  181. /**
  182. * @brief Crop image endpoint handler
  183. */
  184. void handleImageCrop(const httplib::Request& req, httplib::Response& res);
  185. // Specialized generation endpoints
  186. /**
  187. * @brief Text-to-image generation endpoint handler
  188. */
  189. void handleText2Img(const httplib::Request& req, httplib::Response& res);
  190. /**
  191. * @brief Image-to-image generation endpoint handler
  192. */
  193. void handleImg2Img(const httplib::Request& req, httplib::Response& res);
  194. /**
  195. * @brief ControlNet generation endpoint handler
  196. */
  197. void handleControlNet(const httplib::Request& req, httplib::Response& res);
  198. /**
  199. * @brief Upscaler endpoint handler
  200. */
  201. void handleUpscale(const httplib::Request& req, httplib::Response& res);
  202. /**
  203. * @brief Inpainting endpoint handler
  204. */
  205. void handleInpainting(const httplib::Request& req, httplib::Response& res);
  206. // Utility endpoints
  207. /**
  208. * @brief List available sampling methods endpoint handler
  209. */
  210. void handleSamplers(const httplib::Request& req, httplib::Response& res);
  211. /**
  212. * @brief List available schedulers endpoint handler
  213. */
  214. void handleSchedulers(const httplib::Request& req, httplib::Response& res);
  215. /**
  216. * @brief Get parameter schema and validation rules endpoint handler
  217. */
  218. void handleParameters(const httplib::Request& req, httplib::Response& res);
  219. /**
  220. * @brief Validate generation parameters endpoint handler
  221. */
  222. void handleValidate(const httplib::Request& req, httplib::Response& res);
  223. /**
  224. * @brief Estimate generation time and memory usage endpoint handler
  225. */
  226. void handleEstimate(const httplib::Request& req, httplib::Response& res);
  227. /**
  228. * @brief Get/set server configuration endpoint handler
  229. */
  230. void handleConfig(const httplib::Request& req, httplib::Response& res);
  231. /**
  232. * @brief System information and capabilities endpoint handler
  233. */
  234. void handleSystem(const httplib::Request& req, httplib::Response& res);
  235. /**
  236. * @brief System restart endpoint handler
  237. */
  238. void handleSystemRestart(const httplib::Request& req, httplib::Response& res);
  239. // Authentication endpoint handlers
  240. /**
  241. * @brief Login endpoint handler
  242. */
  243. void handleLogin(const httplib::Request& req, httplib::Response& res);
  244. /**
  245. * @brief Logout endpoint handler
  246. */
  247. void handleLogout(const httplib::Request& req, httplib::Response& res);
  248. /**
  249. * @brief Token validation endpoint handler
  250. */
  251. void handleValidateToken(const httplib::Request& req, httplib::Response& res);
  252. /**
  253. * @brief Token refresh endpoint handler
  254. */
  255. void handleRefreshToken(const httplib::Request& req, httplib::Response& res);
  256. /**
  257. * @brief Get current user endpoint handler
  258. */
  259. void handleGetCurrentUser(const httplib::Request& req, httplib::Response& res);
  260. /**
  261. * @brief Send JSON response with proper headers
  262. */
  263. void sendJsonResponse(httplib::Response& res, const nlohmann::json& json, int status_code = 200);
  264. /**
  265. * @brief Send error response with proper headers
  266. */
  267. void sendErrorResponse(httplib::Response& res, const std::string& message, int status_code = 400,
  268. const std::string& error_code = "", const std::string& request_id = "");
  269. /**
  270. * @brief Validate generation parameters
  271. */
  272. std::pair<bool, std::string> validateGenerationParameters(const nlohmann::json& params);
  273. /**
  274. * @brief Parse sampling method from string
  275. */
  276. SamplingMethod parseSamplingMethod(const std::string& method);
  277. /**
  278. * @brief Parse scheduler from string
  279. */
  280. Scheduler parseScheduler(const std::string& scheduler);
  281. /**
  282. * @brief Generate unique request ID
  283. */
  284. std::string generateRequestId();
  285. /**
  286. * @brief Get sampling method as string
  287. */
  288. std::string samplingMethodToString(SamplingMethod method);
  289. /**
  290. * @brief Get scheduler as string
  291. */
  292. std::string schedulerToString(Scheduler scheduler);
  293. /**
  294. * @brief Estimate generation time based on parameters
  295. */
  296. uint64_t estimateGenerationTime(const GenerationRequest& request);
  297. /**
  298. * @brief Estimate memory usage based on parameters
  299. */
  300. size_t estimateMemoryUsage(const GenerationRequest& request);
  301. /**
  302. * @brief Get model capabilities based on type
  303. */
  304. nlohmann::json getModelCapabilities(ModelType type);
  305. /**
  306. * @brief Get statistics for each model type
  307. */
  308. nlohmann::json getModelTypeStatistics();
  309. // Additional helper methods for model management
  310. /**
  311. * @brief Get model compatibility information
  312. */
  313. nlohmann::json getModelCompatibility(const ModelManager::ModelInfo& modelInfo);
  314. /**
  315. * @brief Get model requirements based on type
  316. */
  317. nlohmann::json getModelRequirements(ModelType type);
  318. /**
  319. * @brief Get recommended usage parameters for model type
  320. */
  321. nlohmann::json getRecommendedUsage(ModelType type);
  322. /**
  323. * @brief Load image from base64 or file path
  324. * @return tuple of (data, width, height, channels, success, error_message)
  325. */
  326. std::tuple<std::vector<uint8_t>, int, int, int, bool, std::string>
  327. loadImageFromInput(const std::string& input);
  328. /**
  329. * @brief Get model type from directory name
  330. */
  331. std::string getModelTypeFromDirectoryName(const std::string& dirName);
  332. /**
  333. * @brief Get description for model directory
  334. */
  335. std::string getDirectoryDescription(const std::string& dirName);
  336. /**
  337. * @brief Get contents of a directory
  338. */
  339. nlohmann::json getDirectoryContents(const std::string& dirPath);
  340. /**
  341. * @brief Get largest model from collection
  342. */
  343. nlohmann::json getLargestModel(const std::map<std::string, ModelManager::ModelInfo>& allModels);
  344. /**
  345. * @brief Get smallest model from collection
  346. */
  347. nlohmann::json getSmallestModel(const std::map<std::string, ModelManager::ModelInfo>& allModels);
  348. /**
  349. * @brief Validate model file and format
  350. */
  351. nlohmann::json validateModelFile(const std::string& modelPath, const std::string& modelType);
  352. /**
  353. * @brief Check model compatibility with system
  354. */
  355. nlohmann::json checkModelCompatibility(const ModelManager::ModelInfo& modelInfo, const std::string& systemInfo);
  356. /**
  357. * @brief Calculate specific requirements for model configuration
  358. */
  359. nlohmann::json calculateSpecificRequirements(const std::string& modelType, const std::string& resolution, const std::string& batchSize);
  360. /**
  361. * @brief Server thread function
  362. */
  363. void serverThreadFunction(const std::string& host, int port);
  364. ModelManager* m_modelManager; ///< Pointer to model manager
  365. GenerationQueue* m_generationQueue; ///< Pointer to generation queue
  366. std::unique_ptr<httplib::Server> m_httpServer; ///< HTTP server instance
  367. std::thread m_serverThread; ///< Thread for running the server
  368. std::atomic<bool> m_isRunning; ///< Flag indicating if server is running
  369. std::atomic<bool> m_startupFailed; ///< Flag indicating if server startup failed
  370. std::string m_host; ///< Host address
  371. int m_port; ///< Port number
  372. std::string m_outputDir; ///< Output directory for generated files
  373. std::string m_uiDir; ///< Directory containing static web UI files
  374. std::string m_currentlyLoadedModel; ///< Currently loaded model name
  375. mutable std::mutex m_currentModelMutex; ///< Mutex for thread-safe access to current model
  376. std::shared_ptr<UserManager> m_userManager; ///< User manager instance
  377. std::shared_ptr<AuthMiddleware> m_authMiddleware; ///< Authentication middleware instance
  378. };
  379. #endif // SERVER_H