Document codebase: comments, per-area READMEs, deployment guide

Readability pass across all four areas of the stack. Comments explain why
rather than what, concentrated at the points where behaviour is non-obvious:
concurrency, caching, auth, scraping and nginx templating.

Backend: doc comments on every exported declaration across handlers,
services, models and resolvers. Resolver commentary lives inside function
bodies so gqlgen does not strip it on regeneration; schema files use #
comments rather than description blocks so introspection output is
unchanged. Extracted the duplicated auth-cookie blocks into helpers.

Frontend: header comments on every component, store and view, including
STATUS: notes marking which of the parallel/legacy views are still live.
Documented the non-reactive animation-state pattern, the homeData hub and
the WebSocket stale-socket guard. Removed a few dead imports and named the
reconnect-backoff and poll-interval constants.

Python: module and function docstrings covering the Travelodge scraping
contract, the deadline threading, the two-executor concurrency and the
NDJSON streaming protocol.

Infra: header blocks on every compose file, nginx template, Dockerfile and
entrypoint, covering the config selection, envsubst allow-lists, rate-limit
semantics and volume persistence. Hoisted the duplicated envsubst variable
list in nginx/entrypoint.sh.

New: backend/README.md, python/README.md, DEPLOYMENT.md, .env.example,
backend/graph/doc.go. Refreshed vue/README.md. Corrected CLAUDE.md, which
stated a 24h access token where main.go sets 7 days.

