All files / packages/coordination/src/runtime session-transport.ts

91.07% Statements 153/168
75.51% Branches 37/49
91.89% Functions 34/37
90.96% Lines 151/166

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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488                                                                                12x             9x     9x     9x 9x 9x       17x       10x 1x     9x 9x 9x             128x   128x 128x 128x 128x 128x   128x 128x 128x 128x         128x 128x                           129x       129x       97x       86x       125x 125x       90x 90x       2x       126x                                   128x           129x 129x       86x       126x           581x       581x                   399x   399x   398x 398x 398x   398x 398x   398x                                     11x 11x 11x   11x   11x   5x             5x               9x 9x       9x 9x 9x   9x       17x 17x       17x 9x     17x 17x       9x 9x 9x     9x 8x         2x 2x                   610x   610x 610x   610x 606x   4x 4x                 128x                   129x 129x         129x   129x 129x   129x   129x                           129x             129x 129x 129x 129x   129x 129x 129x     731x 731x 409x 409x   322x 15x 15x         307x     103x       129x   129x 129x 129x         129x 129x 129x       258x 258x 258x   258x 258x 258x   258x 129x         129x 129x       258x       97x                 86x 86x 86x                 125x 125x       90x 90x 90x 90x       254x 126x     128x   128x 128x 1x     128x         128x 128x 128x   128x       15x 15x 6x     9x 9x        
import { create } from '@bufbuild/protobuf'
import { abortable, linkSignals } from '@ydbjs/abortable'
import {
	SessionRequest_PingPongSchema,
	SessionRequest_SessionStartSchema,
	SessionRequest_SessionStopSchema,
} from '@ydbjs/api/coordination'
import { loggers } from '@ydbjs/debug'
import { type MachineRuntime, createMachineRuntime } from '@ydbjs/fsm'
import { AsyncQueue } from '@ydbjs/fsm/queue'
 
import {
	type Deferred,
	SessionReconnectError,
	SessionRequestRegistry,
	createDeferred,
} from './session-registry.js'
import {
	type CoordinationSessionClient,
	type StreamEnvelope,
	type StreamOpenParams,
	type TransportCtx,
	type TransportEffect,
	type TransportEvent,
	type TransportOutput,
	type TransportState,
	type WatchChange,
	classifyMessage,
	isAbortError,
	transportTransition,
} from './session-state.js'
 
export type {
	CoordinationSessionClient,
	StreamEnvelope,
	StreamOpenParams,
	TransportOutput,
	WatchChange,
}
 
let dbg = loggers.coordination.extend('transport')
 
// ── Watch subscription ─────────────────────────────────────────────────────────
 
export class WatchSubscription implements Disposable {
	#transport: SessionTransport
	#name: string
	#disposed = false
 
	queue: AsyncQueue<WatchChange>
	reqId = 0n
 
	constructor(transport: SessionTransport, name: string, queue: AsyncQueue<WatchChange>) {
		this.#transport = transport
		this.#name = name
		this.queue = queue
	}
 
	updateReqId(reqId: bigint): void {
		this.#transport.remapWatch(this.#name, this, reqId)
	}
 
	[Symbol.dispose](): void {
		if (this.#disposed) {
			return
		}
 
		this.#disposed = true
		this.#transport.removeWatch(this.#name, this)
		this.queue.close()
	}
}
 
// ── Session transport ──────────────────────────────────────────────────────────
 
export class SessionTransport implements Disposable {
	#ac = new AbortController()
	#client: CoordinationSessionClient
	#registry = new SessionRequestRegistry()
	#readyDeferred: Deferred<void> = createDeferred<void>()
	#destroyed = false
	#watchesByName = new Map<string, WatchSubscription>()
	#watchesByReqId = new Map<bigint, WatchSubscription>()
 
	#streamAC: AbortController | null = null
	#streamInput: AsyncQueue<StreamEnvelope> | null = null
	#streamParams: StreamOpenParams | null = null
	#streamIngestTask: Promise<void> | null = null
 
	#machine: MachineRuntime<TransportState, TransportCtx, TransportEvent, TransportOutput>
 
	constructor(client: CoordinationSessionClient) {
		this.#client = client
		this.#machine = createMachineRuntime<
			TransportState,
			TransportCtx,
			{},
			TransportEvent,
			TransportEffect,
			TransportOutput
		>({
			initialState: 'idle',
			ctx: { wasEverReady: false },
			env: {},
			transition: transportTransition,
			effects: {
				'transport.effect.open_stream': () => {
					this.#openStream()
				},
 
				'transport.effect.close_stream': async () => {
					await this.#closeStream()
				},
 
				'transport.effect.send_pong': (_ctx, effect) => {
					this.#sendPong(effect.opaque)
				},
 
				'transport.effect.send_stop': () => {
					this.#sendStop()
				},
 
				'transport.effect.mark_ready': (_ctx, effect, runtime) => {
					this.#markReady(effect.sessionId)
					runtime.emit({ type: 'transport.stream.started', sessionId: effect.sessionId })
				},
 
				'transport.effect.mark_disconnected': (_ctx, _effect, runtime) => {
					this.#markDisconnected()
					runtime.emit({ type: 'transport.stream.disconnected' })
				},
 
				'transport.effect.notify_watches': () => {
					this.notifyAllWatches()
				},
 
				'transport.effect.finalize': (_ctx, effect) => {
					this.#finalize(effect.reason)
				},
			},
		})
	}
 
