Line data Source code
1 : import axios from 'axios'
2 : import { shallowReactive } from 'vue'
3 :
4 : import { combineAbortSignals } from '@comfyorg/api-client/abortSignal'
5 : import { useChainCallback } from '@/composables/functional/useChainCallback'
6 : import type { ComboWidgetInventoryStatus } from '@/core/graph/widgets/comboWidgetInventory'
7 : import type { IWidget, LGraphNode } from '@/lib/litegraph/src/litegraph'
8 : import { isCloud } from '@/platform/distribution/types'
9 : import type { RemoteWidgetConfig } from '@comfyorg/object-info-parser'
10 : import { api } from '@/scripts/api'
11 : import { useAuthStore } from '@/stores/authStore'
12 :
13 2356 : const MAX_RETRIES = 5
14 2356 : const TIMEOUT = 4096
15 :
16 : interface CacheEntry<T> {
17 : data: T
18 : timestamp?: number
19 : error?: Error | null
20 : fetchPromise?: Promise<T>
21 : controller?: AbortController
22 : lastErrorTime?: number
23 : retryCount?: number
24 : failed?: boolean
25 : }
26 :
27 33 : async function getAuthHeaders() {
28 : if (isCloud) {
29 : const authStore = useAuthStore()
30 : const authHeader = await authStore.getAuthHeader()
31 : return {
32 : ...(authHeader && { headers: authHeader })
33 : }
34 : }
35 33 : return {}
36 : }
37 :
38 2356 : const dataCache = shallowReactive(new Map<string, CacheEntry<unknown>>())
39 :
40 2356 : const createCacheKey = (config: RemoteWidgetConfig): string => {
41 33 : const { route, query_params = {}, refresh = 0 } = config
42 :
43 33 : const paramsKey = Object.entries(query_params)
44 : .sort(([a], [b]) => a.localeCompare(b))
45 : .map(([k, v]) => `${k}=${v}`)
46 : .join('&')
47 :
48 33 : return [route, `r=${refresh}`, paramsKey].join(';')
49 : }
50 :
51 2356 : const getBackoff = (retryCount: number) =>
52 : Math.min(1000 * Math.pow(2, retryCount), 512)
53 :
54 2356 : const isInitialized = (entry: CacheEntry<unknown> | undefined) =>
55 : entry?.data !== undefined &&
56 : entry.timestamp !== undefined &&
57 : entry.timestamp > 0
58 :
59 2356 : const isStale = (entry: CacheEntry<unknown> | undefined, ttl: number) =>
60 : entry?.timestamp && Date.now() - entry.timestamp >= ttl
61 :
62 2356 : const isFetching = (entry: CacheEntry<unknown> | undefined) =>
63 : entry?.fetchPromise !== undefined
64 :
65 2356 : const isFailed = (entry: CacheEntry<unknown> | undefined) =>
66 : entry?.failed === true
67 :
68 2356 : const isBackingOff = (entry: CacheEntry<unknown> | undefined) =>
69 : entry?.error &&
70 : entry.lastErrorTime &&
71 : Date.now() - entry.lastErrorTime < getBackoff(entry.retryCount || 0)
72 :
73 2356 : class RemoteWidgetRequestError extends Error {}
74 :
75 2356 : const isSameOrigin = (route: string) =>
76 : new URL(route, location.href).origin === location.origin
77 :
78 2356 : const withQuery = (
79 : route: string,
80 : params: RemoteWidgetConfig['query_params']
81 : ) => {
82 33 : const query = new URLSearchParams(params).toString()
83 33 : if (!query) return route
84 33 : return `${route}${route.includes('?') ? '&' : '?'}${query}`
85 : }
86 :
87 2356 : const parseBody = (text: string): unknown => {
88 0 : try {
89 0 : return JSON.parse(text)
90 : } catch {
91 0 : return text
92 : }
93 : }
94 :
95 2356 : const pickKey = (data: unknown, key: string | undefined) => {
96 0 : if (!key) return data
97 0 : return typeof data === 'object' && data !== null
98 : ? Reflect.get(data, key)
99 : : undefined
100 : }
101 :
102 2356 : const fetchOnSession = async (
103 : config: RemoteWidgetConfig,
104 : controller: AbortController
105 : ): Promise<{ data: unknown } | undefined> => {
106 33 : const { route, query_params, timeout = TIMEOUT } = config
107 33 : if (!isSameOrigin(route)) return undefined
108 :
109 33 : const timeoutController = new AbortController()
110 33 : const timer =
111 : timeout > 0 ? setTimeout(() => timeoutController.abort(), timeout) : 0
112 33 : try {
113 33 : const res = await api.fetchOnWebSession(withQuery(route, query_params), {
114 : method: 'GET',
115 : signal: combineAbortSignals([controller.signal, timeoutController.signal])
116 : })
117 33 : if (!res) return undefined
118 0 : if (!res.ok) {
119 0 : throw new RemoteWidgetRequestError(
120 : `Request failed with status ${res.status}`
121 : )
122 : }
123 0 : return { data: parseBody(await res.text()) }
124 : } finally {
125 33 : clearTimeout(timer)
126 : }
127 : }
128 :
129 2356 : const fetchData = async (
130 : config: RemoteWidgetConfig,
131 : controller: AbortController
132 : ) => {
133 33 : const { route, response_key, query_params, timeout = TIMEOUT } = config
134 :
135 33 : const sessionRes = await fetchOnSession(config, controller)
136 33 : if (sessionRes) return pickKey(sessionRes.data, response_key)
137 :
138 33 : const authHeaders = isSameOrigin(route) ? await getAuthHeaders() : {}
139 :
140 33 : const res = await axios.get(route, {
141 : params: query_params,
142 : signal: controller.signal,
143 : timeout,
144 : ...authHeaders
145 : })
146 :
147 33 : return response_key ? res.data[response_key] : res.data
148 : }
149 :
150 33 : export function useRemoteWidget<
151 : T extends string | number | boolean | object
152 : >(options: {
153 : remoteConfig: RemoteWidgetConfig
154 : defaultValue: T
155 : node: LGraphNode
156 : widget: IWidget
157 : }) {
158 33 : const { remoteConfig, defaultValue, node, widget } = options
159 33 : const { refresh = 0, max_retries = MAX_RETRIES } = remoteConfig
160 33 : const isPermanent = refresh <= 0
161 33 : const cacheKey = createCacheKey(remoteConfig)
162 33 : let isLoaded = false
163 33 : let refreshQueued = false
164 33 : let removed = false
165 :
166 33 : const setSuccess = (entry: CacheEntry<T>, data: T) => {
167 28 : entry.retryCount = 0
168 28 : entry.lastErrorTime = 0
169 28 : entry.error = null
170 28 : entry.timestamp = Date.now()
171 28 : entry.data = data
172 : }
173 :
174 33 : const setError = (entry: CacheEntry<T>, error: unknown) => {
175 3 : entry.retryCount = (entry.retryCount || 0) + 1
176 3 : entry.lastErrorTime = Date.now()
177 3 : entry.error = error instanceof Error ? error : new Error(String(error))
178 3 : entry.fetchPromise = undefined
179 3 : if (entry.retryCount >= max_retries) {
180 0 : setFailed(entry)
181 : }
182 : }
183 :
184 33 : const setFailed = (entry: CacheEntry<T>) => {
185 0 : dataCache.set(cacheKey, {
186 : data: entry.data,
187 : failed: true
188 : })
189 : }
190 :
191 33 : const isFirstLoad = () => {
192 223 : return !isLoaded && isInitialized(dataCache.get(cacheKey))
193 : }
194 :
195 33 : const onFirstLoad = (data: T | T[]) => {
196 31 : isLoaded = true
197 31 : const nextValue = Array.isArray(data)
198 : ? (data.find((value) => value === widget.value) ?? data[0])
199 : : undefined
200 31 : widget.value = nextValue ?? (Array.isArray(data) ? defaultValue : data)
201 31 : widget.callback?.(widget.value)
202 31 : node.graph?.setDirtyCanvas(true)
203 : }
204 :
205 33 : const fetchValue = async () => {
206 225 : const entry = dataCache.get(cacheKey)
207 :
208 225 : if (isFailed(entry)) return entry!.data as T
209 :
210 : const isValid =
211 : isInitialized(entry) && (isPermanent || !isStale(entry, refresh))
212 225 : if (isValid || isBackingOff(entry) || isFetching(entry))
213 192 : return entry!.data as T
214 :
215 225 : const currentEntry: CacheEntry<T> = shallowReactive(
216 : (entry as CacheEntry<T> | undefined) || { data: defaultValue }
217 : )
218 225 : dataCache.set(cacheKey, currentEntry)
219 :
220 225 : try {
221 225 : currentEntry.controller = new AbortController()
222 225 : currentEntry.fetchPromise = fetchData(
223 : remoteConfig,
224 : currentEntry.controller
225 : )
226 225 : const data = await currentEntry.fetchPromise
227 :
228 28 : setSuccess(currentEntry, data)
229 28 : return currentEntry.data
230 : } catch (err) {
231 3 : setError(currentEntry, err)
232 3 : return currentEntry.data
233 : } finally {
234 31 : currentEntry.fetchPromise = undefined
235 31 : currentEntry.controller = undefined
236 : }
237 : }
238 :
239 33 : const onRefresh = () => {
240 4 : if (remoteConfig.control_after_refresh) {
241 1 : const data = getCachedValue()
242 1 : if (!Array.isArray(data)) return // control_after_refresh is only supported for array values
243 :
244 1 : switch (remoteConfig.control_after_refresh) {
245 : case 'first':
246 1 : widget.value = data[0] ?? defaultValue
247 1 : break
248 : case 'last':
249 0 : widget.value = data.at(-1) ?? defaultValue
250 : break
251 : }
252 1 : widget.callback?.(widget.value)
253 1 : node.graph?.setDirtyCanvas(true)
254 : }
255 : }
256 :
257 : /**
258 : * Clear the widget's cached value, forcing a refresh on next access (e.g., a new render)
259 : */
260 33 : const clearCachedValue = () => {
261 4 : const entry = dataCache.get(cacheKey)
262 4 : if (!entry) return
263 4 : if (entry.fetchPromise) entry.controller?.abort() // Abort in-flight request
264 4 : dataCache.delete(cacheKey)
265 : }
266 :
267 : /**
268 : * Get the cached value of the widget without starting a new fetch.
269 : * @returns the most recently computed value of the widget.
270 : */
271 226 : function getCachedValue() {
272 226 : return dataCache.get(cacheKey)?.data as T
273 : }
274 :
275 2 : function getInventoryStatus(): ComboWidgetInventoryStatus {
276 2 : const entry = dataCache.get(cacheKey)
277 : const isFresh =
278 : isInitialized(entry) && (isPermanent || !isStale(entry, refresh))
279 2 : if (isFresh) return isLoaded ? 'ready' : 'loading'
280 1 : if (isFetching(entry)) return 'loading'
281 2 : if (isFailed(entry) || entry?.error) return 'error'
282 0 : return 'loading'
283 : }
284 :
285 1 : async function waitForInventory(signal?: AbortSignal): Promise<void> {
286 1 : while (!signal?.aborted) {
287 2 : const inFlight = dataCache.get(cacheKey)?.fetchPromise
288 2 : if (inFlight) {
289 1 : await inFlight.catch(() => undefined)
290 1 : continue
291 : }
292 1 : await new Promise<void>((resolve) => getValue(resolve))
293 2 : if (!dataCache.get(cacheKey)?.fetchPromise) return
294 : }
295 : }
296 :
297 : /**
298 : * Getter of the remote property of the widget (e.g., options.values, value, etc.).
299 : * Starts the fetch process then returns the cached value immediately.
300 : * @returns the most recent value of the widget.
301 : */
302 225 : function getValue(onFulfilled?: () => void) {
303 225 : void fetchValue()
304 : .then((data) => {
305 223 : if (removed) return
306 223 : if (isFirstLoad()) onFirstLoad(data)
307 223 : if (refreshQueued && data !== defaultValue) {
308 4 : onRefresh()
309 4 : refreshQueued = false
310 : }
311 : })
312 : .finally(() => onFulfilled?.())
313 : .catch((err) => {
314 0 : console.error(err)
315 : })
316 225 : return getCachedValue()
317 : }
318 :
319 : /**
320 : * Force the widget to refresh its value
321 : */
322 33 : widget.refresh = function () {
323 4 : refreshQueued = true
324 4 : clearCachedValue()
325 4 : getValue()
326 : }
327 :
328 : /**
329 : * Add a refresh button to the node that, when clicked, will force the widget to refresh
330 : */
331 21 : function addRefreshButton() {
332 21 : node.addWidget('button', 'refresh', 'refresh', widget.refresh)
333 : }
334 :
335 : /**
336 : * Add auto-refresh toggle widget and execution success listener
337 : */
338 33 : function addAutoRefreshToggle() {
339 33 : let autoRefreshEnabled = false
340 :
341 : // Handler for execution success
342 33 : const handleExecutionSuccess = () => {
343 0 : if (autoRefreshEnabled && widget.refresh) {
344 0 : widget.refresh()
345 : }
346 : }
347 :
348 : // Add toggle widget
349 33 : const autoRefreshWidget = node.addWidget(
350 : 'toggle',
351 : 'Auto-refresh after generation',
352 : false,
353 : (value: boolean) => {
354 0 : autoRefreshEnabled = value
355 : },
356 : {
357 : serialize: false
358 : }
359 : )
360 :
361 : // Register event listener
362 33 : api.addEventListener('execution_success', handleExecutionSuccess)
363 :
364 33 : const cleanup = () => {
365 5 : api.removeEventListener('execution_success', handleExecutionSuccess)
366 : }
367 33 : widget.onRemove = useChainCallback(widget.onRemove, () => {
368 3 : removed = true
369 3 : cleanup()
370 : })
371 33 : node.onRemoved = useChainCallback(node.onRemoved, cleanup)
372 :
373 33 : return autoRefreshWidget
374 : }
375 :
376 : // Always add auto-refresh toggle for remote widgets
377 33 : addAutoRefreshToggle()
378 :
379 33 : return {
380 : getCachedValue,
381 : getValue,
382 : refreshValue: widget.refresh,
383 : addRefreshButton,
384 : getCacheEntry: () => dataCache.get(cacheKey),
385 : getInventoryStatus,
386 : waitForInventory,
387 :
388 : cacheKey
389 : }
390 : }
|