No behaviour change. go build/vet, vite build, py_compile and docker
compose config all pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
2026-09-16 15:57:48 +01:00
co-authored by Claude Opus 5
parent a1102b4aa1
commit 64df70e5d2
183 changed files with 4691 additions and 204 deletions
+10
View File
@@ -1,3 +1,8 @@
/**
* Media/activity log for the Consumption widget. A view over homeData.activities;
* see stores/posts.js for the placeholder-then-overwrite pattern.
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { useHomeDataStore } from "@/stores/homeData";
@@ -14,6 +19,10 @@ export const useActivityStore = defineStore("activity", () => {
const activityCount = computed(() => activity.value.length);
const homeData = useHomeDataStore();
// Mirror the shared home query. `immediate` matters: homeData may already
// have loaded by the time this store is first used, and a plain watch would
// never fire for that existing value. The `length > 0` test keeps the
// placeholder on screen when the backend returns nothing.
watch(
() => homeData.activities,
(newActivities) => {
@@ -24,6 +33,7 @@ export const useActivityStore = defineStore("activity", () => {
{ immediate: true },
);
/** Refresh by re-running the whole home query; the watch above applies it. */
async function fetchActivity() {
await homeData.fetchAll();
}
+26
View File
@@ -1,3 +1,16 @@
/**
* Current user + login/logout mutations.
*
* `user` is populated two ways: mirrored from homeData.me (the shared home query
* also returns the session user), and set directly by logIn()/refreshToken().
* The watch is `immediate` so a store created after homeData has already loaded
* still picks up the user.
*
* The JWTs themselves are never visible here — the backend sets access_token and
* refresh_token as HTTP-only cookies, so `loggedIn` is inferred purely from
* whether a username came back.
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { gql } from "@/graphql";
@@ -8,6 +21,10 @@ export const useAuthStore = defineStore("auth", () => {
const loggedIn = computed(() => !!user.value.username);
const homeData = useHomeDataStore();
// Mirror the `me` field from the shared home query. `immediate` so a store
// created after homeData loaded still sees the user. Only overwrite on a
// truthy `me` — a logged-out response is null and must not clobber a user
// that logIn() just set.
watch(
() => homeData.me,
(me) => {
@@ -18,6 +35,8 @@ export const useAuthStore = defineStore("auth", () => {
{ immediate: true },
);
/** Clear the session cookies server-side, then blank the local user.
* Deliberately clears `user` even if the mutation fails. */
async function logOut() {
try {
await gql(`mutation { logout }`);
@@ -27,6 +46,8 @@ export const useAuthStore = defineStore("auth", () => {
user.value = {};
}
/** Log in and populate `user`. Swallows errors: on a bad password `user`
* is left untouched, so `loggedIn` simply stays false. */
async function logIn(username, password) {
try {
const data = await gql(
@@ -39,6 +60,8 @@ export const useAuthStore = defineStore("auth", () => {
}
}
/** Admin-only: create an account. Returns the new user; re-throws on failure
* so the calling form can show a message. */
async function createUser(username, password) {
try {
const data = await gql(
@@ -52,6 +75,8 @@ export const useAuthStore = defineStore("auth", () => {
}
}
/** Exchange the long-lived refresh_token cookie for a fresh access_token and
* re-read the user. */
async function refreshToken() {
try {
const data = await gql(
@@ -63,6 +88,7 @@ export const useAuthStore = defineStore("auth", () => {
}
}
/** Admin-only: grant/revoke admin. Returns the updated user; re-throws. */
async function setUserAdmin(userId, admin) {
try {
const data = await gql(
+10
View File
@@ -1,3 +1,8 @@
/**
* Favourites for the Favorites widget. A view over homeData.favorites; see
* stores/posts.js for the placeholder-then-overwrite pattern.
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { useHomeDataStore } from "@/stores/homeData";
@@ -14,6 +19,10 @@ export const useFavoritesStore = defineStore("favorites", () => {
const favoritesCount = computed(() => favorites.value.length);
const homeData = useHomeDataStore();
// Mirror the shared home query. `immediate` matters: homeData may already
// have loaded by the time this store is first used, and a plain watch would
// never fire for that existing value. The `length > 0` test keeps the
// placeholder on screen when the backend returns nothing.
watch(
() => homeData.favorites,
(newFavorites) => {
@@ -24,6 +33,7 @@ export const useFavoritesStore = defineStore("favorites", () => {
{ immediate: true },
);
/** Refresh by re-running the whole home query; the watch above applies it. */
async function fetchFavorites() {
await homeData.fetchAll();
}
+26
View File
@@ -1,3 +1,18 @@
/**
* The single source of truth for the home page.
*
* One GraphQL query fetches everything the /stp widgets need (posts, favorites,
* activities, Spotify, rowing, bookmarks, Gitea feed, Steam, current user) in a
* single round trip, instead of each widget issuing its own request. The
* per-domain stores (posts, favorites, activity, songs, steam, auth) are thin
* views over this one — they `watch` their slice of it rather than fetching.
*
* fetchAll() is called once at the bottom of the setup function, i.e. the first
* time any component calls useHomeDataStore(). That is why no component has to
* kick off the initial load, and why `loaded` is the flag the router guard waits
* on to know whether `me` has been resolved yet.
*/
import { defineStore } from "pinia";
import { ref } from "vue";
import { gql } from "@/graphql";
@@ -18,6 +33,11 @@ export const useHomeDataStore = defineStore("homeData", () => {
const bookmarks = ref([]);
const radioLive = ref(false);
/**
* Fetch every home-page dataset in one GraphQL round trip, plus the radio
* liveness probe in parallel. Sets `loaded` on success and `error` on
* failure; never throws. Safe to call again to refresh.
*/
async function fetchAll() {
try {
const [data] = await Promise.all([
@@ -52,6 +72,10 @@ export const useHomeDataStore = defineStore("homeData", () => {
}
}
/**
* Probe the Icecast stream with a HEAD request and set `radioLive`.
* A failure (404/connection refused) means "offline", not an error.
*/
async function fetchRadioStatus() {
try {
await axios.head("/radio/stream");
@@ -61,6 +85,8 @@ export const useHomeDataStore = defineStore("homeData", () => {
}
}
// Kick off the initial load as a side effect of the first useHomeDataStore()
// call. Pinia setup stores run once, so this fires exactly once per page load.
fetchAll();
return {
+39 -3
View File
@@ -1,7 +1,21 @@
/**
* WebSocket-backed chat, used by components/util/Chat.vue.
*
* Owns one socket at a time, auto-reconnects with exponential backoff (1s
* doubling to a 30s ceiling, reset on a successful open) and refuses to reconnect
* after an intentional disconnect().
*/
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import axios from "axios";
/**
* Same-origin ws:// or wss:// URL for the chat socket, derived from the page's
* own protocol and host. Nothing is configurable: nginx (prod) and the Vite
* proxy (dev) both serve /api/ws from the same origin as the page, and the
* auth cookies only travel if the origin matches.
*/
function getWebSocketURL() {
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
return `${protocol}//${window.location.host}/api/ws`;
@@ -12,12 +26,16 @@ export const useMessagesStore = defineStore("messages", () => {
const messages = ref([]);
const isConnected = ref(false);
const lastError = ref(null);
const INITIAL_RECONNECT_DELAY_MS = 1000;
const MAX_RECONNECT_DELAY_MS = 30000;
let intentionalClose = false;
let reconnectDelay = 1000;
let reconnectDelay = INITIAL_RECONNECT_DELAY_MS;
let reconnectTimer = null;
const messagesCount = computed(() => messages.value.length);
/** Open the socket (no-op if one already exists) and arm auto-reconnect. */
function connect() {
if (socket.value) return;
intentionalClose = false;
@@ -35,13 +53,15 @@ export const useMessagesStore = defineStore("messages", () => {
if (socket.value !== ws) return;
isConnected.value = true;
lastError.value = null;
reconnectDelay = 1000;
reconnectDelay = INITIAL_RECONNECT_DELAY_MS;
};
ws.onmessage = (event) => {
if (socket.value !== ws) return;
try {
const data = JSON.parse(event.data);
// Sent once per connection. On a reconnect it repeats messages we
// already have.
if (data.action === "history") {
// Replace in one go so keyed rows (and their images) are patched in
// place rather than unmounted and recreated.
@@ -52,9 +72,12 @@ export const useMessagesStore = defineStore("messages", () => {
messages.value = messages.value.filter((m) => m.id !== data.id);
return;
}
// Dedup by id: the server can re-broadcast a message we already hold
// (e.g. our own send echoed back, or an overlap with `history`).
if (data.id && messages.value.some((m) => m.id === data.id)) return;
messages.value.push(data);
} catch {
// Non-JSON frame: show it verbatim rather than dropping it.
messages.value.push({ text: event.data });
}
};
@@ -72,11 +95,16 @@ export const useMessagesStore = defineStore("messages", () => {
reconnectTimer = setTimeout(() => {
connect();
}, reconnectDelay);
reconnectDelay = Math.min(reconnectDelay * 2, 30000);
reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
}
};
}
/**
* Close the socket and suppress auto-reconnect. Clearing `socket.value`
* *before* calling close() is what makes the onclose guard above see a stale
* socket, so a later connect() is not fought over by the dying one.
*/
function disconnect() {
intentionalClose = true;
clearTimeout(reconnectTimer);
@@ -87,11 +115,14 @@ export const useMessagesStore = defineStore("messages", () => {
ws.close();
}
/** Send a chat line. Silently drops it if the socket is not open. */
function sendMessage(text, isPrivate = false) {
if (!socket.value || !isConnected.value) return;
socket.value.send(JSON.stringify({ text, private: isPrivate }));
}
/** Ask the server to delete a message; the removal arrives back as a
* broadcast "delete" frame, so local state is not touched here. */
function deleteMessage(id) {
if (!socket.value || !isConnected.value) return;
socket.value.send(JSON.stringify({ action: "delete", id }));
@@ -101,6 +132,11 @@ export const useMessagesStore = defineStore("messages", () => {
messages.value = [];
}
/**
* POST a file to the REST upload endpoint, then send its returned URL over
* the socket as a normal message. Two steps because the socket carries JSON
* text only. Errors surface via `lastError`.
*/
async function uploadAndSendFile(file, isPrivate = false) {
try {
const formData = new FormData();
+8
View File
@@ -1,3 +1,11 @@
/**
* Hand-written classes that coerce raw API JSON into real Date objects.
*
* STATUS: not imported anywhere. Stores consume the GraphQL payloads directly and
* format dates at the point of display, so these are dormant; kept as a record of
* the intended shape of User/Message/Post.
*/
export class User {
constructor({ id, createdAt, updatedAt, deletedAt, username, admin }) {
this.id = id;
+15
View File
@@ -1,7 +1,17 @@
/**
* Places-to-go list (the "Places" tab inside the Collage widget) — full CRUD.
*
* Not part of the homeData query because it is sign-in-only; PlacesTable.vue
* fetches it lazily once the user is logged in. PLACE_FIELDS is interpolated into
* every query/mutation so the selection set can never drift between them.
*/
import { defineStore } from "pinia";
import { ref } from "vue";
import { gql } from "@/graphql";
// Shared selection set: interpolated into every query and mutation so they can
// never drift apart.
const PLACE_FIELDS = `
id
title
@@ -22,6 +32,7 @@ export const usePlacesStore = defineStore("places", () => {
const loading = ref(false);
const error = ref(null);
/** Load all places into `places`. Records failures on `error` rather than throwing. */
async function fetch() {
loading.value = true;
try {
@@ -36,6 +47,7 @@ export const usePlacesStore = defineStore("places", () => {
}
}
/** Create a place and prepend it locally (newest first). Throws on failure. */
async function create(input) {
const data = await gql(
`mutation CreatePlace($input: CreatePlaceInput!) {
@@ -47,6 +59,7 @@ export const usePlacesStore = defineStore("places", () => {
return data.createPlace;
}
/** Patch a place and replace it in the local list. Throws on failure. */
async function update(id, input) {
const data = await gql(
`mutation UpdatePlace($id: ID!, $input: UpdatePlaceInput!) {
@@ -59,10 +72,12 @@ export const usePlacesStore = defineStore("places", () => {
return data.updatePlace;
}
/** Flip a place's `done` flag. */
async function toggleDone(place) {
return update(place.id, { done: !place.done });
}
/** Soft-delete a place and drop it from the local list. */
async function remove(id) {
await gql(
`mutation DeletePlace($id: ID!) { deletePlace(id: $id) { id } }`,
+14
View File
@@ -1,3 +1,11 @@
/**
* Blog posts for the Feed widget. A view over homeData.posts.
*
* `post_template` is placeholder content rendered before (or instead of) a
* successful fetch — the watch only overwrites `posts` when the fetch returned a
* non-empty list, so the widget never flashes empty.
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { gql } from "@/graphql";
@@ -19,6 +27,10 @@ export const usePostsStore = defineStore("posts", () => {
const postsCount = computed(() => posts.value.length);
const homeData = useHomeDataStore();
// Mirror the shared home query. `immediate` matters: homeData may already
// have loaded by the time this store is first used, and a plain watch would
// never fire for that existing value. The `length > 0` test keeps the
// placeholder on screen when the backend returns nothing.
watch(
() => homeData.posts,
(newPosts) => {
@@ -29,10 +41,12 @@ export const usePostsStore = defineStore("posts", () => {
{ immediate: true },
);
/** Refresh by re-running the whole home query; the watch above applies it. */
async function fetchPosts() {
await homeData.fetchAll();
}
/** Soft-delete a post, then refetch so every widget sees the new list. */
async function deletePost(post) {
try {
await gql(
+13
View File
@@ -1,3 +1,11 @@
/**
* Recently played Spotify tracks for the Listening widget.
*
* Unlike the other derived stores this one also has its own fetchSongs(), because
* Listening.vue re-polls Spotify every 2 minutes and re-running the whole
* homeData query for that would be wasteful.
*/
import { defineStore } from "pinia";
import { ref, computed, watch } from "vue";
import { gql } from "@/graphql";
@@ -17,6 +25,10 @@ export const useSongsStore = defineStore("songs", () => {
const songsCount = computed(() => songs.value.length);
const homeData = useHomeDataStore();
// Mirror the shared home query. `immediate` matters: homeData may already
// have loaded by the time this store is first used, and a plain watch would
// never fire for that existing value. The `length > 0` test keeps the
// placeholder on screen when the backend returns nothing.
watch(
() => homeData.spotifyRecent,
(newSongs) => {
@@ -27,6 +39,7 @@ export const useSongsStore = defineStore("songs", () => {
{ immediate: true },
);
/** Re-poll Spotify alone (cheaper than fetchAll). Keeps the old list on error. */
async function fetchSongs() {
try {
const data = await gql(`
+9
View File
@@ -1,3 +1,9 @@
/**
* Steam online status and recent games for the Steam widget. Mirrors
* homeData.steamStatus, plus a standalone fetchSteam() used for the widget's own
* 5-minute refresh.
*/
import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { gql } from "@/graphql";
@@ -7,6 +13,8 @@ export const useSteamStore = defineStore("steam", () => {
const steamStatus = ref({ online: false, recentGames: [] });
const homeData = useHomeDataStore();
// Mirror the shared home query; `immediate` so a store created after
// homeData has already loaded still picks up the value.
watch(
() => homeData.steamStatus,
(newStatus) => {
@@ -17,6 +25,7 @@ export const useSteamStore = defineStore("steam", () => {
{ immediate: true },
);
/** Re-poll Steam alone (cheaper than fetchAll). Keeps the old value on error. */
async function fetchSteam() {
try {
const data = await gql(`