forge
Explore
Log in

Don't you dare go Hollow

🐛 keep the app alive when /users/me fails

Browse files at this commit

e4045ccc8aa33eed4aec925e801e695d7112859bAhmet Kaan GümüşParent: 905655a
  • fix
    • 🐛 keep the app alive when /users/me fails
Show full message
fix: 🐛 keep the app alive when /users/me fails

A non-401 failure on the bootstrap /users/me (e.g. a 429 once the API
rate limit trips) threw out of an unguarded resource and blanked the
whole tab with no way back but a fresh tab. Now the resource swallows
every non-401 error into an error signal and resolves immediately, so it
never re-throws during render nor suspends the shell. RouteGuard shows a
translated alert with a Try-again button, a root ErrorBoundary backstops
anything else, and a non-blocking background timer auto-retries after the
server's Retry-After so the tab self-heals once the window rolls over.
src/api/client/client.tsmodified+1 -1
@@ -172,7 +172,7 @@ const FIELD_LABELS: Record<string, Record<Locale, string>> = {
172 username: { en: "Username", tr: "Kullanıcı adı" },172 username: { en: "Username", tr: "Kullanıcı adı" },
173 };173 };
174 174
175-function currentLocale(): Locale {175+export function currentLocale(): Locale {
176 if (typeof window === "undefined") return "en";176 if (typeof window === "undefined") return "en";
177 try {177 try {
178 const saved = window.localStorage.getItem("hezarfen.locale");178 const saved = window.localStorage.getItem("hezarfen.locale");
src/app.tsxmodified+28 -3
@@ -1,18 +1,43 @@
1 import { RouterProvider } from "@tanstack/solid-router";1 import { RouterProvider } from "@tanstack/solid-router";
2-import { Suspense, lazy } from "solid-js";2+import { ErrorBoundary, Suspense, lazy } from "solid-js";
3+import { currentLocale, formatApiError } from "@/api/client";
3 import { router } from "@/routes/router";4 import { router } from "@/routes/router";
4 5
5 const RouterDevtools = import.meta.env.DEV ? lazy(() => import("@/router-devtools")) : undefined;6 const RouterDevtools = import.meta.env.DEV ? lazy(() => import("@/router-devtools")) : undefined;
6 7
8+// Last-resort backstop for anything that throws during render. It lives above
9+// the i18n provider, so it mirrors the client's own bilingual-fallback idiom
10+// instead of using t(...); a real message + reload beats a blank document.
11+function RootErrorFallback(props: { error: unknown; reset: () => void }) {
12+ const tr = currentLocale() === "tr";
13+ return (
14+ <div class="flex min-h-screen items-center justify-center bg-background px-4 text-foreground">
15+ <div class="w-full max-w-md space-y-4 rounded-md border border-destructive/30 bg-destructive/10 p-6 text-center text-destructive">
16+ <p class="text-sm">{formatApiError(props.error)}</p>
17+ <button
18+ type="button"
19+ class="rounded-md border border-current px-4 py-2 text-sm font-medium"
20+ onClick={() => {
21+ props.reset();
22+ window.location.reload();
23+ }}
24+ >
25+ {tr ? "Yeniden yükle" : "Reload"}
26+ </button>
27+ </div>
28+ </div>
29+ );
30+}
31+
7 export function App() {32 export function App() {
8 return (33 return (
9- <>34+ <ErrorBoundary fallback={(error, reset) => <RootErrorFallback error={error} reset={reset} />}>
10 <RouterProvider router={router} />35 <RouterProvider router={router} />
11 {RouterDevtools ? (36 {RouterDevtools ? (
12 <Suspense>37 <Suspense>
13 <RouterDevtools />38 <RouterDevtools />
14 </Suspense>39 </Suspense>
15 ) : null}40 ) : null}
16- </>41+ </ErrorBoundary>
17 );42 );
18 }43 }
src/components/layout/route-guard.tsxmodified+13 -0
@@ -1,7 +1,9 @@
1 import { Navigate } from "@tanstack/solid-router";1 import { Navigate } from "@tanstack/solid-router";
2 import { type ParentProps, Show } from "solid-js";2 import { type ParentProps, Show } from "solid-js";
3 import type { Role } from "@/api/client";3 import type { Role } from "@/api/client";
4+import { formatApiError } from "@/api/client";
4 import { Alert } from "@/components/ui/alert";5 import { Alert } from "@/components/ui/alert";
6+import { Button } from "@/components/ui/button";
5 import { PageSpinner } from "@/components/ui/page-spinner";7 import { PageSpinner } from "@/components/ui/page-spinner";
6 import { hasExactRole, roleInRange } from "@/lib/roles";8 import { hasExactRole, roleInRange } from "@/lib/roles";
7 import { useAuth } from "@/stores/auth-context";9 import { useAuth } from "@/stores/auth-context";
@@ -27,6 +29,16 @@ export function RouteGuard(
27 29
28 return (30 return (
29 <Show when={!auth.loading()} fallback={<PageSpinner />}>31 <Show when={!auth.loading()} fallback={<PageSpinner />}>
32+ <Show when={!auth.error()} fallback={
33+ <Alert variant="destructive">
34+ <div class="space-y-3">
35+ <p>{formatApiError(auth.error())}</p>
36+ <Button variant="outline" size="sm" onClick={() => void auth.refresh()}>
37+ {t("common.tryAgain")}
38+ </Button>
39+ </div>
40+ </Alert>
41+ }>
30 <Show when={auth.user()} fallback={<Navigate to="/login" />}>42 <Show when={auth.user()} fallback={<Navigate to="/login" />}>
31 {(u) => (43 {(u) => (
32 <Show44 <Show
@@ -37,6 +49,7 @@ export function RouteGuard(
37 </Show>49 </Show>
38 )}50 )}
39 </Show>51 </Show>
52+ </Show>
40 </Show>53 </Show>
41 );54 );
42 }55 }
src/stores/auth-context.tsxmodified+35 -1
@@ -5,6 +5,7 @@ import {
5 createEffect,5 createEffect,
6 createResource,6 createResource,
7 createSignal,7 createSignal,
8+ onCleanup,
8 useContext,9 useContext,
9 } from "solid-js";10 } from "solid-js";
10 import { getMe } from "@/api/users";11 import { getMe } from "@/api/users";
@@ -16,21 +17,42 @@ import { usePreferences } from "@/stores/preferences-context";
16 type AuthContextValue = {17 type AuthContextValue = {
17 user: Accessor<User | null | undefined>;18 user: Accessor<User | null | undefined>;
18 loading: Accessor<boolean>;19 loading: Accessor<boolean>;
20+ /** Non-401 bootstrap failure. 401 is "logged out", not an error. */
21+ error: Accessor<unknown>;
19 refresh: () => Promise<User | null | undefined>;22 refresh: () => Promise<User | null | undefined>;
20 logout: () => Promise<void>;23 logout: () => Promise<void>;
21 };24 };
22 25
23 const AuthContext = createContext<AuthContextValue>();26 const AuthContext = createContext<AuthContextValue>();
24 27
28+/** Retry-After (seconds) for a transient 429/503, else null. */
29+function retryAfterFor(err: unknown): number | null {
30+ if (
31+ err instanceof ApiError &&
32+ (err.status === 429 || err.status === 503) &&
33+ err.retryAfter != null
34+ ) {
35+ return Math.min(Math.max(err.retryAfter, 0), 60);
36+ }
37+ return null;
38+}
39+
25 export function AuthProvider(props: ParentProps) {40 export function AuthProvider(props: ParentProps) {
26 const prefs = usePreferences();41 const prefs = usePreferences();
27 const [override, setOverride] = createSignal<User | null | undefined>(undefined);42 const [override, setOverride] = createSignal<User | null | undefined>(undefined);
43+ const [error, setError] = createSignal<unknown>(null);
44+ // The fetcher swallows every failure into `error` state and resolves
45+ // IMMEDIATELY: it must never stay `loading` (that suspends the whole shell
46+ // and blanks the page) nor re-throw during render. Transient 429/503 waits
47+ // happen off the resource, in the background timer below.
28 const [me, { refetch }] = createResource(async () => {48 const [me, { refetch }] = createResource(async () => {
49+ setError(null);
29 try {50 try {
30 return await getMe();51 return await getMe();
31 } catch (err) {52 } catch (err) {
32 if (err instanceof ApiError && err.status === 401) return null;53 if (err instanceof ApiError && err.status === 401) return null;
33- throw err;54+ setError(err);
55+ return null;
34 }56 }
35 });57 });
36 58
@@ -51,6 +73,17 @@ export function AuthProvider(props: ParentProps) {
51 return result as User | null | undefined;73 return result as User | null | undefined;
52 };74 };
53 75
76+ // Auto-heal a rate-limited bootstrap without blocking render: once `error`
77+ // holds a 429/503 with a Retry-After, schedule one background refresh. The
78+ // user is already looking at the error Alert while this waits; on success
79+ // the app paints. Re-running the effect (new attempt) clears the old timer.
80+ createEffect(() => {
81+ const wait = retryAfterFor(error());
82+ if (wait == null) return;
83+ const timer = setTimeout(() => void refresh(), wait * 1000);
84+ onCleanup(() => clearTimeout(timer));
85+ });
86+
54 const logout = async () => {87 const logout = async () => {
55 try {88 try {
56 await postLogout();89 await postLogout();
@@ -62,6 +95,7 @@ export function AuthProvider(props: ParentProps) {
62 const value: AuthContextValue = {95 const value: AuthContextValue = {
63 user,96 user,
64 loading: () => me.loading && override() === undefined,97 loading: () => me.loading && override() === undefined,
98+ error: () => (override() === undefined ? error() : null),
65 refresh,99 refresh,
66 logout,100 logout,
67 };101 };