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:
parent
8ba936baae
commit
d92180542b
|
|
@ -118,12 +118,24 @@ export class ApiError extends Error {
|
|||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
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 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 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
|
||||
|
||||
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}` } : {}) },
|
||||
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();
|
||||
if (res.status === 401 && auth && this.tokens && (await this.refresh())) res = await send();
|
||||
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`, {
|
||||
method: 'POST', headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ access_token: this.tokens.access, refresh_token: this.tokens.refresh }),
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
}).then(async (r) => {
|
||||
const j = await r.json().catch(() => null);
|
||||
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. */
|
||||
start: async (c: Contact): Promise<'code' | 'done'> => {
|
||||
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;
|
||||
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'; }
|
||||
|
|
@ -197,7 +223,7 @@ export class ApiDataSource implements DataSource {
|
|||
},
|
||||
verify: async (c: Contact, code: string): Promise<void> => {
|
||||
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; }
|
||||
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 });
|
||||
|
|
@ -213,7 +239,7 @@ export class ApiDataSource implements DataSource {
|
|||
};
|
||||
|
||||
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.refreshAll();
|
||||
}
|
||||
|
|
@ -232,16 +258,16 @@ export class ApiDataSource implements DataSource {
|
|||
|
||||
private async loadCourses(): Promise<Course[]> {
|
||||
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));
|
||||
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.
|
||||
const r = await this.request<{ lessons: RawLesson[] }>('GET', `/chapters/${ids.num(ch.id)}/lessons?limit=200`).catch(() => null);
|
||||
for (const l of r?.lessons ?? []) {
|
||||
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; }
|
||||
}
|
||||
})));
|
||||
});
|
||||
return courses;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1418,6 +1418,8 @@ function SignIn() {
|
|||
setCode(String(Math.floor(100000 + Math.random() * 900000))); setTries(5); setEntered(''); setWait(60); setStep('code');
|
||||
};
|
||||
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.
|
||||
const finish = async () => {
|
||||
await reloadViewer(); signIn();
|
||||
|
|
@ -1429,7 +1431,7 @@ function SignIn() {
|
|||
try {
|
||||
const next = await auth!.start(contact());
|
||||
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);
|
||||
};
|
||||
const verify = async (e: React.FormEvent) => {
|
||||
|
|
@ -1437,7 +1439,7 @@ function SignIn() {
|
|||
if (auth) {
|
||||
setBusy(true);
|
||||
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);
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -86,6 +86,7 @@
|
|||
"resend": "አዲስ ኮድ ላክ",
|
||||
"resendIn": "በ{s} ሰከንድ ውስጥ አዲስ ኮድ መላክ ይችላሉ",
|
||||
"wrongCode": "ኮዱ ትክክል አይደለም። {n} ሙከራ ቀርቷል።",
|
||||
"networkError": "ከአገልጋዩ ጋር መገናኘት አልተቻለም። ግንኙነትዎን ያረጋግጡና እንደገና ይሞክሩ።",
|
||||
"locked": "ብዙ የተሳሳቱ ሙከራዎች። አዲስ ኮድ ይላኩ።",
|
||||
"noIdentity": "የተማሪ መለያ ለመፍጠር ወደ Claude ገብተው ይህን ማሳያ ይክፈቱ።",
|
||||
"welcome": "እንኳን ደህና መጡ",
|
||||
|
|
|
|||
|
|
@ -86,6 +86,7 @@
|
|||
"resend": "Send a new code",
|
||||
"resendIn": "Send a new code in {s} s",
|
||||
"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.",
|
||||
"noIdentity": "Open this demo while signed in to Claude to create a student account.",
|
||||
"welcome": "Welcome back",
|
||||
|
|
|
|||
|
|
@ -86,6 +86,7 @@
|
|||
"resend": "Koodii haaraa ergi",
|
||||
"resendIn": "Sekondii {s} booda koodii haaraa erguu dandeessa",
|
||||
"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.",
|
||||
"noIdentity": "Herrega barataa uumuuf Claude'tti seenii agarsiisa kana bani.",
|
||||
"welcome": "Welcome back",
|
||||
|
|
|
|||
|
|
@ -86,6 +86,7 @@
|
|||
"resend": "ሓድሽ ኮድ ስደድ",
|
||||
"resendIn": "ድሕሪ {s} ካልኢት ሓድሽ ኮድ ክትሰድድ ትኽእል",
|
||||
"wrongCode": "እቲ ኮድ ጌጋ እዩ። {n} ፈተነ ተሪፉ።",
|
||||
"networkError": "ምስ ሰርቨር ክራኸብ ኣይተኻእለን። ርክብካ ኣረጋግጽን እንደገና ፈትንን።",
|
||||
"locked": "ብዙሕ ጌጋ ፈተነታት። ሓድሽ ኮድ ስደድ።",
|
||||
"noIdentity": "ናይ ተማሃራይ ሕሳብ ንምፍጣር ናብ Claude ኣቲኻ እዚ መርኣያ ክፈቶ።",
|
||||
"welcome": "Welcome back",
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user