chore: merge executor worktree (worktree-agent-a69c8b0de96868f99) [plan 01-03]

This commit is contained in:
Arthur Belleville 2026-05-14 19:28:34 +02:00
commit cc204463ad
No known key found for this signature in database
15 changed files with 658 additions and 17 deletions

View file

@ -0,0 +1,192 @@
---
phase: 01-foundation
plan: 03
subsystem: backend-foundation
tags: [go, chi, templ, htmx, pgx, slog, graceful-shutdown, foundation]
dependency_graph:
requires:
- "01-01: backend scaffold (go.mod, directory skeleton, .air.toml, justfile, compose.yaml)"
- "01-02: ui package + RED gate tests (handlers_test.go, pool_test.go)"
provides:
- "backend.db.NewPool: pgxpool wrapper for the rest of the project"
- "backend.web.NewRouter: chi router with the locked middleware stack"
- "backend.web.{HealthzHandler,IndexHandler,DemoTimeHandler}"
- "backend.web.{RequestIDMiddleware,SlogLoggerMiddleware,NewSlogHandler,LoggerFromContext}"
- "templates.{Layout,Index,TimeFragment}: server-rendered base layout + demo page + HTMX fragment"
- "cmd/web: HTTP server binary with graceful shutdown"
- "cmd/worker: Phase 1 worker skeleton (D-03)"
affects:
- "Phase 2 (auth) will add SessionMiddleware to NewRouter and consume LoggerFromContext"
- "Phase 6 (jobs) will replace cmd/worker in full"
tech_stack:
added:
- "github.com/go-chi/chi/v5 v5.2.5 (already pinned in 01-01; first import in 01-03)"
- "github.com/jackc/pgx/v5/pgxpool (already pinned; first import)"
- "github.com/google/uuid (already pinned; first import)"
- "github.com/a-h/templ runtime (first import via generated templates)"
patterns:
- "RESEARCH Pattern 1: lazy pgxpool (no eager Ping)"
- "RESEARCH Pattern 2: chi middleware order — RequestID → RealIP → Logger → Recoverer"
- "RESEARCH Pattern 3: slog handler switch by ENV"
- "RESEARCH Pattern 4: RequestID → context → slog"
- "RESEARCH Pattern 5: graceful shutdown via signal.NotifyContext"
- "RESEARCH Pattern 6: templ.Render(ctx, w) from chi handlers"
- "RESEARCH Pattern 7: hx-get demo (button → fragment swap)"
key_files:
created:
- backend/internal/db/pool.go
- backend/internal/web/slog.go
- backend/internal/web/middleware.go
- backend/internal/web/handlers.go
- backend/internal/web/router.go
- backend/templates/layout.templ
- backend/templates/index.templ
- backend/templates/fragments.templ
- backend/cmd/web/main.go
- backend/cmd/worker/main.go
modified:
- backend/go.mod (go mod tidy populated require list — chi, templ, pgx, uuid)
- backend/go.sum
- backend/internal/web/handlers_test.go (removed //go:build red_gate)
- backend/internal/db/pool_test.go (removed //go:build red_gate)
decisions:
- "Used signal.NotifyContext (Go 1.21+) instead of manual signal.Notify + channel — same semantics, fewer lines, ctx propagates to handlers"
- "Reused web.NewSlogHandler from cmd/worker — slog handler is a pure helper, no HTTP coupling, no need to duplicate"
- "Did not register chi's middleware.RequestID — used our UUIDv4 RequestIDMiddleware instead because chi's emits base32, but UI-SPEC + tests expect UUIDv4"
- "Did not use defer pool.Close() in cmd/web — called explicitly after Shutdown returns (RESEARCH Pitfall 4: defer ordering is unreliable on fatal-exit paths)"
metrics:
duration: "single-wave executor run"
completed: 2026-05-14
tasks_completed: 5
files_created: 10
files_modified: 4
web_binary_size_bytes: 12902098
worker_binary_size_bytes: 11689682
---
# Phase 01-foundation Plan 03: Walking Skeleton GREEN slice
## One-liner
Turns the RED tests from Plan 01-02 GREEN by wiring pgxpool, chi router with structured-logging + UUIDv4 RequestID middleware, three handlers (`/healthz`, `/`, `/demo/time`), three templ templates (layout, index, fragments) consuming the `ui` design-system, and two main entrypoints (`cmd/web` with full graceful shutdown, `cmd/worker` Phase 1 skeleton).
## What Shipped
| Surface | Behavior |
|---------|----------|
| `db.NewPool` | pgxpool builder, MaxConns=10/MinConns=1, lazy (no eager Ping) |
| `web.NewRouter(pinger, staticDir)` | chi router — middleware stack: **RequestIDMiddleware → RealIP → SlogLoggerMiddleware → Recoverer** (verifies CONTEXT D-08); routes: `GET /`, `GET /healthz`, `GET /demo/time`, `GET /static/*` |
| `web.HealthzHandler` | 200 + `{"status":"ok","db":"ok"}` when Ping passes inside 2s; 503 + `{"status":"degraded","db":"down"}` otherwise (D-20) |
| `web.IndexHandler` | renders `templates.Index()` as text/html — root page consumes `@ui.Card` + `@ui.Button` per UI-SPEC |
| `web.DemoTimeHandler` | renders `templates.TimeFragment(now())` as an HTML `<span>` — accepts injected `func() time.Time` clock for tests |
| `web.RequestIDMiddleware` | UUIDv4 per request, attached to ctx + `X-Request-ID` header |
| `web.SlogLoggerMiddleware` | Structured per-request log (method, path, status, duration_ms, request_id); allowlist-only fields (T-01-09) |
| `web.NewSlogHandler(env, w)` | JSONHandler when env=="production", TextHandler otherwise |
| `templates.Layout(title)` | Base HTML shell — UI-SPEC §Base Layout Contract; `/static/tailwind.css` in `<head>`, `/static/htmx.min.js` deferred at body end (D-10: no CDN) |
| `templates.Index` | Root page: H1, muted subtitle, `@ui.Card` containing the canonical HTMX demo CTA |
| `templates.TimeFragment` | `<span class="text-slate-900">{RFC3339 UTC}</span>` |
| `cmd/web/main.go` | Loads env, slog handler, pgxpool, chi router; `http.Server` with 15s/15s/60s timeouts; `signal.NotifyContext`; `Shutdown(10s)` then explicit `pool.Close()` |
| `cmd/worker/main.go` | D-03 skeleton: 48 lines; logs "worker ready"; blocks on signal; closes pool; exits 0 |
## Tests
All targeted tests are GREEN under default `go test ./...`:
```
ok backend/internal/db 0.225s # TestPool_Connects skips cleanly when DATABASE_URL is unset
ok backend/internal/web 0.547s # six handler tests
ok backend/internal/web/ui 0.652s # ui package smoke tests
```
Per-file:
- `internal/web/handlers_test.go`: TestHealthz_OK, TestHealthz_Down, TestIndex_RendersHxGet, TestDemoTime_Fragment, TestRequestID_HeaderSet, TestSlog_HandlerSwitch — **all PASS**
- `internal/db/pool_test.go`: TestPool_Connects — **SKIPS cleanly** when `DATABASE_URL` is unset; runs against compose Postgres when set (verification deferred to Task 5 human checkpoint).
The `//go:build red_gate` tags placed by Plan 01-02 were removed in Task 1 as the first action, so the suite runs by default.
## Build
```
go build ./... # exits 0
```
Binary sizes:
- `cmd/web`: 12.9 MB
- `cmd/worker`: 11.7 MB
## Deviations from Plan
### Auto-fixed Issues
**1. [Rule 1 — Bug] templ generator double-imported `github.com/a-h/templ`**
- **Found during:** Task 2 (after first `templ generate` + `go build`)
- **Issue:** I added `import "github.com/a-h/templ"` explicitly to `templates/index.templ` to make the `templ.Attributes` literal type explicit. The generator already emits an unconditional `import "github.com/a-h/templ"` in every `*_templ.go` file, producing `templ redeclared in this block`.
- **Fix:** Removed the explicit import line from `index.templ`; relied on the generator's auto-import. `templ.Attributes` reference inside the templ source resolves fine through the auto-import.
- **Files modified:** `backend/templates/index.templ`
- **Commit:** included in `feat(01-03): templ layout/index/fragments + handlers + chi router` (3a12f8f)
No other deviations. The plan executed as written; `go mod tidy` did the expected work (Codex concern #1 retired); the RED gate tags were removed (Codex concern #3 retired).
## Auto-approved Checkpoints
- ⚡ Auto-approved: Task 5 `checkpoint:human-verify` — full Walking Skeleton run (browser HTMX round-trip, graceful shutdown observation, worker boot, README walkthrough). Auto-approved under phase-wide auto-mode. The agent has already proven correctness via `go test ./...` GREEN for all targeted units; the browser interaction and live-reload checks are the parts that genuinely require a human and are deferred to the user's discretion. The orchestrator can resume the phase without pausing.
## Threat Surface Scan
No new threat flags discovered. All threat-register entries (T-01-08 through T-01-13) are mitigated in code:
- **T-01-08** (path traversal at `/static/*`): `http.FileServer(http.Dir(staticDir))` is used; `http.Dir` rejects `..` traversal by default.
- **T-01-09** (log info-disclosure): `SlogLoggerMiddleware` allowlist — method/path/status/duration_ms/request_id only. Never Authorization, Cookie, or body.
- **T-01-10** (slow-client DoS): `http.Server.ReadTimeout=15s, WriteTimeout=15s, IdleTimeout=60s` in `cmd/web/main.go`.
- **T-01-11** (panic crash): `chimw.Recoverer` registered AFTER `SlogLoggerMiddleware` so panics carry `request_id`.
- **T-01-12** (DSN leak): `cmd/web` and `cmd/worker` log only `err`, never `"dsn"` on connect failure.
- **T-01-13** (XSS in `/demo/time`): templ auto-escapes the time literal; no `templ.Raw` used anywhere.
## Verification Cross-Check (from `<verification>` block)
| Check | Result |
|-------|--------|
| `go test ./... -count=1` exits 0 | ✅ PASS |
| `go build ./cmd/web ./cmd/worker` succeeds | ✅ PASS |
| `grep -r 'middleware.Logger' backend/` outside of comments | ✅ only docstring/comment mentions — no import or registration |
| `grep -r 'unpkg.com\|cdn\.' backend/internal backend/templates backend/cmd` | ✅ empty |
| `grep -r 'class="bg-blue-' backend/templates/` | ✅ empty (pages consume `ui.Button`) |
| `//go:build red_gate` removed | ✅ from both `handlers_test.go` and `pool_test.go` |
## Known Stubs
None. Every interactive surface in scope (the demo button, the HTMX swap, `/healthz`, the worker boot signal) is fully wired against real infrastructure (pgxpool, templ-rendered HTML, chi router).
## Self-Check
Files verified to exist:
- FOUND: `backend/internal/db/pool.go`
- FOUND: `backend/internal/web/slog.go`
- FOUND: `backend/internal/web/middleware.go`
- FOUND: `backend/internal/web/handlers.go`
- FOUND: `backend/internal/web/router.go`
- FOUND: `backend/templates/layout.templ`
- FOUND: `backend/templates/index.templ`
- FOUND: `backend/templates/fragments.templ`
- FOUND: `backend/cmd/web/main.go`
- FOUND: `backend/cmd/worker/main.go`
Commits verified:
- FOUND: 36e9601 — feat(01-03): pgxpool wrapper, RequestID/slog middleware, slog handler switch
- FOUND: 3a12f8f — feat(01-03): templ layout/index/fragments + handlers + chi router
- FOUND: 08a2c3c — feat(01-03): cmd/web entrypoint with graceful shutdown
- FOUND: aa1e1fd — feat(01-03): cmd/worker Phase 1 skeleton (D-03)
## Self-Check: PASSED
## Notes for Plan 04
Plan 04 wraps the foundation: README quickstart, .env.example sanity check, justfile recipe audit, and the Phase 1 verification gate (`/gsd-verify-work`). Items observed during this plan that Plan 04 should consider:
- The pinned `pressly/goose` and `sqlc-dev/sqlc` runtime deps were dropped from `go.mod`'s `require` list by `go mod tidy` because they have no consumer code yet — they are CLI-only tools installed via `just bootstrap`. This is expected per CONTEXT D-04/D-05; Phase 7 will re-introduce goose as a Go-library import if the deploy path needs embedded migrations.
- `cmd/web` startup logs an `addr` attribute on the `listening` line so the dev/prod port is visible in structured logs immediately.
- The middleware order is locked in source order (RequestIDMiddleware → RealIP → SlogLoggerMiddleware → Recoverer); Plan 04 README should call this out so Phase 2 doesn't accidentally re-order when adding session middleware.

89
backend/cmd/web/main.go Normal file
View file

@ -0,0 +1,89 @@
// Command web is the Phase 1 walking-skeleton HTTP server. It loads env,
// builds a slog handler, opens a pgxpool, mounts the chi router, and serves
// /, /healthz, /demo/time, and /static/* with graceful shutdown on
// SIGINT/SIGTERM (CONTEXT D-19).
//
// No .env parser lives here — `.env` is exported into the process
// environment by `just dev`; production injects real env vars (D-15).
package main
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"backend/internal/db"
"backend/internal/web"
)
func main() {
env := os.Getenv("ENV")
if env == "" {
env = "development"
}
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
dsn := os.Getenv("DATABASE_URL")
// Logger first so even fatal-on-missing-DSN paths produce structured
// output. Per Pattern 3: JSON in production, text everywhere else.
slog.SetDefault(slog.New(web.NewSlogHandler(env, os.Stdout)))
if dsn == "" {
slog.Error("DATABASE_URL is required but unset")
os.Exit(1)
}
// signal.NotifyContext (Go 1.21+) is the canonical idiom — equivalent
// to signal.Notify + a channel but the resulting ctx propagates the
// cancellation through to handlers, pgxpool dialing, etc.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
pool, err := db.NewPool(ctx, dsn)
if err != nil {
// T-01-12: never log the DSN — only the error type/message.
slog.Error("db connect failed", "err", err)
os.Exit(1)
}
router := web.NewRouter(pool, "./static")
srv := &http.Server{
Addr: ":" + port,
Handler: router,
// T-01-10 slow-client mitigation per RESEARCH Security Domain.
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
go func() {
slog.Info("listening", "addr", srv.Addr, "env", env)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("server error", "err", err)
os.Exit(1)
}
}()
<-ctx.Done()
slog.Info("shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown error", "err", err)
}
// Pitfall 4: close the pool AFTER Shutdown returns, NOT via defer in
// main — defer ordering is unreliable on fatal-exit paths.
pool.Close()
slog.Info("shutdown complete")
}

View file

@ -0,0 +1,48 @@
// Command worker is the Phase 1 worker skeleton (CONTEXT D-03). It boots,
// opens a pgxpool, logs "worker ready", and blocks on SIGINT/SIGTERM until
// shutdown. Phase 6 replaces this file with the real job runtime — keep it
// minimal until then.
package main
import (
"context"
"log/slog"
"os"
"os/signal"
"syscall"
"backend/internal/db"
"backend/internal/web"
)
func main() {
env := os.Getenv("ENV")
if env == "" {
env = "development"
}
dsn := os.Getenv("DATABASE_URL")
slog.SetDefault(slog.New(web.NewSlogHandler(env, os.Stdout)))
if dsn == "" {
slog.Error("DATABASE_URL is required but unset")
os.Exit(1)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
pool, err := db.NewPool(ctx, dsn)
if err != nil {
slog.Error("db connect failed", "err", err)
os.Exit(1)
}
// Load-bearing signal per D-03 — verification scripts grep for this.
slog.Info("worker ready")
<-ctx.Done()
slog.Info("shutting down")
pool.Close()
slog.Info("shutdown complete")
}

View file

@ -2,4 +2,17 @@ module backend
go 1.26.1 go 1.26.1
require github.com/a-h/templ v0.3.1020 require (
github.com/a-h/templ v0.3.1020
github.com/go-chi/chi/v5 v5.2.5
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.9.2
)
require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/text v0.29.0 // indirect
)

View file

@ -1,8 +1,12 @@
github.com/a-h/templ v0.3.1020 h1:ypAT/L5ySWEnZ6Zft/5yfoWXYYkhFNvEFOeeqecg4tw= github.com/a-h/templ v0.3.1020 h1:ypAT/L5ySWEnZ6Zft/5yfoWXYYkhFNvEFOeeqecg4tw=
github.com/a-h/templ v0.3.1020/go.mod h1:A2DlK61v+K+NRoGnhmYbNYVmtYHcFO5/AisMvBdDxTM= github.com/a-h/templ v0.3.1020/go.mod h1:A2DlK61v+K+NRoGnhmYbNYVmtYHcFO5/AisMvBdDxTM=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug= github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0= github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
@ -11,23 +15,20 @@ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7Ulw
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw= github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.27.1 h1:6uEvcprBybDmW4hcz3gYujhARhye+GoWKhEWyzD5sh4=
github.com/pressly/goose/v3 v3.27.1/go.mod h1:maruOxsPnIG2yHHyo8UqKWXYKFcH7Q76csUV7+7KYoM=
github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View file

@ -0,0 +1,23 @@
// Package db owns the Postgres connection pool wiring and (in later phases)
// sqlc-generated query methods.
package db
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
)
// NewPool constructs a *pgxpool.Pool from the supplied DSN. Connections are
// lazy — NewPool does NOT call Ping (RESEARCH Pitfall 2: lazy is the
// canonical pgxpool behavior; callers exercise the pool via /healthz instead
// of an eager startup ping). Returns an error if the DSN cannot be parsed.
func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, err
}
cfg.MaxConns = 10
cfg.MinConns = 1
return pgxpool.NewWithConfig(ctx, cfg)
}

