server.h 12 KB

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