()
| 60 | } |
| 61 | |
| 62 | export function useRouting(): RoutingState { |
| 63 | const { api } = useAPI(); |
| 64 | const { config: providersConfig } = useProvidersConfig(); |
| 65 | const [routePriority, setRoutePriorityState] = useState<string[]>(DEFAULT_ROUTE_PRIORITY); |
| 66 | const [routeOverrides, setRouteOverridesState] = useState<Record<string, string>>({}); |
| 67 | // Ignore stale config fetches so backend refreshes can't overwrite newer optimistic edits. |
| 68 | const fetchVersionRef = useRef(0); |
| 69 | |
| 70 | const fetchRoutingConfig = useCallback(async () => { |
| 71 | const getConfig = api?.config?.getConfig; |
| 72 | if (!getConfig) { |
| 73 | return; |
| 74 | } |
| 75 | |
| 76 | const fetchVersion = ++fetchVersionRef.current; |
| 77 | |
| 78 | try { |
| 79 | const config = await getConfig(); |
| 80 | if (fetchVersion !== fetchVersionRef.current) { |
| 81 | return; |
| 82 | } |
| 83 | |
| 84 | setRoutePriorityState(config.routePriority ?? DEFAULT_ROUTE_PRIORITY); |
| 85 | setRouteOverridesState(config.routeOverrides ?? {}); |
| 86 | } catch { |
| 87 | // Best-effort only. |
| 88 | } |
| 89 | }, [api]); |
| 90 | |
| 91 | useEffect(() => { |
| 92 | const onConfigChanged = api?.config?.onConfigChanged; |
| 93 | if (!onConfigChanged) { |
| 94 | return; |
| 95 | } |
| 96 | |
| 97 | const abortController = new AbortController(); |
| 98 | const { signal } = abortController; |
| 99 | let iterator: AsyncIterator<unknown> | null = null; |
| 100 | |
| 101 | void fetchRoutingConfig(); |
| 102 | |
| 103 | (async () => { |
| 104 | try { |
| 105 | const subscribedIterator = await onConfigChanged(undefined, { signal }); |
| 106 | |
| 107 | if (signal.aborted) { |
| 108 | void subscribedIterator.return?.(); |
| 109 | return; |
| 110 | } |
| 111 | |
| 112 | iterator = subscribedIterator; |
| 113 | |
| 114 | for await (const _ of subscribedIterator) { |
| 115 | if (signal.aborted) { |
| 116 | break; |
| 117 | } |
| 118 | void fetchRoutingConfig(); |
| 119 | } |
no test coverage detected