14 KiB
Ruby Sea Battle
Introduction
"Ruby Sea Battle" is a battleship-like multiplayer browser game with a simple React front-end and a back-end composed of two servers:
- the main server for handling users (sign-up/sign-in, profile customization, etc.), direct user-to-user interactions, match-making and player rating.
- the game server for managing matches, with real-time client-server communication and score calculation. The players are invited to join the game on the game server by the main server, and once the game finishes the game server reports back the results.
Tech stack
- Ruby on Rails is used as a basis for the main server, implementing only an HTTP API without hosting the front-end.
- The game server is written in Go with no framework, implementing a WebSockets server
Directory structure
The repository's directory structure is simple: there are 3 directories for each part of the project: frontend, game-server and main-server. The documentation for main-server currently resides fully in main-server/API.md, but more files can be added in main-server/docs, if needed. game-server also has its own README.md, where all relevant information is contained at the moment. The docs for main-server and game-server are in Russian.
Project roadmap
- Basic sign-up/sign-in function
- Matchmaking with delegation to the game server (using a shared JWT secret)
- Actual game logic & game UI
- Ship placement UI and logic
- Battle UI and logic
- End of battle UI
- Saving results on the main server, match history, rating calculation
- Additional in-game features: chat, reactions, live connection status
- Profile customization
Testing
Every part of the project is tested differently. There is a single entry point for all of it — scripts/test.sh — and the same script is what .github/workflows/ci.yml runs, so local and CI results cannot drift apart.
| Part | Suite | Single part | Script (from the repo root) | External requirements |
|---|---|---|---|---|
main-server |
RSpec (17 spec files) + audits | cd main-server && bundle exec rspec |
scripts/test.sh main |
Redis on localhost:6379 |
game-server |
Go testing + httptest |
cd game-server && go test -race ./... |
scripts/test.sh game |
none |
frontend |
no automated tests | cd frontend && npm run build |
scripts/test.sh frontend |
none |
Quick run of everything (all is the default):
scripts/test.sh # all three parts
scripts/test.sh main # only one part
scripts/test.sh frontend --install # force `npm ci` first
scripts/test.sh --help
The script fails fast (set -euo pipefail), checks Redis before touching main-server, and prints one ==> line per step. CI (.github/workflows/ci.yml) runs it in three parallel jobs: scripts/test.sh main (with a Redis service installed by the job), scripts/test.sh game, and scripts/test.sh frontend --install. The workflow is written for Gitea Actions as well as GitHub Actions; Gitea picks it up from .github/workflows and needs an act_runner built for node24 actions (>= v2.327.1), because actions/checkout@v5 and actions/setup-node@v5 require it.
If
.gitea/workflowsis ever created, Gitea ignores.github/workflowscompletely — keep one copy, not two.
main-server (Ruby on Rails / RSpec)
Setup (idempotent):
cd main-server
bundle install
bin/rails db:prepare # creates/updates storage/development.sqlite3 and storage/test.sqlite3
Run:
bundle exec rspec # full suite
bundle exec rspec spec/models # a directory
bundle exec rspec spec/models/match_spec.rb:12 # a single example
COVERAGE=true bundle exec rspec # SimpleCov report -> main-server/coverage/index.html (git-ignored)
Notes:
- Redis is mandatory for the suite:
MatchmakingService, the channel and the sweep job specs talk to a real Redis.config/initializers/redis.rbforcesRails.env.test?onto logical database 15 and the specs runFLUSHDBthere, so never pointREDIS_URLin tests at a DB that holds data you care about. A localredis-server(ordocker run -d -p 6379:6379 redis) is enough. - The test database is SQLite (
storage/test.sqlite3) plus a separate Solid Queue DB; both are recreated fromdb/schema.rbbymaintain_test_schema!. Pending migrations abort the suite with an explicit message. - Coverage by area:
spec/models,spec/services(JwtService,MatchmakingService,InternalSignatureService),spec/controllers,spec/requests(includingapi/internal/match_results_spec.rb),spec/channels,spec/jobs.
Static checks / audits (all run from main-server, and all are steps of scripts/test.sh main):
bundle exec rubocop # style (rubocop-rails-omakase)
bundle exec bundler-audit check --update # known CVEs in gems
bundle exec brakeman --quiet --no-pager --exit-on-warn --exit-on-error --ensure-ignore-notes
Use the bundle exec forms: the bare bin/rubocop, bin/brakeman and bin/bundler-audit wrappers put the active Ruby's gem path ahead of Bundler's (bundle exec ruby -e 'puts Gem.path' fails on a multi-Ruby-machine), so the wrappers can fail with Bundler::GemNotFound even when bundle exec works.
Baseline (verified 2026-11-29): 155 examples green, rubocop clean, bundler-audit clean, brakeman clean. The single security finding — Ruby2Shell (CVE-2026-132825) on Ruby 4.0.0 — is recorded with an explanation in main-server/config/brakeman.ignore (brakeman auto-loads it); Ruby 4.0.10 fixes it but is not installable on this machine yet (no ruby-build definition, and the Docker tag ruby:4.0.10-slim exists but the pin in Dockerfile must be bumped together with .ruby-version). When you bump Ruby, delete that ignore entry — --ensure-ignore-notes will keep you honest about it.
Do not use bin/ci: it requires config/ci.rb, which does not exist in this repo (only the Rails template for it is generated). scripts/test.sh main is the replacement.
game-server (Go)
The Go suite is self-contained: the websocket integration tests use httptest and sign their own tokens, and the match-result reporter is tested against an in-process HTTP server, so no Redis, main-server or network access is needed.
cd game-server
go test ./... # all packages
go test -race ./... # recommended; the CI-equivalent command
go test ./internal/game -run TestFireWinCondition -count=1
go test ./internal/ws -count=1 # end-to-end websocket scenarios (real sockets, ~2s)
gofmt -l . # must print nothing (checked by scripts/test.sh)
go vet ./... # static check (also in scripts/test.sh)
go build -o /tmp/game-server ./cmd/server # compile check (cmd/server has no tests)
The gofmt check is part of scripts/test.sh game (and therefore of CI), so format before pushing. Note that parts of the tree were not gofmt-clean when this check was introduced; they have been reformatted once and the check keeps them that way.
Covered: JWT claims validation (internal/auth), message encoding/parsing incl. ship placement (internal/protocol), match manager scenarios (join/timeout/reconnect/ACK/placement/fire/win/reporting — internal/game), HMAC signing and the HTTP reporter with retries (internal/mainserver), and full end-to-end games over a real websocket (internal/ws).
frontend (React + Vite)
There is no test runner installed (no vitest/jest/playwright/testing-library in package.json or node_modules), and no lint/format config. shipLogic.js exposes pure helpers (canPlaceShip, randomFleet, …) which are the natural candidates if a suite is ever added; until then verification is a build plus the manual end-to-end scenario below.
cd frontend
npm ci # deterministic install from package-lock.json
npm run dev # Vite dev server on http://localhost:5173
npm run build # build check -> dist/ (git-ignored)
npm run preview # serve the built bundle
scripts/test.sh frontend runs npm ci (only when node_modules is missing or --install is passed) and then npm run build. It also runs npm test if a test script exists in package.json — the hook is already in place for when a runner is added.
The API base URL defaults to http://localhost:3000 and can be overridden with VITE_API_URL (see src/api.js); Action Cable and the game server URLs are derived from it / from the matched payload. http://localhost:5173/uikit.html renders the UI-kit reference page (a second Vite entry point).
Shared cross-part contract
contracts/test_signature_vectors.json is the single source of truth for the HMAC wire format of the internal game-server -> main-server report. Both suites read it — main-server/spec/services/internal_signature_service_spec.rb and game-server/internal/mainserver/reporter_test.go (which also reuses its secret for JWT signing in internal/ws/handler_game_test.go). If the signature formula changes, update the implementation on both sides and regenerate the vectors; never edit a vector just to make a test pass (the other part will then fail).
End-to-end manual test (all three parts together)
The three processes must agree on two values, otherwise matchmaking succeeds but the game never starts:
main-serverSECRET_KEY_BASE=game-serverJWT_SECRET(JWT signing and report HMAC share one secret);main-serverGAME_SERVER_URL=game-serverPUBLIC_ADDR, compared byte-for-byte (defaultws://localhost:8081/ws).
- Start Redis:
redis-server(ordocker run -d -p 6379:6379 redis). - Start the main server:
cd main-server && bin/rails server(Puma on:3000); checkcurl localhost:3000/up. - Start the game server:
(
cd game-server go build -o /tmp/game-server ./cmd/server LISTEN_ADDR=:8081 PUBLIC_ADDR=ws://localhost:8081/ws JWT_SECRET=4 \ MAIN_SERVER_URL=http://localhost:3000 /tmp/game-servergame-server/.envalready carriesPUBLIC_ADDR/JWT_SECRET=4and is auto-loaded bygodotenv/autoload;main-server/.envsetsSECRET_KEY_BASE=4andGAME_SERVER_URL. Checkcurl localhost:8081/healthz.) - Start the frontend:
cd frontend && npm run dev, openhttp://localhost:5173. - Register two players (two browsers or a normal + private window), then either press "random battle" in both windows, or use the invite flow:
create_invite→ the code comes back asinvite_created→ the second player enters it and getsmatched. - Play through the whole loop: ship placement → turns (
STATE4/5,FIRE_RESULT1–4) →END(code 1 victory / 2 defeat / -1 join timeout). NoteMATCHMAKING_TOKEN_TTLis 120 s, so a match must be joined soon aftermatched. - Verify the result travelled back:
GET http://localhost:3000/api/matches/:uuid(bearer token of a participant) should show the finished status,finished_atandduration_seconds. This is the same data the game server posts to the internal endpoint, which can also be exercised directly from the shell:(idempotent for an already finished match; aUUID=<match uuid>; BODY='{"status":"player1_won","duration_seconds":125}'; TS=$(date +%s) SIG=$(printf '%s.%s.%s' "$TS" "/api/internal/matches/$UUID/result" "$BODY" \ | openssl dgst -sha256 -hmac "$SECRET_KEY_BASE" -hex | sed 's/^.* //') curl -X POST "http://localhost:3000/api/internal/matches/$UUID/result" \ -H 'Content-Type: application/json' \ -H "X-Request-Timestamp: $TS" -H "X-Request-Signature: sha256=$SIG" -d "$BODY"409means it was closed with a different outcome).
Match history is visible in the UI (GET /api/matches) once the report has been processed; rating_change values stay zero until rating recalculation is implemented on main-server.
Quick protocol poke without the UI (the game server speaks raw JSON opcode arrays from game-server/README.md): take the game_token from the matched message and connect with websocat/"wscat", send [1, "<game_token>", "<user_token>"], ACK each seq with [4, <seq>], then [5, ...30 ship args] and [6, x, y]. Without websocat installed, go test -race ./internal/ws covers exactly these flows.
Guidelines
- The mentioned documentation files should be kept up-to-date and updated in the same language. The formatting can be changed, though, if it could improve readability.
- Whenever you change business logic, update (and run) the corresponding suites listed in Testing — RSpec for
main-server,go test -race ./...forgame-server, and keepcontracts/test_signature_vectors.jsonin sync if the HMAC format is touched. - Before pushing, run
scripts/test.sh(or at least the parts you touched). It is the same script CI runs, so a green local run means a green pipeline; do not rely on the barebin/*wrappers ofmain-server, which break on a machine with several Ruby installs. - When adding a check to CI, add the corresponding step to
scripts/test.shinstead of inlining it in the workflow, otherwise local and CI runs drift apart. - The Ruby backend should be written with Rails principles in mind. The tasks performed by this backend are going to be relatively simple (especially at earlier stages of this project), so the focus should be on clean code and best practices, not unnecessary complexity.
- The methods in the Ruby backend comprising the business-logic should be covered with unit-tests after being implemented.