From 120b7f0f97c9c6a7bd7a141db9a5494cdf636217 Mon Sep 17 00:00:00 2001 From: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:16:21 +0000 Subject: [PATCH] fix(visitors): hide footer stats when Upstash isn't configured Without UPSTASH_REDIS_REST_URL/TOKEN the API 500'd and the footer showed a broken Stats block on every page. The route now answers 204 for GET and POST when either secret is missing, and the footer hides the Stats block on any non-200 response, remembering it across client-side navigations. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- src/components/Footer.astro | 26 +++++++- src/lib/upstash.ts | 6 ++ src/pages/api/visitors.ts | 4 +- tests/api/visitors.test.ts | 129 ++++++++++++++++++++++++++++++++++++ 4 files changed, 161 insertions(+), 4 deletions(-) create mode 100644 tests/api/visitors.test.ts diff --git a/src/components/Footer.astro b/src/components/Footer.astro index bb221a0..2a10f98 100644 --- a/src/components/Footer.astro +++ b/src/components/Footer.astro @@ -187,6 +187,8 @@ const year = new Date().getFullYear(); (function() { // The router swaps the footer on every navigation and runs this script only // once. The numbers are fetched once, and every new footer is filled in from them. + // Counts once fetched, or false when the API has no counter to show + // (204 on self-hosted copies without Upstash, or any other error). var latest = null; var loading = false; @@ -197,9 +199,19 @@ const year = new Date().getFullYear(); if (total) total.textContent = (data.total || 0).toLocaleString(); } + // Hide the Stats title and counters in whichever footer is on the page, + // keeping the MIT License and copyright line below them. + function hideStats() { + var title = document.querySelector('.footer-stats-col .footer-col-title'); + var stats = document.querySelector('.footer-stats-col .footer-stats'); + if (title) title.style.display = 'none'; + if (stats) stats.style.display = 'none'; + } + function loadVisitors() { - if (latest) { - updateDOM(latest); + if (latest !== null) { + if (latest === false) hideStats(); + else updateDOM(latest); return; } // A fetch is already on its way and will fill in whichever footer is on the page @@ -212,8 +224,16 @@ const year = new Date().getFullYear(); ? fetch('/api/visitors') : fetch('/api/visitors', { method: 'POST', headers: { 'Content-Type': 'application/json' } }); request - .then(function(r) { return r.json(); }) + .then(function(r) { + if (r.status !== 200) return null; + return r.json(); + }) .then(function(data) { + if (data === null) { + latest = false; + hideStats(); + return; + } if (!counted) sessionStorage.setItem('ogcops-counted', '1'); latest = data; updateDOM(data); diff --git a/src/lib/upstash.ts b/src/lib/upstash.ts index 2bdb4ef..64dd78b 100644 --- a/src/lib/upstash.ts +++ b/src/lib/upstash.ts @@ -9,6 +9,12 @@ function upstash(): { url: string; token: string } { return { url, token }; } +// Same per-call read as upstash(): routes check this to skip the counter +// entirely on self-hosted copies that never set the secrets. +export function hasUpstashCredentials(): boolean { + return Boolean(getSecret('UPSTASH_REDIS_REST_URL') && getSecret('UPSTASH_REDIS_REST_TOKEN')); +} + async function redis(command: string[]): Promise { const { url, token } = upstash(); const res = await fetch(url, { diff --git a/src/pages/api/visitors.ts b/src/pages/api/visitors.ts index b547c07..b18e85e 100644 --- a/src/pages/api/visitors.ts +++ b/src/pages/api/visitors.ts @@ -1,5 +1,5 @@ import type { APIRoute } from 'astro'; -import { incrementVisitors, getVisitors } from '../../lib/upstash'; +import { incrementVisitors, getVisitors, hasUpstashCredentials } from '../../lib/upstash'; const SITE = 'ogcops'; const HEADERS = { @@ -8,6 +8,7 @@ const HEADERS = { }; export const POST: APIRoute = async () => { + if (!hasUpstashCredentials()) return new Response(null, { status: 204 }); try { const counts = await incrementVisitors(SITE); return new Response(JSON.stringify(counts), { headers: HEADERS }); @@ -17,6 +18,7 @@ export const POST: APIRoute = async () => { }; export const GET: APIRoute = async () => { + if (!hasUpstashCredentials()) return new Response(null, { status: 204 }); try { const counts = await getVisitors(SITE); return new Response(JSON.stringify(counts), { headers: HEADERS }); diff --git a/tests/api/visitors.test.ts b/tests/api/visitors.test.ts new file mode 100644 index 0000000..1a0a819 --- /dev/null +++ b/tests/api/visitors.test.ts @@ -0,0 +1,129 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +// astro:env/server is a Vite virtual module, so it is mocked the same way +// tests/middleware.test.ts mocks astro:middleware. +const mocks = vi.hoisted(() => ({ + getSecret: vi.fn<(key: string) => string | undefined>(), +})); + +vi.mock('astro:env/server', () => ({ + getSecret: mocks.getSecret, +})); + +const { GET, POST } = await import('@/pages/api/visitors'); + +const context = {} as Parameters>[0]; + +const URL_SECRET = 'UPSTASH_REDIS_REST_URL'; +const TOKEN_SECRET = 'UPSTASH_REDIS_REST_TOKEN'; + +function setSecrets(url: string | undefined, token: string | undefined) { + mocks.getSecret.mockImplementation((key: string) => { + if (key === URL_SECRET) return url; + if (key === TOKEN_SECRET) return token; + return undefined; + }); +} + +describe('/api/visitors without Upstash secrets', () => { + afterEach(() => { + vi.unstubAllGlobals(); + mocks.getSecret.mockReset(); + }); + + it.each([ + ['neither', undefined, undefined], + ['only the URL', 'https://example.upstash.io', undefined], + ['only the token', undefined, 'token'], + ])('GET answers 204 and calls no fetch when %s is set', async (_case, url, token) => { + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + setSecrets(url, token); + + const res = await GET(context); + + expect(res.status).toBe(204); + expect(await res.text()).toBe(''); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it.each([ + ['neither', undefined, undefined], + ['only the URL', 'https://example.upstash.io', undefined], + ['only the token', undefined, 'token'], + ])('POST answers 204 and calls no fetch when %s is set', async (_case, url, token) => { + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + setSecrets(url, token); + + const res = await POST(context); + + expect(res.status).toBe(204); + expect(await res.text()).toBe(''); + expect(fetchSpy).not.toHaveBeenCalled(); + }); +}); + +describe('/api/visitors with Upstash secrets set', () => { + afterEach(() => { + vi.unstubAllGlobals(); + mocks.getSecret.mockReset(); + }); + + it('GET returns the stored counts', async () => { + setSecrets('https://example.upstash.io', 'token'); + const fetchSpy = vi.fn().mockResolvedValue( + new Response(JSON.stringify([{ result: '7' }, { result: '123' }]), { status: 200 }) + ); + vi.stubGlobal('fetch', fetchSpy); + + const res = await GET(context); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ today: 7, total: 123 }); + expect(fetchSpy).toHaveBeenCalledWith( + 'https://example.upstash.io/pipeline', + expect.objectContaining({ method: 'POST' }) + ); + }); + + it('POST increments and returns the counts', async () => { + setSecrets('https://example.upstash.io', 'token'); + const fetchSpy = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ result: [7, 123] }), { status: 200 }) + ); + vi.stubGlobal('fetch', fetchSpy); + + const res = await POST(context); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ today: 7, total: 123 }); + expect(fetchSpy).toHaveBeenCalledWith( + 'https://example.upstash.io', + expect.objectContaining({ method: 'POST' }) + ); + }); + + it('POST stays a 500 when Upstash answers with an error', async () => { + setSecrets('https://example.upstash.io', 'token'); + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue(new Response('upstream error', { status: 500 })) + ); + + const res = await POST(context); + + expect(res.status).toBe(500); + expect(await res.json()).toEqual({ today: 0, total: 0 }); + }); + + it('GET stays a 500 when the Upstash request throws', async () => { + setSecrets('https://example.upstash.io', 'token'); + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down'))); + + const res = await GET(context); + + expect(res.status).toBe(500); + expect(await res.json()).toEqual({ today: 0, total: 0 }); + }); +});