@open-mercato/shared 0.9.1-develop.7573.1.d0ccc51d5b → 0.9.1-develop.7574.1.837288eec1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/AGENTS.md +1 -1
- package/dist/lib/db/advisoryLock.js +172 -0
- package/dist/lib/db/advisoryLock.js.map +7 -0
- package/dist/lib/db/pg-errors.js +14 -0
- package/dist/lib/db/pg-errors.js.map +2 -2
- package/dist/lib/version.js +1 -1
- package/dist/lib/version.js.map +1 -1
- package/dist/modules/integrations/types.js.map +2 -2
- package/package.json +9 -2
- package/src/lib/db/__tests__/advisoryLock.integration.test.ts +343 -0
- package/src/lib/db/__tests__/advisoryLock.test.ts +564 -0
- package/src/lib/db/__tests__/pg-errors.test.ts +68 -1
- package/src/lib/db/advisoryLock.ts +271 -0
- package/src/lib/db/pg-errors.ts +35 -0
- package/src/modules/integrations/types.ts +6 -0
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
2
|
+
import { calculateBackoffDelayMs } from '../delivery/retry'
|
|
3
|
+
import { isTransientLockDbError } from './pg-errors'
|
|
4
|
+
|
|
5
|
+
/** @internal */
|
|
6
|
+
export type AdvisoryLockWaitResult<T> = { done: true; value: T } | { done: false }
|
|
7
|
+
|
|
8
|
+
export type AdvisoryLockOptions<T> = {
|
|
9
|
+
/** Total waiting budget from the call start. Default 15_000. */
|
|
10
|
+
waitDeadlineMs?: number
|
|
11
|
+
/** @internal Called after each failed attempt, with no connection held; `done: true` short-circuits. */
|
|
12
|
+
onWait?: () => Promise<AdvisoryLockWaitResult<T>>
|
|
13
|
+
/** Per process and key namespace: at most this many lock transactions at once (attempts included).
|
|
14
|
+
* Waiting for a slot holds no connection and counts against `waitDeadlineMs`. Default: unlimited. */
|
|
15
|
+
maxConcurrentHolders?: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const ADVISORY_LOCK_UNAVAILABLE_BRAND = Symbol.for('@open-mercato/shared:AdvisoryLockUnavailableError')
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The helper's own work failed with an error `isTransientLockDbError` accepts (kept as `cause`), or
|
|
22
|
+
* the wait ran out. `deadline`: the wait budget ran out (contention or no free holder slot), so `fn`
|
|
23
|
+
* never ran. `transient_db`: the begin or the lock query failed, so `fn` never ran. `commit_unknown`:
|
|
24
|
+
* `fn` returned and the flush or commit after it failed, so its writes may or may not be committed.
|
|
25
|
+
* `reason` is additive-only; branch on it, never on the message.
|
|
26
|
+
*/
|
|
27
|
+
export type AdvisoryLockUnavailableReason = 'deadline' | 'transient_db' | 'commit_unknown'
|
|
28
|
+
|
|
29
|
+
const ADVISORY_LOCK_UNAVAILABLE_MESSAGES: Record<AdvisoryLockUnavailableReason, string> = {
|
|
30
|
+
deadline: '[internal] Advisory lock not acquired before the wait deadline',
|
|
31
|
+
transient_db: '[internal] Advisory lock transaction failed with a transient database error',
|
|
32
|
+
commit_unknown: '[internal] Advisory lock transaction failed after its callback returned; the commit outcome is unknown',
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class AdvisoryLockUnavailableError extends Error {
|
|
36
|
+
static [Symbol.hasInstance](value: unknown): boolean {
|
|
37
|
+
return typeof value === 'object' && value !== null && Reflect.get(value, ADVISORY_LOCK_UNAVAILABLE_BRAND) === true
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
readonly reason: AdvisoryLockUnavailableReason
|
|
41
|
+
readonly key: string
|
|
42
|
+
constructor(reason: AdvisoryLockUnavailableReason, key: string, cause?: unknown) {
|
|
43
|
+
super(ADVISORY_LOCK_UNAVAILABLE_MESSAGES[reason], cause === undefined ? undefined : { cause })
|
|
44
|
+
Object.defineProperty(this, ADVISORY_LOCK_UNAVAILABLE_BRAND, { value: true, enumerable: false })
|
|
45
|
+
this.name = 'AdvisoryLockUnavailableError'
|
|
46
|
+
this.reason = reason
|
|
47
|
+
this.key = key
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const DEFAULT_WAIT_DEADLINE_MS = 15_000
|
|
52
|
+
const BACKOFF_ATTEMPT_CAP = 5
|
|
53
|
+
const BACKOFF_OPTIONS = { baseDelayMs: 50, maxJitterMs: 25 }
|
|
54
|
+
const KEY_NAMESPACE_PATTERN = /^[a-z][a-z0-9_]*$/
|
|
55
|
+
const ADVISORY_LOCK_SQL = 'select pg_try_advisory_xact_lock(hashtextextended(?, 0)) as locked'
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* `disableContextResolution` keeps the fork off an outer transaction resolved from the
|
|
59
|
+
* async context, `useContext: false` keeps the fork's own transaction from joining one
|
|
60
|
+
* later, `disableTransactions: false` keeps a source EntityManager with transactions disabled
|
|
61
|
+
* from turning the lock into a statement-scoped no-op, and the cloned event manager carries
|
|
62
|
+
* the request's subscribers (tenant field encryption among them) into the lock transaction.
|
|
63
|
+
*/
|
|
64
|
+
const LOCK_FORK_OPTIONS = {
|
|
65
|
+
disableContextResolution: true,
|
|
66
|
+
clear: true,
|
|
67
|
+
useContext: false,
|
|
68
|
+
disableTransactions: false,
|
|
69
|
+
cloneEventManager: true,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Holder slots live on `globalThis` so duplicated module instances in one process (dev
|
|
74
|
+
* HMR, standalone server chunks) count against one limit. The map is created once and
|
|
75
|
+
* never replaced; each namespace entry is created on first use and kept.
|
|
76
|
+
*/
|
|
77
|
+
const GLOBAL_SLOTS_KEY = '__openMercatoAdvisoryLockSlots__'
|
|
78
|
+
|
|
79
|
+
type SlotWaiter = {
|
|
80
|
+
limit: number
|
|
81
|
+
grant: () => void
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
type NamespaceSlots = {
|
|
85
|
+
held: number
|
|
86
|
+
waiters: SlotWaiter[]
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
type SlotRelease = () => void
|
|
90
|
+
|
|
91
|
+
type AttemptOutcome<T> = { acquired: true; value: T } | { acquired: false }
|
|
92
|
+
|
|
93
|
+
const NOT_ACQUIRED: AttemptOutcome<never> = { acquired: false }
|
|
94
|
+
|
|
95
|
+
const releaseNothing: SlotRelease = () => undefined
|
|
96
|
+
|
|
97
|
+
function getSlotRegistry(): Map<string, NamespaceSlots> {
|
|
98
|
+
const globals = globalThis as Record<string, unknown>
|
|
99
|
+
const existing = globals[GLOBAL_SLOTS_KEY]
|
|
100
|
+
if (existing instanceof Map) return existing as Map<string, NamespaceSlots>
|
|
101
|
+
const created = new Map<string, NamespaceSlots>()
|
|
102
|
+
globals[GLOBAL_SLOTS_KEY] = created
|
|
103
|
+
return created
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function getNamespaceSlots(namespace: string): NamespaceSlots {
|
|
107
|
+
const registry = getSlotRegistry()
|
|
108
|
+
const existing = registry.get(namespace)
|
|
109
|
+
if (existing) return existing
|
|
110
|
+
const created: NamespaceSlots = { held: 0, waiters: [] }
|
|
111
|
+
registry.set(namespace, created)
|
|
112
|
+
return created
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function handOffSlots(slots: NamespaceSlots): void {
|
|
116
|
+
let index = 0
|
|
117
|
+
while (index < slots.waiters.length) {
|
|
118
|
+
const waiter = slots.waiters[index]
|
|
119
|
+
if (slots.held >= waiter.limit) {
|
|
120
|
+
index += 1
|
|
121
|
+
continue
|
|
122
|
+
}
|
|
123
|
+
slots.waiters.splice(index, 1)
|
|
124
|
+
slots.held += 1
|
|
125
|
+
waiter.grant()
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function createSlotRelease(slots: NamespaceSlots): SlotRelease {
|
|
130
|
+
let released = false
|
|
131
|
+
return () => {
|
|
132
|
+
if (released) return
|
|
133
|
+
released = true
|
|
134
|
+
slots.held -= 1
|
|
135
|
+
handOffSlots(slots)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function acquireSlot(namespace: string, limit: number, key: string, deadlineAt: number): Promise<SlotRelease> {
|
|
140
|
+
const slots = getNamespaceSlots(namespace)
|
|
141
|
+
if (slots.held < limit) {
|
|
142
|
+
slots.held += 1
|
|
143
|
+
return Promise.resolve(createSlotRelease(slots))
|
|
144
|
+
}
|
|
145
|
+
const remainingMs = deadlineAt - Date.now()
|
|
146
|
+
if (remainingMs <= 0) return Promise.reject(new AdvisoryLockUnavailableError('deadline', key))
|
|
147
|
+
return new Promise<SlotRelease>((resolve, reject) => {
|
|
148
|
+
const waiter: SlotWaiter = {
|
|
149
|
+
limit,
|
|
150
|
+
grant: () => {
|
|
151
|
+
clearTimeout(deadlineTimer)
|
|
152
|
+
resolve(createSlotRelease(slots))
|
|
153
|
+
},
|
|
154
|
+
}
|
|
155
|
+
const deadlineTimer = setTimeout(() => {
|
|
156
|
+
const position = slots.waiters.indexOf(waiter)
|
|
157
|
+
if (position >= 0) slots.waiters.splice(position, 1)
|
|
158
|
+
reject(new AdvisoryLockUnavailableError('deadline', key))
|
|
159
|
+
}, remainingMs)
|
|
160
|
+
slots.waiters.push(waiter)
|
|
161
|
+
})
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function parseKeyNamespace(key: unknown): string {
|
|
165
|
+
const separator = typeof key === 'string' ? key.indexOf(':') : -1
|
|
166
|
+
if (typeof key === 'string' && separator > 0 && separator < key.length - 1) {
|
|
167
|
+
const namespace = key.slice(0, separator)
|
|
168
|
+
if (KEY_NAMESPACE_PATTERN.test(namespace)) return namespace
|
|
169
|
+
}
|
|
170
|
+
throw new TypeError('[internal] Advisory lock key must be "<namespace>:<parts>" with a namespace matching ^[a-z][a-z0-9_]*$')
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function resolveWaitDeadlineMs(value: number | undefined): number {
|
|
174
|
+
if (value === undefined) return DEFAULT_WAIT_DEADLINE_MS
|
|
175
|
+
if (Number.isFinite(value) && value >= 0) return value
|
|
176
|
+
throw new TypeError('[internal] Advisory lock waitDeadlineMs must be a finite number of at least 0')
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function resolveMaxConcurrentHolders(value: number | undefined): number | null {
|
|
180
|
+
if (value === undefined) return null
|
|
181
|
+
if (Number.isInteger(value) && value > 0) return value
|
|
182
|
+
throw new TypeError('[internal] Advisory lock maxConcurrentHolders must be a positive integer')
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function sleep(delayMs: number): Promise<void> {
|
|
186
|
+
return new Promise((resolve) => setTimeout(resolve, delayMs))
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async function attemptLock<T>(
|
|
190
|
+
lockEm: EntityManager,
|
|
191
|
+
key: string,
|
|
192
|
+
fn: (txEm: EntityManager) => Promise<T>,
|
|
193
|
+
): Promise<AttemptOutcome<T>> {
|
|
194
|
+
const callback: { thrown: boolean; returned: boolean; error: unknown } = { thrown: false, returned: false, error: undefined }
|
|
195
|
+
try {
|
|
196
|
+
return await lockEm.transactional(async (txEm): Promise<AttemptOutcome<T>> => {
|
|
197
|
+
const rows = await txEm.execute<Array<{ locked: boolean }>>(ADVISORY_LOCK_SQL, [key])
|
|
198
|
+
if (rows[0]?.locked !== true) return NOT_ACQUIRED
|
|
199
|
+
try {
|
|
200
|
+
const value = await fn(txEm)
|
|
201
|
+
callback.returned = true
|
|
202
|
+
return { acquired: true, value }
|
|
203
|
+
} catch (error) {
|
|
204
|
+
callback.thrown = true
|
|
205
|
+
callback.error = error
|
|
206
|
+
throw error
|
|
207
|
+
}
|
|
208
|
+
})
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (callback.thrown) throw callback.error
|
|
211
|
+
if (isTransientLockDbError(error)) {
|
|
212
|
+
throw new AdvisoryLockUnavailableError(callback.returned ? 'commit_unknown' : 'transient_db', key, error)
|
|
213
|
+
}
|
|
214
|
+
throw error
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Runs `fn` in one transaction that holds `pg_try_advisory_xact_lock(hashtextextended(key, 0))`.
|
|
220
|
+
* - `key` is `<namespace>:<parts>` with namespace `^[a-z][a-z0-9_]*$`; anything else throws `TypeError`.
|
|
221
|
+
* - `waitDeadlineMs` must be a finite number ≥ 0 and `maxConcurrentHolders` a positive integer;
|
|
222
|
+
* anything else throws `TypeError` before any connection is taken.
|
|
223
|
+
* - Pass the request (container) EntityManager. The helper forks it with
|
|
224
|
+
* `{ disableContextResolution: true, clear: true, useContext: false, disableTransactions: false, cloneEventManager: true }`,
|
|
225
|
+
* so the lock transaction never nests in a caller's transaction and commits on its own.
|
|
226
|
+
* - `fn` MUST do all DB I/O on `txEm`, MUST flush its own writes, MUST be bounded (≤ one external
|
|
227
|
+
* call), MUST NOT call `transactional` again (it only opens a savepoint in the lock transaction) and
|
|
228
|
+
* MUST NOT fork or use `getConnection().execute` (another pooled connection, outside the lock).
|
|
229
|
+
* - `txEm` carries the request EntityManager's subscribers (cloned event manager).
|
|
230
|
+
* - A failed attempt ends its empty transaction, so waiters hold no connection between attempts.
|
|
231
|
+
* They back off 50 ms doubling up to 800 ms (plus up to 24 ms jitter), never past
|
|
232
|
+
* `waitDeadlineMs` measured from the call start, then retry.
|
|
233
|
+
* - With `maxConcurrentHolders`, each attempt first takes a per-process slot for the key
|
|
234
|
+
* namespace and gives it back when the attempt fails or the lock transaction settles.
|
|
235
|
+
* - Errors from the helper's own begin, lock query and commit that `isTransientLockDbError` accepts,
|
|
236
|
+
* and the deadline, throw `AdvisoryLockUnavailableError` (its `reason` says whether `fn` ran); any
|
|
237
|
+
* other error from them, and every error thrown by `fn`, propagates unchanged (a throw from `fn`
|
|
238
|
+
* rolls back).
|
|
239
|
+
*/
|
|
240
|
+
export async function withAdvisoryXactLock<T>(
|
|
241
|
+
em: EntityManager,
|
|
242
|
+
key: string,
|
|
243
|
+
fn: (txEm: EntityManager) => Promise<T>,
|
|
244
|
+
options: AdvisoryLockOptions<T> = {},
|
|
245
|
+
): Promise<T> {
|
|
246
|
+
const namespace = parseKeyNamespace(key)
|
|
247
|
+
const waitDeadlineMs = resolveWaitDeadlineMs(options.waitDeadlineMs)
|
|
248
|
+
const maxConcurrentHolders = resolveMaxConcurrentHolders(options.maxConcurrentHolders)
|
|
249
|
+
const deadlineAt = Date.now() + waitDeadlineMs
|
|
250
|
+
const lockEm = em.fork(LOCK_FORK_OPTIONS)
|
|
251
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
252
|
+
const releaseSlot = maxConcurrentHolders === null
|
|
253
|
+
? releaseNothing
|
|
254
|
+
: await acquireSlot(namespace, maxConcurrentHolders, key, deadlineAt)
|
|
255
|
+
let outcome: AttemptOutcome<T>
|
|
256
|
+
try {
|
|
257
|
+
outcome = await attemptLock(lockEm, key, fn)
|
|
258
|
+
} finally {
|
|
259
|
+
releaseSlot()
|
|
260
|
+
}
|
|
261
|
+
if (outcome.acquired) return outcome.value
|
|
262
|
+
const remainingMs = deadlineAt - Date.now()
|
|
263
|
+
if (remainingMs <= 0) throw new AdvisoryLockUnavailableError('deadline', key)
|
|
264
|
+
await sleep(Math.min(calculateBackoffDelayMs(Math.min(attempt, BACKOFF_ATTEMPT_CAP), BACKOFF_OPTIONS), remainingMs))
|
|
265
|
+
if (options.onWait) {
|
|
266
|
+
const waitResult = await options.onWait()
|
|
267
|
+
if (waitResult.done) return waitResult.value
|
|
268
|
+
}
|
|
269
|
+
if (Date.now() >= deadlineAt) throw new AdvisoryLockUnavailableError('deadline', key)
|
|
270
|
+
}
|
|
271
|
+
}
|
package/src/lib/db/pg-errors.ts
CHANGED
|
@@ -148,3 +148,38 @@ export function isTransientDbError(err: unknown): boolean {
|
|
|
148
148
|
}
|
|
149
149
|
return false
|
|
150
150
|
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* SQLSTATEs that end a lock transaction early but say nothing about the data it
|
|
154
|
+
* would have written, so the work can be retried: lock_not_available (55P03,
|
|
155
|
+
* raised by `DB_LOCK_TIMEOUT_MS`), query_canceled (57014, raised by the opt-in
|
|
156
|
+
* `DB_STATEMENT_TIMEOUT_MS`) and idle_in_transaction_session_timeout (25P03).
|
|
157
|
+
*/
|
|
158
|
+
const TRANSIENT_LOCK_SQLSTATES = new Set(['55P03', '57014', '25P03'])
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Driver messages for a connection that never arrived or was lost mid-transaction:
|
|
162
|
+
* the pg-pool acquire timeout (`connectionTimeoutMillis`) and node-postgres's
|
|
163
|
+
* error for a client whose connection already failed.
|
|
164
|
+
*/
|
|
165
|
+
const TRANSIENT_LOCK_MESSAGE_PATTERNS = [
|
|
166
|
+
/timeout exceeded when trying to connect/i,
|
|
167
|
+
/client has encountered a connection error and is not queryable/i,
|
|
168
|
+
]
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* @internal Detect a transient failure of a short lock transaction: everything
|
|
172
|
+
* `isTransientDbError` matches, plus lock, statement and idle-in-transaction
|
|
173
|
+
* timeouts, the pg-pool acquire timeout and node-postgres's "not queryable"
|
|
174
|
+
* error. Checks every layer of the driver-error wrapper chain (`cause` /
|
|
175
|
+
* `previous`, see `pgErrorCandidates`). `isTransientDbError` keeps its narrower
|
|
176
|
+
* scope because its callers answer 503 "service unavailable".
|
|
177
|
+
*/
|
|
178
|
+
export function isTransientLockDbError(err: unknown): boolean {
|
|
179
|
+
return pgErrorCandidates(err).some((candidate) => {
|
|
180
|
+
if (isTransientDbError(candidate)) return true
|
|
181
|
+
if (typeof candidate.code === 'string' && TRANSIENT_LOCK_SQLSTATES.has(candidate.code)) return true
|
|
182
|
+
const message = candidate.message
|
|
183
|
+
return typeof message === 'string' && TRANSIENT_LOCK_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))
|
|
184
|
+
})
|
|
185
|
+
}
|
|
@@ -157,6 +157,12 @@ export interface IntegrationDetailPageConfig {
|
|
|
157
157
|
* Provider modules can replace these with injected tabs using the same spot.
|
|
158
158
|
*/
|
|
159
159
|
hiddenTabs?: IntegrationDetailBuiltInTab[]
|
|
160
|
+
/**
|
|
161
|
+
* Detail-page tab that holds the provider's Connect / Reconnect controls (a built-in tab id or
|
|
162
|
+
* an injected tab id). The OAuth reauth banner links to `?tab=<connectTabId>` while that tab is
|
|
163
|
+
* visible and the viewer holds `integrations.credentials.manage`.
|
|
164
|
+
*/
|
|
165
|
+
connectTabId?: string
|
|
160
166
|
}
|
|
161
167
|
|
|
162
168
|
export type IntegrationDetailBuiltInTab =
|