Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/workflows/keepalive.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: Keep SupportOps available

on:
schedule:
- cron: "17 13 * * *"
workflow_dispatch:

permissions:
contents: read

jobs:
health-check:
runs-on: ubuntu-latest
timeout-minutes: 8
steps:
- name: Wake the API
run: |
curl --fail-with-body \
--retry 3 \
--retry-all-errors \
--retry-delay 10 \
--connect-timeout 15 \
--max-time 90 \
https://supportops-api.onrender.com/health

- name: Verify the database connection
run: |
curl --fail-with-body \
--retry 5 \
--retry-all-errors \
--retry-delay 20 \
--connect-timeout 15 \
--max-time 90 \
https://supportops-api.onrender.com/health/dependencies
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,9 @@ App runs at `http://localhost:5173`.
- **Frontend** — Vercel, SPA rewrites in `frontend/vercel.json`. Env: `VITE_API_BASE_URL`.
- **Backend** — Render web service from `render.yaml` at repo root. Python 3.11.9. Env: `SUPABASE_URL`, `SUPABASE_KEY`, `ANTHROPIC_API_KEY`, `ANTHROPIC_MODEL`. Health check: `/health`.

Free-tier dynos sleep after 15 min of inactivity. The frontend warms the backend on app load — see `frontend/src/api.js` (`warmupBackend`).
Free-tier dynos sleep after 15 min of inactivity. The frontend warms the backend on app load, and `.github/workflows/keepalive.yml` runs a daily dependency check to keep the free Supabase project active and catch outages early.

`GET /health` confirms the API process is running. `GET /health/dependencies` performs a real database query and returns `503` with a `Retry-After` header when Supabase is unavailable.

---

Expand Down
21 changes: 12 additions & 9 deletions backend/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
DATABASE_UNAVAILABLE_DETAIL = (
"SupportOps database is unavailable. Check SUPABASE_URL, SUPABASE_KEY, "
"and Supabase table setup in Render."
"SupportOps data service is temporarily unavailable. It may be starting up; retry in a moment."
)


Expand Down Expand Up @@ -57,13 +56,17 @@ def handle_response(response):

def request_supabase(method, table, params="", data=None):
query = f"?{params}" if params else ""
response = requests.request(
method,
f"{SUPABASE_URL}/rest/v1/{table}{query}",
headers=get_headers(),
json=data,
timeout=20,
)
try:
response = requests.request(
method,
f"{SUPABASE_URL}/rest/v1/{table}{query}",
headers=get_headers(),
json=data,
timeout=20,
)
except requests.RequestException as error:
raise DatabaseRequestError(DATABASE_UNAVAILABLE_DETAIL) from error

return handle_response(response)


Expand Down
7 changes: 6 additions & 1 deletion backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ def database_config_error(_request: Request, exc: DatabaseConfigError):

@app.exception_handler(DatabaseRequestError)
def database_request_error(_request: Request, exc: DatabaseRequestError):
return JSONResponse(status_code=503, content={"detail": str(exc)})
return JSONResponse(
status_code=503,
content={"detail": str(exc)},
headers={"Retry-After": "30"},
)


# --- Models ---
Expand Down Expand Up @@ -104,6 +108,7 @@ def dependency_health(response: Response):
reachable = True
except (DatabaseConfigError, DatabaseRequestError) as error:
response.status_code = 503
response.headers["Retry-After"] = "30"
detail = str(error)

