-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPostgresAdvisoryLocker.php
More file actions
383 lines (344 loc) · 15.1 KB
/
PostgresAdvisoryLocker.php
File metadata and controls
383 lines (344 loc) · 15.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
382
383
<?php
/*
* This file is part of PHP DB Locker.
*
* (c) Anton Komarev <anton@komarev.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Cog\DbLocker\Postgres;
use Cog\DbLocker\ConnectionAdapterInterface;
use Cog\DbLocker\Exception\LockAcquireException;
use Cog\DbLocker\Exception\LockReleaseException;
use Cog\DbLocker\Postgres\Enum\PostgresLockAccessModeEnum;
use Cog\DbLocker\Postgres\Enum\PostgresLockLevelEnum;
use Cog\DbLocker\Postgres\LockHandle\SessionLevelLockHandle;
use Cog\DbLocker\Postgres\LockHandle\WithinSessionLevelLockHandle;
use Cog\DbLocker\Postgres\LockHandle\TransactionLevelLockHandle;
use Cog\DbLocker\TimeoutDuration;
final class PostgresAdvisoryLocker
{
/**
* Acquire a transaction-level advisory lock with configurable timeout and access mode.
*
* @param TimeoutDuration $timeoutDuration Maximum wait time. Use TimeoutDuration::zero() for an immediate (non-blocking) attempt.
* @return TransactionLevelLockHandle Handle with wasAcquired=false if lock is held by another process (normal competition).
*
* @throws LockAcquireException If a database error occurs (connection failures, query errors, etc.). NOT thrown for normal lock contention.
* @throws \LogicException If attempting to acquire outside of an active transaction.
*/
public function acquireTransactionLevelLock(
ConnectionAdapterInterface $dbConnection,
PostgresLockKey $key,
TimeoutDuration $timeoutDuration,
PostgresLockAccessModeEnum $accessMode = PostgresLockAccessModeEnum::Exclusive,
): TransactionLevelLockHandle {
return new TransactionLevelLockHandle(
lockKey: $key,
accessMode: $accessMode,
wasAcquired: $this->acquireLock(
dbConnection: $dbConnection,
key: $key,
level: PostgresLockLevelEnum::Transaction,
timeoutDuration: $timeoutDuration,
accessMode: $accessMode,
),
);
}
/**
* Acquires a session-level advisory lock, executes the callback only if acquired, and ensures release.
*
* The callback is invoked only when the lock is successfully acquired. If the lock
* is not acquired (held by another process), the callback is not called and
* a handle with `wasAcquired = false` is returned.
*
* This method guarantees that the lock is released even if an exception is thrown during execution.
* Useful for safely wrapping critical sections that require locking.
*
* ⚠️ Transaction-level advisory locks are strongly preferred whenever possible,
* as they are automatically released at the end of a transaction and are less error-prone.
* Use session-level locks only when transactional context is not available.
*
* @param callable(): TReturn $callback A callback to execute while the lock is held.
* @param TimeoutDuration $timeoutDuration Maximum wait time. Use TimeoutDuration::zero() for an immediate (non-blocking) attempt.
* @return WithinSessionLevelLockHandle<TReturn|null> Handle with wasAcquired and result of the callback (null if not acquired).
*
* @throws LockAcquireException If a database error occurs during lock acquisition. NOT thrown for normal lock contention.
* @throws LockReleaseException If a database error occurs during lock release (only thrown if no other exception occurred during callback execution).
* ⚠️ A LockReleaseException guarantees that the callback has completed successfully,
* but the callback's return value is lost. If you need access to the callback result
* in this scenario, use acquireSessionLevelLock() / releaseSessionLevelLock() directly.
*
* @see acquireTransactionLevelLock() for preferred locking strategy.
*
* @template TReturn
*/
public function withinSessionLevelLock(
ConnectionAdapterInterface $dbConnection,
PostgresLockKey $key,
callable $callback,
TimeoutDuration $timeoutDuration,
PostgresLockAccessModeEnum $accessMode = PostgresLockAccessModeEnum::Exclusive,
): WithinSessionLevelLockHandle {
$lockHandle = $this->acquireSessionLevelLock(
dbConnection: $dbConnection,
key: $key,
timeoutDuration: $timeoutDuration,
accessMode: $accessMode,
);
if (!$lockHandle->wasAcquired) {
return new WithinSessionLevelLockHandle(
wasAcquired: false,
result: null,
);
}
$exception = null;
try {
$result = $callback();
return new WithinSessionLevelLockHandle(
wasAcquired: true,
result: $result,
);
} catch (\Throwable $e) {
$exception = $e;
throw $e;
} finally {
try {
$this->releaseSessionLevelLock(
dbConnection: $dbConnection,
key: $key,
accessMode: $accessMode,
);
} catch (\Throwable $releaseException) {
if ($exception === null) {
throw $releaseException;
}
}
}
}
/**
* Acquire a session-level advisory lock with configurable timeout and access mode.
*
* ⚠️ Transaction-level advisory locks are strongly preferred whenever possible,
* as they are automatically released at the end of a transaction and are less error-prone.
* Use session-level locks only when transactional context is not available.
*
* ⚠️ When using session-level locks, prefer withinSessionLevelLock() over this method,
* as it guarantees automatic lock release via try/finally even if exceptions occur.
* This method requires manual release management via releaseSessionLevelLock() or the
* lock handle's release() method.
*
* @param TimeoutDuration $timeoutDuration Maximum wait time. Use TimeoutDuration::zero() for an immediate (non-blocking) attempt.
* @return SessionLevelLockHandle Handle with wasAcquired=false if lock is held by another process (normal competition).
*
* @throws LockAcquireException If a database error occurs (connection failures, query errors, etc.). NOT thrown for normal lock contention.
*
* @see acquireTransactionLevelLock() for preferred locking strategy.
* @see withinSessionLevelLock() for automatic session lock management.
*/
public function acquireSessionLevelLock(
ConnectionAdapterInterface $dbConnection,
PostgresLockKey $key,
TimeoutDuration $timeoutDuration,
PostgresLockAccessModeEnum $accessMode = PostgresLockAccessModeEnum::Exclusive,
): SessionLevelLockHandle {
return new SessionLevelLockHandle(
dbConnection: $dbConnection,
locker: $this,
lockKey: $key,
accessMode: $accessMode,
wasAcquired: $this->acquireLock(
dbConnection: $dbConnection,
key: $key,
level: PostgresLockLevelEnum::Session,
timeoutDuration: $timeoutDuration,
accessMode: $accessMode,
),
);
}
/**
* Release session level advisory lock.
*
* @return bool True if the lock was successfully released, false if it was not held by this session.
*
* @throws LockReleaseException If a database error occurs during release.
*/
public function releaseSessionLevelLock(
ConnectionAdapterInterface $dbConnection,
PostgresLockKey $key,
PostgresLockAccessModeEnum $accessMode = PostgresLockAccessModeEnum::Exclusive,
): bool {
try {
$sql = match ($accessMode) {
PostgresLockAccessModeEnum::Exclusive
=> 'SELECT PG_ADVISORY_UNLOCK(:class_id, :object_id);',
PostgresLockAccessModeEnum::Share
=> 'SELECT PG_ADVISORY_UNLOCK_SHARED(:class_id, :object_id);',
};
$sql .= " -- $key->humanReadableValue";
return $dbConnection->fetchColumn($sql, [
'class_id' => $key->classId,
'object_id' => $key->objectId,
]);
} catch (\Exception $exception) {
throw LockReleaseException::fromDatabaseError($key, $exception);
}
}
/**
* Release all session level advisory locks held by the current session.
*/
public function releaseAllSessionLevelLocks(
ConnectionAdapterInterface $dbConnection,
): void {
$dbConnection->execute('SELECT PG_ADVISORY_UNLOCK_ALL();');
}
private function acquireLock(
ConnectionAdapterInterface $dbConnection,
PostgresLockKey $key,
PostgresLockLevelEnum $level,
TimeoutDuration $timeoutDuration,
PostgresLockAccessModeEnum $accessMode = PostgresLockAccessModeEnum::Exclusive,
): bool {
if ($level === PostgresLockLevelEnum::Transaction && $dbConnection->isTransactionActive() === false) {
throw new \LogicException(
"Transaction-level advisory lock `$key->humanReadableValue` cannot be acquired outside of transaction",
);
}
return $timeoutDuration->toMilliseconds() === 0
? $this->tryAcquireLock(
dbConnection: $dbConnection,
key: $key,
level: $level,
accessMode: $accessMode,
)
: $this->acquireLockWithTimeout(
dbConnection: $dbConnection,
key: $key,
level: $level,
accessMode: $accessMode,
timeoutDuration: $timeoutDuration,
);
}
private function tryAcquireLock(
ConnectionAdapterInterface $dbConnection,
PostgresLockKey $key,
PostgresLockLevelEnum $level,
PostgresLockAccessModeEnum $accessMode,
): bool {
try {
$sql = match ([$level, $accessMode]) {
[PostgresLockLevelEnum::Session, PostgresLockAccessModeEnum::Exclusive]
=> 'SELECT PG_TRY_ADVISORY_LOCK(:class_id, :object_id);',
[PostgresLockLevelEnum::Session, PostgresLockAccessModeEnum::Share]
=> 'SELECT PG_TRY_ADVISORY_LOCK_SHARED(:class_id, :object_id);',
[PostgresLockLevelEnum::Transaction, PostgresLockAccessModeEnum::Exclusive]
=> 'SELECT PG_TRY_ADVISORY_XACT_LOCK(:class_id, :object_id);',
[PostgresLockLevelEnum::Transaction, PostgresLockAccessModeEnum::Share]
=> 'SELECT PG_TRY_ADVISORY_XACT_LOCK_SHARED(:class_id, :object_id);',
};
$sql .= " -- $key->humanReadableValue";
return $dbConnection->fetchColumn($sql, [
'class_id' => $key->classId,
'object_id' => $key->objectId,
]);
} catch (\Exception $exception) {
throw LockAcquireException::fromDatabaseError($key, $exception);
}
}
private function acquireLockWithTimeout(
ConnectionAdapterInterface $dbConnection,
PostgresLockKey $key,
PostgresLockLevelEnum $level,
PostgresLockAccessModeEnum $accessMode,
TimeoutDuration $timeoutDuration,
): bool {
$sql = match ([$level, $accessMode]) {
[PostgresLockLevelEnum::Session, PostgresLockAccessModeEnum::Exclusive]
=> 'SELECT PG_ADVISORY_LOCK(:class_id, :object_id);',
[PostgresLockLevelEnum::Session, PostgresLockAccessModeEnum::Share]
=> 'SELECT PG_ADVISORY_LOCK_SHARED(:class_id, :object_id);',
[PostgresLockLevelEnum::Transaction, PostgresLockAccessModeEnum::Exclusive]
=> 'SELECT PG_ADVISORY_XACT_LOCK(:class_id, :object_id);',
[PostgresLockLevelEnum::Transaction, PostgresLockAccessModeEnum::Share]
=> 'SELECT PG_ADVISORY_XACT_LOCK_SHARED(:class_id, :object_id);',
};
$sql .= " -- $key->humanReadableValue";
return match ($level) {
PostgresLockLevelEnum::Transaction => $this->acquireTransactionLockWithTimeout(
dbConnection: $dbConnection,
sql: $sql,
key: $key,
timeoutDuration: $timeoutDuration,
),
PostgresLockLevelEnum::Session => $this->acquireSessionLockWithTimeout(
dbConnection: $dbConnection,
sql: $sql,
key: $key,
timeoutDuration: $timeoutDuration,
),
};
}
private function acquireTransactionLockWithTimeout(
ConnectionAdapterInterface $dbConnection,
string $sql,
PostgresLockKey $key,
TimeoutDuration $timeoutDuration,
): bool {
try {
$timeoutMs = $timeoutDuration->toMilliseconds();
$dbConnection->execute("SET LOCAL lock_timeout = '$timeoutMs'");
/**
* Use a savepoint so that a lock_timeout error does not abort the entire transaction.
* PostgreSQL handles same-name savepoints as a stack, so nested calls are safe.
*/
$dbConnection->execute('SAVEPOINT _lock_timeout_savepoint');
try {
$dbConnection->execute($sql, [
'class_id' => $key->classId,
'object_id' => $key->objectId,
]);
$dbConnection->execute('RELEASE SAVEPOINT _lock_timeout_savepoint');
return true;
} catch (\Exception $exception) {
if ($dbConnection->isLockNotAvailable($exception)) {
$dbConnection->execute('ROLLBACK TO SAVEPOINT _lock_timeout_savepoint');
return false;
}
throw $exception;
}
} catch (\Exception $exception) {
throw LockAcquireException::fromDatabaseError($key, $exception);
}
}
private function acquireSessionLockWithTimeout(
ConnectionAdapterInterface $dbConnection,
string $sql,
PostgresLockKey $key,
TimeoutDuration $timeoutDuration,
): bool {
try {
$timeoutMs = $timeoutDuration->toMilliseconds();
$originalLockTimeout = $dbConnection->fetchColumn('SHOW lock_timeout');
$dbConnection->execute("SET lock_timeout = '$timeoutMs'");
try {
$dbConnection->execute($sql, [
'class_id' => $key->classId,
'object_id' => $key->objectId,
]);
return true;
} catch (\Exception $exception) {
if ($dbConnection->isLockNotAvailable($exception)) {
return false;
}
throw $exception;
}
finally {
$dbConnection->execute("SET lock_timeout = '$originalLockTimeout'");
}
} catch (\Exception $exception) {
throw LockAcquireException::fromDatabaseError($key, $exception);
}
}
}