diff --git a/frontend/.env.example b/frontend/.env.example index 8a338ea..2a70242 100644 --- a/frontend/.env.example +++ b/frontend/.env.example @@ -2,11 +2,12 @@ # Get your publishable key from https://dashboard.clerk.com EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_your_key_here -# Backend API URL -# For web/localhost: http://localhost:5000/api -# For Android Emulator: http://10.0.2.2:5000/api -# For Physical device (Expo Go): http://:5000/api -EXPO_PUBLIC_API_BASE_URL=http://localhost:5000/api +# Backend API URLs +# Primary: Vultr +EXPO_PUBLIC_API_PRIMARY=https://YOUR_VULTR_URL/api + +# Fallback: Render +EXPO_PUBLIC_API_FALLBACK=https://YOUR_RENDER_URL/api # Public web client used for shared journey links (not the landing website). EXPO_PUBLIC_WEB_APP_URL=https://path-finder-webapp.vercel.app diff --git a/frontend/api/api.ts b/frontend/api/api.ts index 4ce223a..c4c498c 100644 --- a/frontend/api/api.ts +++ b/frontend/api/api.ts @@ -1,62 +1,117 @@ -const API_BASE_URL = process.env.EXPO_PUBLIC_API_BASE_URL!; -const DEFAULT_TIMEOUT_MS = 60_000; // 60 seconds to allow for long LLM processing + import { fetch } from "expo/fetch"; -export async function apiFetch( +const PRIMARY_API_URL = process.env.EXPO_PUBLIC_API_PRIMARY!; +const FALLBACK_API_URL = process.env.EXPO_PUBLIC_API_FALLBACK; + +const DEFAULT_TIMEOUT_MS = 60_000; + +async function requestWithFallback( endpoint: string, options: RequestInit = {}, token?: string, isMultipart: boolean = false -): Promise { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS); - - try { - const headers: Record = { - ...(options.headers as Record ?? {}), - ...(token ? { Authorization: `Bearer ${token}` } : {}), - }; - - if (!isMultipart && !headers["Content-Type"]) { - headers["Content-Type"] = "application/json"; - } +): Promise { + if (!PRIMARY_API_URL) { + throw new Error("Primary API URL is not configured."); + } + + const urls = [ + PRIMARY_API_URL, + ...(FALLBACK_API_URL && FALLBACK_API_URL !== PRIMARY_API_URL + ? [FALLBACK_API_URL] + : []), + ]; + + const headers: Record = { + ...(options.headers as Record ?? {}), + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }; + + if (!isMultipart && !headers["Content-Type"]) { + headers["Content-Type"] = "application/json"; + } + + let lastError: unknown; + + for (let i = 0; i < urls.length; i++) { + const controller = new AbortController(); + const timeoutId = setTimeout( + () => controller.abort(), + DEFAULT_TIMEOUT_MS + ); + + try { + const baseUrl = urls[i].replace(/\/+$/, ""); - const response = await fetch( - `${API_BASE_URL}${endpoint}`, - { + const response = await fetch(`${baseUrl}${endpoint}`, { ...options, signal: controller.signal, headers, + }); + + // Retry on gateway/service availability errors. + if ([502, 503, 504].includes(response.status) && i < urls.length - 1) { + console.warn(`Backend unavailable at ${baseUrl}. Trying fallback...`); + continue; } - ); - if (!response.ok) { - let message = await response.text(); - // If the backend returns HTML (e.g. 404 Cannot GET), clean it up - if (message.includes("") || message.includes("")) { - if (response.status === 404) { - message = `Endpoint ${endpoint} not implemented on the backend yet.`; - } else { - message = `Server error ${response.status}: ${response.statusText}`; - } - } else { - try { - const jsonError = JSON.parse(message); - message = jsonError.error || jsonError.message || message; - } catch { - // keep as raw text + return response; + } catch (err: any) { + lastError = err; + + if (i === urls.length - 1) { + if (err.name === "AbortError") { + throw new Error("Request timed out. Both backend attempts failed."); } + throw err; } - throw new Error(message || `Request failed with status ${response.status}`); + + console.warn(`Backend request failed at ${urls[i]}. Trying fallback...`); + } finally { + clearTimeout(timeoutId); } + } + + throw lastError || new Error("All backend servers are unavailable."); +} + +export async function apiRequest( + endpoint: string, + options: RequestInit = {}, + token?: string, + isMultipart: boolean = false +): Promise { + return requestWithFallback(endpoint, options, token, isMultipart); +} + +export async function apiFetch( + endpoint: string, + options: RequestInit = {}, + token?: string, + isMultipart: boolean = false +): Promise { + const response = await apiRequest(endpoint, options, token, isMultipart); + + if (!response.ok) { + let message = await response.text(); - return response.json(); - } catch (err: any) { - if (err.name === "AbortError") { - throw new Error(`Request timed out after ${DEFAULT_TIMEOUT_MS / 1000} seconds. Please check if your backend server is running and accessible.`); + if (message.includes("") || message.includes("")) { + message = + response.status === 404 + ? `Endpoint ${endpoint} not implemented on the backend yet.` + : `Server error ${response.status}: ${response.statusText}`; + } else { + try { + const jsonError = JSON.parse(message); + message = jsonError.error || jsonError.message || message; + } catch { + // Keep the original error message. + } } - throw err; - } finally { - clearTimeout(timeoutId); + + throw new Error(message || `Request failed with status ${response.status}`); } + + return response.json(); } diff --git a/frontend/api/output.api.ts b/frontend/api/output.api.ts index 2257f53..a585b14 100644 --- a/frontend/api/output.api.ts +++ b/frontend/api/output.api.ts @@ -1,4 +1,5 @@ -import { apiFetch } from "./api"; + +import { apiFetch, apiRequest } from "./api"; export interface TranslateResponse { translatedAiInsights: { @@ -23,34 +24,36 @@ export async function translateInsights( ); } -const API_BASE_URL = process.env.EXPO_PUBLIC_API_BASE_URL || "http://localhost:5000/api"; - export async function generateSpeechUri( token: string | null, aiInsights: any, language: string ): Promise { - const response = await fetch(`${API_BASE_URL}/output/speech`, { - method: "POST", - headers: { - "Content-Type": "application/json", - ...(token ? { Authorization: `Bearer ${token}` } : {}), + const response = await apiRequest( + "/output/speech", + { + method: "POST", + body: JSON.stringify({ + aiInsights, + language, + speaker: "shubh", + }), }, - body: JSON.stringify({ aiInsights, language, speaker: "shubh" }), // Use valid speaker "shubh" - }); + token || undefined + ); if (!response.ok) { throw new Error("Failed to generate speech"); } - // We need to read the audio blob as base64 and return a data URI for expo-audio const blob = await response.blob(); + return new Promise((resolve, reject) => { const reader = new FileReader(); - reader.onload = () => { - resolve(reader.result as string); // reader.result is already a data URI string - }; + + reader.onload = () => resolve(reader.result as string); reader.onerror = reject; + reader.readAsDataURL(blob); }); } diff --git a/frontend/api/query.api.ts b/frontend/api/query.api.ts index 5b7fec1..030712d 100644 --- a/frontend/api/query.api.ts +++ b/frontend/api/query.api.ts @@ -1,4 +1,7 @@ -const API_BASE_URL = process.env.EXPO_PUBLIC_API_BASE_URL!; + +import { apiRequest } from "./api"; +import { File } from "expo-file-system"; +import { Platform } from "react-native"; export interface QueryResponse { query: string; @@ -8,17 +11,16 @@ export interface QueryResponse { aggregatedContext?: string; } -import { File } from "expo-file-system"; -import { Platform } from 'react-native'; - export async function submitQuery( token: string, searchText?: string | null, audioUri?: string | null ): Promise { let response: Response; + if (audioUri) { const formData = new FormData(); + if (Platform.OS === "web") { const res = await fetch(audioUri); const blob = await res.blob(); @@ -27,25 +29,29 @@ export async function submitQuery( const file = new File(audioUri); formData.append("audio", file); } - response = await fetch(`${API_BASE_URL}/query`, { - method: "POST", - headers: { - Authorization: `Bearer ${token}`, + + response = await apiRequest( + "/query", + { + method: "POST", + body: formData, }, - body: formData, - }); + token, + true + ); } else if (searchText) { - response = await fetch(`${API_BASE_URL}/query`, { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${token}`, + response = await apiRequest( + "/query", + { + method: "POST", + body: JSON.stringify({ query: searchText }), }, - body: JSON.stringify({ query: searchText }), - }); + token + ); } else { throw new Error("Must provide either text query or audio."); } + if (!response.ok) { const message = await response.text(); throw new Error(`API error: ${message}`);