server-queue.h 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. #pragma once
  2. #include "server-task.h"
  3. #include <condition_variable>
  4. #include <deque>
  5. #include <mutex>
  6. #include <vector>
  7. #include <unordered_set>
  8. // struct for managing server tasks
  9. // in most cases, use server_response_reader to post new tasks and retrieve results
  10. struct server_queue {
  11. private:
  12. int id = 0;
  13. bool running = false;
  14. bool sleeping = false;
  15. bool req_stop_sleeping = false;
  16. int64_t time_last_task = 0;
  17. // queues
  18. std::deque<server_task> queue_tasks;
  19. std::deque<server_task> queue_tasks_deferred;
  20. std::mutex mutex_tasks;
  21. std::condition_variable condition_tasks;
  22. // callback functions
  23. std::function<void(server_task &&)> callback_new_task;
  24. std::function<void(void)> callback_update_slots;
  25. std::function<void(bool)> callback_sleeping_state;
  26. public:
  27. // Add a new task to the end of the queue
  28. int post(server_task && task, bool front = false);
  29. // multi-task version of post()
  30. int post(std::vector<server_task> && tasks, bool front = false);
  31. // Add a new task, but defer until one slot is available
  32. void defer(server_task && task);
  33. // Get the next id for creating a new task
  34. int get_new_id();
  35. // Call when the state of one slot is changed, it will move one task from deferred to main queue
  36. void pop_deferred_task();
  37. // if sleeping, request exiting sleep state and wait until it is done
  38. // returns immediately if not sleeping
  39. void wait_until_no_sleep();
  40. bool is_sleeping() {
  41. std::unique_lock<std::mutex> lock(mutex_tasks);
  42. return sleeping;
  43. }
  44. // end the start_loop routine
  45. void terminate();
  46. /**
  47. * Main loop consists of these steps:
  48. * - Wait until a new task arrives
  49. * - Process the task (i.e. maybe copy data into slot)
  50. * - Check if multitask is finished
  51. * - Update all slots
  52. *
  53. * Sleeping procedure (disabled if idle_sleep_ms < 0):
  54. * - If there is no task after idle_sleep_ms, enter sleeping state
  55. * - Call callback_sleeping_state(true)
  56. * - Wait until req_stop_sleeping is set to true
  57. * - Call callback_sleeping_state(false)
  58. * - Exit sleeping state
  59. */
  60. void start_loop(int64_t idle_sleep_ms = -1);
  61. // for metrics
  62. size_t queue_tasks_deferred_size() {
  63. std::unique_lock<std::mutex> lock(mutex_tasks);
  64. return queue_tasks_deferred.size();
  65. }
  66. //
  67. // Functions below are not thread-safe, must only be used before start_loop() is called
  68. //
  69. // Register function to process a new task
  70. void on_new_task(std::function<void(server_task &&)> callback) {
  71. callback_new_task = std::move(callback);
  72. }
  73. // Register the function to be called when all slots data is ready to be processed
  74. void on_update_slots(std::function<void(void)> callback) {
  75. callback_update_slots = std::move(callback);
  76. }
  77. // Register callback for sleeping state change
  78. // note: when entering sleeping state, the callback is called AFTER sleeping is set to true
  79. // when leaving sleeping state, the callback is called BEFORE sleeping is set to false
  80. void on_sleeping_state(std::function<void(bool)> callback) {
  81. callback_sleeping_state = std::move(callback);
  82. }
  83. private:
  84. void cleanup_pending_task(int id_target);
  85. };
  86. // struct for managing server responses
  87. // in most cases, use server_response_reader to retrieve results
  88. struct server_response {
  89. private:
  90. bool running = true;
  91. // for keeping track of all tasks waiting for the result
  92. std::unordered_set<int> waiting_task_ids;
  93. // the main result queue (using ptr for polymorphism)
  94. std::vector<server_task_result_ptr> queue_results;
  95. std::mutex mutex_results;
  96. std::condition_variable condition_results;
  97. public:
  98. // add the id_task to the list of tasks waiting for response
  99. void add_waiting_task_id(int id_task);
  100. void add_waiting_tasks(const std::vector<server_task> & tasks);
  101. // when the request is finished, we can remove task associated with it
  102. void remove_waiting_task_id(int id_task);
  103. // remove multiple tasks from waiting list
  104. void remove_waiting_task_ids(const std::unordered_set<int> & id_tasks);
  105. // This function blocks the thread until there is a response for one of the id_tasks
  106. server_task_result_ptr recv(const std::unordered_set<int> & id_tasks);
  107. // same as recv(), but have timeout in seconds
  108. // if timeout is reached, nullptr is returned
  109. server_task_result_ptr recv_with_timeout(const std::unordered_set<int> & id_tasks, int timeout);
  110. // single-task version of recv()
  111. server_task_result_ptr recv(int id_task);
  112. // Send a new result to a waiting id_task
  113. void send(server_task_result_ptr && result);
  114. // terminate the waiting loop
  115. void terminate();
  116. };
  117. // utility class to make working with server_queue and server_response easier
  118. // it provides a generator-like API for server responses
  119. // support pooling connection state and aggregating multiple results
  120. struct server_response_reader {
  121. std::unordered_set<int> id_tasks;
  122. server_queue & queue_tasks;
  123. server_response & queue_results;
  124. size_t received_count = 0;
  125. bool cancelled = false;
  126. int polling_interval_seconds;
  127. // tracking generation state and partial tool calls
  128. // only used by streaming completions
  129. std::vector<task_result_state> states;
  130. // should_stop function will be called each polling_interval_seconds
  131. server_response_reader(server_queue & queue_tasks, server_response & queue_results, int polling_interval_seconds)
  132. : queue_tasks(queue_tasks), queue_results(queue_results), polling_interval_seconds(polling_interval_seconds) {}
  133. ~server_response_reader() {
  134. stop();
  135. }
  136. int get_new_id() {
  137. return queue_tasks.get_new_id();
  138. }
  139. // if front = true, the task will be posted to the front of the queue (high priority)
  140. void post_task(server_task && task, bool front = false);
  141. void post_tasks(std::vector<server_task> && tasks, bool front = false);
  142. bool has_next() const;
  143. // return nullptr if should_stop() is true before receiving a result
  144. // note: if one error is received, it will stop further processing and return error result
  145. server_task_result_ptr next(const std::function<bool()> & should_stop);
  146. struct batch_response {
  147. bool is_terminated = false; // if true, indicates that processing was stopped before all results were received
  148. std::vector<server_task_result_ptr> results;
  149. server_task_result_ptr error; // nullptr if no error
  150. };
  151. // aggregate multiple results
  152. batch_response wait_for_all(const std::function<bool()> & should_stop);
  153. void stop();
  154. };