server.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. #ifndef SERVER_H
  2. #define SERVER_H
  3. #include <atomic>
  4. #include <functional>
  5. #include <memory>
  6. #include <nlohmann/json.hpp>
  7. #include <string>
  8. #include <thread>
  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 Log HTTP access request
  88. */
  89. void logHttpAccess(const httplib::Request& req, const httplib::Response& res, const std::string& endpoint = "");
  90. /**
  91. * @brief Health check endpoint handler
  92. */
  93. void handleHealthCheck(const httplib::Request& req, httplib::Response& res);
  94. /**
  95. * @brief API status endpoint handler
  96. */
  97. void handleApiStatus(const httplib::Request& req, httplib::Response& res);
  98. /**
  99. * @brief Version information endpoint handler
  100. */
  101. void handleVersion(const httplib::Request& req, httplib::Response& res);
  102. /**
  103. * @brief Models list endpoint handler
  104. */
  105. void handleModelsList(const httplib::Request& req, httplib::Response& res);
  106. /**
  107. * @brief Hash models endpoint handler
  108. */
  109. void handleHashModels(const httplib::Request& req, httplib::Response& res);
  110. /**
  111. * @brief Convert/quantize model endpoint handler
  112. */
  113. void handleConvertModel(const httplib::Request& req, httplib::Response& res);
  114. // Enhanced model management endpoints
  115. /**
  116. * @brief Get detailed information about a specific model
  117. */
  118. void handleModelInfo(const httplib::Request& req, httplib::Response& res);
  119. /**
  120. * @brief Load a specific model by ID
  121. */
  122. void handleLoadModelById(const httplib::Request& req, httplib::Response& res);
  123. /**
  124. * @brief Unload a specific model by ID
  125. */
  126. void handleUnloadModelById(const httplib::Request& req, httplib::Response& res);
  127. /**
  128. * @brief List all available model types
  129. */
  130. void handleModelTypes(const httplib::Request& req, httplib::Response& res);
  131. /**
  132. * @brief List model directories and their contents
  133. */
  134. void handleModelDirectories(const httplib::Request& req, httplib::Response& res);
  135. /**
  136. * @brief Force refresh of model cache
  137. */
  138. void handleRefreshModels(const httplib::Request& req, httplib::Response& res);
  139. /**
  140. * @brief Get statistics about loaded models
  141. */
  142. void handleModelStats(const httplib::Request& req, httplib::Response& res);
  143. /**
  144. * @brief Batch operations on multiple models
  145. */
  146. void handleBatchModels(const httplib::Request& req, httplib::Response& res);
  147. /**
  148. * @brief Validate model files and format
  149. */
  150. void handleValidateModel(const httplib::Request& req, httplib::Response& res);
  151. /**
  152. * @brief Check model compatibility with current configuration
  153. */
  154. void handleCheckCompatibility(const httplib::Request& req, httplib::Response& res);
  155. /**
  156. * @brief Get system requirements for specific models
  157. */
  158. void handleModelRequirements(const httplib::Request& req, httplib::Response& res);
  159. /**
  160. * @brief Queue status endpoint handler
  161. */
  162. void handleQueueStatus(const httplib::Request& req, httplib::Response& res);
  163. /**
  164. * @brief Job status endpoint handler
  165. */
  166. void handleJobStatus(const httplib::Request& req, httplib::Response& res);
  167. /**
  168. * @brief Cancel job endpoint handler
  169. */
  170. void handleCancelJob(const httplib::Request& req, httplib::Response& res);
  171. /**
  172. * @brief Clear queue endpoint handler
  173. */
  174. void handleClearQueue(const httplib::Request& req, httplib::Response& res);
  175. /**
  176. * @brief Download job output file endpoint handler
  177. */
  178. void handleDownloadOutput(const httplib::Request& req, httplib::Response& res);
  179. /**
  180. * @brief Get job output by job ID endpoint handler
  181. */
  182. void handleJobOutput(const httplib::Request& req, httplib::Response& res);
  183. /**
  184. * @brief Get specific job output file by filename endpoint handler
  185. */
  186. void handleJobOutputFile(const httplib::Request& req, httplib::Response& res);
  187. /**
  188. * @brief Download image from URL and return as base64 endpoint handler
  189. */
  190. void handleDownloadImageFromUrl(const httplib::Request& req, httplib::Response& res);
  191. /**
  192. * @brief Resize image endpoint handler
  193. */
  194. void handleImageResize(const httplib::Request& req, httplib::Response& res);
  195. /**
  196. * @brief Crop image endpoint handler
  197. */
  198. void handleImageCrop(const httplib::Request& req, httplib::Response& res);
  199. /**
  200. * @brief Serve temporary image endpoint handler
  201. */
  202. void handleTempImage(const httplib::Request& req, httplib::Response& res);
  203. // Specialized generation endpoints
  204. /**
  205. * @brief Text-to-image generation endpoint handler
  206. */
  207. void handleText2Img(const httplib::Request& req, httplib::Response& res);
  208. /**
  209. * @brief Image-to-image generation endpoint handler
  210. */
  211. void handleImg2Img(const httplib::Request& req, httplib::Response& res);
  212. /**
  213. * @brief ControlNet generation endpoint handler
  214. */
  215. void handleControlNet(const httplib::Request& req, httplib::Response& res);
  216. /**
  217. * @brief Upscaler endpoint handler
  218. */
  219. void handleUpscale(const httplib::Request& req, httplib::Response& res);
  220. /**
  221. * @brief Inpainting endpoint handler
  222. */
  223. void handleInpainting(const httplib::Request& req, httplib::Response& res);
  224. // Utility endpoints
  225. /**
  226. * @brief List available sampling methods endpoint handler
  227. */
  228. void handleSamplers(const httplib::Request& req, httplib::Response& res);
  229. /**
  230. * @brief List available schedulers endpoint handler
  231. */
  232. void handleSchedulers(const httplib::Request& req, httplib::Response& res);
  233. /**
  234. * @brief Get parameter schema and validation rules endpoint handler
  235. */
  236. void handleParameters(const httplib::Request& req, httplib::Response& res);
  237. /**
  238. * @brief Validate generation parameters endpoint handler
  239. */
  240. void handleValidate(const httplib::Request& req, httplib::Response& res);
  241. /**
  242. * @brief Estimate generation time and memory usage endpoint handler
  243. */
  244. void handleEstimate(const httplib::Request& req, httplib::Response& res);
  245. /**
  246. * @brief Get/set server configuration endpoint handler
  247. */
  248. void handleConfig(const httplib::Request& req, httplib::Response& res);
  249. /**
  250. * @brief System information and capabilities endpoint handler
  251. */
  252. void handleSystem(const httplib::Request& req, httplib::Response& res);
  253. /**
  254. * @brief System restart endpoint handler
  255. */
  256. void handleSystemRestart(const httplib::Request& req, httplib::Response& res);
  257. // Authentication endpoint handlers
  258. /**
  259. * @brief Login endpoint handler
  260. */
  261. void handleLogin(const httplib::Request& req, httplib::Response& res);
  262. /**
  263. * @brief Logout endpoint handler
  264. */
  265. void handleLogout(const httplib::Request& req, httplib::Response& res);
  266. /**
  267. * @brief Token validation endpoint handler
  268. */
  269. void handleValidateToken(const httplib::Request& req, httplib::Response& res);
  270. /**
  271. * @brief Token refresh endpoint handler
  272. */
  273. void handleRefreshToken(const httplib::Request& req, httplib::Response& res);
  274. /**
  275. * @brief Get current user endpoint handler
  276. */
  277. void handleGetCurrentUser(const httplib::Request& req, httplib::Response& res);
  278. /**
  279. * @brief Send JSON response with proper headers
  280. */
  281. void sendJsonResponse(httplib::Response& res, const nlohmann::json& json, int status_code = 200);
  282. /**
  283. * @brief Send error response with proper headers
  284. */
  285. void sendErrorResponse(httplib::Response& res, const std::string& message, int status_code = 400, const std::string& error_code = "", const std::string& request_id = "");
  286. /**
  287. * @brief Validate generation parameters
  288. */
  289. std::pair<bool, std::string> validateGenerationParameters(const nlohmann::json& params);
  290. /**
  291. * @brief Parse sampling method from string
  292. */
  293. SamplingMethod parseSamplingMethod(const std::string& method);
  294. /**
  295. * @brief Parse scheduler from string
  296. */
  297. Scheduler parseScheduler(const std::string& scheduler);
  298. /**
  299. * @brief Generate unique request ID
  300. */
  301. std::string generateRequestId();
  302. /**
  303. * @brief Get sampling method as string
  304. */
  305. std::string samplingMethodToString(SamplingMethod method);
  306. /**
  307. * @brief Get scheduler as string
  308. */
  309. std::string schedulerToString(Scheduler scheduler);
  310. /**
  311. * @brief Estimate generation time based on parameters
  312. */
  313. uint64_t estimateGenerationTime(const GenerationRequest& request);
  314. /**
  315. * @brief Estimate memory usage based on parameters
  316. */
  317. size_t estimateMemoryUsage(const GenerationRequest& request);
  318. /**
  319. * @brief Get model capabilities based on type
  320. */
  321. nlohmann::json getModelCapabilities(ModelType type);
  322. /**
  323. * @brief Get statistics for each model type
  324. */
  325. nlohmann::json getModelTypeStatistics();
  326. // Additional helper methods for model management
  327. /**
  328. * @brief Get model compatibility information
  329. */
  330. nlohmann::json getModelCompatibility(const ModelManager::ModelInfo& modelInfo);
  331. /**
  332. * @brief Get model requirements based on type
  333. */
  334. nlohmann::json getModelRequirements(ModelType type);
  335. /**
  336. * @brief Get recommended usage parameters for model type
  337. */
  338. nlohmann::json getRecommendedUsage(ModelType type);
  339. /**
  340. * @brief Load image from base64 or file path
  341. * @return tuple of (data, width, height, channels, success, error_message)
  342. */
  343. std::tuple<std::vector<uint8_t>, int, int, int, bool, std::string>
  344. loadImageFromInput(const std::string& input);
  345. /**
  346. * @brief Get model type from directory name
  347. */
  348. std::string getModelTypeFromDirectoryName(const std::string& dirName);
  349. /**
  350. * @brief Get description for model directory
  351. */
  352. std::string getDirectoryDescription(const std::string& dirName);
  353. /**
  354. * @brief Get contents of a directory
  355. */
  356. nlohmann::json getDirectoryContents(const std::string& dirPath);
  357. /**
  358. * @brief Get largest model from collection
  359. */
  360. nlohmann::json getLargestModel(const std::map<std::string, ModelManager::ModelInfo>& allModels);
  361. /**
  362. * @brief Get smallest model from collection
  363. */
  364. nlohmann::json getSmallestModel(const std::map<std::string, ModelManager::ModelInfo>& allModels);
  365. /**
  366. * @brief Validate model file and format
  367. */
  368. nlohmann::json validateModelFile(const std::string& modelPath, const std::string& modelType);
  369. /**
  370. * @brief Check model compatibility with system
  371. */
  372. nlohmann::json checkModelCompatibility(const ModelManager::ModelInfo& modelInfo, const std::string& systemInfo);
  373. /**
  374. * @brief Calculate specific requirements for model configuration
  375. */
  376. nlohmann::json calculateSpecificRequirements(const std::string& modelType, const std::string& resolution, const std::string& batchSize);
  377. /**
  378. * @brief Convert ModelDetails vector to JSON array
  379. */
  380. nlohmann::json modelDetailsToJson(const std::vector<ModelManager::ModelDetails>& modelDetails);
  381. /**
  382. * @brief Determine which recommended fields to include based on architecture
  383. */
  384. std::map<std::string, bool> getRecommendedModelFields(const std::string& architecture);
  385. /**
  386. * @brief Populate recommended models with existence information
  387. */
  388. void populateRecommendedModels(nlohmann::json& response, const ModelManager::ModelInfo& modelInfo);
  389. /**
  390. * @brief Server thread function
  391. */
  392. void serverThreadFunction(const std::string& host, int port);
  393. ModelManager* m_modelManager; ///< Pointer to model manager
  394. GenerationQueue* m_generationQueue; ///< Pointer to generation queue
  395. std::unique_ptr<httplib::Server> m_httpServer; ///< HTTP server instance
  396. std::thread m_serverThread; ///< Thread for running the server
  397. std::atomic<bool> m_isRunning; ///< Flag indicating if server is running
  398. std::atomic<bool> m_startupFailed; ///< Flag indicating if server startup failed
  399. std::string m_host; ///< Host address
  400. int m_port; ///< Port number
  401. std::string m_outputDir; ///< Output directory for generated files
  402. std::string m_uiDir; ///< Directory containing static web UI files
  403. struct LoadedModels {
  404. std::string checkpoint; ///< Currently loaded checkpoint model (for text2img, img2img, etc.)
  405. std::string esrgan; ///< Currently loaded ESRGAN/upscaler model
  406. };
  407. LoadedModels m_loadedModels; ///< Currently loaded models by type
  408. mutable std::mutex m_loadedModelsMutex; ///< Mutex for thread-safe access to loaded models
  409. std::shared_ptr<UserManager> m_userManager; ///< User manager instance
  410. /**
  411. * @brief Get reference to the appropriate model field based on model type
  412. * @param type The model type
  413. * @return Reference to the model field
  414. */
  415. std::string& getModelField(ModelType type);
  416. std::shared_ptr<AuthMiddleware> m_authMiddleware; ///< Authentication middleware instance
  417. ServerConfig m_config; ///< Server configuration
  418. /**
  419. * @brief Generate thumbnail for image file
  420. *
  421. * @param imagePath Path to the original image file
  422. * @param size Thumbnail size (width and height)
  423. * @return JPEG thumbnail data as string, empty string if failed
  424. */
  425. std::string generateThumbnail(const std::string& imagePath, int size);
  426. };
  427. #endif // SERVER_H