return {
Expand Down
14 changes: 13 additions & 1 deletion backend/test_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,5 +76,17 @@ def test_supabase_http_error_raises_database_error(monkeypatch):
fake_response.raise_for_status.side_effect = requests.HTTPError("503")
monkeypatch.setattr(database.requests, "request", MagicMock(return_value=fake_response))

with pytest.raises(database.DatabaseRequestError, match="SupportOps database is unavailable"):
with pytest.raises(database.DatabaseRequestError, match="temporarily unavailable"):
database.db_get("tickets")


@pytest.mark.parametrize(
"error", [requests.Timeout("timed out"), requests.ConnectionError("offline")]
)
def test_supabase_network_error_raises_database_error(monkeypatch, error):
monkeypatch.setattr(database, "SUPABASE_URL", "https://example.supabase.co")
monkeypatch.setattr(database, "SUPABASE_KEY", "secret")
monkeypatch.setattr(database.requests, "request", MagicMock(side_effect=error))

with pytest.raises(database.DatabaseRequestError, match="temporarily unavailable"):
database.db_get("tickets")
18 changes: 18 additions & 0 deletions backend/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,10 +196,28 @@ def test_dependency_health_returns_503_when_supabase_query_fails(client, monkeyp
res = test_client.get("/health/dependencies")

assert res.status_code == 503
assert res.headers["retry-after"] == "30"
assert res.json()["status"] == "error"
assert res.json()["supabase"]["reachable"] is False


def test_data_route_returns_503_when_supabase_times_out(client, monkeypatch):
test_client, main = client
monkeypatch.setattr(
main,
"db_get",
lambda table, params="": (_ for _ in ()).throw(
main.DatabaseRequestError("SupportOps data service is temporarily unavailable.")
),
)

res = test_client.get("/customers")

assert res.status_code == 503
assert res.headers["retry-after"] == "30"
assert res.json()["detail"] == "SupportOps data service is temporarily unavailable."


def test_get_ticket_not_found_returns_404(client, monkeypatch):
test_client, main = client
monkeypatch.setattr(main, "db_get", lambda table, params="": [])
Expand Down
37 changes: 21 additions & 16 deletions frontend/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,36 +6,41 @@ import Tickets from "./pages/Tickets";
import RMAs from "./pages/RMAs";

export default function App() {
const navigation = [
{ to: "/", label: "Dashboard" },
{ to: "/tickets", label: "Tickets" },
{ to: "/customers", label: "Customers" },
{ to: "/devices", label: "Devices" },
{ to: "/rmas", label: "RMAs" },
];

return (
<BrowserRouter>
<div className="min-h-screen bg-gray-100 flex">
{/* Sidebar */}
<aside className="w-56 bg-gray-900 text-white flex flex-col p-4 gap-2">
<h1 className="text-xl font-bold mb-6">SupportOps</h1>
{[
{ to: "/", label: "Dashboard" },
{ to: "/tickets", label: "Tickets" },
{ to: "/customers", label: "Customers" },
{ to: "/devices", label: "Devices" },
{ to: "/rmas", label: "RMAs" },
].map(({ to, label }) => (
<div className="min-h-screen bg-gray-100 lg:flex">
<aside className="bg-gray-950 text-white p-4 lg:w-60 lg:min-h-screen lg:p-5">
<div className="mb-4 flex items-center justify-between lg:mb-8">
<h1 className="text-xl font-bold">SupportOps</h1>
<span className="text-xs text-gray-400 lg:hidden">Service console</span>
</div>
<nav aria-label="Primary" className="grid grid-cols-3 gap-2 sm:grid-cols-5 lg:flex lg:flex-col">
{navigation.map(({ to, label }) => (
<NavLink
key={to}
to={to}
end={to === "/"}
className={({ isActive }) =>
`px-3 py-2 rounded text-sm font-medium transition ${
isActive ? "bg-blue-600" : "hover:bg-gray-700"
`min-w-0 px-2 py-2 text-center text-sm font-medium transition lg:px-3 lg:text-left ${
isActive ? "bg-blue-600 text-white" : "text-gray-300 hover:bg-gray-800 hover:text-white"
}`
}
>
{label}
</NavLink>
))}
))}
</nav>
</aside>

{/* Main content */}
<main className="flex-1 p-8">
<main className="min-w-0 flex-1 p-4 sm:p-6 lg:p-8">
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/tickets" element={<Tickets />} />
Expand Down
64 changes: 51 additions & 13 deletions frontend/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,40 @@ if (!BASE) {
// 90s — long enough for a Render free-tier cold start.
const DEFAULT_TIMEOUT_MS = 90_000;

export class ApiError extends Error {
constructor(message, status = 0) {
super(message);
this.name = "ApiError";
this.status = status;
}
}

async function responseDetail(response) {
const contentType = response.headers.get("content-type") || "";

if (contentType.includes("application/json")) {
const payload = await response.json().catch(() => null);
if (typeof payload?.detail === "string") return payload.detail;
}

return response.text().catch(() => "");
}

function apiErrorMessage(status, detail) {
if (status === 503) {
return "SupportOps is temporarily unavailable while its data service recovers. Wait a moment, then try again.";
}
if (status >= 500) {
return "SupportOps hit a server error. Try again in a moment.";
}
return detail || `Request failed with status ${status}.`;
}

async function request(path, { method = "GET", body, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
if (!BASE) {
throw new ApiError("SupportOps is missing its API configuration.");
}

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);

Expand All @@ -22,18 +55,21 @@ async function request(path, { method = "GET", body, timeoutMs = DEFAULT_TIMEOUT
});

if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`${res.status} ${res.statusText}${text ? ` — ${text.slice(0, 200)}` : ""}`);
const detail = await responseDetail(res);
throw new ApiError(apiErrorMessage(res.status, detail), res.status);
}

if (res.status === 204) return null;
return await res.json();
} catch (err) {
if (err.name === "AbortError") {
throw new Error(
"Request timed out. The demo backend runs on Render's free tier and may take up to a minute to wake from sleep — please retry."
throw new ApiError(
"SupportOps took too long to respond. The service may be waking up; please try again."
);
}
if (err instanceof TypeError) {
throw new ApiError("SupportOps could not reach its API. Check your connection and try again.");
}
throw err;
} finally {
clearTimeout(timer);
Expand Down Expand Up @@ -61,17 +97,19 @@ export function useApiResource(path) {
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);

const load = useCallback(() => {
const load = useCallback(async () => {
setLoading(true);
setError(null);
api
.get(path)
.then((d) => {
setData(d);
setError(null);
})
.catch((e) => setError(e.message || String(e)))
.finally(() => setLoading(false));

try {
const result = await api.get(path);
setData(result);
setError(null);
} catch (error) {
setError(error.message || String(error));
} finally {
setLoading(false);
}
}, [path]);

useEffect(() => {
Expand Down
28 changes: 20 additions & 8 deletions frontend/src/components/AsyncState.jsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,41 @@
export function LoadingState({ message }) {
return (
<div className="flex flex-col items-center justify-center py-16 text-gray-600">
<div className="w-10 h-10 border-4 border-gray-300 border-t-blue-600 rounded-full animate-spin mb-4" />
<div role="status" className="flex flex-col items-center justify-center py-16 text-gray-600">
<div
aria-hidden="true"
className="w-10 h-10 border-4 border-gray-300 border-t-blue-600 rounded-full animate-spin mb-4"
/>
<p className="text-sm font-medium">{message || "Loading…"}</p>
<p className="text-xs text-gray-500 mt-2 max-w-md text-center">
The demo backend runs on Render's free tier and sleeps after 15 min of inactivity.
First load after a nap can take up to a minute while the server wakes up.
The service may need a moment to wake up after a period of inactivity.
</p>
</div>
);
}

export function ErrorState({ error, onRetry }) {
return (
<div className="rounded-lg border border-red-300 bg-red-50 p-6 max-w-2xl">
<p className="text-red-800 font-semibold mb-1">Couldn't load data</p>
<p className="text-red-700 text-sm mb-4 break-words">{error}</p>
<div role="alert" className="rounded-lg border border-red-300 bg-red-50 p-5 max-w-2xl">
<p className="text-red-900 font-semibold mb-1">SupportOps could not load this view</p>
<p className="text-red-800 text-sm mb-4 break-words">{error}</p>
{onRetry && (
<button
onClick={onRetry}
className="px-4 py-2 bg-red-600 text-white text-sm font-medium rounded hover:bg-red-700 transition"
>
Retry
Try again
</button>
)}
</div>
);
}

export function InlineError({ error }) {
if (!error) return null;

return (
<p role="alert" className="mb-4 rounded border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800">
{error}
</p>
);
}
Loading