All files / packages/topic/src/reader transport.ts

91.25% Statements 73/80
80% Branches 20/25
100% Functions 14/14
91.25% Lines 73/80

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                                                  22x       22x 22x 22x       22x                                     10734x 10734x 10734x 10734x     10734x 10734x   10734x                           10751x     10751x     10734x               10734x       10751x             11110x             25x 18x   7x 7x 7x 7x                 7x                   10734x       10734x       11117x 11117x     11117x 11117x       10751x   10751x 10751x   10751x                             10751x   10751x 10751x 10751x   10751x       10751x   10751x 11262x       11262x 11x 11x       11x     11251x 10738x       10738x       10738x     513x 1x     513x     10693x 10693x   54x 54x             10751x 10751x 10751x 10751x       32236x 32236x 32236x   32236x 32236x 32236x   32236x 21485x     10751x 10751x 32236x      
import { create } from '@bufbuild/protobuf'
import { StatusIds_StatusCode } from '@ydbjs/api/operation'
import {
	type StreamReadMessage_FromClient,
	StreamReadMessage_FromClientSchema,
	StreamReadMessage_InitRequestSchema,
	type StreamReadMessage_InitRequest_TopicReadSettings,
	TopicServiceDefinition,
	UpdateTokenRequestSchema,
} from '@ydbjs/api/topic'
import type { Driver } from '@ydbjs/core'
import { loggers } from '@ydbjs/debug'
import { YDBError } from '@ydbjs/error'
import { type MachineRuntime, createMachineRuntime } from '@ydbjs/fsm'
import { AsyncPriorityQueue } from '@ydbjs/fsm/queue'
 
import {
	type TransportCtx,
	type TransportEffect,
	type TransportEvent,
	type TransportOutput,
	type TransportState,
	transportTransition,
} from './transport-state.js'
 
let dbg = loggers.topic.extend('reader').extend('transport')
 
// Priorities keep the init handshake ahead of everything and token refreshes
// ahead of the read/commit backlog on the single outgoing stream.
let PRIORITY_INIT = 100
let PRIORITY_TOKEN = 10
let PRIORITY_DEFAULT = 0
// Partition-session control frames (start/stop responses) must overtake queued
// data-plane frames (commits at PRIORITY_DEFAULT): a reconciled commit may never
// reach the wire before the start response that makes its session live.
export const PRIORITY_CONTROL = 10
 
export type InitParams = {
	consumer: string
	topicsReadSettings: StreamReadMessage_InitRequest_TopicReadSettings[]
	readerName?: string
	autoPartitioningSupport?: boolean
}
 
// Owns one streamRead gRPC stream at a time. Reconnecting the underlying stream
// is transparent to the reader FSM: each open pushes a fresh init request and the
// ingest task forwards server messages (verbatim, except the init handshake) as
// transport outputs.
export class ReaderTransport {
	#driver: Driver
	#params: InitParams
 
	#machine: MachineRuntime<TransportState, TransportCtx, TransportEvent, TransportOutput>
 
	#streamAC: AbortController | null = null
	#streamInput: AsyncPriorityQueue<StreamReadMessage_FromClient> | null = null
	#streamTask: Promise<void> | null = null
	#tokenPending = false
 
	constructor(driver: Driver, params: InitParams) {
		this.#driver = driver
		this.#params = params
 
		this.#machine = createMachineRuntime<
			TransportState,
			TransportCtx,
			{},
			TransportEvent,
			TransportEffect,
			TransportOutput
		>({
			initialState: 'idle',
			ctx: {},
			env: {},
			transition: transportTransition,
			effects: {
				'transport.effect.open_stream': () => {
					this.#openStream()
				},
				'transport.effect.close_stream': async () => {
					await this.#closeStream()
				},
				'transport.effect.finalize': async () => {
					await this.#closeStream()
				},
			},
		})
	}
 
	// The reader FSM ingests this to receive stream lifecycle events.
	get events(): AsyncIterable<TransportOutput> {
		return this.#machine
	}
 
	connect(): void {
		this.#machine.dispatch({ type: 'transport.connect' })
	}
 
