All files / packages/core/src/endpoints endpoints-runtime.ts

97.87% Statements 276/282
91.19% Branches 145/159
96.77% Functions 60/62
99.23% Lines 259/261

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 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001                                                                                                55x   55x                                         55x 55x 55x     55x 55x 55x 55x                                                                                                                   55x 6x 6x     55x 21834x 21834x 311x 311x               55x         183x 3x 3x 3x 2x 2x   3x       180x     183x 183x 183x 183x 183x 183x 183x 183x 183x 40x 40x             55x 10630x 5315x 5315x 5315x 5315x 5315x             5315x       55x 5339x     55x 5337x     55x 5321x 5314x 5314x 5x   5313x     55x 50x 50x 42x   50x                 55x       5321x   5321x 10580x               5321x 5x                   5321x                           5321x 8x                 5321x         55x               5334x         5334x 5334x 1x     5334x     5334x 5334x 5334x 5334x   5334x       5321x 5321x   5321x       5321x 5321x             13x     11x 11x           5334x 5334x           314x 314x   314x   314x                 314x               314x 10x   3x 3x   314x 314x       21520x               5x 5x 2x 2x   3x 3x 3x       183x                 81x 81x 150x 150x 149x   81x 149x   81x 1x                 4x 4x 3x 3x 1x 1x   2x 1x 1x   1x 1x       1x 1x                 5315x                                         5315x         5315x           5315x 5315x       603x         689x 686x 689x 685x           6x 6x 6x 4x             6x           1x             667x       614x 614x 587x 587x   27x     27x 1x 1x                               4x                           3x       7x               682x 682x       84x 84x       5232x               689x   689x     689x 42x 42x 3x 39x                 39x   42x                     5315x 5315x 5315x             5315x   5315x 5315x         5315x 5315x 11459x   5532x       5532x 5532x 5532x       184x   180x               180x   4x 4x 4x                 4x             4x   1x 1x 1x 1x                 1x               1x         120x 120x 120x             120x     11x 11x           11x   107x 107x 107x       107x   5x 5x         5x   5315x 5315x         5315x 5315x           2x           5532x 5532x 5532x           50x                     5532x 5532x   5532x       5532x 2x 2x               55x           6x                                                     55x     5315x 20x           5315x                                                                 5315x   5315x           5315x                             5315x       5315x                           5315x   5315x     55x     21x                             55x     36x                       36x       36x     55x 9x   2x   1x   1x   1x   1x   2x   1x      
// The effectful half of the endpoints engine: the EndpointPool facade + the
// createEndpointsRuntime wiring. Owns all I/O — the discovery call, gRPC
// channels, timers, and the clock — while the pure FSM (endpoints-state.ts)
// owns the lifecycle and health decisions.
//
// RCU two-plane: the FSM emits an immutable RoutingSnapshot; #consume swaps
// #snapshot by reference; the synchronous acquire()/acquireNode() read that
// reference, select (pure), and materialize a channel — never dispatching on
// the hot path except a cheap fire-and-forget RPC-outcome report.
 
import { channel as dc, tracingChannel } from 'node:diagnostics_channel'
 
import { create } from '@bufbuild/protobuf'
import { connectivityState } from '@grpc/grpc-js'
import { abortable, linkSignals } from '@ydbjs/abortable'
import { PileState_State } from '@ydbjs/api/bridge'
import { EndpointInfoSchema } from '@ydbjs/api/discovery'
import type { ListEndpointsResult, EndpointInfo as ProtoEndpointInfo } from '@ydbjs/api/discovery'
import { loggers } from '@ydbjs/debug'
import { isRetryableError } from '@ydbjs/retry'
import { type MachineRuntime, createMachineRuntime } from '@ydbjs/fsm'
import type { ChannelCredentials, ChannelOptions } from 'nice-grpc'
 
import { type Connection, GrpcConnection } from '../conn.js'
import type { DriverIdentity } from '../driver-identity.js'
import { EndpointsUnavailableError } from '../errors.js'
import type { DriverHooks, EndpointInfo } from '../hooks.js'
import { safeHook } from '../hooks.js'
import {
	type DiscoveredEndpoint,
	type EndpointsCtx,
	type EndpointsEffect,
	type EndpointsEvent,
	type EndpointsOutput,
	type EndpointsState,
	type PileState,
	type PileStatus,
	computeRoundDiff,
	createEndpointsCtx,
	endpointsTransition,
} from './endpoints-state.js'
import {
	EMPTY_SNAPSHOT,
	type EndpointRef,
	type RoutingSnapshot,
	selectEndpoint,
} from './snapshot.js'
 
let dbg = loggers.driver.extend('endpoints')
 
let discoveryCh = tracingChannel<{ driver: DriverIdentity }>('tracing:ydb:driver.discovery')
 
// A discovery round's domain result. The real Driver wiring passes a closure
// that maps the proto ListEndpointsResult via `mapDiscoveryResult`; tests pass
// this shape directly. Keeping the seam DTO-shaped is what makes the module
// Driver-independent.
export type DiscoveryResult = {
	endpoints: DiscoveredEndpoint[]
	selfLocation: string
	pileStates: PileState[]
}
 
