diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d67b52..3216511 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,6 +51,8 @@ jobs: working-directory: frontend - name: Build API run: dotnet build backend/Pitwall.Api/Pitwall.Api.csproj -c Release + - name: Verify authoritative room simulation and permissions + run: dotnet run -c Release --project backend/Pitwall.RoomChecks - name: Test API against PostgreSQL, including restart persistence run: python scripts/test-api.py --postgres env: diff --git a/README.md b/README.md index b41dff3..b75773f 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ The [handbook](docs/USER-GUIDE.md) documents every current user flow: steps, def - A held-out pace backtest comparing past-only flat and trend baselines with later recorded laps, with explicit errors and pit-free/data-quality requirements. - A circuit race sandbox with editable connected pit lanes, one to six named/coloured drivers, individual pace, scheduled service stops, a simulated running order and browser-saved setups. - Finite 1–50 lap fictional races with exact finish times/results, plus selected-driver live pit calls, cancellation before entry and repeat visits. See [race sessions](docs/guide/05-race-sandbox.md#sandbox-08). +- Private multiplayer rooms with a C#-owned simulation clock, SignalR snapshots, guest driver claims/readiness, host controls, live pit calls, reconnect, spectator support, guest removal and driver/host handover. Rooms are temporary and use one API instance. See [the multiplayer guide](docs/guide/07-multiplayer.md). - On-demand tool bundles, recovery from tool download failures, indexed replay lookups, a read-only setup doctor, and a one-command local preview. - Light/dark themes with a header toggle, system preference on first visit, and a browser-saved choice across races. - Save, revisit, and delete replay moments. Bookmarks are isolated by race and survive API restarts in PostgreSQL. diff --git a/backend/Pitwall.Api/Program.cs b/backend/Pitwall.Api/Program.cs index 4288dfc..38f5c7a 100644 --- a/backend/Pitwall.Api/Program.cs +++ b/backend/Pitwall.Api/Program.cs @@ -1,11 +1,23 @@ using System.Text.Json; using Npgsql; +using System.Threading.RateLimiting; +using Microsoft.AspNetCore.RateLimiting; var builder = WebApplication.CreateBuilder(args); builder.Logging.ClearProviders(); builder.Logging.AddConsole(); builder.Services.AddProblemDetails(); builder.Services.AddResponseCompression(); +builder.Services.AddSignalR(options => { options.MaximumReceiveMessageSize = 8192; options.MaximumParallelInvocationsPerClient = 1; }); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(); +builder.Services.AddRateLimiter(options => { + options.RejectionStatusCode = 429; + options.AddPolicy("room-guests", context => RateLimitPartition.GetFixedWindowLimiter( + context.Connection.RemoteIpAddress?.ToString() ?? "local", _ => new FixedWindowRateLimiterOptions { + PermitLimit = 20, Window = TimeSpan.FromMinutes(1), QueueLimit = 0, AutoReplenishment = true + })); +}); var connection = builder.Configuration.GetConnectionString("Pitwall"); if (!string.IsNullOrWhiteSpace(connection)) builder.Services.AddSingleton(NpgsqlDataSource.Create(connection)); builder.Services.AddSingleton(); @@ -17,9 +29,19 @@ var app = builder.Build(); app.UseExceptionHandler(); app.UseResponseCompression(); +app.UseRateLimiter(); await app.Services.GetRequiredService().InitializeAsync(); app.UseDefaultFiles(); app.UseStaticFiles(); +app.MapHub("/api/rooms/live"); +app.MapPost("/api/rooms", (RoomCreateInput input, RaceRooms rooms) => { + try { return Results.Ok(rooms.Create(input)); } + catch (RoomError e) { return Results.BadRequest(new { message = e.Message }); } +}).RequireRateLimiting("room-guests").WithMetadata(new Microsoft.AspNetCore.Mvc.RequestSizeLimitAttribute(100000)); +app.MapPost("/api/rooms/{code}/join", (string code, RoomJoinInput input, RaceRooms rooms) => { + try { return Results.Ok(rooms.Join(code, input.Name)); } + catch (RoomError e) { return Results.BadRequest(new { message = e.Message }); } +}).RequireRateLimiting("room-guests"); app.MapGet("/health", async (RaceStore data, CancellationToken ct) => await data.ReadyAsync(ct) ? Results.Ok(new { status = "healthy", storage = data.Storage }) : Results.StatusCode(503)); diff --git a/backend/Pitwall.Api/RaceRooms.cs b/backend/Pitwall.Api/RaceRooms.cs new file mode 100644 index 0000000..240bbe1 --- /dev/null +++ b/backend/Pitwall.Api/RaceRooms.cs @@ -0,0 +1,211 @@ +using System.Diagnostics; +using System.Security.Cryptography; +using Microsoft.AspNetCore.SignalR; + +public record RoomCreateInput(string Name, CircuitSpec Track, RoomSetup Setup); +public record RoomJoinInput(string Name); +public record RoomTicket(string Code, string PlayerId, string Token); +public record RoomCommand(string Action, string? DriverId = null, string? PlayerId = null, double? Speed = null); +public record RoomPlayerView(string Id, string Name, bool Connected, bool Ready); +public record RoomSeatView(string DriverId, string? PlayerId); +public record RoomView(string Code, long Revision, string HostId, CircuitSpec Track, RoomSetup Setup, + RoomPlayerView[] Players, RoomSeatView[] Seats, RoomDriverState[] States, string[] Order, + double Elapsed, bool Running, double Speed, bool Complete); + +// All room mutations and snapshots share one lock. A single process owns each race. +public sealed class RaceRooms { + sealed class Player(string name) { + public string Id { get; } = Guid.NewGuid().ToString("N"); + public string Token { get; } = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + public string Name { get; } = name; + public bool Ready { get; set; } + public HashSet Connections { get; } = []; + public long LastCommand { get; set; } + public int CommandCount { get; set; } + } + sealed class Room(string code, RoomSimulation simulation, Player host) { + public string Code { get; } = code; + public RoomSimulation Sim { get; } = simulation; + public string HostId { get; set; } = host.Id; + public List Players { get; } = [host]; + public Dictionary Seats { get; } = simulation.Setup.Drivers.ToDictionary(d=>d.Id,_=>(string?)null); + public bool Running { get; set; } + public double Speed { get; set; } = 10; + public long Revision { get; set; } + public DateTimeOffset LastActive { get; set; } = DateTimeOffset.UtcNow; + } + readonly object gate = new(); + readonly Dictionary rooms = []; + readonly Dictionary connections = []; + readonly List<(string Connection,string Code)> revoked = []; + static string Name(string? name) => !string.IsNullOrWhiteSpace(name) && name.Trim().Length<=24 && !name.Any(char.IsControl) + ? name.Trim() : throw new RoomError("Use a guest name of 1–24 characters."); + Room Find(string code) => code is {Length:12} && rooms.TryGetValue(code.ToUpperInvariant(),out var room) ? room : throw new RoomError("Room unavailable or expired. Ask the host for a fresh invitation."); + public RoomTicket Create(RoomCreateInput input) { + var name=Name(input.Name); + var sim=new RoomSimulation(input.Track,input.Setup); + lock(gate) { + Expire(); + if(rooms.Count>=32)throw new RoomError("The server has 32 rooms already. Try again later."); + string code;do{code=Convert.ToHexString(RandomNumberGenerator.GetBytes(6));}while(rooms.ContainsKey(code)); + var host=new Player(name);var room=new Room(code,sim,host);rooms.Add(code,room); + return new(code,host.Id,host.Token); + } + } + public RoomTicket Join(string code,string name) { + name=Name(name); + lock(gate){ + Expire();var room=Find(code); + if(room.Players.Count>=12)throw new RoomError("This room already has twelve guests, including spectators."); + var player=new Player(name);room.Players.Add(player);room.LastActive=DateTimeOffset.UtcNow;room.Revision++; + return new(room.Code,player.Id,player.Token); + } + } + public RoomView Attach(string connection,string code,string token) { + lock(gate){ + var room=Find(code); + var player=room.Players.FirstOrDefault(p=>p.Token==token)??throw new RoomError("Guest session unavailable. Join again with the invitation."); + if(connections.ContainsKey(connection))throw new RoomError("This connection is already in a room."); + connections[connection]=(room,player);player.Connections.Add(connection); + room.LastActive=DateTimeOffset.UtcNow;room.Revision++; + return View(room); + } + } + public RoomView? Detach(string connection) { + lock(gate){ + if(!connections.Remove(connection,out var member))return null; + member.player.Connections.Remove(connection);member.room.Revision++; + member.room.LastActive=DateTimeOffset.UtcNow; + return rooms.ContainsKey(member.room.Code)?View(member.room):null; + } + } + public RoomView Execute(string connection,RoomCommand command) { + lock(gate){ + if(!connections.TryGetValue(connection,out var member))throw new RoomError("Reconnect to the room first."); + var (room,player)=member; + if(!room.Players.Contains(player))throw new RoomError("You left this room. Join again."); + var now=Stopwatch.GetTimestamp(); + if(player.LastCommand==0 || Stopwatch.GetElapsedTime(player.LastCommand,now).TotalSeconds>=1){player.LastCommand=now;player.CommandCount=0;} + if(++player.CommandCount>20) + throw new RoomError("Please wait a moment before the next decision."); + var host=room.HostId==player.Id; + string Driver() => command.DriverId is not null&&room.Seats.ContainsKey(command.DriverId)?command.DriverId:throw new RoomError("Choose a driver."); + void Host(){if(!host)throw new RoomError("Only the host can change race controls.");} + switch(command.Action){ + case "claim": { + var driver=Driver(); + if(room.Seats[driver] is not null && room.Seats[driver]!=player.Id)throw new RoomError("That driver is already claimed."); + foreach(var key in room.Seats.Where(kv=>kv.Value==player.Id).Select(kv=>kv.Key).ToArray())room.Seats[key]=null; + room.Seats[driver]=player.Id;player.Ready=false;break; + } + case "release": case "handover": { + var driver=Driver(); + if(room.Seats[driver]!=player.Id&&!host)throw new RoomError("Only the owner or host can hand over a driver."); + Player? target=null; + if(command.Action=="handover"){ + target=room.Players.FirstOrDefault(p=>p.Id==command.PlayerId&&p.Connections.Count>0)??throw new RoomError("Choose a connected guest."); + if(room.Seats.Values.Contains(target.Id))throw new RoomError("That guest already controls a driver. Release it first."); + } + room.Seats[driver]=target?.Id;if(target is not null)target.Ready=false;break; + } + case "ready": + if(!room.Seats.Values.Contains(player.Id))throw new RoomError("Claim a driver before getting ready."); + player.Ready=!player.Ready;break; + case "start": + Host(); + if(room.Sim.Complete)throw new RoomError("Reset the finished race first."); + if(room.Sim.Elapsed==0 && (!room.Seats.Values.Any(v=>v is not null)||room.Players.Any(p=>room.Seats.Values.Contains(p.Id)&&(!p.Ready||p.Connections.Count==0)))) + throw new RoomError("At least one driver must be claimed. All claimed drivers must be connected and ready."); + room.Running=true;break; + case "pause": Host();room.Running=false;break; + case "reset": Host();room.Running=false;room.Sim.Reset();foreach(var p in room.Players)p.Ready=false;break; + case "speed": Host();if(command.Speed is not (1 or 5 or 10 or 25))throw new RoomError("Choose 1×, 5×, 10× or 25×.");room.Speed=command.Speed.Value;break; + case "box": case "cancel": { + var driver=Driver(); + if(room.Seats[driver]!=player.Id)throw new RoomError("You can make pit calls only for your claimed driver."); + room.Sim.Call(driver,command.Action=="box");break; + } + case "host": + Host();var next=room.Players.FirstOrDefault(p=>p.Id==command.PlayerId&&p.Connections.Count>0)??throw new RoomError("Choose a connected guest."); + room.HostId=next.Id;break; + case "remove": { + Host();var removed=room.Players.FirstOrDefault(p=>p.Id==command.PlayerId&&p.Id!=player.Id)??throw new RoomError("Choose another guest to remove."); + foreach(var key in room.Seats.Where(kv=>kv.Value==removed.Id).Select(kv=>kv.Key).ToArray())room.Seats[key]=null; + room.Players.Remove(removed); + foreach(var id in removed.Connections){connections.Remove(id);revoked.Add((id,room.Code));} + removed.Connections.Clear();break; + } + case "leave": + foreach(var key in room.Seats.Where(kv=>kv.Value==player.Id).Select(kv=>kv.Key).ToArray())room.Seats[key]=null; + room.Players.Remove(player); + foreach(var id in player.Connections){connections.Remove(id);revoked.Add((id,room.Code));} + player.Connections.Clear(); + if(host && room.Players.Count>0)room.HostId=room.Players.OrderByDescending(p=>p.Connections.Count>0).First().Id; + if(room.Players.Count==0)rooms.Remove(room.Code); + break; + default: throw new RoomError("Unknown room decision."); + } + room.LastActive=DateTimeOffset.UtcNow;room.Revision++; + return View(room); + } + } + public RoomView[] Advance(double seconds) { + lock(gate){ + Expire();var updates=new List(); + foreach(var room in rooms.Values){ + if(room.Players.Any(p=>p.Connections.Count>0))room.LastActive=DateTimeOffset.UtcNow; + if(!room.Running)continue; + room.Sim.Advance(Math.Clamp(seconds,0,1)*room.Speed); + if(room.Sim.Complete)room.Running=false; + room.Revision++;updates.Add(View(room)); + } + return updates.ToArray(); + } + } + public (string Connection,string Code)[] DrainRevoked() { + lock(gate){var result=revoked.ToArray();revoked.Clear();return result;} + } + void Expire(){ + foreach(var room in rooms.Values.Where(r=>DateTimeOffset.UtcNow-r.LastActive>TimeSpan.FromHours(2)).ToArray())rooms.Remove(room.Code); + } + static RoomView View(Room r)=>new(r.Code,r.Revision,r.HostId,r.Sim.Track,r.Sim.Setup, + r.Players.Select(p=>new RoomPlayerView(p.Id,p.Name,p.Connections.Count>0,p.Ready)).ToArray(), + r.Seats.Select(k=>new RoomSeatView(k.Key,k.Value)).ToArray(),r.Sim.States.Select(s=>s with{}).ToArray(),r.Sim.Order(),r.Sim.Elapsed,r.Running,r.Speed,r.Sim.Complete); +} +public sealed class RaceRoomHub(RaceRooms rooms):Hub { + public async Task Enter(string code,string token){ + try { + var room=rooms.Attach(Context.ConnectionId,code,token); + await Groups.AddToGroupAsync(Context.ConnectionId,room.Code); + await Clients.Group(room.Code).SendAsync("Room",room); + return room; + }catch(RoomError e){throw new HubException(e.Message);} + } + public async Task Decide(RoomCommand command){ + try { + var room=rooms.Execute(Context.ConnectionId,command); + foreach(var removed in rooms.DrainRevoked()){ + await Groups.RemoveFromGroupAsync(removed.Connection,removed.Code); + if(removed.Connection!=Context.ConnectionId)await Clients.Client(removed.Connection).SendAsync("MembershipEnded"); + } + if(command.Action=="leave")await Groups.RemoveFromGroupAsync(Context.ConnectionId,room.Code); + await Clients.Group(room.Code).SendAsync("Room",room); + return room; + }catch(RoomError e){throw new HubException(e.Message);} + } + public override async Task OnDisconnectedAsync(Exception? exception){ + var room=rooms.Detach(Context.ConnectionId); + if(room is not null)await Clients.Group(room.Code).SendAsync("Room",room); + await base.OnDisconnectedAsync(exception); + } +} +public sealed class RaceRoomClock(RaceRooms rooms,IHubContext hub):BackgroundService { + protected override async Task ExecuteAsync(CancellationToken stoppingToken){ + using var timer=new PeriodicTimer(TimeSpan.FromMilliseconds(100)); + var previous=Stopwatch.GetTimestamp(); + while(await timer.WaitForNextTickAsync(stoppingToken)){ + var now=Stopwatch.GetTimestamp();var seconds=Stopwatch.GetElapsedTime(previous,now).TotalSeconds;previous=now; + foreach(var room in rooms.Advance(seconds))await hub.Clients.Group(room.Code).SendAsync("Room",room,stoppingToken); + } + } +} diff --git a/backend/Pitwall.Api/RoomSimulation.cs b/backend/Pitwall.Api/RoomSimulation.cs new file mode 100644 index 0000000..e31f5a4 --- /dev/null +++ b/backend/Pitwall.Api/RoomSimulation.cs @@ -0,0 +1,174 @@ +// Authoritative counterpart of the local sandbox's geometry/pace model. +// Rooms accept definitions and decisions, never client positions or elapsed time. +public record CircuitSpec(int Version, string Id, string Name, double[][] Points, int[] SectorEnds, double CornerRadius); +public record RoomDriver(string Id, string Name, string Color, double PaceOffset, int PitLap, double ServiceSeconds); +public record RoomSetup(int Version, int RaceLaps, double BaseLapSeconds, double Entry, double Exit, double[][] PitControls, RoomDriver[] Drivers); +public record RoomDriverState { + public required string Id { get; init; } + public double RaceProgress { get; set; } + public string Phase { get; set; } = "track"; + public double PitProgress { get; set; } + public double StopRemaining { get; set; } + public bool Serviced { get; set; } + public bool Visited { get; set; } + public int Stops { get; set; } + public double? PitTarget { get; set; } + public double? FinishTime { get; set; } + public bool FinishedInPit { get; set; } +} +public sealed class RoomSimulation { + public CircuitSpec Track { get; } + public RoomSetup Setup { get; } + public RoomDriverState[] States { get; private set; } + public double Elapsed { get; private set; } + public bool Complete => States.All(s => s.FinishTime.HasValue); + readonly double mainLength, pitLength; + public RoomSimulation(CircuitSpec track, RoomSetup setup) { + Validate(track, setup); + Track = track; Setup = setup; + var main = Rounded(track.Points, track.CornerRadius, true); + var closed = main.Append(main[0]).ToArray(); + var pit = Rounded(new[] {At(closed, setup.Entry)}.Concat(setup.PitControls).Append(At(closed, setup.Exit)).ToArray(), 24, false); + mainLength = Length(closed); pitLength = Length(pit); + if (pitLength < 20 || CrossesSelf(pit, false) || CrossesRoutes(pit, closed)) + throw new RoomError("The pit lane must be long enough and cannot cross itself or the circuit."); + States = Initial(); + } + RoomDriverState[] Initial() => Setup.Drivers.Select((d, i) => new RoomDriverState { + Id = d.Id, RaceProgress = -i * .006, + PitTarget = d.PitLap > 0 && d.PitLap - 1 + Setup.Entry < Setup.RaceLaps ? d.PitLap - 1 + Setup.Entry : null + }).ToArray(); + public void Reset() { States = Initial(); Elapsed = 0; } + public void Call(string driverId, bool box) { + var s = States.Single(s => s.Id == driverId); + if (s.Phase != "track") throw new RoomError("This driver has committed to the pit lane or finished."); + if (!box) { s.PitTarget = null; return; } + var target = Math.Floor(Math.Max(0, s.RaceProgress)) + Setup.Entry; + if (target < s.RaceProgress - 1e-9) target++; + if (target >= Setup.RaceLaps) throw new RoomError("No pit entry remains before the finish."); + s.PitTarget = target; + } + public void Advance(double seconds) { + if (!double.IsFinite(seconds) || seconds <= 0 || Complete) return; + for (var i = 0; i < States.Length; i++) AdvanceDriver(States[i], Setup.Drivers[i], seconds); + Elapsed = Complete ? States.Max(s => s.FinishTime!.Value) : Elapsed + seconds; + } + void AdvanceDriver(RoomDriverState s, RoomDriver d, double seconds) { + if (s.Phase == "finished") return; + var remaining = seconds; + var lap = Setup.BaseLapSeconds + d.PaceOffset; + var span = (Setup.Exit - Setup.Entry + 1) % 1; + void Finish(bool pit) { + s.FinishTime = Elapsed + seconds - remaining; + s.FinishedInPit = pit; s.Phase = "finished"; + s.RaceProgress = Setup.RaceLaps; s.PitTarget = null; remaining = 0; + } + for (var guard = 0; remaining > 1e-9 && guard < 12; guard++) { + if (s.Phase == "track") { + var target = s.PitTarget ?? Setup.RaceLaps; + var until = (target - s.RaceProgress) * lap; + if (until >= -1e-8 && until <= remaining) { + s.RaceProgress = target; remaining -= Math.Max(0, until); + if (s.PitTarget is null) { Finish(false); break; } + s.Phase = "pit"; s.PitProgress = 0; s.Serviced = false; s.PitTarget = null; + } else { s.RaceProgress += remaining / lap; remaining = 0; } + } else if (s.Phase == "service") { + var used = Math.Min(remaining, s.StopRemaining); + remaining -= used; s.StopRemaining -= used; + if (s.StopRemaining <= 1e-9) s.Phase = "pit"; + } else { + var speed = mainLength / lap * .35 / Math.Max(1, pitLength); + var stopTarget = s.Serviced ? 1 : .5; + var fraction = (Setup.RaceLaps - s.RaceProgress) / span; + var finish = fraction >= s.PitProgress - 1e-9 && fraction <= stopTarget + 1e-9; + var target = finish ? Math.Min(stopTarget, Math.Max(s.PitProgress, fraction)) : stopTarget; + var until = (target - s.PitProgress) / speed; + if (until > remaining + 1e-8) { s.PitProgress += remaining * speed; remaining = 0; } + else { + s.PitProgress = target; remaining = Math.Max(0, remaining - Math.Max(0, until)); + if (finish) { Finish(true); break; } + if (!s.Serviced) { s.Serviced = true; s.Phase = "service"; s.StopRemaining = d.ServiceSeconds; } + else { s.Phase = "track"; s.Visited = true; s.Stops++; s.RaceProgress += span; } + } + } + } + } + public string[] Order() => States.OrderBy(s => s.FinishTime.HasValue ? 0 : 1) + .ThenBy(s => s.FinishTime ?? -(s.RaceProgress + (s.Phase is "pit" or "service" ? s.PitProgress * ((Setup.Exit - Setup.Entry + 1) % 1) : 0))) + .Select(s => s.Id).ToArray(); + static bool Range(double n, double min, double max) => double.IsFinite(n) && n >= min && n <= max; + static bool Points(double[][]? p, int min, int max) => p is not null && p.Length >= min && p.Length <= max && + p.All(v => v is {Length: 2} && Range(v[0], 20, 780) && Range(v[1], 20, 500)); + static void Validate(CircuitSpec t, RoomSetup s) { + if (t is null || s is null || t.Version != 1 || s.Version != 1 || string.IsNullOrWhiteSpace(t.Name) || t.Name.Length > 48 || + string.IsNullOrWhiteSpace(t.Id) || t.Id.Length > 80 || !Points(t.Points, 6, 120) || !Range(t.CornerRadius, 0, 80) || + t.SectorEnds is not {Length: 2} || t.SectorEnds[0] <= 0 || t.SectorEnds[0] >= t.SectorEnds[1] || t.SectorEnds[1] >= t.Points.Length || + !Range(s.RaceLaps, 1, 50) || !Range(s.BaseLapSeconds, 30, 300) || !Range(s.Entry, 0, .99) || !Range(s.Exit, 0, .99) || + Math.Abs(s.Entry - s.Exit) < .01 || !Points(s.PitControls, 1, 12) || s.Drivers is null || s.Drivers.Length is < 1 or > 6) + throw new RoomError("Provide a valid circuit, 1–50 laps, 1–6 drivers and bounded pit/pace settings."); + if (CrossesSelf(t.Points.Append(t.Points[0]).ToArray(), true) || + t.Points.Where((p, i) => Distance(p, t.Points[(i + 1) % t.Points.Length]) < 8).Any() || + Math.Abs(t.Points.Select((p, i) => p[0] * t.Points[(i + 1) % t.Points.Length][1] - t.Points[(i + 1) % t.Points.Length][0] * p[1]).Sum()) < 1000) + throw new RoomError("The circuit needs separated points, enough area and no crossing/touching edges."); + var ids = new HashSet(); + foreach (var d in s.Drivers) if (d is null || string.IsNullOrWhiteSpace(d.Id) || d.Id.Length > 80 || !ids.Add(d.Id) || + string.IsNullOrWhiteSpace(d.Name) || d.Name.Length > 24 || d.Color is null || !System.Text.RegularExpressions.Regex.IsMatch(d.Color, "^#[0-9a-fA-F]{6}$") || + !Range(d.PaceOffset, -10, 10) || d.PitLap is < 0 or > 10 || !Range(d.ServiceSeconds, 0, 15)) + throw new RoomError("Invalid driver settings or duplicate IDs."); + } + static double Distance(double[] a, double[] b) => Math.Sqrt(Math.Pow(a[0]-b[0], 2) + Math.Pow(a[1]-b[1], 2)); + static double[] Mix(double[] a, double[] b, double t) => [a[0]+(b[0]-a[0])*t, a[1]+(b[1]-a[1])*t]; + static double[] Curve(double[] a, double[] b, double[] c, double t) => Mix(Mix(a,b,t), Mix(b,c,t), t); + static double SegmentDistance(double[] p, double[] a, double[] b) { + var dx=b[0]-a[0]; var dy=b[1]-a[1]; var n=dx*dx+dy*dy; + var t=n>0?Math.Clamp(((p[0]-a[0])*dx+(p[1]-a[1])*dy)/n,0,1):0; + return Distance(p,[a[0]+dx*t,a[1]+dy*t]); + } + static double Cross(double[] a,double[] b,double[] c) => (b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]); + static bool Touch(double[] a,double[] b,double[] p) => Math.Abs(Cross(a,b,p))<1e-7 && p[0]>=Math.Min(a[0],b[0])-1e-7 && p[0]<=Math.Max(a[0],b[0])+1e-7 && p[1]>=Math.Min(a[1],b[1])-1e-7 && p[1]<=Math.Max(a[1],b[1])+1e-7; + static bool Intersects(double[] a,double[] b,double[] c,double[] d,bool touches) => + Cross(a,b,c)*Cross(a,b,d)<-1e-6 && Cross(c,d,a)*Cross(c,d,b)<-1e-6 || touches && (Touch(a,b,c)||Touch(a,b,d)||Touch(c,d,a)||Touch(c,d,b)); + static bool CrossesSelf(double[][] p,bool closed) { + for(var i=1;i p.Skip(1).Select((v,i)=>Distance(p[i],v)).Sum(); + static double[] At(double[][] p,double fraction) { + var target=Length(p)*fraction; + for(var i=1;i0?target/span:0);target-=span;} + return p[^1]; + } + static double[][] Rounded(double[][] p,double radius,bool closed) { + if(!closed){ + var path=new List{p[0]}; + for(var i=1;i{ + var previous=p[(i+p.Length-1)%p.Length];var next=p[(i+1)%p.Length]; + var clearance=Enumerable.Range(0,p.Length).Where(j=>j!=i&&(j+1)%p.Length!=i).Min(j=>SegmentDistance(v,p[j],p[(j+1)%p.Length])); + var trim=Math.Min(radius,Math.Min(80,Math.Min(Distance(v,previous)*.45,Math.Min(Distance(v,next)*.45,clearance*.45)))); + return (v,entry:Mix(v,previous,trim/Distance(v,previous)),exit:Mix(v,next,trim/Distance(v,next))); + }).ToArray(); + var result=new List{Curve(corners[0].entry,corners[0].v,corners[0].exit,.5)}; + for(var j=9;j<=16;j++)result.Add(Curve(corners[0].entry,corners[0].v,corners[0].exit,j/16.0)); + foreach(var c in corners.Skip(1)){result.Add(c.entry);for(var j=1;j<=16;j++)result.Add(Curve(c.entry,c.v,c.exit,j/16.0));} + result.Add(corners[0].entry);for(var j=1;j<8;j++)result.Add(Curve(corners[0].entry,corners[0].v,corners[0].exit,j/16.0)); + var clean=result.Where((v,i)=>i==0||Distance(v,result[i-1])>.0001).ToList(); + if(clean.Count>1&&Distance(clean[^1],clean[0])<.0001)clean.RemoveAt(clean.Count-1); + return clean.ToArray(); + } +} +public sealed class RoomError(string message) : Exception(message); diff --git a/backend/Pitwall.RoomChecks/Pitwall.RoomChecks.csproj b/backend/Pitwall.RoomChecks/Pitwall.RoomChecks.csproj new file mode 100644 index 0000000..d44eb3f --- /dev/null +++ b/backend/Pitwall.RoomChecks/Pitwall.RoomChecks.csproj @@ -0,0 +1,5 @@ + + Exenet10.0enableenabletrue + + + diff --git a/backend/Pitwall.RoomChecks/Program.cs b/backend/Pitwall.RoomChecks/Program.cs new file mode 100644 index 0000000..457c81c --- /dev/null +++ b/backend/Pitwall.RoomChecks/Program.cs @@ -0,0 +1,71 @@ +using System.Text.Json; +static void Check(bool value,string message){if(!value)throw new Exception(message);} +static void Reject(Action action,string text){try{action();throw new Exception("Expected rejection: "+text);}catch(RoomError e){Check(e.Message.Contains(text,StringComparison.OrdinalIgnoreCase),e.Message);}} +static void Near(double a,double b)=>Check(Math.Abs(a-b)<1e-7,$"Expected {a} ≈ {b}"); +var track=new CircuitSpec(1,"room-check","Shared test circuit",[[150,150],[400,150],[650,150],[650,370],[400,370],[150,370]],[2,4],0); +var setup=new RoomSetup(1,3,30,.92,.08,[[80,265],[80,80],[265,80]],[new("one","One","#ff665d",0,1,2.5),new("two","Two","#6d9fff",2,0,2.5)]); +var a=new RoomSimulation(track,setup);var b=new RoomSimulation(track,setup); +a.Advance(180);for(var i=0;i<1800;i++)b.Advance(.1); +foreach(var s in a.States){var other=b.States.Single(v=>v.Id==s.Id);Near(s.FinishTime!.Value,other.FinishTime!.Value);Check(s.Phase=="finished","Race did not finish");} +Near(a.States[1].FinishTime!.Value,3.006*32); +var frozen=a.Elapsed;a.Advance(100);Near(a.Elapsed,frozen); +var pit=new RoomSimulation(track,setup);pit.Call("one",false);pit.Advance(30);Near(pit.States[0].RaceProgress,1); +pit.Call("one",true);Near(pit.States[0].PitTarget!.Value,1.92); +pit.Advance(30);Check(pit.States[0].Phase is "pit" or "service","Live stop did not enter lane");Reject(()=>pit.Call("one",false),"committed"); +Reject(()=>new RoomSimulation(track,setup with{RaceLaps=0}),"valid"); +Reject(()=>new RoomSimulation(track,setup with{Drivers=[setup.Drivers[0],setup.Drivers[0]]}),"duplicate"); +var rooms=new RaceRooms();var host=rooms.Create(new("Host",track,setup));var guest=rooms.Join(host.Code,"Guest"); +var h=rooms.Attach("h",host.Code,host.Token);rooms.Attach("g",host.Code,guest.Token); +Reject(()=>rooms.Attach("bad",host.Code,"wrong"),"session"); +Reject(()=>rooms.Execute("g",new("start")),"host"); +Reject(()=>rooms.Execute("h",new("start")),"ready"); +var claims=0;Parallel.Invoke( + ()=>{try{rooms.Execute("h",new("claim","one"));Interlocked.Increment(ref claims);}catch(RoomError){}}, + ()=>{try{rooms.Execute("g",new("claim","one"));Interlocked.Increment(ref claims);}catch(RoomError){}}); +Check(claims==1,"Concurrent clients both claimed one driver"); +// Normalize ownership for permission, handover and reconnect checks. +rooms.Execute("h",new("release","one"));rooms.Execute("h",new("claim","one"));rooms.Execute("g",new("claim","two")); +Reject(()=>rooms.Execute("g",new("box","one")),"claimed driver"); +rooms.Execute("h",new("ready"));rooms.Execute("g",new("ready"));rooms.Execute("h",new("start")); +var updates=rooms.Advance(.5);Check(updates.Single().Elapsed>0,"Server clock did not advance"); +rooms.Execute("h",new("pause"));var paused=rooms.Advance(.5);Check(paused.Length==0,"Paused room advanced"); +rooms.Detach("g");var reconnect=rooms.Attach("g2",host.Code,guest.Token);Check(reconnect.Seats.Single(s=>s.DriverId=="two").PlayerId==guest.PlayerId,"Reconnect lost seat"); +rooms.Execute("g2",new("release","two"));rooms.Execute("h",new("handover","one",guest.PlayerId)); +Reject(()=>rooms.Execute("h",new("box","one")),"claimed driver");rooms.Execute("g2",new("box","one")); +var transferred=rooms.Execute("h",new("host",PlayerId:guest.PlayerId));Check(transferred.HostId==guest.PlayerId,"Host transfer failed"); +Reject(()=>rooms.Execute("h",new("reset")),"host");rooms.Execute("g2",new("reset")); +rooms.Execute("g2",new("leave"));Reject(()=>rooms.Attach("again",host.Code,guest.Token),"session"); +var extra=rooms.Join(host.Code,"Removable");rooms.Attach("extra",host.Code,extra.Token); +rooms.Execute("h",new("remove",PlayerId:extra.PlayerId)); +Reject(()=>rooms.Attach("extra-again",host.Code,extra.Token),"session"); +Reject(()=>rooms.Execute("extra",new("claim","two")),"Reconnect"); +Console.WriteLine("PASS: authoritative physics, frame invariance, finite results, live calls, validation, concurrent seat claims, host/driver permissions, reconnect, handover and leave."); +var jsonOptions=new JsonSerializerOptions{PropertyNamingPolicy=JsonNamingPolicy.CamelCase,WriteIndented=true}; +if(args.Length==2&&args[0]=="--write-fixture"){ + var fixtureTrack=track with{CornerRadius=28}; + var sim=new RoomSimulation(fixtureTrack,setup);var samples=new List(); + foreach(var seconds in new[]{28.0,4,4,4,5,35,100}){ + sim.Advance(seconds); + samples.Add(new{seconds,elapsed=sim.Elapsed,states=sim.States.Select(s=>s with{}).ToArray(),order=sim.Order()}); + } + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(args[1]))!); + File.WriteAllText(args[1],JsonSerializer.Serialize(new{track=fixtureTrack,setup,samples},jsonOptions)); +} +var fixturePath=Path.Combine(AppContext.BaseDirectory,"room-model.json"); +if(File.Exists(fixturePath)){ + using var fixture=JsonDocument.Parse(File.ReadAllText(fixturePath));var root=fixture.RootElement; + var sim=new RoomSimulation(root.GetProperty("track").Deserialize(jsonOptions)!,root.GetProperty("setup").Deserialize(jsonOptions)!); + foreach(var sample in root.GetProperty("samples").EnumerateArray()){ + sim.Advance(sample.GetProperty("seconds").GetDouble());Near(sim.Elapsed,sample.GetProperty("elapsed").GetDouble()); + foreach(var expected in sample.GetProperty("states").EnumerateArray()){ + var actual=sim.States.Single(s=>s.Id==expected.GetProperty("id").GetString()); + Near(actual.RaceProgress,expected.GetProperty("raceProgress").GetDouble()); + Near(actual.PitProgress,expected.GetProperty("pitProgress").GetDouble()); + Near(actual.StopRemaining,expected.GetProperty("stopRemaining").GetDouble()); + Check(actual.Phase==expected.GetProperty("phase").GetString(),"Shared model phase drift"); + Check(actual.Stops==expected.GetProperty("stops").GetInt32(),"Shared model stop count drift"); + if(actual.FinishTime.HasValue)Near(actual.FinishTime.Value,expected.GetProperty("finishTime").GetDouble()); + } + } + Console.WriteLine("PASS: shared browser/server model contract fixture."); +} diff --git a/data/testing/room-model.json b/data/testing/room-model.json new file mode 100644 index 0000000..63487be --- /dev/null +++ b/data/testing/room-model.json @@ -0,0 +1,331 @@ +{ + "track": { + "version": 1, + "id": "room-check", + "name": "Shared test circuit", + "points": [ + [ + 150, + 150 + ], + [ + 400, + 150 + ], + [ + 650, + 150 + ], + [ + 650, + 370 + ], + [ + 400, + 370 + ], + [ + 150, + 370 + ] + ], + "sectorEnds": [ + 2, + 4 + ], + "cornerRadius": 28 + }, + "setup": { + "version": 1, + "raceLaps": 3, + "baseLapSeconds": 30, + "entry": 0.92, + "exit": 0.08, + "pitControls": [ + [ + 80, + 265 + ], + [ + 80, + 80 + ], + [ + 265, + 80 + ] + ], + "drivers": [ + { + "id": "one", + "name": "One", + "color": "#ff665d", + "paceOffset": 0, + "pitLap": 1, + "serviceSeconds": 2.5 + }, + { + "id": "two", + "name": "Two", + "color": "#6d9fff", + "paceOffset": 2, + "pitLap": 0, + "serviceSeconds": 2.5 + } + ] + }, + "samples": [ + { + "seconds": 28, + "elapsed": 28, + "states": [ + { + "id": "one", + "raceProgress": 0.92, + "phase": "pit", + "pitProgress": 0.013491303965643416, + "stopRemaining": 0, + "serviced": false, + "visited": false, + "stops": 0, + "pitTarget": null, + "finishTime": null, + "finishedInPit": false + }, + { + "id": "two", + "raceProgress": 0.869, + "phase": "track", + "pitProgress": 0, + "stopRemaining": 0, + "serviced": false, + "visited": false, + "stops": 0, + "pitTarget": null, + "finishTime": null, + "finishedInPit": false + } + ], + "order": [ + "one", + "two" + ] + }, + { + "seconds": 4, + "elapsed": 32, + "states": [ + { + "id": "one", + "raceProgress": 0.92, + "phase": "pit", + "pitProgress": 0.14840434362207805, + "stopRemaining": 0, + "serviced": false, + "visited": false, + "stops": 0, + "pitTarget": null, + "finishTime": null, + "finishedInPit": false + }, + { + "id": "two", + "raceProgress": 0.994, + "phase": "track", + "pitProgress": 0, + "stopRemaining": 0, + "serviced": false, + "visited": false, + "stops": 0, + "pitTarget": null, + "finishTime": null, + "finishedInPit": false + } + ], + "order": [ + "two", + "one" + ] + }, + { + "seconds": 4, + "elapsed": 36, + "states": [ + { + "id": "one", + "raceProgress": 0.92, + "phase": "pit", + "pitProgress": 0.2833173832785127, + "stopRemaining": 0, + "serviced": false, + "visited": false, + "stops": 0, + "pitTarget": null, + "finishTime": null, + "finishedInPit": false + }, + { + "id": "two", + "raceProgress": 1.119, + "phase": "track", + "pitProgress": 0, + "stopRemaining": 0, + "serviced": false, + "visited": false, + "stops": 0, + "pitTarget": null, + "finishTime": null, + "finishedInPit": false + } + ], + "order": [ + "two", + "one" + ] + }, + { + "seconds": 4, + "elapsed": 40, + "states": [ + { + "id": "one", + "raceProgress": 0.92, + "phase": "pit", + "pitProgress": 0.41823042293494733, + "stopRemaining": 0, + "serviced": false, + "visited": false, + "stops": 0, + "pitTarget": null, + "finishTime": null, + "finishedInPit": false + }, + { + "id": "two", + "raceProgress": 1.244, + "phase": "track", + "pitProgress": 0, + "stopRemaining": 0, + "serviced": false, + "visited": false, + "stops": 0, + "pitTarget": null, + "finishTime": null, + "finishedInPit": false + } + ], + "order": [ + "two", + "one" + ] + }, + { + "seconds": 5, + "elapsed": 45, + "states": [ + { + "id": "one", + "raceProgress": 0.92, + "phase": "pit", + "pitProgress": 0.502551072720219, + "stopRemaining": 0, + "serviced": true, + "visited": false, + "stops": 0, + "pitTarget": null, + "finishTime": null, + "finishedInPit": false + }, + { + "id": "two", + "raceProgress": 1.40025, + "phase": "track", + "pitProgress": 0, + "stopRemaining": 0, + "serviced": false, + "visited": false, + "stops": 0, + "pitTarget": null, + "finishTime": null, + "finishedInPit": false + } + ], + "order": [ + "two", + "one" + ] + }, + { + "seconds": 35, + "elapsed": 80, + "states": [ + { + "id": "one", + "raceProgress": 1.7550424040586254, + "phase": "track", + "pitProgress": 1, + "stopRemaining": 0, + "serviced": true, + "visited": true, + "stops": 1, + "pitTarget": null, + "finishTime": null, + "finishedInPit": false + }, + { + "id": "two", + "raceProgress": 2.4939999999999998, + "phase": "track", + "pitProgress": 0, + "stopRemaining": 0, + "serviced": false, + "visited": false, + "stops": 0, + "pitTarget": null, + "finishTime": null, + "finishedInPit": false + } + ], + "order": [ + "two", + "one" + ] + }, + { + "seconds": 100, + "elapsed": 117.34872787824123, + "states": [ + { + "id": "one", + "raceProgress": 3, + "phase": "finished", + "pitProgress": 1, + "stopRemaining": 0, + "serviced": true, + "visited": true, + "stops": 1, + "pitTarget": null, + "finishTime": 117.34872787824123, + "finishedInPit": false + }, + { + "id": "two", + "raceProgress": 3, + "phase": "finished", + "pitProgress": 0, + "stopRemaining": 0, + "serviced": false, + "visited": false, + "stops": 0, + "pitTarget": null, + "finishTime": 96.19200000000001, + "finishedInPit": false + } + ], + "order": [ + "two", + "one" + ] + } + ] +} \ No newline at end of file diff --git a/docs/DEMO.md b/docs/DEMO.md index b6ff926..3c200c7 100644 --- a/docs/DEMO.md +++ b/docs/DEMO.md @@ -28,7 +28,7 @@ The next session increment also lets you choose **Race distance (laps)**, select ## Engineering evidence -- [Testing guide](TESTING.md): 65 frontend unit checks, nine Node checks, 46 browser scenarios, real API/database integration and dedicated concurrency checks. +- [Testing guide](TESTING.md): 66 frontend unit checks, nine Node checks, 49 browser scenarios, real API/database integration and dedicated storage/room concurrency checks. - [v1.3 architecture and limitations](V1.3.md): separate recorded/fictional state, independent enrichment, data quality and model assumptions. - `node scripts/benchmark-replay.mjs`: reproducible lookup-only comparison against v1.2 with correctness assertions. - GitHub Actions builds and tests the application and container; release branches publish an image. Hosting, accounts and multiplayer are later scope. diff --git a/docs/FOLLOW-UP-PLAN.md b/docs/FOLLOW-UP-PLAN.md index 80d70be..94df30a 100644 --- a/docs/FOLLOW-UP-PLAN.md +++ b/docs/FOLLOW-UP-PLAN.md @@ -47,6 +47,8 @@ v1.3 adds held-out pace-baseline evaluation: past-only training within the curre The first v1.4 increment implements finite fictional sessions (1–50 laps), deterministic finishing order/times, live selected-driver pit calls, cancellation before entry and repeat visits. See [the current sandbox guide](guide/05-race-sandbox.md). Next increments: explicit game-model tyre tradeoffs, a balanced upgrade budget, then complete session save/resume. These are planned; current setup saves do not restore runtime. +The private-room increment adds a server-owned C# simulation, SignalR guest connections, exclusive driver claims/readiness, shared host controls, live calls, spectator support, reconnect and explicit driver/host handover. See [multiplayer flows](guide/07-multiplayer.md). Room storage is in memory, independent of PostgreSQL; public hosting, durable room recovery and multiple-instance coordination remain future scope. + ## Branch and validation workflow Use a focused feature branch for each milestone, run timing/camera unit tests and browser tests, and review into `develop`. Promote to `master` once the integration branch is ready. Container delivery continues through the existing GitHub Actions workflow. diff --git a/docs/TESTING.md b/docs/TESTING.md index 4fa7c1c..4d0507d 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -6,7 +6,7 @@ Run `node scripts/check-docs.mjs` from the repository root. CI runs the same che When changing a flow, update its chapter and `docs/flows.json`, then run `node scripts/update-guide-index.mjs` and the checker. Follow [CONTRIBUTING](../CONTRIBUTING.md). Checks catch structural drift; reviewing the steps against actual behavior remains necessary. Documentation-only changes need this check, without repeating unrelated application suites locally. -## Playwright: 46 browser scenarios +## Playwright: 49 browser scenarios | Area | Coverage | | --- | --- | @@ -32,6 +32,7 @@ When changing a flow, update its chapter and `docs/flows.json`, then run `node s | Pace backtest | Past/holdout separation in exports, eligible-window search, invalid-window explanations, branch replay jumps, mobile layout | | Circuit race sandbox | Pit entry/service/exit, running order, driver settings, persistent setup/session export, pit validation and undo, keyboard handles, animation, tab isolation and storage/mobile recovery | | Race sessions and live calls | Exact finite-race results/frozen clock, reset/distance preservation, cancellation without resetting, entry commitment, next-lap targeting and selected-driver/mobile controls | +| Multiplayer | Two independent guest sessions, readiness, synchronized clock/results, live calls, reload/reconnect, driver/host handover, invalid invitations, mobile leave, real-hub concurrent claim conflicts, token/ownership/host checks, forged-time rejection and guest removal | | Sector map | Completed-reference alignment, saved layout preference, no invented coordinates during gaps, hidden markers before coverage or in estimate mode | | Tool loading | Studio bundle stays deferred until opened; a failed download returns to a usable replay | @@ -39,7 +40,8 @@ These scenarios run against the production frontend build in Chromium. Historica ## Other checks -- 65 Vitest checks cover replay timing and indexed boundary/seek behavior, track interpolation, map/layout preferences, recorded sample lookup and sector alignment, trails, share links, named layouts, geometry/rounding/import validation, deterministic strategy math, held-out pace evaluation, sandbox route/service transitions, setup migration, finish timing/frame invariance, result ordering, cancellation/repeat visits and pit-lane finishes. +- 66 Vitest checks cover replay timing and indexed boundary/seek behavior, track interpolation, map/layout preferences, recorded sample lookup and sector alignment, trails, share links, named layouts, geometry/rounding/import validation, deterministic strategy math, held-out pace evaluation, sandbox route/service transitions, setup migration, finish timing/frame invariance, result ordering, cancellation/repeat visits and pit-lane finishes. A committed shared fixture checks browser/server parity for rounded geometry, pit traversal/service/rejoin and finite results. +- `Pitwall.RoomChecks` checks authoritative room physics, frame invariance, validation, concurrent seat claims, host/driver authorization, reconnect, handover, guest removal and departure. It also consumes `data/testing/room-model.json`; fixture changes need review, rather than automatic regeneration to make a failure pass. - Nine Node tests cover catalog filtering, identifiers, location alignment/quality, measured-sector/pit normalization, local environment parsing, bounded ports and connection-string escaping. - `Pitwall.StoreChecks` verifies enrichment preservation, downgrade protection, concurrent writes, safe bundle seeding and bookmarks against both in-memory storage and PostgreSQL. It creates uniquely named test rows and removes only those rows. - Python integration checks cover the real API, input validation, race-specific bookmarks, SQL migrations, PostgreSQL restart persistence, and bundled trace ordering/bounds. A real cache upgrade was also checked against the development database to verify bookmark preservation. @@ -55,6 +57,7 @@ From the repository root: dotnet build backend/Pitwall.Api/Pitwall.Api.csproj -c Release node --test scripts/import-race.test.mjs scripts/local-tools.test.mjs dotnet run -c Release --project backend/Pitwall.StoreChecks +dotnet run -c Release --project backend/Pitwall.RoomChecks cd frontend npm ci npm test @@ -65,6 +68,8 @@ npm run test:e2e Playwright starts the API and production-preview server when they are absent. Locally it can reuse running servers; CI starts isolated ones with automatic provider refresh disabled. API integration checks are documented in the README. +To use a separately prepared preview without starting/reusing the default ports, set `$env:PITWALL_E2E_BASE_URL='http://127.0.0.1:5084'` to its actual address before invoking Playwright. Use an isolated snapshot/test server for checks, not a friend's running room or personal database. Clear this variable to restore the default harness. SignalR/WebSocket proxying is configured for both Vite development and preview. + ## Inspect failures ```powershell diff --git a/docs/USER-GUIDE.md b/docs/USER-GUIDE.md index 0329dac..36491f2 100644 --- a/docs/USER-GUIDE.md +++ b/docs/USER-GUIDE.md @@ -14,6 +14,7 @@ This is the current handbook for what each flow does, how to use it, what is sav 4. [Design and save a fictional circuit](guide/04-circuit-studio.md). 5. [Configure drivers and pit stops in the race sandbox](guide/05-race-sandbox.md). 6. [Understand storage, maintenance and guide updates](guide/06-maintenance.md). +7. [Host, join and hand over a private multiplayer race](guide/07-multiplayer.md). Each flow has a stable ID, a **What**, **How**, **Result and storage**, and **Recovery and limits** section. Use these IDs in issues and pull requests instead of relying on a screenshot or an old chat. @@ -27,6 +28,7 @@ Each flow has a stable ID, a **What**, **How**, **Result and storage**, and **Re | How well do past-only pace baselines match later laps? | Pace forecast backtest | Held-out pace evaluation, not proof of an unobserved pit decision | | Can I design my own circuit? | Custom circuit studio → Circuit editor | Fictional geometry, separate from real replays | | Can I run a custom grid with scheduled stops? | Circuit race sandbox | Fictional pace/route/service animation | +| Can friends control drivers in the same race? | Multiplayer rooms | One server-owned fictional race with guest driver ownership | ```mermaid flowchart LR @@ -38,6 +40,7 @@ flowchart LR Replay --> Backtest[Held-out pace evaluation] Replay --> Editor[Fictional circuit editor] Editor --> Sandbox[Driver and pit sandbox] + Sandbox --> Room[Private multiplayer room] ``` ![Recorded race analysis desk](images/v1.3-analysis.png) @@ -56,6 +59,7 @@ Saving to PostgreSQL, saving in your browser and downloading a file are differen | Strategy/backtest/analysis JSON or analysis CSV | No dedicated importer | Inspection/export artifacts | | Combined sandbox session JSON | No session importer yet | Contains geometry/setup/runtime for inspection | | Share link | Yes, if its server/session is available | Encodes replay settings, not private saves or custom workspaces | +| Multiplayer room | Reconnect while that API process retains it | Guest token in tab session storage; rooms are in server memory even with PostgreSQL | Closing a studio or scenario without saving can lose its draft. Clearing browser data, changing browser/profile, or using another hostname/port can change which browser saves you see. A normal database-backed API restart does not erase server caches/bookmarks. @@ -77,7 +81,7 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser -68 documented flows. Each ID links directly to its instructions. +76 documented flows. Each ID links directly to its instructions. ### Start Pitwall and choose a race @@ -176,6 +180,19 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser | [OPS-03](guide/06-maintenance.md#ops-03) | Publish branches and verify CI | | [OPS-04](guide/06-maintenance.md#ops-04) | Restart, update or recover the running app | | [OPS-05](guide/06-maintenance.md#ops-05) | Update this guide with each behavior change | + +### Private multiplayer races + +| Flow | What you can do | +| --- | --- | +| [ROOM-01](guide/07-multiplayer.md#room-01) | Create a private race room | +| [ROOM-02](guide/07-multiplayer.md#room-02) | Invite friends and join as a guest | +| [ROOM-03](guide/07-multiplayer.md#room-03) | Claim a driver, spectate and get ready | +| [ROOM-04](guide/07-multiplayer.md#room-04) | Make shared live pit decisions | +| [ROOM-05](guide/07-multiplayer.md#room-05) | Control the race as host | +| [ROOM-06](guide/07-multiplayer.md#room-06) | Hand over a driver without resetting | +| [ROOM-07](guide/07-multiplayer.md#room-07) | Reconnect, leave and remove guests | +| [ROOM-08](guide/07-multiplayer.md#room-08) | Run a two-player trial and prepare outside access | ## How this stays current diff --git a/docs/flows.json b/docs/flows.json index f836c6f..c1ec25a 100644 --- a/docs/flows.json +++ b/docs/flows.json @@ -26,6 +26,10 @@ { "path": "docs/guide/06-maintenance.md", "title": "Storage, validation and keeping the guide current" + }, + { + "path": "docs/guide/07-multiplayer.md", + "title": "Private multiplayer races" } ], "sharedComponents": [ @@ -762,6 +766,142 @@ "frontend/src/sandbox.test.ts", "frontend/e2e/sandbox.spec.ts" ] + }, + { + "id": "ROOM-01", + "title": "Create a private race room", + "guide": "docs/guide/07-multiplayer.md", + "anchor": "room-01", + "sources": [ + "frontend/src/MultiplayerRooms.tsx", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/vite.config.ts", + "backend/Pitwall.Api/RaceRooms.cs", + "backend/Pitwall.Api/RoomSimulation.cs", + "backend/Pitwall.Api/Program.cs", + "backend/Pitwall.RoomChecks/Program.cs", + "frontend/e2e/multiplayer.spec.ts" + ] + }, + { + "id": "ROOM-02", + "title": "Invite friends and join as a guest", + "guide": "docs/guide/07-multiplayer.md", + "anchor": "room-02", + "sources": [ + "frontend/src/MultiplayerRooms.tsx", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/vite.config.ts", + "backend/Pitwall.Api/RaceRooms.cs", + "backend/Pitwall.Api/RoomSimulation.cs", + "backend/Pitwall.Api/Program.cs", + "backend/Pitwall.RoomChecks/Program.cs", + "frontend/e2e/multiplayer.spec.ts" + ] + }, + { + "id": "ROOM-03", + "title": "Claim a driver, spectate and get ready", + "guide": "docs/guide/07-multiplayer.md", + "anchor": "room-03", + "sources": [ + "frontend/src/MultiplayerRooms.tsx", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/vite.config.ts", + "backend/Pitwall.Api/RaceRooms.cs", + "backend/Pitwall.Api/RoomSimulation.cs", + "backend/Pitwall.Api/Program.cs", + "backend/Pitwall.RoomChecks/Program.cs", + "frontend/e2e/multiplayer.spec.ts" + ] + }, + { + "id": "ROOM-04", + "title": "Make shared live pit decisions", + "guide": "docs/guide/07-multiplayer.md", + "anchor": "room-04", + "sources": [ + "frontend/src/MultiplayerRooms.tsx", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/vite.config.ts", + "backend/Pitwall.Api/RaceRooms.cs", + "backend/Pitwall.Api/RoomSimulation.cs", + "backend/Pitwall.Api/Program.cs", + "backend/Pitwall.RoomChecks/Program.cs", + "frontend/e2e/multiplayer.spec.ts" + ] + }, + { + "id": "ROOM-05", + "title": "Control the race as host", + "guide": "docs/guide/07-multiplayer.md", + "anchor": "room-05", + "sources": [ + "frontend/src/MultiplayerRooms.tsx", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/vite.config.ts", + "backend/Pitwall.Api/RaceRooms.cs", + "backend/Pitwall.Api/RoomSimulation.cs", + "backend/Pitwall.Api/Program.cs", + "backend/Pitwall.RoomChecks/Program.cs", + "frontend/e2e/multiplayer.spec.ts" + ] + }, + { + "id": "ROOM-06", + "title": "Hand over a driver without resetting", + "guide": "docs/guide/07-multiplayer.md", + "anchor": "room-06", + "sources": [ + "frontend/src/MultiplayerRooms.tsx", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/vite.config.ts", + "backend/Pitwall.Api/RaceRooms.cs", + "backend/Pitwall.Api/RoomSimulation.cs", + "backend/Pitwall.Api/Program.cs", + "backend/Pitwall.RoomChecks/Program.cs", + "frontend/e2e/multiplayer.spec.ts" + ] + }, + { + "id": "ROOM-07", + "title": "Reconnect, leave and remove guests", + "guide": "docs/guide/07-multiplayer.md", + "anchor": "room-07", + "sources": [ + "frontend/src/MultiplayerRooms.tsx", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/vite.config.ts", + "backend/Pitwall.Api/RaceRooms.cs", + "backend/Pitwall.Api/RoomSimulation.cs", + "backend/Pitwall.Api/Program.cs", + "backend/Pitwall.RoomChecks/Program.cs", + "frontend/e2e/multiplayer.spec.ts" + ] + }, + { + "id": "ROOM-08", + "title": "Run a two-player trial and prepare outside access", + "guide": "docs/guide/07-multiplayer.md", + "anchor": "room-08", + "sources": [ + "frontend/src/MultiplayerRooms.tsx", + "frontend/src/App.tsx", + "frontend/src/CircuitSandbox.tsx", + "frontend/vite.config.ts", + "backend/Pitwall.Api/RaceRooms.cs", + "backend/Pitwall.Api/RoomSimulation.cs", + "backend/Pitwall.Api/Program.cs", + "backend/Pitwall.RoomChecks/Program.cs", + "frontend/e2e/multiplayer.spec.ts" + ] } ] } diff --git a/docs/guide/06-maintenance.md b/docs/guide/06-maintenance.md index 238e614..f0ab8a7 100644 --- a/docs/guide/06-maintenance.md +++ b/docs/guide/06-maintenance.md @@ -17,6 +17,7 @@ | Theme/default map/named map layouts | Browser only | Browser only | Hostname + port + scheme + browser/profile | | Saved circuits/sandbox setups/strategy scenarios | Browser only | Browser only | Same origin isolation | | Unsaved drafts, tool selections, simulation clock | Current page/tool session | Current page/tool session | Not automatically restored | +| Multiplayer rooms/shared race clock | API process memory; lost on restart | API process memory; lost on restart | Guest credential in tab session storage, no token in invitation | | Exported files | Download location you choose | Download location you choose | Not automatically re-imported | **Result and storage:** `localhost:5080`, `127.0.0.1:5080`, `localhost:5173` and `localhost:8080` are different browser origins. They can expose the same database while showing different browser-only saves. Different browsers/profiles are isolated too. diff --git a/docs/guide/07-multiplayer.md b/docs/guide/07-multiplayer.md new file mode 100644 index 0000000..06727f2 --- /dev/null +++ b/docs/guide/07-multiplayer.md @@ -0,0 +1,93 @@ +# Private multiplayer races + +[Guide home](../USER-GUIDE.md) · [Local sandbox](05-race-sandbox.md) · [Storage](06-maintenance.md) + +Rooms run a shared fictional race on the C# server. This is separate from historical replay and from the local sandbox. SignalR delivers snapshots; browsers send decisions rather than positions or time. + + +## ROOM-01 — Create a private race room + +**What:** Host a shared copy of a fictional circuit and setup. + +**How:** Open **Multiplayer rooms** in the replay toolbar. Enter **Guest name**, optionally choose a saved circuit, then **Create private room**. To use a draft and its current driver/pit/distance settings, open **Custom circuit studio → Circuit race sandbox → Host this setup with friends** instead. Creating from the main toolbar uses the starter circuit or the selected circuit's browser-saved setup. + +**Result and storage:** The server validates and freezes the room's geometry/setup. Subsequent local edits do not change that room. You become host; no driver is automatically claimed. The local sandbox pauses when opening its room panel. Room creation does not save a circuit or overwrite the local run. + +**Recovery and limits:** Invalid geometry/settings reject creation. Rooms allow 1–6 driver seats, twelve guests including spectators/offline guests, and 32 rooms per API process. Create/join requests are limited to twenty per minute per IP. A rejected request leaves the existing editor/replay intact; retry after the stated error or limit clears. Guest names are 1–24 characters, independent of driver names. + + +## ROOM-02 — Invite friends and join as a guest + +**What:** Join one shared race from separate browser sessions. + +**How:** Copy **Invite friends**, or send the twelve-character room code. The invitation opens the room panel automatically. Enter a guest name and **Join room**. Alternatively open the toolbar's room panel and enter its **Room code**. Wait for **Connected** before making decisions. + +**Result and storage:** The server issues a private guest token, stored in this tab's session storage. Invitation URLs contain only the room code. A new guest begins as a spectator and sees current state, including an already-running or finished race. The same guest name can belong to different people; the server uses IDs/tokens for identity. + +**Recovery and limits:** An invitation is access to this private room; anyone holding it can join while capacity permits. An unavailable/expired room shows an error and allows creating another. A localhost invitation works only on the host computer. For two local players, use separate browsers/profiles or fresh tabs without a copied guest session. Duplicating a tab can clone its session storage and therefore its guest identity. + + +## ROOM-03 — Claim a driver, spectate and get ready + +**What:** Reserve exclusive control of a driver while sharing the race with others. + +**How:** Choose **Claim [driver]**, then **Ready to race**. All claimed drivers must be connected and ready before the host can **Start shared race**. **Not ready** reverses readiness in the lobby. Leave all seats unclaimed to spectate. + +**Result and storage:** A guest owns at most one seat; claiming another free driver releases the previous seat and clears readiness. Concurrent claims are serialized by the server: exactly one wins. Unclaimed drivers still follow their configured pace and scheduled stops. You may claim a free seat mid-race and take over its current state; mid-race resume does not require another ready check. + +**Recovery and limits:** Claimed seats cannot be stolen. Ask the owner/host to release or hand over one. Disconnected guests keep their seats until they reconnect, explicitly leave, or the host releases/removes them. The host receives a clear error if starting before the readiness requirements are met. Setup edits are unavailable inside a room; create a new room for a different setup. + + +## ROOM-04 — Make shared live pit decisions + +**What:** Make pit calls for your driver in one authoritative race. + +**How:** Under **Your strategy**, use **Box this lap** or **Box next lap**, and **Cancel shared pit call** before entry. Read the queued lap or committed phase. Spectators must claim a driver first. + +**Result and storage:** The server advances one clock and validates ownership and entry timing. Every guest receives the same order, pit state and exact finishing times. Calls preserve the shared clock and other cars. Repeated visits use the configured service duration. Race distance and mapped pit-lane finishes follow [SANDBOX-08](05-race-sandbox.md#sandbox-08); every driver completes the full distance. + +**Recovery and limits:** Pit/service and finished states lock calls. Calls after entry target the next eligible lap; no remaining entry disables the action. Connection loss locks controls while showing the last received snapshot. Decisions are acknowledged once and are not automatically replayed after a reconnect; check the returned authoritative state if a connection drops during a call. The server caps decision bursts at twenty per second per guest. + + +## ROOM-05 — Control the race as host + +**What:** Start, pause, resume, reset and change shared speed. + +**How:** Use **Start shared race**, **Pause shared race**, **Resume shared race**, **Reset shared race**, and **Shared speed** (1×/5×/10×/25×). To appoint a new host, select a connected **Handover recipient**, then **Transfer host role**. + +**Result and storage:** Host controls affect every guest. Reset pauses at the grid, clears pit decisions/visits/results and readiness, reinstates configured scheduled stops, and keeps current seat ownership. Host transfer retains the race and removes the previous host's host-only controls. Final results and clock freeze once all drivers finish. + +**Recovery and limits:** The server rejects host commands from other players even if they bypass the UI. Disconnecting reserves the host role for reconnect; it does not automatically promote another guest. Transfer before an intended handoff, or reconnect to manage the room. Ordinary simulation updates are about ten per second; prolonged server stalls can slow the game clock rather than jump ahead. + + +## ROOM-06 — Hand over a driver without resetting + +**What:** Let another guest take over an existing car during a race. + +**How:** Select a connected **Handover recipient**, then **Hand over [driver]**. The owner can hand over its own seat; the host can hand over or **Release [driver]** for any seat. The recipient must release its existing driver first. + +**Result and storage:** Position, elapsed clock, pit commitment, queued call, completed stops and finish result stay with the driver. Ownership changes atomically. The previous owner becomes a spectator and loses permission to make that driver's pit calls immediately. + +**Recovery and limits:** Offline recipients and guests already owning another seat are rejected. A handover does not cancel a committed pit visit or restart the race. Host role and driver ownership are separate; transfer both explicitly if required. + + +## ROOM-07 — Reconnect, leave and remove guests + +**What:** Recover a guest identity or deliberately release it. + +**How:** Reopen the room panel or refresh the same tab to restore its saved guest token. Temporary network loss triggers automatic reconnect attempts; after those stop, use **Reconnect room**. **Leave room and release seat** removes your membership. The host's **Remove [guest]** releases its seat and invalidates its token, including other connected tabs using it. + +**Result and storage:** Reconnect fetches a full current snapshot and restores host/driver rights without resetting the race. Closing the panel disconnects but reserves membership; the server race continues. Explicit host departure promotes a remaining connected guest first, otherwise another remaining guest. Leaving the final membership deletes the room. Rooms expire after two hours without connected guests or decisions. API restarts lose all rooms in both database and snapshot modes. + +**Recovery and limits:** Browser session storage is scoped to a tab and origin. If it is blocked, a warning says to keep the tab open; after losing the token, join as a new guest and ask the host to release/remove the old membership. **Forget guest session** clears only this tab's credential; it does not remove an unreachable server membership. Removed/left tokens cannot reconnect. There is no account recovery, room save/resume or durable room history yet. + + +## ROOM-08 — Run a two-player trial and prepare outside access + +**What:** Separate local multiplayer testing from public hosting. + +**How:** Locally, create a room in one browser, open its invite in a fresh second browser/profile, claim different drivers, mark both ready, and start. Watch both clocks/order, try a pit call, refresh one guest, then test a handover. Keep both using the same server address. For a prepared isolated test preview, set `PITWALL_E2E_BASE_URL` before Playwright; otherwise the standard test configuration starts its own servers. + +**Result and storage:** The same API process owns every room's time/state. The Docker image includes the room service. Development/preview proxies forward the SignalR endpoint and WebSockets. A public host needs an HTTPS address and reverse proxy supporting SignalR traffic/WebSocket upgrades; local loopback bindings alone are not accessible to friends on other computers. + +**Recovery and limits:** Public deployment is not configured by creating a room. Run one API instance for this prototype; adding replicas without shared room coordination splits races. PostgreSQL does not preserve these in-memory rooms. Platform restarts/redeploys end races, so do them between sessions. Hosting/domain/provider setup remains a separate deployment step. See the [official SignalR client reference](https://learn.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-10.0) for transport/reconnect details. diff --git a/frontend/e2e/multiplayer.spec.ts b/frontend/e2e/multiplayer.spec.ts new file mode 100644 index 0000000..fe01bbc --- /dev/null +++ b/frontend/e2e/multiplayer.spec.ts @@ -0,0 +1,110 @@ +import { test, expect } from "@playwright/test"; +import { HubConnectionBuilder, LogLevel } from "@microsoft/signalr"; +import { newTrack } from "../src/custom-track"; +import { sandboxDefaults } from "../src/sandbox"; + +test("two guests share one server race, reconnect, hand over control and finish together", async ({page, browser, baseURL}) => { + const other = await browser.newContext({baseURL}); + const guest = await other.newPage(); + try { + await page.goto("/?race=monza-2024&t=120"); + await page.getByRole("button", {name:"Custom circuit studio",exact:true}).click(); + await page.getByRole("button", {name:"Circuit race sandbox",exact:true}).click(); + await page.getByLabel("Sandbox driver count").selectOption("2"); + await page.getByLabel("Race distance laps",{exact:true}).fill("2"); + await page.getByLabel("Sandbox base lap seconds",{exact:true}).fill("30"); + await page.getByRole("button",{name:"Host this setup with friends",exact:true}).click(); + const host = page.getByRole("dialog",{name:"Multiplayer rooms",exact:true}); + await host.getByLabel("Guest name",{exact:true}).fill("Alpha"); + await host.getByRole("button",{name:"Create private room",exact:true}).click(); + await expect(host.getByRole("status",{exact:true})).toHaveText("Connected"); + const code = await host.getByTestId("room-code").innerText(); + await guest.goto(`/?room=${code}`); + const join = guest.getByRole("dialog",{name:"Multiplayer rooms",exact:true}); + await join.getByLabel("Guest name",{exact:true}).fill("Bravo"); + await join.getByRole("button",{name:"Join room",exact:true}).click(); + await expect(join.getByRole("status",{exact:true})).toHaveText("Connected"); + await host.getByRole("button",{name:"Claim Driver 1",exact:true}).click(); + await join.getByRole("button",{name:"Claim Driver 2",exact:true}).click(); + await host.getByRole("button",{name:"Start shared race",exact:true}).click(); + await expect(host.getByRole("alert")).toContainText("ready"); + await host.getByRole("button",{name:"Cancel shared pit call",exact:true}).click(); + await host.getByRole("button",{name:"Ready to race",exact:true}).click(); + await join.getByRole("button",{name:"Ready to race",exact:true}).click(); + await host.getByRole("button",{name:"Start shared race",exact:true}).click(); + await expect(host.getByTestId("room-clock")).not.toHaveText("00:00:00"); + await host.getByRole("button",{name:"Pause shared race",exact:true}).click(); + const clock = await host.getByTestId("room-clock").innerText(); + await expect(join.getByTestId("room-clock")).toHaveText(clock); + await join.getByRole("button",{name:/Box (this|next) lap/}).click(); + await expect(join.getByTestId("room-pit-status")).toContainText("queued"); + await join.getByRole("button",{name:"Cancel shared pit call",exact:true}).click(); + await expect(join.getByTestId("room-pit-status")).toContainText("Stay out"); + await guest.reload(); + await expect(join.getByRole("status",{exact:true})).toHaveText("Connected"); + await expect(join.getByRole("heading",{name:"Your strategy · Driver 2",exact:true})).toBeVisible(); + await expect(join.getByTestId("room-clock")).toHaveText(clock); + await join.getByRole("button",{name:"Release Driver 2",exact:true}).click(); + await host.getByLabel("Handover recipient").selectOption({label:"Bravo"}); + await host.getByRole("button",{name:"Hand over Driver 1",exact:true}).click(); + await expect(host.getByRole("heading",{name:"Your strategy · Spectating",exact:true})).toBeVisible(); + await expect(join.getByRole("heading",{name:"Your strategy · Driver 1",exact:true})).toBeVisible(); + await expect(host.getByRole("button",{name:"Box this lap",exact:true})).toBeDisabled(); + await host.getByRole("button",{name:"Transfer host role",exact:true}).click(); + await expect(join.getByRole("button",{name:"Resume shared race",exact:true})).toBeVisible(); + await join.getByLabel("Shared race speed").selectOption("25"); + await join.getByRole("button",{name:"Resume shared race",exact:true}).click(); + await expect(join.getByRole("heading",{name:"Final results",exact:true})).toBeVisible({timeout:15000}); + await expect(host.getByRole("heading",{name:"Final results",exact:true})).toBeVisible(); + await expect(join.getByLabel("Shared running order")).toHaveText(await host.getByLabel("Shared running order").innerText(), {useInnerText:true}); + await expect(join.getByTestId("room-clock")).toHaveText(await host.getByTestId("room-clock").innerText()); + await join.getByRole("button",{name:"Reset shared race",exact:true}).click(); + await expect(host.getByTestId("room-clock")).toHaveText("00:00:00"); + } finally { await other.close(); } +}); + +test("the real room hub rejects forged control, duplicate seat claims and invalid guest tokens", async ({request, baseURL}) => { + const track=newTrack(), setup=sandboxDefaults(track); + const created=await request.post("/api/rooms",{data:{name:"Wire host",track,setup}}); + expect(created.ok()).toBe(true); + const host=await created.json(); + const guest=await (await request.post(`/api/rooms/${host.code}/join`,{data:{name:"Wire guest"}})).json(); + const h=new HubConnectionBuilder().withUrl(`${baseURL}/api/rooms/live`).configureLogging(LogLevel.None).build(); + const g=new HubConnectionBuilder().withUrl(`${baseURL}/api/rooms/live`).configureLogging(LogLevel.None).build(); + try { + await Promise.all([h.start(),g.start()]); + await expect(g.invoke("Enter",host.code,"invalid")).rejects.toThrow(/session/); + const initial=await h.invoke("Enter",host.code,host.token); + await g.invoke("Enter",host.code,guest.token); + expect(JSON.stringify(initial)).not.toContain(host.token); + await expect(g.invoke("Decide",{action:"start"})).rejects.toThrow(/host/); + const claims=await Promise.allSettled([h.invoke("Decide",{action:"claim",driverId:setup.drivers[0].id}),g.invoke("Decide",{action:"claim",driverId:setup.drivers[0].id})]); + expect(claims.filter(r=>r.status==="fulfilled")).toHaveLength(1); + await h.invoke("Decide",{action:"release",driverId:setup.drivers[0].id}); + await h.invoke("Decide",{action:"claim",driverId:setup.drivers[0].id}); + await expect(g.invoke("Decide",{action:"box",driverId:setup.drivers[0].id})).rejects.toThrow(/claimed driver/); + await expect(g.invoke("Decide",{action:"reset"})).rejects.toThrow(/host/); + await expect(g.invoke("Decide",{action:"advance",elapsed:99999,positions:[]})).rejects.toThrow(/Unknown/); + const unchanged=await h.invoke("Decide",{action:"pause"}); + expect(unchanged.elapsed).toBe(0); + await h.invoke("Decide",{action:"remove",playerId:guest.playerId}); + await expect(g.invoke("Decide",{action:"claim",driverId:setup.drivers[1].id})).rejects.toThrow(/Reconnect/); + await h.invoke("Decide",{action:"leave"}); + await expect(h.invoke("Decide",{action:"box",driverId:setup.drivers[0].id})).rejects.toThrow(/Reconnect/); + } finally { await Promise.all([h.stop(),g.stop()]); } +}); + +test("room invitations fail clearly and mobile guests can join, leave and release their seat", async ({page}) => { + await page.setViewportSize({width:390,height:844}); + await page.goto("/?room=000000000000"); + const panel=page.getByRole("dialog",{name:"Multiplayer rooms",exact:true}); + await panel.getByLabel("Guest name",{exact:true}).fill("Mobile"); + await panel.getByRole("button",{name:"Join room",exact:true}).click(); + await expect(panel.getByRole("alert")).toContainText("unavailable"); + await panel.getByRole("button",{name:"Create private room",exact:true}).click(); + await expect(panel.getByRole("status",{exact:true})).toHaveText("Connected"); + await panel.getByRole("button",{name:"Claim Driver 1",exact:true}).click(); + expect(await panel.evaluate(e=>e.scrollWidth<=e.clientWidth)).toBe(true); + await panel.getByRole("button",{name:"Leave room and release seat",exact:true}).click(); + await expect(panel.getByRole("button",{name:"Create private room",exact:true})).toBeVisible(); +}); diff --git a/frontend/package-lock.json b/frontend/package-lock.json index cac98a8..e3bf5d6 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -8,6 +8,7 @@ "name": "pitwall-web", "version": "1.3.0", "dependencies": { + "@microsoft/signalr": "^10.0.11", "lucide-react": "^0.468.0", "react": "^19.3.1", "react-dom": "^19.3.1" @@ -797,6 +798,19 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@microsoft/signalr": { + "version": "10.0.11", + "resolved": "https://registry.npmjs.org/@microsoft/signalr/-/signalr-10.0.11.tgz", + "integrity": "sha512-FulOJ2EEtKvLQcswe/U7v8pzyXyk7Jua5xgWJPPwyQU/2Z9ORvKcVjyO75VvLsem+CJ1ORRexJ+7Bz1FCei2aw==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "eventsource": "^2.0.2", + "fetch-cookie": "^2.0.3", + "node-fetch": "^2.6.7", + "ws": "^7.5.10" + } + }, "node_modules/@playwright/test": { "version": "1.65.1", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.1.tgz", @@ -1464,6 +1478,18 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -1660,6 +1686,24 @@ "@types/estree": "^1.0.0" } }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/eventsource": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-2.0.2.tgz", + "integrity": "sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/expect-type": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", @@ -1688,6 +1732,16 @@ } } }, + "node_modules/fetch-cookie": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/fetch-cookie/-/fetch-cookie-2.2.0.tgz", + "integrity": "sha512-h9AgfjURuCgA2+2ISl8GbavpUdR+WGAM2McW/ovn4tVccegp8ZqCKWSBR8uRdM8dDNlx5WdKRWxBYUwteLDCNQ==", + "license": "Unlicense", + "dependencies": { + "set-cookie-parser": "^2.4.8", + "tough-cookie": "^4.0.0" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -1801,6 +1855,26 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, "node_modules/node-releases": { "version": "2.0.64", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.64.tgz", @@ -1910,6 +1984,33 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/psl": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz", + "integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "funding": { + "url": "https://github.com/sponsors/lupomontero" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", + "license": "MIT" + }, "node_modules/react": { "version": "19.3.1", "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", @@ -1941,6 +2042,12 @@ "node": ">=0.10.0" } }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "license": "MIT" + }, "node_modules/rollup": { "version": "4.68.3", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.3.tgz", @@ -2003,6 +2110,12 @@ "semver": "bin/semver.js" } }, + "node_modules/set-cookie-parser": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.3.tgz", + "integrity": "sha512-irZHtTqurLna57KQG/s+fzOwv/J6XSH4cs8M/vsrY3uCaQ3S6+QJguAH0WdN47SXlk82voMZ4naWMQf8fdEoIg==", + "license": "MIT" + }, "node_modules/siginfo": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", @@ -2078,6 +2191,27 @@ "node": ">=14.0.0" } }, + "node_modules/tough-cookie": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", + "integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==", + "license": "BSD-3-Clause", + "dependencies": { + "psl": "^1.1.33", + "punycode": "^2.1.1", + "universalify": "^0.2.0", + "url-parse": "^1.5.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -2099,6 +2233,15 @@ "dev": true, "license": "MIT" }, + "node_modules/universalify": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", + "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", + "license": "MIT", + "engines": { + "node": ">= 4.0.0" + } + }, "node_modules/update-browserslist-db": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", @@ -2130,6 +2273,16 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/url-parse": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", + "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", + "license": "MIT", + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, "node_modules/vite": { "version": "7.3.8", "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.8.tgz", @@ -2295,6 +2448,22 @@ } } }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, "node_modules/why-is-node-running": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", @@ -2312,6 +2481,27 @@ "node": ">=8" } }, + "node_modules/ws": { + "version": "7.5.14", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.14.tgz", + "integrity": "sha512-u9Oi2nQ8SZnTUAf6spLLKF5TyqoG3Nbbrd4ai6Sjo4P24bycDewhQqtNMIg4bFpnpH/TD4qk4IuAVhT0HIIqug==", + "license": "MIT", + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index ee84edb..003749a 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -11,9 +11,10 @@ "preview": "vite preview --configLoader native --host 127.0.0.1" }, "dependencies": { + "@microsoft/signalr": "^10.0.11", + "lucide-react": "^0.468.0", "react": "^19.3.1", - "react-dom": "^19.3.1", - "lucide-react": "^0.468.0" + "react-dom": "^19.3.1" }, "devDependencies": { "@playwright/test": "^1.56.1", diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index a8880ee..f258775 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -1,16 +1,17 @@ import { defineConfig } from "@playwright/test"; +const preparedPreview = process.env.PITWALL_E2E_BASE_URL; export default defineConfig({ testDir: "./e2e", fullyParallel: false, workers: 1, reporter: [["list"], ["html", { open: "never" }]], use: { - baseURL: "http://127.0.0.1:5173", + baseURL: preparedPreview ?? "http://127.0.0.1:5173", trace: "retain-on-failure", screenshot: "only-on-failure", video: "retain-on-failure", }, - webServer: [ + webServer: preparedPreview ? undefined : [ { command: "dotnet run --no-build -c Release --project ../backend/Pitwall.Api --urls http://127.0.0.1:5080", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1c48b1c..5533191 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -47,6 +47,7 @@ const TrackEditor = lazy(() => import("./TrackEditor")); const StrategyLab = lazy(() => import("./StrategyLab")); const RaceAnalysis = lazy(() => import("./RaceAnalysis")); const PaceBacktest = lazy(() => import("./PaceBacktest")); +const MultiplayerRooms = lazy(() => import("./MultiplayerRooms")); import "./lab.css"; import { momentLink, readMoment } from "./replay-link"; import { ensureTiming } from "./import-job"; @@ -89,7 +90,8 @@ function App() { const [showStrategy, setShowStrategy] = useState(false); const [showAnalysis, setShowAnalysis] = useState(false); const [showBacktest, setShowBacktest] = useState(false); - const activeTool = showLibrary + const [showRooms, setShowRooms] = useState(() => new URLSearchParams(location.search).has("room")); + const activeTool = showRooms ? "rooms" : showLibrary ? "library" : shareLink ? "share" @@ -103,6 +105,7 @@ function App() { ? "backtest" : "none"; const closeTools = () => { + setShowRooms(false); setShowLibrary(false); setShareLink(null); setShowTrackEditor(false); @@ -189,6 +192,7 @@ function App() { showStrategy || showAnalysis || showBacktest || + showRooms || document.querySelector("dialog[open]") ) return; @@ -217,6 +221,7 @@ function App() { showStrategy, showAnalysis, showBacktest, + showRooms, ]); useEffect(() => { if (!notice) return; @@ -414,6 +419,7 @@ function App() {
REPLAY TOOLS +
+ + {showRoom && Loading multiplayer…

}> setShowRoom(false)} />
}