Enhance world simulation and API functionality; implement clock management improvements, ensure proper handling of world states during updates, and refine data persistence methods to prevent resurrecting deleted worlds.

This commit is contained in:
Leonid Pershin
2026-08-16 22:02:45 +03:00
parent 9d1e3c29c7
commit 3610ee8051
12 changed files with 352 additions and 80 deletions
@@ -51,12 +51,13 @@ public static class WorldEndpoints
private static async Task<IResult> CreateWorld(
CreateWorldRequest request,
WorldGenerationService generation,
WorldSimulationHost simulation,
CancellationToken cancellationToken)
{
try
{
var summary = await generation.StartAsync(request, cancellationToken);
return Results.Created($"/api/worlds/{summary.Id}", summary with { LastTickedAt = null });
return Results.Created($"/api/worlds/{summary.Id}", simulation.Overlay(summary));
}
catch (ArgumentException ex)
{
@@ -11,8 +11,6 @@ namespace TheLivingWorld.Api.Simulation;
/// </summary>
public sealed class WorldSimulation : IDisposable
{
private static readonly ClockSystem ClockSystem = new();
private readonly object _gate = new();
private readonly World _ecs;
private readonly Entity _clockEntity;
@@ -85,10 +83,11 @@ public sealed class WorldSimulation : IDisposable
if (realElapsed > TimeSpan.Zero)
{
var before = SnapshotClockUnlocked();
// Compare raw ticks: this runs at 10 Hz per world, so snapshotting DTOs just to diff would
// allocate for nothing.
var before = _ecs.Get<GameClock>(_clockEntity).Ticks;
ClockSystem.Execute(_ecs, realElapsed);
var after = SnapshotClockUnlocked();
if (after.GameTime != before.GameTime) _dirty = true;
if (_ecs.Get<GameClock>(_clockEntity).Ticks != before) _dirty = true;
}
_lastTickedAt = DateTimeOffset.UtcNow;
@@ -24,14 +24,10 @@ public sealed class WorldSimulationHost(
ArgumentNullException.ThrowIfNull(summary);
if (summary.Status != WorldStatus.Ready) return;
_simulations.GetOrAdd(summary.Id, _ =>
{
var hydrated = EnsureClock(summary);
// Catch up only when we have a prior tick stamp (restart). Fresh Ready worlds start clean.
var catchUp = summary.Clock is not null && summary.LastTickedAt is not null;
// Catch up only when we have a prior tick stamp (restart). Fresh Ready worlds start clean.
var catchUp = summary.Clock is not null && summary.LastTickedAt is not null;
if (AttachCore(EnsureClock(summary), catchUp))
logger.LogInformation("Attached simulation for world {Id}", summary.Id);
return WorldSimulation.Create(hydrated, catchUp);
});
}
/// <summary>Stops simulation for a world. Safe to call when the world was never attached.</summary>
@@ -47,6 +43,11 @@ public sealed class WorldSimulationHost(
public WorldClockDto? TryGetClock(string id) =>
_simulations.TryGetValue(id, out var simulation) ? simulation.SnapshotClock() : null;
/// <summary>
/// The one projection from stored/in-flight state to what clients see: overlays the live clock when the
/// world is running and always drops <see cref="WorldSummaryDto.LastTickedAt"/>, which is storage-only.
/// Every endpoint that returns a summary must go through here.
/// </summary>
public WorldSummaryDto Overlay(WorldSummaryDto summary) =>
_simulations.TryGetValue(summary.Id, out var simulation)
? simulation.OverlayForApi(summary)
@@ -109,13 +110,22 @@ public sealed class WorldSimulationHost(
public override async Task StopAsync(CancellationToken cancellationToken)
{
await PersistDirtyAsync(cancellationToken).ConfigureAwait(false);
// Let the tick loop finish first so the final write captures the very last game time, then persist
// with an uncancellable token: by the time shutdown reaches us the caller's token is usually already
// cancelled, and skipping this write would drop up to a full persist interval of play.
await base.StopAsync(cancellationToken).ConfigureAwait(false);
await PersistDirtyAsync(CancellationToken.None, waitForGate: true).ConfigureAwait(false);
foreach (var id in _simulations.Keys.ToArray())
Detach(id);
}
// Not in StopAsync: a shutdown that hits its timeout returns from base.StopAsync with the tick loop still
// running, and disposing the gate underneath it would fault the service. The container disposes us last.
public override void Dispose()
{
_persistGate.Dispose();
base.Dispose();
}
private async Task LoadReadyWorldsAsync(CancellationToken cancellationToken)
@@ -160,11 +170,24 @@ public sealed class WorldSimulationHost(
private void AttachSeeded(WorldSummaryDto summary)
{
_simulations.GetOrAdd(summary.Id, _ =>
{
if (AttachCore(summary, catchUp: false))
logger.LogInformation("Attached simulation for world {Id} (hydrated, no catch-up)", summary.Id);
return WorldSimulation.Create(summary, catchUp: false);
});
}
/// <summary>
/// Registers a simulation for a world, returning false when one was already running. A losing racer must
/// be disposed explicitly: an Arch <c>World</c> lives in a static registry and is never reclaimed by the
/// GC, so dropping the instance would leak it for the lifetime of the process.
/// </summary>
private bool AttachCore(WorldSummaryDto summary, bool catchUp)
{
if (_simulations.ContainsKey(summary.Id)) return false;
var created = WorldSimulation.Create(summary, catchUp);
if (ReferenceEquals(_simulations.GetOrAdd(summary.Id, created), created)) return true;
created.Dispose();
return false;
}
private static WorldSummaryDto EnsureClock(WorldSummaryDto summary) =>
@@ -176,9 +199,15 @@ public sealed class WorldSimulationHost(
LastTickedAt = DateTimeOffset.UtcNow,
};
private async Task PersistDirtyAsync(CancellationToken cancellationToken)
/// <param name="waitForGate">
/// False for the periodic pass - a persist already in flight is as good as ours. True on shutdown, where
/// the final write must not be skipped.
/// </param>
private async Task PersistDirtyAsync(CancellationToken cancellationToken, bool waitForGate = false)
{
if (!await _persistGate.WaitAsync(0, cancellationToken).ConfigureAwait(false))
if (waitForGate)
await _persistGate.WaitAsync(cancellationToken).ConfigureAwait(false);
else if (!await _persistGate.WaitAsync(0, cancellationToken).ConfigureAwait(false))
return;
try
@@ -190,15 +219,24 @@ public sealed class WorldSimulationHost(
try
{
var existing = await store.GetSummaryAsync(simulation.WorldId, cancellationToken).ConfigureAwait(false);
if (existing is null || existing.Status != WorldStatus.Ready)
if (existing is null)
{
// Deleted underneath us - stop burning ticks on a world that no longer exists.
Detach(simulation.WorldId);
continue;
}
if (existing.Status != WorldStatus.Ready)
{
simulation.ClearDirty();
continue;
}
var updated = simulation.ApplyTo(existing);
await store.SaveSummaryAsync(updated, cancellationToken).ConfigureAwait(false);
simulation.ClearDirty();
if (await store.TryUpdateSummaryAsync(updated, cancellationToken).ConfigureAwait(false))
simulation.ClearDirty();
else
Detach(simulation.WorldId);
}
catch (Exception ex)
{
+49 -7
View File
@@ -89,6 +89,28 @@ public sealed class WorldStore(IOptions<WorldStorageOptions> options, ILogger<Wo
await WriteJsonAsync(Path.Combine(directory, StateFileName), summary, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates an existing world's state file without ever creating its folder. Returns false when the world
/// was deleted underneath the caller, so a background writer cannot resurrect it as a stateful husk with
/// no map behind it.
/// </summary>
public async Task<bool> TryUpdateSummaryAsync(
WorldSummaryDto summary,
CancellationToken cancellationToken = default)
{
var path = Path.Combine(WorldDirectory(summary.Id), StateFileName);
try
{
await WriteJsonAsync(path, summary, cancellationToken).ConfigureAwait(false);
return true;
}
catch (DirectoryNotFoundException)
{
return false;
}
}
public async Task<WorldDto?> GetWorldAsync(string id, CancellationToken cancellationToken = default)
{
var path = Path.Combine(WorldDirectory(id), IndexFileName);
@@ -148,13 +170,33 @@ public sealed class WorldStore(IOptions<WorldStorageOptions> options, ILogger<Wo
private static async Task WriteJsonAsync<T>(string path, T value, CancellationToken cancellationToken)
{
// Write beside the target and swap, so a reader never sees a half-written file.
var temporary = path + ".tmp";
await using (var stream = File.Create(temporary))
{
await JsonSerializer.SerializeAsync(stream, value, MapJson.Options, cancellationToken).ConfigureAwait(false);
}
// Write beside the target and swap, so a reader never sees a half-written file. The name carries
// entropy: state.json now has two writers (generation and the simulation host) that must not
// collide on a shared scratch file.
var temporary = $"{path}.{Guid.NewGuid():n}.tmp";
File.Move(temporary, path, overwrite: true);
try
{
await using (var stream = File.Create(temporary))
{
await JsonSerializer.SerializeAsync(stream, value, MapJson.Options, cancellationToken).ConfigureAwait(false);
}
File.Move(temporary, path, overwrite: true);
}
catch
{
// A unique name never gets reclaimed by the next write, so clean up after ourselves.
try
{
File.Delete(temporary);
}
catch (IOException)
{
// Best effort - the original failure is what matters.
}
throw;
}
}
}
@@ -4,11 +4,11 @@ using TheLivingWorld.Core.Ecs;
namespace TheLivingWorld.Core.Simulation;
/// <summary>Advances every <see cref="GameClock"/> entity by wall-clock elapsed time.</summary>
public sealed class ClockSystem
public static class ClockSystem
{
private static readonly QueryDescription Clocks = new QueryDescription().WithAll<GameClock>();
public void Execute(World ecs, TimeSpan realElapsed)
public static void Execute(World ecs, TimeSpan realElapsed)
{
if (realElapsed <= TimeSpan.Zero) return;
+10 -2
View File
@@ -13,7 +13,8 @@ public static class GameTime
/// <summary>
/// Advances a naive game calendar by wall-clock elapsed time. Returns <paramref name="current"/> unchanged
/// when paused or when elapsed is non-positive.
/// when paused or when elapsed is non-positive; saturates at <see cref="DateTime.MaxValue"/> rather than
/// throwing, so a world started near the end of the calendar cannot fault its tick loop.
/// </summary>
public static DateTime Advance(DateTime current, TimeSpan realElapsed, int timeScale, bool paused)
{
@@ -22,7 +23,14 @@ public static class GameTime
var scale = Math.Clamp(timeScale, MinTimeScale, MaxTimeScale);
// 1 real second → 5 * scale game minutes. Multiply by 60 (minutes→seconds) in tick space,
// keeping the product in range for multi-hour catch-up gaps.
var gameTicks = checked(realElapsed.Ticks * GameMinutesPerRealSecond * scale * 60);
var factor = (long)GameMinutesPerRealSecond * scale * 60;
var headroom = (DateTime.MaxValue - current).Ticks;
// Compare before multiplying: the product itself would overflow on an absurd gap.
var gameTicks = realElapsed.Ticks > headroom / factor
? headroom
: realElapsed.Ticks * factor;
return current.AddTicks(gameTicks);
}
@@ -24,6 +24,12 @@ describe('parseGameTime', () => {
expect(parseGameTime('')).toBeNull();
expect(parseGameTime('not-a-date')).toBeNull();
});
it('rejects out-of-range components instead of rolling them over', () => {
expect(parseGameTime('2012-04-12T06:00:60')).toBeNull();
expect(parseGameTime('2012-04-12T06:60:00')).toBeNull();
expect(parseGameTime('2012-02-30T06:00:00')).toBeNull();
});
});
describe('formatGameTime', () => {
@@ -65,6 +71,27 @@ describe('interpolateGameTime', () => {
expect(date).not.toBeNull();
expect(formatGameTime(date!)).toBe('12 April 2012 · 06:10');
});
it('clamps timeScale the way the server does', () => {
const tooFast = interpolateGameTime(
{ gameTime: '2012-04-12T06:00:00', timeScale: 99, paused: false },
1000,
);
expect(formatGameTime(tooFast!)).toBe('12 April 2012 · 06:20');
const tooSlow = interpolateGameTime(
{ gameTime: '2012-04-12T06:00:00', timeScale: 0, paused: false },
1000,
);
expect(formatGameTime(tooSlow!)).toBe('12 April 2012 · 06:05');
});
});
describe('startGameTimeFromInput', () => {
it('rejects out-of-range components', () => {
expect(startGameTimeFromInput('2012-04-12T06:60')).toBeNull();
expect(startGameTimeFromInput('2012-04-12T06:00:60')).toBeNull();
});
});
describe('startGameTimeFromInput', () => {
+10 -1
View File
@@ -3,6 +3,10 @@ import type { WorldClock } from '../api/types';
/** Matches server GameTime: five game minutes per real second at x1. */
export const GAME_MINUTES_PER_REAL_SECOND = 5;
/** Mirrors GameTime.MinTimeScale / MaxTimeScale, which the server clamps to. */
export const MIN_TIME_SCALE = 1;
export const MAX_TIME_SCALE = 4;
const MONTHS = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December',
@@ -30,6 +34,7 @@ export function parseGameTime(raw: string): Date | null {
|| date.getDate() !== day
|| date.getHours() !== hour
|| date.getMinutes() !== minute
|| date.getSeconds() !== second
) {
return null;
}
@@ -64,7 +69,10 @@ export function interpolateGameTime(
if (!base) return null;
if (clock.paused || elapsedRealMs <= 0) return base;
const scale = Number.isFinite(clock.timeScale) ? clock.timeScale : 1;
// Clamp like the server does, so a contract drift cannot make the client draw a time nobody is simulating.
const scale = Number.isFinite(clock.timeScale)
? Math.min(Math.max(clock.timeScale, MIN_TIME_SCALE), MAX_TIME_SCALE)
: MIN_TIME_SCALE;
const gameMs = (elapsedRealMs / 1000) * GAME_MINUTES_PER_REAL_SECOND * scale * 60_000;
return new Date(base.getTime() + gameMs);
}
@@ -97,6 +105,7 @@ export function startGameTimeFromInput(raw: string): string | null {
|| date.getDate() !== day
|| date.getHours() !== hour
|| date.getMinutes() !== minute
|| date.getSeconds() !== second
) {
return null;
}