pool.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. #pragma once
  2. #include <iostream>
  3. #include <mutex>
  4. #include <memory>
  5. #include <thread>
  6. #include <atomic>
  7. #include <condition_variable>
  8. #include <vector>
  9. #include <deque>
  10. #include <algorithm>
  11. #include <cmath>
  12. #include <chrono>
  13. #include <optional>
  14. #include "base/error.h"
  15. #include "base/exception.h"
  16. #include "util/time.h"
  17. namespace ylib {
  18. class example_core{
  19. public:
  20. virtual void recover() = 0;
  21. virtual void task_out() = 0;
  22. };
  23. class poolcore:public ylib::error_base
  24. {
  25. public:
  26. virtual ~poolcore() = default;
  27. virtual void recover(void* example) = 0;
  28. public:
  29. void* env = nullptr;
  30. protected:
  31. std::mutex m_mutex;
  32. bool m_closing = false;
  33. size_t m_max_size = 0;
  34. size_t m_pop_size = 0; // 当前借出(使用中)数量
  35. };
  36. enum EXAMPLE_START_RESULT
  37. {
  38. SR_SUCCESS,
  39. SR_TIMEOUT,
  40. SR_FAILED,
  41. };
  42. template<typename INFO>
  43. class example:public example_core
  44. {
  45. public:
  46. public:
  47. example()
  48. {
  49. m_pool = nullptr;
  50. }
  51. virtual EXAMPLE_START_RESULT start(const INFO& info) = 0;
  52. virtual void close() = 0;
  53. inline void pool(poolcore *pool)
  54. {
  55. m_pool = pool;
  56. }
  57. inline poolcore *pool()
  58. {
  59. return m_pool;
  60. }
  61. protected:
  62. poolcore *m_pool;
  63. };
  64. /**
  65. * @brief 连接池连接自动归还(可移动,不可拷贝)
  66. */
  67. template<typename EXAMPLE>
  68. class conn_autofree
  69. {
  70. public:
  71. explicit conn_autofree(EXAMPLE* conn = nullptr) : m_conn(conn) {}
  72. conn_autofree(const conn_autofree&) = delete;
  73. conn_autofree& operator=(const conn_autofree&) = delete;
  74. conn_autofree(conn_autofree&& other) noexcept : m_conn(other.m_conn)
  75. {
  76. other.m_conn = nullptr;
  77. }
  78. conn_autofree& operator=(conn_autofree&& other) noexcept
  79. {
  80. if (this != &other) {
  81. release();
  82. m_conn = other.m_conn;
  83. other.m_conn = nullptr;
  84. }
  85. return *this;
  86. }
  87. ~conn_autofree()
  88. {
  89. release();
  90. }
  91. EXAMPLE* operator->() const { return m_conn; }
  92. EXAMPLE* get() const { return m_conn; }
  93. explicit operator bool() const { return m_conn != nullptr; }
  94. bool empty() const { return m_conn == nullptr; }
  95. void reset() { release(); }
  96. private:
  97. void release()
  98. {
  99. if (m_conn == nullptr) {
  100. return;
  101. }
  102. if (m_conn->pool() != nullptr) {
  103. m_conn->pool()->recover(m_conn);
  104. }
  105. m_conn = nullptr;
  106. }
  107. EXAMPLE* m_conn = nullptr;
  108. };
  109. /// 连接池增量配置:只填需要覆盖的项,未填项使用默认值
  110. struct pool_options
  111. {
  112. std::optional<size_t> max_size; // 默认 50
  113. std::optional<size_t> min_size; // 默认 2
  114. std::optional<uint32> idle_timeout_sec; // 默认 60;0=不按空闲超时释放
  115. std::optional<uint32> shrink_interval_sec; // 默认 5
  116. std::optional<uint32> usage_window_sec; // 默认 30
  117. std::optional<double> shrink_threshold; // 默认 0.5
  118. std::optional<double> shrink_headroom; // 默认 2.0
  119. std::optional<bool> enable_auto_shrink; // 默认 true
  120. };
  121. /// 解析后实际生效的连接池配置
  122. struct pool_config
  123. {
  124. size_t max_size = 50;
  125. size_t min_size = 2;
  126. uint32 idle_timeout_sec = 60;
  127. uint32 shrink_interval_sec = 5;
  128. uint32 usage_window_sec = 30;
  129. double shrink_threshold = 0.5;
  130. double shrink_headroom = 2.0;
  131. bool enable_auto_shrink = true;
  132. };
  133. inline pool_config make_pool_config(const pool_options& opt = {})
  134. {
  135. pool_config c;
  136. if (opt.max_size) c.max_size = *opt.max_size;
  137. if (opt.min_size) c.min_size = *opt.min_size;
  138. if (opt.idle_timeout_sec) c.idle_timeout_sec = *opt.idle_timeout_sec;
  139. if (opt.shrink_interval_sec) c.shrink_interval_sec = *opt.shrink_interval_sec;
  140. if (opt.usage_window_sec) c.usage_window_sec = *opt.usage_window_sec;
  141. if (opt.shrink_threshold) c.shrink_threshold = *opt.shrink_threshold;
  142. if (opt.shrink_headroom) c.shrink_headroom = *opt.shrink_headroom;
  143. if (opt.enable_auto_shrink) c.enable_auto_shrink = *opt.enable_auto_shrink;
  144. // 仅做结构约束,不覆盖调用方已给出的业务参数
  145. if (c.max_size < 1)
  146. c.max_size = 1;
  147. if (c.min_size > c.max_size)
  148. c.min_size = c.max_size;
  149. if (c.shrink_interval_sec < 1)
  150. c.shrink_interval_sec = 1;
  151. if (c.usage_window_sec < 1)
  152. c.usage_window_sec = 1;
  153. if (c.shrink_headroom < 1.0)
  154. c.shrink_headroom = 1.0;
  155. return c;
  156. }
  157. template<typename EXAMPLE,typename INFO>
  158. class pool :public poolcore
  159. {
  160. private:
  161. struct idle_entry
  162. {
  163. void* example = nullptr;
  164. timestamp idle_since_msec = 0;
  165. };
  166. public:
  167. pool()
  168. {
  169. m_max_size = 0;
  170. m_pop_size = 0;
  171. m_closing = false;
  172. m_alive_size = 0;
  173. }
  174. ~pool()
  175. {
  176. close();
  177. }
  178. /// 全部使用默认配置
  179. bool start(const INFO& info)
  180. {
  181. return start(info, pool_options{});
  182. }
  183. /// 仅覆盖 max_size,其余默认
  184. bool start(const INFO& info, size_t max_size)
  185. {
  186. pool_options opt;
  187. opt.max_size = max_size;
  188. return start(info, opt);
  189. }
  190. /// 增量配置:opt 里写了的字段生效,没写的用默认值
  191. bool start(const INFO& info, const pool_options& opt)
  192. {
  193. close();
  194. {
  195. std::unique_lock<std::mutex> sp(m_mutex);
  196. m_closing = false;
  197. m_info = info;
  198. m_opt = make_pool_config(opt);
  199. m_max_size = m_opt.max_size;
  200. m_pop_size = 0;
  201. m_alive_size = 0;
  202. m_idle.clear();
  203. m_usage_buckets.assign(m_opt.usage_window_sec, 0);
  204. m_usage_bucket_idx = 0;
  205. m_usage_bucket_sec = 0;
  206. }
  207. // 预热到最低维持数量(创建时不长时间占锁)
  208. for (size_t i = 0; i < m_opt.min_size; ++i)
  209. {
  210. EXAMPLE* ex = create_example();
  211. if (!ex)
  212. break;
  213. std::unique_lock<std::mutex> sp(m_mutex);
  214. if (m_closing)
  215. {
  216. sp.unlock();
  217. destroy_example(ex);
  218. break;
  219. }
  220. m_idle.push_back(idle_entry{ ex, ylib::time::now_msec() });
  221. m_alive_size++;
  222. }
  223. if (m_opt.enable_auto_shrink)
  224. {
  225. m_shrink_stop = false;
  226. m_shrink_thread = std::thread([this]() { shrink_loop(); });
  227. }
  228. return true;
  229. }
  230. void close()
  231. {
  232. {
  233. std::unique_lock<std::mutex> sp(m_mutex);
  234. m_closing = true;
  235. m_shrink_stop = true;
  236. }
  237. m_shrink_cv.notify_all();
  238. if (m_shrink_thread.joinable())
  239. m_shrink_thread.join();
  240. std::vector<void*> doomed;
  241. {
  242. std::unique_lock<std::mutex> sp(m_mutex);
  243. doomed.reserve(m_idle.size());
  244. for (auto& e : m_idle)
  245. doomed.push_back(e.example);
  246. m_idle.clear();
  247. m_alive_size = 0;
  248. m_pop_size = 0;
  249. }
  250. for (void* p : doomed)
  251. destroy_example(p);
  252. }
  253. void* get_ptr() { return (void*)get(); }
  254. EXAMPLE* get()
  255. {
  256. std::vector<void*> doomed;
  257. EXAMPLE* result = nullptr;
  258. {
  259. std::unique_lock<std::mutex> sp(m_mutex);
  260. if (m_closing)
  261. throw ylib::exception("pool is shutting down");
  262. collect_idle_timeout_unlocked(doomed);
  263. if (!m_idle.empty())
  264. {
  265. idle_entry entry = m_idle.front();
  266. m_idle.pop_front();
  267. m_pop_size++;
  268. note_usage_unlocked(m_pop_size);
  269. result = (EXAMPLE*)entry.example;
  270. result->pool(this);
  271. }
  272. else if (m_alive_size < m_max_size)
  273. {
  274. // 先占名额,锁外创建,失败再回滚
  275. m_alive_size++;
  276. m_pop_size++;
  277. note_usage_unlocked(m_pop_size);
  278. sp.unlock();
  279. for (void* p : doomed)
  280. destroy_example(p);
  281. doomed.clear();
  282. EXAMPLE* ex = create_example();
  283. if (!ex)
  284. {
  285. std::unique_lock<std::mutex> sp2(m_mutex);
  286. if (m_alive_size > 0) m_alive_size--;
  287. if (m_pop_size > 0) m_pop_size--;
  288. throw ylib::exception(m_lastErrorDesc.empty() ? "create connection failed" : m_lastErrorDesc);
  289. }
  290. ex->task_out();
  291. return ex;
  292. }
  293. else
  294. {
  295. sp.unlock();
  296. for (void* p : doomed)
  297. destroy_example(p);
  298. throw ylib::exception("maximum capacity exceeded");
  299. }
  300. }
  301. for (void* p : doomed)
  302. destroy_example(p);
  303. result->task_out();
  304. return result;
  305. }
  306. void recover(void* example) override
  307. {
  308. if (example == NULL)
  309. return;
  310. ((ylib::example_core*)example)->recover();
  311. std::vector<void*> doomed;
  312. {
  313. std::unique_lock<std::mutex> sp(m_mutex);
  314. if (m_pop_size > 0)
  315. m_pop_size--;
  316. if (m_closing)
  317. {
  318. if (m_alive_size > 0)
  319. m_alive_size--;
  320. doomed.push_back(example);
  321. }
  322. else
  323. {
  324. m_idle.push_back(idle_entry{ example, ylib::time::now_msec() });
  325. collect_shrink_unlocked(doomed);
  326. }
  327. }
  328. for (void* p : doomed)
  329. destroy_example(p);
  330. }
  331. /// 空闲连接数
  332. size_t idle_size()
  333. {
  334. std::unique_lock<std::mutex> sp(m_mutex);
  335. return m_idle.size();
  336. }
  337. /// 使用中连接数
  338. size_t busy_size()
  339. {
  340. std::unique_lock<std::mutex> sp(m_mutex);
  341. return m_pop_size;
  342. }
  343. /// 已建立连接总数
  344. size_t alive_size()
  345. {
  346. std::unique_lock<std::mutex> sp(m_mutex);
  347. return m_alive_size;
  348. }
  349. /// 兼容旧接口:剩余可借出容量
  350. size_t size()
  351. {
  352. std::unique_lock<std::mutex> sp(m_mutex);
  353. if (m_max_size < m_pop_size)
  354. return 0;
  355. return m_max_size - m_pop_size;
  356. }
  357. /// 当前生效配置(已与默认值合并)
  358. const pool_config& options() const { return m_opt; }
  359. public:
  360. INFO m_info;
  361. private:
  362. EXAMPLE* create_example()
  363. {
  364. EXAMPLE* ex = new EXAMPLE;
  365. ex->pool(this);
  366. bool init_success = false;
  367. for (uint32 i = 0; i < 3; i++)
  368. {
  369. auto SR = ex->start(m_info);
  370. if (SR == SR_SUCCESS)
  371. {
  372. init_success = true;
  373. break;
  374. }
  375. else if (SR == SR_TIMEOUT)
  376. {
  377. std::cout << "start failed." << ex->last_error().c_str() << std::endl;
  378. std::cout << "restart " << std::to_string(i + 1).c_str() << "." << std::endl;
  379. }
  380. else if (SR == SR_FAILED)
  381. {
  382. break;
  383. }
  384. }
  385. if (!init_success)
  386. {
  387. m_lastErrorDesc = ex->last_error();
  388. delete ex;
  389. return nullptr;
  390. }
  391. return ex;
  392. }
  393. void destroy_example(void* example)
  394. {
  395. if (!example)
  396. return;
  397. EXAMPLE* ex = (EXAMPLE*)example;
  398. try
  399. {
  400. ex->pool(nullptr);
  401. ex->close();
  402. }
  403. catch (...)
  404. {
  405. }
  406. delete ex;
  407. }
  408. void note_usage_unlocked(size_t in_use)
  409. {
  410. const size_t window = m_usage_buckets.empty() ? 1 : m_usage_buckets.size();
  411. timestamp sec = ylib::time::now_msec() / 1000;
  412. if (m_usage_bucket_sec == 0)
  413. {
  414. m_usage_bucket_sec = sec;
  415. m_usage_buckets.assign(window, 0);
  416. m_usage_bucket_idx = 0;
  417. }
  418. while (sec > m_usage_bucket_sec)
  419. {
  420. m_usage_bucket_idx = (m_usage_bucket_idx + 1) % window;
  421. m_usage_buckets[m_usage_bucket_idx] = 0;
  422. m_usage_bucket_sec++;
  423. if (sec > m_usage_bucket_sec && (sec - m_usage_bucket_sec) >= (timestamp)window)
  424. {
  425. std::fill(m_usage_buckets.begin(), m_usage_buckets.end(), 0);
  426. m_usage_bucket_sec = sec;
  427. m_usage_bucket_idx = 0;
  428. break;
  429. }
  430. }
  431. if (in_use > m_usage_buckets[m_usage_bucket_idx])
  432. m_usage_buckets[m_usage_bucket_idx] = in_use;
  433. }
  434. size_t usage_peak_unlocked() const
  435. {
  436. size_t peak = 0;
  437. for (size_t v : m_usage_buckets)
  438. {
  439. if (v > peak)
  440. peak = v;
  441. }
  442. if (m_pop_size > peak)
  443. peak = m_pop_size;
  444. return peak;
  445. }
  446. void collect_idle_timeout_unlocked(std::vector<void*>& doomed)
  447. {
  448. if (m_opt.idle_timeout_sec == 0)
  449. return;
  450. const timestamp now = ylib::time::now_msec();
  451. const timestamp timeout_msec = (timestamp)m_opt.idle_timeout_sec * 1000;
  452. while (m_alive_size > m_opt.min_size && !m_idle.empty())
  453. {
  454. if (now - m_idle.front().idle_since_msec < timeout_msec)
  455. break;
  456. doomed.push_back(m_idle.front().example);
  457. m_idle.pop_front();
  458. m_alive_size--;
  459. }
  460. }
  461. void collect_shrink_unlocked(std::vector<void*>& doomed)
  462. {
  463. if (!m_opt.enable_auto_shrink)
  464. return;
  465. collect_idle_timeout_unlocked(doomed);
  466. if (m_alive_size <= m_opt.min_size)
  467. return;
  468. note_usage_unlocked(m_pop_size);
  469. const size_t peak = usage_peak_unlocked();
  470. const size_t alive = m_alive_size;
  471. const size_t threshold_alive = (size_t)std::ceil((double)alive * m_opt.shrink_threshold);
  472. // 近期峰值仍占存活一半以上:不按量缩减
  473. if (peak >= threshold_alive)
  474. return;
  475. size_t target = (size_t)std::ceil((double)peak * m_opt.shrink_headroom);
  476. if (target < m_opt.min_size)
  477. target = m_opt.min_size;
  478. if (target > m_opt.max_size)
  479. target = m_opt.max_size;
  480. while (m_alive_size > target && !m_idle.empty())
  481. {
  482. doomed.push_back(m_idle.front().example);
  483. m_idle.pop_front();
  484. m_alive_size--;
  485. }
  486. }
  487. void shrink_loop()
  488. {
  489. while (true)
  490. {
  491. std::vector<void*> doomed;
  492. {
  493. std::unique_lock<std::mutex> sp(m_mutex);
  494. m_shrink_cv.wait_for(sp, std::chrono::seconds(m_opt.shrink_interval_sec), [this]() {
  495. return m_shrink_stop || m_closing;
  496. });
  497. if (m_shrink_stop || m_closing)
  498. return;
  499. collect_shrink_unlocked(doomed);
  500. }
  501. for (void* p : doomed)
  502. destroy_example(p);
  503. }
  504. }
  505. private:
  506. pool_config m_opt;
  507. std::deque<idle_entry> m_idle;
  508. size_t m_alive_size = 0;
  509. std::vector<size_t> m_usage_buckets;
  510. size_t m_usage_bucket_idx = 0;
  511. timestamp m_usage_bucket_sec = 0;
  512. std::thread m_shrink_thread;
  513. std::condition_variable m_shrink_cv;
  514. bool m_shrink_stop = true;
  515. };
  516. }