// The single injectable discovery dependency (idempotent, one round per call —
// retry/backoff is the FSM's job, not this seam's).
export type ListEndpoints = (signal: AbortSignal) => Promise<DiscoveryResult>
 
// The injectable channel seam (default = GrpcConnection). This is what makes the
// pool fully testable with drivable fake connections and retires the old
// POOL_*_FOR_TESTING symbols.
export type ConnectionFactory = (ref: EndpointRef) => Connection
 
export const DEFAULT_DISCOVERY_TIMEOUT_MS = 10_000
export const DEFAULT_DISCOVERY_INTERVAL_MS = 60_000
export const DEFAULT_IDLE_INTERVAL_MS = 60_000
// Retired-connection idle grace: kept this long (absorbing flaps) before it is
// eligible to be reaped when idle and un-returned by discovery.
export const DEFAULT_RETIRED_GRACE_MS = 300_000
export const DEFAULT_CLOSE_DEADLINE_MS = 10_000
export const DEFAULT_BACKOFF_BASE_MS = 50
export const DEFAULT_BACKOFF_MAX_MS = 30_000
 
type RemovedReason = 'idle' | 'pool_close'
 
type EndpointsEnv = {
	identity: DriverIdentity
	hooks: DriverHooks | undefined
	listEndpoints: ListEndpoints
	connectionFactory: ConnectionFactory
 
	// I/O-owned channel state — NEVER touched by the transition.
	channels: Map<bigint, Connection>
	retiredChannels: Map<bigint, Connection>
	pinnedChannels: Map<bigint, Connection>
	banStart: Map<bigint, number>
	retiredAt: Map<bigint, number>
	// When a retired channel was first seen in TRANSIENT_FAILURE — used to require
	// a SUSTAINED failure (not one blip) before reaping it.
	transientSince: Map<bigint, number>
	// Per-node in-flight RPC count, maintained by BalancedChannel around each call.
	// Lets graceful close finalize as soon as a channel's streams have drained.
	inflight: Map<bigint, number>
	// While closing: the nodeIds whose channels are still busy and must drain
	// before finalize. Undefined outside the closing drain.
	draining: Set<bigint> | undefined
 
	discoveryTimeoutMs: number
	discoveryIntervalMs: number
	idleIntervalMs: number
	retiredGraceMs: number
	closeDeadlineMs: number
	backoffBaseMs: number
	backoffMaxMs: number
 
	ac: AbortController
	readyDeferred: PromiseWithResolvers<void>
	closedDeferred: PromiseWithResolvers<void>
	isFinalized: boolean
	timers: Map<string, ReturnType<typeof setTimeout>>
 
	roundStart: number
	initAt: number
	readyAt: number | undefined
 
	// Bridge (2DC) observability state (never read by the transition).
	preferPrimaryPile: boolean
	// Last observed pile roster: the prev value for pile.changed detection and the
	// current roster for pool.stats. Updated once per applied discovery round.
	lastPileStates: PileState[]
	// Whether the pool last reported serving from the SYNCHRONIZED fallback tier
	// (primary pile empty under preferPrimaryPile) — drives edge-triggered events.
	prevFallbackActive: boolean
}
 
type FullCtx = EndpointsCtx & EndpointsEnv
 
// ── Timers (equal-jitter backoff, mirrors reader-runtime.ts) ────────────────
 
let backoffDelay = function backoffDelay(env: EndpointsEnv, attempts: number): number {
	let capped = Math.min(env.backoffBaseMs * 2 ** attempts, env.backoffMaxMs)
	return Math.round(capped / 2 + Math.random() * (capped / 2))
}
 
let clearTimerByKey = function clearTimerByKey(env: EndpointsEnv, key: string): void {
	let handle = env.timers.get(key)
	if (handle !== undefined) {
		clearTimeout(handle)
		env.timers.delete(key)
	}
}
 
// Physically close a materialized channel. `store: 'pinned'` closes only the pin
// (leaving a discovered channel that shares the nodeId intact); otherwise the
// channel is dropped from whichever store holds it. No diagnostics here — the FSM
// emits the `removed` output and the facade republishes it.
let dropChannel = function dropChannel(
	env: EndpointsEnv,
	nodeId: bigint,
	store: 'any' | 'pinned' = 'any'
): void {
	if (store === 'pinned') {
		let pinned = env.pinnedChannels.get(nodeId)
		env.pinnedChannels.delete(nodeId)
		if (pinned !== undefined) {
			dbg.log('close pinned channel to node %d', nodeId)
			pinned.close()
		}
		return
	}
 
	let conn =
		env.channels.get(nodeId) ??
		env.retiredChannels.get(nodeId) ??
		env.pinnedChannels.get(nodeId)
	env.channels.delete(nodeId)
	env.retiredChannels.delete(nodeId)
	env.pinnedChannels.delete(nodeId)
	env.banStart.delete(nodeId)
	env.retiredAt.delete(nodeId)
	env.transientSince.delete(nodeId)
	env.inflight.delete(nodeId)
	env.draining?.delete(nodeId)
	if (conn !== undefined) {
		dbg.log('close channel to node %d', nodeId)
		conn.close()
	}
}
 
