Stage 1: backend foundation (Postgres, sessions, accounts, OTel)
Tests · Go / test (push) Successful in 11s
Tests · Integration / integration (push) Successful in 8s

- internal/postgres: pgx-over-database/sql pool (otelsql), embedded goose
  migrations into schema 'backend', committed go-jet code + cmd/jetgen tool.
- internal/account: durable accounts + unified telegram/email identities
  (UUIDv7 keys), find-or-create provisioning with unique-conflict handling.
- internal/session: opaque 256-bit tokens stored as a SHA-256 hash, revoke-only
  (no TTL); write-through cache gating /readyz; store + service.
- internal/telemetry: OTel tracer/meter providers (none/stdout) + request-timing
  middleware; internal/config gains Postgres + OTel env loading.
- internal/server: /api/v1 {public,user,internal,admin} skeleton + X-User-ID
  middleware; /readyz checks DB ping + cache; main wires
  telemetry -> db+migrate -> warm cache -> server.
- Tests: unit + integration (build tag 'integration', testcontainers
  postgres:17) for migrations, accounts, sessions, readyz; new integration.yaml.
- Docs: ARCHITECTURE, TESTING, PLAN refinements, root + backend READMEs.

Session/account REST handlers deferred to Stage 6 (gateway); OTLP + dashboards
to Stage 11.
This commit is contained in:
Ilia Denisov
2026-06-02 13:52:26 +02:00
parent da079b2bc6
commit eeaad62b10
45 changed files with 3461 additions and 92 deletions
+91
View File
@@ -0,0 +1,91 @@
//go:build integration
package inttest
import (
"context"
"errors"
"testing"
"github.com/google/uuid"
"scrabble/backend/internal/account"
)
// TestAccountProvisionByIdentity covers find-or-create semantics, distinct
// accounts per identity, GetByID, and the identity confirmed flag per kind.
func TestAccountProvisionByIdentity(t *testing.T) {
ctx := context.Background()
store := account.NewStore(testDB)
tgExternal := "tg-" + uuid.NewString()
first, err := store.ProvisionByIdentity(ctx, account.KindTelegram, tgExternal)
if err != nil {
t.Fatalf("provision telegram: %v", err)
}
if first.ID == uuid.Nil {
t.Fatal("expected a non-nil account id")
}
if first.PreferredLanguage != "en" {
t.Errorf("PreferredLanguage = %q, want default en", first.PreferredLanguage)
}
if first.TimeZone != "UTC" {
t.Errorf("TimeZone = %q, want default UTC", first.TimeZone)
}
// Re-provisioning the same identity returns the same account.
again, err := store.ProvisionByIdentity(ctx, account.KindTelegram, tgExternal)
if err != nil {
t.Fatalf("re-provision telegram: %v", err)
}
if again.ID != first.ID {
t.Errorf("re-provision id = %s, want %s", again.ID, first.ID)
}
// A different identity yields a different account.
other, err := store.ProvisionByIdentity(ctx, account.KindTelegram, "tg-"+uuid.NewString())
if err != nil {
t.Fatalf("provision other telegram: %v", err)
}
if other.ID == first.ID {
t.Error("distinct identity must map to a distinct account")
}
// GetByID round-trips, and a random id reports ErrNotFound.
got, err := store.GetByID(ctx, first.ID)
if err != nil {
t.Fatalf("get by id: %v", err)
}
if got.ID != first.ID {
t.Errorf("get id = %s, want %s", got.ID, first.ID)
}
if _, err := store.GetByID(ctx, uuid.New()); !errors.Is(err, account.ErrNotFound) {
t.Errorf("get missing = %v, want ErrNotFound", err)
}
// A platform identity is confirmed; an email identity starts unconfirmed.
if c := identityConfirmed(t, account.KindTelegram, tgExternal); !c {
t.Error("telegram identity must be confirmed")
}
emailExternal := "e-" + uuid.NewString() + "@example.com"
if _, err := store.ProvisionByIdentity(ctx, account.KindEmail, emailExternal); err != nil {
t.Fatalf("provision email: %v", err)
}
if c := identityConfirmed(t, account.KindEmail, emailExternal); c {
t.Error("email identity must start unconfirmed")
}
}
// identityConfirmed reads the confirmed flag for one identity directly.
func identityConfirmed(t *testing.T, kind, externalID string) bool {
t.Helper()
var confirmed bool
err := testDB.QueryRowContext(context.Background(),
"SELECT confirmed FROM identities WHERE kind = $1 AND external_id = $2",
kind, externalID,
).Scan(&confirmed)
if err != nil {
t.Fatalf("read confirmed for (%s, %s): %v", kind, externalID, err)
}
return confirmed
}
+12
View File
@@ -0,0 +1,12 @@
// Package inttest holds the Postgres-backed integration tests for the backend.
//
// The tests are guarded by the `integration` build tag and run against a
// throwaway postgres:17-alpine container started with testcontainers-go, so a
// reachable Docker daemon is required. Run them with:
//
// go test -tags=integration ./backend/...
//
// They fail loudly when Docker is unavailable rather than skipping, per
// docs/TESTING.md. This file carries no build tag so the package is non-empty
// in the default (no-tag) build.
package inttest
+109
View File
@@ -0,0 +1,109 @@
//go:build integration
package inttest
import (
"context"
"database/sql"
"fmt"
"net/url"
"os"
"testing"
"time"
testcontainers "github.com/testcontainers/testcontainers-go"
tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/testcontainers/testcontainers-go/wait"
"scrabble/backend/internal/postgres"
)
// testDB is the shared, migrated pool every integration test runs against. It is
// hydrated once by TestMain.
var testDB *sql.DB
const (
pgImage = "postgres:17-alpine"
pgDatabase = "scrabble_backend"
pgUser = "scrabble"
pgPassword = "scrabble"
pgSchema = "backend"
containerStartup = 90 * time.Second
containerShutdown = 30 * time.Second
)
// TestMain starts one Postgres container, applies the migrations, and shares the
// resulting pool with every test. Any setup failure aborts the suite loudly
// (exit 1) rather than skipping coverage.
func TestMain(m *testing.M) {
code, err := runSuite(m)
if err != nil {
fmt.Fprintln(os.Stderr, "inttest:", err)
os.Exit(1)
}
os.Exit(code)
}
func runSuite(m *testing.M) (int, error) {
ctx := context.Background()
container, err := tcpostgres.Run(ctx, pgImage,
tcpostgres.WithDatabase(pgDatabase),
tcpostgres.WithUsername(pgUser),
tcpostgres.WithPassword(pgPassword),
testcontainers.WithWaitStrategy(
wait.ForLog("database system is ready to accept connections").
WithOccurrence(2).
WithStartupTimeout(containerStartup),
),
)
if err != nil {
return 0, fmt.Errorf("start postgres container: %w", err)
}
defer func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), containerShutdown)
defer cancel()
if termErr := container.Terminate(shutdownCtx); termErr != nil {
fmt.Fprintln(os.Stderr, "inttest: terminate container:", termErr)
}
}()
baseDSN, err := container.ConnectionString(ctx, "sslmode=disable")
if err != nil {
return 0, fmt.Errorf("resolve container dsn: %w", err)
}
dsn, err := withSearchPath(baseDSN, pgSchema)
if err != nil {
return 0, err
}
cfg := postgres.DefaultConfig()
cfg.DSN = dsn
db, err := postgres.Open(ctx, cfg)
if err != nil {
return 0, fmt.Errorf("open pool: %w", err)
}
defer func() { _ = db.Close() }()
if err := postgres.ApplyMigrations(ctx, db); err != nil {
return 0, fmt.Errorf("apply migrations: %w", err)
}
testDB = db
return m.Run(), nil
}
// withSearchPath rewrites dsn so every connection pins search_path to schema.
func withSearchPath(dsn, schema string) (string, error) {
u, err := url.Parse(dsn)
if err != nil {
return "", fmt.Errorf("parse dsn: %w", err)
}
q := u.Query()
q.Set("search_path", schema)
if q.Get("sslmode") == "" {
q.Set("sslmode", "disable")
}
u.RawQuery = q.Encode()
return u.String(), nil
}
+25
View File
@@ -0,0 +1,25 @@
//go:build integration
package inttest
import (
"context"
"testing"
"scrabble/backend/internal/postgres"
)
// TestApplyMigrationsIdempotent re-applies the migrations against the already
// migrated database and confirms the expected tables are queryable.
func TestApplyMigrationsIdempotent(t *testing.T) {
ctx := context.Background()
if err := postgres.ApplyMigrations(ctx, testDB); err != nil {
t.Fatalf("re-apply migrations: %v", err)
}
for _, table := range []string{"accounts", "identities", "sessions"} {
var n int
if err := testDB.QueryRowContext(ctx, "SELECT count(*) FROM "+table).Scan(&n); err != nil {
t.Errorf("count %s: %v", table, err)
}
}
}
+41
View File
@@ -0,0 +1,41 @@
//go:build integration
package inttest
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"go.uber.org/zap/zaptest"
"scrabble/backend/internal/server"
"scrabble/backend/internal/session"
)
// TestReadyzWithRealDatabase exercises the assembled server against the live
// container: /readyz answers 200 once the database pings and the session cache
// is warmed, closing the gap the unit test (nil database) cannot cover.
func TestReadyzWithRealDatabase(t *testing.T) {
svc := session.NewService(session.NewStore(testDB), session.NewCache())
if err := svc.Warm(context.Background()); err != nil {
t.Fatalf("warm session cache: %v", err)
}
srv := server.New(":0", server.Deps{
Logger: zaptest.NewLogger(t),
DB: testDB,
PingTimeout: 5 * time.Second,
SessionsReady: svc.Ready,
})
for _, path := range []string{"/healthz", "/readyz"} {
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
if rec.Code != http.StatusOK {
t.Errorf("%s status = %d, want 200", path, rec.Code)
}
}
}
+80
View File
@@ -0,0 +1,80 @@
//go:build integration
package inttest
import (
"context"
"errors"
"testing"
"github.com/google/uuid"
"scrabble/backend/internal/account"
"scrabble/backend/internal/session"
)
// TestSessionLifecycle covers create, cache-hit resolve, DB-fallback resolve
// after a cold cache warm, idempotent revoke, and post-revoke resolution.
func TestSessionLifecycle(t *testing.T) {
ctx := context.Background()
acc, err := account.NewStore(testDB).ProvisionByIdentity(ctx, account.KindTelegram, "tg-"+uuid.NewString())
if err != nil {
t.Fatalf("provision account: %v", err)
}
store := session.NewStore(testDB)
svc := session.NewService(store, session.NewCache())
token, sess, err := svc.Create(ctx, acc.ID)
if err != nil {
t.Fatalf("create session: %v", err)
}
if sess.AccountID != acc.ID {
t.Errorf("session account = %s, want %s", sess.AccountID, acc.ID)
}
if token == sess.TokenHash {
t.Error("plaintext token must not equal the stored hash")
}
// Resolve via the warm write-through cache.
got, err := svc.Resolve(ctx, token)
if err != nil {
t.Fatalf("resolve (cache): %v", err)
}
if got.ID != sess.ID {
t.Errorf("resolve id = %s, want %s", got.ID, sess.ID)
}
// An unknown token is not found.
if _, err := svc.Resolve(ctx, "not-a-real-token"); !errors.Is(err, session.ErrNotFound) {
t.Errorf("resolve unknown = %v, want ErrNotFound", err)
}
// A fresh service with a cold cache resolves through the DB after Warm.
cold := session.NewCache()
svc2 := session.NewService(store, cold)
if err := svc2.Warm(ctx); err != nil {
t.Fatalf("warm: %v", err)
}
if !cold.Ready() {
t.Error("cache must be ready after Warm")
}
if _, ok := cold.Get(session.HashToken(token)); !ok {
t.Error("Warm must load the active session into the cache")
}
if got2, err := svc2.Resolve(ctx, token); err != nil || got2.ID != sess.ID {
t.Errorf("resolve after warm = (%s, %v), want %s", got2.ID, err, sess.ID)
}
// Revoke, then the token no longer resolves; revoke again is a no-op.
if err := svc.Revoke(ctx, token); err != nil {
t.Fatalf("revoke: %v", err)
}
if _, err := svc.Resolve(ctx, token); !errors.Is(err, session.ErrNotFound) {
t.Errorf("resolve after revoke = %v, want ErrNotFound", err)
}
if err := svc.Revoke(ctx, token); err != nil {
t.Errorf("idempotent revoke: %v", err)
}
}