-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPool.php
More file actions
381 lines (333 loc) · 10.1 KB
/
Pool.php
File metadata and controls
381 lines (333 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
<?php
namespace Utopia\Pools;
use Exception;
use Utopia\Telemetry\Adapter as Telemetry;
use Utopia\Telemetry\Adapter\None as NoTelemetry;
use Utopia\Telemetry\Gauge;
use Utopia\Telemetry\Histogram;
/**
* @template TResource
*/
class Pool
{
/**
* @var string
*/
protected string $name;
/**
* @var int
*/
protected int $size = 0;
/**
* @var callable
*/
protected $init = null;
/**
* @var int
*/
protected int $reconnectAttempts = 3;
/**
* @var int
*/
protected int $reconnectSleep = 1; // seconds
/**
* @var int
*/
protected int $retryAttempts = 3;
/**
* @var int
*/
protected int $retrySleep = 1; // seconds
/**
* @var array<Connection<TResource>|true>
*/
protected array $pool = [];
/**
* @var array<string, Connection<TResource>>
*/
protected array $active = [];
private Gauge $telemetryOpenConnections;
private Gauge $telemetryActiveConnections;
private Gauge $telemetryIdleConnections;
private Gauge $telemetryPoolCapacity;
private Histogram $telemetryWaitDuration;
private Histogram $telemetryUseDuration;
/** @var array<string, int|string> */
private array $telemetryAttributes;
/**
* @param string $name
* @param int $size
* @param callable(): TResource $init
*/
public function __construct(string $name, int $size, callable $init)
{
$this->name = $name;
$this->size = $size;
$this->init = $init;
$this->pool = array_fill(0, $size, true);
$this->setTelemetry(new NoTelemetry());
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return int
*/
public function getSize(): int
{
return $this->size;
}
/**
* @return int
*/
public function getReconnectAttempts(): int
{
return $this->reconnectAttempts;
}
/**
* @param int $reconnectAttempts
* @return $this<TResource>
*/
public function setReconnectAttempts(int $reconnectAttempts): static
{
$this->reconnectAttempts = $reconnectAttempts;
return $this;
}
/**
* @return int
*/
public function getReconnectSleep(): int
{
return $this->reconnectSleep;
}
/**
* @param int $reconnectSleep
* @return $this<TResource>
*/
public function setReconnectSleep(int $reconnectSleep): static
{
$this->reconnectSleep = $reconnectSleep;
return $this;
}
/**
* @return int
*/
public function getRetryAttempts(): int
{
return $this->retryAttempts;
}
/**
* @param int $retryAttempts
* @return $this<TResource>
*/
public function setRetryAttempts(int $retryAttempts): static
{
$this->retryAttempts = $retryAttempts;
return $this;
}
/**
* @return int
*/
public function getRetrySleep(): int
{
return $this->retrySleep;
}
/**
* @param int $retrySleep
* @return $this<TResource>
*/
public function setRetrySleep(int $retrySleep): static
{
$this->retrySleep = $retrySleep;
return $this;
}
/**
* @param Telemetry $telemetry
* @return $this<TResource>
*/
public function setTelemetry(Telemetry $telemetry): static
{
$this->telemetryOpenConnections = $telemetry->createGauge('pool.connection.open.count');
$this->telemetryActiveConnections = $telemetry->createGauge('pool.connection.active.count');
$this->telemetryIdleConnections = $telemetry->createGauge('pool.connection.idle.count');
$this->telemetryPoolCapacity = $telemetry->createGauge('pool.connection.capacity.count');
$this->telemetryWaitDuration = $telemetry->createHistogram(
name: 'pool.connection.wait_time',
unit: 's',
advisory: ['ExplicitBucketBoundaries' => [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10]],
);
$this->telemetryUseDuration = $telemetry->createHistogram(
name: 'pool.connection.use_time',
unit: 's',
advisory: ['ExplicitBucketBoundaries' => [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10]],
);
$this->telemetryAttributes = ['pool' => $this->name, 'size' => $this->size];
return $this;
}
/**
* Execute a callback with a managed connection
*
* @template T
* @param callable(mixed): T $callback Function that receives the connection resource
* @return T Return value from the callback
*/
public function use(callable $callback): mixed
{
$start = microtime(true);
$connection = null;
try {
$connection = $this->pop();
return $callback($connection->getResource());
} finally {
if ($connection !== null) {
$this->telemetryUseDuration->record(microtime(true) - $start, $this->telemetryAttributes);
$this->reclaim($connection);
}
}
}
/**
* Summary:
* 1. Try to get a connection from the pool
* 2. If no connection is available, wait for one to be released
* 3. If still no connection is available, throw an exception
* 4. If a connection is available, return it
*
* @return Connection<TResource>
* @throws Exception
* @internal Please migrate to `use`.
*/
public function pop(): Connection
{
$attempts = 0;
$totalSleepTime = 0;
try {
do {
$attempts++;
$connection = array_pop($this->pool);
if (is_null($connection)) {
if ($attempts >= $this->getRetryAttempts()) {
throw new Exception("Pool '{$this->name}' is empty (size {$this->size})");
}
$totalSleepTime += $this->getRetrySleep();
sleep($this->getRetrySleep());
} else {
break;
}
} while ($attempts < $this->getRetryAttempts());
if ($connection === true) { // Pool has space, create connection
$attempts = 0;
do {
try {
$attempts++;
$connection = new Connection(($this->init)());
break; // leave loop if successful
} catch (\Exception $e) {
if ($attempts >= $this->getReconnectAttempts()) {
throw new \Exception('Failed to create connection: ' . $e->getMessage());
}
$totalSleepTime += $this->getReconnectSleep();
sleep($this->getReconnectSleep());
}
} while ($attempts < $this->getReconnectAttempts());
}
if ($connection instanceof Connection) { // connection is available, return it
if (empty($connection->getID())) {
$connection->setID($this->getName() . '-' . uniqid());
}
$connection->setPool($this);
$this->active[$connection->getID()] = $connection;
return $connection;
}
throw new Exception('Failed to get a connection from the pool');
} finally {
$this->recordPoolTelemetry();
$this->telemetryWaitDuration->record($totalSleepTime, $this->telemetryAttributes);
}
}
/**
* @param Connection<TResource> $connection
* @return $this<TResource>
*/
public function push(Connection $connection): static
{
try {
$this->pool[] = $connection;
unset($this->active[$connection->getID()]);
return $this;
} finally {
$this->recordPoolTelemetry();
}
}
/**
* @return int
*/
public function count(): int
{
return count($this->pool);
}
/**
* @param Connection<TResource>|null $connection
* @return $this<TResource>
*/
public function reclaim(Connection $connection = null): static
{
if ($connection !== null) {
$this->push($connection);
return $this;
}
foreach ($this->active as $connection) {
$this->push($connection);
}
return $this;
}
/**
* @param Connection<TResource>|null $connection
* @return $this<TResource>
*/
public function destroy(Connection $connection = null): static
{
try {
if ($connection !== null) {
$this->pool[] = true;
unset($this->active[$connection->getID()]);
return $this;
}
foreach ($this->active as $connection) {
$this->pool[] = true;
unset($this->active[$connection->getID()]);
}
return $this;
} finally {
$this->recordPoolTelemetry();
}
}
/**
* @return bool
*/
public function isEmpty(): bool
{
return empty($this->pool);
}
/**
* @return bool
*/
public function isFull(): bool
{
return count($this->pool) === $this->size;
}
private function recordPoolTelemetry(): void
{
// Connections get removed from $this->pool when they are active
$activeConnections = count($this->active);
$existingConnections = count($this->pool);
$idleConnections = count(array_filter($this->pool, fn ($data) => $data instanceof Connection));
$this->telemetryActiveConnections->record($activeConnections, $this->telemetryAttributes);
$this->telemetryIdleConnections->record($idleConnections, $this->telemetryAttributes);
$this->telemetryOpenConnections->record($activeConnections + $idleConnections, $this->telemetryAttributes);
$this->telemetryPoolCapacity->record($activeConnections + $existingConnections, $this->telemetryAttributes);
}
}