// Idempotent teardown of all I/O: clear timers, drop every channel, abort the
// pool signal. Called by the `finalize` effect on a clean close and by #consume's
// finally as a fault backstop — one owner so the two paths can't drift.
let finalizeEnv = function finalizeEnv(env: EndpointsEnv): void {
	if (env.isFinalized) return
	env.isFinalized = true
	env.draining = undefined
	for (let handle of env.timers.values()) clearTimeout(handle)
	env.timers.clear()
	for (let nodeId of [
		...env.channels.keys(),
		...env.retiredChannels.keys(),
		...env.pinnedChannels.keys(),
	]) {
		dropChannel(env, nodeId)
	}
	Eif (!env.ac.signal.aborted) env.ac.abort(new Error('Endpoints finalized'))
}
 
// Bridge topology helpers — pure, shared by the round + pool.stats publishers.
let primaryPileName = function primaryPileName(piles: PileState[]): string | undefined {
	return piles.find((p) => p.status === 'PRIMARY')?.pileName
}
 
let pileRoster = function pileRoster(piles: PileState[]): { name: string; status: PileStatus }[] {
	return piles.map((p) => ({ name: p.pileName, status: p.status }))
}
 
let pilesEqual = function pilesEqual(a: PileState[], b: PileState[]): boolean {
	if (a.length !== b.length) return false
	let byName = new Map(a.map((p) => [p.pileName, p.status]))
	for (let p of b) {
		if (byName.get(p.pileName) !== p.status) return false
	}
	return true
}
 
let countPileNodes = function countPileNodes(snapshot: RoutingSnapshot, pile: string): number {
	let n = 0
	for (let ref of snapshot.byNodeId.values()) {
		if (ref.pile === pile) n++
	}
	return n
}
 
// Publish the round-derived connection diagnostics + discovery.completed + any
// pile topology change. Called INSIDE the discovery tracePromise (before the
// round is dispatched, so it runs against the pre-round registry) so
// @ydbjs/telemetry attaches these to the discovery span — the async #consume
// loop has no active span. Uses the same `computeRoundDiff` rule the FSM's
// applyRound uses, so the two can't drift.
let publishRoundDiagnostics = function publishRoundDiagnostics(
	ctx: FullCtx,
	result: DiscoveryResult
): void {
	let { added, retired } = computeRoundDiff(ctx.byNodeId, result.endpoints)
 
	for (let a of added) {
		dc('ydb:driver.connection.added').publish({
			driver: ctx.identity,
			nodeId: a.nodeId,
			address: a.address,
			location: a.location,
			pile: a.pile,
		})
	}
	for (let r of retired) {
		dc('ydb:driver.connection.retired').publish({
			driver: ctx.identity,
			nodeId: r.nodeId,
			address: r.address,
			location: r.location,
			pile: r.pile,
			reason: r.reason,
		})
	}
 
	dc('ydb:driver.discovery.completed').publish({
		driver: ctx.identity,
		addedCount: added.length,
		removedCount: retired.length,
		totalCount: result.endpoints.length,
		duration: Date.now() - ctx.roundStart,
		selfLocation: result.selfLocation,
		piles: pileRoster(result.pileStates),
		primaryPile: primaryPileName(result.pileStates),
	})
 
	// Topology: emit pile.changed only when the roster/statuses differ from the
	// last applied round (the first bridge round reports `before: []`). Refresh
	// lastPileStates regardless — pool.stats reads it as the current roster.
	if (!pilesEqual(ctx.lastPileStates, result.pileStates)) {
		dc('ydb:driver.pile.changed').publish({
			driver: ctx.identity,
			selfLocation: result.selfLocation,
			before: pileRoster(ctx.lastPileStates),
			after: pileRoster(result.pileStates),
			primaryBefore: primaryPileName(ctx.lastPileStates),
			primaryAfter: primaryPileName(result.pileStates),
		})
	}
	ctx.lastPileStates = result.pileStates
}
 
// ── Effect handlers ─────────────────────────────────────────────────────────
 