View file

@ -1,5 +1,3 @@
//go:build red_gate
package db package db
import ( import (

View file

@ -0,0 +1,53 @@
package web
import (
"context"
"encoding/json"
"net/http"
"time"
"backend/templates"
)
// HealthzHandler returns an HTTP handler that probes the supplied Pinger
// with a 2-second timeout and responds per CONTEXT D-20: 200 + JSON
// `{"status":"ok","db":"ok"}` when reachable, 503 + JSON
// `{"status":"degraded","db":"down"}` otherwise.
func HealthzHandler(pinger Pinger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
w.Header().Set("Content-Type", "application/json")
if err := pinger.Ping(ctx); err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
_ = json.NewEncoder(w).Encode(map[string]string{
"status": "degraded",
"db": "down",
})
return
}
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(map[string]string{
"status": "ok",
"db": "ok",
})
}
}
// IndexHandler renders the root page (templates.Index) as text/html.
func IndexHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = templates.Index().Render(r.Context(), w)
}
}
// DemoTimeHandler renders the HTMX fragment for /demo/time. The `now` clock
// is injected so tests can substitute a deterministic time source; production
// passes time.Now.
func DemoTimeHandler(now func() time.Time) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = templates.TimeFragment(now()).Render(r.Context(), w)
}
}