	// ── Accessors ──────────────────────────────────────────────────────────────
 
	get signal(): AbortSignal {
		return this.#ac.signal
	}
 
	get state(): TransportState {
		return this.#machine.state
	}
 
	// The parent session FSM iterates this to receive transport events.
	get events(): AsyncIterable<TransportOutput> {
		return this.#machine
	}
 
	// ── Commands (called by parent session FSM) ────────────────────────────────
 
	connect(params: StreamOpenParams): void {
		this.#streamParams = params
		this.#machine.dispatch({ type: 'transport.connect' })
	}
 
	stop(): void {
		this.#machine.dispatch({ type: 'transport.stop' })
	}
 
	close(): void {
		this.#machine.dispatch({ type: 'transport.close' })
	}
 
	// ── Request multiplexing (called by business layer) ────────────────────────
 
	send(envelope: StreamEnvelope): void {
		Iif (!this.#streamInput || this.#streamInput.isClosed || this.#streamInput.isDestroyed) {
			return
		}
 
		this.#streamInput.push(envelope)
	}
 
	// Send a request and wait for the matching response. Retries transparently
	// on reconnect — allocates a fresh reqId each attempt because the server
	// lost the previous request state.
	async call(
		buildEnvelope: (reqId: bigint) => StreamEnvelope,
		signal?: AbortSignal
	): Promise<import('@ydbjs/api/coordination').SessionResponse> {
		for (;;) {
			// oxlint-disable-next-line no-await-in-loop
			await this.waitReady(signal)
 
			let reqId = this.#registry.nextReqId()
			using pending = this.#registry.register(reqId)
			using combined = linkSignals(this.#ac.signal, signal)
 
			try {
				this.send(buildEnvelope(reqId))
				// oxlint-disable-next-line no-await-in-loop
				return await abortable(combined.signal, pending.promise)
			} catch (error) {
				if (error instanceof SessionReconnectError) {
					continue
				}
 
				throw error
			}
		}
	}
 
	// Wait for a response to an already-sent request with a pinned reqId.
	// Used by the acquire pending loop — the server tracks the waiter slot
	// by reqId so it must not change across reconnects.
	async callPinned(
		reqId: bigint,
		resend: () => void,
		signal?: AbortSignal
	): Promise<import('@ydbjs/api/coordination').SessionResponse> {
		for (;;) {
			using pending = this.#registry.register(reqId)
			using combined = linkSignals(this.#ac.signal, signal)
 
			try {
				// oxlint-disable-next-line no-await-in-loop
				return await abortable(combined.signal, pending.promise)
			} catch (error) {
				Iif (error instanceof SessionReconnectError) {
					// oxlint-disable-next-line no-await-in-loop
					await this.waitReady(signal)
					resend()
					continue
				}
 
				throw error
			}
		}
	}
 
	// ── Watch subscriptions ────────────────────────────────────────────────────
 
	watch(name: string): WatchSubscription {
		let previous = this.#watchesByName.get(name)
		Iif (previous) {
			previous[Symbol.dispose]()
		}
 
		let queue = new AsyncQueue<WatchChange>()
		let subscription = new WatchSubscription(this, name, queue)
		this.#watchesByName.set(name, subscription)
 
		return subscription
	}
 
	remapWatch(name: string, subscription: WatchSubscription, reqId: bigint): void {
		let active = this.#watchesByName.get(name)
		Iif (active !== subscription) {
			return
		}
 
		if (subscription.reqId !== 0n) {
			this.#watchesByReqId.delete(subscription.reqId)
		}
 
		subscription.reqId = reqId
		this.#watchesByReqId.set(reqId, subscription)
	}
 
	removeWatch(name: string, subscription: WatchSubscription): void {
		let active = this.#watchesByName.get(name)
		Eif (active === subscription) {
			this.#watchesByName.delete(name)
		}
 
		if (subscription.reqId !== 0n) {
			this.#watchesByReqId.delete(subscription.reqId)
		}
	}
 
	notifyAllWatches(): void {
		dbg.log('notifying %d active watches to re-read after reconnect', this.#watchesByName.size)
		for (let subscription of this.#watchesByName.values()) {
			subscription.queue.push({ dataChanged: false, ownersChanged: false })
		}
	}
 
	// ── waitReady ──────────────────────────────────────────────────────────────
 
	// Loops through transient reconnect rejections — each time readyDeferred
	// is rejected the transport replaces it with a fresh one.
	async waitReady(callerSignal?: AbortSignal): Promise<void> {
		using combined = linkSignals(this.#ac.signal, callerSignal)
 
		for (;;) {
			try {
				// oxlint-disable-next-line no-await-in-loop
				await abortable(combined.signal, this.#readyDeferred.promise)
				return
			} catch (error) {
				Eif (combined.signal.aborted) {
					throw error
				}
			}
		}
	}
 
	// ── Teardown ───────────────────────────────────────────────────────────────
 
	destroy(reason: unknown): void {
		this.#finalize(reason)
	}
 
	[Symbol.dispose](): void {
		this.destroy(new Error('Transport disposed'))
	}
 
	// ── Internal ───────────────────────────────────────────────────────────────
 
	#openStream(): void {
		let params = this.#streamParams
		Iif (!params) {
			throw new Error('No stream params set — call connect() first')
		}
 
		// Dispose previous stream if any (fire-and-forget).
		void this.#closeStream()
 
		let ac = new AbortController()
		let input = new AsyncQueue<StreamEnvelope>()
 
		let grpcStream = this.#client.session(input, { signal: ac.signal })
 
		input.push({
			request: {
				case: 'sessionStart',
				value: create(SessionRequest_SessionStartSchema, {
					path: params.path,
					sessionId: params.sessionId ?? 0n,
					timeoutMillis: BigInt(params.recoveryWindow),
					description: params.description,
					seqNo: 0n,
					protectionKey: new Uint8Array(),
				}),
			},
		})
 
		dbg.log(
			'connecting to %s (sessionId=%s, recoveryWindow=%dms)',
			params.path,
			params.sessionId ?? 'new',
			params.recoveryWindow
		)
 
		let registry = this.#registry
		let dispatch = this.#machine.dispatch.bind(this.#machine)
		let handleWatch = this.#handleWatch.bind(this)
		let endEmitted = false
 
		let ingestTask = (async () => {
			try {
				for await (let response of grpcStream) {
					// Responses and watch notifications are resolved directly —
					// they bypass the FSM because they don't affect transport state.
					let msg = classifyMessage(response)
					if (msg && msg.kind === 'response') {
						registry.resolve(msg.reqId, msg.response)
						continue
					}
					if (msg && msg.kind === 'watch') {
						handleWatch(msg.reqId, msg.change)
						continue
					}
 
					// Everything else (ping, started, stopped, failure) goes
					// through the transport FSM for state transitions.
					dispatch({ type: 'transport.stream.message', response })
				}
			} catch (error) {
				Iif (!isAbortError(error)) {
					dispatch({ type: 'transport.stream.error', error })
				}
			} finally {
				input.close()
 
				Eif (!endEmitted) {
					endEmitted = true
					dispatch({ type: 'transport.stream.ended' })
				}
			}
		})()
 
		this.#streamAC = ac
		this.#streamInput = input
		this.#streamIngestTask = ingestTask
	}
 
	async #closeStream(): Promise<void> {
		let ac = this.#streamAC
		let input = this.#streamInput
		let ingestTask = this.#streamIngestTask
 
		this.#streamAC = null
		this.#streamInput = null
		this.#streamIngestTask = null
 
		if (!ac) {
			return
		}
 
		// Abort first so the gRPC read unblocks — without this
		// the ingest task deadlocks waiting for a message that never arrives.
		ac.abort(new Error('Stream disposed'))
		input?.close()
 
		// Wait for the ingest finally{} block so the ended event
		// is dispatched before we return.
		await ingestTask
	}
 
	#sendPong(opaque: bigint): void {
		this.send({
			request: {
				case: 'pong',
				value: create(SessionRequest_PingPongSchema, { opaque }),
			},
		})
	}
 
	#sendStop(): void {
		dbg.log('requesting graceful session stop')
		this.#registry.close()
		this.send({
			request: {
				case: 'sessionStop',
				value: create(SessionRequest_SessionStopSchema, {}),
			},
		})
	}
 
	#markReady(sessionId: bigint): void {
		dbg.log('transport ready (sessionId=%s)', sessionId)
		this.#readyDeferred.resolve()
	}
 
	#markDisconnected(): void {
		dbg.log('transport disconnected, rejecting pending requests')
		this.#registry.reconnect()
		this.#readyDeferred.reject(new Error('Session reconnecting'))
		this.#readyDeferred = createDeferred<void>()
	}
 
	#finalize(reason: unknown): void {
		if (this.#destroyed) {
			return
		}
 
		this.#destroyed = true
 
		let watches = Array.from(this.#watchesByName.values())
		for (let subscription of watches) {
			subscription[Symbol.dispose]()
		}
 
		this.#registry.destroy(reason)
 
		// Replace the deferred with an already-rejected one so that any future
		// waitReady() call rejects immediately. The old deferred is safe to
		// reject because createDeferred attaches a no-op .catch() guard.
		this.#readyDeferred.reject(reason)
		this.#readyDeferred = createDeferred<void>()
		this.#readyDeferred.reject(reason)
 
		this.#ac.abort(reason)
	}
 
	#handleWatch(reqId: bigint, change: WatchChange): void {
		let subscription = this.#watchesByReqId.get(reqId)
		if (!subscription) {
			return
		}
 
		Eif (subscription.reqId === reqId) {
			subscription.queue.push(change)
		}
	}
}