/
DoctrineDbalStore.php
285 lines (250 loc) · 10.5 KB
/
DoctrineDbalStore.php
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
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Lock\Store;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Exception as DBALException;
use Doctrine\DBAL\Exception\TableNotFoundException;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Schema\DefaultSchemaManagerFactory;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Tools\DsnParser;
use Symfony\Component\Lock\Exception\InvalidArgumentException;
use Symfony\Component\Lock\Exception\InvalidTtlException;
use Symfony\Component\Lock\Exception\LockConflictedException;
use Symfony\Component\Lock\Key;
use Symfony\Component\Lock\PersistingStoreInterface;
/**
* DbalStore is a PersistingStoreInterface implementation using a Doctrine DBAL connection.
*
* Lock metadata are stored in a table. You can use createTable() to initialize
* a correctly defined table.
*
* CAUTION: This store relies on all client and server nodes to have
* synchronized clocks for lock expiry to occur at the correct time.
* To ensure locks don't expire prematurely; the TTLs should be set with enough
* extra time to account for any clock drift between nodes.
*
* @author Jérémy Derussé <jeremy@derusse.com>
*/
class DoctrineDbalStore implements PersistingStoreInterface
{
use DatabaseTableTrait;
use ExpiringStoreTrait;
private Connection $conn;
/**
* List of available options:
* * db_table: The name of the table [default: lock_keys]
* * db_id_col: The column where to store the lock key [default: key_id]
* * db_token_col: The column where to store the lock token [default: key_token]
* * db_expiration_col: The column where to store the expiration [default: key_expiration].
*
* @param Connection|string $connOrUrl A DBAL Connection instance or Doctrine URL
* @param array $options An associative array of options
* @param float $gcProbability Probability expressed as floating number between 0 and 1 to clean old locks
* @param int $initialTtl The expiration delay of locks in seconds
*
* @throws InvalidArgumentException When namespace contains invalid characters
* @throws InvalidArgumentException When the initial ttl is not valid
*/
public function __construct(Connection|string $connOrUrl, array $options = [], float $gcProbability = 0.01, int $initialTtl = 300)
{
$this->init($options, $gcProbability, $initialTtl);
if ($connOrUrl instanceof Connection) {
$this->conn = $connOrUrl;
} else {
if (!class_exists(DriverManager::class)) {
throw new InvalidArgumentException('Failed to parse the DSN. Try running "composer require doctrine/dbal".');
}
if (class_exists(DsnParser::class)) {
$params = (new DsnParser([
'db2' => 'ibm_db2',
'mssql' => 'pdo_sqlsrv',
'mysql' => 'pdo_mysql',
'mysql2' => 'pdo_mysql',
'postgres' => 'pdo_pgsql',
'postgresql' => 'pdo_pgsql',
'pgsql' => 'pdo_pgsql',
'sqlite' => 'pdo_sqlite',
'sqlite3' => 'pdo_sqlite',
]))->parse($connOrUrl);
} else {
$params = ['url' => $connOrUrl];
}
$config = new Configuration();
if (class_exists(DefaultSchemaManagerFactory::class)) {
$config->setSchemaManagerFactory(new DefaultSchemaManagerFactory());
}
$this->conn = DriverManager::getConnection($params, $config);
}
}
/**
* @return void
*/
public function save(Key $key)
{
$key->reduceLifetime($this->initialTtl);
$sql = "INSERT INTO $this->table ($this->idCol, $this->tokenCol, $this->expirationCol) VALUES (?, ?, {$this->getCurrentTimestampStatement()} + $this->initialTtl)";
try {
$this->conn->executeStatement($sql, [
$this->getHashedKey($key),
$this->getUniqueToken($key),
], [
ParameterType::STRING,
ParameterType::STRING,
]);
} catch (TableNotFoundException) {
if (!$this->conn->isTransactionActive() || $this->platformSupportsTableCreationInTransaction()) {
$this->createTable();
}
try {
$this->conn->executeStatement($sql, [
$this->getHashedKey($key),
$this->getUniqueToken($key),
], [
ParameterType::STRING,
ParameterType::STRING,
]);
} catch (DBALException) {
$this->putOffExpiration($key, $this->initialTtl);
}
} catch (DBALException) {
// the lock is already acquired. It could be us. Let's try to put off.
$this->putOffExpiration($key, $this->initialTtl);
}
$this->randomlyPrune();
$this->checkNotExpired($key);
}
/**
* @return void
*/
public function putOffExpiration(Key $key, $ttl)
{
if ($ttl < 1) {
throw new InvalidTtlException(sprintf('"%s()" expects a TTL greater or equals to 1 second. Got "%s".', __METHOD__, $ttl));
}
$key->reduceLifetime($ttl);
$sql = "UPDATE $this->table SET $this->expirationCol = {$this->getCurrentTimestampStatement()} + ?, $this->tokenCol = ? WHERE $this->idCol = ? AND ($this->tokenCol = ? OR $this->expirationCol <= {$this->getCurrentTimestampStatement()})";
$uniqueToken = $this->getUniqueToken($key);
$result = $this->conn->executeQuery($sql, [
$ttl,
$uniqueToken,
$this->getHashedKey($key),
$uniqueToken,
], [
ParameterType::INTEGER,
ParameterType::STRING,
ParameterType::STRING,
ParameterType::STRING,
]);
// If this method is called twice in the same second, the row wouldn't be updated. We have to call exists to know if we are the owner
if (!$result->rowCount() && !$this->exists($key)) {
throw new LockConflictedException();
}
$this->checkNotExpired($key);
}
/**
* @return void
*/
public function delete(Key $key)
{
$this->conn->delete($this->table, [
$this->idCol => $this->getHashedKey($key),
$this->tokenCol => $this->getUniqueToken($key),
]);
}
public function exists(Key $key): bool
{
$sql = "SELECT 1 FROM $this->table WHERE $this->idCol = ? AND $this->tokenCol = ? AND $this->expirationCol > {$this->getCurrentTimestampStatement()}";
$result = $this->conn->fetchOne($sql, [
$this->getHashedKey($key),
$this->getUniqueToken($key),
], [
ParameterType::STRING,
ParameterType::STRING,
]);
return (bool) $result;
}
/**
* Creates the table to store lock keys which can be called once for setup.
*
* @throws DBALException When the table already exists
*/
public function createTable(): void
{
$schema = new Schema();
$this->configureSchema($schema);
foreach ($schema->toSql($this->conn->getDatabasePlatform()) as $sql) {
$this->conn->executeStatement($sql);
}
}
/**
* Adds the Table to the Schema if it doesn't exist.
*
* @param \Closure $isSameDatabase
*/
public function configureSchema(Schema $schema/* , \Closure $isSameDatabase */): void
{
if ($schema->hasTable($this->table)) {
return;
}
$isSameDatabase = 1 < \func_num_args() ? func_get_arg(1) : static fn () => true;
if (!$isSameDatabase($this->conn->executeStatement(...))) {
return;
}
$table = $schema->createTable($this->table);
$table->addColumn($this->idCol, 'string', ['length' => 64]);
$table->addColumn($this->tokenCol, 'string', ['length' => 44]);
$table->addColumn($this->expirationCol, 'integer', ['unsigned' => true]);
$table->setPrimaryKey([$this->idCol]);
}
/**
* Cleans up the table by removing all expired locks.
*/
private function prune(): void
{
$sql = "DELETE FROM $this->table WHERE $this->expirationCol <= {$this->getCurrentTimestampStatement()}";
$this->conn->executeStatement($sql);
}
/**
* Provides an SQL function to get the current timestamp regarding the current connection's driver.
*/
private function getCurrentTimestampStatement(): string
{
$platform = $this->conn->getDatabasePlatform();
return match (true) {
$platform instanceof \Doctrine\DBAL\Platforms\MySQLPlatform,
$platform instanceof \Doctrine\DBAL\Platforms\MySQL57Platform => 'UNIX_TIMESTAMP()',
$platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform => 'strftime(\'%s\',\'now\')',
$platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform,
$platform instanceof \Doctrine\DBAL\Platforms\PostgreSQL94Platform => 'CAST(EXTRACT(epoch FROM NOW()) AS INT)',
$platform instanceof \Doctrine\DBAL\Platforms\OraclePlatform => '(SYSDATE - TO_DATE(\'19700101\',\'yyyymmdd\'))*86400 - TO_NUMBER(SUBSTR(TZ_OFFSET(sessiontimezone), 1, 3))*3600',
$platform instanceof \Doctrine\DBAL\Platforms\SQLServerPlatform,
$platform instanceof \Doctrine\DBAL\Platforms\SQLServer2012Platform => 'DATEDIFF(s, \'1970-01-01\', GETUTCDATE())',
default => (string) time(),
};
}
/**
* Checks whether current platform supports table creation within transaction.
*/
private function platformSupportsTableCreationInTransaction(): bool
{
$platform = $this->conn->getDatabasePlatform();
return match (true) {
$platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform,
$platform instanceof \Doctrine\DBAL\Platforms\PostgreSQL94Platform,
$platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform,
$platform instanceof \Doctrine\DBAL\Platforms\SQLServerPlatform,
$platform instanceof \Doctrine\DBAL\Platforms\SQLServer2012Platform => true,
default => false,
};
}
}