Detect backend down (#5010)

# Description of Changes

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.
This commit is contained in:
Reece Browne
2025-11-25 22:10:38 +00:00
committed by GitHub
parent d8a99fcb07
commit 31b3219169
8 changed files with 315 additions and 23 deletions
@@ -51,6 +51,7 @@ describe('AppConfigContext', () => {
expect(apiClient.get).toHaveBeenCalledWith('/api/v1/config/app-config', {
suppressErrorToast: true,
skipAuthRedirect: true,
});
});
@@ -282,6 +283,7 @@ describe('AppConfigContext', () => {
await waitFor(() => {
expect(apiClient.get).toHaveBeenCalledWith('/api/v1/config/app-config', {
suppressErrorToast: true,
skipAuthRedirect: true,
});
});
});
@@ -87,7 +87,8 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
const isBlockingMode = bootstrapMode === 'blocking';
const [config, setConfig] = useState<AppConfig | null>(initialConfig);
const [error, setError] = useState<string | null>(null);
const [fetchCount, setFetchCount] = useState(0);
// Track how many times we've attempted to fetch. useRef avoids re-renders that can trigger loops.
const fetchCountRef = React.useRef(0);
const [hasResolvedConfig, setHasResolvedConfig] = useState(Boolean(initialConfig) && !isBlockingMode);
const [loading, setLoading] = useState(!hasResolvedConfig);
@@ -96,11 +97,14 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
const fetchConfig = useCallback(async (force = false) => {
// Prevent duplicate fetches unless forced
if (!force && fetchCount > 0) {
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 = !hasResolvedConfig || isBlockingMode;
if (shouldBlockUI) {
setLoading(true);
@@ -112,7 +116,6 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
const testConfig = getSimulatedAppConfig();
if (testConfig) {
setConfig(testConfig);
setFetchCount((prev) => prev + 1);
setHasResolvedConfig(true);
setLoading(false);
return;
@@ -128,12 +131,17 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
// apiClient automatically adds JWT header if available via interceptors
// Always suppress error toast - we handle 401 errors locally
const response = await apiClient.get<AppConfig>('/api/v1/config/app-config', { suppressErrorToast: true });
const response = await apiClient.get<AppConfig>(
'/api/v1/config/app-config',
{
suppressErrorToast: true,
skipAuthRedirect: true,
} as any,
);
const data = response.data;
console.debug('[AppConfig] Config fetched successfully:', data);
setConfig(data);
setFetchCount(prev => prev + 1);
setHasResolvedConfig(true);
setLoading(false);
return; // Success - exit function
@@ -170,7 +178,7 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
}
setLoading(false);
}, [fetchCount, hasResolvedConfig, isBlockingMode, maxRetries, initialDelay]);
}, [hasResolvedConfig, isBlockingMode, maxRetries, initialDelay]);
useEffect(() => {
// Skip config fetch on auth pages (/login, /signup, /auth/callback, /invite/*)
@@ -209,11 +217,13 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
return () => window.removeEventListener('jwt-available', handleJwtAvailable);
}, [fetchConfig]);
const refetch = useCallback(() => fetchConfig(true), [fetchConfig]);
const value: AppConfigContextValue = {
config,
loading,
error,
refetch: () => fetchConfig(true),
refetch,
};
return (
@@ -0,0 +1,86 @@
import { useCallback, useEffect, useState } from 'react';
import { BASE_PATH } from '@app/constants/app';
type BackendStatus = 'up' | 'starting' | 'down';
interface BackendProbeState {
status: BackendStatus;
loginDisabled: boolean;
loading: boolean;
}
/**
* Lightweight backend probe that avoids global axios interceptors.
* Used on auth screens to decide whether to show login, anonymous mode, or a backend-starting message.
*/
export function useBackendProbe() {
const [state, setState] = useState<BackendProbeState>({
status: 'starting',
loginDisabled: false,
loading: true,
});
const probe = useCallback(async () => {
const statusUrl = `${BASE_PATH || ''}/api/v1/info/status`;
const loginUrl = `${BASE_PATH || ''}/api/v1/proprietary/ui-data/login`;
const next: BackendProbeState = {
status: 'starting',
loginDisabled: false,
loading: false,
};
try {
const res = await fetch(statusUrl, { method: 'GET', cache: 'no-store' });
if (res.ok) {
const data = await res.json().catch(() => null);
if (data && data.status === 'UP') {
next.status = 'up';
setState(next);
return next;
}
next.status = 'starting';
} else if (res.status === 404 || res.status === 503) {
next.status = 'starting';
} else {
next.status = 'down';
}
} catch {
next.status = 'down';
}
// Fallback: proprietary login endpoint to detect disabled login and backend availability
try {
const res = await fetch(loginUrl, { method: 'GET', cache: 'no-store' });
if (res.ok) {
next.status = 'up';
const data = await res.json().catch(() => null);
if (data && data.enableLogin === false) {
next.loginDisabled = true;
}
} else if (res.status === 404) {
// Endpoint missing usually means login disabled
next.status = 'up';
next.loginDisabled = true;
} else if (res.status === 503) {
next.status = 'starting';
} else {
next.status = 'down';
}
} catch {
// keep previous inferred state (down/starting)
}
setState(next);
return next;
}, []);
useEffect(() => {
void probe();
}, [probe]);
return {
...state,
probe,
};
}
+12 -4
View File
@@ -88,6 +88,7 @@ const SPECIAL_SUPPRESS_MS = 1500; // brief window to suppress generic duplicate
* Returns true if the error should be suppressed (deduplicated), false otherwise
*/
export async function handleHttpError(error: any): Promise<boolean> {
const skipAuthRedirect = error?.config?.skipAuthRedirect === true;
// Check if this error should skip the global toast (component will handle it)
if (error?.config?.suppressErrorToast === true) {
return false; // Don't show global toast, but continue rejection
@@ -105,12 +106,19 @@ export async function handleHttpError(error: any): Promise<boolean> {
pathname.includes('/invite/');
// If not on auth page, redirect to login with expired session message
if (!isAuthPage) {
if (!isAuthPage && !skipAuthRedirect) {
console.debug('[httpErrorHandler] 401 detected, redirecting to login');
// Store the current location so we can redirect back after login
const currentLocation = window.location.pathname + window.location.search;
// Redirect to login with state
window.location.href = `/login?expired=true&from=${encodeURIComponent(currentLocation)}`;
// Redirect to login with state (only show expired when a JWT existed)
let hadStoredJwt = false;
try {
hadStoredJwt = Boolean(localStorage.getItem('stirling_jwt'));
} catch {
// ignore storage access failures
}
const expiredPrefix = hadStoredJwt ? 'expired=true&' : '';
window.location.href = `/login?${expiredPrefix}from=${encodeURIComponent(currentLocation)}`;
return true; // Suppress toast since we're redirecting
}
@@ -173,4 +181,4 @@ export async function handleHttpError(error: any): Promise<boolean> {
}
return false; // Error was handled with toast, continue normal rejection
}
}