diff --git a/Server/architecture.md b/Server/architecture.md new file mode 100644 index 0000000..0809e5d --- /dev/null +++ b/Server/architecture.md @@ -0,0 +1,1533 @@ +# SOR Server — Programming Architecture + +This document defines the strict, repeatable architecture every service in the SOR backend follows. +It is the canonical source of truth for how code is organized, how services communicate, and how +patterns are applied consistently across the codebase. + +**Language**: C# 12 (.NET 8) +**Build system**: MSBuild via the .sln solution file +**Repo layout**: Monorepo — all services and shared code live in one repository + +--- + +## Table of Contents + +1. [Why C# / .NET 8](#1-why-c--net-8) +2. [Repository Structure](#2-repository-structure) +3. [Service Project Layout (3-Layer Pattern)](#3-service-project-layout) +4. [Shared Library — SOR.Shared](#4-shared-library--sorshared) +5. [Protobuf Contracts — SOR.Shared.Proto](#5-protobuf-contracts--sorsharedproto) +6. [Multi-Service Runner — SOR.Host](#6-multi-service-runner--sorhost) +7. [Dependency Injection](#7-dependency-injection) +8. [Configuration System](#8-configuration-system) +9. [gRPC Handlers](#9-grpc-handlers) +10. [NATS Integration](#10-nats-integration) +11. [Redis Integration](#11-redis-integration) +12. [Database — EF Core + PostgreSQL](#12-database--ef-core--postgresql) +13. [Logging — Serilog](#13-logging--serilog) +14. [Error Handling](#14-error-handling) +15. [Health Checks](#15-health-checks) +16. [Testing Patterns](#16-testing-patterns) +17. [Naming Conventions](#17-naming-conventions) +18. [Hard Rules](#18-hard-rules) + +--- + +## 1. Why C# / .NET 8 + +C# is a statically typed, compiled language in the same family as Java and Kotlin, but with +a cleaner modern syntax and exceptional first-class support for async/await, which is critical +for a server that handles thousands of concurrent connections. + +**.NET 8** is the current long-term support (LTS) release. It includes: +- Native AOT compilation (faster startup, smaller containers — optional, enabled per service) +- `System.Threading.Channels` — lock-free async queues (used in Gateway for message dispatch) +- Top-level programs — less boilerplate in `Program.cs` +- Source generators — compile-time code generation for Protobuf and serialization + +**ASP.NET Core** is the web framework built into .NET. It hosts HTTP endpoints, gRPC endpoints, +and WebSocket connections in the same process with a unified middleware pipeline. No external +web framework is needed. + +--- + +## 2. Repository Structure + +``` +SOR/ +└── Server/ + ├── SOR.sln # Visual Studio solution — lists all projects + ├── Directory.Build.props # MSBuild properties shared across ALL projects + ├── Directory.Packages.props # Central NuGet package version management + │ + ├── src/ + │ ├── SOR.Host/ # Multi-service runner (the deployable binary) + │ ├── SOR.Shared/ # Shared utilities, base classes, interfaces + │ ├── SOR.Shared.Proto/ # Protobuf .proto files + generated C# code + │ │ + │ ├── SOR.Gateway/ # Gateway service module + │ ├── SOR.Auth/ # Auth service module + │ ├── SOR.Game/ # Game service module + │ ├── SOR.Chat/ # Chat service module + │ ├── SOR.Collection/ # Collection service module + │ ├── SOR.Bazaar/ # Bazaar service module + │ ├── SOR.Admin/ # Admin service module + │ ├── SOR.Leaderboard/ # Leaderboard service module + │ └── SOR.Content/ # Content service module + │ + └── tests/ + ├── SOR.Auth.Tests/ + ├── SOR.Game.Tests/ + ├── SOR.Chat.Tests/ + ├── SOR.Collection.Tests/ + ├── SOR.Bazaar.Tests/ + ├── SOR.Leaderboard.Tests/ + └── SOR.Content.Tests/ +``` + +### Directory.Build.props + +This file applies MSBuild properties to every project without repeating them. It lives at the +`Server/` level and is automatically picked up by all `.csproj` files underneath it. + +```xml + + + + + net8.0 + + + enable + + + latest + + + true + + + enable + + +``` + +### Directory.Packages.props + +Central package version management. All NuGet package versions are declared here once. +Individual `.csproj` files reference package names without version numbers — they inherit +from here. This prevents version drift across projects. + +```xml + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +--- + +## 3. Service Project Layout + +Every service follows the identical three-layer structure. No exceptions. + +``` +src/SOR.Auth/ +├── SOR.Auth.csproj +├── ServiceRegistration.cs # The ONE public entry point for this module +│ +├── Handlers/ # Layer 1 — receives external calls (gRPC, NATS) +│ └── AuthGrpcHandler.cs # Implements the gRPC service contract +│ +├── Services/ # Layer 2 — all business logic lives here +│ ├── IAuthService.cs # Interface (used for testing / substitution) +│ └── AuthService.cs # Implementation +│ +├── Repositories/ # Layer 3 — all database access lives here +│ ├── IAuthRepository.cs # Interface +│ └── AuthRepository.cs # Implementation using EF Core +│ +├── Models/ # Domain objects used inside this service +│ ├── User.cs +│ └── SessionToken.cs +│ +└── Data/ # EF Core database context for this service + ├── AuthDbContext.cs + └── Migrations/ # Auto-generated by EF Core; tracks schema changes +``` + +### The Three Layers + +**Layer 1 — Handlers** receive the incoming request from outside. They are thin: +- Deserialize the incoming message +- Call the appropriate Service method +- Serialize and return the response +- No business logic here + +**Layer 2 — Services** contain all business logic: +- Validation +- Orchestrating calls to repositories and other services +- Applying rules +- Never talk directly to the database — always go through repositories + +**Layer 3 — Repositories** contain all database access: +- Query the database using EF Core +- Return domain model objects (not raw database rows) +- No business logic here + +### Why this separation matters + +Each layer can be tested independently. A service test mocks the repository so no database +is needed. A handler test mocks the service so no business logic runs. This makes tests fast, +reliable, and easy to write. + +### ServiceRegistration.cs — the module's public contract + +Every service module exposes exactly ONE public method: a static extension method called +`Add{ServiceName}Service`. This is how SOR.Host enables a service. Nothing else in the +module is public unless it must be. + +```csharp +// src/SOR.Auth/ServiceRegistration.cs + +// 'namespace' groups related code together and prevents naming collisions. +// Convention: namespace matches folder path from solution root. +namespace SOR.Auth; + +// 'static class' means this class can never be instantiated — it only holds +// static methods. Extension method containers are always static classes. +public static class ServiceRegistration +{ + // This is an extension method on IServiceCollection. The 'this' keyword + // on the first parameter is what makes it an extension method — it can + // be called as if it were a method on IServiceCollection itself: + // builder.Services.AddAuthService(builder.Configuration) + // + // IServiceCollection is the .NET dependency injection container that tracks + // everything the app needs. You register things into it during startup, and + // the framework injects them wherever they're needed at runtime. + public static IServiceCollection AddAuthService( + this IServiceCollection services, + IConfiguration configuration) + { + // Bind the "Auth" section of appsettings.json to a typed options class. + // IOptions can then be injected anywhere in this service. + services.Configure(configuration.GetSection("Auth")); + + // Register the database context scoped to each request. + // "Scoped" means one instance per request — all code within a single + // request shares the same DbContext instance. + services.AddDbContext(options => + options.UseNpgsql(configuration.GetConnectionString("Auth"))); + + // Register the repository and service. + // AddScoped: whenever something asks for + // IAuthRepository, the DI container creates an AuthRepository. + services.AddScoped(); + services.AddScoped(); + + // Register the gRPC handler. MapGrpcService (called later in Host) + // routes incoming gRPC calls to this handler class. + services.AddGrpc(); + + return services; + } +} +``` + +--- + +## 4. Shared Library — SOR.Shared + +`SOR.Shared` is the one library every other project references. It contains code that would +otherwise be duplicated across services. Strict rule: **add to SOR.Shared only when two or more +services need the same code**. Do not preemptively add things here. + +``` +src/SOR.Shared/ +├── SOR.Shared.csproj +│ +├── Interfaces/ +│ └── ISorService.cs # Marker interface every service implements +│ +├── Redis/ +│ ├── RedisConnectionFactory.cs # Builds and caches the Redis connection +│ └── RedisKeys.cs # All Redis key name constants in one place +│ +├── Nats/ +│ ├── NatsConnectionFactory.cs # Builds the NATS connection +│ └── NatsSubjects.cs # All NATS subject name constants in one place +│ +├── Models/ +│ └── ServiceResult.cs # Standardized operation result wrapper +│ +├── Exceptions/ +│ └── SorException.cs # Base exception with error codes +│ +└── Extensions/ + └── StringExtensions.cs # Utility methods on string, Guid, etc. +``` + +### ServiceResult — the standard return type + +Business logic methods return `ServiceResult` instead of throwing exceptions for +expected failures (user not found, invalid password, etc.). Exceptions are reserved for +truly unexpected failures (database down, out of memory). + +```csharp +// src/SOR.Shared/Models/ServiceResult.cs +namespace SOR.Shared.Models; + +// A 'record' is an immutable data structure in C#. It generates equality checks, +// ToString(), and other utilities automatically based on its properties. +// The makes it generic — T is replaced with the actual type at the call site, +// e.g., ServiceResult or ServiceResult. +public record ServiceResult +{ + // 'required' means this property must be set when constructing the record. + // The '?' after 'T' makes the type nullable — Value can be null. + public required bool Success { get; init; } + public T? Value { get; init; } + public string? ErrorCode { get; init; } + public string? ErrorMessage { get; init; } + + // Static factory methods — create results without calling 'new' directly. + // 'static' means these belong to the type, not an instance. + public static ServiceResult Ok(T value) => + new() { Success = true, Value = value }; + + public static ServiceResult Fail(string errorCode, string message) => + new() { Success = false, ErrorCode = errorCode, ErrorMessage = message }; +} +``` + +### RedisKeys — all key names in one place + +Every Redis key used across all services is defined as a constant here. This prevents +typos, name collisions between services, and makes key naming auditable at a glance. + +```csharp +// src/SOR.Shared/Redis/RedisKeys.cs +namespace SOR.Shared.Redis; + +public static class RedisKeys +{ + // String.Format-style method: call Session("abc123") → "session:abc123" + // The 'static' modifier means no instance is needed to call these. + public static string Session(string token) => $"session:{token}"; + public static string ActiveGame(string gameId) => $"game:active:{gameId}"; + public static string LeaderboardRanked() => "leaderboard:ranked"; + public static string FeatureFlag(string flag) => $"config:flag:{flag}"; + public static string ClientPushChannel(string userId) => $"push:{userId}"; +} +``` + +### NatsSubjects — all NATS subject names in one place + +Same principle as RedisKeys. Centralizing subject names means a rename touches one file. + +```csharp +// src/SOR.Shared/Nats/NatsSubjects.cs +namespace SOR.Shared.Nats; + +public static class NatsSubjects +{ + public const string GameEnded = "sor.game.ended"; + public const string PurchaseCompleted = "sor.bazaar.purchase.completed"; + public const string CardGranted = "sor.collection.card.granted"; + public const string MatchRated = "sor.game.match.rated"; + public const string PlayerBanned = "sor.admin.player.banned"; +} +``` + +--- + +## 5. Protobuf Contracts — SOR.Shared.Proto + +gRPC uses Protobuf (`.proto` files) as its interface definition language. The `.proto` files +define the message types and service methods. The `dotnet-grpc` tooling generates C# code +from them automatically on build — you never edit the generated files manually. + +``` +src/SOR.Shared.Proto/ +├── SOR.Shared.Proto.csproj +│ +└── Protos/ + ├── auth.proto # Auth service contract + ├── game.proto # Game service contract + ├── chat.proto # Chat service contract + ├── collection.proto # Collection service contract + ├── bazaar.proto # Bazaar service contract + ├── leaderboard.proto # Leaderboard service contract + └── content.proto # Content service contract +``` + +### Example: auth.proto + +```protobuf +// src/SOR.Shared.Proto/Protos/auth.proto + +// proto3 is the current version of the Protobuf language. +syntax = "proto3"; + +// The C# namespace the generated code will live in. +option csharp_namespace = "SOR.Shared.Proto"; + +// The package prevents naming collisions with other .proto files. +package sor.auth; + +// A 'message' is a structured data type — equivalent to a C# class with properties. +// Each field has a type, a name, and a field number (used in binary encoding — never change these). +message LoginRequest { + string email = 1; + string password = 2; +} + +message LoginResponse { + bool success = 1; + string session_token = 2; // Only set on success + string error_code = 3; // Only set on failure +} + +message ValidateTokenRequest { + string session_token = 1; +} + +message ValidateTokenResponse { + bool valid = 1; + string user_id = 2; + string display_name = 3; +} + +// A 'service' defines the RPC methods. The generated C# code creates a +// base class (AuthService.AuthServiceBase) that the handler inherits from. +service AuthService { + rpc Login(LoginRequest) returns (LoginResponse); + rpc ValidateToken(ValidateTokenRequest) returns (ValidateTokenResponse); +} +``` + +### SOR.Shared.Proto.csproj + +```xml + + + SOR.Shared.Proto + + + + + + + + + + + +``` + +--- + +## 6. Multi-Service Runner — SOR.Host + +`SOR.Host` is the deployable binary. It is the only executable project in the solution. +It reads the `ENABLED_SERVICES` environment variable and starts only the listed services. + +This is how we run N services per box: set `ENABLED_SERVICES=auth,chat,collection` on a +VM and that VM runs exactly those three services in a single .NET process. + +**Why a single process?** Within one process, services share memory for config, the DI +container, and connection pools. There is zero network overhead between co-located services +since gRPC calls between them go through localhost. Deploying fewer processes also means +fewer Kubernetes pods to manage on smaller infrastructure. + +```csharp +// src/SOR.Host/Program.cs + +// 'using' imports a namespace so its types can be used without the full namespace prefix. +// Normally you'd need to write 'SOR.Auth.ServiceRegistration.AddAuthService(...)' — +// the using directive means you can just call 'AddAuthService(...)'. +using SOR.Auth; +using SOR.Chat; +using SOR.Collection; +using SOR.Bazaar; +using SOR.Admin; +using SOR.Leaderboard; +using SOR.Content; +using SOR.Gateway; +using Serilog; + +// Read which services this instance should run. +// Environment.GetEnvironmentVariable returns null if the variable isn't set, +// so ?? "all" is a fallback: if unset, run everything (useful for development). +var rawServices = Environment.GetEnvironmentVariable("ENABLED_SERVICES") ?? "all"; + +// Split "auth,chat,collection" into ["auth", "chat", "collection"]. +// ToHashSet() for O(1) Contains() lookups. +var enabledServices = rawServices + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + +bool IsEnabled(string name) => + enabledServices.Contains("all") || enabledServices.Contains(name); + +// WebApplication.CreateBuilder sets up the ASP.NET Core application builder. +// args are the command-line arguments passed at startup. +var builder = WebApplication.CreateBuilder(args); + +// --- Logging --- +// Replace the default logger with Serilog (see §13 for details). +builder.Host.UseSerilog((context, config) => + config.ReadFrom.Configuration(context.Configuration)); + +// --- Shared infrastructure: registered once, used by all enabled services --- + +// AddStackExchangeRedisCache registers IConnectionMultiplexer (the Redis client) +// as a singleton — one shared connection for the whole process lifetime. +builder.Services.AddSingleton( + ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("Redis")!)); + +// NATS connection registered as singleton. +builder.Services.AddNatsClient(opts => + opts with { Url = builder.Configuration["Nats:Url"]! }); + +// --- Service registrations --- +// Each service registers its own DbContext, repositories, services, and handlers. +// Only services listed in ENABLED_SERVICES are registered. + +if (IsEnabled("auth")) builder.Services.AddAuthService(builder.Configuration); +if (IsEnabled("chat")) builder.Services.AddChatService(builder.Configuration); +if (IsEnabled("collection")) builder.Services.AddCollectionService(builder.Configuration); +if (IsEnabled("bazaar")) builder.Services.AddBazaarService(builder.Configuration); +if (IsEnabled("admin")) builder.Services.AddAdminService(builder.Configuration); +if (IsEnabled("leaderboard")) builder.Services.AddLeaderboardService(builder.Configuration); +if (IsEnabled("content")) builder.Services.AddContentService(builder.Configuration); +if (IsEnabled("gateway")) builder.Services.AddGatewayService(builder.Configuration); + +// Build the application from the configured builder. +var app = builder.Build(); + +// --- Middleware pipeline --- +// Middleware runs in the order it's added. Each piece can intercept a request, +// do something, and pass it to the next piece. +app.UseRouting(); +app.UseAuthentication(); +app.UseAuthorization(); + +// --- Route gRPC handlers --- +// MapGrpcService connects the URL route to the handler class. +// The handler class is only registered if the service is enabled. +if (IsEnabled("auth")) app.MapGrpcService(); +if (IsEnabled("chat")) app.MapGrpcService(); +if (IsEnabled("collection")) app.MapGrpcService(); +if (IsEnabled("bazaar")) app.MapGrpcService(); +if (IsEnabled("leaderboard")) app.MapGrpcService(); +if (IsEnabled("content")) app.MapGrpcService(); + +// Health check endpoint for Kubernetes liveness/readiness probes. +app.MapHealthChecks("/health"); + +// Start the application. This call blocks until the process is stopped. +await app.RunAsync(); +``` + +### Deployment examples + +```yaml +# Kubernetes deployment: Auth + Collection + Bazaar on one pod +env: + - name: ENABLED_SERVICES + value: "auth,collection,bazaar" + +# Kubernetes deployment: Chat + Leaderboard on another pod +env: + - name: ENABLED_SERVICES + value: "chat,leaderboard" + +# Development: run everything +env: + - name: ENABLED_SERVICES + value: "all" +``` + +--- + +## 7. Dependency Injection + +.NET has a built-in dependency injection (DI) container. Understanding it is essential to +reading and writing code in this codebase. + +### The concept + +Instead of a class creating its own dependencies (`new AuthRepository()`), you declare what +you need in the constructor and the DI container creates and injects the right instance. + +```csharp +// Without DI — bad: AuthService is tightly coupled to AuthRepository. +// You can't swap the repository for a mock in tests. +public class AuthService +{ + private readonly AuthRepository _repo = new AuthRepository(); // hard dependency +} + +// With DI — good: AuthService depends on the interface, not the implementation. +// In tests, you inject a mock. In production, you inject the real repository. +public class AuthService : IAuthService +{ + private readonly IAuthRepository _repo; + + // The DI container sees that AuthService needs IAuthRepository, + // looks up what was registered for that interface, creates it, + // and passes it here automatically. + public AuthService(IAuthRepository repo) + { + _repo = repo; + } +} +``` + +### Service lifetimes + +When you register something in the DI container, you specify its lifetime: + +| Lifetime | Meaning | Use for | +|---|---|---| +| `AddSingleton` | One instance for the entire process lifetime | Redis connection, NATS connection, config | +| `AddScoped` | One instance per request (HTTP request or gRPC call) | DbContext, repositories, services | +| `AddTransient` | New instance every time it's requested | Rarely used; lightweight stateless utilities | + +**Rule**: DbContexts and repositories must always be `AddScoped`. Redis and NATS connections +must always be `AddSingleton`. Business logic services (`AddScoped` — they depend on scoped repositories). + +### Injecting things + +Once registered, anything can be injected into any constructor: + +```csharp +// The DI container automatically provides all three of these. +// No 'new' calls anywhere in business logic. +public class AuthService : IAuthService +{ + private readonly IAuthRepository _repo; + private readonly IConnectionMultiplexer _redis; + private readonly IOptions _options; + + public AuthService( + IAuthRepository repo, + IConnectionMultiplexer redis, + IOptions options) + { + _repo = repo; + _redis = redis; + _options = options; + } +} +``` + +--- + +## 8. Configuration System + +Configuration follows the standard .NET layered approach: + +1. `appsettings.json` — base config checked into source control (no secrets) +2. `appsettings.{Environment}.json` — environment overrides (Development, Staging, Production) +3. Environment variables — override anything from the above files (used in Docker/K8s) + +### appsettings.json structure + +```json +{ + "ConnectionStrings": { + "Auth": "Host=postgres;Database=sor_auth;Username=sor;Password=", + "Chat": "Host=postgres;Database=sor_chat;Username=sor;Password=", + "Redis": "redis:6379", + "ChatColdStorage": "server=mysql;database=sor_chat_archive;user=sor;password=" + }, + "Nats": { + "Url": "nats://nats:4222" + }, + "Auth": { + "SessionTtlMinutes": 1440, + "MaxSessionsPerUser": 5 + }, + "Serilog": { + "MinimumLevel": "Information", + "WriteTo": [ + { "Name": "Console" } + ] + } +} +``` + +### Strongly typed options classes + +Instead of calling `configuration["Auth:SessionTtlMinutes"]` everywhere (string-based, no +validation, no autocomplete), bind config sections to a typed class: + +```csharp +// src/SOR.Auth/AuthOptions.cs +namespace SOR.Auth; + +// This class mirrors the structure of the "Auth" section in appsettings.json. +// Properties must match the key names exactly (case-insensitive by default). +public class AuthOptions +{ + // DataAnnotations attributes validate the values at startup. + // If SessionTtlMinutes is 0, the app will throw before serving any requests. + [Range(1, int.MaxValue)] + public int SessionTtlMinutes { get; set; } = 1440; + + [Range(1, 100)] + public int MaxSessionsPerUser { get; set; } = 5; +} +``` + +Registered in ServiceRegistration.cs: +```csharp +services.Configure(configuration.GetSection("Auth")); +``` + +Injected and used: +```csharp +public class AuthService : IAuthService +{ + private readonly AuthOptions _options; + + // IOptions is the DI wrapper around a config section. + // Calling .Value gives you the typed AuthOptions instance. + public AuthService(IOptions options) + { + _options = options.Value; + } + + public TimeSpan GetSessionTtl() => + TimeSpan.FromMinutes(_options.SessionTtlMinutes); +} +``` + +### Environment variable overrides + +.NET automatically maps environment variables with double underscores to nested config keys: + +```bash +# Sets ConnectionStrings:Auth +ConnectionStrings__Auth="Host=prod-postgres;Database=sor_auth;Username=sor;Password=secret" + +# Sets Auth:SessionTtlMinutes +Auth__SessionTtlMinutes=2880 +``` + +In Kubernetes, secrets are injected as environment variables. The code never knows whether +config came from a file or an environment variable. + +--- + +## 9. gRPC Handlers + +A gRPC handler is the Layer 1 entry point for a service. It inherits from the base class +generated by the Protobuf tooling and delegates all logic to the service layer. + +```csharp +// src/SOR.Auth/Handlers/AuthGrpcHandler.cs +namespace SOR.Auth.Handlers; + +// The generated base class is AuthService.AuthServiceBase (from auth.proto). +// It contains abstract or virtual methods for each rpc defined in the proto file. +// We override those methods to provide our implementation. +// +// [GrpcService] is not needed here — gRPC in ASP.NET Core finds the handler +// automatically when it's registered via MapGrpcService in Program.cs. +public sealed class AuthGrpcHandler : AuthService.AuthServiceBase +{ + private readonly IAuthService _authService; + private readonly ILogger _logger; + + // Constructor injection — the DI container provides these. + public AuthGrpcHandler(IAuthService authService, ILogger logger) + { + _authService = authService; + _logger = logger; + } + + // Override the Login method defined in auth.proto. + // + // 'override' means we're replacing the base class's implementation. + // Task is the C# async return type — 'async' + 'await' let us write + // async code that looks sequential without blocking threads. + // ServerCallContext carries metadata about the gRPC call (deadline, peer address, etc.). + public override async Task Login( + LoginRequest request, + ServerCallContext context) + { + // Validate inputs before calling business logic. + // Return early with an error response — no exception needed for expected failures. + if (string.IsNullOrWhiteSpace(request.Email) || + string.IsNullOrWhiteSpace(request.Password)) + { + return new LoginResponse + { + Success = false, + ErrorCode = "INVALID_INPUT" + }; + } + + // Delegate to the service layer. The handler never touches the database directly. + var result = await _authService.LoginAsync(request.Email, request.Password); + + // Map ServiceResult to the Protobuf response message. + if (!result.Success) + { + _logger.LogWarning("Login failed for {Email}: {ErrorCode}", request.Email, result.ErrorCode); + return new LoginResponse + { + Success = false, + ErrorCode = result.ErrorCode ?? "UNKNOWN_ERROR" + }; + } + + return new LoginResponse + { + Success = true, + SessionToken = result.Value! + }; + } + + public override async Task ValidateToken( + ValidateTokenRequest request, + ServerCallContext context) + { + var result = await _authService.ValidateTokenAsync(request.SessionToken); + + if (!result.Success) + return new ValidateTokenResponse { Valid = false }; + + return new ValidateTokenResponse + { + Valid = true, + UserId = result.Value!.UserId, + DisplayName = result.Value.DisplayName + }; + } +} +``` + +### Calling another service via gRPC (client side) + +When a service needs to call another service synchronously, it uses the generated gRPC client stub. + +```csharp +// In ServiceRegistration.cs for a service that needs to call Auth: +services.AddGrpcClient(options => +{ + // The address of the Auth service — a Kubernetes service DNS name. + options.Address = new Uri(configuration["Services:Auth"]!); +}); + +// In a handler or service that calls Auth: +public class GatewayAuthValidator +{ + private readonly AuthService.AuthServiceClient _authClient; + + public GatewayAuthValidator(AuthService.AuthServiceClient authClient) + { + _authClient = authClient; + } + + public async Task ValidateAsync(string token) + { + var response = await _authClient.ValidateTokenAsync( + new ValidateTokenRequest { SessionToken = token }); + return response.Valid; + } +} +``` + +--- + +## 10. NATS Integration + +NATS is used for async fan-out events. One service publishes; zero or more services subscribe. +Publishers and subscribers have no knowledge of each other. + +### Publishing an event + +```csharp +// src/SOR.Game/Services/GameService.cs (excerpt) + +// INatsClient is the official NATS client interface — inject it from DI. +public class GameService : IGameService +{ + private readonly INatsClient _nats; + + public GameService(INatsClient nats) { _nats = nats; } + + public async Task RecordMatchResultAsync(MatchResult result) + { + // ... persist result ... + + // Publish an event to NATS. Any service subscribed to this subject + // will receive it independently. Game service doesn't care who listens. + // + // PublishAsync serializes T to JSON (or Protobuf if configured) automatically. + await _nats.PublishAsync(NatsSubjects.GameEnded, new GameEndedEvent + { + GameId = result.GameId, + WinnerId = result.WinnerId, + LoserId = result.LoserId, + EndedAt = DateTimeOffset.UtcNow + }); + } +} +``` + +### Subscribing to events + +NATS subscribers are registered as `IHostedService` background workers — they run for the +entire lifetime of the process and receive events as they arrive. + +```csharp +// src/SOR.Leaderboard/Subscribers/GameEndedSubscriber.cs +namespace SOR.Leaderboard.Subscribers; + +// IHostedService is the .NET interface for background services. +// The framework starts it on app startup and stops it on shutdown. +public sealed class GameEndedSubscriber : IHostedService +{ + private readonly INatsClient _nats; + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger _logger; + + // IServiceScopeFactory is needed because this is a Singleton (runs forever), + // but it needs to create Scoped services (like repositories) per message. + // Creating a scope per message ensures DbContext is not shared across messages. + public GameEndedSubscriber( + INatsClient nats, + IServiceScopeFactory scopeFactory, + ILogger logger) + { + _nats = nats; + _scopeFactory = scopeFactory; + _logger = logger; + } + + // CancellationToken signals when the application is shutting down. + // We pass it through so async operations can cancel cleanly. + public async Task StartAsync(CancellationToken cancellationToken) + { + // SubscribeAsync returns an IAsyncEnumerable — an async stream of messages. + // 'await foreach' processes each message as it arrives without blocking. + await foreach (var msg in _nats.SubscribeAsync( + NatsSubjects.GameEnded, cancellationToken: cancellationToken)) + { + if (msg.Data is null) continue; + + try + { + // Create a fresh DI scope for each message so EF Core DbContext + // is properly disposed after handling each event. + await using var scope = _scopeFactory.CreateAsyncScope(); + var service = scope.ServiceProvider.GetRequiredService(); + await service.ProcessGameResultAsync(msg.Data); + } + catch (Exception ex) + { + // Log and continue — a bad message must not crash the subscriber. + _logger.LogError(ex, "Failed to process GameEnded event {GameId}", msg.Data?.GameId); + } + } + } + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} +``` + +Register the subscriber in ServiceRegistration.cs: +```csharp +// IHostedService registrations use AddHostedService. +services.AddHostedService(); +``` + +--- + +## 11. Redis Integration + +Redis is used for session storage, client push delivery, live game state, leaderboard Sorted +Sets, and runtime feature flags. + +### Registering the connection + +Registered once in `Program.cs` as a Singleton — the connection multiplexer manages an +internal connection pool and is safe to share across the entire process. + +```csharp +// Program.cs (already shown in §6) +builder.Services.AddSingleton( + ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("Redis")!)); +``` + +### Using Redis in a service + +```csharp +// src/SOR.Auth/Services/AuthService.cs (excerpt) +public class AuthService : IAuthService +{ + private readonly IDatabase _redis; + private readonly AuthOptions _options; + + // IConnectionMultiplexer.GetDatabase() returns a lightweight IDatabase handle. + // It is safe to call GetDatabase() on every request — it does not create new connections. + public AuthService(IConnectionMultiplexer redis, IOptions options) + { + _redis = redis.GetDatabase(); + _options = options.Value; + } + + public async Task CreateSessionAsync(string userId, string displayName) + { + // Guid.NewGuid() generates a cryptographically random 128-bit identifier. + // ToString("N") formats it as a 32-character hex string with no dashes. + var token = Guid.NewGuid().ToString("N"); + var ttl = TimeSpan.FromMinutes(_options.SessionTtlMinutes); + + // Serialize session data to JSON. + // System.Text.Json is the built-in .NET JSON library — fast and allocation-efficient. + var sessionJson = JsonSerializer.Serialize(new + { + UserId = userId, + DisplayName = displayName, + CreatedAt = DateTimeOffset.UtcNow + }); + + // SET key value EX seconds — sets the key and its TTL atomically. + // RedisKeys.Session(token) returns the namespaced key string "session:{token}". + await _redis.StringSetAsync( + RedisKeys.Session(token), + sessionJson, + expiry: ttl); + + return token; + } + + public async Task RevokeSessionAsync(string token) + { + // DEL key — removes the key. If the key doesn't exist, this is a no-op. + await _redis.KeyDeleteAsync(RedisKeys.Session(token)); + } +} +``` + +--- + +## 12. Database — EF Core + PostgreSQL + +Entity Framework Core (EF Core) is the ORM. It lets you define your database schema as C# +classes and query the database using LINQ (Language Integrated Query) instead of raw SQL. +EF Core translates LINQ queries into optimized SQL at runtime. + +### DbContext + +Each service has its own DbContext. A DbContext represents a database connection session and +tracks all changes to entities loaded through it. + +```csharp +// src/SOR.Auth/Data/AuthDbContext.cs +namespace SOR.Auth.Data; + +// DbContext is the EF Core base class. We inherit from it and add our DbSets. +public class AuthDbContext : DbContext +{ + // Constructor: passes options to the base class. + // Options include the connection string — provided by DI from config. + public AuthDbContext(DbContextOptions options) : base(options) { } + + // DbSet represents a database table. Querying _users runs a SELECT; + // adding to it and calling SaveChanges() runs an INSERT. + public DbSet Users => Set(); + public DbSet OAuthLinks => Set(); + + // OnModelCreating configures the schema (table names, indexes, constraints). + // This runs once when EF Core builds its internal model of the schema. + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + // Configure the Users table. + modelBuilder.Entity(entity => + { + // Explicit table name (default would be "Users" — being explicit is safer). + entity.ToTable("users", schema: "auth"); + + // Primary key. EF Core auto-detects properties named "Id" but being + // explicit documents intent. + entity.HasKey(u => u.Id); + + // Index for fast email lookups. IsUnique enforces the DB constraint. + entity.HasIndex(u => u.Email).IsUnique(); + + // Column type: varchar with a max length (enforced at DB level). + entity.Property(u => u.Email).HasMaxLength(256).IsRequired(); + entity.Property(u => u.DisplayName).HasMaxLength(64).IsRequired(); + }); + } +} +``` + +### Entity classes + +Entities are plain C# classes that map to database rows. They live in the service's `Data/` +or `Models/` folder. They are the internal database representation — not the API response. + +```csharp +// src/SOR.Auth/Models/UserEntity.cs +namespace SOR.Auth.Models; + +public class UserEntity +{ + public Guid Id { get; set; } + public required string Email { get; set; } + public required string DisplayName { get; set; } + public required string PasswordHash { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public bool IsBanned { get; set; } +} +``` + +### Repository implementation + +```csharp +// src/SOR.Auth/Repositories/AuthRepository.cs +namespace SOR.Auth.Repositories; + +public class AuthRepository : IAuthRepository +{ + private readonly AuthDbContext _db; + + public AuthRepository(AuthDbContext db) + { + _db = db; + } + + // FirstOrDefaultAsync returns the first matching row, or null if none. + // The lambda expression 'u => u.Email == email' is the WHERE clause. + // 'await' pauses this method until the database responds, without blocking the thread. + public async Task FindByEmailAsync(string email, CancellationToken ct = default) + { + return await _db.Users + .FirstOrDefaultAsync(u => u.Email == email, ct); + } + + public async Task CreateAsync(UserEntity user, CancellationToken ct = default) + { + // Add the entity to the change tracker. + _db.Users.Add(user); + + // SaveChangesAsync flushes all pending changes to the database in one transaction. + await _db.SaveChangesAsync(ct); + + return user; + } +} +``` + +### Migrations + +Migrations are auto-generated files that track schema changes over time. When you change an +entity class (add a column, change a type), you generate a new migration and apply it. + +```bash +# Generate a migration (run from Server/ directory). +# Initial is just a descriptive name for the migration. +dotnet ef migrations add AuthInitial \ + --project src/SOR.Auth \ + --startup-project src/SOR.Host \ + --context AuthDbContext + +# Apply all pending migrations to the database. +dotnet ef database update \ + --project src/SOR.Auth \ + --startup-project src/SOR.Host \ + --context AuthDbContext +``` + +In production, migrations are applied automatically on startup: + +```csharp +// ServiceRegistration.cs — after the DbContext is registered: +services.AddHostedService>(); +``` + +--- + +## 13. Logging — Serilog + +All logging uses Serilog with structured log output. Every log entry is a structured event, +not just a string — this allows log aggregators (Seq, Grafana Loki, etc.) to query and filter +on field values. + +### Log levels + +| Level | When to use | +|---|---| +| `LogTrace` | Extremely verbose — step-by-step flow. Disabled in production. | +| `LogDebug` | Developer details — query parameters, intermediate values. Disabled in production. | +| `LogInformation` | Normal operational events — service started, login succeeded, game created. | +| `LogWarning` | Something unexpected but recoverable — login failed, retrying a DB query. | +| `LogError` | An operation failed — unhandled exception, external call failed. | +| `LogCritical` | System is broken — database unreachable on startup, OOM. | + +### Usage + +```csharp +// Always inject ILogger where T is the class using it. +// The T type name appears in log output so you know where the log came from. +private readonly ILogger _logger; + +// Structured logging: use message templates with {Property} placeholders. +// Serilog captures the actual value as a named property — not just a string. +// This means you can search logs for "UserId = abc123" later. +_logger.LogInformation("User {UserId} logged in from {IpAddress}", userId, ipAddress); + +// Log exceptions: pass the exception as the first argument. +// Serilog captures the full stack trace as a structured field. +try { ... } +catch (Exception ex) +{ + _logger.LogError(ex, "Login failed for {Email}", email); + throw; // Re-throw after logging if the caller needs to handle it. +} +``` + +--- + +## 14. Error Handling + +### Expected failures: ServiceResult + +Expected failures (user not found, invalid password, deck too large) are returned as +`ServiceResult.Fail(...)`. No exception is thrown. The caller checks `result.Success` and +maps to an appropriate response. + +```csharp +public async Task> LoginAsync(string email, string password) +{ + var user = await _repo.FindByEmailAsync(email); + + // Expected failure — return a result, don't throw. + if (user is null) + return ServiceResult.Fail("USER_NOT_FOUND", "Invalid credentials."); + + if (!PasswordHasher.Verify(password, user.PasswordHash)) + return ServiceResult.Fail("INVALID_PASSWORD", "Invalid credentials."); + + if (user.IsBanned) + return ServiceResult.Fail("ACCOUNT_BANNED", "This account has been banned."); + + var token = await CreateSessionAsync(user.Id.ToString(), user.DisplayName); + return ServiceResult.Ok(token); +} +``` + +### Unexpected failures: exceptions + +Unexpected failures (DB connection lost, OOM, null where impossible) are allowed to throw. +A global exception handler in ASP.NET Core catches them, logs them, and returns a generic +5xx response to the caller. + +```csharp +// Program.cs — catch-all for unhandled exceptions in the middleware pipeline. +app.UseExceptionHandler(exceptionHandlerApp => + exceptionHandlerApp.Run(async context => + { + var feature = context.Features.Get(); + var logger = context.RequestServices.GetRequiredService>(); + logger.LogError(feature?.Error, "Unhandled exception on {Path}", context.Request.Path); + context.Response.StatusCode = 500; + })); +``` + +### Never swallow exceptions silently + +```csharp +// BAD: The exception disappears. The caller thinks nothing went wrong. +try { await _repo.SaveAsync(entity); } +catch (Exception) { } + +// GOOD: Log and re-throw, or return a failure result. +try { await _repo.SaveAsync(entity); } +catch (Exception ex) +{ + _logger.LogError(ex, "Failed to save entity {Id}", entity.Id); + throw; +} +``` + +--- + +## 15. Health Checks + +Every running instance exposes `/health` for Kubernetes liveness and readiness probes. +Health checks verify that the service's critical dependencies (database, Redis) are reachable. + +```csharp +// ServiceRegistration.cs — register health checks alongside services. +services.AddHealthChecks() + .AddNpgSql(configuration.GetConnectionString("Auth")!, name: "auth-db") + .AddRedis(configuration.GetConnectionString("Redis")!, name: "redis"); + +// Program.cs — expose the endpoint (already shown in §6). +app.MapHealthChecks("/health"); +``` + +--- + +## 16. Testing Patterns + +### Unit tests + +Unit tests test a single class in isolation. All dependencies are replaced with mocks. +No database, no Redis, no network — tests run in milliseconds. + +```csharp +// tests/SOR.Auth.Tests/AuthServiceTests.cs +namespace SOR.Auth.Tests; + +// [Fact] marks a test method. xUnit discovers and runs all methods marked with [Fact]. +public class AuthServiceTests +{ + // Moq: create a mock implementation of the interface. + // The mock records calls made to it and can be configured to return specific values. + private readonly Mock _repoMock = new(); + private readonly Mock _redisMock = new(); + private readonly IAuthService _sut; // "sut" = System Under Test — common convention. + + public AuthServiceTests() + { + var options = Options.Create(new AuthOptions { SessionTtlMinutes = 60 }); + _sut = new AuthService(_repoMock.Object, _redisMock.Object, options); + } + + [Fact] + public async Task Login_WithValidCredentials_ReturnsSuccessResult() + { + // Arrange: configure the mock to return a specific user when queried. + _repoMock + .Setup(r => r.FindByEmailAsync("test@example.com", default)) + .ReturnsAsync(new UserEntity + { + Id = Guid.NewGuid(), + Email = "test@example.com", + DisplayName = "TestUser", + PasswordHash = PasswordHasher.Hash("correct-password"), + CreatedAt = DateTimeOffset.UtcNow + }); + + // Act: call the method being tested. + var result = await _sut.LoginAsync("test@example.com", "correct-password"); + + // Assert: verify the result. FluentAssertions provides readable assertions. + result.Success.Should().BeTrue(); + result.Value.Should().NotBeNullOrEmpty(); + } + + [Fact] + public async Task Login_WithWrongPassword_ReturnsFailResult() + { + _repoMock + .Setup(r => r.FindByEmailAsync("test@example.com", default)) + .ReturnsAsync(new UserEntity + { + Id = Guid.NewGuid(), + Email = "test@example.com", + DisplayName = "TestUser", + PasswordHash = PasswordHasher.Hash("correct-password"), + CreatedAt = DateTimeOffset.UtcNow + }); + + var result = await _sut.LoginAsync("test@example.com", "wrong-password"); + + result.Success.Should().BeFalse(); + result.ErrorCode.Should().Be("INVALID_PASSWORD"); + } +} +``` + +### Integration tests + +Integration tests spin up a real application with a real database (test-specific). Used to test +the full stack — handler → service → repository → database — without mocks. + +```csharp +// tests/SOR.Auth.Tests/AuthIntegrationTests.cs + +// WebApplicationFactory starts the real app in-memory for testing. +// T is the entry point — usually Program.cs is referenced via a partial class. +public class AuthIntegrationTests : IClassFixture> +{ + private readonly WebApplicationFactory _factory; + + public AuthIntegrationTests(WebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureAppConfiguration((_, config) => + { + // Override connection strings to point at a test database. + config.AddInMemoryCollection(new Dictionary + { + ["ConnectionStrings:Auth"] = "Host=localhost;Database=sor_auth_test;...", + ["ENABLED_SERVICES"] = "auth" + }); + }); + }); + } + + [Fact] + public async Task Login_ValidUser_ReturnsToken() + { + // Use the generated gRPC client against the in-memory server. + var client = new AuthService.AuthServiceClient( + GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions + { + HttpClient = _factory.CreateClient() + })); + + var response = await client.LoginAsync(new LoginRequest + { + Email = "seed@example.com", + Password = "testpassword" + }); + + response.Success.Should().BeTrue(); + response.SessionToken.Should().NotBeEmpty(); + } +} +``` + +### Test file naming conventions + +| File | What it tests | +|---|---| +| `{Class}Tests.cs` | Unit tests for a single class | +| `{Service}IntegrationTests.cs` | Integration tests for a full service stack | +| `{Handler}HandlerTests.cs` | Tests for a gRPC handler (mock the service layer) | + +--- + +## 17. Naming Conventions + +C# uses different casing conventions for different kinds of identifiers. These are enforced +by the compiler for some cases and by team convention for others. + +| Kind | Convention | Example | +|---|---|---| +| Namespace | PascalCase | `SOR.Auth.Services` | +| Class / Interface / Record | PascalCase | `AuthService`, `IAuthRepository` | +| Method | PascalCase | `LoginAsync`, `FindByEmailAsync` | +| Property | PascalCase | `SessionTtlMinutes`, `ErrorCode` | +| Constant (`const`) | PascalCase | `NatsSubjects.GameEnded` | +| Private field | `_camelCase` | `_repo`, `_logger` | +| Local variable | camelCase | `sessionToken`, `userId` | +| Parameter | camelCase | `email`, `password` | +| Interface | `I` prefix | `IAuthService`, `IAuthRepository` | +| Async method | `Async` suffix | `LoginAsync`, `SaveChangesAsync` | +| Generic type parameter | `T` prefix | `ServiceResult`, `DbSet` | + +### File naming + +- One class per file. +- File name must match class name exactly: `AuthService.cs` contains `class AuthService`. +- Interface files: `IAuthService.cs` contains `interface IAuthService`. + +### Project naming + +All projects in the solution are prefixed with `SOR.`: +- `SOR.Host` — multi-service runner +- `SOR.Shared` — shared library +- `SOR.Auth` — Auth service module +- `SOR.Auth.Tests` — tests for Auth + +--- + +## 18. Hard Rules + +These rules are non-negotiable. Every code review checks for violations. + +1. **No cross-service database access.** Each service's DbContext connects to its own schema. + Service A never queries Service B's schema. Inter-service data goes through gRPC or NATS. + +2. **No business logic in handlers.** Handlers receive, validate inputs, call the service, + and return. All business logic lives in the service layer. + +3. **No database access in services.** Services call repositories. They never instantiate + DbContext directly or run SQL. + +4. **No `new` for injected dependencies.** If something is registered in the DI container, + it is injected through the constructor — never created with `new` inside a class. + +5. **All async methods must be awaited.** Never call an async method and discard the `Task`. + This hides exceptions and can cause subtle race conditions. + +6. **All Redis key names go through `RedisKeys`.** No inline string literals like `"session:" + token`. + +7. **All NATS subject names go through `NatsSubjects`.** No inline string literals. + +8. **No shared mutable state between services.** Services share DI infrastructure (Redis, + NATS connections) but never share in-memory objects or static mutable state. + +9. **Every service module exposes exactly one public entry point: `Add{Name}Service`.** All + other types in the module are `internal` unless explicitly needed by other assemblies. + +10. **No catching `Exception` without re-throwing or returning a result.** Swallowing exceptions + silently is forbidden. + +11. **Log at the correct level.** Never log expected failures at `Error`. Never flood `Information` + with per-message trace data in production. + +12. **Entities are internal to their service.** `UserEntity` from SOR.Auth is never referenced + in SOR.Gateway. Share data through Protobuf messages or strongly-typed C# DTOs in SOR.Shared. diff --git a/Server/initial-plan.md b/Server/initial-plan.md index b5602dc..ca765d9 100644 --- a/Server/initial-plan.md +++ b/Server/initial-plan.md @@ -14,6 +14,7 @@ All components are open-source and self-hosted. No licensing fees. | Component | Choice | License | |---|---|---| +| **Programming language** | **C# 12 (.NET 8)** | MIT | | Primary database | PostgreSQL | PostgreSQL License | | Session store / live game state / rankings | Redis (Community Edition) | BSD 3-Clause | | Async event bus (inter-service fan-out) | NATS | Apache 2.0 | @@ -22,6 +23,10 @@ All components are open-source and self-hosted. No licensing fees. | Client transport | WebSocket | Open standard | | Object storage (CDN origin) | Ceph (via RADOSGW S3 API) | LGPL v2.1 | | Chat cold storage (archive) | Remote MySQL (third-party hosted, unlimited storage deal) | N/A | +| ORM | Entity Framework Core + Npgsql | MIT | +| Logging | Serilog | Apache 2.0 | + +**Programming architecture** (repo structure, service patterns, DI, config, error handling, testing): see `Server/architecture.md`. **Payment processing** is the one mandatory third-party service. Accepting real-money card payments requires PCI DSS compliance and direct card network relationships — this cannot be built in-house. Stripe is the recommended processor (per-transaction fee only, no monthly license). The integration will be **implemented but disabled** until real-money features are ready to launch. All other payment handling logic (wallets, currency conversion, transaction records) is built internally in the Bazaar service. @@ -368,6 +373,7 @@ This is not a service but an infrastructure component managed through the Admin | Decision | Choice | Notes | |---|---|---| +| Programming language | C# 12 (.NET 8) | ASP.NET Core for gRPC + WebSocket; EF Core for ORM; see architecture.md | | Primary database | PostgreSQL | JSONB, concurrency, analytics; over MySQL | | Async event bus | NATS | Lightweight, low-latency, pub/sub + request/reply; Apache 2.0 | | Sync inter-service RPC | gRPC + Protobuf | Schema-first, code-generated, binary |