	// Enqueue a client message (read request, commit, partition-session response)
	// on the current stream. No-op if the stream is gone — the reader FSM rebuilds
	// its outgoing state on the next init anyway.
	send(message: StreamReadMessage_FromClient, priority: number = PRIORITY_DEFAULT): boolean {
		return this.#push(message, priority)
	}
 
	async sendUpdateToken(): Promise<void> {
		// Coalesce: keep at most one un-acknowledged update-token queued (see the
		// writer transport for the rationale) — an interval-driven push on a wedged
		// stream would otherwise pile up unboundedly.
		if (this.#tokenPending) {
			return
		}
		this.#tokenPending = true
		try {
			let token = await this.#driver.token
			let queued = this.#push(
				create(StreamReadMessage_FromClientSchema, {
					clientMessage: {
						case: 'updateTokenRequest',
						value: create(UpdateTokenRequestSchema, { token }),
					},
				}),
				PRIORITY_TOKEN
			)
			Iif (!queued) {
				this.#tokenPending = false // nothing landed on the wire; allow a retry
			}
		} catch (error) {
			this.#tokenPending = false
			throw error
		}
	}
 
	close(): void {
		this.#machine.dispatch({ type: 'transport.close' })
	}
 
	destroy(reason?: unknown): void {
		this.#machine.dispatch({ type: 'transport.destroy', reason })
	}
 
	#push(message: StreamReadMessage_FromClient, priority: number): boolean {
		let input = this.#streamInput
		Iif (!input || input.isClosed) {
			return false
		}
		input.push(message, priority)
		return true
	}
 
	#openStream(): void {
		void this.#closeStream()
 
		let ac = new AbortController()
		let input = new AsyncPriorityQueue<StreamReadMessage_FromClient>()
 
		input.push(
			create(StreamReadMessage_FromClientSchema, {
				clientMessage: {
					case: 'initRequest',
					value: create(StreamReadMessage_InitRequestSchema, {
						consumer: this.#params.consumer,
						topicsReadSettings: this.#params.topicsReadSettings,
						readerName: this.#params.readerName ?? '',
						autoPartitioningSupport: this.#params.autoPartitioningSupport ?? false,
					}),
				},
			}),
			PRIORITY_INIT
		)
 
		let dispatch = this.#machine.dispatch.bind(this.#machine)
 
		let task = (async () => {
			try {
				await this.#driver.ready(ac.signal)
 
				let stream = this.#driver
					.createClient(TopicServiceDefinition)
					.streamRead(input, { signal: ac.signal })
 
				dbg.log('stream opened (consumer=%s)', this.#params.consumer)
 
				for await (let response of stream) {
					Iif (ac.signal.aborted) {
						return
					}
 
					if (response.status !== StatusIds_StatusCode.SUCCESS) {
						dbg.log('recv non-success status %d', response.status)
						dispatch({
							type: 'transport.error',
							error: new YDBError(response.status, response.issues),
						})
						return
					}
 
					if (response.serverMessage.case === 'initResponse') {
						dbg.log(
							'recv initResponse (sessionId=%s)',
							response.serverMessage.value.sessionId
						)
						dispatch({
							type: 'transport.init',
							sessionId: response.serverMessage.value.sessionId,
						})
						continue
					}
 
					if (response.serverMessage.case === 'updateTokenResponse') {
						this.#tokenPending = false
					}
 
					dispatch({ type: 'transport.message', message: response })
				}
 
				dbg.log('stream ended')
				dispatch({ type: 'transport.ended' })
			} catch (error) {
				Eif (ac.signal.aborted) {
					return
				}
				dbg.log('stream error: %O', error)
				dispatch({ type: 'transport.error', error })
			}
		})()
 
		this.#streamAC = ac
		this.#streamInput = input
		this.#streamTask = task
		this.#tokenPending = false // fresh stream — the previous token, if any, is gone
	}
 
	async #closeStream(): Promise<void> {
		let ac = this.#streamAC
		let input = this.#streamInput
		let task = this.#streamTask
 
		this.#streamAC = null
		this.#streamInput = null
		this.#streamTask = null
 
		if (!ac) {
			return
		}
 
		ac.abort(new Error('Stream disposed'))
		input?.close()
		await task
	}
}