## Summary Phase 3 of the anchored-time work: **every actively-written delta-time value in the engine now stores an anchored timestamp** — absolute on the wire, shifted forward by the downtime at load. Remaining time survives restarts (as delta did), and unlike delta, the bytes do not change on every save, so an idle world serializes identically save after save. The answer to "is it possible everywhere": **yes** — including the one case that looked impossible. ## The GenericPersistence problem, solved `GenericPersistence` bins (`Virtues.bin`, `StealableArtifacts.bin`, …) are raw payloads with no idx header, so they have no anchor of their own — anchored reads there would silently apply zero shift. But the anchor is a property of the **save**, not the file: every file in one save shares one `World.SaveStartTime`, and `Persistence.Load` reads **all** entity indexes (phase 1) before **any** persistence payload (phase 2). So the idx v5 header stamps a save-wide `World.LoadTimeShift`, and generic persistence readers inherit it. No file-format change, no per-bin header, old bins unaffected. ## Converted - **Item v10 → v11**: `LastMoved` — previously whole-minute delta, rewritten every save for every item, the single largest source of idle-save churn — and `DecayResetTime` (retiring the TODO from #2583). **Mobile v37 → v38**: the three stat-gain stamps. **BaseCreature v20 → v21**: `SummonEnd`. - **17 code-generated classes** (`[DeltaDateTime]` → `[AnchoredDateTime]`, version bump + `MigrateFrom` each): the five field spells, TransientItem, VirtueContext (×7 fields), PuzzleChestSolutionAndTime, BaseCamp, BaseBoat, RentedVendor, PlayerVendor, Ethics Player, Sheep, StarRoomGate, ChampionSpawn (×3), Corpse (`TimeOfDeath`, v19). The `MigrateFrom` bodies were generated from each class's current migration schema and are compiler-verified; VirtueContext's save-flagged nullables fall back to the same defaults the old deserialize left in place. Corpse's six migrations moved to a new `Corpse.Migrations.cs`. - **Hand-written sites**: StealableArtifacts (v2), VendorInventory (v1), ML quest objectives (persistence v3) — each gated on its own version. **Not converted, deliberately**: the ~25 read-only `ReadDeltaTime` sites in legacy version fallbacks and migration replays — they decode existing old bytes and must never change. `[DeltaDateTime]`/`WriteDeltaTime` remain available for them. ## Verification - Build 0 errors / 0 warnings; **837 + 708 tests green**. - Schema regeneration produced exactly the 17 expected new `vN.json` files (all `AnchoredTime` rule args), nothing else touched. - **New acceptance tests** pin the point of the whole effort: serializing the same item at two save times **5 hours apart produces byte-identical output**, and `LastMoved`/`DecayResetTime` round-trip **exactly** at sub-minute precision (the old minutes encoding destroyed both properties). ## Notes for review - `LastMoved` grows from a 1–3 byte encoded minutes value to 8-byte ticks per item — the price of byte-stability; it repays itself in incremental-save behavior since unchanged items now produce unchanged bytes. - BaseEscortable-style semantics are unchanged: anchored shift preserves *remaining* time exactly, the same contract delta provided, so no gameplay-visible behavior changes — deadlines simply stop being consumed by downtime that delta already protected against, now with stable bytes. ## Enforcement `WriteDeltaTime` is now `[Obsolete]` (interface + implementation). With the repo's warnings-as-errors, any new delta-time write — hand-written or emitted by a still-unconverted `[DeltaDateTime]` field — fails the build, with the migration instructions in the message. That the full solution still builds with **zero warnings** is itself the proof no active delta writer survived the conversion. `ReadDeltaTime` deliberately stays un-attributed: its remaining callers decode existing old bytes and are correct forever; its XML docs now state the legacy-decode-only contract.
138 lines
5 KiB
C#
138 lines
5 KiB
C#
/*************************************************************************
|
|
* ModernUO *
|
|
* Copyright 2019-2026 - ModernUO Development Team *
|
|
* Email: hi@modernuo.com *
|
|
* File: GenericPersistence.cs *
|
|
* *
|
|
* This program is free software: you can redistribute it and/or modify *
|
|
* it under the terms of the GNU General Public License as published by *
|
|
* the Free Software Foundation, either version 3 of the License, or *
|
|
* (at your option) any later version. *
|
|
* *
|
|
* You should have received a copy of the GNU General Public License *
|
|
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
|
|
*************************************************************************/
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.IO.MemoryMappedFiles;
|
|
|
|
namespace Server;
|
|
|
|
public abstract class GenericPersistence : Persistence, IGenericSerializable
|
|
{
|
|
public string Name { get; }
|
|
public string SaveFilePath { get; protected set; } // "<Folder>/<System>.bin"
|
|
|
|
// Placement of the self-payload in the worker heaps for the most recent save. Only
|
|
// persistences carry placement state — entities are located through the per-worker
|
|
// segment logs instead.
|
|
private protected byte _selfThread;
|
|
private protected int _selfPosition;
|
|
private protected int _selfLength;
|
|
|
|
internal void SetSelfPlacement(byte thread, int position, int length)
|
|
{
|
|
_selfThread = thread;
|
|
_selfPosition = position;
|
|
_selfLength = length;
|
|
}
|
|
|
|
private long _loadedFileLength;
|
|
|
|
// Scheduling estimate only: previous save's payload size, or the loaded file size before the first save.
|
|
internal long EstimatedSize => _selfLength > 0 ? _selfLength : _loadedFileLength;
|
|
|
|
public GenericPersistence(string name, int priority) : base(priority)
|
|
{
|
|
Name = name;
|
|
SaveFilePath = Path.Combine(Name, $"{Name}.bin");
|
|
}
|
|
|
|
public override void Serialize()
|
|
{
|
|
// Always a dedicated chunk: self-payloads can be arbitrarily large and must not
|
|
// ride inside a shared chunk where one worker would serialize them plus the chunk.
|
|
World.PushSingleToCache(this);
|
|
}
|
|
|
|
public override void WriteSnapshot(string savePath)
|
|
{
|
|
if (_selfLength == 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var file = Path.Combine(savePath, SaveFilePath);
|
|
var dir = Path.GetDirectoryName(file);
|
|
PathUtility.EnsureDirectory(dir);
|
|
|
|
var threads = World._threadWorkers;
|
|
|
|
using var binFs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None);
|
|
|
|
binFs.Write(threads[_selfThread].GetHeap(_selfPosition, _selfLength));
|
|
}
|
|
|
|
public override unsafe void Deserialize(string savePath, Dictionary<ulong, string> typesDb)
|
|
{
|
|
// Assume savePath has the Core.BaseDirectory already prepended
|
|
var dataPath = Path.GetFullPath(SaveFilePath, savePath);
|
|
var file = new FileInfo(dataPath);
|
|
|
|
if (!file.Exists || file.Length <= 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var fileLength = file.Length;
|
|
_loadedFileLength = fileLength;
|
|
|
|
string error;
|
|
|
|
try
|
|
{
|
|
using var mmf = MemoryMappedFile.CreateFromFile(dataPath, FileMode.Open);
|
|
using var accessor = mmf.CreateViewStream();
|
|
|
|
byte* ptr = null;
|
|
accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
|
|
var dataReader = new UnmanagedDataReader(ptr, accessor.Length, typesDb)
|
|
{
|
|
// These payloads carry no anchor of their own; they inherit the save-wide
|
|
// shift stamped while the entity indexes were read (indexes always load
|
|
// before persistence payloads — see Persistence.Load).
|
|
AnchoredTimeShift = World.LoadTimeShift
|
|
};
|
|
Deserialize(dataReader);
|
|
|
|
error = dataReader.Position != fileLength
|
|
? $"Serialized {fileLength} bytes, but {dataReader.Position} bytes deserialized"
|
|
: null;
|
|
|
|
accessor.SafeMemoryMappedViewHandle.ReleasePointer();
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
error = e.ToString();
|
|
}
|
|
|
|
if (error != null)
|
|
{
|
|
Console.WriteLine($"***** Bad deserialize of {file.FullName} *****");
|
|
Console.WriteLine(error);
|
|
|
|
Console.Write("Skip this file and continue? (y/n): ");
|
|
var y = ConsoleInputHandler.ReadLine();
|
|
|
|
if (!y.InsensitiveEquals("y"))
|
|
{
|
|
throw new Exception("Deserialization failed.");
|
|
}
|
|
}
|
|
}
|
|
|
|
public abstract void Serialize(IGenericWriter writer);
|
|
public abstract void Deserialize(IGenericReader reader);
|
|
}
|