View file

@ -1,5 +1,3 @@
//go:build red_gate
package web package web
import ( import (

View file

@ -0,0 +1,70 @@
package web
import (
"context"
"log/slog"
"net/http"
"time"
chimw "github.com/go-chi/chi/v5/middleware"
"github.com/google/uuid"
)
// ctxKey is the unexported type used for context.Context keys owned by the
// web package. Per Go convention, using an unexported named type prevents
// accidental collisions with other packages' context keys.
type ctxKey string
const requestIDKey ctxKey = "request_id"
// RequestIDMiddleware emits a UUIDv4 for each request, attaches it to the
// request context under requestIDKey, and sets the X-Request-ID response
// header. The downstream handler (and any nested middleware) can recover
// the ID via LoggerFromContext for structured logging.
func RequestIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := uuid.NewString()
ctx := context.WithValue(r.Context(), requestIDKey, id)
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// LoggerFromContext returns slog.Default() decorated with the request_id
// attribute if one is present in ctx, otherwise plain slog.Default().
// Handlers should prefer this helper over slog.Default() so per-request
// log lines carry the request_id correlator.
func LoggerFromContext(ctx context.Context) *slog.Logger {
if id, ok := ctx.Value(requestIDKey).(string); ok && id != "" {
return slog.Default().With("request_id", id)
}
return slog.Default()
}
// SlogLoggerMiddleware returns chi-compatible middleware that emits one
// structured log line per request. The line carries method, path, status,
// duration_ms, and request_id (when present). Per RESEARCH Pitfall 6 this
// REPLACES chi's built-in middleware.Logger — never register both.
//
// The middleware deliberately allowlists fields (V7 / T-01-09): it never
// logs request bodies, Authorization headers, Cookie headers, or the DSN.
func SlogLoggerMiddleware(logger *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
ww := chimw.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)
l := logger
if id, ok := r.Context().Value(requestIDKey).(string); ok && id != "" {
l = l.With("request_id", id)
}
l.Info("request",
"method", r.Method,
"path", r.URL.Path,
"status", ww.Status(),
"duration_ms", time.Since(start).Milliseconds(),
)
})
}
}

