perf(save): encode detached snapshots and expose phase timings

This commit is contained in:
2026-09-29 10:14:43 +08:00
parent d26f1a94ef
commit ac557b7a0f
6 changed files with 65 additions and 19 deletions
+1 -1
View File
@@ -5,7 +5,7 @@
<AssemblyName>ShrinkDataSaver.Runtime</AssemblyName> <AssemblyName>ShrinkDataSaver.Runtime</AssemblyName>
<RootNamespace>ShrinkDataSaver</RootNamespace> <RootNamespace>ShrinkDataSaver</RootNamespace>
<PackageId>ShrinkSDK.DataSaver</PackageId> <PackageId>ShrinkSDK.DataSaver</PackageId>
<Version>2.3.0</Version> <Version>2.4.0</Version>
<Description>ShrinkSDK engine-neutral versioned save and settings runtime.</Description> <Description>ShrinkSDK engine-neutral versioned save and settings runtime.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled> <ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
<Nullable>disable</Nullable> <Nullable>disable</Nullable>
+10
View File
@@ -542,3 +542,13 @@ await ShrinkSave.LoadSlotAsync(slotIndex, key);
## 📄 License ## 📄 License
[MIT](LICENSE) [MIT](LICENSE)
## 可复用能力
<!-- shrink:capabilities -->
Capability: 模块化存档、槽位、设置、迁移、加密和损坏备份恢复
Aliases: 存储 存档 保存 读档 设置 持久化 save
Limits: 模块负责采集一致状态;后台不得读取 Unity 对象;不会自动保存任意游戏字段
Extension: 存档模块注册、序列化器、迁移链与平台路径服务
Evidence: [ShrinkSave](Runtime/ShrinkSave.cs); [ShrinkDataSaverRuntime](DotNet~/Runtime/ShrinkDataSaverRuntime.cs)
<!-- /shrink:capabilities -->
+2 -2
View File
@@ -108,8 +108,8 @@ namespace ShrinkDataSaver
} }
} }
public UniTask<bool> ExistsAsync(string path, CancellationToken ct = default) => public async UniTask<bool> ExistsAsync(string path, CancellationToken ct = default) =>
Task.Run(() => File.Exists(Resolve(path)), ct).AsUniTask(); await Task.Run(() => File.Exists(Resolve(path)), ct);
public async UniTask DeleteAsync(string path, CancellationToken ct = default) public async UniTask DeleteAsync(string path, CancellationToken ct = default)
{ {
+13
View File
@@ -59,8 +59,21 @@ namespace ShrinkDataSaver
} }
public sealed class SavePhaseTimings
{
public double CaptureMilliseconds { get; internal set; }
public double EncodeMilliseconds { get; internal set; }
public double EncryptMilliseconds { get; internal set; }
public double WriteMilliseconds { get; internal set; }
public long EncodedBytes { get; internal set; }
}
public class SaveOptions public class SaveOptions
{ {
/// <summary>Only the detached JToken snapshot is encoded off-thread; module capture stays on the caller thread.</summary>
public bool EncodeInBackground = false;
public bool CollectTimings = false;
public SavePhaseTimings LastTimings { get; internal set; }
public string SlotName = "New Save"; public string SlotName = "New Save";
public bool CaptureScreenshot = false; public bool CaptureScreenshot = false;
#if UNITY_5_3_OR_NEWER #if UNITY_5_3_OR_NEWER
+38 -15
View File
@@ -1,6 +1,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading; using System.Threading;
using Cysharp.Threading.Tasks; using Cysharp.Threading.Tasks;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@@ -183,6 +185,14 @@ namespace ShrinkDataSaver
{ {
options ??= new SaveOptions(); options ??= new SaveOptions();
ValidateSlotIndex(slotIndex); ValidateSlotIndex(slotIndex);
ct.ThrowIfCancellationRequested();
var timings = options.CollectTimings ? new SavePhaseTimings() : null;
options.LastTimings = timings;
var captureStarted = Stopwatch.GetTimestamp();
var encrypt = options.Encrypt;
var encryptionKey = options.EncryptionKey;
var encodeInBackground = options.EncodeInBackground;
var storage = _storage;
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
OnSaveStarted?.Invoke(new SaveStartedEventArgs { SlotIndex = slotIndex, Timestamp = timestamp }); OnSaveStarted?.Invoke(new SaveStartedEventArgs { SlotIndex = slotIndex, Timestamp = timestamp });
@@ -198,7 +208,7 @@ namespace ShrinkDataSaver
SaveVersion = _currentSaveVersion, SaveVersion = _currentSaveVersion,
LastModified = timestamp, LastModified = timestamp,
PlaytimeSeconds = GetCurrentPlaytime(), PlaytimeSeconds = GetCurrentPlaytime(),
IsEncrypted = options.Encrypt IsEncrypted = encrypt
} }
}; };
@@ -233,24 +243,35 @@ namespace ShrinkDataSaver
} }
} }
if (options.Encrypt) if (timings != null) timings.CaptureMilliseconds = PhaseElapsed(captureStarted);
ct.ThrowIfCancellationRequested();
// Modules have been materialized as private JSON tokens; the worker never touches providers or engine objects.
byte[] Encode()
{ {
if (string.IsNullOrEmpty(options.EncryptionKey)) ct.ThrowIfCancellationRequested();
var stage = Stopwatch.GetTimestamp();
if (encrypt)
{ {
throw new ArgumentException("EncryptionKey missing."); if (string.IsNullOrEmpty(encryptionKey)) throw new ArgumentException("EncryptionKey missing.");
var modulesBytes = DataSerializer.Serialize(modulesDict);
if (timings != null) timings.EncodeMilliseconds += PhaseElapsed(stage);
stage = Stopwatch.GetTimestamp();
var encryptedBytes = SaveEncryptor.Encrypt(modulesBytes, encryptionKey);
if (timings != null) timings.EncryptMilliseconds = PhaseElapsed(stage);
packet.EncryptedModules = Convert.ToBase64String(encryptedBytes);
} }
else packet.Modules = modulesDict;
var modulesBytes = DataSerializer.Serialize(modulesDict); ct.ThrowIfCancellationRequested();
var encryptedBytes = SaveEncryptor.Encrypt(modulesBytes, options.EncryptionKey); stage = Stopwatch.GetTimestamp();
packet.EncryptedModules = Convert.ToBase64String(encryptedBytes); var bytes = DataSerializer.Serialize(packet);
if (timings != null) { timings.EncodeMilliseconds += PhaseElapsed(stage); timings.EncodedBytes = bytes.Length; }
return bytes;
} }
else var finalBytes = encodeInBackground ? await Task.Run(Encode, ct) : Encode();
{ ct.ThrowIfCancellationRequested();
packet.Modules = modulesDict; var writeStarted = Stopwatch.GetTimestamp();
} await storage.WriteAsync(SlotPath(slotIndex), finalBytes, ct);
if (timings != null) timings.WriteMilliseconds = PhaseElapsed(writeStarted);
var finalBytes = DataSerializer.Serialize(packet);
await _storage.WriteAsync(SlotPath(slotIndex), finalBytes, ct);
OnSaveCompleted?.Invoke(new SaveCompletedEventArgs OnSaveCompleted?.Invoke(new SaveCompletedEventArgs
{ {
@@ -271,6 +292,8 @@ namespace ShrinkDataSaver
} }
} }
private static double PhaseElapsed(long started) => (Stopwatch.GetTimestamp() - started) * 1000d / Stopwatch.Frequency;
public static async UniTask LoadSlotAsync(int slotIndex, string decryptionKey = null, CancellationToken ct = default) public static async UniTask LoadSlotAsync(int slotIndex, string decryptionKey = null, CancellationToken ct = default)
{ {
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "com.cneicy.shrink-datasaver", "name": "com.cneicy.shrink-datasaver",
"version": "2.3.0", "version": "2.4.0",
"displayName": "ShrinkDataSaver", "displayName": "ShrinkDataSaver",
"description": "模块化 Unity 存档与设置管理系统,支持多槽位、链式版本迁移、AES-256 加密、关键模块保护、跨模块查询与事件驱动架构。", "description": "模块化 Unity 存档与设置管理系统,支持多槽位、链式版本迁移、AES-256 加密、关键模块保护、跨模块查询与事件驱动架构。",
"unity": "2022.3", "unity": "2022.3",