-
Notifications
You must be signed in to change notification settings - Fork 6.8k
Expand file tree
/
Copy pathAppConfigContext.tsx
More file actions
260 lines (227 loc) · 7.84 KB
/
AppConfigContext.tsx
File metadata and controls
260 lines (227 loc) · 7.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import React, {
createContext,
useContext,
useState,
useEffect,
ReactNode,
useCallback,
} from "react";
import apiClient from "@app/services/apiClient";
import { getSimulatedAppConfig } from "@app/testing/serverExperienceSimulations";
import type { AppConfig, AppConfigBootstrapMode } from "@app/types/appConfig";
import { useJwtConfigSync } from "@app/hooks/useJwtConfigSync";
/**
* Sleep utility for delays
*/
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export interface AppConfigRetryOptions {
maxRetries?: number;
initialDelay?: number;
}
export type { AppConfig, AppConfigBootstrapMode };
interface AppConfigContextValue {
config: AppConfig | null;
loading: boolean;
error: string | null;
refetch: () => Promise<void>;
}
const AppConfigContext = createContext<AppConfigContextValue | undefined>({
config: null,
loading: true,
error: null,
refetch: async () => {},
});
/**
* Provider component that fetches and provides app configuration
* Should be placed at the top level of the app, before any components that need config
*/
export interface AppConfigProviderProps {
children: ReactNode;
retryOptions?: AppConfigRetryOptions;
initialConfig?: AppConfig | null;
bootstrapMode?: AppConfigBootstrapMode;
autoFetch?: boolean;
onConfigLoaded?: (config: AppConfig) => void;
}
export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
children,
retryOptions,
initialConfig = null,
bootstrapMode = "blocking",
autoFetch = true,
onConfigLoaded,
}) => {
const isBlockingMode = bootstrapMode === "blocking";
const [config, setConfig] = useState<AppConfig | null>(initialConfig);
const [error, setError] = useState<string | null>(null);
// Track how many times we've attempted to fetch. useRef avoids re-renders that can trigger loops.
const fetchCountRef = React.useRef(0);
// Use a Ref for hasResolvedConfig to avoid re-creating fetchConfig when it changes.
// This prevents unnecessary re-renders and potential infinite loops in consumers.
const hasResolvedConfigRef = React.useRef(
Boolean(initialConfig) && !isBlockingMode,
);
const [hasResolvedConfig, setHasResolvedConfigState] = useState(
hasResolvedConfigRef.current,
);
const setHasResolvedConfig = (val: boolean) => {
hasResolvedConfigRef.current = val;
setHasResolvedConfigState(val);
};
const [loading, setLoading] = useState(!hasResolvedConfig);
const onConfigLoadedRef = React.useRef(onConfigLoaded);
onConfigLoadedRef.current = onConfigLoaded;
const maxRetries = retryOptions?.maxRetries ?? 0;
const initialDelay = retryOptions?.initialDelay ?? 1000;
const fetchConfig = useCallback(
async (force = false) => {
// Prevent duplicate fetches unless forced
if (!force && fetchCountRef.current > 0) {
console.debug("[AppConfig] Already fetched, skipping");
return;
}
// Mark that we've attempted a fetch to prevent repeated auto-fetch loops
fetchCountRef.current += 1;
const shouldBlockUI = !hasResolvedConfigRef.current || isBlockingMode;
if (shouldBlockUI) {
setLoading(true);
}
setError(null);
const startTime = performance.now();
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const testConfig = getSimulatedAppConfig();
if (testConfig) {
setConfig(testConfig);
setHasResolvedConfig(true);
setLoading(false);
return;
}
if (attempt > 0) {
const delay = initialDelay * Math.pow(2, attempt - 1);
console.log(
`[AppConfig] Retry attempt ${attempt}/${maxRetries} after ${delay}ms delay...`,
);
await sleep(delay);
} else {
console.log("[AppConfig] Fetching app config...");
}
// Parallelize app-config and status calls to minimize initialization time
const [configResponse] = await Promise.all([
apiClient.get<AppConfig>("/api/v1/config/app-config", {
suppressErrorToast: true,
skipAuthRedirect: true,
} as any),
// Background probe for status to warm up the connection/cache
apiClient
.get("/api/v1/info/status", {
suppressErrorToast: true,
skipAuthRedirect: true,
} as any)
.catch(() => null),
]);
const data = configResponse.data;
console.debug("[AppConfig] Config fetched successfully:", data);
console.debug(
"[AppConfig] Fetch duration ms:",
(performance.now() - startTime).toFixed(2),
);
setConfig(data);
setHasResolvedConfig(true);
setLoading(false);
onConfigLoadedRef.current?.(data);
return; // Success - exit function
} catch (err: any) {
const status = err?.response?.status;
// On 401 (not authenticated), use default config with login enabled
// This allows the app to work even without authentication
if (status === 401) {
console.debug(
"[AppConfig] 401 error - using default config (login enabled)",
);
console.debug(
"[AppConfig] Fetch duration ms:",
(performance.now() - startTime).toFixed(2),
);
setConfig({ enableLogin: true });
setHasResolvedConfig(true);
setLoading(false);
return;
}
// Check if we should retry (network errors or 5xx errors)
const shouldRetry =
(!status || status >= 500) && attempt < maxRetries;
if (shouldRetry) {
console.warn(
`[AppConfig] Attempt ${attempt + 1} failed (status ${status || "network error"}):`,
err.message,
"- will retry...",
);
continue;
}
// Final attempt failed or non-retryable error (4xx)
const errorMessage =
err?.response?.data?.message ||
err?.message ||
"Unknown error occurred";
setError(errorMessage);
console.error(
`[AppConfig] Failed to fetch app config after ${attempt + 1} attempts:`,
err,
);
console.debug(
"[AppConfig] Fetch duration ms:",
(performance.now() - startTime).toFixed(2),
);
// Preserve existing config (initial default or previous fetch). If nothing is set, assume login enabled.
setConfig((current) => current ?? { enableLogin: true });
setHasResolvedConfig(true);
break;
}
}
setLoading(false);
},
[isBlockingMode, maxRetries, initialDelay],
);
const { isAuthPage } = useJwtConfigSync(fetchConfig);
useEffect(() => {
if (isAuthPage) {
console.debug(
"[AppConfig] On auth page - using default config, skipping fetch",
{ path: window.location.pathname },
);
setConfig({ enableLogin: true });
setHasResolvedConfig(true);
setLoading(false);
return;
}
if (autoFetch) {
fetchConfig();
}
}, [autoFetch, fetchConfig, isAuthPage]);
const refetch = useCallback(() => fetchConfig(true), [fetchConfig]);
const value: AppConfigContextValue = {
config,
loading,
error,
refetch,
};
return (
<AppConfigContext.Provider value={value}>
{children}
</AppConfigContext.Provider>
);
};
/**
* Hook to access application configuration
* Must be used within AppConfigProvider
*/
export function useAppConfig(): AppConfigContextValue {
const context = useContext(AppConfigContext);
if (context === undefined) {
throw new Error("useAppConfig must be used within AppConfigProvider");
}
return context;
}