let effects = {
	// Discovery is unary-per-round (not a stream) — a timer/effect loop, not
	// ingest. tracePromise preserves the tracing:ydb:driver.discovery contract.
	// The round-derived diagnostics (connection.added/retired + discovery.completed)
	// are published INSIDE the tracePromise callback so @ydbjs/telemetry attaches
	// them to the discovery span — the async #consume loop has no active span, so
	// publishing them there would silently drop them from traces.
	'endpoints.effect.run_discovery_round': (ctx: FullCtx, _effect, runtime) => {
		ctx.roundStart = Date.now()
		// Bound each round independently: a single hung listEndpoints must not
		// wedge the single-flight discovery forever (a timeout is retryable). A
		// clearable timer (not AbortSignal.timeout, whose timer can't be cancelled)
		// so a fast round doesn't leave a live timeout pending until it fires.
		let timeoutAc = new AbortController()
		let timer = setTimeout(
			() => timeoutAc.abort(new Error('discovery round timed out')),
			ctx.discoveryTimeoutMs
		)
		timer.unref?.()
		// linkSignals (not AbortSignal.any) so the listeners are removed on dispose
		// — a churn of short-lived pools must not accumulate signal listeners.
		let link = linkSignals(ctx.ac.signal, timeoutAc.signal)
		void (async () => {
			try {
				let result = await discoveryCh.tracePromise(
					async () => {
						let r = await ctx.listEndpoints(link.signal)
						// An empty result is rejected by the FSM (retryable failure)
						// in every state — publishing added/retired/completed for a
						// round that never applies would lie to subscribers.
						Eif (!ctx.ac.signal.aborted && r.endpoints.length > 0) {
							publishRoundDiagnostics(ctx, r)
						}
						return r
					},
					{ driver: ctx.identity }
				)
				Iif (ctx.ac.signal.aborted) return
				runtime.dispatch({
					type: 'endpoints.discovery.round_succeeded',
					endpoints: result.endpoints,
					selfLocation: result.selfLocation,
					pileStates: result.pileStates,
				})
			} catch (error) {
				if (ctx.ac.signal.aborted) return
				// A per-round timeout (not the pool abort) is retryable — keep the
				// interval/backoff cadence rather than treating it as terminal.
				let timedOut = timeoutAc.signal.aborted
				runtime.dispatch({
					type: 'endpoints.discovery.round_failed',
					error,
					retryable: timedOut || isRetryableError(error, true),
				})
			} finally {
				clearTimeout(timer)
				link[Symbol.dispose]()
			}
		})()
	},
 
	'endpoints.effect.timer.schedule': (ctx: FullCtx, effect, runtime) => {
		let key = effect.which
		clearTimerByKey(ctx, key)
 
		let repeating = effect.which === 'discovery_interval' || effect.which === 'idle_sweep'
		let delay =
			effect.which === 'discovery_interval'
				? ctx.discoveryIntervalMs
				: effect.which === 'idle_sweep'
					? ctx.idleIntervalMs
					: effect.which === 'discovery_backoff'
						? backoffDelay(ctx, ctx.attempts)
						: ctx.closeDeadlineMs
 
		let event: EndpointsEvent =
			effect.which === 'discovery_interval'
				? { type: 'endpoints.timer.discovery_interval' }
				: effect.which === 'idle_sweep'
					? { type: 'endpoints.timer.idle_sweep' }
					: effect.which === 'discovery_backoff'
						? { type: 'endpoints.timer.discovery_backoff' }
						: { type: 'endpoints.timer.close_deadline' }
 
		let handle = repeating
			? setInterval(() => runtime.dispatch(event), delay)
			: setTimeout(() => {
					ctx.timers.delete(key)
					runtime.dispatch(event)
				}, delay)
		handle.unref?.()
		ctx.timers.set(key, handle)
	},
 
	'endpoints.effect.timer.clear': (ctx: FullCtx, effect) => {
		clearTimerByKey(ctx, effect.which)
	},
 
	// Retire-to-drain: keep the channel open, move it to the drain-watch set. If
	// the node was never dialed there is nothing to drain — tell the FSM it is
	// closeable now so the registry entry is reaped instead of leaking forever
	// (idle_sweep only scans materialized retired channels).
	'endpoints.effect.retire_channel': (ctx: FullCtx, effect, runtime) => {
		let conn = ctx.channels.get(effect.nodeId)
		if (conn === undefined) {
			runtime.dispatch({ type: 'endpoints.channel_closeable', nodeId: effect.nodeId })
			return
		}
		ctx.channels.delete(effect.nodeId)
		ctx.retiredChannels.set(effect.nodeId, conn)
		ctx.retiredAt.set(effect.nodeId, Date.now())
	},
 
	'endpoints.effect.close_channel': (ctx: FullCtx, effect) => {
		dropChannel(ctx, effect.nodeId, effect.store ?? 'any')
	},
 
	// Graceful close: an idle channel is closeable now; a busy one is registered
	// so it becomes closeable as soon as its in-flight streams finish (`callEnded`
	// dispatches `channel_closeable`). Dropping the last channel finalizes the
	// FSM; `close_deadline` is the hard cap. This is what keeps `await using
	// driver` from always waiting the full deadline.
	'endpoints.effect.begin_close_drain': (ctx: FullCtx, _effect, runtime) => {
		ctx.draining = new Set()
		let watch = (nodeId: bigint, hasChannel: boolean) => {
			let busy = hasChannel && (ctx.inflight.get(nodeId) ?? 0) > 0
			if (busy) ctx.draining!.add(nodeId)
			else runtime.dispatch({ type: 'endpoints.channel_closeable', nodeId })
		}
		for (let nodeId of ctx.byNodeId.keys()) {
			watch(nodeId, ctx.channels.has(nodeId) || ctx.retiredChannels.has(nodeId))
		}
		for (let nodeId of ctx.pinned.keys()) {
			watch(nodeId, ctx.pinnedChannels.has(nodeId))
		}
	},
 
	// Reap retired channels that are genuinely gone. A working (READY / idle-but-
	// reconnectable) channel is KEPT so a returning node reuses it — no churn.
	// SHUTDOWN is closed at once; a TRANSIENT_FAILURE must be SUSTAINED past the
	// grace window (one blip is absorbed), same as any other non-READY idle state.
	'endpoints.effect.idle_sweep': (ctx: FullCtx, _effect, runtime) => {
		let now = Date.now()
		for (let [nodeId, conn] of ctx.retiredChannels) {
			let state = conn.channel.getConnectivityState(false)
			if (state === connectivityState.READY) {
				ctx.transientSince.delete(nodeId)
				continue
			}
			if (state === connectivityState.SHUTDOWN) {
				runtime.dispatch({ type: 'endpoints.channel_closeable', nodeId })
				continue
			}
			Eif (state === connectivityState.TRANSIENT_FAILURE && !ctx.transientSince.has(nodeId)) {
				ctx.transientSince.set(nodeId, now)
			}
			// Non-READY (incl. sustained TRANSIENT_FAILURE) at/past the grace window
			// (>= so a zero grace reaps a non-READY channel on the first sweep).
			Eif (now - (ctx.retiredAt.get(nodeId) ?? now) >= ctx.retiredGraceMs) {
				runtime.dispatch({ type: 'endpoints.channel_closeable', nodeId })
			}
		}
	},
 
	// closedDeferred is resolved by #consume when it publishes the `closed` output,
	// so `await close()` returns only after ydb:driver.closed is published (and as
	// a fault backstop in #consume's finally) — not here.
	'endpoints.effect.finalize': (ctx: FullCtx) => {
		finalizeEnv(ctx)
	},
} satisfies {
	[K in EndpointsEffect['type']]: (
		ctx: FullCtx,
		effect: Extract<EndpointsEffect, { type: K }>,
		runtime: { emit(o: EndpointsOutput): void; dispatch(e: EndpointsEvent): void }
	) => void
}
 
