ModernUO/Projects/Server/Serialization/IGenericReader.cs
Kamron Batman 126a10ce53
feat: anchored-time infrastructure with a save-start anchor in idx v5 (#2585)
## Summary

The save-stability infrastructure consumed by generator v3's `[AnchoredDateTime]`: anchored timestamps are written as **absolute values** and re-based once at load by the elapsed time since the save started — so downtime doesn't age them, and an unchanged entity serializes to identical bytes (the prerequisite for replacing delta-time encodings, which rewrite every entity on every save).

## Design

- **`WriteAnchoredTime` / `ReadAnchoredTime`** on `IGenericWriter`/`IGenericReader`. The read side applies the reader's `AnchoredTimeShift`; `Min/MaxValue` sentinels pass through unshifted, and shifts saturate instead of overflowing.
- **`World.SaveStartTime`** is stamped the moment the world freezes for a snapshot — one anchor for the entire save, no per-persistence skew.
- **idx v5**: the anchor ticks sit in the header right after the version. The anchor travels with the file it re-anchors, so a single idx+bin pair restored from a backup is self-describing, and anchor presence is guaranteed by the same version gate as the record format — there is no separate anchor file to lose.
- **The shift rides the reader instance** (`BufferReader`, `UnmanagedDataReader`, `BinaryFileReader` delegating), not a static — parallel per-persistence loads and ad-hoc restores each see their own file's anchor. idx v4 and older read with a zero shift.

## Scope

Behavior-neutral: nothing serializes anchored values yet (`Item.DecayResetTime` and the `[DeltaDateTime]` field migrations come separately, with their own version bumps). Saves written from this branch are idx v5; loading v4/v3 saves is unchanged and remains pinned by the existing hand-written-header tests.

## Testing

- Unit round-trips: exact with zero shift, shifted read, sentinel passthrough, saturation, Local→UTC normalization.
- End-to-end through the real worker/segment-log pipeline: an anchored timestamp re-bases across a simulated two-hour downtime via the idx v5 header.
- Full suites green: Server.Tests 835/835, UOContent.Tests 708/708 (including the existing v4/v3 idx loading tests).
2026-08-22 15:59:39 -07:00

181 lines
5.2 KiB
C#

/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: IGenericReader.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.Buffers;
using System.Collections;
using System.IO;
using System.Net;
namespace Server;
public interface IGenericReader
{
string ReadString(bool intern = false);
public string ReadStringRaw(bool intern = false);
long ReadLong();
ulong ReadULong();
int ReadInt();
uint ReadUInt();
short ReadShort();
ushort ReadUShort();
double ReadDouble();
float ReadFloat();
byte ReadByte();
sbyte ReadSByte();
bool ReadBool();
Serial ReadSerial();
Type ReadType();
DateTime ReadDateTime() => new(ReadLong(), DateTimeKind.Utc);
TimeSpan ReadTimeSpan() => new(ReadLong());
DateTime ReadDeltaTime()
{
return ReadLong() switch
{
long.MinValue => DateTime.MinValue,
long.MaxValue => DateTime.MaxValue,
var delta => new DateTime(delta + DateTime.UtcNow.Ticks, DateTimeKind.Utc)
};
}
/// <summary>
/// Elapsed time between the loaded save starting and this load, applied by
/// <see cref="ReadAnchoredTime" />. Zero when the source carries no anchor.
/// </summary>
TimeSpan AnchoredTimeShift => TimeSpan.Zero;
DateTime ReadAnchoredTime()
{
var value = ReadDateTime();
if (value == DateTime.MinValue || value == DateTime.MaxValue)
{
return value;
}
var shift = AnchoredTimeShift;
if (shift == TimeSpan.Zero)
{
return value;
}
var ticks = value.Ticks + shift.Ticks;
if (ticks >= DateTime.MaxValue.Ticks)
{
return DateTime.MaxValue;
}
return ticks <= 0 ? DateTime.MinValue : new DateTime(ticks, DateTimeKind.Utc);
}
decimal ReadDecimal() => new([ReadInt(), ReadInt(), ReadInt(), ReadInt()]);
int ReadEncodedInt()
{
int v = 0, shift = 0;
byte b;
do
{
b = ReadByte();
v |= (b & 0x7F) << shift;
shift += 7;
}
while (b >= 0x80);
return v;
}
IPAddress ReadIPAddress()
{
var length = ReadByte();
// Either 2 ushorts, or 8 ushorts
Span<byte> integer = stackalloc byte[length];
Read(integer);
return Utility.Intern(new IPAddress(integer));
}
Point3D ReadPoint3D() => new(ReadInt(), ReadInt(), ReadInt());
Point2D ReadPoint2D() => new(ReadInt(), ReadInt());
Rectangle2D ReadRect2D() => new(ReadPoint2D(), ReadPoint2D());
Rectangle3D ReadRect3D() => new(ReadPoint3D(), ReadPoint3D());
Map ReadMap() => Map.Maps[ReadByte()];
Race ReadRace() => Race.Races[ReadByte()];
int Read(Span<byte> buffer);
unsafe T ReadEnum<T>() where T : unmanaged, Enum
{
switch (sizeof(T))
{
case 1:
{
var num = ReadByte();
return *(T*)&num;
}
case 2:
{
var num = ReadShort();
return *(T*)&num;
}
case 4:
{
var num = ReadEncodedInt();
return *(T*)&num;
}
case 8:
{
var num = ReadLong();
return *(T*)&num;
}
}
return default;
}
Guid ReadGuid()
{
Span<byte> bytes = stackalloc byte[16];
Read(bytes);
return new Guid(bytes);
}
public BitArray ReadBitArray()
{
var bitLength = ReadEncodedInt();
var byteLength = (bitLength + 7) / 8;
var buffer = ArrayPool<byte>.Shared.Rent(byteLength);
try
{
Read(buffer.AsSpan(0, byteLength));
return new BitArray(buffer) { Length = bitLength };
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
TextDefinition ReadTextDefinition()
{
return ReadEncodedInt() switch
{
0 => TextDefinition.Empty,
1 => ReadEncodedInt(),
2 => ReadString(),
_ => null
};
}
long Seek(long offset, SeekOrigin origin);
}