Refactor world simulation and API to enhance world state management; introduce StoredWorldDto for internal bookkeeping, improve synchronization between simulation and API data, and implement new simulation options for idle and catch-up behavior. Update documentation to reflect changes in data structures and API endpoints.

This commit is contained in:
Leonid Pershin
2026-08-16 23:28:29 +03:00
parent 2a8b7b49b3
commit cb5117edba
23 changed files with 639 additions and 121 deletions
@@ -43,6 +43,39 @@ public sealed class GameTimeTests
Assert.Equal(new DateTime(2012, 4, 24, 18, 0, 0, DateTimeKind.Unspecified), next);
}
[Fact]
public void LimitCatchUp_trims_a_step_to_the_game_time_it_is_allowed_to_bank()
{
var cap = TimeSpan.FromHours(24);
// At x1 a day of game time is 288 real seconds, so a week of downtime comes back trimmed to that.
var trimmed = GameTime.LimitCatchUp(TimeSpan.FromDays(7), timeScale: 1, cap);
Assert.Equal(288, trimmed.TotalSeconds, 1);
Assert.Equal(cap, GameTime.Advance(GameTime.DefaultStart, trimmed, 1, false) - GameTime.DefaultStart);
// Four times the speed banks the same day of game time in a quarter of the wall clock.
Assert.Equal(72, GameTime.LimitCatchUp(TimeSpan.FromDays(7), timeScale: 4, cap).TotalSeconds, 1);
}
[Fact]
public void LimitCatchUp_leaves_an_ordinary_tick_alone()
{
var tick = TimeSpan.FromMilliseconds(100);
Assert.Equal(tick, GameTime.LimitCatchUp(tick, 1, TimeSpan.FromHours(24)));
// Five seconds is what an idle world banks between lazy ticks; it must survive untouched too.
var lazy = TimeSpan.FromSeconds(5);
Assert.Equal(lazy, GameTime.LimitCatchUp(lazy, 4, TimeSpan.FromHours(24)));
}
[Fact]
public void LimitCatchUp_treats_a_non_positive_cap_as_no_cap()
{
var week = TimeSpan.FromDays(7);
Assert.Equal(week, GameTime.LimitCatchUp(week, 1, TimeSpan.Zero));
Assert.Equal(week, GameTime.LimitCatchUp(week, 1, TimeSpan.FromHours(-1)));
}
[Fact]
public void DefaultStart_is_morning_of_12_April_2012()
{
@@ -236,6 +236,21 @@ public sealed class WeatherModelTests
Assert.Equal(0f, WeatherModel.UpdateSnowDepth(-5f, -10f, 0f, 0f));
}
[Fact]
public void Lying_snow_thins_out_over_the_warmer_parts_of_the_map()
{
const float pack = 200f;
// Well below freezing the whole pack shows; the warmer corners of the field go patchy.
Assert.Equal(pack, WeatherModel.LocalSnowDepth(pack, -10f), 1);
Assert.True(WeatherModel.LocalSnowDepth(pack, 4f) < pack);
Assert.True(WeatherModel.LocalSnowDepth(pack, 12f) < WeatherModel.LocalSnowDepth(pack, 4f));
// It thins rather than vanishing - melting is the integral's job, not the renderer's.
Assert.True(WeatherModel.LocalSnowDepth(pack, 30f) > 0f);
Assert.Equal(0f, WeatherModel.LocalSnowDepth(0f, -10f));
}
[Fact]
public void A_world_opened_in_deep_winter_already_has_snow_on_the_ground()
{
@@ -140,7 +140,10 @@ public sealed class WorldGenerationServiceTests : IDisposable
generator,
_store,
new ChunkExporter(),
new WorldSimulationHost(_store, NullLogger<WorldSimulationHost>.Instance),
new WorldSimulationHost(
_store,
Options.Create(new SimulationOptions()),
NullLogger<WorldSimulationHost>.Instance),
Options.Create(new WorldStorageOptions
{
RootDirectory = _root,
@@ -150,7 +153,7 @@ public sealed class WorldGenerationServiceTests : IDisposable
NullLogger<WorldGenerationService>.Instance);
}
private static WorldSummaryDto Summary(string id, string name) => new()
private static StoredWorldDto Summary(string id, string name) => new()
{
Id = id,
Name = name,
@@ -18,7 +18,10 @@ public sealed class WorldSimulationHostTests : IDisposable
_store = new WorldStore(
Options.Create(new WorldStorageOptions { RootDirectory = _root }),
NullLogger<WorldStore>.Instance);
_host = new WorldSimulationHost(_store, NullLogger<WorldSimulationHost>.Instance);
_host = new WorldSimulationHost(
_store,
Options.Create(new SimulationOptions()),
NullLogger<WorldSimulationHost>.Instance);
}
[Fact]
@@ -100,26 +103,61 @@ public sealed class WorldSimulationHostTests : IDisposable
Assert.Null(_host.TryGetClock(summary.Id));
}
/// <summary>
/// Storage bookkeeping cannot leak here by construction - <see cref="WorldSummaryDto"/> has no field to
/// hold it - so what is left to check is that the facts survive the projection and the live values land.
/// </summary>
[Fact]
public void Overlay_strips_last_ticked_at_for_api()
public void Overlay_carries_the_stored_facts_and_the_live_clock()
{
var summary = Summary("ready-33333333", "Ready");
_host.Attach(summary);
var overlaid = _host.Overlay(summary);
Assert.Equal(summary.Id, overlaid.Id);
Assert.Equal(summary.Name, overlaid.Name);
Assert.Equal(summary.SizeMeters, overlaid.SizeMeters);
Assert.Equal(summary.CreatedAt, overlaid.CreatedAt);
Assert.NotNull(overlaid.Clock);
Assert.Null(overlaid.LastTickedAt);
Assert.NotNull(overlaid.Weather);
}
[Fact]
public void Overlay_strips_last_ticked_at_for_worlds_that_are_not_running()
public void Overlay_falls_back_to_the_stored_facts_for_a_world_that_is_not_running()
{
var overlaid = _host.Overlay(Summary("pending-66666666", "Pending") with
{
Status = WorldStatus.Pending,
});
var pending = Summary("pending-66666666", "Pending") with { Status = WorldStatus.Pending };
Assert.Null(overlaid.LastTickedAt);
var overlaid = _host.Overlay(pending);
Assert.Equal(WorldStatus.Pending, overlaid.Status);
Assert.Equal(pending.Name, overlaid.Name);
// No simulation is running, so there is no live weather to lay over it.
Assert.Null(overlaid.Weather);
}
[Fact]
public async Task Reading_a_lazily_ticked_world_reports_the_current_time_not_a_stale_one()
{
var summary = Summary("lazy-88888888", "Lazy");
await _store.SaveSummaryAsync(summary);
_host.Attach(summary);
var before = _host.TryGetClock(summary.Id);
Assert.NotNull(before);
// Nothing ticks it in between; the read itself has to do the skipped work.
await Task.Delay(400);
var after = _host.TryGetClock(summary.Id);
Assert.NotNull(after);
Assert.True(
after.GameTime > before.GameTime,
"A read must bring the world current rather than answering from the last lazy tick.");
// 400 ms at x1 is 2 game minutes; allow for scheduling slop either side.
var advanced = after.GameTime - before.GameTime;
Assert.InRange(advanced, TimeSpan.FromMinutes(1.5), TimeSpan.FromMinutes(6));
}
/// <summary>
@@ -156,7 +194,7 @@ public sealed class WorldSimulationHostTests : IDisposable
throw new TimeoutException($"Simulation for world '{id}' never attached.");
}
private static WorldSummaryDto Summary(string id, string name) => new()
private static StoredWorldDto Summary(string id, string name) => new()
{
Id = id,
Name = name,
@@ -175,7 +213,7 @@ public sealed class WorldSimulationHostTests : IDisposable
string[] ids =
[
"legacy-11111111", "ready-22222222", "ready-33333333",
"racy-44444444", "stale-55555555", "pending-66666666", "doomed-77777777",
"racy-44444444", "stale-55555555", "pending-66666666", "doomed-77777777", "lazy-88888888",
];
foreach (var id in ids)
@@ -100,15 +100,12 @@ public sealed class WorldSimulationTests
}
[Fact]
public void OverlayForApi_strips_storage_only_state_and_adds_live_weather()
public void OverlayForApi_projects_the_stored_world_and_adds_live_weather()
{
using var simulation = WorldSimulation.Create(ReadySummary(), catchUp: false);
var overlaid = simulation.OverlayForApi(ReadySummary());
Assert.NotNull(overlaid.Clock);
Assert.Null(overlaid.LastTickedAt);
Assert.Null(overlaid.WeatherState);
Assert.Equal(ClimateKind.CentralEuropean, overlaid.Climate);
Assert.NotNull(overlaid.Weather);
Assert.InRange(overlaid.Weather.Humidity, 0, 1);
@@ -137,8 +134,25 @@ public sealed class WorldSimulationTests
Assert.NotNull(stored.WeatherState);
Assert.NotEmpty(stored.WeatherState.Systems);
Assert.NotEqual(0ul, stored.WeatherState.RngState);
// Weather itself is derived, so it has no business in the file.
Assert.Null(stored.Weather);
}
/// <summary>
/// The projection is one-way on purpose: the storage type carries the bookkeeping, the wire type has no
/// field that could hold it, and derived weather never reaches the file.
/// </summary>
[Fact]
public void The_stored_shape_and_the_wire_shape_carry_different_things()
{
var storedFields = typeof(StoredWorldDto).GetProperties().Select(static p => p.Name).ToHashSet();
var wireFields = typeof(WorldSummaryDto).GetProperties().Select(static p => p.Name).ToHashSet();
Assert.Contains("LastTickedAt", storedFields);
Assert.Contains("WeatherState", storedFields);
Assert.DoesNotContain("LastTickedAt", wireFields);
Assert.DoesNotContain("WeatherState", wireFields);
Assert.Contains("Weather", wireFields);
Assert.DoesNotContain("Weather", storedFields);
}
[Fact]
@@ -157,6 +171,61 @@ public sealed class WorldSimulationTests
Assert.Equal(weatherBefore.Condition, weatherAfter.Condition);
}
[Fact]
public void A_week_of_downtime_only_costs_the_world_the_capped_amount_of_game_time()
{
var summary = ReadySummary() with { LastTickedAt = DateTimeOffset.UtcNow - TimeSpan.FromDays(7) };
var options = new SimulationOptions { MaxCatchUpGameHours = 24 };
using var simulation = WorldSimulation.Create(summary, catchUp: true, options);
// Uncapped this would be about six game years; the world wakes up one day older instead.
var advanced = simulation.SnapshotClock().GameTime - GameTime.DefaultStart;
Assert.InRange(advanced, TimeSpan.FromHours(24), TimeSpan.FromHours(24.2));
}
[Fact]
public void A_zero_cap_means_the_world_replays_everything_it_missed()
{
var summary = ReadySummary() with { LastTickedAt = DateTimeOffset.UtcNow - TimeSpan.FromHours(1) };
var options = new SimulationOptions { MaxCatchUpGameHours = 0 };
using var simulation = WorldSimulation.Create(summary, catchUp: true, options);
// One real hour at x1 is 12.5 game days, and nothing trims it.
var advanced = simulation.SnapshotClock().GameTime - GameTime.DefaultStart;
Assert.InRange(advanced, TimeSpan.FromDays(12), TimeSpan.FromDays(13));
}
[Fact]
public void A_world_is_watched_when_it_attaches_and_goes_idle_once_nobody_asks()
{
using var simulation = WorldSimulation.Create(ReadySummary(), catchUp: false);
var now = DateTimeOffset.UtcNow;
Assert.False(simulation.IsIdle(now, TimeSpan.FromSeconds(20)));
Assert.True(simulation.IsIdle(now + TimeSpan.FromMinutes(5), TimeSpan.FromSeconds(20)));
simulation.Touch();
Assert.False(simulation.IsIdle(DateTimeOffset.UtcNow, TimeSpan.FromSeconds(20)));
// A zero threshold turns the whole idea off: everything stays watched.
Assert.False(simulation.IsIdle(now + TimeSpan.FromDays(1), TimeSpan.Zero));
}
[Fact]
public void Ticking_lazily_lands_on_the_same_game_time_as_ticking_often()
{
using var lazy = WorldSimulation.Create(ReadySummary(), catchUp: false);
using var eager = WorldSimulation.Create(ReadySummary(), catchUp: false);
lazy.Tick(TimeSpan.FromSeconds(5));
for (var i = 0; i < 50; i++) eager.Tick(TimeSpan.FromMilliseconds(100));
// The tick rate is a cost decision, not a correctness one: a step is driven by elapsed wall time.
Assert.Equal(lazy.SnapshotClock().GameTime, eager.SnapshotClock().GameTime);
}
[Fact]
public void A_long_absence_rolls_a_fresh_sky_instead_of_stepping_through_it()
{
@@ -209,7 +278,7 @@ public sealed class WorldSimulationTests
}
}
private static WorldSummaryDto ReadySummary() => new()
private static StoredWorldDto ReadySummary() => new()
{
Id = "town-aaaaaaaa",
Name = "Town",
@@ -80,7 +80,7 @@ public sealed class WorldStoreTests : IDisposable
Assert.Equal(["state.json"], files.Select(static path => Path.GetFileName(path)).Order().ToArray()!);
}
private static WorldSummaryDto Summary(string id, string name) => new()
private static StoredWorldDto Summary(string id, string name) => new()
{
Id = id,
Name = name,