12 Commits

Author SHA1 Message Date
Ryan Hamamura
b1f754831a fix: limit request body size on auth form handlers (gosec G120)
All checks were successful
CI / Deploy / test (push) Successful in 14s
CI / Deploy / lint (push) Successful in 45s
CI / Deploy / deploy (push) Successful in 1m34s
2026-03-11 10:19:03 -10:00
93147ffc46 Merge pull request 'fix: convert auth flows from SSE to standard HTTP to fix session cookies' (#14) from fix/login-session-cookie into main
Some checks failed
CI / Deploy / test (push) Successful in 7s
CI / Deploy / lint (push) Failing after 37s
CI / Deploy / deploy (push) Has been skipped
2026-03-11 20:14:35 +00:00
Ryan Hamamura
72d31fd143 fix: convert auth flows from SSE to standard HTTP to fix session cookies
Some checks failed
CI / Deploy / test (pull_request) Successful in 33s
CI / Deploy / lint (pull_request) Failing after 38s
CI / Deploy / deploy (pull_request) Has been skipped
Datastar's NewSSE() flushes HTTP headers before SCS's session middleware
can attach the Set-Cookie header, so the session cookie never reaches the
browser after login/register/logout.

Convert login, register, and logout to standard HTML forms with HTTP
redirects, which lets SCS write cookies normally. Also fix return_url
capture on the login page (was never being stored in the session).

Add handler tests covering login, register, and logout flows.
2026-03-11 10:10:28 -10:00
Ryan Hamamura
8573e87bf6 fix: add /assets/ prefix to hashfs paths in prod
All checks were successful
CI / Deploy / test (push) Successful in 13s
CI / Deploy / lint (push) Successful in 24s
CI / Deploy / deploy (push) Successful in 1m27s
2026-03-03 13:37:04 -10:00
67a768ea22 Fix SSE architecture for reliable connections (#13)
All checks were successful
CI / Deploy / test (push) Successful in 14s
CI / Deploy / lint (push) Successful in 25s
CI / Deploy / deploy (push) Successful in 1m32s
2026-03-03 23:33:13 +00:00
Ryan Hamamura
331c4c8759 docs: add AGENTS.md with coding guidelines for AI agents
All checks were successful
CI / Deploy / test (push) Successful in 15s
CI / Deploy / lint (push) Successful in 28s
CI / Deploy / deploy (push) Successful in 1m28s
Includes build/test commands, code style guidelines, naming conventions,
error handling patterns, and Go/templ/Datastar patterns used in this repo.
2026-03-03 10:53:14 -10:00
f6c5949247 Merge pull request 'Fix connection indicator script duplication on SSE patches' (#12) from fix/connection-indicator-script into main
All checks were successful
CI / Deploy / test (push) Successful in 18s
CI / Deploy / lint (push) Successful in 25s
CI / Deploy / deploy (push) Successful in 1m27s
2026-03-03 20:44:56 +00:00
Ryan Hamamura
d6e64763cc fix: use templ.NewOnceHandle to prevent script duplication on SSE patches
All checks were successful
CI / Deploy / test (pull_request) Successful in 15s
CI / Deploy / lint (pull_request) Successful in 25s
CI / Deploy / deploy (pull_request) Has been skipped
Replace ConnectionIndicatorWithScript wrapper with a single ConnectionIndicator
component that uses templ.NewOnceHandle() to ensure the watcher script is only
rendered once per page, even when the indicator is patched via SSE.
2026-03-03 10:43:23 -10:00
589d1f09e8 Merge pull request 'Refactor connection indicator to patch with timestamp' (#11) from refactor/patch-connection-indicator into main
All checks were successful
CI / Deploy / test (push) Successful in 14s
CI / Deploy / lint (push) Successful in 25s
CI / Deploy / deploy (push) Successful in 1m22s
2026-03-03 20:32:11 +00:00
Ryan Hamamura
06b3839c3a refactor: patch connection indicator with timestamp
All checks were successful
CI / Deploy / test (pull_request) Successful in 14s
CI / Deploy / lint (pull_request) Successful in 26s
CI / Deploy / deploy (pull_request) Has been skipped
Server patches the ConnectionIndicator element with a timestamp on
each heartbeat. Client-side JS checks every second if the timestamp
is stale (>20s) and toggles red/green accordingly.

This properly detects connection loss since the indicator will turn
red if no patches are received.
2026-03-03 10:30:55 -10:00
99f14ca170 Merge pull request 'Add connection status indicator with SSE heartbeat' (#10) from feat/sse-heartbeat into main
All checks were successful
CI / Deploy / test (push) Successful in 15s
CI / Deploy / lint (push) Successful in 27s
CI / Deploy / deploy (push) Successful in 1m23s
2026-03-03 20:15:29 +00:00
Ryan Hamamura
da82f31d46 feat: add connection status indicator with SSE heartbeat
All checks were successful
CI / Deploy / test (pull_request) Successful in 14s
CI / Deploy / lint (pull_request) Successful in 25s
CI / Deploy / deploy (pull_request) Has been skipped
- Add ConnectionIndicator component showing green/red dot
- Send lastPing signal every 15 seconds via SSE
- Indicator turns red if no ping received in 20 seconds
- Gives users confidence the live connection is active
2026-03-03 10:05:03 -10:00
29 changed files with 3636 additions and 300 deletions

1
.gitignore vendored
View File

@@ -19,6 +19,7 @@
!.env.example
!LICENSE
!AGENTS.md
!assets/**/*

253
AGENTS.md Normal file
View File

@@ -0,0 +1,253 @@
# AGENTS.md
Instructions for AI coding agents working in this repository.
## Quick Reference
```bash
# Development
task live # Hot-reload dev server (templ + tailwind + air)
task build # Production build to bin/games
task run # Build and run server
# Quality
task test # Run all tests: go test ./...
task lint # Run linter: golangci-lint run
# Single test
go test -run TestName ./path/to/package
# Code generation
task build:templ # Compile .templ files
task build:styles # Build TailwindCSS
go generate ./... # Run sqlc for DB queries
```
## Workflow Rules
- **Never merge PRs without explicit user approval.** Create the PR, push changes, then wait.
- Always use PRs via `tea` CLI - never push directly to main.
- Write semantic commit messages focusing on "why" not "what".
## Project Structure
```
games/
├── connect4/, snake/ # Game logic packages (pure Go)
├── features/ # Feature modules (handlers, routes, templates)
│ ├── auth/ # Login/register
│ ├── c4game/ # Connect 4 UI
│ ├── snakegame/ # Snake UI
│ ├── lobby/ # Game lobby
│ └── common/ # Shared components, layouts
├── chat/ # Reusable chat room (NATS + persistence)
├── db/ # SQLite, migrations, sqlc queries
├── assets/ # Static files (embedded)
└── config/, logging/, nats/, sessions/, router/ # Infrastructure
```
## Code Style
### Imports
Organize in three groups: stdlib, third-party, local. The linter enforces this.
```go
import (
"context"
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
"github.com/ryanhamamura/games/connect4"
"github.com/ryanhamamura/games/db/repository"
)
```
### Naming Conventions
| Type | Convention | Examples |
|------|------------|----------|
| Files | lowercase, underscores | `config_dev.go`, `handlers.go` |
| HTTP handlers | `Handle` prefix | `HandleGamePage`, `HandleLogin` |
| Constructors | `New` prefix | `NewStore`, `NewRoom` |
| Getters | `Get` prefix | `GetPlayerID`, `GetGame` |
| Setup functions | `Setup` prefix | `SetupRoutes`, `SetupLogger` |
| Types | PascalCase | `Game`, `Player`, `Instance` |
| Status enums | `Status` prefix | `StatusWaitingForPlayer`, `StatusInProgress` |
| Session keys | `Key` prefix | `KeyPlayerID`, `KeyUserID` |
### Error Handling
1. **Wrap errors with context:**
```go
return fmt.Errorf("loading game %s: %w", id, err)
```
2. **Return (result, error) tuples:**
```go
func loadGame(queries *repository.Queries, id string) (*Game, error)
```
3. **Best-effort operations** - use nolint comment:
```go
nc.Publish(subject, nil) //nolint:errcheck // best-effort notification
```
4. **HTTP errors:**
```go
http.Error(w, "game not found", http.StatusNotFound)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
```
### Comments
- Focus on **why**, not **how**. Avoid superfluous comments.
- Package comments at top of primary file:
```go
// Package connect4 implements Connect 4 game logic, state management, and persistence.
package connect4
```
- Function comments for exported functions:
```go
// DropPiece attempts to drop a piece in the given column.
// Returns (row placed, success).
func (g *Game) DropPiece(col, playerColor int) (int, bool)
```
## Go Patterns
### Dependency Injection via Closures
Handlers receive dependencies and return `http.HandlerFunc`:
```go
func HandleGamePage(store *connect4.Store, sm *scs.SessionManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// use store, sm here
}
}
```
### Mutex for Concurrent Access
```go
type Store struct {
games map[string]*Instance
gamesMu sync.RWMutex
}
func (s *Store) Get(id string) (*Instance, bool) {
s.gamesMu.RLock()
defer s.gamesMu.RUnlock()
inst, ok := s.games[id]
return inst, ok
}
```
### Build Tags for Environment
```go
//go:build dev
//go:build !dev
```
### Embedded Filesystems
```go
//go:embed assets
var assets embed.FS
//go:embed migrations/*.sql
var MigrationFS embed.FS
```
### Graceful Shutdown
```go
eg, egctx := errgroup.WithContext(ctx)
eg.Go(func() error { return server.ListenAndServe() })
eg.Go(func() error {
<-egctx.Done()
return server.Shutdown(context.Background())
})
return eg.Wait()
```
## Templ + Datastar Patterns
### SSE Connection with Disabled Cancellation
Datastar cancels SSE on user interaction by default. Disable for persistent connections:
```go
data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) }
```
### Prevent Script Duplication on SSE Patches
Use `templ.NewOnceHandle()` for scripts in components that get patched:
```go
var scriptHandle = templ.NewOnceHandle()
templ MyComponent() {
<div id="my-component">...</div>
@scriptHandle.Once() {
@myScript()
}
}
```
### Conditional Classes with templ.KV
```go
class={
"status status-sm",
templ.KV("status-success", isConnected),
templ.KV("status-error", !isConnected),
}
```
### Datastar SSE Responses
```go
sse := datastar.NewSSE(w, r)
sse.MergeFragmentTempl(components.GameBoard(game))
```
## Tech Stack
| Layer | Technology |
|-------|------------|
| Templates | templ (type-safe HTML) |
| Reactivity | Datastar (SSE-driven) |
| CSS | TailwindCSS v4 + daisyUI |
| Router | chi/v5 |
| Sessions | scs/v2 |
| Database | SQLite (modernc.org/sqlite) |
| Migrations | goose |
| SQL codegen | sqlc |
| Pub/sub | Embedded NATS |
| Logging | zerolog |
## Testing
```bash
# All tests
task test
# Single test
go test -run TestDropPiece ./connect4
# With verbose output
go test -v -run TestDropPiece ./connect4
# Test a package
go test ./connect4/...
```
Use `testutil.SetupTestDB()` for tests requiring database access.

5
assets/assets.go Normal file
View File

@@ -0,0 +1,5 @@
// Package assets provides static file serving with build-tag switching
// between live filesystem (dev) and embedded hashfs (prod).
package assets
const DirectoryPath = "assets"

File diff suppressed because one or more lines are too long

22
assets/static_dev.go Normal file
View File

@@ -0,0 +1,22 @@
//go:build dev
package assets
import (
"net/http"
"os"
"github.com/rs/zerolog/log"
)
func Handler() http.Handler {
log.Debug().Str("path", DirectoryPath).Msg("static assets served from filesystem")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
http.StripPrefix("/assets/", http.FileServerFS(os.DirFS(DirectoryPath))).ServeHTTP(w, r)
})
}
func StaticPath(path string) string {
return "/assets/" + path
}

26
assets/static_prod.go Normal file
View File

@@ -0,0 +1,26 @@
//go:build !dev
package assets
import (
"embed"
"net/http"
"github.com/benbjohnson/hashfs"
"github.com/rs/zerolog/log"
)
var (
//go:embed css js
staticFiles embed.FS
staticSys = hashfs.NewFS(staticFiles)
)
func Handler() http.Handler {
log.Debug().Msg("static assets are embedded with hashfs")
return http.StripPrefix("/assets/", hashfs.FileServer(staticSys))
}
func StaticPath(path string) string {
return "/assets/" + staticSys.HashName(path)
}

View File

@@ -3,10 +3,10 @@ package auth
import (
"database/sql"
"net/http"
"net/url"
"github.com/alexedwards/scs/v2"
"github.com/google/uuid"
"github.com/starfederation/datastar-go/datastar"
"github.com/ryanhamamura/games/auth"
"github.com/ryanhamamura/games/db/repository"
@@ -14,20 +14,15 @@ import (
appsessions "github.com/ryanhamamura/games/sessions"
)
type LoginSignals struct {
Username string `json:"username"`
Password string `json:"password"` //nolint:gosec // form input, not stored
}
type RegisterSignals struct {
Username string `json:"username"`
Password string `json:"password"` //nolint:gosec // form input, not stored
Confirm string `json:"confirm"`
}
func HandleLoginPage() http.HandlerFunc {
func HandleLoginPage(sessions *scs.SessionManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := pages.LoginPage().Render(r.Context(), w); err != nil {
// Capture return_url so we can redirect back after login
if returnURL := r.URL.Query().Get("return_url"); returnURL != "" {
sessions.Put(r.Context(), "return_url", returnURL)
}
errorMsg := r.URL.Query().Get("error")
if err := pages.LoginPage(errorMsg).Render(r.Context(), w); err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
@@ -35,7 +30,8 @@ func HandleLoginPage() http.HandlerFunc {
func HandleRegisterPage() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := pages.RegisterPage().Render(r.Context(), w); err != nil {
errorMsg := r.URL.Query().Get("error")
if err := pages.RegisterPage(errorMsg).Render(r.Context(), w); err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
@@ -43,25 +39,21 @@ func HandleRegisterPage() http.HandlerFunc {
func HandleLogin(queries *repository.Queries, sessions *scs.SessionManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var signals LoginSignals
if err := datastar.ReadSignals(r, &signals); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
r.Body = http.MaxBytesReader(w, r.Body, 1024)
username := r.FormValue("username")
password := r.FormValue("password")
sse := datastar.NewSSE(w, r)
user, err := queries.GetUserByUsername(r.Context(), signals.Username)
user, err := queries.GetUserByUsername(r.Context(), username)
if err == sql.ErrNoRows {
sse.MarshalAndPatchSignals(map[string]any{"error": "Invalid username or password"}) //nolint:errcheck
http.Redirect(w, r, "/login?error="+url.QueryEscape("Invalid username or password"), http.StatusSeeOther)
return
}
if err != nil {
sse.MarshalAndPatchSignals(map[string]any{"error": "An error occurred"}) //nolint:errcheck
http.Redirect(w, r, "/login?error="+url.QueryEscape("An error occurred"), http.StatusSeeOther)
return
}
if !auth.CheckPassword(signals.Password, user.PasswordHash) {
sse.MarshalAndPatchSignals(map[string]any{"error": "Invalid username or password"}) //nolint:errcheck
if !auth.CheckPassword(password, user.PasswordHash) {
http.Redirect(w, r, "/login?error="+url.QueryEscape("Invalid username or password"), http.StatusSeeOther)
return
}
@@ -76,46 +68,43 @@ func HandleLogin(queries *repository.Queries, sessions *scs.SessionManager) http
redirectURL = returnURL
}
sse.Redirect(redirectURL) //nolint:errcheck
http.Redirect(w, r, redirectURL, http.StatusSeeOther)
}
}
func HandleRegister(queries *repository.Queries, sessions *scs.SessionManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var signals RegisterSignals
if err := datastar.ReadSignals(r, &signals); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
r.Body = http.MaxBytesReader(w, r.Body, 1024)
username := r.FormValue("username")
password := r.FormValue("password")
confirm := r.FormValue("confirm")
if err := auth.ValidateUsername(username); err != nil {
http.Redirect(w, r, "/register?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
return
}
if err := auth.ValidatePassword(password); err != nil {
http.Redirect(w, r, "/register?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
return
}
if password != confirm {
http.Redirect(w, r, "/register?error="+url.QueryEscape("Passwords do not match"), http.StatusSeeOther)
return
}
sse := datastar.NewSSE(w, r)
if err := auth.ValidateUsername(signals.Username); err != nil {
sse.MarshalAndPatchSignals(map[string]any{"error": err.Error()}) //nolint:errcheck
return
}
if err := auth.ValidatePassword(signals.Password); err != nil {
sse.MarshalAndPatchSignals(map[string]any{"error": err.Error()}) //nolint:errcheck
return
}
if signals.Password != signals.Confirm {
sse.MarshalAndPatchSignals(map[string]any{"error": "Passwords do not match"}) //nolint:errcheck
return
}
hash, err := auth.HashPassword(signals.Password)
hash, err := auth.HashPassword(password)
if err != nil {
sse.MarshalAndPatchSignals(map[string]any{"error": "An error occurred"}) //nolint:errcheck
http.Redirect(w, r, "/register?error="+url.QueryEscape("An error occurred"), http.StatusSeeOther)
return
}
user, err := queries.CreateUser(r.Context(), repository.CreateUserParams{
ID: uuid.New().String(),
Username: signals.Username,
Username: username,
PasswordHash: hash,
})
if err != nil {
sse.MarshalAndPatchSignals(map[string]any{"error": "Username already taken"}) //nolint:errcheck
http.Redirect(w, r, "/register?error="+url.QueryEscape("Username already taken"), http.StatusSeeOther)
return
}
@@ -130,6 +119,6 @@ func HandleRegister(queries *repository.Queries, sessions *scs.SessionManager) h
redirectURL = returnURL
}
sse.Redirect(redirectURL) //nolint:errcheck
http.Redirect(w, r, redirectURL, http.StatusSeeOther)
}
}

View File

@@ -0,0 +1,351 @@
package auth_test
import (
"context"
"database/sql"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/alexedwards/scs/v2"
"github.com/google/uuid"
"github.com/ryanhamamura/games/auth"
"github.com/ryanhamamura/games/db/repository"
featauth "github.com/ryanhamamura/games/features/auth"
"github.com/ryanhamamura/games/features/lobby"
appsessions "github.com/ryanhamamura/games/sessions"
"github.com/ryanhamamura/games/testutil"
)
// sessionCookieName is the default SCS cookie name used in tests.
const sessionCookieName = "session"
type testSetup struct {
db *sql.DB
queries *repository.Queries
sm *scs.SessionManager
}
func (s *testSetup) ctx() context.Context {
return context.Background()
}
func newTestSetup(t *testing.T) *testSetup {
t.Helper()
db, queries := testutil.NewTestDB(t)
sm := testutil.NewTestSessionManager(t, db)
return &testSetup{db: db, queries: queries, sm: sm}
}
// createTestUser inserts a user into the test database and returns the user ID.
func createTestUser(t *testing.T, setup *testSetup, username, password string) string {
t.Helper()
hash, err := auth.HashPassword(password)
if err != nil {
t.Fatalf("hashing password: %v", err)
}
id := uuid.New().String()
_, err = setup.queries.CreateUser(setup.ctx(), repository.CreateUserParams{
ID: id,
Username: username,
PasswordHash: hash,
})
if err != nil {
t.Fatalf("creating test user: %v", err)
}
return id
}
// postForm sends a POST request with form-encoded body through the session middleware,
// forwarding any cookies from a previous response.
func postForm(handler http.Handler, path string, values url.Values, cookies []*http.Cookie) *httptest.ResponseRecorder {
body := strings.NewReader(values.Encode())
req := httptest.NewRequest(http.MethodPost, path, body)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
for _, c := range cookies {
req.AddCookie(c)
}
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec
}
// getPage sends a GET request through the session middleware, forwarding cookies.
func getPage(handler http.Handler, path string, cookies []*http.Cookie) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
for _, c := range cookies {
req.AddCookie(c)
}
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec
}
// extractSessionValue makes a GET request with the given cookies to a test endpoint
// that reads a session value, verifying the session was persisted correctly.
func extractSessionValue(t *testing.T, setup *testSetup, cookies []*http.Cookie, key string) string {
t.Helper()
var value string
handler := setup.sm.LoadAndSave(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
value = setup.sm.GetString(r.Context(), key)
}))
req := httptest.NewRequest(http.MethodGet, "/check-session", nil)
for _, c := range cookies {
req.AddCookie(c)
}
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("session check returned %d", rec.Code)
}
return value
}
func TestHandleLogin_Success(t *testing.T) {
setup := newTestSetup(t)
createTestUser(t, setup, "alice", "password123")
handler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
rec := postForm(handler, "/auth/login", url.Values{
"username": {"alice"},
"password": {"password123"},
}, nil)
if rec.Code != http.StatusSeeOther {
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
}
if loc := rec.Header().Get("Location"); loc != "/" {
t.Errorf("expected redirect to /, got %q", loc)
}
// Verify the response sets a session cookie
cookies := rec.Result().Cookies()
if !hasCookie(cookies, sessionCookieName) {
t.Fatal("response did not set a session cookie")
}
// Verify session contains user data by reading it back
userID := extractSessionValue(t, setup, cookies, appsessions.KeyUserID)
if userID == "" {
t.Error("session does not contain user_id after login")
}
nickname := extractSessionValue(t, setup, cookies, appsessions.KeyNickname)
if nickname != "alice" {
t.Errorf("expected nickname %q, got %q", "alice", nickname)
}
}
func TestHandleLogin_InvalidPassword(t *testing.T) {
setup := newTestSetup(t)
createTestUser(t, setup, "alice", "password123")
handler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
rec := postForm(handler, "/auth/login", url.Values{
"username": {"alice"},
"password": {"wrongpassword"},
}, nil)
if rec.Code != http.StatusSeeOther {
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
}
loc := rec.Header().Get("Location")
if !strings.HasPrefix(loc, "/login?error=") {
t.Errorf("expected redirect to /login?error=..., got %q", loc)
}
}
func TestHandleLogin_UnknownUser(t *testing.T) {
setup := newTestSetup(t)
handler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
rec := postForm(handler, "/auth/login", url.Values{
"username": {"nonexistent"},
"password": {"password123"},
}, nil)
if rec.Code != http.StatusSeeOther {
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
}
loc := rec.Header().Get("Location")
if !strings.HasPrefix(loc, "/login?error=") {
t.Errorf("expected redirect to /login?error=..., got %q", loc)
}
}
func TestHandleLogin_ReturnURL(t *testing.T) {
setup := newTestSetup(t)
createTestUser(t, setup, "alice", "password123")
// First, visit the login page with a return_url to store it in the session
loginPageHandler := setup.sm.LoadAndSave(featauth.HandleLoginPage(setup.sm))
pageRec := getPage(loginPageHandler, "/login?return_url=/games/abc", nil)
cookies := pageRec.Result().Cookies()
// Now log in with those cookies so the handler can read return_url from session
loginHandler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
rec := postForm(loginHandler, "/auth/login", url.Values{
"username": {"alice"},
"password": {"password123"},
}, cookies)
if rec.Code != http.StatusSeeOther {
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
}
if loc := rec.Header().Get("Location"); loc != "/games/abc" {
t.Errorf("expected redirect to /games/abc, got %q", loc)
}
}
func TestHandleRegister_Success(t *testing.T) {
setup := newTestSetup(t)
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
rec := postForm(handler, "/auth/register", url.Values{
"username": {"newuser"},
"password": {"password123"},
"confirm": {"password123"},
}, nil)
if rec.Code != http.StatusSeeOther {
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
}
if loc := rec.Header().Get("Location"); loc != "/" {
t.Errorf("expected redirect to /, got %q", loc)
}
cookies := rec.Result().Cookies()
if !hasCookie(cookies, sessionCookieName) {
t.Fatal("response did not set a session cookie")
}
userID := extractSessionValue(t, setup, cookies, appsessions.KeyUserID)
if userID == "" {
t.Error("session does not contain user_id after registration")
}
}
func TestHandleRegister_PasswordMismatch(t *testing.T) {
setup := newTestSetup(t)
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
rec := postForm(handler, "/auth/register", url.Values{
"username": {"newuser"},
"password": {"password123"},
"confirm": {"differentpassword"},
}, nil)
if rec.Code != http.StatusSeeOther {
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
}
loc := rec.Header().Get("Location")
if !strings.Contains(loc, "Passwords+do+not+match") {
t.Errorf("expected error about password mismatch, got %q", loc)
}
}
func TestHandleRegister_InvalidUsername(t *testing.T) {
setup := newTestSetup(t)
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
rec := postForm(handler, "/auth/register", url.Values{
"username": {"ab"}, // too short
"password": {"password123"},
"confirm": {"password123"},
}, nil)
if rec.Code != http.StatusSeeOther {
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
}
loc := rec.Header().Get("Location")
if !strings.HasPrefix(loc, "/register?error=") {
t.Errorf("expected redirect to /register?error=..., got %q", loc)
}
}
func TestHandleRegister_ShortPassword(t *testing.T) {
setup := newTestSetup(t)
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
rec := postForm(handler, "/auth/register", url.Values{
"username": {"validuser"},
"password": {"short"},
"confirm": {"short"},
}, nil)
if rec.Code != http.StatusSeeOther {
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
}
loc := rec.Header().Get("Location")
if !strings.HasPrefix(loc, "/register?error=") {
t.Errorf("expected redirect to /register?error=..., got %q", loc)
}
}
func TestHandleRegister_DuplicateUsername(t *testing.T) {
setup := newTestSetup(t)
createTestUser(t, setup, "taken", "password123")
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
rec := postForm(handler, "/auth/register", url.Values{
"username": {"taken"},
"password": {"password123"},
"confirm": {"password123"},
}, nil)
if rec.Code != http.StatusSeeOther {
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
}
loc := rec.Header().Get("Location")
if !strings.Contains(loc, "Username+already+taken") {
t.Errorf("expected error about duplicate username, got %q", loc)
}
}
func TestHandleLogout(t *testing.T) {
setup := newTestSetup(t)
createTestUser(t, setup, "alice", "password123")
// Log in first to establish a session
loginHandler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
loginRec := postForm(loginHandler, "/auth/login", url.Values{
"username": {"alice"},
"password": {"password123"},
}, nil)
cookies := loginRec.Result().Cookies()
// Verify we're logged in
userID := extractSessionValue(t, setup, cookies, appsessions.KeyUserID)
if userID == "" {
t.Fatal("expected to be logged in before testing logout")
}
// Now log out
logoutHandler := setup.sm.LoadAndSave(lobby.HandleLogout(setup.sm))
logoutRec := postForm(logoutHandler, "/logout", nil, cookies)
if logoutRec.Code != http.StatusSeeOther {
t.Errorf("expected status %d, got %d", http.StatusSeeOther, logoutRec.Code)
}
if loc := logoutRec.Header().Get("Location"); loc != "/" {
t.Errorf("expected redirect to /, got %q", loc)
}
// Verify session is cleared — use the cookies from the logout response
logoutCookies := logoutRec.Result().Cookies()
userID = extractSessionValue(t, setup, logoutCookies, appsessions.KeyUserID)
if userID != "" {
t.Errorf("expected empty user_id after logout, got %q", userID)
}
}
func hasCookie(cookies []*http.Cookie, name string) bool {
for _, c := range cookies {
if c.Name == name {
return true
}
}
return false
}

View File

@@ -1,45 +1,39 @@
package pages
import (
"github.com/ryanhamamura/games/features/common/layouts"
"github.com/starfederation/datastar-go/datastar"
)
import "github.com/ryanhamamura/games/features/common/layouts"
templ LoginPage() {
templ LoginPage(errorMsg string) {
@layouts.Base("Login") {
<main class="max-w-sm mx-auto mt-8 text-center" data-signals="{username: '', password: '', error: ''}">
<main class="max-w-sm mx-auto mt-8 text-center">
<h1 class="text-3xl font-bold">Login</h1>
<p class="mb-4">Sign in to your account</p>
<div data-show="$error != ''" class="alert alert-error mb-4" data-text="$error"></div>
<div>
if errorMsg != "" {
<div class="alert alert-error mb-4">{ errorMsg }</div>
}
<form method="POST" action="/auth/login">
<fieldset class="fieldset">
<label class="label" for="username">Username</label>
<input
class="input input-bordered w-full"
id="username"
name="username"
type="text"
placeholder="Enter your username"
data-bind="username"
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/login") }
autofocus
/>
autofocus
/>
<label class="label" for="password">Password</label>
<input
class="input input-bordered w-full"
id="password"
name="password"
type="password"
placeholder="Enter your password"
data-bind="password"
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/login") }
/>
</fieldset>
<button
class="btn btn-primary w-full"
data-on:click={ datastar.PostSSE("/auth/login") }
>
<button type="submit" class="btn btn-primary w-full">
Login
</button>
</div>
</form>
<p>
Don't have an account? <a class="link" href="/register">Register</a>
</p>

View File

@@ -1,54 +1,47 @@
package pages
import (
"github.com/ryanhamamura/games/features/common/layouts"
"github.com/starfederation/datastar-go/datastar"
)
import "github.com/ryanhamamura/games/features/common/layouts"
templ RegisterPage() {
templ RegisterPage(errorMsg string) {
@layouts.Base("Register") {
<main class="max-w-sm mx-auto mt-8 text-center" data-signals="{username: '', password: '', confirm: '', error: ''}">
<main class="max-w-sm mx-auto mt-8 text-center">
<h1 class="text-3xl font-bold">Register</h1>
<p class="mb-4">Create a new account</p>
<div data-show="$error != ''" class="alert alert-error mb-4" data-text="$error"></div>
<div>
if errorMsg != "" {
<div class="alert alert-error mb-4">{ errorMsg }</div>
}
<form method="POST" action="/auth/register">
<fieldset class="fieldset">
<label class="label" for="username">Username</label>
<input
class="input input-bordered w-full"
id="username"
name="username"
type="text"
placeholder="Choose a username"
data-bind="username"
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/register") }
autofocus
/>
autofocus
/>
<label class="label" for="password">Password</label>
<input
class="input input-bordered w-full"
id="password"
name="password"
type="password"
placeholder="Choose a password (min 8 chars)"
data-bind="password"
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/register") }
/>
/>
<label class="label" for="confirm">Confirm Password</label>
<input
class="input input-bordered w-full"
id="confirm"
name="confirm"
type="password"
placeholder="Confirm your password"
data-bind="confirm"
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/register") }
/>
</fieldset>
<button
class="btn btn-primary w-full"
data-on:click={ datastar.PostSSE("/auth/register") }
>
<button type="submit" class="btn btn-primary w-full">
Register
</button>
</div>
</form>
<p>
Already have an account? <a class="link" href="/login">Login</a>
</p>

View File

@@ -9,7 +9,7 @@ import (
)
func SetupRoutes(router chi.Router, queries *repository.Queries, sessions *scs.SessionManager) {
router.Get("/login", HandleLoginPage())
router.Get("/login", HandleLoginPage(sessions))
router.Get("/register", HandleRegisterPage())
router.Post("/auth/login", HandleLogin(queries, sessions))
router.Post("/auth/register", HandleRegister(queries, sessions))

View File

@@ -1,47 +1,23 @@
package c4game
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/alexedwards/scs/v2"
"github.com/go-chi/chi/v5"
"github.com/nats-io/nats.go"
"github.com/starfederation/datastar-go/datastar"
"github.com/ryanhamamura/games/chat"
chatcomponents "github.com/ryanhamamura/games/chat/components"
"github.com/ryanhamamura/games/connect4"
"github.com/ryanhamamura/games/db/repository"
"github.com/ryanhamamura/games/features/c4game/pages"
"github.com/ryanhamamura/games/features/c4game/services"
"github.com/ryanhamamura/games/sessions"
)
// c4ChatColors maps player color (1=Red, 2=Yellow) to CSS background colors.
var c4ChatColors = map[int]string{
0: "#4a2a3a", // color 1 stored as slot 0
1: "#2a4545", // color 2 stored as slot 1
}
func c4ChatColor(slot int) string {
if c, ok := c4ChatColors[slot]; ok {
return c
}
return "#666"
}
func c4ChatConfig(gameID string) chatcomponents.Config {
return chatcomponents.Config{
CSSPrefix: "c4",
PostURL: fmt.Sprintf("/games/%s/chat", gameID),
Color: c4ChatColor,
}
}
func HandleGamePage(store *connect4.Store, sm *scs.SessionManager, queries *repository.Queries) http.HandlerFunc {
func HandleGamePage(store *connect4.Store, svc *services.GameService, sm *scs.SessionManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gameID := chi.URLParam(r, "id")
@@ -85,16 +61,17 @@ func HandleGamePage(store *connect4.Store, sm *scs.SessionManager, queries *repo
}
g := gi.GetGame()
room := chat.NewPersistentRoom(nil, "", queries, gameID)
room := svc.ChatRoom(gameID)
if err := pages.GamePage(g, myColor, room.Messages(), c4ChatConfig(gameID)).Render(r.Context(), w); err != nil {
if err := pages.GamePage(g, myColor, room.Messages(), svc.ChatConfig(gameID)).Render(r.Context(), w); err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
}
func HandleGameEvents(store *connect4.Store, nc *nats.Conn, sm *scs.SessionManager, queries *repository.Queries) http.HandlerFunc {
func HandleGameEvents(store *connect4.Store, svc *services.GameService, sm *scs.SessionManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
gameID := chi.URLParam(r, "id")
gi, exists := store.Get(gameID)
@@ -104,71 +81,74 @@ func HandleGameEvents(store *connect4.Store, nc *nats.Conn, sm *scs.SessionManag
}
playerID := sessions.GetPlayerID(sm, r)
myColor := gi.GetPlayerColor(playerID)
sse := datastar.NewSSE(w, r, datastar.WithCompression(
datastar.WithBrotli(datastar.WithBrotliLevel(5)),
))
chatCfg := c4ChatConfig(gameID)
room := chat.NewPersistentRoom(nc, connect4.ChatSubject(gameID), queries, gameID)
patchAll := func() error {
myColor = gi.GetPlayerColor(playerID)
g := gi.GetGame()
return sse.PatchElementTempl(pages.GameContent(g, myColor, room.Messages(), chatCfg))
}
sendPing := func() error {
data, _ := json.Marshal(struct {
LastPing int64 `json:"lastPing"`
}{time.Now().UnixMilli()})
return sse.PatchSignals(data)
}
// Send initial render and ping
if err := sendPing(); err != nil {
return
}
if err := patchAll(); err != nil {
return
}
heartbeat := time.NewTicker(15 * time.Second)
defer heartbeat.Stop()
// Subscribe to game state updates
gameCh := make(chan *nats.Msg, 64)
gameSub, err := nc.ChanSubscribe(connect4.GameSubject(gameID), gameCh)
// Subscribe to game state updates BEFORE creating SSE
gameSub, gameCh, err := svc.SubscribeGameUpdates(gameID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer gameSub.Unsubscribe() //nolint:errcheck
// Subscribe to chat messages
// Subscribe to chat messages BEFORE creating SSE
chatCfg := svc.ChatConfig(gameID)
room := svc.ChatRoom(gameID)
chatCh, cleanupChat := room.Subscribe()
defer cleanupChat()
ctx := r.Context()
// Setup heartbeat BEFORE creating SSE
heartbeat := time.NewTicker(1 * time.Second)
defer heartbeat.Stop()
// NOW create SSE
sse := datastar.NewSSE(w, r, datastar.WithCompression(
datastar.WithBrotli(datastar.WithBrotliLevel(5)),
))
// Define patch function
patchAll := func() error {
myColor := gi.GetPlayerColor(playerID)
g := gi.GetGame()
return sse.PatchElementTempl(pages.GameContent(g, myColor, room.Messages(), chatCfg))
}
// Send initial state
if err := patchAll(); err != nil {
return
}
// Event loop
for {
select {
case <-ctx.Done():
return
case <-heartbeat.C:
if err := sendPing(); err != nil {
return
}
case <-gameCh:
// Drain rapid-fire notifications
drainGame:
for {
select {
case <-gameCh:
default:
break drainGame
}
}
if err := patchAll(); err != nil {
return
}
case chatMsg := <-chatCh:
err := sse.PatchElementTempl(
if err := sse.PatchElementTempl(
chatcomponents.ChatMessage(chatMsg, chatCfg),
datastar.WithSelectorID("c4-chat-history"),
datastar.WithModeAppend(),
)
if err != nil {
); err != nil {
return
}
case <-heartbeat.C:
// Heartbeat refreshes game state to keep connection alive
if err := patchAll(); err != nil {
return
}
}
@@ -205,7 +185,7 @@ func HandleDropPiece(store *connect4.Store, sm *scs.SessionManager) http.Handler
}
}
func HandleSendChat(store *connect4.Store, nc *nats.Conn, sm *scs.SessionManager, queries *repository.Queries) http.HandlerFunc {
func HandleSendChat(store *connect4.Store, svc *services.GameService, sm *scs.SessionManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gameID := chi.URLParam(r, "id")
@@ -252,7 +232,7 @@ func HandleSendChat(store *connect4.Store, nc *nats.Conn, sm *scs.SessionManager
Message: signals.ChatMsg,
Time: time.Now().UnixMilli(),
}
room := chat.NewPersistentRoom(nc, connect4.ChatSubject(gameID), queries, gameID)
room := svc.ChatRoom(gameID)
room.Send(msg)
sse := datastar.NewSSE(w, r)

View File

@@ -15,10 +15,9 @@ templ GamePage(g *connect4.Game, myColor int, messages []chat.Message, chatCfg c
@layouts.Base("Connect 4") {
<main
class="flex flex-col items-center gap-4 p-4"
data-signals="{chatMsg: '', lastPing: 0}"
data-signals="{chatMsg: ''}"
data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) }
>
@sharedcomponents.ConnectionIndicator()
@GameContent(g, myColor, messages, chatCfg)
</main>
}
@@ -26,6 +25,7 @@ templ GamePage(g *connect4.Game, myColor int, messages []chat.Message, chatCfg c
templ GameContent(g *connect4.Game, myColor int, messages []chat.Message, chatCfg chatcomponents.Config) {
<div id="game-content">
@sharedcomponents.LiveClock()
@sharedcomponents.BackToLobby()
@sharedcomponents.StealthTitle("text-3xl font-bold")
@components.PlayerInfo(g, myColor)

View File

@@ -4,24 +4,22 @@ package c4game
import (
"github.com/alexedwards/scs/v2"
"github.com/go-chi/chi/v5"
"github.com/nats-io/nats.go"
"github.com/ryanhamamura/games/connect4"
"github.com/ryanhamamura/games/db/repository"
"github.com/ryanhamamura/games/features/c4game/services"
)
func SetupRoutes(
router chi.Router,
store *connect4.Store,
nc *nats.Conn,
svc *services.GameService,
sessions *scs.SessionManager,
queries *repository.Queries,
) {
router.Route("/games/{id}", func(r chi.Router) {
r.Get("/", HandleGamePage(store, sessions, queries))
r.Get("/events", HandleGameEvents(store, nc, sessions, queries))
r.Get("/", HandleGamePage(store, svc, sessions))
r.Get("/events", HandleGameEvents(store, svc, sessions))
r.Post("/drop", HandleDropPiece(store, sessions))
r.Post("/chat", HandleSendChat(store, nc, sessions, queries))
r.Post("/chat", HandleSendChat(store, svc, sessions))
r.Post("/join", HandleSetNickname(store, sessions))
r.Post("/rematch", HandleRematch(store, sessions))
})

View File

@@ -0,0 +1,70 @@
// Package services provides the game service layer for Connect 4,
// handling NATS subscriptions and chat room management.
package services
import (
"fmt"
"github.com/nats-io/nats.go"
"github.com/ryanhamamura/games/chat"
chatcomponents "github.com/ryanhamamura/games/chat/components"
"github.com/ryanhamamura/games/connect4"
"github.com/ryanhamamura/games/db/repository"
)
// c4ChatColors maps player slot (0-indexed) to CSS background colors.
var c4ChatColors = map[int]string{
0: "#4a2a3a", // Red player
1: "#2a4545", // Yellow player
}
func c4ChatColor(slot int) string {
if c, ok := c4ChatColors[slot]; ok {
return c
}
return "#666"
}
// GameService manages NATS subscriptions and chat for Connect 4 games.
type GameService struct {
nc *nats.Conn
queries *repository.Queries
}
// NewGameService creates a new game service.
func NewGameService(nc *nats.Conn, queries *repository.Queries) *GameService {
return &GameService{
nc: nc,
queries: queries,
}
}
// SubscribeGameUpdates returns a NATS subscription and channel for game state updates.
func (s *GameService) SubscribeGameUpdates(gameID string) (*nats.Subscription, <-chan *nats.Msg, error) {
ch := make(chan *nats.Msg, 64)
sub, err := s.nc.ChanSubscribe(connect4.GameSubject(gameID), ch)
if err != nil {
return nil, nil, fmt.Errorf("subscribing to game updates: %w", err)
}
return sub, ch, nil
}
// ChatConfig returns the chat configuration for a game.
func (s *GameService) ChatConfig(gameID string) chatcomponents.Config {
return chatcomponents.Config{
CSSPrefix: "c4",
PostURL: fmt.Sprintf("/games/%s/chat", gameID),
Color: c4ChatColor,
}
}
// ChatRoom returns a persistent chat room for a game.
func (s *GameService) ChatRoom(gameID string) *chat.Room {
return chat.NewPersistentRoom(s.nc, connect4.ChatSubject(gameID), s.queries, gameID)
}
// PublishGameUpdate sends a notification that the game state has changed.
func (s *GameService) PublishGameUpdate(gameID string) error {
return s.nc.Publish(connect4.GameSubject(gameID), nil)
}

View File

@@ -1,6 +1,10 @@
package components
import "github.com/starfederation/datastar-go/datastar"
import (
"time"
"github.com/starfederation/datastar-go/datastar"
)
templ BackToLobby() {
<a class="link text-sm opacity-70" href="/">&larr; Back</a>
@@ -44,18 +48,12 @@ templ NicknamePrompt(returnPath string) {
</main>
}
// ConnectionIndicator shows a small dot indicating SSE connection status.
// It requires a `lastPing` signal (unix ms timestamp) to be set by the server.
templ ConnectionIndicator() {
<div
id="connection-indicator"
class="fixed top-2 right-2 flex items-center gap-1 text-xs text-gray-500"
title="Connection status"
>
<span
class="w-2 h-2 rounded-full transition-colors duration-300"
data-class="{'bg-green-500': Date.now() - $lastPing < 20000, 'bg-red-500': Date.now() - $lastPing >= 20000}"
></span>
// LiveClock shows the current server time, updated every second via SSE.
// If the clock stops updating, users know the connection is stale.
templ LiveClock() {
<div class="fixed top-2 right-2 flex items-center gap-1.5 text-xs opacity-60 font-mono">
<div style="width: 6px; height: 6px; border-radius: 50%; background-color: #22c55e;"></div>
{ time.Now().Format("15:04:05") }
</div>
}

View File

@@ -1,6 +1,7 @@
package layouts
import (
"github.com/ryanhamamura/games/assets"
"github.com/ryanhamamura/games/config"
"github.com/ryanhamamura/games/version"
)
@@ -11,8 +12,8 @@ templ Base(title string) {
<head>
<title>{ title }</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
<script defer type="module" src="/assets/js/datastar.js"></script>
<link href="/assets/css/output.css" rel="stylesheet" type="text/css"/>
<script defer type="module" src={ assets.StaticPath("js/datastar.js") }></script>
<link href={ assets.StaticPath("css/output.css") } rel="stylesheet" type="text/css"/>
</head>
<body class="flex flex-col h-screen">
if config.Global.Environment == config.Dev {

View File

@@ -171,7 +171,6 @@ func HandleLogout(sessions *scs.SessionManager) http.HandlerFunc {
return
}
sse := datastar.NewSSE(w, r)
sse.ExecuteScript("window.location.href='/'") //nolint:errcheck
http.Redirect(w, r, "/", http.StatusSeeOther)
}
}

View File

@@ -20,13 +20,11 @@ templ LobbyPage(data LobbyData) {
if data.IsLoggedIn {
<div class="flex justify-center items-center gap-4 mb-4 p-2 bg-base-200 rounded-lg">
<span>Logged in as <strong>{ data.Username }</strong></span>
<button
type="button"
class="btn btn-ghost btn-sm"
data-on:click={ datastar.PostSSE("/logout") }
>
Logout
</button>
<form method="POST" action="/logout" class="inline">
<button type="submit" class="btn btn-ghost btn-sm">
Logout
</button>
</form>
</div>
} else {
<div class="alert text-sm mb-4">

View File

@@ -1,41 +1,24 @@
package snakegame
import (
"encoding/json"
"fmt"
"errors"
"net/http"
"strconv"
"time"
"github.com/alexedwards/scs/v2"
"github.com/go-chi/chi/v5"
"github.com/nats-io/nats.go"
"github.com/starfederation/datastar-go/datastar"
"github.com/ryanhamamura/games/chat"
chatcomponents "github.com/ryanhamamura/games/chat/components"
"github.com/ryanhamamura/games/features/snakegame/pages"
"github.com/ryanhamamura/games/features/snakegame/services"
"github.com/ryanhamamura/games/sessions"
"github.com/ryanhamamura/games/snake"
)
func snakeChatColor(slot int) string {
if slot >= 0 && slot < len(snake.SnakeColors) {
return snake.SnakeColors[slot]
}
return "#666"
}
func snakeChatConfig(gameID string) chatcomponents.Config {
return chatcomponents.Config{
CSSPrefix: "snake",
PostURL: fmt.Sprintf("/snake/%s/chat", gameID),
Color: snakeChatColor,
StopKeyPropagation: true,
}
}
func HandleSnakePage(snakeStore *snake.SnakeStore, sm *scs.SessionManager) http.HandlerFunc {
func HandleSnakePage(snakeStore *snake.SnakeStore, svc *services.GameService, sm *scs.SessionManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gameID := chi.URLParam(r, "id")
si, ok := snakeStore.Get(gameID)
@@ -77,13 +60,14 @@ func HandleSnakePage(snakeStore *snake.SnakeStore, sm *scs.SessionManager) http.
}
sg := si.GetGame()
if err := pages.GamePage(sg, mySlot, nil, snakeChatConfig(gameID), gameID).Render(r.Context(), w); err != nil {
chatCfg := svc.ChatConfig(gameID)
if err := pages.GamePage(sg, mySlot, nil, chatCfg, gameID).Render(r.Context(), w); err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
}
func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.SessionManager) http.HandlerFunc {
func HandleSnakeEvents(snakeStore *snake.SnakeStore, svc *services.GameService, sm *scs.SessionManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gameID := chi.URLParam(r, "id")
si, ok := snakeStore.Get(gameID)
@@ -95,17 +79,25 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
playerID := sessions.GetPlayerID(sm, r)
mySlot := si.GetPlayerSlot(playerID)
// Subscribe to game updates BEFORE creating SSE (following portigo pattern)
gameSub, gameCh, err := svc.SubscribeGameUpdates(gameID)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
defer gameSub.Unsubscribe() //nolint:errcheck
sse := datastar.NewSSE(w, r, datastar.WithCompression(
datastar.WithBrotli(datastar.WithBrotliLevel(5)),
))
chatCfg := snakeChatConfig(gameID)
chatCfg := svc.ChatConfig(gameID)
// Chat room (multiplayer only)
var room *chat.Room
sg := si.GetGame()
if sg.Mode == snake.ModeMultiplayer {
room = chat.NewRoom(nc, snake.ChatSubject(gameID))
room = svc.ChatRoom(gameID)
}
chatMessages := func() []chat.Message {
@@ -118,39 +110,21 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
patchAll := func() error {
si, ok = snakeStore.Get(gameID)
if !ok {
return fmt.Errorf("game not found")
return errors.New("game not found")
}
mySlot = si.GetPlayerSlot(playerID)
sg = si.GetGame()
return sse.PatchElementTempl(pages.GameContent(sg, mySlot, chatMessages(), chatCfg, gameID))
}
sendPing := func() error {
data, _ := json.Marshal(struct {
LastPing int64 `json:"lastPing"`
}{time.Now().UnixMilli()})
return sse.PatchSignals(data)
}
// Send initial render and ping
if err := sendPing(); err != nil {
return
}
// Send initial render
if err := patchAll(); err != nil {
return
}
heartbeat := time.NewTicker(15 * time.Second)
heartbeat := time.NewTicker(1 * time.Second)
defer heartbeat.Stop()
// Subscribe to game updates via NATS
gameCh := make(chan *nats.Msg, 64)
gameSub, err := nc.ChanSubscribe(snake.GameSubject(gameID), gameCh)
if err != nil {
return
}
defer gameSub.Unsubscribe() //nolint:errcheck
// Chat subscription (multiplayer only)
var chatCh <-chan chat.Message
var cleanupChat func()
@@ -167,7 +141,8 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
return
case <-heartbeat.C:
if err := sendPing(); err != nil {
// Heartbeat refreshes game state to keep connection alive
if err := patchAll(); err != nil {
return
}
@@ -234,7 +209,7 @@ type chatSignals struct {
ChatMsg string `json:"chatMsg"`
}
func HandleSendChat(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.SessionManager) http.HandlerFunc {
func HandleSendChat(snakeStore *snake.SnakeStore, svc *services.GameService, sm *scs.SessionManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gameID := chi.URLParam(r, "id")
si, ok := snakeStore.Get(gameID)
@@ -267,7 +242,7 @@ func HandleSendChat(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Session
Message: signals.ChatMsg,
}
room := chat.NewRoom(nc, snake.ChatSubject(gameID))
room := svc.ChatRoom(gameID)
room.Send(msg)
sse := datastar.NewSSE(w, r)

View File

@@ -32,12 +32,11 @@ templ GamePage(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg
@layouts.Base("Snake") {
<main
class="snake-wrapper flex flex-col items-center gap-4 p-4"
data-signals={ `{"chatMsg":"","lastPing":0}` }
data-signals={ `{"chatMsg":""}` }
data-init={ fmt.Sprintf("@get('/snake/%s/events',{requestCancellation:'disabled'})", gameID) }
data-on:keydown__throttle.100ms={ keydownScript(gameID) }
tabindex="0"
>
@components.ConnectionIndicator()
@GameContent(sg, mySlot, messages, chatCfg, gameID)
</main>
}
@@ -45,6 +44,7 @@ templ GamePage(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg
templ GameContent(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg chatcomponents.Config, gameID string) {
<div id="game-content">
@components.LiveClock()
@components.BackToLobby()
<h1 class="text-3xl font-bold">~~~~</h1>
@snakecomponents.PlayerList(sg, mySlot)

View File

@@ -4,17 +4,17 @@ package snakegame
import (
"github.com/alexedwards/scs/v2"
"github.com/go-chi/chi/v5"
"github.com/nats-io/nats.go"
"github.com/ryanhamamura/games/features/snakegame/services"
"github.com/ryanhamamura/games/snake"
)
func SetupRoutes(router chi.Router, snakeStore *snake.SnakeStore, nc *nats.Conn, sessions *scs.SessionManager) {
func SetupRoutes(router chi.Router, snakeStore *snake.SnakeStore, svc *services.GameService, sessions *scs.SessionManager) {
router.Route("/snake/{id}", func(r chi.Router) {
r.Get("/", HandleSnakePage(snakeStore, sessions))
r.Get("/events", HandleSnakeEvents(snakeStore, nc, sessions))
r.Get("/", HandleSnakePage(snakeStore, svc, sessions))
r.Get("/events", HandleSnakeEvents(snakeStore, svc, sessions))
r.Post("/dir", HandleSetDirection(snakeStore, sessions))
r.Post("/chat", HandleSendChat(snakeStore, nc, sessions))
r.Post("/chat", HandleSendChat(snakeStore, svc, sessions))
r.Post("/join", HandleSetNickname(snakeStore, sessions))
r.Post("/rematch", HandleRematch(snakeStore, sessions))
})

View File

@@ -0,0 +1,62 @@
// Package services provides the game service layer for Snake,
// handling NATS subscriptions and chat room management.
package services
import (
"fmt"
"github.com/nats-io/nats.go"
"github.com/ryanhamamura/games/chat"
chatcomponents "github.com/ryanhamamura/games/chat/components"
"github.com/ryanhamamura/games/snake"
)
func snakeChatColor(slot int) string {
if slot >= 0 && slot < len(snake.SnakeColors) {
return snake.SnakeColors[slot]
}
return "#666"
}
// GameService manages NATS subscriptions and chat for Snake games.
type GameService struct {
nc *nats.Conn
}
// NewGameService creates a new game service.
func NewGameService(nc *nats.Conn) *GameService {
return &GameService{
nc: nc,
}
}
// SubscribeGameUpdates returns a NATS subscription and channel for game state updates.
func (s *GameService) SubscribeGameUpdates(gameID string) (*nats.Subscription, <-chan *nats.Msg, error) {
ch := make(chan *nats.Msg, 64)
sub, err := s.nc.ChanSubscribe(snake.GameSubject(gameID), ch)
if err != nil {
return nil, nil, fmt.Errorf("subscribing to game updates: %w", err)
}
return sub, ch, nil
}
// ChatConfig returns the chat configuration for a game.
func (s *GameService) ChatConfig(gameID string) chatcomponents.Config {
return chatcomponents.Config{
CSSPrefix: "snake",
PostURL: fmt.Sprintf("/snake/%s/chat", gameID),
Color: snakeChatColor,
StopKeyPropagation: true,
}
}
// ChatRoom returns a chat room for a game (ephemeral, not persisted).
func (s *GameService) ChatRoom(gameID string) *chat.Room {
return chat.NewRoom(s.nc, snake.ChatSubject(gameID))
}
// PublishGameUpdate sends a notification that the game state has changed.
func (s *GameService) PublishGameUpdate(gameID string) error {
return s.nc.Publish(snake.GameSubject(gameID), nil)
}

4
go.mod
View File

@@ -68,6 +68,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 // indirect
github.com/aws/smithy-go v1.24.0 // indirect
github.com/benbjohnson/hashfs v0.2.2 // indirect
github.com/bep/godartsass/v2 v2.5.0 // indirect
github.com/bep/golibsass v1.2.0 // indirect
github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect
@@ -170,6 +171,9 @@ require (
github.com/rivo/uniseg v0.4.7 // indirect
github.com/riza-io/grpc-go v0.2.0 // indirect
github.com/sajari/fuzzy v1.0.0 // indirect
github.com/samber/lo v1.52.0 // indirect
github.com/samber/slog-common v0.20.0 // indirect
github.com/samber/slog-zerolog/v2 v2.9.1 // indirect
github.com/segmentio/asm v1.2.1 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
github.com/shopspring/decimal v1.4.0 // indirect

8
go.sum
View File

@@ -136,6 +136,8 @@ github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/benbjohnson/hashfs v0.2.2 h1:vFZtksphM5LcnMRFctj49jCUkCc7wp3NP6INyfjkse4=
github.com/benbjohnson/hashfs v0.2.2/go.mod h1:7OMXaMVo1YkfiIPxKrl7OXkUTUgWjmsAKyR+E6xDIRM=
github.com/bep/clocks v0.5.0 h1:hhvKVGLPQWRVsBP/UB7ErrHYIO42gINVbvqxvYTPVps=
github.com/bep/clocks v0.5.0/go.mod h1:SUq3q+OOq41y2lRQqH5fsOoxN8GbxSiT6jvoVVLCVhU=
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
@@ -565,6 +567,12 @@ github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sajari/fuzzy v1.0.0 h1:+FmwVvJErsd0d0hAPlj4CxqxUtQY/fOoY0DwX4ykpRY=
github.com/sajari/fuzzy v1.0.0/go.mod h1:OjYR6KxoWOe9+dOlXeiCJd4dIbED4Oo8wpS89o0pwOo=
github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
github.com/samber/slog-common v0.20.0 h1:WaLnm/aCvBJSk5nR5aXZTFBaV0B47A+AEaEOiZDeUnc=
github.com/samber/slog-common v0.20.0/go.mod h1:+Ozat1jgnnE59UAlmNX1IF3IByHsODnnwf9jUcBZ+m8=
github.com/samber/slog-zerolog/v2 v2.9.1 h1:RMOq8XqzfuGx1X0TEIlS9OXbbFmqLY2/wJppghz66YY=
github.com/samber/slog-zerolog/v2 v2.9.1/go.mod h1:DQYYve14WgCRN/XnKeHl4266jXK0DgYkYXkfZ4Fp98k=
github.com/sebdah/goldie/v2 v2.8.0 h1:dZb9wR8q5++oplmEiJT+U/5KyotVD+HNGCAc5gNr8rc=
github.com/sebdah/goldie/v2 v2.8.0/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI=
github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=

View File

@@ -5,10 +5,11 @@ import (
"net/http"
"time"
"github.com/ryanhamamura/games/config"
"github.com/go-chi/chi/v5/middleware"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/ryanhamamura/games/config"
)
const (
@@ -64,25 +65,15 @@ func colorLatency(d time.Duration, useColor bool) string {
}
}
type responseWriter struct {
http.ResponseWriter
status int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.status = code
rw.ResponseWriter.WriteHeader(code)
}
func RequestLogger(logger *zerolog.Logger, env config.Environment) 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()
rw := &responseWriter{ResponseWriter: w}
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(rw, r)
next.ServeHTTP(ww, r)
status := rw.status
status := ww.Status()
if status == 0 {
status = http.StatusOK
}

28
main.go
View File

@@ -2,7 +2,6 @@ package main
import (
"context"
"embed"
"fmt"
"log/slog"
"net"
@@ -11,6 +10,12 @@ import (
"syscall"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/rs/zerolog/log"
slogzerolog "github.com/samber/slog-zerolog/v2"
"golang.org/x/sync/errgroup"
"github.com/ryanhamamura/games/config"
"github.com/ryanhamamura/games/connect4"
"github.com/ryanhamamura/games/db"
@@ -21,22 +26,19 @@ import (
"github.com/ryanhamamura/games/sessions"
"github.com/ryanhamamura/games/snake"
"github.com/ryanhamamura/games/version"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/rs/zerolog/log"
"golang.org/x/sync/errgroup"
)
//go:embed assets
var assets embed.FS
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
cfg := config.Global
logging.SetupLogger(cfg.Environment, cfg.LogLevel)
zerologLogger := logging.SetupLogger(cfg.Environment, cfg.LogLevel)
slog.SetDefault(slog.New(slogzerolog.Option{
Level: slogzerolog.ZeroLogLeveler{Logger: zerologLogger},
Logger: zerologLogger,
NoTimestamp: true,
}.NewZerologHandler()))
if err := run(ctx); err != nil && err != http.ErrServerClosed {
log.Fatal().Err(err).Msg("server error")
@@ -91,7 +93,7 @@ func run(ctx context.Context) error {
sessionManager.LoadAndSave,
)
router.SetupRoutes(r, queries, sessionManager, nc, store, snakeStore, assets)
router.SetupRoutes(r, queries, sessionManager, nc, store, snakeStore)
// HTTP server
srv := &http.Server{
@@ -101,6 +103,10 @@ func run(ctx context.Context) error {
BaseContext: func(l net.Listener) context.Context {
return egctx
},
ErrorLog: slog.NewLogLogger(
slog.Default().Handler(),
slog.LevelError,
),
}
eg.Go(func() error {

View File

@@ -2,24 +2,25 @@
package router
import (
"embed"
"io/fs"
"net/http"
"sync"
"github.com/ryanhamamura/games/config"
"github.com/ryanhamamura/games/connect4"
"github.com/ryanhamamura/games/db/repository"
"github.com/ryanhamamura/games/features/auth"
"github.com/ryanhamamura/games/features/c4game"
"github.com/ryanhamamura/games/features/lobby"
"github.com/ryanhamamura/games/features/snakegame"
"github.com/ryanhamamura/games/snake"
"github.com/alexedwards/scs/v2"
"github.com/go-chi/chi/v5"
"github.com/nats-io/nats.go"
"github.com/starfederation/datastar-go/datastar"
"github.com/ryanhamamura/games/assets"
"github.com/ryanhamamura/games/config"
"github.com/ryanhamamura/games/connect4"
"github.com/ryanhamamura/games/db/repository"
"github.com/ryanhamamura/games/features/auth"
"github.com/ryanhamamura/games/features/c4game"
c4services "github.com/ryanhamamura/games/features/c4game/services"
"github.com/ryanhamamura/games/features/lobby"
"github.com/ryanhamamura/games/features/snakegame"
snakeservices "github.com/ryanhamamura/games/features/snakegame/services"
"github.com/ryanhamamura/games/snake"
)
func SetupRoutes(
@@ -29,21 +30,23 @@ func SetupRoutes(
nc *nats.Conn,
store *connect4.Store,
snakeStore *snake.SnakeStore,
assets embed.FS,
) {
// Static assets
subFS, _ := fs.Sub(assets, "assets")
router.Handle("/assets/*", http.StripPrefix("/assets/", http.FileServerFS(subFS)))
router.Handle("/assets/*", assets.Handler())
// Hot-reload for development
if config.Global.Environment == config.Dev {
setupReload(router)
}
// Services
c4Svc := c4services.NewGameService(nc, queries)
snakeSvc := snakeservices.NewGameService(nc)
auth.SetupRoutes(router, queries, sessions)
lobby.SetupRoutes(router, queries, sessions, store, snakeStore)
c4game.SetupRoutes(router, store, nc, sessions, queries)
snakegame.SetupRoutes(router, snakeStore, nc, sessions)
c4game.SetupRoutes(router, store, c4Svc, sessions)
snakegame.SetupRoutes(router, snakeStore, snakeSvc, sessions)
}
func setupReload(router chi.Router) {

View File

@@ -33,7 +33,7 @@ func SetupSessionManager(db *sql.DB) (*scs.SessionManager, func()) {
sessionManager.Cookie.Name = "games_session"
sessionManager.Cookie.Path = "/"
sessionManager.Cookie.HttpOnly = true
sessionManager.Cookie.Secure = true
sessionManager.Cookie.Secure = false
sessionManager.Cookie.SameSite = http.SameSiteLaxMode
slog.Info("session manager configured")