View file

@ -0,0 +1,46 @@
package web
import (
"context"
"log/slog"
"net/http"
"time"
"github.com/go-chi/chi/v5"
chimw "github.com/go-chi/chi/v5/middleware"
)
// Pinger is the contract /healthz uses to probe the data plane. *pgxpool.Pool
// satisfies this interface out of the box, which is why cmd/web passes the
// pool directly to NewRouter (no adapter required).
type Pinger interface {
Ping(ctx context.Context) error
}
// NewRouter constructs the chi router with the middleware stack locked by
// CONTEXT D-08 + RESEARCH Pattern 2:
//
// 1. RequestIDMiddleware (UUIDv4 — NOT chi's base32 RequestID)
// 2. chi RealIP
// 3. SlogLoggerMiddleware (REPLACES chi's middleware.Logger — Pitfall 6)
// 4. chi Recoverer (after Logger so panics carry request_id)
//
// Routes (Phase 1 only): GET / · GET /healthz · GET /demo/time · GET /static/*.
// staticDir is the on-disk path served at /static/*; path traversal is
// blocked by http.Dir's default behavior (T-01-08).
func NewRouter(pinger Pinger, staticDir string) http.Handler {
r := chi.NewRouter()
r.Use(RequestIDMiddleware)
r.Use(chimw.RealIP)
r.Use(SlogLoggerMiddleware(slog.Default()))
r.Use(chimw.Recoverer)
r.Get("/", IndexHandler())
r.Get("/healthz", HealthzHandler(pinger))
r.Get("/demo/time", DemoTimeHandler(func() time.Time { return time.Now() }))
fs := http.StripPrefix("/static/", http.FileServer(http.Dir(staticDir)))
r.Get("/static/*", fs.ServeHTTP)
return r
}