// ── Facade ──────────────────────────────────────────────────────────────────
 
export type EndpointsRuntime = {
	machine: MachineRuntime<EndpointsState, EndpointsCtx, EndpointsEvent, EndpointsOutput>
	pool: EndpointPool
}
 
export class EndpointPool implements Disposable, AsyncDisposable {
	#machine: MachineRuntime<EndpointsState, EndpointsCtx, EndpointsEvent, EndpointsOutput>
	#env: EndpointsEnv
	// RCU read plane — swapped by reference in #consume, read (never mutated) by acquire.
	#snapshot: RoutingSnapshot = EMPTY_SNAPSHOT
 
	constructor(
		machine: MachineRuntime<EndpointsState, EndpointsCtx, EndpointsEvent, EndpointsOutput>
	) {
		this.#machine = machine
		// The machine merges env into ctx once (Object.assign(ctx, env)); effects
		// mutate THAT object. Read the same merged object here so scalar writes made
		// inside effects (isFinalized, draining, roundStart, readyAt) are visible —
		// a separate `env` reference would only share the Map/object fields, not the
		// reassigned scalars.
		this.#env = machine.ctx as unknown as EndpointsEnv
		void this.#consume().catch((error) => dbg.log('consume loop ended: %O', error))
	}
 
	get snapshot(): RoutingSnapshot {
		return this.#snapshot
	}
 
