All files / packages/coordination/src semaphore.ts

85.58% Statements 95/111
72.41% Branches 42/58
90% Functions 27/30
85.45% Lines 94/110

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453                                        11x   11x       293x     11x 11x       11x                                                                                           90x       90x               22x       88x 2x     86x 86x 86x               9x                   142x 142x 142x       124x       52x   52x 52x                           52x       52x             6x   6x 6x                         6x       6x             2x   2x 2x                         2x       2x             105x 105x 105x 105x   105x   105x                                 105x 105x 105x           105x   11x             100x       100x         100x 8x     90x   90x       86x   86x 86x                       86x       86x                   12x   12x 12x   8x 8x 8x                     30x 30x                               30x       30x         30x 30x       28x             9x 9x   9x     18x 17x 17x                             17x       17x         17x 17x       17x 17x     17x     9x   6x 9x 9x         11x 262x 121x     141x       141x                   11x 45x           13x                                
import { create } from '@bufbuild/protobuf'
import { abortable, linkSignals } from '@ydbjs/abortable'
import {
	SessionRequest_AcquireSemaphoreSchema,
	SessionRequest_CreateSemaphoreSchema,
	SessionRequest_DeleteSemaphoreSchema,
	SessionRequest_DescribeSemaphoreSchema,
	SessionRequest_ReleaseSemaphoreSchema,
	SessionRequest_UpdateSemaphoreSchema,
	type SessionResponse,
} from '@ydbjs/api/coordination'
import { StatusIds_StatusCode } from '@ydbjs/api/operation'
import { loggers } from '@ydbjs/debug'
 
import { YDBError } from '@ydbjs/error'
import * as assert from 'node:assert'
 
import { LeaseReleasedError, TryAcquireMissError, isTryAcquireMiss } from './errors.js'
import type { SessionTransport, StreamEnvelope } from './runtime/session-transport.js'
 
let dbg = loggers.coordination.extend('semaphore')
 
let assertResultStatus = function assertResultStatus(
	status: StatusIds_StatusCode,
	issues: unknown[]
): void {
	assert.strictEqual(status, StatusIds_StatusCode.SUCCESS, new YDBError(status, issues as any[]))
}
 
let maxUint64 = 2n ** 64n - 1n
let emptyBytes = new Uint8Array()
 
// MAX_UINT64 tells the server to keep the acquire request queued indefinitely.
// A value of 0 means "return immediately if not available" (tryAcquire).
let waitIndefinitely = maxUint64
 
export interface CreateSemaphoreOptions {
	limit: number | bigint
	data?: Uint8Array
}
 
export interface DeleteSemaphoreOptions {
	force?: boolean
}
 
export interface AcquireSemaphoreOptions {
	count?: number | bigint
	data?: Uint8Array
	ephemeral?: boolean
	waitTimeout?: number | bigint
}
 
export interface DescribeSemaphoreOptions {
	owners?: boolean
	waiters?: boolean
}
 
export interface WatchSemaphoreOptions extends DescribeSemaphoreOptions {
	data?: boolean
}
 
export interface SemaphoreSessionDescription {
	data: Uint8Array
	count: bigint
	orderId: bigint
	sessionId: bigint
	timeoutMillis: bigint
}
 
export interface SemaphoreDescription {
	name: string
	data: Uint8Array
	count: bigint
	limit: bigint
	ephemeral: boolean
	owners?: SemaphoreSessionDescription[]
	waiters?: SemaphoreSessionDescription[]
}
 
export class Lease implements AsyncDisposable {
	#ac = new AbortController()
	#semaphore: Semaphore
 
	constructor(semaphore: Semaphore) {
		this.#semaphore = semaphore
	}
 
	get name(): string {
		return this.#semaphore.name
	}
 
	get signal(): AbortSignal {
		return this.#ac.signal
	}
 
	async release(signal?: AbortSignal): Promise<void> {
		if (this.#ac.signal.aborted) {
			return
		}
 
		try {
			await this.#semaphore.release(signal)
			this.#ac.abort(new LeaseReleasedError())
		} catch (error) {
			this.#ac.abort(error)
			throw error
		}
	}
 
	async [Symbol.asyncDispose](): Promise<void> {
		await this.release()
	}
}
 
export class Semaphore {
	#name: string
	#transport: SessionTransport
	#sessionSignal: AbortSignal
 
	constructor(name: string, transport: SessionTransport, sessionSignal: AbortSignal) {
		this.#name = name
		this.#transport = transport
		this.#sessionSignal = sessionSignal
	}
 
	get name(): string {
		return this.#name
	}
 
