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 | 22x 22x 10x 10x 10x 12x 12x 12x 11x 11x 12x 10x 11x 12x 10x 10x 10x 10x 10734x 10734x 10734x 10734x 10734x 10734x 10734x 10734x 10734x 10734x 10734x 10734x 10734x 10734x 14x 10734x 10734x 10738x 10734x 10734x 10734x 10734x 14x 14x 10x 10x 14x 2x 14x 4x 2x 22x 229x 229x 2x 227x 229x 227x 1188x 1x 1187x 1188x 1188x 17759x 1187x 73x 8x 3x 5x 65x 65x 65x 65x 65x 21279x 13x 21266x 21266x 21279x 21279x 53x 53x 10671x 2x 227x 1x 226x 226x 226x 616x 1x 615x 615x 615x 615x 615x 616x 833x 616x 830x 830x 557x 6x 551x 551x 273x 14x 14x 259x 259x 257x 257x 259x 41x 609x 136x 136x 136x 136x 136x 133x 136x 473x 458x 614x 404x 14x 5x 9x 225x 135x 135x 135x 135x 136x 136x 136x 136x 257x 257x 257x 167860x 257x 257x 254x 254x 136x 269x 168027x 168027x 269x 2x 2x 267x 615x 609x 6x 6x 6x 6x 10x 10x 10x 6x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 1x 87x 87x 87x 17759x 17759x 17759x 17759x 90x 90x 17759x 87x 87x 87x 90x 90x 17757x 86x 4x 87x 87x 86x 86x 86x 86x 86x 87x 87x 86x 3x 87x 7x 80x 10734x 22090x 267x 267x 267x 267x 167934x 264x 264x 264x 3x 3x 267x 145x 145x 145x 19x 2x 2x 19x 19x 81x 6x 6x 81x 81x 83x 83x 83x 83x 83x 3x 3x 3x 3x 3x 17x 17x 17x 3x 3x 3x 3x 10734x 10734x 10734x 10734x 10738x 10738x 10738x 10734x 10734x 10734x 10734x 10734x 10734x 10734x 10720x 4x | import { create } from '@bufbuild/protobuf'
import { StatusIds_StatusCode } from '@ydbjs/api/operation'
import {
OffsetsRangeSchema,
TopicServiceDefinition,
TransactionIdentitySchema,
UpdateOffsetsInTransactionRequestSchema,
UpdateOffsetsInTransactionRequest_TopicOffsetsSchema,
UpdateOffsetsInTransactionRequest_TopicOffsets_PartitionOffsetsSchema,
} from '@ydbjs/api/topic'
import { linkSignals } from '@ydbjs/abortable'
import type { Driver } from '@ydbjs/core'
import { loggers } from '@ydbjs/debug'
import { YDBError } from '@ydbjs/error'
import { AsyncQueue } from '@ydbjs/fsm/queue'
import { type CodecMap, defaultCodecMap } from '../codec.js'
import type { TopicMessage } from '../message.js'
import type { TopicPartitionSession } from '../partition-session.js'
import type { TX } from '../tx.js'
import { parseReadSettings } from './read-settings.js'
import {
type TxReadOffsetUpdate,
type TxReadOffsets,
buildCommitRanges,
growTxOffsets,
toTopicMessage,
txOffsetUpdates,
} from './reader-internals.js'
import {
type ReaderScope,
publishBufferChanged,
publishClosed,
publishCommitted,
publishErrored,
publishOpened,
publishPartitionStarted,
publishPartitionStopped,
publishReconnecting,
publishSessionStarted,
traceCommit,
} from './diagnostics.js'
import {
DEFAULT_MAX_BUFFER_BYTES,
type ReaderRuntime,
createReaderRuntime,
} from './reader-runtime.js'
import { type OffsetRange, partitionKey } from './reader-state.js'
import type { TopicReadOptions, TopicReaderOptions, TopicTxReader } from './types.js'
let dbg = loggers.topic.extend('reader')
// A decoded ReadResponse: the consumer takes the messages, then the reader releases
// the response's flow-control credit (backpressure — credit is granted only as the
// consumer keeps up).
type Chunk = { messages: TopicMessage[]; releaseBytes: bigint }
type CommitBatch = {
messages: TopicMessage[]
completion: PromiseWithResolvers<void>
promise: Promise<void>
flushed: boolean
}
// Bind the read offsets to the transaction via UpdateOffsetsInTransaction, so they
// become committed if and only if the transaction commits. Called from the tx.onCommit
// hook the constructor wires; a throw here fails the commit, and the offsets roll
// back with it.
let commitTxOffsets = async function commitTxOffsets(
tx: TX,
driver: Driver,
consumer: string,
updates: TxReadOffsetUpdate[]
): Promise<void> {
Iif (updates.length === 0) {
return
}
// The request nests ranges per topic per partition; updates arrive flat.
let partitionsByTopic = new Map<string, TxReadOffsetUpdate[]>()
for (let update of updates) {
let path = update.partitionSession.topicPath
let partitions = partitionsByTopic.get(path)
if (!partitions) {
partitions = []
partitionsByTopic.set(path, partitions)
}
partitions.push(update)
}
let request = create(UpdateOffsetsInTransactionRequestSchema, {
tx: create(TransactionIdentitySchema, {
id: tx.transactionId,
session: tx.sessionId,
}),
topics: Array.from(partitionsByTopic, ([path, partitions]) =>
create(UpdateOffsetsInTransactionRequest_TopicOffsetsSchema, {
path,
partitions: partitions.map((update) =>
create(UpdateOffsetsInTransactionRequest_TopicOffsets_PartitionOffsetsSchema, {
partitionId: update.partitionSession.partitionId,
partitionOffsets: [
create(OffsetsRangeSchema, {
start: update.offsetRange.firstOffset,
// The wire range is half-open; updates carry inclusive lastOffset.
end: update.offsetRange.lastOffset + 1n,
}),
],
})
),
})
),
consumer,
})
dbg.log('committing read offsets in tx %s (%d partitions)', tx.transactionId, updates.length)
let client = driver.createClient(TopicServiceDefinition, tx.nodeId)
let response = await client.updateOffsetsInTransaction(request)
Iif (response.operation?.status !== StatusIds_StatusCode.SUCCESS) {
// YDBError carries the status code and issues, so retry classifiers and user
// code can inspect it like every other server-status failure in the package.
throw new YDBError(
response.operation?.status ?? StatusIds_StatusCode.STATUS_CODE_UNSPECIFIED,
response.operation?.issues ?? []
)
}
}
// The public topic reader. read() is a pull async-iterator over decoded batches;
// commit() acknowledges offsets and resolves once the server's committed high-water
// mark reaches them — surviving transparent reconnects (never rejected by one).
export class TopicReader implements AsyncDisposable, Disposable {
#options: TopicReaderOptions
#codecs: CodecMap
#runtime: ReaderRuntime
#chunks = new AsyncQueue<Chunk>()
#bufferedBytes = 0n
// waiterId -> commit() promise; the FSM only carries the id, never the callback.
#waiters = new Map<number, PromiseWithResolvers<void>>()
#nextWaiterId = 1
#commitBatch: CommitBatch | undefined
// Every partition session this reader ever created — the commit() ownership
// check. A WeakSet so retired sessions do not leak.
#ownedSessions = new WeakSet<TopicPartitionSession>()
// ReadResponses pulled off the chunk queue but not yet fully yielded to the
// consumer. Keeping the response boundary preserves its flow-control credit until
// the last message from that response passes through the async iterable.
#carry: Chunk[] = []
// tx read offsets per stable partitionKey, recorded ONLY when a batch is yielded
// to the consumer — a tx must never bind offsets of messages the app never saw.
// firstOffset is the first delivered message's stitched commitRangeStart, so the
// committed range starts at the server committed offset across a head gap.
// Undefined for a non-tx reader.
#txReadOffsets?: Map<string, TxReadOffsets>
// Shadow of the FSM's terminal error: set by the #consume drain on `reader.error`
// (or a machine fault), then consulted synchronously by read()/commit()/close() to
// surface it to the caller — the FSM cannot reject an already-running read() promise.
#lastError: unknown = undefined
#closed = false
#closing = false
#reading = false // read() is single-consumer
#transactional: boolean
#scope: ReaderScope
#closedDeferred = Promise.withResolvers<void>()
constructor(driver: Driver, options: TopicReaderOptions, runtimeOptions?: { tx?: TX }) {
this.#options = options
this.#transactional = runtimeOptions?.tx !== undefined
if (this.#transactional) {
this.#txReadOffsets = new Map()
}
this.#codecs = options.codecMap ?? defaultCodecMap
this.#scope = {
driver: driver.identity,
consumer: options.consumer,
topics: parseReadSettings(options.topic).map((settings) => settings.path),
}
publishOpened(this.#scope, {
maxBufferBytes: options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES,
updateTokenIntervalMs: options.updateTokenIntervalMs ?? 60_000,
gracefulShutdownTimeoutMs: options.gracefulShutdownTimeoutMs ?? 30_000,
recoveryWindowMs: options.recoveryWindowMs ?? Infinity,
retryOnSchemeError: options.retryOnSchemeError ?? false,
})
this.#runtime = createReaderRuntime(driver, options)
// Fire-and-forget drain; an internal machine fault rethrows and is funneled to
// the terminal path (never an unhandled rejection).
this.#consume().catch((error) => this.#fail(error))
// Tx lifecycle is wired here — not in the factory — so the hooks can reach
// #-private state directly instead of going through an exported accessor.
if (runtimeOptions?.tx) {
let tx = runtimeOptions.tx
tx.onCommit(async () => {
// Bind the read offsets to the tx; on failure the commit (and thus the
// offsets) roll back, and the reader is torn down by onClose below.
await commitTxOffsets(
tx,
driver,
options.consumer,
txOffsetUpdates(this.#txReadOffsets)
)
// Release the partition once offsets are committed. A tx reader left open
// keeps the consumer's partition assigned server-side, so a later reader on
// the same consumer never gets a partition session — it hangs until its
// read deadline.
await this.close()
})
tx.onRollback(() => {
this.destroy(new Error('Transaction rolled back'))
})
tx.onClose((committed) => {
if (!committed) {
this.destroy(new Error('Transaction closed without commit'))
}
})
}
}
// Server-accounted bytes retained by the reader and not yet fully delivered through
// read(). This can exceed maxBufferBytes when a single server response overdraws the
// credit window.
get bufferedBytes(): bigint {
return this.#bufferedBytes
}
read(options?: TopicReadOptions): AsyncIterable<TopicMessage[]> {
// Validate eagerly — an async generator would defer the throw to the first
// next(), and a zero/negative limit would otherwise spin an infinite
// empty-slice loop instead of failing.
let limit = options?.limit
if (limit !== undefined && (!Number.isSafeInteger(limit) || limit <= 0)) {
throw new RangeError(`read limit must be a positive integer, got ${limit}`)
}
// `waitMs` is the deprecated alias for `batchWindowMs`.
let batchWindowMs = options?.batchWindowMs ?? options?.waitMs
Iif (batchWindowMs !== undefined && (!Number.isFinite(batchWindowMs) || batchWindowMs < 0)) {
throw new RangeError(
`batchWindowMs must be a non-negative finite number, got ${batchWindowMs}`
)
}
return this.#readLoop(limit, batchWindowMs, options?.signal)
}
commit(input: TopicMessage | TopicMessage[]): Promise<void> {
// The TopicTxReader type hides commit(), but the method still exists on the
// runtime object — enforce the boundary for plain-JS callers too: a manual
// commit would land outside the transaction and survive its rollback.
if (this.#transactional) {
throw new Error(
'Tx reader commits offsets via the transaction — commit() is not available'
)
}
let batch = this.#commitBatch ?? this.#createCommitBatch()
let messages = Array.isArray(input) ? input : [input]
for (let message of messages) {
batch.messages.push(message)
}
return batch.promise
}
async close(): Promise<void> {
if (this.#closed) {
if (this.#lastError) {
throw this.#lastError
}
return
}
// Preserve call order when commit() and close() happen in the same turn: dispatch
// the queued commit before the close transition starts draining pending work.
Iif (this.#commitBatch) {
this.#flushCommitBatch(this.#commitBatch)
}
this.#closing = true
this.#runtime.machine.dispatch({ type: 'reader.close' })
await this.#closedDeferred.promise
Iif (this.#lastError) {
throw this.#lastError
}
}
destroy(reason?: unknown): void {
if (this.#closed) {
return
}
this.#closing = true
let error = reason ?? new Error('Reader destroyed')
this.#lastError = error
this.#runtime.machine.dispatch({ type: 'reader.destroy', reason: error })
}
async [Symbol.asyncDispose](): Promise<void> {
try {
await this.close()
} catch (error) {
this.destroy(error)
throw error
}
}
[Symbol.dispose](): void {
this.destroy()
}
// Debuggers and util.inspect show the constructor name, which cannot tell a tx
// reader apart — the tag makes it render as TopicReader [TopicTxReader] { ... }.
get [Symbol.toStringTag](): string {
return this.#transactional ? 'TopicTxReader' : 'TopicReader'
}
async *#readLoop(
limit: number | undefined,
batchWindowMs: number | undefined,
signal: AbortSignal | undefined
): AsyncIterable<TopicMessage[]> {
// Single-consumer: two concurrent read() loops would race the shared chunk
// iterator and double-release flow-control credit.
if (this.#reading) {
throw new Error('read() is already in progress — the reader is single-consumer')
}
this.#reading = true
try {
for (;;) {
if (this.#lastError) {
throw this.#lastError
}
// Accumulate a batch of up to `limit` messages, waiting at most
// `batchWindowMs` (a batch is yielded — possibly empty — once the window
// elapses so an idle topic never hangs the consumer). With no
// `batchWindowMs`, block for one chunk. Starts from the carry-over of a
// previously aborted call — those messages were dequeued but never
// delivered.
let chunks: Chunk[] = this.#takeCarry()
let batchLength = chunks.reduce((count, chunk) => count + chunk.messages.length, 0)
let closed = false
try {
// The batch window is a cancellation source: link it with the user signal
// so take() aborts when either fires. linkSignals (not the banned
// AbortSignal.any) releases its listeners at batch end via `using`. No
// window → wait on the user signal directly.
using window =
batchWindowMs !== undefined
? linkSignals(signal, AbortSignal.timeout(batchWindowMs))
: undefined
let waitSignal = window ? window.signal : signal
// Carried messages satisfy a no-window read on their own — blocking for
// one more chunk with deliverable messages in hand would stall the
// consumer.
let wantMore = () =>
(batchLength === 0 || batchWindowMs !== undefined) &&
(limit === undefined || batchLength < limit)
while (wantMore()) {
let result: IteratorResult<Chunk>
try {
// oxlint-disable-next-line no-await-in-loop
result = await this.#chunks.take(waitSignal)
} catch (error) {
// A user cancel propagates; the batch window elapsing just ends
// accumulation so an idle topic yields an empty batch. Anything
// else (a failed queue) is a real fault — rethrow it.
if (signal?.aborted) {
throw signal.reason
}
Eif (waitSignal?.aborted) {
break
}
throw error
}
if (result.done) {
closed = true
break
}
let chunk = this.#filterChunk(result.value)
if (chunk) {
chunks.push(chunk)
batchLength += chunk.messages.length
}
if (
(limit !== undefined && batchLength >= limit) ||
batchWindowMs === undefined
) {
break
}
}
if (batchLength > 0) {
while (batchLength > 0) {
let batch = this.#takeBatch(chunks, limit)
batchLength -= batch.messages.length
growTxOffsets(this.#txReadOffsets, batch.messages)
if (batch.releaseBytes > 0n) {
this.#releaseReadBytes(batch.releaseBytes)
}
yield batch.messages
}
} else if (batchWindowMs !== undefined && !closed) {
// Idle-window tick: yield an empty batch so the consumer can act.
yield []
}
} finally {
this.#carry.push(...chunks)
}
if (closed) {
// A terminal error surfaces to the consumer — it must not look like a
// clean end-of-stream. Any buffered batch above was delivered first, then
// we throw. The reader is already torn down (markClosed + FSM finalize):
// it is not reusable, and every further read()/commit() throws this too.
if (this.#lastError) {
throw this.#lastError
}
return
}
}
} finally {
this.#reading = false
}
}
#releaseReadBytes(bytes: bigint): void {
this.#bufferedBytes -= bytes
Iif (this.#bufferedBytes < 0n) {
this.#bufferedBytes = 0n
}
publishBufferChanged(this.#scope, this.#bufferedBytes)
this.#runtime.machine.dispatch({ type: 'reader.read_release', bytes })
}
// Remove up to `limit` messages while retaining the response boundary. Credit for
// a response is returned only by the batch containing its final message.
#takeBatch(chunks: Chunk[], limit: number | undefined): Chunk {
let messages: TopicMessage[] = []
let releaseBytes = 0n
let remaining = limit ?? Infinity
while (chunks.length > 0 && remaining > 0) {
let chunk = chunks[0]!
let count = Math.min(chunk.messages.length, remaining)
for (let message of chunk.messages.splice(0, count)) {
messages.push(message)
}
remaining -= count
if (chunk.messages.length === 0) {
releaseBytes += chunk.releaseBytes
chunks.shift()
}
}
return { messages, releaseBytes }
}
// A force-stopped partition is re-read by its new owner. If filtering consumes the
// whole response, there is no user-visible message to gate its credit on.
#filterChunk(chunk: Chunk): Chunk | undefined {
let messages = chunk.messages.filter((message) => {
let session = message.partitionSession.deref()
return session !== undefined && !session.isStopped
})
if (messages.length === 0) {
this.#releaseReadBytes(chunk.releaseBytes)
return undefined
}
return { messages, releaseBytes: chunk.releaseBytes }
}
// Drain the carry-over, re-applying the stopped-session filter — a partition may
// have been lost between the aborted call and this one.
#takeCarry(): Chunk[] {
if (this.#carry.length === 0) {
return []
}
let carried = this.#carry
this.#carry = []
let chunks: Chunk[] = []
for (let chunk of carried) {
let filtered = this.#filterChunk(chunk)
Eif (filtered) {
chunks.push(filtered)
}
}
return chunks
}
#createCommitBatch(): CommitBatch {
let completion = Promise.withResolvers<void>()
let batch: CommitBatch = {
messages: [],
completion,
promise: traceCommit(this.#scope, () => completion.promise),
flushed: false,
}
this.#commitBatch = batch
queueMicrotask(() => this.#flushCommitBatch(batch))
return batch
}
#flushCommitBatch(batch: CommitBatch): void {
Iif (batch.flushed) {
return
}
batch.flushed = true
Eif (this.#commitBatch === batch) {
this.#commitBatch = undefined
}
void this.#commitOffsets(batch.messages).then(
batch.completion.resolve,
batch.completion.reject
)
}
async #commitOffsets(messages: TopicMessage[]): Promise<void> {
if (this.#lastError) {
throw this.#lastError
}
Iif (this.#closed || this.#closing) {
throw new Error('Reader is closed — cannot commit')
}
// Commits are independent per partition. A stopped session in a mixed batch
// must not suppress a live partition: skipping its range creates a permanent
// gap that prevents every later commit watermark from advancing.
let messagesByPartition = new Map<string | symbol, TopicMessage[]>()
for (let message of messages) {
let session = message.partitionSession.deref()
let key = session
? partitionKey(session.topicPath, session.partitionId)
: Symbol('expired partition session')
let partitionMessages = messagesByPartition.get(key)
if (partitionMessages === undefined) {
partitionMessages = []
messagesByPartition.set(key, partitionMessages)
}
partitionMessages.push(message)
}
let byPartition = new Map<string, OffsetRange[]>()
let errors: unknown[] = []
for (let partitionMessages of messagesByPartition.values()) {
try {
for (let [key, ranges] of buildCommitRanges(partitionMessages, (session) =>
this.#ownedSessions.has(session)
)) {
byPartition.set(key, ranges)
}
} catch (error) {
errors.push(error)
}
}
// One waiter per partition; the call resolves only when every partition's
// offsets are acknowledged. Sessions of one partition share the stable
// partitionKey, so a batch spanning a re-grant still lands on one waiter.
let promises: Promise<void>[] = []
for (let [key, ranges] of byPartition) {
let waiterId = this.#nextWaiterId++
let waiter = Promise.withResolvers<void>()
this.#waiters.set(waiterId, waiter)
this.#runtime.machine.dispatch({
type: 'reader.commit',
partitionKey: key,
ranges,
waiterId,
})
promises.push(waiter.promise)
}
// Settle every valid partition before reporting invalid ones so a rejected
// call never leaves hidden commit work running behind the caller.
let results = await Promise.allSettled(promises)
for (let result of results) {
if (result.status === 'rejected') {
errors.push(result.reason)
}
}
if (errors.length === 1) {
throw errors[0]
}
Iif (errors.length > 1) {
throw new AggregateError(errors, 'Cannot commit one or more partitions')
}
}
// ── internals ────────────────────────────────────────────────────────────────
async #consume(): Promise<void> {
for await (let output of this.#runtime.machine) {
switch (output.type) {
case 'reader.messages': {
// tx read-offset tracking happens at read() yield time, not here — a tx
// must never bind offsets of messages the consumer never saw.
try {
let messages: TopicMessage[] = []
for (let group of output.groups) {
for (let message of group.messages) {
messages.push(toTopicMessage(this.#codecs, group.session, message))
}
}
this.#bufferedBytes += output.releaseBytes
publishBufferChanged(this.#scope, this.#bufferedBytes)
this.#chunks.push({ messages, releaseBytes: output.releaseBytes })
} catch (error) {
// An undecodable message (corrupt payload / unsupported codec)
// faults the reader — tear the machine down cleanly rather than
// crash the drain loop into an unhandled rejection.
this.#lastError ??= error
this.#runtime.machine.dispatch({ type: 'reader.destroy', reason: error })
}
break
}
case 'reader.partition.started':
this.#ownedSessions.add(output.session)
publishPartitionStarted(
this.#scope,
output.partitionId,
output.partitionSessionId,
output.committedOffset
)
break
case 'reader.partition.stopped': {
// For a graceful stop the runtime already ran onPartitionSessionStop as
// the awaited pre-response hook (the session was still committable) —
// invoking it again here would double-notify. Forced stops and
// end-of-partition are after-the-fact notifications.
if (
(output.reason === 'lost' || output.reason === 'ended') &&
this.#options.onPartitionSessionStop
) {
// Callback errors are logged via dbg and ignored — a throwing user
// callback must never break the machine. Async rejections are caught
// the same way.
try {
Promise.resolve(
this.#options.onPartitionSessionStop(
output.session,
output.session.partitionCommittedOffset
)
).catch((error) => dbg.log('onPartitionSessionStop threw: %O', error))
} catch (error) {
dbg.log('onPartitionSessionStop threw: %O', error)
}
}
publishPartitionStopped(this.#scope, output.partitionId, output.reason)
break
}
case 'reader.partition.committed': {
// Every server-confirmed advance reports here — commit acks, the
// watermark carried by a stop request, and commitOffset overrides alike;
// also for ended/stopped partitions (a consumer tracking offsets
// externally needs the final ack).
if (this.#options.onCommittedOffset) {
// Callback errors are logged via dbg and ignored — a throwing user
// callback must never break the machine.
try {
this.#options.onCommittedOffset(output.session, output.committedOffset)
} catch (error) {
dbg.log('onCommittedOffset threw: %O', error)
}
}
publishCommitted(this.#scope, output.partitionId, output.committedOffset)
break
}
case 'reader.commit.resolved': {
let waiter = this.#waiters.get(output.waiterId)
Eif (waiter) {
this.#waiters.delete(output.waiterId)
waiter.resolve()
}
break
}
case 'reader.commit.rejected': {
let waiter = this.#waiters.get(output.waiterId)
Eif (waiter) {
this.#waiters.delete(output.waiterId)
waiter.reject(output.reason)
}
break
}
case 'reader.reconnecting':
dbg.log('reconnecting (attempt %d): %O', output.attempt, output.error)
publishReconnecting(this.#scope, output.attempt, output.error)
break
case 'reader.error':
dbg.log('errored: %O', output.error)
this.#lastError = output.error
publishErrored(this.#scope, output.error)
break
case 'reader.closed':
dbg.log('closed')
publishClosed(this.#scope)
this.#markClosed()
break
case 'reader.session':
dbg.log('session started (id=%s)', output.sessionId)
publishSessionStarted(this.#scope, output.sessionId)
break
}
}
// Stream ended; if no reader.closed arrived, the machine faulted — surface it.
Iif (!this.#closed) {
this.#fail(
this.#runtime.machine.signal.reason ?? new Error('Reader stopped unexpectedly')
)
}
}
#markClosed(): void {
Iif (this.#closed) {
return
}
this.#closed = true
this.#chunks.close()
// #txReadOffsets is deliberately kept: a tx reader closed before the tx commits
// still binds the offsets it delivered — clearing here would silently commit
// the transaction with no offsets and redeliver everything after it.
// The FSM's terminate() already rejects outstanding commits via
// reader.commit.rejected; this settles any that slipped through, avoiding leaks.
for (let waiter of this.#waiters.values()) {
waiter.reject(this.#lastError ?? new Error('Reader closed'))
}
this.#waiters.clear()
this.#closedDeferred.resolve()
}
#fail(error: unknown): void {
if (this.#closed) {
return
}
this.#lastError ??= error
this.#markClosed()
}
}
export function createTopicReader(driver: Driver, options: TopicReaderOptions): TopicReader {
return new TopicReader(driver, options)
}
export function createTopicTxReader(
tx: TX,
driver: Driver,
options: TopicReaderOptions
): TopicTxReader {
// The constructor wires the tx lifecycle. The instance is returned as-is under the
// TopicTxReader type: offsets are tracked automatically, commit() is hidden by the
// type and guarded at runtime, and the Symbol.toStringTag renders the tx flavor.
return new TopicReader(driver, options, { tx })
}
|