	// ── SYNCHRONOUS hot path — one Map.get or one random index + lazy materialize ──
	acquire(preferNodeId?: bigint): Connection {
		if (this.#env.isFinalized) throw new EndpointsUnavailableError('Endpoints closed')
		let ref = selectEndpoint(this.#snapshot, preferNodeId !== undefined ? { preferNodeId } : {})
		if (ref === undefined) throw new EndpointsUnavailableError()
		return this.#materialize(ref)
	}
 
	// Direct-IO: exact node. `hard` never substitutes (throws on miss) — for a
	// server-named node_id outside ListEndpoints.
	acquireNode(nodeId: bigint, opts: { hard?: boolean } = {}): Connection {
		Iif (this.#env.isFinalized) throw new EndpointsUnavailableError('Endpoints closed')
		let ref = selectEndpoint(this.#snapshot, { preferNodeId: nodeId, hard: opts.hard ?? false })
		if (ref === undefined) throw new EndpointsUnavailableError(`No endpoint for node ${nodeId}`)
		return this.#materialize(ref)
	}
 
	// Move a node out of active rotation after a transport failure. Fire-and-forget:
	// enqueue-only, handled async off the hot path. Callers penalize only on
	// pessimizable (non-cancel transport) errors.
	penalize(nodeId: bigint): void {
		this.#machine.dispatch({ type: 'endpoints.rpc_failed', nodeId })
	}
 
	// Restore a node to active rotation after a successful RPC (no-op unless it is
	// currently pessimized). Fire-and-forget, same as penalize().
	recover(nodeId: bigint): void {
		this.#machine.dispatch({ type: 'endpoints.rpc_ok', nodeId })
	}
 
	// Call-lifecycle bookkeeping used by BalancedChannel to keep a per-node
	// in-flight count. Graceful close consults it to finalize as soon as a
	// channel's streams have drained instead of waiting the full close deadline.
	callStarted(nodeId: bigint): void {
		this.#env.inflight.set(nodeId, (this.#env.inflight.get(nodeId) ?? 0) + 1)
	}
 
	callEnded(nodeId: bigint): void {
		let n = (this.#env.inflight.get(nodeId) ?? 0) - 1
		if (n > 0) {
			this.#env.inflight.set(nodeId, n)
			return
		}
		this.#env.inflight.delete(nodeId)
		// If this channel was the last thing a close() was waiting to drain, tell
		// the FSM it is now closeable.
		if (this.#env.draining?.has(nodeId)) {
			this.#env.draining.delete(nodeId)
			this.#machine.dispatch({ type: 'endpoints.channel_closeable', nodeId })
		}
	}
 
	pin(
		nodeId: bigint,
		host: string,
		port: number,
		opts: {
			location?: string | undefined
			sslTargetNameOverride?: string | undefined
			ipV4?: string[] | undefined
			ipV6?: string[] | undefined
			generation?: number | undefined
		} = {}
	): void {
		this.#machine.dispatch({
			type: 'endpoints.pin',
			nodeId,
			host,
			port,
			location: opts.location ?? '',
			sslTargetNameOverride: opts.sslTargetNameOverride ?? '',
			ipV4: opts.ipV4 ?? [],
			ipV6: opts.ipV6 ?? [],
			generation: opts.generation ?? 0,
		})
	}
 
	invalidate(nodeId: bigint): void {
		this.#machine.dispatch({ type: 'endpoints.invalidate', nodeId })
	}
 
	forceRediscovery(): void {
		this.#machine.dispatch({ type: 'endpoints.discovery.force' })
	}
 
	async ready(signal?: AbortSignal): Promise<void> {
		// readyDeferred is the authoritative latch: #consume resolves it on
		// `ready` and rejects it with the real cause on `failed`/`closed`. We do
		// NOT link the pool's own ac.signal here — its abort reason ('Endpoints
		// finalized') would otherwise race ahead of the true discovery error.
		let promise = this.#env.readyDeferred.promise
		await (signal !== undefined ? abortable(signal, promise) : promise)
	}
 
	async close(): Promise<void> {
		this.#machine.dispatch({ type: 'endpoints.close' })
		await this.#env.closedDeferred.promise
	}
 
	[Symbol.dispose](): void {
		this.#machine.dispatch({ type: 'endpoints.destroy' })
	}
 
	async [Symbol.asyncDispose](): Promise<void> {
		await this.close()
	}
 
	#materialize(ref: EndpointRef): Connection {
		let nodeId = ref.nodeId
		let existing =
			this.#env.channels.get(nodeId) ??
			this.#env.retiredChannels.get(nodeId) ??
			this.#env.pinnedChannels.get(nodeId)
		if (existing !== undefined) return existing
		let conn = this.#env.connectionFactory(ref)
		if (ref.state === 'pinned') {
			this.#env.pinnedChannels.set(nodeId, conn)
		} else Iif (ref.state === 'retired') {
			// A channel first dialed after the node was retired must land in the
			// retired store so idle_sweep governs it. Defensive: a retired ref with
			// no channel is reaped before it can be selected.
			/* node:coverage ignore start */
			this.#env.retiredChannels.set(nodeId, conn)
			this.#env.retiredAt.set(nodeId, Date.now())
			/* node:coverage ignore stop */
		} else {
			this.#env.channels.set(nodeId, conn)
		}
		return conn
	}
 
	// RCU swap + diagnostics republish — consumes the machine's output stream
	// (the reader.ts pattern), NOT ingest. The round-derived events
	// (connection.added/retired + discovery.completed) are published by the
	// discovery effect inside the tracing span, not here — see
	// publishRoundDiagnostics. The try/finally is a backstop: if the machine
	// faults (a transition/effect throws, the iterator rethrows), close()/ready()
	// awaiters are still released and channels/timers are still torn down.
	async #consume(): Promise<void> {
		let env = this.#env
		try {
			await this.#drain()
			/* node:coverage ignore start -- backstop for an unrecoverable FSM fault (should never happen) */
		} catch (error) {
			dbg.log('endpoints machine faulted: %O', error)
			env.readyDeferred.reject(error)
			/* node:coverage ignore stop */
		} finally {
			finalizeEnv(env)
			// No-ops if already settled; guarantees no awaiter hangs on a fault.
			env.readyDeferred.reject(new Error('Endpoints closed'))
			env.closedDeferred.resolve()
		}
	}
 
	async #drain(): Promise<void> {
		let env = this.#env
		for await (let out of this.#machine) {
			switch (out.type) {
				case 'endpoints.snapshot':
					this.#snapshot = out.snapshot
					// Snapshot rebuilds fire only when the routable set changes, so
					// stats track topology change (not RPC volume); fallback is
					// edge-triggered inside its publisher.
					this.#publishPoolStats()
					this.#publishFallbackTransition()
					break
				case 'endpoints.added':
				case 'endpoints.retired':
					// Published within the discovery span by publishRoundDiagnostics.
					break
				case 'endpoints.removed':
					dc('ydb:driver.connection.removed').publish({
						driver: env.identity,
						nodeId: out.nodeId,
						address: out.address,
						location: out.location,
						pile: out.pile,
						reason: out.reason satisfies RemovedReason,
					})
					break
				case 'endpoints.pessimized':
					env.banStart.set(out.nodeId, Date.now())
					safeHook('onPessimize', () =>
						env.hooks?.onPessimize?.({
							endpoint: {
								nodeId: out.nodeId,
								address: out.address,
								location: out.location,
								pile: out.pile,
							},
						})
					)
					dc('ydb:driver.connection.pessimized').publish({
						driver: env.identity,
						nodeId: out.nodeId,
						address: out.address,
						location: out.location,
						pile: out.pile,
					})
					break
				case 'endpoints.unpessimized': {
					let duration = Date.now() - (env.banStart.get(out.nodeId) ?? Date.now())
					env.banStart.delete(out.nodeId)
					safeHook('onUnpessimize', () =>
						env.hooks?.onUnpessimize?.({
							endpoint: {
								nodeId: out.nodeId,
								address: out.address,
								location: out.location,
								pile: out.pile,
							},
						})
					)
					dc('ydb:driver.connection.unpessimized').publish({
						driver: env.identity,
						nodeId: out.nodeId,
						address: out.address,
						location: out.location,
						pile: out.pile,
						duration,
					})
					break
				}
				case 'endpoints.discovery_completed': {
					// ydb:driver.discovery.completed is published within the discovery
					// span by publishRoundDiagnostics; here we only fire the hook.
					let duration = Date.now() - env.roundStart
					safeHook('onDiscovery', () =>
						env.hooks?.onDiscovery?.({
							added: out.added.map(toEndpointInfo),
							removed: out.removed.map(toEndpointInfo),
							duration,
							endpoints: this.#snapshotEndpoints(),
						})
					)
					break
				}
				case 'endpoints.discovery_failed':
					safeHook('onDiscoveryError', () =>
						env.hooks?.onDiscoveryError?.({
							error: out.error,
							attempt: out.attempt,
							duration: Date.now() - env.roundStart,
						})
					)
					break
				case 'endpoints.ready':
					env.readyAt = Date.now()
					env.readyDeferred.resolve()
					dc('ydb:driver.ready').publish({
						driver: env.identity,
						duration: env.readyAt - env.initAt,
					})
					break
				case 'endpoints.failed':
					env.readyDeferred.reject(out.error)
					dc('ydb:driver.failed').publish({
						driver: env.identity,
						duration: Date.now() - env.initAt,
						error: out.error,
					})
					break
				case 'endpoints.closed':
					env.readyDeferred.reject(new Error('Endpoints closed'))
					dc('ydb:driver.closed').publish({
						driver: env.identity,
						uptime: env.readyAt !== undefined ? Date.now() - env.readyAt : 0,
					})
					// Resolve AFTER the publish so `await close()` observes it.
					env.closedDeferred.resolve()
					break
			}
		}
	}
 
