All files / packages/topic/src/reader reader-runtime.ts

92.56% Statements 112/121
84.33% Branches 70/83
96.29% Functions 26/27
92.56% Lines 112/121

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                                                        22x     22x 22x 22x     22x 22x   22x 22x 22x                                                 22x 22x   22x 21518x   10751x   17x       10738x       5x         5x   2x         22x 17x 17x     22x 21518x   10751x   17x       10738x     5x   5x   2x           22x 107906x     22x 107906x 107906x 21497x 21497x       22x 11271x 11271x   10738x   20x         513x               22x     513x 513x   267x           145x 145x     145x                   15x             75x         5x           5x               1x               10734x           10734x                                         10734x               10734x                       33149x 33149x     33149x       10751x 10751x       10873x                     86x                                     4x                       5x                       25x           10734x                             145x 145x       145x 13x 13x         11x 5x 5x     1x       144x                               5x 5x   5x 3x 3x           5x                       142x                                       21518x   21518x     21518x   21518x 21518x 21518x   21518x 25x   20x 20x     21518x 21518x       86388x       10734x     10734x   10734x 1x   10734x   10734x 10734x 10734x         10734x   10734x 10734x   10734x    
import { create } from '@bufbuild/protobuf'
import type { StreamReadMessage_FromServer } from '@ydbjs/api/topic'
import { StreamReadMessage_FromClientSchema } from '@ydbjs/api/topic'
import type { Driver } from '@ydbjs/core'
import { loggers } from '@ydbjs/debug'
import { type MachineRuntime, createMachineRuntime } from '@ydbjs/fsm'
 
import { parseReadSettings } from './read-settings.js'
import { PRIORITY_CONTROL, ReaderTransport } from './transport.js'
import type { TransportOutput } from './transport-state.js'
import {
	type ReaderCtx,
	type ReaderEffect,
	type ReaderEvent,
	type ReaderOutput,
	type ReaderState,
	type TimerName,
	type TimerRef,
	createReaderCtx,
	readerTransition,
} from './reader-state.js'
import type {
	TopicReaderOptions,
	onPartitionSessionStartCallback,
	onPartitionSessionStopCallback,
} from './types.js'
 
// Watchdog for a connect that never produces an init response.
let DEFAULT_START_TIMEOUT_MS = 30_000
// Unbounded by default: the reader reconnects forever (waits for the server / topic).
// A finite `recoveryWindowMs` option re-imposes a terminal deadline.
let DEFAULT_RECOVERY_WINDOW_MS = Infinity
let DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_MS = 30_000
let DEFAULT_UPDATE_TOKEN_INTERVAL_MS = 60_000
// Bound how long pending commits are held for a partition that was stopped
// (rebalanced away) and never re-Started before rejecting them.
let DEFAULT_PARTITION_REASSIGN_GC_MS = 60_000
let COMMIT_STATUS_INTERVAL_MS = 1000
// Single source of truth — the facade imports it for its diagnostics config snapshot.
export const DEFAULT_MAX_BUFFER_BYTES = 8n * 1024n * 1024n
let BACKOFF_BASE_MS = 50
let BACKOFF_MAX_MS = 30_000
 
// I/O handles and config — visible to effect handlers only, never to the transition.
type ReaderEnv = {
	transport: ReaderTransport
	onPartitionSessionStart?: onPartitionSessionStartCallback
	onPartitionSessionStop?: onPartitionSessionStopCallback
 
	startTimeoutMs: number
	updateTokenIntervalMs: number
	gracefulShutdownTimeoutMs: number
	partitionReassignGcMs: number
 
	ac: AbortController
	closedDeferred: PromiseWithResolvers<void>
	isFinalized: boolean
	timers: Map<string, ReturnType<typeof setTimeout>>
}
 
type FullCtx = ReaderCtx & ReaderEnv
 
export type ReaderRuntime = {
	machine: MachineRuntime<ReaderState, ReaderCtx, ReaderEvent, ReaderOutput>
}
 
let dbg = loggers.topic.extend('reader')
let evdbg = dbg.extend('event')
 
let timerEvent = function timerEvent(ref: TimerRef): ReaderEvent {
	switch (ref.which) {
		case 'start_timeout':
			return { type: 'reader.timer.start_timeout' }
		case 'retry_backoff':
			return { type: 'reader.timer.retry_backoff' }
		case 'recovery_window':
			return { type: 'reader.timer.recovery_window' }
		case 'update_token':
			return { type: 'reader.timer.update_token' }
		case 'graceful_timeout':
			return { type: 'reader.timer.graceful_timeout' }
		case 'partition_graceful_timeout':
			return {
				type: 'reader.timer.partition_graceful_timeout',
				partitionKey: ref.partitionKey,
			}
		case 'partition_reassign_gc':
			return { type: 'reader.timer.partition_reassign_gc', partitionKey: ref.partitionKey }
		case 'partition_commit_status':
			return { type: 'reader.timer.partition_commit_status', partitionKey: ref.partitionKey }
	}
}
 
