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
26 changes: 23 additions & 3 deletions src/components/Footer.astro
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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
Expand All @@ -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);
Expand Down
6 changes: 6 additions & 0 deletions src/lib/upstash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<any> {
const { url, token } = upstash();
const res = await fetch(url, {
Expand Down
4 changes: 3 additions & 1 deletion src/pages/api/visitors.ts
Original file line number Diff line number Diff line change
@@ -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 = {
Expand All @@ -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 });
Expand All @@ -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 });
Expand Down
129 changes: 129 additions & 0 deletions tests/api/visitors.test.ts
Original file line number Diff line number Diff line change
@@ -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<NonNullable<typeof GET>>[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 });
});
});
Loading