	#snapshotEndpoints(): EndpointInfo[] {
		return Array.from(this.#snapshot.byNodeId.values(), toEndpointInfo)
	}
 
	// Aggregate routing snapshot — a baseline for a subscriber that attaches
	// mid-life, and per-pile node counts for bridge clusters.
	#publishPoolStats(): void {
		let env = this.#env
		let s = this.#snapshot
		dc('ydb:driver.connection.pool.stats').publish({
			driver: env.identity,
			total: s.byNodeId.size,
			prefer: s.prefer.length,
			fallback: s.fallback.length,
			pessimized: s.pessimizedCount,
			piles: env.lastPileStates.map((p) => ({
				name: p.pileName,
				status: p.status,
				nodes: countPileNodes(s, p.pileName),
			})),
		})
	}
 
	// Edge-triggered: fires only when preferPrimaryPile starts/stops serving from
	// the SYNCHRONIZED fallback tier (the primary pile has no available node).
	#publishFallbackTransition(): void {
		let env = this.#env
		let s = this.#snapshot
		let active =
			env.preferPrimaryPile &&
			s.pileStatesPresent &&
			s.prefer.length === 0 &&
			s.fallback.length > 0
		if (active === env.prevFallbackActive) return
		env.prevFallbackActive = active
		dc('ydb:driver.pile.fallback').publish({
			driver: env.identity,
			active,
			primaryPile: primaryPileName(env.lastPileStates),
		})
	}
}
 
let toEndpointInfo = function toEndpointInfo(e: {
	nodeId: bigint
	address: string
	location: string
	pile: string
}): EndpointInfo {
	return Object.freeze<EndpointInfo>({
		nodeId: e.nodeId,
		address: e.address,
		location: e.location,
		pile: e.pile,
	})
}
 
// ── Wiring ──────────────────────────────────────────────────────────────────
 
export type EndpointsRuntimeConfig = {
	identity: DriverIdentity
	listEndpoints: ListEndpoints
	channelCredentials: ChannelCredentials
	channelOptions?: ChannelOptions | undefined
	connectionFactory?: ConnectionFactory | undefined
	hooks?: DriverHooks | undefined
	localityEnabled?: boolean | undefined
	preferPrimaryPile?: boolean | undefined
	degradedThreshold?: number | undefined
	discoveryTimeoutMs?: number | undefined
	discoveryIntervalMs?: number | undefined
	idleIntervalMs?: number | undefined
	retiredGraceMs?: number | undefined
	closeDeadlineMs?: number | undefined
}
 
