Repository navigation
Expand file tree
/
Copy pathPdoDbService.php
More file actions
269 lines (228 loc) · 9.8 KB
/
Copy pathPdoDbService.php
File metadata and controls
269 lines (228 loc) · 9.8 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
<?php
declare(strict_types=1);
namespace SqlFirstDemo\Db;
use Generator;
use PDO;
use PDOStatement;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use SqlFirstDemo\Result\RowSet;
use Throwable;
/**
* The real gateway: a thin layer over PDO that every query in the application goes through.
*
* "Thin" is the point. It adds the handful of behaviours you want on EVERY statement and nothing
* that changes what the SQL means:
*
* 1. Connection-loss retry, for READS. Long-running workers, idle pools and failovers all produce
* "MySQL server has gone away". Running a SELECT a second time on a new connection is
* harmless, so reads are retried a few times, with a short pause. See {@see self::withRetry()}.
* 2. No retry for WRITES. A connection can drop after the server has already run and committed
* the statement but before the reply arrives. Re-sending `SET stock = stock + 3` or an INSERT
* would then apply it twice. So a write that loses its connection is reported, not repeated;
* the dead connection is discarded so the next statement gets a fresh one, and the caller
* (who knows whether the write is safe to repeat) decides what to do.
* 3. No retry inside a transaction, for reads either. Inside {@see self::transactional()} the
* meaning of a statement depends on connection state (the open transaction) that a new
* connection does not have. Reconnecting there would quietly auto-commit the rest of the work
* outside the transaction, whilst the caller is told it failed.
* 4. A bounded prepared-statement cache, so a statement run in a loop is prepared once.
* 5. Slow-query logging, with the SQL, so the log line says what was slow.
* 6. Every failure wrapped in one {@see QueryException} carrying the SQL.
*
* It does not parse, rewrite or build SQL. What a query class passes in is what MySQL receives.
*/
final class PdoDbService implements DbServiceInterface
{
private const int SLOW_QUERY_MS = 1000;
private const int STATEMENT_CACHE_SIZE = 100;
/**
* Fragments of the driver messages that mean "the connection is gone", as opposed to "the SQL
* is wrong". Error 2006 is "MySQL server has gone away", 2013 is "Lost connection to MySQL
* server during query".
*/
private const array CONNECTION_LOST = [
'server has gone away',
'Lost connection',
'Error while sending',
'Connection refused',
'Connection timed out',
'Broken pipe',
'2006',
'2013',
];
/** How many transactional() calls we are inside. Nothing is retried whilst this is above zero. */
private int $transactionDepth = 0;
/** @var array<string, PDOStatement> keyed by SQL text plus connection identity */
private array $statements = [];
public function __construct(
private readonly PdoConnectionFactory $connections,
private readonly LoggerInterface $logger = new NullLogger(),
private readonly int $retryAttempts = 3,
private readonly int $retryDelayMs = 100,
) {
}
public function queryRows(string $sql, array $params = []): RowSet
{
return RowSet::fromRawRows($this->query($sql, $params));
}
public function query(string $sql, array $params = []): array
{
return $this->run($sql, $params, retryable: true, consume: static function (PDOStatement $stmt): array {
/** @var list<array<string, mixed>> $rows */
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
return $rows;
});
}
public function stream(string $sql, array $params = []): Generator
{
$stmt = $this->run($sql, $params, retryable: true, consume: static fn (PDOStatement $stmt): PDOStatement => $stmt);
try {
while (false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
/** @var array<string, mixed> $row */
yield $row;
}
} finally {
$stmt->closeCursor();
}
}
public function execute(string $sql, array $params = []): int
{
return $this->run($sql, $params, retryable: false, consume: static function (PDOStatement $stmt): int {
$count = $stmt->rowCount();
$stmt->closeCursor();
return $count;
});
}
public function insert(string $sql, array $params = []): int
{
if (!str_starts_with(strtoupper(ltrim($sql)), 'INSERT')) {
throw QueryException::forNonInsert($sql);
}
return $this->run($sql, $params, retryable: false, consume: function (PDOStatement $stmt): int {
$stmt->closeCursor();
return (int)$this->connections->getConnection()->lastInsertId();
});
}
public function transactional(callable $action): mixed
{
$pdo = $this->connections->getConnection();
$pdo->beginTransaction();
++$this->transactionDepth;
try {
$result = $action();
$pdo->commit();
return $result;
} catch (Throwable $e) {
if ($this->isConnectionLost($e)) {
// The server rolled the transaction back when the connection dropped. Calling
// rollBack() on the dead handle would only throw a second, less useful exception.
// Discard the handle so the caller's next statement gets a working connection.
$this->discardConnection();
} elseif ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $e instanceof QueryException ? $e : QueryException::forFailedTransaction($e);
} finally {
--$this->transactionDepth;
}
}
/**
* Prepare (or reuse), bind, execute, then hand the statement to `$consume`, all inside the
* retry loop and the timing, with any failure wrapped as a QueryException.
*
* @template T
*
* @param array<string, scalar|null> $params
* @param callable(PDOStatement): T $consume
*
* @return T
*/
private function run(string $sql, array $params, bool $retryable, callable $consume): mixed
{
$started = hrtime(true);
try {
return $this->withRetry($retryable, function (PDO $pdo) use ($sql, $params, $consume): mixed {
$stmt = $this->statementFor($pdo, $sql);
$stmt->execute($params);
return $consume($stmt);
});
} catch (Throwable $e) {
throw $e instanceof QueryException ? $e : QueryException::forFailedStatement($sql, $params, $e);
} finally {
$this->logIfSlow($sql, (int)((hrtime(true) - $started) / 1_000_000));
}
}
/**
* @template T
*
* @param callable(PDO): T $attempt
*
* @return T
*/
private function withRetry(bool $retryable, callable $attempt): mixed
{
for ($try = 1; ; ++$try) {
try {
return $attempt($this->connections->getConnection());
} catch (Throwable $e) {
if (!$this->isConnectionLost($e)) {
throw $e; // the SQL is wrong, or a constraint failed: never retried
}
if ($this->transactionDepth > 0) {
$this->logger->error('Connection lost inside a transaction; not retrying.', ['exception' => $e]);
throw $e; // transactional() discards the connection
}
// Outside a transaction the dead handle is useless either way, so drop it now and
// the next statement, retried or not, starts on a fresh connection.
$this->discardConnection();
if (!$retryable || $try > $this->retryAttempts) {
$this->logger->error('Connection lost; not retrying ' . ($retryable ? 'again.' : 'a write, which may already have been applied.'), ['exception' => $e]);
throw $e;
}
$this->logger->warning(\sprintf('Connection lost (attempt %d of %d); reconnecting.', $try, $this->retryAttempts), ['exception' => $e]);
usleep($this->retryDelayMs * 1000);
}
}
}
private function discardConnection(): void
{
$this->connections->reset();
$this->statements = []; // prepared statements die with their connection
}
/**
* Search the whole cause chain: by the time a failure reaches transactional() it has usually
* been wrapped, and the driver's "gone away" text is one getPrevious() down.
*/
private function isConnectionLost(Throwable $e): bool
{
for ($cause = $e; null !== $cause; $cause = $cause->getPrevious()) {
foreach (self::CONNECTION_LOST as $marker) {
if (str_contains($cause->getMessage(), $marker)) {
return true;
}
}
}
return false;
}
private function statementFor(PDO $pdo, string $sql): PDOStatement
{
// The connection's identity is part of the key: a statement prepared on a connection
// that has since been replaced belongs to the dead one and cannot be reused.
$key = spl_object_id($pdo) . '|' . $sql;
if (isset($this->statements[$key])) {
return $this->statements[$key];
}
if (\count($this->statements) >= self::STATEMENT_CACHE_SIZE) {
unset($this->statements[array_key_first($this->statements)]);
}
return $this->statements[$key] = $pdo->prepare($sql);
}
private function logIfSlow(string $sql, int $elapsedMs): void
{
if ($elapsedMs >= self::SLOW_QUERY_MS) {
$this->logger->warning(\sprintf('Slow query (%d ms)', $elapsedMs), ['sql' => $sql, 'elapsed_ms' => $elapsedMs]);
}
}
}