// Equal-jitter exponential backoff: half fixed, half random in [d/2, d].
let backoffDelay = function backoffDelay(attempts: number): number {
	let capped = Math.min(BACKOFF_BASE_MS * 2 ** attempts, BACKOFF_MAX_MS)
	return Math.round(capped / 2 + Math.random() * (capped / 2))
}
 
let delayFor = function delayFor(ctx: FullCtx, which: TimerName): number {
	switch (which) {
		case 'start_timeout':
			return ctx.startTimeoutMs
		case 'retry_backoff':
			return backoffDelay(ctx.attempts)
		case 'recovery_window':
			return ctx.recoveryWindowMs
		case 'update_token':
			return ctx.updateTokenIntervalMs
		case 'graceful_timeout':
		case 'partition_graceful_timeout':
			return ctx.gracefulShutdownTimeoutMs
		case 'partition_reassign_gc':
			return ctx.partitionReassignGcMs
		case 'partition_commit_status':
			return COMMIT_STATUS_INTERVAL_MS
	}
}
 
// Timer key — global key is the name; partition_* timers key per partition so
// concurrently stopping partitions cannot collide.
let timerKey = function timerKey(ref: TimerRef): string {
	return 'partitionKey' in ref ? `${ref.which}:${ref.partitionKey}` : ref.which
}
 
let clearTimerByKey = function clearTimerByKey(ctx: FullCtx, key: string): void {
	let handle = ctx.timers.get(key)
	if (handle) {
		clearTimeout(handle)
		ctx.timers.delete(key)
	}
}
 
let mapTransportOutput = function mapTransportOutput(output: TransportOutput): ReaderEvent | null {
	evdbg.log('transport → reader: %s', output.type)
	switch (output.type) {
		case 'transport.stream.init_response':
			return { type: 'reader.stream.init_response', sessionId: output.sessionId }
		case 'transport.stream.disconnected':
			return {
				type: 'reader.stream.disconnected',
				...('error' in output ? { error: output.error } : {}),
			}
		case 'transport.stream.message':
			return classifyServerMessage(output.message)
		default:
			return null
	}
}
 
// Classify one raw StreamRead server frame into a typed reader event. This is the
// single protobuf → domain boundary; the reader FSM never touches serverMessage.case.
let classifyServerMessage = function classifyServerMessage(
	message: StreamReadMessage_FromServer
): ReaderEvent | null {
	let server = message.serverMessage
	switch (server.case) {
		case 'readResponse':
			return {
				type: 'reader.stream.read_response',
				partitionData: server.value.partitionData,
				bytesSize: server.value.bytesSize,
			}
		case 'startPartitionSessionRequest': {
			let ps = server.value.partitionSession
			Iif (!ps) {
				return null
			}
			return {
				type: 'reader.stream.start_partition',
				partitionSessionId: ps.partitionSessionId,
				partitionId: ps.partitionId,
				path: ps.path,
				committedOffset: server.value.committedOffset,
				partitionOffsets: server.value.partitionOffsets ?? { start: 0n, end: 0n },
			}
		}
		case 'stopPartitionSessionRequest':
			return {
				type: 'reader.stream.stop_partition',
				partitionSessionId: server.value.partitionSessionId,
				graceful: server.value.graceful,
				committedOffset: server.value.committedOffset,
			}
		case 'commitOffsetResponse':
			return {
				type: 'reader.stream.commit_response',
				committed: server.value.partitionsCommittedOffsets,
			}
		case 'partitionSessionStatusResponse':
			return {
				type: 'reader.stream.partition_status',
				partitionSessionId: server.value.partitionSessionId,
				committedOffset: server.value.committedOffset,
			}
		case 'endPartitionSession':
			return {
				type: 'reader.stream.end_partition',
				partitionSessionId: server.value.partitionSessionId,
				childPartitionIds: server.value.childPartitionIds,
				adjacentPartitionIds: server.value.adjacentPartitionIds,
			}
		// Direct-read / token frames — nothing for the reader FSM to route.
		default:
			return null
	}
}
 
