UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

1 lines • 55.2 kB
{"version":3,"file":"ordered-source-loader.cjs","sources":["../../../../src/query/live/ordered-source-loader.ts"],"sourcesContent":["import {\n  buildCursorCurrent,\n  canExpressCursorOrder,\n} from '../../utils/cursor.js'\nimport { normalizeError } from '../../utils/error.js'\nimport { runAllCallbacks } from '../../utils/callbacks.js'\nimport { normalizeOrderByPaths } from '../compiler/expressions.js'\nimport type {\n  CollectionSubscription,\n  ReleaseLoadSubset,\n} from '../../collection/subscription.js'\nimport type {\n  ChangeMessage,\n  LoadSubsetOptions,\n  LoadSubsetRequestResult,\n} from '../../types.js'\nimport type { OrderByOptimizationInfo } from '../compiler/order-by.js'\n\ntype OrderedRequestKind =\n  | `ordered`\n  | `ordered-repair`\n  | `boundary`\n  | `full-source`\n\ntype OrderedContinuation = {\n  kind: `boundary` | `more`\n  orderedLoadGeneration: number\n  orderingInvalidationGeneration: number\n  isAuthoritativeRepair: boolean\n  windowOperationGeneration?: number\n  continuesOrderedPrefixRepair: boolean\n}\n\nclass OrderedPostSettlementError {\n  constructor(readonly cause: unknown) {}\n}\n\n/** Owns the conservative provider-loading policy for one ordered source. */\nexport class OrderedSourceLoader {\n  private pending: Promise<void> | undefined\n  // Exact request settlement is not provider extent. This latch only records\n  // that some request once completed; reset may discard the boundary, and an\n  // empty page retains it. A failure never reads it before a full-source\n  // completion sets it again, so it never needs clearing.\n  private hasSettledSourceRequest = false\n  private settledSourceBoundary: Record<string, unknown> | undefined\n  // Independent of ordinary finite success: an authoritative full-source or\n  // ordered-prefix refresh repairs ordering.\n  private needsOrderingRepair = false\n  // A live delete or order-changing update invalidates the settled prefix,\n  // but unlike a failed request it cannot have partially written unknown rows.\n  // Re-reading the exact ordered prefix is therefore authoritative for the\n  // current window and preserves the provider query shape.\n  private canRepairWithOrderedPrefix = false\n  private requesting = false\n  // Retaining a demand does not prove it succeeded. Async failure retains it\n  // (`failed`) for replay; a synchronous startup failure retains nothing.\n  private authoritativeRequestState: `none` | `held` | `complete` | `failed` =\n    `none`\n  private authoritativeRequestKind: `ordered-repair` | `full-source` | undefined\n  // Keep callbacks, not copied requests or rows. Successful full-source work\n  // subsumes these logical owners; unfinished transports remain observed.\n  private settledFiniteAcquisitions = new Map<\n    ReleaseLoadSubset,\n    number | undefined\n  >()\n  private orderedRepairAcquisitions = new Set<ReleaseLoadSubset>()\n  // The record's presence blocks automatic retry, including initial requests\n  // that have no explicit window-operation generation.\n  private failedRequest:\n    | { windowOperationGeneration: number | undefined }\n    | undefined\n  private failedAcquisitions = new Map<ReleaseLoadSubset, OrderedRequestKind>()\n  private active = true\n  private orderedLoadGeneration = 0\n  private orderingInvalidationGeneration = 0\n  private orderedPrefixRepairGeneration: number | undefined\n  private lastPage: { count: number; boundary: unknown } | undefined\n  private lastPrefixCount: number | undefined\n  private lastBoundary: unknown\n  private repairRetries = 0\n  private repairTimer: ReturnType<typeof setTimeout> | undefined\n  private stagedContinuation: OrderedContinuation | undefined\n  private blockedLoadMore:\n    | {\n        windowOperationGeneration?: number\n        continuesOrderedPrefixRepair: boolean\n      }\n    | undefined\n  private drainingNoInputContinuations = false\n\n  constructor(\n    private readonly info: OrderByOptimizationInfo,\n    private readonly subscription: CollectionSubscription,\n    private readonly alias: string,\n    private readonly onResult: (\n      result: LoadSubsetRequestResult,\n      holdPublication: boolean,\n      settlesAsync: boolean,\n    ) => void = () => {},\n    private readonly canRetryRepair: () => boolean = () => false,\n    private readonly getGraphInputRevision?: () => number,\n    private readonly hasPendingJoinedWork: () => boolean = () => false,\n  ) {\n    this.info.isRequesting = () => this.requesting\n  }\n\n  /** Derive invalidation from actual contributions, not a second cursor. */\n  onSourceChanges(\n    changes: Array<ChangeMessage<Record<string, unknown>, string | number>>,\n    sentRows: ReadonlyMap<string | number, Record<string, unknown>> | undefined,\n  ): void {\n    let hasNewRows = false\n    for (const change of changes) {\n      const previous = sentRows?.get(change.key)\n      if (\n        change.type !== `insert` &&\n        previous !== undefined &&\n        (change.type === `delete` ||\n          this.info.comparator(previous, change.value) !== 0)\n      ) {\n        this.invalidateSourceOrdering()\n        return\n      }\n      if (change.type !== `delete` && previous === undefined) hasNewRows = true\n    }\n    // New keys, including ties, may need another page. Duplicate delivery or\n    // an order-equal update cannot invalidate an already attempted request.\n    if (hasNewRows) this.invalidateCursor()\n  }\n\n  start(): void {\n    const { index, limit, offset, requiresFullSource } = this.info\n    if (index) this.subscription.setOrderByIndex(index)\n    if (limit === 0) return\n    if (requiresFullSource) {\n      this.loadFullSource()\n      return\n    }\n    if (!index) {\n      this.loadPrefix(offset + limit)\n      return\n    }\n    this.loadPage(offset + limit)\n  }\n\n  loadMore(\n    windowOperationGeneration?: number,\n    continuesOrderedPrefixRepair = false,\n  ): Promise<void> | undefined {\n    if (!this.active || this.info.limit === 0 || this.requesting) return\n    windowOperationGeneration ??=\n      this.blockedLoadMore?.windowOperationGeneration\n    continuesOrderedPrefixRepair ||=\n      this.blockedLoadMore?.continuesOrderedPrefixRepair ?? false\n    if (this.info.joinedFilterSourceId && this.hasPendingJoinedWork()) {\n      if (\n        windowOperationGeneration !== undefined ||\n        continuesOrderedPrefixRepair\n      ) {\n        this.blockedLoadMore = {\n          windowOperationGeneration,\n          continuesOrderedPrefixRepair,\n        }\n      }\n      return this.pending\n    }\n    this.blockedLoadMore = undefined\n    if (this.stagedContinuation) {\n      // A synchronous finite request can deliver an order-changing mutation.\n      // Its continuation is staged after that mutation invalidates ordering,\n      // so authoritative repair must supersede the stale finite chain.\n      if (\n        this.needsOrderingRepair &&\n        !this.stagedContinuation.isAuthoritativeRepair\n      ) {\n        this.stagedContinuation = undefined\n      } else {\n        this.consumeStagedContinuation(windowOperationGeneration)\n        // The consumed continuation can synchronously dispose this loader.\n        // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n        if (!this.active || this.pending) return this.pending\n      }\n    }\n    const mayRetryFailure =\n      this.failedRequest === undefined ||\n      (windowOperationGeneration !== undefined &&\n        windowOperationGeneration !==\n          this.failedRequest.windowOperationGeneration)\n    if (!mayRetryFailure) return this.pending\n    if (\n      (this.failedRequest || this.failedAcquisitions.size > 0) &&\n      windowOperationGeneration !== undefined\n    ) {\n      this.cancelRepairRetry()\n      this.repairRetries = 0\n      // Move ownership to the explicit replacement before releasing the old\n      // acquisition lease. Adapter cleanup may reenter the loader.\n      if (this.failedRequest) {\n        this.failedRequest.windowOperationGeneration = windowOperationGeneration\n      }\n      this.releaseFailedAcquisitions()\n      // Adapter cleanup can synchronously tear down this loader.\n      // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n      if (!this.active) return\n    }\n    if (this.authoritativeRequestState === `failed`) {\n      this.authoritativeRequestState = `none`\n    } else if (\n      this.authoritativeRequestState !== `none` &&\n      !(\n        continuesOrderedPrefixRepair &&\n        this.authoritativeRequestKind === `ordered-repair`\n      )\n    )\n      return this.pending\n    if (\n      (this.needsOrderingRepair &&\n        !(\n          continuesOrderedPrefixRepair &&\n          this.authoritativeRequestKind === `ordered-repair`\n        )) ||\n      this.info.requiresFullSource\n    ) {\n      if (this.canRepairWithOrderedPrefix && !this.info.requiresFullSource) {\n        this.loadOrderedPrefixRepair(windowOperationGeneration)\n      } else {\n        this.loadFullSource(windowOperationGeneration)\n      }\n      return this.pending\n    }\n    if (!this.info.index) {\n      const shouldLoad =\n        windowOperationGeneration !== undefined ||\n        (this.info.dataNeeded?.() ?? 0) > 0 ||\n        (this.lastPrefixCount !== undefined &&\n          this.lastPrefixCount < this.info.offset + this.info.limit)\n      if (shouldLoad) {\n        this.loadPrefix(\n          this.info.offset + this.info.limit,\n          windowOperationGeneration,\n          continuesOrderedPrefixRepair,\n        )\n      } else if (continuesOrderedPrefixRepair) {\n        this.finishOrderedPrefixRepair(windowOperationGeneration)\n      }\n      return this.pending\n    }\n    if (!this.info.dataNeeded || this.pending) {\n      if (continuesOrderedPrefixRepair && !this.pending) {\n        this.finishOrderedPrefixRepair(windowOperationGeneration)\n      }\n      return this.pending\n    }\n    // A recorded failure always carries repair debt, so it cannot reach this\n    // finite path; only the first request needs the whole prefix here.\n    let count = Math.max(\n      this.info.dataNeeded(),\n      this.hasSettledSourceRequest ? 0 : this.info.offset + this.info.limit,\n    )\n    if (\n      windowOperationGeneration !== undefined &&\n      this.settledSourceBoundary !== undefined\n    ) {\n      const needed = this.info.offset + this.info.limit\n      count = Math.max(count, needed - this.countAcquiredRows())\n    }\n    if (count > 0) {\n      this.loadPage(\n        count,\n        windowOperationGeneration,\n        continuesOrderedPrefixRepair,\n      )\n    } else if (continuesOrderedPrefixRepair) {\n      this.finishOrderedPrefixRepair(windowOperationGeneration)\n    }\n    return this.pending\n  }\n\n  loadFullSource(windowOperationGeneration?: number): void {\n    if (!this.active || this.authoritativeRequestState !== `none`) return\n    this.authoritativeRequestState = `held`\n    this.authoritativeRequestKind = `full-source`\n    this.requestAndObserve(\n      (onLoadSubsetResult) => {\n        this.subscription.requestSnapshot({\n          ...(this.needsOrderingRepair ? { refetch: true } : {}),\n          trackLoadSubsetPromise: false,\n          onLoadSubsetResult,\n        })\n      },\n      `full-source`,\n      windowOperationGeneration,\n    )\n  }\n\n  private loadOrderedPrefixRepair(windowOperationGeneration?: number): void {\n    if (!this.active || this.authoritativeRequestState !== `none`) return\n    // Any older finite request may still settle, but it cannot refine from a\n    // boundary that predates this authoritative prefix.\n    this.orderedPrefixRepairGeneration = this.orderingInvalidationGeneration\n    this.orderedRepairAcquisitions = new Set()\n    this.authoritativeRequestState = `held`\n    this.authoritativeRequestKind = `ordered-repair`\n    this.requestAndObserve(\n      (onLoadSubsetResult) => {\n        this.subscription.requestSnapshot({\n          refetch: true,\n          orderBy: normalizeOrderByPaths(this.info.orderBy, this.alias),\n          limit: this.info.offset + this.info.limit,\n          trackLoadSubsetPromise: false,\n          onLoadSubsetResult,\n        })\n      },\n      `ordered-repair`,\n      windowOperationGeneration,\n      true,\n    )\n  }\n\n  private loadPrefix(\n    count: number,\n    windowOperationGeneration?: number,\n    continuesOrderedPrefixRepair = false,\n  ): void {\n    if (!this.active || this.pending || this.stagedContinuation) return\n    if (this.lastPrefixCount === count) {\n      if ((this.info.dataNeeded?.() ?? 0) > 0) {\n        if (continuesOrderedPrefixRepair) this.abandonOrderedPrefixRepair()\n        this.loadFullSource(windowOperationGeneration)\n      } else if (continuesOrderedPrefixRepair) {\n        this.finishOrderedPrefixRepair(windowOperationGeneration)\n      }\n      return\n    }\n    this.requestAndObserve(\n      (onLoadSubsetResult) => {\n        this.subscription.requestSnapshot({\n          ...(continuesOrderedPrefixRepair ? { refetch: true } : {}),\n          orderBy: normalizeOrderByPaths(this.info.orderBy, this.alias),\n          limit: count,\n          trackLoadSubsetPromise: false,\n          onLoadSubsetResult,\n        })\n      },\n      `ordered`,\n      windowOperationGeneration,\n      continuesOrderedPrefixRepair,\n    )\n    this.lastPrefixCount = count\n  }\n\n  resetCursor(): void {\n    this.cancelRepairRetry()\n    this.repairRetries = 0\n    this.orderedLoadGeneration++\n    if (this.authoritativeRequestState === `complete`)\n      this.authoritativeRequestState = `held`\n    this.pending = undefined\n    this.blockedLoadMore = undefined\n    this.lastBoundary = undefined\n    this.settledSourceBoundary = undefined\n    this.stagedContinuation = undefined\n    this.invalidateCursor()\n  }\n\n  settleFullSourceReplay(): void {\n    if (this.authoritativeRequestKind === `ordered-repair`) {\n      this.finishOrderedPrefixRepair()\n      return\n    }\n    // Replay repaired the retained logical acquisition. A later window retry\n    // must not release that now-successful source demand. A failed finite\n    // page is still obsolete and must be released by that retry.\n    if (this.authoritativeRequestState === `failed`) {\n      for (const [release, kind] of this.failedAcquisitions) {\n        if (kind === `full-source`) this.failedAcquisitions.delete(release)\n      }\n      this.authoritativeRequestState = `held`\n    }\n    if (this.authoritativeRequestState !== `none`) {\n      this.authoritativeRequestState = `complete`\n      this.authoritativeRequestKind = undefined\n      this.retireSettledFiniteAcquisitions()\n    }\n  }\n\n  private retireSettledFiniteAcquisitions(\n    prefix?: {\n      release: ReleaseLoadSubset\n      count: number\n    },\n    retained?: ReadonlySet<ReleaseLoadSubset>,\n  ): void {\n    if (\n      (this.authoritativeRequestState !== `complete` && !prefix && !retained) ||\n      this.subscription.hasPendingTruncateReplacement\n    )\n      return\n    const orderedLoadGeneration = this.orderedLoadGeneration\n    runAllCallbacks(\n      Array.from(this.settledFiniteAcquisitions, ([release, count]) => () => {\n        if (retained?.has(release)) return\n        if (\n          !this.active ||\n          orderedLoadGeneration !== this.orderedLoadGeneration\n        )\n          return\n        if (\n          this.authoritativeRequestState !== `complete` &&\n          !retained &&\n          (!prefix ||\n            release === prefix.release ||\n            count === undefined ||\n            count > prefix.count)\n        )\n          return\n        this.settledFiniteAcquisitions.delete(release)\n        release()\n      }),\n    )\n  }\n\n  invalidateCursor(): void {\n    if (!this.stagedContinuation?.isAuthoritativeRepair) {\n      this.stagedContinuation = undefined\n    }\n    this.lastPage = undefined\n    this.lastPrefixCount = undefined\n  }\n\n  invalidateSourceOrdering(): void {\n    this.orderingInvalidationGeneration++\n    this.invalidateCursor()\n    this.lastBoundary = undefined\n    if (\n      !this.needsOrderingRepair &&\n      this.hasSettledSourceRequest &&\n      this.pending === undefined &&\n      this.authoritativeRequestState === `none`\n    ) {\n      this.canRepairWithOrderedPrefix = true\n    }\n    this.settledSourceBoundary = undefined\n    this.needsOrderingRepair = true\n  }\n\n  private finishOrderedPrefixRepair(windowOperationGeneration?: number): void {\n    if (this.authoritativeRequestKind !== `ordered-repair`) return\n    if (\n      this.orderedPrefixRepairGeneration !== this.orderingInvalidationGeneration\n    ) {\n      // A later mutation invalidated the source order while this chain was\n      // running. Start its replacement before the current participant settles\n      // so Collection and Effect publication remain behind one continuous gate.\n      this.orderedRepairAcquisitions = new Set()\n      this.authoritativeRequestState = `none`\n      this.authoritativeRequestKind = undefined\n      this.orderedPrefixRepairGeneration = undefined\n      if (!this.active) return\n      if (this.failedRequest) {\n        this.canRepairWithOrderedPrefix = false\n        this.loadFullSource(windowOperationGeneration)\n      } else {\n        this.canRepairWithOrderedPrefix = true\n        this.loadOrderedPrefixRepair(windowOperationGeneration)\n      }\n      return\n    }\n    const retained = this.orderedRepairAcquisitions\n    try {\n      this.retireSettledFiniteAcquisitions(undefined, retained)\n    } finally {\n      const hasSupersededAcquisition = [\n        ...this.settledFiniteAcquisitions.keys(),\n      ].some((release) => !retained.has(release))\n      // A release callback may synchronously begin truncate replay. Keep the\n      // repair ownership open so replay settlement can finish retiring the\n      // remaining superseded leases without releasing the refreshed prefix.\n      if (!this.active || !hasSupersededAcquisition) {\n        this.orderedRepairAcquisitions = new Set()\n        this.cancelRepairRetry()\n        this.repairRetries = 0\n        this.canRepairWithOrderedPrefix = false\n        this.needsOrderingRepair = false\n        this.authoritativeRequestState = `none`\n        this.authoritativeRequestKind = undefined\n        this.orderedPrefixRepairGeneration = undefined\n      }\n    }\n  }\n\n  private abandonOrderedPrefixRepair(): void {\n    if (this.authoritativeRequestKind !== `ordered-repair`) return\n    this.orderedRepairAcquisitions = new Set()\n    this.canRepairWithOrderedPrefix = false\n    this.authoritativeRequestState = `none`\n    this.authoritativeRequestKind = undefined\n    this.orderedPrefixRepairGeneration = undefined\n  }\n\n  dispose(): void {\n    this.active = false\n    this.stagedContinuation = undefined\n    this.resetCursor()\n    this.failedAcquisitions.clear()\n    this.settledFiniteAcquisitions.clear()\n  }\n\n  private countAcquiredRows(): number {\n    return this.subscription\n      .readOrderedSnapshot({\n        orderBy: normalizeOrderByPaths(this.info.orderBy, this.alias),\n        limit: this.info.offset + this.info.limit,\n      })\n      .filter(\n        ({ value }) =>\n          this.info.comparator(value, this.settledSourceBoundary) <= 0,\n      ).length\n  }\n\n  private loadPage(\n    count: number,\n    windowOperationGeneration?: number,\n    continuesOrderedPrefixRepair = false,\n  ): void {\n    if (!this.active || this.pending || this.stagedContinuation) return\n    // Rows observed before the first provider request do not prove ordered\n    // source coverage. In particular, a row inserted while limit is zero must\n    // not become the cursor when that window first opens.\n    const startsFromSourcePrefix = this.settledSourceBoundary === undefined\n    const biggest = this.settledSourceBoundary\n    let minValues: Array<unknown> | undefined\n    if (biggest !== undefined) {\n      const value = this.info.valueExtractorForRawRow(biggest)\n      if (!canExpressCursorOrder(this.info.orderBy, [value])) {\n        this.loadPrefix(\n          this.info.offset + this.info.limit,\n          windowOperationGeneration,\n          continuesOrderedPrefixRepair,\n        )\n        return\n      }\n      minValues = [value]\n    }\n    const boundary = minValues?.[0]\n    if (\n      this.lastPage?.count === count &&\n      Object.is(this.lastPage.boundary, boundary)\n    ) {\n      if (continuesOrderedPrefixRepair) {\n        this.finishOrderedPrefixRepair(windowOperationGeneration)\n      }\n      return\n    }\n    this.lastPage = { count, boundary }\n    this.requestAndObserve(\n      (onLoadSubsetResult) => {\n        this.subscription.requestLimitedSnapshot({\n          ...(continuesOrderedPrefixRepair ? { refetch: true } : {}),\n          orderBy: normalizeOrderByPaths(this.info.orderBy, this.alias),\n          limit: count,\n          minValues,\n          // Local rows seen before the first provider request prove neither\n          // a cursor nor a remote offset. Start the first acquisition at zero.\n          offset: startsFromSourcePrefix ? 0 : this.countAcquiredRows(),\n          trackLoadSubsetPromise: false,\n          onLoadSubsetResult,\n        })\n      },\n      `ordered`,\n      windowOperationGeneration,\n      continuesOrderedPrefixRepair,\n    )\n  }\n\n  private observe(\n    result: LoadSubsetRequestResult,\n    releaseAcquisition: ReleaseLoadSubset,\n    kind: OrderedRequestKind,\n    windowOperationGeneration?: number,\n    options?: LoadSubsetOptions,\n    continuesOrderedPrefixRepair = false,\n    requestGraphInputRevision?: number,\n  ): Promise<void> | undefined {\n    const isFullSource = kind === `full-source`\n    const isOrderedRepair = kind === `ordered-repair`\n    const isAuthoritativeRepair =\n      isFullSource || isOrderedRepair || continuesOrderedPrefixRepair\n    const retryRepair =\n      isAuthoritativeRepair &&\n      this.hasSettledSourceRequest &&\n      this.needsOrderingRepair &&\n      windowOperationGeneration === undefined\n    const orderedLoadGeneration = this.orderedLoadGeneration\n    const orderingInvalidationGeneration = this.orderingInvalidationGeneration\n    const settlesAsync = result instanceof Promise\n    const canSettleSynchronously =\n      !settlesAsync &&\n      windowOperationGeneration === undefined &&\n      !isAuthoritativeRepair &&\n      requestGraphInputRevision !== undefined\n    let synchronousCompletionFailure: { error: unknown } | undefined\n    const continuation = (\n      continuationKind: OrderedContinuation[`kind`],\n    ): OrderedContinuation => ({\n      kind: continuationKind,\n      orderedLoadGeneration,\n      orderingInvalidationGeneration,\n      isAuthoritativeRepair,\n      windowOperationGeneration,\n      continuesOrderedPrefixRepair,\n    })\n    const continueOrStage = (\n      next: OrderedContinuation,\n      deferContinuation: boolean,\n    ): void => {\n      if (deferContinuation) {\n        this.stagedContinuation = next\n      } else {\n        this.runContinuation(next)\n      }\n    }\n    const complete = (\n      trackedRequest?: Promise<void>,\n      deferContinuation = false,\n    ): void => {\n      if (trackedRequest && this.pending === trackedRequest) {\n        this.pending = undefined\n      }\n      if (!this.active) return\n      // Retirement failure does not undo a successful acquisition. Finish its\n      // boundary and continuation, then report the first cleanup error.\n      runAllCallbacks([\n        () => {\n          if (!isFullSource) {\n            // A replay can replace the acquisition lease while this older\n            // transport finishes. Retire its logical owner only outside the\n            // replay barrier.\n            const prefixCount =\n              options?.orderBy && !options.cursor ? options.limit : undefined\n            this.settledFiniteAcquisitions.set(releaseAcquisition, prefixCount)\n            if (isOrderedRepair || continuesOrderedPrefixRepair) {\n              this.orderedRepairAcquisitions.add(releaseAcquisition)\n            }\n            if (!continuesOrderedPrefixRepair) {\n              this.retireSettledFiniteAcquisitions()\n            }\n            if (\n              !continuesOrderedPrefixRepair &&\n              orderedLoadGeneration === this.orderedLoadGeneration &&\n              prefixCount !== undefined\n            ) {\n              this.retireSettledFiniteAcquisitions({\n                release: releaseAcquisition,\n                count: prefixCount,\n              })\n            }\n          }\n        },\n        () => {\n          if (orderedLoadGeneration !== this.orderedLoadGeneration) return\n          if (\n            !isAuthoritativeRepair &&\n            orderingInvalidationGeneration !==\n              this.orderingInvalidationGeneration\n          )\n            return\n          // A finite request may finish behind an authoritative repair. It cannot\n          // clear that repair's failure or resume finite refinement around it.\n          if (\n            !isAuthoritativeRepair &&\n            (this.failedRequest || this.authoritativeRequestState !== `none`)\n          )\n            return\n          // If an older overlapping request failed, its unknown partial\n          // writes upgrade the debt to a full-source repair. The ordered\n          // prefix must not erase that failure merely because it settled\n          // later.\n          if (\n            (isOrderedRepair || continuesOrderedPrefixRepair) &&\n            this.failedRequest\n          ) {\n            this.abandonOrderedPrefixRepair()\n            return\n          }\n          this.failedRequest = undefined\n          if (kind !== `boundary`) {\n            this.hasSettledSourceRequest = true\n            // Source delivery can invalidate the in-flight prefix marker.\n            if (options?.orderBy && !options.cursor) {\n              this.lastPrefixCount = options.limit\n            }\n            if (!isFullSource && options?.orderBy) {\n              try {\n                this.settledSourceBoundary =\n                  this.subscription.readOrderedSnapshot(options).at(-1)\n                    ?.value ?? this.settledSourceBoundary\n              } catch (error) {\n                if (canSettleSynchronously) {\n                  synchronousCompletionFailure = { error }\n                  throw error\n                }\n                fail(error)\n              }\n            }\n          }\n          if (\n            (isOrderedRepair || continuesOrderedPrefixRepair) &&\n            this.orderedPrefixRepairGeneration !==\n              this.orderingInvalidationGeneration\n          ) {\n            // The settled request may apply its rows, but a later mutation has\n            // already invalidated this chain. Replace it before issuing stale\n            // tie or refill work.\n            this.finishOrderedPrefixRepair(windowOperationGeneration)\n            return\n          }\n          if (isFullSource) {\n            this.cancelRepairRetry()\n            this.repairRetries = 0\n            this.canRepairWithOrderedPrefix = false\n            this.needsOrderingRepair = false\n            this.authoritativeRequestState = `complete`\n            this.authoritativeRequestKind = undefined\n            this.orderedPrefixRepairGeneration = undefined\n            this.retireSettledFiniteAcquisitions()\n          }\n          if (isOrderedRepair || kind === `ordered`) {\n            continueOrStage(continuation(`boundary`), deferContinuation)\n            return\n          }\n          // A boundary request may add tied rows without filling the query's\n          // window. Resume forward loading once it settles.\n          continueOrStage(continuation(`more`), deferContinuation)\n        },\n      ])\n    }\n    const fail = (error: unknown, trackedRequest?: Promise<void>) => {\n      this.settledFiniteAcquisitions.delete(releaseAcquisition)\n      this.stagedContinuation = undefined\n      if (trackedRequest && this.pending === trackedRequest) {\n        this.pending = undefined\n      }\n      if (!this.active) return\n      // A failed request may already have written only part of its result.\n      // None of those rows is a safe continuation boundary.\n      this.requireFullSourceRepair()\n      if (orderedLoadGeneration !== this.orderedLoadGeneration) return\n      // A failed request proves no full-source coverage. An explicit window\n      // move or later replay may retry it, but an ordinary graph pass must\n      // not start an eager retry loop.\n      if (isAuthoritativeRepair) {\n        if (isFullSource) {\n          this.authoritativeRequestState = `failed`\n        } else {\n          this.authoritativeRequestState = `none`\n          this.authoritativeRequestKind = undefined\n          this.orderedPrefixRepairGeneration = undefined\n        }\n      }\n      this.recordRequestFailure(windowOperationGeneration)\n      this.failedAcquisitions.set(releaseAcquisition, kind)\n      if (retryRepair) this.scheduleRepairRetry()\n      throw error\n    }\n    if (canSettleSynchronously) {\n      try {\n        runAllCallbacks([\n          () => complete(undefined, true),\n          () => {\n            if (!synchronousCompletionFailure) {\n              this.onResult(true, false, false)\n            }\n          },\n          () => {\n            if (\n              !synchronousCompletionFailure &&\n              this.getGraphInputRevision?.() === requestGraphInputRevision\n            ) {\n              this.drainNoInputContinuations(requestGraphInputRevision)\n            }\n          },\n        ])\n      } catch (error) {\n        if (synchronousCompletionFailure) {\n          throw synchronousCompletionFailure.error\n        }\n        throw new OrderedPostSettlementError(error)\n      }\n      return this.pending\n    }\n    const request: Promise<void> = settlesAsync ? result : Promise.resolve()\n    const tracked: Promise<void> = request.then(\n      () => complete(tracked),\n      (error) => fail(error, tracked),\n    )\n    this.pending = tracked\n    void tracked.catch(() => {})\n    // Register each request separately. The operation tracker observes the\n    // next request before this promise settles, so the logical chain remains\n    // pending without retaining every ancestor promise until the final page.\n    this.onResult(\n      tracked,\n      isAuthoritativeRepair && this.needsOrderingRepair,\n      settlesAsync,\n    )\n    return tracked\n  }\n\n  private runContinuation(\n    continuation: OrderedContinuation,\n    windowOperationGeneration = continuation.windowOperationGeneration,\n  ): void {\n    if (\n      !this.active ||\n      continuation.orderedLoadGeneration !== this.orderedLoadGeneration ||\n      (!continuation.isAuthoritativeRepair &&\n        continuation.orderingInvalidationGeneration !==\n          this.orderingInvalidationGeneration)\n    )\n      return\n    if (continuation.kind === `boundary`) {\n      this.loadBoundary(\n        windowOperationGeneration,\n        continuation.continuesOrderedPrefixRepair,\n      )\n    } else {\n      if (this.info.joinedFilterSourceId && this.hasPendingJoinedWork()) {\n        this.stagedContinuation = continuation\n        return\n      }\n      this.loadMore(\n        windowOperationGeneration,\n        continuation.continuesOrderedPrefixRepair,\n      )\n    }\n  }\n\n  private consumeStagedContinuation(windowOperationGeneration?: number): void {\n    const continuation = this.stagedContinuation\n    if (!continuation) return\n    this.stagedContinuation = undefined\n    this.runContinuation(continuation, windowOperationGeneration)\n  }\n\n  private drainNoInputContinuations(graphInputRevision: number): void {\n    if (this.drainingNoInputContinuations) return\n    this.drainingNoInputContinuations = true\n    try {\n      while (\n        this.stagedContinuation &&\n        !this.pending &&\n        this.getGraphInputRevision?.() === graphInputRevision\n      ) {\n        this.consumeStagedContinuation()\n      }\n    } finally {\n      this.drainingNoInputContinuations = false\n    }\n  }\n\n  private loadBoundary(\n    windowOperationGeneration?: number,\n    continuesOrderedPrefixRepair = false,\n  ): Promise<void> | undefined {\n    const biggest = this.settledSourceBoundary\n    if (biggest === undefined) {\n      return continuesOrderedPrefixRepair\n        ? this.loadMore(windowOperationGeneration, true)\n        : undefined\n    }\n    const value = this.info.valueExtractorForRawRow(biggest)\n    const orderBy = normalizeOrderByPaths(this.info.orderBy, this.alias)\n    if (!canExpressCursorOrder(orderBy.slice(0, 1), [value])) {\n      if (continuesOrderedPrefixRepair) this.abandonOrderedPrefixRepair()\n      this.loadFullSource(windowOperationGeneration)\n      return this.pending\n    }\n    // Undefined is not an expressible cursor boundary, so it denotes that no\n    // tie request has been attempted. Other falsy values remain valid keys.\n    if (Object.is(this.lastBoundary, value)) {\n      return this.loadMore(\n        windowOperationGeneration,\n        continuesOrderedPrefixRepair,\n      )\n    }\n    const where = buildCursorCurrent(orderBy, [value])\n    if (!where) {\n      if (continuesOrderedPrefixRepair) this.abandonOrderedPrefixRepair()\n      this.loadFullSource(windowOperationGeneration)\n      return this.pending\n    }\n    this.lastBoundary = value\n    return this.requestAndObserve(\n      (onLoadSubsetResult) => {\n        this.subscription.requestSnapshot({\n          ...(continuesOrderedPrefixRepair ? { refetch: true } : {}),\n          where,\n          trackLoadSubsetPromise: false,\n          onLoadSubsetResult,\n        })\n      },\n      `boundary`,\n      windowOperationGeneration,\n      continuesOrderedPrefixRepair,\n    )\n  }\n\n  private requireFullSourceRepair(): void {\n    this.settledSourceBoundary = undefined\n    this.canRepairWithOrderedPrefix = false\n    this.orderedRepairAcquisitions.clear()\n    this.orderedPrefixRepairGeneration = undefined\n    this.needsOrderingRepair = true\n  }\n\n  private cancelRepairRetry(): void {\n    clearTimeout(this.repairTimer)\n    this.repairTimer = undefined\n  }\n\n  private releaseFailedAcquisitions(): void {\n    const failed = this.failedAcquisitions\n    this.failedAcquisitions = new Map()\n    this.requesting = true\n    try {\n      runAllCallbacks(failed.keys())\n    } finally {\n      this.requesting = false\n    }\n  }\n\n  private scheduleRepairRetry(): void {\n    if (\n      !this.active ||\n      !this.canRetryRepair() ||\n      this.repairTimer !== undefined ||\n      this.repairRetries >= 2\n    )\n      return\n    const orderedLoadGeneration = this.orderedLoadGeneration\n    const failedRequest = this.failedRequest\n    this.repairTimer = setTimeout(\n      () => {\n        this.repairTimer = undefined\n        const retry = Promise.resolve().then(() => {\n          if (\n            !this.active ||\n            !this.canRetryRepair() ||\n            orderedLoadGeneration !== this.orderedLoadGeneration ||\n            this.failedRequest !== failedRequest ||\n            this.failedRequest?.windowOperationGeneration !== undefined\n          )\n            return\n          this.releaseFailedAcquisitions()\n          // Release may dispose or start a new replay; neither belongs to this retry.\n          if (\n            // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- release callbacks can dispose the loader\n            !this.active ||\n            orderedLoadGeneration !== this.orderedLoadGeneration ||\n            this.subscription.hasPendingTruncateReplacement\n          )\n            return\n          this.failedRequest = undefined\n          this.authoritativeRequestState = `none`\n          this.loadFullSource()\n        })\n        void retry.catch(() => {})\n        this.onResult(retry, true, true)\n      },\n      250 * 2 ** this.repairRetries++,\n    )\n  }\n\n  private failRequest(\n    observed:\n      | {\n          result: LoadSubsetRequestResult\n          options: LoadSubsetOptions\n          release: ReleaseLoadSubset\n        }\n      | undefined,\n    error: Error,\n    isAuthoritativeRepair: boolean,\n    windowOperationGeneration?: number,\n    cancelObservedSettlement = false,\n  ): Error {\n    if (cancelObservedSettlement) {\n      this.orderedLoadGeneration++\n      this.pending = undefined\n    }\n    this.requireFullSourceRepair()\n    this.recordRequestFailure(windowOperationGeneration)\n    if (isAuthoritativeRepair) {\n      this.authoritativeRequestState = `none`\n      this.authoritativeRequestKind = undefined\n    }\n    try {\n      observed?.release({ error })\n    } catch {\n      // Cleanup is attempted once and must not replace the request failure.\n    }\n    if (\n      isAuthoritativeRepair &&\n      this.hasSettledSourceRequest &&\n      windowOperationGeneration === undefined\n    ) {\n      this.scheduleRepairRetry()\n    }\n    return error\n  }\n\n  /** A failed request blocks ordinary refinement until a new operation. */\n  private recordRequestFailure(windowOperationGeneration?: number): void {\n    this.failedRequest = { windowOperationGeneration }\n    this.stagedContinuation = undefined\n    this.blockedLoadMore = undefined\n    this.invalidateCursor()\n    this.lastBoundary = undefined\n  }\n\n  /** Observe settlement only after all synchronous request work succeeds. */\n  private requestAndObserve(\n    request: (\n      onResult: (\n        result: LoadSubsetRequestResult,\n        options: LoadSubsetOptions,\n        release: ReleaseLoadSubset,\n      ) => void,\n    ) => void,\n    kind: OrderedRequestKind,\n    windowOperationGeneration?: number,\n    continuesOrderedPrefixRepair = false,\n  ): Promise<void> | undefined {\n    const isFullSource = kind === `full-source`\n    const isAuthoritativeRepair =\n      isFullSource || kind === `ordered-repair` || continuesOrderedPrefixRepair\n    let observed:\n      | {\n          result: LoadSubsetRequestResult\n          options: LoadSubsetOptions\n          release: ReleaseLoadSubset\n        }\n      | undefined\n    this.requesting = true\n    let observing = false\n    const graphInputRevision = this.getGraphInputRevision?.()\n    try {\n      try {\n        request((result, options, release) => {\n          observed = { result, options, release }\n        })\n      } finally {\n        this.requesting = false\n      }\n      if (!observed) return\n      observing = true\n      return this.observe(\n        observed.result,\n        observed.release,\n        kind,\n        windowOperationGeneration,\n        observed.options,\n        continuesOrderedPrefixRepair,\n        graphInputRevision,\n      )\n    } catch (error) {\n      if (error instanceof OrderedPostSettlementError) throw error.cause\n      // Both request and settlement callbacks may reenter through cleanup.\n      // Keep refinement blocked until failure and release finish unwinding.\n      this.requesting = true\n      try {\n        const failure = this.failRequest(\n          observed,\n          normalizeError(error),\n          isAuthoritativeRepair,\n          windowOperationGeneration,\n          observing,\n        )\n        if (\n          !observing &&\n          isAuthoritativeRepair &&\n          this.hasSettledSourceRequest\n        ) {\n          // A synchronous repair failure has no transport promise, but must\n          // still close publication before the triggering graph turn returns.\n          const rejected = Promise.reject(failure)\n          void rejected.catch(() => {})\n          this.onResult(rejected, true, true)\n        }\n        throw failure\n      } finally {\n        this.requesting = false\n      }\n    }\n  }\n}\n"],"names":["normalizeOrderByPaths","runAllCallbacks","canExpressCursorOrder","error","buildCursorCurrent","normalizeError"],"mappings":";;;;;;AAiCA,MAAM,2BAA2B;AAAA,EAC/B,YAAqB,OAAgB;AAAhB,SAAA,QAAA;AAAA,EAAiB;AACxC;AAGO,MAAM,oBAAoB;AAAA,EAqD/B,YACmB,MACA,cACA,OACA,WAIL,MAAM;AAAA,EAAC,GACF,iBAAgC,MAAM,OACtC,uBACA,uBAAsC,MAAM,OAC7D;AAXiB,SAAA,OAAA;AACA,SAAA,eAAA;AACA,SAAA,QAAA;AACA,SAAA,WAAA;AAKA,SAAA,iBAAA;AACA,SAAA,wBAAA;AACA,SAAA,uBAAA;AA1DnB,SAAQ,0BAA0B;AAIlC,SAAQ,sBAAsB;AAK9B,SAAQ,6BAA6B;AACrC,SAAQ,aAAa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