Skip to content

Commit

Permalink
fix(base): wait for all chunked requests to arrive before continuing (#…
Browse files Browse the repository at this point in the history
…4017)

Our previous approach of chunking document availability requests did not wait for all the chunks to finish before returning the results. The debounceCollect utility expects an observable that returns all results in one go, but because we returned a stream that would emit the chunks one-by-one as they arrived, we would only handle the first emission, which would not include the whole result set, breaking assumptions further down the line.

This patch fixes the issue by reducing over each emission, successively add them to an array. (the reduce operator will wait for the stream to finish before emitting a single reduced value).
  • Loading branch information
bjoerge committed Dec 22, 2022
1 parent 9eae0b0 commit 2134b27
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion packages/sanity/src/core/preview/availability.ts
Expand Up @@ -2,7 +2,7 @@

import type {SanityClient} from '@sanity/client'
import {combineLatest, defer, from, Observable, of} from 'rxjs'
import {distinctUntilChanged, map, mergeMap, switchMap} from 'rxjs/operators'
import {distinctUntilChanged, map, mergeMap, reduce, switchMap} from 'rxjs/operators'
import shallowEquals from 'shallow-equals'
import {flatten, keyBy} from 'lodash'
import {getDraftId, getPublishedId, isRecord} from '../util'
Expand Down Expand Up @@ -56,6 +56,16 @@ function chunkDocumentIds(documentIds: string[]): string[][] {
return chunks
}

/**
* Mutative concat
* @param array - the array to concat to
* @param chunks - the items to concat to the array
*/
function mutConcat<T>(array: T[], chunks: T[]) {
array.push(...chunks)
return array
}

export function create_preview_availability(
versionedClient: SanityClient,
observePaths: ObservePathsFn
Expand Down Expand Up @@ -111,6 +121,7 @@ export function create_preview_availability(
const uniqueIds = [...new Set(flatten(args))]
return from(chunkDocumentIds(uniqueIds)).pipe(
mergeMap(fetchDocumentReadabilityChunked, 10),
reduce<DocumentAvailability[], DocumentAvailability[]>(mutConcat, []),
map((res) => args.map(([id]) => res[uniqueIds.indexOf(id)]))
)
},
Expand Down

1 comment on commit 2134b27

@vercel
Copy link

@vercel vercel bot commented on 2134b27 Dec 22, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

test-studio – ./

test-studio.sanity.build
test-studio-git-next.sanity.build

Please sign in to comment.