	async create(options: CreateSemaphoreOptions, signal?: AbortSignal): Promise<void> {
		dbg.log('creating %s (limit=%s)', this.#name, options.limit)
 
		let response = await this.#transport.call(
			(reqId) => ({
				request: {
					case: 'createSemaphore',
					value: create(SessionRequest_CreateSemaphoreSchema, {
						reqId,
						name: this.#name,
						limit: toBigInt(options.limit),
						data: options.data ?? emptyBytes,
					}),
				},
			}),
			signal
		)
 
		Iif (response.response.case !== 'createSemaphoreResult') {
			throw new Error('Unexpected response for createSemaphore')
		}
 
		assertResultStatus(
			response.response.value.status as StatusIds_StatusCode,
			response.response.value.issues
		)
	}
 
	async update(data: Uint8Array, signal?: AbortSignal): Promise<void> {
		dbg.log('updating data on %s (%d bytes)', this.#name, data.byteLength)
 
		let response = await this.#transport.call(
			(reqId) => ({
				request: {
					case: 'updateSemaphore',
					value: create(SessionRequest_UpdateSemaphoreSchema, {
						reqId,
						name: this.#name,
						data,
					}),
				},
			}),
			signal
		)
 
		Iif (response.response.case !== 'updateSemaphoreResult') {
			throw new Error('Unexpected response for updateSemaphore')
		}
 
		assertResultStatus(
			response.response.value.status as StatusIds_StatusCode,
			response.response.value.issues
		)
	}
 
	async delete(options?: DeleteSemaphoreOptions, signal?: AbortSignal): Promise<void> {
		dbg.log('deleting %s%s', this.#name, options?.force ? ' (force)' : '')
 
		let response = await this.#transport.call(
			(reqId) => ({
				request: {
					case: 'deleteSemaphore',
					value: create(SessionRequest_DeleteSemaphoreSchema, {
						reqId,
						name: this.#name,
						force: options?.force ?? false,
					}),
				},
			}),
			signal
		)
 
		Iif (response.response.case !== 'deleteSemaphoreResult') {
			throw new Error('Unexpected response for deleteSemaphore')
		}
 
		assertResultStatus(
			response.response.value.status as StatusIds_StatusCode,
			response.response.value.issues
		)
	}
 
	async acquire(options?: AcquireSemaphoreOptions, signal?: AbortSignal): Promise<Lease> {
		let count = toBigInt(options?.count ?? 1)
		let waitTimeout = toBigInt(options?.waitTimeout ?? waitIndefinitely)
		let data = options?.data ?? emptyBytes
		let ephemeral = options?.ephemeral ?? false
 
		dbg.log('waiting to acquire %s (count=%s)', this.#name, count)
 
		let buildEnvelope = (reqId: bigint): StreamEnvelope => ({
			request: {
				case: 'acquireSemaphore',
				value: create(SessionRequest_AcquireSemaphoreSchema, {
					reqId,
					name: this.#name,
					timeoutMillis: waitTimeout,
					count,
					data,
					ephemeral,
				}),
			},
		})
 
		// The initial request allocates a reqId that is pinned for the entire
		// acquire flow — the server uses it to identify the waiter slot.
		let pinnedReqId!: bigint
		let response = await this.#transport.call((reqId) => {
			pinnedReqId = reqId
			return buildEnvelope(reqId)
		}, signal)
 