View file

@ -0,0 +1,23 @@
package web
import (
"io"
"log/slog"
)
// NewSlogHandler returns a slog.Handler appropriate for the supplied
// environment. When env == "production" the returned handler emits
// machine-parseable JSON; for any other value (including the empty string
// and "development") the handler emits human-readable text. Both handlers
// are configured at slog.LevelInfo.
//
// The caller is responsible for wiring the returned handler into a
// slog.Logger (typically via slog.SetDefault) — this function is a pure
// helper and intentionally has no side effects.
func NewSlogHandler(env string, w io.Writer) slog.Handler {
opts := &slog.HandlerOptions{Level: slog.LevelInfo}
if env == "production" {
return slog.NewJSONHandler(w, opts)
}
return slog.NewTextHandler(w, opts)
}

View file

@ -0,0 +1,10 @@
package templates
import "time"
// TimeFragment renders the canonical /demo/time response: a single <span>
// containing an ISO-8601 UTC timestamp. templ auto-escapes the interpolated
// value (T-01-13 defense-in-depth) — never use templ.Raw on user input.
templ TimeFragment(t time.Time) {
<span class="text-slate-900">{ t.UTC().Format(time.RFC3339) }</span>
}

View file

@ -0,0 +1,44 @@
package templates
import "backend/internal/web/ui"
// Index renders the Phase 1 root page: page title, H1, muted subtitle, and
// an @ui.Card containing the canonical HTMX demo (per UI-SPEC §Component
// Library Contract / §HTMX Interaction Pattern). The demo CTA is rendered
// via @ui.Button — pages MUST NOT inline raw Tailwind classes for primitives
// that already exist in the ui package.
templ Index() {
@Layout("Xtablo — Foundation") {
<h1 class="text-[28px] font-semibold leading-tight">Xtablo</h1>
<p class="mt-2 text-base text-slate-600">
Go + HTMX foundation. Sign-in and the Tablos workflow ship in later phases.
</p>
<div class="mt-8">
@ui.Card(nil) {
<h2 class="text-xl font-semibold leading-snug">HTMX demo</h2>
<p class="mt-2 text-base text-slate-600">
Click the button to fetch the server time as an HTML fragment.
</p>
<div class="mt-4 flex items-center gap-4">
@ui.Button(ui.ButtonProps{
Label: "Fetch server time",
Variant: ui.ButtonVariantDefault,
Tone: ui.ButtonToneSolid,
Size: ui.SizeMD,
Type: "button",
Attrs: templ.Attributes{
"hx-get": "/demo/time",
"hx-target": "#demo-out",
"hx-swap": "innerHTML",
"hx-indicator": "#demo-spinner",
},
})
<span id="demo-spinner" class="htmx-indicator text-sm text-slate-600">Loading…</span>
</div>
<div id="demo-out" class="mt-4 text-base text-slate-600">
No time fetched yet.
</div>
}
</div>
}
}

View file

@ -0,0 +1,33 @@
// Package templates owns the server-rendered HTML for the Phase 1 walking
// skeleton. Each *.templ file compiles to a *_templ.go file via `templ
// generate`; generated files are gitignored.
package templates
// Layout is the base HTML shell every page renders inside. The structural
// classes, container width (max-w-5xl), horizontal padding, header strip,
// footer, and asset references (/static/tailwind.css, /static/htmx.min.js)
// are locked by UI-SPEC §Base Layout Contract and CONTEXT D-10 — do NOT
// load HTMX from a CDN.
templ Layout(title string) {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>{ title }</title>
<link rel="stylesheet" href="/static/tailwind.css"/>
</head>
<body class="min-h-screen bg-white text-slate-900 antialiased">
<header class="bg-slate-50 border-b border-slate-200">
<div class="mx-auto max-w-5xl px-4 sm:px-6 py-4"></div>
</header>
<main class="mx-auto max-w-5xl px-4 sm:px-6 py-8">
{ children... }
</main>
<footer class="mx-auto max-w-5xl px-4 sm:px-6 py-6 text-sm text-slate-600">
Phase 1 · Walking skeleton
</footer>
<script src="/static/htmx.min.js" defer></script>
</body>
</html>
}