Fix security issues, bugs, and convoluted code across the stack
Security: - Token revocation. User gains a TokenVersion counter embedded in both tokens as a "tv" claim; AuthenticateToken rejects a token whose version no longer matches the row. Logout bumps it, so logging out now kills outstanding tokens rather than only clearing cookies. Costs one primary-key SELECT per authenticated request, which is the price of having revocation at all. - Spotify OAuth CSRF. The fixed SPOTIFY_AUTH_STATE constant is replaced by a per-request one-shot nonce, verified and consumed on callback. - Private chat attachments. Attachments on private messages are written to /backend/uploads/private/ and served at /uploads/private/, gated by the same nginx auth_request admin check used for /hasura/ and /notes/. Private uploads are rejected from non-admin callers. - The icecast admin UI (/radio/admin/) is behind the admin gate; listener traffic is untouched. - Store caches are mutex-guarded, so -race is clean. Bugs: - The email pipeline no longer drops emails permanently on transient failure. Failures record an attempt counter and are retried up to 3 times; the fetch window rewinds to the oldest retryable email's ReceivedAt, without which a retry could never re-fetch it. - Rowing duplicate detection distinguishes ErrRecordNotFound from a real DB error, so a transient failure no longer causes a duplicate insert plus a paid Claude call. - DeletePost propagates its delete error instead of reporting success. - RecentlyPlayed populates the cache it reads. - main.go exits non-zero if r.Run fails, so a port conflict is visible. - Python: the scan truncation flag is set on every deadline path; timed_out is reported by the worker rather than inferred from the clock; date validation uses Europe/London rather than server-local time. - Vue: Time.vue and Radio.vue intervals are cleared on unmount; Feed.vue guards a missing author; Timer.vue gets an explicit state machine and compares total elapsed seconds; Elle.vue's comma-operator call and per-frame console.log are fixed. Simplification: - One TTLCache replaces three near-identical cache implementations, with the differing eviction rules as explicit parameters. - run_scan's transport index no longer uses one object as both ordering record and live output; its three phases are separate functions. - _price_hotels submits all work to a single pool, so the nested-executor deadlock hazard is gone by construction. - The NDJSON event generators share one implementation. - IMAP FETCH responses pair each line with its literal in the type, so callers no longer hand-skip alternate entries. - Shared helpers for slice-of-pointers, markdown fences and auth cookies. - Vue: useHotelSearch, createMirrorStore, useRotation, useCreateForm, useLinkAttrs, ListWidget and LinkTableItems replace duplicated blocks. - nginx dev config's duplicated :80/:443 bodies share one partial. Infra: certbot passes --deploy-hook touching a sentinel that nginx's watcher reloads on, so renewed certs are served without a restart, and the watcher also removes the manual restart after first issuance. db is gated on service_healthy, autoheal is pinned, and the unused envsubst entries are dropped. Verified: go build/vet, npx vite build, py_compile, docker compose config for both overlays, bash -n on all scripts, and an envsubst render of every nginx template (no leftover placeholders, runtime vars preserved, braces balanced). Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
@@ -71,10 +71,6 @@ EMAIL_SYNC_ENABLED=
|
||||
# --- Services that nginx substitutes but no longer runs -----------------------
|
||||
# Kept because nginx/entrypoint.sh lists them in its envsubst allow-list; no
|
||||
# compose service uses them today. Harmless if blank.
|
||||
UPTIMEKUMA_HOST=
|
||||
UPTIMEKUMA_PORT=
|
||||
WALLABAG_HOST=
|
||||
WALLABAG_PORT=
|
||||
|
||||
# --- Quartz (notes site at /notes/) ------------------------------------------
|
||||
QUARTZ_HOST=quartz
|
||||
|
||||
+10
-3
@@ -150,9 +150,16 @@ generated struct rather than the model you expected.
|
||||
are benign (at worst a duplicate upstream fetch), but do not add a field
|
||||
there that would be unsafe to tear.
|
||||
- **Claude output is parsed as JSON** after stripping a possible markdown code
|
||||
fence, in both `handle_rowing.go` and `email_sync.go`.
|
||||
- **The email pipeline never retries.** A failed email is recorded with action
|
||||
`"error"` so the next sync skips it.
|
||||
fence — via the shared `services.StripMarkdownFence`, used by both
|
||||
`handle_rowing.go` and `email_sync.go`.
|
||||
- **The email pipeline retries a failure up to `maxEmailAttempts` (3) times.**
|
||||
A failed email is recorded with action `"error"` and an attempt counter;
|
||||
while it has attempts left the next sync reprocesses it and updates the same
|
||||
row. Because the fetch window is anchored to *processing* time, which has
|
||||
already moved past the failure, the sync also rewinds the window to the
|
||||
oldest retryable row's `ReceivedAt` — otherwise the email could never be
|
||||
re-fetched. Once the cap is reached the row is terminal, so an email Claude
|
||||
can never parse stops costing API calls.
|
||||
- **Authenticating email after start-up does not start the scheduler**, which
|
||||
only checks readiness once — restart, or trigger syncs by hand.
|
||||
- **Introspection and the playground are off** unless `DEV_MODE=true` *and*
|
||||
|
||||
@@ -39,14 +39,7 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&activities).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &activities[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Activity, len(activities))
|
||||
for i := range activities {
|
||||
result[i] = &activities[i]
|
||||
}
|
||||
return result, nil
|
||||
return ptrs(activities), nil
|
||||
}
|
||||
|
||||
// Activity returns ActivityResolver implementation.
|
||||
|
||||
@@ -7,11 +7,13 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"log"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
@@ -48,7 +50,7 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
|
||||
return nil, fmt.Errorf("failed to generate tokens")
|
||||
}
|
||||
|
||||
setAuthCookies(gc, r.Store.Auth.Config, tokens)
|
||||
services.SetAuthCookies(gc, r.Store.Auth.Config, tokens)
|
||||
|
||||
// The payload carries no token: the tokens only ever travel as HttpOnly
|
||||
// cookies, so client JavaScript never sees them.
|
||||
@@ -62,12 +64,18 @@ func (r *mutationResolver) Logout(ctx context.Context) (bool, error) {
|
||||
return false, fmt.Errorf("could not get gin context")
|
||||
}
|
||||
|
||||
// Max-age -1 tells the browser to drop the cookies. Nothing is
|
||||
// invalidated server-side, so a token captured beforehand still works
|
||||
// until it expires.
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie("access_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true)
|
||||
gc.SetCookie("refresh_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true)
|
||||
// Bumping the token version is what actually revokes the tokens; clearing
|
||||
// the cookies only stops the browser presenting them. Both are best
|
||||
// effort and logout always reports success, matching the REST endpoint.
|
||||
if userID, ok := UserIDFromCtx(ctx); ok {
|
||||
// The context only carries claims from a token that already
|
||||
// verified, so this cannot be used to revoke someone else's sessions.
|
||||
if err := services.BumpTokenVersion(r.Store.DB, userID); err != nil {
|
||||
log.Printf("logout: failed to revoke tokens for user %d: %v", userID, err)
|
||||
}
|
||||
}
|
||||
|
||||
services.ClearAuthCookies(gc, r.Store.Auth.Config)
|
||||
|
||||
return true, nil
|
||||
}
|
||||
@@ -84,33 +92,31 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
claims, err := r.Store.Auth.VerifyJWT(refreshToken)
|
||||
// Shared with the REST refresh endpoint, but the messages below are the
|
||||
// ones this resolver already returned, so the GraphQL error strings are
|
||||
// unchanged. Admin status and the token version are both re-read from the
|
||||
// database here, which is what lets a revoked admin flag or a logout take
|
||||
// effect on refresh.
|
||||
user, err := r.Store.Auth.AuthenticateToken(r.Store.DB, refreshToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
switch {
|
||||
case errors.Is(err, services.ErrInvalidClaims):
|
||||
return nil, fmt.Errorf("invalid token claims")
|
||||
case errors.Is(err, services.ErrUserNotFound):
|
||||
return nil, fmt.Errorf("user not found")
|
||||
default:
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
}
|
||||
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid token claims")
|
||||
}
|
||||
|
||||
// Setting the primary key and calling First with no condition makes GORM
|
||||
// look the row up by that key. Admin status is re-read from the database
|
||||
// here, which is what lets a revoked admin flag take effect on refresh.
|
||||
var user models.User
|
||||
user.ID = uint(userIDF)
|
||||
if err := r.Store.DB.First(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
tokens, err := r.Store.Auth.GenerateJWT(&user)
|
||||
tokens, err := r.Store.Auth.GenerateJWT(user)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate tokens")
|
||||
}
|
||||
|
||||
setAuthCookies(gc, r.Store.Auth.Config, tokens)
|
||||
services.SetAuthCookies(gc, r.Store.Auth.Config, tokens)
|
||||
|
||||
return &model.AuthPayload{User: &user}, nil
|
||||
return &model.AuthPayload{User: user}, nil
|
||||
}
|
||||
|
||||
// Me is the resolver for the me field.
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// setAuthCookies writes the access/refresh cookie pair on a GraphQL response.
|
||||
//
|
||||
// This mirrors handlers.Store.setAuthCookies — the two cannot be shared
|
||||
// because importing graph from handlers would be a cycle, so any change to
|
||||
// cookie attributes has to be made in both places or login via REST and login
|
||||
// via GraphQL will disagree.
|
||||
//
|
||||
// gin's SetCookie takes Secure and HttpOnly as its two trailing booleans, both
|
||||
// true here: the cookies never travel over plain HTTP and are invisible to
|
||||
// JavaScript. SameSite=Lax survives a top-level navigation back from an OAuth
|
||||
// provider while still blocking cross-site POSTs. Each max-age mirrors the
|
||||
// lifetime baked into the token itself.
|
||||
//
|
||||
// It lives in its own file rather than in auth.resolvers.go because gqlgen may
|
||||
// relocate hand-written code in the files it regenerates.
|
||||
func setAuthCookies(gc *gin.Context, config *services.AuthConfig, tokens *services.Tokens) {
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
config.Domain,
|
||||
true, true,
|
||||
)
|
||||
}
|
||||
@@ -54,14 +54,7 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro
|
||||
if err := r.Store.DB.Order("category ASC, created_at ASC").Find(&bookmarks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &bookmarks[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Bookmark, len(bookmarks))
|
||||
for i := range bookmarks {
|
||||
result[i] = &bookmarks[i]
|
||||
}
|
||||
return result, nil
|
||||
return ptrs(bookmarks), nil
|
||||
}
|
||||
|
||||
// Bookmark returns BookmarkResolver implementation.
|
||||
|
||||
@@ -38,14 +38,7 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&favorites).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &favorites[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Favorite, len(favorites))
|
||||
for i := range favorites {
|
||||
result[i] = &favorites[i]
|
||||
}
|
||||
return result, nil
|
||||
return ptrs(favorites), nil
|
||||
}
|
||||
|
||||
// Favorite returns FavoriteResolver implementation.
|
||||
|
||||
@@ -7,7 +7,6 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/services"
|
||||
@@ -17,8 +16,8 @@ import (
|
||||
func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, error) {
|
||||
// One-minute cache on the Store, shared by every visitor, so a busy home
|
||||
// page does not hammer the Gitea container.
|
||||
if r.Store.GiteaFeedFresh() {
|
||||
return mapGiteaFeed(r.Store.GiteaFeed), nil
|
||||
if cached, ok := r.Store.CachedGiteaFeed(); ok {
|
||||
return mapGiteaFeed(cached), nil
|
||||
}
|
||||
|
||||
feed, err := services.FetchLatestFeed(r.Store.GiteaHost, r.Store.GiteaPort)
|
||||
@@ -33,8 +32,7 @@ func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, er
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
r.Store.GiteaFeed = feed
|
||||
r.Store.GiteaFeedFetchedAt = time.Now()
|
||||
r.Store.SetGiteaFeed(feed)
|
||||
|
||||
return mapGiteaFeed(feed), nil
|
||||
}
|
||||
|
||||
@@ -40,14 +40,7 @@ func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error)
|
||||
if err := query.Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &messages[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Message, len(messages))
|
||||
for i := range messages {
|
||||
result[i] = &messages[i]
|
||||
}
|
||||
return result, nil
|
||||
return ptrs(messages), nil
|
||||
}
|
||||
|
||||
// Message returns MessageResolver implementation.
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// AuthContextMiddleware prepares the request context for the GraphQL handler.
|
||||
@@ -16,16 +17,22 @@ import (
|
||||
// into the individual resolvers (see IsAdminFromCtx). Both cookie and verify
|
||||
// errors are swallowed for exactly that reason.
|
||||
//
|
||||
// It takes the database because validating a token means loading the user to
|
||||
// compare token versions; see services.Auth.AuthenticateTokenWithClaims.
|
||||
//
|
||||
// Unlike the REST path there is no refresh-token fallback here, so once the
|
||||
// access token expires GraphQL treats the caller as anonymous until the front
|
||||
// end refreshes.
|
||||
func AuthContextMiddleware(auth *services.Auth) gin.HandlerFunc {
|
||||
func AuthContextMiddleware(auth *services.Auth, db *gorm.DB) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx := context.WithValue(c.Request.Context(), ginContextKey, c)
|
||||
|
||||
accessToken, err := c.Cookie("access_token")
|
||||
if err == nil {
|
||||
claims, err := auth.VerifyJWT(accessToken)
|
||||
// The database is needed to check the token version, so a
|
||||
// revoked token (logout, password change) leaves the request
|
||||
// anonymous instead of continuing to authorise mutations.
|
||||
_, claims, err := auth.AuthenticateTokenWithClaims(db, accessToken)
|
||||
if err == nil {
|
||||
ctx = context.WithValue(ctx, userClaimsKey, claims)
|
||||
}
|
||||
|
||||
@@ -111,11 +111,7 @@ func (r *queryResolver) Places(ctx context.Context) ([]*models.Place, error) {
|
||||
if err := r.Store.DB.Order("done ASC, priority DESC, created_at DESC").Find(&places).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Place, len(places))
|
||||
for i := range places {
|
||||
result[i] = &places[i]
|
||||
}
|
||||
return result, nil
|
||||
return ptrs(places), nil
|
||||
}
|
||||
|
||||
// Place returns PlaceResolver implementation.
|
||||
|
||||
@@ -85,9 +85,13 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
|
||||
return nil, fmt.Errorf("you can only delete your own posts")
|
||||
}
|
||||
|
||||
// Soft delete; the error is dropped, so a failed delete still reports
|
||||
// success to the client.
|
||||
r.Store.DB.Delete(&post)
|
||||
// Soft delete. The error is propagated: reporting success for a delete
|
||||
// that did not happen would leave the client showing the post as gone
|
||||
// until the next reload.
|
||||
if err := r.Store.DB.Delete(&post).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
@@ -105,14 +109,7 @@ func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
|
||||
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &posts[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Post, len(posts))
|
||||
for i := range posts {
|
||||
result[i] = &posts[i]
|
||||
}
|
||||
return result, nil
|
||||
return ptrs(posts), nil
|
||||
}
|
||||
|
||||
// Post is the resolver for the post field.
|
||||
|
||||
@@ -17,14 +17,7 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &rows[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Rowing, len(rows))
|
||||
for i := range rows {
|
||||
result[i] = &rows[i]
|
||||
}
|
||||
return result, nil
|
||||
return ptrs(rows), nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package graph
|
||||
|
||||
// This file is hand-written and is never regenerated by gqlgen — it is not
|
||||
// named after a schema file, so `gqlgen generate` leaves it alone.
|
||||
|
||||
// ptrs copies a slice of values into a slice of pointers to those values.
|
||||
//
|
||||
// Every list query loads rows with Find(&xs) into a []T and then has to hand
|
||||
// gqlgen a []*T, because the schema returns lists of nullable objects. Taking
|
||||
// &xs[i] is safe: the slice is never appended to after this point, so the
|
||||
// backing array cannot move and the pointers stay valid.
|
||||
//
|
||||
// Loading straight into a []*T would avoid the copy but changes the query
|
||||
// GORM emits, so the copy is kept deliberately.
|
||||
func ptrs[T any](xs []T) []*T {
|
||||
result := make([]*T, len(xs))
|
||||
for i := range xs {
|
||||
result[i] = &xs[i]
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -7,10 +7,8 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
spotify "github.com/zmb3/spotify/v2"
|
||||
)
|
||||
|
||||
// SpotifyListening is the resolver for the spotifyListening field.
|
||||
@@ -40,20 +38,12 @@ func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRece
|
||||
return []*model.SpotifyRecentItem{}, nil
|
||||
}
|
||||
|
||||
// One-minute cache. This resolver is the only writer of that cache; the
|
||||
// REST /spotify/recent endpoint reads it but never fills it.
|
||||
if r.Store.RecentSongsFresh() {
|
||||
return mapRecentItems(*r.Store.RecentSongs), nil
|
||||
}
|
||||
|
||||
opts := spotify.RecentlyPlayedOptions{Limit: 3}
|
||||
played, err := r.Store.SpotifyClient.PlayerRecentlyPlayedOpt(ctx, &opts)
|
||||
// Shared one-minute cache, filled by whichever of this resolver and the
|
||||
// REST /spotify/recent endpoint misses it first.
|
||||
played, err := r.Store.RecentlyPlayedTracks(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
r.Store.RecentSongs = &played
|
||||
r.Store.RecentSongsFetchedAt = time.Now()
|
||||
|
||||
return mapRecentItems(played), nil
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/services"
|
||||
@@ -21,10 +20,10 @@ func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, er
|
||||
|
||||
// Five-minute cache across both Steam calls, which are made together and
|
||||
// expire together.
|
||||
if r.Store.SteamFresh() {
|
||||
if games, online, ok := r.Store.CachedSteam(); ok {
|
||||
return &model.SteamStatus{
|
||||
Online: r.Store.SteamOnline,
|
||||
RecentGames: mapSteamGames(r.Store.SteamRecentGames),
|
||||
Online: online,
|
||||
RecentGames: mapSteamGames(games),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -45,9 +44,7 @@ func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, er
|
||||
online = summary.PersonaState > 0
|
||||
}
|
||||
|
||||
r.Store.SteamRecentGames = games
|
||||
r.Store.SteamOnline = online
|
||||
r.Store.SteamFetchedAt = time.Now()
|
||||
r.Store.SetSteam(games, online)
|
||||
|
||||
return &model.SteamStatus{
|
||||
Online: online,
|
||||
|
||||
@@ -92,14 +92,7 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
if err := r.Store.DB.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &users[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.User, len(users))
|
||||
for i := range users {
|
||||
result[i] = &users[i]
|
||||
}
|
||||
return result, nil
|
||||
return ptrs(users), nil
|
||||
}
|
||||
|
||||
// User is the resolver for the user field.
|
||||
|
||||
+83
-107
@@ -1,6 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
@@ -36,7 +37,7 @@ type UserCredentials struct {
|
||||
//
|
||||
// It deliberately does NOT fall back to the refresh token: an expired access
|
||||
// token yields a 401 and the front end is expected to call /auth/refresh and
|
||||
// retry.
|
||||
// retry. A token whose version has been revoked is also a 401.
|
||||
func (store *Store) AuthMiddlewear(ctx *gin.Context) {
|
||||
access_token, err := ctx.Cookie("access_token")
|
||||
if err != nil {
|
||||
@@ -44,7 +45,10 @@ func (store *Store) AuthMiddlewear(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := store.Auth.VerifyJWT(access_token)
|
||||
// Validated against the database, not just cryptographically: that is
|
||||
// what makes a logged-out or password-changed token stop working here
|
||||
// rather than lingering until it expires.
|
||||
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, access_token)
|
||||
if err != nil {
|
||||
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
@@ -105,9 +109,9 @@ func (store *Store) ValidateAdmin(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := store.Auth.VerifyJWT(accessToken)
|
||||
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
|
||||
if err != nil {
|
||||
// Expired/invalid access token — try refreshing
|
||||
// Expired, invalid or revoked access token — try refreshing
|
||||
if !store.tryRefreshAndValidateAdmin(ctx) {
|
||||
ctx.Status(http.StatusUnauthorized)
|
||||
}
|
||||
@@ -139,30 +143,19 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
claims, err := store.Auth.VerifyJWT(refreshToken)
|
||||
// Any failure at all (bad token, unknown user, revoked version) is
|
||||
// "cannot decide" here, exactly as before: the caller sends 401.
|
||||
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
// Pre-setting ID and calling First with no explicit condition makes GORM
|
||||
// use the primary key already in the struct as the lookup. Soft-deleted
|
||||
// users are excluded automatically, so a deleted admin fails here.
|
||||
user := models.User{ID: uint(userIDF)}
|
||||
if err := store.DB.First(&user).Error; err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if !user.Admin {
|
||||
ctx.Status(http.StatusForbidden)
|
||||
return true
|
||||
}
|
||||
|
||||
tokens, err := store.Auth.GenerateJWT(&user)
|
||||
tokens, err := store.Auth.GenerateJWT(user)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
@@ -173,32 +166,11 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// setAuthCookies writes the access/refresh cookie pair.
|
||||
//
|
||||
// The two trailing booleans of gin's SetCookie are Secure and HttpOnly, both
|
||||
// true here: the cookies are never sent over plain HTTP and are invisible to
|
||||
// JavaScript. SameSite=Lax lets them survive a top-level navigation back from
|
||||
// an OAuth provider while still blocking cross-site POSTs. Each cookie's
|
||||
// max-age mirrors the lifetime baked into the token itself, so the browser
|
||||
// drops it at roughly the moment it stops being accepted.
|
||||
// setAuthCookies writes the access/refresh cookie pair. The cookie
|
||||
// attributes live in services.SetAuthCookies so that REST and GraphQL cannot
|
||||
// disagree about them; this method is just the Store-shaped spelling of it.
|
||||
func (store *Store) setAuthCookies(ctx *gin.Context, tokens *services.Tokens) {
|
||||
ctx.SetSameSite(http.SameSiteLaxMode)
|
||||
ctx.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
ctx.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
services.SetAuthCookies(ctx, store.Auth.Config, tokens)
|
||||
}
|
||||
|
||||
// CheckToken backs GET /auth/check: it returns the current user for a valid
|
||||
@@ -212,38 +184,31 @@ func (store *Store) CheckToken(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := store.Auth.VerifyJWT(access_token)
|
||||
// Status codes here are unchanged from the hand-rolled version: a bad
|
||||
// token or bad claims are both 401, and only a missing user is 404 with
|
||||
// the cookies cleared. A revoked (out-of-date version) token joins the
|
||||
// 401 case, since from the client's point of view it is simply no longer
|
||||
// a valid token.
|
||||
user, err := store.Auth.AuthenticateToken(store.DB, access_token)
|
||||
if err != nil {
|
||||
if errors.Is(err, services.ErrUserNotFound) {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
store.removeCookies(ctx)
|
||||
return
|
||||
}
|
||||
ctx.JSON(401, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
// JWT claims come back through encoding/json, so every number is a
|
||||
// float64 regardless of the Go type it was signed from.
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
ctx.JSON(401, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
userID := uint(userIDF)
|
||||
|
||||
user := models.User{ID: userID}
|
||||
tx := store.DB.First(&user)
|
||||
if tx.Error != nil {
|
||||
log.Println(tx.Error)
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
store.removeCookies(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
// RefreshToken backs POST /auth/refresh: it exchanges a valid refresh token
|
||||
// for a new cookie pair and returns the user.
|
||||
//
|
||||
// Tokens are not rotated in any revocable sense — the old refresh token stays
|
||||
// valid until it expires, because nothing is tracked server-side.
|
||||
// The old refresh token is not rotated, but it does die when the user logs out
|
||||
// or changes their password, because those bump the token version this checks.
|
||||
func (store *Store) RefreshToken(ctx *gin.Context) {
|
||||
refreshToken, err := ctx.Cookie("refresh_token")
|
||||
if err != nil {
|
||||
@@ -251,29 +216,27 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := store.Auth.VerifyJWT(refreshToken)
|
||||
// The three outcomes below preserve the original status codes exactly:
|
||||
// an unusable token is 401, unreadable claims are 500, and a token for a
|
||||
// user that no longer exists is 404 with the cookies cleared. A revoked
|
||||
// token is treated as an unusable one (401) — the client's correct
|
||||
// response is to log in again.
|
||||
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
switch {
|
||||
case errors.Is(err, services.ErrInvalidClaims):
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid token claims"})
|
||||
case errors.Is(err, services.ErrUserNotFound):
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
store.removeCookies(ctx)
|
||||
default:
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid token claims"})
|
||||
return
|
||||
}
|
||||
userID := uint(userIDF)
|
||||
|
||||
user := models.User{ID: userID}
|
||||
tx := store.DB.First(&user)
|
||||
if tx.Error != nil {
|
||||
log.Println(tx.Error)
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
store.removeCookies(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
tokens, err := store.Auth.GenerateJWT(&user)
|
||||
tokens, err := store.Auth.GenerateJWT(user)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
@@ -329,34 +292,47 @@ func (store *Store) Login(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusAccepted, user)
|
||||
}
|
||||
|
||||
// Logout backs POST /auth/logout. It only clears the browser's cookies —
|
||||
// the tokens themselves stay cryptographically valid until they expire, so a
|
||||
// copy taken beforehand would still work.
|
||||
// Logout backs POST /auth/logout. As well as clearing the browser's cookies
|
||||
// it bumps the user's token version, so the tokens it just discarded — and
|
||||
// any copy taken beforehand — stop being accepted immediately.
|
||||
//
|
||||
// It always answers 200: identifying the caller is best effort (the cookies
|
||||
// may already be gone or expired), and a client that cannot be identified has
|
||||
// nothing to revoke anyway.
|
||||
func (store *Store) Logout(ctx *gin.Context) {
|
||||
store.revokeCallerTokens(ctx)
|
||||
store.removeCookies(ctx)
|
||||
|
||||
ctx.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
// removeCookies expires both auth cookies. The max-age of -1 is what tells
|
||||
// the browser to delete them; path, domain and the Secure/HttpOnly flags must
|
||||
// match those used when setting them or the browser keeps the originals.
|
||||
// revokeCallerTokens bumps the token version of whoever made this request,
|
||||
// identified from the access token or, failing that, the refresh token.
|
||||
//
|
||||
// It deliberately verifies the token rather than just reading the id out of
|
||||
// it: without that, anyone could bump an arbitrary user's version by posting a
|
||||
// forged cookie, which is a denial-of-service on that account's sessions.
|
||||
func (store *Store) revokeCallerTokens(ctx *gin.Context) {
|
||||
for _, name := range []string{"access_token", "refresh_token"} {
|
||||
token, err := ctx.Cookie(name)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
user, err := store.Auth.AuthenticateToken(store.DB, token)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if err := services.BumpTokenVersion(store.DB, user.ID); err != nil {
|
||||
// Logged rather than returned: the cookies are still cleared, but
|
||||
// this means the logout did not actually revoke anything.
|
||||
log.Printf("logout: failed to revoke tokens for user %d: %v", user.ID, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// removeCookies expires both auth cookies; see services.ClearAuthCookies for
|
||||
// why the attributes have to match those used when setting them.
|
||||
func (store *Store) removeCookies(ctx *gin.Context) {
|
||||
ctx.SetSameSite(http.SameSiteLaxMode)
|
||||
ctx.SetCookie(
|
||||
"access_token",
|
||||
"",
|
||||
-1,
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
ctx.SetCookie(
|
||||
"refresh_token",
|
||||
"",
|
||||
-1,
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
services.ClearAuthCookies(ctx, store.Auth.Config)
|
||||
}
|
||||
|
||||
@@ -10,11 +10,17 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Attachment upload for the chat. Files land in a directory that nginx serves
|
||||
// directly at /uploads/, so anything written here is publicly reachable by
|
||||
// URL — which is why the extension and content checks below matter.
|
||||
// Attachment upload for the chat.
|
||||
//
|
||||
// Files land in one of two directories. /backend/uploads/ is served by nginx
|
||||
// at /uploads/ with no authentication, so anything written there is publicly
|
||||
// reachable by URL — which is why the extension and content checks below
|
||||
// matter. /backend/uploads/private/ holds attachments for private (admin-only)
|
||||
// messages and is served at /uploads/private/ behind an nginx auth_request
|
||||
// gate; only an admin may upload there.
|
||||
|
||||
// allowedExtensions is the upload allow-list, keyed by lower-cased extension.
|
||||
var allowedExtensions = map[string]bool{
|
||||
@@ -36,10 +42,28 @@ var extensionToMIMEPrefix = map[string]string{
|
||||
".pdf": "application/pdf", ".txt": "text/",
|
||||
}
|
||||
|
||||
// publicUploadDir and privateUploadDir are the two destinations; the private
|
||||
// one is created on demand because nothing else guarantees it exists.
|
||||
const (
|
||||
publicUploadDir = "/backend/uploads/"
|
||||
privateUploadDir = "/backend/uploads/private/"
|
||||
)
|
||||
|
||||
// UploadMessageFile backs POST /messages/upload (login required) and returns
|
||||
// the public URL of the stored file, which the client then sends over the
|
||||
// WebSocket as a message's fileUrl.
|
||||
// the URL of the stored file, which the client then sends over the WebSocket
|
||||
// as a message's fileUrl.
|
||||
//
|
||||
// The multipart form takes an optional "private" field: "true" stores the file
|
||||
// under /uploads/private/ for use as a private message's attachment. That is
|
||||
// admin-only, because private messages themselves are — an attachment URL
|
||||
// leaking out is the same disclosure as the message leaking out.
|
||||
func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
private := ctx.PostForm("private") == "true"
|
||||
if private && !requestIsAdmin(ctx) {
|
||||
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||
return
|
||||
}
|
||||
|
||||
file, err := ctx.FormFile("file")
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
|
||||
@@ -94,7 +118,18 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
}
|
||||
filename := hex.EncodeToString(b) + ext
|
||||
|
||||
uploadDir := "/backend/uploads/"
|
||||
uploadDir := publicUploadDir
|
||||
urlPrefix := "/uploads/"
|
||||
if private {
|
||||
uploadDir = privateUploadDir
|
||||
urlPrefix = "/uploads/private/"
|
||||
// 0755 so nginx (a different user) can traverse the directory to
|
||||
// serve the files once its auth_request gate has approved.
|
||||
if err := os.MkdirAll(uploadDir, 0755); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
||||
return
|
||||
}
|
||||
}
|
||||
dest := filepath.Join(uploadDir, filename)
|
||||
|
||||
// Reopened rather than rewound: the earlier handle was closed after
|
||||
@@ -119,5 +154,25 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"url": "/uploads/" + filename})
|
||||
ctx.JSON(http.StatusOK, gin.H{"url": urlPrefix + filename})
|
||||
}
|
||||
|
||||
// requestIsAdmin reports whether the caller's access token carries admin=true.
|
||||
//
|
||||
// This route sits in the `protected` group, which runs AuthMiddlewear but not
|
||||
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
|
||||
// public attachments — so the admin check is made here from the same
|
||||
// "userClaims" value AdminMiddleware would have read.
|
||||
func requestIsAdmin(ctx *gin.Context) bool {
|
||||
claims, exists := ctx.Get("userClaims")
|
||||
if !exists {
|
||||
return false
|
||||
}
|
||||
mapClaims, ok := claims.(*jwt.MapClaims)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
admin, ok := (*mapClaims)["admin"].(bool)
|
||||
|
||||
return ok && admin
|
||||
}
|
||||
|
||||
@@ -4,16 +4,18 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/rwcarlsen/goexif/exif"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Rowing log. The interesting endpoint is CreateRowing: rather than a form,
|
||||
@@ -109,13 +111,21 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
|
||||
// Duplicate guard: two photos of the same session share an EXIF capture
|
||||
// time to the second. Checked before the Claude call so a re-upload costs
|
||||
// nothing. Note this reads err == nil as "found" — an actual database
|
||||
// error is indistinguishable from "no match" here and lets the insert
|
||||
// proceed.
|
||||
// nothing.
|
||||
//
|
||||
// Fails closed: only gorm.ErrRecordNotFound means "no duplicate". Any
|
||||
// other error is a real database problem, and treating it as "not found"
|
||||
// would both insert a duplicate and spend a paid Claude call to do it.
|
||||
var existing models.Rowing
|
||||
if err := store.DB.Where("date = ?", dateTaken).First(&existing).Error; err == nil {
|
||||
err = store.DB.Where("date = ?", dateTaken).First(&existing).Error
|
||||
switch {
|
||||
case err == nil:
|
||||
ctx.JSON(http.StatusConflict, gin.H{"error": "duplicate entry for this date"})
|
||||
return
|
||||
case !errors.Is(err, gorm.ErrRecordNotFound):
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
|
||||
// Build the message with an image + text prompt
|
||||
@@ -158,15 +168,10 @@ No text, no markdown, no explanation. Just the JSON object.`),
|
||||
}
|
||||
|
||||
// Strip a markdown code fence if the model wrapped its JSON in one
|
||||
// despite the prompt. Same defensive dance as in services/email_sync.go.
|
||||
// despite the prompt; shared with the email pipeline, which asks for bare
|
||||
// JSON in the same way and gets fenced output just as often.
|
||||
extractedData := ExtractedRowingData{}
|
||||
raw := message.Content[0].Text
|
||||
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "```json")
|
||||
raw = strings.TrimPrefix(raw, "```")
|
||||
raw = strings.TrimSuffix(raw, "```")
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw := services.StripMarkdownFence(message.Content[0].Text)
|
||||
|
||||
err = json.Unmarshal([]byte(raw), &extractedData)
|
||||
if err != nil {
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -22,6 +21,18 @@ import (
|
||||
// restart.
|
||||
func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
|
||||
state := ctx.Query("state")
|
||||
// CSRF check: the state must be a nonce this process handed out from
|
||||
// StartSpotifyAuth and has not seen come back yet. Without it, anyone who
|
||||
// could get the site owner's browser to hit this URL with an attacker's
|
||||
// authorisation code would bind the site to the attacker's Spotify
|
||||
// account. The library also compares the state to the value passed below,
|
||||
// but since that value is the one just received, this check is the real
|
||||
// one.
|
||||
if !store.ConsumeSpotifyState(state) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid state"})
|
||||
return
|
||||
}
|
||||
|
||||
// context.Background, not the request context: the client built below
|
||||
// outlives this request and would otherwise be cancelled when it ends.
|
||||
c := context.Background()
|
||||
@@ -50,6 +61,24 @@ func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// StartSpotifyAuth backs the admin-only GET /spotify/auth. It returns the
|
||||
// Spotify authorisation URL carrying a freshly minted one-shot state nonce,
|
||||
// which CompleteSpotifyAuth then verifies and consumes.
|
||||
//
|
||||
// This exists because the state has to be per-request to be a CSRF defence,
|
||||
// and the start of the flow therefore has to be a request rather than a line
|
||||
// printed at start-up.
|
||||
func (store *Store) StartSpotifyAuth(ctx *gin.Context) {
|
||||
state, err := store.NewSpotifyState()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"url": store.SpotifyAuth.AuthURL(state)})
|
||||
}
|
||||
|
||||
// ListeningTo backs GET /spotify/listening with the currently playing track.
|
||||
// A nil client means the OAuth flow has never been completed, reported here
|
||||
// as a 500.
|
||||
@@ -71,26 +100,16 @@ func (store *Store) ListeningTo(ctx *gin.Context) {
|
||||
ctx.JSON(200, playing)
|
||||
}
|
||||
|
||||
// RecentlyPlayed backs GET /spotify/recent.
|
||||
//
|
||||
// It reads the cache but never writes it: only the GraphQL spotifyRecent
|
||||
// resolver populates Store.RecentSongs. So this endpoint serves cached data
|
||||
// only when a GraphQL query happened to fill the cache in the last minute,
|
||||
// and otherwise calls Spotify every time.
|
||||
// RecentlyPlayed backs GET /spotify/recent, serving the shared one-minute
|
||||
// cache. Both this endpoint and the GraphQL spotifyRecent resolver go through
|
||||
// RecentlyPlayedTracks, so either one can fill the cache for the other.
|
||||
func (store *Store) RecentlyPlayed(ctx *gin.Context) {
|
||||
if store.SpotifyClient == nil {
|
||||
ctx.JSON(500, gin.H{"error": "Spotify not authenticated"})
|
||||
return
|
||||
}
|
||||
|
||||
opts := spotify.RecentlyPlayedOptions{Limit: 3}
|
||||
|
||||
if store.RecentSongsFresh() {
|
||||
ctx.JSON(200, *store.RecentSongs)
|
||||
return
|
||||
}
|
||||
|
||||
played, err := store.SpotifyClient.PlayerRecentlyPlayedOpt(ctx, &opts)
|
||||
played, err := store.RecentlyPlayedTracks(ctx)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(500, gin.H{"error": "failed to fetch recently played"})
|
||||
@@ -100,17 +119,23 @@ func (store *Store) RecentlyPlayed(ctx *gin.Context) {
|
||||
ctx.JSON(200, played)
|
||||
}
|
||||
|
||||
// RecentSongsFresh reports whether the cached recently-played list is within
|
||||
// its one-minute TTL. An empty list counts as stale, so an empty listening
|
||||
// history is re-fetched every time.
|
||||
func (s *Store) RecentSongsFresh() bool {
|
||||
if s.RecentSongs == nil {
|
||||
return false
|
||||
// RecentlyPlayedTracks returns the last few played tracks, from the cache when
|
||||
// it is fresh and from Spotify otherwise — populating the cache in that case.
|
||||
//
|
||||
// This is the single fetch-and-cache path for recently-played data; the caller
|
||||
// must have checked SpotifyClient is non-nil.
|
||||
func (store *Store) RecentlyPlayedTracks(ctx context.Context) ([]spotify.RecentlyPlayedItem, error) {
|
||||
if cached, ok := store.CachedRecentSongs(); ok {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
if len(*s.RecentSongs) == 0 {
|
||||
return false
|
||||
opts := spotify.RecentlyPlayedOptions{Limit: 3}
|
||||
played, err := store.SpotifyClient.PlayerRecentlyPlayedOpt(ctx, &opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return time.Since(s.RecentSongsFetchedAt) < time.Minute
|
||||
store.SetRecentSongs(played)
|
||||
|
||||
return played, nil
|
||||
}
|
||||
|
||||
+140
-19
@@ -1,6 +1,9 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
@@ -17,11 +20,11 @@ import (
|
||||
// Store is the backend's dependency container: it is built once in main and
|
||||
// passed around by pointer, so the caches on it are shared process-wide.
|
||||
//
|
||||
// Concurrency note: the cache fields below are read and written by concurrent
|
||||
// requests without a mutex. The races are benign in practice (worst case two
|
||||
// requests refresh the same third-party API at once, or one reads a value
|
||||
// being replaced), but this is a deliberate simplification, not an oversight
|
||||
// — do not add a field here that would be unsafe to tear.
|
||||
// Concurrency note: the third-party caches below are read and written by
|
||||
// concurrent requests, so every access goes through cacheMu and the accessor
|
||||
// methods at the bottom of this file. Do not touch the cache fields directly
|
||||
// — an unsynchronised read of one of them is a data race, not merely a stale
|
||||
// value.
|
||||
type Store struct {
|
||||
DB *gorm.DB
|
||||
SpotifyAuth *spotifyauth.Authenticator
|
||||
@@ -35,6 +38,12 @@ type Store struct {
|
||||
// Cached "recently played" tracks, refreshed at most once a minute by the
|
||||
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
|
||||
// mean "never fetched" distinctly from "fetched, empty".
|
||||
// cacheMu guards every cache field below (and only those). One mutex for
|
||||
// all of them keeps the locking obvious; the critical sections are just
|
||||
// field copies, never network calls, so there is no contention worth
|
||||
// splitting it up for.
|
||||
cacheMu sync.RWMutex
|
||||
|
||||
RecentSongs *[]spotify.RecentlyPlayedItem
|
||||
RecentSongsFetchedAt time.Time
|
||||
|
||||
@@ -50,25 +59,137 @@ type Store struct {
|
||||
SteamRecentGames []services.SteamRecentGame
|
||||
SteamOnline bool
|
||||
SteamFetchedAt time.Time
|
||||
|
||||
// spotifyStates holds the one-shot CSRF nonces handed out by
|
||||
// GET /spotify/auth, mapped to their creation time. In-memory is enough:
|
||||
// there is one backend instance, and losing them on restart only means
|
||||
// restarting an OAuth flow that takes seconds.
|
||||
spotifyStatesMu sync.Mutex
|
||||
spotifyStates map[string]time.Time
|
||||
}
|
||||
|
||||
// GiteaFeedFresh reports whether the cached Gitea feed entry is still within
|
||||
// its one-minute TTL. A nil cache is never fresh, so the first request always
|
||||
// hits Gitea.
|
||||
func (s *Store) GiteaFeedFresh() bool {
|
||||
if s.GiteaFeed == nil {
|
||||
return false
|
||||
// spotifyStateTTL is how long an unused Spotify OAuth nonce stays valid. Long
|
||||
// enough to log in at Spotify and approve the scopes, short enough that a
|
||||
// leaked authorisation URL is not reusable later.
|
||||
const spotifyStateTTL = 10 * time.Minute
|
||||
|
||||
// NewSpotifyState mints a one-shot CSRF nonce for the Spotify authorisation
|
||||
// URL and remembers it. Expired entries are pruned on the way through, which
|
||||
// is the only cleanup there is — the map is otherwise unbounded, and only an
|
||||
// admin can add to it.
|
||||
func (s *Store) NewSpotifyState() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return time.Since(s.GiteaFeedFetchedAt) < time.Minute
|
||||
state := hex.EncodeToString(b)
|
||||
|
||||
s.spotifyStatesMu.Lock()
|
||||
defer s.spotifyStatesMu.Unlock()
|
||||
if s.spotifyStates == nil {
|
||||
s.spotifyStates = make(map[string]time.Time)
|
||||
}
|
||||
for k, created := range s.spotifyStates {
|
||||
if time.Since(created) > spotifyStateTTL {
|
||||
delete(s.spotifyStates, k)
|
||||
}
|
||||
}
|
||||
s.spotifyStates[state] = time.Now()
|
||||
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// SteamFresh reports whether the cached Steam data is still within its
|
||||
// five-minute TTL. Note it tests only SteamRecentGames: if Steam legitimately
|
||||
// returns no recent games, the cache never registers as fresh and every
|
||||
// request re-queries the API.
|
||||
func (s *Store) SteamFresh() bool {
|
||||
if s.SteamRecentGames == nil {
|
||||
// ConsumeSpotifyState checks a nonce returned by Spotify's redirect and
|
||||
// removes it, so a replayed callback fails. An unknown or expired nonce
|
||||
// returns false, which the callback must treat as a rejected request.
|
||||
func (s *Store) ConsumeSpotifyState(state string) bool {
|
||||
if state == "" {
|
||||
return false
|
||||
}
|
||||
return time.Since(s.SteamFetchedAt) < 5*time.Minute
|
||||
|
||||
s.spotifyStatesMu.Lock()
|
||||
defer s.spotifyStatesMu.Unlock()
|
||||
created, ok := s.spotifyStates[state]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
delete(s.spotifyStates, state)
|
||||
|
||||
return time.Since(created) <= spotifyStateTTL
|
||||
}
|
||||
|
||||
// The cache accessors below are the only supported way to touch the cache
|
||||
// fields. Each "Cached..." method returns the value plus a bool that is true
|
||||
// only when the entry is present and inside its TTL; each "Set..." method
|
||||
// stores a value and stamps it.
|
||||
|
||||
// CachedRecentSongs returns the cached Spotify recently-played list if it is
|
||||
// within its one-minute TTL. An empty list counts as stale, so an empty
|
||||
// listening history is re-fetched every time (unchanged behaviour).
|
||||
func (s *Store) CachedRecentSongs() ([]spotify.RecentlyPlayedItem, bool) {
|
||||
s.cacheMu.RLock()
|
||||
defer s.cacheMu.RUnlock()
|
||||
|
||||
if s.RecentSongs == nil || len(*s.RecentSongs) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
if time.Since(s.RecentSongsFetchedAt) >= time.Minute {
|
||||
return nil, false
|
||||
}
|
||||
return *s.RecentSongs, true
|
||||
}
|
||||
|
||||
// SetRecentSongs replaces the cached recently-played list.
|
||||
func (s *Store) SetRecentSongs(songs []spotify.RecentlyPlayedItem) {
|
||||
s.cacheMu.Lock()
|
||||
defer s.cacheMu.Unlock()
|
||||
|
||||
s.RecentSongs = &songs
|
||||
s.RecentSongsFetchedAt = time.Now()
|
||||
}
|
||||
|
||||
// CachedGiteaFeed returns the cached Gitea activity entry if it is within its
|
||||
// one-minute TTL. A nil cache is never fresh, so the first request always hits
|
||||
// Gitea.
|
||||
func (s *Store) CachedGiteaFeed() (*services.GiteaFeedResponse, bool) {
|
||||
s.cacheMu.RLock()
|
||||
defer s.cacheMu.RUnlock()
|
||||
|
||||
if s.GiteaFeed == nil || time.Since(s.GiteaFeedFetchedAt) >= time.Minute {
|
||||
return nil, false
|
||||
}
|
||||
return s.GiteaFeed, true
|
||||
}
|
||||
|
||||
// SetGiteaFeed replaces the cached Gitea feed entry.
|
||||
func (s *Store) SetGiteaFeed(feed *services.GiteaFeedResponse) {
|
||||
s.cacheMu.Lock()
|
||||
defer s.cacheMu.Unlock()
|
||||
|
||||
s.GiteaFeed = feed
|
||||
s.GiteaFeedFetchedAt = time.Now()
|
||||
}
|
||||
|
||||
// CachedSteam returns the cached Steam recent games and online flag if they
|
||||
// are within their five-minute TTL. As before, freshness is judged only on the
|
||||
// games list: if Steam legitimately returns no recent games the cache never
|
||||
// registers as fresh and every request re-queries the API.
|
||||
func (s *Store) CachedSteam() (games []services.SteamRecentGame, online bool, ok bool) {
|
||||
s.cacheMu.RLock()
|
||||
defer s.cacheMu.RUnlock()
|
||||
|
||||
if s.SteamRecentGames == nil || time.Since(s.SteamFetchedAt) >= 5*time.Minute {
|
||||
return nil, false, false
|
||||
}
|
||||
return s.SteamRecentGames, s.SteamOnline, true
|
||||
}
|
||||
|
||||
// SetSteam replaces the cached Steam data.
|
||||
func (s *Store) SetSteam(games []services.SteamRecentGame, online bool) {
|
||||
s.cacheMu.Lock()
|
||||
defer s.cacheMu.Unlock()
|
||||
|
||||
s.SteamRecentGames = games
|
||||
s.SteamOnline = online
|
||||
s.SteamFetchedAt = time.Now()
|
||||
}
|
||||
|
||||
+14
-6
@@ -76,11 +76,12 @@ func main() {
|
||||
services.InitWebSocket(db, domainName)
|
||||
|
||||
// SPOTIFY
|
||||
spotifyAuthState := os.Getenv("SPOTIFY_AUTH_STATE")
|
||||
// No SPOTIFY_AUTH_STATE: the OAuth `state` is now a one-shot nonce minted
|
||||
// per authorisation request, so there is nothing to configure.
|
||||
spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI")
|
||||
spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID")
|
||||
spotifyClientSecret := os.Getenv("SPOTIFY_CLIENT_SECRET")
|
||||
spotifyConfig := services.SpotifyConfig{AuthState: spotifyAuthState, RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret}
|
||||
spotifyConfig := services.SpotifyConfig{RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret}
|
||||
spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig)
|
||||
|
||||
// CLAUDE
|
||||
@@ -163,7 +164,11 @@ func main() {
|
||||
admin.POST("/email/sync", store.TriggerEmailSync)
|
||||
|
||||
// SPOTIFY
|
||||
// The callback must be open — Spotify redirects a logged-out browser to
|
||||
// it — and is protected by the state nonce instead. Starting the flow is
|
||||
// admin-only, since that is what mints the nonce.
|
||||
r.GET("/spotify/callback", store.CompleteSpotifyAuth)
|
||||
admin.GET("/spotify/auth", store.StartSpotifyAuth)
|
||||
r.GET("/spotify/listening", store.ListeningTo)
|
||||
r.GET("/spotify/recent", store.RecentlyPlayed)
|
||||
// r.POST("/spotify", store.SendSong)
|
||||
@@ -212,7 +217,7 @@ func main() {
|
||||
// AuthContextMiddleware copies the Gin context and any verified claims
|
||||
// into the request context, which is what resolvers read. The closure is
|
||||
// needed because gqlgen speaks net/http, not gin.
|
||||
r.POST("/graphql", graph.AuthContextMiddleware(auth), func(c *gin.Context) {
|
||||
r.POST("/graphql", graph.AuthContextMiddleware(auth, db), func(c *gin.Context) {
|
||||
gqlSrv.ServeHTTP(c.Writer, c.Request)
|
||||
})
|
||||
if devMode && os.Getenv("GQL_PLAYGROUND") == "true" {
|
||||
@@ -234,7 +239,10 @@ func main() {
|
||||
go store.EmailSync.StartScheduler(ctx)
|
||||
|
||||
port := os.Getenv("BACKEND_PORT")
|
||||
// Blocks forever; its error is not checked, so a failure to bind the port
|
||||
// exits main silently with status 0.
|
||||
r.Run(fmt.Sprintf(":%s", port))
|
||||
// Blocks until the server stops. Any return is a failure — a port clash,
|
||||
// most often — so it must exit non-zero, or Docker sees a clean shutdown
|
||||
// and reports the container as having succeeded.
|
||||
if err := r.Run(fmt.Sprintf(":%s", port)); err != nil {
|
||||
log.Fatalf("http server stopped: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +38,19 @@ type User struct {
|
||||
// Admin gates almost every mutation. It is copied into the access token,
|
||||
// so a change here only takes effect on the user's next token refresh.
|
||||
Admin bool `json:"admin"`
|
||||
// TokenVersion is the session generation counter. Every issued JWT
|
||||
// carries the value current at the time it was minted, and
|
||||
// services.Auth rejects a token whose value no longer matches, so
|
||||
// incrementing this column revokes every outstanding token for the user
|
||||
// at once (logout, password change). It is the only server-side
|
||||
// revocation mechanism there is.
|
||||
//
|
||||
// Pre-migration rows: AutoMigrate adds the column with DEFAULT 1, but a
|
||||
// row that somehow ends up at 0 is normalised to 1 by
|
||||
// services.tokenVersionOf, as is a token minted before the "tv" claim
|
||||
// existed. So the migration invalidates nobody's existing session, and
|
||||
// the first bump moves a user to 2 and invalidates everything older.
|
||||
TokenVersion uint `gorm:"not null;default:1" json:"-"`
|
||||
}
|
||||
|
||||
// Post is a blog entry. Author is loaded with Preload("Author") by the post
|
||||
@@ -158,6 +171,21 @@ type ProcessedEmail struct {
|
||||
// The application this email created or updated, if any. A plain nullable
|
||||
// column, not a GORM association — nothing preloads it.
|
||||
JobAppID *uint `json:"jobAppId"`
|
||||
// Attempts counts how many times processing this email has been tried.
|
||||
// A row with Action "error" and Attempts below the cap is retryable: the
|
||||
// next sync re-processes it instead of skipping it. Once Attempts reaches
|
||||
// the cap the row becomes terminal, so a genuinely unprocessable email
|
||||
// (one Claude can never parse) eventually stops consuming API calls.
|
||||
// Rows written before this column existed default to 1 and so get their
|
||||
// remaining attempts.
|
||||
Attempts int `gorm:"not null;default:1" json:"attempts"`
|
||||
// ReceivedAt is the provider's own timestamp for the email, as distinct
|
||||
// from CreatedAt (when we processed it). It exists so a retryable failure
|
||||
// can pull the fetch window back far enough to actually re-fetch the
|
||||
// email: the window is otherwise anchored to processing time, which would
|
||||
// have already advanced past it. Zero for rows written before this
|
||||
// column existed, and for those the clamp is skipped.
|
||||
ReceivedAt time.Time `json:"receivedAt"`
|
||||
}
|
||||
|
||||
// Place is an entry on the places-to-go list. Creating or editing one needs
|
||||
|
||||
+160
-6
@@ -2,16 +2,23 @@ package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Auth mints and verifies the HS256 JWTs that back the site's login. Tokens
|
||||
// are handed to the browser as HTTP-only cookies (see handlers.Store.Login);
|
||||
// there is no server-side session or token blacklist, so a token stays valid
|
||||
// until it expires even after logout.
|
||||
// are handed to the browser as HTTP-only cookies (see handlers.Store.Login).
|
||||
//
|
||||
// There is no token blacklist, but there is coarse server-side revocation:
|
||||
// every token carries the user's models.User.TokenVersion in a "tv" claim,
|
||||
// and AuthenticateToken rejects a token whose version has moved on. Bumping
|
||||
// that column (BumpTokenVersion) therefore kills all of a user's outstanding
|
||||
// tokens at once — which is what logout and a password change do.
|
||||
type Auth struct {
|
||||
Config *AuthConfig
|
||||
}
|
||||
@@ -43,19 +50,26 @@ func InitAuth(config *AuthConfig) *Auth {
|
||||
//
|
||||
// The access token carries the authorisation data the API needs (id, admin)
|
||||
// so that most requests can be authorised without touching the database. The
|
||||
// refresh token deliberately carries only the id: admin status is re-read
|
||||
// from the database when refreshing, so revoking someone's admin flag takes
|
||||
// effect on their next refresh rather than only when they log in again.
|
||||
// refresh token deliberately carries only the id (plus the version): admin
|
||||
// status is re-read from the database when refreshing, so revoking someone's
|
||||
// admin flag takes effect on their next refresh rather than only when they
|
||||
// log in again.
|
||||
//
|
||||
// Both tokens carry "tv", the user's TokenVersion at minting time. Anything
|
||||
// that validates a token against the database checks it, so the pair dies the
|
||||
// moment the column is bumped.
|
||||
func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
|
||||
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"username": user.Username,
|
||||
"id": user.ID,
|
||||
"admin": user.Admin,
|
||||
"tv": tokenVersionOf(user.TokenVersion),
|
||||
"exp": time.Now().Add(auth.Config.AccessTokenLifetime).Unix(),
|
||||
})
|
||||
|
||||
refreshToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"id": user.ID,
|
||||
"tv": tokenVersionOf(user.TokenVersion),
|
||||
"exp": time.Now().Add(auth.Config.RefreshTokenLifetime).Unix(),
|
||||
})
|
||||
|
||||
@@ -99,3 +113,143 @@ func (auth *Auth) VerifyJWT(tokenStr string) (*jwt.MapClaims, error) {
|
||||
|
||||
return &claims, nil
|
||||
}
|
||||
|
||||
// Typed errors returned by AuthenticateToken so each call site can keep its
|
||||
// own response for each case — the REST and GraphQL entry points deliberately
|
||||
// answer differently (401 vs 500 vs 404-plus-cookie-clear).
|
||||
var (
|
||||
// ErrInvalidToken means the token is missing, malformed, expired or not
|
||||
// correctly signed.
|
||||
ErrInvalidToken = errors.New("invalid token")
|
||||
// ErrInvalidClaims means the token verified but its "id" claim is absent
|
||||
// or not a number — a server-side inconsistency, not a client error.
|
||||
ErrInvalidClaims = errors.New("invalid token claims")
|
||||
// ErrUserNotFound means the token named a user that no longer exists (or
|
||||
// has been soft deleted).
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
// ErrTokenRevoked means the token is otherwise valid but was minted
|
||||
// before the user's TokenVersion was bumped, i.e. logout or a password
|
||||
// change has invalidated it.
|
||||
ErrTokenRevoked = errors.New("token revoked")
|
||||
)
|
||||
|
||||
// tokenVersionOf normalises a stored or claimed token version.
|
||||
//
|
||||
// Zero means "unset": either a row that predates the token_version column, or
|
||||
// a token minted before the "tv" claim existed. Both are normalised to 1, the
|
||||
// column's default, so introducing versioning logs nobody out. The first
|
||||
// BumpTokenVersion moves a user to 2 and invalidates every older token.
|
||||
func tokenVersionOf(v uint) uint {
|
||||
if v == 0 {
|
||||
return 1
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// AuthenticateToken is the one place a token string is turned into a user: it
|
||||
// verifies the signature and expiry, reads the id claim, loads the row, and
|
||||
// checks the token version. Every caller that used to hand-roll this sequence
|
||||
// (handlers.Store.CheckToken, handlers.Store.RefreshToken,
|
||||
// handlers.Store.tryRefreshAndValidateAdmin and the GraphQL refreshToken
|
||||
// resolver) now goes through here, so the checks cannot drift apart.
|
||||
//
|
||||
// The returned error is always one of the sentinels above, wrapped or not, so
|
||||
// call sites can map each case onto whatever status code they already used.
|
||||
func (auth *Auth) AuthenticateToken(db *gorm.DB, tokenStr string) (*models.User, error) {
|
||||
user, _, err := auth.AuthenticateTokenWithClaims(db, tokenStr)
|
||||
return user, err
|
||||
}
|
||||
|
||||
// AuthenticateTokenWithClaims is AuthenticateToken plus the raw claims, for
|
||||
// the middlewares that go on to read claims the User struct does not carry
|
||||
// (notably "admin", which is authoritative from the token rather than the
|
||||
// row — see handlers.AdminMiddleware).
|
||||
//
|
||||
// Note this costs one primary-key SELECT per authenticated request. That is
|
||||
// the price of revocation: without loading the row there is no version to
|
||||
// compare against, and logout could not kill a live access token.
|
||||
func (auth *Auth) AuthenticateTokenWithClaims(db *gorm.DB, tokenStr string) (*models.User, *jwt.MapClaims, error) {
|
||||
claims, err := auth.VerifyJWT(tokenStr)
|
||||
if err != nil {
|
||||
return nil, nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
// Claims are decoded by encoding/json, so every number arrives as a
|
||||
// float64 regardless of the Go type it was signed from.
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
return nil, nil, ErrInvalidClaims
|
||||
}
|
||||
|
||||
// Pre-setting the primary key and calling First with no explicit
|
||||
// condition makes GORM look the row up by that key. Soft-deleted users
|
||||
// are excluded automatically, so a deleted account fails here.
|
||||
user := models.User{ID: uint(userIDF)}
|
||||
if err := db.First(&user).Error; err != nil {
|
||||
return nil, nil, ErrUserNotFound
|
||||
}
|
||||
|
||||
// A token with no "tv" claim reads as 0 and is normalised to 1, matching
|
||||
// an un-bumped user — see tokenVersionOf.
|
||||
claimedVersion, _ := (*claims)["tv"].(float64)
|
||||
if tokenVersionOf(uint(claimedVersion)) != tokenVersionOf(user.TokenVersion) {
|
||||
return nil, nil, ErrTokenRevoked
|
||||
}
|
||||
|
||||
return &user, claims, nil
|
||||
}
|
||||
|
||||
// BumpTokenVersion invalidates every token previously issued to userID by
|
||||
// incrementing the user's version counter. Callers treat a failure as
|
||||
// non-fatal (logout still clears the cookies), but it must be logged: a
|
||||
// silent failure here means a logout that did not actually revoke anything.
|
||||
//
|
||||
// COALESCE covers a pre-migration row sitting at 0 or NULL: it is treated as
|
||||
// 1, so the bump lands on 2 and invalidates tokens claiming either.
|
||||
func BumpTokenVersion(db *gorm.DB, userID uint) error {
|
||||
return db.Model(&models.User{}).
|
||||
Where("id = ?", userID).
|
||||
UpdateColumn("token_version", gorm.Expr("COALESCE(token_version, 1) + 1")).
|
||||
Error
|
||||
}
|
||||
|
||||
// SetAuthCookies writes the access/refresh cookie pair.
|
||||
//
|
||||
// It lives in services because both handlers and graph need it and handlers
|
||||
// cannot import graph (that would be an import cycle); keeping one copy is
|
||||
// what stops REST login and GraphQL login drifting apart.
|
||||
//
|
||||
// gin's SetCookie takes Secure and HttpOnly as its two trailing booleans, both
|
||||
// true here: the cookies never travel over plain HTTP and are invisible to
|
||||
// JavaScript. SameSite=Lax survives a top-level navigation back from an OAuth
|
||||
// provider while still blocking cross-site POSTs. Each cookie's max-age
|
||||
// mirrors the lifetime baked into the token itself, so the browser drops it at
|
||||
// roughly the moment it stops being accepted.
|
||||
func SetAuthCookies(gc *gin.Context, config *AuthConfig, tokens *Tokens) {
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
config.Domain,
|
||||
true, true,
|
||||
)
|
||||
}
|
||||
|
||||
// ClearAuthCookies expires both auth cookies. The max-age of -1 is what tells
|
||||
// the browser to delete them; path, domain and the Secure/HttpOnly flags must
|
||||
// match those used when setting them or the browser keeps the originals.
|
||||
func ClearAuthCookies(gc *gin.Context, config *AuthConfig) {
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie("access_token", "", -1, "/", config.Domain, true, true)
|
||||
gc.SetCookie("refresh_token", "", -1, "/", config.Domain, true, true)
|
||||
}
|
||||
|
||||
@@ -136,27 +136,35 @@ func (c *imapClient) readLiteral(size int) (string, error) {
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
// fetchPart is one FETCH response line plus the literal payload that followed
|
||||
// it, if any. Pairing them in the type removes the need for callers to walk an
|
||||
// interleaved slice and manually skip every second entry — the previous shape,
|
||||
// where a literal was simply the next element and a caller that forgot to
|
||||
// advance would parse message bytes as a protocol line.
|
||||
type fetchPart struct {
|
||||
Line string
|
||||
// Literal is the payload that followed Line, valid only when HasLiteral.
|
||||
Literal string
|
||||
HasLiteral bool
|
||||
}
|
||||
|
||||
// sendFetch sends a FETCH and collects its response, handling literals.
|
||||
//
|
||||
// The returned slice interleaves protocol lines with literal payloads: when a
|
||||
// line ends in "{N}" the next entry is the N bytes that followed it. The
|
||||
// caller (fetchEmailsIMAP) relies on that pairing.
|
||||
//
|
||||
// The literal is detected with LastIndex("{") plus a "}" suffix rather than a
|
||||
// real parse, so a line whose text merely ends in braces could be misread —
|
||||
// tolerable because only FETCH responses reach this code.
|
||||
func (c *imapClient) sendFetch(cmd string) ([]string, error) {
|
||||
func (c *imapClient) sendFetch(cmd string) ([]fetchPart, error) {
|
||||
tag := c.nextTag()
|
||||
_, err := fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var lines []string
|
||||
var parts []fetchPart
|
||||
for {
|
||||
line, err := c.readLine()
|
||||
if err != nil {
|
||||
return lines, err
|
||||
return parts, err
|
||||
}
|
||||
|
||||
// Check for literal marker {N} at end of line
|
||||
@@ -166,23 +174,22 @@ func (c *imapClient) sendFetch(cmd string) ([]string, error) {
|
||||
if _, err := fmt.Sscanf(sizeStr, "%d", &size); err == nil && size > 0 {
|
||||
literal, err := c.readLiteral(size)
|
||||
if err != nil {
|
||||
return lines, fmt.Errorf("reading literal of %d bytes: %w", size, err)
|
||||
return parts, fmt.Errorf("reading literal of %d bytes: %w", size, err)
|
||||
}
|
||||
lines = append(lines, line)
|
||||
lines = append(lines, literal)
|
||||
parts = append(parts, fetchPart{Line: line, Literal: literal, HasLiteral: true})
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if strings.HasPrefix(line, tag+" ") {
|
||||
// Check for OK
|
||||
parts := strings.SplitN(line, " ", 3)
|
||||
if len(parts) >= 2 && parts[1] != "OK" {
|
||||
return lines, fmt.Errorf("FETCH failed: %s", line)
|
||||
fields := strings.SplitN(line, " ", 3)
|
||||
if len(fields) >= 2 && fields[1] != "OK" {
|
||||
return parts, fmt.Errorf("FETCH failed: %s", line)
|
||||
}
|
||||
return lines, nil
|
||||
return parts, nil
|
||||
}
|
||||
lines = append(lines, line)
|
||||
parts = append(parts, fetchPart{Line: line})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,33 +252,24 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err
|
||||
// sequence set, and each full body is held in memory. A mailbox with a
|
||||
// very busy day could make this large — there is no batching.
|
||||
seqSet := strings.Join(seqNums, ",")
|
||||
fetchLines, err := c.sendFetch(fmt.Sprintf("FETCH %s (BODY[])", seqSet))
|
||||
fetchParts, err := c.sendFetch(fmt.Sprintf("FETCH %s (BODY[])", seqSet))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP fetch: %w", err)
|
||||
}
|
||||
|
||||
// Pair each "... BODY[] {N}" header line with the literal that sendFetch
|
||||
// stored immediately after it. A message that fails to parse is logged and
|
||||
// skipped rather than failing the whole sync.
|
||||
// Each body arrives as a "... BODY[] {N}" line carrying its literal, so
|
||||
// the pairing is now part of the value rather than something this loop has
|
||||
// to reconstruct by skipping entries. A message that fails to parse is
|
||||
// logged and skipped rather than failing the whole sync.
|
||||
var messages []graphMessage
|
||||
for i := 0; i < len(fetchLines); i++ {
|
||||
line := fetchLines[i]
|
||||
// Look for a literal following this line
|
||||
if strings.Contains(line, "BODY[]") && strings.HasSuffix(line, "}") {
|
||||
if i+1 < len(fetchLines) {
|
||||
raw := fetchLines[i+1]
|
||||
// Advance past the literal so its contents are never
|
||||
// examined as a protocol line. Note this is a C-style loop
|
||||
// precisely so i can be advanced here; a range loop could
|
||||
// not do it.
|
||||
i++
|
||||
gm, err := parseRawEmail(raw)
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync/IMAP] Error parsing email: %v", err)
|
||||
continue
|
||||
}
|
||||
messages = append(messages, gm)
|
||||
for _, part := range fetchParts {
|
||||
if part.HasLiteral && strings.Contains(part.Line, "BODY[]") {
|
||||
gm, err := parseRawEmail(part.Literal)
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync/IMAP] Error parsing email: %v", err)
|
||||
continue
|
||||
}
|
||||
messages = append(messages, gm)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+126
-28
@@ -406,6 +406,21 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
since = latest.CreatedAt
|
||||
}
|
||||
|
||||
// Pull the window back to cover any still-retryable failure. Without this
|
||||
// the clamp above would have advanced past a failed email — the error row
|
||||
// is written now, so the next window starts after it — and the retry
|
||||
// below could never see the email again. Rows predating ReceivedAt have
|
||||
// a zero value and are ignored rather than dragging the window to 0001.
|
||||
var oldestRetryable models.ProcessedEmail
|
||||
if err := s.DB.
|
||||
Where("action = ? AND attempts < ? AND received_at > ?", "error", maxEmailAttempts, time.Time{}).
|
||||
Order("received_at ASC").
|
||||
First(&oldestRetryable).Error; err == nil && oldestRetryable.ReceivedAt.Before(since) {
|
||||
log.Printf("[EmailSync] Rewinding window to %s to retry a previous failure",
|
||||
oldestRetryable.ReceivedAt.Format(time.RFC3339))
|
||||
since = oldestRetryable.ReceivedAt
|
||||
}
|
||||
|
||||
// Fetch emails from Microsoft Graph
|
||||
emails, err := s.fetchEmails(ctx, since)
|
||||
if err != nil {
|
||||
@@ -421,36 +436,50 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
var created, updated, skipped, errored int
|
||||
|
||||
for _, email := range filtered {
|
||||
// Dedup check
|
||||
// Dedup check. A row is terminal — and so genuinely skippable — if it
|
||||
// succeeded, or if it failed the maximum number of times. A row that
|
||||
// failed but has attempts left is deliberately NOT skipped: it is
|
||||
// reprocessed below and the same row updated, so a transient Claude
|
||||
// or network outage no longer drops the email permanently.
|
||||
var existing models.ProcessedEmail
|
||||
if err := s.DB.Where("graph_message_id = ?", email.ID).First(&existing).Error; err == nil {
|
||||
found := s.DB.Where("graph_message_id = ?", email.ID).First(&existing).Error == nil
|
||||
if found && !retryableFailure(&existing) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
// A failed email is still recorded (with action "error") so the next
|
||||
// sync skips it rather than retrying — and, importantly, so it does
|
||||
// not hold the window open. The trade-off is that a transient Claude
|
||||
// outage permanently drops those emails.
|
||||
action, jobAppID, processErr := s.processEmail(ctx, email)
|
||||
if processErr != nil {
|
||||
log.Printf("[EmailSync] Error processing email %q: %v", email.Subject, processErr)
|
||||
s.DB.Create(&models.ProcessedEmail{
|
||||
GraphMessageID: email.ID,
|
||||
Subject: truncate(email.Subject, 255),
|
||||
Action: "error",
|
||||
})
|
||||
errored++
|
||||
continue
|
||||
if found {
|
||||
log.Printf("[EmailSync] Retrying previously failed email %q (attempt %d of %d)",
|
||||
email.Subject, existing.Attempts+1, maxEmailAttempts)
|
||||
}
|
||||
|
||||
// Record as processed
|
||||
s.DB.Create(&models.ProcessedEmail{
|
||||
action, jobAppID, processErr := s.processEmail(ctx, email)
|
||||
|
||||
// The row carries the outcome either way. On failure the attempt
|
||||
// counter advances, so repeated failures walk the row towards the cap
|
||||
// and it eventually stops being retried.
|
||||
record := models.ProcessedEmail{
|
||||
GraphMessageID: email.ID,
|
||||
Subject: truncate(email.Subject, 255),
|
||||
Action: action,
|
||||
JobAppID: jobAppID,
|
||||
})
|
||||
ReceivedAt: parseReceivedAt(email.ReceivedDateTime),
|
||||
Attempts: existing.Attempts + 1,
|
||||
}
|
||||
|
||||
if processErr != nil {
|
||||
log.Printf("[EmailSync] Error processing email %q: %v", email.Subject, processErr)
|
||||
record.Action = "error"
|
||||
record.JobAppID = nil
|
||||
if record.Attempts >= maxEmailAttempts {
|
||||
log.Printf("[EmailSync] Email %q has failed %d times; giving up on it",
|
||||
email.Subject, record.Attempts)
|
||||
}
|
||||
s.saveProcessed(found, &existing, &record)
|
||||
errored++
|
||||
continue
|
||||
}
|
||||
|
||||
s.saveProcessed(found, &existing, &record)
|
||||
|
||||
switch action {
|
||||
case "created":
|
||||
@@ -597,14 +626,8 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
|
||||
|
||||
// Only the first content block is read, and the prompt asks for bare JSON,
|
||||
// but models still wrap output in a markdown fence often enough that it is
|
||||
// stripped defensively here. The two TrimPrefix calls are ordered so that
|
||||
// "```json" is removed first and a plain "```" otherwise.
|
||||
raw := message.Content[0].Text
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "```json")
|
||||
raw = strings.TrimPrefix(raw, "```")
|
||||
raw = strings.TrimSuffix(raw, "```")
|
||||
raw = strings.TrimSpace(raw)
|
||||
// stripped defensively here.
|
||||
raw := StripMarkdownFence(message.Content[0].Text)
|
||||
|
||||
var analysis EmailAnalysis
|
||||
if err := json.Unmarshal([]byte(raw), &analysis); err != nil {
|
||||
@@ -804,3 +827,78 @@ Return ONLY a JSON object with these exact keys:
|
||||
- "notes": string or null - brief summary of what this email communicates (e.g. "Interview scheduled for March 15", "Application confirmed via Greenhouse")
|
||||
|
||||
If isJobEmail is false, only include that field. No text, no markdown, no explanation. Just the JSON object.`
|
||||
|
||||
// StripMarkdownFence removes a surrounding markdown code fence from a model's
|
||||
// response, so text that should have been bare JSON can be unmarshalled
|
||||
// whether or not the model wrapped it.
|
||||
//
|
||||
// The two TrimPrefix calls are ordered so that "```json" is removed first and
|
||||
// a plain "```" otherwise. It is deliberately forgiving: unfenced input is
|
||||
// returned unchanged apart from surrounding whitespace.
|
||||
//
|
||||
// Shared with handlers.CreateRowing, which prompts for bare JSON in the same
|
||||
// way and gets the same fenced output.
|
||||
func StripMarkdownFence(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "```json")
|
||||
raw = strings.TrimPrefix(raw, "```")
|
||||
raw = strings.TrimSuffix(raw, "```")
|
||||
|
||||
return strings.TrimSpace(raw)
|
||||
}
|
||||
|
||||
// maxEmailAttempts caps how many times a failing email is reprocessed. Each
|
||||
// attempt costs a Claude call, so the cap is what stops one permanently
|
||||
// unparseable email billing on every sync forever. Three gives a transient
|
||||
// outage two further chances across subsequent syncs.
|
||||
const maxEmailAttempts = 3
|
||||
|
||||
// retryableFailure reports whether a previously recorded email should be
|
||||
// processed again. Only failures are retried, and only while they have
|
||||
// attempts left; anything that succeeded is terminal.
|
||||
func retryableFailure(row *models.ProcessedEmail) bool {
|
||||
return row.Action == "error" && row.Attempts < maxEmailAttempts
|
||||
}
|
||||
|
||||
// parseReceivedAt converts the provider's timestamp to a time.Time, returning
|
||||
// the zero value if it is missing or malformed. A zero value is safe: it only
|
||||
// means this row cannot pull the fetch window back, so the email is retried
|
||||
// on the next sync that happens to cover it rather than being chased.
|
||||
func parseReceivedAt(raw string) time.Time {
|
||||
if raw == "" {
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
received, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync] Unparseable receivedDateTime %q: %v", raw, err)
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
return received
|
||||
}
|
||||
|
||||
// saveProcessed writes the outcome of an attempt: updating the existing row
|
||||
// when this was a retry, inserting when it is the first attempt. Update is
|
||||
// used rather than Save so the row keeps its original CreatedAt, which the
|
||||
// fetch window depends on.
|
||||
func (s *EmailSyncService) saveProcessed(found bool, existing, record *models.ProcessedEmail) {
|
||||
var err error
|
||||
if found {
|
||||
err = s.DB.Model(existing).Updates(map[string]any{
|
||||
"action": record.Action,
|
||||
"job_app_id": record.JobAppID,
|
||||
"attempts": record.Attempts,
|
||||
"received_at": record.ReceivedAt,
|
||||
}).Error
|
||||
} else {
|
||||
err = s.DB.Create(record).Error
|
||||
}
|
||||
|
||||
// Logged rather than returned: a bookkeeping failure must not abort the
|
||||
// rest of the batch. It does mean the email is reprocessed next sync,
|
||||
// which the dedup treats as a first attempt.
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync] Failed to record processed email %q: %v", record.Subject, err)
|
||||
}
|
||||
}
|
||||
|
||||
+13
-13
@@ -13,12 +13,12 @@ import (
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// SpotifyConfig holds the OAuth app credentials. AuthState is the fixed
|
||||
// `state` value used in the authorisation URL; because the flow is only ever
|
||||
// driven by hand by the site owner, it is a constant rather than a
|
||||
// per-request nonce.
|
||||
// SpotifyConfig holds the OAuth app credentials.
|
||||
//
|
||||
// There is no state value here any more: the `state` parameter is a one-shot
|
||||
// CSRF nonce minted per authorisation request by handlers.Store, so a fixed
|
||||
// configured value would defeat the point.
|
||||
type SpotifyConfig struct {
|
||||
AuthState string
|
||||
RedirectURL string
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
@@ -93,10 +93,12 @@ func LoadSpotifyToken(path string) (*oauth2.Token, error) {
|
||||
// exists, an authenticated client.
|
||||
//
|
||||
// Start-up never fails on Spotify problems: when there is no token or the
|
||||
// refresh is rejected it prints the authorisation URL to the container log
|
||||
// and returns a nil client. Every Spotify handler and resolver therefore has
|
||||
// to nil-check Store.SpotifyClient. Visiting that URL sends the browser to
|
||||
// /spotify/callback, which fills the client in at runtime.
|
||||
// refresh is rejected it logs how to authenticate and returns a nil client.
|
||||
// Every Spotify handler and resolver therefore has to nil-check
|
||||
// Store.SpotifyClient. The authorisation URL can no longer be printed here
|
||||
// because its state nonce is per-request (see handlers.Store.StartSpotifyAuth);
|
||||
// following it sends the browser to /spotify/callback, which fills the client
|
||||
// in at runtime.
|
||||
func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotify.Client) {
|
||||
auth := spotifyauth.New(
|
||||
spotifyauth.WithRedirectURL(config.RedirectURL),
|
||||
@@ -112,16 +114,14 @@ func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotif
|
||||
// check if token exists locally
|
||||
token, err := LoadSpotifyToken(SPOTIFY_TOKEN_JSON_PATH)
|
||||
if err != nil || token == nil {
|
||||
fmt.Println("No token saved. Authenticate Spotify with:")
|
||||
fmt.Println(auth.AuthURL(config.AuthState))
|
||||
fmt.Println("No Spotify token saved. Authenticate by calling GET /api/spotify/auth as an admin and opening the URL it returns.")
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
// refresh token and client
|
||||
client, err := RefreshClient(auth, token)
|
||||
if err != nil {
|
||||
fmt.Println("Failed to refresh token. Authenticate Spotify with:")
|
||||
fmt.Println(auth.AuthURL(config.AuthState))
|
||||
fmt.Println("Failed to refresh Spotify token. Re-authenticate by calling GET /api/spotify/auth as an admin and opening the URL it returns.")
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
|
||||
+25
-13
@@ -32,15 +32,20 @@
|
||||
# it just means the renewal window is checked twice a day rather than once a
|
||||
# month. Certificates are valid 90 days, so a renewal lands ~day 60.
|
||||
#
|
||||
# IMPORTANT CAVEAT: there is NO --deploy-hook here, and this container cannot
|
||||
# signal nginx (no docker socket, no shared PID namespace). nginx loads the
|
||||
# certificate files at startup and keeps them in memory, so a freshly renewed
|
||||
# certificate is NOT picked up until nginx is reloaded or restarted. In
|
||||
# practice the site is redeployed often enough (the Gitea Actions deploy
|
||||
# workflow runs `docker compose up -d --build` on every push to main, which
|
||||
# recreates nginx) that this has not bitten — but on a quiet month it could.
|
||||
# See DEPLOYMENT.md "Renew certificates" for the manual reload, and the
|
||||
# proposal to add a reload hook.
|
||||
# nginx loads the certificate files at startup and keeps them in memory, so a
|
||||
# renewed certificate is not served until nginx is reloaded. This container
|
||||
# cannot signal nginx directly (no docker socket, no shared PID namespace),
|
||||
# so --deploy-hook instead TOUCHES A SENTINEL FILE in /etc/letsencrypt, which
|
||||
# is bind-mounted read-write into BOTH containers. A background watcher in
|
||||
# nginx/entrypoint.sh polls for that file, deletes it and runs `nginx -s
|
||||
# reload`. certbot only fires a deploy hook when a certificate was actually
|
||||
# renewed, so the sentinel appears roughly once every 60 days, not twice a
|
||||
# day. --deploy-hook is passed to both `certonly` and `renew`.
|
||||
#
|
||||
# The alternative — giving this container the docker socket so the hook could
|
||||
# `docker exec nginx nginx -s reload` — was rejected: the socket is
|
||||
# root-equivalent on the host, and the shared cert directory is a capability
|
||||
# both containers already have.
|
||||
#
|
||||
# ENV VARS REQUIRED (from ./.env via `env_file`)
|
||||
# DOMAIN apex domain; both $DOMAIN and www.$DOMAIN go on one certificate,
|
||||
@@ -61,16 +66,23 @@
|
||||
# Port 80 reachable from the public internet for $DOMAIN and www.$DOMAIN.
|
||||
# =============================================================================
|
||||
|
||||
# The reload sentinel: a file in the SHARED /etc/letsencrypt mount that nginx's
|
||||
# entrypoint polls for. Touching it is the entire "tell nginx to reload" signal
|
||||
# — see RELOAD SIGNAL above.
|
||||
RELOAD_SENTINEL=/etc/letsencrypt/.nginx-reload
|
||||
|
||||
certbot certonly --webroot -w /var/www/certbot \
|
||||
--email ${EMAIL} \
|
||||
-d ${DOMAIN} -d www.${DOMAIN} \
|
||||
--cert-name ${DOMAIN} \
|
||||
--email "${EMAIL}" \
|
||||
-d "${DOMAIN}" -d "www.${DOMAIN}" \
|
||||
--cert-name "${DOMAIN}" \
|
||||
--deploy-hook "touch ${RELOAD_SENTINEL}" \
|
||||
--agree-tos --non-interactive --expand;
|
||||
|
||||
# Exit promptly on `docker compose stop` instead of sitting out the 12h sleep.
|
||||
trap exit TERM;
|
||||
|
||||
while :; do
|
||||
certbot renew --webroot -w /var/www/certbot;
|
||||
certbot renew --webroot -w /var/www/certbot \
|
||||
--deploy-hook "touch ${RELOAD_SENTINEL}";
|
||||
sleep 12h;
|
||||
done
|
||||
|
||||
+39
-3
@@ -154,8 +154,17 @@ services:
|
||||
dockerfile: Dockerfile
|
||||
container_name: "${BACKEND_HOST}"
|
||||
restart: always
|
||||
# MAP form, not the list form used elsewhere: this waits for db's
|
||||
# healthcheck to pass, not merely for its container to start. Without it
|
||||
# the Go process raced Postgres on every boot, failed its first connection,
|
||||
# died, and relied on `restart: always` to try again — noisy log churn and
|
||||
# a slower cold start in practice.
|
||||
# `restart: always` is deliberately KEPT as the backstop: if db's health
|
||||
# probe were ever to stall past compose's patience, or the DB dropped out
|
||||
# later, the restart policy still recovers the backend.
|
||||
depends_on:
|
||||
- db
|
||||
db:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- app-network
|
||||
env_file:
|
||||
@@ -191,10 +200,17 @@ services:
|
||||
# AUTOHEAL_CONTAINER_LABEL=all means "watch every container that defines a
|
||||
# healthcheck" (i.e. backend and python) rather than only labelled ones.
|
||||
# It mounts the docker socket, which is effectively root on the host — that
|
||||
# is the price of the feature; keep the image pinned-ish and trusted.
|
||||
# is the price of the feature. Because of that the image is pinned BY DIGEST,
|
||||
# not by a floating tag: `:latest` meant any future push to Docker Hub would
|
||||
# silently gain root on the Pi at the next `docker compose pull`/`up`. The
|
||||
# digest below is a multi-arch index (it includes linux/arm64, which is what
|
||||
# the Pi pulls) and was the content of `willfarrell/autoheal:latest` at the
|
||||
# time of pinning. To bump it: pull the new tag, `docker image inspect
|
||||
# willfarrell/autoheal:<tag> --format '{{index .RepoDigests 0}}'`, and paste
|
||||
# the digest here — never go back to a bare tag.
|
||||
# Deliberately NOT on app-network: it talks only to the socket.
|
||||
autoheal:
|
||||
image: willfarrell/autoheal:latest
|
||||
image: willfarrell/autoheal@sha256:4ce976e9033b41426d44633295d6a08f9bc5929b27866352d91b31d4f6b26447
|
||||
container_name: autoheal
|
||||
restart: always
|
||||
environment:
|
||||
@@ -220,6 +236,26 @@ services:
|
||||
- app-network
|
||||
volumes:
|
||||
- dbdata:/var/lib/postgresql/data
|
||||
# Postgres is the one dependency the backend genuinely cannot start
|
||||
# without, so `backend` gates on this healthcheck (condition:
|
||||
# service_healthy) instead of on mere container start.
|
||||
# TUNED FOR SLOW ARM HARDWARE: on a Raspberry Pi with a cold page cache a
|
||||
# first-boot Postgres can take well over a minute to finish initdb/recovery
|
||||
# and accept connections. start_period is the grace window during which a
|
||||
# failing probe does NOT count against `retries` and does NOT mark the
|
||||
# container unhealthy, so 90s costs nothing on a warm boot and prevents a
|
||||
# false "unhealthy" on a cold one. After that, 10 retries at 10s gives
|
||||
# another ~100s before anything gives up. `pg_isready -U $POSTGRES_USER`
|
||||
# is the cheapest real readiness probe (it does a protocol-level connect,
|
||||
# not just a TCP open). Note $$POSTGRES_USER: the doubled $ escapes
|
||||
# compose's own interpolation so the variable is expanded by the shell
|
||||
# INSIDE the container, from env_file, at probe time.
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\" -q"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
start_period: 90s
|
||||
|
||||
# Admin-only DB browser, reached at /hasura/. Console and dev mode are OFF in
|
||||
# production (turned on by the dev override). It is additionally gated in
|
||||
|
||||
+7
-2
@@ -19,8 +19,9 @@
|
||||
#
|
||||
# apt lists are deleted in the SAME RUN layer so they never end up in the image.
|
||||
#
|
||||
# NO nginx.conf IS COPIED IN. All three templates are, and entrypoint.sh picks
|
||||
# one at container start. See nginx/entrypoint.sh for that decision.
|
||||
# NO nginx.conf IS COPIED IN. All three templates (plus the dev partial) are,
|
||||
# and entrypoint.sh picks one at container start. See nginx/entrypoint.sh for
|
||||
# that decision.
|
||||
# =============================================================================
|
||||
FROM nginx:1.27
|
||||
RUN rm -rf /etc/nginx/html/* && \
|
||||
@@ -29,5 +30,9 @@ RUN rm -rf /etc/nginx/html/* && \
|
||||
COPY nginx.conf.template /etc/nginx/nginx.conf.template
|
||||
COPY nginx_setup.conf.template /etc/nginx/nginx_setup.conf.template
|
||||
COPY nginx_dev.conf.template /etc/nginx/nginx_dev.conf.template
|
||||
# Shared body of the dev :80 and :443 server blocks. entrypoint.sh renders it
|
||||
# (same envsubst allow-list) to /etc/nginx/nginx_dev_common.conf, which is the
|
||||
# path both `include` directives in nginx_dev.conf.template point at.
|
||||
COPY nginx_dev_common.conf.template /etc/nginx/nginx_dev_common.conf.template
|
||||
COPY entrypoint.sh /entrypoint.sh
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
|
||||
+101
-11
@@ -1,11 +1,15 @@
|
||||
#!/bin/sh
|
||||
# =============================================================================
|
||||
# nginx entrypoint — picks one of three nginx configs at container start.
|
||||
# nginx entrypoint — picks one of three nginx configs at container start, then
|
||||
# watches for certificate changes and reloads nginx in place.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# nginx.conf is not shipped in the image. Instead three *templates* are baked
|
||||
# in (see nginx/Dockerfile) and this script renders exactly one of them to
|
||||
# /etc/nginx/nginx.conf before starting nginx in the foreground.
|
||||
# /etc/nginx/nginx.conf before starting nginx in the foreground. In dev it
|
||||
# also renders the shared server-block partial the dev template includes.
|
||||
# After nginx starts, a background watcher handles certificates appearing or
|
||||
# being renewed — see CERTIFICATE WATCHER at the bottom of this file.
|
||||
#
|
||||
# WHEN IT RUNS
|
||||
# Every time the `nginx` container starts (ENTRYPOINT). It is therefore also
|
||||
@@ -37,10 +41,11 @@
|
||||
# a. nginx starts with nginx_setup.conf (port 80, ACME webroot only).
|
||||
# b. certbot container runs `certbot certonly --webroot`, writes the cert
|
||||
# into the shared ./certbot/conf volume.
|
||||
# c. nginx is restarted (manually, or by a redeploy) — this script re-runs,
|
||||
# now finds the cert, and renders the production config.
|
||||
# Step (c) is NOT automatic. A first deploy on a new domain needs one manual
|
||||
# `docker compose restart nginx` after certbot succeeds.
|
||||
# c. the background certificate watcher in this script notices the cert
|
||||
# file appear (within CERT_WATCH_INTERVAL, default 60s), re-renders the
|
||||
# production config, validates it and reloads nginx in place.
|
||||
# Step (c) IS automatic now. A first deploy on a new domain no longer needs a
|
||||
# manual `docker compose restart nginx`; a restart remains a valid fallback.
|
||||
#
|
||||
# THE envsubst TEMPLATING PATTERN
|
||||
# The templates are plain nginx configs containing $VARIABLES. Two different
|
||||
@@ -65,10 +70,9 @@
|
||||
# HASURA_HOST / HASURA_PORT Hasura console upstream
|
||||
# QUARTZ_HOST / QUARTZ_PORT notes site upstream
|
||||
# PYTHON_HOST / PYTHON_PORT FastAPI upstream (defaulted below)
|
||||
# UPTIMEKUMA_* / WALLABAG_* substituted but not currently referenced by
|
||||
# any template; kept so adding those services
|
||||
# back needs no entrypoint change.
|
||||
# DEV_MODE "true" only via docker-compose.dev.yml
|
||||
# CERT_WATCH_INTERVAL optional, seconds between certificate-watch
|
||||
# polls (default 60). Production only.
|
||||
#
|
||||
# ASSUMES EXISTS
|
||||
# /etc/letsencrypt (bind mount of ./certbot/conf, shared with certbot)
|
||||
@@ -86,7 +90,7 @@ export PYTHON_PORT="${PYTHON_PORT:-8000}"
|
||||
# The envsubst allow-list, defined once and reused by both full-config branches
|
||||
# so the two lists cannot drift apart. It MUST stay single-quoted here and be
|
||||
# passed as "$ENVSUBST_VARS" (one argument) below.
|
||||
ENVSUBST_VARS='${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${HASURA_HOST} ${HASURA_PORT} ${QUARTZ_HOST} ${QUARTZ_PORT} ${UPTIMEKUMA_HOST} ${UPTIMEKUMA_PORT} ${WALLABAG_HOST} ${WALLABAG_PORT} ${PYTHON_HOST} ${PYTHON_PORT}'
|
||||
ENVSUBST_VARS='${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${HASURA_HOST} ${HASURA_PORT} ${QUARTZ_HOST} ${QUARTZ_PORT} ${PYTHON_HOST} ${PYTHON_PORT}'
|
||||
|
||||
# Check if DEV_MODE
|
||||
if [ "$DEV_MODE" = "true" ]; then
|
||||
@@ -101,21 +105,29 @@ if [ "$DEV_MODE" = "true" ]; then
|
||||
-out "$CERT_DIR/fullchain.pem" \
|
||||
-subj "/CN=localhost" 2>/dev/null
|
||||
fi
|
||||
# In dev mode, so use nginx_dev.conf.template
|
||||
# In dev mode, so use nginx_dev.conf.template. Its two server blocks both
|
||||
# `include /etc/nginx/nginx_dev_common.conf`, so the shared partial has to be
|
||||
# rendered through the SAME allow-list, into exactly that path, first.
|
||||
envsubst "$ENVSUBST_VARS" \
|
||||
</etc/nginx/nginx_dev_common.conf.template \
|
||||
>/etc/nginx/nginx_dev_common.conf
|
||||
envsubst "$ENVSUBST_VARS" \
|
||||
</etc/nginx/nginx_dev.conf.template \
|
||||
>/etc/nginx/nginx.conf
|
||||
CONFIG_MODE=dev
|
||||
elif [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ] && [ -f "/etc/letsencrypt/live/$DOMAIN/privkey.pem" ]; then
|
||||
echo "Certificates found. Using production nginx config."
|
||||
# In production with certificates already existing, so use nginx.conf.template
|
||||
envsubst "$ENVSUBST_VARS" \
|
||||
</etc/nginx/nginx.conf.template \
|
||||
>/etc/nginx/nginx.conf
|
||||
CONFIG_MODE=prod
|
||||
else
|
||||
echo "Certificates NOT found. Using setup nginx config."
|
||||
# In production with no certificates, so use nginx_setup.conf.template and will need restart after generation
|
||||
# Only ${DOMAIN} is substituted: the setup config has no upstreams at all.
|
||||
envsubst '${DOMAIN}' </etc/nginx/nginx_setup.conf.template >/etc/nginx/nginx.conf
|
||||
CONFIG_MODE=setup
|
||||
fi
|
||||
|
||||
# Ensure upload directory is traversable by nginx worker.
|
||||
@@ -148,5 +160,83 @@ if [ "$DEV_MODE" != "true" ]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
# =============================================================================
|
||||
# CERTIFICATE WATCHER (production only)
|
||||
#
|
||||
# Solves two long-standing manual steps:
|
||||
# 1. FIRST ISSUANCE. If we booted with the bootstrap config (CONFIG_MODE=
|
||||
# setup) because no certificate existed yet, the watcher notices the
|
||||
# certificate appearing, re-renders the production template and reloads
|
||||
# nginx in place. No `docker compose restart nginx` is needed any more.
|
||||
# 2. RENEWAL. nginx reads the certificate files once at startup and keeps
|
||||
# them in memory, so a renewed cert is not served until a reload.
|
||||
# certbot/entrypoint.sh passes --deploy-hook, which touches a sentinel
|
||||
# file in the SHARED /etc/letsencrypt mount on every successful renewal.
|
||||
# The watcher sees the sentinel, deletes it, and reloads.
|
||||
#
|
||||
# WHY A SENTINEL FILE AND NOT THE DOCKER SOCKET
|
||||
# The obvious alternative is to mount /var/run/docker.sock into certbot and
|
||||
# have the deploy hook run `docker exec nginx nginx -s reload`. That works,
|
||||
# but the docker socket is root-equivalent on the host, and it would hand
|
||||
# that to a container whose whole job is talking to the public internet.
|
||||
# Both containers ALREADY share ./certbot/conf read-write, so a touched file
|
||||
# in that directory is a capability they already have and grants nothing new.
|
||||
# Cost: a reload lands up to $CERT_WATCH_INTERVAL late (default 60s), which
|
||||
# is irrelevant for a cert renewed 30 days before expiry.
|
||||
#
|
||||
# FAIL-SAFE DESIGN
|
||||
# The watcher NEVER overwrites a working /etc/nginx/nginx.conf with an
|
||||
# untested one: it renders to a temp file, runs `nginx -t -c` on it, and only
|
||||
# installs + reloads if that passes. A reload that would fail is skipped, and
|
||||
# the currently-running nginx keeps serving. `set +e` inside the watcher so a
|
||||
# transient failure cannot kill the loop (and the loop is a background job,
|
||||
# so it can never take nginx down with it).
|
||||
# =============================================================================
|
||||
RELOAD_SENTINEL=/etc/letsencrypt/.nginx-reload
|
||||
CERT_WATCH_INTERVAL="${CERT_WATCH_INTERVAL:-60}"
|
||||
|
||||
# Render the production template to a temp file, validate it, and only then
|
||||
# install it. Returns non-zero (installing nothing) if either step fails.
|
||||
render_prod_config() {
|
||||
_candidate=/tmp/nginx.conf.candidate
|
||||
envsubst "$ENVSUBST_VARS" </etc/nginx/nginx.conf.template >"$_candidate" 2>/dev/null || return 1
|
||||
nginx -t -c "$_candidate" >/dev/null 2>&1 || return 1
|
||||
cat "$_candidate" >/etc/nginx/nginx.conf || return 1
|
||||
return 0
|
||||
}
|
||||
|
||||
cert_watcher() {
|
||||
set +e
|
||||
while :; do
|
||||
sleep "$CERT_WATCH_INTERVAL"
|
||||
if [ "$CONFIG_MODE" = "setup" ]; then
|
||||
# B2: bootstrap -> production, once certbot's first issuance lands.
|
||||
if [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ] && \
|
||||
[ -f "/etc/letsencrypt/live/$DOMAIN/privkey.pem" ]; then
|
||||
echo "Certificate for $DOMAIN appeared. Switching to production config."
|
||||
if render_prod_config && nginx -s reload; then
|
||||
CONFIG_MODE=prod
|
||||
rm -f "$RELOAD_SENTINEL"
|
||||
echo "Production nginx config live."
|
||||
else
|
||||
echo "WARNING: could not switch to production config; staying on setup config and retrying."
|
||||
fi
|
||||
fi
|
||||
elif [ -f "$RELOAD_SENTINEL" ]; then
|
||||
# B1: certbot renewed the certificate and touched the sentinel.
|
||||
rm -f "$RELOAD_SENTINEL"
|
||||
echo "Certificate renewal detected. Reloading nginx."
|
||||
nginx -t >/dev/null 2>&1 && nginx -s reload
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
if [ "$DEV_MODE" != "true" ]; then
|
||||
# Drop any sentinel left over from a previous run: we have just loaded the
|
||||
# certificate files from disk, so there is by definition nothing to reload.
|
||||
rm -f "$RELOAD_SENTINEL" 2>/dev/null || true
|
||||
cert_watcher &
|
||||
fi
|
||||
|
||||
# Start nginx in the foreground so it is PID 1 and docker can signal/restart it.
|
||||
nginx -g 'daemon off;'
|
||||
|
||||
@@ -189,6 +189,23 @@ http {
|
||||
add_header Cache-Control "public";
|
||||
}
|
||||
|
||||
# PRIVATE attachments (admin-only). Attachments on *private* chat
|
||||
# messages are written by the backend to /backend/uploads/private/ and
|
||||
# must not be readable by the public, so this subpath is put behind the
|
||||
# same admin `auth_request` used for /hasura/ and /notes/. nginx picks
|
||||
# the LONGEST matching prefix location, so this block wins over the
|
||||
# public /uploads/ block below for /uploads/private/* regardless of
|
||||
# ordering. Same three hardening headers as the public block, because
|
||||
# the bytes are just as attacker-supplied.
|
||||
location /uploads/private/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
alias /uploads/private/;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Content-Disposition "inline" always;
|
||||
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||
}
|
||||
|
||||
# User-uploaded files, served straight off the shared `uploads` volume
|
||||
# so the Go process never has to stream them. Because these are
|
||||
# attacker-supplied bytes on our own origin, three headers neutralise
|
||||
@@ -225,11 +242,12 @@ http {
|
||||
}
|
||||
|
||||
# One-off: this GIF is a "web stamp" other people's sites hot-link, so
|
||||
# it needs an explicit CORS header. Ironically the origin allowed is our
|
||||
# own, which means cross-origin embedders are not actually permitted —
|
||||
# see the proposals in DEPLOYMENT.md before changing it.
|
||||
# it needs an explicit CORS header. It is a public, deliberately
|
||||
# hot-linkable image, so the allowed origin is `*` — it used to be our
|
||||
# own origin, which defeated the point (no cross-origin embedder was
|
||||
# actually permitted). Nothing here is credentialed, so `*` is safe.
|
||||
location = /img/stamps/mine.gif {
|
||||
add_header Access-Control-Allow-Origin "https://www.$DOMAIN";
|
||||
add_header Access-Control-Allow-Origin "*";
|
||||
expires 7d;
|
||||
add_header Cache-Control "public";
|
||||
}
|
||||
@@ -338,6 +356,25 @@ http {
|
||||
return 301 /radio/;
|
||||
}
|
||||
|
||||
# The icecast ADMIN UI (/radio/admin/*) is a full station-control
|
||||
# surface — kick sources, change metadata — protected only by the
|
||||
# icecast admin password, and it was reachable from the public
|
||||
# internet through this proxy. Put it behind the same admin
|
||||
# `auth_request` as /hasura/ and /notes/ so an admin session cookie is
|
||||
# required before the request ever reaches icecast. Longest-prefix
|
||||
# matching means this wins over /radio/ below; listener traffic
|
||||
# (/radio/$ICECAST_MOUNT, /radio/status.xsl) is untouched.
|
||||
location /radio/admin/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /radio/ {
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
|
||||
@@ -80,183 +80,7 @@ http {
|
||||
listen 80;
|
||||
server_name $DOMAIN www.$DOMAIN;
|
||||
|
||||
set $upstream_backend http://$BACKEND_HOST:$BACKEND_PORT;
|
||||
set $upstream_icecast http://$ICECAST_HOST:$ICECAST_PORT;
|
||||
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
|
||||
set $upstream_quartz http://$QUARTZ_HOST:$QUARTZ_PORT;
|
||||
set $upstream_python http://$PYTHON_HOST:$PYTHON_PORT;
|
||||
|
||||
location /uploads/ {
|
||||
alias /uploads/;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Content-Disposition "inline" always;
|
||||
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://vue:5173;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT {
|
||||
return 301 $BACKEND_ENDPOINT/;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/ws {
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/auth/login {
|
||||
limit_req zone=login burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/messages/upload {
|
||||
limit_req zone=upload burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /radio {
|
||||
return 301 /radio/;
|
||||
}
|
||||
|
||||
location /radio/ {
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /gitea {
|
||||
return 301 /gitea/;
|
||||
}
|
||||
|
||||
location /gitea/ {
|
||||
rewrite ^/gitea/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_gitea;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /hasura {
|
||||
return 301 /hasura/;
|
||||
}
|
||||
|
||||
location /hasura/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/hasura/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_hasura;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
|
||||
location /notes {
|
||||
return 301 /notes/;
|
||||
}
|
||||
|
||||
location /notes/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/notes/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_quartz;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /py {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
# /py/hotels/search[/stream] and /py/hotels/scan/stream: long-running NDJSON streams
|
||||
location ~ ^/py/hotels/(search|scan) {
|
||||
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
|
||||
limit_req zone=hotel_search burst=2 nodelay;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
# The stream variant sends NDJSON progress lines; pass them through as they arrive
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /py/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
# Hotel search blocks for up to a few minutes while it calls Travelodge and TfL
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location = /internal/auth/admin-validate {
|
||||
internal;
|
||||
rewrite ^ /auth/validate-admin break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
}
|
||||
|
||||
location @auth_denied {
|
||||
return 302 /admin/login?redirect=$request_uri;
|
||||
}
|
||||
include /etc/nginx/nginx_dev_common.conf;
|
||||
|
||||
}
|
||||
|
||||
@@ -267,183 +91,7 @@ http {
|
||||
ssl_certificate /etc/letsencrypt/live/localhost/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/localhost/privkey.pem;
|
||||
|
||||
set $upstream_backend http://$BACKEND_HOST:$BACKEND_PORT;
|
||||
set $upstream_icecast http://$ICECAST_HOST:$ICECAST_PORT;
|
||||
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
|
||||
set $upstream_quartz http://$QUARTZ_HOST:$QUARTZ_PORT;
|
||||
set $upstream_python http://$PYTHON_HOST:$PYTHON_PORT;
|
||||
|
||||
location /uploads/ {
|
||||
alias /uploads/;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Content-Disposition "inline" always;
|
||||
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://vue:5173;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT {
|
||||
return 301 $BACKEND_ENDPOINT/;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/ws {
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/auth/login {
|
||||
limit_req zone=login burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/messages/upload {
|
||||
limit_req zone=upload burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /radio {
|
||||
return 301 /radio/;
|
||||
}
|
||||
|
||||
location /radio/ {
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /gitea {
|
||||
return 301 /gitea/;
|
||||
}
|
||||
|
||||
location /gitea/ {
|
||||
rewrite ^/gitea/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_gitea;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /hasura {
|
||||
return 301 /hasura/;
|
||||
}
|
||||
|
||||
location /hasura/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/hasura/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_hasura;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
|
||||
location /notes {
|
||||
return 301 /notes/;
|
||||
}
|
||||
|
||||
location /notes/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/notes/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_quartz;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /py {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
# /py/hotels/search[/stream] and /py/hotels/scan/stream: long-running NDJSON streams
|
||||
location ~ ^/py/hotels/(search|scan) {
|
||||
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
|
||||
limit_req zone=hotel_search burst=2 nodelay;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
# The stream variant sends NDJSON progress lines; pass them through as they arrive
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /py/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
# Hotel search blocks for up to a few minutes while it calls Travelodge and TfL
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location = /internal/auth/admin-validate {
|
||||
internal;
|
||||
rewrite ^ /auth/validate-admin break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
}
|
||||
|
||||
location @auth_denied {
|
||||
return 302 /admin/login?redirect=$request_uri;
|
||||
}
|
||||
include /etc/nginx/nginx_dev_common.conf;
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
# =============================================================================
|
||||
# nginx_dev.conf.template — SHARED BODY of the dev :80 and :443 server blocks.
|
||||
#
|
||||
# WHY THIS FILE EXISTS
|
||||
# In dev the :80 and :443 server blocks are byte-for-byte identical apart
|
||||
# from `listen` and the self-signed `ssl_certificate` pair. They used to be
|
||||
# ~190 duplicated lines, so every routing fix had to be made twice and could
|
||||
# silently drift. Both blocks now `include` this partial instead.
|
||||
#
|
||||
# HOW IT IS RENDERED
|
||||
# nginx/entrypoint.sh runs the SAME envsubst allow-list over this file as
|
||||
# over nginx_dev.conf.template, writing the result to
|
||||
# /etc/nginx/nginx_dev_common.conf — which is exactly the path the two
|
||||
# `include` directives in the rendered nginx.conf point at. If you add
|
||||
# a new substituted variable here, it must also be added to ENVSUBST_VARS in
|
||||
# the entrypoint, or it will reach nginx unsubstituted.
|
||||
#
|
||||
# WHAT BELONGS HERE
|
||||
# Everything inside a `server { ... }` block: the `set $upstream_*` vars and
|
||||
# every `location`. NOT `listen`, `server_name` or the ssl_certificate lines
|
||||
# (those differ between the two blocks), and NOT the enclosing braces — this
|
||||
# file must be brace-balanced on its own.
|
||||
#
|
||||
# This is the DEV file only. Production uses a single :443 server block in
|
||||
# nginx.conf.template and needs no partial.
|
||||
# =============================================================================
|
||||
set $upstream_backend http://$BACKEND_HOST:$BACKEND_PORT;
|
||||
set $upstream_icecast http://$ICECAST_HOST:$ICECAST_PORT;
|
||||
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
|
||||
set $upstream_quartz http://$QUARTZ_HOST:$QUARTZ_PORT;
|
||||
set $upstream_python http://$PYTHON_HOST:$PYTHON_PORT;
|
||||
|
||||
# PRIVATE attachments (admin-only). Attachments on *private* chat
|
||||
# messages are written by the backend to /backend/uploads/private/ and
|
||||
# must not be readable by the public, so this subpath is put behind the
|
||||
# same admin `auth_request` used for /hasura/ and /notes/. nginx picks
|
||||
# the LONGEST matching prefix location, so this block wins over the
|
||||
# public /uploads/ block below for /uploads/private/* regardless of
|
||||
# ordering. Same three hardening headers as the public block, because
|
||||
# the bytes are just as attacker-supplied.
|
||||
location /uploads/private/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
alias /uploads/private/;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Content-Disposition "inline" always;
|
||||
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||
}
|
||||
|
||||
location /uploads/ {
|
||||
alias /uploads/;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Content-Disposition "inline" always;
|
||||
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://vue:5173;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT {
|
||||
return 301 $BACKEND_ENDPOINT/;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/ws {
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/auth/login {
|
||||
limit_req zone=login burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/messages/upload {
|
||||
limit_req zone=upload burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /radio {
|
||||
return 301 /radio/;
|
||||
}
|
||||
|
||||
# The icecast ADMIN UI (/radio/admin/*) is a full station-control
|
||||
# surface — kick sources, change metadata — protected only by the
|
||||
# icecast admin password, and it was reachable from the public
|
||||
# internet through this proxy. Put it behind the same admin
|
||||
# `auth_request` as /hasura/ and /notes/ so an admin session cookie is
|
||||
# required before the request ever reaches icecast. Longest-prefix
|
||||
# matching means this wins over /radio/ below; listener traffic
|
||||
# (/radio/$ICECAST_MOUNT, /radio/status.xsl) is untouched.
|
||||
location /radio/admin/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /radio/ {
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /gitea {
|
||||
return 301 /gitea/;
|
||||
}
|
||||
|
||||
location /gitea/ {
|
||||
rewrite ^/gitea/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_gitea;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /hasura {
|
||||
return 301 /hasura/;
|
||||
}
|
||||
|
||||
location /hasura/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/hasura/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_hasura;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
|
||||
location /notes {
|
||||
return 301 /notes/;
|
||||
}
|
||||
|
||||
location /notes/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/notes/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_quartz;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /py {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
# /py/hotels/search[/stream] and /py/hotels/scan/stream: long-running NDJSON streams
|
||||
location ~ ^/py/hotels/(search|scan) {
|
||||
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
|
||||
limit_req zone=hotel_search burst=2 nodelay;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
# The stream variant sends NDJSON progress lines; pass them through as they arrive
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /py/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
# Hotel search blocks for up to a few minutes while it calls Travelodge and TfL
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location = /internal/auth/admin-validate {
|
||||
internal;
|
||||
rewrite ^ /auth/validate-admin break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
}
|
||||
|
||||
location @auth_denied {
|
||||
return 302 /admin/login?redirect=$request_uri;
|
||||
}
|
||||
+92
-84
@@ -24,9 +24,9 @@ prefix. Field names in the models below are part of that contract.
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.responses import StreamingResponse
|
||||
@@ -81,14 +81,29 @@ MAX_ADULTS = 8
|
||||
MAX_CHILDREN = 8
|
||||
MAX_SCAN_DAYS = travelodge.SCAN_MAX_DAYS
|
||||
CACHE_TTL_S = 10 * 60
|
||||
CACHE_MAX = 200
|
||||
|
||||
# The service prices London hotels and London transport, so "today" means today
|
||||
# in London - not on whatever timezone the server happens to be set to. Using
|
||||
# the server's local date refused a check-in that was still today for a user
|
||||
# west of it (and, on a UTC server during BST, accepted one an hour late).
|
||||
LONDON_TZ = ZoneInfo("Europe/London")
|
||||
|
||||
|
||||
def london_today() -> date:
|
||||
"""Today's date in London, the reference for "today or later" validation."""
|
||||
return datetime.now(LONDON_TZ).date()
|
||||
|
||||
# Only one live search or scan may run at a time, process-wide. A run can spend
|
||||
# the entire anonymous TfL budget (50 requests/min), so two concurrent runs
|
||||
# would simply starve each other into rate-limit backoff. Callers that find the
|
||||
# slot taken get an immediate "try again" rather than queueing.
|
||||
_search_slot = threading.Semaphore(1)
|
||||
_cache_lock = threading.Lock()
|
||||
_cache: dict = {} # key -> (expires_at, response dict)
|
||||
# Finished responses, keyed by the canonical request body. Bounded as well as
|
||||
# swept: the one-at-a-time guard makes growth slow, but "slow" is not "never",
|
||||
# and a response holds every row of a scan. Eviction is insertion order, so a
|
||||
# repeatedly-requested entry still ages out and is refetched.
|
||||
_cache = travelodge.TTLCache(CACHE_TTL_S, max_entries=CACHE_MAX)
|
||||
|
||||
|
||||
class Origin(BaseModel):
|
||||
@@ -181,11 +196,11 @@ class HotelSearchRequest(HotelRequestBase):
|
||||
|
||||
`checkout` wins when both are given; otherwise it is derived from
|
||||
`nights`. Both fields are then written back so downstream code can
|
||||
trust either one. `date.today()` is the server's local date, so a user
|
||||
in another timezone can be refused a checkin that is still valid for
|
||||
them.
|
||||
trust either one. "Today" is London's date (see :func:`london_today`),
|
||||
not the server's, so the answer does not depend on the container's
|
||||
timezone.
|
||||
"""
|
||||
if self.checkin < date.today():
|
||||
if self.checkin < london_today():
|
||||
raise ValueError("checkin must be today or later")
|
||||
checkout = self.checkout or self.checkin + timedelta(days=self.nights)
|
||||
if checkout <= self.checkin:
|
||||
@@ -235,7 +250,7 @@ class HotelScanRequest(HotelRequestBase):
|
||||
"Mondays only" over a Tuesday-to-Thursday window fails here with a clear
|
||||
message instead of producing an empty scan.
|
||||
"""
|
||||
if self.start < date.today():
|
||||
if self.start < london_today(): # London's date, see london_today()
|
||||
raise ValueError("start must be today or later")
|
||||
if self.end < self.start:
|
||||
raise ValueError("end must be on or after start")
|
||||
@@ -402,30 +417,6 @@ class HotelScanEvent(BaseModel):
|
||||
detail: Optional[str] = None
|
||||
|
||||
|
||||
def _cache_get(key: str):
|
||||
"""Return a cached response payload for `key`, or None if absent/expired."""
|
||||
now = time.monotonic()
|
||||
with _cache_lock:
|
||||
hit = _cache.get(key)
|
||||
if hit and hit[0] > now:
|
||||
return hit[1]
|
||||
return None
|
||||
|
||||
|
||||
def _cache_put(key: str, result: dict) -> None:
|
||||
"""Cache a completed response for CACHE_TTL_S, sweeping expired entries.
|
||||
|
||||
The sweep is the only eviction: the cache is unbounded between sweeps, which
|
||||
is fine because the one-at-a-time guard caps how fast entries can be added.
|
||||
"""
|
||||
now = time.monotonic()
|
||||
with _cache_lock:
|
||||
expired = [k for k, (exp, _) in _cache.items() if exp <= now]
|
||||
for k in expired:
|
||||
del _cache[k]
|
||||
_cache[key] = (now + CACHE_TTL_S, result)
|
||||
|
||||
|
||||
ALREADY_RUNNING = "A search is already running, try again in a minute."
|
||||
|
||||
|
||||
@@ -451,77 +442,94 @@ def _guarded(run, make_error):
|
||||
_search_slot.release()
|
||||
|
||||
|
||||
def _search_events(req: HotelSearchRequest):
|
||||
"""Yield HotelSearchEvent objects for a request, serving from cache when possible.
|
||||
def _run_events(*, req, prefix, model, make_gen, first_event, list_key, row_keys):
|
||||
"""Shared body of the two streaming endpoints, differing only in their types.
|
||||
|
||||
A cache hit replays a two-line stream ("hotels" then "done") carrying the
|
||||
finished result, so the client's streaming reader needs no special case; the
|
||||
`cached` flag is the only difference it can observe. The key is the
|
||||
canonical JSON of the whole validated request, which makes it exact but also
|
||||
means a cosmetically different body (a different `top`, say) misses.
|
||||
Searches and scans have the same shape: build a cache key from the request,
|
||||
replay a finished result as two lines if it is cached, otherwise run the
|
||||
travelodge generator under the single-search guard and wrap each upstream
|
||||
event in a Pydantic event model.
|
||||
|
||||
Args:
|
||||
req: the validated request; its canonical JSON is the cache key, which
|
||||
makes the key exact but also means a cosmetically different body (a
|
||||
different `top`, say) misses.
|
||||
prefix: cache-key namespace ("search:"/"scan:") so the two endpoints
|
||||
cannot collide.
|
||||
model: the event model to emit (HotelSearchEvent or HotelScanEvent).
|
||||
make_gen: zero-argument callable returning the travelodge generator.
|
||||
Called inside the guard so that anything it raises while binding
|
||||
its arguments becomes an "error" event rather than a 500.
|
||||
first_event: name of the opening list event ("hotels"/"scan"). A cache
|
||||
hit replays it followed by "done", both carrying the finished
|
||||
result, so the client's streaming reader needs no special case and
|
||||
the `cached` flag is the only difference it can observe.
|
||||
list_key: model field holding the whole list ("rows"/"nights"); only the
|
||||
final "done" event is worth caching.
|
||||
row_keys: kind -> model field for the per-item events, e.g.
|
||||
{"transport": "row"} for a search.
|
||||
|
||||
Upstream events are 3-tuples of (kind, summary, payload) except run_search's
|
||||
"transport", which is a 2-tuple of (kind, row); that one is normalised to a
|
||||
None summary here, and `exclude_none=True` at serialisation time drops the
|
||||
key exactly as before.
|
||||
"""
|
||||
key = "search:" + json.dumps(req.model_dump(mode="json"), sort_keys=True)
|
||||
hit = _cache_get(key)
|
||||
key = prefix + json.dumps(req.model_dump(mode="json"), sort_keys=True)
|
||||
hit = _cache.get(key)
|
||||
if hit:
|
||||
yield HotelSearchEvent(event="hotels", cached=True, **hit)
|
||||
yield HotelSearchEvent(event="done", cached=True, **hit)
|
||||
yield model(event=first_event, cached=True, **hit)
|
||||
yield model(event="done", cached=True, **hit)
|
||||
return
|
||||
|
||||
def run():
|
||||
# run_search yields 3-tuples except for "transport", which is a 2-tuple
|
||||
# of (kind, row) - hence the shape test before unpacking. Only the final
|
||||
# "done" event is worth caching.
|
||||
gen = travelodge.run_search(
|
||||
for ev in make_gen():
|
||||
kind, summary, payload = (ev[0], None, ev[1]) if len(ev) == 2 else ev
|
||||
if kind in row_keys:
|
||||
yield model(event=kind, summary=summary, **{row_keys[kind]: payload})
|
||||
else:
|
||||
if kind == "done":
|
||||
_cache.set(key, {"summary": summary, list_key: payload})
|
||||
yield model(event=kind, summary=summary, **{list_key: payload})
|
||||
|
||||
yield from _guarded(run, lambda detail: model(event="error", detail=detail))
|
||||
|
||||
|
||||
def _search_events(req: HotelSearchRequest):
|
||||
"""Yield HotelSearchEvent objects for a request, serving from cache when possible."""
|
||||
return _run_events(
|
||||
req=req,
|
||||
prefix="search:",
|
||||
model=HotelSearchEvent,
|
||||
make_gen=lambda: travelodge.run_search(
|
||||
checkin=req.checkin,
|
||||
checkout=req.checkout,
|
||||
top=req.top,
|
||||
**req.shared_kwargs(),
|
||||
)
|
||||
for ev in gen:
|
||||
if ev[0] == "transport":
|
||||
yield HotelSearchEvent(event="transport", row=ev[1])
|
||||
else:
|
||||
kind, summary, rows = ev
|
||||
if kind == "done":
|
||||
_cache_put(key, {"summary": summary, "rows": rows})
|
||||
yield HotelSearchEvent(event=kind, summary=summary, rows=rows)
|
||||
|
||||
yield from _guarded(run, lambda detail: HotelSearchEvent(event="error", detail=detail))
|
||||
),
|
||||
first_event="hotels",
|
||||
list_key="rows",
|
||||
row_keys={"transport": "row"},
|
||||
)
|
||||
|
||||
|
||||
def _scan_events(req: HotelScanRequest):
|
||||
"""Yield HotelScanEvent objects for a scan, serving from cache when possible.
|
||||
|
||||
As with searches, a cache hit is replayed as a "scan" line followed by
|
||||
"done" so the client parses it exactly like a live stream.
|
||||
"""
|
||||
key = "scan:" + json.dumps(req.model_dump(mode="json"), sort_keys=True)
|
||||
hit = _cache_get(key)
|
||||
if hit:
|
||||
yield HotelScanEvent(event="scan", cached=True, **hit)
|
||||
yield HotelScanEvent(event="done", cached=True, **hit)
|
||||
return
|
||||
|
||||
def run():
|
||||
gen = travelodge.run_scan(
|
||||
"""Yield HotelScanEvent objects for a scan, serving from cache when possible."""
|
||||
return _run_events(
|
||||
req=req,
|
||||
prefix="scan:",
|
||||
model=HotelScanEvent,
|
||||
make_gen=lambda: travelodge.run_scan(
|
||||
start=req.start,
|
||||
end=req.end,
|
||||
weekdays=set(req.weekdays),
|
||||
nights=req.nights,
|
||||
per_night=req.per_night,
|
||||
**req.shared_kwargs(),
|
||||
)
|
||||
for kind, summary, payload in gen:
|
||||
if kind == "night":
|
||||
yield HotelScanEvent(event=kind, summary=summary, night=payload)
|
||||
elif kind == "transport":
|
||||
yield HotelScanEvent(event=kind, summary=summary, transport=payload)
|
||||
else:
|
||||
if kind == "done":
|
||||
_cache_put(key, {"summary": summary, "nights": payload})
|
||||
yield HotelScanEvent(event=kind, summary=summary, nights=payload)
|
||||
|
||||
yield from _guarded(run, lambda detail: HotelScanEvent(event="error", detail=detail))
|
||||
),
|
||||
first_event="scan",
|
||||
list_key="nights",
|
||||
row_keys={"night": "night", "transport": "transport"},
|
||||
)
|
||||
|
||||
|
||||
_SEARCH_DESCRIPTION = (
|
||||
|
||||
+416
-210
@@ -4,7 +4,8 @@ Ported from ~/cheap_hotel/cheap_travelodge.py. The pricing logic is unchanged;
|
||||
the plumbing around it has been rewritten for speed:
|
||||
|
||||
* Travelodge result pages are fetched in parallel batches.
|
||||
* TfL journeys are fetched by a worker pool, throttled to the anonymous API
|
||||
* TfL journeys are fetched by one flat worker pool (every hotel/query pair is
|
||||
submitted to it and results gathered per hotel), throttled to the anonymous API
|
||||
limit (50 requests/min; 500/min with TFL_APP_KEY) and cached for a while
|
||||
so repeat searches don't spend the budget again.
|
||||
* `run_search` is a generator that yields the hotel list first and then one
|
||||
@@ -44,7 +45,7 @@ Fragility
|
||||
|
||||
Concurrency
|
||||
Everything here is thread-based (requests is blocking), not asyncio. Module
|
||||
state - the two response caches, the rate limiters and the shared
|
||||
state - the two :class:`TTLCache` response caches, the rate limiters and the shared
|
||||
requests.Session - is process-global and guarded by plain locks, so it is
|
||||
shared across concurrent FastAPI requests. main.py additionally allows only
|
||||
one live search at a time, which is what keeps the TfL budget spendable by a
|
||||
@@ -122,7 +123,6 @@ TL_MAX_START = 500
|
||||
# TfL: anonymous callers get 50 requests/min, keyed callers 500/min. A call
|
||||
# normally takes 1-5s; the odd one hangs, so time out early and retry.
|
||||
TFL_WORKERS = 12
|
||||
TFL_HOTEL_WORKERS = 4
|
||||
TFL_TIMEOUT_S = 15
|
||||
TFL_RATE_ANON = 48
|
||||
TFL_RATE_KEYED = 450
|
||||
@@ -149,6 +149,62 @@ class UpstreamError(Exception):
|
||||
"""Travelodge or TfL could not be reached or returned garbage."""
|
||||
|
||||
|
||||
class TTLCache:
|
||||
"""A small thread-safe dict with per-entry expiry, shared by every cache here.
|
||||
|
||||
There used to be three hand-rolled copies of this (Travelodge results, TfL
|
||||
journeys, and main.py's response cache) whose eviction rules genuinely
|
||||
differed, so the differences are constructor parameters rather than being
|
||||
quietly unified:
|
||||
|
||||
* ``ttl_s`` - how long a stored value stays fresh.
|
||||
* ``max_entries`` - hard cap on size, or None for unbounded. Eviction is
|
||||
*insertion order*, not LRU: dicts keep insertion order, so dropping the
|
||||
first key drops the oldest *written* entry regardless of recent reads.
|
||||
* ``sweep_above`` - only walk the whole dict looking for expired entries
|
||||
once it holds more than this many. 0 (the default) means sweep on every
|
||||
write; a large value keeps the common path O(1) for a big cache whose
|
||||
entries are cheap to keep around.
|
||||
|
||||
Expiry is by :func:`time.monotonic`, so a wall-clock change cannot make an
|
||||
entry immortal. Values are returned by reference and callers must treat them
|
||||
as read-only.
|
||||
"""
|
||||
|
||||
def __init__(self, ttl_s: float, max_entries: int | None = None, sweep_above: int = 0) -> None:
|
||||
self.ttl_s = ttl_s
|
||||
self.max_entries = max_entries
|
||||
self.sweep_above = sweep_above
|
||||
self._store: dict = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def get(self, key):
|
||||
"""Return the value stored for `key`, or None if absent or expired."""
|
||||
now = time.monotonic()
|
||||
with self._lock:
|
||||
hit = self._store.get(key)
|
||||
if hit and hit[0] > now:
|
||||
return hit[1]
|
||||
return None
|
||||
|
||||
def set(self, key, value) -> None:
|
||||
"""Store `value` for `key` for ttl_s seconds, evicting as configured."""
|
||||
with self._lock:
|
||||
now = time.monotonic()
|
||||
if len(self._store) > self.sweep_above:
|
||||
for k in [k for k, (exp, _) in self._store.items() if exp <= now]:
|
||||
del self._store[k]
|
||||
if self.max_entries is not None:
|
||||
# >= because this write is about to add one more entry.
|
||||
while len(self._store) >= self.max_entries and key not in self._store:
|
||||
del self._store[next(iter(self._store))]
|
||||
self._store[key] = (now + self.ttl_s, value)
|
||||
|
||||
def __len__(self) -> int:
|
||||
with self._lock:
|
||||
return len(self._store)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Input parsing
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -355,8 +411,9 @@ def normalise_hotel(h: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
_tl_cache = {} # (location, checkin, checkout, rooms) -> (expires_at, [normalised hotel dicts])
|
||||
_tl_cache_lock = threading.Lock()
|
||||
# (location, checkin, checkout, rooms) -> [normalised hotel dicts]. Bounded by
|
||||
# count, and expired entries are swept on every write (the cache is small).
|
||||
_tl_cache = TTLCache(TL_CACHE_TTL_S, max_entries=TL_CACHE_MAX)
|
||||
|
||||
|
||||
def hotels_for(location, checkin, checkout, rooms, deadline=None):
|
||||
@@ -368,27 +425,15 @@ def hotels_for(location, checkin, checkout, rooms, deadline=None):
|
||||
# "central london " share one cache entry; rooms must be hashable, hence
|
||||
# the tuple.
|
||||
key = (location.strip().lower(), checkin, checkout, tuple(rooms))
|
||||
now = time.monotonic()
|
||||
with _tl_cache_lock:
|
||||
hit = _tl_cache.get(key)
|
||||
if hit and hit[0] > now:
|
||||
return hit[1]
|
||||
hit = _tl_cache.get(key)
|
||||
if hit is not None:
|
||||
return hit
|
||||
|
||||
# Deliberately outside the lock: a slow upstream fetch must not block other
|
||||
# threads reading the cache. Two threads racing on the same key both fetch
|
||||
# and the second write wins, which is harmless.
|
||||
# The fetch deliberately happens outside any cache lock: a slow upstream
|
||||
# must not block other threads reading the cache. Two threads racing on the
|
||||
# same key both fetch and the second write wins, which is harmless.
|
||||
hotels = [normalise_hotel(h) for h in fetch_hotels(location, checkin, checkout, rooms, deadline=deadline)]
|
||||
|
||||
with _tl_cache_lock:
|
||||
now = time.monotonic()
|
||||
expired = [k for k, (exp, _) in _tl_cache.items() if exp <= now]
|
||||
for k in expired:
|
||||
del _tl_cache[k]
|
||||
# Bounded, not LRU: dicts preserve insertion order, so evicting the
|
||||
# first key drops the oldest *written* entry regardless of recent reads.
|
||||
while len(_tl_cache) >= TL_CACHE_MAX:
|
||||
del _tl_cache[next(iter(_tl_cache))]
|
||||
_tl_cache[key] = (now + TL_CACHE_TTL_S, hotels)
|
||||
_tl_cache.set(key, hotels)
|
||||
return hotels
|
||||
|
||||
|
||||
@@ -574,8 +619,10 @@ def _limiter(app_key: str | None) -> RateLimiter:
|
||||
return lim
|
||||
|
||||
|
||||
_tfl_cache = {} # key -> (expires_at, journeys)
|
||||
_tfl_cache_lock = threading.Lock()
|
||||
# journey key -> journeys. Unbounded on purpose (entries are small and a long
|
||||
# scan wants them all), so expired entries are only swept once it is large,
|
||||
# keeping the common write O(1).
|
||||
_tfl_cache = TTLCache(TFL_CACHE_TTL_S, sweep_above=5000)
|
||||
|
||||
|
||||
def sleep_within(seconds, deadline):
|
||||
@@ -587,8 +634,15 @@ def sleep_within(seconds, deadline):
|
||||
return True
|
||||
|
||||
|
||||
def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=None) -> list[dict]:
|
||||
"""Journeys from TfL for one origin/destination/time/mode, cached and rate limited.
|
||||
def _tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=None) -> tuple[list[dict], bool]:
|
||||
"""Journeys from TfL, plus whether the call was abandoned on the deadline.
|
||||
|
||||
Same contract as :func:`tfl_journeys` but returns (journeys, abandoned).
|
||||
`abandoned` is True only when every attempt was given up because the
|
||||
deadline was too close (no slot from the rate limiter, no time left for the
|
||||
request, or a backoff sleep that would overrun it). It is False for a
|
||||
genuine "TfL has no route/fare here" answer, which is what lets the caller
|
||||
tell those two cases apart instead of guessing from the clock.
|
||||
|
||||
Args:
|
||||
frm, to: (lat, lon) tuples; TfL accepts raw coordinates in the path.
|
||||
@@ -622,11 +676,9 @@ def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=No
|
||||
# from the key on purpose: the route and fare do not depend on it.
|
||||
key = (round(frm[0], 5), round(frm[1], 5), round(to[0], 5), round(to[1], 5), params["date"], params["time"],
|
||||
tuple(sorted((extra or {}).items())))
|
||||
now = time.monotonic()
|
||||
with _tfl_cache_lock:
|
||||
hit = _tfl_cache.get(key)
|
||||
if hit and hit[0] > now:
|
||||
return hit[1]
|
||||
hit = _tfl_cache.get(key)
|
||||
if hit is not None:
|
||||
return hit, False
|
||||
|
||||
if app_key:
|
||||
params["app_key"] = app_key
|
||||
@@ -672,17 +724,37 @@ def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=No
|
||||
# without caching so a later, less rushed call can try again. An empty list
|
||||
# from a *successful* response is cached - "no route" is a real answer.
|
||||
if journeys is None:
|
||||
return []
|
||||
with _tfl_cache_lock:
|
||||
# Sweep expired entries only once the cache is large, so the common path
|
||||
# stays O(1); TFL_CACHE_TTL_S is long because journey times and fares
|
||||
# for a fixed date/time do not change.
|
||||
if len(_tfl_cache) > 5000:
|
||||
expired = [k for k, (exp, _) in _tfl_cache.items() if exp <= now]
|
||||
for k in expired:
|
||||
del _tfl_cache[k]
|
||||
_tfl_cache[key] = (time.monotonic() + TFL_CACHE_TTL_S, journeys)
|
||||
return journeys
|
||||
return [], True
|
||||
# TFL_CACHE_TTL_S is long because journey times and fares for a fixed
|
||||
# date/time do not change.
|
||||
_tfl_cache.set(key, journeys)
|
||||
return journeys, False
|
||||
|
||||
|
||||
def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=None) -> list[dict]:
|
||||
"""Journeys from TfL for one origin/destination/time/mode, cached and rate limited.
|
||||
|
||||
Args:
|
||||
frm, to: (lat, lon) tuples; TfL accepts raw coordinates in the path.
|
||||
when: naive :class:`datetime` of the intended departure, London local
|
||||
time (TfL interprets it as such; no timezone is sent).
|
||||
extra: additional query parameters, e.g. ``{"mode": "bus,walking"}`` to
|
||||
force a bus-only route or ``{"mode": "cycle"}`` for cycle routing.
|
||||
app_key: TfL API key from the TFL_APP_KEY env var, or None for the
|
||||
anonymous tier.
|
||||
retries: attempts before giving up.
|
||||
deadline: time.monotonic() value bounding the whole call.
|
||||
|
||||
Returns:
|
||||
The ``journeys`` array, or [] on any failure. This function never
|
||||
raises: a missing route and a dead API look the same to the caller, who
|
||||
simply ends up with no priced option for that hotel. That is deliberate
|
||||
- one flaky lookup should not abort a 40-hotel search - but it does mean
|
||||
a total TfL outage shows up in the UI as "no TfL fare found" rather than
|
||||
as an error. Callers that need to tell "no route" from "abandoned on the
|
||||
deadline" apart should call :func:`_tfl_journeys` instead.
|
||||
"""
|
||||
return _tfl_journeys(frm, to, when, extra, app_key, retries, deadline)[0]
|
||||
|
||||
|
||||
# Two journey queries per hotel, because TfL's default "LeastTime" answer is
|
||||
@@ -693,23 +765,16 @@ TRANSPORT_QUERIES = (("fast", None), ("bus", {"mode": "bus,walking"}))
|
||||
CYCLE_QUERY = {"mode": "cycle"}
|
||||
|
||||
|
||||
def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, app_key=None, deadline=None, pool=None):
|
||||
"""Cheapest acceptable round-trip transport to a hotel.
|
||||
def _score_transport(results, adults, railcard_holders, max_minutes):
|
||||
"""Pick the cheapest acceptable option out of already-fetched journeys.
|
||||
|
||||
Args:
|
||||
origin: (lat, lon) of the journey start.
|
||||
hotel: normalised hotel dict; only lat/lon are read.
|
||||
when: departure datetime for the outbound leg.
|
||||
results: iterable of (label, journeys) - the "fast" and "bus" answers
|
||||
from TfL, in any order.
|
||||
adults, railcard_holders: party makeup, passed to :func:`price_journey`.
|
||||
max_minutes: routes slower than this are rejected - unless *every*
|
||||
route is slower, in which case the fastest is kept so the hotel
|
||||
still gets a price rather than vanishing from the results.
|
||||
app_key: TfL key or None.
|
||||
deadline: time.monotonic() budget.
|
||||
pool: optional executor; the two queries are independent, so running
|
||||
them concurrently halves the latency per hotel. Note this pool is
|
||||
shared with the caller's other work, so it must never be sized 1 or
|
||||
the map below can deadlock behind its own parent task.
|
||||
max_minutes: routes slower than this are rejected - unless *every* route
|
||||
is slower, in which case the fastest is kept so the hotel still gets
|
||||
a price rather than vanishing from the results.
|
||||
|
||||
Returns:
|
||||
The chosen option as a dict with keys ``kind`` ("fast"/"bus"),
|
||||
@@ -718,20 +783,11 @@ def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, a
|
||||
the UI can show the speed/price trade-off. None if nothing was priceable.
|
||||
|
||||
Ties are broken by duration, so two equally cheap routes resolve to the
|
||||
quicker one.
|
||||
quicker one. This is pure - no network, no clock - which is what lets the
|
||||
fetching be reorganised without touching the pricing rules.
|
||||
"""
|
||||
dest = (hotel["lat"], hotel["lon"])
|
||||
|
||||
def query(q):
|
||||
return tfl_journeys(origin, dest, when, q[1], app_key, deadline=deadline)
|
||||
|
||||
if pool is not None:
|
||||
results = list(pool.map(query, TRANSPORT_QUERIES))
|
||||
else:
|
||||
results = [query(q) for q in TRANSPORT_QUERIES]
|
||||
|
||||
options = []
|
||||
for (label, _), journeys in zip(TRANSPORT_QUERIES, results):
|
||||
for label, journeys in results:
|
||||
for j in journeys:
|
||||
if not isinstance(j.get("duration"), int):
|
||||
continue
|
||||
@@ -758,6 +814,41 @@ def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, a
|
||||
return cheapest
|
||||
|
||||
|
||||
def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, app_key=None, deadline=None, pool=None):
|
||||
"""Cheapest acceptable round-trip transport to a single hotel.
|
||||
|
||||
Convenience wrapper: fetch both TfL queries for one hotel, then score them
|
||||
with :func:`_score_transport` (see there for the return shape and the
|
||||
selection rules). :func:`_price_hotels` does not use this - it submits every
|
||||
(hotel, query) pair to one flat pool instead - so this is the one-off path.
|
||||
|
||||
Args:
|
||||
origin: (lat, lon) of the journey start.
|
||||
hotel: normalised hotel dict; only lat/lon are read.
|
||||
when: departure datetime for the outbound leg.
|
||||
adults, railcard_holders: party makeup.
|
||||
max_minutes: slowest acceptable route, softened as described above.
|
||||
app_key: TfL key or None.
|
||||
deadline: time.monotonic() budget.
|
||||
pool: optional executor used to run the two independent queries
|
||||
concurrently. Only pass a pool this call is not itself running
|
||||
inside, or the map below can block behind its own parent task.
|
||||
"""
|
||||
dest = (hotel["lat"], hotel["lon"])
|
||||
|
||||
def query(q):
|
||||
return tfl_journeys(origin, dest, when, q[1], app_key, deadline=deadline)
|
||||
|
||||
if pool is not None:
|
||||
results = list(pool.map(query, TRANSPORT_QUERIES))
|
||||
else:
|
||||
results = [query(q) for q in TRANSPORT_QUERIES]
|
||||
return _score_transport(
|
||||
[(label, journeys) for (label, _), journeys in zip(TRANSPORT_QUERIES, results)],
|
||||
adults, railcard_holders, max_minutes,
|
||||
)
|
||||
|
||||
|
||||
def cycle_time(origin, hotel, when, app_key, deadline=None, journeys=None):
|
||||
"""(minutes, km, source) for cycling to the hotel.
|
||||
|
||||
@@ -883,52 +974,81 @@ def _make_row(h: dict, origin: tuple[float, float]) -> dict:
|
||||
def _price_hotels(hotels, origin, depart_dt, adults, railcard_holders, max_travel_min, app_key, deadline):
|
||||
"""Price TfL transport for each hotel, cheapest rooms first.
|
||||
|
||||
Generator of (code, transport_or_None, cycle_or_None, timed_out) in the order
|
||||
TfL answers. Owns the worker pools; leftover work is cancelled if the
|
||||
Generator of (code, transport_or_None, cycle_or_None, timed_out) in the
|
||||
order TfL answers. Owns the worker pool; leftover work is cancelled if the
|
||||
consumer stops early.
|
||||
|
||||
Two pools, not one: `hotel_pool` runs at most TFL_HOTEL_WORKERS hotels at a
|
||||
time and each of those tasks submits its own sub-queries to the larger
|
||||
`tfl_pool`. Sharing one pool would let the hotel tasks fill every slot and
|
||||
then block waiting for sub-tasks that can never be scheduled - a classic
|
||||
executor deadlock.
|
||||
One flat pool, not nested ones: every (hotel, query) pair - the two fare
|
||||
queries plus, with an app key, the cycle query - is submitted to a single
|
||||
executor and the results are gathered per hotel as they land. An earlier
|
||||
version ran hotels in one pool and their sub-queries in another, which is
|
||||
only deadlock-free while both pools are bigger than one worker and the
|
||||
nesting is exactly two deep; nothing here waits on the pool from inside the
|
||||
pool any more, so that hazard is gone by construction. Submission order is
|
||||
still cheapest room first, so the most useful rows are asked for first, and
|
||||
the shared :class:`RateLimiter` - not the pool size - is what keeps the run
|
||||
inside TfL's per-minute budget.
|
||||
|
||||
`timed_out` distinguishes "TfL has no fare for this hotel" from "we ran out
|
||||
of time before asking", which the caller surfaces as summary["truncated"].
|
||||
Note it is inferred from the clock at completion time rather than reported
|
||||
by the worker, so it can misattribute a genuine no-fare result that happens
|
||||
to land after the deadline.
|
||||
`timed_out` means "we gave up on the deadline before getting an answer", as
|
||||
reported by :func:`_tfl_journeys`, not inferred from the clock: a hotel TfL
|
||||
genuinely cannot price is reported with timed_out False even if its answer
|
||||
happens to arrive after the deadline. It is True when the hotel ended up
|
||||
unpriced and at least one of its queries was abandoned, since in that case
|
||||
we never really finished asking. The caller surfaces it as the
|
||||
"not priced (time limit)" route and summary["truncated"].
|
||||
|
||||
The cancel loop in `finally` is best-effort - it only stops tasks that have
|
||||
not started - and the `with` blocks still join running workers, so an
|
||||
not started - and the `with` block still joins running workers, so an
|
||||
abandoned stream takes up to one in-flight TfL timeout to unwind.
|
||||
"""
|
||||
with ThreadPoolExecutor(max_workers=TFL_WORKERS) as tfl_pool, \
|
||||
ThreadPoolExecutor(max_workers=TFL_HOTEL_WORKERS) as hotel_pool:
|
||||
|
||||
def price(h):
|
||||
# Kick off the cycle lookup first so it overlaps the fare lookups.
|
||||
cycle_fut = None
|
||||
with ThreadPoolExecutor(max_workers=TFL_WORKERS) as pool:
|
||||
pending = {} # code -> {hotel, fares: {label: (journeys, abandoned)}, left, cycle future}
|
||||
owner = {} # future -> (code, label)
|
||||
for h in hotels:
|
||||
code = h["code"]
|
||||
if code in pending: # a hotel is priced once even if it is listed twice
|
||||
continue
|
||||
dest = (h["lat"], h["lon"])
|
||||
entry = {"hotel": h, "fares": {}, "left": len(TRANSPORT_QUERIES), "cycle": None}
|
||||
pending[code] = entry
|
||||
for label, extra in TRANSPORT_QUERIES:
|
||||
fut = pool.submit(_tfl_journeys, origin, dest, depart_dt, extra, app_key, deadline=deadline)
|
||||
owner[fut] = (code, label)
|
||||
if app_key:
|
||||
cycle_fut = tfl_pool.submit(
|
||||
tfl_journeys, origin, (h["lat"], h["lon"]), depart_dt, CYCLE_QUERY, app_key, deadline=deadline
|
||||
# Cycle routing costs a third rate-limited request, so it is
|
||||
# only asked for when a key lifts the anonymous budget.
|
||||
entry["cycle"] = pool.submit(
|
||||
_tfl_journeys, origin, dest, depart_dt, CYCLE_QUERY, app_key, 1, deadline
|
||||
)
|
||||
t = best_transport(origin, h, depart_dt, adults, railcard_holders, max_travel_min, app_key,
|
||||
deadline=deadline, pool=tfl_pool)
|
||||
cyc = None
|
||||
if cycle_fut is not None:
|
||||
cyc = cycle_time(origin, h, depart_dt, app_key, deadline=deadline, journeys=cycle_fut.result())
|
||||
return h["code"], t, cyc
|
||||
|
||||
futures = [hotel_pool.submit(price, h) for h in hotels]
|
||||
try:
|
||||
for fut in as_completed(futures):
|
||||
code, t, cyc = fut.result()
|
||||
timed_out = t is None and time.monotonic() >= deadline
|
||||
yield code, t, cyc, timed_out
|
||||
for fut in as_completed(list(owner)):
|
||||
code, label = owner[fut]
|
||||
entry = pending[code]
|
||||
entry["fares"][label] = fut.result()
|
||||
entry["left"] -= 1
|
||||
if entry["left"]:
|
||||
continue # this hotel's other query is still outstanding
|
||||
h = entry["hotel"]
|
||||
t = _score_transport(
|
||||
[(lbl, entry["fares"][lbl][0]) for lbl, _ in TRANSPORT_QUERIES],
|
||||
adults, railcard_holders, max_travel_min,
|
||||
)
|
||||
abandoned = any(entry["fares"][lbl][1] for lbl, _ in TRANSPORT_QUERIES)
|
||||
cyc = None
|
||||
if entry["cycle"] is not None:
|
||||
# Already submitted above, so this wait is usually over by
|
||||
# now; waiting here (in the consumer, never in a worker) is
|
||||
# safe with a single flat pool.
|
||||
cyc = cycle_time(origin, h, depart_dt, app_key, deadline=deadline,
|
||||
journeys=entry["cycle"].result()[0])
|
||||
yield code, t, cyc, (t is None and abandoned)
|
||||
finally:
|
||||
for f in futures:
|
||||
for f in owner:
|
||||
f.cancel()
|
||||
for entry in pending.values():
|
||||
if entry["cycle"] is not None:
|
||||
entry["cycle"].cancel()
|
||||
|
||||
|
||||
def _apply_transport(row: dict, t: dict | None, cyc: tuple | None, timed_out: bool) -> dict:
|
||||
@@ -1065,6 +1185,167 @@ def _copy_night(n: dict) -> dict:
|
||||
return dict(n, hotels=[dict(r) for r in n["hotels"]])
|
||||
|
||||
|
||||
def _scan_rooms(*, candidates, by_checkin, summary, location, rooms, max_miles, per_night, origin, fetch_deadline):
|
||||
"""Phase 1 of a scan: Travelodge room prices, a few candidate nights at a time.
|
||||
|
||||
Mutates each night dict in `by_checkin` in place and bumps the matching
|
||||
counters on the shared `summary`, yielding ("night", summary snapshot,
|
||||
night copy) as each date answers - in completion order, not date order.
|
||||
One bad night must not sink the scan, so an upstream failure is recorded on
|
||||
that night only, and a night not started before `fetch_deadline` is marked
|
||||
"skipped" and sets summary["truncated"].
|
||||
"""
|
||||
|
||||
def fetch_night(ci, co):
|
||||
if time.monotonic() > fetch_deadline:
|
||||
return ci, "skipped", [], 0, "not fetched (time limit)"
|
||||
try:
|
||||
hotels = hotels_for(location, ci, co, rooms, deadline=fetch_deadline + 30)
|
||||
except UpstreamError as e:
|
||||
return ci, "failed", [], 0, str(e)
|
||||
avail, short = _shortlist(hotels, max_miles, per_night)
|
||||
return ci, "ok", short, len(avail), None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=SCAN_DATE_WORKERS) as ex:
|
||||
futures = [ex.submit(fetch_night, ci, co) for ci, co in candidates]
|
||||
try:
|
||||
for fut in as_completed(futures):
|
||||
ci, status, short, n_avail, detail = fut.result()
|
||||
night = by_checkin[ci]
|
||||
night["status"] = status
|
||||
night["detail"] = detail
|
||||
night["hotels_available"] = n_avail
|
||||
if status == "ok":
|
||||
night["hotels"] = [_make_row(h, origin) for h in short]
|
||||
if night["hotels"]:
|
||||
night["best_room"] = night["hotels"][0]["room_price"]
|
||||
summary["nights_fetched"] += 1
|
||||
elif status == "failed":
|
||||
summary["nights_failed"] += 1
|
||||
else:
|
||||
summary["nights_skipped"] += 1
|
||||
summary["truncated"] = True
|
||||
yield "night", dict(summary), _copy_night(night)
|
||||
finally:
|
||||
for f in futures:
|
||||
f.cancel()
|
||||
|
||||
|
||||
def _scan_order(night_list):
|
||||
"""Decide the order hotels get their (night-independent) fares priced in.
|
||||
|
||||
A hotel can appear on many nights but is priced once, so this collapses the
|
||||
nights into one entry per hotel code. Its ordering key is its best (lowest)
|
||||
position in any night's list, tiebroken by room price, so hotels that top
|
||||
some night get their fares first and a truncated scan still has the likely
|
||||
winners priced.
|
||||
|
||||
Returns:
|
||||
(ordered, cycle_base) where `ordered` is a list of minimal hotel dicts
|
||||
(code/lat/lon - all :func:`_price_hotels` reads) in pricing order, and
|
||||
`cycle_base` maps code -> the local cycle estimate already computed for
|
||||
that hotel, used when TfL gives no cycle answer. Deliberately *not* the
|
||||
live row objects: the ordering record and the output rows used to be the
|
||||
same mutable dict, which made it far too easy to write a phase-2 field
|
||||
onto one night's row by accident.
|
||||
"""
|
||||
best = {} # code -> (best rank, room price at that rank)
|
||||
coords = {} # code -> minimal hotel dict for _price_hotels
|
||||
cycle_base = {} # code -> the local cycle estimate already on the rows
|
||||
for n in night_list:
|
||||
for rank, row in enumerate(n["hotels"]):
|
||||
code = row["code"]
|
||||
key = (rank, row["room_price"])
|
||||
if code not in best or key < best[code]:
|
||||
best[code] = key
|
||||
if code not in coords:
|
||||
coords[code] = {"code": code, "lat": row["lat"], "lon": row["lon"]}
|
||||
# The estimate is a pure function of the coordinates, so any
|
||||
# night's row carries the same values.
|
||||
cycle_base[code] = {k: row[k] for k in ("cycle_minutes", "cycle_km", "cycle_source")}
|
||||
# sorted() is stable and `best` is in first-seen order, matching the old
|
||||
# index-based ordering exactly.
|
||||
ordered = [coords[code] for code in sorted(best, key=lambda c: best[c])]
|
||||
return ordered, cycle_base
|
||||
|
||||
|
||||
def _scan_transport(*, ordered, cycle_base, transport, summary, origin, depart_dt, adults, railcard_holders,
|
||||
max_travel_min, app_key, deadline):
|
||||
"""Phase 2 of a scan: one TfL price per unique hotel, filling `transport`.
|
||||
|
||||
`transport` is an out-parameter (code -> transport + cycle fields) that
|
||||
phase 3 then applies to every night containing that code. Yields
|
||||
("transport", summary snapshot, fields copy) per hotel as TfL answers.
|
||||
"""
|
||||
for code, t, cyc, timed_out in _price_hotels(
|
||||
ordered, origin, depart_dt, adults, railcard_holders, max_travel_min, app_key, deadline
|
||||
):
|
||||
# Transport here is night-independent, so there is no room price to add:
|
||||
# a dummy 0 is passed and the resulting "total" discarded. Each night
|
||||
# computes its own total in phase 3.
|
||||
fields = _transport_fields({"room_price": 0}, t)
|
||||
fields.pop("total", None)
|
||||
if timed_out:
|
||||
fields["route"] = TIME_LIMIT_ROUTE
|
||||
summary["truncated"] = True
|
||||
if cyc:
|
||||
fields["cycle_minutes"], fields["cycle_km"], fields["cycle_source"] = cyc
|
||||
else:
|
||||
# No TfL cycle result: keep the local estimate computed when the
|
||||
# rows were built, since these fields are copied wholesale onto
|
||||
# every night's copy of this hotel.
|
||||
fields.update(cycle_base.get(code, {}))
|
||||
fields["code"] = code
|
||||
transport[code] = fields
|
||||
summary["hotels_priced"] += 1
|
||||
yield "transport", dict(summary), dict(fields)
|
||||
|
||||
|
||||
def _scan_totals(night_list, transport, summary) -> None:
|
||||
"""Phase 3 of a scan: apply transport to every night and order the results.
|
||||
|
||||
Mutates `night_list` in place: fills each row's transport columns and total,
|
||||
sorts each night's hotels, records the night's best total/room/code, and
|
||||
finally sorts the nights themselves. A hotel with no entry in `transport`
|
||||
was never reached before the deadline, which is marked on the row *and* on
|
||||
summary["truncated"] - phase 2 only sets the flag for hotels it actually
|
||||
started, so without this a scan could show unpriced rows while claiming it
|
||||
was complete.
|
||||
"""
|
||||
for n in night_list:
|
||||
if n["status"] != "ok":
|
||||
continue
|
||||
for row in n["hotels"]:
|
||||
fields = transport.get(row["code"])
|
||||
# Missing means phase 2 ran out of time before reaching this hotel.
|
||||
if fields is None:
|
||||
row["route"] = TIME_LIMIT_ROUTE
|
||||
summary["truncated"] = True
|
||||
continue
|
||||
row.update({k: v for k, v in fields.items() if k != "code"})
|
||||
if row["transport_total"] is not None:
|
||||
row["total"] = round(row["room_price"] + row["transport_total"], 2)
|
||||
sort_rows(n["hotels"])
|
||||
if n["hotels"]:
|
||||
best = n["hotels"][0]
|
||||
n["best_total"] = best["total"]
|
||||
n["best_code"] = best["code"]
|
||||
n["best_room"] = min(r["room_price"] for r in n["hotels"])
|
||||
|
||||
# Cheapest night first; nights with no total (failed, skipped, or unpriced)
|
||||
# fall to the bottom, ordered by best room price and then by date so the
|
||||
# list is still deterministic.
|
||||
night_list.sort(
|
||||
key=lambda n: (
|
||||
n["best_total"] is None,
|
||||
n["best_total"] or 0,
|
||||
n["best_room"] is None,
|
||||
n["best_room"] or 0,
|
||||
n["checkin"],
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def run_scan(
|
||||
*,
|
||||
location: str,
|
||||
@@ -1152,112 +1433,37 @@ def run_scan(
|
||||
}
|
||||
yield "scan", dict(summary), [_copy_night(n) for n in night_list]
|
||||
|
||||
# Phase 1: room prices, a few nights at a time. One bad night must not
|
||||
# sink the scan, so upstream failures are recorded on that night only.
|
||||
def fetch_night(ci, co):
|
||||
if time.monotonic() > fetch_deadline:
|
||||
return ci, "skipped", [], 0, "not fetched (time limit)"
|
||||
try:
|
||||
hotels = hotels_for(location, ci, co, rooms, deadline=fetch_deadline + 30)
|
||||
except UpstreamError as e:
|
||||
return ci, "failed", [], 0, str(e)
|
||||
avail, short = _shortlist(hotels, max_miles, per_night)
|
||||
return ci, "ok", short, len(avail), None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=SCAN_DATE_WORKERS) as ex:
|
||||
futures = [ex.submit(fetch_night, ci, co) for ci, co in candidates]
|
||||
try:
|
||||
for fut in as_completed(futures):
|
||||
ci, status, short, n_avail, detail = fut.result()
|
||||
night = by_checkin[ci]
|
||||
night["status"] = status
|
||||
night["detail"] = detail
|
||||
night["hotels_available"] = n_avail
|
||||
if status == "ok":
|
||||
night["hotels"] = [_make_row(h, origin) for h in short]
|
||||
if night["hotels"]:
|
||||
night["best_room"] = night["hotels"][0]["room_price"]
|
||||
summary["nights_fetched"] += 1
|
||||
elif status == "failed":
|
||||
summary["nights_failed"] += 1
|
||||
else:
|
||||
summary["nights_skipped"] += 1
|
||||
summary["truncated"] = True
|
||||
yield "night", dict(summary), _copy_night(night)
|
||||
finally:
|
||||
for f in futures:
|
||||
f.cancel()
|
||||
|
||||
# Phase 2: one TfL price per unique hotel. Hotels that are cheapest on some
|
||||
# night go first, since they are the likely winners if time runs out.
|
||||
# A hotel can appear on many nights; it is priced once. Its ordering key is
|
||||
# its best (lowest) position in any night's list, tiebroken by price, so
|
||||
# hotels that top some night get their fares first and a truncated scan
|
||||
# still has the likely winners priced.
|
||||
index = {} # code -> ((best rank, min room price), row)
|
||||
for n in night_list:
|
||||
for rank, row in enumerate(n["hotels"]):
|
||||
key = (rank, row["room_price"])
|
||||
cur = index.get(row["code"])
|
||||
if cur is None or key < cur[0]:
|
||||
index[row["code"]] = (key, row)
|
||||
ordered = [row for _, row in sorted(index.values(), key=lambda x: x[0])]
|
||||
summary["hotels_unique"] = len(ordered)
|
||||
|
||||
transport = {} # code -> transport + cycle fields
|
||||
for code, t, cyc, timed_out in _price_hotels(
|
||||
ordered, origin, depart_dt, adults, railcard_holders, max_travel_min, app_key, deadline
|
||||
):
|
||||
base = index[code][1]
|
||||
# Transport here is night-independent, so there is no room price to add:
|
||||
# a dummy 0 is passed and the resulting "total" discarded. Each night
|
||||
# computes its own total in phase 3.
|
||||
fields = _transport_fields({"room_price": 0}, t)
|
||||
fields.pop("total", None)
|
||||
if timed_out:
|
||||
fields["route"] = TIME_LIMIT_ROUTE
|
||||
summary["truncated"] = True
|
||||
if cyc:
|
||||
fields["cycle_minutes"], fields["cycle_km"], fields["cycle_source"] = cyc
|
||||
else:
|
||||
# No TfL cycle result: keep the local estimate already on the row,
|
||||
# since these fields are copied wholesale onto every night's copy.
|
||||
fields.update({k: base[k] for k in ("cycle_minutes", "cycle_km", "cycle_source")})
|
||||
fields["code"] = code
|
||||
transport[code] = fields
|
||||
summary["hotels_priced"] += 1
|
||||
yield "transport", dict(summary), dict(fields)
|
||||
|
||||
# Phase 3: totals per night.
|
||||
for n in night_list:
|
||||
if n["status"] != "ok":
|
||||
continue
|
||||
for row in n["hotels"]:
|
||||
fields = transport.get(row["code"])
|
||||
# Missing means phase 2 ran out of time before reaching this hotel.
|
||||
if fields is None:
|
||||
row["route"] = TIME_LIMIT_ROUTE
|
||||
continue
|
||||
row.update({k: v for k, v in fields.items() if k != "code"})
|
||||
if row["transport_total"] is not None:
|
||||
row["total"] = round(row["room_price"] + row["transport_total"], 2)
|
||||
sort_rows(n["hotels"])
|
||||
if n["hotels"]:
|
||||
best = n["hotels"][0]
|
||||
n["best_total"] = best["total"]
|
||||
n["best_code"] = best["code"]
|
||||
n["best_room"] = min(r["room_price"] for r in n["hotels"])
|
||||
|
||||
# Cheapest night first; nights with no total (failed, skipped, or unpriced)
|
||||
# fall to the bottom, ordered by best room price and then by date so the
|
||||
# list is still deterministic.
|
||||
night_list.sort(
|
||||
key=lambda n: (
|
||||
n["best_total"] is None,
|
||||
n["best_total"] or 0,
|
||||
n["best_room"] is None,
|
||||
n["best_room"] or 0,
|
||||
n["checkin"],
|
||||
)
|
||||
# Phase 1: room prices per candidate night.
|
||||
yield from _scan_rooms(
|
||||
candidates=candidates,
|
||||
by_checkin=by_checkin,
|
||||
summary=summary,
|
||||
location=location,
|
||||
rooms=rooms,
|
||||
max_miles=max_miles,
|
||||
per_night=per_night,
|
||||
origin=origin,
|
||||
fetch_deadline=fetch_deadline,
|
||||
)
|
||||
|
||||
# Phase 2: one TfL price per unique hotel, cheapest-on-some-night first.
|
||||
ordered, cycle_base = _scan_order(night_list)
|
||||
summary["hotels_unique"] = len(ordered)
|
||||
transport = {} # code -> transport + cycle fields
|
||||
yield from _scan_transport(
|
||||
ordered=ordered,
|
||||
cycle_base=cycle_base,
|
||||
transport=transport,
|
||||
summary=summary,
|
||||
origin=origin,
|
||||
depart_dt=depart_dt,
|
||||
adults=adults,
|
||||
railcard_holders=railcard_holders,
|
||||
max_travel_min=max_travel_min,
|
||||
app_key=app_key,
|
||||
deadline=deadline,
|
||||
)
|
||||
|
||||
# Phase 3: totals per night, then ordering.
|
||||
_scan_totals(night_list, transport, summary)
|
||||
yield "done", dict(summary), [_copy_night(n) for n in night_list]
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Decorative animated colour bars. STATUS: not imported anywhere.
|
||||
*
|
||||
* Two known problems if it is ever revived: the call
|
||||
* `generateOffsets((150, 15, 10))` uses the comma operator, so it passes a single
|
||||
* argument 10 as `width` and the other two defaults apply; and animate() logs to
|
||||
* the console on every frame.
|
||||
*/
|
||||
import { ref, onMounted, useTemplateRef, onUnmounted } from "vue";
|
||||
import { getRandomColor } from "@/js/utils";
|
||||
@@ -20,7 +15,7 @@ function generateOffsets(width = 100, step = 10, n = 20) {
|
||||
color: getRandomColor(),
|
||||
}));
|
||||
}
|
||||
const offsets = ref(generateOffsets((150, 15, 10)));
|
||||
const offsets = ref(generateOffsets(150, 15, 10));
|
||||
let rafId;
|
||||
|
||||
const speed = 0.5; // pixels per frame
|
||||
@@ -30,8 +25,6 @@ function animate() {
|
||||
for (const item of offsets.value) {
|
||||
const width = Math.max(ctnr.offsetWidth, item.width);
|
||||
|
||||
console.log(ctnr.offsetWidth);
|
||||
|
||||
item.offset -= speed;
|
||||
if (item.offset <= -width) {
|
||||
item.color = getRandomColor();
|
||||
|
||||
@@ -1,22 +1,14 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Link styled to sit inside running prose (bold italic, no underline). Same
|
||||
* `to` vs `href` and auto-`rel` behaviour as Link.vue.
|
||||
* `to` vs `href` and auto-`rel` behaviour as Link.vue, shared through
|
||||
* useLinkAttrs.js.
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
import { linkProps, useComputedRel } from "@/components/text/useLinkAttrs";
|
||||
|
||||
const props = defineProps({
|
||||
href: { type: String, default: "" },
|
||||
to: { type: String, default: "" },
|
||||
target: { type: String, default: undefined },
|
||||
rel: { type: String, default: undefined },
|
||||
});
|
||||
const props = defineProps({ ...linkProps });
|
||||
|
||||
const computedRel = computed(() => {
|
||||
if (props.rel !== undefined) return props.rel;
|
||||
if (props.target === "_blank") return "noopener noreferrer";
|
||||
return undefined;
|
||||
});
|
||||
const computedRel = useComputedRel(props);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -2,23 +2,17 @@
|
||||
/**
|
||||
* Standard link. Renders a <RouterLink> when given `to`, a plain <a> when given
|
||||
* `href`. `bare` drops the styling (used where the parent styles the anchor).
|
||||
* External `target="_blank"` links get rel="noopener noreferrer" automatically.
|
||||
* External `target="_blank"` links get rel="noopener noreferrer" automatically
|
||||
* (shared with InlineLink.vue via useLinkAttrs.js).
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
import { linkProps, useComputedRel } from "@/components/text/useLinkAttrs";
|
||||
|
||||
const props = defineProps({
|
||||
href: { type: String, default: "" },
|
||||
to: { type: String, default: "" },
|
||||
target: { type: String, default: undefined },
|
||||
rel: { type: String, default: undefined },
|
||||
...linkProps,
|
||||
bare: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const computedRel = computed(() => {
|
||||
if (props.rel !== undefined) return props.rel;
|
||||
if (props.target === "_blank") return "noopener noreferrer";
|
||||
return undefined;
|
||||
});
|
||||
const computedRel = useComputedRel(props);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// Shared link behaviour for components/text/Link.vue and InlineLink.vue, which
|
||||
// render the same thing (a <RouterLink> for `to`, an <a> for `href`) and differ
|
||||
// only in styling.
|
||||
|
||||
import { computed } from "vue";
|
||||
|
||||
/** Props every link component accepts. Spread into defineProps(). */
|
||||
export const linkProps = {
|
||||
href: { type: String, default: "" },
|
||||
to: { type: String, default: "" },
|
||||
target: { type: String, default: undefined },
|
||||
rel: { type: String, default: undefined },
|
||||
};
|
||||
|
||||
/**
|
||||
* `rel` for the rendered <a>: an explicit `rel` prop wins, otherwise
|
||||
* target="_blank" links get noopener/noreferrer so the opened page cannot
|
||||
* reach back through window.opener.
|
||||
*/
|
||||
export function useComputedRel(props) {
|
||||
return computed(() => {
|
||||
if (props.rel !== undefined) return props.rel;
|
||||
if (props.target === "_blank") return "noopener noreferrer";
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
@@ -87,6 +87,8 @@ async function onFileSelected(e) {
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
isNearBottom.value = true;
|
||||
// The private flag both routes the upload to /uploads/private/ and marks the
|
||||
// message itself private; the two must agree.
|
||||
await messagesStore.uploadAndSendFile(
|
||||
file,
|
||||
isAdmin.value && sendPrivate.value,
|
||||
@@ -102,10 +104,19 @@ function isVideoUrl(url) {
|
||||
return /\.(mp4|webm|ogg|mov)$/i.test(url);
|
||||
}
|
||||
|
||||
// Public attachments live under /uploads/; attachments on private messages are
|
||||
// written under /uploads/private/, which nginx gates behind an admin check.
|
||||
const UPLOAD_PREFIXES = ["/uploads/", "/uploads/private/"];
|
||||
|
||||
/** Only render attachments the backend served from its own upload directory —
|
||||
* the fileUrl arrives over the socket and is otherwise attacker-controlled. */
|
||||
* the fileUrl arrives over the socket and is otherwise attacker-controlled.
|
||||
* A strict prefix allowlist, so absolute ("https://evil/uploads/x") and
|
||||
* protocol-relative ("//evil/uploads/x") URLs are rejected; "..", which could
|
||||
* otherwise escape the directory, is rejected outright. */
|
||||
function isSafeFileUrl(url) {
|
||||
return typeof url === "string" && url.startsWith("/uploads/");
|
||||
if (typeof url !== "string") return false;
|
||||
if (url.includes("..")) return false;
|
||||
return UPLOAD_PREFIXES.some((prefix) => url.startsWith(prefix));
|
||||
}
|
||||
|
||||
// NOTE: a module-level /g regex carries `lastIndex` between calls. It is safe
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
* Renders a list of {name, link, type} either as stacked link buttons
|
||||
* (variant="list") or as a two-column table (variant="table").
|
||||
*
|
||||
* Passing `title` wraps the whole thing in a collapsible <ToggleHeader>.
|
||||
* Passing `title` wraps the whole thing in a collapsible <ToggleHeader> (and a
|
||||
* .h-fit.w-full div); without a title the items are rendered bare. The items
|
||||
* themselves live in LinkTableItems.vue so both branches share one copy.
|
||||
* Used by the Bookmarks, Favorites, Consumption and Links widgets.
|
||||
*/
|
||||
import { ref } from "vue";
|
||||
import Link from "@/components/text/Link.vue";
|
||||
import LinkTableItems from "@/components/util/LinkTableItems.vue";
|
||||
import ToggleHeader from "@/components/text/ToggleHeader.vue";
|
||||
|
||||
const props = defineProps({
|
||||
@@ -33,44 +35,7 @@ const show = ref(false);
|
||||
<ToggleHeader v-model="show" class="justify-between flex items-center">
|
||||
{{ title }}
|
||||
</ToggleHeader>
|
||||
<template v-if="show">
|
||||
<Link
|
||||
v-if="variant === 'list'"
|
||||
v-for="(item, i) in items"
|
||||
:key="i"
|
||||
:href="item.link"
|
||||
>
|
||||
<p class="bdr-2 bg-surface-tint">{{ item.name }}</p>
|
||||
</Link>
|
||||
<table class="w-full" v-else>
|
||||
<tbody>
|
||||
<tr v-for="item in items" :key="item.id">
|
||||
<th>{{ item.type }}</th>
|
||||
<td v-if="item.link">
|
||||
<Link :href="item.link">{{ item.name }}</Link>
|
||||
</td>
|
||||
<td v-else>{{ item.name }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</template>
|
||||
<LinkTableItems v-if="show" :items="items" :variant="variant" />
|
||||
</div>
|
||||
<template v-else>
|
||||
<template v-if="variant === 'list'">
|
||||
<Link v-for="(item, i) in items" :key="i" :href="item.link">
|
||||
<p class="bdr-2 bg-surface-tint">{{ item.name }}</p>
|
||||
</Link>
|
||||
</template>
|
||||
<table class="w-full" v-else>
|
||||
<tbody>
|
||||
<tr v-for="item in items" :key="item.id">
|
||||
<th>{{ item.type }}</th>
|
||||
<td v-if="item.link">
|
||||
<Link :href="item.link">{{ item.name }}</Link>
|
||||
</td>
|
||||
<td v-else>{{ item.name }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</template>
|
||||
<LinkTableItems v-else :items="items" :variant="variant" />
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<script setup>
|
||||
/**
|
||||
* The body of LinkTable.vue: the items rendered either as stacked link buttons
|
||||
* (variant="list") or as a two-column table (variant="table").
|
||||
*
|
||||
* Split out only so LinkTable can render the same markup inside and outside its
|
||||
* collapsible <ToggleHeader> wrapper without duplicating it. A component adds no
|
||||
* DOM of its own, so the rendered output is unchanged.
|
||||
*/
|
||||
import Link from "@/components/text/Link.vue";
|
||||
|
||||
defineProps({
|
||||
items: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
variant: {
|
||||
type: String,
|
||||
default: "list",
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-if="variant === 'list'">
|
||||
<Link v-for="(item, i) in items" :key="i" :href="item.link">
|
||||
<p class="bdr-2 bg-surface-tint">{{ item.name }}</p>
|
||||
</Link>
|
||||
</template>
|
||||
<table class="w-full" v-else>
|
||||
<tbody>
|
||||
<tr v-for="item in items" :key="item.id">
|
||||
<th>{{ item.type }}</th>
|
||||
<td v-if="item.link">
|
||||
<Link :href="item.link">{{ item.name }}</Link>
|
||||
</td>
|
||||
<td v-else>{{ item.name }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</template>
|
||||
@@ -21,10 +21,7 @@ const resolvedColumns = computed(() => {
|
||||
Object.keys(obj).forEach((key) => keys.add(key));
|
||||
}
|
||||
|
||||
return Array.from(keys).map((key) => ({
|
||||
key,
|
||||
label: key,
|
||||
}));
|
||||
return Array.from(keys);
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -32,16 +29,16 @@ const resolvedColumns = computed(() => {
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th v-for="col in resolvedColumns" :key="col.key">
|
||||
{{ col.label }}
|
||||
<th v-for="col in resolvedColumns" :key="col">
|
||||
{{ col }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
<tr v-for="(row, rowIndex) in objArr" :key="rowIndex">
|
||||
<td v-for="col in resolvedColumns" :key="col.key">
|
||||
{{ row[col.key] ?? "" }}
|
||||
<td v-for="col in resolvedColumns" :key="col">
|
||||
{{ row[col] ?? "" }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
*/
|
||||
import Button from "@/components/input/Button.vue";
|
||||
import Header from "@/components/text/Header.vue";
|
||||
import { ref, useTemplateRef, onMounted, nextTick } from "vue";
|
||||
import { ref, useTemplateRef, onMounted, onUnmounted, nextTick } from "vue";
|
||||
import axios from "axios";
|
||||
|
||||
const POLL_INTERVAL_MS = 120000; // re-probe the stream every 2 minutes
|
||||
@@ -54,9 +54,15 @@ async function checkStream() {
|
||||
}
|
||||
}
|
||||
|
||||
let pollId;
|
||||
|
||||
onMounted(() => {
|
||||
checkStream();
|
||||
setInterval(checkStream, POLL_INTERVAL_MS);
|
||||
pollId = setInterval(checkStream, POLL_INTERVAL_MS);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
clearInterval(pollId);
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Clock and date widget. updateDateTime() runs once immediately and then every
|
||||
* minute. Note the interval is module-level and never cleared — harmless because
|
||||
* the widget lives for the life of the home page, but it would leak if reused.
|
||||
* minute, with the interval owned by the component lifecycle so it is cleared
|
||||
* on unmount.
|
||||
*/
|
||||
import Header from "@/components/text/Header.vue";
|
||||
import { ref } from "vue";
|
||||
import { ref, onMounted, onUnmounted } from "vue";
|
||||
|
||||
const time = ref("");
|
||||
const weekday = ref("");
|
||||
@@ -25,7 +25,15 @@ function updateDateTime() {
|
||||
|
||||
updateDateTime();
|
||||
|
||||
setInterval(updateDateTime, 60000);
|
||||
let intervalId;
|
||||
|
||||
onMounted(() => {
|
||||
intervalId = setInterval(updateDateTime, 60000);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
clearInterval(intervalId);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -2,18 +2,20 @@
|
||||
/**
|
||||
* Countdown widget with minute/second sliders and a sound on completion.
|
||||
*
|
||||
* The four mutually exclusive v-if blocks are a state machine over
|
||||
* (finished, paused): set/idle, finished, paused, running.
|
||||
* `state` is an explicit state machine — "idle" (sliders), "running",
|
||||
* "paused" and "finished" — one screen per state. Completion is decided by
|
||||
* comparing total elapsed seconds with the total target, so it does not depend
|
||||
* on the minute and second fields crossing their targets independently.
|
||||
*/
|
||||
import Button from "@/components/input/Button.vue";
|
||||
import Header from "@/components/text/Header.vue";
|
||||
|
||||
import { ref } from "vue";
|
||||
import { ref, onUnmounted } from "vue";
|
||||
|
||||
const timer = ref(null);
|
||||
|
||||
const finished = ref(true);
|
||||
const paused = ref(true);
|
||||
/** "idle" | "running" | "paused" | "finished" */
|
||||
const state = ref("idle");
|
||||
|
||||
const minutesInput = ref(0);
|
||||
const secondsInput = ref(0);
|
||||
@@ -30,41 +32,45 @@ function tick() {
|
||||
seconds.value = 0;
|
||||
}
|
||||
|
||||
if (minutes.value >= minutesInput.value) {
|
||||
if (seconds.value >= secondsInput.value) {
|
||||
finished.value = true;
|
||||
playFinishedSound();
|
||||
clearInterval(timer.value);
|
||||
}
|
||||
const elapsed = minutes.value * 60 + seconds.value;
|
||||
const target = Number(minutesInput.value) * 60 + Number(secondsInput.value);
|
||||
|
||||
if (elapsed >= target) {
|
||||
state.value = "finished";
|
||||
playFinishedSound();
|
||||
clearInterval(timer.value);
|
||||
}
|
||||
}
|
||||
|
||||
function startTimer() {
|
||||
finished.value = false;
|
||||
paused.value = false;
|
||||
state.value = "running";
|
||||
timer.value = setInterval(tick, 1000);
|
||||
}
|
||||
|
||||
function pauseTimer() {
|
||||
if (finished.value) return;
|
||||
if (state.value === "finished") return;
|
||||
|
||||
if (paused.value) {
|
||||
if (state.value === "paused") {
|
||||
timer.value = setInterval(tick, 1000);
|
||||
paused.value = false;
|
||||
state.value = "running";
|
||||
} else {
|
||||
clearInterval(timer.value);
|
||||
paused.value = true;
|
||||
state.value = "paused";
|
||||
}
|
||||
}
|
||||
|
||||
/** Back to the slider screen, ready to set a new countdown. */
|
||||
function resetTimer() {
|
||||
finished.value = true;
|
||||
paused.value = true;
|
||||
state.value = "idle";
|
||||
clearInterval(timer.value);
|
||||
minutes.value = 0;
|
||||
seconds.value = 0;
|
||||
}
|
||||
|
||||
onUnmounted(() => {
|
||||
clearInterval(timer.value);
|
||||
});
|
||||
|
||||
function playFinishedSound() {
|
||||
audio.play();
|
||||
}
|
||||
@@ -73,7 +79,7 @@ function playFinishedSound() {
|
||||
<template>
|
||||
<div class="timer-root flex flex-col gap-1 p-1 items-center">
|
||||
<Header>Timer</Header>
|
||||
<div v-if="finished && paused" class="flex flex-col">
|
||||
<div v-if="state === 'idle'" class="flex flex-col">
|
||||
<div class="flex flex-row p-2 place-content-around">
|
||||
<input
|
||||
class="w-2/3"
|
||||
@@ -98,15 +104,15 @@ function playFinishedSound() {
|
||||
</div>
|
||||
<Button @click="startTimer">Proceed</Button>
|
||||
</div>
|
||||
<div v-if="finished && !paused" class="flex flex-col">
|
||||
<div v-if="state === 'finished'" class="flex flex-col">
|
||||
<h1>Timer finished!</h1>
|
||||
<Button @click="resetTimer">Reset</Button>
|
||||
</div>
|
||||
<div v-if="!finished && paused" class="flex flex-col">
|
||||
<div v-if="state === 'paused'" class="flex flex-col">
|
||||
<h1>Paused</h1>
|
||||
<Button @click="resetTimer">Reset</Button>
|
||||
</div>
|
||||
<div v-if="!finished && !paused" class="flex flex-col">
|
||||
<div v-if="state === 'running'" class="flex flex-col">
|
||||
<p>
|
||||
{{ minutes.toString().padStart(2, "0") }}:{{
|
||||
seconds.toString().padStart(2, "0")
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// The shared body of the admin "create X" forms (CreatePost, CreateFavorite,
|
||||
// CreateActivity, CreateBookmark): a ref per field, a GraphQL mutation taking a
|
||||
// single `input`, clear the fields on success, then emit "done" so the host
|
||||
// modal can close. Failures are logged and leave the fields alone, exactly as
|
||||
// the hand-written versions did.
|
||||
|
||||
import { ref } from "vue";
|
||||
import { gql } from "@/graphql";
|
||||
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {string} options.mutation GraphQL mutation with one $input variable
|
||||
* @param {string[]} options.fields input field names, one text ref each
|
||||
* @param {(event: string) => void} options.emit the component's emit
|
||||
* @param {string[]} [options.optional] fields sent as undefined when blank,
|
||||
* so the backend sees "not set" rather than an empty string
|
||||
* @param {string} [options.resultKey] mutation field to log on success
|
||||
* @returns {{ values: Record<string, import("vue").Ref<string>>, submit: () => Promise<void> }}
|
||||
*/
|
||||
export function useCreateForm({
|
||||
mutation,
|
||||
fields,
|
||||
emit,
|
||||
optional = [],
|
||||
resultKey,
|
||||
}) {
|
||||
const values = Object.fromEntries(fields.map((name) => [name, ref("")]));
|
||||
|
||||
async function submit() {
|
||||
try {
|
||||
const input = {};
|
||||
for (const name of fields) {
|
||||
const value = values[name].value;
|
||||
input[name] = optional.includes(name) ? value || undefined : value;
|
||||
}
|
||||
const data = await gql(mutation, { input });
|
||||
for (const name of fields) values[name].value = "";
|
||||
if (resultKey) console.log(data[resultKey]);
|
||||
emit("done");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
return { values, submit };
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Rotate through a list on a timer, as the Listening and Steam widgets do.
|
||||
//
|
||||
// A self-rearming setTimeout rather than setInterval, so clicking to advance
|
||||
// manually restarts the full delay instead of leaving whatever was left of the
|
||||
// current tick. An optional periodic refresh callback covers the "re-poll the
|
||||
// source every few minutes" half of the same pattern. Both timers are cleared
|
||||
// on unmount.
|
||||
|
||||
import { ref, unref, onMounted, onUnmounted } from "vue";
|
||||
|
||||
/**
|
||||
* @param {import("vue").Ref<Array>|(() => Array)} items the list being rotated
|
||||
* @param {number} ms delay between rotations
|
||||
* @param {object} [options]
|
||||
* @param {() => void} [options.refresh] called every refreshMs
|
||||
* @param {number} [options.refreshMs] refresh interval
|
||||
* @returns {{ idx: import("vue").Ref<number>, next: () => void }}
|
||||
*/
|
||||
export function useRotation(items, ms, { refresh, refreshMs } = {}) {
|
||||
const idx = ref(0);
|
||||
let nextId = null;
|
||||
let refreshId = null;
|
||||
|
||||
function list() {
|
||||
return (typeof items === "function" ? items() : unref(items)) ?? [];
|
||||
}
|
||||
|
||||
/** Advance one step and re-arm. Leaves the index alone on an empty list. */
|
||||
function next() {
|
||||
clearTimeout(nextId);
|
||||
nextId = setTimeout(next, ms);
|
||||
const count = list().length;
|
||||
if (count) idx.value = (idx.value + 1) % count;
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
nextId = setTimeout(next, ms);
|
||||
if (refresh && refreshMs) refreshId = setInterval(refresh, refreshMs);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
clearTimeout(nextId);
|
||||
clearInterval(refreshId);
|
||||
});
|
||||
|
||||
return { idx, next };
|
||||
}
|
||||
+11
-30
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* Media/activity log for the Consumption widget. A view over homeData.activities;
|
||||
* see stores/posts.js for the placeholder-then-overwrite pattern.
|
||||
* Media/activity log for the Consumption widget. A view over homeData.activities,
|
||||
* built by createMirrorStore(); see stores/createMirrorStore.js for the
|
||||
* placeholder-then-overwrite pattern.
|
||||
*/
|
||||
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useHomeDataStore } from "@/stores/homeData";
|
||||
import { createMirrorStore } from "@/stores/createMirrorStore";
|
||||
|
||||
const activity_template = {
|
||||
type: "activity",
|
||||
@@ -14,33 +14,14 @@ const activity_template = {
|
||||
};
|
||||
|
||||
export const useActivityStore = defineStore("activity", () => {
|
||||
const activity = ref([activity_template]);
|
||||
|
||||
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) => {
|
||||
if (newActivities.length > 0) {
|
||||
activity.value = newActivities;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** Refresh by re-running the whole home query; the watch above applies it. */
|
||||
async function fetchActivity() {
|
||||
await homeData.fetchAll();
|
||||
}
|
||||
const { items, count, fetch } = createMirrorStore({
|
||||
slice: "activities",
|
||||
template: activity_template,
|
||||
});
|
||||
|
||||
return {
|
||||
activity,
|
||||
activityCount,
|
||||
fetchActivity,
|
||||
activity: items,
|
||||
activityCount: count,
|
||||
fetchActivity: fetch,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Factory for the "mirror store" pattern shared by stores/posts.js,
|
||||
* favorites.js and activity.js.
|
||||
*
|
||||
* Each of those is a thin view over one slice of the shared home query
|
||||
* (stores/homeData.js): a ref seeded with placeholder content, an `immediate`
|
||||
* watch that copies the homeData slice in, a count computed and a fetch
|
||||
* function that just re-runs the whole home query.
|
||||
*
|
||||
* The state/getter/action names differ per store and components import them by
|
||||
* name, so the caller supplies them explicitly rather than having them derived.
|
||||
*/
|
||||
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useHomeDataStore } from "@/stores/homeData";
|
||||
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {string} options.slice key on the homeData store to mirror
|
||||
* @param {*} options.template placeholder item shown before a successful fetch
|
||||
* @returns {{ items: import("vue").Ref, count: import("vue").ComputedRef, fetch: () => Promise<void>, homeData: object }}
|
||||
*/
|
||||
export function createMirrorStore({ slice, template }) {
|
||||
const items = ref([template]);
|
||||
|
||||
const count = computed(() => items.value.length);
|
||||
|
||||
const homeData = useHomeDataStore();
|
||||
// `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[slice],
|
||||
(newItems) => {
|
||||
if (newItems.length > 0) {
|
||||
items.value = newItems;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** Refresh by re-running the whole home query; the watch above applies it. */
|
||||
async function fetch() {
|
||||
await homeData.fetchAll();
|
||||
}
|
||||
|
||||
return { items, count, fetch, homeData };
|
||||
}
|
||||
+11
-30
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* Favourites for the Favorites widget. A view over homeData.favorites; see
|
||||
* stores/posts.js for the placeholder-then-overwrite pattern.
|
||||
* Favourites for the Favorites widget. A view over homeData.favorites, built by
|
||||
* createMirrorStore(); see stores/createMirrorStore.js for the
|
||||
* placeholder-then-overwrite pattern.
|
||||
*/
|
||||
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useHomeDataStore } from "@/stores/homeData";
|
||||
import { createMirrorStore } from "@/stores/createMirrorStore";
|
||||
|
||||
const favorite_template = {
|
||||
type: "favorite",
|
||||
@@ -14,33 +14,14 @@ const favorite_template = {
|
||||
};
|
||||
|
||||
export const useFavoritesStore = defineStore("favorites", () => {
|
||||
const favorites = ref([favorite_template]);
|
||||
|
||||
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) => {
|
||||
if (newFavorites.length > 0) {
|
||||
favorites.value = newFavorites;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** Refresh by re-running the whole home query; the watch above applies it. */
|
||||
async function fetchFavorites() {
|
||||
await homeData.fetchAll();
|
||||
}
|
||||
const { items, count, fetch } = createMirrorStore({
|
||||
slice: "favorites",
|
||||
template: favorite_template,
|
||||
});
|
||||
|
||||
return {
|
||||
favorites,
|
||||
favoritesCount,
|
||||
fetchFavorites,
|
||||
favorites: items,
|
||||
favoritesCount: count,
|
||||
fetchFavorites: fetch,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -136,11 +136,16 @@ export const useMessagesStore = defineStore("messages", () => {
|
||||
* 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`.
|
||||
*
|
||||
* `private` is sent with the upload as well as with the message: the backend
|
||||
* stores private attachments under /uploads/private/, which nginx gates
|
||||
* behind an admin check.
|
||||
*/
|
||||
async function uploadAndSendFile(file, isPrivate = false) {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append("private", isPrivate ? "true" : "false");
|
||||
const res = await axios.post("/api/messages/upload", formData);
|
||||
const { url } = res.data;
|
||||
if (!socket.value || !isConnected.value) return;
|
||||
|
||||
+12
-31
@@ -1,15 +1,15 @@
|
||||
/**
|
||||
* Blog posts for the Feed widget. A view over homeData.posts.
|
||||
* Blog posts for the Feed widget. A view over homeData.posts, built by
|
||||
* createMirrorStore(); see stores/createMirrorStore.js for the
|
||||
* placeholder-then-overwrite pattern.
|
||||
*
|
||||
* `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.
|
||||
* successful fetch, so the widget never flashes empty.
|
||||
*/
|
||||
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { gql } from "@/graphql";
|
||||
import { useHomeDataStore } from "@/stores/homeData";
|
||||
import { createMirrorStore } from "@/stores/createMirrorStore";
|
||||
|
||||
const post_template = {
|
||||
title: "Can't fetch from the db yo",
|
||||
@@ -22,29 +22,10 @@ const post_template = {
|
||||
};
|
||||
|
||||
export const usePostsStore = defineStore("posts", () => {
|
||||
const posts = ref([post_template]);
|
||||
|
||||
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) => {
|
||||
if (newPosts.length > 0) {
|
||||
posts.value = newPosts;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** Refresh by re-running the whole home query; the watch above applies it. */
|
||||
async function fetchPosts() {
|
||||
await homeData.fetchAll();
|
||||
}
|
||||
const { items, count, fetch, homeData } = createMirrorStore({
|
||||
slice: "posts",
|
||||
template: post_template,
|
||||
});
|
||||
|
||||
/** Soft-delete a post, then refetch so every widget sees the new list. */
|
||||
async function deletePost(post) {
|
||||
@@ -61,11 +42,11 @@ export const usePostsStore = defineStore("posts", () => {
|
||||
}
|
||||
|
||||
return {
|
||||
posts,
|
||||
posts: items,
|
||||
|
||||
postsCount,
|
||||
postsCount: count,
|
||||
|
||||
fetchPosts,
|
||||
fetchPosts: fetch,
|
||||
deletePost,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -3,37 +3,19 @@
|
||||
* Admin form: log a consumed book/film/game. Emits "done"/"cancel".
|
||||
*/
|
||||
import Button from "@/components/input/Button.vue";
|
||||
import { useCreateForm } from "@/js/useCreateForm";
|
||||
|
||||
import { ref } from "vue";
|
||||
import { gql } from "@/graphql";
|
||||
|
||||
const emit = defineEmits(["done", "cancel"]);
|
||||
|
||||
const type = ref("");
|
||||
const name = ref("");
|
||||
const link = ref("");
|
||||
|
||||
async function post() {
|
||||
try {
|
||||
const data = await gql(
|
||||
`mutation CreateActivity($input: CreateActivityInput!) { createActivity(input: $input) { id } }`,
|
||||
{
|
||||
input: {
|
||||
type: type.value,
|
||||
name: name.value,
|
||||
link: link.value || undefined,
|
||||
},
|
||||
},
|
||||
);
|
||||
type.value = "";
|
||||
name.value = "";
|
||||
link.value = "";
|
||||
console.log(data.createActivity);
|
||||
emit("done");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
const { values, submit: post } = useCreateForm({
|
||||
mutation: `mutation CreateActivity($input: CreateActivityInput!) { createActivity(input: $input) { id } }`,
|
||||
fields: ["type", "name", "link"],
|
||||
optional: ["link"],
|
||||
resultKey: "createActivity",
|
||||
emit,
|
||||
});
|
||||
const { type, name, link } = values;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -3,31 +3,17 @@
|
||||
* Admin form: create a categorised bookmark. Emits "done"/"cancel".
|
||||
*/
|
||||
import Button from "@/components/input/Button.vue";
|
||||
import { ref } from "vue";
|
||||
import { gql } from "@/graphql";
|
||||
import { useCreateForm } from "@/js/useCreateForm";
|
||||
|
||||
|
||||
const emit = defineEmits(["done", "cancel"]);
|
||||
|
||||
const category = ref("");
|
||||
const name = ref("");
|
||||
const link = ref("");
|
||||
|
||||
async function submit() {
|
||||
try {
|
||||
await gql(
|
||||
`mutation CreateBookmark($input: CreateBookmarkInput!) { createBookmark(input: $input) { id } }`,
|
||||
{
|
||||
input: { category: category.value, name: name.value, link: link.value },
|
||||
},
|
||||
);
|
||||
category.value = "";
|
||||
name.value = "";
|
||||
link.value = "";
|
||||
emit("done");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
const { values, submit } = useCreateForm({
|
||||
mutation: `mutation CreateBookmark($input: CreateBookmarkInput!) { createBookmark(input: $input) { id } }`,
|
||||
fields: ["category", "name", "link"],
|
||||
emit,
|
||||
});
|
||||
const { category, name, link } = values;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -3,37 +3,19 @@
|
||||
* Admin form: create a favourite. Emits "done"/"cancel" (see CreatePost.vue).
|
||||
*/
|
||||
import Button from "@/components/input/Button.vue";
|
||||
import { useCreateForm } from "@/js/useCreateForm";
|
||||
|
||||
import { ref } from "vue";
|
||||
import { gql } from "@/graphql";
|
||||
|
||||
const emit = defineEmits(["done", "cancel"]);
|
||||
|
||||
const type = ref("");
|
||||
const name = ref("");
|
||||
const link = ref("");
|
||||
|
||||
async function post() {
|
||||
try {
|
||||
const data = await gql(
|
||||
`mutation CreateFavorite($input: CreateFavoriteInput!) { createFavorite(input: $input) { id } }`,
|
||||
{
|
||||
input: {
|
||||
type: type.value,
|
||||
name: name.value,
|
||||
link: link.value || undefined,
|
||||
},
|
||||
},
|
||||
);
|
||||
type.value = "";
|
||||
name.value = "";
|
||||
link.value = "";
|
||||
console.log(data.createFavorite);
|
||||
emit("done");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
const { values, submit: post } = useCreateForm({
|
||||
mutation: `mutation CreateFavorite($input: CreateFavoriteInput!) { createFavorite(input: $input) { id } }`,
|
||||
fields: ["type", "name", "link"],
|
||||
optional: ["link"],
|
||||
resultKey: "createFavorite",
|
||||
emit,
|
||||
});
|
||||
const { type, name, link } = values;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -2,31 +2,21 @@
|
||||
/**
|
||||
* Admin form: create a blog post. Emits "done" on success and "cancel" when
|
||||
* dismissed, so the host (the Feed widget's modal, or Admin.vue) decides what to
|
||||
* close or refresh.
|
||||
* close or refresh. The submit plumbing is shared via useCreateForm().
|
||||
*/
|
||||
import Button from "@/components/input/Button.vue";
|
||||
import { ref } from "vue";
|
||||
import { gql } from "@/graphql";
|
||||
import { useCreateForm } from "@/js/useCreateForm";
|
||||
|
||||
|
||||
const emit = defineEmits(["done", "cancel"]);
|
||||
|
||||
const title = ref("");
|
||||
const content = ref("");
|
||||
|
||||
async function post() {
|
||||
try {
|
||||
const data = await gql(
|
||||
`mutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { id } }`,
|
||||
{ input: { title: title.value, content: content.value } },
|
||||
);
|
||||
title.value = "";
|
||||
content.value = "";
|
||||
console.log(data.createPost);
|
||||
emit("done");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
const { values, submit: post } = useCreateForm({
|
||||
mutation: `mutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { id } }`,
|
||||
fields: ["title", "content"],
|
||||
resultKey: "createPost",
|
||||
emit,
|
||||
});
|
||||
const { title, content } = values;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
<script setup>
|
||||
/**
|
||||
* "Consumption" widget on /stp (books/films/games logged as activities). Same
|
||||
* shape as Favorites.vue: AutoScroll list + admin-only lazy create form.
|
||||
* shape as Favorites.vue — both are ListWidget.vue with a different store.
|
||||
*/
|
||||
import AutoScroll from "@/components/util/AutoScroll.vue";
|
||||
import Modal from "@/components/util/Modal.vue";
|
||||
import LinkTable from "@/components/util/LinkTable.vue";
|
||||
import Header from "@/components/text/Header.vue";
|
||||
import CreateToggle from "@/components/input/CreateToggle.vue";
|
||||
import ListWidget from "@/views/home/ListWidget.vue";
|
||||
|
||||
import { ref, defineAsyncComponent } from "vue";
|
||||
import { defineAsyncComponent } from "vue";
|
||||
import { useActivityStore } from "@/stores/activity";
|
||||
|
||||
const CreateActivity = defineAsyncComponent(
|
||||
@@ -17,27 +13,12 @@ const CreateActivity = defineAsyncComponent(
|
||||
);
|
||||
|
||||
const activityStore = useActivityStore();
|
||||
const showCreate = ref(false);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col items-center">
|
||||
<Header>
|
||||
Consumption
|
||||
<template #action><CreateToggle v-model="showCreate" /></template>
|
||||
</Header>
|
||||
<AutoScroll class="flex-1 w-full">
|
||||
<LinkTable
|
||||
variant="table"
|
||||
class="w-full"
|
||||
:items="activityStore.activity"
|
||||
/>
|
||||
</AutoScroll>
|
||||
<Modal v-model="showCreate">
|
||||
<CreateActivity
|
||||
@done="showCreate = false"
|
||||
@cancel="showCreate = false"
|
||||
/>
|
||||
</Modal>
|
||||
</div>
|
||||
<ListWidget
|
||||
title="Consumption"
|
||||
:items="activityStore.activity"
|
||||
:create-form="CreateActivity"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
<script setup>
|
||||
/**
|
||||
* "Favorites" widget on /stp: a self-scrolling <AutoScroll> list, plus an
|
||||
* admin-only create form in a <Modal> (lazily imported).
|
||||
* "Favorites" widget on /stp. All of the markup lives in ListWidget.vue; this
|
||||
* file only binds the favourites store and the (lazily imported) create form.
|
||||
*/
|
||||
import Header from "@/components/text/Header.vue";
|
||||
import CreateToggle from "@/components/input/CreateToggle.vue";
|
||||
import LinkTable from "@/components/util/LinkTable.vue";
|
||||
import AutoScroll from "@/components/util/AutoScroll.vue";
|
||||
import Modal from "@/components/util/Modal.vue";
|
||||
import ListWidget from "@/views/home/ListWidget.vue";
|
||||
|
||||
import { ref, defineAsyncComponent } from "vue";
|
||||
import { defineAsyncComponent } from "vue";
|
||||
import { useFavoritesStore } from "@/stores/favorites";
|
||||
|
||||
const CreateFavorite = defineAsyncComponent(
|
||||
@@ -17,27 +13,12 @@ const CreateFavorite = defineAsyncComponent(
|
||||
);
|
||||
|
||||
const favoritesStore = useFavoritesStore();
|
||||
const showCreate = ref(false);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col items-center">
|
||||
<Header>
|
||||
favs
|
||||
<template #action><CreateToggle v-model="showCreate" /></template>
|
||||
</Header>
|
||||
<AutoScroll class="w-full flex-1">
|
||||
<LinkTable
|
||||
variant="table"
|
||||
class="w-full"
|
||||
:items="favoritesStore.favorites"
|
||||
/>
|
||||
</AutoScroll>
|
||||
<Modal v-model="showCreate">
|
||||
<CreateFavorite
|
||||
@done="showCreate = false"
|
||||
@cancel="showCreate = false"
|
||||
/>
|
||||
</Modal>
|
||||
</div>
|
||||
<ListWidget
|
||||
title="favs"
|
||||
:items="favoritesStore.favorites"
|
||||
:create-form="CreateFavorite"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -28,8 +28,9 @@ const leftCap = computed(() => idx.value === 0);
|
||||
const rightCap = computed(() => idx.value === postsStore.postsCount - 1);
|
||||
|
||||
const post = computed(() => postsStore.posts[idx.value]);
|
||||
// Guarded: `post` can be a placeholder or a row fetched without an author.
|
||||
const userOwnsPost = computed(
|
||||
() => post.value.author.username == authStore.user.username,
|
||||
() => post.value?.author?.username == authStore.user?.username,
|
||||
);
|
||||
|
||||
function nextPost() {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Shared shape of the "favs" and "Consumption" widgets on /stp: a header with a
|
||||
* create toggle, a self-scrolling <AutoScroll> list rendered through
|
||||
* <LinkTable>, and an admin-only create form in a <Modal>.
|
||||
*
|
||||
* `createForm` is the component to show in the modal. The hosts pass a
|
||||
* defineAsyncComponent() so the admin form is still only fetched when a widget
|
||||
* is actually opened.
|
||||
*/
|
||||
import Header from "@/components/text/Header.vue";
|
||||
import CreateToggle from "@/components/input/CreateToggle.vue";
|
||||
import LinkTable from "@/components/util/LinkTable.vue";
|
||||
import AutoScroll from "@/components/util/AutoScroll.vue";
|
||||
import Modal from "@/components/util/Modal.vue";
|
||||
|
||||
import { ref } from "vue";
|
||||
|
||||
defineProps({
|
||||
title: { type: String, required: true },
|
||||
items: { type: Array, required: true },
|
||||
createForm: { type: [Object, Function], required: true },
|
||||
});
|
||||
|
||||
const showCreate = ref(false);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col items-center">
|
||||
<Header>
|
||||
{{ title }}
|
||||
<template #action><CreateToggle v-model="showCreate" /></template>
|
||||
</Header>
|
||||
<AutoScroll class="flex-1 w-full">
|
||||
<LinkTable variant="table" class="w-full" :items="items" />
|
||||
</AutoScroll>
|
||||
<Modal v-model="showCreate">
|
||||
<component
|
||||
:is="createForm"
|
||||
@done="showCreate = false"
|
||||
@cancel="showCreate = false"
|
||||
/>
|
||||
</Modal>
|
||||
</div>
|
||||
</template>
|
||||
@@ -2,38 +2,28 @@
|
||||
/**
|
||||
* "Listening" widget on /stp: rotates through recent Spotify plays.
|
||||
*
|
||||
* Two timers: a 5s rotation (self-rearming setTimeout, so a manual change would
|
||||
* reset the full interval) and a 2-minute re-poll of Spotify. Both are cleared on
|
||||
* unmount.
|
||||
* Two timers, both owned by useRotation(): a 5s rotation and a 2-minute re-poll
|
||||
* of Spotify.
|
||||
*/
|
||||
import Header from "@/components/text/Header.vue";
|
||||
import { ref, computed, onMounted, onUnmounted } from "vue";
|
||||
import { computed, onMounted } from "vue";
|
||||
import { useSongsStore } from "@/stores/songs";
|
||||
import { useRotation } from "@/js/useRotation";
|
||||
|
||||
const ROTATE_MS = 5000;
|
||||
const REFRESH_MS = 120000;
|
||||
|
||||
const songsStore = useSongsStore();
|
||||
const idx = ref(0);
|
||||
|
||||
const { idx, next: nextSong } = useRotation(() => songsStore.songs, ROTATE_MS, {
|
||||
refresh: () => songsStore.fetchSongs(),
|
||||
refreshMs: REFRESH_MS,
|
||||
});
|
||||
|
||||
const song = computed(() => songsStore.songs[idx.value]);
|
||||
|
||||
let nextId = null;
|
||||
let refreshId = null;
|
||||
|
||||
// Self-rearming timeout rather than setInterval, so the full 5s is restarted
|
||||
// whenever the song changes rather than leaving a short remainder.
|
||||
function nextSong() {
|
||||
clearTimeout(nextId);
|
||||
nextId = setTimeout(nextSong, 5000);
|
||||
idx.value = (idx.value + 1) % songsStore.songsCount;
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
songsStore.fetchSongs();
|
||||
nextId = setTimeout(nextSong, 5000);
|
||||
refreshId = setInterval(songsStore.fetchSongs, 120000);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
clearTimeout(nextId);
|
||||
clearInterval(refreshId);
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,43 +1,33 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Steam widget on /stp: online status plus a rotation through recent games
|
||||
* (5s rotation, 5-minute re-poll). `loaded` comes from homeData so the widget can
|
||||
* tell "not fetched yet" from "fetched, nothing to show".
|
||||
* (5s rotation, 5-minute re-poll, both from useRotation()). `loaded` comes from
|
||||
* homeData so the widget can tell "not fetched yet" from "fetched, nothing to
|
||||
* show".
|
||||
*/
|
||||
import { ref, computed, onMounted, onUnmounted } from "vue";
|
||||
import { computed } from "vue";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { useSteamStore } from "@/stores/steam";
|
||||
import { useHomeDataStore } from "@/stores/homeData";
|
||||
import Header from "@/components/text/Header.vue";
|
||||
import { useRotation } from "@/js/useRotation";
|
||||
|
||||
const ROTATE_MS = 5000;
|
||||
const REFRESH_MS = 5 * 60 * 1000;
|
||||
|
||||
const steamStore = useSteamStore();
|
||||
const { steamStatus } = storeToRefs(steamStore);
|
||||
const homeData = useHomeDataStore();
|
||||
const { loaded } = storeToRefs(homeData);
|
||||
|
||||
const idx = ref(0);
|
||||
const { idx, next: nextGame } = useRotation(
|
||||
() => steamStatus.value.recentGames,
|
||||
ROTATE_MS,
|
||||
{ refresh: () => steamStore.fetchSteam(), refreshMs: REFRESH_MS },
|
||||
);
|
||||
|
||||
const game = computed(() => steamStatus.value.recentGames[idx.value]);
|
||||
|
||||
let nextId = null;
|
||||
let refreshId = null;
|
||||
|
||||
function nextGame() {
|
||||
clearTimeout(nextId);
|
||||
nextId = setTimeout(nextGame, 5000);
|
||||
if (steamStatus.value.recentGames.length) {
|
||||
idx.value = (idx.value + 1) % steamStatus.value.recentGames.length;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
nextId = setTimeout(nextGame, 5000);
|
||||
refreshId = setInterval(() => steamStore.fetchSteam(), 5 * 60 * 1000);
|
||||
});
|
||||
onUnmounted(() => {
|
||||
clearTimeout(nextId);
|
||||
clearInterval(refreshId);
|
||||
});
|
||||
|
||||
function formatHours(minutes) {
|
||||
const hrs = (minutes / 60).toFixed(1);
|
||||
return `${hrs}h`;
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
/**
|
||||
* "Cheapest night" tab of /hotels: scans a date range (capped at MAX_SPAN_DAYS,
|
||||
* optionally filtered to particular weekdays) and reports the best hotel per
|
||||
* night. Same streaming/abort/ticker mechanics as SingleStayPanel.vue.
|
||||
* night. Shares the streaming/abort/ticker lifecycle with SingleStayPanel.vue
|
||||
* through useHotelSearch(); only the event shapes differ.
|
||||
*/
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
|
||||
import { ref, computed, onMounted } from "vue";
|
||||
import SharedFields from "./SharedFields.vue";
|
||||
import HotelRows from "./HotelRows.vue";
|
||||
import { runStream } from "./hotelsStream.js";
|
||||
import { useHotelSearch } from "./useHotelSearch.js";
|
||||
import { todayIso, addDays, loadFrom, saveTo } from "./useHotelForm.js";
|
||||
import {
|
||||
gbp,
|
||||
@@ -53,29 +54,33 @@ function setDays(list) {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Scan state
|
||||
// Scan state (searching/errorMsg/summary/done/elapsed come from the
|
||||
// composable; the night rows and their transport cache are this panel's own)
|
||||
// ---------------------------------------------------------------------------
|
||||
const searching = ref(false);
|
||||
const errorMsg = ref("");
|
||||
const summary = ref(null);
|
||||
const nightRows = ref([]);
|
||||
const cached = ref(false);
|
||||
const done = ref(false);
|
||||
const elapsed = ref(0);
|
||||
const expanded = ref(new Set());
|
||||
let transportByCode = {};
|
||||
let ticker = null;
|
||||
let aborter = null;
|
||||
|
||||
const statusText = computed(() => {
|
||||
if (errorMsg.value) return "Error";
|
||||
if (searching.value) return "Scanning";
|
||||
if (done.value) return "Done";
|
||||
return "Idle";
|
||||
const {
|
||||
searching,
|
||||
errorMsg,
|
||||
summary,
|
||||
done,
|
||||
elapsed,
|
||||
statusText,
|
||||
hasResults,
|
||||
run: onScan,
|
||||
} = useHotelSearch({
|
||||
url: "/py/hotels/scan/stream",
|
||||
buildRequest,
|
||||
applyEvent,
|
||||
onStart,
|
||||
busyLabel: "Scanning",
|
||||
failMessage: "Scan failed.",
|
||||
earlyMessage: "The scan ended early; showing what came back.",
|
||||
});
|
||||
|
||||
const hasResults = computed(() => summary.value !== null);
|
||||
|
||||
const fetchedCount = computed(() => {
|
||||
const s = summary.value;
|
||||
return s ? s.nights_fetched + s.nights_failed + s.nights_skipped : 0;
|
||||
@@ -306,43 +311,16 @@ function applyEvent(ev) {
|
||||
}
|
||||
}
|
||||
|
||||
async function onScan() {
|
||||
if (searching.value) return;
|
||||
errorMsg.value = "";
|
||||
summary.value = null;
|
||||
/** Reset this panel's own result state before a run. */
|
||||
function onStart() {
|
||||
nightRows.value = [];
|
||||
transportByCode = {};
|
||||
expanded.value = new Set();
|
||||
cached.value = false;
|
||||
done.value = false;
|
||||
searching.value = true;
|
||||
elapsed.value = 0;
|
||||
saveConfig();
|
||||
ticker = setInterval(() => elapsed.value++, 1000);
|
||||
aborter = new AbortController();
|
||||
try {
|
||||
await runStream("/py/hotels/scan/stream", buildRequest(), {
|
||||
signal: aborter.signal,
|
||||
onEvent: applyEvent,
|
||||
});
|
||||
if (!done.value && !errorMsg.value)
|
||||
errorMsg.value = "The scan ended early; showing what came back.";
|
||||
} catch (e) {
|
||||
if (e.name !== "AbortError") errorMsg.value = e.message || "Scan failed.";
|
||||
} finally {
|
||||
clearInterval(ticker);
|
||||
ticker = null;
|
||||
aborter = null;
|
||||
searching.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadConfig);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (ticker) clearInterval(ticker);
|
||||
if (aborter) aborter.abort();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -7,13 +7,13 @@
|
||||
* are patched in place by hotel `code` so the table fills in rather than
|
||||
* reloading, and PENDING_ROUTE marks the not-yet-priced ones.
|
||||
*
|
||||
* An AbortController cancels an in-flight stream; a 1s ticker drives the elapsed
|
||||
* counter. Both are torn down in the `finally` and on unmount.
|
||||
* The abort/ticker/stream lifecycle lives in useHotelSearch(); this panel only
|
||||
* supplies the request body and how to apply each streamed event.
|
||||
*/
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
|
||||
import { ref, computed, onMounted } from "vue";
|
||||
import SharedFields from "./SharedFields.vue";
|
||||
import HotelRows from "./HotelRows.vue";
|
||||
import { runStream } from "./hotelsStream.js";
|
||||
import { useHotelSearch } from "./useHotelSearch.js";
|
||||
import { nextFriday, todayIso } from "./useHotelForm.js";
|
||||
import {
|
||||
gbp,
|
||||
@@ -47,31 +47,35 @@ const top = ref(20);
|
||||
const rankBy = ref("total");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Search state
|
||||
// Search state (searching/errorMsg/summary/done/elapsed come from the
|
||||
// composable; rows and `cached` are this panel's own)
|
||||
// ---------------------------------------------------------------------------
|
||||
const searching = ref(false);
|
||||
const errorMsg = ref("");
|
||||
const summary = ref(null);
|
||||
const rows = ref([]);
|
||||
const cached = ref(false);
|
||||
const done = ref(false);
|
||||
const elapsed = ref(0);
|
||||
let ticker = null;
|
||||
let aborter = null;
|
||||
|
||||
const statusText = computed(() => {
|
||||
if (errorMsg.value) return "Error";
|
||||
if (searching.value) return "Searching";
|
||||
if (done.value) return "Done";
|
||||
return "Idle";
|
||||
const {
|
||||
searching,
|
||||
errorMsg,
|
||||
summary,
|
||||
done,
|
||||
elapsed,
|
||||
statusText,
|
||||
hasResults,
|
||||
run: onSearch,
|
||||
} = useHotelSearch({
|
||||
url: "/py/hotels/search/stream",
|
||||
buildRequest,
|
||||
applyEvent,
|
||||
onStart,
|
||||
busyLabel: "Searching",
|
||||
failMessage: "Search failed.",
|
||||
earlyMessage: "The search ended early; showing what came back.",
|
||||
});
|
||||
|
||||
const pricedCount = computed(
|
||||
() => rows.value.filter((r) => r.total != null || r.route !== PENDING_ROUTE).length,
|
||||
);
|
||||
|
||||
const hasResults = computed(() => summary.value !== null);
|
||||
|
||||
const sortedRows = computed(() => {
|
||||
const cmp = { total: byTotal, room: byRoom, cycle: byCycle, minutes: byMinutes }[
|
||||
rankBy.value
|
||||
@@ -204,43 +208,14 @@ function applyEvent(ev) {
|
||||
}
|
||||
}
|
||||
|
||||
async function onSearch() {
|
||||
if (searching.value) return;
|
||||
errorMsg.value = "";
|
||||
summary.value = null;
|
||||
/** Reset this panel's own result state before a run. */
|
||||
function onStart() {
|
||||
rows.value = [];
|
||||
cached.value = false;
|
||||
done.value = false;
|
||||
searching.value = true;
|
||||
elapsed.value = 0;
|
||||
saveConfig();
|
||||
// 1s elapsed counter plus an AbortController to cancel the stream; both
|
||||
// are torn down in the finally below and on unmount.
|
||||
ticker = setInterval(() => elapsed.value++, 1000);
|
||||
aborter = new AbortController();
|
||||
try {
|
||||
await runStream("/py/hotels/search/stream", buildRequest(), {
|
||||
signal: aborter.signal,
|
||||
onEvent: applyEvent,
|
||||
});
|
||||
if (!done.value && !errorMsg.value)
|
||||
errorMsg.value = "The search ended early; showing what came back.";
|
||||
} catch (e) {
|
||||
if (e.name !== "AbortError") errorMsg.value = e.message || "Search failed.";
|
||||
} finally {
|
||||
clearInterval(ticker);
|
||||
ticker = null;
|
||||
aborter = null;
|
||||
searching.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadConfig);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (ticker) clearInterval(ticker);
|
||||
if (aborter) aborter.abort();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// Search lifecycle shared by the "Single stay" and "Cheapest night" panels.
|
||||
//
|
||||
// Both panels run the same routine: reset the result state, start a 1s elapsed
|
||||
// ticker and an AbortController, stream NDJSON events from a Python endpoint,
|
||||
// then tear everything down in a `finally` (and again on unmount, so leaving
|
||||
// the page cancels an in-flight request). Only the events themselves differ,
|
||||
// so each panel supplies its own applyEvent().
|
||||
|
||||
import { ref, computed, onBeforeUnmount } from "vue";
|
||||
import { runStream } from "./hotelsStream.js";
|
||||
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {string} options.url NDJSON streaming endpoint to POST to
|
||||
* @param {() => object} options.buildRequest request body for one run
|
||||
* @param {(ev: object) => void} options.applyEvent apply one streamed event.
|
||||
* Called for every event; it is the panel's job to write into
|
||||
* `summary` / `done` / `errorMsg` from the returned object. Declare it
|
||||
* as a hoisted `function` so it can reference that object.
|
||||
* @param {() => void} [options.onStart] reset panel-local state before a run
|
||||
* @param {string} [options.busyLabel] status chip text while running
|
||||
* @param {string} [options.failMessage] fallback message for a thrown error
|
||||
* @param {string} [options.earlyMessage] shown when the stream ends without `done`
|
||||
*/
|
||||
export function useHotelSearch({
|
||||
url,
|
||||
buildRequest,
|
||||
applyEvent,
|
||||
onStart,
|
||||
busyLabel = "Searching",
|
||||
failMessage = "Search failed.",
|
||||
earlyMessage = "The search ended early; showing what came back.",
|
||||
}) {
|
||||
const searching = ref(false);
|
||||
const errorMsg = ref("");
|
||||
const summary = ref(null);
|
||||
const done = ref(false);
|
||||
const elapsed = ref(0);
|
||||
let ticker = null;
|
||||
let aborter = null;
|
||||
|
||||
const statusText = computed(() => {
|
||||
if (errorMsg.value) return "Error";
|
||||
if (searching.value) return busyLabel;
|
||||
if (done.value) return "Done";
|
||||
return "Idle";
|
||||
});
|
||||
|
||||
const hasResults = computed(() => summary.value !== null);
|
||||
|
||||
async function run() {
|
||||
if (searching.value) return;
|
||||
errorMsg.value = "";
|
||||
summary.value = null;
|
||||
done.value = false;
|
||||
searching.value = true;
|
||||
elapsed.value = 0;
|
||||
if (onStart) onStart();
|
||||
ticker = setInterval(() => elapsed.value++, 1000);
|
||||
aborter = new AbortController();
|
||||
try {
|
||||
await runStream(url, buildRequest(), {
|
||||
signal: aborter.signal,
|
||||
onEvent: applyEvent,
|
||||
});
|
||||
if (!done.value && !errorMsg.value) errorMsg.value = earlyMessage;
|
||||
} catch (e) {
|
||||
// An abort is the user leaving or restarting, not a failure.
|
||||
if (e.name !== "AbortError") errorMsg.value = e.message || failMessage;
|
||||
} finally {
|
||||
clearInterval(ticker);
|
||||
ticker = null;
|
||||
aborter = null;
|
||||
searching.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (ticker) clearInterval(ticker);
|
||||
if (aborter) aborter.abort();
|
||||
});
|
||||
|
||||
return { searching, errorMsg, summary, done, elapsed, statusText, hasResults, run };
|
||||
}
|
||||
Reference in New Issue
Block a user