Lightweight 0.20260617.0
Loading...
Searching...
No Matches
ConnectionPool.hpp
1// SPDX-License-Identifier: Apache-2.0
2#pragma once
3
4#include "../Api.hpp"
5#include "../SqlConnection.hpp"
6#include "Common.hpp" // ConnectWithRetry
7#include "SqlBackup.hpp" // ProgressManager, RetrySettings
8
9#include <condition_variable>
10#include <memory>
11#include <mutex>
12#include <vector>
13
14namespace Lightweight::SqlBackup::detail
15{
16
17/// A runtime-sized, thread-safe pool of SqlConnection instances for backup/restore workers.
18///
19/// BoundedWait semantics: Acquire() blocks until a connection is free. All connections are created
20/// up front (sequentially, via ConnectWithRetry) to avoid concurrent-connect driver races and to
21/// pay connection setup cost once.
22class ConnectionPool
23{
24 public:
25 /// RAII lease: returns its connection to the pool on destruction. Move-only.
26 class Lease
27 {
28 public:
29 /// Move constructor; leaves @p other empty.
30 LIGHTWEIGHT_API Lease(Lease&& other) noexcept;
31 Lease& operator=(Lease&&) = delete;
32 Lease(Lease const&) = delete;
33 Lease& operator=(Lease const&) = delete;
34 LIGHTWEIGHT_API ~Lease();
35
36 /// Access the leased connection.
37 [[nodiscard]] SqlConnection& Get() const noexcept
38 {
39 return *_conn;
40 }
41
42 private:
43 friend class ConnectionPool;
44 Lease(ConnectionPool& pool, std::unique_ptr<SqlConnection> conn) noexcept;
45 ConnectionPool* _pool;
46 std::unique_ptr<SqlConnection> _conn;
47 };
48
49 /// Pre-creates @p size connections to @p connectionString (sequentially, via ConnectWithRetry).
50 /// @param connectionString The connection string each pooled connection connects to.
51 /// @param size The number of connections to pre-create.
52 /// @param retrySettings Retry configuration for transient connection errors.
53 /// @param progress Progress manager for reporting connection/retry status.
54 /// @throws std::runtime_error if any connection cannot be established.
55 LIGHTWEIGHT_API ConnectionPool(SqlConnectionString const& connectionString,
56 unsigned size,
57 RetrySettings const& retrySettings,
58 ProgressManager& progress);
59
60 ConnectionPool(ConnectionPool const&) = delete;
61 ConnectionPool& operator=(ConnectionPool const&) = delete;
62 ConnectionPool(ConnectionPool&&) = delete;
63 ConnectionPool& operator=(ConnectionPool&&) = delete;
64 ~ConnectionPool() = default;
65
66 /// Borrows a connection, blocking until one is free. Returned via the Lease's destructor.
67 /// @return An RAII lease owning one pooled connection.
68 [[nodiscard]] LIGHTWEIGHT_API Lease Acquire();
69
70 private:
71 void Return(std::unique_ptr<SqlConnection> conn) noexcept;
72
73 std::mutex _mutex;
74 std::condition_variable _cv;
75 std::vector<std::unique_ptr<SqlConnection>> _idle;
76};
77
78} // namespace Lightweight::SqlBackup::detail