export let createEndpointsRuntime = function createEndpointsRuntime(
	config: EndpointsRuntimeConfig
): EndpointsRuntime {
	let defaultFactory: ConnectionFactory = (ref) =>
		new GrpcConnection(
			defaultProtoEndpoint(ref),
			config.channelCredentials,
			config.channelOptions
		)
 
	let env: EndpointsEnv = {
		identity: config.identity,
		hooks: config.hooks,
		listEndpoints: config.listEndpoints,
		connectionFactory: config.connectionFactory ?? defaultFactory,
		channels: new Map(),
		retiredChannels: new Map(),
		pinnedChannels: new Map(),
		banStart: new Map(),
		retiredAt: new Map(),
		transientSince: new Map(),
		inflight: new Map(),
		draining: undefined,
		discoveryTimeoutMs: config.discoveryTimeoutMs ?? DEFAULT_DISCOVERY_TIMEOUT_MS,
		discoveryIntervalMs: config.discoveryIntervalMs ?? DEFAULT_DISCOVERY_INTERVAL_MS,
		idleIntervalMs: config.idleIntervalMs ?? DEFAULT_IDLE_INTERVAL_MS,
		retiredGraceMs: config.retiredGraceMs ?? DEFAULT_RETIRED_GRACE_MS,
		closeDeadlineMs: config.closeDeadlineMs ?? DEFAULT_CLOSE_DEADLINE_MS,
		backoffBaseMs: DEFAULT_BACKOFF_BASE_MS,
		backoffMaxMs: DEFAULT_BACKOFF_MAX_MS,
		ac: new AbortController(),
		readyDeferred: Promise.withResolvers<void>(),
		closedDeferred: Promise.withResolvers<void>(),
		isFinalized: false,
		timers: new Map(),
		roundStart: 0,
		initAt: Date.now(),
		readyAt: undefined,
		preferPrimaryPile: config.preferPrimaryPile ?? false,
		lastPileStates: [],
		prevFallbackActive: false,
	}
	// Silence unobserved-rejection noise when nobody awaits ready().
	env.readyDeferred.promise.catch(() => {})
 
	let ctx = createEndpointsCtx({
		localityEnabled: config.localityEnabled,
		preferPrimaryPile: config.preferPrimaryPile,
		degradedThreshold: config.degradedThreshold,
	})
 
	let machine = createMachineRuntime<
		EndpointsState,
		EndpointsCtx,
		EndpointsEnv,
		EndpointsEvent,
		EndpointsEffect,
		EndpointsOutput
	>({
		initialState: 'idle',
		ctx,
		env,
		transition: endpointsTransition,
		effects,
	})
 
	let pool = new EndpointPool(machine)
 
	// One-shot config snapshot (AGENTS.md: config goes on *.pool.opened, fired once)
	// so a subscriber attached before the first round has the full driver config.
	dc('ydb:driver.connection.pool.opened').publish({
		driver: config.identity,
		config: {
			localityEnabled: ctx.config.localityEnabled,
			preferPrimaryPile: ctx.config.preferPrimaryPile,
			degradedThreshold: ctx.config.degradedThreshold,
			discoveryIntervalMs: env.discoveryIntervalMs,
			idleIntervalMs: env.idleIntervalMs,
			retiredGraceMs: env.retiredGraceMs,
			closeDeadlineMs: env.closeDeadlineMs,
		},
	})
 
	// No ingest — discovery is unary-per-round. Kick the initial round.
	machine.dispatch({ type: 'endpoints.discovery.start' })
 
	return { machine, pool }
}
 
export let defaultProtoEndpoint = function defaultProtoEndpoint(
	ref: EndpointRef
): ProtoEndpointInfo {
	return create(EndpointInfoSchema, {
		address: ref.host,
		port: ref.port,
		nodeId: Number(ref.nodeId),
		location: ref.location,
		sslTargetNameOverride: ref.sslTargetNameOverride,
		// Carry the pile onto the dial proto so the production GrpcConnection's
		// EndpointInfo.pile (and thus the onCall hook) sees it on a bridge cluster.
		bridgePileName: ref.pile,
	})
}
 
// Map a raw proto ListEndpointsResult to the domain DiscoveryResult. Used by
// Driver's listEndpoints seam (#fetchEndpoints). pile_states is empty on
// non-bridge clusters ⇒ identity.
export let mapDiscoveryResult = function mapDiscoveryResult(
	result: ListEndpointsResult
): DiscoveryResult {
	let endpoints: DiscoveredEndpoint[] = result.endpoints.map((ep) => ({
		nodeId: BigInt(ep.nodeId),
		host: ep.address,
		port: ep.port,
		location: ep.location,
		loadFactor: ep.loadFactor,
		sslTargetNameOverride: ep.sslTargetNameOverride,
		ipV4: ep.ipV4,
		ipV6: ep.ipV6,
		bridgePileName: ep.bridgePileName,
		services: ep.service,
	}))
	let pileStates: PileState[] = result.pileStates.map((p) => ({
		pileName: p.pileName,
		status: mapPileStatus(p.state),
	}))
	return { endpoints, selfLocation: result.selfLocation, pileStates }
}
 
let mapPileStatus = function mapPileStatus(state: PileState_State): PileStatus {
	switch (state) {
		case PileState_State.PRIMARY:
			return 'PRIMARY'
		case PileState_State.PROMOTED:
			return 'PROMOTED'
		case PileState_State.SYNCHRONIZED:
			return 'SYNCHRONIZED'
		case PileState_State.NOT_SYNCHRONIZED:
			return 'NOT_SYNCHRONIZED'
		case PileState_State.SUSPENDED:
			return 'SUSPENDED'
		case PileState_State.DISCONNECTED:
			return 'DISCONNECTED'
		default:
			return 'UNSPECIFIED'
	}
}