fix(api): time out and retry when the API server drops connections

About a third of new connections to api.rezina.yaltopia.com never complete (the TCP
connect hangs; requests that do connect answer in ~0.5s). With no timeout, sign-in sat
on a busy button forever.

- every API call gives up after 12s
- calls that are safe to repeat retry twice: reads, the account lookup, password login;
  sending or verifying a code never retries, so nobody gets two texts or burns a code
- the catalog keeps at most 3 requests in flight instead of firing one per course at once
- sign-in shows "Couldn't reach the server. Check your connection and try again."
  (auth.networkError, om/ti drafts) instead of hanging
This commit is contained in:
n3p-tun3 2026-11-02 19:29:37 +03:00
parent 8ba936baae
commit d92180542b
6 changed files with 43 additions and 11 deletions

View File

@ -118,12 +118,24 @@ export class ApiError extends Error {
constructor(status: number, message: string) { constructor(status: number, message: string) {
super(message); super(message);
this.status = status; this.status = status;
this.code = status === 401 ? 'unauthenticated' : status === 403 ? 'not_granted' : 'api_error'; this.code = status === 0 ? 'network' : status === 401 ? 'unauthenticated' : status === 403 ? 'not_granted' : 'api_error';
} }
} }
const notConnected = (what: string) => Object.assign(new Error(`${what} isn't connected to the API yet.`), { code: 'not_granted' }); const notConnected = (what: string) => Object.assign(new Error(`${what} isn't connected to the API yet.`), { code: 'not_granted' });
const TOKENS_KEY = 'lms.api.tokens'; const TOKENS_KEY = 'lms.api.tokens';
const REQUEST_TIMEOUT_MS = 12000;
const REQUEST_RETRIES = 2;
const PARALLEL = 3; // the catalog fans out one call per course/chapter; a smaller burst is gentler on the server
/** Like Promise.all over `items`, with at most `limit` calls in flight. */
async function mapLimit<T, R>(items: T[], limit: number, fn: (x: T) => Promise<R>): Promise<R[]> {
const out: R[] = new Array(items.length); let next = 0;
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
while (next < items.length) { const i = next++; out[i] = await fn(items[i]); }
}));
return out;
}
const readTokens = (): Tokens | null => { try { return JSON.parse(localStorage.getItem(TOKENS_KEY) ?? 'null'); } catch { return null; } }; const readTokens = (): Tokens | null => { try { return JSON.parse(localStorage.getItem(TOKENS_KEY) ?? 'null'); } catch { return null; } };
const writeTokens = (t: Tokens | null) => { try { t ? localStorage.setItem(TOKENS_KEY, JSON.stringify(t)) : localStorage.removeItem(TOKENS_KEY); } catch { /* storage blocked: session-only */ } }; const writeTokens = (t: Tokens | null) => { try { t ? localStorage.setItem(TOKENS_KEY, JSON.stringify(t)) : localStorage.removeItem(TOKENS_KEY); } catch { /* storage blocked: session-only */ } };
@ -146,11 +158,24 @@ export class ApiDataSource implements DataSource {
// ---- transport // ---- transport
private async request<T>(method: string, path: string, body?: unknown, auth = true): Promise<T> { /**
const send = () => fetch(`${this.base.replace(/\/+$/, '')}/api/v1${path}`, { * One API call. Every attempt gives up after REQUEST_TIMEOUT_MS: the server has been seen dropping new connections
* (they hang instead of failing), and a hung sign-in looks like a broken button. Calls that are safe to repeat
* (reads, the account lookup, password login) retry; ones with side effects (sending a code, verifying it) never do,
* so a learner can't get two texts or burn a code.
*/
private async request<T>(method: string, path: string, body?: unknown, auth = true, retry = method === 'GET'): Promise<T> {
const attempt = () => fetch(`${this.base.replace(/\/+$/, '')}/api/v1${path}`, {
method, headers: { 'content-type': 'application/json', ...(auth && this.tokens ? { authorization: `Bearer ${this.tokens.access}` } : {}) }, method, headers: { 'content-type': 'application/json', ...(auth && this.tokens ? { authorization: `Bearer ${this.tokens.access}` } : {}) },
body: body === undefined ? undefined : JSON.stringify(body), body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
}); });
const send = async () => {
for (let i = 0; ; i++) {
try { return await attempt(); }
catch { if (!retry || i >= REQUEST_RETRIES) throw new ApiError(0, "Couldn't reach the server."); }
}
};
let res = await send(); let res = await send();
if (res.status === 401 && auth && this.tokens && (await this.refresh())) res = await send(); if (res.status === 401 && auth && this.tokens && (await this.refresh())) res = await send();
const json = await res.json().catch(() => null); const json = await res.json().catch(() => null);
@ -164,6 +189,7 @@ export class ApiDataSource implements DataSource {
this.refreshing ??= fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, { this.refreshing ??= fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, {
method: 'POST', headers: { 'content-type': 'application/json' }, method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ access_token: this.tokens.access, refresh_token: this.tokens.refresh }), body: JSON.stringify({ access_token: this.tokens.access, refresh_token: this.tokens.refresh }),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
}).then(async (r) => { }).then(async (r) => {
const j = await r.json().catch(() => null); const j = await r.json().catch(() => null);
if (!r.ok || !j?.data?.access_token) { this.setTokens(null); return false; } if (!r.ok || !j?.data?.access_token) { this.setTokens(null); return false; }
@ -187,7 +213,7 @@ export class ApiDataSource implements DataSource {
/** 'code' when the learner must enter a one-time code next; 'done' when they're signed in already. */ /** 'code' when the learner must enter a one-time code next; 'done' when they're signed in already. */
start: async (c: Contact): Promise<'code' | 'done'> => { start: async (c: Contact): Promise<'code' | 'done'> => {
const who = c.phone ? { phone_number: c.phone } : { email: c.email }; const who = c.phone ? { phone_number: c.phone } : { email: c.email };
const exists = await this.request<{ email_exist: boolean; phone_number_exist: boolean }>('POST', '/user/checkPhoneEmailExist', who, false); const exists = await this.request<{ email_exist: boolean; phone_number_exist: boolean }>('POST', '/user/checkPhoneEmailExist', who, false, true);
const known = c.phone ? exists.phone_number_exist : exists.email_exist; const known = c.phone ? exists.phone_number_exist : exists.email_exist;
if (c.email && known) { await this.login({ email: c.email, password: c.password }); return 'done'; } if (c.email && known) { await this.login({ email: c.email, password: c.password }); return 'done'; }
if (c.phone && known) { await this.request('POST', '/user/resend-otp', who, false); return 'code'; } if (c.phone && known) { await this.request('POST', '/user/resend-otp', who, false); return 'code'; }
@ -197,7 +223,7 @@ export class ApiDataSource implements DataSource {
}, },
verify: async (c: Contact, code: string): Promise<void> => { verify: async (c: Contact, code: string): Promise<void> => {
const who = c.phone ? { phone_number: c.phone } : { email: c.email }; const who = c.phone ? { phone_number: c.phone } : { email: c.email };
const exists = await this.request<{ email_exist: boolean; phone_number_exist: boolean }>('POST', '/user/checkPhoneEmailExist', who, false); const exists = await this.request<{ email_exist: boolean; phone_number_exist: boolean }>('POST', '/user/checkPhoneEmailExist', who, false, true);
if (c.phone && exists.phone_number_exist) { await this.login({ phone_number: c.phone, otp_code: code }); return; } if (c.phone && exists.phone_number_exist) { await this.login({ phone_number: c.phone, otp_code: code }); return; }
const t = await this.request<{ access_token: string; refresh_token: string; user_id: number }>('POST', '/user/verify-otp', { ...who, otp: code }, false); const t = await this.request<{ access_token: string; refresh_token: string; user_id: number }>('POST', '/user/verify-otp', { ...who, otp: code }, false);
this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id }); this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id });
@ -213,7 +239,7 @@ export class ApiDataSource implements DataSource {
}; };
private async login(body: Record<string, unknown>) { private async login(body: Record<string, unknown>) {
const t = await this.request<{ access_token: string; refresh_token: string; user_id: number }>('POST', '/auth/customer-login', body, false); const t = await this.request<{ access_token: string; refresh_token: string; user_id: number }>('POST', '/auth/customer-login', body, false, !body.otp_code); // a code is single-use: no retry
this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id }); this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id });
this.refreshAll(); this.refreshAll();
} }
@ -232,16 +258,16 @@ export class ApiDataSource implements DataSource {
private async loadCourses(): Promise<Course[]> { private async loadCourses(): Promise<Course[]> {
const page = await this.request<{ courses: RawCourse[]; total_count: number }>('GET', '/catalog/courses?limit=100', undefined, false); const page = await this.request<{ courses: RawCourse[]; total_count: number }>('GET', '/catalog/courses?limit=100', undefined, false);
const outlines = await Promise.all(page.courses.map((c) => this.request<RawOutline>('GET', `/catalog/courses/${c.id}`, undefined, false).catch(() => null))); const outlines = await mapLimit(page.courses, PARALLEL, (c) => this.request<RawOutline>('GET', `/catalog/courses/${c.id}`, undefined, false).catch(() => null));
const courses = outlines.filter((o): o is RawOutline => !!o).map((o) => mapOutline(o, this.base)); const courses = outlines.filter((o): o is RawOutline => !!o).map((o) => mapOutline(o, this.base));
if (this.tokens) await Promise.all(courses.flatMap((c) => c.chapters.map(async (ch) => { if (this.tokens) await mapLimit(courses.flatMap((c) => c.chapters), PARALLEL, async (ch) => {
// Signed in: lesson video URLs (and sort order) only come from the authenticated lesson list. // Signed in: lesson video URLs (and sort order) only come from the authenticated lesson list.
const r = await this.request<{ lessons: RawLesson[] }>('GET', `/chapters/${ids.num(ch.id)}/lessons?limit=200`).catch(() => null); const r = await this.request<{ lessons: RawLesson[] }>('GET', `/chapters/${ids.num(ch.id)}/lessons?limit=200`).catch(() => null);
for (const l of r?.lessons ?? []) { for (const l of r?.lessons ?? []) {
const m = ch.lessons.find((x) => x.id === ids.lesson(l.id)); const m = ch.lessons.find((x) => x.id === ids.lesson(l.id));
if (m) { m.videoAssetId = l.video_url || m.videoAssetId; if (l.sort_order != null) m.sortOrder = l.sort_order; } if (m) { m.videoAssetId = l.video_url || m.videoAssetId; if (l.sort_order != null) m.sortOrder = l.sort_order; }
} }
}))); });
return courses; return courses;
} }

View File

@ -1418,6 +1418,8 @@ function SignIn() {
setCode(String(Math.floor(100000 + Math.random() * 900000))); setTries(5); setEntered(''); setWait(60); setStep('code'); setCode(String(Math.floor(100000 + Math.random() * 900000))); setTries(5); setEntered(''); setWait(60); setStep('code');
}; };
const contact = () => (mode === 'phone' ? { phone: e164 } : { email, password: pw }); const contact = () => (mode === 'phone' ? { phone: e164 } : { email, password: pw });
// The server's own message when it gave one; a plain "couldn't reach the server" when it never answered.
const apiErr = (e: unknown) => ((e as { code?: string })?.code === 'network' ? t('auth.networkError') : (e as Error)?.message || t('auth.networkError'));
// After a real sign-in: a learner without a name yet goes to profile setup, everyone else home. // After a real sign-in: a learner without a name yet goes to profile setup, everyone else home.
const finish = async () => { const finish = async () => {
await reloadViewer(); signIn(); await reloadViewer(); signIn();
@ -1429,7 +1431,7 @@ function SignIn() {
try { try {
const next = await auth!.start(contact()); const next = await auth!.start(contact());
if (next === 'done') await finish(); else { setEntered(''); setWait(60); setStep('code'); } if (next === 'done') await finish(); else { setEntered(''); setWait(60); setStep('code'); }
} catch (e) { setErr((e as Error).message || t('common.saveFailed')); } } catch (e) { setErr(apiErr(e)); }
setBusy(false); setBusy(false);
}; };
const verify = async (e: React.FormEvent) => { const verify = async (e: React.FormEvent) => {
@ -1437,7 +1439,7 @@ function SignIn() {
if (auth) { if (auth) {
setBusy(true); setBusy(true);
try { await auth.verify(contact(), entered); await finish(); } try { await auth.verify(contact(), entered); await finish(); }
catch (x) { setErr((x as Error).message || t('auth.wrongCode', { n: '' })); } catch (x) { setErr(apiErr(x)); }
setBusy(false); setBusy(false);
return; return;
} }

View File

@ -86,6 +86,7 @@
"resend": "አዲስ ኮድ ላክ", "resend": "አዲስ ኮድ ላክ",
"resendIn": "በ{s} ሰከንድ ውስጥ አዲስ ኮድ መላክ ይችላሉ", "resendIn": "በ{s} ሰከንድ ውስጥ አዲስ ኮድ መላክ ይችላሉ",
"wrongCode": "ኮዱ ትክክል አይደለም። {n} ሙከራ ቀርቷል።", "wrongCode": "ኮዱ ትክክል አይደለም። {n} ሙከራ ቀርቷል።",
"networkError": "ከአገልጋዩ ጋር መገናኘት አልተቻለም። ግንኙነትዎን ያረጋግጡና እንደገና ይሞክሩ።",
"locked": "ብዙ የተሳሳቱ ሙከራዎች። አዲስ ኮድ ይላኩ።", "locked": "ብዙ የተሳሳቱ ሙከራዎች። አዲስ ኮድ ይላኩ።",
"noIdentity": "የተማሪ መለያ ለመፍጠር ወደ Claude ገብተው ይህን ማሳያ ይክፈቱ።", "noIdentity": "የተማሪ መለያ ለመፍጠር ወደ Claude ገብተው ይህን ማሳያ ይክፈቱ።",
"welcome": "እንኳን ደህና መጡ", "welcome": "እንኳን ደህና መጡ",

View File

@ -86,6 +86,7 @@
"resend": "Send a new code", "resend": "Send a new code",
"resendIn": "Send a new code in {s} s", "resendIn": "Send a new code in {s} s",
"wrongCode": "That code is wrong. {n, plural, one {# try} other {# tries}} left.", "wrongCode": "That code is wrong. {n, plural, one {# try} other {# tries}} left.",
"networkError": "Couldn't reach the server. Check your connection and try again.",
"locked": "Too many wrong tries. Send a new code.", "locked": "Too many wrong tries. Send a new code.",
"noIdentity": "Open this demo while signed in to Claude to create a student account.", "noIdentity": "Open this demo while signed in to Claude to create a student account.",
"welcome": "Welcome back", "welcome": "Welcome back",

View File

@ -86,6 +86,7 @@
"resend": "Koodii haaraa ergi", "resend": "Koodii haaraa ergi",
"resendIn": "Sekondii {s} booda koodii haaraa erguu dandeessa", "resendIn": "Sekondii {s} booda koodii haaraa erguu dandeessa",
"wrongCode": "Koodiin sun dogoggora. Yaaliin {n} hafeera.", "wrongCode": "Koodiin sun dogoggora. Yaaliin {n} hafeera.",
"networkError": "Sarvarii qaqqabuu hin dandeenye. Walqunnamtii kee mirkaneessiitii irra deebi'ii yaali.",
"locked": "Yaaliin dogoggoraa baay'ateera. Koodii haaraa ergi.", "locked": "Yaaliin dogoggoraa baay'ateera. Koodii haaraa ergi.",
"noIdentity": "Herrega barataa uumuuf Claude'tti seenii agarsiisa kana bani.", "noIdentity": "Herrega barataa uumuuf Claude'tti seenii agarsiisa kana bani.",
"welcome": "Welcome back", "welcome": "Welcome back",

View File

@ -86,6 +86,7 @@
"resend": "ሓድሽ ኮድ ስደድ", "resend": "ሓድሽ ኮድ ስደድ",
"resendIn": "ድሕሪ {s} ካልኢት ሓድሽ ኮድ ክትሰድድ ትኽእል", "resendIn": "ድሕሪ {s} ካልኢት ሓድሽ ኮድ ክትሰድድ ትኽእል",
"wrongCode": "እቲ ኮድ ጌጋ እዩ። {n} ፈተነ ተሪፉ።", "wrongCode": "እቲ ኮድ ጌጋ እዩ። {n} ፈተነ ተሪፉ።",
"networkError": "ምስ ሰርቨር ክራኸብ ኣይተኻእለን። ርክብካ ኣረጋግጽን እንደገና ፈትንን።",
"locked": "ብዙሕ ጌጋ ፈተነታት። ሓድሽ ኮድ ስደድ።", "locked": "ብዙሕ ጌጋ ፈተነታት። ሓድሽ ኮድ ስደድ።",
"noIdentity": "ናይ ተማሃራይ ሕሳብ ንምፍጣር ናብ Claude ኣቲኻ እዚ መርኣያ ክፈቶ።", "noIdentity": "ናይ ተማሃራይ ሕሳብ ንምፍጣር ናብ Claude ኣቲኻ እዚ መርኣያ ክፈቶ።",
"welcome": "Welcome back", "welcome": "Welcome back",