Compare commits
1 Commits
v0.1.5
...
c77c491b64
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c77c491b64 |
@@ -48,8 +48,6 @@ jobs:
|
|||||||
runs-on: games
|
runs-on: games
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
|
||||||
fetch-depth: 0 # Need full history for git describe
|
|
||||||
|
|
||||||
- name: Sync to deploy directory
|
- name: Sync to deploy directory
|
||||||
run: |
|
run: |
|
||||||
@@ -61,8 +59,4 @@ jobs:
|
|||||||
mkdir -p $DEPLOY_DIR/data
|
mkdir -p $DEPLOY_DIR/data
|
||||||
|
|
||||||
- name: Rebuild and restart
|
- name: Rebuild and restart
|
||||||
run: |
|
run: cd $DEPLOY_DIR && docker compose up -d --build --remove-orphans
|
||||||
cd $DEPLOY_DIR
|
|
||||||
VERSION=$(git describe --tags --always)
|
|
||||||
COMMIT=$(git rev-parse --short HEAD)
|
|
||||||
VERSION=$VERSION COMMIT=$COMMIT docker compose up -d --build --remove-orphans
|
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -19,7 +19,6 @@
|
|||||||
|
|
||||||
!.env.example
|
!.env.example
|
||||||
!LICENSE
|
!LICENSE
|
||||||
!AGENTS.md
|
|
||||||
|
|
||||||
!assets/**/*
|
!assets/**/*
|
||||||
|
|
||||||
|
|||||||
253
AGENTS.md
253
AGENTS.md
@@ -1,253 +0,0 @@
|
|||||||
# 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.
|
|
||||||
10
Dockerfile
10
Dockerfile
@@ -1,9 +1,6 @@
|
|||||||
FROM docker.io/golang:1.25.4-alpine AS build
|
FROM docker.io/golang:1.25.4-alpine AS build
|
||||||
|
|
||||||
ARG VERSION=dev
|
RUN apk add --no-cache upx git
|
||||||
ARG COMMIT=unknown
|
|
||||||
|
|
||||||
RUN apk add --no-cache upx
|
|
||||||
|
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
@@ -13,8 +10,9 @@ COPY . .
|
|||||||
RUN go tool templ generate
|
RUN go tool templ generate
|
||||||
RUN go tool gotailwind -i assets/css/input.css -o assets/css/output.css --minify
|
RUN go tool gotailwind -i assets/css/input.css -o assets/css/output.css --minify
|
||||||
RUN --mount=type=cache,target=/root/.cache/go-build \
|
RUN --mount=type=cache,target=/root/.cache/go-build \
|
||||||
MODULE=$(head -1 go.mod | awk '{print $2}') && \
|
VERSION=$(git describe --tags --always) && \
|
||||||
CGO_ENABLED=0 go build -ldflags="-s -X $MODULE/version.Version=$VERSION -X $MODULE/version.Commit=$COMMIT" -o /bin/games .
|
COMMIT=$(git rev-parse --short HEAD) && \
|
||||||
|
CGO_ENABLED=0 go build -ldflags="-s -X github.com/ryanhamamura/games/version.Version=$VERSION -X github.com/ryanhamamura/games/version.Commit=$COMMIT" -o /bin/games .
|
||||||
RUN upx -9 -k /bin/games
|
RUN upx -9 -k /bin/games
|
||||||
|
|
||||||
FROM scratch
|
FROM scratch
|
||||||
|
|||||||
42
chat/chat.go
42
chat/chat.go
@@ -76,11 +76,12 @@ func (r *Room) Send(msg Message) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// receive processes an incoming NATS message, appending it to the buffer.
|
// Receive processes an incoming NATS message, appending it to the buffer.
|
||||||
func (r *Room) receive(data []byte) (Message, bool) {
|
// Returns the new message and a snapshot of all messages.
|
||||||
|
func (r *Room) Receive(data []byte) (Message, []Message) {
|
||||||
var msg Message
|
var msg Message
|
||||||
if err := json.Unmarshal(data, &msg); err != nil {
|
if err := json.Unmarshal(data, &msg); err != nil {
|
||||||
return msg, false
|
return msg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
r.mu.Lock()
|
r.mu.Lock()
|
||||||
@@ -88,9 +89,11 @@ func (r *Room) receive(data []byte) (Message, bool) {
|
|||||||
if len(r.messages) > maxMessages {
|
if len(r.messages) > maxMessages {
|
||||||
r.messages = r.messages[len(r.messages)-maxMessages:]
|
r.messages = r.messages[len(r.messages)-maxMessages:]
|
||||||
}
|
}
|
||||||
|
snapshot := make([]Message, len(r.messages))
|
||||||
|
copy(snapshot, r.messages)
|
||||||
r.mu.Unlock()
|
r.mu.Unlock()
|
||||||
|
|
||||||
return msg, true
|
return msg, snapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
// Messages returns a snapshot of the current message buffer.
|
// Messages returns a snapshot of the current message buffer.
|
||||||
@@ -102,32 +105,15 @@ func (r *Room) Messages() []Message {
|
|||||||
return snapshot
|
return snapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
// Subscribe returns a channel of parsed messages and a cleanup function.
|
// Subscribe creates a NATS channel subscription for the room's subject.
|
||||||
// The room handles NATS subscription internally and buffers messages.
|
// Caller is responsible for unsubscribing.
|
||||||
func (r *Room) Subscribe() (<-chan Message, func()) {
|
func (r *Room) Subscribe() (chan *nats.Msg, *nats.Subscription, error) {
|
||||||
natsCh := make(chan *nats.Msg, 64)
|
ch := make(chan *nats.Msg, 64)
|
||||||
msgCh := make(chan Message, 64)
|
sub, err := r.nc.ChanSubscribe(r.subject, ch)
|
||||||
|
|
||||||
sub, err := r.nc.ChanSubscribe(r.subject, natsCh)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
close(msgCh)
|
return nil, nil, err
|
||||||
return msgCh, func() {}
|
|
||||||
}
|
}
|
||||||
|
return ch, sub, nil
|
||||||
go func() {
|
|
||||||
for natsMsg := range natsCh {
|
|
||||||
if msg, ok := r.receive(natsMsg.Data); ok {
|
|
||||||
msgCh <- msg
|
|
||||||
}
|
|
||||||
}
|
|
||||||
close(msgCh)
|
|
||||||
}()
|
|
||||||
|
|
||||||
cleanup := func() {
|
|
||||||
_ = sub.Unsubscribe()
|
|
||||||
}
|
|
||||||
|
|
||||||
return msgCh, cleanup
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Room) saveMessage(msg Message) {
|
func (r *Room) saveMessage(msg Message) {
|
||||||
|
|||||||
@@ -23,8 +23,10 @@ type Config struct {
|
|||||||
StopKeyPropagation bool
|
StopKeyPropagation bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// ChatMessage renders a single chat message. Used for appending new messages via SSE.
|
templ Chat(messages []chat.Message, cfg Config) {
|
||||||
templ ChatMessage(m chat.Message, cfg Config) {
|
<div id={ cfg.CSSPrefix + "-chat" } class={ cfg.CSSPrefix + "-chat" }>
|
||||||
|
<div class={ cfg.CSSPrefix + "-chat-history" }>
|
||||||
|
for _, m := range messages {
|
||||||
<div class={ cfg.CSSPrefix + "-chat-msg" }>
|
<div class={ cfg.CSSPrefix + "-chat-msg" }>
|
||||||
<span style={ fmt.Sprintf("color:%s;font-weight:bold;", cfg.Color(m.Slot)) }>
|
<span style={ fmt.Sprintf("color:%s;font-weight:bold;", cfg.Color(m.Slot)) }>
|
||||||
{ m.Nickname + ": " }
|
{ m.Nickname + ": " }
|
||||||
@@ -32,13 +34,6 @@ templ ChatMessage(m chat.Message, cfg Config) {
|
|||||||
<span>{ m.Message }</span>
|
<span>{ m.Message }</span>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
templ Chat(messages []chat.Message, cfg Config) {
|
|
||||||
<div id={ cfg.CSSPrefix + "-chat" } class={ cfg.CSSPrefix + "-chat" }>
|
|
||||||
<div id={ cfg.CSSPrefix + "-chat-history" } class={ cfg.CSSPrefix + "-chat-history" }>
|
|
||||||
for _, m := range messages {
|
|
||||||
@ChatMessage(m, cfg)
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
<div class={ cfg.CSSPrefix + "-chat-input" } data-morph-ignore>
|
<div class={ cfg.CSSPrefix + "-chat-input" } data-morph-ignore>
|
||||||
if cfg.StopKeyPropagation {
|
if cfg.StopKeyPropagation {
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
services:
|
services:
|
||||||
games:
|
games:
|
||||||
build:
|
build: .
|
||||||
context: .
|
|
||||||
args:
|
|
||||||
VERSION: ${VERSION:-dev}
|
|
||||||
COMMIT: ${COMMIT:-unknown}
|
|
||||||
container_name: games
|
container_name: games
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import (
|
|||||||
"github.com/ryanhamamura/games/connect4"
|
"github.com/ryanhamamura/games/connect4"
|
||||||
"github.com/ryanhamamura/games/db/repository"
|
"github.com/ryanhamamura/games/db/repository"
|
||||||
"github.com/ryanhamamura/games/features/c4game/pages"
|
"github.com/ryanhamamura/games/features/c4game/pages"
|
||||||
sharedcomponents "github.com/ryanhamamura/games/features/common/components"
|
|
||||||
"github.com/ryanhamamura/games/sessions"
|
"github.com/ryanhamamura/games/sessions"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -119,21 +118,11 @@ func HandleGameEvents(store *connect4.Store, nc *nats.Conn, sm *scs.SessionManag
|
|||||||
return sse.PatchElementTempl(pages.GameContent(g, myColor, room.Messages(), chatCfg))
|
return sse.PatchElementTempl(pages.GameContent(g, myColor, room.Messages(), chatCfg))
|
||||||
}
|
}
|
||||||
|
|
||||||
sendPing := func() error {
|
// Send initial render
|
||||||
return sse.PatchElementTempl(sharedcomponents.ConnectionIndicator(time.Now().UnixMilli()))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send initial render and ping
|
|
||||||
if err := sendPing(); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := patchAll(); err != nil {
|
if err := patchAll(); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
heartbeat := time.NewTicker(15 * time.Second)
|
|
||||||
defer heartbeat.Stop()
|
|
||||||
|
|
||||||
// Subscribe to game state updates
|
// Subscribe to game state updates
|
||||||
gameCh := make(chan *nats.Msg, 64)
|
gameCh := make(chan *nats.Msg, 64)
|
||||||
gameSub, err := nc.ChanSubscribe(connect4.GameSubject(gameID), gameCh)
|
gameSub, err := nc.ChanSubscribe(connect4.GameSubject(gameID), gameCh)
|
||||||
@@ -143,29 +132,24 @@ func HandleGameEvents(store *connect4.Store, nc *nats.Conn, sm *scs.SessionManag
|
|||||||
defer gameSub.Unsubscribe() //nolint:errcheck
|
defer gameSub.Unsubscribe() //nolint:errcheck
|
||||||
|
|
||||||
// Subscribe to chat messages
|
// Subscribe to chat messages
|
||||||
chatCh, cleanupChat := room.Subscribe()
|
chatCh, chatSub, err := room.Subscribe()
|
||||||
defer cleanupChat()
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer chatSub.Unsubscribe() //nolint:errcheck
|
||||||
|
|
||||||
ctx := r.Context()
|
ctx := r.Context()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return
|
return
|
||||||
case <-heartbeat.C:
|
|
||||||
if err := sendPing(); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
case <-gameCh:
|
case <-gameCh:
|
||||||
if err := patchAll(); err != nil {
|
if err := patchAll(); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
case chatMsg := <-chatCh:
|
case msg := <-chatCh:
|
||||||
err := sse.PatchElementTempl(
|
room.Receive(msg.Data)
|
||||||
chatcomponents.ChatMessage(chatMsg, chatCfg),
|
if err := patchAll(); err != nil {
|
||||||
datastar.WithSelectorID("c4-chat-history"),
|
|
||||||
datastar.WithModeAppend(),
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ templ GamePage(g *connect4.Game, myColor int, messages []chat.Message, chatCfg c
|
|||||||
data-signals="{chatMsg: ''}"
|
data-signals="{chatMsg: ''}"
|
||||||
data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) }
|
data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) }
|
||||||
>
|
>
|
||||||
@sharedcomponents.ConnectionIndicator(0)
|
|
||||||
@GameContent(g, myColor, messages, chatCfg)
|
@GameContent(g, myColor, messages, chatCfg)
|
||||||
</main>
|
</main>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
package components
|
package components
|
||||||
|
|
||||||
import (
|
import "github.com/starfederation/datastar-go/datastar"
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/starfederation/datastar-go/datastar"
|
|
||||||
)
|
|
||||||
|
|
||||||
templ BackToLobby() {
|
templ BackToLobby() {
|
||||||
<a class="link text-sm opacity-70" href="/">← Back</a>
|
<a class="link text-sm opacity-70" href="/">← Back</a>
|
||||||
@@ -48,62 +44,6 @@ templ NicknamePrompt(returnPath string) {
|
|||||||
</main>
|
</main>
|
||||||
}
|
}
|
||||||
|
|
||||||
func isStale(lastPing int64) bool {
|
|
||||||
return lastPing == 0
|
|
||||||
}
|
|
||||||
|
|
||||||
var connectionWatcherHandle = templ.NewOnceHandle()
|
|
||||||
|
|
||||||
// ConnectionIndicator shows a small dot indicating SSE connection status.
|
|
||||||
// Server patches this with a timestamp; client JS detects staleness.
|
|
||||||
templ ConnectionIndicator(lastPing int64) {
|
|
||||||
<div
|
|
||||||
id="connection-indicator"
|
|
||||||
class="fixed top-2 right-2"
|
|
||||||
data-last-ping={ fmt.Sprintf("%d", lastPing) }
|
|
||||||
>
|
|
||||||
<div class="inline-grid *:[grid-area:1/1]">
|
|
||||||
<div
|
|
||||||
id="connection-ping"
|
|
||||||
class={
|
|
||||||
"status status-sm",
|
|
||||||
templ.KV("status-success animate-ping", !isStale(lastPing)),
|
|
||||||
templ.KV("status-error", isStale(lastPing)),
|
|
||||||
}
|
|
||||||
></div>
|
|
||||||
<div
|
|
||||||
id="connection-dot"
|
|
||||||
class={
|
|
||||||
"status status-sm",
|
|
||||||
templ.KV("status-success", !isStale(lastPing)),
|
|
||||||
templ.KV("status-error", isStale(lastPing)),
|
|
||||||
}
|
|
||||||
></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
@connectionWatcherHandle.Once() {
|
|
||||||
@connectionWatcher()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
script connectionWatcher() {
|
|
||||||
setInterval(function() {
|
|
||||||
var el = document.getElementById('connection-indicator');
|
|
||||||
var dot = document.getElementById('connection-dot');
|
|
||||||
var ping = document.getElementById('connection-ping');
|
|
||||||
if (!el || !dot || !ping) return;
|
|
||||||
|
|
||||||
var lastPing = parseInt(el.dataset.lastPing, 10) || 0;
|
|
||||||
var stale = Date.now() - lastPing > 20000;
|
|
||||||
|
|
||||||
dot.classList.toggle('status-success', !stale);
|
|
||||||
dot.classList.toggle('status-error', stale);
|
|
||||||
ping.classList.toggle('status-success', !stale);
|
|
||||||
ping.classList.toggle('status-error', stale);
|
|
||||||
ping.classList.toggle('animate-ping', !stale);
|
|
||||||
}, 1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
templ GameJoinPrompt(loginURL string, registerURL string, gamePath string) {
|
templ GameJoinPrompt(loginURL string, registerURL string, gamePath string) {
|
||||||
<main class="max-w-sm mx-auto mt-8 text-center">
|
<main class="max-w-sm mx-auto mt-8 text-center">
|
||||||
<h1 class="text-3xl font-bold">Join Game</h1>
|
<h1 class="text-3xl font-bold">Join Game</h1>
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/alexedwards/scs/v2"
|
"github.com/alexedwards/scs/v2"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
@@ -13,7 +12,6 @@ import (
|
|||||||
|
|
||||||
"github.com/ryanhamamura/games/chat"
|
"github.com/ryanhamamura/games/chat"
|
||||||
chatcomponents "github.com/ryanhamamura/games/chat/components"
|
chatcomponents "github.com/ryanhamamura/games/chat/components"
|
||||||
sharedcomponents "github.com/ryanhamamura/games/features/common/components"
|
|
||||||
"github.com/ryanhamamura/games/features/snakegame/pages"
|
"github.com/ryanhamamura/games/features/snakegame/pages"
|
||||||
"github.com/ryanhamamura/games/sessions"
|
"github.com/ryanhamamura/games/sessions"
|
||||||
"github.com/ryanhamamura/games/snake"
|
"github.com/ryanhamamura/games/snake"
|
||||||
@@ -125,21 +123,11 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
|
|||||||
return sse.PatchElementTempl(pages.GameContent(sg, mySlot, chatMessages(), chatCfg, gameID))
|
return sse.PatchElementTempl(pages.GameContent(sg, mySlot, chatMessages(), chatCfg, gameID))
|
||||||
}
|
}
|
||||||
|
|
||||||
sendPing := func() error {
|
// Send initial render
|
||||||
return sse.PatchElementTempl(sharedcomponents.ConnectionIndicator(time.Now().UnixMilli()))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send initial render and ping
|
|
||||||
if err := sendPing(); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := patchAll(); err != nil {
|
if err := patchAll(); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
heartbeat := time.NewTicker(15 * time.Second)
|
|
||||||
defer heartbeat.Stop()
|
|
||||||
|
|
||||||
// Subscribe to game updates via NATS
|
// Subscribe to game updates via NATS
|
||||||
gameCh := make(chan *nats.Msg, 64)
|
gameCh := make(chan *nats.Msg, 64)
|
||||||
gameSub, err := nc.ChanSubscribe(snake.GameSubject(gameID), gameCh)
|
gameSub, err := nc.ChanSubscribe(snake.GameSubject(gameID), gameCh)
|
||||||
@@ -149,12 +137,15 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
|
|||||||
defer gameSub.Unsubscribe() //nolint:errcheck
|
defer gameSub.Unsubscribe() //nolint:errcheck
|
||||||
|
|
||||||
// Chat subscription (multiplayer only)
|
// Chat subscription (multiplayer only)
|
||||||
var chatCh <-chan chat.Message
|
var chatCh chan *nats.Msg
|
||||||
var cleanupChat func()
|
var chatSub *nats.Subscription
|
||||||
|
|
||||||
if room != nil {
|
if room != nil {
|
||||||
chatCh, cleanupChat = room.Subscribe()
|
chatCh, chatSub, err = room.Subscribe()
|
||||||
defer cleanupChat()
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer chatSub.Unsubscribe() //nolint:errcheck
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx := r.Context()
|
ctx := r.Context()
|
||||||
@@ -163,11 +154,6 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
|
|||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return
|
return
|
||||||
|
|
||||||
case <-heartbeat.C:
|
|
||||||
if err := sendPing(); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
case <-gameCh:
|
case <-gameCh:
|
||||||
// Drain backed-up game updates
|
// Drain backed-up game updates
|
||||||
for {
|
for {
|
||||||
@@ -182,16 +168,12 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
case chatMsg, ok := <-chatCh:
|
case msg := <-chatCh:
|
||||||
if !ok {
|
if msg == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
err := sse.PatchElementTempl(
|
room.Receive(msg.Data)
|
||||||
chatcomponents.ChatMessage(chatMsg, chatCfg),
|
if err := patchAll(); err != nil {
|
||||||
datastar.WithSelectorID("snake-chat-history"),
|
|
||||||
datastar.WithModeAppend(),
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,7 +37,6 @@ templ GamePage(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg
|
|||||||
data-on:keydown__throttle.100ms={ keydownScript(gameID) }
|
data-on:keydown__throttle.100ms={ keydownScript(gameID) }
|
||||||
tabindex="0"
|
tabindex="0"
|
||||||
>
|
>
|
||||||
@components.ConnectionIndicator(0)
|
|
||||||
@GameContent(sg, mySlot, messages, chatCfg, gameID)
|
@GameContent(sg, mySlot, messages, chatCfg, gameID)
|
||||||
</main>
|
</main>
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user