Line data Source code
1 : import { computed, onScopeDispose, ref, toValue, watch } from 'vue'
2 : import type { MaybeRefOrGetter, Ref } from 'vue'
3 :
4 : import {
5 : DEFAULT_PAGE_SIZE,
6 : PACK_SEARCHABLE_ATTRIBUTES,
7 : USER_SEARCH_ANALYTICS_TAG
8 : } from '@/constants/searchConstants'
9 : import { reportError } from '@comfyorg/telemetry/reportError'
10 : import { useRegistrySearchGateway } from '@/services/gateway/registrySearchGateway'
11 : import type {
12 : SearchAttribute,
13 : SearchNodePacksParams
14 : } from '@/types/algoliaTypes'
15 : import type { components } from '@/types/comfyRegistryTypes'
16 : import type {
17 : QuerySuggestion,
18 : SearchMode,
19 : SearchPacksResult
20 : } from '@/types/searchServiceTypes'
21 : import { usePreemptableQueue } from '@/utils/pagedList'
22 : import type { PagedList } from '@/utils/pagedList'
23 :
24 : type RegistryNodePack = components['schemas']['Node']
25 :
26 : type FirstPage =
27 : | { status: 'loading' }
28 : | { status: 'failed'; query: string }
29 : | { status: 'loaded'; query: string; rawResultsEmpty: boolean }
30 :
31 2355 : const LOADING_FIRST_PAGE: FirstPage = { status: 'loading' }
32 :
33 : type PageFreshness = 'current' | 'stale'
34 :
35 : /**
36 : * Offset-paged registry search as a {@link PagedList} that reloads from the
37 : * first page whenever its inputs change.
38 : */
39 15 : export function useRegistrySearch(inputs: {
40 : query: MaybeRefOrGetter<string>
41 : searchMode: MaybeRefOrGetter<SearchMode>
42 : /** Whether the query came from the user typing, for analytics tagging. */
43 : isTypedQuery?: MaybeRefOrGetter<boolean>
44 : /** Whether the results are on screen; only on-screen failures are reported. */
45 : isVisible?: MaybeRefOrGetter<boolean>
46 : }): PagedList<RegistryNodePack> & {
47 : suggestions: Readonly<Ref<QuerySuggestion[]>>
48 : /**
49 : * The first page for the current inputs: loading from an input change
50 : * until its search settles, then the query it searched and its outcome.
51 : */
52 : firstPage: Readonly<Ref<FirstPage>>
53 : /** Whether the page after the loaded ones failed and waits for a retry. */
54 : isNextPageFailed: Readonly<Ref<boolean>>
55 : /** Loads the failed next page again for the same search. */
56 : retryNextPage: () => Promise<boolean>
57 : } {
58 15 : const { searchPacks, resetCircuits } = useRegistrySearchGateway()
59 :
60 15 : let pageNumber = 0
61 15 : let generation = 0
62 15 : let failureReportedSinceSuccess = false
63 15 : let isDisposed = false
64 15 : const items = ref<RegistryNodePack[]>([])
65 15 : const morePages = ref(true)
66 15 : const isNextPageFailed = ref(false)
67 15 : const suggestions = ref<QuerySuggestion[]>([])
68 15 : const firstPage = ref<FirstPage>(LOADING_FIRST_PAGE)
69 15 : const { enqueue, preempt, running: isLoading } = usePreemptableQueue()
70 15 : const searchedQuery = () => toValue(inputs.query).trim()
71 :
72 15 : const searchableAttributes = (searchMode: SearchMode): SearchAttribute[] =>
73 : searchMode === 'nodes' ? ['comfy_nodes'] : [...PACK_SEARCHABLE_ATTRIBUTES]
74 :
75 20 : function analyticsParams(
76 : query: string
77 : ): Pick<SearchNodePacksParams, 'analyticsTags'> {
78 : const isTypedSearch =
79 : pageNumber === 0 &&
80 : query !== '' &&
81 : (toValue(inputs.isTypedQuery) ?? false)
82 20 : return isTypedSearch ? { analyticsTags: [USER_SEARCH_ANALYTICS_TAG] } : {}
83 : }
84 :
85 1 : function reportFirstFailureSinceSuccess(cause: unknown) {
86 1 : if (failureReportedSinceSuccess || !(toValue(inputs.isVisible) ?? true)) {
87 0 : return
88 : }
89 1 : failureReportedSinceSuccess = true
90 1 : reportError(cause, {
91 : errorType: 'error_searching_registry_packs',
92 : surface: 'platform',
93 : level: 'warning',
94 : tags: { outcome: 'degraded' }
95 : })
96 : }
97 :
98 19 : function applyPage(query: string, result: SearchPacksResult) {
99 19 : const { nodePacks } = result
100 19 : morePages.value = result.hasMore ?? nodePacks.length >= DEFAULT_PAGE_SIZE
101 19 : if (pageNumber === 0) {
102 18 : firstPage.value = {
103 : status: 'loaded',
104 : query,
105 : rawResultsEmpty: result.rawResultsEmpty ?? nodePacks.length === 0
106 : }
107 : }
108 19 : items.value.push(...nodePacks)
109 19 : suggestions.value = result.querySuggestions
110 19 : pageNumber++
111 : }
112 :
113 1 : function applyFailure(query: string, cause: unknown) {
114 1 : reportFirstFailureSinceSuccess(cause)
115 1 : if (pageNumber > 0) {
116 1 : isNextPageFailed.value = true
117 1 : return
118 : }
119 0 : morePages.value = false
120 0 : firstPage.value = { status: 'failed', query }
121 0 : suggestions.value = []
122 : }
123 :
124 20 : async function doLoadMore(): Promise<PageFreshness> {
125 20 : if (!morePages.value || isNextPageFailed.value) return 'current'
126 20 : const requestGeneration = generation
127 20 : const query = searchedQuery()
128 20 : const outcome = await searchPacks(query, {
129 : pageSize: DEFAULT_PAGE_SIZE,
130 : pageNumber,
131 : restrictSearchableAttributes: searchableAttributes(
132 : toValue(inputs.searchMode)
133 : ),
134 : ...analyticsParams(query)
135 : })
136 20 : if (outcome.ok) failureReportedSinceSuccess = false
137 20 : if (isDisposed || requestGeneration !== generation) return 'stale'
138 20 : if (outcome.ok) applyPage(query, outcome.result)
139 1 : else applyFailure(query, outcome.cause)
140 20 : return 'current'
141 : }
142 :
143 18 : async function loadCurrentFirstPage(): Promise<void> {
144 18 : if ((await doLoadMore()) === 'stale' && !isDisposed) {
145 0 : return loadCurrentFirstPage()
146 : }
147 : }
148 :
149 18 : function reload() {
150 18 : generation++
151 18 : pageNumber = 0
152 18 : morePages.value = true
153 18 : isNextPageFailed.value = false
154 18 : firstPage.value = LOADING_FIRST_PAGE
155 18 : items.value = []
156 18 : return preempt(loadCurrentFirstPage)
157 : }
158 :
159 2 : async function loadMore() {
160 2 : const startingPage = pageNumber
161 2 : await enqueue('loadMore', async () => {
162 2 : await doLoadMore()
163 : })
164 2 : return pageNumber > startingPage
165 : }
166 :
167 0 : function retry() {
168 0 : resetCircuits()
169 0 : return reload()
170 : }
171 :
172 1 : async function retryNextPage() {
173 1 : if (!isNextPageFailed.value) return false
174 1 : resetCircuits()
175 1 : isNextPageFailed.value = false
176 1 : return loadMore()
177 : }
178 :
179 15 : onScopeDispose(() => {
180 1 : isDisposed = true
181 : }, true)
182 :
183 15 : watch(
184 : [searchedQuery, () => toValue(inputs.searchMode)],
185 : () => void reload(),
186 : {
187 : immediate: true
188 : }
189 : )
190 :
191 15 : return {
192 : items,
193 : hasMore: computed(() => morePages.value && !isNextPageFailed.value),
194 : isLoading,
195 : loadMore,
196 : loadNew: retry,
197 : invalidate: reload,
198 : suggestions,
199 : firstPage,
200 : isNextPageFailed,
201 : retryNextPage
202 : }
203 : }
|