		// The server may respond with acquireSemaphorePending before the final
		// result. We keep waiting with the same pinned reqId — on reconnect
		// the full request is re-sent because the server lost the waiter state.
		while (response.response.case === 'acquireSemaphorePending') {
			// oxlint-disable-next-line no-await-in-loop
			response = await this.#transport.callPinned(
				pinnedReqId,
				() => this.#transport.send(buildEnvelope(pinnedReqId)),
				signal
			)
		}
 
		Iif (response.response.case !== 'acquireSemaphoreResult') {
			throw new Error('Unexpected response for acquireSemaphore')
		}
 
		assertResultStatus(
			response.response.value.status as StatusIds_StatusCode,
			response.response.value.issues
		)
 
		if (!response.response.value.acquired) {
			throw new TryAcquireMissError()
		}
 
		dbg.log('acquired %s', this.#name)
 
		return new Lease(this)
	}
 
	async release(signal?: AbortSignal): Promise<void> {
		dbg.log('releasing %s', this.#name)
 
		let response = await this.#transport.call(
			(reqId) => ({
				request: {
					case: 'releaseSemaphore',
					value: create(SessionRequest_ReleaseSemaphoreSchema, {
						reqId,
						name: this.#name,
					}),
				},
			}),
			signal
		)
 
		Iif (response.response.case !== 'releaseSemaphoreResult') {
			throw new Error('Unexpected response for releaseSemaphore')
		}
 
		assertResultStatus(
			response.response.value.status as StatusIds_StatusCode,
			response.response.value.issues
		)
	}
 
	async tryAcquire(
		options?: AcquireSemaphoreOptions,
		signal?: AbortSignal
	): Promise<Lease | null> {
		dbg.log('trying to acquire %s without waiting (count=%s)', this.#name, options?.count ?? 1)
 
		try {
			return await this.acquire({ ...options, waitTimeout: 0n }, signal)
		} catch (error) {
			Eif (isTryAcquireMiss(error)) {
				dbg.log('%s is already held, skipping', this.#name)
				return null
			}
 
			throw error
		}
	}
 
	async describe(
		options?: DescribeSemaphoreOptions,
		signal?: AbortSignal
	): Promise<SemaphoreDescription> {
		let response = await this.#transport.call(
			(reqId) => ({
				request: {
					case: 'describeSemaphore',
					value: create(SessionRequest_DescribeSemaphoreSchema, {
						reqId,
						name: this.#name,
						includeOwners: options?.owners ?? false,
						includeWaiters: options?.waiters ?? false,
						watchData: false,
						watchOwners: false,
					}),
				},
			}),
			signal
		)
 
		Iif (response.response.case !== 'describeSemaphoreResult') {
			throw new Error('Unexpected response for describeSemaphore')
		}
 
		assertResultStatus(
			response.response.value.status as StatusIds_StatusCode,
			response.response.value.issues
		)
 
		let raw = response.response.value.semaphoreDescription
		Iif (!raw) {
			throw new Error('Missing semaphore description in response')
		}
 
		return mapDescription(raw)
	}
 
	async *watch(
		options?: WatchSemaphoreOptions,
		signal?: AbortSignal
	): AsyncIterable<SemaphoreDescription> {
		using subscription = this.#transport.watch(this.#name)
		using combined = linkSignals(this.#sessionSignal, signal)
 
		let describeAndWatch = async (): Promise<SemaphoreDescription> => {
			let watchReqId!: bigint
 
			let response = await this.#transport.call((reqId) => {
				watchReqId = reqId
				return {
					request: {
						case: 'describeSemaphore',
						value: create(SessionRequest_DescribeSemaphoreSchema, {
							reqId,
							name: this.#name,
							includeOwners: options?.owners ?? false,
							includeWaiters: options?.waiters ?? false,
							watchData: options?.data ?? false,
							watchOwners: options?.owners ?? false,
						}),
					},
				}
			}, combined.signal)
 
			Iif (response.response.case !== 'describeSemaphoreResult') {
				throw new Error('Unexpected response for describeSemaphore (watch)')
			}
 
			assertResultStatus(
				response.response.value.status as StatusIds_StatusCode,
				response.response.value.issues
			)
 
			let raw = response.response.value.semaphoreDescription
			Iif (!raw) {
				throw new Error('Missing semaphore description in watch result')
			}
 
			Eif (response.response.value.watchAdded) {
				subscription.updateReqId(watchReqId)
			}
 
			return mapDescription(raw)
		}
 
		yield await describeAndWatch()
 
		for await (let _change of subscription.queue) {
			combined.signal.throwIfAborted()
			yield await abortable(combined.signal, describeAndWatch())
		}
	}
}
 
let toBigInt = function toBigInt(value: number | bigint): bigint {
	if (typeof value === 'bigint') {
		return value
	}
 
	Iif (value === Infinity) {
		return maxUint64
	}
 
	return BigInt(value)
}
 
type RawDescription = NonNullable<
	Extract<
		SessionResponse['response'],
		{ case: 'describeSemaphoreResult' }
	>['value']['semaphoreDescription']
>
 
let mapDescription = function mapDescription(raw: RawDescription): SemaphoreDescription {
	return {
		name: raw.name,
		data: raw.data,
		count: raw.count,
		limit: raw.limit,
		ephemeral: raw.ephemeral,
		owners: raw.owners.map((item) => ({
			data: item.data,
			count: item.count,
			orderId: item.orderId,
			sessionId: item.sessionId,
			timeoutMillis: item.timeoutMillis,
		})),
		waiters: raw.waiters.map((item) => ({
			data: item.data,
			count: item.count,
			orderId: item.orderId,
			sessionId: item.sessionId,
			timeoutMillis: item.timeoutMillis,
		})),
	}
}