Merge PR #379: fix Flotsam asset cache for .NET 10

Replace removed BinaryFormatter cache persistence with bounded, versioned SHA-256-protected simulator cache. Legacy cache entries are discarded per entry and re-fetched upstream. Full Linux/Windows/ARM64 and NexVerse CI passed. No asset store or DB migration.
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-11-04 18:02:52 +01:00
commit 7164de3049
6 files changed
+328 -23

No files matched your search

+7
View File
@@ -34,6 +34,9 @@ jobs:
- name: Build Generation 1.1 server and addons
run: dotnet build OpenSim.sln --configuration Release --no-restore
- name: Regression-test .NET 10 Flotsam disk-cache serialization
run: dotnet run --configuration Release --project tools/ci/FlotsamCacheNet10Regression/FlotsamCacheNet10Regression.csproj
- name: Verify isolated .NET 10 ROBUST runtime on Linux x64
run: |
python3 tools/gen11/robust_runtime_smoke.py
@@ -64,6 +67,10 @@ jobs:
shell: cmd
run: dotnet build OpenSim.sln --configuration Release
- name: Regression-test .NET 10 Flotsam disk-cache serialization on Windows
shell: pwsh
run: dotnet run --configuration Release --project tools/ci/FlotsamCacheNet10Regression/FlotsamCacheNet10Regression.csproj
- name: Runtime smoke - boot real ROBUST .NET 10 on Windows x64
shell: pwsh
run: |
+4
View File
@@ -694,6 +694,10 @@ jobs:
shell: bash
run: python3 tools/gen11/robust_runtime_smoke.py
- name: Regression-test .NET 10 Flotsam disk-cache roundtrip and old-format fallback
shell: bash
run: dotnet run --configuration Release --project tools/ci/FlotsamCacheNet10Regression/FlotsamCacheNet10Regression.csproj
- name: Verify server build includes all five simulator addon DLLs
shell: bash
run: |
@@ -29,7 +29,7 @@ using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Timers;
@@ -522,12 +522,7 @@ namespace OpenSim.Region.CoreModules.Asset
{
using FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
if (stream.Length == 0) // Empty file will trigger exception below
return null;
BinaryFormatter bformatter = new();
asset = (AssetBase)bformatter.Deserialize(stream);
asset = FlotsamAssetCacheBinaryFormat.Read(stream, id);
m_DiskHits++;
}
catch (FileNotFoundException)
@@ -536,15 +531,21 @@ namespace OpenSim.Region.CoreModules.Asset
catch (DirectoryNotFoundException)
{
}
catch (System.Runtime.Serialization.SerializationException e)
catch (FlotsamAssetCacheBinaryFormat.LegacyCacheFormatException)
{
m_log.Warn($"[FLOTSAM ASSET CACHE]: Failed to get file {filename} for asset {id}: {e.Message}");
// If there was a problem deserializing the asset, the asset may
// either be corrupted OR was serialized under an old format
// {different version of AssetBase} -- we should attempt to
// delete it and re-cache
File.Delete(filename);
// Files written by .NET 8 BinaryFormatter cannot be read on .NET 10.
// This is only a disposable simulator cache, NOT the asset store.
// Silently drop the obsolete entry and fetch it again upstream.
try { File.Delete(filename); }
catch (IOException e) { m_log.Warn($"[FLOTSAM ASSET CACHE]: Cannot remove obsolete cache entry {filename}: {e.Message}"); }
catch (UnauthorizedAccessException e) { m_log.Warn($"[FLOTSAM ASSET CACHE]: Cannot remove obsolete cache entry {filename}: {e.Message}"); }
}
catch (Exception e) when (e is InvalidDataException || e is EndOfStreamException || e is DecoderFallbackException)
{
m_log.Warn($"[FLOTSAM ASSET CACHE]: Discarding invalid cache entry {filename} for {id}: {e.Message}");
try { File.Delete(filename); }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
catch (Exception e)
{
@@ -1009,24 +1010,22 @@ namespace OpenSim.Region.CoreModules.Asset
Directory.CreateDirectory(directory);
}
using (Stream stream = File.Open(tempname, FileMode.Create))
using (Stream stream = File.Open(tempname, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
BinaryFormatter bformatter = new();
bformatter.Serialize(stream, asset);
FlotsamAssetCacheBinaryFormat.Write(stream, asset);
stream.Flush();
}
m_lastFileAccessTimeChange?.Add(filename, 900000);
}
catch (IOException e)
catch (Exception e)
{
m_log.Warn(
$"[FLOTSAM ASSET CACHE]: Failed to write asset {asset.ID} to temporary location {tempname} (final {filename}) on cache in {directory}: {e.Message}");
try { File.Delete(tempname); }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return;
}
catch (UnauthorizedAccessException)
{
}
try
{
@@ -1720,4 +1719,152 @@ namespace OpenSim.Region.CoreModules.Asset
}
#endregion
}
/// <summary>
/// Versioned, bounded, integrity-checked local simulator cache encoding.
/// This format never invokes BinaryFormatter or deserializes executable types.
/// The file cache is disposable: old BinaryFormatter entries are discarded
/// and re-fetched through the configured authoritative asset service.
/// </summary>
internal static class FlotsamAssetCacheBinaryFormat
{
private const uint Magic = 0x31434C46; // FLC1 in little-endian
private const int Version = 1;
private const int MaxStringBytes = 1024 * 1024;
private const int MaxAssetBytes = 512 * 1024 * 1024;
private const int MaxHashBytes = 128;
internal sealed class LegacyCacheFormatException : IOException
{
internal LegacyCacheFormatException()
: base("Obsolete BinaryFormatter cache entry; re-fetch from asset service") { }
}
private static void WriteBytes(BinaryWriter writer, byte[] bytes, int limit)
{
if (bytes is null)
{
writer.Write(-1);
return;
}
if (bytes.Length > limit)
throw new InvalidDataException("Cache field exceeds configured size limit");
writer.Write(bytes.Length);
writer.Write(bytes);
}
private static byte[] ReadBytes(BinaryReader reader, int limit)
{
int length = reader.ReadInt32();
if (length == -1)
return null;
if (length < 0 || length > limit || length > reader.BaseStream.Length - reader.BaseStream.Position)
throw new InvalidDataException("Invalid cache field length");
byte[] bytes = reader.ReadBytes(length);
if (bytes.Length != length)
throw new EndOfStreamException("Truncated cache field");
return bytes;
}
private static void WriteString(BinaryWriter writer, string value)
{
WriteBytes(writer, value is null ? null : Encoding.UTF8.GetBytes(value), MaxStringBytes);
}
private static string ReadString(BinaryReader reader)
{
byte[] data = ReadBytes(reader, MaxStringBytes);
return data is null ? null : new UTF8Encoding(false, true).GetString(data);
}
internal static void Write(Stream stream, AssetBase asset)
{
if (asset is null || asset.Metadata is null)
throw new InvalidDataException("Missing asset or metadata");
using BinaryWriter writer = new(stream, Encoding.UTF8, leaveOpen: true);
writer.Write(Magic);
writer.Write(Version);
AssetMetadata metadata = asset.Metadata;
WriteString(writer, metadata.FullID.ToString());
WriteString(writer, metadata.ID);
WriteString(writer, metadata.Name);
WriteString(writer, metadata.Description);
WriteString(writer, metadata.CreatorID);
WriteString(writer, metadata.ContentType);
writer.Write(metadata.Type);
writer.Write((int)metadata.Flags);
writer.Write(metadata.Local);
writer.Write(metadata.Temporary);
writer.Write(metadata.CreationDate.ToBinary());
WriteBytes(writer, metadata.SHA1, MaxHashBytes);
writer.Write(asset.UploadAttempts);
WriteBytes(writer, asset.Data, MaxAssetBytes);
writer.Write(SHA256.HashData(asset.Data ?? Array.Empty<byte>()));
writer.Flush();
}
internal static AssetBase Read(Stream stream, string expectedId)
{
if (!stream.CanSeek)
throw new InvalidDataException("File cache stream must be seekable");
using BinaryReader reader = new(stream, new UTF8Encoding(false, true), leaveOpen: true);
if (reader.ReadUInt32() != Magic)
throw new LegacyCacheFormatException();
if (reader.ReadInt32() != Version)
throw new InvalidDataException("Unsupported Flotsam cache version");
string fullId = ReadString(reader);
string id = ReadString(reader);
if (!string.Equals(id, expectedId, StringComparison.Ordinal))
throw new InvalidDataException("Asset ID does not match cache key");
string name = ReadString(reader);
string description = ReadString(reader);
string creatorId = ReadString(reader);
string contentType = ReadString(reader);
sbyte type = reader.ReadSByte();
AssetFlags flags = (AssetFlags)reader.ReadInt32();
bool local = reader.ReadBoolean();
bool temporary = reader.ReadBoolean();
DateTime created = DateTime.FromBinary(reader.ReadInt64());
byte[] sha1 = ReadBytes(reader, MaxHashBytes);
int uploadAttempts = reader.ReadInt32();
byte[] payload = ReadBytes(reader, MaxAssetBytes);
byte[] checksum = reader.ReadBytes(32);
if (checksum.Length != 32 ||
!CryptographicOperations.FixedTimeEquals(checksum, SHA256.HashData(payload ?? Array.Empty<byte>())) ||
reader.BaseStream.Position != reader.BaseStream.Length)
throw new InvalidDataException("Cache payload checksum or length mismatch");
AssetMetadata metadata = new();
if (UUID.TryParse(fullId, out UUID uuid))
metadata.FullID = uuid;
metadata.ID = id;
metadata.Name = name;
metadata.Description = description;
metadata.CreatorID = creatorId;
if (contentType is not null)
metadata.ContentType = contentType;
metadata.Type = type; // Preserve original type after ContentType setter.
metadata.Flags = flags;
metadata.Local = local;
metadata.Temporary = temporary;
metadata.CreationDate = created;
metadata.SHA1 = sha1;
return new AssetBase
{
Metadata = metadata,
Data = payload,
UploadAttempts = uploadAttempts
};
}
}
}
+25
View File
@@ -0,0 +1,25 @@
# Flotsam Asset Cache: .NET 10 format migration
The Generation 1 Flotsam simulator-side **file cache** previously used `BinaryFormatter` to persist `AssetBase`. `BinaryFormatter` cannot be used on .NET 10. This made old cache entries unreadable and attempted writes fail.
The fix implements a bounded, versioned `FLC1` disk-cache format with a SHA-256 payload checksum, preserving asset metadata and binary payload without reconstructing arbitrary object graphs. It intentionally **does not read the old BinaryFormatter format**. On encountering an obsolete entry, the simulator removes **that cache file only** and re-fetches it through the configured authoritative asset service (for example ROBUST FSAssets).
This is **not** a database or asset-store migration. Do **not** delete the central FSAssets directory, asset SQL tables, inventory, OAR/IAR files, or arbitrary `bin/` files.
## Immediate workaround while binaries are not yet deployed
In the active simulator's `[AssetCache]` configuration (typically `bin/config-include/FlotsamCache.ini`), set `FileCacheEnabled = false` and restart the simulator normally. This disables only Flotsam's file cache. It may increase ROBUST asset-service load. Re-enable after deploying the corrected binary.
## Cache path and cleanup
The checked-in setting `CacheDirectory = ./opt/cache/assetcache` is intentionally relative to the simulator's process working directory, hence `/opt/robust/bin/opt/cache/assetcache` when launched from `/opt/robust/bin`. To use an external absolute path instead, change the active setting to `CacheDirectory = /opt/cache/assetcache` **only after** checking directory permissions and that no other service uses that path. The format fix does **not** automatically move files or change operator-owned settings.
Existing stale cache files will be discarded on access. A controlled offline cache reset may accelerate reclamation, but only after the active cache directory is confirmed and it is verified to be exclusively a disposable simulator-side Flotsam cache.
## Regression
```bash
dotnet run --configuration Release --project tools/ci/FlotsamCacheNet10Regression/FlotsamCacheNet10Regression.csproj
```
This checks metadata and binary payload fidelity, rejected legacy entries, cache file disposal, wrong-ID rejection, tampering and truncation. It does not require MariaDB and never connects to a live grid.
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Reference Include="OpenMetaverseTypes"><HintPath>../../../bin/OpenMetaverseTypes.dll</HintPath></Reference>
<Reference Include="OpenMetaverse"><HintPath>../../../bin/OpenMetaverse.dll</HintPath></Reference>
<ProjectReference Include="../../../OpenSim/Framework/OpenSim.Framework.csproj" />
<ProjectReference Include="../../../OpenSim/Region/CoreModules/OpenSim.Region.CoreModules.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,108 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Asset;
internal static class Program
{
private static int Main()
{
string root = Path.Combine(Path.GetTempPath(), "ogl-flotsam-net10-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
try
{
Type format = typeof(FlotsamAssetCache).Assembly.GetType(
"OpenSim.Region.CoreModules.Asset.FlotsamAssetCacheBinaryFormat", throwOnError: true)!;
MethodInfo write = format.GetMethod("Write", BindingFlags.Static | BindingFlags.NonPublic)!;
MethodInfo read = format.GetMethod("Read", BindingFlags.Static | BindingFlags.NonPublic)!;
if (write is null || read is null)
throw new Exception("Missing versioned Flotsam codec");
const string id = "fee03dc5-1f4d-46cc-8456-e19b85699c69";
AssetBase original = new();
original.ID = id;
original.Name = "Net10 cache fixture";
original.Type = 7;
original.CreatorID = "creator-test";
original.Description = "Structured cache metadata roundtrip";
original.Metadata.CreationDate = new DateTime(2026, 11, 4, 12, 30, 0, DateTimeKind.Utc);
original.Metadata.ContentType = "application/vnd.ll.notecard";
original.Type = 7;
original.Metadata.SHA1 = Enumerable.Range(0, 20).Select(i => (byte)i).ToArray();
original.Local = true;
original.Temporary = true;
original.Flags = AssetFlags.Collectable;
original.UploadAttempts = 3;
original.Data = Enumerable.Range(0, 256).Select(i => (byte)i).ToArray();
using MemoryStream encoded = new();
write.Invoke(null, new object[] { encoded, original });
if (encoded.Length <= original.Data.Length)
throw new Exception("Invalid cache encoding");
encoded.Position = 0;
AssetBase restored = (AssetBase)read.Invoke(null, new object[] { encoded, id })!;
Check(restored.ID == original.ID, "ID mismatch");
Check(restored.Name == original.Name, "Name mismatch");
Check(restored.Description == original.Description, "Description mismatch");
Check(restored.CreatorID == original.CreatorID, "Creator mismatch");
Check(restored.Type == original.Type, "Asset Type mismatch");
Check(restored.Metadata.ContentType == original.Metadata.ContentType, "Content type mismatch");
Check(restored.Flags == original.Flags, "Flags mismatch");
Check(restored.Local && restored.Temporary, "Local/Temporary lost");
Check(restored.UploadAttempts == original.UploadAttempts, "UploadAttempts mismatch");
Check(restored.Metadata.CreationDate == original.Metadata.CreationDate, "Creation time mismatch");
Check(restored.Metadata.SHA1!.SequenceEqual(original.Metadata.SHA1!), "SHA1 mismatch");
Check(restored.Data.SequenceEqual(original.Data), "Payload mismatch");
byte[] payload = encoded.ToArray();
byte[] tampered = (byte[])payload.Clone();
tampered[^33] ^= 0x11;
MustReject(read, tampered, id, "corrupt payload hash");
MustReject(read, payload.Take(payload.Length - 6).ToArray(), id, "truncated file");
MustReject(read, payload, "11111111-2222-3333-4444-555555555555", "wrong asset ID");
MustReject(read, new byte[] { 0, 1, 0, 0, 0, 0, 0, 0 }, id, "legacy format");
var cache = new FlotsamAssetCache();
typeof(FlotsamAssetCache).GetField("m_CacheDirectory", BindingFlags.Instance | BindingFlags.NonPublic)!
.SetValue(cache, root);
var filename = typeof(FlotsamAssetCache).GetMethod("GetFileName", BindingFlags.Instance | BindingFlags.NonPublic)!;
var getFile = typeof(FlotsamAssetCache).GetMethod("GetFromFileCache", BindingFlags.Instance | BindingFlags.NonPublic)!;
string path = (string)filename.Invoke(cache, new object[] { id })!;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllBytes(path, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 });
Check(getFile.Invoke(cache, new object[] { id }) is null, "Legacy cache returned an asset");
Check(!File.Exists(path), "Legacy cache entry was not discarded");
File.WriteAllBytes(path, payload);
var fromFile = (AssetBase)getFile.Invoke(cache, new object[] { id })!;
Check(fromFile is not null && fromFile.Data.SequenceEqual(original.Data), "File cache could not read new versioned format");
Console.WriteLine("PASS: Flotsam .NET10 binary cache roundtrip, integrity, bounded legacy rejection and refetch");
return 0;
}
finally
{
Directory.Delete(root, recursive: true);
}
}
private static void Check(bool ok, string error)
{
if (!ok)
throw new InvalidOperationException(error);
}
private static void MustReject(MethodInfo read, byte[] contents, string id, string label)
{
using MemoryStream stream = new(contents);
try
{
read.Invoke(null, new object[] { stream, id });
throw new InvalidOperationException("Invalid cache accepted: " + label);
}
catch (TargetInvocationException ex) when (ex.InnerException is InvalidDataException || ex.InnerException is IOException)
{
}
}
}