// Builds the reader FSM and binds its effects to real I/O: transport connect/send,
// timers with equal-jitter backoff, the async onPartitionSessionStart handshake, and
// transport-output → reader-event mapping.
export function createReaderRuntime(driver: Driver, options: TopicReaderOptions): ReaderRuntime {
	let transport = new ReaderTransport(driver, {
		consumer: options.consumer,
		topicsReadSettings: parseReadSettings(options.topic),
		autoPartitioningSupport: options.autoPartitioningSupport ?? false,
	})
 
	let env: ReaderEnv = {
		transport,
		...(options.onPartitionSessionStart && {
			onPartitionSessionStart: options.onPartitionSessionStart,
		}),
		...(options.onPartitionSessionStop && {
			onPartitionSessionStop: options.onPartitionSessionStop,
		}),
 
		startTimeoutMs: DEFAULT_START_TIMEOUT_MS,
		updateTokenIntervalMs: options.updateTokenIntervalMs ?? DEFAULT_UPDATE_TOKEN_INTERVAL_MS,
		gracefulShutdownTimeoutMs:
			options.gracefulShutdownTimeoutMs ?? DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_MS,
		partitionReassignGcMs: DEFAULT_PARTITION_REASSIGN_GC_MS,
 
		ac: new AbortController(),
		closedDeferred: Promise.withResolvers<void>(),
		isFinalized: false,
		timers: new Map(),
	}
 
	let ctx = createReaderCtx(
		{ maxBufferBytes: options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES },
		{
			retryOnSchemeError: options.retryOnSchemeError ?? false,
			recoveryWindowMs: options.recoveryWindowMs ?? DEFAULT_RECOVERY_WINDOW_MS,
		}
	)
 
	let machine = createMachineRuntime<
		ReaderState,
		ReaderCtx,
		ReaderEnv,
		ReaderEvent,
		ReaderEffect,
		ReaderOutput
	>({
		initialState: 'idle',
		ctx,
		env,
		transition: (fullCtx, event, runtime) => {
			let result = readerTransition(fullCtx, event, runtime)
			Iif (evdbg.enabled) {
				evdbg.log('%s: %s → %s', event.type, runtime.state, result?.state ?? runtime.state)
			}
			return result
		},
		effects: {
			'reader.effect.transport.connect': (fullCtx) => {
				dbg.log('connect')
				fullCtx.transport.connect()
			},
 
			'reader.effect.send.read_request': (fullCtx, effect) => {
				fullCtx.transport.send(
					create(StreamReadMessage_FromClientSchema, {
						clientMessage: {
							case: 'readRequest',
							value: { bytesSize: effect.bytesSize },
						},
					})
				)
			},
 
			'reader.effect.send.commit': (fullCtx, effect) => {
				fullCtx.transport.send(
					create(StreamReadMessage_FromClientSchema, {
						clientMessage: {
							case: 'commitOffsetRequest',
							value: {
								commitOffsets: [
									{
										partitionSessionId: effect.partitionSessionId,
										offsets: effect.ranges,
									},
								],
							},
						},
					})
				)
			},
 
			'reader.effect.send.stop_response': (fullCtx, effect) => {
				// Partition-session handshake — keep it ahead of the read/commit backlog.
				fullCtx.transport.send(
					create(StreamReadMessage_FromClientSchema, {
						clientMessage: {
							case: 'stopPartitionSessionResponse',
							value: { partitionSessionId: effect.partitionSessionId },
						},
					}),
					PRIORITY_CONTROL
				)
			},
 
			'reader.effect.send.partition_status': (fullCtx, effect) => {
				fullCtx.transport.send(
					create(StreamReadMessage_FromClientSchema, {
						clientMessage: {
							case: 'partitionSessionStatusRequest',
							value: { partitionSessionId: effect.partitionSessionId },
						},
					}),
					PRIORITY_CONTROL
				)
			},
 
			'reader.effect.send.update_token': (fullCtx) => {
				void fullCtx.transport.sendUpdateToken().catch(() => {
					// Token refresh failures surface as a stream error on the next read.
				})
			},
 
			'reader.effect.transport.close': (fullCtx) => {
				fullCtx.transport.close()
			},
 
			// The one effect where the runtime makes a domain decision, by necessity: the
			// StartPartitionSessionResponse's read_offset/commit_offset come from the async
			// `onPartitionSessionStart` hook (typically an external offset-store lookup — I/O),
			// which the pure synchronous transition cannot await. So the hook call, the
			// reassign guard, and the response are built here — an intrinsic async protocol
			// handshake, not leaked policy. The FSM owns "the partition started" (the
			// reader.partition.started output + this effect); the runtime owns the async ack.
			'reader.effect.partition.start_hook': (fullCtx, effect, runtime) => {
				// The user hook runs DETACHED: awaiting it here would freeze the whole
				// drain loop (every partition, commits, even destroy) on user code. Its
				// result re-enters the machine as reader.partition.start_ready, so the
				// answer-or-not decision is made against fresh state in the transition.
				void (async () => {
					let session = fullCtx.partitions.get(effect.partitionKey)?.session
					let readOffset: bigint | undefined
					let commitOffset: bigint | undefined
 
					if (fullCtx.onPartitionSessionStart && session) {
						try {
							let result = await fullCtx.onPartitionSessionStart(
								session,
								effect.committedOffset,
								effect.partitionOffsets
							)
							if (result) {
								readOffset = result.readOffset
								commitOffset = result.commitOffset
							}
						} catch (error) {
							dbg.log('onPartitionSessionStart threw: %O', error)
						}
					}
 
					runtime.dispatch({
						type: 'reader.partition.start_ready',
						partitionSessionId: effect.partitionSessionId,
						partitionKey: effect.partitionKey,
						grantId: effect.grantId,
						...(readOffset !== undefined && { readOffset }),
						...(commitOffset !== undefined && { commitOffset }),
					})
				})()
			},
 
			// The graceful-stop counterpart of start_hook: the session is still
			// deliverable and committable while the user callback runs — this is the
			// documented "last chance to commit" of the soft-stop contract. The stop
			// response goes out only after stop_ready AND the pending commits drain.
			'reader.effect.partition.stop_hook': (fullCtx, effect, runtime) => {
				void (async () => {
					let session = fullCtx.partitions.get(effect.partitionKey)?.session
 
					if (fullCtx.onPartitionSessionStop && session) {
						try {
							await fullCtx.onPartitionSessionStop(session, effect.committedOffset)
						} catch (error) {
							dbg.log('onPartitionSessionStop threw: %O', error)
						}
					}
 
					runtime.dispatch({
						type: 'reader.partition.stop_ready',
						partitionKey: effect.partitionKey,
						grantId: effect.grantId,
					})
				})()
			},
 
			'reader.effect.send.start_response': (fullCtx, effect) => {
				// Omit read_offset/commit_offset unless the hook set them: the server
				// validates read_offset >= committed offset, so a spurious 0 would be
				// rejected when the committed offset is already past 0.
				fullCtx.transport.send(
					create(StreamReadMessage_FromClientSchema, {
						clientMessage: {
							case: 'startPartitionSessionResponse',
							value: {
								partitionSessionId: effect.partitionSessionId,
								...(effect.readOffset !== undefined && {
									readOffset: effect.readOffset,
								}),
								...(effect.commitOffset !== undefined && {
									commitOffset: effect.commitOffset,
								}),
							},
						},
					}),
					PRIORITY_CONTROL
				)
			},
 
			'reader.effect.timer.schedule': (fullCtx, effect, runtime) => {
				let key = timerKey(effect)
				// The recovery window is armed once per reconnect saga.
				Iif (effect.which === 'recovery_window' && fullCtx.timers.has(key)) {
					return
				}
				clearTimerByKey(fullCtx, key)
 
				let repeating = effect.which === 'update_token'
				let delay = delayFor(fullCtx, effect.which)
				let event = timerEvent(effect)
 
				let handle = repeating
					? setInterval(() => runtime.dispatch(event), delay)
					: setTimeout(() => {
							fullCtx.timers.delete(key)
							runtime.dispatch(event)
						}, delay)
 
				handle.unref?.()
				fullCtx.timers.set(key, handle)
			},
 
			'reader.effect.timer.clear': (fullCtx, effect) => {
				clearTimerByKey(fullCtx, timerKey(effect))
			},
 
			'reader.effect.finalize': (fullCtx, effect) => {
				Iif (fullCtx.isFinalized) {
					return
				}
				fullCtx.isFinalized = true
 
				for (let handle of fullCtx.timers.values()) {
					clearTimeout(handle)
				}
				fullCtx.timers.clear()
 
				fullCtx.transport.destroy(effect.reason)
				fullCtx.ac.abort(effect.reason)
				fullCtx.closedDeferred.resolve()
			},
		},
	})
 
	machine.ingest(transport.events, mapTransportOutput)
 
	dbg.log('starting reader on consumer %s', options.consumer)
	machine.dispatch({ type: 'reader.start' })
 
	return { machine }
}